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