1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/media/MediaCurl.cc
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"
23 #include "zypp/media/MediaCurl.h"
24 #include "zypp/media/ProxyInfo.h"
25 #include "zypp/media/MediaUserAuth.h"
26 #include "zypp/media/CredentialManager.h"
27 #include "zypp/media/CurlConfig.h"
28 #include "zypp/Target.h"
29 #include "zypp/ZYppFactory.h"
30 #include "zypp/ZConfig.h"
33 #include <sys/types.h>
35 #include <sys/mount.h>
40 #define DETECT_DIR_INDEX 0
41 #define CONNECT_TIMEOUT 60
42 #define TRANSFER_TIMEOUT_MAX 60 * 60
44 #define EXPLICITLY_NO_PROXY "_none_"
46 #undef CURLVERSION_AT_LEAST
47 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
50 using namespace zypp::base;
54 inline void globalInitOnce()
56 // function-level static <=> std::call_once
57 static bool once __attribute__ ((__unused__)) = ( [] {
58 if ( curl_global_init( CURL_GLOBAL_ALL ) != 0 )
59 WAR << "curl global init failed" << endl;
63 int log_curl(CURL *curl, curl_infotype info,
64 char *ptr, size_t len, void *max_lvl)
70 case CURLINFO_TEXT: lvl = 1; pfx = "*"; break;
71 case CURLINFO_HEADER_IN: lvl = 2; pfx = "<"; break;
72 case CURLINFO_HEADER_OUT: lvl = 2; pfx = ">"; break;
75 if( lvl > 0 && max_lvl != NULL && lvl <= *((long *)max_lvl))
77 std::string msg(ptr, len);
78 std::list<std::string> lines;
79 std::list<std::string>::const_iterator line;
80 zypp::str::split(msg, std::back_inserter(lines), "\r\n");
81 for(line = lines.begin(); line != lines.end(); ++line)
83 DBG << pfx << " " << *line << endl;
89 static size_t log_redirects_curl( char *ptr, size_t size, size_t nmemb, void *userdata)
91 // INT << "got header: " << string(ptr, ptr + size*nmemb) << endl;
93 char * lstart = ptr, * lend = ptr;
95 size_t max = size * nmemb;
99 for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
101 // look for "Location"
102 if ( lstart[0] == 'L'
110 && lstart[8] == ':' )
112 std::string line { lstart, *(lend-1)=='\r' ? lend-1 : lend };
113 DBG << "redirecting to " << line << endl;
115 *reinterpret_cast<std::string *>( userdata ) = line;
120 // continue with the next line
136 ///////////////////////////////////////////////////////////////////
141 inline int getZYPP_MEDIA_CURL_IPRESOLVE()
144 if ( const char * envp = getenv( "ZYPP_MEDIA_CURL_IPRESOLVE" ) )
146 WAR << "env set: $ZYPP_MEDIA_CURL_IPRESOLVE='" << envp << "'" << endl;
147 if ( strcmp( envp, "4" ) == 0 ) ret = 4;
148 else if ( strcmp( envp, "6" ) == 0 ) ret = 6;
154 inline int ZYPP_MEDIA_CURL_IPRESOLVE()
156 static int _v = getZYPP_MEDIA_CURL_IPRESOLVE();
160 ///////////////////////////////////////////////////////////////////
167 ProgressData( CURL *_curl, time_t _timeout = 0, const Url & _url = Url(),
168 ByteCount expectedFileSize_r = 0,
169 callback::SendReport<DownloadProgressReport> *_report = nullptr )
172 , timeout( _timeout )
174 , fileSizeExceeded ( false )
176 , _expectedFileSize( expectedFileSize_r )
183 bool fileSizeExceeded;
184 callback::SendReport<DownloadProgressReport> *report;
185 ByteCount _expectedFileSize;
187 time_t _timeStart = 0; ///< Start total stats
188 time_t _timeLast = 0; ///< Start last period(~1sec)
189 time_t _timeRcv = 0; ///< Start of no-data timeout
190 time_t _timeNow = 0; ///< Now
192 double _dnlTotal = 0.0; ///< Bytes to download or 0 if unknown
193 double _dnlLast = 0.0; ///< Bytes downloaded at period start
194 double _dnlNow = 0.0; ///< Bytes downloaded now
196 int _dnlPercent= 0; ///< Percent completed or 0 if _dnlTotal is unknown
198 double _drateTotal= 0.0; ///< Download rate so far
199 double _drateLast = 0.0; ///< Download rate in last period
201 void updateStats( double dltotal = 0.0, double dlnow = 0.0 )
203 time_t now = _timeNow = time(0);
205 // If called without args (0.0), recompute based on the last values seen
206 if ( dltotal && dltotal != _dnlTotal )
209 if ( dlnow && dlnow != _dnlNow )
214 else if ( !_dnlNow && !_dnlTotal )
216 // Start time counting as soon as first data arrives.
217 // Skip the connection / redirection time at begin.
221 // init or reset if time jumps back
222 if ( !_timeStart || _timeStart > now )
223 _timeStart = _timeLast = _timeRcv = now;
227 reached = ( (now - _timeRcv) > timeout );
229 // check if the downloaded data is already bigger than what we expected
230 fileSizeExceeded = _expectedFileSize > 0 && _expectedFileSize < static_cast<ByteCount::SizeType>(_dnlNow);
234 _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
237 _drateTotal = _dnlNow / std::max( int(now - _timeStart), 1 );
239 if ( _timeLast < now )
241 _drateLast = (_dnlNow - _dnlLast) / int(now - _timeLast);
246 else if ( _timeStart == _timeLast )
247 _drateLast = _drateTotal;
250 int reportProgress() const
252 if ( fileSizeExceeded )
255 return 1; // no-data timeout
256 if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
257 return 1; // user requested abort
262 // download rate of the last period (cca 1 sec)
264 // bytes downloaded at the start of the last period
266 // seconds from the start of the download
268 // average download rate
270 // last time the progress was reported
272 // bytes downloaded at the moment the progress was last reported
274 // bytes uploaded at the moment the progress was last reported
278 ///////////////////////////////////////////////////////////////////
280 inline void escape( string & str_r,
281 const char char_r, const string & escaped_r ) {
282 for ( string::size_type pos = str_r.find( char_r );
283 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
284 str_r.replace( pos, 1, escaped_r );
288 inline string escapedPath( string path_r ) {
289 escape( path_r, ' ', "%20" );
293 inline string unEscape( string text_r ) {
294 char * tmp = curl_unescape( text_r.c_str(), 0 );
303 * Fills the settings structure using options passed on the url
304 * for example ?timeout=x&proxy=foo
306 void fillSettingsFromUrl( const Url &url, TransferSettings &s )
308 std::string param(url.getQueryParam("timeout"));
311 long num = str::strtonum<long>(param);
312 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
316 if ( ! url.getUsername().empty() )
318 s.setUsername(url.getUsername());
319 if ( url.getPassword().size() )
320 s.setPassword(url.getPassword());
324 // if there is no username, set anonymous auth
325 if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
326 s.setAnonymousAuth();
329 if ( url.getScheme() == "https" )
331 s.setVerifyPeerEnabled(false);
332 s.setVerifyHostEnabled(false);
334 std::string verify( url.getQueryParam("ssl_verify"));
335 if( verify.empty() ||
338 s.setVerifyPeerEnabled(true);
339 s.setVerifyHostEnabled(true);
341 else if( verify == "no")
343 s.setVerifyPeerEnabled(false);
344 s.setVerifyHostEnabled(false);
348 std::vector<std::string> flags;
349 std::vector<std::string>::const_iterator flag;
350 str::split( verify, std::back_inserter(flags), ",");
351 for(flag = flags.begin(); flag != flags.end(); ++flag)
354 s.setVerifyHostEnabled(true);
355 else if( *flag == "peer")
356 s.setVerifyPeerEnabled(true);
358 ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
363 Pathname ca_path( url.getQueryParam("ssl_capath") );
364 if( ! ca_path.empty())
366 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
367 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
369 s.setCertificateAuthoritiesPath(ca_path);
372 Pathname client_cert( url.getQueryParam("ssl_clientcert") );
373 if( ! client_cert.empty())
375 if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
376 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientcert file"));
378 s.setClientCertificatePath(client_cert);
380 Pathname client_key( url.getQueryParam("ssl_clientkey") );
381 if( ! client_key.empty())
383 if( !PathInfo(client_key).isFile() || !client_key.absolute())
384 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
386 s.setClientKeyPath(client_key);
389 param = url.getQueryParam( "proxy" );
390 if ( ! param.empty() )
392 if ( param == EXPLICITLY_NO_PROXY ) {
393 // Workaround TransferSettings shortcoming: With an
394 // empty proxy string, code will continue to look for
395 // valid proxy settings. So set proxy to some non-empty
396 // string, to indicate it has been explicitly disabled.
397 s.setProxy(EXPLICITLY_NO_PROXY);
398 s.setProxyEnabled(false);
401 string proxyport( url.getQueryParam( "proxyport" ) );
402 if ( ! proxyport.empty() ) {
403 param += ":" + proxyport;
406 s.setProxyEnabled(true);
410 param = url.getQueryParam( "proxyuser" );
411 if ( ! param.empty() )
413 s.setProxyUsername(param);
414 s.setProxyPassword(url.getQueryParam( "proxypass" ));
417 // HTTP authentication type
418 param = url.getQueryParam("auth");
419 if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
423 CurlAuthData::auth_type_str2long(param); // check if we know it
425 catch (MediaException & ex_r)
427 DBG << "Rethrowing as MediaUnauthorizedException.";
428 ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
430 s.setAuthType(param);
434 param = url.getQueryParam("head_requests");
435 if( !param.empty() && param == "no" )
436 s.setHeadRequestsAllowed(false);
440 * Reads the system proxy configuration and fills the settings
441 * structure proxy information
443 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
445 ProxyInfo proxy_info;
446 if ( proxy_info.useProxyFor( url ) )
448 // We must extract any 'user:pass' from the proxy url
449 // otherwise they won't make it into curl (.curlrc wins).
451 Url u( proxy_info.proxy( url ) );
452 s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
453 // don't overwrite explicit auth settings
454 if ( s.proxyUsername().empty() )
456 s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
457 s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
459 s.setProxyEnabled( true );
461 catch (...) {} // no proxy if URL is malformed
465 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
468 * initialized only once, this gets the anonymous id
469 * from the target, which we pass in the http header
471 static const char *const anonymousIdHeader()
473 // we need to add the release and identifier to the
475 // The target could be not initialized, and then this information
477 static const std::string _value(
478 str::trim( str::form(
479 "X-ZYpp-AnonymousId: %s",
480 Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
482 return _value.c_str();
486 * initialized only once, this gets the distribution flavor
487 * from the target, which we pass in the http header
489 static const char *const distributionFlavorHeader()
491 // we need to add the release and identifier to the
493 // The target could be not initialized, and then this information
495 static const std::string _value(
496 str::trim( str::form(
497 "X-ZYpp-DistributionFlavor: %s",
498 Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
500 return _value.c_str();
504 * initialized only once, this gets the agent string
505 * which also includes the curl version
507 static const char *const agentString()
509 // we need to add the release and identifier to the
511 // The target could be not initialized, and then this information
513 static const std::string _value(
515 "ZYpp %s (curl %s) %s"
517 , curl_version_info(CURLVERSION_NOW)->version
518 , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
521 return _value.c_str();
524 // we use this define to unbloat code as this C setting option
525 // and catching exception is done frequently.
526 /** \todo deprecate SET_OPTION and use the typed versions below. */
527 #define SET_OPTION(opt,val) do { \
528 ret = curl_easy_setopt ( _curl, opt, val ); \
530 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
534 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
535 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
536 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
538 MediaCurl::MediaCurl( const Url & url_r,
539 const Pathname & attach_point_hint_r )
540 : MediaHandler( url_r, attach_point_hint_r,
541 "/", // urlpath at attachpoint
542 true ), // does_download
546 _curlError[0] = '\0';
549 MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
553 if( !attachPoint().empty())
555 PathInfo ainfo(attachPoint());
556 Pathname apath(attachPoint() + "XXXXXX");
557 char *atemp = ::strdup( apath.asString().c_str());
559 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
560 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
562 WAR << "attach point " << ainfo.path()
563 << " is not useable for " << url_r.getScheme() << endl;
564 setAttachPoint("", true);
566 else if( atest != NULL)
574 Url MediaCurl::clearQueryString(const Url &url) const
577 curlUrl.setUsername( "" );
578 curlUrl.setPassword( "" );
579 curlUrl.setPathParams( "" );
580 curlUrl.setFragment( "" );
581 curlUrl.delQueryParam("cookies");
582 curlUrl.delQueryParam("proxy");
583 curlUrl.delQueryParam("proxyport");
584 curlUrl.delQueryParam("proxyuser");
585 curlUrl.delQueryParam("proxypass");
586 curlUrl.delQueryParam("ssl_capath");
587 curlUrl.delQueryParam("ssl_verify");
588 curlUrl.delQueryParam("ssl_clientcert");
589 curlUrl.delQueryParam("timeout");
590 curlUrl.delQueryParam("auth");
591 curlUrl.delQueryParam("username");
592 curlUrl.delQueryParam("password");
593 curlUrl.delQueryParam("mediahandler");
594 curlUrl.delQueryParam("credentials");
595 curlUrl.delQueryParam("head_requests");
599 TransferSettings & MediaCurl::settings()
605 void MediaCurl::setCookieFile( const Pathname &fileName )
607 _cookieFile = fileName;
610 ///////////////////////////////////////////////////////////////////
612 void MediaCurl::checkProtocol(const Url &url) const
614 curl_version_info_data *curl_info = NULL;
615 curl_info = curl_version_info(CURLVERSION_NOW);
616 // curl_info does not need any free (is static)
617 if (curl_info->protocols)
619 const char * const *proto;
620 std::string scheme( url.getScheme());
622 for(proto=curl_info->protocols; !found && *proto; ++proto)
624 if( scheme == std::string((const char *)*proto))
629 std::string msg("Unsupported protocol '");
632 ZYPP_THROW(MediaBadUrlException(_url, msg));
637 void MediaCurl::setupEasy()
640 char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
641 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
644 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
645 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
646 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
650 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
651 curl_easy_setopt(_curl, CURLOPT_HEADERDATA, &_lastRedirect);
652 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
654 ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
657 SET_OPTION(CURLOPT_FAILONERROR, 1L);
658 SET_OPTION(CURLOPT_NOSIGNAL, 1L);
660 // create non persistant settings
661 // so that we don't add headers twice
662 TransferSettings vol_settings(_settings);
664 // add custom headers for download.opensuse.org (bsc#955801)
665 if ( _url.getHost() == "download.opensuse.org" )
667 vol_settings.addHeader(anonymousIdHeader());
668 vol_settings.addHeader(distributionFlavorHeader());
670 vol_settings.addHeader("Pragma:");
672 _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
673 _settings.setConnectTimeout(CONNECT_TIMEOUT);
675 _settings.setUserAgentString(agentString());
677 // fill some settings from url query parameters
680 fillSettingsFromUrl(_url, _settings);
682 catch ( const MediaException &e )
687 // if the proxy was not set (or explicitly unset) by url, then look...
688 if ( _settings.proxy().empty() )
690 // ...at the system proxy settings
691 fillSettingsSystemProxy(_url, _settings);
695 if ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
697 switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
699 case 4: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); break;
700 case 6: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); break;
707 SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
708 // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
709 // just in case curl does not trigger its progress callback frequently
711 if ( _settings.timeout() )
713 SET_OPTION(CURLOPT_TIMEOUT, 3600L);
716 // follow any Location: header that the server sends as part of
717 // an HTTP header (#113275)
718 SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
719 // 3 redirects seem to be too few in some cases (bnc #465532)
720 SET_OPTION(CURLOPT_MAXREDIRS, 6L);
722 if ( _url.getScheme() == "https" )
724 #if CURLVERSION_AT_LEAST(7,19,4)
725 // restrict following of redirections from https to https only
726 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
728 #if CURLVERSION_AT_LEAST(7,60,0) // SLE15+
729 SET_OPTION( CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS );
732 if( _settings.verifyPeerEnabled() ||
733 _settings.verifyHostEnabled() )
735 SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
738 if( ! _settings.clientCertificatePath().empty() )
740 SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
742 if( ! _settings.clientKeyPath().empty() )
744 SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
747 #ifdef CURLSSLOPT_ALLOW_BEAST
749 ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
752 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
755 SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
756 SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
757 // bnc#903405 - POODLE: libzypp should only talk TLS
758 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
761 SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
763 /*---------------------------------------------------------------*
764 CURLOPT_USERPWD: [user name]:[password]
766 Url::username/password -> CURLOPT_USERPWD
767 If not provided, anonymous FTP identification
768 *---------------------------------------------------------------*/
770 if ( _settings.userPassword().size() )
772 SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
773 string use_auth = _settings.authType();
774 if (use_auth.empty())
775 use_auth = "digest,basic"; // our default
776 long auth = CurlAuthData::auth_type_str2long(use_auth);
777 if( auth != CURLAUTH_NONE)
779 DBG << "Enabling HTTP authentication methods: " << use_auth
780 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
781 SET_OPTION(CURLOPT_HTTPAUTH, auth);
785 if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
787 DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
788 SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
789 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
790 /*---------------------------------------------------------------*
791 * CURLOPT_PROXYUSERPWD: [user name]:[password]
793 * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
794 * If not provided, $HOME/.curlrc is evaluated
795 *---------------------------------------------------------------*/
797 string proxyuserpwd = _settings.proxyUserPassword();
799 if ( proxyuserpwd.empty() )
802 CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
803 if ( curlconf.proxyuserpwd.empty() )
804 DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
807 proxyuserpwd = curlconf.proxyuserpwd;
808 DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
813 DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
816 if ( ! proxyuserpwd.empty() )
818 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
821 #if CURLVERSION_AT_LEAST(7,19,4)
822 else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
824 // Explicitly disabled in URL (see fillSettingsFromUrl()).
825 // This should also prevent libcurl from looking into the environment.
826 DBG << "Proxy: explicitly NOPROXY" << endl;
827 SET_OPTION(CURLOPT_NOPROXY, "*");
832 DBG << "Proxy: not explicitly set" << endl;
833 DBG << "Proxy: libcurl may look into the environment" << endl;
837 if ( _settings.minDownloadSpeed() != 0 )
839 SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
840 // default to 10 seconds at low speed
841 SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
844 #if CURLVERSION_AT_LEAST(7,15,5)
845 if ( _settings.maxDownloadSpeed() != 0 )
846 SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
849 /*---------------------------------------------------------------*
850 *---------------------------------------------------------------*/
852 _currentCookieFile = _cookieFile.asString();
853 if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
854 SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
856 MIL << "No cookies requested" << endl;
857 SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
858 SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
859 SET_OPTION(CURLOPT_NOPROGRESS, 0L);
861 #if CURLVERSION_AT_LEAST(7,18,0)
863 SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
865 // append settings custom headers to curl
866 for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
867 it != vol_settings.headersEnd();
870 // MIL << "HEADER " << *it << std::endl;
872 _customHeaders = curl_slist_append(_customHeaders, it->c_str());
873 if ( !_customHeaders )
874 ZYPP_THROW(MediaCurlInitException(_url));
877 SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
880 ///////////////////////////////////////////////////////////////////
883 void MediaCurl::attachTo (bool next)
886 ZYPP_THROW(MediaNotSupportedException(_url));
888 if ( !_url.isValid() )
889 ZYPP_THROW(MediaBadUrlException(_url));
892 if( !isUseableAttachPoint( attachPoint() ) )
894 setAttachPoint( createAttachPoint(), true );
897 disconnectFrom(); // clean _curl if needed
898 _curl = curl_easy_init();
900 ZYPP_THROW(MediaCurlInitException(_url));
906 catch (Exception & ex)
912 // FIXME: need a derived class to propelly compare url's
913 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
914 setMediaSource(media);
918 MediaCurl::checkAttachPoint(const Pathname &apoint) const
920 return MediaHandler::checkAttachPoint( apoint, true, true);
923 ///////////////////////////////////////////////////////////////////
925 void MediaCurl::disconnectFrom()
927 if ( _customHeaders )
929 curl_slist_free_all(_customHeaders);
935 curl_easy_cleanup( _curl );
940 ///////////////////////////////////////////////////////////////////
942 void MediaCurl::releaseFrom( const std::string & ejectDev )
947 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
949 // Simply extend the URLs pathname. An 'absolute' URL path
950 // is achieved by encoding the leading '/' in an URL path:
951 // URL: ftp://user@server -> ~user
952 // URL: ftp://user@server/ -> ~user
953 // URL: ftp://user@server// -> ~user
954 // URL: ftp://user@server/%2F -> /
955 // ^- this '/' is just a separator
957 newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
961 ///////////////////////////////////////////////////////////////////
963 void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
965 // Use absolute file name to prevent access of files outside of the
966 // hierarchy below the attach point.
967 getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
970 ///////////////////////////////////////////////////////////////////
972 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
974 callback::SendReport<DownloadProgressReport> report;
976 Url fileurl(getFileUrl(filename));
984 doGetFileCopy(filename, target, report, expectedFileSize_r);
987 // retry with proper authentication data
988 catch (MediaUnauthorizedException & ex_r)
990 if(authenticate(ex_r.hint(), !retry))
994 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
998 // unexpected exception
999 catch (MediaException & excpt_r)
1001 media::DownloadProgressReport::Error reason = media::DownloadProgressReport::ERROR;
1002 if( typeid(excpt_r) == typeid( media::MediaFileNotFoundException ) ||
1003 typeid(excpt_r) == typeid( media::MediaNotAFileException ) )
1005 reason = media::DownloadProgressReport::NOT_FOUND;
1007 report->finish(fileurl, reason, excpt_r.asUserHistory());
1008 ZYPP_RETHROW(excpt_r);
1013 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
1016 ///////////////////////////////////////////////////////////////////
1018 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
1026 return doGetDoesFileExist( filename );
1028 // authentication problem, retry with proper authentication data
1029 catch (MediaUnauthorizedException & ex_r)
1031 if(authenticate(ex_r.hint(), !retry))
1036 // unexpected exception
1037 catch (MediaException & excpt_r)
1039 ZYPP_RETHROW(excpt_r);
1047 ///////////////////////////////////////////////////////////////////
1049 void MediaCurl::evaluateCurlCode(const Pathname &filename,
1051 bool timeout_reached) const
1056 if (filename.empty())
1059 url = getFileUrl(filename);
1065 case CURLE_UNSUPPORTED_PROTOCOL:
1066 err = " Unsupported protocol";
1067 if ( !_lastRedirect.empty() )
1069 err += " or redirect (";
1070 err += _lastRedirect;
1074 case CURLE_URL_MALFORMAT:
1075 case CURLE_URL_MALFORMAT_USER:
1078 case CURLE_LOGIN_DENIED:
1080 MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
1082 case CURLE_HTTP_RETURNED_ERROR:
1084 long httpReturnCode = 0;
1085 CURLcode infoRet = curl_easy_getinfo( _curl,
1086 CURLINFO_RESPONSE_CODE,
1088 if ( infoRet == CURLE_OK )
1090 string msg = "HTTP response: " + str::numstring( httpReturnCode );
1091 switch ( httpReturnCode )
1095 string auth_hint = getAuthHint();
1097 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1098 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1100 ZYPP_THROW(MediaUnauthorizedException(
1101 url, "Login failed.", _curlError, auth_hint
1105 case 502: // bad gateway (bnc #1070851)
1106 case 503: // service temporarily unavailable (bnc #462545)
1107 ZYPP_THROW(MediaTemporaryProblemException(url));
1108 case 504: // gateway timeout
1109 ZYPP_THROW(MediaTimeoutException(url));
1113 if ( url.getHost().find(".suse.com") != string::npos )
1114 msg403 = _("Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
1115 else if (url.asString().find("novell.com") != string::npos)
1116 msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1117 ZYPP_THROW(MediaForbiddenException(url, msg403));
1121 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1124 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1125 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1129 string msg = "Unable to retrieve HTTP response:";
1130 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1131 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1135 case CURLE_FTP_COULDNT_RETR_FILE:
1136 #if CURLVERSION_AT_LEAST(7,16,0)
1137 case CURLE_REMOTE_FILE_NOT_FOUND:
1139 case CURLE_FTP_ACCESS_DENIED:
1140 case CURLE_TFTP_NOTFOUND:
1141 err = "File not found";
1142 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1144 case CURLE_BAD_PASSWORD_ENTERED:
1145 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1146 err = "Login failed";
1148 case CURLE_COULDNT_RESOLVE_PROXY:
1149 case CURLE_COULDNT_RESOLVE_HOST:
1150 case CURLE_COULDNT_CONNECT:
1151 case CURLE_FTP_CANT_GET_HOST:
1152 err = "Connection failed";
1154 case CURLE_WRITE_ERROR:
1155 err = "Write error";
1157 case CURLE_PARTIAL_FILE:
1158 case CURLE_OPERATION_TIMEDOUT:
1159 timeout_reached = true; // fall though to TimeoutException
1161 case CURLE_ABORTED_BY_CALLBACK:
1162 if( timeout_reached )
1164 err = "Timeout reached";
1165 ZYPP_THROW(MediaTimeoutException(url));
1172 case CURLE_SSL_PEER_CERTIFICATE:
1174 err = "Curl error " + str::numstring( code );
1178 // uhm, no 0 code but unknown curl exception
1179 ZYPP_THROW(MediaCurlException(url, err, _curlError));
1184 // actually the code is 0, nothing happened
1188 ///////////////////////////////////////////////////////////////////
1190 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1192 DBG << filename.asString() << endl;
1195 ZYPP_THROW(MediaBadUrlException(_url));
1197 if(_url.getHost().empty())
1198 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1200 Url url(getFileUrl(filename));
1202 DBG << "URL: " << url.asString() << endl;
1203 // Use URL without options and without username and passwd
1204 // (some proxies dislike them in the URL).
1205 // Curl seems to need the just scheme, hostname and a path;
1206 // the rest was already passed as curl options (in attachTo).
1207 Url curlUrl( clearQueryString(url) );
1210 // See also Bug #154197 and ftp url definition in RFC 1738:
1211 // The url "ftp://user@host/foo/bar/file" contains a path,
1212 // that is relative to the user's home.
1213 // The url "ftp://user@host//foo/bar/file" (or also with
1214 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1215 // contains an absolute path.
1217 _lastRedirect.clear();
1218 string urlBuffer( curlUrl.asString());
1219 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1220 urlBuffer.c_str() );
1222 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1225 // instead of returning no data with NOBODY, we return
1226 // little data, that works with broken servers, and
1227 // works for ftp as well, because retrieving only headers
1228 // ftp will return always OK code ?
1229 // See http://curl.haxx.se/docs/knownbugs.html #58
1230 if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1231 _settings.headRequestsAllowed() )
1232 ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1234 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1237 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1238 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1239 /* yes, this is why we never got to get NOBODY working before,
1240 because setting it changes this option too, and we also
1242 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1244 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1245 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1248 AutoFILE file { ::fopen( "/dev/null", "w" ) };
1250 ERR << "fopen failed for /dev/null" << endl;
1251 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1252 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1253 /* yes, this is why we never got to get NOBODY working before,
1254 because setting it changes this option too, and we also
1256 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1258 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1260 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1262 ZYPP_THROW(MediaWriteException("/dev/null"));
1265 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, (*file) );
1267 std::string err( _curlError);
1268 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1269 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1270 /* yes, this is why we never got to get NOBODY working before,
1271 because setting it changes this option too, and we also
1273 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1275 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1277 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1279 ZYPP_THROW(MediaCurlSetOptException(url, err));
1282 CURLcode ok = curl_easy_perform( _curl );
1283 MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1285 // reset curl settings
1286 if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1288 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1290 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1293 /* yes, this is why we never got to get NOBODY working before,
1294 because setting it changes this option too, and we also
1296 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1298 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1300 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1306 // for FTP we set different options
1307 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1309 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1313 // as we are not having user interaction, the user can't cancel
1314 // the file existence checking, a callback or timeout return code
1315 // will be always a timeout.
1317 evaluateCurlCode( filename, ok, true /* timeout */);
1319 catch ( const MediaFileNotFoundException &e ) {
1320 // if the file did not exist then we can return false
1323 catch ( const MediaException &e ) {
1324 // some error, we are not sure about file existence, rethrw
1328 return ( ok == CURLE_OK );
1331 ///////////////////////////////////////////////////////////////////
1334 #if DETECT_DIR_INDEX
1335 bool MediaCurl::detectDirIndex() const
1337 if(_url.getScheme() != "http" && _url.getScheme() != "https")
1340 // try to check the effective url and set the not_a_file flag
1341 // if the url path ends with a "/", what usually means, that
1342 // we've received a directory index (index.html content).
1344 // Note: This may be dangerous and break file retrieving in
1345 // case of some server redirections ... ?
1347 bool not_a_file = false;
1349 CURLcode ret = curl_easy_getinfo( _curl,
1350 CURLINFO_EFFECTIVE_URL,
1352 if ( ret == CURLE_OK && ptr != NULL)
1357 std::string path( eurl.getPathName());
1358 if( !path.empty() && path != "/" && *path.rbegin() == '/')
1360 DBG << "Effective url ("
1362 << ") seems to provide the index of a directory"
1374 ///////////////////////////////////////////////////////////////////
1376 void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1378 Pathname dest = target.absolutename();
1379 if( assert_dir( dest.dirname() ) )
1381 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1382 ZYPP_THROW( MediaSystemException(getFileUrl(filename), "System error on " + dest.dirname().asString()) );
1385 ManagedFile destNew { target.extend( ".new.zypp.XXXXXX" ) };
1388 AutoFREE<char> buf { ::strdup( (*destNew).c_str() ) };
1391 ERR << "out of memory for temp file name" << endl;
1392 ZYPP_THROW(MediaSystemException(getFileUrl(filename), "out of memory for temp file name"));
1395 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1398 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1399 ZYPP_THROW(MediaWriteException(destNew));
1401 destNew = ManagedFile( (*buf), filesystem::unlink );
1403 file = ::fdopen( tmp_fd, "we" );
1406 ERR << "fopen failed for file '" << destNew << "'" << endl;
1407 ZYPP_THROW(MediaWriteException(destNew));
1409 tmp_fd.resetDispose(); // don't close it here! ::fdopen moved ownership to file
1412 DBG << "dest: " << dest << endl;
1413 DBG << "temp: " << destNew << endl;
1415 // set IFMODSINCE time condition (no download if not modified)
1416 if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1418 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1419 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1423 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1424 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1428 doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
1430 catch (Exception &e)
1432 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1433 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1437 long httpReturnCode = 0;
1438 CURLcode infoRet = curl_easy_getinfo(_curl,
1439 CURLINFO_RESPONSE_CODE,
1441 bool modified = true;
1442 if (infoRet == CURLE_OK)
1444 DBG << "HTTP response: " + str::numstring(httpReturnCode);
1445 if ( httpReturnCode == 304
1446 || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1448 DBG << " Not modified.";
1455 WAR << "Could not get the reponse code." << endl;
1458 if (modified || infoRet != CURLE_OK)
1461 if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1463 ERR << "Failed to chmod file " << destNew << endl;
1466 file.resetDispose(); // we're going to close it manually here
1467 if ( ::fclose( file ) )
1469 ERR << "Fclose failed for file '" << destNew << "'" << endl;
1470 ZYPP_THROW(MediaWriteException(destNew));
1473 // move the temp file into dest
1474 if ( rename( destNew, dest ) != 0 ) {
1475 ERR << "Rename failed" << endl;
1476 ZYPP_THROW(MediaWriteException(dest));
1478 destNew.resetDispose(); // no more need to unlink it
1481 DBG << "done: " << PathInfo(dest) << endl;
1484 ///////////////////////////////////////////////////////////////////
1486 void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1488 DBG << filename.asString() << endl;
1491 ZYPP_THROW(MediaBadUrlException(_url));
1493 if(_url.getHost().empty())
1494 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1496 Url url(getFileUrl(filename));
1498 DBG << "URL: " << url.asString() << endl;
1499 // Use URL without options and without username and passwd
1500 // (some proxies dislike them in the URL).
1501 // Curl seems to need the just scheme, hostname and a path;
1502 // the rest was already passed as curl options (in attachTo).
1503 Url curlUrl( clearQueryString(url) );
1506 // See also Bug #154197 and ftp url definition in RFC 1738:
1507 // The url "ftp://user@host/foo/bar/file" contains a path,
1508 // that is relative to the user's home.
1509 // The url "ftp://user@host//foo/bar/file" (or also with
1510 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1511 // contains an absolute path.
1513 _lastRedirect.clear();
1514 string urlBuffer( curlUrl.asString());
1515 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1516 urlBuffer.c_str() );
1518 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1521 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1523 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1526 // Set callback and perform.
1527 ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
1528 if (!(options & OPTION_NO_REPORT_START))
1529 report->start(url, dest);
1530 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1531 WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1534 ret = curl_easy_perform( _curl );
1535 #if CURLVERSION_AT_LEAST(7,19,4)
1536 // bnc#692260: If the client sends a request with an If-Modified-Since header
1537 // with a future date for the server, the server may respond 200 sending a
1539 // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1540 if ( ftell(file) == 0 && ret == 0 )
1542 long httpReturnCode = 33;
1543 if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1545 long conditionUnmet = 33;
1546 if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1548 WAR << "TIMECONDITION unmet - retry without." << endl;
1549 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1550 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1551 ret = curl_easy_perform( _curl );
1557 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1558 WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1563 ERR << "curl error: " << ret << ": " << _curlError
1564 << ", temp file size " << ftell(file)
1565 << " bytes." << endl;
1567 // the timeout is determined by the progress data object
1568 // which holds whether the timeout was reached or not,
1569 // otherwise it would be a user cancel
1572 if ( progressData.fileSizeExceeded )
1573 ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
1575 evaluateCurlCode( filename, ret, progressData.reached );
1577 catch ( const MediaException &e ) {
1578 // some error, we are not sure about file existence, rethrw
1583 #if DETECT_DIR_INDEX
1584 if (!ret && detectDirIndex())
1586 ZYPP_THROW(MediaNotAFileException(_url, filename));
1588 #endif // DETECT_DIR_INDEX
1591 ///////////////////////////////////////////////////////////////////
1593 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1595 filesystem::DirContent content;
1596 getDirInfo( content, dirname, /*dots*/false );
1598 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1599 Pathname filename = dirname + it->name;
1602 switch ( it->type ) {
1603 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1604 case filesystem::FT_FILE:
1605 getFile( filename, 0 );
1607 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1609 getDir( filename, recurse_r );
1611 res = assert_dir( localPath( filename ) );
1613 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1618 // don't provide devices, sockets, etc.
1624 ///////////////////////////////////////////////////////////////////
1626 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1627 const Pathname & dirname, bool dots ) const
1629 getDirectoryYast( retlist, dirname, dots );
1632 ///////////////////////////////////////////////////////////////////
1634 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1635 const Pathname & dirname, bool dots ) const
1637 getDirectoryYast( retlist, dirname, dots );
1640 ///////////////////////////////////////////////////////////////////
1642 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1644 ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1647 // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1648 // prevent a percentage raise while downloading a metalink file. Download
1649 // activity however is indicated by propagating the download rate (via dlnow).
1650 pdata->updateStats( 0.0, dlnow );
1651 return pdata->reportProgress();
1656 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1658 ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1661 // work around curl bug that gives us old data
1662 long httpReturnCode = 0;
1663 if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1664 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1666 pdata->updateStats( dltotal, dlnow );
1667 return pdata->reportProgress();
1672 CURL *MediaCurl::progressCallback_getcurl( void *clientp )
1674 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1675 return pdata ? pdata->curl : 0;
1678 ///////////////////////////////////////////////////////////////////
1680 string MediaCurl::getAuthHint() const
1682 long auth_info = CURLAUTH_NONE;
1685 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1687 if(infoRet == CURLE_OK)
1689 return CurlAuthData::auth_type_long2str(auth_info);
1696 * MediaMultiCurl needs to reset the expected filesize in case a metalink file is downloaded
1697 * otherwise this function should not be called
1699 void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
1701 ProgressData *data = reinterpret_cast<ProgressData *>(clientp);
1703 data->_expectedFileSize = expectedFileSize;
1707 ///////////////////////////////////////////////////////////////////
1709 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1711 //! \todo need a way to pass different CredManagerOptions here
1712 CredentialManager cm(CredManagerOptions(ZConfig::instance().repoManagerRoot()));
1713 CurlAuthData_Ptr credentials;
1715 // get stored credentials
1716 AuthData_Ptr cmcred = cm.getCred(_url);
1718 if (cmcred && firstTry)
1720 credentials.reset(new CurlAuthData(*cmcred));
1721 DBG << "got stored credentials:" << endl << *credentials << endl;
1723 // if not found, ask user
1727 CurlAuthData_Ptr curlcred;
1728 curlcred.reset(new CurlAuthData());
1729 callback::SendReport<AuthenticationReport> auth_report;
1731 // preset the username if present in current url
1732 if (!_url.getUsername().empty() && firstTry)
1733 curlcred->setUsername(_url.getUsername());
1734 // if CM has found some credentials, preset the username from there
1736 curlcred->setUsername(cmcred->username());
1738 // indicate we have no good credentials from CM
1741 string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1743 // set available authentication types from the exception
1744 // might be needed in prompt
1745 curlcred->setAuthType(availAuthTypes);
1748 if (auth_report->prompt(_url, prompt_msg, *curlcred))
1750 DBG << "callback answer: retry" << endl
1751 << "CurlAuthData: " << *curlcred << endl;
1753 if (curlcred->valid())
1755 credentials = curlcred;
1756 // if (credentials->username() != _url.getUsername())
1757 // _url.setUsername(credentials->username());
1759 * \todo find a way to save the url with changed username
1760 * back to repoinfo or dont store urls with username
1761 * (and either forbid more repos with the same url and different
1762 * user, or return a set of credentials from CM and try them one
1769 DBG << "callback answer: cancel" << endl;
1773 // set username and password
1776 // HACK, why is this const?
1777 const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1778 const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1780 // set username and password
1781 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1782 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1784 // set available authentication types from the exception
1785 if (credentials->authType() == CURLAUTH_NONE)
1786 credentials->setAuthType(availAuthTypes);
1788 // set auth type (seems this must be set _after_ setting the userpwd)
1789 if (credentials->authType() != CURLAUTH_NONE)
1791 // FIXME: only overwrite if not empty?
1792 const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1793 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1794 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1799 credentials->setUrl(_url);
1800 cm.addCred(*credentials);
1810 //need a out of line definiton, otherwise vtable is emitted for every translation unit
1811 MediaCurl::Callbacks::~Callbacks() {}
1814 } // namespace media