libzypp  16.22.5
MediaCurl.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
13 #include <iostream>
14 #include <list>
15 
16 #include "zypp/base/Logger.h"
17 #include "zypp/ExternalProgram.h"
18 #include "zypp/base/String.h"
19 #include "zypp/base/Gettext.h"
20 #include "zypp/base/Sysconfig.h"
21 #include "zypp/base/Gettext.h"
22 
23 #include "zypp/media/MediaCurl.h"
24 #include "zypp/media/ProxyInfo.h"
27 #include "zypp/media/CurlConfig.h"
28 #include "zypp/thread/Once.h"
29 #include "zypp/Target.h"
30 #include "zypp/ZYppFactory.h"
31 #include "zypp/ZConfig.h"
32 
33 #include <cstdlib>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/mount.h>
37 #include <errno.h>
38 #include <dirent.h>
39 #include <unistd.h>
40 
41 #define DETECT_DIR_INDEX 0
42 #define CONNECT_TIMEOUT 60
43 #define TRANSFER_TIMEOUT_MAX 60 * 60
44 
45 #define EXPLICITLY_NO_PROXY "_none_"
46 
47 #undef CURLVERSION_AT_LEAST
48 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
49 
50 using namespace std;
51 using namespace zypp::base;
52 
53 namespace
54 {
55  zypp::thread::OnceFlag g_InitOnceFlag = PTHREAD_ONCE_INIT;
56  zypp::thread::OnceFlag g_FreeOnceFlag = PTHREAD_ONCE_INIT;
57 
58  extern "C" void _do_free_once()
59  {
60  curl_global_cleanup();
61  }
62 
63  extern "C" void globalFreeOnce()
64  {
65  zypp::thread::callOnce(g_FreeOnceFlag, _do_free_once);
66  }
67 
68  extern "C" void _do_init_once()
69  {
70  CURLcode ret = curl_global_init( CURL_GLOBAL_ALL );
71  if ( ret != 0 )
72  {
73  WAR << "curl global init failed" << endl;
74  }
75 
76  //
77  // register at exit handler ?
78  // this may cause trouble, because we can protect it
79  // against ourself only.
80  // if the app sets an atexit handler as well, it will
81  // cause a double free while the second of them runs.
82  //
83  //std::atexit( globalFreeOnce);
84  }
85 
86  inline void globalInitOnce()
87  {
88  zypp::thread::callOnce(g_InitOnceFlag, _do_init_once);
89  }
90 
91  int log_curl(CURL *curl, curl_infotype info,
92  char *ptr, size_t len, void *max_lvl)
93  {
94  if ( max_lvl == nullptr )
95  return 0;
96 
97  long maxlvl = *((long *)max_lvl);
98 
99  char pfx = ' ';
100  switch( info )
101  {
102  case CURLINFO_TEXT: if ( maxlvl < 1 ) return 0; pfx = '*'; break;
103  case CURLINFO_HEADER_IN: if ( maxlvl < 2 ) return 0; pfx = '<'; break;
104  case CURLINFO_HEADER_OUT: if ( maxlvl < 2 ) return 0; pfx = '>'; break;
105  default:
106  return 0;
107  }
108 
109  std::vector<std::string> lines;
110  zypp::str::split( std::string(ptr,len), std::back_inserter(lines), "\r\n" );
111  for( const auto & line : lines )
112  {
113  if ( zypp::str::startsWith( line, "Authorization:" ) ) {
114  std::string::size_type pos { line.find( " ", 15 ) }; // Authorization: <type> <credentials>
115  if ( pos == std::string::npos )
116  pos = 15;
117  DBG << pfx << " " << line.substr( 0, pos ) << " <credentials removed>" << std::endl;
118  }
119  else
120  DBG << pfx << " " << line << std::endl;
121  }
122  return 0;
123  }
124 
125  static size_t
126  log_redirects_curl(
127  void *ptr, size_t size, size_t nmemb, void *stream)
128  {
129  // INT << "got header: " << string((char *)ptr, ((char*)ptr) + size*nmemb) << endl;
130 
131  char * lstart = (char *)ptr, * lend = (char *)ptr;
132  size_t pos = 0;
133  size_t max = size * nmemb;
134  while (pos + 1 < max)
135  {
136  // get line
137  for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
138 
139  // look for "Location"
140  string line(lstart, lend);
141  if (line.find("Location") != string::npos)
142  {
143  DBG << "redirecting to " << line << endl;
144  return max;
145  }
146 
147  // continue with the next line
148  if (pos + 1 < max)
149  {
150  ++lend;
151  ++pos;
152  }
153  else
154  break;
155  }
156 
157  return max;
158  }
159 }
160 
161 namespace zypp {
162 
164  namespace env
165  {
166  namespace
167  {
168  inline int getZYPP_MEDIA_CURL_IPRESOLVE()
169  {
170  int ret = 0;
171  if ( const char * envp = getenv( "ZYPP_MEDIA_CURL_IPRESOLVE" ) )
172  {
173  WAR << "env set: $ZYPP_MEDIA_CURL_IPRESOLVE='" << envp << "'" << endl;
174  if ( strcmp( envp, "4" ) == 0 ) ret = 4;
175  else if ( strcmp( envp, "6" ) == 0 ) ret = 6;
176  }
177  return ret;
178  }
179  }
180 
182  {
183  static int _v = getZYPP_MEDIA_CURL_IPRESOLVE();
184  return _v;
185  }
186  } // namespace env
188 
189  namespace media {
190 
191  namespace {
192  struct ProgressData
193  {
194  ProgressData( CURL *_curl, time_t _timeout = 0, const Url & _url = Url(),
195  ByteCount expectedFileSize_r = 0,
196  callback::SendReport<DownloadProgressReport> *_report = nullptr )
197  : curl( _curl )
198  , url( _url )
199  , timeout( _timeout )
200  , reached( false )
201  , fileSizeExceeded ( false )
202  , report( _report )
203  , _expectedFileSize( expectedFileSize_r )
204  {}
205 
206  CURL *curl;
207  Url url;
208  time_t timeout;
209  bool reached;
211  callback::SendReport<DownloadProgressReport> *report;
212  ByteCount _expectedFileSize;
213 
214  time_t _timeStart = 0;
215  time_t _timeLast = 0;
216  time_t _timeRcv = 0;
217  time_t _timeNow = 0;
218 
219  double _dnlTotal = 0.0;
220  double _dnlLast = 0.0;
221  double _dnlNow = 0.0;
222 
223  int _dnlPercent= 0;
224 
225  double _drateTotal= 0.0;
226  double _drateLast = 0.0;
227 
228  void updateStats( double dltotal = 0.0, double dlnow = 0.0 )
229  {
230  time_t now = _timeNow = time(0);
231 
232  // If called without args (0.0), recompute based on the last values seen
233  if ( dltotal && dltotal != _dnlTotal )
234  _dnlTotal = dltotal;
235 
236  if ( dlnow && dlnow != _dnlNow )
237  {
238  _timeRcv = now;
239  _dnlNow = dlnow;
240  }
241  else if ( !_dnlNow && !_dnlTotal )
242  {
243  // Start time counting as soon as first data arrives.
244  // Skip the connection / redirection time at begin.
245  return;
246  }
247 
248  // init or reset if time jumps back
249  if ( !_timeStart || _timeStart > now )
250  _timeStart = _timeLast = _timeRcv = now;
251 
252  // timeout condition
253  if ( timeout )
254  reached = ( (now - _timeRcv) > timeout );
255 
256  // check if the downloaded data is already bigger than what we expected
257  fileSizeExceeded = _expectedFileSize > 0 && _expectedFileSize < static_cast<ByteCount::SizeType>(_dnlNow);
258 
259  // percentage:
260  if ( _dnlTotal )
261  _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
262 
263  // download rates:
264  _drateTotal = _dnlNow / std::max( int(now - _timeStart), 1 );
265 
266  if ( _timeLast < now )
267  {
268  _drateLast = (_dnlNow - _dnlLast) / int(now - _timeLast);
269  // start new period
270  _timeLast = now;
271  _dnlLast = _dnlNow;
272  }
273  else if ( _timeStart == _timeLast )
275  }
276 
277  int reportProgress() const
278  {
279  if ( fileSizeExceeded )
280  return 1;
281  if ( reached )
282  return 1; // no-data timeout
283  if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
284  return 1; // user requested abort
285  return 0;
286  }
287 
288 
289  // download rate of the last period (cca 1 sec)
290  double drate_period;
291  // bytes downloaded at the start of the last period
292  double dload_period;
293  // seconds from the start of the download
294  long secs;
295  // average download rate
296  double drate_avg;
297  // last time the progress was reported
298  time_t ltime;
299  // bytes downloaded at the moment the progress was last reported
300  double dload;
301  // bytes uploaded at the moment the progress was last reported
302  double uload;
303  };
304 
306 
307  inline void escape( string & str_r,
308  const char char_r, const string & escaped_r ) {
309  for ( string::size_type pos = str_r.find( char_r );
310  pos != string::npos; pos = str_r.find( char_r, pos ) ) {
311  str_r.replace( pos, 1, escaped_r );
312  }
313  }
314 
315  inline string escapedPath( string path_r ) {
316  escape( path_r, ' ', "%20" );
317  return path_r;
318  }
319 
320  inline string unEscape( string text_r ) {
321  char * tmp = curl_unescape( text_r.c_str(), 0 );
322  string ret( tmp );
323  curl_free( tmp );
324  return ret;
325  }
326 
327  }
328 
334 {
335  std::string param(url.getQueryParam("timeout"));
336  if( !param.empty())
337  {
338  long num = str::strtonum<long>(param);
339  if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
340  s.setTimeout(num);
341  }
342 
343  if ( ! url.getUsername().empty() )
344  {
345  s.setUsername(url.getUsername());
346  if ( url.getPassword().size() )
347  s.setPassword(url.getPassword());
348  }
349  else
350  {
351  // if there is no username, set anonymous auth
352  if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
353  s.setAnonymousAuth();
354  }
355 
356  if ( url.getScheme() == "https" )
357  {
358  s.setVerifyPeerEnabled(false);
359  s.setVerifyHostEnabled(false);
360 
361  std::string verify( url.getQueryParam("ssl_verify"));
362  if( verify.empty() ||
363  verify == "yes")
364  {
365  s.setVerifyPeerEnabled(true);
366  s.setVerifyHostEnabled(true);
367  }
368  else if( verify == "no")
369  {
370  s.setVerifyPeerEnabled(false);
371  s.setVerifyHostEnabled(false);
372  }
373  else
374  {
375  std::vector<std::string> flags;
376  std::vector<std::string>::const_iterator flag;
377  str::split( verify, std::back_inserter(flags), ",");
378  for(flag = flags.begin(); flag != flags.end(); ++flag)
379  {
380  if( *flag == "host")
381  s.setVerifyHostEnabled(true);
382  else if( *flag == "peer")
383  s.setVerifyPeerEnabled(true);
384  else
385  ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
386  }
387  }
388  }
389 
390  Pathname ca_path( url.getQueryParam("ssl_capath") );
391  if( ! ca_path.empty())
392  {
393  if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
394  ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
395  else
397  }
398 
399  Pathname client_cert( url.getQueryParam("ssl_clientcert") );
400  if( ! client_cert.empty())
401  {
402  if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
403  ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientcert file"));
404  else
405  s.setClientCertificatePath(client_cert);
406  }
407  Pathname client_key( url.getQueryParam("ssl_clientkey") );
408  if( ! client_key.empty())
409  {
410  if( !PathInfo(client_key).isFile() || !client_key.absolute())
411  ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
412  else
413  s.setClientKeyPath(client_key);
414  }
415 
416  param = url.getQueryParam( "proxy" );
417  if ( ! param.empty() )
418  {
419  if ( param == EXPLICITLY_NO_PROXY ) {
420  // Workaround TransferSettings shortcoming: With an
421  // empty proxy string, code will continue to look for
422  // valid proxy settings. So set proxy to some non-empty
423  // string, to indicate it has been explicitly disabled.
425  s.setProxyEnabled(false);
426  }
427  else {
428  string proxyport( url.getQueryParam( "proxyport" ) );
429  if ( ! proxyport.empty() ) {
430  param += ":" + proxyport;
431  }
432  s.setProxy(param);
433  s.setProxyEnabled(true);
434  }
435  }
436 
437  param = url.getQueryParam( "proxyuser" );
438  if ( ! param.empty() )
439  {
440  s.setProxyUsername(param);
441  s.setProxyPassword(url.getQueryParam( "proxypass" ));
442  }
443 
444  // HTTP authentication type
445  param = url.getQueryParam("auth");
446  if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
447  {
448  try
449  {
450  CurlAuthData::auth_type_str2long(param); // check if we know it
451  }
452  catch (MediaException & ex_r)
453  {
454  DBG << "Rethrowing as MediaUnauthorizedException.";
455  ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
456  }
457  s.setAuthType(param);
458  }
459 
460  // workarounds
461  param = url.getQueryParam("head_requests");
462  if( !param.empty() && param == "no" )
463  s.setHeadRequestsAllowed(false);
464 }
465 
471 {
472  ProxyInfo proxy_info;
473  if ( proxy_info.useProxyFor( url ) )
474  {
475  // We must extract any 'user:pass' from the proxy url
476  // otherwise they won't make it into curl (.curlrc wins).
477  try {
478  Url u( proxy_info.proxy( url ) );
479  s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
480  // don't overwrite explicit auth settings
481  if ( s.proxyUsername().empty() )
482  {
483  s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
484  s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
485  }
486  s.setProxyEnabled( true );
487  }
488  catch (...) {} // no proxy if URL is malformed
489  }
490 }
491 
492 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
493 
498 static const char *const anonymousIdHeader()
499 {
500  // we need to add the release and identifier to the
501  // agent string.
502  // The target could be not initialized, and then this information
503  // is guessed.
504  static const std::string _value(
506  "X-ZYpp-AnonymousId: %s",
507  Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
508  );
509  return _value.c_str();
510 }
511 
516 static const char *const distributionFlavorHeader()
517 {
518  // we need to add the release and identifier to the
519  // agent string.
520  // The target could be not initialized, and then this information
521  // is guessed.
522  static const std::string _value(
524  "X-ZYpp-DistributionFlavor: %s",
525  Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
526  );
527  return _value.c_str();
528 }
529 
534 static const char *const agentString()
535 {
536  // we need to add the release and identifier to the
537  // agent string.
538  // The target could be not initialized, and then this information
539  // is guessed.
540  static const std::string _value(
541  str::form(
542  "ZYpp %s (curl %s) %s"
543  , VERSION
544  , curl_version_info(CURLVERSION_NOW)->version
545  , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
546  )
547  );
548  return _value.c_str();
549 }
550 
551 // we use this define to unbloat code as this C setting option
552 // and catching exception is done frequently.
554 #define SET_OPTION(opt,val) do { \
555  ret = curl_easy_setopt ( _curl, opt, val ); \
556  if ( ret != 0) { \
557  ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
558  } \
559  } while ( false )
560 
561 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
562 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
563 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
564 
565 MediaCurl::MediaCurl( const Url & url_r,
566  const Pathname & attach_point_hint_r )
567  : MediaHandler( url_r, attach_point_hint_r,
568  "/", // urlpath at attachpoint
569  true ), // does_download
570  _curl( NULL ),
571  _customHeaders(0L)
572 {
573  _curlError[0] = '\0';
574  _curlDebug = 0L;
575 
576  MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
577 
578  globalInitOnce();
579 
580  if( !attachPoint().empty())
581  {
582  PathInfo ainfo(attachPoint());
583  Pathname apath(attachPoint() + "XXXXXX");
584  char *atemp = ::strdup( apath.asString().c_str());
585  char *atest = NULL;
586  if( !ainfo.isDir() || !ainfo.userMayRWX() ||
587  atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
588  {
589  WAR << "attach point " << ainfo.path()
590  << " is not useable for " << url_r.getScheme() << endl;
591  setAttachPoint("", true);
592  }
593  else if( atest != NULL)
594  ::rmdir(atest);
595 
596  if( atemp != NULL)
597  ::free(atemp);
598  }
599 }
600 
602 {
603  Url curlUrl (url);
604  curlUrl.setUsername( "" );
605  curlUrl.setPassword( "" );
606  curlUrl.setPathParams( "" );
607  curlUrl.setFragment( "" );
608  curlUrl.delQueryParam("cookies");
609  curlUrl.delQueryParam("proxy");
610  curlUrl.delQueryParam("proxyport");
611  curlUrl.delQueryParam("proxyuser");
612  curlUrl.delQueryParam("proxypass");
613  curlUrl.delQueryParam("ssl_capath");
614  curlUrl.delQueryParam("ssl_verify");
615  curlUrl.delQueryParam("ssl_clientcert");
616  curlUrl.delQueryParam("timeout");
617  curlUrl.delQueryParam("auth");
618  curlUrl.delQueryParam("username");
619  curlUrl.delQueryParam("password");
620  curlUrl.delQueryParam("mediahandler");
621  curlUrl.delQueryParam("credentials");
622  curlUrl.delQueryParam("head_requests");
623  return curlUrl;
624 }
625 
627 {
628  return _settings;
629 }
630 
631 
632 void MediaCurl::setCookieFile( const Pathname &fileName )
633 {
634  _cookieFile = fileName;
635 }
636 
638 
639 void MediaCurl::checkProtocol(const Url &url) const
640 {
641  curl_version_info_data *curl_info = NULL;
642  curl_info = curl_version_info(CURLVERSION_NOW);
643  // curl_info does not need any free (is static)
644  if (curl_info->protocols)
645  {
646  const char * const *proto;
647  std::string scheme( url.getScheme());
648  bool found = false;
649  for(proto=curl_info->protocols; !found && *proto; ++proto)
650  {
651  if( scheme == std::string((const char *)*proto))
652  found = true;
653  }
654  if( !found)
655  {
656  std::string msg("Unsupported protocol '");
657  msg += scheme;
658  msg += "'";
660  }
661  }
662 }
663 
665 {
666  {
667  char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
668  _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
669  if( _curlDebug > 0)
670  {
671  curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
672  curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
673  curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
674  }
675  }
676 
677  curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
678  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
679  if ( ret != 0 ) {
680  ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
681  }
682 
683  SET_OPTION(CURLOPT_FAILONERROR, 1L);
684  SET_OPTION(CURLOPT_NOSIGNAL, 1L);
685 
686  // create non persistant settings
687  // so that we don't add headers twice
688  TransferSettings vol_settings(_settings);
689 
690  // add custom headers for download.opensuse.org (bsc#955801)
691  if ( _url.getHost() == "download.opensuse.org" )
692  {
693  vol_settings.addHeader(anonymousIdHeader());
694  vol_settings.addHeader(distributionFlavorHeader());
695  }
696  vol_settings.addHeader("Pragma:");
697 
698  _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
700 
702 
703  // fill some settings from url query parameters
704  try
705  {
707  }
708  catch ( const MediaException &e )
709  {
710  disconnectFrom();
711  ZYPP_RETHROW(e);
712  }
713  // if the proxy was not set (or explicitly unset) by url, then look...
714  if ( _settings.proxy().empty() )
715  {
716  // ...at the system proxy settings
718  }
719 
722  {
723  switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
724  {
725  case 4: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); break;
726  case 6: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); break;
727  }
728  }
729 
733  SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
734  // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
735  // just in case curl does not trigger its progress callback frequently
736  // enough.
737  if ( _settings.timeout() )
738  {
739  SET_OPTION(CURLOPT_TIMEOUT, 3600L);
740  }
741 
742  // follow any Location: header that the server sends as part of
743  // an HTTP header (#113275)
744  SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
745  // 3 redirects seem to be too few in some cases (bnc #465532)
746  SET_OPTION(CURLOPT_MAXREDIRS, 6L);
747 
748  if ( _url.getScheme() == "https" )
749  {
750 #if CURLVERSION_AT_LEAST(7,19,4)
751  // restrict following of redirections from https to https only
752  SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
753 #endif
754 
757  {
758  SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
759  }
760 
761  if( ! _settings.clientCertificatePath().empty() )
762  {
763  SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
764  }
765  if( ! _settings.clientKeyPath().empty() )
766  {
767  SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
768  }
769 
770 #ifdef CURLSSLOPT_ALLOW_BEAST
771  // see bnc#779177
772  ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
773  if ( ret != 0 ) {
774  disconnectFrom();
776  }
777 #endif
778  SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
779  SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
780  // bnc#903405 - POODLE: libzypp should only talk TLS
781  SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
782  }
783 
784  SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
785 
786  /*---------------------------------------------------------------*
787  CURLOPT_USERPWD: [user name]:[password]
788 
789  Url::username/password -> CURLOPT_USERPWD
790  If not provided, anonymous FTP identification
791  *---------------------------------------------------------------*/
792 
793  if ( _settings.userPassword().size() )
794  {
795  SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
796  string use_auth = _settings.authType();
797  if (use_auth.empty())
798  use_auth = "digest,basic"; // our default
799  long auth = CurlAuthData::auth_type_str2long(use_auth);
800  if( auth != CURLAUTH_NONE)
801  {
802  DBG << "Enabling HTTP authentication methods: " << use_auth
803  << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
804  SET_OPTION(CURLOPT_HTTPAUTH, auth);
805  }
806  }
807 
808  if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
809  {
810  DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
811  SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
812  SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
813  /*---------------------------------------------------------------*
814  * CURLOPT_PROXYUSERPWD: [user name]:[password]
815  *
816  * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
817  * If not provided, $HOME/.curlrc is evaluated
818  *---------------------------------------------------------------*/
819 
820  string proxyuserpwd = _settings.proxyUserPassword();
821 
822  if ( proxyuserpwd.empty() )
823  {
824  CurlConfig curlconf;
825  CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
826  if ( curlconf.proxyuserpwd.empty() )
827  DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
828  else
829  {
830  proxyuserpwd = curlconf.proxyuserpwd;
831  DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
832  }
833  }
834  else
835  {
836  DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
837  }
838 
839  if ( ! proxyuserpwd.empty() )
840  {
841  SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
842  }
843  }
844 #if CURLVERSION_AT_LEAST(7,19,4)
845  else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
846  {
847  // Explicitly disabled in URL (see fillSettingsFromUrl()).
848  // This should also prevent libcurl from looking into the environment.
849  DBG << "Proxy: explicitly NOPROXY" << endl;
850  SET_OPTION(CURLOPT_NOPROXY, "*");
851  }
852 #endif
853  else
854  {
855  DBG << "Proxy: not explicitly set" << endl;
856  DBG << "Proxy: libcurl may look into the environment" << endl;
857  }
858 
860  if ( _settings.minDownloadSpeed() != 0 )
861  {
862  SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
863  // default to 10 seconds at low speed
864  SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
865  }
866 
867 #if CURLVERSION_AT_LEAST(7,15,5)
868  if ( _settings.maxDownloadSpeed() != 0 )
869  SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
870 #endif
871 
872  /*---------------------------------------------------------------*
873  *---------------------------------------------------------------*/
874 
875  _currentCookieFile = _cookieFile.asString();
877  if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
878  SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
879  else
880  MIL << "No cookies requested" << endl;
881  SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
882  SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
883  SET_OPTION(CURLOPT_NOPROGRESS, 0L);
884 
885 #if CURLVERSION_AT_LEAST(7,18,0)
886  // bnc #306272
887  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
888 #endif
889  // append settings custom headers to curl
890  for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
891  it != vol_settings.headersEnd();
892  ++it )
893  {
894  // MIL << "HEADER " << *it << std::endl;
895 
896  _customHeaders = curl_slist_append(_customHeaders, it->c_str());
897  if ( !_customHeaders )
899  }
900 
901  SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
902 }
903 
905 
906 
907 void MediaCurl::attachTo (bool next)
908 {
909  if ( next )
911 
912  if ( !_url.isValid() )
914 
917  {
919  }
920 
921  disconnectFrom(); // clean _curl if needed
922  _curl = curl_easy_init();
923  if ( !_curl ) {
925  }
926  try
927  {
928  setupEasy();
929  }
930  catch (Exception & ex)
931  {
932  disconnectFrom();
933  ZYPP_RETHROW(ex);
934  }
935 
936  // FIXME: need a derived class to propelly compare url's
938  setMediaSource(media);
939 }
940 
941 bool
942 MediaCurl::checkAttachPoint(const Pathname &apoint) const
943 {
944  return MediaHandler::checkAttachPoint( apoint, true, true);
945 }
946 
948 
950 {
951  if ( _customHeaders )
952  {
953  curl_slist_free_all(_customHeaders);
954  _customHeaders = 0L;
955  }
956 
957  if ( _curl )
958  {
959  curl_easy_cleanup( _curl );
960  _curl = NULL;
961  }
962 }
963 
965 
966 void MediaCurl::releaseFrom( const std::string & ejectDev )
967 {
968  disconnect();
969 }
970 
971 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
972 {
973  // Simply extend the URLs pathname. An 'absolute' URL path
974  // is achieved by encoding the leading '/' in an URL path:
975  // URL: ftp://user@server -> ~user
976  // URL: ftp://user@server/ -> ~user
977  // URL: ftp://user@server// -> ~user
978  // URL: ftp://user@server/%2F -> /
979  // ^- this '/' is just a separator
980  Url newurl( _url );
981  newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
982  return newurl;
983 }
984 
986 
987 void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
988 {
989  // Use absolute file name to prevent access of files outside of the
990  // hierarchy below the attach point.
991  getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
992 }
993 
995 
996 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
997 {
999 
1000  Url fileurl(getFileUrl(filename));
1001 
1002  bool retry = false;
1003 
1004  do
1005  {
1006  try
1007  {
1008  doGetFileCopy(filename, target, report, expectedFileSize_r);
1009  retry = false;
1010  }
1011  // retry with proper authentication data
1012  catch (MediaUnauthorizedException & ex_r)
1013  {
1014  if(authenticate(ex_r.hint(), !retry))
1015  retry = true;
1016  else
1017  {
1018  report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
1019  ZYPP_RETHROW(ex_r);
1020  }
1021  }
1022  // unexpected exception
1023  catch (MediaException & excpt_r)
1024  {
1026  if( typeid(excpt_r) == typeid( media::MediaFileNotFoundException ) ||
1027  typeid(excpt_r) == typeid( media::MediaNotAFileException ) )
1028  {
1030  }
1031  report->finish(fileurl, reason, excpt_r.asUserHistory());
1032  ZYPP_RETHROW(excpt_r);
1033  }
1034  }
1035  while (retry);
1036 
1037  report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
1038 }
1039 
1041 
1042 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
1043 {
1044  bool retry = false;
1045 
1046  do
1047  {
1048  try
1049  {
1050  return doGetDoesFileExist( filename );
1051  }
1052  // authentication problem, retry with proper authentication data
1053  catch (MediaUnauthorizedException & ex_r)
1054  {
1055  if(authenticate(ex_r.hint(), !retry))
1056  retry = true;
1057  else
1058  ZYPP_RETHROW(ex_r);
1059  }
1060  // unexpected exception
1061  catch (MediaException & excpt_r)
1062  {
1063  ZYPP_RETHROW(excpt_r);
1064  }
1065  }
1066  while (retry);
1067 
1068  return false;
1069 }
1070 
1072 
1073 void MediaCurl::evaluateCurlCode(const Pathname &filename,
1074  CURLcode code,
1075  bool timeout_reached) const
1076 {
1077  if ( code != 0 )
1078  {
1079  Url url;
1080  if (filename.empty())
1081  url = _url;
1082  else
1083  url = getFileUrl(filename);
1084 
1085  std::string err;
1086  {
1087  switch ( code )
1088  {
1089  case CURLE_UNSUPPORTED_PROTOCOL:
1090  case CURLE_URL_MALFORMAT:
1091  case CURLE_URL_MALFORMAT_USER:
1092  err = " Bad URL";
1093  break;
1094  case CURLE_LOGIN_DENIED:
1095  ZYPP_THROW(
1096  MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
1097  break;
1098  case CURLE_HTTP_RETURNED_ERROR:
1099  {
1100  long httpReturnCode = 0;
1101  CURLcode infoRet = curl_easy_getinfo( _curl,
1102  CURLINFO_RESPONSE_CODE,
1103  &httpReturnCode );
1104  if ( infoRet == CURLE_OK )
1105  {
1106  string msg = "HTTP response: " + str::numstring( httpReturnCode );
1107  switch ( httpReturnCode )
1108  {
1109  case 401:
1110  {
1111  string auth_hint = getAuthHint();
1112 
1113  DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1114  DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1115 
1117  url, "Login failed.", _curlError, auth_hint
1118  ));
1119  }
1120 
1121  case 502: // bad gateway (bnc #1070851)
1122  case 503: // service temporarily unavailable (bnc #462545)
1124  case 504: // gateway timeout
1126  case 403:
1127  {
1128  string msg403;
1129  if (url.asString().find("novell.com") != string::npos)
1130  msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1131  ZYPP_THROW(MediaForbiddenException(url, msg403));
1132  }
1133  case 404:
1134  case 410:
1136  }
1137 
1138  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1140  }
1141  else
1142  {
1143  string msg = "Unable to retrieve HTTP response:";
1144  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1146  }
1147  }
1148  break;
1149  case CURLE_FTP_COULDNT_RETR_FILE:
1150 #if CURLVERSION_AT_LEAST(7,16,0)
1151  case CURLE_REMOTE_FILE_NOT_FOUND:
1152 #endif
1153  case CURLE_FTP_ACCESS_DENIED:
1154  case CURLE_TFTP_NOTFOUND:
1155  err = "File not found";
1157  break;
1158  case CURLE_BAD_PASSWORD_ENTERED:
1159  case CURLE_FTP_USER_PASSWORD_INCORRECT:
1160  err = "Login failed";
1161  break;
1162  case CURLE_COULDNT_RESOLVE_PROXY:
1163  case CURLE_COULDNT_RESOLVE_HOST:
1164  case CURLE_COULDNT_CONNECT:
1165  case CURLE_FTP_CANT_GET_HOST:
1166  err = "Connection failed";
1167  break;
1168  case CURLE_WRITE_ERROR:
1169  err = "Write error";
1170  break;
1171  case CURLE_PARTIAL_FILE:
1172  case CURLE_OPERATION_TIMEDOUT:
1173  timeout_reached = true; // fall though to TimeoutException
1174  // fall though...
1175  case CURLE_ABORTED_BY_CALLBACK:
1176  if( timeout_reached )
1177  {
1178  err = "Timeout reached";
1180  }
1181  else
1182  {
1183  err = "User abort";
1184  }
1185  break;
1186  case CURLE_SSL_PEER_CERTIFICATE:
1187  default:
1188  err = "Curl error " + str::numstring( code );
1189  break;
1190  }
1191 
1192  // uhm, no 0 code but unknown curl exception
1194  }
1195  }
1196  else
1197  {
1198  // actually the code is 0, nothing happened
1199  }
1200 }
1201 
1203 
1204 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1205 {
1206  DBG << filename.asString() << endl;
1207 
1208  if(!_url.isValid())
1210 
1211  if(_url.getHost().empty())
1213 
1214  Url url(getFileUrl(filename));
1215 
1216  DBG << "URL: " << url.asString() << endl;
1217  // Use URL without options and without username and passwd
1218  // (some proxies dislike them in the URL).
1219  // Curl seems to need the just scheme, hostname and a path;
1220  // the rest was already passed as curl options (in attachTo).
1221  Url curlUrl( clearQueryString(url) );
1222 
1223  //
1224  // See also Bug #154197 and ftp url definition in RFC 1738:
1225  // The url "ftp://user@host/foo/bar/file" contains a path,
1226  // that is relative to the user's home.
1227  // The url "ftp://user@host//foo/bar/file" (or also with
1228  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1229  // contains an absolute path.
1230  //
1231  string urlBuffer( curlUrl.asString());
1232  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1233  urlBuffer.c_str() );
1234  if ( ret != 0 ) {
1236  }
1237 
1238  // instead of returning no data with NOBODY, we return
1239  // little data, that works with broken servers, and
1240  // works for ftp as well, because retrieving only headers
1241  // ftp will return always OK code ?
1242  // See http://curl.haxx.se/docs/knownbugs.html #58
1243  if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1245  ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1246  else
1247  ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1248 
1249  if ( ret != 0 ) {
1250  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1251  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1252  /* yes, this is why we never got to get NOBODY working before,
1253  because setting it changes this option too, and we also
1254  need to reset it
1255  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1256  */
1257  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1259  }
1260 
1261  AutoFILE file { ::fopen( "/dev/null", "w" ) };
1262  if ( !file ) {
1263  ERR << "fopen failed for /dev/null" << endl;
1264  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1265  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1266  /* yes, this is why we never got to get NOBODY working before,
1267  because setting it changes this option too, and we also
1268  need to reset it
1269  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1270  */
1271  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1272  if ( ret != 0 ) {
1274  }
1275  ZYPP_THROW(MediaWriteException("/dev/null"));
1276  }
1277 
1278  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, (*file) );
1279  if ( ret != 0 ) {
1280  std::string err( _curlError);
1281  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1282  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1283  /* yes, this is why we never got to get NOBODY working before,
1284  because setting it changes this option too, and we also
1285  need to reset it
1286  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1287  */
1288  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1289  if ( ret != 0 ) {
1291  }
1293  }
1294 
1295  CURLcode ok = curl_easy_perform( _curl );
1296  MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1297 
1298  // reset curl settings
1299  if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1300  {
1301  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1302  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1303  if ( ret != 0 ) {
1305  }
1306 
1307  /* yes, this is why we never got to get NOBODY working before,
1308  because setting it changes this option too, and we also
1309  need to reset it
1310  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1311  */
1312  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1313  if ( ret != 0 ) {
1315  }
1316 
1317  }
1318  else
1319  {
1320  // for FTP we set different options
1321  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1322  if ( ret != 0 ) {
1324  }
1325  }
1326 
1327  // as we are not having user interaction, the user can't cancel
1328  // the file existence checking, a callback or timeout return code
1329  // will be always a timeout.
1330  try {
1331  evaluateCurlCode( filename, ok, true /* timeout */);
1332  }
1333  catch ( const MediaFileNotFoundException &e ) {
1334  // if the file did not exist then we can return false
1335  return false;
1336  }
1337  catch ( const MediaException &e ) {
1338  // some error, we are not sure about file existence, rethrw
1339  ZYPP_RETHROW(e);
1340  }
1341  // exists
1342  return ( ok == CURLE_OK );
1343 }
1344 
1346 
1347 
1348 #if DETECT_DIR_INDEX
1349 bool MediaCurl::detectDirIndex() const
1350 {
1351  if(_url.getScheme() != "http" && _url.getScheme() != "https")
1352  return false;
1353  //
1354  // try to check the effective url and set the not_a_file flag
1355  // if the url path ends with a "/", what usually means, that
1356  // we've received a directory index (index.html content).
1357  //
1358  // Note: This may be dangerous and break file retrieving in
1359  // case of some server redirections ... ?
1360  //
1361  bool not_a_file = false;
1362  char *ptr = NULL;
1363  CURLcode ret = curl_easy_getinfo( _curl,
1364  CURLINFO_EFFECTIVE_URL,
1365  &ptr);
1366  if ( ret == CURLE_OK && ptr != NULL)
1367  {
1368  try
1369  {
1370  Url eurl( ptr);
1371  std::string path( eurl.getPathName());
1372  if( !path.empty() && path != "/" && *path.rbegin() == '/')
1373  {
1374  DBG << "Effective url ("
1375  << eurl
1376  << ") seems to provide the index of a directory"
1377  << endl;
1378  not_a_file = true;
1379  }
1380  }
1381  catch( ... )
1382  {}
1383  }
1384  return not_a_file;
1385 }
1386 #endif
1387 
1389 
1390 void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1391 {
1392  Pathname dest = target.absolutename();
1393  if( assert_dir( dest.dirname() ) )
1394  {
1395  DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1396  ZYPP_THROW( MediaSystemException(getFileUrl(filename), "System error on " + dest.dirname().asString()) );
1397  }
1398 
1399  ManagedFile destNew { target.extend( ".new.zypp.XXXXXX" ) };
1400  AutoFILE file;
1401  {
1402  AutoFREE<char> buf { ::strdup( (*destNew).c_str() ) };
1403  if( ! buf )
1404  {
1405  ERR << "out of memory for temp file name" << endl;
1406  ZYPP_THROW(MediaSystemException(getFileUrl(filename), "out of memory for temp file name"));
1407  }
1408 
1409  AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1410  if( tmp_fd == -1 )
1411  {
1412  ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1413  ZYPP_THROW(MediaWriteException(destNew));
1414  }
1415  destNew = ManagedFile( (*buf), filesystem::unlink );
1416 
1417  file = ::fdopen( tmp_fd, "we" );
1418  if ( ! file )
1419  {
1420  ERR << "fopen failed for file '" << destNew << "'" << endl;
1421  ZYPP_THROW(MediaWriteException(destNew));
1422  }
1423  tmp_fd.resetDispose(); // don't close it here! ::fdopen moved ownership to file
1424  }
1425 
1426  DBG << "dest: " << dest << endl;
1427  DBG << "temp: " << destNew << endl;
1428 
1429  // set IFMODSINCE time condition (no download if not modified)
1430  if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1431  {
1432  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1433  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1434  }
1435  else
1436  {
1437  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1438  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1439  }
1440  try
1441  {
1442  doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
1443  }
1444  catch (Exception &e)
1445  {
1446  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1447  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1448  ZYPP_RETHROW(e);
1449  }
1450 
1451  long httpReturnCode = 0;
1452  CURLcode infoRet = curl_easy_getinfo(_curl,
1453  CURLINFO_RESPONSE_CODE,
1454  &httpReturnCode);
1455  bool modified = true;
1456  if (infoRet == CURLE_OK)
1457  {
1458  DBG << "HTTP response: " + str::numstring(httpReturnCode);
1459  if ( httpReturnCode == 304
1460  || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1461  {
1462  DBG << " Not modified.";
1463  modified = false;
1464  }
1465  DBG << endl;
1466  }
1467  else
1468  {
1469  WAR << "Could not get the reponse code." << endl;
1470  }
1471 
1472  if (modified || infoRet != CURLE_OK)
1473  {
1474  // apply umask
1475  if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1476  {
1477  ERR << "Failed to chmod file " << destNew << endl;
1478  }
1479 
1480  file.resetDispose(); // we're going to close it manually here
1481  if ( ::fclose( file ) )
1482  {
1483  ERR << "Fclose failed for file '" << destNew << "'" << endl;
1484  ZYPP_THROW(MediaWriteException(destNew));
1485  }
1486 
1487  // move the temp file into dest
1488  if ( rename( destNew, dest ) != 0 ) {
1489  ERR << "Rename failed" << endl;
1491  }
1492  destNew.resetDispose(); // no more need to unlink it
1493  }
1494 
1495  DBG << "done: " << PathInfo(dest) << endl;
1496 }
1497 
1499 
1500 void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1501 {
1502  DBG << filename.asString() << endl;
1503 
1504  if(!_url.isValid())
1506 
1507  if(_url.getHost().empty())
1509 
1510  Url url(getFileUrl(filename));
1511 
1512  DBG << "URL: " << url.asString() << endl;
1513  // Use URL without options and without username and passwd
1514  // (some proxies dislike them in the URL).
1515  // Curl seems to need the just scheme, hostname and a path;
1516  // the rest was already passed as curl options (in attachTo).
1517  Url curlUrl( clearQueryString(url) );
1518 
1519  //
1520  // See also Bug #154197 and ftp url definition in RFC 1738:
1521  // The url "ftp://user@host/foo/bar/file" contains a path,
1522  // that is relative to the user's home.
1523  // The url "ftp://user@host//foo/bar/file" (or also with
1524  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1525  // contains an absolute path.
1526  //
1527  string urlBuffer( curlUrl.asString());
1528  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1529  urlBuffer.c_str() );
1530  if ( ret != 0 ) {
1532  }
1533 
1534  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1535  if ( ret != 0 ) {
1537  }
1538 
1539  // Set callback and perform.
1540  ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
1541  if (!(options & OPTION_NO_REPORT_START))
1542  report->start(url, dest);
1543  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1544  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1545  }
1546 
1547  ret = curl_easy_perform( _curl );
1548 #if CURLVERSION_AT_LEAST(7,19,4)
1549  // bnc#692260: If the client sends a request with an If-Modified-Since header
1550  // with a future date for the server, the server may respond 200 sending a
1551  // zero size file.
1552  // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1553  if ( ftell(file) == 0 && ret == 0 )
1554  {
1555  long httpReturnCode = 33;
1556  if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1557  {
1558  long conditionUnmet = 33;
1559  if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1560  {
1561  WAR << "TIMECONDITION unmet - retry without." << endl;
1562  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1563  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1564  ret = curl_easy_perform( _curl );
1565  }
1566  }
1567  }
1568 #endif
1569 
1570  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1571  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1572  }
1573 
1574  if ( ret != 0 )
1575  {
1576  ERR << "curl error: " << ret << ": " << _curlError
1577  << ", temp file size " << ftell(file)
1578  << " bytes." << endl;
1579 
1580  // the timeout is determined by the progress data object
1581  // which holds whether the timeout was reached or not,
1582  // otherwise it would be a user cancel
1583  try {
1584 
1585  if ( progressData.fileSizeExceeded )
1586  ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
1587 
1588  evaluateCurlCode( filename, ret, progressData.reached );
1589  }
1590  catch ( const MediaException &e ) {
1591  // some error, we are not sure about file existence, rethrw
1592  ZYPP_RETHROW(e);
1593  }
1594  }
1595 
1596 #if DETECT_DIR_INDEX
1597  if (!ret && detectDirIndex())
1598  {
1600  }
1601 #endif // DETECT_DIR_INDEX
1602 }
1603 
1605 
1606 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1607 {
1608  filesystem::DirContent content;
1609  getDirInfo( content, dirname, /*dots*/false );
1610 
1611  for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1612  Pathname filename = dirname + it->name;
1613  int res = 0;
1614 
1615  switch ( it->type ) {
1616  case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1617  case filesystem::FT_FILE:
1618  getFile( filename, 0 );
1619  break;
1620  case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1621  if ( recurse_r ) {
1622  getDir( filename, recurse_r );
1623  } else {
1624  res = assert_dir( localPath( filename ) );
1625  if ( res ) {
1626  WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1627  }
1628  }
1629  break;
1630  default:
1631  // don't provide devices, sockets, etc.
1632  break;
1633  }
1634  }
1635 }
1636 
1638 
1639 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1640  const Pathname & dirname, bool dots ) const
1641 {
1642  getDirectoryYast( retlist, dirname, dots );
1643 }
1644 
1646 
1648  const Pathname & dirname, bool dots ) const
1649 {
1650  getDirectoryYast( retlist, dirname, dots );
1651 }
1652 
1654 //
1655 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1656 {
1657  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1658  if( pdata )
1659  {
1660  // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1661  // prevent a percentage raise while downloading a metalink file. Download
1662  // activity however is indicated by propagating the download rate (via dlnow).
1663  pdata->updateStats( 0.0, dlnow );
1664  return pdata->reportProgress();
1665  }
1666  return 0;
1667 }
1668 
1669 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1670 {
1671  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1672  if( pdata )
1673  {
1674  // work around curl bug that gives us old data
1675  long httpReturnCode = 0;
1676  if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1677  return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1678 
1679  pdata->updateStats( dltotal, dlnow );
1680  return pdata->reportProgress();
1681  }
1682  return 0;
1683 }
1684 
1686 {
1687  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1688  return pdata ? pdata->curl : 0;
1689 }
1690 
1692 
1694 {
1695  long auth_info = CURLAUTH_NONE;
1696 
1697  CURLcode infoRet =
1698  curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1699 
1700  if(infoRet == CURLE_OK)
1701  {
1702  return CurlAuthData::auth_type_long2str(auth_info);
1703  }
1704 
1705  return "";
1706 }
1707 
1712 void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
1713 {
1714  ProgressData *data = reinterpret_cast<ProgressData *>(clientp);
1715  if ( data ) {
1716  data->_expectedFileSize = expectedFileSize;
1717  }
1718 }
1719 
1721 
1722 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1723 {
1725  Target_Ptr target = zypp::getZYpp()->getTarget();
1726  CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1727  CurlAuthData_Ptr credentials;
1728 
1729  // get stored credentials
1730  AuthData_Ptr cmcred = cm.getCred(_url);
1731 
1732  if (cmcred && firstTry)
1733  {
1734  credentials.reset(new CurlAuthData(*cmcred));
1735  DBG << "got stored credentials:" << endl << *credentials << endl;
1736  }
1737  // if not found, ask user
1738  else
1739  {
1740 
1741  CurlAuthData_Ptr curlcred;
1742  curlcred.reset(new CurlAuthData());
1744 
1745  // preset the username if present in current url
1746  if (!_url.getUsername().empty() && firstTry)
1747  curlcred->setUsername(_url.getUsername());
1748  // if CM has found some credentials, preset the username from there
1749  else if (cmcred)
1750  curlcred->setUsername(cmcred->username());
1751 
1752  // indicate we have no good credentials from CM
1753  cmcred.reset();
1754 
1755  string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1756 
1757  // set available authentication types from the exception
1758  // might be needed in prompt
1759  curlcred->setAuthType(availAuthTypes);
1760 
1761  // ask user
1762  if (auth_report->prompt(_url, prompt_msg, *curlcred))
1763  {
1764  DBG << "callback answer: retry" << endl
1765  << "CurlAuthData: " << *curlcred << endl;
1766 
1767  if (curlcred->valid())
1768  {
1769  credentials = curlcred;
1770  // if (credentials->username() != _url.getUsername())
1771  // _url.setUsername(credentials->username());
1779  }
1780  }
1781  else
1782  {
1783  DBG << "callback answer: cancel" << endl;
1784  }
1785  }
1786 
1787  // set username and password
1788  if (credentials)
1789  {
1790  // HACK, why is this const?
1791  const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1792  const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1793 
1794  // set username and password
1795  CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1797 
1798  // set available authentication types from the exception
1799  if (credentials->authType() == CURLAUTH_NONE)
1800  credentials->setAuthType(availAuthTypes);
1801 
1802  // set auth type (seems this must be set _after_ setting the userpwd)
1803  if (credentials->authType() != CURLAUTH_NONE)
1804  {
1805  // FIXME: only overwrite if not empty?
1806  const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1807  ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1809  }
1810 
1811  if (!cmcred)
1812  {
1813  credentials->setUrl(_url);
1814  cm.addCred(*credentials);
1815  cm.save();
1816  }
1817 
1818  return true;
1819  }
1820 
1821  return false;
1822 }
1823 
1824 
1825  } // namespace media
1826 } // namespace zypp
1827 //
void setPassword(const std::string &pass, EEncoding eflag=zypp::url::E_DECODED)
Set the password in the URL authority.
Definition: Url.cc:733
std::string userPassword() const
returns the user and password as a user:pass string
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
Definition: PathInfo.cc:320
Interface to gettext.
void checkProtocol(const Url &url) const
check the url is supported by the curl library
Definition: MediaCurl.cc:639
#define SET_OPTION_OFFT(opt, val)
Definition: MediaCurl.cc:561
double _dnlLast
Bytes downloaded at period start.
Definition: MediaCurl.cc:220
#define MIL
Definition: Logger.h:64
#define CONNECT_TIMEOUT
Definition: MediaCurl.cc:42
bool verifyHostEnabled() const
Whether to verify host for ssl.
Pathname clientKeyPath() const
SSL client key file.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:350
bool authenticate(const std::string &availAuthTypes, bool firstTry) const
Definition: MediaCurl.cc:1722
static ZConfig & instance()
Singleton ctor.
Definition: Resolver.cc:122
virtual void releaseFrom(const std::string &ejectDev)
Call concrete handler to release the media.
Definition: MediaCurl.cc:966
const std::string & msg() const
Return the message string provided to the ctor.
Definition: Exception.h:193
Implementation class for FTP, HTTP and HTTPS MediaHandler.
Definition: MediaCurl.h:32
Flag to request encoded string(s).
Definition: UrlUtils.h:53
long connectTimeout() const
connection timeout
Headers::const_iterator headersEnd() const
end iterators to additional headers
Store and operate with byte count.
Definition: ByteCount.h:30
time_t _timeStart
Start total stats.
Definition: MediaCurl.cc:214
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
Definition: Url.cc:598
void setClientKeyPath(const zypp::Pathname &path)
Sets the SSL client key file.
to not add a IFMODSINCE header if target exists
Definition: MediaCurl.h:44
TransferSettings & settings()
Definition: MediaCurl.cc:626
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
Definition: Url.cc:582
Holds transfer setting.
Url clearQueryString(const Url &url) const
Definition: MediaCurl.cc:601
void save()
Saves any unsaved credentials added via addUserCred() or addGlobalCred() methods. ...
std::string escape(const C_Str &str_r, const char sep_r)
Escape desired character c using a backslash.
Definition: String.cc:369
static int progressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
Callback reporting download progress.
Definition: MediaCurl.cc:1669
void setProxyUsername(const std::string &proxyuser)
sets the proxy user
void setAttachPoint(const Pathname &path, bool temp)
Set a new attach point.
Pathname createAttachPoint() const
Try to create a default / temporary attach point.
Pathname certificateAuthoritiesPath() const
SSL certificate authorities path ( default: /etc/ssl/certs )
void setPathParams(const std::string &params)
Set the path parameters.
Definition: Url.cc:785
void setHeadRequestsAllowed(bool allowed)
set whether HEAD requests are allowed
static int aliveCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
Callback sending just an alive trigger to the UI, without stats (e.g.
Definition: MediaCurl.cc:1655
pthread_once_t OnceFlag
The OnceFlag variable type.
Definition: Once.h:32
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.
Definition: Url.cc:566
long minDownloadSpeed() const
Minimum download speed (bytes per second) until the connection is dropped.
AuthData_Ptr getCred(const Url &url)
Get credentials for the specified url.
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
Definition: ManagedFile.h:27
time_t _timeNow
Now.
Definition: MediaCurl.cc:217
Url url
Definition: MediaCurl.cc:207
void setConnectTimeout(long t)
set the connect timeout
void setUsername(const std::string &user, EEncoding eflag=zypp::url::E_DECODED)
Set the username in the URL authority.
Definition: Url.cc:724
double dload
Definition: MediaCurl.cc:300
virtual void setupEasy()
initializes the curl easy handle with the data from the url
Definition: MediaCurl.cc:664
#define EXPLICITLY_NO_PROXY
Definition: MediaCurl.cc:45
Convenient building of std::string with boost::format.
Definition: String.h:248
Structure holding values of curlrc options.
Definition: CurlConfig.h:16
bool isValid() const
Verifies the Url.
Definition: Url.cc:483
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
Definition: String.cc:36
Edition * _value
Definition: SysContent.cc:311
AutoDispose<int> calling ::close
Definition: AutoDispose.h:203
virtual bool checkAttachPoint(const Pathname &apoint) const
Verify if the specified directory as attach point (root) as requires by the particular media handler ...
std::string _currentCookieFile
Definition: MediaCurl.h:170
void setProxy(const std::string &proxyhost)
proxy to use if it is enabled
void setFragment(const std::string &fragment, EEncoding eflag=zypp::url::E_DECODED)
Set the fragment string in the URL.
Definition: Url.cc:716
#define ERR
Definition: Logger.h:66
void setPassword(const std::string &password)
sets the auth password
std::string asString() const
Returns a default string representation of the Url object.
Definition: Url.cc:491
void setUsername(const std::string &username)
sets the auth username
bool headRequestsAllowed() const
whether HEAD requests are allowed
void setAnonymousAuth()
sets anonymous authentication (ie: for ftp)
int ZYPP_MEDIA_CURL_IPRESOLVE()
Definition: MediaCurl.cc:181
std::string proxy(const Url &url) const
Definition: ProxyInfo.cc:44
static void setCookieFile(const Pathname &)
Definition: MediaCurl.cc:632
std::string getAuthHint() const
Return a comma separated list of available authentication methods supported by server.
Definition: MediaCurl.cc:1693
static void resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
MediaMultiCurl needs to reset the expected filesize in case a metalink file is downloaded otherwise t...
Definition: MediaCurl.cc:1712
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:358
void setPathName(const std::string &path, EEncoding eflag=zypp::url::E_DECODED)
Set the path name.
Definition: Url.cc:758
static int parseConfig(CurlConfig &config, const std::string &filename="")
Parse a curlrc file and store the result in the config structure.
Definition: CurlConfig.cc:24
int assert_file_mode(const Pathname &path, unsigned mode)
Like assert_file but enforce mode even if the file already exists.
Definition: PathInfo.cc:1161
virtual void doGetFileCopy(const Pathname &srcFilename, const Pathname &targetFilename, callback::SendReport< DownloadProgressReport > &_report, const ByteCount &expectedFileSize_r, RequestOptions options=OPTION_NONE) const
Definition: MediaCurl.cc:1390
std::string userAgentString() const
user agent string
unsigned split(const C_Str &line_r, TOutputIterator result_r, const C_Str &sepchars_r=" \t")
Split line_r into words.
Definition: String.h:519
time_t timeout
Definition: MediaCurl.cc:208
void setProxyPassword(const std::string &proxypass)
sets the proxy password
Abstract base class for 'physical' MediaHandler like MediaCD, etc.
Definition: MediaHandler.h:45
int _dnlPercent
Percent completed or 0 if _dnlTotal is unknown.
Definition: MediaCurl.cc:223
void callOnce(OnceFlag &flag, void(*func)())
Call once function.
Definition: Once.h:50
void setAuthType(const std::string &authtype)
set the allowed authentication types
std::string trim(const std::string &s, const Trim trim_r)
Definition: String.cc:221
int unlink(const Pathname &path)
Like 'unlink'.
Definition: PathInfo.cc:662
const Url _url
Url to handle.
Definition: MediaHandler.h:110
virtual bool getDoesFileExist(const Pathname &filename) const
Repeatedly calls doGetDoesFileExist() until it successfully returns, fails unexpectedly, or user cancels the operation.
Definition: MediaCurl.cc:1042
void setMediaSource(const MediaSourceRef &ref)
Set new media source reference.
int rename(const Pathname &oldpath, const Pathname &newpath)
Like 'rename'.
Definition: PathInfo.cc:704
Just inherits Exception to separate media exceptions.
bool fileSizeExceeded
Definition: MediaCurl.cc:210
virtual void getFileCopy(const Pathname &srcFilename, const Pathname &targetFilename, const ByteCount &expectedFileSize_r) const override
Definition: MediaCurl.cc:996
void disconnect()
Use concrete handler to isconnect media.
do not send a start ProgressReport
Definition: MediaCurl.h:46
#define WAR
Definition: Logger.h:65
TransferSettings _settings
Definition: MediaCurl.h:177
bool startsWith(const C_Str &str_r, const C_Str &prefix_r)
alias for hasPrefix
Definition: String.h:1095
time_t ltime
Definition: MediaCurl.cc:298
bool reached
Definition: MediaCurl.cc:209
std::list< DirEntry > DirContent
Returned by readdir.
Definition: PathInfo.h:547
bool verifyPeerEnabled() const
Whether to verify peer for ssl.
void setTimeout(long t)
set the transfer timeout
bool useProxyFor(const Url &url_r) const
Return true if enabled and url_r does not match noProxy.
Definition: ProxyInfo.cc:56
#define _(MSG)
Definition: Gettext.h:29
std::string proxyUserPassword() const
returns the proxy user and password as a user:pass string
static const char *const agentString()
initialized only once, this gets the agent string which also includes the curl version ...
Definition: MediaCurl.cc:534
Pathname localPath(const Pathname &pathname) const
Files provided will be available at 'localPath(filename)'.
std::string proxyuserpwd
Definition: CurlConfig.h:39
std::string getQueryParam(const std::string &param, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
Definition: Url.cc:654
bool isUseableAttachPoint(const Pathname &path, bool mtab=true) const
Ask media manager, if the specified path is already used as attach point or if there are another atta...
virtual void getFile(const Pathname &filename, const ByteCount &expectedFileSize_r) const override
Call concrete handler to provide file below attach point.
Definition: MediaCurl.cc:987
virtual bool checkAttachPoint(const Pathname &apoint) const
Verify if the specified directory as attach point (root) as requires by the particular media handler ...
Definition: MediaCurl.cc:942
shared_ptr< CurlAuthData > CurlAuthData_Ptr
virtual void getDir(const Pathname &dirname, bool recurse_r) const
Call concrete handler to provide directory content (not recursive!) below attach point.
Definition: MediaCurl.cc:1606
std::string numstring(char n, int w=0)
Definition: String.h:305
virtual void disconnectFrom()
Definition: MediaCurl.cc:949
void getDirectoryYast(std::list< std::string > &retlist, const Pathname &dirname, bool dots=true) const
Retrieve and if available scan dirname/directory.yast.
void resetDispose()
Set no dispose function.
Definition: AutoDispose.h:162
SolvableIdType size_type
Definition: PoolMember.h:152
bool detectDirIndex() const
Media source internally used by MediaManager and MediaHandler.
Definition: MediaSource.h:36
static std::string auth_type_long2str(long auth_type)
Converts a long of ORed CURLAUTH_* identifiers into a string of comma separated list of authenticatio...
void fillSettingsFromUrl(const Url &url, TransferSettings &s)
Fills the settings structure using options passed on the url for example ?timeout=x&proxy=foo.
Definition: MediaCurl.cc:333
curl_slist * _customHeaders
Definition: MediaCurl.h:176
Headers::const_iterator headersBegin() const
begin iterators to additional headers
void setClientCertificatePath(const zypp::Pathname &path)
Sets the SSL client certificate file.
shared_ptr< AuthData > AuthData_Ptr
Definition: MediaUserAuth.h:69
int rmdir(const Pathname &path)
Like 'rmdir'.
Definition: PathInfo.cc:367
#define SET_OPTION(opt, val)
Definition: MediaCurl.cc:554
Pathname attachPoint() const
Return the currently used attach point.
Url getFileUrl(const Pathname &filename) const
concatenate the attach url and the filename to a complete download url
Definition: MediaCurl.cc:971
Base class for Exception.
Definition: Exception.h:143
virtual void getDirInfo(std::list< std::string > &retlist, const Pathname &dirname, bool dots=true) const
Call concrete handler to provide a content list of directory on media via retlist.
Definition: MediaCurl.cc:1639
time_t _timeRcv
Start of no-data timeout.
Definition: MediaCurl.cc:216
const std::string & hint() const
comma separated list of available authentication types
static const char *const distributionFlavorHeader()
initialized only once, this gets the distribution flavor from the target, which we pass in the http h...
Definition: MediaCurl.cc:516
void doGetFileCopyFile(const Pathname &srcFilename, const Pathname &dest, FILE *file, callback::SendReport< DownloadProgressReport > &_report, const ByteCount &expectedFileSize_r, RequestOptions options=OPTION_NONE) const
Definition: MediaCurl.cc:1500
void fillSettingsSystemProxy(const Url &url, TransferSettings &s)
Reads the system proxy configuration and fills the settings structure proxy information.
Definition: MediaCurl.cc:470
callback::SendReport< DownloadProgressReport > * report
Definition: MediaCurl.cc:211
void addHeader(const std::string &header)
add a header, on the form "Foo: Bar"
CURL * curl
Definition: MediaCurl.cc:206
static CURL * progressCallback_getcurl(void *clientp)
Definition: MediaCurl.cc:1685
void setCertificateAuthoritiesPath(const zypp::Pathname &path)
Sets the SSL certificate authorities path.
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
Definition: String.h:445
static long auth_type_str2long(std::string &auth_type_str)
Converts a string of comma separated list of authetication type names into a long of ORed CURLAUTH_* ...
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
Definition: AutoDispose.h:92
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Definition: Exception.cc:91
virtual void attachTo(bool next=false)
Call concrete handler to attach the media.
Definition: MediaCurl.cc:907
double dload_period
Definition: MediaCurl.cc:292
AutoDispose<FILE*> calling ::fclose
Definition: AutoDispose.h:214
static Pathname _cookieFile
Definition: MediaCurl.h:171
double _drateLast
Download rate in last period.
Definition: MediaCurl.cc:226
double drate_avg
Definition: MediaCurl.cc:296
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
Definition: PathInfo.h:813
virtual bool doGetDoesFileExist(const Pathname &filename) const
Definition: MediaCurl.cc:1204
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:527
time_t _timeLast
Start last period(~1sec)
Definition: MediaCurl.cc:215
std::string authType() const
get the allowed authentication types
double uload
Definition: MediaCurl.cc:302
void addCred(const AuthData &cred)
Add new credentials with user callbacks.
#define TRANSFER_TIMEOUT_MAX
Definition: MediaCurl.cc:43
Curl HTTP authentication data.
Definition: MediaUserAuth.h:74
double drate_period
Definition: MediaCurl.cc:290
char _curlError[CURL_ERROR_SIZE]
Definition: MediaCurl.h:175
void setVerifyPeerEnabled(bool enabled)
Sets whether to verify host for ssl.
Pathname clientCertificatePath() const
SSL client certificate file.
void evaluateCurlCode(const zypp::Pathname &filename, CURLcode code, bool timeout) const
Evaluates a curl return code and throws the right MediaException filename Filename being downloaded c...
Definition: MediaCurl.cc:1073
double _dnlNow
Bytes downloaded now.
Definition: MediaCurl.cc:221
Url url() const
Url used.
Definition: MediaHandler.h:507
std::string proxy() const
proxy host
bool proxyEnabled() const
proxy is enabled
long secs
Definition: MediaCurl.cc:294
Convenience interface for handling authentication data of media user.
void setVerifyHostEnabled(bool enabled)
Sets whether to verify host for ssl.
Url manipulation class.
Definition: Url.h:87
void setUserAgentString(const std::string &agent)
sets the user agent ie: "Mozilla v3"
long maxDownloadSpeed() const
Maximum download speed (bytes per second)
static const char *const anonymousIdHeader()
initialized only once, this gets the anonymous id from the target, which we pass in the http header ...
Definition: MediaCurl.cc:498
double _drateTotal
Download rate so far.
Definition: MediaCurl.cc:225
void setProxyEnabled(bool enabled)
whether the proxy is used or not
std::string username() const
auth username
#define DBG
Definition: Logger.h:63
std::string getPassword(EEncoding eflag=zypp::url::E_DECODED) const
Returns the password from the URL authority.
Definition: Url.cc:574
void delQueryParam(const std::string &param)
remove the specified query parameter.
Definition: Url.cc:839
std::string proxyUsername() const
proxy auth username
ByteCount _expectedFileSize
Definition: MediaCurl.cc:212
long timeout() const
transfer timeout
double _dnlTotal
Bytes to download or 0 if unknown.
Definition: MediaCurl.cc:219