libzypp  17.23.8
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/media/CurlHelper.h>
29 #include <zypp/Target.h>
30 #include <zypp/ZYppFactory.h>
31 #include <zypp/ZConfig.h>
32 
33 #include <cstdlib>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/mount.h>
37 #include <errno.h>
38 #include <dirent.h>
39 #include <unistd.h>
40 
41 using std::endl;
42 
43 using namespace internal;
44 using namespace zypp::base;
45 
46 namespace zypp {
47 
48  namespace media {
49 
50  namespace {
51  struct ProgressData
52  {
53  ProgressData( CURL *_curl, time_t _timeout = 0, const Url & _url = Url(),
54  ByteCount expectedFileSize_r = 0,
55  callback::SendReport<DownloadProgressReport> *_report = nullptr )
56  : curl( _curl )
57  , url( _url )
58  , timeout( _timeout )
59  , reached( false )
60  , fileSizeExceeded ( false )
61  , report( _report )
62  , _expectedFileSize( expectedFileSize_r )
63  {}
64 
65  CURL *curl;
66  Url url;
67  time_t timeout;
68  bool reached;
70  callback::SendReport<DownloadProgressReport> *report;
71  ByteCount _expectedFileSize;
72 
73  time_t _timeStart = 0;
74  time_t _timeLast = 0;
75  time_t _timeRcv = 0;
76  time_t _timeNow = 0;
77 
78  double _dnlTotal = 0.0;
79  double _dnlLast = 0.0;
80  double _dnlNow = 0.0;
81 
82  int _dnlPercent= 0;
83 
84  double _drateTotal= 0.0;
85  double _drateLast = 0.0;
86 
87  void updateStats( double dltotal = 0.0, double dlnow = 0.0 )
88  {
89  time_t now = _timeNow = time(0);
90 
91  // If called without args (0.0), recompute based on the last values seen
92  if ( dltotal && dltotal != _dnlTotal )
93  _dnlTotal = dltotal;
94 
95  if ( dlnow && dlnow != _dnlNow )
96  {
97  _timeRcv = now;
98  _dnlNow = dlnow;
99  }
100  else if ( !_dnlNow && !_dnlTotal )
101  {
102  // Start time counting as soon as first data arrives.
103  // Skip the connection / redirection time at begin.
104  return;
105  }
106 
107  // init or reset if time jumps back
108  if ( !_timeStart || _timeStart > now )
109  _timeStart = _timeLast = _timeRcv = now;
110 
111  // timeout condition
112  if ( timeout )
113  reached = ( (now - _timeRcv) > timeout );
114 
115  // check if the downloaded data is already bigger than what we expected
116  fileSizeExceeded = _expectedFileSize > 0 && _expectedFileSize < static_cast<ByteCount::SizeType>(_dnlNow);
117 
118  // percentage:
119  if ( _dnlTotal )
120  _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
121 
122  // download rates:
123  _drateTotal = _dnlNow / std::max( int(now - _timeStart), 1 );
124 
125  if ( _timeLast < now )
126  {
127  _drateLast = (_dnlNow - _dnlLast) / int(now - _timeLast);
128  // start new period
129  _timeLast = now;
130  _dnlLast = _dnlNow;
131  }
132  else if ( _timeStart == _timeLast )
134  }
135 
136  int reportProgress() const
137  {
138  if ( fileSizeExceeded )
139  return 1;
140  if ( reached )
141  return 1; // no-data timeout
142  if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
143  return 1; // user requested abort
144  return 0;
145  }
146 
147 
148  // download rate of the last period (cca 1 sec)
149  double drate_period;
150  // bytes downloaded at the start of the last period
151  double dload_period;
152  // seconds from the start of the download
153  long secs;
154  // average download rate
155  double drate_avg;
156  // last time the progress was reported
157  time_t ltime;
158  // bytes downloaded at the moment the progress was last reported
159  double dload;
160  // bytes uploaded at the moment the progress was last reported
161  double uload;
162  };
163  }
164 
165 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
166 
167 // we use this define to unbloat code as this C setting option
168 // and catching exception is done frequently.
170 #define SET_OPTION(opt,val) do { \
171  ret = curl_easy_setopt ( _curl, opt, val ); \
172  if ( ret != 0) { \
173  ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
174  } \
175  } while ( false )
176 
177 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
178 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
179 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
180 
181 MediaCurl::MediaCurl( const Url & url_r,
182  const Pathname & attach_point_hint_r )
183  : MediaHandler( url_r, attach_point_hint_r,
184  "/", // urlpath at attachpoint
185  true ), // does_download
186  _curl( NULL ),
187  _customHeaders(0L)
188 {
189  _curlError[0] = '\0';
190  _curlDebug = 0L;
191 
192  MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
193 
195 
196  if( !attachPoint().empty())
197  {
198  PathInfo ainfo(attachPoint());
199  Pathname apath(attachPoint() + "XXXXXX");
200  char *atemp = ::strdup( apath.asString().c_str());
201  char *atest = NULL;
202  if( !ainfo.isDir() || !ainfo.userMayRWX() ||
203  atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
204  {
205  WAR << "attach point " << ainfo.path()
206  << " is not useable for " << url_r.getScheme() << endl;
207  setAttachPoint("", true);
208  }
209  else if( atest != NULL)
210  ::rmdir(atest);
211 
212  if( atemp != NULL)
213  ::free(atemp);
214  }
215 }
216 
218 {
220 }
221 
223 {
224  return _settings;
225 }
226 
227 
228 void MediaCurl::setCookieFile( const Pathname &fileName )
229 {
230  _cookieFile = fileName;
231 }
232 
234 
235 void MediaCurl::checkProtocol(const Url &url) const
236 {
237  curl_version_info_data *curl_info = NULL;
238  curl_info = curl_version_info(CURLVERSION_NOW);
239  // curl_info does not need any free (is static)
240  if (curl_info->protocols)
241  {
242  const char * const *proto;
243  std::string scheme( url.getScheme());
244  bool found = false;
245  for(proto=curl_info->protocols; !found && *proto; ++proto)
246  {
247  if( scheme == std::string((const char *)*proto))
248  found = true;
249  }
250  if( !found)
251  {
252  std::string msg("Unsupported protocol '");
253  msg += scheme;
254  msg += "'";
256  }
257  }
258 }
259 
261 {
262  {
263  char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
264  _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
265  if( _curlDebug > 0)
266  {
267  curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
268  curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
269  curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
270  }
271  }
272 
273  curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
274  curl_easy_setopt(_curl, CURLOPT_HEADERDATA, &_lastRedirect);
275  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
276  if ( ret != 0 ) {
277  ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
278  }
279 
280  SET_OPTION(CURLOPT_FAILONERROR, 1L);
281  SET_OPTION(CURLOPT_NOSIGNAL, 1L);
282 
283  // create non persistant settings
284  // so that we don't add headers twice
285  TransferSettings vol_settings(_settings);
286 
287  // add custom headers for download.opensuse.org (bsc#955801)
288  if ( _url.getHost() == "download.opensuse.org" )
289  {
290  vol_settings.addHeader(anonymousIdHeader());
291  vol_settings.addHeader(distributionFlavorHeader());
292  }
293  vol_settings.addHeader("Pragma:");
294 
295  _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
297 
299 
300  // fill some settings from url query parameters
301  try
302  {
304  }
305  catch ( const MediaException &e )
306  {
307  disconnectFrom();
308  ZYPP_RETHROW(e);
309  }
310  // if the proxy was not set (or explicitly unset) by url, then look...
311  if ( _settings.proxy().empty() )
312  {
313  // ...at the system proxy settings
315  }
316 
319  {
320  switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
321  {
322  case 4: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); break;
323  case 6: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); break;
324  }
325  }
326 
330  SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
331  // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
332  // just in case curl does not trigger its progress callback frequently
333  // enough.
334  if ( _settings.timeout() )
335  {
336  SET_OPTION(CURLOPT_TIMEOUT, 3600L);
337  }
338 
339  // follow any Location: header that the server sends as part of
340  // an HTTP header (#113275)
341  SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
342  // 3 redirects seem to be too few in some cases (bnc #465532)
343  SET_OPTION(CURLOPT_MAXREDIRS, 6L);
344 
345  if ( _url.getScheme() == "https" )
346  {
347 #if CURLVERSION_AT_LEAST(7,19,4)
348  // restrict following of redirections from https to https only
349  SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
350 #endif
351 
354  {
356  }
357 
359  {
360  SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
361  }
362  if( ! _settings.clientKeyPath().empty() )
363  {
364  SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
365  }
366 
367 #ifdef CURLSSLOPT_ALLOW_BEAST
368  // see bnc#779177
369  ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
370  if ( ret != 0 ) {
371  disconnectFrom();
373  }
374 #endif
375  SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
376  SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
377  // bnc#903405 - POODLE: libzypp should only talk TLS
378  SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
379  }
380 
381  SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
382 
383  /*---------------------------------------------------------------*
384  CURLOPT_USERPWD: [user name]:[password]
385 
386  Url::username/password -> CURLOPT_USERPWD
387  If not provided, anonymous FTP identification
388  *---------------------------------------------------------------*/
389 
390  if ( _settings.userPassword().size() )
391  {
392  SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
393  std::string use_auth = _settings.authType();
394  if (use_auth.empty())
395  use_auth = "digest,basic"; // our default
396  long auth = CurlAuthData::auth_type_str2long(use_auth);
397  if( auth != CURLAUTH_NONE)
398  {
399  DBG << "Enabling HTTP authentication methods: " << use_auth
400  << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
401  SET_OPTION(CURLOPT_HTTPAUTH, auth);
402  }
403  }
404 
405  if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
406  {
407  DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
408  SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
409  SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
410  /*---------------------------------------------------------------*
411  * CURLOPT_PROXYUSERPWD: [user name]:[password]
412  *
413  * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
414  * If not provided, $HOME/.curlrc is evaluated
415  *---------------------------------------------------------------*/
416 
417  std::string proxyuserpwd = _settings.proxyUserPassword();
418 
419  if ( proxyuserpwd.empty() )
420  {
421  CurlConfig curlconf;
422  CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
423  if ( curlconf.proxyuserpwd.empty() )
424  DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
425  else
426  {
427  proxyuserpwd = curlconf.proxyuserpwd;
428  DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
429  }
430  }
431  else
432  {
433  DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
434  }
435 
436  if ( ! proxyuserpwd.empty() )
437  {
438  SET_OPTION(CURLOPT_PROXYUSERPWD, curlUnEscape( proxyuserpwd ).c_str());
439  }
440  }
441 #if CURLVERSION_AT_LEAST(7,19,4)
442  else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
443  {
444  // Explicitly disabled in URL (see fillSettingsFromUrl()).
445  // This should also prevent libcurl from looking into the environment.
446  DBG << "Proxy: explicitly NOPROXY" << endl;
447  SET_OPTION(CURLOPT_NOPROXY, "*");
448  }
449 #endif
450  else
451  {
452  DBG << "Proxy: not explicitly set" << endl;
453  DBG << "Proxy: libcurl may look into the environment" << endl;
454  }
455 
457  if ( _settings.minDownloadSpeed() != 0 )
458  {
459  SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
460  // default to 10 seconds at low speed
461  SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
462  }
463 
464 #if CURLVERSION_AT_LEAST(7,15,5)
465  if ( _settings.maxDownloadSpeed() != 0 )
466  SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
467 #endif
468 
469  /*---------------------------------------------------------------*
470  *---------------------------------------------------------------*/
471 
474  if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
475  SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
476  else
477  MIL << "No cookies requested" << endl;
478  SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
479  SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
480  SET_OPTION(CURLOPT_NOPROGRESS, 0L);
481 
482 #if CURLVERSION_AT_LEAST(7,18,0)
483  // bnc #306272
484  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
485 #endif
486  // append settings custom headers to curl
487  for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
488  it != vol_settings.headersEnd();
489  ++it )
490  {
491  // MIL << "HEADER " << *it << std::endl;
492 
493  _customHeaders = curl_slist_append(_customHeaders, it->c_str());
494  if ( !_customHeaders )
496  }
497 
498  SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
499 }
500 
502 
503 
504 void MediaCurl::attachTo (bool next)
505 {
506  if ( next )
508 
509  if ( !_url.isValid() )
511 
514  {
516  }
517 
518  disconnectFrom(); // clean _curl if needed
519  _curl = curl_easy_init();
520  if ( !_curl ) {
522  }
523  try
524  {
525  setupEasy();
526  }
527  catch (Exception & ex)
528  {
529  disconnectFrom();
530  ZYPP_RETHROW(ex);
531  }
532 
533  // FIXME: need a derived class to propelly compare url's
535  setMediaSource(media);
536 }
537 
538 bool
540 {
541  return MediaHandler::checkAttachPoint( apoint, true, true);
542 }
543 
545 
547 {
548  if ( _customHeaders )
549  {
550  curl_slist_free_all(_customHeaders);
551  _customHeaders = 0L;
552  }
553 
554  if ( _curl )
555  {
556  curl_easy_cleanup( _curl );
557  _curl = NULL;
558  }
559 }
560 
562 
563 void MediaCurl::releaseFrom( const std::string & ejectDev )
564 {
565  disconnect();
566 }
567 
568 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
569 {
570  // Simply extend the URLs pathname. An 'absolute' URL path
571  // is achieved by encoding the leading '/' in an URL path:
572  // URL: ftp://user@server -> ~user
573  // URL: ftp://user@server/ -> ~user
574  // URL: ftp://user@server// -> ~user
575  // URL: ftp://user@server/%2F -> /
576  // ^- this '/' is just a separator
577  Url newurl( _url );
578  newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
579  return newurl;
580 }
581 
583 
584 void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
585 {
586  // Use absolute file name to prevent access of files outside of the
587  // hierarchy below the attach point.
588  getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
589 }
590 
592 
593 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
594 {
596 
597  Url fileurl(getFileUrl(filename));
598 
599  bool retry = false;
600 
601  do
602  {
603  try
604  {
605  doGetFileCopy(filename, target, report, expectedFileSize_r);
606  retry = false;
607  }
608  // retry with proper authentication data
609  catch (MediaUnauthorizedException & ex_r)
610  {
611  if(authenticate(ex_r.hint(), !retry))
612  retry = true;
613  else
614  {
616  ZYPP_RETHROW(ex_r);
617  }
618  }
619  // unexpected exception
620  catch (MediaException & excpt_r)
621  {
623  if( typeid(excpt_r) == typeid( media::MediaFileNotFoundException ) ||
624  typeid(excpt_r) == typeid( media::MediaNotAFileException ) )
625  {
627  }
628  report->finish(fileurl, reason, excpt_r.asUserHistory());
629  ZYPP_RETHROW(excpt_r);
630  }
631  }
632  while (retry);
633 
635 }
636 
638 
639 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
640 {
641  bool retry = false;
642 
643  do
644  {
645  try
646  {
647  return doGetDoesFileExist( filename );
648  }
649  // authentication problem, retry with proper authentication data
650  catch (MediaUnauthorizedException & ex_r)
651  {
652  if(authenticate(ex_r.hint(), !retry))
653  retry = true;
654  else
655  ZYPP_RETHROW(ex_r);
656  }
657  // unexpected exception
658  catch (MediaException & excpt_r)
659  {
660  ZYPP_RETHROW(excpt_r);
661  }
662  }
663  while (retry);
664 
665  return false;
666 }
667 
669 
671  CURLcode code,
672  bool timeout_reached) const
673 {
674  if ( code != 0 )
675  {
676  Url url;
677  if (filename.empty())
678  url = _url;
679  else
680  url = getFileUrl(filename);
681 
682  std::string err;
683  {
684  switch ( code )
685  {
686  case CURLE_UNSUPPORTED_PROTOCOL:
687  err = " Unsupported protocol";
688  if ( !_lastRedirect.empty() )
689  {
690  err += " or redirect (";
691  err += _lastRedirect;
692  err += ")";
693  }
694  break;
695  case CURLE_URL_MALFORMAT:
696  case CURLE_URL_MALFORMAT_USER:
697  err = " Bad URL";
698  break;
699  case CURLE_LOGIN_DENIED:
700  ZYPP_THROW(
701  MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
702  break;
703  case CURLE_HTTP_RETURNED_ERROR:
704  {
705  long httpReturnCode = 0;
706  CURLcode infoRet = curl_easy_getinfo( _curl,
707  CURLINFO_RESPONSE_CODE,
708  &httpReturnCode );
709  if ( infoRet == CURLE_OK )
710  {
711  std::string msg = "HTTP response: " + str::numstring( httpReturnCode );
712  switch ( httpReturnCode )
713  {
714  case 401:
715  {
716  std::string auth_hint = getAuthHint();
717 
718  DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
719  DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
720 
722  url, "Login failed.", _curlError, auth_hint
723  ));
724  }
725 
726  case 502: // bad gateway (bnc #1070851)
727  case 503: // service temporarily unavailable (bnc #462545)
729  case 504: // gateway timeout
731  case 403:
732  {
733  std::string msg403;
734  if ( url.getHost().find(".suse.com") != std::string::npos )
735  msg403 = _("Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
736  else if (url.asString().find("novell.com") != std::string::npos)
737  msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
739  }
740  case 404:
741  case 410:
743  }
744 
745  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
747  }
748  else
749  {
750  std::string msg = "Unable to retrieve HTTP response:";
751  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
753  }
754  }
755  break;
756  case CURLE_FTP_COULDNT_RETR_FILE:
757 #if CURLVERSION_AT_LEAST(7,16,0)
758  case CURLE_REMOTE_FILE_NOT_FOUND:
759 #endif
760  case CURLE_FTP_ACCESS_DENIED:
761  case CURLE_TFTP_NOTFOUND:
762  err = "File not found";
764  break;
765  case CURLE_BAD_PASSWORD_ENTERED:
766  case CURLE_FTP_USER_PASSWORD_INCORRECT:
767  err = "Login failed";
768  break;
769  case CURLE_COULDNT_RESOLVE_PROXY:
770  case CURLE_COULDNT_RESOLVE_HOST:
771  case CURLE_COULDNT_CONNECT:
772  case CURLE_FTP_CANT_GET_HOST:
773  err = "Connection failed";
774  break;
775  case CURLE_WRITE_ERROR:
776  err = "Write error";
777  break;
778  case CURLE_PARTIAL_FILE:
779  case CURLE_OPERATION_TIMEDOUT:
780  timeout_reached = true; // fall though to TimeoutException
781  // fall though...
782  case CURLE_ABORTED_BY_CALLBACK:
783  if( timeout_reached )
784  {
785  err = "Timeout reached";
787  }
788  else
789  {
790  err = "User abort";
791  }
792  break;
793  case CURLE_SSL_PEER_CERTIFICATE:
794  default:
795  err = "Curl error " + str::numstring( code );
796  break;
797  }
798 
799  // uhm, no 0 code but unknown curl exception
801  }
802  }
803  else
804  {
805  // actually the code is 0, nothing happened
806  }
807 }
808 
810 
811 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
812 {
813  DBG << filename.asString() << endl;
814 
815  if(!_url.isValid())
817 
818  if(_url.getHost().empty())
820 
821  Url url(getFileUrl(filename));
822 
823  DBG << "URL: " << url.asString() << endl;
824  // Use URL without options and without username and passwd
825  // (some proxies dislike them in the URL).
826  // Curl seems to need the just scheme, hostname and a path;
827  // the rest was already passed as curl options (in attachTo).
828  Url curlUrl( clearQueryString(url) );
829 
830  //
831  // See also Bug #154197 and ftp url definition in RFC 1738:
832  // The url "ftp://user@host/foo/bar/file" contains a path,
833  // that is relative to the user's home.
834  // The url "ftp://user@host//foo/bar/file" (or also with
835  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
836  // contains an absolute path.
837  //
838  _lastRedirect.clear();
839  std::string urlBuffer( curlUrl.asString());
840  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
841  urlBuffer.c_str() );
842  if ( ret != 0 ) {
844  }
845 
846  // instead of returning no data with NOBODY, we return
847  // little data, that works with broken servers, and
848  // works for ftp as well, because retrieving only headers
849  // ftp will return always OK code ?
850  // See http://curl.haxx.se/docs/knownbugs.html #58
851  if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
853  ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
854  else
855  ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
856 
857  if ( ret != 0 ) {
858  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
859  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
860  /* yes, this is why we never got to get NOBODY working before,
861  because setting it changes this option too, and we also
862  need to reset it
863  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
864  */
865  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
867  }
868 
869  AutoFILE file { ::fopen( "/dev/null", "w" ) };
870  if ( !file ) {
871  ERR << "fopen failed for /dev/null" << endl;
872  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
873  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
874  /* yes, this is why we never got to get NOBODY working before,
875  because setting it changes this option too, and we also
876  need to reset it
877  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
878  */
879  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
880  if ( ret != 0 ) {
882  }
883  ZYPP_THROW(MediaWriteException("/dev/null"));
884  }
885 
886  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, (*file) );
887  if ( ret != 0 ) {
888  std::string err( _curlError);
889  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
890  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
891  /* yes, this is why we never got to get NOBODY working before,
892  because setting it changes this option too, and we also
893  need to reset it
894  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
895  */
896  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
897  if ( ret != 0 ) {
899  }
901  }
902 
903  CURLcode ok = curl_easy_perform( _curl );
904  MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
905 
906  // reset curl settings
907  if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
908  {
909  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
910  if ( ret != 0 ) {
912  }
913 
914  /* yes, this is why we never got to get NOBODY working before,
915  because setting it changes this option too, and we also
916  need to reset it
917  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
918  */
919  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
920  if ( ret != 0 ) {
922  }
923 
924  }
925  else
926  {
927  // for FTP we set different options
928  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
929  if ( ret != 0 ) {
931  }
932  }
933 
934  // as we are not having user interaction, the user can't cancel
935  // the file existence checking, a callback or timeout return code
936  // will be always a timeout.
937  try {
938  evaluateCurlCode( filename, ok, true /* timeout */);
939  }
940  catch ( const MediaFileNotFoundException &e ) {
941  // if the file did not exist then we can return false
942  return false;
943  }
944  catch ( const MediaException &e ) {
945  // some error, we are not sure about file existence, rethrw
946  ZYPP_RETHROW(e);
947  }
948  // exists
949  return ( ok == CURLE_OK );
950 }
951 
953 
954 
955 #if DETECT_DIR_INDEX
956 bool MediaCurl::detectDirIndex() const
957 {
958  if(_url.getScheme() != "http" && _url.getScheme() != "https")
959  return false;
960  //
961  // try to check the effective url and set the not_a_file flag
962  // if the url path ends with a "/", what usually means, that
963  // we've received a directory index (index.html content).
964  //
965  // Note: This may be dangerous and break file retrieving in
966  // case of some server redirections ... ?
967  //
968  bool not_a_file = false;
969  char *ptr = NULL;
970  CURLcode ret = curl_easy_getinfo( _curl,
971  CURLINFO_EFFECTIVE_URL,
972  &ptr);
973  if ( ret == CURLE_OK && ptr != NULL)
974  {
975  try
976  {
977  Url eurl( ptr);
978  std::string path( eurl.getPathName());
979  if( !path.empty() && path != "/" && *path.rbegin() == '/')
980  {
981  DBG << "Effective url ("
982  << eurl
983  << ") seems to provide the index of a directory"
984  << endl;
985  not_a_file = true;
986  }
987  }
988  catch( ... )
989  {}
990  }
991  return not_a_file;
992 }
993 #endif
994 
996 
997 void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
998 {
999  Pathname dest = target.absolutename();
1000  if( assert_dir( dest.dirname() ) )
1001  {
1002  DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1003  ZYPP_THROW( MediaSystemException(getFileUrl(filename), "System error on " + dest.dirname().asString()) );
1004  }
1005 
1006  ManagedFile destNew { target.extend( ".new.zypp.XXXXXX" ) };
1007  AutoFILE file;
1008  {
1009  AutoFREE<char> buf { ::strdup( (*destNew).c_str() ) };
1010  if( ! buf )
1011  {
1012  ERR << "out of memory for temp file name" << endl;
1013  ZYPP_THROW(MediaSystemException(getFileUrl(filename), "out of memory for temp file name"));
1014  }
1015 
1016  AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1017  if( tmp_fd == -1 )
1018  {
1019  ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1020  ZYPP_THROW(MediaWriteException(destNew));
1021  }
1022  destNew = ManagedFile( (*buf), filesystem::unlink );
1023 
1024  file = ::fdopen( tmp_fd, "we" );
1025  if ( ! file )
1026  {
1027  ERR << "fopen failed for file '" << destNew << "'" << endl;
1028  ZYPP_THROW(MediaWriteException(destNew));
1029  }
1030  tmp_fd.resetDispose(); // don't close it here! ::fdopen moved ownership to file
1031  }
1032 
1033  DBG << "dest: " << dest << endl;
1034  DBG << "temp: " << destNew << endl;
1035 
1036  // set IFMODSINCE time condition (no download if not modified)
1037  if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1038  {
1039  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1040  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1041  }
1042  else
1043  {
1044  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1045  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1046  }
1047  try
1048  {
1049  doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
1050  }
1051  catch (Exception &e)
1052  {
1053  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1054  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1055  ZYPP_RETHROW(e);
1056  }
1057 
1058  long httpReturnCode = 0;
1059  CURLcode infoRet = curl_easy_getinfo(_curl,
1060  CURLINFO_RESPONSE_CODE,
1061  &httpReturnCode);
1062  bool modified = true;
1063  if (infoRet == CURLE_OK)
1064  {
1065  DBG << "HTTP response: " + str::numstring(httpReturnCode);
1066  if ( httpReturnCode == 304
1067  || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1068  {
1069  DBG << " Not modified.";
1070  modified = false;
1071  }
1072  DBG << endl;
1073  }
1074  else
1075  {
1076  WAR << "Could not get the reponse code." << endl;
1077  }
1078 
1079  if (modified || infoRet != CURLE_OK)
1080  {
1081  // apply umask
1082  if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1083  {
1084  ERR << "Failed to chmod file " << destNew << endl;
1085  }
1086 
1087  file.resetDispose(); // we're going to close it manually here
1088  if ( ::fclose( file ) )
1089  {
1090  ERR << "Fclose failed for file '" << destNew << "'" << endl;
1091  ZYPP_THROW(MediaWriteException(destNew));
1092  }
1093 
1094  // move the temp file into dest
1095  if ( rename( destNew, dest ) != 0 ) {
1096  ERR << "Rename failed" << endl;
1098  }
1099  destNew.resetDispose(); // no more need to unlink it
1100  }
1101 
1102  DBG << "done: " << PathInfo(dest) << endl;
1103 }
1104 
1106 
1107 void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1108 {
1109  DBG << filename.asString() << endl;
1110 
1111  if(!_url.isValid())
1113 
1114  if(_url.getHost().empty())
1116 
1117  Url url(getFileUrl(filename));
1118 
1119  DBG << "URL: " << url.asString() << endl;
1120  // Use URL without options and without username and passwd
1121  // (some proxies dislike them in the URL).
1122  // Curl seems to need the just scheme, hostname and a path;
1123  // the rest was already passed as curl options (in attachTo).
1124  Url curlUrl( clearQueryString(url) );
1125 
1126  //
1127  // See also Bug #154197 and ftp url definition in RFC 1738:
1128  // The url "ftp://user@host/foo/bar/file" contains a path,
1129  // that is relative to the user's home.
1130  // The url "ftp://user@host//foo/bar/file" (or also with
1131  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1132  // contains an absolute path.
1133  //
1134  _lastRedirect.clear();
1135  std::string urlBuffer( curlUrl.asString());
1136  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1137  urlBuffer.c_str() );
1138  if ( ret != 0 ) {
1140  }
1141 
1142  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1143  if ( ret != 0 ) {
1145  }
1146 
1147  // Set callback and perform.
1148  ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
1149  if (!(options & OPTION_NO_REPORT_START))
1150  report->start(url, dest);
1151  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1152  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1153  }
1154 
1155  ret = curl_easy_perform( _curl );
1156 #if CURLVERSION_AT_LEAST(7,19,4)
1157  // bnc#692260: If the client sends a request with an If-Modified-Since header
1158  // with a future date for the server, the server may respond 200 sending a
1159  // zero size file.
1160  // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1161  if ( ftell(file) == 0 && ret == 0 )
1162  {
1163  long httpReturnCode = 33;
1164  if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1165  {
1166  long conditionUnmet = 33;
1167  if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1168  {
1169  WAR << "TIMECONDITION unmet - retry without." << endl;
1170  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1171  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1172  ret = curl_easy_perform( _curl );
1173  }
1174  }
1175  }
1176 #endif
1177 
1178  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1179  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1180  }
1181 
1182  if ( ret != 0 )
1183  {
1184  ERR << "curl error: " << ret << ": " << _curlError
1185  << ", temp file size " << ftell(file)
1186  << " bytes." << endl;
1187 
1188  // the timeout is determined by the progress data object
1189  // which holds whether the timeout was reached or not,
1190  // otherwise it would be a user cancel
1191  try {
1192 
1193  if ( progressData.fileSizeExceeded )
1194  ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
1195 
1196  evaluateCurlCode( filename, ret, progressData.reached );
1197  }
1198  catch ( const MediaException &e ) {
1199  // some error, we are not sure about file existence, rethrw
1200  ZYPP_RETHROW(e);
1201  }
1202  }
1203 
1204 #if DETECT_DIR_INDEX
1205  if (!ret && detectDirIndex())
1206  {
1208  }
1209 #endif // DETECT_DIR_INDEX
1210 }
1211 
1213 
1214 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1215 {
1216  filesystem::DirContent content;
1217  getDirInfo( content, dirname, /*dots*/false );
1218 
1219  for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1220  Pathname filename = dirname + it->name;
1221  int res = 0;
1222 
1223  switch ( it->type ) {
1224  case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1225  case filesystem::FT_FILE:
1226  getFile( filename, 0 );
1227  break;
1228  case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1229  if ( recurse_r ) {
1230  getDir( filename, recurse_r );
1231  } else {
1232  res = assert_dir( localPath( filename ) );
1233  if ( res ) {
1234  WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1235  }
1236  }
1237  break;
1238  default:
1239  // don't provide devices, sockets, etc.
1240  break;
1241  }
1242  }
1243 }
1244 
1246 
1247 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1248  const Pathname & dirname, bool dots ) const
1249 {
1250  getDirectoryYast( retlist, dirname, dots );
1251 }
1252 
1254 
1256  const Pathname & dirname, bool dots ) const
1257 {
1258  getDirectoryYast( retlist, dirname, dots );
1259 }
1260 
1262 //
1263 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1264 {
1265  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1266  if( pdata )
1267  {
1268  // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1269  // prevent a percentage raise while downloading a metalink file. Download
1270  // activity however is indicated by propagating the download rate (via dlnow).
1271  pdata->updateStats( 0.0, dlnow );
1272  return pdata->reportProgress();
1273  }
1274  return 0;
1275 }
1276 
1277 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1278 {
1279  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1280  if( pdata )
1281  {
1282  // work around curl bug that gives us old data
1283  long httpReturnCode = 0;
1284  if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1285  return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1286 
1287  pdata->updateStats( dltotal, dlnow );
1288  return pdata->reportProgress();
1289  }
1290  return 0;
1291 }
1292 
1294 {
1295  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1296  return pdata ? pdata->curl : 0;
1297 }
1298 
1300 
1301 std::string MediaCurl::getAuthHint() const
1302 {
1303  long auth_info = CURLAUTH_NONE;
1304 
1305  CURLcode infoRet =
1306  curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1307 
1308  if(infoRet == CURLE_OK)
1309  {
1310  return CurlAuthData::auth_type_long2str(auth_info);
1311  }
1312 
1313  return "";
1314 }
1315 
1320 void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
1321 {
1322  ProgressData *data = reinterpret_cast<ProgressData *>(clientp);
1323  if ( data ) {
1324  data->_expectedFileSize = expectedFileSize;
1325  }
1326 }
1327 
1329 
1330 bool MediaCurl::authenticate(const std::string & availAuthTypes, bool firstTry) const
1331 {
1333  CredentialManager cm(CredManagerOptions(ZConfig::instance().repoManagerRoot()));
1334  CurlAuthData_Ptr credentials;
1335 
1336  // get stored credentials
1337  AuthData_Ptr cmcred = cm.getCred(_url);
1338 
1339  if (cmcred && firstTry)
1340  {
1341  credentials.reset(new CurlAuthData(*cmcred));
1342  DBG << "got stored credentials:" << endl << *credentials << endl;
1343  }
1344  // if not found, ask user
1345  else
1346  {
1347 
1348  CurlAuthData_Ptr curlcred;
1349  curlcred.reset(new CurlAuthData());
1351 
1352  // preset the username if present in current url
1353  if (!_url.getUsername().empty() && firstTry)
1354  curlcred->setUsername(_url.getUsername());
1355  // if CM has found some credentials, preset the username from there
1356  else if (cmcred)
1357  curlcred->setUsername(cmcred->username());
1358 
1359  // indicate we have no good credentials from CM
1360  cmcred.reset();
1361 
1362  std::string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1363 
1364  // set available authentication types from the exception
1365  // might be needed in prompt
1366  curlcred->setAuthType(availAuthTypes);
1367 
1368  // ask user
1369  if (auth_report->prompt(_url, prompt_msg, *curlcred))
1370  {
1371  DBG << "callback answer: retry" << endl
1372  << "CurlAuthData: " << *curlcred << endl;
1373 
1374  if (curlcred->valid())
1375  {
1376  credentials = curlcred;
1377  // if (credentials->username() != _url.getUsername())
1378  // _url.setUsername(credentials->username());
1386  }
1387  }
1388  else
1389  {
1390  DBG << "callback answer: cancel" << endl;
1391  }
1392  }
1393 
1394  // set username and password
1395  if (credentials)
1396  {
1397  // HACK, why is this const?
1398  const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1399  const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1400 
1401  // set username and password
1402  CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1404 
1405  // set available authentication types from the exception
1406  if (credentials->authType() == CURLAUTH_NONE)
1407  credentials->setAuthType(availAuthTypes);
1408 
1409  // set auth type (seems this must be set _after_ setting the userpwd)
1410  if (credentials->authType() != CURLAUTH_NONE)
1411  {
1412  // FIXME: only overwrite if not empty?
1413  const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1414  ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1416  }
1417 
1418  if (!cmcred)
1419  {
1420  credentials->setUrl(_url);
1421  cm.addCred(*credentials);
1422  cm.save();
1423  }
1424 
1425  return true;
1426  }
1427 
1428  return false;
1429 }
1430 
1431 //need a out of line definiton, otherwise vtable is emitted for every translation unit
1433 
1434 
1435  } // namespace media
1436 } // namespace zypp
1437 //
zypp::media::CredManagerOptions
Definition: CredentialManager.h:38
zypp::media::TransferSettings::verifyHostEnabled
bool verifyHostEnabled() const
Whether to verify host for ssl.
Definition: TransferSettings.cc:218
secs
long secs
Definition: MediaCurl.cc:153
ExternalProgram.h
zypp::media::TransferSettings::verifyPeerEnabled
bool verifyPeerEnabled() const
Whether to verify peer for ssl.
Definition: TransferSettings.cc:225
internal::curlUnEscape
std::string curlUnEscape(std::string text_r)
Definition: CurlHelper.cc:343
zypp::media::MediaCurl::getDirInfo
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:1247
zypp::media::MediaCurl::setCookieFile
static void setCookieFile(const Pathname &)
Definition: MediaCurl.cc:228
zypp::filesystem::assert_dir
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
Definition: PathInfo.cc:315
CONNECT_TIMEOUT
#define CONNECT_TIMEOUT
Definition: CurlHelper.h:21
zypp::media::MediaSource
Media source internally used by MediaManager and MediaHandler.
Definition: MediaSource.h:36
zypp::filesystem::PathInfo::path
const Pathname & path() const
Return current Pathname.
Definition: PathInfo.h:246
zypp::Url::getScheme
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:528
zypp::media::MediaUnauthorizedException::hint
const std::string & hint() const
comma separated list of available authentication types
Definition: MediaException.h:452
zypp::media::MediaException
Just inherits Exception to separate media exceptions.
Definition: MediaException.h:35
zypp::media::MediaCurl::getDir
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:1214
fileSizeExceeded
bool fileSizeExceeded
Definition: MediaCurl.cc:69
zypp::media::TransferSettings::setConnectTimeout
void setConnectTimeout(long t)
set the connect timeout
Definition: TransferSettings.cc:180
zypp::media::TransferSettings::userPassword
std::string userPassword() const
returns the user and password as a user:pass string
Definition: TransferSettings.cc:121
reached
bool reached
Definition: MediaCurl.cc:68
internal::agentString
const char * agentString()
initialized only once, this gets the agent string which also includes the curl version
Definition: CurlHelper.cc:314
zypp::media::MediaCurl::OPTION_NO_IFMODSINCE
to not add a IFMODSINCE header if target exists
Definition: MediaCurl.h:44
ZYppFactory.h
zypp::media::CurlConfig::proxyuserpwd
std::string proxyuserpwd
Definition: CurlConfig.h:39
zypp::media::MediaCurl::evaluateCurlCode
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:670
zypp::Exception
Base class for Exception.
Definition: Exception.h:145
zypp::filesystem::assert_file_mode
int assert_file_mode(const Pathname &path, unsigned mode)
Like assert_file but enforce mode even if the file already exists.
Definition: PathInfo.cc:1150
zypp::media::MediaCurl::_lastRedirect
std::string _lastRedirect
to log/report redirections
Definition: MediaCurl.h:173
zypp::callback::SendReport
Definition: Callback.h:236
zypp::media::MediaFileNotFoundException
Definition: MediaException.h:145
dload_period
double dload_period
Definition: MediaCurl.cc:151
zypp::filesystem::FT_NOT_AVAIL
Definition: PathInfo.h:57
zypp::media::TransferSettings::setTimeout
void setTimeout(long t)
set the transfer timeout
Definition: TransferSettings.cc:173
zypp::media::CredentialManager
Definition: CredentialManager.h:62
zypp::media::TransferSettings::headersBegin
Headers::const_iterator headersBegin() const
begin iterators to additional headers
Definition: TransferSettings.cc:95
zypp::media::MediaHandler::getDirectoryYast
void getDirectoryYast(std::list< std::string > &retlist, const Pathname &dirname, bool dots=true) const
Retrieve and if available scan dirname/directory.yast.
Definition: MediaHandler.cc:1151
internal::log_curl
int log_curl(CURL *curl, curl_infotype info, char *ptr, size_t len, void *max_lvl)
Definition: CurlHelper.cc:28
zypp::media::TransferSettings::minDownloadSpeed
long minDownloadSpeed() const
Minimum download speed (bytes per second) until the connection is dropped.
Definition: TransferSettings.cc:197
zypp::media::MediaCurl::checkProtocol
void checkProtocol(const Url &url) const
check the url is supported by the curl library
Definition: MediaCurl.cc:235
zypp::media::MediaCurl::_cookieFile
static Pathname _cookieFile
Definition: MediaCurl.h:171
zypp::media::CredentialManager::getCred
AuthData_Ptr getCred(const Url &url)
Get credentials for the specified url.
Definition: CredentialManager.cc:292
ZConfig.h
zypp::filesystem::rename
int rename(const Pathname &oldpath, const Pathname &newpath)
Like 'rename'.
Definition: PathInfo.cc:690
zypp::media::MediaBadUrlException
Definition: MediaException.h:269
zypp::ManagedFile
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
Definition: ManagedFile.h:27
curl
CURL * curl
Definition: MediaCurl.cc:65
SET_OPTION_OFFT
#define SET_OPTION_OFFT(opt, val)
Definition: MediaCurl.cc:177
zypp::media::TransferSettings::certificateAuthoritiesPath
Pathname certificateAuthoritiesPath() const
SSL certificate authorities path ( default: /etc/ssl/certs )
Definition: TransferSettings.cc:246
zypp::media::TransferSettings::timeout
long timeout() const
transfer timeout
Definition: TransferSettings.cc:176
MIL
#define MIL
Definition: Logger.h:79
zypp::media::MediaTimeoutException
Definition: MediaException.h:476
zypp::media::TransferSettings::authType
std::string authType() const
get the allowed authentication types
Definition: TransferSettings.cc:253
internal::fillSettingsSystemProxy
void fillSettingsSystemProxy(const Url &url, media::TransferSettings &s)
Reads the system proxy configuration and fills the settings structure proxy information.
Definition: CurlHelper.cc:250
zypp::media::MediaCurl::resetExpectedFileSize
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:1320
zypp::media::CredentialManager::save
void save()
Saves any unsaved credentials added via addUserCred() or addGlobalCred() methods.
Definition: CredentialManager.cc:348
zypp::media::MediaHandler
Abstract base class for 'physical' MediaHandler like MediaCD, etc.
Definition: MediaHandler.h:45
zypp::media::MediaCurl::getFileUrl
Url getFileUrl(const Pathname &filename) const
concatenate the attach url and the filename to a complete download url
Definition: MediaCurl.cc:568
ZYPP_THROW
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:392
zypp::str::strToBool
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
Definition: String.h:426
ProxyInfo.h
_drateLast
double _drateLast
Download rate in last period.
Definition: MediaCurl.cc:85
_timeRcv
time_t _timeRcv
Start of no-data timeout.
Definition: MediaCurl.cc:75
zypp::media::MediaCurl::doGetFileCopy
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:997
zypp::filesystem::PathInfo::isDir
bool isDir() const
Definition: PathInfo.h:290
zypp::media::MediaHandler::isUseableAttachPoint
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...
Definition: MediaHandler.cc:446
zypp::media::MediaCurl::doGetFileCopyFile
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:1107
zypp::media::MediaNotSupportedException
Definition: MediaException.h:329
zypp::media::MediaCurl::doGetDoesFileExist
virtual bool doGetDoesFileExist(const Pathname &filename) const
Definition: MediaCurl.cc:811
zypp::media::MediaCurl::_customHeaders
curl_slist * _customHeaders
Definition: MediaCurl.h:178
zypp::media::MediaForbiddenException
Definition: MediaException.h:462
zypp::media::MediaCurl::detectDirIndex
bool detectDirIndex() const
zypp::media::TransferSettings::proxyUserPassword
std::string proxyUserPassword() const
returns the proxy user and password as a user:pass string
Definition: TransferSettings.cc:163
zypp::media::TransferSettings::headRequestsAllowed
bool headRequestsAllowed() const
whether HEAD requests are allowed
Definition: TransferSettings.cc:260
zypp::media::MediaHandler::setMediaSource
void setMediaSource(const MediaSourceRef &ref)
Set new media source reference.
Definition: MediaHandler.cc:462
internal::anonymousIdHeader
const char * anonymousIdHeader()
initialized only once, this gets the anonymous id from the target, which we pass in the http header
Definition: CurlHelper.cc:286
Target.h
report
callback::SendReport< DownloadProgressReport > * report
Definition: MediaCurl.cc:70
zypp::media::MediaCurl::Callbacks::~Callbacks
virtual ~Callbacks()
Definition: MediaCurl.cc:1432
zypp::filesystem::unlink
int unlink(const Pathname &path)
Like 'unlink'.
Definition: PathInfo.cc:648
zypp::media::TransferSettings::proxyEnabled
bool proxyEnabled() const
proxy is enabled
Definition: TransferSettings.cc:140
zypp::media::TransferSettings
Holds transfer setting.
Definition: TransferSettings.h:20
_dnlLast
double _dnlLast
Bytes downloaded at period start.
Definition: MediaCurl.cc:79
internal::fillSettingsFromUrl
void fillSettingsFromUrl(const Url &url, media::TransferSettings &s)
Fills the settings structure using options passed on the url for example ?timeout=x&proxy=foo.
Definition: CurlHelper.cc:102
SET_OPTION
#define SET_OPTION(opt, val)
Definition: MediaCurl.cc:170
zypp::ByteCount
Store and operate with byte count.
Definition: ByteCount.h:30
zypp::media::MediaCurl::_curlError
char _curlError[CURL_ERROR_SIZE]
Definition: MediaCurl.h:177
internal::globalInitCurlOnce
void globalInitCurlOnce()
Definition: CurlHelper.cc:19
zypp::media::DownloadProgressReport::NO_ERROR
Definition: ZYppCallbacks.h:363
zypp::media::MediaCurl::progressCallback
static int progressCallback(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:1277
internal::env::ZYPP_MEDIA_CURL_IPRESOLVE
int ZYPP_MEDIA_CURL_IPRESOLVE()
Definition: CurlHelper.h:36
zypp::Url::getQueryParam
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
_drateTotal
double _drateTotal
Download rate so far.
Definition: MediaCurl.cc:84
zypp::RW_pointer< MediaSource >
drate_avg
double drate_avg
Definition: MediaCurl.cc:155
zypp::media::MediaCurl::settings
TransferSettings & settings()
Definition: MediaCurl.cc:222
zypp::filesystem::rmdir
int rmdir(const Pathname &path)
Like 'rmdir'.
Definition: PathInfo.cc:362
zypp::filesystem::PathInfo
Wrapper class for ::stat/::lstat.
Definition: PathInfo.h:220
zypp::AutoFD
AutoDispose<int> calling ::close
Definition: AutoDispose.h:203
zypp::media::MediaCurl::setupEasy
virtual void setupEasy()
initializes the curl easy handle with the data from the url
Definition: MediaCurl.cc:260
zypp::Exception::asUserHistory
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Definition: Exception.cc:91
zypp::media::MediaCurl::_currentCookieFile
std::string _currentCookieFile
Definition: MediaCurl.h:170
zypp::media::MediaCurl::getAuthHint
std::string getAuthHint() const
Return a comma separated list of available authentication methods supported by server.
Definition: MediaCurl.cc:1301
internal::clearQueryString
Url clearQueryString(const Url &url)
Definition: CurlHelper.cc:350
zypp::Url::asString
std::string asString() const
Returns a default string representation of the Url object.
Definition: Url.cc:492
zypp::media::MediaHandler::setAttachPoint
void setAttachPoint(const Pathname &path, bool temp)
Set a new attach point.
Definition: MediaHandler.cc:230
zypp::filesystem::Pathname::c_str
const char * c_str() const
String representation.
Definition: Pathname.h:110
zypp::media::TransferSettings::proxyUsername
std::string proxyUsername() const
proxy auth username
Definition: TransferSettings.cc:154
zypp::media::MediaNotAFileException
Definition: MediaException.h:235
zypp::Url::setPathName
void setPathName(const std::string &path, EEncoding eflag=zypp::url::E_DECODED)
Set the path name.
Definition: Url.cc:759
_dnlNow
double _dnlNow
Bytes downloaded now.
Definition: MediaCurl.cc:80
Sysconfig.h
zypp::media::MediaCurl::releaseFrom
virtual void releaseFrom(const std::string &ejectDev) override
Call concrete handler to release the media.
Definition: MediaCurl.cc:563
zypp::media::MediaCurlException
Definition: MediaException.h:342
zypp::media::MediaCurl::checkAttachPoint
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:539
Logger.h
zypp::media::CurlConfig
Structure holding values of curlrc options.
Definition: CurlConfig.h:16
WAR
#define WAR
Definition: Logger.h:80
zypp::media::MediaCurl::getFile
virtual void getFile(const Pathname &filename, const ByteCount &expectedFileSize_r) const override
Call concrete handler to provide file below attach point.
Definition: MediaCurl.cc:584
zypp::media::MediaCurl::authenticate
bool authenticate(const std::string &availAuthTypes, bool firstTry) const
Definition: MediaCurl.cc:1330
zypp::filesystem::Pathname::absolutename
Pathname absolutename() const
Return this path, adding a leading '/' if relative.
Definition: Pathname.h:139
zypp::media::MediaHandler::disconnect
void disconnect()
Use concrete handler to isconnect media.
Definition: MediaHandler.cc:723
_expectedFileSize
ByteCount _expectedFileSize
Definition: MediaCurl.cc:71
_
#define _(MSG)
Definition: Gettext.h:37
zypp::media::MediaUnauthorizedException
Definition: MediaException.h:427
zypp::media::CurlAuthData_Ptr
shared_ptr< CurlAuthData > CurlAuthData_Ptr
Definition: MediaUserAuth.h:153
zypp::Url::isValid
bool isValid() const
Verifies the Url.
Definition: Url.cc:484
zypp::ZConfig::instance
static ZConfig & instance()
Singleton ctor.
Definition: Resolver.cc:126
CredentialManager.h
_timeStart
time_t _timeStart
Start total stats.
Definition: MediaCurl.cc:73
uload
double uload
Definition: MediaCurl.cc:161
zypp::media::MediaCurl::_curlDebug
long _curlDebug
Definition: MediaCurl.h:168
zypp
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:1
zypp::filesystem::DirContent
std::list< DirEntry > DirContent
Returned by readdir.
Definition: PathInfo.h:547
zypp::str::numstring
std::string numstring(char n, int w=0)
Definition: String.h:286
zypp::media::DownloadProgressReport::ACCESS_DENIED
Definition: ZYppCallbacks.h:366
zypp::media::TransferSettings::userAgentString
std::string userAgentString() const
user agent string
Definition: TransferSettings.cc:105
zypp::filesystem::FT_FILE
Definition: PathInfo.h:59
zypp::media::DownloadProgressReport::NOT_FOUND
Definition: ZYppCallbacks.h:364
zypp::media::MediaCurl::disconnectFrom
virtual void disconnectFrom() override
Definition: MediaCurl.cc:546
zypp::media::MediaCurl::attachTo
virtual void attachTo(bool next=false) override
Call concrete handler to attach the media.
Definition: MediaCurl.cc:504
zypp::media::MediaHandler::localPath
Pathname localPath(const Pathname &pathname) const
Files provided will be available at 'localPath(filename)'.
Definition: MediaHandler.cc:700
zypp::media::TransferSettings::clientKeyPath
Pathname clientKeyPath() const
SSL client key file.
Definition: TransferSettings.cc:239
zypp::media::MediaHandler::url
Url url() const
Url used.
Definition: MediaHandler.h:507
zypp::media::TransferSettings::clientCertificatePath
Pathname clientCertificatePath() const
SSL client certificate file.
Definition: TransferSettings.cc:232
zypp::media::CurlAuthData::auth_type_long2str
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...
Definition: MediaUserAuth.cc:142
_dnlTotal
double _dnlTotal
Bytes to download or 0 if unknown.
Definition: MediaCurl.cc:78
zypp::media::MediaSystemException
Definition: MediaException.h:218
zypp::AutoFREE
Definition: AutoDispose.h:225
zypp::media::MediaCurl::progressCallback_getcurl
static CURL * progressCallback_getcurl(void *clientp)
Definition: MediaCurl.cc:1293
_timeNow
time_t _timeNow
Now.
Definition: MediaCurl.cc:76
zypp::media::MediaCurlInitException
Definition: MediaException.h:204
zypp::AutoFILE
AutoDispose<FILE*> calling ::fclose
Definition: AutoDispose.h:214
zypp::media::MediaBadUrlEmptyHostException
Definition: MediaException.h:285
zypp::media::CurlAuthData
Curl HTTP authentication data.
Definition: MediaUserAuth.h:74
_dnlPercent
int _dnlPercent
Percent completed or 0 if _dnlTotal is unknown.
Definition: MediaCurl.cc:82
zypp::media::MediaFileSizeExceededException
Definition: MediaException.h:490
dload
double dload
Definition: MediaCurl.cc:159
zypp::media::TransferSettings::addHeader
void addHeader(std::string &&val_r)
add a header, on the form "Foo: Bar"
Definition: TransferSettings.cc:92
_timeLast
time_t _timeLast
Start last period(~1sec)
Definition: MediaCurl.cc:74
Gettext.h
zypp::Url::getPathName
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
Definition: Url.cc:599
ZYPP_RETHROW
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:400
zypp::AutoDispose
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
Definition: AutoDispose.h:92
zypp::media::AuthData_Ptr
shared_ptr< AuthData > AuthData_Ptr
Definition: MediaUserAuth.h:69
drate_period
double drate_period
Definition: MediaCurl.cc:149
zypp::filesystem::Pathname::dirname
Pathname dirname() const
Return all but the last component od this path.
Definition: Pathname.h:124
zypp::media::MediaCurl::clearQueryString
Url clearQueryString(const Url &url) const
Definition: MediaCurl.cc:217
zypp::filesystem::Pathname::extend
Pathname extend(const std::string &r) const
Append string r to the last component of the path.
Definition: Pathname.h:170
zypp::media::MediaCurl::getDoesFileExist
virtual bool getDoesFileExist(const Pathname &filename) const override
Repeatedly calls doGetDoesFileExist() until it successfully returns, fails unexpectedly,...
Definition: MediaCurl.cc:639
zypp::media::MediaHandler::attachPoint
Pathname attachPoint() const
Return the currently used attach point.
Definition: MediaHandler.cc:215
zypp::media::MediaHandler::checkAttachPoint
virtual bool checkAttachPoint(const Pathname &apoint) const
Verify if the specified directory as attach point (root) as requires by the particular media handler ...
Definition: MediaHandler.cc:884
zypp::filesystem::Pathname::empty
bool empty() const
Test for an empty path.
Definition: Pathname.h:114
internal::distributionFlavorHeader
const char * distributionFlavorHeader()
initialized only once, this gets the distribution flavor from the target, which we pass in the http h...
Definition: CurlHelper.cc:300
zypp::media::MediaCurlSetOptException
Definition: MediaException.h:362
String.h
zypp::filesystem::Pathname
Pathname.
Definition: Pathname.h:44
zypp::Url::getHost
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
Definition: Url.cc:583
ERR
#define ERR
Definition: Logger.h:81
zypp::base
Definition: DrunkenBishop.cc:24
timeout
time_t timeout
Definition: MediaCurl.cc:67
zypp::media::MediaHandler::_url
const Url _url
Url to handle.
Definition: MediaHandler.h:110
zypp::media::CredentialManager::addCred
void addCred(const AuthData &cred)
Add new credentials with user callbacks.
Definition: CredentialManager.cc:305
zypp::media::MediaHandler::createAttachPoint
Pathname createAttachPoint() const
Try to create a default / temporary attach point.
Definition: MediaHandler.cc:342
DBG
#define DBG
Definition: Logger.h:78
zypp::media::CurlAuthData::auth_type_str2long
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_* ...
Definition: MediaUserAuth.cc:93
zypp::str::Format
Convenient building of std::string with boost::format. Basically a boost::format autoconvertible to s...
Definition: String.h:249
internal
Definition: CurlHelper.cc:16
zypp::media::TransferSettings::connectTimeout
long connectTimeout() const
connection timeout
Definition: TransferSettings.cc:183
zypp::AutoDispose::resetDispose
void resetDispose()
Set no dispose function.
Definition: AutoDispose.h:162
zypp::filesystem::applyUmaskTo
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
Definition: PathInfo.h:813
zypp::media::MediaCurl::_curl
CURL * _curl
Definition: MediaCurl.h:176
zypp::media::TransferSettings::setUserAgentString
void setUserAgentString(std::string &&val_r)
sets the user agent ie: "Mozilla v3"
Definition: TransferSettings.cc:102
zypp::media::TransferSettings::headersEnd
Headers::const_iterator headersEnd() const
end iterators to additional headers
Definition: TransferSettings.cc:98
MediaCurl.h
CurlHelper.h
MediaUserAuth.h
zypp::filesystem::Pathname::asString
const std::string & asString() const
String representation.
Definition: Pathname.h:91
zypp::filesystem::FT_DIR
Definition: PathInfo.h:60
url
Url url
Definition: MediaCurl.cc:66
zypp::Url
Url manipulation class.
Definition: Url.h:87
zypp::media::DownloadProgressReport::Error
Error
Definition: ZYppCallbacks.h:362
zypp::media::MediaCurl::OPTION_NO_REPORT_START
do not send a start ProgressReport
Definition: MediaCurl.h:46
CurlConfig.h
internal::log_redirects_curl
size_t log_redirects_curl(char *ptr, size_t size, size_t nmemb, void *userdata)
Definition: CurlHelper.cc:54
zypp::media::MediaCurl::getFileCopy
virtual void getFileCopy(const Pathname &srcFilename, const Pathname &targetFilename, const ByteCount &expectedFileSize_r) const override
Definition: MediaCurl.cc:593
zypp::media::DownloadProgressReport::ERROR
Definition: ZYppCallbacks.h:367
zypp::media::TransferSettings::proxy
std::string proxy() const
proxy host
Definition: TransferSettings.cc:147
zypp::media::MediaWriteException
Definition: MediaException.h:162
zypp::Url::getUsername
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.
Definition: Url.cc:567
zypp::media::MediaCurl::_settings
TransferSettings _settings
Definition: MediaCurl.h:179
zypp::media::CurlConfig::parseConfig
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
EXPLICITLY_NO_PROXY
#define EXPLICITLY_NO_PROXY
Definition: CurlHelper.h:25
ltime
time_t ltime
Definition: MediaCurl.cc:157
zypp::filesystem::PathInfo::userMayRWX
bool userMayRWX() const
Definition: PathInfo.h:353
zypp::media::MediaTemporaryProblemException
For HTTP 503 and similar.
Definition: MediaException.h:508
zypp::media::TransferSettings::maxDownloadSpeed
long maxDownloadSpeed() const
Maximum download speed (bytes per second)
Definition: TransferSettings.cc:204