libzypp  17.19.0
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/Target.h"
29 #include "zypp/ZYppFactory.h"
30 #include "zypp/ZConfig.h"
31 
32 #include <cstdlib>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <sys/mount.h>
36 #include <errno.h>
37 #include <dirent.h>
38 #include <unistd.h>
39 
40 #define DETECT_DIR_INDEX 0
41 #define CONNECT_TIMEOUT 60
42 #define TRANSFER_TIMEOUT_MAX 60 * 60
43 
44 #define EXPLICITLY_NO_PROXY "_none_"
45 
46 #undef CURLVERSION_AT_LEAST
47 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
48 
49 using namespace std;
50 using namespace zypp::base;
51 
52 namespace
53 {
54  inline void globalInitOnce()
55  {
56  // function-level static <=> std::call_once
57  static bool once __attribute__ ((__unused__)) = ( [] {
58  if ( curl_global_init( CURL_GLOBAL_ALL ) != 0 )
59  WAR << "curl global init failed" << endl;
60  } (), true );
61  }
62 
63  int log_curl(CURL *curl, curl_infotype info,
64  char *ptr, size_t len, void *max_lvl)
65  {
66  std::string pfx(" ");
67  long lvl = 0;
68  switch( info)
69  {
70  case CURLINFO_TEXT: lvl = 1; pfx = "*"; break;
71  case CURLINFO_HEADER_IN: lvl = 2; pfx = "<"; break;
72  case CURLINFO_HEADER_OUT: lvl = 2; pfx = ">"; break;
73  default: break;
74  }
75  if( lvl > 0 && max_lvl != NULL && lvl <= *((long *)max_lvl))
76  {
77  std::string msg(ptr, len);
78  std::list<std::string> lines;
79  std::list<std::string>::const_iterator line;
80  zypp::str::split(msg, std::back_inserter(lines), "\r\n");
81  for(line = lines.begin(); line != lines.end(); ++line)
82  {
83  DBG << pfx << " " << *line << endl;
84  }
85  }
86  return 0;
87  }
88 
89  static size_t log_redirects_curl( char *ptr, size_t size, size_t nmemb, void *userdata)
90  {
91  // INT << "got header: " << string(ptr, ptr + size*nmemb) << endl;
92 
93  char * lstart = ptr, * lend = ptr;
94  size_t pos = 0;
95  size_t max = size * nmemb;
96  while (pos + 1 < max)
97  {
98  // get line
99  for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
100 
101  // look for "Location"
102  if ( lstart[0] == 'L'
103  && lstart[1] == 'o'
104  && lstart[2] == 'c'
105  && lstart[3] == 'a'
106  && lstart[4] == 't'
107  && lstart[5] == 'i'
108  && lstart[6] == 'o'
109  && lstart[7] == 'n'
110  && lstart[8] == ':' )
111  {
112  std::string line { lstart, *(lend-1)=='\r' ? lend-1 : lend };
113  DBG << "redirecting to " << line << endl;
114  if ( userdata ) {
115  *reinterpret_cast<std::string *>( userdata ) = line;
116  }
117  return max;
118  }
119 
120  // continue with the next line
121  if (pos + 1 < max)
122  {
123  ++lend;
124  ++pos;
125  }
126  else
127  break;
128  }
129 
130  return max;
131  }
132 }
133 
134 namespace zypp {
135 
137  namespace env
138  {
139  namespace
140  {
141  inline int getZYPP_MEDIA_CURL_IPRESOLVE()
142  {
143  int ret = 0;
144  if ( const char * envp = getenv( "ZYPP_MEDIA_CURL_IPRESOLVE" ) )
145  {
146  WAR << "env set: $ZYPP_MEDIA_CURL_IPRESOLVE='" << envp << "'" << endl;
147  if ( strcmp( envp, "4" ) == 0 ) ret = 4;
148  else if ( strcmp( envp, "6" ) == 0 ) ret = 6;
149  }
150  return ret;
151  }
152  }
153 
155  {
156  static int _v = getZYPP_MEDIA_CURL_IPRESOLVE();
157  return _v;
158  }
159  } // namespace env
161 
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  curl_easy_setopt(_curl, CURLOPT_HEADERDATA, &_lastRedirect);
652  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
653  if ( ret != 0 ) {
654  ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
655  }
656 
657  SET_OPTION(CURLOPT_FAILONERROR, 1L);
658  SET_OPTION(CURLOPT_NOSIGNAL, 1L);
659 
660  // create non persistant settings
661  // so that we don't add headers twice
662  TransferSettings vol_settings(_settings);
663 
664  // add custom headers for download.opensuse.org (bsc#955801)
665  if ( _url.getHost() == "download.opensuse.org" )
666  {
667  vol_settings.addHeader(anonymousIdHeader());
668  vol_settings.addHeader(distributionFlavorHeader());
669  }
670  vol_settings.addHeader("Pragma:");
671 
672  _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
674 
676 
677  // fill some settings from url query parameters
678  try
679  {
681  }
682  catch ( const MediaException &e )
683  {
684  disconnectFrom();
685  ZYPP_RETHROW(e);
686  }
687  // if the proxy was not set (or explicitly unset) by url, then look...
688  if ( _settings.proxy().empty() )
689  {
690  // ...at the system proxy settings
692  }
693 
696  {
697  switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
698  {
699  case 4: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); break;
700  case 6: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); break;
701  }
702  }
703 
707  SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
708  // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
709  // just in case curl does not trigger its progress callback frequently
710  // enough.
711  if ( _settings.timeout() )
712  {
713  SET_OPTION(CURLOPT_TIMEOUT, 3600L);
714  }
715 
716  // follow any Location: header that the server sends as part of
717  // an HTTP header (#113275)
718  SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
719  // 3 redirects seem to be too few in some cases (bnc #465532)
720  SET_OPTION(CURLOPT_MAXREDIRS, 6L);
721 
722  if ( _url.getScheme() == "https" )
723  {
724 #if CURLVERSION_AT_LEAST(7,19,4)
725  // restrict following of redirections from https to https only
726  SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
727 #endif
728 
731  {
733  }
734 
736  {
737  SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
738  }
739  if( ! _settings.clientKeyPath().empty() )
740  {
741  SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
742  }
743 
744 #ifdef CURLSSLOPT_ALLOW_BEAST
745  // see bnc#779177
746  ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
747  if ( ret != 0 ) {
748  disconnectFrom();
750  }
751 #endif
752  SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
753  SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
754  // bnc#903405 - POODLE: libzypp should only talk TLS
755  SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
756  }
757 
758  SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
759 
760  /*---------------------------------------------------------------*
761  CURLOPT_USERPWD: [user name]:[password]
762 
763  Url::username/password -> CURLOPT_USERPWD
764  If not provided, anonymous FTP identification
765  *---------------------------------------------------------------*/
766 
767  if ( _settings.userPassword().size() )
768  {
769  SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
770  string use_auth = _settings.authType();
771  if (use_auth.empty())
772  use_auth = "digest,basic"; // our default
773  long auth = CurlAuthData::auth_type_str2long(use_auth);
774  if( auth != CURLAUTH_NONE)
775  {
776  DBG << "Enabling HTTP authentication methods: " << use_auth
777  << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
778  SET_OPTION(CURLOPT_HTTPAUTH, auth);
779  }
780  }
781 
782  if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
783  {
784  DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
785  SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
786  SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
787  /*---------------------------------------------------------------*
788  * CURLOPT_PROXYUSERPWD: [user name]:[password]
789  *
790  * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
791  * If not provided, $HOME/.curlrc is evaluated
792  *---------------------------------------------------------------*/
793 
794  string proxyuserpwd = _settings.proxyUserPassword();
795 
796  if ( proxyuserpwd.empty() )
797  {
798  CurlConfig curlconf;
799  CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
800  if ( curlconf.proxyuserpwd.empty() )
801  DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
802  else
803  {
804  proxyuserpwd = curlconf.proxyuserpwd;
805  DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
806  }
807  }
808  else
809  {
810  DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
811  }
812 
813  if ( ! proxyuserpwd.empty() )
814  {
815  SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
816  }
817  }
818 #if CURLVERSION_AT_LEAST(7,19,4)
819  else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
820  {
821  // Explicitly disabled in URL (see fillSettingsFromUrl()).
822  // This should also prevent libcurl from looking into the environment.
823  DBG << "Proxy: explicitly NOPROXY" << endl;
824  SET_OPTION(CURLOPT_NOPROXY, "*");
825  }
826 #endif
827  else
828  {
829  DBG << "Proxy: not explicitly set" << endl;
830  DBG << "Proxy: libcurl may look into the environment" << endl;
831  }
832 
834  if ( _settings.minDownloadSpeed() != 0 )
835  {
836  SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
837  // default to 10 seconds at low speed
838  SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
839  }
840 
841 #if CURLVERSION_AT_LEAST(7,15,5)
842  if ( _settings.maxDownloadSpeed() != 0 )
843  SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
844 #endif
845 
846  /*---------------------------------------------------------------*
847  *---------------------------------------------------------------*/
848 
851  if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
852  SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
853  else
854  MIL << "No cookies requested" << endl;
855  SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
856  SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
857  SET_OPTION(CURLOPT_NOPROGRESS, 0L);
858 
859 #if CURLVERSION_AT_LEAST(7,18,0)
860  // bnc #306272
861  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
862 #endif
863  // append settings custom headers to curl
864  for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
865  it != vol_settings.headersEnd();
866  ++it )
867  {
868  // MIL << "HEADER " << *it << std::endl;
869 
870  _customHeaders = curl_slist_append(_customHeaders, it->c_str());
871  if ( !_customHeaders )
873  }
874 
875  SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
876 }
877 
879 
880 
881 void MediaCurl::attachTo (bool next)
882 {
883  if ( next )
885 
886  if ( !_url.isValid() )
888 
891  {
893  }
894 
895  disconnectFrom(); // clean _curl if needed
896  _curl = curl_easy_init();
897  if ( !_curl ) {
899  }
900  try
901  {
902  setupEasy();
903  }
904  catch (Exception & ex)
905  {
906  disconnectFrom();
907  ZYPP_RETHROW(ex);
908  }
909 
910  // FIXME: need a derived class to propelly compare url's
912  setMediaSource(media);
913 }
914 
915 bool
917 {
918  return MediaHandler::checkAttachPoint( apoint, true, true);
919 }
920 
922 
924 {
925  if ( _customHeaders )
926  {
927  curl_slist_free_all(_customHeaders);
928  _customHeaders = 0L;
929  }
930 
931  if ( _curl )
932  {
933  curl_easy_cleanup( _curl );
934  _curl = NULL;
935  }
936 }
937 
939 
940 void MediaCurl::releaseFrom( const std::string & ejectDev )
941 {
942  disconnect();
943 }
944 
945 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
946 {
947  // Simply extend the URLs pathname. An 'absolute' URL path
948  // is achieved by encoding the leading '/' in an URL path:
949  // URL: ftp://user@server -> ~user
950  // URL: ftp://user@server/ -> ~user
951  // URL: ftp://user@server// -> ~user
952  // URL: ftp://user@server/%2F -> /
953  // ^- this '/' is just a separator
954  Url newurl( _url );
955  newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
956  return newurl;
957 }
958 
960 
961 void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
962 {
963  // Use absolute file name to prevent access of files outside of the
964  // hierarchy below the attach point.
965  getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
966 }
967 
969 
970 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
971 {
973 
974  Url fileurl(getFileUrl(filename));
975 
976  bool retry = false;
977 
978  do
979  {
980  try
981  {
982  doGetFileCopy(filename, target, report, expectedFileSize_r);
983  retry = false;
984  }
985  // retry with proper authentication data
986  catch (MediaUnauthorizedException & ex_r)
987  {
988  if(authenticate(ex_r.hint(), !retry))
989  retry = true;
990  else
991  {
993  ZYPP_RETHROW(ex_r);
994  }
995  }
996  // unexpected exception
997  catch (MediaException & excpt_r)
998  {
1000  if( typeid(excpt_r) == typeid( media::MediaFileNotFoundException ) ||
1001  typeid(excpt_r) == typeid( media::MediaNotAFileException ) )
1002  {
1004  }
1005  report->finish(fileurl, reason, excpt_r.asUserHistory());
1006  ZYPP_RETHROW(excpt_r);
1007  }
1008  }
1009  while (retry);
1010 
1012 }
1013 
1015 
1016 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
1017 {
1018  bool retry = false;
1019 
1020  do
1021  {
1022  try
1023  {
1024  return doGetDoesFileExist( filename );
1025  }
1026  // authentication problem, retry with proper authentication data
1027  catch (MediaUnauthorizedException & ex_r)
1028  {
1029  if(authenticate(ex_r.hint(), !retry))
1030  retry = true;
1031  else
1032  ZYPP_RETHROW(ex_r);
1033  }
1034  // unexpected exception
1035  catch (MediaException & excpt_r)
1036  {
1037  ZYPP_RETHROW(excpt_r);
1038  }
1039  }
1040  while (retry);
1041 
1042  return false;
1043 }
1044 
1046 
1048  CURLcode code,
1049  bool timeout_reached) const
1050 {
1051  if ( code != 0 )
1052  {
1053  Url url;
1054  if (filename.empty())
1055  url = _url;
1056  else
1057  url = getFileUrl(filename);
1058 
1059  std::string err;
1060  {
1061  switch ( code )
1062  {
1063  case CURLE_UNSUPPORTED_PROTOCOL:
1064  err = " Unsupported protocol";
1065  if ( !_lastRedirect.empty() )
1066  {
1067  err += " or redirect (";
1068  err += _lastRedirect;
1069  err += ")";
1070  }
1071  break;
1072  case CURLE_URL_MALFORMAT:
1073  case CURLE_URL_MALFORMAT_USER:
1074  err = " Bad URL";
1075  break;
1076  case CURLE_LOGIN_DENIED:
1077  ZYPP_THROW(
1078  MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
1079  break;
1080  case CURLE_HTTP_RETURNED_ERROR:
1081  {
1082  long httpReturnCode = 0;
1083  CURLcode infoRet = curl_easy_getinfo( _curl,
1084  CURLINFO_RESPONSE_CODE,
1085  &httpReturnCode );
1086  if ( infoRet == CURLE_OK )
1087  {
1088  string msg = "HTTP response: " + str::numstring( httpReturnCode );
1089  switch ( httpReturnCode )
1090  {
1091  case 401:
1092  {
1093  string auth_hint = getAuthHint();
1094 
1095  DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1096  DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1097 
1099  url, "Login failed.", _curlError, auth_hint
1100  ));
1101  }
1102 
1103  case 502: // bad gateway (bnc #1070851)
1104  case 503: // service temporarily unavailable (bnc #462545)
1106  case 504: // gateway timeout
1108  case 403:
1109  {
1110  string msg403;
1111  if ( url.getHost().find(".suse.com") != string::npos )
1112  msg403 = _("Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
1113  else if (url.asString().find("novell.com") != string::npos)
1114  msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1116  }
1117  case 404:
1118  case 410:
1120  }
1121 
1122  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1124  }
1125  else
1126  {
1127  string msg = "Unable to retrieve HTTP response:";
1128  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1130  }
1131  }
1132  break;
1133  case CURLE_FTP_COULDNT_RETR_FILE:
1134 #if CURLVERSION_AT_LEAST(7,16,0)
1135  case CURLE_REMOTE_FILE_NOT_FOUND:
1136 #endif
1137  case CURLE_FTP_ACCESS_DENIED:
1138  case CURLE_TFTP_NOTFOUND:
1139  err = "File not found";
1141  break;
1142  case CURLE_BAD_PASSWORD_ENTERED:
1143  case CURLE_FTP_USER_PASSWORD_INCORRECT:
1144  err = "Login failed";
1145  break;
1146  case CURLE_COULDNT_RESOLVE_PROXY:
1147  case CURLE_COULDNT_RESOLVE_HOST:
1148  case CURLE_COULDNT_CONNECT:
1149  case CURLE_FTP_CANT_GET_HOST:
1150  err = "Connection failed";
1151  break;
1152  case CURLE_WRITE_ERROR:
1153  err = "Write error";
1154  break;
1155  case CURLE_PARTIAL_FILE:
1156  case CURLE_OPERATION_TIMEDOUT:
1157  timeout_reached = true; // fall though to TimeoutException
1158  // fall though...
1159  case CURLE_ABORTED_BY_CALLBACK:
1160  if( timeout_reached )
1161  {
1162  err = "Timeout reached";
1164  }
1165  else
1166  {
1167  err = "User abort";
1168  }
1169  break;
1170  case CURLE_SSL_PEER_CERTIFICATE:
1171  default:
1172  err = "Curl error " + str::numstring( code );
1173  break;
1174  }
1175 
1176  // uhm, no 0 code but unknown curl exception
1178  }
1179  }
1180  else
1181  {
1182  // actually the code is 0, nothing happened
1183  }
1184 }
1185 
1187 
1188 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1189 {
1190  DBG << filename.asString() << endl;
1191 
1192  if(!_url.isValid())
1194 
1195  if(_url.getHost().empty())
1197 
1198  Url url(getFileUrl(filename));
1199 
1200  DBG << "URL: " << url.asString() << endl;
1201  // Use URL without options and without username and passwd
1202  // (some proxies dislike them in the URL).
1203  // Curl seems to need the just scheme, hostname and a path;
1204  // the rest was already passed as curl options (in attachTo).
1205  Url curlUrl( clearQueryString(url) );
1206 
1207  //
1208  // See also Bug #154197 and ftp url definition in RFC 1738:
1209  // The url "ftp://user@host/foo/bar/file" contains a path,
1210  // that is relative to the user's home.
1211  // The url "ftp://user@host//foo/bar/file" (or also with
1212  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1213  // contains an absolute path.
1214  //
1215  _lastRedirect.clear();
1216  string urlBuffer( curlUrl.asString());
1217  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1218  urlBuffer.c_str() );
1219  if ( ret != 0 ) {
1221  }
1222 
1223  // instead of returning no data with NOBODY, we return
1224  // little data, that works with broken servers, and
1225  // works for ftp as well, because retrieving only headers
1226  // ftp will return always OK code ?
1227  // See http://curl.haxx.se/docs/knownbugs.html #58
1228  if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1230  ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1231  else
1232  ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1233 
1234  if ( ret != 0 ) {
1235  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1236  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1237  /* yes, this is why we never got to get NOBODY working before,
1238  because setting it changes this option too, and we also
1239  need to reset it
1240  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1241  */
1242  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1244  }
1245 
1246  AutoFILE file { ::fopen( "/dev/null", "w" ) };
1247  if ( !file ) {
1248  ERR << "fopen failed for /dev/null" << endl;
1249  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1250  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
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  }
1260  ZYPP_THROW(MediaWriteException("/dev/null"));
1261  }
1262 
1263  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, (*file) );
1264  if ( ret != 0 ) {
1265  std::string err( _curlError);
1266  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1267  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1268  /* yes, this is why we never got to get NOBODY working before,
1269  because setting it changes this option too, and we also
1270  need to reset it
1271  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1272  */
1273  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1274  if ( ret != 0 ) {
1276  }
1278  }
1279 
1280  CURLcode ok = curl_easy_perform( _curl );
1281  MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1282 
1283  // reset curl settings
1284  if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1285  {
1286  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1287  if ( ret != 0 ) {
1289  }
1290 
1291  /* yes, this is why we never got to get NOBODY working before,
1292  because setting it changes this option too, and we also
1293  need to reset it
1294  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1295  */
1296  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1297  if ( ret != 0 ) {
1299  }
1300 
1301  }
1302  else
1303  {
1304  // for FTP we set different options
1305  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1306  if ( ret != 0 ) {
1308  }
1309  }
1310 
1311  // as we are not having user interaction, the user can't cancel
1312  // the file existence checking, a callback or timeout return code
1313  // will be always a timeout.
1314  try {
1315  evaluateCurlCode( filename, ok, true /* timeout */);
1316  }
1317  catch ( const MediaFileNotFoundException &e ) {
1318  // if the file did not exist then we can return false
1319  return false;
1320  }
1321  catch ( const MediaException &e ) {
1322  // some error, we are not sure about file existence, rethrw
1323  ZYPP_RETHROW(e);
1324  }
1325  // exists
1326  return ( ok == CURLE_OK );
1327 }
1328 
1330 
1331 
1332 #if DETECT_DIR_INDEX
1333 bool MediaCurl::detectDirIndex() const
1334 {
1335  if(_url.getScheme() != "http" && _url.getScheme() != "https")
1336  return false;
1337  //
1338  // try to check the effective url and set the not_a_file flag
1339  // if the url path ends with a "/", what usually means, that
1340  // we've received a directory index (index.html content).
1341  //
1342  // Note: This may be dangerous and break file retrieving in
1343  // case of some server redirections ... ?
1344  //
1345  bool not_a_file = false;
1346  char *ptr = NULL;
1347  CURLcode ret = curl_easy_getinfo( _curl,
1348  CURLINFO_EFFECTIVE_URL,
1349  &ptr);
1350  if ( ret == CURLE_OK && ptr != NULL)
1351  {
1352  try
1353  {
1354  Url eurl( ptr);
1355  std::string path( eurl.getPathName());
1356  if( !path.empty() && path != "/" && *path.rbegin() == '/')
1357  {
1358  DBG << "Effective url ("
1359  << eurl
1360  << ") seems to provide the index of a directory"
1361  << endl;
1362  not_a_file = true;
1363  }
1364  }
1365  catch( ... )
1366  {}
1367  }
1368  return not_a_file;
1369 }
1370 #endif
1371 
1373 
1374 void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1375 {
1376  Pathname dest = target.absolutename();
1377  if( assert_dir( dest.dirname() ) )
1378  {
1379  DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1380  ZYPP_THROW( MediaSystemException(getFileUrl(filename), "System error on " + dest.dirname().asString()) );
1381  }
1382 
1383  ManagedFile destNew { target.extend( ".new.zypp.XXXXXX" ) };
1384  AutoFILE file;
1385  {
1386  AutoFREE<char> buf { ::strdup( (*destNew).c_str() ) };
1387  if( ! buf )
1388  {
1389  ERR << "out of memory for temp file name" << endl;
1390  ZYPP_THROW(MediaSystemException(getFileUrl(filename), "out of memory for temp file name"));
1391  }
1392 
1393  AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1394  if( tmp_fd == -1 )
1395  {
1396  ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1397  ZYPP_THROW(MediaWriteException(destNew));
1398  }
1399  destNew = ManagedFile( (*buf), filesystem::unlink );
1400 
1401  file = ::fdopen( tmp_fd, "we" );
1402  if ( ! file )
1403  {
1404  ERR << "fopen failed for file '" << destNew << "'" << endl;
1405  ZYPP_THROW(MediaWriteException(destNew));
1406  }
1407  tmp_fd.resetDispose(); // don't close it here! ::fdopen moved ownership to file
1408  }
1409 
1410  DBG << "dest: " << dest << endl;
1411  DBG << "temp: " << destNew << endl;
1412 
1413  // set IFMODSINCE time condition (no download if not modified)
1414  if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1415  {
1416  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1417  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1418  }
1419  else
1420  {
1421  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1422  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1423  }
1424  try
1425  {
1426  doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
1427  }
1428  catch (Exception &e)
1429  {
1430  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1431  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1432  ZYPP_RETHROW(e);
1433  }
1434 
1435  long httpReturnCode = 0;
1436  CURLcode infoRet = curl_easy_getinfo(_curl,
1437  CURLINFO_RESPONSE_CODE,
1438  &httpReturnCode);
1439  bool modified = true;
1440  if (infoRet == CURLE_OK)
1441  {
1442  DBG << "HTTP response: " + str::numstring(httpReturnCode);
1443  if ( httpReturnCode == 304
1444  || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1445  {
1446  DBG << " Not modified.";
1447  modified = false;
1448  }
1449  DBG << endl;
1450  }
1451  else
1452  {
1453  WAR << "Could not get the reponse code." << endl;
1454  }
1455 
1456  if (modified || infoRet != CURLE_OK)
1457  {
1458  // apply umask
1459  if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1460  {
1461  ERR << "Failed to chmod file " << destNew << endl;
1462  }
1463 
1464  file.resetDispose(); // we're going to close it manually here
1465  if ( ::fclose( file ) )
1466  {
1467  ERR << "Fclose failed for file '" << destNew << "'" << endl;
1468  ZYPP_THROW(MediaWriteException(destNew));
1469  }
1470 
1471  // move the temp file into dest
1472  if ( rename( destNew, dest ) != 0 ) {
1473  ERR << "Rename failed" << endl;
1475  }
1476  destNew.resetDispose(); // no more need to unlink it
1477  }
1478 
1479  DBG << "done: " << PathInfo(dest) << endl;
1480 }
1481 
1483 
1484 void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1485 {
1486  DBG << filename.asString() << endl;
1487 
1488  if(!_url.isValid())
1490 
1491  if(_url.getHost().empty())
1493 
1494  Url url(getFileUrl(filename));
1495 
1496  DBG << "URL: " << url.asString() << endl;
1497  // Use URL without options and without username and passwd
1498  // (some proxies dislike them in the URL).
1499  // Curl seems to need the just scheme, hostname and a path;
1500  // the rest was already passed as curl options (in attachTo).
1501  Url curlUrl( clearQueryString(url) );
1502 
1503  //
1504  // See also Bug #154197 and ftp url definition in RFC 1738:
1505  // The url "ftp://user@host/foo/bar/file" contains a path,
1506  // that is relative to the user's home.
1507  // The url "ftp://user@host//foo/bar/file" (or also with
1508  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1509  // contains an absolute path.
1510  //
1511  _lastRedirect.clear();
1512  string urlBuffer( curlUrl.asString());
1513  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1514  urlBuffer.c_str() );
1515  if ( ret != 0 ) {
1517  }
1518 
1519  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1520  if ( ret != 0 ) {
1522  }
1523 
1524  // Set callback and perform.
1525  ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
1526  if (!(options & OPTION_NO_REPORT_START))
1527  report->start(url, dest);
1528  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1529  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1530  }
1531 
1532  ret = curl_easy_perform( _curl );
1533 #if CURLVERSION_AT_LEAST(7,19,4)
1534  // bnc#692260: If the client sends a request with an If-Modified-Since header
1535  // with a future date for the server, the server may respond 200 sending a
1536  // zero size file.
1537  // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1538  if ( ftell(file) == 0 && ret == 0 )
1539  {
1540  long httpReturnCode = 33;
1541  if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1542  {
1543  long conditionUnmet = 33;
1544  if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1545  {
1546  WAR << "TIMECONDITION unmet - retry without." << endl;
1547  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1548  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1549  ret = curl_easy_perform( _curl );
1550  }
1551  }
1552  }
1553 #endif
1554 
1555  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1556  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1557  }
1558 
1559  if ( ret != 0 )
1560  {
1561  ERR << "curl error: " << ret << ": " << _curlError
1562  << ", temp file size " << ftell(file)
1563  << " bytes." << endl;
1564 
1565  // the timeout is determined by the progress data object
1566  // which holds whether the timeout was reached or not,
1567  // otherwise it would be a user cancel
1568  try {
1569 
1570  if ( progressData.fileSizeExceeded )
1571  ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
1572 
1573  evaluateCurlCode( filename, ret, progressData.reached );
1574  }
1575  catch ( const MediaException &e ) {
1576  // some error, we are not sure about file existence, rethrw
1577  ZYPP_RETHROW(e);
1578  }
1579  }
1580 
1581 #if DETECT_DIR_INDEX
1582  if (!ret && detectDirIndex())
1583  {
1585  }
1586 #endif // DETECT_DIR_INDEX
1587 }
1588 
1590 
1591 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1592 {
1593  filesystem::DirContent content;
1594  getDirInfo( content, dirname, /*dots*/false );
1595 
1596  for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1597  Pathname filename = dirname + it->name;
1598  int res = 0;
1599 
1600  switch ( it->type ) {
1601  case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1602  case filesystem::FT_FILE:
1603  getFile( filename, 0 );
1604  break;
1605  case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1606  if ( recurse_r ) {
1607  getDir( filename, recurse_r );
1608  } else {
1609  res = assert_dir( localPath( filename ) );
1610  if ( res ) {
1611  WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1612  }
1613  }
1614  break;
1615  default:
1616  // don't provide devices, sockets, etc.
1617  break;
1618  }
1619  }
1620 }
1621 
1623 
1624 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1625  const Pathname & dirname, bool dots ) const
1626 {
1627  getDirectoryYast( retlist, dirname, dots );
1628 }
1629 
1631 
1633  const Pathname & dirname, bool dots ) const
1634 {
1635  getDirectoryYast( retlist, dirname, dots );
1636 }
1637 
1639 //
1640 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1641 {
1642  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1643  if( pdata )
1644  {
1645  // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1646  // prevent a percentage raise while downloading a metalink file. Download
1647  // activity however is indicated by propagating the download rate (via dlnow).
1648  pdata->updateStats( 0.0, dlnow );
1649  return pdata->reportProgress();
1650  }
1651  return 0;
1652 }
1653 
1654 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1655 {
1656  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1657  if( pdata )
1658  {
1659  // work around curl bug that gives us old data
1660  long httpReturnCode = 0;
1661  if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1662  return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1663 
1664  pdata->updateStats( dltotal, dlnow );
1665  return pdata->reportProgress();
1666  }
1667  return 0;
1668 }
1669 
1671 {
1672  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1673  return pdata ? pdata->curl : 0;
1674 }
1675 
1677 
1679 {
1680  long auth_info = CURLAUTH_NONE;
1681 
1682  CURLcode infoRet =
1683  curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1684 
1685  if(infoRet == CURLE_OK)
1686  {
1687  return CurlAuthData::auth_type_long2str(auth_info);
1688  }
1689 
1690  return "";
1691 }
1692 
1697 void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
1698 {
1699  ProgressData *data = reinterpret_cast<ProgressData *>(clientp);
1700  if ( data ) {
1701  data->_expectedFileSize = expectedFileSize;
1702  }
1703 }
1704 
1706 
1707 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1708 {
1710  CredentialManager cm(CredManagerOptions(ZConfig::instance().repoManagerRoot()));
1711  CurlAuthData_Ptr credentials;
1712 
1713  // get stored credentials
1714  AuthData_Ptr cmcred = cm.getCred(_url);
1715 
1716  if (cmcred && firstTry)
1717  {
1718  credentials.reset(new CurlAuthData(*cmcred));
1719  DBG << "got stored credentials:" << endl << *credentials << endl;
1720  }
1721  // if not found, ask user
1722  else
1723  {
1724 
1725  CurlAuthData_Ptr curlcred;
1726  curlcred.reset(new CurlAuthData());
1728 
1729  // preset the username if present in current url
1730  if (!_url.getUsername().empty() && firstTry)
1731  curlcred->setUsername(_url.getUsername());
1732  // if CM has found some credentials, preset the username from there
1733  else if (cmcred)
1734  curlcred->setUsername(cmcred->username());
1735 
1736  // indicate we have no good credentials from CM
1737  cmcred.reset();
1738 
1739  string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1740 
1741  // set available authentication types from the exception
1742  // might be needed in prompt
1743  curlcred->setAuthType(availAuthTypes);
1744 
1745  // ask user
1746  if (auth_report->prompt(_url, prompt_msg, *curlcred))
1747  {
1748  DBG << "callback answer: retry" << endl
1749  << "CurlAuthData: " << *curlcred << endl;
1750 
1751  if (curlcred->valid())
1752  {
1753  credentials = curlcred;
1754  // if (credentials->username() != _url.getUsername())
1755  // _url.setUsername(credentials->username());
1763  }
1764  }
1765  else
1766  {
1767  DBG << "callback answer: cancel" << endl;
1768  }
1769  }
1770 
1771  // set username and password
1772  if (credentials)
1773  {
1774  // HACK, why is this const?
1775  const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1776  const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1777 
1778  // set username and password
1779  CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1781 
1782  // set available authentication types from the exception
1783  if (credentials->authType() == CURLAUTH_NONE)
1784  credentials->setAuthType(availAuthTypes);
1785 
1786  // set auth type (seems this must be set _after_ setting the userpwd)
1787  if (credentials->authType() != CURLAUTH_NONE)
1788  {
1789  // FIXME: only overwrite if not empty?
1790  const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1791  ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1793  }
1794 
1795  if (!cmcred)
1796  {
1797  credentials->setUrl(_url);
1798  cm.addCred(*credentials);
1799  cm.save();
1800  }
1801 
1802  return true;
1803  }
1804 
1805  return false;
1806 }
1807 
1808 //need a out of line definiton, otherwise vtable is emitted for every translation unit
1810 
1811 
1812  } // namespace media
1813 } // namespace zypp
1814 //
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:528
void setPassword(const std::string &pass, EEncoding eflag=zypp::url::E_DECODED)
Set the password in the URL authority.
Definition: Url.cc:734
long timeout() const
transfer timeout
std::string authType() const
get the allowed authentication types
virtual bool checkAttachPoint(const Pathname &apoint) const override
Verify if the specified directory as attach point (root) as requires by the particular media handler ...
Definition: MediaCurl.cc:916
int assert_dir(const Pathname &path, unsigned mode)
Like &#39;mkdir -p&#39;.
Definition: PathInfo.cc:320
Interface to gettext.
#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:79
#define CONNECT_TIMEOUT
Definition: MediaCurl.cc:41
const Pathname & path() const
Return current Pathname.
Definition: PathInfo.h:246
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:392
static ZConfig & instance()
Singleton ctor.
Definition: Resolver.cc:124
std::string proxyUserPassword() const
returns the proxy user and password as a user:pass string
void checkProtocol(const Url &url) const
check the url is supported by the curl library
Definition: MediaCurl.cc:612
bool authenticate(const std::string &availAuthTypes, bool firstTry) const
Definition: MediaCurl.cc:1707
Implementation class for FTP, HTTP and HTTPS MediaHandler.
Definition: MediaCurl.h:32
Flag to request encoded string(s).
Definition: UrlUtils.h:53
Pathname clientCertificatePath() const
SSL client certificate file.
virtual bool checkAttachPoint(const Pathname &apoint) const
Verify if the specified directory as attach point (root) as requires by the particular media handler ...
Store and operate with byte count.
Definition: ByteCount.h:30
long maxDownloadSpeed() const
Maximum download speed (bytes per second)
std::string proxy() const
proxy host
time_t _timeStart
Start total stats.
Definition: MediaCurl.cc:187
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
Holds transfer setting.
void save()
Saves any unsaved credentials added via addUserCred() or addGlobalCred() methods. ...
bool verifyHostEnabled() const
Whether to verify host for ssl.
static int progressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
Callback reporting download progress.
Definition: MediaCurl.cc:1654
Pathname extend(const std::string &r) const
Append string r to the last component of the path.
Definition: Pathname.h:169
void setProxyUsername(const std::string &proxyuser)
sets the proxy user
void setAttachPoint(const Pathname &path, bool temp)
Set a new attach point.
bool useProxyFor(const Url &url_r) const
Return true if enabled and url_r does not match noProxy.
Definition: ProxyInfo.cc:56
const char * c_str() const
String representation.
Definition: Pathname.h:109
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...
void setPathParams(const std::string &params)
Set the path parameters.
Definition: Url.cc:786
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:1640
Pathname certificateAuthoritiesPath() const
SSL certificate authorities path ( default: /etc/ssl/certs )
Definition: Arch.h:347
AuthData_Ptr getCred(const Url &url)
Get credentials for the specified url.
std::string username() const
auth username
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:725
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:44
Convenient building of std::string with boost::format.
Definition: String.h:251
Structure holding values of curlrc options.
Definition: CurlConfig.h:16
Headers::const_iterator headersEnd() const
end iterators to additional headers
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
Definition: String.cc:36
std::string userAgentString() const
user agent string
Edition * _value
Definition: SysContent.cc:311
AutoDispose<int> calling ::close
Definition: AutoDispose.h:203
std::string _currentCookieFile
Definition: MediaCurl.h:170
virtual void getDir(const Pathname &dirname, bool recurse_r) const override
Call concrete handler to provide directory content (not recursive!) below attach point.
Definition: MediaCurl.cc:1591
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:717
#define ERR
Definition: Logger.h:81
Url getFileUrl(const Pathname &filename) const
concatenate the attach url and the filename to a complete download url
Definition: MediaCurl.cc:945
void setPassword(const std::string &password)
sets the auth password
Pathname localPath(const Pathname &pathname) const
Files provided will be available at &#39;localPath(filename)&#39;.
void setUsername(const std::string &username)
sets the auth username
void setAnonymousAuth()
sets anonymous authentication (ie: for ftp)
int ZYPP_MEDIA_CURL_IPRESOLVE()
Definition: MediaCurl.cc:154
static void setCookieFile(const Pathname &)
Definition: MediaCurl.cc:605
virtual void releaseFrom(const std::string &ejectDev) override
Call concrete handler to release the media.
Definition: MediaCurl.cc:940
bool verifyPeerEnabled() const
Whether to verify peer for ssl.
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:1697
const std::string & hint() const
comma separated list of available authentication types
bool empty() const
Test for an empty path.
Definition: Pathname.h:113
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:400
bool detectDirIndex() const
void setPathName(const std::string &path, EEncoding eflag=zypp::url::E_DECODED)
Set the path name.
Definition: Url.cc:759
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:1152
unsigned split(const C_Str &line_r, TOutputIterator result_r, const C_Str &sepchars_r=" \, const Trim trim_r=NO_TRIM)
Split line_r into words.
Definition: String.h:529
std::string asString() const
Returns a default string representation of the Url object.
Definition: Url.cc:492
time_t timeout
Definition: MediaCurl.cc:181
std::string escape(const C_Str &str_r, const char sep_r)
Escape desired character c using a backslash.
Definition: String.cc:371
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:655
void setProxyPassword(const std::string &proxypass)
sets the proxy password
Abstract base class for &#39;physical&#39; MediaHandler like MediaCD, etc.
Definition: MediaHandler.h:45
Url clearQueryString(const Url &url) const
Definition: MediaCurl.cc:574
int _dnlPercent
Percent completed or 0 if _dnlTotal is unknown.
Definition: MediaCurl.cc:196
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:223
int unlink(const Pathname &path)
Like &#39;unlink&#39;.
Definition: PathInfo.cc:653
const Url _url
Url to handle.
Definition: MediaHandler.h:110
void setMediaSource(const MediaSourceRef &ref)
Set new media source reference.
const std::string & asString() const
String representation.
Definition: Pathname.h:90
int rename(const Pathname &oldpath, const Pathname &newpath)
Like &#39;rename&#39;.
Definition: PathInfo.cc:695
Just inherits Exception to separate media exceptions.
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:1047
bool fileSizeExceeded
Definition: MediaCurl.cc:183
virtual void getFileCopy(const Pathname &srcFilename, const Pathname &targetFilename, const ByteCount &expectedFileSize_r) const override
Definition: MediaCurl.cc:970
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Definition: Exception.cc:91
void disconnect()
Use concrete handler to isconnect media.
long connectTimeout() const
connection timeout
Pathname dirname() const
Return all but the last component od this path.
Definition: Pathname.h:123
do not send a start ProgressReport
Definition: MediaCurl.h:46
#define WAR
Definition: Logger.h:80
TransferSettings _settings
Definition: MediaCurl.h:179
time_t ltime
Definition: MediaCurl.cc:271
bool reached
Definition: MediaCurl.cc:182
std::list< DirEntry > DirContent
Returned by readdir.
Definition: PathInfo.h:547
void getDirectoryYast(std::list< std::string > &retlist, const Pathname &dirname, bool dots=true) const
Retrieve and if available scan dirname/directory.yast.
void setTimeout(long t)
set the transfer timeout
std::string proxy(const Url &url) const
Definition: ProxyInfo.cc:44
Headers::const_iterator headersBegin() const
begin iterators to additional headers
#define _(MSG)
Definition: Gettext.h:37
static const char *const agentString()
initialized only once, this gets the agent string which also includes the curl version ...
Definition: MediaCurl.cc:507
std::string proxyuserpwd
Definition: CurlConfig.h:39
Pathname clientKeyPath() const
SSL client key file.
bool isValid() const
Verifies the Url.
Definition: Url.cc:484
virtual bool doGetDoesFileExist(const Pathname &filename) const
Definition: MediaCurl.cc:1188
virtual void getFile(const Pathname &filename, const ByteCount &expectedFileSize_r) const override
Call concrete handler to provide file below attach point.
Definition: MediaCurl.cc:961
shared_ptr< CurlAuthData > CurlAuthData_Ptr
virtual void attachTo(bool next=false) override
Call concrete handler to attach the media.
Definition: MediaCurl.cc:881
std::string numstring(char n, int w=0)
Definition: String.h:288
virtual bool getDoesFileExist(const Pathname &filename) const override
Repeatedly calls doGetDoesFileExist() until it successfully returns, fails unexpectedly, or user cancels the operation.
Definition: MediaCurl.cc:1016
void resetDispose()
Set no dispose function.
Definition: AutoDispose.h:162
SolvableIdType size_type
Definition: PoolMember.h:126
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...
long minDownloadSpeed() const
Minimum download speed (bytes per second) until the connection is dropped.
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:178
void setClientCertificatePath(const zypp::Pathname &path)
Sets the SSL client certificate file.
bool proxyEnabled() const
proxy is enabled
shared_ptr< AuthData > AuthData_Ptr
Definition: MediaUserAuth.h:69
int rmdir(const Pathname &path)
Like &#39;rmdir&#39;.
Definition: PathInfo.cc:367
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:1484
#define SET_OPTION(opt, val)
Definition: MediaCurl.cc:527
Pathname absolutename() const
Return this path, adding a leading &#39;/&#39; if relative.
Definition: Pathname.h:138
Base class for Exception.
Definition: Exception.h:145
Pathname attachPoint() const
Return the currently used attach point.
time_t _timeRcv
Start of no-data timeout.
Definition: MediaCurl.cc:189
std::string _lastRedirect
to log/report redirections
Definition: MediaCurl.h:173
Url url() const
Url used.
Definition: MediaHandler.h:507
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 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"
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
Definition: Url.cc:599
CURL * curl
Definition: MediaCurl.cc:179
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
Definition: Url.cc:583
virtual void getDirInfo(std::list< std::string > &retlist, const Pathname &dirname, bool dots=true) const override
Call concrete handler to provide a content list of directory on media via retlist.
Definition: MediaCurl.cc:1624
virtual void disconnectFrom() override
Definition: MediaCurl.cc:923
static CURL * progressCallback_getcurl(void *clientp)
Definition: MediaCurl.cc:1670
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:428
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
Wrapper class for ::stat/::lstat.
Definition: PathInfo.h:220
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:813
std::string userPassword() const
returns the user and password as a user:pass string
time_t _timeLast
Start last period(~1sec)
Definition: MediaCurl.cc:188
std::string proxyUsername() const
proxy auth username
double uload
Definition: MediaCurl.cc:275
Pathname createAttachPoint() const
Try to create a default / temporary attach point.
void addCred(const AuthData &cred)
Add new credentials with user callbacks.
#define TRANSFER_TIMEOUT_MAX
Definition: MediaCurl.cc:42
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:1
Curl HTTP authentication data.
Definition: MediaUserAuth.h:74
std::string getAuthHint() const
Return a comma separated list of available authentication methods supported by server.
Definition: MediaCurl.cc:1678
double drate_period
Definition: MediaCurl.cc:263
char _curlError[CURL_ERROR_SIZE]
Definition: MediaCurl.h:177
void setVerifyPeerEnabled(bool enabled)
Sets whether to verify host for ssl.
double _dnlNow
Bytes downloaded now.
Definition: MediaCurl.cc:194
long secs
Definition: MediaCurl.cc:267
Convenience interface for handling authentication data of media user.
bool userMayRWX() const
Definition: PathInfo.h:353
void setVerifyHostEnabled(bool enabled)
Sets whether to verify host for ssl.
Url manipulation class.
Definition: Url.h:87
bool headRequestsAllowed() const
whether HEAD requests are allowed
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:1374
void setUserAgentString(const std::string &agent)
sets the user agent ie: "Mozilla v3"
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
#define DBG
Definition: Logger.h:78
void delQueryParam(const std::string &param)
remove the specified query parameter.
Definition: Url.cc:840
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.
Definition: Url.cc:567
ByteCount _expectedFileSize
Definition: MediaCurl.cc:185
double _dnlTotal
Bytes to download or 0 if unknown.
Definition: MediaCurl.cc:192
const std::string & msg() const
Return the message string provided to the ctor.
Definition: Exception.h:195