libzypp  13.10.6
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  Pathname client_key( url.getQueryParam("ssl_clientkey") );
299  if( ! client_key.empty())
300  {
301  if( !PathInfo(client_key).isFile() || !client_key.absolute())
302  ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
303  else
304  s.setClientKeyPath(client_key);
305  }
306 
307  param = url.getQueryParam( "proxy" );
308  if ( ! param.empty() )
309  {
310  if ( param == EXPLICITLY_NO_PROXY ) {
311  // Workaround TransferSettings shortcoming: With an
312  // empty proxy string, code will continue to look for
313  // valid proxy settings. So set proxy to some non-empty
314  // string, to indicate it has been explicitly disabled.
316  s.setProxyEnabled(false);
317  }
318  else {
319  string proxyport( url.getQueryParam( "proxyport" ) );
320  if ( ! proxyport.empty() ) {
321  param += ":" + proxyport;
322  }
323  s.setProxy(param);
324  s.setProxyEnabled(true);
325  }
326  }
327 
328  param = url.getQueryParam( "proxyuser" );
329  if ( ! param.empty() )
330  {
331  s.setProxyUsername(param);
332  s.setProxyPassword(url.getQueryParam( "proxypass" ));
333  }
334 
335  // HTTP authentication type
336  param = url.getQueryParam("auth");
337  if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
338  {
339  try
340  {
341  CurlAuthData::auth_type_str2long(param); // check if we know it
342  }
343  catch (MediaException & ex_r)
344  {
345  DBG << "Rethrowing as MediaUnauthorizedException.";
346  ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
347  }
348  s.setAuthType(param);
349  }
350 
351  // workarounds
352  param = url.getQueryParam("head_requests");
353  if( !param.empty() && param == "no" )
354  s.setHeadRequestsAllowed(false);
355 }
356 
362 {
363  ProxyInfo proxy_info;
364  if ( proxy_info.useProxyFor( url ) )
365  {
366  // We must extract any 'user:pass' from the proxy url
367  // otherwise they won't make it into curl (.curlrc wins).
368  try {
369  Url u( proxy_info.proxy( url ) );
370  s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
371  // don't overwrite explicit auth settings
372  if ( s.proxyUsername().empty() )
373  {
374  s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
375  s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
376  }
377  s.setProxyEnabled( true );
378  }
379  catch (...) {} // no proxy if URL is malformed
380  }
381 }
382 
383 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
384 
389 static const char *const anonymousIdHeader()
390 {
391  // we need to add the release and identifier to the
392  // agent string.
393  // The target could be not initialized, and then this information
394  // is guessed.
395  static const std::string _value(
397  "X-ZYpp-AnonymousId: %s",
398  Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
399  );
400  return _value.c_str();
401 }
402 
407 static const char *const distributionFlavorHeader()
408 {
409  // we need to add the release and identifier to the
410  // agent string.
411  // The target could be not initialized, and then this information
412  // is guessed.
413  static const std::string _value(
415  "X-ZYpp-DistributionFlavor: %s",
416  Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
417  );
418  return _value.c_str();
419 }
420 
425 static const char *const agentString()
426 {
427  // we need to add the release and identifier to the
428  // agent string.
429  // The target could be not initialized, and then this information
430  // is guessed.
431  static const std::string _value(
432  str::form(
433  "ZYpp %s (curl %s) %s"
434  , VERSION
435  , curl_version_info(CURLVERSION_NOW)->version
436  , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
437  )
438  );
439  return _value.c_str();
440 }
441 
442 // we use this define to unbloat code as this C setting option
443 // and catching exception is done frequently.
445 #define SET_OPTION(opt,val) do { \
446  ret = curl_easy_setopt ( _curl, opt, val ); \
447  if ( ret != 0) { \
448  ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
449  } \
450  } while ( false )
451 
452 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
453 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
454 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
455 
456 MediaCurl::MediaCurl( const Url & url_r,
457  const Pathname & attach_point_hint_r )
458  : MediaHandler( url_r, attach_point_hint_r,
459  "/", // urlpath at attachpoint
460  true ), // does_download
461  _curl( NULL ),
462  _customHeaders(0L)
463 {
464  _curlError[0] = '\0';
465  _curlDebug = 0L;
466 
467  MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
468 
469  globalInitOnce();
470 
471  if( !attachPoint().empty())
472  {
473  PathInfo ainfo(attachPoint());
474  Pathname apath(attachPoint() + "XXXXXX");
475  char *atemp = ::strdup( apath.asString().c_str());
476  char *atest = NULL;
477  if( !ainfo.isDir() || !ainfo.userMayRWX() ||
478  atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
479  {
480  WAR << "attach point " << ainfo.path()
481  << " is not useable for " << url_r.getScheme() << endl;
482  setAttachPoint("", true);
483  }
484  else if( atest != NULL)
485  ::rmdir(atest);
486 
487  if( atemp != NULL)
488  ::free(atemp);
489  }
490 }
491 
493 {
494  Url curlUrl (url);
495  curlUrl.setUsername( "" );
496  curlUrl.setPassword( "" );
497  curlUrl.setPathParams( "" );
498  curlUrl.setFragment( "" );
499  curlUrl.delQueryParam("cookies");
500  curlUrl.delQueryParam("proxy");
501  curlUrl.delQueryParam("proxyport");
502  curlUrl.delQueryParam("proxyuser");
503  curlUrl.delQueryParam("proxypass");
504  curlUrl.delQueryParam("ssl_capath");
505  curlUrl.delQueryParam("ssl_verify");
506  curlUrl.delQueryParam("timeout");
507  curlUrl.delQueryParam("auth");
508  curlUrl.delQueryParam("username");
509  curlUrl.delQueryParam("password");
510  curlUrl.delQueryParam("mediahandler");
511  return curlUrl;
512 }
513 
515 {
516  return _settings;
517 }
518 
519 
520 void MediaCurl::setCookieFile( const Pathname &fileName )
521 {
522  _cookieFile = fileName;
523 }
524 
526 
527 void MediaCurl::checkProtocol(const Url &url) const
528 {
529  curl_version_info_data *curl_info = NULL;
530  curl_info = curl_version_info(CURLVERSION_NOW);
531  // curl_info does not need any free (is static)
532  if (curl_info->protocols)
533  {
534  const char * const *proto;
535  std::string scheme( url.getScheme());
536  bool found = false;
537  for(proto=curl_info->protocols; !found && *proto; ++proto)
538  {
539  if( scheme == std::string((const char *)*proto))
540  found = true;
541  }
542  if( !found)
543  {
544  std::string msg("Unsupported protocol '");
545  msg += scheme;
546  msg += "'";
548  }
549  }
550 }
551 
553 {
554  {
555  char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
556  _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
557  if( _curlDebug > 0)
558  {
559  curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
560  curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
561  curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
562  }
563  }
564 
565  curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
566  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
567  if ( ret != 0 ) {
568  ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
569  }
570 
571  SET_OPTION(CURLOPT_FAILONERROR, 1L);
572  SET_OPTION(CURLOPT_NOSIGNAL, 1L);
573 
574  // create non persistant settings
575  // so that we don't add headers twice
576  TransferSettings vol_settings(_settings);
577 
578  // add custom headers
579  vol_settings.addHeader(anonymousIdHeader());
580  vol_settings.addHeader(distributionFlavorHeader());
581  vol_settings.addHeader("Pragma:");
582 
583  _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
585 
587 
588  // fill some settings from url query parameters
589  try
590  {
592  }
593  catch ( const MediaException &e )
594  {
595  disconnectFrom();
596  ZYPP_RETHROW(e);
597  }
598  // if the proxy was not set (or explicitly unset) by url, then look...
599  if ( _settings.proxy().empty() )
600  {
601  // ...at the system proxy settings
603  }
604 
608  SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
609  // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
610  // just in case curl does not trigger its progress callback frequently
611  // enough.
612  if ( _settings.timeout() )
613  {
614  SET_OPTION(CURLOPT_TIMEOUT, 3600L);
615  }
616 
617  // follow any Location: header that the server sends as part of
618  // an HTTP header (#113275)
619  SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
620  // 3 redirects seem to be too few in some cases (bnc #465532)
621  SET_OPTION(CURLOPT_MAXREDIRS, 6L);
622 
623  if ( _url.getScheme() == "https" )
624  {
625 #if CURLVERSION_AT_LEAST(7,19,4)
626  // restrict following of redirections from https to https only
627  SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
628 #endif
629 
632  {
633  SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
634  }
635 
636  if( ! _settings.clientCertificatePath().empty() )
637  {
638  SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
639  }
640  if( ! _settings.clientKeyPath().empty() )
641  {
642  SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
643  }
644 
645 #ifdef CURLSSLOPT_ALLOW_BEAST
646  // see bnc#779177
647  ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
648  if ( ret != 0 ) {
649  disconnectFrom();
651  }
652 #endif
653  SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
654  SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
655  // bnc#903405 - POODLE: libzypp should only talk TLS
656  SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
657  }
658 
659  SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
660 
661  /*---------------------------------------------------------------*
662  CURLOPT_USERPWD: [user name]:[password]
663 
664  Url::username/password -> CURLOPT_USERPWD
665  If not provided, anonymous FTP identification
666  *---------------------------------------------------------------*/
667 
668  if ( _settings.userPassword().size() )
669  {
670  SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
671  string use_auth = _settings.authType();
672  if (use_auth.empty())
673  use_auth = "digest,basic"; // our default
674  long auth = CurlAuthData::auth_type_str2long(use_auth);
675  if( auth != CURLAUTH_NONE)
676  {
677  DBG << "Enabling HTTP authentication methods: " << use_auth
678  << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
679  SET_OPTION(CURLOPT_HTTPAUTH, auth);
680  }
681  }
682 
683  if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
684  {
685  DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
686  SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
687  SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
688  /*---------------------------------------------------------------*
689  * CURLOPT_PROXYUSERPWD: [user name]:[password]
690  *
691  * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
692  * If not provided, $HOME/.curlrc is evaluated
693  *---------------------------------------------------------------*/
694 
695  string proxyuserpwd = _settings.proxyUserPassword();
696 
697  if ( proxyuserpwd.empty() )
698  {
699  CurlConfig curlconf;
700  CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
701  if ( curlconf.proxyuserpwd.empty() )
702  DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
703  else
704  {
705  proxyuserpwd = curlconf.proxyuserpwd;
706  DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
707  }
708  }
709  else
710  {
711  DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
712  }
713 
714  if ( ! proxyuserpwd.empty() )
715  {
716  SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
717  }
718  }
719 #if CURLVERSION_AT_LEAST(7,19,4)
720  else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
721  {
722  // Explicitly disabled in URL (see fillSettingsFromUrl()).
723  // This should also prevent libcurl from looking into the environment.
724  DBG << "Proxy: explicitly NOPROXY" << endl;
725  SET_OPTION(CURLOPT_NOPROXY, "*");
726  }
727 #endif
728  else
729  {
730  // libcurl may look into the enviroanment
731  DBG << "Proxy: not explicitly set" << endl;
732  }
733 
735  if ( _settings.minDownloadSpeed() != 0 )
736  {
737  SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
738  // default to 10 seconds at low speed
739  SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
740  }
741 
742 #if CURLVERSION_AT_LEAST(7,15,5)
743  if ( _settings.maxDownloadSpeed() != 0 )
744  SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
745 #endif
746 
747  /*---------------------------------------------------------------*
748  *---------------------------------------------------------------*/
749 
750  _currentCookieFile = _cookieFile.asString();
751  if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
752  SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
753  else
754  MIL << "No cookies requested" << endl;
755  SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
756  SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
757  SET_OPTION(CURLOPT_NOPROGRESS, 0L);
758 
759 #if CURLVERSION_AT_LEAST(7,18,0)
760  // bnc #306272
761  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
762 #endif
763  // append settings custom headers to curl
764  for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
765  it != vol_settings.headersEnd();
766  ++it )
767  {
768  // MIL << "HEADER " << *it << std::endl;
769 
770  _customHeaders = curl_slist_append(_customHeaders, it->c_str());
771  if ( !_customHeaders )
773  }
774 
775  SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
776 }
777 
779 
780 
781 void MediaCurl::attachTo (bool next)
782 {
783  if ( next )
785 
786  if ( !_url.isValid() )
788 
791  {
792  std::string mountpoint = createAttachPoint().asString();
793 
794  if( mountpoint.empty())
796 
797  setAttachPoint( mountpoint, true);
798  }
799 
800  disconnectFrom(); // clean _curl if needed
801  _curl = curl_easy_init();
802  if ( !_curl ) {
804  }
805  try
806  {
807  setupEasy();
808  }
809  catch (Exception & ex)
810  {
811  disconnectFrom();
812  ZYPP_RETHROW(ex);
813  }
814 
815  // FIXME: need a derived class to propelly compare url's
817  setMediaSource(media);
818 }
819 
820 bool
821 MediaCurl::checkAttachPoint(const Pathname &apoint) const
822 {
823  return MediaHandler::checkAttachPoint( apoint, true, true);
824 }
825 
827 
829 {
830  if ( _customHeaders )
831  {
832  curl_slist_free_all(_customHeaders);
833  _customHeaders = 0L;
834  }
835 
836  if ( _curl )
837  {
838  curl_easy_cleanup( _curl );
839  _curl = NULL;
840  }
841 }
842 
844 
845 void MediaCurl::releaseFrom( const std::string & ejectDev )
846 {
847  disconnect();
848 }
849 
850 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
851 {
852  std::string path( _url.getPathName() );
853  // Simply extend the URLs pathname. An 'absolute' URL path
854  // is achieved by encoding the 2nd '/' in the URL:
855  // URL: ftp://user@server -> ~user
856  // URL: ftp://user@server/ -> ~user
857  // URL: ftp://user@server// -> /
858  // ^- this '/' is just a separator
859  if ( path.empty() || path == "/" ) // empty URL path; the '/' is just a separator
860  {
861  path = filename_r.absolutename().asString();
862  }
863  else if ( *path.rbegin() == '/' )
864  {
865  path += filename_r.absolutename().asString().substr(1);
866  }
867  else
868  {
869  path += filename_r.absolutename().asString();
870  }
871  Url newurl( _url );
872  newurl.setPathName( path );
873  return newurl;
874 }
875 
877 
878 void MediaCurl::getFile( const Pathname & filename ) const
879 {
880  // Use absolute file name to prevent access of files outside of the
881  // hierarchy below the attach point.
882  getFileCopy(filename, localPath(filename).absolutename());
883 }
884 
886 
887 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
888 {
890 
891  Url fileurl(getFileUrl(filename));
892 
893  bool retry = false;
894 
895  do
896  {
897  try
898  {
899  doGetFileCopy(filename, target, report);
900  retry = false;
901  }
902  // retry with proper authentication data
903  catch (MediaUnauthorizedException & ex_r)
904  {
905  if(authenticate(ex_r.hint(), !retry))
906  retry = true;
907  else
908  {
909  report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
910  ZYPP_RETHROW(ex_r);
911  }
912  }
913  // unexpected exception
914  catch (MediaException & excpt_r)
915  {
916  // FIXME: error number fix
917  report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
918  ZYPP_RETHROW(excpt_r);
919  }
920  }
921  while (retry);
922 
923  report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
924 }
925 
927 
928 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
929 {
930  bool retry = false;
931 
932  do
933  {
934  try
935  {
936  return doGetDoesFileExist( filename );
937  }
938  // authentication problem, retry with proper authentication data
939  catch (MediaUnauthorizedException & ex_r)
940  {
941  if(authenticate(ex_r.hint(), !retry))
942  retry = true;
943  else
944  ZYPP_RETHROW(ex_r);
945  }
946  // unexpected exception
947  catch (MediaException & excpt_r)
948  {
949  ZYPP_RETHROW(excpt_r);
950  }
951  }
952  while (retry);
953 
954  return false;
955 }
956 
958 
959 void MediaCurl::evaluateCurlCode( const Pathname &filename,
960  CURLcode code,
961  bool timeout_reached ) const
962 {
963  if ( code != 0 )
964  {
965  Url url;
966  if (filename.empty())
967  url = _url;
968  else
969  url = getFileUrl(filename);
970  std::string err;
971  try
972  {
973  switch ( code )
974  {
975  case CURLE_UNSUPPORTED_PROTOCOL:
976  case CURLE_URL_MALFORMAT:
977  case CURLE_URL_MALFORMAT_USER:
978  err = " Bad URL";
979  break;
980  case CURLE_LOGIN_DENIED:
981  ZYPP_THROW(
982  MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
983  break;
984  case CURLE_HTTP_RETURNED_ERROR:
985  {
986  long httpReturnCode = 0;
987  CURLcode infoRet = curl_easy_getinfo( _curl,
988  CURLINFO_RESPONSE_CODE,
989  &httpReturnCode );
990  if ( infoRet == CURLE_OK )
991  {
992  string msg = "HTTP response: " + str::numstring( httpReturnCode );
993  switch ( httpReturnCode )
994  {
995  case 401:
996  {
997  string auth_hint = getAuthHint();
998 
999  DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1000  DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1001 
1003  url, "Login failed.", _curlError, auth_hint
1004  ));
1005  }
1006 
1007  case 503: // service temporarily unavailable (bnc #462545)
1009  case 504: // gateway timeout
1011  case 403:
1012  {
1013  string msg403;
1014  if (url.asString().find("novell.com") != string::npos)
1015  msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1016  ZYPP_THROW(MediaForbiddenException(url, msg403));
1017  }
1018  case 404:
1020  }
1021 
1022  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1024  }
1025  else
1026  {
1027  string msg = "Unable to retrieve HTTP response:";
1028  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1030  }
1031  }
1032  break;
1033  case CURLE_FTP_COULDNT_RETR_FILE:
1034 #if CURLVERSION_AT_LEAST(7,16,0)
1035  case CURLE_REMOTE_FILE_NOT_FOUND:
1036 #endif
1037  case CURLE_FTP_ACCESS_DENIED:
1038  case CURLE_TFTP_NOTFOUND:
1039  err = "File not found";
1041  break;
1042  case CURLE_BAD_PASSWORD_ENTERED:
1043  case CURLE_FTP_USER_PASSWORD_INCORRECT:
1044  err = "Login failed";
1045  break;
1046  case CURLE_COULDNT_RESOLVE_PROXY:
1047  case CURLE_COULDNT_RESOLVE_HOST:
1048  case CURLE_COULDNT_CONNECT:
1049  case CURLE_FTP_CANT_GET_HOST:
1050  err = "Connection failed";
1051  break;
1052  case CURLE_WRITE_ERROR:
1053  err = "Write error";
1054  break;
1055  case CURLE_PARTIAL_FILE:
1056  case CURLE_OPERATION_TIMEDOUT:
1057  timeout_reached = true; // fall though to TimeoutException
1058  // fall though...
1059  case CURLE_ABORTED_BY_CALLBACK:
1060  if( timeout_reached )
1061  {
1062  err = "Timeout reached";
1064  }
1065  else
1066  {
1067  err = "User abort";
1068  }
1069  break;
1070  case CURLE_SSL_PEER_CERTIFICATE:
1071  default:
1072  err = "Unrecognized error";
1073  break;
1074  }
1075 
1076  // uhm, no 0 code but unknown curl exception
1078  }
1079  catch (const MediaException & excpt_r)
1080  {
1081  ZYPP_RETHROW(excpt_r);
1082  }
1083  }
1084  else
1085  {
1086  // actually the code is 0, nothing happened
1087  }
1088 }
1089 
1091 
1092 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1093 {
1094  DBG << filename.asString() << endl;
1095 
1096  if(!_url.isValid())
1098 
1099  if(_url.getHost().empty())
1101 
1102  Url url(getFileUrl(filename));
1103 
1104  DBG << "URL: " << url.asString() << endl;
1105  // Use URL without options and without username and passwd
1106  // (some proxies dislike them in the URL).
1107  // Curl seems to need the just scheme, hostname and a path;
1108  // the rest was already passed as curl options (in attachTo).
1109  Url curlUrl( clearQueryString(url) );
1110 
1111  //
1112  // See also Bug #154197 and ftp url definition in RFC 1738:
1113  // The url "ftp://user@host/foo/bar/file" contains a path,
1114  // that is relative to the user's home.
1115  // The url "ftp://user@host//foo/bar/file" (or also with
1116  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1117  // contains an absolute path.
1118  //
1119  string urlBuffer( curlUrl.asString());
1120  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1121  urlBuffer.c_str() );
1122  if ( ret != 0 ) {
1124  }
1125 
1126  // instead of returning no data with NOBODY, we return
1127  // little data, that works with broken servers, and
1128  // works for ftp as well, because retrieving only headers
1129  // ftp will return always OK code ?
1130  // See http://curl.haxx.se/docs/knownbugs.html #58
1131  if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1133  ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1134  else
1135  ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1136 
1137  if ( ret != 0 ) {
1138  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1139  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1140  /* yes, this is why we never got to get NOBODY working before,
1141  because setting it changes this option too, and we also
1142  need to reset it
1143  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1144  */
1145  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1147  }
1148 
1149  FILE *file = ::fopen( "/dev/null", "w" );
1150  if ( !file ) {
1151  ERR << "fopen failed for /dev/null" << endl;
1152  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1153  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1154  /* yes, this is why we never got to get NOBODY working before,
1155  because setting it changes this option too, and we also
1156  need to reset it
1157  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1158  */
1159  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1160  if ( ret != 0 ) {
1162  }
1163  ZYPP_THROW(MediaWriteException("/dev/null"));
1164  }
1165 
1166  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1167  if ( ret != 0 ) {
1168  ::fclose(file);
1169  std::string err( _curlError);
1170  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1171  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1172  /* yes, this is why we never got to get NOBODY working before,
1173  because setting it changes this option too, and we also
1174  need to reset it
1175  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1176  */
1177  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1178  if ( ret != 0 ) {
1180  }
1182  }
1183 
1184  CURLcode ok = curl_easy_perform( _curl );
1185  MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1186 
1187  // reset curl settings
1188  if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1189  {
1190  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1191  if ( ret != 0 ) {
1193  }
1194 
1195  /* yes, this is why we never got to get NOBODY working before,
1196  because setting it changes this option too, and we also
1197  need to reset it
1198  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1199  */
1200  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1201  if ( ret != 0 ) {
1203  }
1204 
1205  }
1206  else
1207  {
1208  // for FTP we set different options
1209  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1210  if ( ret != 0 ) {
1212  }
1213  }
1214 
1215  // if the code is not zero, close the file
1216  if ( ok != 0 )
1217  ::fclose(file);
1218 
1219  // as we are not having user interaction, the user can't cancel
1220  // the file existence checking, a callback or timeout return code
1221  // will be always a timeout.
1222  try {
1223  evaluateCurlCode( filename, ok, true /* timeout */);
1224  }
1225  catch ( const MediaFileNotFoundException &e ) {
1226  // if the file did not exist then we can return false
1227  return false;
1228  }
1229  catch ( const MediaException &e ) {
1230  // some error, we are not sure about file existence, rethrw
1231  ZYPP_RETHROW(e);
1232  }
1233  // exists
1234  return ( ok == CURLE_OK );
1235 }
1236 
1238 
1239 
1240 #if DETECT_DIR_INDEX
1241 bool MediaCurl::detectDirIndex() const
1242 {
1243  if(_url.getScheme() != "http" && _url.getScheme() != "https")
1244  return false;
1245  //
1246  // try to check the effective url and set the not_a_file flag
1247  // if the url path ends with a "/", what usually means, that
1248  // we've received a directory index (index.html content).
1249  //
1250  // Note: This may be dangerous and break file retrieving in
1251  // case of some server redirections ... ?
1252  //
1253  bool not_a_file = false;
1254  char *ptr = NULL;
1255  CURLcode ret = curl_easy_getinfo( _curl,
1256  CURLINFO_EFFECTIVE_URL,
1257  &ptr);
1258  if ( ret == CURLE_OK && ptr != NULL)
1259  {
1260  try
1261  {
1262  Url eurl( ptr);
1263  std::string path( eurl.getPathName());
1264  if( !path.empty() && path != "/" && *path.rbegin() == '/')
1265  {
1266  DBG << "Effective url ("
1267  << eurl
1268  << ") seems to provide the index of a directory"
1269  << endl;
1270  not_a_file = true;
1271  }
1272  }
1273  catch( ... )
1274  {}
1275  }
1276  return not_a_file;
1277 }
1278 #endif
1279 
1281 
1282 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1283 {
1284  Pathname dest = target.absolutename();
1285  if( assert_dir( dest.dirname() ) )
1286  {
1287  DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1288  Url url(getFileUrl(filename));
1289  ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1290  }
1291  string destNew = target.asString() + ".new.zypp.XXXXXX";
1292  char *buf = ::strdup( destNew.c_str());
1293  if( !buf)
1294  {
1295  ERR << "out of memory for temp file name" << endl;
1296  Url url(getFileUrl(filename));
1297  ZYPP_THROW(MediaSystemException(url, "out of memory for temp file name"));
1298  }
1299 
1300  int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1301  if( tmp_fd == -1)
1302  {
1303  free( buf);
1304  ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1305  ZYPP_THROW(MediaWriteException(destNew));
1306  }
1307  destNew = buf;
1308  free( buf);
1309 
1310  FILE *file = ::fdopen( tmp_fd, "we" );
1311  if ( !file ) {
1312  ::close( tmp_fd);
1313  filesystem::unlink( destNew );
1314  ERR << "fopen failed for file '" << destNew << "'" << endl;
1315  ZYPP_THROW(MediaWriteException(destNew));
1316  }
1317 
1318  DBG << "dest: " << dest << endl;
1319  DBG << "temp: " << destNew << endl;
1320 
1321  // set IFMODSINCE time condition (no download if not modified)
1322  if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1323  {
1324  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1325  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1326  }
1327  else
1328  {
1329  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1330  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1331  }
1332  try
1333  {
1334  doGetFileCopyFile(filename, dest, file, report, options);
1335  }
1336  catch (Exception &e)
1337  {
1338  ::fclose( file );
1339  filesystem::unlink( destNew );
1340  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1341  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1342  ZYPP_RETHROW(e);
1343  }
1344 
1345  long httpReturnCode = 0;
1346  CURLcode infoRet = curl_easy_getinfo(_curl,
1347  CURLINFO_RESPONSE_CODE,
1348  &httpReturnCode);
1349  bool modified = true;
1350  if (infoRet == CURLE_OK)
1351  {
1352  DBG << "HTTP response: " + str::numstring(httpReturnCode);
1353  if ( httpReturnCode == 304
1354  || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1355  {
1356  DBG << " Not modified.";
1357  modified = false;
1358  }
1359  DBG << endl;
1360  }
1361  else
1362  {
1363  WAR << "Could not get the reponse code." << endl;
1364  }
1365 
1366  if (modified || infoRet != CURLE_OK)
1367  {
1368  // apply umask
1369  if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1370  {
1371  ERR << "Failed to chmod file " << destNew << endl;
1372  }
1373  if (::fclose( file ))
1374  {
1375  ERR << "Fclose failed for file '" << destNew << "'" << endl;
1376  ZYPP_THROW(MediaWriteException(destNew));
1377  }
1378  // move the temp file into dest
1379  if ( rename( destNew, dest ) != 0 ) {
1380  ERR << "Rename failed" << endl;
1382  }
1383  }
1384  else
1385  {
1386  // close and remove the temp file
1387  ::fclose( file );
1388  filesystem::unlink( destNew );
1389  }
1390 
1391  DBG << "done: " << PathInfo(dest) << endl;
1392 }
1393 
1395 
1396 void MediaCurl::doGetFileCopyFile( const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1397 {
1398  DBG << filename.asString() << endl;
1399 
1400  if(!_url.isValid())
1402 
1403  if(_url.getHost().empty())
1405 
1406  Url url(getFileUrl(filename));
1407 
1408  DBG << "URL: " << url.asString() << endl;
1409  // Use URL without options and without username and passwd
1410  // (some proxies dislike them in the URL).
1411  // Curl seems to need the just scheme, hostname and a path;
1412  // the rest was already passed as curl options (in attachTo).
1413  Url curlUrl( clearQueryString(url) );
1414 
1415  //
1416  // See also Bug #154197 and ftp url definition in RFC 1738:
1417  // The url "ftp://user@host/foo/bar/file" contains a path,
1418  // that is relative to the user's home.
1419  // The url "ftp://user@host//foo/bar/file" (or also with
1420  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1421  // contains an absolute path.
1422  //
1423  string urlBuffer( curlUrl.asString());
1424  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1425  urlBuffer.c_str() );
1426  if ( ret != 0 ) {
1428  }
1429 
1430  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1431  if ( ret != 0 ) {
1433  }
1434 
1435  // Set callback and perform.
1436  ProgressData progressData(_curl, _settings.timeout(), url, &report);
1437  if (!(options & OPTION_NO_REPORT_START))
1438  report->start(url, dest);
1439  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1440  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1441  }
1442 
1443  ret = curl_easy_perform( _curl );
1444 #if CURLVERSION_AT_LEAST(7,19,4)
1445  // bnc#692260: If the client sends a request with an If-Modified-Since header
1446  // with a future date for the server, the server may respond 200 sending a
1447  // zero size file.
1448  // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1449  if ( ftell(file) == 0 && ret == 0 )
1450  {
1451  long httpReturnCode = 33;
1452  if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1453  {
1454  long conditionUnmet = 33;
1455  if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1456  {
1457  WAR << "TIMECONDITION unmet - retry without." << endl;
1458  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1459  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1460  ret = curl_easy_perform( _curl );
1461  }
1462  }
1463  }
1464 #endif
1465 
1466  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1467  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1468  }
1469 
1470  if ( ret != 0 )
1471  {
1472  ERR << "curl error: " << ret << ": " << _curlError
1473  << ", temp file size " << ftell(file)
1474  << " bytes." << endl;
1475 
1476  // the timeout is determined by the progress data object
1477  // which holds whether the timeout was reached or not,
1478  // otherwise it would be a user cancel
1479  try {
1480  evaluateCurlCode( filename, ret, progressData.reached);
1481  }
1482  catch ( const MediaException &e ) {
1483  // some error, we are not sure about file existence, rethrw
1484  ZYPP_RETHROW(e);
1485  }
1486  }
1487 
1488 #if DETECT_DIR_INDEX
1489  if (!ret && detectDirIndex())
1490  {
1492  }
1493 #endif // DETECT_DIR_INDEX
1494 }
1495 
1497 
1498 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1499 {
1500  filesystem::DirContent content;
1501  getDirInfo( content, dirname, /*dots*/false );
1502 
1503  for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1504  Pathname filename = dirname + it->name;
1505  int res = 0;
1506 
1507  switch ( it->type ) {
1508  case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1509  case filesystem::FT_FILE:
1510  getFile( filename );
1511  break;
1512  case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1513  if ( recurse_r ) {
1514  getDir( filename, recurse_r );
1515  } else {
1516  res = assert_dir( localPath( filename ) );
1517  if ( res ) {
1518  WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1519  }
1520  }
1521  break;
1522  default:
1523  // don't provide devices, sockets, etc.
1524  break;
1525  }
1526  }
1527 }
1528 
1530 
1531 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1532  const Pathname & dirname, bool dots ) const
1533 {
1534  getDirectoryYast( retlist, dirname, dots );
1535 }
1536 
1538 
1540  const Pathname & dirname, bool dots ) const
1541 {
1542  getDirectoryYast( retlist, dirname, dots );
1543 }
1544 
1546 
1547 int MediaCurl::progressCallback( void *clientp,
1548  double dltotal, double dlnow,
1549  double ultotal, double ulnow)
1550 {
1551  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1552  if( pdata)
1553  {
1554  // work around curl bug that gives us old data
1555  long httpReturnCode = 0;
1556  if (curl_easy_getinfo(pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode) != CURLE_OK || httpReturnCode == 0)
1557  return 0;
1558 
1559  time_t now = time(NULL);
1560  if( now > 0)
1561  {
1562  // reset time of last change in case initial time()
1563  // failed or the time was adjusted (goes backward)
1564  if( pdata->ltime <= 0 || pdata->ltime > now)
1565  {
1566  pdata->ltime = now;
1567  }
1568 
1569  // start time counting as soon as first data arrives
1570  // (skip the connection / redirection time at begin)
1571  time_t dif = 0;
1572  if (dlnow > 0 || ulnow > 0)
1573  {
1574  dif = (now - pdata->ltime);
1575  dif = dif > 0 ? dif : 0;
1576 
1577  pdata->secs += dif;
1578  }
1579 
1580  // update the drate_avg and drate_period only after a second has passed
1581  // (this callback is called much more often than a second)
1582  // otherwise the values would be far from accurate when measuring
1583  // the time in seconds
1585 
1586  if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1587  pdata->drate_avg = (dlnow / pdata->secs);
1588 
1589  if ( dif > 0 )
1590  {
1591  pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1592  pdata->dload_period = dlnow;
1593  }
1594  }
1595 
1596  // send progress report first, abort transfer if requested
1597  if( pdata->report)
1598  {
1599  if (!(*(pdata->report))->progress(int( dltotal ? dlnow * 100 / dltotal : 0 ),
1600  pdata->url,
1601  pdata->drate_avg,
1602  pdata->drate_period))
1603  {
1604  return 1; // abort transfer
1605  }
1606  }
1607 
1608  // check if we there is a timeout set
1609  if( pdata->timeout > 0)
1610  {
1611  if( now > 0)
1612  {
1613  bool progress = false;
1614 
1615  // update download data if changed, mark progress
1616  if( dlnow != pdata->dload)
1617  {
1618  progress = true;
1619  pdata->dload = dlnow;
1620  pdata->ltime = now;
1621  }
1622  // update upload data if changed, mark progress
1623  if( ulnow != pdata->uload)
1624  {
1625  progress = true;
1626  pdata->uload = ulnow;
1627  pdata->ltime = now;
1628  }
1629 
1630  if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1631  {
1632  pdata->reached = true;
1633  return 1; // aborts transfer
1634  }
1635  }
1636  }
1637  }
1638  return 0;
1639 }
1640 
1642 {
1643  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1644  return pdata ? pdata->curl : 0;
1645 }
1646 
1648 
1650 {
1651  long auth_info = CURLAUTH_NONE;
1652 
1653  CURLcode infoRet =
1654  curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1655 
1656  if(infoRet == CURLE_OK)
1657  {
1658  return CurlAuthData::auth_type_long2str(auth_info);
1659  }
1660 
1661  return "";
1662 }
1663 
1665 
1666 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1667 {
1669  Target_Ptr target = zypp::getZYpp()->getTarget();
1670  CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1671  CurlAuthData_Ptr credentials;
1672 
1673  // get stored credentials
1674  AuthData_Ptr cmcred = cm.getCred(_url);
1675 
1676  if (cmcred && firstTry)
1677  {
1678  credentials.reset(new CurlAuthData(*cmcred));
1679  DBG << "got stored credentials:" << endl << *credentials << endl;
1680  }
1681  // if not found, ask user
1682  else
1683  {
1684 
1685  CurlAuthData_Ptr curlcred;
1686  curlcred.reset(new CurlAuthData());
1688 
1689  // preset the username if present in current url
1690  if (!_url.getUsername().empty() && firstTry)
1691  curlcred->setUsername(_url.getUsername());
1692  // if CM has found some credentials, preset the username from there
1693  else if (cmcred)
1694  curlcred->setUsername(cmcred->username());
1695 
1696  // indicate we have no good credentials from CM
1697  cmcred.reset();
1698 
1699  string prompt_msg = boost::str(boost::format(
1701  _("Authentication required for '%s'")) % _url.asString());
1702 
1703  // set available authentication types from the exception
1704  // might be needed in prompt
1705  curlcred->setAuthType(availAuthTypes);
1706 
1707  // ask user
1708  if (auth_report->prompt(_url, prompt_msg, *curlcred))
1709  {
1710  DBG << "callback answer: retry" << endl
1711  << "CurlAuthData: " << *curlcred << endl;
1712 
1713  if (curlcred->valid())
1714  {
1715  credentials = curlcred;
1716  // if (credentials->username() != _url.getUsername())
1717  // _url.setUsername(credentials->username());
1725  }
1726  }
1727  else
1728  {
1729  DBG << "callback answer: cancel" << endl;
1730  }
1731  }
1732 
1733  // set username and password
1734  if (credentials)
1735  {
1736  // HACK, why is this const?
1737  const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1738  const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1739 
1740  // set username and password
1741  CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1743 
1744  // set available authentication types from the exception
1745  if (credentials->authType() == CURLAUTH_NONE)
1746  credentials->setAuthType(availAuthTypes);
1747 
1748  // set auth type (seems this must be set _after_ setting the userpwd)
1749  if (credentials->authType() != CURLAUTH_NONE)
1750  {
1751  // FIXME: only overwrite if not empty?
1752  const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1753  ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1755  }
1756 
1757  if (!cmcred)
1758  {
1759  credentials->setUrl(_url);
1760  cm.addCred(*credentials);
1761  cm.save();
1762  }
1763 
1764  return true;
1765  }
1766 
1767  return false;
1768 }
1769 
1770 
1771  } // namespace media
1772 } // namespace zypp
1773 //
void setPassword(const std::string &pass, EEncoding eflag=zypp::url::E_DECODED)
Set the password in the URL authority.
Definition: Url.cc:733
std::string userPassword() const
returns the user and password as a user:pass string
int assert_dir(const Pathname &path, unsigned mode)
Like &#39;mkdir -p&#39;.
Definition: PathInfo.cc:324
Interface to gettext.
void checkProtocol(const Url &url) const
check the url is supported by the curl library
Definition: MediaCurl.cc:527
#define SET_OPTION_OFFT(opt, val)
Definition: MediaCurl.cc:452
#define MIL
Definition: Logger.h:47
#define CONNECT_TIMEOUT
Definition: MediaCurl.cc:43
bool verifyHostEnabled() const
Whether to verify host for ssl.
Pathname clientKeyPath() const
SSL client key file.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:320
bool authenticate(const std::string &availAuthTypes, bool firstTry) const
Definition: MediaCurl.cc:1666
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:845
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:394
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
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:514
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:492
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:1547
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
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:552
#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
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:878
std::string proxy(const Url &url) const
Definition: ProxyInfo.cc:44
static void setCookieFile(const Pathname &)
Definition: MediaCurl.cc:520
std::string getAuthHint() const
Return a comma separated list of available authentication methods supported by server.
Definition: MediaCurl.cc:1649
#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:1396
std::string userAgentString() const
user agent string
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
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 &#39;unlink&#39;.
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:928
void setMediaSource(const MediaSourceRef &ref)
Set new media source reference.
int rename(const Pathname &oldpath, const Pathname &newpath)
Like &#39;rename&#39;.
Definition: PathInfo.cc: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:425
Pathname localPath(const Pathname &pathname) const
Files provided will be available at &#39;localPath(filename)&#39;.
std::string proxyuserpwd
Definition: CurlConfig.h:39
std::string getQueryParam(const std::string &param, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
Definition: Url.cc:654
bool isUseableAttachPoint(const Pathname &path, bool mtab=true) const
Ask media manager, if the specified path is already used as attach point or if there are another atta...
virtual bool checkAttachPoint(const Pathname &apoint) const
Verify if the specified directory as attach point (root) as requires by the particular media handler ...
Definition: MediaCurl.cc:821
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:1498
std::string numstring(char n, int w=0)
Definition: String.h:219
virtual void disconnectFrom()
Definition: MediaCurl.cc:828
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&amp;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.
std::string form(const char *format,...)
Printf style construction of std::string.
Definition: String.cc:34
shared_ptr< AuthData > AuthData_Ptr
Definition: MediaUserAuth.h:69
int rmdir(const Pathname &path)
Like &#39;rmdir&#39;.
Definition: PathInfo.cc:371
#define SET_OPTION(opt, val)
Definition: MediaCurl.cc:445
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:850
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:1531
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:407
void fillSettingsSystemProxy(const Url &url, TransferSettings &s)
Reads the system proxy configuration and fills the settings structure proxy information.
Definition: MediaCurl.cc:361
callback::SendReport< DownloadProgressReport > * report
Definition: MediaCurl.cc:178
void addHeader(const std::string &header)
add a header, on the form &quot;Foo: Bar&quot;
CURL * curl
Definition: MediaCurl.cc:175
static CURL * progressCallback_getcurl(void *clientp)
Definition: MediaCurl.cc:1641
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:345
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:781
virtual void getFileCopy(const Pathname &srcFilename, const Pathname &targetFilename) const
Definition: MediaCurl.cc:887
double dload_period
Definition: MediaCurl.cc:182
virtual void doGetFileCopy(const Pathname &srcFilename, const Pathname &targetFilename, callback::SendReport< DownloadProgressReport > &_report, RequestOptions options=OPTION_NONE) const
Definition: MediaCurl.cc:1282
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 &amp; ~getUmask() ).
Definition: PathInfo.h:801
virtual bool doGetDoesFileExist(const Pathname &filename) const
Definition: MediaCurl.cc:1092
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
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:959
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: &quot;Mozilla v3&quot;
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:389
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