libzypp  12.16.5
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("timeout");
499  curlUrl.delQueryParam("auth");
500  curlUrl.delQueryParam("username");
501  curlUrl.delQueryParam("password");
502  curlUrl.delQueryParam("mediahandler");
503  return curlUrl;
504 }
505 
507 {
508  return _settings;
509 }
510 
511 
512 void MediaCurl::setCookieFile( const Pathname &fileName )
513 {
514  _cookieFile = fileName;
515 }
516 
518 
519 void MediaCurl::checkProtocol(const Url &url) const
520 {
521  curl_version_info_data *curl_info = NULL;
522  curl_info = curl_version_info(CURLVERSION_NOW);
523  // curl_info does not need any free (is static)
524  if (curl_info->protocols)
525  {
526  const char * const *proto;
527  std::string scheme( url.getScheme());
528  bool found = false;
529  for(proto=curl_info->protocols; !found && *proto; ++proto)
530  {
531  if( scheme == std::string((const char *)*proto))
532  found = true;
533  }
534  if( !found)
535  {
536  std::string msg("Unsupported protocol '");
537  msg += scheme;
538  msg += "'";
540  }
541  }
542 }
543 
545 {
546  {
547  char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
548  _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
549  if( _curlDebug > 0)
550  {
551  curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
552  curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
553  curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
554  }
555  }
556 
557  curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
558  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
559  if ( ret != 0 ) {
560  ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
561  }
562 
563  SET_OPTION(CURLOPT_FAILONERROR, 1L);
564  SET_OPTION(CURLOPT_NOSIGNAL, 1L);
565 
566  // create non persistant settings
567  // so that we don't add headers twice
568  TransferSettings vol_settings(_settings);
569 
570  // add custom headers
571  vol_settings.addHeader(anonymousIdHeader());
572  vol_settings.addHeader(distributionFlavorHeader());
573  vol_settings.addHeader("Pragma:");
574 
575  _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
577 
579 
580  // fill some settings from url query parameters
581  try
582  {
584  }
585  catch ( const MediaException &e )
586  {
587  disconnectFrom();
588  ZYPP_RETHROW(e);
589  }
590  // if the proxy was not set (or explicitly unset) by url, then look...
591  if ( _settings.proxy().empty() )
592  {
593  // ...at the system proxy settings
595  }
596 
600  SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
601 
602  // follow any Location: header that the server sends as part of
603  // an HTTP header (#113275)
604  SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
605  // 3 redirects seem to be too few in some cases (bnc #465532)
606  SET_OPTION(CURLOPT_MAXREDIRS, 6L);
607 
608  if ( _url.getScheme() == "https" )
609  {
610 #if CURLVERSION_AT_LEAST(7,19,4)
611  // restrict following of redirections from https to https only
612  SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
613 #endif
614 
617  {
618  SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
619  }
620 
621  if( ! _settings.clientCertificatePath().empty() )
622  {
623  SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
624  }
625 
626 #ifdef CURLSSLOPT_ALLOW_BEAST
627  // see bnc#779177
628  ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
629  if ( ret != 0 ) {
630  disconnectFrom();
632  }
633 #endif
634  SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
635  SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
636  }
637 
638  SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
639 
640  /*---------------------------------------------------------------*
641  CURLOPT_USERPWD: [user name]:[password]
642 
643  Url::username/password -> CURLOPT_USERPWD
644  If not provided, anonymous FTP identification
645  *---------------------------------------------------------------*/
646 
647  if ( _settings.userPassword().size() )
648  {
649  SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
650  string use_auth = _settings.authType();
651  if (use_auth.empty())
652  use_auth = "digest,basic"; // our default
653  long auth = CurlAuthData::auth_type_str2long(use_auth);
654  if( auth != CURLAUTH_NONE)
655  {
656  DBG << "Enabling HTTP authentication methods: " << use_auth
657  << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
658  SET_OPTION(CURLOPT_HTTPAUTH, auth);
659  }
660  }
661 
662  if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
663  {
664  DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
665  SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
666  SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
667  /*---------------------------------------------------------------*
668  * CURLOPT_PROXYUSERPWD: [user name]:[password]
669  *
670  * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
671  * If not provided, $HOME/.curlrc is evaluated
672  *---------------------------------------------------------------*/
673 
674  string proxyuserpwd = _settings.proxyUserPassword();
675 
676  if ( proxyuserpwd.empty() )
677  {
678  CurlConfig curlconf;
679  CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
680  if ( curlconf.proxyuserpwd.empty() )
681  DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
682  else
683  {
684  proxyuserpwd = curlconf.proxyuserpwd;
685  DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
686  }
687  }
688  else
689  {
690  DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
691  }
692 
693  if ( ! proxyuserpwd.empty() )
694  {
695  SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
696  }
697  }
698 #if CURLVERSION_AT_LEAST(7,19,4)
699  else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
700  {
701  // Explicitly disabled in URL (see fillSettingsFromUrl()).
702  // This should also prevent libcurl from looking into the environment.
703  DBG << "Proxy: explicitly NOPROXY" << endl;
704  SET_OPTION(CURLOPT_NOPROXY, "*");
705  }
706 #endif
707  else
708  {
709  // libcurl may look into the enviroanment
710  DBG << "Proxy: not explicitly set" << endl;
711  }
712 
714  if ( _settings.minDownloadSpeed() != 0 )
715  {
716  SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
717  // default to 10 seconds at low speed
718  SET_OPTION(CURLOPT_LOW_SPEED_TIME, 10L);
719  }
720 
721 #if CURLVERSION_AT_LEAST(7,15,5)
722  if ( _settings.maxDownloadSpeed() != 0 )
723  SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
724 #endif
725 
726  /*---------------------------------------------------------------*
727  *---------------------------------------------------------------*/
728 
729  _currentCookieFile = _cookieFile.asString();
730  if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
731  SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
732  else
733  MIL << "No cookies requested" << endl;
734  SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
735  SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
736  SET_OPTION(CURLOPT_NOPROGRESS, 0L);
737 
738 #if CURLVERSION_AT_LEAST(7,18,0)
739  // bnc #306272
740  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
741 #endif
742  // append settings custom headers to curl
743  for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
744  it != vol_settings.headersEnd();
745  ++it )
746  {
747  // MIL << "HEADER " << *it << std::endl;
748 
749  _customHeaders = curl_slist_append(_customHeaders, it->c_str());
750  if ( !_customHeaders )
752  }
753 
754  SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
755 }
756 
758 
759 
760 void MediaCurl::attachTo (bool next)
761 {
762  if ( next )
764 
765  if ( !_url.isValid() )
767 
770  {
771  std::string mountpoint = createAttachPoint().asString();
772 
773  if( mountpoint.empty())
775 
776  setAttachPoint( mountpoint, true);
777  }
778 
779  disconnectFrom(); // clean _curl if needed
780  _curl = curl_easy_init();
781  if ( !_curl ) {
783  }
784  try
785  {
786  setupEasy();
787  }
788  catch (Exception & ex)
789  {
790  disconnectFrom();
791  ZYPP_RETHROW(ex);
792  }
793 
794  // FIXME: need a derived class to propelly compare url's
796  setMediaSource(media);
797 }
798 
799 bool
800 MediaCurl::checkAttachPoint(const Pathname &apoint) const
801 {
802  return MediaHandler::checkAttachPoint( apoint, true, true);
803 }
804 
806 
808 {
809  if ( _customHeaders )
810  {
811  curl_slist_free_all(_customHeaders);
812  _customHeaders = 0L;
813  }
814 
815  if ( _curl )
816  {
817  curl_easy_cleanup( _curl );
818  _curl = NULL;
819  }
820 }
821 
823 
824 void MediaCurl::releaseFrom( const std::string & ejectDev )
825 {
826  disconnect();
827 }
828 
829 Url MediaCurl::getFileUrl(const Pathname & filename) const
830 {
831  Url newurl(_url);
832  string path = _url.getPathName();
833  if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
834  filename.absolute() )
835  {
836  // If url has a path with trailing slash, remove the leading slash from
837  // the absolute file name
838  path += filename.asString().substr( 1, filename.asString().size() - 1 );
839  }
840  else if ( filename.relative() )
841  {
842  // Add trailing slash to path, if not already there
843  if (path.empty()) path = "/";
844  else if (*path.rbegin() != '/' ) path += "/";
845  // Remove "./" from begin of relative file name
846  path += filename.asString().substr( 2, filename.asString().size() - 2 );
847  }
848  else
849  {
850  path += filename.asString();
851  }
852 
853  newurl.setPathName(path);
854  return newurl;
855 }
856 
858 
859 void MediaCurl::getFile( const Pathname & filename ) const
860 {
861  // Use absolute file name to prevent access of files outside of the
862  // hierarchy below the attach point.
863  getFileCopy(filename, localPath(filename).absolutename());
864 }
865 
867 
868 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
869 {
871 
872  Url fileurl(getFileUrl(filename));
873 
874  bool retry = false;
875 
876  do
877  {
878  try
879  {
880  doGetFileCopy(filename, target, report);
881  retry = false;
882  }
883  // retry with proper authentication data
884  catch (MediaUnauthorizedException & ex_r)
885  {
886  if(authenticate(ex_r.hint(), !retry))
887  retry = true;
888  else
889  {
890  report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
891  ZYPP_RETHROW(ex_r);
892  }
893  }
894  // unexpected exception
895  catch (MediaException & excpt_r)
896  {
897  // FIXME: error number fix
898  report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
899  ZYPP_RETHROW(excpt_r);
900  }
901  }
902  while (retry);
903 
904  report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
905 }
906 
908 
909 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
910 {
911  bool retry = false;
912 
913  do
914  {
915  try
916  {
917  return doGetDoesFileExist( filename );
918  }
919  // authentication problem, retry with proper authentication data
920  catch (MediaUnauthorizedException & ex_r)
921  {
922  if(authenticate(ex_r.hint(), !retry))
923  retry = true;
924  else
925  ZYPP_RETHROW(ex_r);
926  }
927  // unexpected exception
928  catch (MediaException & excpt_r)
929  {
930  ZYPP_RETHROW(excpt_r);
931  }
932  }
933  while (retry);
934 
935  return false;
936 }
937 
939 
940 void MediaCurl::evaluateCurlCode( const Pathname &filename,
941  CURLcode code,
942  bool timeout_reached ) const
943 {
944  if ( code != 0 )
945  {
946  Url url;
947  if (filename.empty())
948  url = _url;
949  else
950  url = getFileUrl(filename);
951  std::string err;
952  try
953  {
954  switch ( code )
955  {
956  case CURLE_UNSUPPORTED_PROTOCOL:
957  case CURLE_URL_MALFORMAT:
958  case CURLE_URL_MALFORMAT_USER:
959  err = " Bad URL";
960  break;
961  case CURLE_LOGIN_DENIED:
962  ZYPP_THROW(
963  MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
964  break;
965  case CURLE_HTTP_RETURNED_ERROR:
966  {
967  long httpReturnCode = 0;
968  CURLcode infoRet = curl_easy_getinfo( _curl,
969  CURLINFO_RESPONSE_CODE,
970  &httpReturnCode );
971  if ( infoRet == CURLE_OK )
972  {
973  string msg = "HTTP response: " + str::numstring( httpReturnCode );
974  switch ( httpReturnCode )
975  {
976  case 401:
977  {
978  string auth_hint = getAuthHint();
979 
980  DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
981  DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
982 
984  url, "Login failed.", _curlError, auth_hint
985  ));
986  }
987 
988  case 503: // service temporarily unavailable (bnc #462545)
990  case 504: // gateway timeout
992  case 403:
993  {
994  string msg403;
995  if (url.asString().find("novell.com") != string::npos)
996  msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
997  ZYPP_THROW(MediaForbiddenException(url, msg403));
998  }
999  case 404:
1001  }
1002 
1003  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1005  }
1006  else
1007  {
1008  string msg = "Unable to retrieve HTTP response:";
1009  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1011  }
1012  }
1013  break;
1014  case CURLE_FTP_COULDNT_RETR_FILE:
1015 #if CURLVERSION_AT_LEAST(7,16,0)
1016  case CURLE_REMOTE_FILE_NOT_FOUND:
1017 #endif
1018  case CURLE_FTP_ACCESS_DENIED:
1019  case CURLE_TFTP_NOTFOUND:
1020  err = "File not found";
1022  break;
1023  case CURLE_BAD_PASSWORD_ENTERED:
1024  case CURLE_FTP_USER_PASSWORD_INCORRECT:
1025  err = "Login failed";
1026  break;
1027  case CURLE_COULDNT_RESOLVE_PROXY:
1028  case CURLE_COULDNT_RESOLVE_HOST:
1029  case CURLE_COULDNT_CONNECT:
1030  case CURLE_FTP_CANT_GET_HOST:
1031  err = "Connection failed";
1032  break;
1033  case CURLE_WRITE_ERROR:
1034  err = "Write error";
1035  break;
1036  case CURLE_PARTIAL_FILE:
1037  case CURLE_OPERATION_TIMEDOUT:
1038  timeout_reached = true; // fall though to TimeoutException
1039  // fall though...
1040  case CURLE_ABORTED_BY_CALLBACK:
1041  if( timeout_reached )
1042  {
1043  err = "Timeout reached";
1045  }
1046  else
1047  {
1048  err = "User abort";
1049  }
1050  break;
1051  case CURLE_SSL_PEER_CERTIFICATE:
1052  default:
1053  err = "Unrecognized error";
1054  break;
1055  }
1056 
1057  // uhm, no 0 code but unknown curl exception
1059  }
1060  catch (const MediaException & excpt_r)
1061  {
1062  ZYPP_RETHROW(excpt_r);
1063  }
1064  }
1065  else
1066  {
1067  // actually the code is 0, nothing happened
1068  }
1069 }
1070 
1072 
1073 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1074 {
1075  DBG << filename.asString() << endl;
1076 
1077  if(!_url.isValid())
1079 
1080  if(_url.getHost().empty())
1082 
1083  Url url(getFileUrl(filename));
1084 
1085  DBG << "URL: " << url.asString() << endl;
1086  // Use URL without options and without username and passwd
1087  // (some proxies dislike them in the URL).
1088  // Curl seems to need the just scheme, hostname and a path;
1089  // the rest was already passed as curl options (in attachTo).
1090  Url curlUrl( clearQueryString(url) );
1091 
1092  //
1093  // See also Bug #154197 and ftp url definition in RFC 1738:
1094  // The url "ftp://user@host/foo/bar/file" contains a path,
1095  // that is relative to the user's home.
1096  // The url "ftp://user@host//foo/bar/file" (or also with
1097  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1098  // contains an absolute path.
1099  //
1100  string urlBuffer( curlUrl.asString());
1101  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1102  urlBuffer.c_str() );
1103  if ( ret != 0 ) {
1105  }
1106 
1107  // instead of returning no data with NOBODY, we return
1108  // little data, that works with broken servers, and
1109  // works for ftp as well, because retrieving only headers
1110  // ftp will return always OK code ?
1111  // See http://curl.haxx.se/docs/knownbugs.html #58
1112  if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1114  ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1115  else
1116  ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1117 
1118  if ( ret != 0 ) {
1119  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1120  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1121  /* yes, this is why we never got to get NOBODY working before,
1122  because setting it changes this option too, and we also
1123  need to reset it
1124  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1125  */
1126  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1128  }
1129 
1130  FILE *file = ::fopen( "/dev/null", "w" );
1131  if ( !file ) {
1132  ERR << "fopen failed for /dev/null" << endl;
1133  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1134  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1135  /* yes, this is why we never got to get NOBODY working before,
1136  because setting it changes this option too, and we also
1137  need to reset it
1138  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1139  */
1140  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1141  if ( ret != 0 ) {
1143  }
1144  ZYPP_THROW(MediaWriteException("/dev/null"));
1145  }
1146 
1147  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1148  if ( ret != 0 ) {
1149  ::fclose(file);
1150  std::string err( _curlError);
1151  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1152  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1153  /* yes, this is why we never got to get NOBODY working before,
1154  because setting it changes this option too, and we also
1155  need to reset it
1156  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1157  */
1158  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1159  if ( ret != 0 ) {
1161  }
1163  }
1164 
1165  CURLcode ok = curl_easy_perform( _curl );
1166  MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1167 
1168  // reset curl settings
1169  if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1170  {
1171  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1172  if ( ret != 0 ) {
1174  }
1175 
1176  /* yes, this is why we never got to get NOBODY working before,
1177  because setting it changes this option too, and we also
1178  need to reset it
1179  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1180  */
1181  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1182  if ( ret != 0 ) {
1184  }
1185 
1186  }
1187  else
1188  {
1189  // for FTP we set different options
1190  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1191  if ( ret != 0 ) {
1193  }
1194  }
1195 
1196  // if the code is not zero, close the file
1197  if ( ok != 0 )
1198  ::fclose(file);
1199 
1200  // as we are not having user interaction, the user can't cancel
1201  // the file existence checking, a callback or timeout return code
1202  // will be always a timeout.
1203  try {
1204  evaluateCurlCode( filename, ok, true /* timeout */);
1205  }
1206  catch ( const MediaFileNotFoundException &e ) {
1207  // if the file did not exist then we can return false
1208  return false;
1209  }
1210  catch ( const MediaException &e ) {
1211  // some error, we are not sure about file existence, rethrw
1212  ZYPP_RETHROW(e);
1213  }
1214  // exists
1215  return ( ok == CURLE_OK );
1216 }
1217 
1219 
1220 
1221 #if DETECT_DIR_INDEX
1222 bool MediaCurl::detectDirIndex() const
1223 {
1224  if(_url.getScheme() != "http" && _url.getScheme() != "https")
1225  return false;
1226  //
1227  // try to check the effective url and set the not_a_file flag
1228  // if the url path ends with a "/", what usually means, that
1229  // we've received a directory index (index.html content).
1230  //
1231  // Note: This may be dangerous and break file retrieving in
1232  // case of some server redirections ... ?
1233  //
1234  bool not_a_file = false;
1235  char *ptr = NULL;
1236  CURLcode ret = curl_easy_getinfo( _curl,
1237  CURLINFO_EFFECTIVE_URL,
1238  &ptr);
1239  if ( ret == CURLE_OK && ptr != NULL)
1240  {
1241  try
1242  {
1243  Url eurl( ptr);
1244  std::string path( eurl.getPathName());
1245  if( !path.empty() && path != "/" && *path.rbegin() == '/')
1246  {
1247  DBG << "Effective url ("
1248  << eurl
1249  << ") seems to provide the index of a directory"
1250  << endl;
1251  not_a_file = true;
1252  }
1253  }
1254  catch( ... )
1255  {}
1256  }
1257  return not_a_file;
1258 }
1259 #endif
1260 
1262 
1263 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1264 {
1265  Pathname dest = target.absolutename();
1266  if( assert_dir( dest.dirname() ) )
1267  {
1268  DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1269  Url url(getFileUrl(filename));
1270  ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1271  }
1272  string destNew = target.asString() + ".new.zypp.XXXXXX";
1273  char *buf = ::strdup( destNew.c_str());
1274  if( !buf)
1275  {
1276  ERR << "out of memory for temp file name" << endl;
1277  Url url(getFileUrl(filename));
1278  ZYPP_THROW(MediaSystemException(url, "out of memory for temp file name"));
1279  }
1280 
1281  int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1282  if( tmp_fd == -1)
1283  {
1284  free( buf);
1285  ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1286  ZYPP_THROW(MediaWriteException(destNew));
1287  }
1288  destNew = buf;
1289  free( buf);
1290 
1291  FILE *file = ::fdopen( tmp_fd, "we" );
1292  if ( !file ) {
1293  ::close( tmp_fd);
1294  filesystem::unlink( destNew );
1295  ERR << "fopen failed for file '" << destNew << "'" << endl;
1296  ZYPP_THROW(MediaWriteException(destNew));
1297  }
1298 
1299  DBG << "dest: " << dest << endl;
1300  DBG << "temp: " << destNew << endl;
1301 
1302  // set IFMODSINCE time condition (no download if not modified)
1303  if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1304  {
1305  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1306  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1307  }
1308  else
1309  {
1310  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1311  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1312  }
1313  try
1314  {
1315  doGetFileCopyFile(filename, dest, file, report, options);
1316  }
1317  catch (Exception &e)
1318  {
1319  ::fclose( file );
1320  filesystem::unlink( destNew );
1321  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1322  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1323  ZYPP_RETHROW(e);
1324  }
1325 
1326  long httpReturnCode = 0;
1327  CURLcode infoRet = curl_easy_getinfo(_curl,
1328  CURLINFO_RESPONSE_CODE,
1329  &httpReturnCode);
1330  bool modified = true;
1331  if (infoRet == CURLE_OK)
1332  {
1333  DBG << "HTTP response: " + str::numstring(httpReturnCode);
1334  if ( httpReturnCode == 304
1335  || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1336  {
1337  DBG << " Not modified.";
1338  modified = false;
1339  }
1340  DBG << endl;
1341  }
1342  else
1343  {
1344  WAR << "Could not get the reponse code." << endl;
1345  }
1346 
1347  if (modified || infoRet != CURLE_OK)
1348  {
1349  // apply umask
1350  if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1351  {
1352  ERR << "Failed to chmod file " << destNew << endl;
1353  }
1354  if (::fclose( file ))
1355  {
1356  ERR << "Fclose failed for file '" << destNew << "'" << endl;
1357  ZYPP_THROW(MediaWriteException(destNew));
1358  }
1359  // move the temp file into dest
1360  if ( rename( destNew, dest ) != 0 ) {
1361  ERR << "Rename failed" << endl;
1363  }
1364  }
1365  else
1366  {
1367  // close and remove the temp file
1368  ::fclose( file );
1369  filesystem::unlink( destNew );
1370  }
1371 
1372  DBG << "done: " << PathInfo(dest) << endl;
1373 }
1374 
1376 
1377 void MediaCurl::doGetFileCopyFile( const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1378 {
1379  DBG << filename.asString() << endl;
1380 
1381  if(!_url.isValid())
1383 
1384  if(_url.getHost().empty())
1386 
1387  Url url(getFileUrl(filename));
1388 
1389  DBG << "URL: " << url.asString() << endl;
1390  // Use URL without options and without username and passwd
1391  // (some proxies dislike them in the URL).
1392  // Curl seems to need the just scheme, hostname and a path;
1393  // the rest was already passed as curl options (in attachTo).
1394  Url curlUrl( clearQueryString(url) );
1395 
1396  //
1397  // See also Bug #154197 and ftp url definition in RFC 1738:
1398  // The url "ftp://user@host/foo/bar/file" contains a path,
1399  // that is relative to the user's home.
1400  // The url "ftp://user@host//foo/bar/file" (or also with
1401  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1402  // contains an absolute path.
1403  //
1404  string urlBuffer( curlUrl.asString());
1405  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1406  urlBuffer.c_str() );
1407  if ( ret != 0 ) {
1409  }
1410 
1411  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1412  if ( ret != 0 ) {
1414  }
1415 
1416  // Set callback and perform.
1417  ProgressData progressData(_curl, _settings.timeout(), url, &report);
1418  if (!(options & OPTION_NO_REPORT_START))
1419  report->start(url, dest);
1420  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1421  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1422  }
1423 
1424  ret = curl_easy_perform( _curl );
1425 #if CURLVERSION_AT_LEAST(7,19,4)
1426  // bnc#692260: If the client sends a request with an If-Modified-Since header
1427  // with a future date for the server, the server may respond 200 sending a
1428  // zero size file.
1429  // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1430  if ( ftell(file) == 0 && ret == 0 )
1431  {
1432  long httpReturnCode = 33;
1433  if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1434  {
1435  long conditionUnmet = 33;
1436  if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1437  {
1438  WAR << "TIMECONDITION unmet - retry without." << endl;
1439  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1440  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1441  ret = curl_easy_perform( _curl );
1442  }
1443  }
1444  }
1445 #endif
1446 
1447  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1448  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1449  }
1450 
1451  if ( ret != 0 )
1452  {
1453  ERR << "curl error: " << ret << ": " << _curlError
1454  << ", temp file size " << ftell(file)
1455  << " bytes." << endl;
1456 
1457  // the timeout is determined by the progress data object
1458  // which holds whether the timeout was reached or not,
1459  // otherwise it would be a user cancel
1460  try {
1461  evaluateCurlCode( filename, ret, progressData.reached);
1462  }
1463  catch ( const MediaException &e ) {
1464  // some error, we are not sure about file existence, rethrw
1465  ZYPP_RETHROW(e);
1466  }
1467  }
1468 
1469 #if DETECT_DIR_INDEX
1470  if (!ret && detectDirIndex())
1471  {
1473  }
1474 #endif // DETECT_DIR_INDEX
1475 }
1476 
1478 
1479 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1480 {
1481  filesystem::DirContent content;
1482  getDirInfo( content, dirname, /*dots*/false );
1483 
1484  for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1485  Pathname filename = dirname + it->name;
1486  int res = 0;
1487 
1488  switch ( it->type ) {
1489  case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1490  case filesystem::FT_FILE:
1491  getFile( filename );
1492  break;
1493  case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1494  if ( recurse_r ) {
1495  getDir( filename, recurse_r );
1496  } else {
1497  res = assert_dir( localPath( filename ) );
1498  if ( res ) {
1499  WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1500  }
1501  }
1502  break;
1503  default:
1504  // don't provide devices, sockets, etc.
1505  break;
1506  }
1507  }
1508 }
1509 
1511 
1512 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1513  const Pathname & dirname, bool dots ) const
1514 {
1515  getDirectoryYast( retlist, dirname, dots );
1516 }
1517 
1519 
1521  const Pathname & dirname, bool dots ) const
1522 {
1523  getDirectoryYast( retlist, dirname, dots );
1524 }
1525 
1527 
1528 int MediaCurl::progressCallback( void *clientp,
1529  double dltotal, double dlnow,
1530  double ultotal, double ulnow)
1531 {
1532  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1533  if( pdata)
1534  {
1535  // work around curl bug that gives us old data
1536  long httpReturnCode = 0;
1537  if (curl_easy_getinfo(pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode) != CURLE_OK || httpReturnCode == 0)
1538  return 0;
1539 
1540  time_t now = time(NULL);
1541  if( now > 0)
1542  {
1543  // reset time of last change in case initial time()
1544  // failed or the time was adjusted (goes backward)
1545  if( pdata->ltime <= 0 || pdata->ltime > now)
1546  {
1547  pdata->ltime = now;
1548  }
1549 
1550  // start time counting as soon as first data arrives
1551  // (skip the connection / redirection time at begin)
1552  time_t dif = 0;
1553  if (dlnow > 0 || ulnow > 0)
1554  {
1555  dif = (now - pdata->ltime);
1556  dif = dif > 0 ? dif : 0;
1557 
1558  pdata->secs += dif;
1559  }
1560 
1561  // update the drate_avg and drate_period only after a second has passed
1562  // (this callback is called much more often than a second)
1563  // otherwise the values would be far from accurate when measuring
1564  // the time in seconds
1566 
1567  if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1568  pdata->drate_avg = (dlnow / pdata->secs);
1569 
1570  if ( dif > 0 )
1571  {
1572  pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1573  pdata->dload_period = dlnow;
1574  }
1575  }
1576 
1577  // send progress report first, abort transfer if requested
1578  if( pdata->report)
1579  {
1580  if (!(*(pdata->report))->progress(int( dltotal ? dlnow * 100 / dltotal : 0 ),
1581  pdata->url,
1582  pdata->drate_avg,
1583  pdata->drate_period))
1584  {
1585  return 1; // abort transfer
1586  }
1587  }
1588 
1589  // check if we there is a timeout set
1590  if( pdata->timeout > 0)
1591  {
1592  if( now > 0)
1593  {
1594  bool progress = false;
1595 
1596  // update download data if changed, mark progress
1597  if( dlnow != pdata->dload)
1598  {
1599  progress = true;
1600  pdata->dload = dlnow;
1601  pdata->ltime = now;
1602  }
1603  // update upload data if changed, mark progress
1604  if( ulnow != pdata->uload)
1605  {
1606  progress = true;
1607  pdata->uload = ulnow;
1608  pdata->ltime = now;
1609  }
1610 
1611  if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1612  {
1613  pdata->reached = true;
1614  return 1; // aborts transfer
1615  }
1616  }
1617  }
1618  }
1619  return 0;
1620 }
1621 
1623 {
1624  ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1625  return pdata ? pdata->curl : 0;
1626 }
1627 
1629 
1631 {
1632  long auth_info = CURLAUTH_NONE;
1633 
1634  CURLcode infoRet =
1635  curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1636 
1637  if(infoRet == CURLE_OK)
1638  {
1639  return CurlAuthData::auth_type_long2str(auth_info);
1640  }
1641 
1642  return "";
1643 }
1644 
1646 
1647 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1648 {
1650  Target_Ptr target = zypp::getZYpp()->getTarget();
1651  CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1652  CurlAuthData_Ptr credentials;
1653 
1654  // get stored credentials
1655  AuthData_Ptr cmcred = cm.getCred(_url);
1656 
1657  if (cmcred && firstTry)
1658  {
1659  credentials.reset(new CurlAuthData(*cmcred));
1660  DBG << "got stored credentials:" << endl << *credentials << endl;
1661  }
1662  // if not found, ask user
1663  else
1664  {
1665 
1666  CurlAuthData_Ptr curlcred;
1667  curlcred.reset(new CurlAuthData());
1669 
1670  // preset the username if present in current url
1671  if (!_url.getUsername().empty() && firstTry)
1672  curlcred->setUsername(_url.getUsername());
1673  // if CM has found some credentials, preset the username from there
1674  else if (cmcred)
1675  curlcred->setUsername(cmcred->username());
1676 
1677  // indicate we have no good credentials from CM
1678  cmcred.reset();
1679 
1680  string prompt_msg = boost::str(boost::format(
1682  _("Authentication required for '%s'")) % _url.asString());
1683 
1684  // set available authentication types from the exception
1685  // might be needed in prompt
1686  curlcred->setAuthType(availAuthTypes);
1687 
1688  // ask user
1689  if (auth_report->prompt(_url, prompt_msg, *curlcred))
1690  {
1691  DBG << "callback answer: retry" << endl
1692  << "CurlAuthData: " << *curlcred << endl;
1693 
1694  if (curlcred->valid())
1695  {
1696  credentials = curlcred;
1697  // if (credentials->username() != _url.getUsername())
1698  // _url.setUsername(credentials->username());
1706  }
1707  }
1708  else
1709  {
1710  DBG << "callback answer: cancel" << endl;
1711  }
1712  }
1713 
1714  // set username and password
1715  if (credentials)
1716  {
1717  // HACK, why is this const?
1718  const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1719  const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1720 
1721  // set username and password
1722  CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1724 
1725  // set available authentication types from the exception
1726  if (credentials->authType() == CURLAUTH_NONE)
1727  credentials->setAuthType(availAuthTypes);
1728 
1729  // set auth type (seems this must be set _after_ setting the userpwd)
1730  if (credentials->authType() != CURLAUTH_NONE)
1731  {
1732  // FIXME: only overwrite if not empty?
1733  const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1734  ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1736  }
1737 
1738  if (!cmcred)
1739  {
1740  credentials->setUrl(_url);
1741  cm.addCred(*credentials);
1742  cm.save();
1743  }
1744 
1745  return true;
1746  }
1747 
1748  return false;
1749 }
1750 
1751 
1752  } // namespace media
1753 } // namespace zypp
1754 //