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