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