libzypp  17.14.1
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 
850  if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
851  SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
852  else
853  MIL << "No cookies requested" << endl;
854  SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
855  SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
856  SET_OPTION(CURLOPT_NOPROGRESS, 0L);
857 
858 #if CURLVERSION_AT_LEAST(7,18,0)
859  // bnc #306272
860  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
861 #endif
862  // append settings custom headers to curl
863  for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
864  it != vol_settings.headersEnd();
865  ++it )
866  {
867  // MIL << "HEADER " << *it << std::endl;
868 
869  _customHeaders = curl_slist_append(_customHeaders, it->c_str());
870  if ( !_customHeaders )
872  }
873 
874  SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
875 }
876 
878 
879 
880 void MediaCurl::attachTo (bool next)
881 {
882  if ( next )
884 
885  if ( !_url.isValid() )
887 
890  {
892  }
893 
894  disconnectFrom(); // clean _curl if needed
895  _curl = curl_easy_init();
896  if ( !_curl ) {
898  }
899  try
900  {
901  setupEasy();
902  }
903  catch (Exception & ex)
904  {
905  disconnectFrom();
906  ZYPP_RETHROW(ex);
907  }
908 
909  // FIXME: need a derived class to propelly compare url's
911  setMediaSource(media);
912 }
913 
914 bool
916 {
917  return MediaHandler::checkAttachPoint( apoint, true, true);
918 }
919 
921 
923 {
924  if ( _customHeaders )
925  {
926  curl_slist_free_all(_customHeaders);
927  _customHeaders = 0L;
928  }
929 
930  if ( _curl )
931  {
932  curl_easy_cleanup( _curl );
933  _curl = NULL;
934  }
935 }
936 
938 
939 void MediaCurl::releaseFrom( const std::string & ejectDev )
940 {
941  disconnect();
942 }
943 
944 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
945 {
946  // Simply extend the URLs pathname. An 'absolute' URL path
947  // is achieved by encoding the leading '/' in an URL path:
948  // URL: ftp://user@server -> ~user
949  // URL: ftp://user@server/ -> ~user
950  // URL: ftp://user@server// -> ~user
951  // URL: ftp://user@server/%2F -> /
952  // ^- this '/' is just a separator
953  Url newurl( _url );
954  newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
955  return newurl;
956 }
957 
959 
960 void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
961 {
962  // Use absolute file name to prevent access of files outside of the
963  // hierarchy below the attach point.
964  getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
965 }
966 
968 
969 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
970 {
972 
973  Url fileurl(getFileUrl(filename));
974 
975  bool retry = false;
976 
977  do
978  {
979  try
980  {
981  doGetFileCopy(filename, target, report, expectedFileSize_r);
982  retry = false;
983  }
984  // retry with proper authentication data
985  catch (MediaUnauthorizedException & ex_r)
986  {
987  if(authenticate(ex_r.hint(), !retry))
988  retry = true;
989  else
990  {
992  ZYPP_RETHROW(ex_r);
993  }
994  }
995  // unexpected exception
996  catch (MediaException & excpt_r)
997  {
999  if( typeid(excpt_r) == typeid( media::MediaFileNotFoundException ) ||
1000  typeid(excpt_r) == typeid( media::MediaNotAFileException ) )
1001  {
1003  }
1004  report->finish(fileurl, reason, excpt_r.asUserHistory());
1005  ZYPP_RETHROW(excpt_r);
1006  }
1007  }
1008  while (retry);
1009 
1011 }
1012 
1014 
1015 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
1016 {
1017  bool retry = false;
1018 
1019  do
1020  {
1021  try
1022  {
1023  return doGetDoesFileExist( filename );
1024  }
1025  // authentication problem, retry with proper authentication data
1026  catch (MediaUnauthorizedException & ex_r)
1027  {
1028  if(authenticate(ex_r.hint(), !retry))
1029  retry = true;
1030  else
1031  ZYPP_RETHROW(ex_r);
1032  }
1033  // unexpected exception
1034  catch (MediaException & excpt_r)
1035  {
1036  ZYPP_RETHROW(excpt_r);
1037  }
1038  }
1039  while (retry);
1040 
1041  return false;
1042 }
1043 
1045 
1047  CURLcode code,
1048  bool timeout_reached) const
1049 {
1050  if ( code != 0 )
1051  {
1052  Url url;
1053  if (filename.empty())
1054  url = _url;
1055  else
1056  url = getFileUrl(filename);
1057 
1058  std::string err;
1059  {
1060  switch ( code )
1061  {
1062  case CURLE_UNSUPPORTED_PROTOCOL:
1063  err = " Unsupported protocol";
1064  if ( !_lastRedirect.empty() )
1065  {
1066  err += " or redirect (";
1067  err += _lastRedirect;
1068  err += ")";
1069  }
1070  break;
1071  case CURLE_URL_MALFORMAT:
1072  case CURLE_URL_MALFORMAT_USER:
1073  err = " Bad URL";
1074  break;
1075  case CURLE_LOGIN_DENIED:
1076  ZYPP_THROW(
1077  MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
1078  break;
1079  case CURLE_HTTP_RETURNED_ERROR:
1080  {
1081  long httpReturnCode = 0;
1082  CURLcode infoRet = curl_easy_getinfo( _curl,
1083  CURLINFO_RESPONSE_CODE,
1084  &httpReturnCode );
1085  if ( infoRet == CURLE_OK )
1086  {
1087  string msg = "HTTP response: " + str::numstring( httpReturnCode );
1088  switch ( httpReturnCode )
1089  {
1090  case 401:
1091  {
1092  string auth_hint = getAuthHint();
1093 
1094  DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1095  DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1096 
1098  url, "Login failed.", _curlError, auth_hint
1099  ));
1100  }
1101 
1102  case 502: // bad gateway (bnc #1070851)
1103  case 503: // service temporarily unavailable (bnc #462545)
1105  case 504: // gateway timeout
1107  case 403:
1108  {
1109  string msg403;
1110  if ( url.getHost().find(".suse.com") != string::npos )
1111  msg403 = _("Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
1112  else if (url.asString().find("novell.com") != string::npos)
1113  msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1115  }
1116  case 404:
1117  case 410:
1119  }
1120 
1121  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1123  }
1124  else
1125  {
1126  string msg = "Unable to retrieve HTTP response:";
1127  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1129  }
1130  }
1131  break;
1132  case CURLE_FTP_COULDNT_RETR_FILE:
1133 #if CURLVERSION_AT_LEAST(7,16,0)
1134  case CURLE_REMOTE_FILE_NOT_FOUND:
1135 #endif
1136  case CURLE_FTP_ACCESS_DENIED:
1137  case CURLE_TFTP_NOTFOUND:
1138  err = "File not found";
1140  break;
1141  case CURLE_BAD_PASSWORD_ENTERED:
1142  case CURLE_FTP_USER_PASSWORD_INCORRECT:
1143  err = "Login failed";
1144  break;
1145  case CURLE_COULDNT_RESOLVE_PROXY:
1146  case CURLE_COULDNT_RESOLVE_HOST:
1147  case CURLE_COULDNT_CONNECT:
1148  case CURLE_FTP_CANT_GET_HOST:
1149  err = "Connection failed";
1150  break;
1151  case CURLE_WRITE_ERROR:
1152  err = "Write error";
1153  break;
1154  case CURLE_PARTIAL_FILE:
1155  case CURLE_OPERATION_TIMEDOUT:
1156  timeout_reached = true; // fall though to TimeoutException
1157  // fall though...
1158  case CURLE_ABORTED_BY_CALLBACK:
1159  if( timeout_reached )
1160  {
1161  err = "Timeout reached";
1163  }
1164  else
1165  {
1166  err = "User abort";
1167  }
1168  break;
1169  case CURLE_SSL_PEER_CERTIFICATE:
1170  default:
1171  err = "Curl error " + str::numstring( code );
1172  break;
1173  }
1174 
1175  // uhm, no 0 code but unknown curl exception
1177  }
1178  }
1179  else
1180  {
1181  // actually the code is 0, nothing happened
1182  }
1183 }
1184 
1186 
1187 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1188 {
1189  DBG << filename.asString() << endl;
1190 
1191  if(!_url.isValid())
1193 
1194  if(_url.getHost().empty())
1196 
1197  Url url(getFileUrl(filename));
1198 
1199  DBG << "URL: " << url.asString() << endl;
1200  // Use URL without options and without username and passwd
1201  // (some proxies dislike them in the URL).
1202  // Curl seems to need the just scheme, hostname and a path;
1203  // the rest was already passed as curl options (in attachTo).
1204  Url curlUrl( clearQueryString(url) );
1205 
1206  //
1207  // See also Bug #154197 and ftp url definition in RFC 1738:
1208  // The url "ftp://user@host/foo/bar/file" contains a path,
1209  // that is relative to the user's home.
1210  // The url "ftp://user@host//foo/bar/file" (or also with
1211  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1212  // contains an absolute path.
1213  //
1214  _lastRedirect.clear();
1215  string urlBuffer( curlUrl.asString());
1216  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1217  urlBuffer.c_str() );
1218  if ( ret != 0 ) {
1220  }
1221 
1222  // instead of returning no data with NOBODY, we return
1223  // little data, that works with broken servers, and
1224  // works for ftp as well, because retrieving only headers
1225  // ftp will return always OK code ?
1226  // See http://curl.haxx.se/docs/knownbugs.html #58
1227  if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1229  ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1230  else
1231  ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1232 
1233  if ( ret != 0 ) {
1234  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1235  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1236  /* yes, this is why we never got to get NOBODY working before,
1237  because setting it changes this option too, and we also
1238  need to reset it
1239  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1240  */
1241  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1243  }
1244 
1245  AutoFILE file { ::fopen( "/dev/null", "w" ) };
1246  if ( !file ) {
1247  ERR << "fopen failed for /dev/null" << endl;
1248  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1249  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1250  /* yes, this is why we never got to get NOBODY working before,
1251  because setting it changes this option too, and we also
1252  need to reset it
1253  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1254  */
1255  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1256  if ( ret != 0 ) {
1258  }
1259  ZYPP_THROW(MediaWriteException("/dev/null"));
1260  }
1261 
1262  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, (*file) );
1263  if ( ret != 0 ) {
1264  std::string err( _curlError);
1265  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1266  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1267  /* yes, this is why we never got to get NOBODY working before,
1268  because setting it changes this option too, and we also
1269  need to reset it
1270  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1271  */
1272  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1273  if ( ret != 0 ) {
1275  }
1277  }
1278 
1279  CURLcode ok = curl_easy_perform( _curl );
1280  MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1281 
1282  // reset curl settings
1283  if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1284  {
1285  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1286  if ( ret != 0 ) {
1288  }
1289 
1290  /* yes, this is why we never got to get NOBODY working before,
1291  because setting it changes this option too, and we also
1292  need to reset it
1293  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1294  */
1295  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1296  if ( ret != 0 ) {
1298  }
1299 
1300  }
1301  else
1302  {
1303  // for FTP we set different options
1304  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1305  if ( ret != 0 ) {
1307  }
1308  }
1309 
1310  // as we are not having user interaction, the user can't cancel
1311  // the file existence checking, a callback or timeout return code
1312  // will be always a timeout.
1313  try {
1314  evaluateCurlCode( filename, ok, true /* timeout */);
1315  }
1316  catch ( const MediaFileNotFoundException &e ) {
1317  // if the file did not exist then we can return false
1318  return false;
1319  }
1320  catch ( const MediaException &e ) {
1321  // some error, we are not sure about file existence, rethrw
1322  ZYPP_RETHROW(e);
1323  }
1324  // exists
1325  return ( ok == CURLE_OK );
1326 }
1327 
1329 
1330 
1331 #if DETECT_DIR_INDEX
1332 bool MediaCurl::detectDirIndex() const
1333 {
1334  if(_url.getScheme() != "http" && _url.getScheme() != "https")
1335  return false;
1336  //
1337  // try to check the effective url and set the not_a_file flag
1338  // if the url path ends with a "/", what usually means, that
1339  // we've received a directory index (index.html content).
1340  //
1341  // Note: This may be dangerous and break file retrieving in
1342  // case of some server redirections ... ?
1343  //
1344  bool not_a_file = false;
1345  char *ptr = NULL;
1346  CURLcode ret = curl_easy_getinfo( _curl,
1347  CURLINFO_EFFECTIVE_URL,
1348  &ptr);
1349  if ( ret == CURLE_OK && ptr != NULL)
1350  {
1351  try
1352  {
1353  Url eurl( ptr);
1354  std::string path( eurl.getPathName());
1355  if( !path.empty() && path != "/" && *path.rbegin() == '/')
1356  {
1357  DBG << "Effective url ("
1358  << eurl
1359  << ") seems to provide the index of a directory"
1360  << endl;
1361  not_a_file = true;
1362  }
1363  }
1364  catch( ... )
1365  {}
1366  }
1367  return not_a_file;
1368 }
1369 #endif
1370 
1372 
1373 void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1374 {
1375  Pathname dest = target.absolutename();
1376  if( assert_dir( dest.dirname() ) )
1377  {
1378  DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1379  ZYPP_THROW( MediaSystemException(getFileUrl(filename), "System error on " + dest.dirname().asString()) );
1380  }
1381 
1382  ManagedFile destNew { target.extend( ".new.zypp.XXXXXX" ) };
1383  AutoFILE file;
1384  {
1385  AutoFREE<char> buf { ::strdup( (*destNew).c_str() ) };
1386  if( ! buf )
1387  {
1388  ERR << "out of memory for temp file name" << endl;
1389  ZYPP_THROW(MediaSystemException(getFileUrl(filename), "out of memory for temp file name"));
1390  }
1391 
1392  AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1393  if( tmp_fd == -1 )
1394  {
1395  ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1396  ZYPP_THROW(MediaWriteException(destNew));
1397  }
1398  destNew = ManagedFile( (*buf), filesystem::unlink );
1399 
1400  file = ::fdopen( tmp_fd, "we" );
1401  if ( ! file )
1402  {
1403  ERR << "fopen failed for file '" << destNew << "'" << endl;
1404  ZYPP_THROW(MediaWriteException(destNew));
1405  }
1406  tmp_fd.resetDispose(); // don't close it here! ::fdopen moved ownership to file
1407  }
1408 
1409  DBG << "dest: " << dest << endl;
1410  DBG << "temp: " << destNew << endl;
1411 
1412  // set IFMODSINCE time condition (no download if not modified)
1413  if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1414  {
1415  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1416  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1417  }
1418  else
1419  {
1420  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1421  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1422  }
1423  try
1424  {
1425  doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
1426  }
1427  catch (Exception &e)
1428  {
1429  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1430  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1431  ZYPP_RETHROW(e);
1432  }
1433 
1434  long httpReturnCode = 0;
1435  CURLcode infoRet = curl_easy_getinfo(_curl,
1436  CURLINFO_RESPONSE_CODE,
1437  &httpReturnCode);
1438  bool modified = true;
1439  if (infoRet == CURLE_OK)
1440  {
1441  DBG << "HTTP response: " + str::numstring(httpReturnCode);
1442  if ( httpReturnCode == 304
1443  || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1444  {
1445  DBG << " Not modified.";
1446  modified = false;
1447  }
1448  DBG << endl;
1449  }
1450  else
1451  {
1452  WAR << "Could not get the reponse code." << endl;
1453  }
1454 
1455  if (modified || infoRet != CURLE_OK)
1456  {
1457  // apply umask
1458  if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1459  {
1460  ERR << "Failed to chmod file " << destNew << endl;
1461  }
1462 
1463  file.resetDispose(); // we're going to close it manually here
1464  if ( ::fclose( file ) )
1465  {
1466  ERR << "Fclose failed for file '" << destNew << "'" << endl;
1467  ZYPP_THROW(MediaWriteException(destNew));
1468  }
1469 
1470  // move the temp file into dest
1471  if ( rename( destNew, dest ) != 0 ) {
1472  ERR << "Rename failed" << endl;
1474  }
1475  destNew.resetDispose(); // no more need to unlink it
1476  }
1477 
1478  DBG << "done: " << PathInfo(dest) << endl;
1479 }
1480 
1482 
1483 void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1484 {
1485  DBG << filename.asString() << endl;
1486 
1487  if(!_url.isValid())
1489 
1490  if(_url.getHost().empty())
1492 
1493  Url url(getFileUrl(filename));
1494 
1495  DBG << "URL: " << url.asString() << endl;
1496  // Use URL without options and without username and passwd
1497  // (some proxies dislike them in the URL).
1498  // Curl seems to need the just scheme, hostname and a path;
1499  // the rest was already passed as curl options (in attachTo).
1500  Url curlUrl( clearQueryString(url) );
1501 
1502  //
1503  // See also Bug #154197 and ftp url definition in RFC 1738:
1504  // The url "ftp://user@host/foo/bar/file" contains a path,
1505  // that is relative to the user's home.
1506  // The url "ftp://user@host//foo/bar/file" (or also with
1507  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1508  // contains an absolute path.
1509  //
1510  _lastRedirect.clear();
1511  string urlBuffer( curlUrl.asString());
1512  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1513  urlBuffer.c_str() );
1514  if ( ret != 0 ) {
1516  }
1517 
1518  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1519  if ( ret != 0 ) {
1521  }
1522 
1523  // Set callback and perform.
1524  ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
1525  if (!(options & OPTION_NO_REPORT_START))
1526  report->start(url, dest);
1527  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1528  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1529  }
1530 
1531  ret = curl_easy_perform( _curl );
1532 #if CURLVERSION_AT_LEAST(7,19,4)
1533  // bnc#692260: If the client sends a request with an If-Modified-Since header
1534  // with a future date for the server, the server may respond 200 sending a
1535  // zero size file.
1536  // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1537  if ( ftell(file) == 0 && ret == 0 )
1538  {
1539  long httpReturnCode = 33;
1540  if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1541  {
1542  long conditionUnmet = 33;
1543  if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1544  {
1545  WAR << "TIMECONDITION unmet - retry without." << endl;
1546  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1547  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1548  ret = curl_easy_perform( _curl );
1549  }
1550  }
1551  }
1552 #endif
1553 
1554  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1555  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1556  }
1557 
1558  if ( ret != 0 )
1559  {
1560  ERR << "curl error: " << ret << ": " << _curlError
1561  << ", temp file size " << ftell(file)
1562  << " bytes." << endl;
1563 
1564  // the timeout is determined by the progress data object
1565  // which holds whether the timeout was reached or not,
1566  // otherwise it would be a user cancel
1567  try {
1568 
1569  if ( progressData.fileSizeExceeded )
1570  ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
1571 
1572  evaluateCurlCode( filename, ret, progressData.reached );
1573  }
1574  catch ( const MediaException &e ) {
1575  // some error, we are not sure about file existence, rethrw
1576  ZYPP_RETHROW(e);
1577  }
1578  }
1579 
1580 #if DETECT_DIR_INDEX
1581  if (!ret && detectDirIndex())
1582  {
1584  }
1585 #endif // DETECT_DIR_INDEX
1586 }
1587 
1589 
1590 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1591 {
1592  filesystem::DirContent content;
1593  getDirInfo( content, dirname, /*dots*/false );
1594 
1595  for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1596  Pathname filename = dirname + it->name;
1597  int res = 0;
1598 
1599  switch ( it->type ) {
1600  case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1601  case filesystem::FT_FILE:
1602  getFile( filename, 0 );
1603  break;
1604  case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1605  if ( recurse_r ) {
1606  getDir( filename, recurse_r );
1607  } else {
1608  res = assert_dir( localPath( filename ) );
1609  if ( res ) {
1610  WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1611  }
1612  }
1613  break;
1614  default:
1615  // don't provide devices, sockets, etc.
1616  break;
1617  }
1618  }
1619 }
1620 
1622 
1623 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1624  const Pathname & dirname, bool dots ) const
1625 {
1626  getDirectoryYast( retlist, dirname, dots );
1627 }
1628 
1630 
1632  const Pathname & dirname, bool dots ) const
1633 {
1634  getDirectoryYast( retlist, dirname, dots );
1635 }
1636 
1638 //
1639 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1640 {
1641  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1642  if( pdata )
1643  {
1644  // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1645  // prevent a percentage raise while downloading a metalink file. Download
1646  // activity however is indicated by propagating the download rate (via dlnow).
1647  pdata->updateStats( 0.0, dlnow );
1648  return pdata->reportProgress();
1649  }
1650  return 0;
1651 }
1652 
1653 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1654 {
1655  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1656  if( pdata )
1657  {
1658  // work around curl bug that gives us old data
1659  long httpReturnCode = 0;
1660  if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1661  return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1662 
1663  pdata->updateStats( dltotal, dlnow );
1664  return pdata->reportProgress();
1665  }
1666  return 0;
1667 }
1668 
1670 {
1671  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1672  return pdata ? pdata->curl : 0;
1673 }
1674 
1676 
1678 {
1679  long auth_info = CURLAUTH_NONE;
1680 
1681  CURLcode infoRet =
1682  curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1683 
1684  if(infoRet == CURLE_OK)
1685  {
1686  return CurlAuthData::auth_type_long2str(auth_info);
1687  }
1688 
1689  return "";
1690 }
1691 
1696 void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
1697 {
1698  ProgressData *data = reinterpret_cast<ProgressData *>(clientp);
1699  if ( data ) {
1700  data->_expectedFileSize = expectedFileSize;
1701  }
1702 }
1703 
1705 
1706 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1707 {
1709  CredentialManager cm(CredManagerOptions(ZConfig::instance().repoManagerRoot()));
1710  CurlAuthData_Ptr credentials;
1711 
1712  // get stored credentials
1713  AuthData_Ptr cmcred = cm.getCred(_url);
1714 
1715  if (cmcred && firstTry)
1716  {
1717  credentials.reset(new CurlAuthData(*cmcred));
1718  DBG << "got stored credentials:" << endl << *credentials << endl;
1719  }
1720  // if not found, ask user
1721  else
1722  {
1723 
1724  CurlAuthData_Ptr curlcred;
1725  curlcred.reset(new CurlAuthData());
1727 
1728  // preset the username if present in current url
1729  if (!_url.getUsername().empty() && firstTry)
1730  curlcred->setUsername(_url.getUsername());
1731  // if CM has found some credentials, preset the username from there
1732  else if (cmcred)
1733  curlcred->setUsername(cmcred->username());
1734 
1735  // indicate we have no good credentials from CM
1736  cmcred.reset();
1737 
1738  string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1739 
1740  // set available authentication types from the exception
1741  // might be needed in prompt
1742  curlcred->setAuthType(availAuthTypes);
1743 
1744  // ask user
1745  if (auth_report->prompt(_url, prompt_msg, *curlcred))
1746  {
1747  DBG << "callback answer: retry" << endl
1748  << "CurlAuthData: " << *curlcred << endl;
1749 
1750  if (curlcred->valid())
1751  {
1752  credentials = curlcred;
1753  // if (credentials->username() != _url.getUsername())
1754  // _url.setUsername(credentials->username());
1762  }
1763  }
1764  else
1765  {
1766  DBG << "callback answer: cancel" << endl;
1767  }
1768  }
1769 
1770  // set username and password
1771  if (credentials)
1772  {
1773  // HACK, why is this const?
1774  const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1775  const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1776 
1777  // set username and password
1778  CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1780 
1781  // set available authentication types from the exception
1782  if (credentials->authType() == CURLAUTH_NONE)
1783  credentials->setAuthType(availAuthTypes);
1784 
1785  // set auth type (seems this must be set _after_ setting the userpwd)
1786  if (credentials->authType() != CURLAUTH_NONE)
1787  {
1788  // FIXME: only overwrite if not empty?
1789  const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1790  ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1792  }
1793 
1794  if (!cmcred)
1795  {
1796  credentials->setUrl(_url);
1797  cm.addCred(*credentials);
1798  cm.save();
1799  }
1800 
1801  return true;
1802  }
1803 
1804  return false;
1805 }
1806 
1807 //need a out of line definiton, otherwise vtable is emitted for every translation unit
1809 
1810 
1811  } // namespace media
1812 } // namespace zypp
1813 //
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:915
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:127
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:1706
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:1653
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:1639
Pathname certificateAuthoritiesPath() const
SSL certificate authorities path ( default: /etc/ssl/certs )
Definition: Arch.h:344
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
unsigned split(const C_Str &line_r, TOutputIterator result_r, const C_Str &sepchars_r=" \)
Split line_r into words.
Definition: String.h:502
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:1590
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:944
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:939
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:1696
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
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:1046
bool fileSizeExceeded
Definition: MediaCurl.cc:183
virtual void getFileCopy(const Pathname &srcFilename, const Pathname &targetFilename, const ByteCount &expectedFileSize_r) const override
Definition: MediaCurl.cc:969
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:1187
virtual void getFile(const Pathname &filename, const ByteCount &expectedFileSize_r) const override
Call concrete handler to provide file below attach point.
Definition: MediaCurl.cc:960
shared_ptr< CurlAuthData > CurlAuthData_Ptr
virtual void attachTo(bool next=false) override
Call concrete handler to attach the media.
Definition: MediaCurl.cc:880
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:1015
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:1483
#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:1623
virtual void disconnectFrom() override
Definition: MediaCurl.cc:922
static CURL * progressCallback_getcurl(void *clientp)
Definition: MediaCurl.cc:1669
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:809
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:1677
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:1373
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