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