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/thread/Once.h"
29 #include "zypp/Target.h"
30 #include "zypp/ZYppFactory.h"
31 #include "zypp/ZConfig.h"
34 #include <sys/types.h>
36 #include <sys/mount.h>
41 #define DETECT_DIR_INDEX 0
42 #define CONNECT_TIMEOUT 60
43 #define TRANSFER_TIMEOUT_MAX 60 * 60
45 #define EXPLICITLY_NO_PROXY "_none_"
47 #undef CURLVERSION_AT_LEAST
48 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
51 using namespace zypp::base;
55 zypp::thread::OnceFlag g_InitOnceFlag = PTHREAD_ONCE_INIT;
56 zypp::thread::OnceFlag g_FreeOnceFlag = PTHREAD_ONCE_INIT;
58 extern "C" void _do_free_once()
60 curl_global_cleanup();
63 extern "C" void globalFreeOnce()
65 zypp::thread::callOnce(g_FreeOnceFlag, _do_free_once);
68 extern "C" void _do_init_once()
70 CURLcode ret = curl_global_init( CURL_GLOBAL_ALL );
73 WAR << "curl global init failed" << endl;
77 // register at exit handler ?
78 // this may cause trouble, because we can protect it
79 // against ourself only.
80 // if the app sets an atexit handler as well, it will
81 // cause a double free while the second of them runs.
83 //std::atexit( globalFreeOnce);
86 inline void globalInitOnce()
88 zypp::thread::callOnce(g_InitOnceFlag, _do_init_once);
91 int log_curl(CURL *curl, curl_infotype info,
92 char *ptr, size_t len, void *max_lvl)
98 case CURLINFO_TEXT: lvl = 1; pfx = "*"; break;
99 case CURLINFO_HEADER_IN: lvl = 2; pfx = "<"; break;
100 case CURLINFO_HEADER_OUT: lvl = 2; pfx = ">"; break;
103 if( lvl > 0 && max_lvl != NULL && lvl <= *((long *)max_lvl))
105 std::string msg(ptr, len);
106 std::list<std::string> lines;
107 std::list<std::string>::const_iterator line;
108 zypp::str::split(msg, std::back_inserter(lines), "\r\n");
109 for(line = lines.begin(); line != lines.end(); ++line)
111 DBG << pfx << " " << *line << endl;
119 void *ptr, size_t size, size_t nmemb, void *stream)
121 // INT << "got header: " << string((char *)ptr, ((char*)ptr) + size*nmemb) << endl;
123 char * lstart = (char *)ptr, * lend = (char *)ptr;
125 size_t max = size * nmemb;
126 while (pos + 1 < max)
129 for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
131 // look for "Location"
132 string line(lstart, lend);
133 if (line.find("Location") != string::npos)
135 DBG << "redirecting to " << line << endl;
139 // continue with the next line
155 ///////////////////////////////////////////////////////////////////
160 inline int getZYPP_MEDIA_CURL_IPRESOLVE()
163 if ( const char * envp = getenv( "ZYPP_MEDIA_CURL_IPRESOLVE" ) )
165 WAR << "env set: $ZYPP_MEDIA_CURL_IPRESOLVE='" << envp << "'" << endl;
166 if ( strcmp( envp, "4" ) == 0 ) ret = 4;
167 else if ( strcmp( envp, "6" ) == 0 ) ret = 6;
173 inline int ZYPP_MEDIA_CURL_IPRESOLVE()
175 static int _v = getZYPP_MEDIA_CURL_IPRESOLVE();
179 ///////////////////////////////////////////////////////////////////
186 ProgressData( CURL *_curl, time_t _timeout = 0, const Url & _url = Url(),
187 ByteCount expectedFileSize_r = 0,
188 callback::SendReport<DownloadProgressReport> *_report = nullptr )
191 , timeout( _timeout )
193 , fileSizeExceeded ( false )
195 , _expectedFileSize( expectedFileSize_r )
202 bool fileSizeExceeded;
203 callback::SendReport<DownloadProgressReport> *report;
204 ByteCount _expectedFileSize;
206 time_t _timeStart = 0; ///< Start total stats
207 time_t _timeLast = 0; ///< Start last period(~1sec)
208 time_t _timeRcv = 0; ///< Start of no-data timeout
209 time_t _timeNow = 0; ///< Now
211 double _dnlTotal = 0.0; ///< Bytes to download or 0 if unknown
212 double _dnlLast = 0.0; ///< Bytes downloaded at period start
213 double _dnlNow = 0.0; ///< Bytes downloaded now
215 int _dnlPercent= 0; ///< Percent completed or 0 if _dnlTotal is unknown
217 double _drateTotal= 0.0; ///< Download rate so far
218 double _drateLast = 0.0; ///< Download rate in last period
220 void updateStats( double dltotal = 0.0, double dlnow = 0.0 )
222 time_t now = _timeNow = time(0);
224 // If called without args (0.0), recompute based on the last values seen
225 if ( dltotal && dltotal != _dnlTotal )
228 if ( dlnow && dlnow != _dnlNow )
233 else if ( !_dnlNow && !_dnlTotal )
235 // Start time counting as soon as first data arrives.
236 // Skip the connection / redirection time at begin.
240 // init or reset if time jumps back
241 if ( !_timeStart || _timeStart > now )
242 _timeStart = _timeLast = _timeRcv = now;
246 reached = ( (now - _timeRcv) > timeout );
248 // check if the downloaded data is already bigger than what we expected
249 fileSizeExceeded = _expectedFileSize > 0 && _expectedFileSize < static_cast<ByteCount::SizeType>(_dnlNow);
253 _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
256 _drateTotal = _dnlNow / std::max( int(now - _timeStart), 1 );
258 if ( _timeLast < now )
260 _drateLast = (_dnlNow - _dnlLast) / int(now - _timeLast);
265 else if ( _timeStart == _timeLast )
266 _drateLast = _drateTotal;
269 int reportProgress() const
271 if ( fileSizeExceeded )
274 return 1; // no-data timeout
275 if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
276 return 1; // user requested abort
281 // download rate of the last period (cca 1 sec)
283 // bytes downloaded at the start of the last period
285 // seconds from the start of the download
287 // average download rate
289 // last time the progress was reported
291 // bytes downloaded at the moment the progress was last reported
293 // bytes uploaded at the moment the progress was last reported
297 ///////////////////////////////////////////////////////////////////
299 inline void escape( string & str_r,
300 const char char_r, const string & escaped_r ) {
301 for ( string::size_type pos = str_r.find( char_r );
302 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
303 str_r.replace( pos, 1, escaped_r );
307 inline string escapedPath( string path_r ) {
308 escape( path_r, ' ', "%20" );
312 inline string unEscape( string text_r ) {
313 char * tmp = curl_unescape( text_r.c_str(), 0 );
322 * Fills the settings structure using options passed on the url
323 * for example ?timeout=x&proxy=foo
325 void fillSettingsFromUrl( const Url &url, TransferSettings &s )
327 std::string param(url.getQueryParam("timeout"));
330 long num = str::strtonum<long>(param);
331 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
335 if ( ! url.getUsername().empty() )
337 s.setUsername(url.getUsername());
338 if ( url.getPassword().size() )
339 s.setPassword(url.getPassword());
343 // if there is no username, set anonymous auth
344 if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
345 s.setAnonymousAuth();
348 if ( url.getScheme() == "https" )
350 s.setVerifyPeerEnabled(false);
351 s.setVerifyHostEnabled(false);
353 std::string verify( url.getQueryParam("ssl_verify"));
354 if( verify.empty() ||
357 s.setVerifyPeerEnabled(true);
358 s.setVerifyHostEnabled(true);
360 else if( verify == "no")
362 s.setVerifyPeerEnabled(false);
363 s.setVerifyHostEnabled(false);
367 std::vector<std::string> flags;
368 std::vector<std::string>::const_iterator flag;
369 str::split( verify, std::back_inserter(flags), ",");
370 for(flag = flags.begin(); flag != flags.end(); ++flag)
373 s.setVerifyHostEnabled(true);
374 else if( *flag == "peer")
375 s.setVerifyPeerEnabled(true);
377 ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
382 Pathname ca_path( url.getQueryParam("ssl_capath") );
383 if( ! ca_path.empty())
385 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
386 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
388 s.setCertificateAuthoritiesPath(ca_path);
391 Pathname client_cert( url.getQueryParam("ssl_clientcert") );
392 if( ! client_cert.empty())
394 if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
395 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientcert file"));
397 s.setClientCertificatePath(client_cert);
399 Pathname client_key( url.getQueryParam("ssl_clientkey") );
400 if( ! client_key.empty())
402 if( !PathInfo(client_key).isFile() || !client_key.absolute())
403 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
405 s.setClientKeyPath(client_key);
408 param = url.getQueryParam( "proxy" );
409 if ( ! param.empty() )
411 if ( param == EXPLICITLY_NO_PROXY ) {
412 // Workaround TransferSettings shortcoming: With an
413 // empty proxy string, code will continue to look for
414 // valid proxy settings. So set proxy to some non-empty
415 // string, to indicate it has been explicitly disabled.
416 s.setProxy(EXPLICITLY_NO_PROXY);
417 s.setProxyEnabled(false);
420 string proxyport( url.getQueryParam( "proxyport" ) );
421 if ( ! proxyport.empty() ) {
422 param += ":" + proxyport;
425 s.setProxyEnabled(true);
429 param = url.getQueryParam( "proxyuser" );
430 if ( ! param.empty() )
432 s.setProxyUsername(param);
433 s.setProxyPassword(url.getQueryParam( "proxypass" ));
436 // HTTP authentication type
437 param = url.getQueryParam("auth");
438 if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
442 CurlAuthData::auth_type_str2long(param); // check if we know it
444 catch (MediaException & ex_r)
446 DBG << "Rethrowing as MediaUnauthorizedException.";
447 ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
449 s.setAuthType(param);
453 param = url.getQueryParam("head_requests");
454 if( !param.empty() && param == "no" )
455 s.setHeadRequestsAllowed(false);
459 * Reads the system proxy configuration and fills the settings
460 * structure proxy information
462 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
464 ProxyInfo proxy_info;
465 if ( proxy_info.useProxyFor( url ) )
467 // We must extract any 'user:pass' from the proxy url
468 // otherwise they won't make it into curl (.curlrc wins).
470 Url u( proxy_info.proxy( url ) );
471 s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
472 // don't overwrite explicit auth settings
473 if ( s.proxyUsername().empty() )
475 s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
476 s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
478 s.setProxyEnabled( true );
480 catch (...) {} // no proxy if URL is malformed
484 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
487 * initialized only once, this gets the anonymous id
488 * from the target, which we pass in the http header
490 static const char *const anonymousIdHeader()
492 // we need to add the release and identifier to the
494 // The target could be not initialized, and then this information
496 static const std::string _value(
497 str::trim( str::form(
498 "X-ZYpp-AnonymousId: %s",
499 Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
501 return _value.c_str();
505 * initialized only once, this gets the distribution flavor
506 * from the target, which we pass in the http header
508 static const char *const distributionFlavorHeader()
510 // we need to add the release and identifier to the
512 // The target could be not initialized, and then this information
514 static const std::string _value(
515 str::trim( str::form(
516 "X-ZYpp-DistributionFlavor: %s",
517 Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
519 return _value.c_str();
523 * initialized only once, this gets the agent string
524 * which also includes the curl version
526 static const char *const agentString()
528 // we need to add the release and identifier to the
530 // The target could be not initialized, and then this information
532 static const std::string _value(
534 "ZYpp %s (curl %s) %s"
536 , curl_version_info(CURLVERSION_NOW)->version
537 , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
540 return _value.c_str();
543 // we use this define to unbloat code as this C setting option
544 // and catching exception is done frequently.
545 /** \todo deprecate SET_OPTION and use the typed versions below. */
546 #define SET_OPTION(opt,val) do { \
547 ret = curl_easy_setopt ( _curl, opt, val ); \
549 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
553 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
554 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
555 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
557 MediaCurl::MediaCurl( const Url & url_r,
558 const Pathname & attach_point_hint_r )
559 : MediaHandler( url_r, attach_point_hint_r,
560 "/", // urlpath at attachpoint
561 true ), // does_download
565 _curlError[0] = '\0';
568 MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
572 if( !attachPoint().empty())
574 PathInfo ainfo(attachPoint());
575 Pathname apath(attachPoint() + "XXXXXX");
576 char *atemp = ::strdup( apath.asString().c_str());
578 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
579 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
581 WAR << "attach point " << ainfo.path()
582 << " is not useable for " << url_r.getScheme() << endl;
583 setAttachPoint("", true);
585 else if( atest != NULL)
593 Url MediaCurl::clearQueryString(const Url &url) const
596 curlUrl.setUsername( "" );
597 curlUrl.setPassword( "" );
598 curlUrl.setPathParams( "" );
599 curlUrl.setFragment( "" );
600 curlUrl.delQueryParam("cookies");
601 curlUrl.delQueryParam("proxy");
602 curlUrl.delQueryParam("proxyport");
603 curlUrl.delQueryParam("proxyuser");
604 curlUrl.delQueryParam("proxypass");
605 curlUrl.delQueryParam("ssl_capath");
606 curlUrl.delQueryParam("ssl_verify");
607 curlUrl.delQueryParam("ssl_clientcert");
608 curlUrl.delQueryParam("timeout");
609 curlUrl.delQueryParam("auth");
610 curlUrl.delQueryParam("username");
611 curlUrl.delQueryParam("password");
612 curlUrl.delQueryParam("mediahandler");
613 curlUrl.delQueryParam("credentials");
614 curlUrl.delQueryParam("head_requests");
618 TransferSettings & MediaCurl::settings()
624 void MediaCurl::setCookieFile( const Pathname &fileName )
626 _cookieFile = fileName;
629 ///////////////////////////////////////////////////////////////////
631 void MediaCurl::checkProtocol(const Url &url) const
633 curl_version_info_data *curl_info = NULL;
634 curl_info = curl_version_info(CURLVERSION_NOW);
635 // curl_info does not need any free (is static)
636 if (curl_info->protocols)
638 const char * const *proto;
639 std::string scheme( url.getScheme());
641 for(proto=curl_info->protocols; !found && *proto; ++proto)
643 if( scheme == std::string((const char *)*proto))
648 std::string msg("Unsupported protocol '");
651 ZYPP_THROW(MediaBadUrlException(_url, msg));
656 void MediaCurl::setupEasy()
659 char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
660 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
663 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
664 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
665 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
669 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
670 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
672 ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
675 SET_OPTION(CURLOPT_FAILONERROR, 1L);
676 SET_OPTION(CURLOPT_NOSIGNAL, 1L);
678 // create non persistant settings
679 // so that we don't add headers twice
680 TransferSettings vol_settings(_settings);
682 // add custom headers for download.opensuse.org (bsc#955801)
683 if ( _url.getHost() == "download.opensuse.org" )
685 vol_settings.addHeader(anonymousIdHeader());
686 vol_settings.addHeader(distributionFlavorHeader());
688 vol_settings.addHeader("Pragma:");
690 _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
691 _settings.setConnectTimeout(CONNECT_TIMEOUT);
693 _settings.setUserAgentString(agentString());
695 // fill some settings from url query parameters
698 fillSettingsFromUrl(_url, _settings);
700 catch ( const MediaException &e )
705 // if the proxy was not set (or explicitly unset) by url, then look...
706 if ( _settings.proxy().empty() )
708 // ...at the system proxy settings
709 fillSettingsSystemProxy(_url, _settings);
713 if ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
715 switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
717 case 4: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); break;
718 case 6: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); break;
725 SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
726 // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
727 // just in case curl does not trigger its progress callback frequently
729 if ( _settings.timeout() )
731 SET_OPTION(CURLOPT_TIMEOUT, 3600L);
734 // follow any Location: header that the server sends as part of
735 // an HTTP header (#113275)
736 SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
737 // 3 redirects seem to be too few in some cases (bnc #465532)
738 SET_OPTION(CURLOPT_MAXREDIRS, 6L);
740 if ( _url.getScheme() == "https" )
742 #if CURLVERSION_AT_LEAST(7,19,4)
743 // restrict following of redirections from https to https only
744 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
747 if( _settings.verifyPeerEnabled() ||
748 _settings.verifyHostEnabled() )
750 SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
753 if( ! _settings.clientCertificatePath().empty() )
755 SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
757 if( ! _settings.clientKeyPath().empty() )
759 SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
762 #ifdef CURLSSLOPT_ALLOW_BEAST
764 ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
767 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
770 SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
771 SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
772 // bnc#903405 - POODLE: libzypp should only talk TLS
773 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
776 SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
778 /*---------------------------------------------------------------*
779 CURLOPT_USERPWD: [user name]:[password]
781 Url::username/password -> CURLOPT_USERPWD
782 If not provided, anonymous FTP identification
783 *---------------------------------------------------------------*/
785 if ( _settings.userPassword().size() )
787 SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
788 string use_auth = _settings.authType();
789 if (use_auth.empty())
790 use_auth = "digest,basic"; // our default
791 long auth = CurlAuthData::auth_type_str2long(use_auth);
792 if( auth != CURLAUTH_NONE)
794 DBG << "Enabling HTTP authentication methods: " << use_auth
795 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
796 SET_OPTION(CURLOPT_HTTPAUTH, auth);
800 if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
802 DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
803 SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
804 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
805 /*---------------------------------------------------------------*
806 * CURLOPT_PROXYUSERPWD: [user name]:[password]
808 * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
809 * If not provided, $HOME/.curlrc is evaluated
810 *---------------------------------------------------------------*/
812 string proxyuserpwd = _settings.proxyUserPassword();
814 if ( proxyuserpwd.empty() )
817 CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
818 if ( curlconf.proxyuserpwd.empty() )
819 DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
822 proxyuserpwd = curlconf.proxyuserpwd;
823 DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
828 DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
831 if ( ! proxyuserpwd.empty() )
833 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
836 #if CURLVERSION_AT_LEAST(7,19,4)
837 else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
839 // Explicitly disabled in URL (see fillSettingsFromUrl()).
840 // This should also prevent libcurl from looking into the environment.
841 DBG << "Proxy: explicitly NOPROXY" << endl;
842 SET_OPTION(CURLOPT_NOPROXY, "*");
847 DBG << "Proxy: not explicitly set" << endl;
848 DBG << "Proxy: libcurl may look into the environment" << endl;
852 if ( _settings.minDownloadSpeed() != 0 )
854 SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
855 // default to 10 seconds at low speed
856 SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
859 #if CURLVERSION_AT_LEAST(7,15,5)
860 if ( _settings.maxDownloadSpeed() != 0 )
861 SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
864 /*---------------------------------------------------------------*
865 *---------------------------------------------------------------*/
867 _currentCookieFile = _cookieFile.asString();
868 if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
869 SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
871 MIL << "No cookies requested" << endl;
872 SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
873 SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
874 SET_OPTION(CURLOPT_NOPROGRESS, 0L);
876 #if CURLVERSION_AT_LEAST(7,18,0)
878 SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
880 // append settings custom headers to curl
881 for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
882 it != vol_settings.headersEnd();
885 // MIL << "HEADER " << *it << std::endl;
887 _customHeaders = curl_slist_append(_customHeaders, it->c_str());
888 if ( !_customHeaders )
889 ZYPP_THROW(MediaCurlInitException(_url));
892 SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
895 ///////////////////////////////////////////////////////////////////
898 void MediaCurl::attachTo (bool next)
901 ZYPP_THROW(MediaNotSupportedException(_url));
903 if ( !_url.isValid() )
904 ZYPP_THROW(MediaBadUrlException(_url));
907 if( !isUseableAttachPoint( attachPoint() ) )
909 setAttachPoint( createAttachPoint(), true );
912 disconnectFrom(); // clean _curl if needed
913 _curl = curl_easy_init();
915 ZYPP_THROW(MediaCurlInitException(_url));
921 catch (Exception & ex)
927 // FIXME: need a derived class to propelly compare url's
928 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
929 setMediaSource(media);
933 MediaCurl::checkAttachPoint(const Pathname &apoint) const
935 return MediaHandler::checkAttachPoint( apoint, true, true);
938 ///////////////////////////////////////////////////////////////////
940 void MediaCurl::disconnectFrom()
942 if ( _customHeaders )
944 curl_slist_free_all(_customHeaders);
950 curl_easy_cleanup( _curl );
955 ///////////////////////////////////////////////////////////////////
957 void MediaCurl::releaseFrom( const std::string & ejectDev )
962 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
964 // Simply extend the URLs pathname. An 'absolute' URL path
965 // is achieved by encoding the leading '/' in an URL path:
966 // URL: ftp://user@server -> ~user
967 // URL: ftp://user@server/ -> ~user
968 // URL: ftp://user@server// -> ~user
969 // URL: ftp://user@server/%2F -> /
970 // ^- this '/' is just a separator
972 newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
976 ///////////////////////////////////////////////////////////////////
978 void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
980 // Use absolute file name to prevent access of files outside of the
981 // hierarchy below the attach point.
982 getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
985 ///////////////////////////////////////////////////////////////////
987 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
989 callback::SendReport<DownloadProgressReport> report;
991 Url fileurl(getFileUrl(filename));
999 doGetFileCopy(filename, target, report, expectedFileSize_r);
1002 // retry with proper authentication data
1003 catch (MediaUnauthorizedException & ex_r)
1005 if(authenticate(ex_r.hint(), !retry))
1009 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
1013 // unexpected exception
1014 catch (MediaException & excpt_r)
1016 media::DownloadProgressReport::Error reason = media::DownloadProgressReport::ERROR;
1017 if( typeid(excpt_r) == typeid( media::MediaFileNotFoundException ) ||
1018 typeid(excpt_r) == typeid( media::MediaNotAFileException ) )
1020 reason = media::DownloadProgressReport::NOT_FOUND;
1022 report->finish(fileurl, reason, excpt_r.asUserHistory());
1023 ZYPP_RETHROW(excpt_r);
1028 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
1031 ///////////////////////////////////////////////////////////////////
1033 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
1041 return doGetDoesFileExist( filename );
1043 // authentication problem, retry with proper authentication data
1044 catch (MediaUnauthorizedException & ex_r)
1046 if(authenticate(ex_r.hint(), !retry))
1051 // unexpected exception
1052 catch (MediaException & excpt_r)
1054 ZYPP_RETHROW(excpt_r);
1062 ///////////////////////////////////////////////////////////////////
1064 void MediaCurl::evaluateCurlCode(const Pathname &filename,
1066 bool timeout_reached) const
1071 if (filename.empty())
1074 url = getFileUrl(filename);
1080 case CURLE_UNSUPPORTED_PROTOCOL:
1081 case CURLE_URL_MALFORMAT:
1082 case CURLE_URL_MALFORMAT_USER:
1085 case CURLE_LOGIN_DENIED:
1087 MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
1089 case CURLE_HTTP_RETURNED_ERROR:
1091 long httpReturnCode = 0;
1092 CURLcode infoRet = curl_easy_getinfo( _curl,
1093 CURLINFO_RESPONSE_CODE,
1095 if ( infoRet == CURLE_OK )
1097 string msg = "HTTP response: " + str::numstring( httpReturnCode );
1098 switch ( httpReturnCode )
1102 string auth_hint = getAuthHint();
1104 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1105 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1107 ZYPP_THROW(MediaUnauthorizedException(
1108 url, "Login failed.", _curlError, auth_hint
1112 case 502: // bad gateway (bnc #1070851)
1113 case 503: // service temporarily unavailable (bnc #462545)
1114 ZYPP_THROW(MediaTemporaryProblemException(url));
1115 case 504: // gateway timeout
1116 ZYPP_THROW(MediaTimeoutException(url));
1120 if (url.asString().find("novell.com") != string::npos)
1121 msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1122 ZYPP_THROW(MediaForbiddenException(url, msg403));
1126 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1129 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1130 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1134 string msg = "Unable to retrieve HTTP response:";
1135 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1136 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1140 case CURLE_FTP_COULDNT_RETR_FILE:
1141 #if CURLVERSION_AT_LEAST(7,16,0)
1142 case CURLE_REMOTE_FILE_NOT_FOUND:
1144 case CURLE_FTP_ACCESS_DENIED:
1145 case CURLE_TFTP_NOTFOUND:
1146 err = "File not found";
1147 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1149 case CURLE_BAD_PASSWORD_ENTERED:
1150 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1151 err = "Login failed";
1153 case CURLE_COULDNT_RESOLVE_PROXY:
1154 case CURLE_COULDNT_RESOLVE_HOST:
1155 case CURLE_COULDNT_CONNECT:
1156 case CURLE_FTP_CANT_GET_HOST:
1157 err = "Connection failed";
1159 case CURLE_WRITE_ERROR:
1160 err = "Write error";
1162 case CURLE_PARTIAL_FILE:
1163 case CURLE_OPERATION_TIMEDOUT:
1164 timeout_reached = true; // fall though to TimeoutException
1166 case CURLE_ABORTED_BY_CALLBACK:
1167 if( timeout_reached )
1169 err = "Timeout reached";
1170 ZYPP_THROW(MediaTimeoutException(url));
1177 case CURLE_SSL_PEER_CERTIFICATE:
1179 err = "Curl error " + str::numstring( code );
1183 // uhm, no 0 code but unknown curl exception
1184 ZYPP_THROW(MediaCurlException(url, err, _curlError));
1189 // actually the code is 0, nothing happened
1193 ///////////////////////////////////////////////////////////////////
1195 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1197 DBG << filename.asString() << endl;
1200 ZYPP_THROW(MediaBadUrlException(_url));
1202 if(_url.getHost().empty())
1203 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1205 Url url(getFileUrl(filename));
1207 DBG << "URL: " << url.asString() << endl;
1208 // Use URL without options and without username and passwd
1209 // (some proxies dislike them in the URL).
1210 // Curl seems to need the just scheme, hostname and a path;
1211 // the rest was already passed as curl options (in attachTo).
1212 Url curlUrl( clearQueryString(url) );
1215 // See also Bug #154197 and ftp url definition in RFC 1738:
1216 // The url "ftp://user@host/foo/bar/file" contains a path,
1217 // that is relative to the user's home.
1218 // The url "ftp://user@host//foo/bar/file" (or also with
1219 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1220 // contains an absolute path.
1222 string urlBuffer( curlUrl.asString());
1223 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1224 urlBuffer.c_str() );
1226 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1229 // instead of returning no data with NOBODY, we return
1230 // little data, that works with broken servers, and
1231 // works for ftp as well, because retrieving only headers
1232 // ftp will return always OK code ?
1233 // See http://curl.haxx.se/docs/knownbugs.html #58
1234 if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1235 _settings.headRequestsAllowed() )
1236 ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1238 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1241 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1242 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1243 /* yes, this is why we never got to get NOBODY working before,
1244 because setting it changes this option too, and we also
1246 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1248 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1249 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1252 FILE *file = ::fopen( "/dev/null", "w" );
1254 ERR << "fopen failed for /dev/null" << endl;
1255 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1256 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1257 /* yes, this is why we never got to get NOBODY working before,
1258 because setting it changes this option too, and we also
1260 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1262 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1264 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1266 ZYPP_THROW(MediaWriteException("/dev/null"));
1269 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1272 std::string err( _curlError);
1273 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1274 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1275 /* yes, this is why we never got to get NOBODY working before,
1276 because setting it changes this option too, and we also
1278 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1280 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1282 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1284 ZYPP_THROW(MediaCurlSetOptException(url, err));
1287 CURLcode ok = curl_easy_perform( _curl );
1288 MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1290 // reset curl settings
1291 if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1293 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1295 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1298 /* yes, this is why we never got to get NOBODY working before,
1299 because setting it changes this option too, and we also
1301 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1303 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1305 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1311 // for FTP we set different options
1312 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1314 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1318 // if the code is not zero, close the file
1322 // as we are not having user interaction, the user can't cancel
1323 // the file existence checking, a callback or timeout return code
1324 // will be always a timeout.
1326 evaluateCurlCode( filename, ok, true /* timeout */);
1328 catch ( const MediaFileNotFoundException &e ) {
1329 // if the file did not exist then we can return false
1332 catch ( const MediaException &e ) {
1333 // some error, we are not sure about file existence, rethrw
1337 return ( ok == CURLE_OK );
1340 ///////////////////////////////////////////////////////////////////
1343 #if DETECT_DIR_INDEX
1344 bool MediaCurl::detectDirIndex() const
1346 if(_url.getScheme() != "http" && _url.getScheme() != "https")
1349 // try to check the effective url and set the not_a_file flag
1350 // if the url path ends with a "/", what usually means, that
1351 // we've received a directory index (index.html content).
1353 // Note: This may be dangerous and break file retrieving in
1354 // case of some server redirections ... ?
1356 bool not_a_file = false;
1358 CURLcode ret = curl_easy_getinfo( _curl,
1359 CURLINFO_EFFECTIVE_URL,
1361 if ( ret == CURLE_OK && ptr != NULL)
1366 std::string path( eurl.getPathName());
1367 if( !path.empty() && path != "/" && *path.rbegin() == '/')
1369 DBG << "Effective url ("
1371 << ") seems to provide the index of a directory"
1383 ///////////////////////////////////////////////////////////////////
1385 void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1387 Pathname dest = target.absolutename();
1388 if( assert_dir( dest.dirname() ) )
1390 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1391 Url url(getFileUrl(filename));
1392 ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1394 string destNew = target.asString() + ".new.zypp.XXXXXX";
1395 char *buf = ::strdup( destNew.c_str());
1398 ERR << "out of memory for temp file name" << endl;
1399 Url url(getFileUrl(filename));
1400 ZYPP_THROW(MediaSystemException(url, "out of memory for temp file name"));
1403 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1407 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1408 ZYPP_THROW(MediaWriteException(destNew));
1413 FILE *file = ::fdopen( tmp_fd, "we" );
1416 filesystem::unlink( destNew );
1417 ERR << "fopen failed for file '" << destNew << "'" << endl;
1418 ZYPP_THROW(MediaWriteException(destNew));
1421 DBG << "dest: " << dest << endl;
1422 DBG << "temp: " << destNew << endl;
1424 // set IFMODSINCE time condition (no download if not modified)
1425 if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1427 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1428 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1432 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1433 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1437 doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
1439 catch (Exception &e)
1442 filesystem::unlink( destNew );
1443 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1444 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1448 long httpReturnCode = 0;
1449 CURLcode infoRet = curl_easy_getinfo(_curl,
1450 CURLINFO_RESPONSE_CODE,
1452 bool modified = true;
1453 if (infoRet == CURLE_OK)
1455 DBG << "HTTP response: " + str::numstring(httpReturnCode);
1456 if ( httpReturnCode == 304
1457 || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1459 DBG << " Not modified.";
1466 WAR << "Could not get the reponse code." << endl;
1469 if (modified || infoRet != CURLE_OK)
1472 if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1474 ERR << "Failed to chmod file " << destNew << endl;
1476 if (::fclose( file ))
1478 ERR << "Fclose failed for file '" << destNew << "'" << endl;
1479 ZYPP_THROW(MediaWriteException(destNew));
1481 // move the temp file into dest
1482 if ( rename( destNew, dest ) != 0 ) {
1483 ERR << "Rename failed" << endl;
1484 ZYPP_THROW(MediaWriteException(dest));
1489 // close and remove the temp file
1491 filesystem::unlink( destNew );
1494 DBG << "done: " << PathInfo(dest) << endl;
1497 ///////////////////////////////////////////////////////////////////
1499 void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1501 DBG << filename.asString() << endl;
1504 ZYPP_THROW(MediaBadUrlException(_url));
1506 if(_url.getHost().empty())
1507 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1509 Url url(getFileUrl(filename));
1511 DBG << "URL: " << url.asString() << endl;
1512 // Use URL without options and without username and passwd
1513 // (some proxies dislike them in the URL).
1514 // Curl seems to need the just scheme, hostname and a path;
1515 // the rest was already passed as curl options (in attachTo).
1516 Url curlUrl( clearQueryString(url) );
1519 // See also Bug #154197 and ftp url definition in RFC 1738:
1520 // The url "ftp://user@host/foo/bar/file" contains a path,
1521 // that is relative to the user's home.
1522 // The url "ftp://user@host//foo/bar/file" (or also with
1523 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1524 // contains an absolute path.
1526 string urlBuffer( curlUrl.asString());
1527 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1528 urlBuffer.c_str() );
1530 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1533 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1535 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1538 // Set callback and perform.
1539 ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
1540 if (!(options & OPTION_NO_REPORT_START))
1541 report->start(url, dest);
1542 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1543 WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1546 ret = curl_easy_perform( _curl );
1547 #if CURLVERSION_AT_LEAST(7,19,4)
1548 // bnc#692260: If the client sends a request with an If-Modified-Since header
1549 // with a future date for the server, the server may respond 200 sending a
1551 // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1552 if ( ftell(file) == 0 && ret == 0 )
1554 long httpReturnCode = 33;
1555 if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1557 long conditionUnmet = 33;
1558 if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1560 WAR << "TIMECONDITION unmet - retry without." << endl;
1561 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1562 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1563 ret = curl_easy_perform( _curl );
1569 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1570 WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1575 ERR << "curl error: " << ret << ": " << _curlError
1576 << ", temp file size " << ftell(file)
1577 << " bytes." << endl;
1579 // the timeout is determined by the progress data object
1580 // which holds whether the timeout was reached or not,
1581 // otherwise it would be a user cancel
1584 if ( progressData.fileSizeExceeded )
1585 ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
1587 evaluateCurlCode( filename, ret, progressData.reached );
1589 catch ( const MediaException &e ) {
1590 // some error, we are not sure about file existence, rethrw
1595 #if DETECT_DIR_INDEX
1596 if (!ret && detectDirIndex())
1598 ZYPP_THROW(MediaNotAFileException(_url, filename));
1600 #endif // DETECT_DIR_INDEX
1603 ///////////////////////////////////////////////////////////////////
1605 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1607 filesystem::DirContent content;
1608 getDirInfo( content, dirname, /*dots*/false );
1610 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1611 Pathname filename = dirname + it->name;
1614 switch ( it->type ) {
1615 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1616 case filesystem::FT_FILE:
1617 getFile( filename, 0 );
1619 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1621 getDir( filename, recurse_r );
1623 res = assert_dir( localPath( filename ) );
1625 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1630 // don't provide devices, sockets, etc.
1636 ///////////////////////////////////////////////////////////////////
1638 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1639 const Pathname & dirname, bool dots ) const
1641 getDirectoryYast( retlist, dirname, dots );
1644 ///////////////////////////////////////////////////////////////////
1646 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1647 const Pathname & dirname, bool dots ) const
1649 getDirectoryYast( retlist, dirname, dots );
1652 ///////////////////////////////////////////////////////////////////
1654 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1656 ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1659 // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1660 // prevent a percentage raise while downloading a metalink file. Download
1661 // activity however is indicated by propagating the download rate (via dlnow).
1662 pdata->updateStats( 0.0, dlnow );
1663 return pdata->reportProgress();
1668 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1670 ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1673 // work around curl bug that gives us old data
1674 long httpReturnCode = 0;
1675 if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1676 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1678 pdata->updateStats( dltotal, dlnow );
1679 return pdata->reportProgress();
1684 CURL *MediaCurl::progressCallback_getcurl( void *clientp )
1686 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1687 return pdata ? pdata->curl : 0;
1690 ///////////////////////////////////////////////////////////////////
1692 string MediaCurl::getAuthHint() const
1694 long auth_info = CURLAUTH_NONE;
1697 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1699 if(infoRet == CURLE_OK)
1701 return CurlAuthData::auth_type_long2str(auth_info);
1708 * MediaMultiCurl needs to reset the expected filesize in case a metalink file is downloaded
1709 * otherwise this function should not be called
1711 void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
1713 ProgressData *data = reinterpret_cast<ProgressData *>(clientp);
1715 data->_expectedFileSize = expectedFileSize;
1719 ///////////////////////////////////////////////////////////////////
1721 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1723 //! \todo need a way to pass different CredManagerOptions here
1724 CredentialManager cm(CredManagerOptions(ZConfig::instance().repoManagerRoot()));
1725 CurlAuthData_Ptr credentials;
1727 // get stored credentials
1728 AuthData_Ptr cmcred = cm.getCred(_url);
1730 if (cmcred && firstTry)
1732 credentials.reset(new CurlAuthData(*cmcred));
1733 DBG << "got stored credentials:" << endl << *credentials << endl;
1735 // if not found, ask user
1739 CurlAuthData_Ptr curlcred;
1740 curlcred.reset(new CurlAuthData());
1741 callback::SendReport<AuthenticationReport> auth_report;
1743 // preset the username if present in current url
1744 if (!_url.getUsername().empty() && firstTry)
1745 curlcred->setUsername(_url.getUsername());
1746 // if CM has found some credentials, preset the username from there
1748 curlcred->setUsername(cmcred->username());
1750 // indicate we have no good credentials from CM
1753 string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1755 // set available authentication types from the exception
1756 // might be needed in prompt
1757 curlcred->setAuthType(availAuthTypes);
1760 if (auth_report->prompt(_url, prompt_msg, *curlcred))
1762 DBG << "callback answer: retry" << endl
1763 << "CurlAuthData: " << *curlcred << endl;
1765 if (curlcred->valid())
1767 credentials = curlcred;
1768 // if (credentials->username() != _url.getUsername())
1769 // _url.setUsername(credentials->username());
1771 * \todo find a way to save the url with changed username
1772 * back to repoinfo or dont store urls with username
1773 * (and either forbid more repos with the same url and different
1774 * user, or return a set of credentials from CM and try them one
1781 DBG << "callback answer: cancel" << endl;
1785 // set username and password
1788 // HACK, why is this const?
1789 const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1790 const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1792 // set username and password
1793 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1794 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1796 // set available authentication types from the exception
1797 if (credentials->authType() == CURLAUTH_NONE)
1798 credentials->setAuthType(availAuthTypes);
1800 // set auth type (seems this must be set _after_ setting the userpwd)
1801 if (credentials->authType() != CURLAUTH_NONE)
1803 // FIXME: only overwrite if not empty?
1804 const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1805 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1806 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1811 credentials->setUrl(_url);
1812 cm.addCred(*credentials);
1823 } // namespace media