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