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 callback::SendReport<DownloadProgressReport> *_report = nullptr )
190 , timeout( _timeout )
199 callback::SendReport<DownloadProgressReport> *report;
201 time_t _timeStart = 0; ///< Start total stats
202 time_t _timeLast = 0; ///< Start last period(~1sec)
203 time_t _timeRcv = 0; ///< Start of no-data timeout
204 time_t _timeNow = 0; ///< Now
206 double _dnlTotal = 0.0; ///< Bytes to download or 0 if unknown
207 double _dnlLast = 0.0; ///< Bytes downloaded at period start
208 double _dnlNow = 0.0; ///< Bytes downloaded now
210 int _dnlPercent= 0; ///< Percent completed or 0 if _dnlTotal is unknown
212 double _drateTotal= 0.0; ///< Download rate so far
213 double _drateLast = 0.0; ///< Download rate in last period
215 void updateStats( double dltotal = 0.0, double dlnow = 0.0 )
217 time_t now = _timeNow = time(0);
219 // If called without args (0.0), recompute based on the last values seen
220 if ( dltotal && dltotal != _dnlTotal )
223 if ( dlnow && dlnow != _dnlNow )
228 else if ( !_dnlNow && !_dnlTotal )
230 // Start time counting as soon as first data arrives.
231 // Skip the connection / redirection time at begin.
235 // init or reset if time jumps back
236 if ( !_timeStart || _timeStart > now )
237 _timeStart = _timeLast = _timeRcv = now;
241 reached = ( (now - _timeRcv) > timeout );
245 _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
248 _drateTotal = _dnlNow / std::max( int(now - _timeStart), 1 );
250 if ( _timeLast < now )
252 _drateLast = (_dnlNow - _dnlLast) / int(now - _timeLast);
257 else if ( _timeStart == _timeLast )
258 _drateLast = _drateTotal;
261 int reportProgress() const
264 return 1; // no-data timeout
265 if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
266 return 1; // user requested abort
271 // download rate of the last period (cca 1 sec)
273 // bytes downloaded at the start of the last period
275 // seconds from the start of the download
277 // average download rate
279 // last time the progress was reported
281 // bytes downloaded at the moment the progress was last reported
283 // bytes uploaded at the moment the progress was last reported
287 ///////////////////////////////////////////////////////////////////
289 inline void escape( string & str_r,
290 const char char_r, const string & escaped_r ) {
291 for ( string::size_type pos = str_r.find( char_r );
292 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
293 str_r.replace( pos, 1, escaped_r );
297 inline string escapedPath( string path_r ) {
298 escape( path_r, ' ', "%20" );
302 inline string unEscape( string text_r ) {
303 char * tmp = curl_unescape( text_r.c_str(), 0 );
312 * Fills the settings structure using options passed on the url
313 * for example ?timeout=x&proxy=foo
315 void fillSettingsFromUrl( const Url &url, TransferSettings &s )
317 std::string param(url.getQueryParam("timeout"));
320 long num = str::strtonum<long>(param);
321 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
325 if ( ! url.getUsername().empty() )
327 s.setUsername(url.getUsername());
328 if ( url.getPassword().size() )
329 s.setPassword(url.getPassword());
333 // if there is no username, set anonymous auth
334 if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
335 s.setAnonymousAuth();
338 if ( url.getScheme() == "https" )
340 s.setVerifyPeerEnabled(false);
341 s.setVerifyHostEnabled(false);
343 std::string verify( url.getQueryParam("ssl_verify"));
344 if( verify.empty() ||
347 s.setVerifyPeerEnabled(true);
348 s.setVerifyHostEnabled(true);
350 else if( verify == "no")
352 s.setVerifyPeerEnabled(false);
353 s.setVerifyHostEnabled(false);
357 std::vector<std::string> flags;
358 std::vector<std::string>::const_iterator flag;
359 str::split( verify, std::back_inserter(flags), ",");
360 for(flag = flags.begin(); flag != flags.end(); ++flag)
363 s.setVerifyHostEnabled(true);
364 else if( *flag == "peer")
365 s.setVerifyPeerEnabled(true);
367 ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
372 Pathname ca_path( url.getQueryParam("ssl_capath") );
373 if( ! ca_path.empty())
375 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
376 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
378 s.setCertificateAuthoritiesPath(ca_path);
381 Pathname client_cert( url.getQueryParam("ssl_clientcert") );
382 if( ! client_cert.empty())
384 if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
385 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientcert file"));
387 s.setClientCertificatePath(client_cert);
389 Pathname client_key( url.getQueryParam("ssl_clientkey") );
390 if( ! client_key.empty())
392 if( !PathInfo(client_key).isFile() || !client_key.absolute())
393 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
395 s.setClientKeyPath(client_key);
398 param = url.getQueryParam( "proxy" );
399 if ( ! param.empty() )
401 if ( param == EXPLICITLY_NO_PROXY ) {
402 // Workaround TransferSettings shortcoming: With an
403 // empty proxy string, code will continue to look for
404 // valid proxy settings. So set proxy to some non-empty
405 // string, to indicate it has been explicitly disabled.
406 s.setProxy(EXPLICITLY_NO_PROXY);
407 s.setProxyEnabled(false);
410 string proxyport( url.getQueryParam( "proxyport" ) );
411 if ( ! proxyport.empty() ) {
412 param += ":" + proxyport;
415 s.setProxyEnabled(true);
419 param = url.getQueryParam( "proxyuser" );
420 if ( ! param.empty() )
422 s.setProxyUsername(param);
423 s.setProxyPassword(url.getQueryParam( "proxypass" ));
426 // HTTP authentication type
427 param = url.getQueryParam("auth");
428 if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
432 CurlAuthData::auth_type_str2long(param); // check if we know it
434 catch (MediaException & ex_r)
436 DBG << "Rethrowing as MediaUnauthorizedException.";
437 ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
439 s.setAuthType(param);
443 param = url.getQueryParam("head_requests");
444 if( !param.empty() && param == "no" )
445 s.setHeadRequestsAllowed(false);
449 * Reads the system proxy configuration and fills the settings
450 * structure proxy information
452 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
454 ProxyInfo proxy_info;
455 if ( proxy_info.useProxyFor( url ) )
457 // We must extract any 'user:pass' from the proxy url
458 // otherwise they won't make it into curl (.curlrc wins).
460 Url u( proxy_info.proxy( url ) );
461 s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
462 // don't overwrite explicit auth settings
463 if ( s.proxyUsername().empty() )
465 s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
466 s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
468 s.setProxyEnabled( true );
470 catch (...) {} // no proxy if URL is malformed
474 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
477 * initialized only once, this gets the anonymous id
478 * from the target, which we pass in the http header
480 static const char *const anonymousIdHeader()
482 // we need to add the release and identifier to the
484 // The target could be not initialized, and then this information
486 static const std::string _value(
487 str::trim( str::form(
488 "X-ZYpp-AnonymousId: %s",
489 Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
491 return _value.c_str();
495 * initialized only once, this gets the distribution flavor
496 * from the target, which we pass in the http header
498 static const char *const distributionFlavorHeader()
500 // we need to add the release and identifier to the
502 // The target could be not initialized, and then this information
504 static const std::string _value(
505 str::trim( str::form(
506 "X-ZYpp-DistributionFlavor: %s",
507 Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
509 return _value.c_str();
513 * initialized only once, this gets the agent string
514 * which also includes the curl version
516 static const char *const agentString()
518 // we need to add the release and identifier to the
520 // The target could be not initialized, and then this information
522 static const std::string _value(
524 "ZYpp %s (curl %s) %s"
526 , curl_version_info(CURLVERSION_NOW)->version
527 , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
530 return _value.c_str();
533 // we use this define to unbloat code as this C setting option
534 // and catching exception is done frequently.
535 /** \todo deprecate SET_OPTION and use the typed versions below. */
536 #define SET_OPTION(opt,val) do { \
537 ret = curl_easy_setopt ( _curl, opt, val ); \
539 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
543 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
544 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
545 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
547 MediaCurl::MediaCurl( const Url & url_r,
548 const Pathname & attach_point_hint_r )
549 : MediaHandler( url_r, attach_point_hint_r,
550 "/", // urlpath at attachpoint
551 true ), // does_download
555 _curlError[0] = '\0';
558 MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
562 if( !attachPoint().empty())
564 PathInfo ainfo(attachPoint());
565 Pathname apath(attachPoint() + "XXXXXX");
566 char *atemp = ::strdup( apath.asString().c_str());
568 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
569 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
571 WAR << "attach point " << ainfo.path()
572 << " is not useable for " << url_r.getScheme() << endl;
573 setAttachPoint("", true);
575 else if( atest != NULL)
583 Url MediaCurl::clearQueryString(const Url &url) const
586 curlUrl.setUsername( "" );
587 curlUrl.setPassword( "" );
588 curlUrl.setPathParams( "" );
589 curlUrl.setFragment( "" );
590 curlUrl.delQueryParam("cookies");
591 curlUrl.delQueryParam("proxy");
592 curlUrl.delQueryParam("proxyport");
593 curlUrl.delQueryParam("proxyuser");
594 curlUrl.delQueryParam("proxypass");
595 curlUrl.delQueryParam("ssl_capath");
596 curlUrl.delQueryParam("ssl_verify");
597 curlUrl.delQueryParam("ssl_clientcert");
598 curlUrl.delQueryParam("timeout");
599 curlUrl.delQueryParam("auth");
600 curlUrl.delQueryParam("username");
601 curlUrl.delQueryParam("password");
602 curlUrl.delQueryParam("mediahandler");
603 curlUrl.delQueryParam("credentials");
604 curlUrl.delQueryParam("head_requests");
608 TransferSettings & MediaCurl::settings()
614 void MediaCurl::setCookieFile( const Pathname &fileName )
616 _cookieFile = fileName;
619 ///////////////////////////////////////////////////////////////////
621 void MediaCurl::checkProtocol(const Url &url) const
623 curl_version_info_data *curl_info = NULL;
624 curl_info = curl_version_info(CURLVERSION_NOW);
625 // curl_info does not need any free (is static)
626 if (curl_info->protocols)
628 const char * const *proto;
629 std::string scheme( url.getScheme());
631 for(proto=curl_info->protocols; !found && *proto; ++proto)
633 if( scheme == std::string((const char *)*proto))
638 std::string msg("Unsupported protocol '");
641 ZYPP_THROW(MediaBadUrlException(_url, msg));
646 void MediaCurl::setupEasy()
649 char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
650 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
653 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
654 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
655 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
659 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
660 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
662 ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
665 SET_OPTION(CURLOPT_FAILONERROR, 1L);
666 SET_OPTION(CURLOPT_NOSIGNAL, 1L);
668 // create non persistant settings
669 // so that we don't add headers twice
670 TransferSettings vol_settings(_settings);
672 // add custom headers for download.opensuse.org (bsc#955801)
673 if ( _url.getHost() == "download.opensuse.org" )
675 vol_settings.addHeader(anonymousIdHeader());
676 vol_settings.addHeader(distributionFlavorHeader());
678 vol_settings.addHeader("Pragma:");
680 _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
681 _settings.setConnectTimeout(CONNECT_TIMEOUT);
683 _settings.setUserAgentString(agentString());
685 // fill some settings from url query parameters
688 fillSettingsFromUrl(_url, _settings);
690 catch ( const MediaException &e )
695 // if the proxy was not set (or explicitly unset) by url, then look...
696 if ( _settings.proxy().empty() )
698 // ...at the system proxy settings
699 fillSettingsSystemProxy(_url, _settings);
703 if ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
705 switch ( env::ZYPP_MEDIA_CURL_IPRESOLVE() )
707 case 4: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); break;
708 case 6: SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); break;
715 SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
716 // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
717 // just in case curl does not trigger its progress callback frequently
719 if ( _settings.timeout() )
721 SET_OPTION(CURLOPT_TIMEOUT, 3600L);
724 // follow any Location: header that the server sends as part of
725 // an HTTP header (#113275)
726 SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
727 // 3 redirects seem to be too few in some cases (bnc #465532)
728 SET_OPTION(CURLOPT_MAXREDIRS, 6L);
730 if ( _url.getScheme() == "https" )
732 #if CURLVERSION_AT_LEAST(7,19,4)
733 // restrict following of redirections from https to https only
734 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
737 if( _settings.verifyPeerEnabled() ||
738 _settings.verifyHostEnabled() )
740 SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
743 if( ! _settings.clientCertificatePath().empty() )
745 SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
747 if( ! _settings.clientKeyPath().empty() )
749 SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
752 #ifdef CURLSSLOPT_ALLOW_BEAST
754 ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
757 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
760 SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
761 SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
762 // bnc#903405 - POODLE: libzypp should only talk TLS
763 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
766 SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
768 /*---------------------------------------------------------------*
769 CURLOPT_USERPWD: [user name]:[password]
771 Url::username/password -> CURLOPT_USERPWD
772 If not provided, anonymous FTP identification
773 *---------------------------------------------------------------*/
775 if ( _settings.userPassword().size() )
777 SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
778 string use_auth = _settings.authType();
779 if (use_auth.empty())
780 use_auth = "digest,basic"; // our default
781 long auth = CurlAuthData::auth_type_str2long(use_auth);
782 if( auth != CURLAUTH_NONE)
784 DBG << "Enabling HTTP authentication methods: " << use_auth
785 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
786 SET_OPTION(CURLOPT_HTTPAUTH, auth);
790 if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
792 DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
793 SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
794 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
795 /*---------------------------------------------------------------*
796 * CURLOPT_PROXYUSERPWD: [user name]:[password]
798 * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
799 * If not provided, $HOME/.curlrc is evaluated
800 *---------------------------------------------------------------*/
802 string proxyuserpwd = _settings.proxyUserPassword();
804 if ( proxyuserpwd.empty() )
807 CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
808 if ( curlconf.proxyuserpwd.empty() )
809 DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
812 proxyuserpwd = curlconf.proxyuserpwd;
813 DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
818 DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
821 if ( ! proxyuserpwd.empty() )
823 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
826 #if CURLVERSION_AT_LEAST(7,19,4)
827 else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
829 // Explicitly disabled in URL (see fillSettingsFromUrl()).
830 // This should also prevent libcurl from looking into the environment.
831 DBG << "Proxy: explicitly NOPROXY" << endl;
832 SET_OPTION(CURLOPT_NOPROXY, "*");
837 DBG << "Proxy: not explicitly set" << endl;
838 DBG << "Proxy: libcurl may look into the environment" << endl;
842 if ( _settings.minDownloadSpeed() != 0 )
844 SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
845 // default to 10 seconds at low speed
846 SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
849 #if CURLVERSION_AT_LEAST(7,15,5)
850 if ( _settings.maxDownloadSpeed() != 0 )
851 SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
854 /*---------------------------------------------------------------*
855 *---------------------------------------------------------------*/
857 _currentCookieFile = _cookieFile.asString();
858 if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
859 SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
861 MIL << "No cookies requested" << endl;
862 SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
863 SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
864 SET_OPTION(CURLOPT_NOPROGRESS, 0L);
866 #if CURLVERSION_AT_LEAST(7,18,0)
868 SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
870 // append settings custom headers to curl
871 for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
872 it != vol_settings.headersEnd();
875 // MIL << "HEADER " << *it << std::endl;
877 _customHeaders = curl_slist_append(_customHeaders, it->c_str());
878 if ( !_customHeaders )
879 ZYPP_THROW(MediaCurlInitException(_url));
882 SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
885 ///////////////////////////////////////////////////////////////////
888 void MediaCurl::attachTo (bool next)
891 ZYPP_THROW(MediaNotSupportedException(_url));
893 if ( !_url.isValid() )
894 ZYPP_THROW(MediaBadUrlException(_url));
897 if( !isUseableAttachPoint( attachPoint() ) )
899 setAttachPoint( createAttachPoint(), true );
902 disconnectFrom(); // clean _curl if needed
903 _curl = curl_easy_init();
905 ZYPP_THROW(MediaCurlInitException(_url));
911 catch (Exception & ex)
917 // FIXME: need a derived class to propelly compare url's
918 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
919 setMediaSource(media);
923 MediaCurl::checkAttachPoint(const Pathname &apoint) const
925 return MediaHandler::checkAttachPoint( apoint, true, true);
928 ///////////////////////////////////////////////////////////////////
930 void MediaCurl::disconnectFrom()
932 if ( _customHeaders )
934 curl_slist_free_all(_customHeaders);
940 curl_easy_cleanup( _curl );
945 ///////////////////////////////////////////////////////////////////
947 void MediaCurl::releaseFrom( const std::string & ejectDev )
952 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
954 // Simply extend the URLs pathname. An 'absolute' URL path
955 // is achieved by encoding the leading '/' in an URL path:
956 // URL: ftp://user@server -> ~user
957 // URL: ftp://user@server/ -> ~user
958 // URL: ftp://user@server// -> ~user
959 // URL: ftp://user@server/%2F -> /
960 // ^- this '/' is just a separator
962 newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
966 ///////////////////////////////////////////////////////////////////
968 void MediaCurl::getFile( const Pathname & filename ) const
970 // Use absolute file name to prevent access of files outside of the
971 // hierarchy below the attach point.
972 getFileCopy(filename, localPath(filename).absolutename());
975 ///////////////////////////////////////////////////////////////////
977 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
979 callback::SendReport<DownloadProgressReport> report;
981 Url fileurl(getFileUrl(filename));
989 doGetFileCopy(filename, target, report);
992 // retry with proper authentication data
993 catch (MediaUnauthorizedException & ex_r)
995 if(authenticate(ex_r.hint(), !retry))
999 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
1003 // unexpected exception
1004 catch (MediaException & excpt_r)
1006 // FIXME: error number fix
1007 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, 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);
1064 case CURLE_UNSUPPORTED_PROTOCOL:
1065 case CURLE_URL_MALFORMAT:
1066 case CURLE_URL_MALFORMAT_USER:
1069 case CURLE_LOGIN_DENIED:
1071 MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
1073 case CURLE_HTTP_RETURNED_ERROR:
1075 long httpReturnCode = 0;
1076 CURLcode infoRet = curl_easy_getinfo( _curl,
1077 CURLINFO_RESPONSE_CODE,
1079 if ( infoRet == CURLE_OK )
1081 string msg = "HTTP response: " + str::numstring( httpReturnCode );
1082 switch ( httpReturnCode )
1086 string auth_hint = getAuthHint();
1088 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1089 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1091 ZYPP_THROW(MediaUnauthorizedException(
1092 url, "Login failed.", _curlError, auth_hint
1096 case 503: // service temporarily unavailable (bnc #462545)
1097 ZYPP_THROW(MediaTemporaryProblemException(url));
1098 case 504: // gateway timeout
1099 ZYPP_THROW(MediaTimeoutException(url));
1103 if (url.asString().find("novell.com") != string::npos)
1104 msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1105 ZYPP_THROW(MediaForbiddenException(url, msg403));
1108 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1111 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1112 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1116 string msg = "Unable to retrieve HTTP response:";
1117 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1118 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1122 case CURLE_FTP_COULDNT_RETR_FILE:
1123 #if CURLVERSION_AT_LEAST(7,16,0)
1124 case CURLE_REMOTE_FILE_NOT_FOUND:
1126 case CURLE_FTP_ACCESS_DENIED:
1127 case CURLE_TFTP_NOTFOUND:
1128 err = "File not found";
1129 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1131 case CURLE_BAD_PASSWORD_ENTERED:
1132 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1133 err = "Login failed";
1135 case CURLE_COULDNT_RESOLVE_PROXY:
1136 case CURLE_COULDNT_RESOLVE_HOST:
1137 case CURLE_COULDNT_CONNECT:
1138 case CURLE_FTP_CANT_GET_HOST:
1139 err = "Connection failed";
1141 case CURLE_WRITE_ERROR:
1142 err = "Write error";
1144 case CURLE_PARTIAL_FILE:
1145 case CURLE_OPERATION_TIMEDOUT:
1146 timeout_reached = true; // fall though to TimeoutException
1148 case CURLE_ABORTED_BY_CALLBACK:
1149 if( timeout_reached )
1151 err = "Timeout reached";
1152 ZYPP_THROW(MediaTimeoutException(url));
1159 case CURLE_SSL_PEER_CERTIFICATE:
1161 err = "Curl error " + str::numstring( code );
1165 // uhm, no 0 code but unknown curl exception
1166 ZYPP_THROW(MediaCurlException(url, err, _curlError));
1171 // actually the code is 0, nothing happened
1175 ///////////////////////////////////////////////////////////////////
1177 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1179 DBG << filename.asString() << endl;
1182 ZYPP_THROW(MediaBadUrlException(_url));
1184 if(_url.getHost().empty())
1185 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1187 Url url(getFileUrl(filename));
1189 DBG << "URL: " << url.asString() << endl;
1190 // Use URL without options and without username and passwd
1191 // (some proxies dislike them in the URL).
1192 // Curl seems to need the just scheme, hostname and a path;
1193 // the rest was already passed as curl options (in attachTo).
1194 Url curlUrl( clearQueryString(url) );
1197 // See also Bug #154197 and ftp url definition in RFC 1738:
1198 // The url "ftp://user@host/foo/bar/file" contains a path,
1199 // that is relative to the user's home.
1200 // The url "ftp://user@host//foo/bar/file" (or also with
1201 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1202 // contains an absolute path.
1204 string urlBuffer( curlUrl.asString());
1205 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1206 urlBuffer.c_str() );
1208 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1211 // instead of returning no data with NOBODY, we return
1212 // little data, that works with broken servers, and
1213 // works for ftp as well, because retrieving only headers
1214 // ftp will return always OK code ?
1215 // See http://curl.haxx.se/docs/knownbugs.html #58
1216 if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1217 _settings.headRequestsAllowed() )
1218 ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1220 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1223 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1224 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1225 /* yes, this is why we never got to get NOBODY working before,
1226 because setting it changes this option too, and we also
1228 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1230 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1231 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1234 FILE *file = ::fopen( "/dev/null", "w" );
1236 ERR << "fopen failed for /dev/null" << endl;
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 );
1246 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1248 ZYPP_THROW(MediaWriteException("/dev/null"));
1251 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1254 std::string err( _curlError);
1255 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1256 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
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(MediaCurlSetOptException(url, err));
1269 CURLcode ok = curl_easy_perform( _curl );
1270 MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1272 // reset curl settings
1273 if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1275 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1277 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1280 /* yes, this is why we never got to get NOBODY working before,
1281 because setting it changes this option too, and we also
1283 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1285 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1287 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1293 // for FTP we set different options
1294 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1296 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1300 // if the code is not zero, close the file
1304 // as we are not having user interaction, the user can't cancel
1305 // the file existence checking, a callback or timeout return code
1306 // will be always a timeout.
1308 evaluateCurlCode( filename, ok, true /* timeout */);
1310 catch ( const MediaFileNotFoundException &e ) {
1311 // if the file did not exist then we can return false
1314 catch ( const MediaException &e ) {
1315 // some error, we are not sure about file existence, rethrw
1319 return ( ok == CURLE_OK );
1322 ///////////////////////////////////////////////////////////////////
1325 #if DETECT_DIR_INDEX
1326 bool MediaCurl::detectDirIndex() const
1328 if(_url.getScheme() != "http" && _url.getScheme() != "https")
1331 // try to check the effective url and set the not_a_file flag
1332 // if the url path ends with a "/", what usually means, that
1333 // we've received a directory index (index.html content).
1335 // Note: This may be dangerous and break file retrieving in
1336 // case of some server redirections ... ?
1338 bool not_a_file = false;
1340 CURLcode ret = curl_easy_getinfo( _curl,
1341 CURLINFO_EFFECTIVE_URL,
1343 if ( ret == CURLE_OK && ptr != NULL)
1348 std::string path( eurl.getPathName());
1349 if( !path.empty() && path != "/" && *path.rbegin() == '/')
1351 DBG << "Effective url ("
1353 << ") seems to provide the index of a directory"
1365 ///////////////////////////////////////////////////////////////////
1367 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1369 Pathname dest = target.absolutename();
1370 if( assert_dir( dest.dirname() ) )
1372 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1373 Url url(getFileUrl(filename));
1374 ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1376 string destNew = target.asString() + ".new.zypp.XXXXXX";
1377 char *buf = ::strdup( destNew.c_str());
1380 ERR << "out of memory for temp file name" << endl;
1381 Url url(getFileUrl(filename));
1382 ZYPP_THROW(MediaSystemException(url, "out of memory for temp file name"));
1385 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1389 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1390 ZYPP_THROW(MediaWriteException(destNew));
1395 FILE *file = ::fdopen( tmp_fd, "we" );
1398 filesystem::unlink( destNew );
1399 ERR << "fopen failed for file '" << destNew << "'" << endl;
1400 ZYPP_THROW(MediaWriteException(destNew));
1403 DBG << "dest: " << dest << endl;
1404 DBG << "temp: " << destNew << endl;
1406 // set IFMODSINCE time condition (no download if not modified)
1407 if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1409 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1410 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1414 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1415 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1419 doGetFileCopyFile(filename, dest, file, report, options);
1421 catch (Exception &e)
1424 filesystem::unlink( destNew );
1425 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1426 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1430 long httpReturnCode = 0;
1431 CURLcode infoRet = curl_easy_getinfo(_curl,
1432 CURLINFO_RESPONSE_CODE,
1434 bool modified = true;
1435 if (infoRet == CURLE_OK)
1437 DBG << "HTTP response: " + str::numstring(httpReturnCode);
1438 if ( httpReturnCode == 304
1439 || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1441 DBG << " Not modified.";
1448 WAR << "Could not get the reponse code." << endl;
1451 if (modified || infoRet != CURLE_OK)
1454 if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1456 ERR << "Failed to chmod file " << destNew << endl;
1458 if (::fclose( file ))
1460 ERR << "Fclose failed for file '" << destNew << "'" << endl;
1461 ZYPP_THROW(MediaWriteException(destNew));
1463 // move the temp file into dest
1464 if ( rename( destNew, dest ) != 0 ) {
1465 ERR << "Rename failed" << endl;
1466 ZYPP_THROW(MediaWriteException(dest));
1471 // close and remove the temp file
1473 filesystem::unlink( destNew );
1476 DBG << "done: " << PathInfo(dest) << endl;
1479 ///////////////////////////////////////////////////////////////////
1481 void MediaCurl::doGetFileCopyFile( const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1483 DBG << filename.asString() << endl;
1486 ZYPP_THROW(MediaBadUrlException(_url));
1488 if(_url.getHost().empty())
1489 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1491 Url url(getFileUrl(filename));
1493 DBG << "URL: " << url.asString() << endl;
1494 // Use URL without options and without username and passwd
1495 // (some proxies dislike them in the URL).
1496 // Curl seems to need the just scheme, hostname and a path;
1497 // the rest was already passed as curl options (in attachTo).
1498 Url curlUrl( clearQueryString(url) );
1501 // See also Bug #154197 and ftp url definition in RFC 1738:
1502 // The url "ftp://user@host/foo/bar/file" contains a path,
1503 // that is relative to the user's home.
1504 // The url "ftp://user@host//foo/bar/file" (or also with
1505 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1506 // contains an absolute path.
1508 string urlBuffer( curlUrl.asString());
1509 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1510 urlBuffer.c_str() );
1512 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1515 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1517 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1520 // Set callback and perform.
1521 ProgressData progressData(_curl, _settings.timeout(), url, &report);
1522 if (!(options & OPTION_NO_REPORT_START))
1523 report->start(url, dest);
1524 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1525 WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1528 ret = curl_easy_perform( _curl );
1529 #if CURLVERSION_AT_LEAST(7,19,4)
1530 // bnc#692260: If the client sends a request with an If-Modified-Since header
1531 // with a future date for the server, the server may respond 200 sending a
1533 // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1534 if ( ftell(file) == 0 && ret == 0 )
1536 long httpReturnCode = 33;
1537 if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1539 long conditionUnmet = 33;
1540 if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1542 WAR << "TIMECONDITION unmet - retry without." << endl;
1543 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1544 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1545 ret = curl_easy_perform( _curl );
1551 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1552 WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1557 ERR << "curl error: " << ret << ": " << _curlError
1558 << ", temp file size " << ftell(file)
1559 << " bytes." << endl;
1561 // the timeout is determined by the progress data object
1562 // which holds whether the timeout was reached or not,
1563 // otherwise it would be a user cancel
1565 evaluateCurlCode( filename, ret, progressData.reached);
1567 catch ( const MediaException &e ) {
1568 // some error, we are not sure about file existence, rethrw
1573 #if DETECT_DIR_INDEX
1574 if (!ret && detectDirIndex())
1576 ZYPP_THROW(MediaNotAFileException(_url, filename));
1578 #endif // DETECT_DIR_INDEX
1581 ///////////////////////////////////////////////////////////////////
1583 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1585 filesystem::DirContent content;
1586 getDirInfo( content, dirname, /*dots*/false );
1588 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1589 Pathname filename = dirname + it->name;
1592 switch ( it->type ) {
1593 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1594 case filesystem::FT_FILE:
1595 getFile( filename );
1597 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1599 getDir( filename, recurse_r );
1601 res = assert_dir( localPath( filename ) );
1603 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1608 // don't provide devices, sockets, etc.
1614 ///////////////////////////////////////////////////////////////////
1616 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1617 const Pathname & dirname, bool dots ) const
1619 getDirectoryYast( retlist, dirname, dots );
1622 ///////////////////////////////////////////////////////////////////
1624 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1625 const Pathname & dirname, bool dots ) const
1627 getDirectoryYast( retlist, dirname, dots );
1630 ///////////////////////////////////////////////////////////////////
1632 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1634 ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1637 // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1638 // prevent a percentage raise while downloading a metalink file. Download
1639 // activity however is indicated by propagating the download rate (via dlnow).
1640 pdata->updateStats( 0.0, dlnow );
1641 return pdata->reportProgress();
1646 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1648 ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1651 // work around curl bug that gives us old data
1652 long httpReturnCode = 0;
1653 if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1654 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1656 pdata->updateStats( dltotal, dlnow );
1657 return pdata->reportProgress();
1662 CURL *MediaCurl::progressCallback_getcurl( void *clientp )
1664 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1665 return pdata ? pdata->curl : 0;
1668 ///////////////////////////////////////////////////////////////////
1670 string MediaCurl::getAuthHint() const
1672 long auth_info = CURLAUTH_NONE;
1675 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1677 if(infoRet == CURLE_OK)
1679 return CurlAuthData::auth_type_long2str(auth_info);
1685 ///////////////////////////////////////////////////////////////////
1687 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1689 //! \todo need a way to pass different CredManagerOptions here
1690 Target_Ptr target = zypp::getZYpp()->getTarget();
1691 CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1692 CurlAuthData_Ptr credentials;
1694 // get stored credentials
1695 AuthData_Ptr cmcred = cm.getCred(_url);
1697 if (cmcred && firstTry)
1699 credentials.reset(new CurlAuthData(*cmcred));
1700 DBG << "got stored credentials:" << endl << *credentials << endl;
1702 // if not found, ask user
1706 CurlAuthData_Ptr curlcred;
1707 curlcred.reset(new CurlAuthData());
1708 callback::SendReport<AuthenticationReport> auth_report;
1710 // preset the username if present in current url
1711 if (!_url.getUsername().empty() && firstTry)
1712 curlcred->setUsername(_url.getUsername());
1713 // if CM has found some credentials, preset the username from there
1715 curlcred->setUsername(cmcred->username());
1717 // indicate we have no good credentials from CM
1720 string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1722 // set available authentication types from the exception
1723 // might be needed in prompt
1724 curlcred->setAuthType(availAuthTypes);
1727 if (auth_report->prompt(_url, prompt_msg, *curlcred))
1729 DBG << "callback answer: retry" << endl
1730 << "CurlAuthData: " << *curlcred << endl;
1732 if (curlcred->valid())
1734 credentials = curlcred;
1735 // if (credentials->username() != _url.getUsername())
1736 // _url.setUsername(credentials->username());
1738 * \todo find a way to save the url with changed username
1739 * back to repoinfo or dont store urls with username
1740 * (and either forbid more repos with the same url and different
1741 * user, or return a set of credentials from CM and try them one
1748 DBG << "callback answer: cancel" << endl;
1752 // set username and password
1755 // HACK, why is this const?
1756 const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1757 const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1759 // set username and password
1760 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1761 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1763 // set available authentication types from the exception
1764 if (credentials->authType() == CURLAUTH_NONE)
1765 credentials->setAuthType(availAuthTypes);
1767 // set auth type (seems this must be set _after_ setting the userpwd)
1768 if (credentials->authType() != CURLAUTH_NONE)
1770 // FIXME: only overwrite if not empty?
1771 const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1772 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1773 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1778 credentials->setUrl(_url);
1779 cm.addCred(*credentials);
1790 } // namespace media