libzypp  15.28.6
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  namespace media {
163 
164  namespace {
165  struct ProgressData
166  {
167  ProgressData( CURL *_curl, time_t _timeout = 0, const Url & _url = Url(),
168  ByteCount expectedFileSize_r = 0,
169  callback::SendReport<DownloadProgressReport> *_report = nullptr )
170  : curl( _curl )
171  , url( _url )
172  , timeout( _timeout )
173  , reached( false )
174  , fileSizeExceeded ( false )
175  , report( _report )
176  , _expectedFileSize( expectedFileSize_r )
177  {}
178 
179  CURL *curl;
180  Url url;
181  time_t timeout;
182  bool reached;
184  callback::SendReport<DownloadProgressReport> *report;
185  ByteCount _expectedFileSize;
186 
187  time_t _timeStart = 0;
188  time_t _timeLast = 0;
189  time_t _timeRcv = 0;
190  time_t _timeNow = 0;
191 
192  double _dnlTotal = 0.0;
193  double _dnlLast = 0.0;
194  double _dnlNow = 0.0;
195 
196  int _dnlPercent= 0;
197 
198  double _drateTotal= 0.0;
199  double _drateLast = 0.0;
200 
201  void updateStats( double dltotal = 0.0, double dlnow = 0.0 )
202  {
203  time_t now = _timeNow = time(0);
204 
205  // If called without args (0.0), recompute based on the last values seen
206  if ( dltotal && dltotal != _dnlTotal )
207  _dnlTotal = dltotal;
208 
209  if ( dlnow && dlnow != _dnlNow )
210  {
211  _timeRcv = now;
212  _dnlNow = dlnow;
213  }
214  else if ( !_dnlNow && !_dnlTotal )
215  {
216  // Start time counting as soon as first data arrives.
217  // Skip the connection / redirection time at begin.
218  return;
219  }
220 
221  // init or reset if time jumps back
222  if ( !_timeStart || _timeStart > now )
223  _timeStart = _timeLast = _timeRcv = now;
224 
225  // timeout condition
226  if ( timeout )
227  reached = ( (now - _timeRcv) > timeout );
228 
229  // check if the downloaded data is already bigger than what we expected
230  fileSizeExceeded = _expectedFileSize > 0 && _expectedFileSize < static_cast<ByteCount::SizeType>(_dnlNow);
231 
232  // percentage:
233  if ( _dnlTotal )
234  _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
235 
236  // download rates:
237  _drateTotal = _dnlNow / std::max( int(now - _timeStart), 1 );
238 
239  if ( _timeLast < now )
240  {
241  _drateLast = (_dnlNow - _dnlLast) / int(now - _timeLast);
242  // start new period
243  _timeLast = now;
244  _dnlLast = _dnlNow;
245  }
246  else if ( _timeStart == _timeLast )
248  }
249 
250  int reportProgress() const
251  {
252  if ( fileSizeExceeded )
253  return 1;
254  if ( reached )
255  return 1; // no-data timeout
256  if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
257  return 1; // user requested abort
258  return 0;
259  }
260 
261 
262  // download rate of the last period (cca 1 sec)
263  double drate_period;
264  // bytes downloaded at the start of the last period
265  double dload_period;
266  // seconds from the start of the download
267  long secs;
268  // average download rate
269  double drate_avg;
270  // last time the progress was reported
271  time_t ltime;
272  // bytes downloaded at the moment the progress was last reported
273  double dload;
274  // bytes uploaded at the moment the progress was last reported
275  double uload;
276  };
277 
279 
280  inline void escape( string & str_r,
281  const char char_r, const string & escaped_r ) {
282  for ( string::size_type pos = str_r.find( char_r );
283  pos != string::npos; pos = str_r.find( char_r, pos ) ) {
284  str_r.replace( pos, 1, escaped_r );
285  }
286  }
287 
288  inline string escapedPath( string path_r ) {
289  escape( path_r, ' ', "%20" );
290  return path_r;
291  }
292 
293  inline string unEscape( string text_r ) {
294  char * tmp = curl_unescape( text_r.c_str(), 0 );
295  string ret( tmp );
296  curl_free( tmp );
297  return ret;
298  }
299 
300  }
301 
307 {
308  std::string param(url.getQueryParam("timeout"));
309  if( !param.empty())
310  {
311  long num = str::strtonum<long>(param);
312  if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
313  s.setTimeout(num);
314  }
315 
316  if ( ! url.getUsername().empty() )
317  {
318  s.setUsername(url.getUsername());
319  if ( url.getPassword().size() )
320  s.setPassword(url.getPassword());
321  }
322  else
323  {
324  // if there is no username, set anonymous auth
325  if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
326  s.setAnonymousAuth();
327  }
328 
329  if ( url.getScheme() == "https" )
330  {
331  s.setVerifyPeerEnabled(false);
332  s.setVerifyHostEnabled(false);
333 
334  std::string verify( url.getQueryParam("ssl_verify"));
335  if( verify.empty() ||
336  verify == "yes")
337  {
338  s.setVerifyPeerEnabled(true);
339  s.setVerifyHostEnabled(true);
340  }
341  else if( verify == "no")
342  {
343  s.setVerifyPeerEnabled(false);
344  s.setVerifyHostEnabled(false);
345  }
346  else
347  {
348  std::vector<std::string> flags;
349  std::vector<std::string>::const_iterator flag;
350  str::split( verify, std::back_inserter(flags), ",");
351  for(flag = flags.begin(); flag != flags.end(); ++flag)
352  {
353  if( *flag == "host")
354  s.setVerifyHostEnabled(true);
355  else if( *flag == "peer")
356  s.setVerifyPeerEnabled(true);
357  else
358  ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
359  }
360  }
361  }
362 
363  Pathname ca_path( url.getQueryParam("ssl_capath") );
364  if( ! ca_path.empty())
365  {
366  if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
367  ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
368  else
370  }
371 
372  Pathname client_cert( url.getQueryParam("ssl_clientcert") );
373  if( ! client_cert.empty())
374  {
375  if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
376  ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientcert file"));
377  else
378  s.setClientCertificatePath(client_cert);
379  }
380  Pathname client_key( url.getQueryParam("ssl_clientkey") );
381  if( ! client_key.empty())
382  {
383  if( !PathInfo(client_key).isFile() || !client_key.absolute())
384  ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
385  else
386  s.setClientKeyPath(client_key);
387  }
388 
389  param = url.getQueryParam( "proxy" );
390  if ( ! param.empty() )
391  {
392  if ( param == EXPLICITLY_NO_PROXY ) {
393  // Workaround TransferSettings shortcoming: With an
394  // empty proxy string, code will continue to look for
395  // valid proxy settings. So set proxy to some non-empty
396  // string, to indicate it has been explicitly disabled.
398  s.setProxyEnabled(false);
399  }
400  else {
401  string proxyport( url.getQueryParam( "proxyport" ) );
402  if ( ! proxyport.empty() ) {
403  param += ":" + proxyport;
404  }
405  s.setProxy(param);
406  s.setProxyEnabled(true);
407  }
408  }
409 
410  param = url.getQueryParam( "proxyuser" );
411  if ( ! param.empty() )
412  {
413  s.setProxyUsername(param);
414  s.setProxyPassword(url.getQueryParam( "proxypass" ));
415  }
416 
417  // HTTP authentication type
418  param = url.getQueryParam("auth");
419  if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
420  {
421  try
422  {
423  CurlAuthData::auth_type_str2long(param); // check if we know it
424  }
425  catch (MediaException & ex_r)
426  {
427  DBG << "Rethrowing as MediaUnauthorizedException.";
428  ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
429  }
430  s.setAuthType(param);
431  }
432 
433  // workarounds
434  param = url.getQueryParam("head_requests");
435  if( !param.empty() && param == "no" )
436  s.setHeadRequestsAllowed(false);
437 }
438 
444 {
445  ProxyInfo proxy_info;
446  if ( proxy_info.useProxyFor( url ) )
447  {
448  // We must extract any 'user:pass' from the proxy url
449  // otherwise they won't make it into curl (.curlrc wins).
450  try {
451  Url u( proxy_info.proxy( url ) );
452  s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
453  // don't overwrite explicit auth settings
454  if ( s.proxyUsername().empty() )
455  {
456  s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
457  s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
458  }
459  s.setProxyEnabled( true );
460  }
461  catch (...) {} // no proxy if URL is malformed
462  }
463 }
464 
465 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
466 
471 static const char *const anonymousIdHeader()
472 {
473  // we need to add the release and identifier to the
474  // agent string.
475  // The target could be not initialized, and then this information
476  // is guessed.
477  static const std::string _value(
479  "X-ZYpp-AnonymousId: %s",
480  Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
481  );
482  return _value.c_str();
483 }
484 
489 static const char *const distributionFlavorHeader()
490 {
491  // we need to add the release and identifier to the
492  // agent string.
493  // The target could be not initialized, and then this information
494  // is guessed.
495  static const std::string _value(
497  "X-ZYpp-DistributionFlavor: %s",
498  Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
499  );
500  return _value.c_str();
501 }
502 
507 static const char *const agentString()
508 {
509  // we need to add the release and identifier to the
510  // agent string.
511  // The target could be not initialized, and then this information
512  // is guessed.
513  static const std::string _value(
514  str::form(
515  "ZYpp %s (curl %s) %s"
516  , VERSION
517  , curl_version_info(CURLVERSION_NOW)->version
518  , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
519  )
520  );
521  return _value.c_str();
522 }
523 
524 // we use this define to unbloat code as this C setting option
525 // and catching exception is done frequently.
527 #define SET_OPTION(opt,val) do { \
528  ret = curl_easy_setopt ( _curl, opt, val ); \
529  if ( ret != 0) { \
530  ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
531  } \
532  } while ( false )
533 
534 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
535 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
536 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
537 
538 MediaCurl::MediaCurl( const Url & url_r,
539  const Pathname & attach_point_hint_r )
540  : MediaHandler( url_r, attach_point_hint_r,
541  "/", // urlpath at attachpoint
542  true ), // does_download
543  _curl( NULL ),
544  _customHeaders(0L)
545 {
546  _curlError[0] = '\0';
547  _curlDebug = 0L;
548 
549  MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
550 
551  globalInitOnce();
552 
553  if( !attachPoint().empty())
554  {
555  PathInfo ainfo(attachPoint());
556  Pathname apath(attachPoint() + "XXXXXX");
557  char *atemp = ::strdup( apath.asString().c_str());
558  char *atest = NULL;
559  if( !ainfo.isDir() || !ainfo.userMayRWX() ||
560  atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
561  {
562  WAR << "attach point " << ainfo.path()
563  << " is not useable for " << url_r.getScheme() << endl;
564  setAttachPoint("", true);
565  }
566  else if( atest != NULL)
567  ::rmdir(atest);
568 
569  if( atemp != NULL)
570  ::free(atemp);
571  }
572 }
573 
575 {
576  Url curlUrl (url);
577  curlUrl.setUsername( "" );
578  curlUrl.setPassword( "" );
579  curlUrl.setPathParams( "" );
580  curlUrl.setFragment( "" );
581  curlUrl.delQueryParam("cookies");
582  curlUrl.delQueryParam("proxy");
583  curlUrl.delQueryParam("proxyport");
584  curlUrl.delQueryParam("proxyuser");
585  curlUrl.delQueryParam("proxypass");
586  curlUrl.delQueryParam("ssl_capath");
587  curlUrl.delQueryParam("ssl_verify");
588  curlUrl.delQueryParam("ssl_clientcert");
589  curlUrl.delQueryParam("timeout");
590  curlUrl.delQueryParam("auth");
591  curlUrl.delQueryParam("username");
592  curlUrl.delQueryParam("password");
593  curlUrl.delQueryParam("mediahandler");
594  curlUrl.delQueryParam("credentials");
595  curlUrl.delQueryParam("head_requests");
596  return curlUrl;
597 }
598 
600 {
601  return _settings;
602 }
603 
604 
605 void MediaCurl::setCookieFile( const Pathname &fileName )
606 {
607  _cookieFile = fileName;
608 }
609 
611 
612 void MediaCurl::checkProtocol(const Url &url) const
613 {
614  curl_version_info_data *curl_info = NULL;
615  curl_info = curl_version_info(CURLVERSION_NOW);
616  // curl_info does not need any free (is static)
617  if (curl_info->protocols)
618  {
619  const char * const *proto;
620  std::string scheme( url.getScheme());
621  bool found = false;
622  for(proto=curl_info->protocols; !found && *proto; ++proto)
623  {
624  if( scheme == std::string((const char *)*proto))
625  found = true;
626  }
627  if( !found)
628  {
629  std::string msg("Unsupported protocol '");
630  msg += scheme;
631  msg += "'";
633  }
634  }
635 }
636 
638 {
639  {
640  char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
641  _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
642  if( _curlDebug > 0)
643  {
644  curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
645  curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
646  curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
647  }
648  }
649 
650  curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
651  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
652  if ( ret != 0 ) {
653  ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
654  }
655 
656  SET_OPTION(CURLOPT_FAILONERROR, 1L);
657  SET_OPTION(CURLOPT_NOSIGNAL, 1L);
658 
659  // create non persistant settings
660  // so that we don't add headers twice
661  TransferSettings vol_settings(_settings);
662 
663  // add custom headers for download.opensuse.org (bsc#955801)
664  if ( _url.getHost() == "download.opensuse.org" )
665  {
666  vol_settings.addHeader(anonymousIdHeader());
667  vol_settings.addHeader(distributionFlavorHeader());
668  }
669  vol_settings.addHeader("Pragma:");
670 
671  _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
673 
675 
676  // fill some settings from url query parameters
677  try
678  {
680  }
681  catch ( const MediaException &e )
682  {
683  disconnectFrom();
684  ZYPP_RETHROW(e);
685  }
686  // if the proxy was not set (or explicitly unset) by url, then look...
687  if ( _settings.proxy().empty() )
688  {
689  // ...at the system proxy settings
691  }
692 
696  SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
697  // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
698  // just in case curl does not trigger its progress callback frequently
699  // enough.
700  if ( _settings.timeout() )
701  {
702  SET_OPTION(CURLOPT_TIMEOUT, 3600L);
703  }
704 
705  // follow any Location: header that the server sends as part of
706  // an HTTP header (#113275)
707  SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
708  // 3 redirects seem to be too few in some cases (bnc #465532)
709  SET_OPTION(CURLOPT_MAXREDIRS, 6L);
710 
711  if ( _url.getScheme() == "https" )
712  {
713 #if CURLVERSION_AT_LEAST(7,19,4)
714  // restrict following of redirections from https to https only
715  SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
716 #endif
717 
720  {
721  SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
722  }
723 
724  if( ! _settings.clientCertificatePath().empty() )
725  {
726  SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
727  }
728  if( ! _settings.clientKeyPath().empty() )
729  {
730  SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
731  }
732 
733 #ifdef CURLSSLOPT_ALLOW_BEAST
734  // see bnc#779177
735  ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
736  if ( ret != 0 ) {
737  disconnectFrom();
739  }
740 #endif
741  SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
742  SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
743  // bnc#903405 - POODLE: libzypp should only talk TLS
744  SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
745  }
746 
747  SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
748 
749  /*---------------------------------------------------------------*
750  CURLOPT_USERPWD: [user name]:[password]
751 
752  Url::username/password -> CURLOPT_USERPWD
753  If not provided, anonymous FTP identification
754  *---------------------------------------------------------------*/
755 
756  if ( _settings.userPassword().size() )
757  {
758  SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
759  string use_auth = _settings.authType();
760  if (use_auth.empty())
761  use_auth = "digest,basic"; // our default
762  long auth = CurlAuthData::auth_type_str2long(use_auth);
763  if( auth != CURLAUTH_NONE)
764  {
765  DBG << "Enabling HTTP authentication methods: " << use_auth
766  << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
767  SET_OPTION(CURLOPT_HTTPAUTH, auth);
768  }
769  }
770 
771  if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
772  {
773  DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
774  SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
775  SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
776  /*---------------------------------------------------------------*
777  * CURLOPT_PROXYUSERPWD: [user name]:[password]
778  *
779  * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
780  * If not provided, $HOME/.curlrc is evaluated
781  *---------------------------------------------------------------*/
782 
783  string proxyuserpwd = _settings.proxyUserPassword();
784 
785  if ( proxyuserpwd.empty() )
786  {
787  CurlConfig curlconf;
788  CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
789  if ( curlconf.proxyuserpwd.empty() )
790  DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
791  else
792  {
793  proxyuserpwd = curlconf.proxyuserpwd;
794  DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
795  }
796  }
797  else
798  {
799  DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
800  }
801 
802  if ( ! proxyuserpwd.empty() )
803  {
804  SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
805  }
806  }
807 #if CURLVERSION_AT_LEAST(7,19,4)
808  else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
809  {
810  // Explicitly disabled in URL (see fillSettingsFromUrl()).
811  // This should also prevent libcurl from looking into the environment.
812  DBG << "Proxy: explicitly NOPROXY" << endl;
813  SET_OPTION(CURLOPT_NOPROXY, "*");
814  }
815 #endif
816  else
817  {
818  DBG << "Proxy: not explicitly set" << endl;
819  DBG << "Proxy: libcurl may look into the environment" << endl;
820  }
821 
823  if ( _settings.minDownloadSpeed() != 0 )
824  {
825  SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
826  // default to 10 seconds at low speed
827  SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
828  }
829 
830 #if CURLVERSION_AT_LEAST(7,15,5)
831  if ( _settings.maxDownloadSpeed() != 0 )
832  SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
833 #endif
834 
835  /*---------------------------------------------------------------*
836  *---------------------------------------------------------------*/
837 
838  _currentCookieFile = _cookieFile.asString();
840  if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
841  SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
842  else
843  MIL << "No cookies requested" << endl;
844  SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
845  SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
846  SET_OPTION(CURLOPT_NOPROGRESS, 0L);
847 
848 #if CURLVERSION_AT_LEAST(7,18,0)
849  // bnc #306272
850  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
851 #endif
852  // append settings custom headers to curl
853  for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
854  it != vol_settings.headersEnd();
855  ++it )
856  {
857  // MIL << "HEADER " << *it << std::endl;
858 
859  _customHeaders = curl_slist_append(_customHeaders, it->c_str());
860  if ( !_customHeaders )
862  }
863 
864  SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
865 }
866 
868 
869 
870 void MediaCurl::attachTo (bool next)
871 {
872  if ( next )
874 
875  if ( !_url.isValid() )
877 
880  {
881  std::string mountpoint = createAttachPoint().asString();
882 
883  if( mountpoint.empty())
885 
886  setAttachPoint( mountpoint, true);
887  }
888 
889  disconnectFrom(); // clean _curl if needed
890  _curl = curl_easy_init();
891  if ( !_curl ) {
893  }
894  try
895  {
896  setupEasy();
897  }
898  catch (Exception & ex)
899  {
900  disconnectFrom();
901  ZYPP_RETHROW(ex);
902  }
903 
904  // FIXME: need a derived class to propelly compare url's
906  setMediaSource(media);
907 }
908 
909 bool
910 MediaCurl::checkAttachPoint(const Pathname &apoint) const
911 {
912  return MediaHandler::checkAttachPoint( apoint, true, true);
913 }
914 
916 
918 {
919  if ( _customHeaders )
920  {
921  curl_slist_free_all(_customHeaders);
922  _customHeaders = 0L;
923  }
924 
925  if ( _curl )
926  {
927  curl_easy_cleanup( _curl );
928  _curl = NULL;
929  }
930 }
931 
933 
934 void MediaCurl::releaseFrom( const std::string & ejectDev )
935 {
936  disconnect();
937 }
938 
939 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
940 {
941  // Simply extend the URLs pathname. An 'absolute' URL path
942  // is achieved by encoding the leading '/' in an URL path:
943  // URL: ftp://user@server -> ~user
944  // URL: ftp://user@server/ -> ~user
945  // URL: ftp://user@server// -> ~user
946  // URL: ftp://user@server/%2F -> /
947  // ^- this '/' is just a separator
948  Url newurl( _url );
949  newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
950  return newurl;
951 }
952 
954 
955 void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
956 {
957  // Use absolute file name to prevent access of files outside of the
958  // hierarchy below the attach point.
959  getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
960 }
961 
963 
964 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
965 {
967 
968  Url fileurl(getFileUrl(filename));
969 
970  bool retry = false;
971 
972  do
973  {
974  try
975  {
976  doGetFileCopy(filename, target, report, expectedFileSize_r);
977  retry = false;
978  }
979  // retry with proper authentication data
980  catch (MediaUnauthorizedException & ex_r)
981  {
982  if(authenticate(ex_r.hint(), !retry))
983  retry = true;
984  else
985  {
986  report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
987  ZYPP_RETHROW(ex_r);
988  }
989  }
990  // unexpected exception
991  catch (MediaException & excpt_r)
992  {
993  // FIXME: error number fix
994  report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
995  ZYPP_RETHROW(excpt_r);
996  }
997  }
998  while (retry);
999 
1000  report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
1001 }
1002 
1004 
1005 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
1006 {
1007  bool retry = false;
1008 
1009  do
1010  {
1011  try
1012  {
1013  return doGetDoesFileExist( filename );
1014  }
1015  // authentication problem, retry with proper authentication data
1016  catch (MediaUnauthorizedException & ex_r)
1017  {
1018  if(authenticate(ex_r.hint(), !retry))
1019  retry = true;
1020  else
1021  ZYPP_RETHROW(ex_r);
1022  }
1023  // unexpected exception
1024  catch (MediaException & excpt_r)
1025  {
1026  ZYPP_RETHROW(excpt_r);
1027  }
1028  }
1029  while (retry);
1030 
1031  return false;
1032 }
1033 
1035 
1036 void MediaCurl::evaluateCurlCode(const Pathname &filename,
1037  CURLcode code,
1038  bool timeout_reached) const
1039 {
1040  if ( code != 0 )
1041  {
1042  Url url;
1043  if (filename.empty())
1044  url = _url;
1045  else
1046  url = getFileUrl(filename);
1047 
1048  std::string err;
1049  try
1050  {
1051  switch ( code )
1052  {
1053  case CURLE_UNSUPPORTED_PROTOCOL:
1054  case CURLE_URL_MALFORMAT:
1055  case CURLE_URL_MALFORMAT_USER:
1056  err = " Bad URL";
1057  break;
1058  case CURLE_LOGIN_DENIED:
1059  ZYPP_THROW(
1060  MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
1061  break;
1062  case CURLE_HTTP_RETURNED_ERROR:
1063  {
1064  long httpReturnCode = 0;
1065  CURLcode infoRet = curl_easy_getinfo( _curl,
1066  CURLINFO_RESPONSE_CODE,
1067  &httpReturnCode );
1068  if ( infoRet == CURLE_OK )
1069  {
1070  string msg = "HTTP response: " + str::numstring( httpReturnCode );
1071  switch ( httpReturnCode )
1072  {
1073  case 401:
1074  {
1075  string auth_hint = getAuthHint();
1076 
1077  DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1078  DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1079 
1081  url, "Login failed.", _curlError, auth_hint
1082  ));
1083  }
1084 
1085  case 502: // bad gateway (bnc #1070851)
1086  case 503: // service temporarily unavailable (bnc #462545)
1088  case 504: // gateway timeout
1090  case 403:
1091  {
1092  string msg403;
1093  if (url.asString().find("novell.com") != string::npos)
1094  msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1095  ZYPP_THROW(MediaForbiddenException(url, msg403));
1096  }
1097  case 404:
1098  case 410:
1100  }
1101 
1102  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1104  }
1105  else
1106  {
1107  string msg = "Unable to retrieve HTTP response:";
1108  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1110  }
1111  }
1112  break;
1113  case CURLE_FTP_COULDNT_RETR_FILE:
1114 #if CURLVERSION_AT_LEAST(7,16,0)
1115  case CURLE_REMOTE_FILE_NOT_FOUND:
1116 #endif
1117  case CURLE_FTP_ACCESS_DENIED:
1118  case CURLE_TFTP_NOTFOUND:
1119  err = "File not found";
1121  break;
1122  case CURLE_BAD_PASSWORD_ENTERED:
1123  case CURLE_FTP_USER_PASSWORD_INCORRECT:
1124  err = "Login failed";
1125  break;
1126  case CURLE_COULDNT_RESOLVE_PROXY:
1127  case CURLE_COULDNT_RESOLVE_HOST:
1128  case CURLE_COULDNT_CONNECT:
1129  case CURLE_FTP_CANT_GET_HOST:
1130  err = "Connection failed";
1131  break;
1132  case CURLE_WRITE_ERROR:
1133  err = "Write error";
1134  break;
1135  case CURLE_PARTIAL_FILE:
1136  case CURLE_OPERATION_TIMEDOUT:
1137  timeout_reached = true; // fall though to TimeoutException
1138  // fall though...
1139  case CURLE_ABORTED_BY_CALLBACK:
1140  if( timeout_reached )
1141  {
1142  err = "Timeout reached";
1144  }
1145  else
1146  {
1147  err = "User abort";
1148  }
1149  break;
1150  case CURLE_SSL_PEER_CERTIFICATE:
1151  default:
1152  err = "Curl error " + str::numstring( code );
1153  break;
1154  }
1155 
1156  // uhm, no 0 code but unknown curl exception
1158  }
1159  catch (const MediaException & excpt_r)
1160  {
1161  ZYPP_RETHROW(excpt_r);
1162  }
1163  }
1164  else
1165  {
1166  // actually the code is 0, nothing happened
1167  }
1168 }
1169 
1171 
1172 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1173 {
1174  DBG << filename.asString() << endl;
1175 
1176  if(!_url.isValid())
1178 
1179  if(_url.getHost().empty())
1181 
1182  Url url(getFileUrl(filename));
1183 
1184  DBG << "URL: " << url.asString() << endl;
1185  // Use URL without options and without username and passwd
1186  // (some proxies dislike them in the URL).
1187  // Curl seems to need the just scheme, hostname and a path;
1188  // the rest was already passed as curl options (in attachTo).
1189  Url curlUrl( clearQueryString(url) );
1190 
1191  //
1192  // See also Bug #154197 and ftp url definition in RFC 1738:
1193  // The url "ftp://user@host/foo/bar/file" contains a path,
1194  // that is relative to the user's home.
1195  // The url "ftp://user@host//foo/bar/file" (or also with
1196  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1197  // contains an absolute path.
1198  //
1199  string urlBuffer( curlUrl.asString());
1200  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1201  urlBuffer.c_str() );
1202  if ( ret != 0 ) {
1204  }
1205 
1206  // instead of returning no data with NOBODY, we return
1207  // little data, that works with broken servers, and
1208  // works for ftp as well, because retrieving only headers
1209  // ftp will return always OK code ?
1210  // See http://curl.haxx.se/docs/knownbugs.html #58
1211  if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1213  ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1214  else
1215  ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1216 
1217  if ( ret != 0 ) {
1218  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1219  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1220  /* yes, this is why we never got to get NOBODY working before,
1221  because setting it changes this option too, and we also
1222  need to reset it
1223  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1224  */
1225  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1227  }
1228 
1229  AutoFILE file { ::fopen( "/dev/null", "w" ) };
1230  if ( !file ) {
1231  ERR << "fopen failed for /dev/null" << endl;
1232  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1233  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1234  /* yes, this is why we never got to get NOBODY working before,
1235  because setting it changes this option too, and we also
1236  need to reset it
1237  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1238  */
1239  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1240  if ( ret != 0 ) {
1242  }
1243  ZYPP_THROW(MediaWriteException("/dev/null"));
1244  }
1245 
1246  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, (*file) );
1247  if ( ret != 0 ) {
1248  std::string err( _curlError);
1249  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1250  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1251  /* yes, this is why we never got to get NOBODY working before,
1252  because setting it changes this option too, and we also
1253  need to reset it
1254  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1255  */
1256  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1257  if ( ret != 0 ) {
1259  }
1261  }
1262 
1263  CURLcode ok = curl_easy_perform( _curl );
1264  MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1265 
1266  // reset curl settings
1267  if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1268  {
1269  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1270  if ( ret != 0 ) {
1272  }
1273 
1274  /* yes, this is why we never got to get NOBODY working before,
1275  because setting it changes this option too, and we also
1276  need to reset it
1277  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1278  */
1279  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1280  if ( ret != 0 ) {
1282  }
1283 
1284  }
1285  else
1286  {
1287  // for FTP we set different options
1288  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1289  if ( ret != 0 ) {
1291  }
1292  }
1293 
1294  // as we are not having user interaction, the user can't cancel
1295  // the file existence checking, a callback or timeout return code
1296  // will be always a timeout.
1297  try {
1298  evaluateCurlCode( filename, ok, true /* timeout */);
1299  }
1300  catch ( const MediaFileNotFoundException &e ) {
1301  // if the file did not exist then we can return false
1302  return false;
1303  }
1304  catch ( const MediaException &e ) {
1305  // some error, we are not sure about file existence, rethrw
1306  ZYPP_RETHROW(e);
1307  }
1308  // exists
1309  return ( ok == CURLE_OK );
1310 }
1311 
1313 
1314 
1315 #if DETECT_DIR_INDEX
1316 bool MediaCurl::detectDirIndex() const
1317 {
1318  if(_url.getScheme() != "http" && _url.getScheme() != "https")
1319  return false;
1320  //
1321  // try to check the effective url and set the not_a_file flag
1322  // if the url path ends with a "/", what usually means, that
1323  // we've received a directory index (index.html content).
1324  //
1325  // Note: This may be dangerous and break file retrieving in
1326  // case of some server redirections ... ?
1327  //
1328  bool not_a_file = false;
1329  char *ptr = NULL;
1330  CURLcode ret = curl_easy_getinfo( _curl,
1331  CURLINFO_EFFECTIVE_URL,
1332  &ptr);
1333  if ( ret == CURLE_OK && ptr != NULL)
1334  {
1335  try
1336  {
1337  Url eurl( ptr);
1338  std::string path( eurl.getPathName());
1339  if( !path.empty() && path != "/" && *path.rbegin() == '/')
1340  {
1341  DBG << "Effective url ("
1342  << eurl
1343  << ") seems to provide the index of a directory"
1344  << endl;
1345  not_a_file = true;
1346  }
1347  }
1348  catch( ... )
1349  {}
1350  }
1351  return not_a_file;
1352 }
1353 #endif
1354 
1356 
1357 void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1358 {
1359  Pathname dest = target.absolutename();
1360  if( assert_dir( dest.dirname() ) )
1361  {
1362  DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1363  ZYPP_THROW( MediaSystemException(getFileUrl(filename), "System error on " + dest.dirname().asString()) );
1364  }
1365 
1366  ManagedFile destNew { target.extend( ".new.zypp.XXXXXX" ) };
1367  AutoFILE file;
1368  {
1369  AutoFREE<char> buf { ::strdup( (*destNew).c_str() ) };
1370  if( ! buf )
1371  {
1372  ERR << "out of memory for temp file name" << endl;
1373  ZYPP_THROW(MediaSystemException(getFileUrl(filename), "out of memory for temp file name"));
1374  }
1375 
1376  AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1377  if( tmp_fd == -1 )
1378  {
1379  ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1380  ZYPP_THROW(MediaWriteException(destNew));
1381  }
1382  destNew = ManagedFile( (*buf), filesystem::unlink );
1383 
1384  file = ::fdopen( tmp_fd, "we" );
1385  if ( ! file )
1386  {
1387  ERR << "fopen failed for file '" << destNew << "'" << endl;
1388  ZYPP_THROW(MediaWriteException(destNew));
1389  }
1390  tmp_fd.resetDispose(); // don't close it here! ::fdopen moved ownership to file
1391  }
1392 
1393  DBG << "dest: " << dest << endl;
1394  DBG << "temp: " << destNew << endl;
1395 
1396  // set IFMODSINCE time condition (no download if not modified)
1397  if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1398  {
1399  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1400  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1401  }
1402  else
1403  {
1404  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1405  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1406  }
1407  try
1408  {
1409  doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
1410  }
1411  catch (Exception &e)
1412  {
1413  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1414  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1415  ZYPP_RETHROW(e);
1416  }
1417 
1418  long httpReturnCode = 0;
1419  CURLcode infoRet = curl_easy_getinfo(_curl,
1420  CURLINFO_RESPONSE_CODE,
1421  &httpReturnCode);
1422  bool modified = true;
1423  if (infoRet == CURLE_OK)
1424  {
1425  DBG << "HTTP response: " + str::numstring(httpReturnCode);
1426  if ( httpReturnCode == 304
1427  || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1428  {
1429  DBG << " Not modified.";
1430  modified = false;
1431  }
1432  DBG << endl;
1433  }
1434  else
1435  {
1436  WAR << "Could not get the reponse code." << endl;
1437  }
1438 
1439  if (modified || infoRet != CURLE_OK)
1440  {
1441  // apply umask
1442  if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1443  {
1444  ERR << "Failed to chmod file " << destNew << endl;
1445  }
1446 
1447  file.resetDispose(); // we're going to close it manually here
1448  if ( ::fclose( file ) )
1449  {
1450  ERR << "Fclose failed for file '" << destNew << "'" << endl;
1451  ZYPP_THROW(MediaWriteException(destNew));
1452  }
1453 
1454  // move the temp file into dest
1455  if ( rename( destNew, dest ) != 0 ) {
1456  ERR << "Rename failed" << endl;
1458  }
1459  destNew.resetDispose(); // no more need to unlink it
1460  }
1461 
1462  DBG << "done: " << PathInfo(dest) << endl;
1463 }
1464 
1466 
1467 void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1468 {
1469  DBG << filename.asString() << endl;
1470 
1471  if(!_url.isValid())
1473 
1474  if(_url.getHost().empty())
1476 
1477  Url url(getFileUrl(filename));
1478 
1479  DBG << "URL: " << url.asString() << endl;
1480  // Use URL without options and without username and passwd
1481  // (some proxies dislike them in the URL).
1482  // Curl seems to need the just scheme, hostname and a path;
1483  // the rest was already passed as curl options (in attachTo).
1484  Url curlUrl( clearQueryString(url) );
1485 
1486  //
1487  // See also Bug #154197 and ftp url definition in RFC 1738:
1488  // The url "ftp://user@host/foo/bar/file" contains a path,
1489  // that is relative to the user's home.
1490  // The url "ftp://user@host//foo/bar/file" (or also with
1491  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1492  // contains an absolute path.
1493  //
1494  string urlBuffer( curlUrl.asString());
1495  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1496  urlBuffer.c_str() );
1497  if ( ret != 0 ) {
1499  }
1500 
1501  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1502  if ( ret != 0 ) {
1504  }
1505 
1506  // Set callback and perform.
1507  ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
1508  if (!(options & OPTION_NO_REPORT_START))
1509  report->start(url, dest);
1510  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1511  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1512  }
1513 
1514  ret = curl_easy_perform( _curl );
1515 #if CURLVERSION_AT_LEAST(7,19,4)
1516  // bnc#692260: If the client sends a request with an If-Modified-Since header
1517  // with a future date for the server, the server may respond 200 sending a
1518  // zero size file.
1519  // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1520  if ( ftell(file) == 0 && ret == 0 )
1521  {
1522  long httpReturnCode = 33;
1523  if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1524  {
1525  long conditionUnmet = 33;
1526  if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1527  {
1528  WAR << "TIMECONDITION unmet - retry without." << endl;
1529  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1530  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1531  ret = curl_easy_perform( _curl );
1532  }
1533  }
1534  }
1535 #endif
1536 
1537  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1538  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1539  }
1540 
1541  if ( ret != 0 )
1542  {
1543  ERR << "curl error: " << ret << ": " << _curlError
1544  << ", temp file size " << ftell(file)
1545  << " bytes." << endl;
1546 
1547  // the timeout is determined by the progress data object
1548  // which holds whether the timeout was reached or not,
1549  // otherwise it would be a user cancel
1550  try {
1551 
1552  if ( progressData.fileSizeExceeded )
1553  ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
1554 
1555  evaluateCurlCode( filename, ret, progressData.reached );
1556  }
1557  catch ( const MediaException &e ) {
1558  // some error, we are not sure about file existence, rethrw
1559  ZYPP_RETHROW(e);
1560  }
1561  }
1562 
1563 #if DETECT_DIR_INDEX
1564  if (!ret && detectDirIndex())
1565  {
1567  }
1568 #endif // DETECT_DIR_INDEX
1569 }
1570 
1572 
1573 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1574 {
1575  filesystem::DirContent content;
1576  getDirInfo( content, dirname, /*dots*/false );
1577 
1578  for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1579  Pathname filename = dirname + it->name;
1580  int res = 0;
1581 
1582  switch ( it->type ) {
1583  case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1584  case filesystem::FT_FILE:
1585  getFile( filename, 0 );
1586  break;
1587  case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1588  if ( recurse_r ) {
1589  getDir( filename, recurse_r );
1590  } else {
1591  res = assert_dir( localPath( filename ) );
1592  if ( res ) {
1593  WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1594  }
1595  }
1596  break;
1597  default:
1598  // don't provide devices, sockets, etc.
1599  break;
1600  }
1601  }
1602 }
1603 
1605 
1606 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1607  const Pathname & dirname, bool dots ) const
1608 {
1609  getDirectoryYast( retlist, dirname, dots );
1610 }
1611 
1613 
1615  const Pathname & dirname, bool dots ) const
1616 {
1617  getDirectoryYast( retlist, dirname, dots );
1618 }
1619 
1621 //
1622 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1623 {
1624  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1625  if( pdata )
1626  {
1627  // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1628  // prevent a percentage raise while downloading a metalink file. Download
1629  // activity however is indicated by propagating the download rate (via dlnow).
1630  pdata->updateStats( 0.0, dlnow );
1631  return pdata->reportProgress();
1632  }
1633  return 0;
1634 }
1635 
1636 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1637 {
1638  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1639  if( pdata )
1640  {
1641  // work around curl bug that gives us old data
1642  long httpReturnCode = 0;
1643  if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1644  return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1645 
1646  pdata->updateStats( dltotal, dlnow );
1647  return pdata->reportProgress();
1648  }
1649  return 0;
1650 }
1651 
1653 {
1654  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1655  return pdata ? pdata->curl : 0;
1656 }
1657 
1659 
1661 {
1662  long auth_info = CURLAUTH_NONE;
1663 
1664  CURLcode infoRet =
1665  curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1666 
1667  if(infoRet == CURLE_OK)
1668  {
1669  return CurlAuthData::auth_type_long2str(auth_info);
1670  }
1671 
1672  return "";
1673 }
1674 
1679 void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
1680 {
1681  ProgressData *data = reinterpret_cast<ProgressData *>(clientp);
1682  if ( data ) {
1683  data->_expectedFileSize = expectedFileSize;
1684  }
1685 }
1686 
1688 
1689 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1690 {
1692  Target_Ptr target = zypp::getZYpp()->getTarget();
1693  CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1694  CurlAuthData_Ptr credentials;
1695 
1696  // get stored credentials
1697  AuthData_Ptr cmcred = cm.getCred(_url);
1698 
1699  if (cmcred && firstTry)
1700  {
1701  credentials.reset(new CurlAuthData(*cmcred));
1702  DBG << "got stored credentials:" << endl << *credentials << endl;
1703  }
1704  // if not found, ask user
1705  else
1706  {
1707 
1708  CurlAuthData_Ptr curlcred;
1709  curlcred.reset(new CurlAuthData());
1711 
1712  // preset the username if present in current url
1713  if (!_url.getUsername().empty() && firstTry)
1714  curlcred->setUsername(_url.getUsername());
1715  // if CM has found some credentials, preset the username from there
1716  else if (cmcred)
1717  curlcred->setUsername(cmcred->username());
1718 
1719  // indicate we have no good credentials from CM
1720  cmcred.reset();
1721 
1722  string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1723 
1724  // set available authentication types from the exception
1725  // might be needed in prompt
1726  curlcred->setAuthType(availAuthTypes);
1727 
1728  // ask user
1729  if (auth_report->prompt(_url, prompt_msg, *curlcred))
1730  {
1731  DBG << "callback answer: retry" << endl
1732  << "CurlAuthData: " << *curlcred << endl;
1733 
1734  if (curlcred->valid())
1735  {
1736  credentials = curlcred;
1737  // if (credentials->username() != _url.getUsername())
1738  // _url.setUsername(credentials->username());
1746  }
1747  }
1748  else
1749  {
1750  DBG << "callback answer: cancel" << endl;
1751  }
1752  }
1753 
1754  // set username and password
1755  if (credentials)
1756  {
1757  // HACK, why is this const?
1758  const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1759  const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1760 
1761  // set username and password
1762  CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1764 
1765  // set available authentication types from the exception
1766  if (credentials->authType() == CURLAUTH_NONE)
1767  credentials->setAuthType(availAuthTypes);
1768 
1769  // set auth type (seems this must be set _after_ setting the userpwd)
1770  if (credentials->authType() != CURLAUTH_NONE)
1771  {
1772  // FIXME: only overwrite if not empty?
1773  const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1774  ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1776  }
1777 
1778  if (!cmcred)
1779  {
1780  credentials->setUrl(_url);
1781  cm.addCred(*credentials);
1782  cm.save();
1783  }
1784 
1785  return true;
1786  }
1787 
1788  return false;
1789 }
1790 
1791 
1792  } // namespace media
1793 } // namespace zypp
1794 //
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:612
#define SET_OPTION_OFFT(opt, val)
Definition: MediaCurl.cc:534
double _dnlLast
Bytes downloaded at period start.
Definition: MediaCurl.cc:193
#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:321
bool authenticate(const std::string &availAuthTypes, bool firstTry) const
Definition: MediaCurl.cc:1689
static ZConfig & instance()
Singleton ctor.
Definition: Resolver.cc:125
virtual void releaseFrom(const std::string &ejectDev)
Call concrete handler to release the media.
Definition: MediaCurl.cc:934
const std::string & msg() const
Return the message string provided to the ctor.
Definition: Exception.h:185
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:187
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:599
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:574
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:1636
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:780
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:1622
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:190
Url url
Definition: MediaCurl.cc:180
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:273
virtual void setupEasy()
initializes the curl easy handle with the data from the url
Definition: MediaCurl.cc:637
#define EXPLICITLY_NO_PROXY
Definition: MediaCurl.cc:45
Convenient building of std::string with boost::format.
Definition: String.h:247
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)
std::string proxy(const Url &url) const
Definition: ProxyInfo.cc:44
static void setCookieFile(const Pathname &)
Definition: MediaCurl.cc:605
std::string getAuthHint() const
Return a comma separated list of available authentication methods supported by server.
Definition: MediaCurl.cc:1660
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:1679
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:329
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:1131
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:1357
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:518
time_t timeout
Definition: MediaCurl.cc:181
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:196
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:1005
void setMediaSource(const MediaSourceRef &ref)
Set new media source reference.
int rename(const Pathname &oldpath, const Pathname &newpath)
Like 'rename'.
Definition: PathInfo.cc:676
Just inherits Exception to separate media exceptions.
bool fileSizeExceeded
Definition: MediaCurl.cc:183
virtual void getFileCopy(const Pathname &srcFilename, const Pathname &targetFilename, const ByteCount &expectedFileSize_r) const override
Definition: MediaCurl.cc:964
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:1066
time_t ltime
Definition: MediaCurl.cc:271
bool reached
Definition: MediaCurl.cc:182
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:507
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:955
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:910
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:1573
std::string numstring(char n, int w=0)
Definition: String.h:304
virtual void disconnectFrom()
Definition: MediaCurl.cc:917
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:306
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:527
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:939
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:1606
time_t _timeRcv
Start of no-data timeout.
Definition: MediaCurl.cc:189
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:489
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:1467
void fillSettingsSystemProxy(const Url &url, TransferSettings &s)
Reads the system proxy configuration and fills the settings structure proxy information.
Definition: MediaCurl.cc:443
callback::SendReport< DownloadProgressReport > * report
Definition: MediaCurl.cc:184
void addHeader(const std::string &header)
add a header, on the form "Foo: Bar"
CURL * curl
Definition: MediaCurl.cc:179
static CURL * progressCallback_getcurl(void *clientp)
Definition: MediaCurl.cc:1652
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:444
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:75
virtual void attachTo(bool next=false)
Call concrete handler to attach the media.
Definition: MediaCurl.cc:870
double dload_period
Definition: MediaCurl.cc:265
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:199
double drate_avg
Definition: MediaCurl.cc:269
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
Definition: PathInfo.h:810
virtual bool doGetDoesFileExist(const Pathname &filename) const
Definition: MediaCurl.cc:1172
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:188
std::string authType() const
get the allowed authentication types
double uload
Definition: MediaCurl.cc:275
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:263
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:1036
double _dnlNow
Bytes downloaded now.
Definition: MediaCurl.cc:194
Url url() const
Url used.
Definition: MediaHandler.h:506
std::string proxy() const
proxy host
bool proxyEnabled() const
proxy is enabled
long secs
Definition: MediaCurl.cc:267
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:471
double _drateTotal
Download rate so far.
Definition: MediaCurl.cc:198
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:834
std::string proxyUsername() const
proxy auth username
ByteCount _expectedFileSize
Definition: MediaCurl.cc:185
long timeout() const
transfer timeout
double _dnlTotal
Bytes to download or 0 if unknown.
Definition: MediaCurl.cc:192