libzypp  16.22.9
MediaCurl.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
13 #include <iostream>
14 #include <list>
15 
16 #include "zypp/base/Logger.h"
17 #include "zypp/ExternalProgram.h"
18 #include "zypp/base/String.h"
19 #include "zypp/base/Gettext.h"
20 #include "zypp/base/Sysconfig.h"
21 #include "zypp/base/Gettext.h"
22 
23 #include "zypp/media/MediaCurl.h"
24 #include "zypp/media/ProxyInfo.h"
27 #include "zypp/media/CurlConfig.h"
28 #include "zypp/thread/Once.h"
29 #include "zypp/Target.h"
30 #include "zypp/ZYppFactory.h"
31 #include "zypp/ZConfig.h"
32 
33 #include <cstdlib>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/mount.h>
37 #include <errno.h>
38 #include <dirent.h>
39 #include <unistd.h>
40 
41 #define DETECT_DIR_INDEX 0
42 #define TRANSFER_TIMEOUT_MAX 60 * 60
43 
44 #define EXPLICITLY_NO_PROXY "_none_"
45 
46 #undef CURLVERSION_AT_LEAST
47 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
48 
49 using namespace std;
50 using namespace zypp::base;
51 
52 namespace
53 {
54  zypp::thread::OnceFlag g_InitOnceFlag = PTHREAD_ONCE_INIT;
55  zypp::thread::OnceFlag g_FreeOnceFlag = PTHREAD_ONCE_INIT;
56 
57  extern "C" void _do_free_once()
58  {
59  curl_global_cleanup();
60  }
61 
62  extern "C" void globalFreeOnce()
63  {
64  zypp::thread::callOnce(g_FreeOnceFlag, _do_free_once);
65  }
66 
67  extern "C" void _do_init_once()
68  {
69  CURLcode ret = curl_global_init( CURL_GLOBAL_ALL );
70  if ( ret != 0 )
71  {
72  WAR << "curl global init failed" << endl;
73  }
74 
75  //
76  // register at exit handler ?
77  // this may cause trouble, because we can protect it
78  // against ourself only.
79  // if the app sets an atexit handler as well, it will
80  // cause a double free while the second of them runs.
81  //
82  //std::atexit( globalFreeOnce);
83  }
84 
85  inline void globalInitOnce()
86  {
87  zypp::thread::callOnce(g_InitOnceFlag, _do_init_once);
88  }
89 
90  int log_curl(CURL *curl, curl_infotype info,
91  char *ptr, size_t len, void *max_lvl)
92  {
93  if ( max_lvl == nullptr )
94  return 0;
95 
96  long maxlvl = *((long *)max_lvl);
97 
98  char pfx = ' ';
99  switch( info )
100  {
101  case CURLINFO_TEXT: if ( maxlvl < 1 ) return 0; pfx = '*'; break;
102  case CURLINFO_HEADER_IN: if ( maxlvl < 2 ) return 0; pfx = '<'; break;
103  case CURLINFO_HEADER_OUT: if ( maxlvl < 2 ) return 0; pfx = '>'; break;
104  default:
105  return 0;
106  }
107 
108  std::vector<std::string> lines;
109  zypp::str::split( std::string(ptr,len), std::back_inserter(lines), "\r\n" );
110  for( const auto & line : lines )
111  {
112  if ( zypp::str::startsWith( line, "Authorization:" ) ) {
113  std::string::size_type pos { line.find( " ", 15 ) }; // Authorization: <type> <credentials>
114  if ( pos == std::string::npos )
115  pos = 15;
116  DBG << pfx << " " << line.substr( 0, pos ) << " <credentials removed>" << std::endl;
117  }
118  else
119  DBG << pfx << " " << line << std::endl;
120  }
121  return 0;
122  }
123 
124  static size_t
125  log_redirects_curl(
126  void *ptr, size_t size, size_t nmemb, void *stream)
127  {
128  // INT << "got header: " << string((char *)ptr, ((char*)ptr) + size*nmemb) << endl;
129 
130  char * lstart = (char *)ptr, * lend = (char *)ptr;
131  size_t pos = 0;
132  size_t max = size * nmemb;
133  while (pos + 1 < max)
134  {
135  // get line
136  for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
137 
138  // look for "Location"
139  string line(lstart, lend);
140  if (line.find("Location") != string::npos)
141  {
142  DBG << "redirecting to " << line << endl;
143  return max;
144  }
145 
146  // continue with the next line
147  if (pos + 1 < max)
148  {
149  ++lend;
150  ++pos;
151  }
152  else
153  break;
154  }
155 
156  return max;
157  }
158 }
159 
160 namespace zypp {
161 
163  namespace env
164  {
165  namespace
166  {
167  inline int getZYPP_MEDIA_CURL_IPRESOLVE()
168  {
169  int ret = 0;
170  if ( const char * envp = getenv( "ZYPP_MEDIA_CURL_IPRESOLVE" ) )
171  {
172  WAR << "env set: $ZYPP_MEDIA_CURL_IPRESOLVE='" << envp << "'" << endl;
173  if ( strcmp( envp, "4" ) == 0 ) ret = 4;
174  else if ( strcmp( envp, "6" ) == 0 ) ret = 6;
175  }
176  return ret;
177  }
178  }
179 
181  {
182  static int _v = getZYPP_MEDIA_CURL_IPRESOLVE();
183  return _v;
184  }
185  } // namespace env
187 
188  namespace media {
189 
190  namespace {
191  struct ProgressData
192  {
193  ProgressData( CURL *_curl, time_t _timeout = 0, const Url & _url = Url(),
194  ByteCount expectedFileSize_r = 0,
196  : curl( _curl )
197  , url( _url )
198  , timeout( _timeout )
199  , reached( false )
200  , fileSizeExceeded ( false )
201  , report( _report )
202  , _expectedFileSize( expectedFileSize_r )
203  {}
204 
205  CURL *curl;
206  Url url;
207  time_t timeout;
208  bool reached;
210  callback::SendReport<DownloadProgressReport> *report;
211  ByteCount _expectedFileSize;
212 
213  time_t _timeStart = 0;
214  time_t _timeLast = 0;
215  time_t _timeRcv = 0;
216  time_t _timeNow = 0;
217 
218  double _dnlTotal = 0.0;
219  double _dnlLast = 0.0;
220  double _dnlNow = 0.0;
221 
222  int _dnlPercent= 0;
223 
224  double _drateTotal= 0.0;
225  double _drateLast = 0.0;
226 
227  void updateStats( double dltotal = 0.0, double dlnow = 0.0 )
228  {
229  time_t now = _timeNow = time(0);
230 
231  // If called without args (0.0), recompute based on the last values seen
232  if ( dltotal && dltotal != _dnlTotal )
233  _dnlTotal = dltotal;
234 
235  if ( dlnow && dlnow != _dnlNow )
236  {
237  _timeRcv = now;
238  _dnlNow = dlnow;
239  }
240  else if ( !_dnlNow && !_dnlTotal )
241  {
242  // Start time counting as soon as first data arrives.
243  // Skip the connection / redirection time at begin.
244  return;
245  }
246 
247  // init or reset if time jumps back
248  if ( !_timeStart || _timeStart > now )
249  _timeStart = _timeLast = _timeRcv = now;
250 
251  // timeout condition
252  if ( timeout )
253  reached = ( (now - _timeRcv) > timeout );
254 
255  // check if the downloaded data is already bigger than what we expected
256  fileSizeExceeded = _expectedFileSize > 0 && _expectedFileSize < static_cast<ByteCount::SizeType>(_dnlNow);
257 
258  // percentage:
259  if ( _dnlTotal )
260  _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
261 
262  // download rates:
263  _drateTotal = _dnlNow / std::max( int(now - _timeStart), 1 );
264 
265  if ( _timeLast < now )
266  {
267  _drateLast = (_dnlNow - _dnlLast) / int(now - _timeLast);
268  // start new period
269  _timeLast = now;
270  _dnlLast = _dnlNow;
271  }
272  else if ( _timeStart == _timeLast )
273  _drateLast = _drateTotal;
274  }
275 
276  int reportProgress() const
277  {
278  if ( fileSizeExceeded )
279  return 1;
280  if ( reached )
281  return 1; // no-data timeout
282  if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
283  return 1; // user requested abort
284  return 0;
285  }
286 
287 
288  // download rate of the last period (cca 1 sec)
289  double drate_period;
290  // bytes downloaded at the start of the last period
291  double dload_period;
292  // seconds from the start of the download
293  long secs;
294  // average download rate
295  double drate_avg;
296  // last time the progress was reported
297  time_t ltime;
298  // bytes downloaded at the moment the progress was last reported
299  double dload;
300  // bytes uploaded at the moment the progress was last reported
301  double uload;
302  };
303 
305 
306  inline void escape( string & str_r,
307  const char char_r, const string & escaped_r ) {
308  for ( string::size_type pos = str_r.find( char_r );
309  pos != string::npos; pos = str_r.find( char_r, pos ) ) {
310  str_r.replace( pos, 1, escaped_r );
311  }
312  }
313 
314  inline string escapedPath( string path_r ) {
315  escape( path_r, ' ', "%20" );
316  return path_r;
317  }
318 
319  inline string unEscape( string text_r ) {
320  char * tmp = curl_unescape( text_r.c_str(), 0 );
321  string ret( tmp );
322  curl_free( tmp );
323  return ret;
324  }
325 
326  }
327 
333 {
334  std::string param(url.getQueryParam("timeout"));
335  if( !param.empty())
336  {
337  long num = str::strtonum<long>(param);
338  if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
339  s.setTimeout(num);
340  }
341 
342  if ( ! url.getUsername().empty() )
343  {
344  s.setUsername(url.getUsername());
345  if ( url.getPassword().size() )
346  s.setPassword(url.getPassword());
347  }
348  else
349  {
350  // if there is no username, set anonymous auth
351  if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
352  s.setAnonymousAuth();
353  }
354 
355  if ( url.getScheme() == "https" )
356  {
357  s.setVerifyPeerEnabled(false);
358  s.setVerifyHostEnabled(false);
359 
360  std::string verify( url.getQueryParam("ssl_verify"));
361  if( verify.empty() ||
362  verify == "yes")
363  {
364  s.setVerifyPeerEnabled(true);
365  s.setVerifyHostEnabled(true);
366  }
367  else if( verify == "no")
368  {
369  s.setVerifyPeerEnabled(false);
370  s.setVerifyHostEnabled(false);
371  }
372  else
373  {
374  std::vector<std::string> flags;
375  std::vector<std::string>::const_iterator flag;
376  str::split( verify, std::back_inserter(flags), ",");
377  for(flag = flags.begin(); flag != flags.end(); ++flag)
378  {
379  if( *flag == "host")
380  s.setVerifyHostEnabled(true);
381  else if( *flag == "peer")
382  s.setVerifyPeerEnabled(true);
383  else
384  ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
385  }
386  }
387  }
388 
389  Pathname ca_path( url.getQueryParam("ssl_capath") );
390  if( ! ca_path.empty())
391  {
392  if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
393  ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
394  else
396  }
397 
398  Pathname client_cert( url.getQueryParam("ssl_clientcert") );
399  if( ! client_cert.empty())
400  {
401  if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
402  ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientcert file"));
403  else
404  s.setClientCertificatePath(client_cert);
405  }
406  Pathname client_key( url.getQueryParam("ssl_clientkey") );
407  if( ! client_key.empty())
408  {
409  if( !PathInfo(client_key).isFile() || !client_key.absolute())
410  ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
411  else
412  s.setClientKeyPath(client_key);
413  }
414 
415  param = url.getQueryParam( "proxy" );
416  if ( ! param.empty() )
417  {
418  if ( param == EXPLICITLY_NO_PROXY ) {
419  // Workaround TransferSettings shortcoming: With an
420  // empty proxy string, code will continue to look for
421  // valid proxy settings. So set proxy to some non-empty
422  // string, to indicate it has been explicitly disabled.
424  s.setProxyEnabled(false);
425  }
426  else {
427  string proxyport( url.getQueryParam( "proxyport" ) );
428  if ( ! proxyport.empty() ) {
429  param += ":" + proxyport;
430  }
431  s.setProxy(param);
432  s.setProxyEnabled(true);
433  }
434  }
435 
436  param = url.getQueryParam( "proxyuser" );
437  if ( ! param.empty() )
438  {
439  s.setProxyUsername(param);
440  s.setProxyPassword(url.getQueryParam( "proxypass" ));
441  }
442 
443  // HTTP authentication type
444  param = url.getQueryParam("auth");
445  if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
446  {
447  try
448  {
449  CurlAuthData::auth_type_str2long(param); // check if we know it
450  }
451  catch (MediaException & ex_r)
452  {
453  DBG << "Rethrowing as MediaUnauthorizedException.";
454  ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
455  }
456  s.setAuthType(param);
457  }
458 
459  // workarounds
460  param = url.getQueryParam("head_requests");
461  if( !param.empty() && param == "no" )
462  s.setHeadRequestsAllowed(false);
463 }
464 
470 {
471  ProxyInfo proxy_info;
472  if ( proxy_info.useProxyFor( url ) )
473  {
474  // We must extract any 'user:pass' from the proxy url
475  // otherwise they won't make it into curl (.curlrc wins).
476  try {
477  Url u( proxy_info.proxy( url ) );
478  s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
479  // don't overwrite explicit auth settings
480  if ( s.proxyUsername().empty() )
481  {
482  s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
483  s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
484  }
485  s.setProxyEnabled( true );
486  }
487  catch (...) {} // no proxy if URL is malformed
488  }
489 }
490 
491 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
492 
497 static const char *const anonymousIdHeader()
498 {
499  // we need to add the release and identifier to the
500  // agent string.
501  // The target could be not initialized, and then this information
502  // is guessed.
503  static const std::string _value(
505  "X-ZYpp-AnonymousId: %s",
506  Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
507  );
508  return _value.c_str();
509 }
510 
515 static const char *const distributionFlavorHeader()
516 {
517  // we need to add the release and identifier to the
518  // agent string.
519  // The target could be not initialized, and then this information
520  // is guessed.
521  static const std::string _value(
523  "X-ZYpp-DistributionFlavor: %s",
524  Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
525  );
526  return _value.c_str();
527 }
528 
533 static const char *const agentString()
534 {
535  // we need to add the release and identifier to the
536  // agent string.
537  // The target could be not initialized, and then this information
538  // is guessed.
539  static const std::string _value(
541  "ZYpp %s (curl %s) %s"
542  , VERSION
543  , curl_version_info(CURLVERSION_NOW)->version
544  , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
545  ) )
546  );
547  return _value.c_str();
548 }
549 
550 // we use this define to unbloat code as this C setting option
551 // and catching exception is done frequently.
553 #define SET_OPTION(opt,val) do { \
554  ret = curl_easy_setopt ( _curl, opt, val ); \
555  if ( ret != 0) { \
556  ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
557  } \
558  } while ( false )
559 
560 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
561 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
562 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
563 
564 MediaCurl::MediaCurl( const Url & url_r,
565  const Pathname & attach_point_hint_r )
566  : MediaHandler( url_r, attach_point_hint_r,
567  "/", // urlpath at attachpoint
568  true ), // does_download
569  _curl( NULL ),
570  _customHeaders(0L)
571 {
572  _curlError[0] = '\0';
573  _curlDebug = 0L;
574 
575  MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
576 
577  globalInitOnce();
578 
579  if( !attachPoint().empty())
580  {
581  PathInfo ainfo(attachPoint());
582  Pathname apath(attachPoint() + "XXXXXX");
583  char *atemp = ::strdup( apath.asString().c_str());
584  char *atest = NULL;
585  if( !ainfo.isDir() || !ainfo.userMayRWX() ||
586  atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
587  {
588  WAR << "attach point " << ainfo.path()
589  << " is not useable for " << url_r.getScheme() << endl;
590  setAttachPoint("", true);
591  }
592  else if( atest != NULL)
593  ::rmdir(atest);
594 
595  if( atemp != NULL)
596  ::free(atemp);
597  }
598 }
599 
601 {
602  Url curlUrl (url);
603  curlUrl.setUsername( "" );
604  curlUrl.setPassword( "" );
605  curlUrl.setPathParams( "" );
606  curlUrl.setFragment( "" );
607  curlUrl.delQueryParam("cookies");
608  curlUrl.delQueryParam("proxy");
609  curlUrl.delQueryParam("proxyport");
610  curlUrl.delQueryParam("proxyuser");
611  curlUrl.delQueryParam("proxypass");
612  curlUrl.delQueryParam("ssl_capath");
613  curlUrl.delQueryParam("ssl_verify");
614  curlUrl.delQueryParam("ssl_clientcert");
615  curlUrl.delQueryParam("timeout");
616  curlUrl.delQueryParam("auth");
617  curlUrl.delQueryParam("username");
618  curlUrl.delQueryParam("password");
619  curlUrl.delQueryParam("mediahandler");
620  curlUrl.delQueryParam("credentials");
621  curlUrl.delQueryParam("head_requests");
622  return curlUrl;
623 }
624 
626 {
627  return _settings;
628 }
629 
630 
631 void MediaCurl::setCookieFile( const Pathname &fileName )
632 {
633  _cookieFile = fileName;
634 }
635 
637 
638 void MediaCurl::checkProtocol(const Url &url) const
639 {
640  curl_version_info_data *curl_info = NULL;
641  curl_info = curl_version_info(CURLVERSION_NOW);
642  // curl_info does not need any free (is static)
643  if (curl_info->protocols)
644  {
645  const char * const *proto;
646  std::string scheme( url.getScheme());
647  bool found = false;
648  for(proto=curl_info->protocols; !found && *proto; ++proto)
649  {
650  if( scheme == std::string((const char *)*proto))
651  found = true;
652  }
653  if( !found)
654  {
655  std::string msg("Unsupported protocol '");
656  msg += scheme;
657  msg += "'";
659  }
660  }
661 }
662 
664 {
665  {
666  char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
667  _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
668  if( _curlDebug > 0)
669  {
670  curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
671  curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
672  curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
673  }
674  }
675 
676  curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
677  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
678  if ( ret != 0 ) {
679  ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
680  }
681 
682  SET_OPTION(CURLOPT_FAILONERROR, 1L);
683  SET_OPTION(CURLOPT_NOSIGNAL, 1L);
684 
685  // create non persistant settings
686  // so that we don't add headers twice
687  TransferSettings vol_settings(_settings);
688 
689  // add custom headers for download.opensuse.org (bsc#955801)
690  if ( _url.getHost() == "download.opensuse.org" )
691  {
692  vol_settings.addHeader(anonymousIdHeader());
693  vol_settings.addHeader(distributionFlavorHeader());
694  }
695  vol_settings.addHeader("Pragma:");
696 
697  _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
698  _settings.setConnectTimeout(ZConfig::instance().download_connect_timeout());
699 
701 
702  // fill some settings from url query parameters
703  try
704  {
706  }
707  catch ( const MediaException &e )
708  {
709  disconnectFrom();
710  ZYPP_RETHROW(e);
711  }
712  // if the proxy was not set (or explicitly unset) by url, then look...
713  if ( _settings.proxy().empty() )
714  {
715  // ...at the system proxy settings
717  }
718 
721  {
722  switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
723  {
724  case 4: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); break;
725  case 6: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); break;
726  }
727  }
728 
732  SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
733  // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
734  // just in case curl does not trigger its progress callback frequently
735  // enough.
736  if ( _settings.timeout() )
737  {
738  SET_OPTION(CURLOPT_TIMEOUT, 3600L);
739  }
740 
741  // follow any Location: header that the server sends as part of
742  // an HTTP header (#113275)
743  SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
744  // 3 redirects seem to be too few in some cases (bnc #465532)
745  SET_OPTION(CURLOPT_MAXREDIRS, 6L);
746 
747  if ( _url.getScheme() == "https" )
748  {
749 #if CURLVERSION_AT_LEAST(7,19,4)
750  // restrict following of redirections from https to https only
751  SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
752 #endif
753 
756  {
757  SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
758  }
759 
760  if( ! _settings.clientCertificatePath().empty() )
761  {
762  SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
763  }
764  if( ! _settings.clientKeyPath().empty() )
765  {
766  SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
767  }
768 
769 #ifdef CURLSSLOPT_ALLOW_BEAST
770  // see bnc#779177
771  ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
772  if ( ret != 0 ) {
773  disconnectFrom();
775  }
776 #endif
777  SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
778  SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
779  // bnc#903405 - POODLE: libzypp should only talk TLS
780  SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
781  }
782 
783  SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
784 
785  /*---------------------------------------------------------------*
786  CURLOPT_USERPWD: [user name]:[password]
787 
788  Url::username/password -> CURLOPT_USERPWD
789  If not provided, anonymous FTP identification
790  *---------------------------------------------------------------*/
791 
792  if ( _settings.userPassword().size() )
793  {
794  SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
795  string use_auth = _settings.authType();
796  if (use_auth.empty())
797  use_auth = "digest,basic"; // our default
798  long auth = CurlAuthData::auth_type_str2long(use_auth);
799  if( auth != CURLAUTH_NONE)
800  {
801  DBG << "Enabling HTTP authentication methods: " << use_auth
802  << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
803  SET_OPTION(CURLOPT_HTTPAUTH, auth);
804  }
805  }
806 
807  if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
808  {
809  DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
810  SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
811  SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
812  /*---------------------------------------------------------------*
813  * CURLOPT_PROXYUSERPWD: [user name]:[password]
814  *
815  * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
816  * If not provided, $HOME/.curlrc is evaluated
817  *---------------------------------------------------------------*/
818 
819  string proxyuserpwd = _settings.proxyUserPassword();
820 
821  if ( proxyuserpwd.empty() )
822  {
823  CurlConfig curlconf;
824  CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
825  if ( curlconf.proxyuserpwd.empty() )
826  DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
827  else
828  {
829  proxyuserpwd = curlconf.proxyuserpwd;
830  DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
831  }
832  }
833  else
834  {
835  DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
836  }
837 
838  if ( ! proxyuserpwd.empty() )
839  {
840  SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
841  }
842  }
843 #if CURLVERSION_AT_LEAST(7,19,4)
844  else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
845  {
846  // Explicitly disabled in URL (see fillSettingsFromUrl()).
847  // This should also prevent libcurl from looking into the environment.
848  DBG << "Proxy: explicitly NOPROXY" << endl;
849  SET_OPTION(CURLOPT_NOPROXY, "*");
850  }
851 #endif
852  else
853  {
854  DBG << "Proxy: not explicitly set" << endl;
855  DBG << "Proxy: libcurl may look into the environment" << endl;
856  }
857 
859  if ( _settings.minDownloadSpeed() != 0 )
860  {
861  SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
862  // default to 10 seconds at low speed
863  SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
864  }
865 
866 #if CURLVERSION_AT_LEAST(7,15,5)
867  if ( _settings.maxDownloadSpeed() != 0 )
868  SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
869 #endif
870 
871  /*---------------------------------------------------------------*
872  *---------------------------------------------------------------*/
873 
874  _currentCookieFile = _cookieFile.asString();
876  if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
877  SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
878  else
879  MIL << "No cookies requested" << endl;
880  SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
881  SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
882  SET_OPTION(CURLOPT_NOPROGRESS, 0L);
883 
884 #if CURLVERSION_AT_LEAST(7,18,0)
885  // bnc #306272
886  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
887 #endif
888  // append settings custom headers to curl
889  for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
890  it != vol_settings.headersEnd();
891  ++it )
892  {
893  // MIL << "HEADER " << *it << std::endl;
894 
895  _customHeaders = curl_slist_append(_customHeaders, it->c_str());
896  if ( !_customHeaders )
898  }
899 
900  SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
901 }
902 
904 
905 
906 void MediaCurl::attachTo (bool next)
907 {
908  if ( next )
910 
911  if ( !_url.isValid() )
913 
916  {
918  }
919 
920  disconnectFrom(); // clean _curl if needed
921  _curl = curl_easy_init();
922  if ( !_curl ) {
924  }
925  try
926  {
927  setupEasy();
928  }
929  catch (Exception & ex)
930  {
931  disconnectFrom();
932  ZYPP_RETHROW(ex);
933  }
934 
935  // FIXME: need a derived class to propelly compare url's
937  setMediaSource(media);
938 }
939 
940 bool
941 MediaCurl::checkAttachPoint(const Pathname &apoint) const
942 {
943  return MediaHandler::checkAttachPoint( apoint, true, true);
944 }
945 
947 
949 {
950  if ( _customHeaders )
951  {
952  curl_slist_free_all(_customHeaders);
953  _customHeaders = 0L;
954  }
955 
956  if ( _curl )
957  {
958  curl_easy_cleanup( _curl );
959  _curl = NULL;
960  }
961 }
962 
964 
965 void MediaCurl::releaseFrom( const std::string & ejectDev )
966 {
967  disconnect();
968 }
969 
970 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
971 {
972  // Simply extend the URLs pathname. An 'absolute' URL path
973  // is achieved by encoding the leading '/' in an URL path:
974  // URL: ftp://user@server -> ~user
975  // URL: ftp://user@server/ -> ~user
976  // URL: ftp://user@server// -> ~user
977  // URL: ftp://user@server/%2F -> /
978  // ^- this '/' is just a separator
979  Url newurl( _url );
980  newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
981  return newurl;
982 }
983 
985 
986 void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
987 {
988  // Use absolute file name to prevent access of files outside of the
989  // hierarchy below the attach point.
990  getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
991 }
992 
994 
995 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
996 {
998 
999  Url fileurl(getFileUrl(filename));
1000 
1001  bool retry = false;
1002 
1003  do
1004  {
1005  try
1006  {
1007  doGetFileCopy(filename, target, report, expectedFileSize_r);
1008  retry = false;
1009  }
1010  // retry with proper authentication data
1011  catch (MediaUnauthorizedException & ex_r)
1012  {
1013  if(authenticate(ex_r.hint(), !retry))
1014  retry = true;
1015  else
1016  {
1017  report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
1018  ZYPP_RETHROW(ex_r);
1019  }
1020  }
1021  // unexpected exception
1022  catch (MediaException & excpt_r)
1023  {
1025  if( typeid(excpt_r) == typeid( media::MediaFileNotFoundException ) ||
1026  typeid(excpt_r) == typeid( media::MediaNotAFileException ) )
1027  {
1029  }
1030  report->finish(fileurl, reason, excpt_r.asUserHistory());
1031  ZYPP_RETHROW(excpt_r);
1032  }
1033  }
1034  while (retry);
1035 
1036  report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
1037 }
1038 
1040 
1041 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
1042 {
1043  bool retry = false;
1044 
1045  do
1046  {
1047  try
1048  {
1049  return doGetDoesFileExist( filename );
1050  }
1051  // authentication problem, retry with proper authentication data
1052  catch (MediaUnauthorizedException & ex_r)
1053  {
1054  if(authenticate(ex_r.hint(), !retry))
1055  retry = true;
1056  else
1057  ZYPP_RETHROW(ex_r);
1058  }
1059  // unexpected exception
1060  catch (MediaException & excpt_r)
1061  {
1062  ZYPP_RETHROW(excpt_r);
1063  }
1064  }
1065  while (retry);
1066 
1067  return false;
1068 }
1069 
1071 
1072 void MediaCurl::evaluateCurlCode(const Pathname &filename,
1073  CURLcode code,
1074  bool timeout_reached) const
1075 {
1076  if ( code != 0 )
1077  {
1078  Url url;
1079  if (filename.empty())
1080  url = _url;
1081  else
1082  url = getFileUrl(filename);
1083 
1084  std::string err;
1085  {
1086  switch ( code )
1087  {
1088  case CURLE_UNSUPPORTED_PROTOCOL:
1089  case CURLE_URL_MALFORMAT:
1090  case CURLE_URL_MALFORMAT_USER:
1091  err = " Bad URL";
1092  break;
1093  case CURLE_LOGIN_DENIED:
1094  ZYPP_THROW(
1095  MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
1096  break;
1097  case CURLE_HTTP_RETURNED_ERROR:
1098  {
1099  long httpReturnCode = 0;
1100  CURLcode infoRet = curl_easy_getinfo( _curl,
1101  CURLINFO_RESPONSE_CODE,
1102  &httpReturnCode );
1103  if ( infoRet == CURLE_OK )
1104  {
1105  string msg = "HTTP response: " + str::numstring( httpReturnCode );
1106  switch ( httpReturnCode )
1107  {
1108  case 401:
1109  {
1110  string auth_hint = getAuthHint();
1111 
1112  DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1113  DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1114 
1116  url, "Login failed.", _curlError, auth_hint
1117  ));
1118  }
1119 
1120  case 502: // bad gateway (bnc #1070851)
1121  case 503: // service temporarily unavailable (bnc #462545)
1123  case 504: // gateway timeout
1125  case 403:
1126  {
1127  string msg403;
1128  if (url.asString().find("novell.com") != string::npos)
1129  msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1130  ZYPP_THROW(MediaForbiddenException(url, msg403));
1131  }
1132  case 404:
1133  case 410:
1135  }
1136 
1137  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1139  }
1140  else
1141  {
1142  string msg = "Unable to retrieve HTTP response:";
1143  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1145  }
1146  }
1147  break;
1148  case CURLE_FTP_COULDNT_RETR_FILE:
1149 #if CURLVERSION_AT_LEAST(7,16,0)
1150  case CURLE_REMOTE_FILE_NOT_FOUND:
1151 #endif
1152  case CURLE_FTP_ACCESS_DENIED:
1153  case CURLE_TFTP_NOTFOUND:
1154  err = "File not found";
1156  break;
1157  case CURLE_BAD_PASSWORD_ENTERED:
1158  case CURLE_FTP_USER_PASSWORD_INCORRECT:
1159  err = "Login failed";
1160  break;
1161  case CURLE_COULDNT_RESOLVE_PROXY:
1162  case CURLE_COULDNT_RESOLVE_HOST:
1163  case CURLE_COULDNT_CONNECT:
1164  case CURLE_FTP_CANT_GET_HOST:
1165  err = "Connection failed";
1166  break;
1167  case CURLE_WRITE_ERROR:
1168  err = "Write error";
1169  break;
1170  case CURLE_PARTIAL_FILE:
1171  case CURLE_OPERATION_TIMEDOUT:
1172  timeout_reached = true; // fall though to TimeoutException
1173  // fall though...
1174  case CURLE_ABORTED_BY_CALLBACK:
1175  if( timeout_reached )
1176  {
1177  err = "Timeout reached";
1179  }
1180  else
1181  {
1182  err = "User abort";
1183  }
1184  break;
1185  case CURLE_SSL_PEER_CERTIFICATE:
1186  default:
1187  err = "Curl error " + str::numstring( code );
1188  break;
1189  }
1190 
1191  // uhm, no 0 code but unknown curl exception
1193  }
1194  }
1195  else
1196  {
1197  // actually the code is 0, nothing happened
1198  }
1199 }
1200 
1202 
1203 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1204 {
1205  DBG << filename.asString() << endl;
1206 
1207  if(!_url.isValid())
1209 
1210  if(_url.getHost().empty())
1212 
1213  Url url(getFileUrl(filename));
1214 
1215  DBG << "URL: " << url.asString() << endl;
1216  // Use URL without options and without username and passwd
1217  // (some proxies dislike them in the URL).
1218  // Curl seems to need the just scheme, hostname and a path;
1219  // the rest was already passed as curl options (in attachTo).
1220  Url curlUrl( clearQueryString(url) );
1221 
1222  //
1223  // See also Bug #154197 and ftp url definition in RFC 1738:
1224  // The url "ftp://user@host/foo/bar/file" contains a path,
1225  // that is relative to the user's home.
1226  // The url "ftp://user@host//foo/bar/file" (or also with
1227  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1228  // contains an absolute path.
1229  //
1230  string urlBuffer( curlUrl.asString());
1231  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1232  urlBuffer.c_str() );
1233  if ( ret != 0 ) {
1235  }
1236 
1237  // instead of returning no data with NOBODY, we return
1238  // little data, that works with broken servers, and
1239  // works for ftp as well, because retrieving only headers
1240  // ftp will return always OK code ?
1241  // See http://curl.haxx.se/docs/knownbugs.html #58
1242  if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1244  ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1245  else
1246  ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1247 
1248  if ( ret != 0 ) {
1249  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1250  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1251  /* yes, this is why we never got to get NOBODY working before,
1252  because setting it changes this option too, and we also
1253  need to reset it
1254  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1255  */
1256  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1258  }
1259 
1260  AutoFILE file { ::fopen( "/dev/null", "w" ) };
1261  if ( !file ) {
1262  ERR << "fopen failed for /dev/null" << endl;
1263  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1264  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1265  /* yes, this is why we never got to get NOBODY working before,
1266  because setting it changes this option too, and we also
1267  need to reset it
1268  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1269  */
1270  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1271  if ( ret != 0 ) {
1273  }
1274  ZYPP_THROW(MediaWriteException("/dev/null"));
1275  }
1276 
1277  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, (*file) );
1278  if ( ret != 0 ) {
1279  std::string err( _curlError);
1280  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1281  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1282  /* yes, this is why we never got to get NOBODY working before,
1283  because setting it changes this option too, and we also
1284  need to reset it
1285  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1286  */
1287  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1288  if ( ret != 0 ) {
1290  }
1292  }
1293 
1294  CURLcode ok = curl_easy_perform( _curl );
1295  MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1296 
1297  // reset curl settings
1298  if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1299  {
1300  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1301  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1302  if ( ret != 0 ) {
1304  }
1305 
1306  /* yes, this is why we never got to get NOBODY working before,
1307  because setting it changes this option too, and we also
1308  need to reset it
1309  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1310  */
1311  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1312  if ( ret != 0 ) {
1314  }
1315 
1316  }
1317  else
1318  {
1319  // for FTP we set different options
1320  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1321  if ( ret != 0 ) {
1323  }
1324  }
1325 
1326  // as we are not having user interaction, the user can't cancel
1327  // the file existence checking, a callback or timeout return code
1328  // will be always a timeout.
1329  try {
1330  evaluateCurlCode( filename, ok, true /* timeout */);
1331  }
1332  catch ( const MediaFileNotFoundException &e ) {
1333  // if the file did not exist then we can return false
1334  return false;
1335  }
1336  catch ( const MediaException &e ) {
1337  // some error, we are not sure about file existence, rethrw
1338  ZYPP_RETHROW(e);
1339  }
1340  // exists
1341  return ( ok == CURLE_OK );
1342 }
1343 
1345 
1346 
1347 #if DETECT_DIR_INDEX
1348 bool MediaCurl::detectDirIndex() const
1349 {
1350  if(_url.getScheme() != "http" && _url.getScheme() != "https")
1351  return false;
1352  //
1353  // try to check the effective url and set the not_a_file flag
1354  // if the url path ends with a "/", what usually means, that
1355  // we've received a directory index (index.html content).
1356  //
1357  // Note: This may be dangerous and break file retrieving in
1358  // case of some server redirections ... ?
1359  //
1360  bool not_a_file = false;
1361  char *ptr = NULL;
1362  CURLcode ret = curl_easy_getinfo( _curl,
1363  CURLINFO_EFFECTIVE_URL,
1364  &ptr);
1365  if ( ret == CURLE_OK && ptr != NULL)
1366  {
1367  try
1368  {
1369  Url eurl( ptr);
1370  std::string path( eurl.getPathName());
1371  if( !path.empty() && path != "/" && *path.rbegin() == '/')
1372  {
1373  DBG << "Effective url ("
1374  << eurl
1375  << ") seems to provide the index of a directory"
1376  << endl;
1377  not_a_file = true;
1378  }
1379  }
1380  catch( ... )
1381  {}
1382  }
1383  return not_a_file;
1384 }
1385 #endif
1386 
1388 
1389 void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1390 {
1391  Pathname dest = target.absolutename();
1392  if( assert_dir( dest.dirname() ) )
1393  {
1394  DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1395  ZYPP_THROW( MediaSystemException(getFileUrl(filename), "System error on " + dest.dirname().asString()) );
1396  }
1397 
1398  ManagedFile destNew { target.extend( ".new.zypp.XXXXXX" ) };
1399  AutoFILE file;
1400  {
1401  AutoFREE<char> buf { ::strdup( (*destNew).c_str() ) };
1402  if( ! buf )
1403  {
1404  ERR << "out of memory for temp file name" << endl;
1405  ZYPP_THROW(MediaSystemException(getFileUrl(filename), "out of memory for temp file name"));
1406  }
1407 
1408  AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1409  if( tmp_fd == -1 )
1410  {
1411  ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1412  ZYPP_THROW(MediaWriteException(destNew));
1413  }
1414  destNew = ManagedFile( (*buf), filesystem::unlink );
1415 
1416  file = ::fdopen( tmp_fd, "we" );
1417  if ( ! file )
1418  {
1419  ERR << "fopen failed for file '" << destNew << "'" << endl;
1420  ZYPP_THROW(MediaWriteException(destNew));
1421  }
1422  tmp_fd.resetDispose(); // don't close it here! ::fdopen moved ownership to file
1423  }
1424 
1425  DBG << "dest: " << dest << endl;
1426  DBG << "temp: " << destNew << endl;
1427 
1428  // set IFMODSINCE time condition (no download if not modified)
1429  if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1430  {
1431  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1432  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1433  }
1434  else
1435  {
1436  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1437  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1438  }
1439  try
1440  {
1441  doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
1442  }
1443  catch (Exception &e)
1444  {
1445  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1446  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1447  ZYPP_RETHROW(e);
1448  }
1449 
1450  long httpReturnCode = 0;
1451  CURLcode infoRet = curl_easy_getinfo(_curl,
1452  CURLINFO_RESPONSE_CODE,
1453  &httpReturnCode);
1454  bool modified = true;
1455  if (infoRet == CURLE_OK)
1456  {
1457  DBG << "HTTP response: " + str::numstring(httpReturnCode);
1458  if ( httpReturnCode == 304
1459  || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1460  {
1461  DBG << " Not modified.";
1462  modified = false;
1463  }
1464  DBG << endl;
1465  }
1466  else
1467  {
1468  WAR << "Could not get the reponse code." << endl;
1469  }
1470 
1471  if (modified || infoRet != CURLE_OK)
1472  {
1473  // apply umask
1474  if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1475  {
1476  ERR << "Failed to chmod file " << destNew << endl;
1477  }
1478 
1479  file.resetDispose(); // we're going to close it manually here
1480  if ( ::fclose( file ) )
1481  {
1482  ERR << "Fclose failed for file '" << destNew << "'" << endl;
1483  ZYPP_THROW(MediaWriteException(destNew));
1484  }
1485 
1486  // move the temp file into dest
1487  if ( rename( destNew, dest ) != 0 ) {
1488  ERR << "Rename failed" << endl;
1490  }
1491  destNew.resetDispose(); // no more need to unlink it
1492  }
1493 
1494  DBG << "done: " << PathInfo(dest) << endl;
1495 }
1496 
1498 
1499 void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1500 {
1501  DBG << filename.asString() << endl;
1502 
1503  if(!_url.isValid())
1505 
1506  if(_url.getHost().empty())
1508 
1509  Url url(getFileUrl(filename));
1510 
1511  DBG << "URL: " << url.asString() << endl;
1512  // Use URL without options and without username and passwd
1513  // (some proxies dislike them in the URL).
1514  // Curl seems to need the just scheme, hostname and a path;
1515  // the rest was already passed as curl options (in attachTo).
1516  Url curlUrl( clearQueryString(url) );
1517 
1518  //
1519  // See also Bug #154197 and ftp url definition in RFC 1738:
1520  // The url "ftp://user@host/foo/bar/file" contains a path,
1521  // that is relative to the user's home.
1522  // The url "ftp://user@host//foo/bar/file" (or also with
1523  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1524  // contains an absolute path.
1525  //
1526  string urlBuffer( curlUrl.asString());
1527  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1528  urlBuffer.c_str() );
1529  if ( ret != 0 ) {
1531  }
1532 
1533  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1534  if ( ret != 0 ) {
1536  }
1537 
1538  // Set callback and perform.
1539  ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
1540  if (!(options & OPTION_NO_REPORT_START))
1541  report->start(url, dest);
1542  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1543  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1544  }
1545 
1546  ret = curl_easy_perform( _curl );
1547 #if CURLVERSION_AT_LEAST(7,19,4)
1548  // bnc#692260: If the client sends a request with an If-Modified-Since header
1549  // with a future date for the server, the server may respond 200 sending a
1550  // zero size file.
1551  // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1552  if ( ftell(file) == 0 && ret == 0 )
1553  {
1554  long httpReturnCode = 33;
1555  if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1556  {
1557  long conditionUnmet = 33;
1558  if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1559  {
1560  WAR << "TIMECONDITION unmet - retry without." << endl;
1561  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1562  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1563  ret = curl_easy_perform( _curl );
1564  }
1565  }
1566  }
1567 #endif
1568 
1569  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1570  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1571  }
1572 
1573  if ( ret != 0 )
1574  {
1575  ERR << "curl error: " << ret << ": " << _curlError
1576  << ", temp file size " << ftell(file)
1577  << " bytes." << endl;
1578 
1579  // the timeout is determined by the progress data object
1580  // which holds whether the timeout was reached or not,
1581  // otherwise it would be a user cancel
1582  try {
1583 
1584  if ( progressData.fileSizeExceeded )
1585  ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
1586 
1587  evaluateCurlCode( filename, ret, progressData.reached );
1588  }
1589  catch ( const MediaException &e ) {
1590  // some error, we are not sure about file existence, rethrw
1591  ZYPP_RETHROW(e);
1592  }
1593  }
1594 
1595 #if DETECT_DIR_INDEX
1596  if (!ret && detectDirIndex())
1597  {
1599  }
1600 #endif // DETECT_DIR_INDEX
1601 }
1602 
1604 
1605 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1606 {
1607  filesystem::DirContent content;
1608  getDirInfo( content, dirname, /*dots*/false );
1609 
1610  for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1611  Pathname filename = dirname + it->name;
1612  int res = 0;
1613 
1614  switch ( it->type ) {
1615  case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1616  case filesystem::FT_FILE:
1617  getFile( filename, 0 );
1618  break;
1619  case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1620  if ( recurse_r ) {
1621  getDir( filename, recurse_r );
1622  } else {
1623  res = assert_dir( localPath( filename ) );
1624  if ( res ) {
1625  WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1626  }
1627  }
1628  break;
1629  default:
1630  // don't provide devices, sockets, etc.
1631  break;
1632  }
1633  }
1634 }
1635 
1637 
1638 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1639  const Pathname & dirname, bool dots ) const
1640 {
1641  getDirectoryYast( retlist, dirname, dots );
1642 }
1643 
1645 
1647  const Pathname & dirname, bool dots ) const
1648 {
1649  getDirectoryYast( retlist, dirname, dots );
1650 }
1651 
1653 //
1654 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1655 {
1656  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1657  if( pdata )
1658  {
1659  // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1660  // prevent a percentage raise while downloading a metalink file. Download
1661  // activity however is indicated by propagating the download rate (via dlnow).
1662  pdata->updateStats( 0.0, dlnow );
1663  return pdata->reportProgress();
1664  }
1665  return 0;
1666 }
1667 
1668 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1669 {
1670  ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1671  if( pdata )
1672  {
1673  // work around curl bug that gives us old data
1674  long httpReturnCode = 0;
1675  if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1676  return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1677 
1678  pdata->updateStats( dltotal, dlnow );
1679  return pdata->reportProgress();
1680  }
1681  return 0;
1682 }
1683 
1685 {
1686  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1687  return pdata ? pdata->curl : 0;
1688 }
1689 
1691 
1693 {
1694  long auth_info = CURLAUTH_NONE;
1695 
1696  CURLcode infoRet =
1697  curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1698 
1699  if(infoRet == CURLE_OK)
1700  {
1701  return CurlAuthData::auth_type_long2str(auth_info);
1702  }
1703 
1704  return "";
1705 }
1706 
1711 void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
1712 {
1713  ProgressData *data = reinterpret_cast<ProgressData *>(clientp);
1714  if ( data ) {
1715  data->_expectedFileSize = expectedFileSize;
1716  }
1717 }
1718 
1720 
1721 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1722 {
1724  Target_Ptr target = zypp::getZYpp()->getTarget();
1725  CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1726  CurlAuthData_Ptr credentials;
1727 
1728  // get stored credentials
1729  AuthData_Ptr cmcred = cm.getCred(_url);
1730 
1731  if (cmcred && firstTry)
1732  {
1733  credentials.reset(new CurlAuthData(*cmcred));
1734  DBG << "got stored credentials:" << endl << *credentials << endl;
1735  }
1736  // if not found, ask user
1737  else
1738  {
1739 
1740  CurlAuthData_Ptr curlcred;
1741  curlcred.reset(new CurlAuthData());
1743 
1744  // preset the username if present in current url
1745  if (!_url.getUsername().empty() && firstTry)
1746  curlcred->setUsername(_url.getUsername());
1747  // if CM has found some credentials, preset the username from there
1748  else if (cmcred)
1749  curlcred->setUsername(cmcred->username());
1750 
1751  // indicate we have no good credentials from CM
1752  cmcred.reset();
1753 
1754  string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1755 
1756  // set available authentication types from the exception
1757  // might be needed in prompt
1758  curlcred->setAuthType(availAuthTypes);
1759 
1760  // ask user
1761  if (auth_report->prompt(_url, prompt_msg, *curlcred))
1762  {
1763  DBG << "callback answer: retry" << endl
1764  << "CurlAuthData: " << *curlcred << endl;
1765 
1766  if (curlcred->valid())
1767  {
1768  credentials = curlcred;
1769  // if (credentials->username() != _url.getUsername())
1770  // _url.setUsername(credentials->username());
1778  }
1779  }
1780  else
1781  {
1782  DBG << "callback answer: cancel" << endl;
1783  }
1784  }
1785 
1786  // set username and password
1787  if (credentials)
1788  {
1789  // HACK, why is this const?
1790  const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1791  const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1792 
1793  // set username and password
1794  CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1796 
1797  // set available authentication types from the exception
1798  if (credentials->authType() == CURLAUTH_NONE)
1799  credentials->setAuthType(availAuthTypes);
1800 
1801  // set auth type (seems this must be set _after_ setting the userpwd)
1802  if (credentials->authType() != CURLAUTH_NONE)
1803  {
1804  // FIXME: only overwrite if not empty?
1805  const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1806  ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1808  }
1809 
1810  if (!cmcred)
1811  {
1812  credentials->setUrl(_url);
1813  cm.addCred(*credentials);
1814  cm.save();
1815  }
1816 
1817  return true;
1818  }
1819 
1820  return false;
1821 }
1822 
1823 
1824  } // namespace media
1825 } // namespace zypp
1826 //
void setPassword(const std::string &pass, EEncoding eflag=zypp::url::E_DECODED)
Set the password in the URL authority.
Definition: Url.cc:733
std::string userPassword() const
returns the user and password as a user:pass string
int assert_dir(const Pathname &path, unsigned mode)
Like &#39;mkdir -p&#39;.
Definition: PathInfo.cc:320
Interface to gettext.
void checkProtocol(const Url &url) const
check the url is supported by the curl library
Definition: MediaCurl.cc:638
#define SET_OPTION_OFFT(opt, val)
Definition: MediaCurl.cc:560
double _dnlLast
Bytes downloaded at period start.
Definition: MediaCurl.cc:219
#define MIL
Definition: Logger.h:64
bool verifyHostEnabled() const
Whether to verify host for ssl.
Pathname clientKeyPath() const
SSL client key file.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:350
bool authenticate(const std::string &availAuthTypes, bool firstTry) const
Definition: MediaCurl.cc:1721
static ZConfig & instance()
Singleton ctor.
Definition: Resolver.cc:122
virtual void releaseFrom(const std::string &ejectDev)
Call concrete handler to release the media.
Definition: MediaCurl.cc:965
const std::string & msg() const
Return the message string provided to the ctor.
Definition: Exception.h:193
Implementation class for FTP, HTTP and HTTPS MediaHandler.
Definition: MediaCurl.h:32
Flag to request encoded string(s).
Definition: UrlUtils.h:53
long connectTimeout() const
connection timeout
Headers::const_iterator headersEnd() const
end iterators to additional headers
Store and operate with byte count.
Definition: ByteCount.h:30
time_t _timeStart
Start total stats.
Definition: MediaCurl.cc:213
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
Definition: Url.cc:598
void setClientKeyPath(const zypp::Pathname &path)
Sets the SSL client key file.
to not add a IFMODSINCE header if target exists
Definition: MediaCurl.h:44
TransferSettings & settings()
Definition: MediaCurl.cc:625
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
Definition: Url.cc:582
Holds transfer setting.
Url clearQueryString(const Url &url) const
Definition: MediaCurl.cc:600
void save()
Saves any unsaved credentials added via addUserCred() or addGlobalCred() methods. ...
std::string escape(const C_Str &str_r, const char sep_r)
Escape desired character c using a backslash.
Definition: String.cc:369
static int progressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
Callback reporting download progress.
Definition: MediaCurl.cc:1668
void setProxyUsername(const std::string &proxyuser)
sets the proxy user
void setAttachPoint(const Pathname &path, bool temp)
Set a new attach point.
Pathname createAttachPoint() const
Try to create a default / temporary attach point.
Pathname certificateAuthoritiesPath() const
SSL certificate authorities path ( default: /etc/ssl/certs )
void setPathParams(const std::string &params)
Set the path parameters.
Definition: Url.cc:785
void setHeadRequestsAllowed(bool allowed)
set whether HEAD requests are allowed
static int aliveCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
Callback sending just an alive trigger to the UI, without stats (e.g.
Definition: MediaCurl.cc:1654
Definition: Arch.h:344
virtual void getFileCopy(const Pathname &srcFilename, const Pathname &targetFilename, const ByteCount &expectedFileSize_r) const override
Definition: MediaCurl.cc:995
pthread_once_t OnceFlag
The OnceFlag variable type.
Definition: Once.h:32
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.
Definition: Url.cc:566
long minDownloadSpeed() const
Minimum download speed (bytes per second) until the connection is dropped.
AuthData_Ptr getCred(const Url &url)
Get credentials for the specified url.
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
Definition: ManagedFile.h:27
time_t _timeNow
Now.
Definition: MediaCurl.cc:216
Url url
Definition: MediaCurl.cc:206
void setConnectTimeout(long t)
set the connect timeout
void setUsername(const std::string &user, EEncoding eflag=zypp::url::E_DECODED)
Set the username in the URL authority.
Definition: Url.cc:724
double dload
Definition: MediaCurl.cc:299
virtual void setupEasy()
initializes the curl easy handle with the data from the url
Definition: MediaCurl.cc:663
#define EXPLICITLY_NO_PROXY
Definition: MediaCurl.cc:44
Convenient building of std::string with boost::format.
Definition: String.h:248
Structure holding values of curlrc options.
Definition: CurlConfig.h:16
bool isValid() const
Verifies the Url.
Definition: Url.cc:483
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
Definition: String.cc:36
Edition * _value
Definition: SysContent.cc:311
AutoDispose<int> calling ::close
Definition: AutoDispose.h:203
virtual bool checkAttachPoint(const Pathname &apoint) const
Verify if the specified directory as attach point (root) as requires by the particular media handler ...
std::string _currentCookieFile
Definition: MediaCurl.h:170
void setProxy(const std::string &proxyhost)
proxy to use if it is enabled
void setFragment(const std::string &fragment, EEncoding eflag=zypp::url::E_DECODED)
Set the fragment string in the URL.
Definition: Url.cc:716
#define ERR
Definition: Logger.h:66
void setPassword(const std::string &password)
sets the auth password
std::string asString() const
Returns a default string representation of the Url object.
Definition: Url.cc:491
void setUsername(const std::string &username)
sets the auth username
bool headRequestsAllowed() const
whether HEAD requests are allowed
void setAnonymousAuth()
sets anonymous authentication (ie: for ftp)
int ZYPP_MEDIA_CURL_IPRESOLVE()
Definition: MediaCurl.cc:180
std::string proxy(const Url &url) const
Definition: ProxyInfo.cc:44
static void setCookieFile(const Pathname &)
Definition: MediaCurl.cc:631
std::string getAuthHint() const
Return a comma separated list of available authentication methods supported by server.
Definition: MediaCurl.cc:1692
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:1711
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:358
void setPathName(const std::string &path, EEncoding eflag=zypp::url::E_DECODED)
Set the path name.
Definition: Url.cc:758
static int parseConfig(CurlConfig &config, const std::string &filename="")
Parse a curlrc file and store the result in the config structure.
Definition: CurlConfig.cc:24
int assert_file_mode(const Pathname &path, unsigned mode)
Like assert_file but enforce mode even if the file already exists.
Definition: PathInfo.cc:1161
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:1389
std::string userAgentString() const
user agent string
unsigned split(const C_Str &line_r, TOutputIterator result_r, const C_Str &sepchars_r=" \t")
Split line_r into words.
Definition: String.h:519
time_t timeout
Definition: MediaCurl.cc:207
void setProxyPassword(const std::string &proxypass)
sets the proxy password
Abstract base class for &#39;physical&#39; MediaHandler like MediaCD, etc.
Definition: MediaHandler.h:45
int _dnlPercent
Percent completed or 0 if _dnlTotal is unknown.
Definition: MediaCurl.cc:222
void callOnce(OnceFlag &flag, void(*func)())
Call once function.
Definition: Once.h:50
void setAuthType(const std::string &authtype)
set the allowed authentication types
std::string trim(const std::string &s, const Trim trim_r)
Definition: String.cc:221
int unlink(const Pathname &path)
Like &#39;unlink&#39;.
Definition: PathInfo.cc:662
const Url _url
Url to handle.
Definition: MediaHandler.h:110
virtual bool getDoesFileExist(const Pathname &filename) const
Repeatedly calls doGetDoesFileExist() until it successfully returns, fails unexpectedly, or user cancels the operation.
Definition: MediaCurl.cc:1041
void setMediaSource(const MediaSourceRef &ref)
Set new media source reference.
int rename(const Pathname &oldpath, const Pathname &newpath)
Like &#39;rename&#39;.
Definition: PathInfo.cc:704
Just inherits Exception to separate media exceptions.
bool fileSizeExceeded
Definition: MediaCurl.cc:209
void disconnect()
Use concrete handler to isconnect media.
do not send a start ProgressReport
Definition: MediaCurl.h:46
#define WAR
Definition: Logger.h:65
TransferSettings _settings
Definition: MediaCurl.h:177
bool startsWith(const C_Str &str_r, const C_Str &prefix_r)
alias for hasPrefix
Definition: String.h:1095
time_t ltime
Definition: MediaCurl.cc:297
Maintain [min,max] and counter (value) for progress counting.
Definition: ProgressData.h:130
bool reached
Definition: MediaCurl.cc:208
std::list< DirEntry > DirContent
Returned by readdir.
Definition: PathInfo.h:547
bool verifyPeerEnabled() const
Whether to verify peer for ssl.
void setTimeout(long t)
set the transfer timeout
bool useProxyFor(const Url &url_r) const
Return true if enabled and url_r does not match noProxy.
Definition: ProxyInfo.cc:56
#define _(MSG)
Definition: Gettext.h:29
std::string proxyUserPassword() const
returns the proxy user and password as a user:pass string
static const char *const agentString()
initialized only once, this gets the agent string which also includes the curl version ...
Definition: MediaCurl.cc:533
Pathname localPath(const Pathname &pathname) const
Files provided will be available at &#39;localPath(filename)&#39;.
std::string proxyuserpwd
Definition: CurlConfig.h:39
std::string getQueryParam(const std::string &param, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
Definition: Url.cc:654
bool isUseableAttachPoint(const Pathname &path, bool mtab=true) const
Ask media manager, if the specified path is already used as attach point or if there are another atta...
virtual bool checkAttachPoint(const Pathname &apoint) const
Verify if the specified directory as attach point (root) as requires by the particular media handler ...
Definition: MediaCurl.cc:941
shared_ptr< CurlAuthData > CurlAuthData_Ptr
virtual void getDir(const Pathname &dirname, bool recurse_r) const
Call concrete handler to provide directory content (not recursive!) below attach point.
Definition: MediaCurl.cc:1605
std::string numstring(char n, int w=0)
Definition: String.h:305
virtual void disconnectFrom()
Definition: MediaCurl.cc:948
void getDirectoryYast(std::list< std::string > &retlist, const Pathname &dirname, bool dots=true) const
Retrieve and if available scan dirname/directory.yast.
void resetDispose()
Set no dispose function.
Definition: AutoDispose.h:162
SolvableIdType size_type
Definition: PoolMember.h:152
bool detectDirIndex() const
Media source internally used by MediaManager and MediaHandler.
Definition: MediaSource.h:36
static std::string auth_type_long2str(long auth_type)
Converts a long of ORed CURLAUTH_* identifiers into a string of comma separated list of authenticatio...
void fillSettingsFromUrl(const Url &url, TransferSettings &s)
Fills the settings structure using options passed on the url for example ?timeout=x&proxy=foo.
Definition: MediaCurl.cc:332
curl_slist * _customHeaders
Definition: MediaCurl.h:176
Headers::const_iterator headersBegin() const
begin iterators to additional headers
void setClientCertificatePath(const zypp::Pathname &path)
Sets the SSL client certificate file.
shared_ptr< AuthData > AuthData_Ptr
Definition: MediaUserAuth.h:69
int rmdir(const Pathname &path)
Like &#39;rmdir&#39;.
Definition: PathInfo.cc:367
#define SET_OPTION(opt, val)
Definition: MediaCurl.cc:553
Pathname attachPoint() const
Return the currently used attach point.
Url getFileUrl(const Pathname &filename) const
concatenate the attach url and the filename to a complete download url
Definition: MediaCurl.cc:970
Base class for Exception.
Definition: Exception.h:143
virtual void getDirInfo(std::list< std::string > &retlist, const Pathname &dirname, bool dots=true) const
Call concrete handler to provide a content list of directory on media via retlist.
Definition: MediaCurl.cc:1638
time_t _timeRcv
Start of no-data timeout.
Definition: MediaCurl.cc:215
const std::string & hint() const
comma separated list of available authentication types
static const char *const distributionFlavorHeader()
initialized only once, this gets the distribution flavor from the target, which we pass in the http h...
Definition: MediaCurl.cc:515
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:1499
void fillSettingsSystemProxy(const Url &url, TransferSettings &s)
Reads the system proxy configuration and fills the settings structure proxy information.
Definition: MediaCurl.cc:469
callback::SendReport< DownloadProgressReport > * report
Definition: MediaCurl.cc:210
void addHeader(const std::string &header)
add a header, on the form "Foo: Bar"
CURL * curl
Definition: MediaCurl.cc:205
static CURL * progressCallback_getcurl(void *clientp)
Definition: MediaCurl.cc:1684
void setCertificateAuthoritiesPath(const zypp::Pathname &path)
Sets the SSL certificate authorities path.
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
Definition: String.h:445
static long auth_type_str2long(std::string &auth_type_str)
Converts a string of comma separated list of authetication type names into a long of ORed CURLAUTH_* ...
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
Definition: AutoDispose.h:92
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Definition: Exception.cc:91
virtual void attachTo(bool next=false)
Call concrete handler to attach the media.
Definition: MediaCurl.cc:906
double dload_period
Definition: MediaCurl.cc:291
Definition: Fd.cc:28
AutoDispose<FILE*> calling ::fclose
Definition: AutoDispose.h:214
static Pathname _cookieFile
Definition: MediaCurl.h:171
double _drateLast
Download rate in last period.
Definition: MediaCurl.cc:225
double drate_avg
Definition: MediaCurl.cc:295
virtual void getFile(const Pathname &filename, const ByteCount &expectedFileSize_r) const override
Call concrete handler to provide file below attach point.
Definition: MediaCurl.cc:986
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
Definition: PathInfo.h:813
virtual bool doGetDoesFileExist(const Pathname &filename) const
Definition: MediaCurl.cc:1203
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:527
time_t _timeLast
Start last period(~1sec)
Definition: MediaCurl.cc:214
std::string authType() const
get the allowed authentication types
double uload
Definition: MediaCurl.cc:301
void addCred(const AuthData &cred)
Add new credentials with user callbacks.
#define TRANSFER_TIMEOUT_MAX
Definition: MediaCurl.cc:42
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:1
Curl HTTP authentication data.
Definition: MediaUserAuth.h:74
double drate_period
Definition: MediaCurl.cc:289
char _curlError[CURL_ERROR_SIZE]
Definition: MediaCurl.h:175
void setVerifyPeerEnabled(bool enabled)
Sets whether to verify host for ssl.
Pathname clientCertificatePath() const
SSL client certificate file.
void evaluateCurlCode(const zypp::Pathname &filename, CURLcode code, bool timeout) const
Evaluates a curl return code and throws the right MediaException filename Filename being downloaded c...
Definition: MediaCurl.cc:1072
double _dnlNow
Bytes downloaded now.
Definition: MediaCurl.cc:220
Url url() const
Url used.
Definition: MediaHandler.h:507
std::string proxy() const
proxy host
bool proxyEnabled() const
proxy is enabled
long secs
Definition: MediaCurl.cc:293
Convenience interface for handling authentication data of media user.
void setVerifyHostEnabled(bool enabled)
Sets whether to verify host for ssl.
Url manipulation class.
Definition: Url.h:87
void setUserAgentString(const std::string &agent)
sets the user agent ie: "Mozilla v3"
long maxDownloadSpeed() const
Maximum download speed (bytes per second)
static const char *const anonymousIdHeader()
initialized only once, this gets the anonymous id from the target, which we pass in the http header ...
Definition: MediaCurl.cc:497
double _drateTotal
Download rate so far.
Definition: MediaCurl.cc:224
void setProxyEnabled(bool enabled)
whether the proxy is used or not
std::string username() const
auth username
#define DBG
Definition: Logger.h:63
std::string getPassword(EEncoding eflag=zypp::url::E_DECODED) const
Returns the password from the URL authority.
Definition: Url.cc:574
void delQueryParam(const std::string &param)
remove the specified query parameter.
Definition: Url.cc:839
std::string proxyUsername() const
proxy auth username
ByteCount _expectedFileSize
Definition: MediaCurl.cc:211
long timeout() const
transfer timeout
double _dnlTotal
Bytes to download or 0 if unknown.
Definition: MediaCurl.cc:218