libzypp  17.25.2
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/media/CurlHelper.h>
29 #include <zypp/Target.h>
30 #include <zypp/ZYppFactory.h>
31 #include <zypp/ZConfig.h>
32 
33 #include <cstdlib>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/mount.h>
37 #include <errno.h>
38 #include <dirent.h>
39 #include <unistd.h>
40 
41 using std::endl;
42 
43 using namespace internal;
44 using namespace zypp::base;
45 
46 namespace zypp {
47 
48  namespace media {
49 
50 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
51 
52 // we use this define to unbloat code as this C setting option
53 // and catching exception is done frequently.
55 #define SET_OPTION(opt,val) do { \
56  ret = curl_easy_setopt ( _curl, opt, val ); \
57  if ( ret != 0) { \
58  ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
59  } \
60  } while ( false )
61 
62 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
63 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
64 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
65 
66 MediaCurl::MediaCurl( const Url & url_r,
67  const Pathname & attach_point_hint_r )
68  : MediaHandler( url_r, attach_point_hint_r,
69  "/", // urlpath at attachpoint
70  true ), // does_download
71  _curl( NULL ),
72  _customHeaders(0L)
73 {
74  _curlError[0] = '\0';
75  _curlDebug = 0L;
76 
77  MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
78 
80 
81  if( !attachPoint().empty())
82  {
83  PathInfo ainfo(attachPoint());
84  Pathname apath(attachPoint() + "XXXXXX");
85  char *atemp = ::strdup( apath.asString().c_str());
86  char *atest = NULL;
87  if( !ainfo.isDir() || !ainfo.userMayRWX() ||
88  atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
89  {
90  WAR << "attach point " << ainfo.path()
91  << " is not useable for " << url_r.getScheme() << endl;
92  setAttachPoint("", true);
93  }
94  else if( atest != NULL)
95  ::rmdir(atest);
96 
97  if( atemp != NULL)
98  ::free(atemp);
99  }
100 }
101 
103 {
105 }
106 
108 {
109  return _settings;
110 }
111 
112 
113 void MediaCurl::setCookieFile( const Pathname &fileName )
114 {
115  _cookieFile = fileName;
116 }
117 
119 
120 void MediaCurl::checkProtocol(const Url &url) const
121 {
122  curl_version_info_data *curl_info = NULL;
123  curl_info = curl_version_info(CURLVERSION_NOW);
124  // curl_info does not need any free (is static)
125  if (curl_info->protocols)
126  {
127  const char * const *proto;
128  std::string scheme( url.getScheme());
129  bool found = false;
130  for(proto=curl_info->protocols; !found && *proto; ++proto)
131  {
132  if( scheme == std::string((const char *)*proto))
133  found = true;
134  }
135  if( !found)
136  {
137  std::string msg("Unsupported protocol '");
138  msg += scheme;
139  msg += "'";
141  }
142  }
143 }
144 
146 {
147  {
148  char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
149  _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
150  if( _curlDebug > 0)
151  {
152  curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
153  curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
154  curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
155  }
156  }
157 
158  curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
159  curl_easy_setopt(_curl, CURLOPT_HEADERDATA, &_lastRedirect);
160  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
161  if ( ret != 0 ) {
162  ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
163  }
164 
165  SET_OPTION(CURLOPT_FAILONERROR, 1L);
166  SET_OPTION(CURLOPT_NOSIGNAL, 1L);
167 
168  // create non persistant settings
169  // so that we don't add headers twice
170  TransferSettings vol_settings(_settings);
171 
172  // add custom headers for download.opensuse.org (bsc#955801)
173  if ( _url.getHost() == "download.opensuse.org" )
174  {
175  vol_settings.addHeader(anonymousIdHeader());
176  vol_settings.addHeader(distributionFlavorHeader());
177  }
178  vol_settings.addHeader("Pragma:");
179 
180  _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
182 
184 
185  // fill some settings from url query parameters
186  try
187  {
189  }
190  catch ( const MediaException &e )
191  {
192  disconnectFrom();
193  ZYPP_RETHROW(e);
194  }
195  // if the proxy was not set (or explicitly unset) by url, then look...
196  if ( _settings.proxy().empty() )
197  {
198  // ...at the system proxy settings
200  }
201 
204  {
205  switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
206  {
207  case 4: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); break;
208  case 6: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); break;
209  }
210  }
211 
215  SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
216  // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
217  // just in case curl does not trigger its progress callback frequently
218  // enough.
219  if ( _settings.timeout() )
220  {
221  SET_OPTION(CURLOPT_TIMEOUT, 3600L);
222  }
223 
224  // follow any Location: header that the server sends as part of
225  // an HTTP header (#113275)
226  SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
227  // 3 redirects seem to be too few in some cases (bnc #465532)
228  SET_OPTION(CURLOPT_MAXREDIRS, 6L);
229 
230  if ( _url.getScheme() == "https" )
231  {
232 #if CURLVERSION_AT_LEAST(7,19,4)
233  // restrict following of redirections from https to https only
234  SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
235 #endif
236 
239  {
241  }
242 
244  {
245  SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
246  }
247  if( ! _settings.clientKeyPath().empty() )
248  {
249  SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
250  }
251 
252 #ifdef CURLSSLOPT_ALLOW_BEAST
253  // see bnc#779177
254  ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
255  if ( ret != 0 ) {
256  disconnectFrom();
258  }
259 #endif
260  SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
261  SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
262  // bnc#903405 - POODLE: libzypp should only talk TLS
263  SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
264  }
265 
266  SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
267 
268  /* Fixes bsc#1174011 "auth=basic ignored in some cases"
269  * We should proactively add the password to the request if basic auth is configured
270  * and a password is available in the credentials but not in the URL.
271  *
272  * We will be a bit paranoid here and require that the URL has a user embedded, otherwise we go the default route
273  * and ask the server first about the auth method
274  */
275  if ( _settings.authType() == "basic"
276  && _settings.username().size()
277  && !_settings.password().size() ) {
278 
279  CredentialManager cm(CredManagerOptions(ZConfig::instance().repoManagerRoot()));
280  const auto cred = cm.getCred( _url );
281  if ( cred && cred->valid() ) {
282  if ( !_settings.username().size() )
283  _settings.setUsername(cred->username());
284  _settings.setPassword(cred->password());
285  }
286  }
287 
288  /*---------------------------------------------------------------*
289  CURLOPT_USERPWD: [user name]:[password]
290 
291  Url::username/password -> CURLOPT_USERPWD
292  If not provided, anonymous FTP identification
293  *---------------------------------------------------------------*/
294 
295  if ( _settings.userPassword().size() )
296  {
297  SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
298  std::string use_auth = _settings.authType();
299  if (use_auth.empty())
300  use_auth = "digest,basic"; // our default
301  long auth = CurlAuthData::auth_type_str2long(use_auth);
302  if( auth != CURLAUTH_NONE)
303  {
304  DBG << "Enabling HTTP authentication methods: " << use_auth
305  << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
306  SET_OPTION(CURLOPT_HTTPAUTH, auth);
307  }
308  }
309 
310  if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
311  {
312  DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
313  SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
314  SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
315  /*---------------------------------------------------------------*
316  * CURLOPT_PROXYUSERPWD: [user name]:[password]
317  *
318  * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
319  * If not provided, $HOME/.curlrc is evaluated
320  *---------------------------------------------------------------*/
321 
322  std::string proxyuserpwd = _settings.proxyUserPassword();
323 
324  if ( proxyuserpwd.empty() )
325  {
326  CurlConfig curlconf;
327  CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
328  if ( curlconf.proxyuserpwd.empty() )
329  DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
330  else
331  {
332  proxyuserpwd = curlconf.proxyuserpwd;
333  DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
334  }
335  }
336  else
337  {
338  DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
339  }
340 
341  if ( ! proxyuserpwd.empty() )
342  {
343  SET_OPTION(CURLOPT_PROXYUSERPWD, curlUnEscape( proxyuserpwd ).c_str());
344  }
345  }
346 #if CURLVERSION_AT_LEAST(7,19,4)
347  else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
348  {
349  // Explicitly disabled in URL (see fillSettingsFromUrl()).
350  // This should also prevent libcurl from looking into the environment.
351  DBG << "Proxy: explicitly NOPROXY" << endl;
352  SET_OPTION(CURLOPT_NOPROXY, "*");
353  }
354 #endif
355  else
356  {
357  DBG << "Proxy: not explicitly set" << endl;
358  DBG << "Proxy: libcurl may look into the environment" << endl;
359  }
360 
362  if ( _settings.minDownloadSpeed() != 0 )
363  {
364  SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
365  // default to 10 seconds at low speed
366  SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
367  }
368 
369 #if CURLVERSION_AT_LEAST(7,15,5)
370  if ( _settings.maxDownloadSpeed() != 0 )
371  SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
372 #endif
373 
374  /*---------------------------------------------------------------*
375  *---------------------------------------------------------------*/
376 
379  if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
380  SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
381  else
382  MIL << "No cookies requested" << endl;
383  SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
384  SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
385  SET_OPTION(CURLOPT_NOPROGRESS, 0L);
386 
387 #if CURLVERSION_AT_LEAST(7,18,0)
388  // bnc #306272
389  SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
390 #endif
391  // append settings custom headers to curl
392  for ( const auto &header : vol_settings.headers() )
393  {
394  // MIL << "HEADER " << *it << std::endl;
395 
396  _customHeaders = curl_slist_append(_customHeaders, header.c_str());
397  if ( !_customHeaders )
399  }
400 
401  SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
402 }
403 
405 
406 
407 void MediaCurl::attachTo (bool next)
408 {
409  if ( next )
411 
412  if ( !_url.isValid() )
414 
417  {
419  }
420 
421  disconnectFrom(); // clean _curl if needed
422  _curl = curl_easy_init();
423  if ( !_curl ) {
425  }
426  try
427  {
428  setupEasy();
429  }
430  catch (Exception & ex)
431  {
432  disconnectFrom();
433  ZYPP_RETHROW(ex);
434  }
435 
436  // FIXME: need a derived class to propelly compare url's
438  setMediaSource(media);
439 }
440 
441 bool
443 {
444  return MediaHandler::checkAttachPoint( apoint, true, true);
445 }
446 
448 
450 {
451  if ( _customHeaders )
452  {
453  curl_slist_free_all(_customHeaders);
454  _customHeaders = 0L;
455  }
456 
457  if ( _curl )
458  {
459  curl_easy_cleanup( _curl );
460  _curl = NULL;
461  }
462 }
463 
465 
466 void MediaCurl::releaseFrom( const std::string & ejectDev )
467 {
468  disconnect();
469 }
470 
471 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
472 {
473  // Simply extend the URLs pathname. An 'absolute' URL path
474  // is achieved by encoding the leading '/' in an URL path:
475  // URL: ftp://user@server -> ~user
476  // URL: ftp://user@server/ -> ~user
477  // URL: ftp://user@server// -> ~user
478  // URL: ftp://user@server/%2F -> /
479  // ^- this '/' is just a separator
480  Url newurl( _url );
481  newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
482  return newurl;
483 }
484 
486 
487 void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
488 {
489  // Use absolute file name to prevent access of files outside of the
490  // hierarchy below the attach point.
491  getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
492 }
493 
495 
496 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
497 {
499 
500  Url fileurl(getFileUrl(filename));
501 
502  bool retry = false;
503 
504  do
505  {
506  try
507  {
508  doGetFileCopy(filename, target, report, expectedFileSize_r);
509  retry = false;
510  }
511  // retry with proper authentication data
512  catch (MediaUnauthorizedException & ex_r)
513  {
514  if(authenticate(ex_r.hint(), !retry))
515  retry = true;
516  else
517  {
518  report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
519  ZYPP_RETHROW(ex_r);
520  }
521  }
522  // unexpected exception
523  catch (MediaException & excpt_r)
524  {
526  if( typeid(excpt_r) == typeid( media::MediaFileNotFoundException ) ||
527  typeid(excpt_r) == typeid( media::MediaNotAFileException ) )
528  {
530  }
531  report->finish(fileurl, reason, excpt_r.asUserHistory());
532  ZYPP_RETHROW(excpt_r);
533  }
534  }
535  while (retry);
536 
537  report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
538 }
539 
541 
542 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
543 {
544  bool retry = false;
545 
546  do
547  {
548  try
549  {
550  return doGetDoesFileExist( filename );
551  }
552  // authentication problem, retry with proper authentication data
553  catch (MediaUnauthorizedException & ex_r)
554  {
555  if(authenticate(ex_r.hint(), !retry))
556  retry = true;
557  else
558  ZYPP_RETHROW(ex_r);
559  }
560  // unexpected exception
561  catch (MediaException & excpt_r)
562  {
563  ZYPP_RETHROW(excpt_r);
564  }
565  }
566  while (retry);
567 
568  return false;
569 }
570 
572 
574  CURLcode code,
575  bool timeout_reached) const
576 {
577  if ( code != 0 )
578  {
579  Url url;
580  if (filename.empty())
581  url = _url;
582  else
583  url = getFileUrl(filename);
584 
585  std::string err;
586  {
587  switch ( code )
588  {
589  case CURLE_UNSUPPORTED_PROTOCOL:
590  err = " Unsupported protocol";
591  if ( !_lastRedirect.empty() )
592  {
593  err += " or redirect (";
594  err += _lastRedirect;
595  err += ")";
596  }
597  break;
598  case CURLE_URL_MALFORMAT:
599  case CURLE_URL_MALFORMAT_USER:
600  err = " Bad URL";
601  break;
602  case CURLE_LOGIN_DENIED:
603  ZYPP_THROW(
604  MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
605  break;
606  case CURLE_HTTP_RETURNED_ERROR:
607  {
608  long httpReturnCode = 0;
609  CURLcode infoRet = curl_easy_getinfo( _curl,
610  CURLINFO_RESPONSE_CODE,
611  &httpReturnCode );
612  if ( infoRet == CURLE_OK )
613  {
614  std::string msg = "HTTP response: " + str::numstring( httpReturnCode );
615  switch ( httpReturnCode )
616  {
617  case 401:
618  {
619  std::string auth_hint = getAuthHint();
620 
621  DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
622  DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
623 
625  url, "Login failed.", _curlError, auth_hint
626  ));
627  }
628 
629  case 502: // bad gateway (bnc #1070851)
630  case 503: // service temporarily unavailable (bnc #462545)
632  case 504: // gateway timeout
634  case 403:
635  {
636  std::string msg403;
637  if ( url.getHost().find(".suse.com") != std::string::npos )
638  msg403 = _("Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
639  else if (url.asString().find("novell.com") != std::string::npos)
640  msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
642  }
643  case 404:
644  case 410:
646  }
647 
648  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
650  }
651  else
652  {
653  std::string msg = "Unable to retrieve HTTP response:";
654  DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
656  }
657  }
658  break;
659  case CURLE_FTP_COULDNT_RETR_FILE:
660 #if CURLVERSION_AT_LEAST(7,16,0)
661  case CURLE_REMOTE_FILE_NOT_FOUND:
662 #endif
663  case CURLE_FTP_ACCESS_DENIED:
664  case CURLE_TFTP_NOTFOUND:
665  err = "File not found";
667  break;
668  case CURLE_BAD_PASSWORD_ENTERED:
669  case CURLE_FTP_USER_PASSWORD_INCORRECT:
670  err = "Login failed";
671  break;
672  case CURLE_COULDNT_RESOLVE_PROXY:
673  case CURLE_COULDNT_RESOLVE_HOST:
674  case CURLE_COULDNT_CONNECT:
675  case CURLE_FTP_CANT_GET_HOST:
676  err = "Connection failed";
677  break;
678  case CURLE_WRITE_ERROR:
679  err = "Write error";
680  break;
681  case CURLE_PARTIAL_FILE:
682  case CURLE_OPERATION_TIMEDOUT:
683  timeout_reached = true; // fall though to TimeoutException
684  // fall though...
685  case CURLE_ABORTED_BY_CALLBACK:
686  if( timeout_reached )
687  {
688  err = "Timeout reached";
690  }
691  else
692  {
693  err = "User abort";
694  }
695  break;
696  case CURLE_SSL_PEER_CERTIFICATE:
697  default:
698  err = "Curl error " + str::numstring( code );
699  break;
700  }
701 
702  // uhm, no 0 code but unknown curl exception
704  }
705  }
706  else
707  {
708  // actually the code is 0, nothing happened
709  }
710 }
711 
713 
714 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
715 {
716  DBG << filename.asString() << endl;
717 
718  if(!_url.isValid())
720 
721  if(_url.getHost().empty())
723 
724  Url url(getFileUrl(filename));
725 
726  DBG << "URL: " << url.asString() << endl;
727  // Use URL without options and without username and passwd
728  // (some proxies dislike them in the URL).
729  // Curl seems to need the just scheme, hostname and a path;
730  // the rest was already passed as curl options (in attachTo).
731  Url curlUrl( clearQueryString(url) );
732 
733  //
734  // See also Bug #154197 and ftp url definition in RFC 1738:
735  // The url "ftp://user@host/foo/bar/file" contains a path,
736  // that is relative to the user's home.
737  // The url "ftp://user@host//foo/bar/file" (or also with
738  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
739  // contains an absolute path.
740  //
741  _lastRedirect.clear();
742  std::string urlBuffer( curlUrl.asString());
743  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
744  urlBuffer.c_str() );
745  if ( ret != 0 ) {
747  }
748 
749  // instead of returning no data with NOBODY, we return
750  // little data, that works with broken servers, and
751  // works for ftp as well, because retrieving only headers
752  // ftp will return always OK code ?
753  // See http://curl.haxx.se/docs/knownbugs.html #58
754  if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
756  ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
757  else
758  ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
759 
760  if ( ret != 0 ) {
761  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
762  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
763  /* yes, this is why we never got to get NOBODY working before,
764  because setting it changes this option too, and we also
765  need to reset it
766  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
767  */
768  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
770  }
771 
772  AutoFILE file { ::fopen( "/dev/null", "w" ) };
773  if ( !file ) {
774  ERR << "fopen failed for /dev/null" << endl;
775  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
776  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
777  /* yes, this is why we never got to get NOBODY working before,
778  because setting it changes this option too, and we also
779  need to reset it
780  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
781  */
782  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
783  if ( ret != 0 ) {
785  }
786  ZYPP_THROW(MediaWriteException("/dev/null"));
787  }
788 
789  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, (*file) );
790  if ( ret != 0 ) {
791  std::string err( _curlError);
792  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
793  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
794  /* yes, this is why we never got to get NOBODY working before,
795  because setting it changes this option too, and we also
796  need to reset it
797  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
798  */
799  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
800  if ( ret != 0 ) {
802  }
804  }
805 
806  CURLcode ok = curl_easy_perform( _curl );
807  MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
808 
809  // reset curl settings
810  if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
811  {
812  curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
813  if ( ret != 0 ) {
815  }
816 
817  /* yes, this is why we never got to get NOBODY working before,
818  because setting it changes this option too, and we also
819  need to reset it
820  See: http://curl.haxx.se/mail/archive-2005-07/0073.html
821  */
822  curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
823  if ( ret != 0 ) {
825  }
826 
827  }
828  else
829  {
830  // for FTP we set different options
831  curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
832  if ( ret != 0 ) {
834  }
835  }
836 
837  // as we are not having user interaction, the user can't cancel
838  // the file existence checking, a callback or timeout return code
839  // will be always a timeout.
840  try {
841  evaluateCurlCode( filename, ok, true /* timeout */);
842  }
843  catch ( const MediaFileNotFoundException &e ) {
844  // if the file did not exist then we can return false
845  return false;
846  }
847  catch ( const MediaException &e ) {
848  // some error, we are not sure about file existence, rethrw
849  ZYPP_RETHROW(e);
850  }
851  // exists
852  return ( ok == CURLE_OK );
853 }
854 
856 
857 
858 #if DETECT_DIR_INDEX
859 bool MediaCurl::detectDirIndex() const
860 {
861  if(_url.getScheme() != "http" && _url.getScheme() != "https")
862  return false;
863  //
864  // try to check the effective url and set the not_a_file flag
865  // if the url path ends with a "/", what usually means, that
866  // we've received a directory index (index.html content).
867  //
868  // Note: This may be dangerous and break file retrieving in
869  // case of some server redirections ... ?
870  //
871  bool not_a_file = false;
872  char *ptr = NULL;
873  CURLcode ret = curl_easy_getinfo( _curl,
874  CURLINFO_EFFECTIVE_URL,
875  &ptr);
876  if ( ret == CURLE_OK && ptr != NULL)
877  {
878  try
879  {
880  Url eurl( ptr);
881  std::string path( eurl.getPathName());
882  if( !path.empty() && path != "/" && *path.rbegin() == '/')
883  {
884  DBG << "Effective url ("
885  << eurl
886  << ") seems to provide the index of a directory"
887  << endl;
888  not_a_file = true;
889  }
890  }
891  catch( ... )
892  {}
893  }
894  return not_a_file;
895 }
896 #endif
897 
899 
900 void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
901 {
902  Pathname dest = target.absolutename();
903  if( assert_dir( dest.dirname() ) )
904  {
905  DBG << "assert_dir " << dest.dirname() << " failed" << endl;
906  ZYPP_THROW( MediaSystemException(getFileUrl(filename), "System error on " + dest.dirname().asString()) );
907  }
908 
909  ManagedFile destNew { target.extend( ".new.zypp.XXXXXX" ) };
910  AutoFILE file;
911  {
912  AutoFREE<char> buf { ::strdup( (*destNew).c_str() ) };
913  if( ! buf )
914  {
915  ERR << "out of memory for temp file name" << endl;
916  ZYPP_THROW(MediaSystemException(getFileUrl(filename), "out of memory for temp file name"));
917  }
918 
919  AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
920  if( tmp_fd == -1 )
921  {
922  ERR << "mkstemp failed for file '" << destNew << "'" << endl;
924  }
925  destNew = ManagedFile( (*buf), filesystem::unlink );
926 
927  file = ::fdopen( tmp_fd, "we" );
928  if ( ! file )
929  {
930  ERR << "fopen failed for file '" << destNew << "'" << endl;
932  }
933  tmp_fd.resetDispose(); // don't close it here! ::fdopen moved ownership to file
934  }
935 
936  DBG << "dest: " << dest << endl;
937  DBG << "temp: " << destNew << endl;
938 
939  // set IFMODSINCE time condition (no download if not modified)
940  if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
941  {
942  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
943  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
944  }
945  else
946  {
947  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
948  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
949  }
950  try
951  {
952  doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
953  }
954  catch (Exception &e)
955  {
956  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
957  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
958  ZYPP_RETHROW(e);
959  }
960 
961  long httpReturnCode = 0;
962  CURLcode infoRet = curl_easy_getinfo(_curl,
963  CURLINFO_RESPONSE_CODE,
964  &httpReturnCode);
965  bool modified = true;
966  if (infoRet == CURLE_OK)
967  {
968  DBG << "HTTP response: " + str::numstring(httpReturnCode);
969  if ( httpReturnCode == 304
970  || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
971  {
972  DBG << " Not modified.";
973  modified = false;
974  }
975  DBG << endl;
976  }
977  else
978  {
979  WAR << "Could not get the reponse code." << endl;
980  }
981 
982  if (modified || infoRet != CURLE_OK)
983  {
984  // apply umask
985  if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
986  {
987  ERR << "Failed to chmod file " << destNew << endl;
988  }
989 
990  file.resetDispose(); // we're going to close it manually here
991  if ( ::fclose( file ) )
992  {
993  ERR << "Fclose failed for file '" << destNew << "'" << endl;
995  }
996 
997  // move the temp file into dest
998  if ( rename( destNew, dest ) != 0 ) {
999  ERR << "Rename failed" << endl;
1001  }
1002  destNew.resetDispose(); // no more need to unlink it
1003  }
1004 
1005  DBG << "done: " << PathInfo(dest) << endl;
1006 }
1007 
1009 
1010 void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1011 {
1012  DBG << filename.asString() << endl;
1013 
1014  if(!_url.isValid())
1016 
1017  if(_url.getHost().empty())
1019 
1020  Url url(getFileUrl(filename));
1021 
1022  DBG << "URL: " << url.asString() << endl;
1023  // Use URL without options and without username and passwd
1024  // (some proxies dislike them in the URL).
1025  // Curl seems to need the just scheme, hostname and a path;
1026  // the rest was already passed as curl options (in attachTo).
1027  Url curlUrl( clearQueryString(url) );
1028 
1029  //
1030  // See also Bug #154197 and ftp url definition in RFC 1738:
1031  // The url "ftp://user@host/foo/bar/file" contains a path,
1032  // that is relative to the user's home.
1033  // The url "ftp://user@host//foo/bar/file" (or also with
1034  // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1035  // contains an absolute path.
1036  //
1037  _lastRedirect.clear();
1038  std::string urlBuffer( curlUrl.asString());
1039  CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1040  urlBuffer.c_str() );
1041  if ( ret != 0 ) {
1043  }
1044 
1045  ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1046  if ( ret != 0 ) {
1048  }
1049 
1050  // Set callback and perform.
1051  internal::ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
1052  if (!(options & OPTION_NO_REPORT_START))
1053  report->start(url, dest);
1054  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1055  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1056  }
1057 
1058  ret = curl_easy_perform( _curl );
1059 #if CURLVERSION_AT_LEAST(7,19,4)
1060  // bnc#692260: If the client sends a request with an If-Modified-Since header
1061  // with a future date for the server, the server may respond 200 sending a
1062  // zero size file.
1063  // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1064  if ( ftell(file) == 0 && ret == 0 )
1065  {
1066  long httpReturnCode = 33;
1067  if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1068  {
1069  long conditionUnmet = 33;
1070  if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1071  {
1072  WAR << "TIMECONDITION unmet - retry without." << endl;
1073  curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1074  curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1075  ret = curl_easy_perform( _curl );
1076  }
1077  }
1078  }
1079 #endif
1080 
1081  if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1082  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1083  }
1084 
1085  if ( ret != 0 )
1086  {
1087  ERR << "curl error: " << ret << ": " << _curlError
1088  << ", temp file size " << ftell(file)
1089  << " bytes." << endl;
1090 
1091  // the timeout is determined by the progress data object
1092  // which holds whether the timeout was reached or not,
1093  // otherwise it would be a user cancel
1094  try {
1095 
1096  if ( progressData.fileSizeExceeded )
1097  ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
1098 
1099  evaluateCurlCode( filename, ret, progressData.reached );
1100  }
1101  catch ( const MediaException &e ) {
1102  // some error, we are not sure about file existence, rethrw
1103  ZYPP_RETHROW(e);
1104  }
1105  }
1106 
1107 #if DETECT_DIR_INDEX
1108  if (!ret && detectDirIndex())
1109  {
1111  }
1112 #endif // DETECT_DIR_INDEX
1113 }
1114 
1116 
1117 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1118 {
1119  filesystem::DirContent content;
1120  getDirInfo( content, dirname, /*dots*/false );
1121 
1122  for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1123  Pathname filename = dirname + it->name;
1124  int res = 0;
1125 
1126  switch ( it->type ) {
1127  case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1128  case filesystem::FT_FILE:
1129  getFile( filename, 0 );
1130  break;
1131  case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1132  if ( recurse_r ) {
1133  getDir( filename, recurse_r );
1134  } else {
1135  res = assert_dir( localPath( filename ) );
1136  if ( res ) {
1137  WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1138  }
1139  }
1140  break;
1141  default:
1142  // don't provide devices, sockets, etc.
1143  break;
1144  }
1145  }
1146 }
1147 
1149 
1150 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1151  const Pathname & dirname, bool dots ) const
1152 {
1153  getDirectoryYast( retlist, dirname, dots );
1154 }
1155 
1157 
1159  const Pathname & dirname, bool dots ) const
1160 {
1161  getDirectoryYast( retlist, dirname, dots );
1162 }
1163 
1165 //
1166 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1167 {
1168  internal::ProgressData *pdata = reinterpret_cast<internal::ProgressData *>( clientp );
1169  if( pdata )
1170  {
1171  // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1172  // prevent a percentage raise while downloading a metalink file. Download
1173  // activity however is indicated by propagating the download rate (via dlnow).
1174  pdata->updateStats( 0.0, dlnow );
1175  return pdata->reportProgress();
1176  }
1177  return 0;
1178 }
1179 
1180 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1181 {
1182  internal::ProgressData *pdata = reinterpret_cast<internal::ProgressData *>( clientp );
1183  if( pdata )
1184  {
1185  // work around curl bug that gives us old data
1186  long httpReturnCode = 0;
1187  if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1188  return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1189 
1190  pdata->updateStats( dltotal, dlnow );
1191  return pdata->reportProgress();
1192  }
1193  return 0;
1194 }
1195 
1197 {
1198  internal::ProgressData *pdata = reinterpret_cast<internal::ProgressData *>(clientp);
1199  return pdata ? pdata->curl : 0;
1200 }
1201 
1203 
1204 std::string MediaCurl::getAuthHint() const
1205 {
1206  long auth_info = CURLAUTH_NONE;
1207 
1208  CURLcode infoRet =
1209  curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1210 
1211  if(infoRet == CURLE_OK)
1212  {
1213  return CurlAuthData::auth_type_long2str(auth_info);
1214  }
1215 
1216  return "";
1217 }
1218 
1223 void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
1224 {
1225  internal::ProgressData *data = reinterpret_cast<internal::ProgressData *>(clientp);
1226  if ( data ) {
1227  data->_expectedFileSize = expectedFileSize;
1228  }
1229 }
1230 
1232 
1233 bool MediaCurl::authenticate(const std::string & availAuthTypes, bool firstTry) const
1234 {
1236  CredentialManager cm(CredManagerOptions(ZConfig::instance().repoManagerRoot()));
1237  CurlAuthData_Ptr credentials;
1238 
1239  // get stored credentials
1240  AuthData_Ptr cmcred = cm.getCred(_url);
1241 
1242  if (cmcred && firstTry)
1243  {
1244  credentials.reset(new CurlAuthData(*cmcred));
1245  DBG << "got stored credentials:" << endl << *credentials << endl;
1246  }
1247  // if not found, ask user
1248  else
1249  {
1250 
1251  CurlAuthData_Ptr curlcred;
1252  curlcred.reset(new CurlAuthData());
1254 
1255  // preset the username if present in current url
1256  if (!_url.getUsername().empty() && firstTry)
1257  curlcred->setUsername(_url.getUsername());
1258  // if CM has found some credentials, preset the username from there
1259  else if (cmcred)
1260  curlcred->setUsername(cmcred->username());
1261 
1262  // indicate we have no good credentials from CM
1263  cmcred.reset();
1264 
1265  std::string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1266 
1267  // set available authentication types from the exception
1268  // might be needed in prompt
1269  curlcred->setAuthType(availAuthTypes);
1270 
1271  // ask user
1272  if (auth_report->prompt(_url, prompt_msg, *curlcred))
1273  {
1274  DBG << "callback answer: retry" << endl
1275  << "CurlAuthData: " << *curlcred << endl;
1276 
1277  if (curlcred->valid())
1278  {
1279  credentials = curlcred;
1280  // if (credentials->username() != _url.getUsername())
1281  // _url.setUsername(credentials->username());
1289  }
1290  }
1291  else
1292  {
1293  DBG << "callback answer: cancel" << endl;
1294  }
1295  }
1296 
1297  // set username and password
1298  if (credentials)
1299  {
1300  // HACK, why is this const?
1301  const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1302  const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1303 
1304  // set username and password
1305  CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1307 
1308  // set available authentication types from the exception
1309  if (credentials->authType() == CURLAUTH_NONE)
1310  credentials->setAuthType(availAuthTypes);
1311 
1312  // set auth type (seems this must be set _after_ setting the userpwd)
1313  if (credentials->authType() != CURLAUTH_NONE)
1314  {
1315  // FIXME: only overwrite if not empty?
1316  const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1317  ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1319  }
1320 
1321  if (!cmcred)
1322  {
1323  credentials->setUrl(_url);
1324  cm.addCred(*credentials);
1325  cm.save();
1326  }
1327 
1328  return true;
1329  }
1330 
1331  return false;
1332 }
1333 
1334 //need a out of line definiton, otherwise vtable is emitted for every translation unit
1336 
1337  } // namespace media
1338 } // namespace zypp
1339 //
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:528
long timeout() const
transfer timeout
void globalInitCurlOnce()
Definition: CurlHelper.cc:19
std::string authType() const
get the allowed authentication types
virtual bool checkAttachPoint(const Pathname &apoint) const override
Verify if the specified directory as attach point (root) as requires by the particular media handler ...
Definition: MediaCurl.cc:442
int assert_dir(const Pathname &path, unsigned mode)
Like &#39;mkdir -p&#39;.
Definition: PathInfo.cc:320
Interface to gettext.
std::string password() const
auth password
#define SET_OPTION_OFFT(opt, val)
Definition: MediaCurl.cc:62
#define MIL
Definition: Logger.h:79
void addHeader(std::string &&val_r)
add a header, on the form "Foo: Bar"
void setAuthType(std::string &&val_r)
set the allowed authentication types
size_t log_redirects_curl(char *ptr, size_t size, size_t nmemb, void *userdata)
Definition: CurlHelper.cc:62
const Pathname & path() const
Return current Pathname.
Definition: PathInfo.h:246
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:392
static ZConfig & instance()
Singleton ctor.
Definition: Resolver.cc:126
std::string proxyUserPassword() const
returns the proxy user and password as a user:pass string
void checkProtocol(const Url &url) const
check the url is supported by the curl library
Definition: MediaCurl.cc:120
bool authenticate(const std::string &availAuthTypes, bool firstTry) const
Definition: MediaCurl.cc:1233
Implementation class for FTP, HTTP and HTTPS MediaHandler.
Definition: MediaCurl.h:31
const char * anonymousIdHeader()
initialized only once, this gets the anonymous id from the target, which we pass in the http header ...
Definition: CurlHelper.cc:294
Pathname clientCertificatePath() const
SSL client certificate file.
virtual bool checkAttachPoint(const Pathname &apoint) const
Verify if the specified directory as attach point (root) as requires by the particular media handler ...
void setUsername(std::string &&val_r)
sets the auth username
Store and operate with byte count.
Definition: ByteCount.h:30
long maxDownloadSpeed() const
Maximum download speed (bytes per second)
std::string proxy() const
proxy host
to not add a IFMODSINCE header if target exists
Definition: MediaCurl.h:43
TransferSettings & settings()
Definition: MediaCurl.cc:107
Holds transfer setting.
void save()
Saves any unsaved credentials added via addUserCred() or addGlobalCred() methods. ...
bool verifyHostEnabled() const
Whether to verify host for ssl.
static int progressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
Callback reporting download progress.
Definition: MediaCurl.cc:1180
Pathname extend(const std::string &r) const
Append string r to the last component of the path.
Definition: Pathname.h:170
int reportProgress() const
Definition: CurlHelper.cc:454
Url clearQueryString(const Url &url)
Definition: CurlHelper.cc:358
void setAttachPoint(const Pathname &path, bool temp)
Set a new attach point.
const char * c_str() const
String representation.
Definition: Pathname.h:110
bool isUseableAttachPoint(const Pathname &path, bool mtab=true) const
Ask media manager, if the specified path is already used as attach point or if there are another atta...
static int aliveCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
Callback sending just an alive trigger to the UI, without stats (e.g.
Definition: MediaCurl.cc:1166
Pathname certificateAuthoritiesPath() const
SSL certificate authorities path ( default: /etc/ssl/certs )
AuthData_Ptr getCred(const Url &url)
Get credentials for the specified url.
std::string username() const
auth username
Headers headers() const
returns a list of all added headers
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
Definition: ManagedFile.h:27
void setConnectTimeout(long t)
set the connect timeout
virtual void setupEasy()
initializes the curl easy handle with the data from the url
Definition: MediaCurl.cc:145
Convenient building of std::string with boost::format.
Definition: String.h:249
Structure holding values of curlrc options.
Definition: CurlConfig.h:16
std::string userAgentString() const
user agent string
AutoDispose<int> calling ::close
Definition: AutoDispose.h:280
std::string _currentCookieFile
Definition: MediaCurl.h:169
virtual void getDir(const Pathname &dirname, bool recurse_r) const override
Call concrete handler to provide directory content (not recursive!) below attach point.
Definition: MediaCurl.cc:1117
const char * distributionFlavorHeader()
initialized only once, this gets the distribution flavor from the target, which we pass in the http h...
Definition: CurlHelper.cc:308
#define ERR
Definition: Logger.h:81
Url getFileUrl(const Pathname &filename) const
concatenate the attach url and the filename to a complete download url
Definition: MediaCurl.cc:471
Pathname localPath(const Pathname &pathname) const
Files provided will be available at &#39;localPath(filename)&#39;.
static void setCookieFile(const Pathname &)
Definition: MediaCurl.cc:113
virtual void releaseFrom(const std::string &ejectDev) override
Call concrete handler to release the media.
Definition: MediaCurl.cc:466
bool verifyPeerEnabled() const
Whether to verify peer for ssl.
static void resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
MediaMultiCurl needs to reset the expected filesize in case a metalink file is downloaded otherwise t...
Definition: MediaCurl.cc:1223
const std::string & hint() const
comma separated list of available authentication types
bool empty() const
Test for an empty path.
Definition: Pathname.h:114
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:400
bool detectDirIndex() const
void setPathName(const std::string &path, EEncoding eflag=zypp::url::E_DECODED)
Set the path name.
Definition: Url.cc:759
static int parseConfig(CurlConfig &config, const std::string &filename="")
Parse a curlrc file and store the result in the config structure.
Definition: CurlConfig.cc:24
int assert_file_mode(const Pathname &path, unsigned mode)
Like assert_file but enforce mode even if the file already exists.
Definition: PathInfo.cc:1155
std::string asString() const
Returns a default string representation of the Url object.
Definition: Url.cc:492
std::string getQueryParam(const std::string &param, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
Definition: Url.cc:655
Abstract base class for &#39;physical&#39; MediaHandler like MediaCD, etc.
Definition: MediaHandler.h:46
Url clearQueryString(const Url &url) const
Definition: MediaCurl.cc:102
int unlink(const Pathname &path)
Like &#39;unlink&#39;.
Definition: PathInfo.cc:653
const Url _url
Url to handle.
Definition: MediaHandler.h:111
void setMediaSource(const MediaSourceRef &ref)
Set new media source reference.
const std::string & asString() const
String representation.
Definition: Pathname.h:91
int rename(const Pathname &oldpath, const Pathname &newpath)
Like &#39;rename&#39;.
Definition: PathInfo.cc:695
Just inherits Exception to separate media exceptions.
void evaluateCurlCode(const zypp::Pathname &filename, CURLcode code, bool timeout) const
Evaluates a curl return code and throws the right MediaException filename Filename being downloaded c...
Definition: MediaCurl.cc:573
virtual void getFileCopy(const Pathname &srcFilename, const Pathname &targetFilename, const ByteCount &expectedFileSize_r) const override
Definition: MediaCurl.cc:496
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Definition: Exception.cc:91
void disconnect()
Use concrete handler to isconnect media.
long connectTimeout() const
connection timeout
Pathname dirname() const
Return all but the last component od this path.
Definition: Pathname.h:124
do not send a start ProgressReport
Definition: MediaCurl.h:45
#define WAR
Definition: Logger.h:80
TransferSettings _settings
Definition: MediaCurl.h:178
std::list< DirEntry > DirContent
Returned by readdir.
Definition: PathInfo.h:547
void getDirectoryYast(std::list< std::string > &retlist, const Pathname &dirname, bool dots=true) const
Retrieve and if available scan dirname/directory.yast.
void fillSettingsFromUrl(const Url &url, media::TransferSettings &s)
Fills the settings structure using options passed on the url for example ?timeout=x&proxy=foo.
Definition: CurlHelper.cc:110
void setTimeout(long t)
set the transfer timeout
#define _(MSG)
Definition: Gettext.h:37
std::string proxyuserpwd
Definition: CurlConfig.h:39
Pathname clientKeyPath() const
SSL client key file.
bool isValid() const
Verifies the Url.
Definition: Url.cc:484
virtual bool doGetDoesFileExist(const Pathname &filename) const
Definition: MediaCurl.cc:714
virtual void getFile(const Pathname &filename, const ByteCount &expectedFileSize_r) const override
Call concrete handler to provide file below attach point.
Definition: MediaCurl.cc:487
shared_ptr< CurlAuthData > CurlAuthData_Ptr
virtual void attachTo(bool next=false) override
Call concrete handler to attach the media.
Definition: MediaCurl.cc:407
std::string numstring(char n, int w=0)
Definition: String.h:286
virtual bool getDoesFileExist(const Pathname &filename) const override
Repeatedly calls doGetDoesFileExist() until it successfully returns, fails unexpectedly, or user cancels the operation.
Definition: MediaCurl.cc:542
void resetDispose()
Set no dispose function.
Definition: AutoDispose.h:162
Media source internally used by MediaManager and MediaHandler.
Definition: MediaSource.h:36
static std::string auth_type_long2str(long auth_type)
Converts a long of ORed CURLAUTH_* identifiers into a string of comma separated list of authenticatio...
zypp::ByteCount _expectedFileSize
Definition: CurlHelper.h:47
long minDownloadSpeed() const
Minimum download speed (bytes per second) until the connection is dropped.
curl_slist * _customHeaders
Definition: MediaCurl.h:177
bool proxyEnabled() const
proxy is enabled
shared_ptr< AuthData > AuthData_Ptr
Definition: MediaUserAuth.h:77
int rmdir(const Pathname &path)
Like &#39;rmdir&#39;.
Definition: PathInfo.cc:367
void doGetFileCopyFile(const Pathname &srcFilename, const Pathname &dest, FILE *file, callback::SendReport< DownloadProgressReport > &_report, const ByteCount &expectedFileSize_r, RequestOptions options=OPTION_NONE) const
Definition: MediaCurl.cc:1010
#define SET_OPTION(opt, val)
Definition: MediaCurl.cc:55
Pathname absolutename() const
Return this path, adding a leading &#39;/&#39; if relative.
Definition: Pathname.h:139
Base class for Exception.
Definition: Exception.h:145
Pathname attachPoint() const
Return the currently used attach point.
std::string _lastRedirect
to log/report redirections
Definition: MediaCurl.h:172
Url url() const
Url used.
Definition: MediaHandler.h:521
#define CONNECT_TIMEOUT
Definition: CurlHelper.h:22
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
Definition: Url.cc:599
std::string curlUnEscape(std::string text_r)
Definition: CurlHelper.cc:351
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
Definition: Url.cc:583
virtual void getDirInfo(std::list< std::string > &retlist, const Pathname &dirname, bool dots=true) const override
Call concrete handler to provide a content list of directory on media via retlist.
Definition: MediaCurl.cc:1150
virtual void disconnectFrom() override
Definition: MediaCurl.cc:449
static CURL * progressCallback_getcurl(void *clientp)
Definition: MediaCurl.cc:1196
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
Definition: String.h:426
static long auth_type_str2long(std::string &auth_type_str)
Converts a string of comma separated list of authetication type names into a long of ORed CURLAUTH_* ...
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
Definition: AutoDispose.h:92
void setUserAgentString(std::string &&val_r)
sets the user agent ie: "Mozilla v3"
Wrapper class for ::stat/::lstat.
Definition: PathInfo.h:220
AutoDispose<FILE*> calling ::fclose
Definition: AutoDispose.h:291
const char * agentString()
initialized only once, this gets the agent string which also includes the curl version ...
Definition: CurlHelper.cc:322
void updateStats(double dltotal=0.0, double dlnow=0.0)
Definition: CurlHelper.cc:405
static Pathname _cookieFile
Definition: MediaCurl.h:170
void fillSettingsSystemProxy(const Url &url, media::TransferSettings &s)
Reads the system proxy configuration and fills the settings structure proxy information.
Definition: CurlHelper.cc:258
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
Definition: PathInfo.h:813
std::string userPassword() const
returns the user and password as a user:pass string
std::string getAuthHint() const
Return a comma separated list of available authentication methods supported by server.
Definition: MediaCurl.cc:1204
void setPassword(std::string &&val_r)
sets the auth password
std::string proxyUsername() const
proxy auth username
Pathname createAttachPoint() const
Try to create a default / temporary attach point.
void addCred(const AuthData &cred)
Add new credentials with user callbacks.
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:1
Curl HTTP authentication data.
Definition: MediaUserAuth.h:82
int log_curl(CURL *curl, curl_infotype info, char *ptr, size_t len, void *max_lvl)
Definition: CurlHelper.cc:28
char _curlError[CURL_ERROR_SIZE]
Definition: MediaCurl.h:176
Convenience interface for handling authentication data of media user.
#define EXPLICITLY_NO_PROXY
Definition: CurlHelper.h:26
bool userMayRWX() const
Definition: PathInfo.h:353
Url manipulation class.
Definition: Url.h:87
bool headRequestsAllowed() const
whether HEAD requests are allowed
virtual void doGetFileCopy(const Pathname &srcFilename, const Pathname &targetFilename, callback::SendReport< DownloadProgressReport > &_report, const ByteCount &expectedFileSize_r, RequestOptions options=OPTION_NONE) const
Definition: MediaCurl.cc:900
int ZYPP_MEDIA_CURL_IPRESOLVE()
Definition: CurlHelper.h:86
#define DBG
Definition: Logger.h:78
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.
Definition: Url.cc:567