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
159 ProgressData( CURL *_curl, time_t _timeout = 0, const Url & _url = Url(),
160 ByteCount expectedFileSize_r = 0,
161 callback::SendReport<DownloadProgressReport> *_report = nullptr )
164 , timeout( _timeout )
166 , fileSizeExceeded ( false )
168 , _expectedFileSize( expectedFileSize_r )
175 bool fileSizeExceeded;
176 callback::SendReport<DownloadProgressReport> *report;
177 ByteCount _expectedFileSize;
179 time_t _timeStart = 0; ///< Start total stats
180 time_t _timeLast = 0; ///< Start last period(~1sec)
181 time_t _timeRcv = 0; ///< Start of no-data timeout
182 time_t _timeNow = 0; ///< Now
184 double _dnlTotal = 0.0; ///< Bytes to download or 0 if unknown
185 double _dnlLast = 0.0; ///< Bytes downloaded at period start
186 double _dnlNow = 0.0; ///< Bytes downloaded now
188 int _dnlPercent= 0; ///< Percent completed or 0 if _dnlTotal is unknown
190 double _drateTotal= 0.0; ///< Download rate so far
191 double _drateLast = 0.0; ///< Download rate in last period
193 void updateStats( double dltotal = 0.0, double dlnow = 0.0 )
195 time_t now = _timeNow = time(0);
197 // If called without args (0.0), recompute based on the last values seen
198 if ( dltotal && dltotal != _dnlTotal )
201 if ( dlnow && dlnow != _dnlNow )
206 else if ( !_dnlNow && !_dnlTotal )
208 // Start time counting as soon as first data arrives.
209 // Skip the connection / redirection time at begin.
213 // init or reset if time jumps back
214 if ( !_timeStart || _timeStart > now )
215 _timeStart = _timeLast = _timeRcv = now;
219 reached = ( (now - _timeRcv) > timeout );
221 // check if the downloaded data is already bigger than what we expected
222 fileSizeExceeded = _expectedFileSize > 0 && _expectedFileSize < static_cast<ByteCount::SizeType>(_dnlNow);
226 _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
229 _drateTotal = _dnlNow / std::max( int(now - _timeStart), 1 );
231 if ( _timeLast < now )
233 _drateLast = (_dnlNow - _dnlLast) / int(now - _timeLast);
238 else if ( _timeStart == _timeLast )
239 _drateLast = _drateTotal;
242 int reportProgress() const
244 if ( fileSizeExceeded )
247 return 1; // no-data timeout
248 if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
249 return 1; // user requested abort
254 // download rate of the last period (cca 1 sec)
256 // bytes downloaded at the start of the last period
258 // seconds from the start of the download
260 // average download rate
262 // last time the progress was reported
264 // bytes downloaded at the moment the progress was last reported
266 // bytes uploaded at the moment the progress was last reported
270 ///////////////////////////////////////////////////////////////////
272 inline void escape( string & str_r,
273 const char char_r, const string & escaped_r ) {
274 for ( string::size_type pos = str_r.find( char_r );
275 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
276 str_r.replace( pos, 1, escaped_r );
280 inline string escapedPath( string path_r ) {
281 escape( path_r, ' ', "%20" );
285 inline string unEscape( string text_r ) {
286 char * tmp = curl_unescape( text_r.c_str(), 0 );
295 * Fills the settings structure using options passed on the url
296 * for example ?timeout=x&proxy=foo
298 void fillSettingsFromUrl( const Url &url, TransferSettings &s )
300 std::string param(url.getQueryParam("timeout"));
303 long num = str::strtonum<long>(param);
304 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
308 if ( ! url.getUsername().empty() )
310 s.setUsername(url.getUsername());
311 if ( url.getPassword().size() )
312 s.setPassword(url.getPassword());
316 // if there is no username, set anonymous auth
317 if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
318 s.setAnonymousAuth();
321 if ( url.getScheme() == "https" )
323 s.setVerifyPeerEnabled(false);
324 s.setVerifyHostEnabled(false);
326 std::string verify( url.getQueryParam("ssl_verify"));
327 if( verify.empty() ||
330 s.setVerifyPeerEnabled(true);
331 s.setVerifyHostEnabled(true);
333 else if( verify == "no")
335 s.setVerifyPeerEnabled(false);
336 s.setVerifyHostEnabled(false);
340 std::vector<std::string> flags;
341 std::vector<std::string>::const_iterator flag;
342 str::split( verify, std::back_inserter(flags), ",");
343 for(flag = flags.begin(); flag != flags.end(); ++flag)
346 s.setVerifyHostEnabled(true);
347 else if( *flag == "peer")
348 s.setVerifyPeerEnabled(true);
350 ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
355 Pathname ca_path( url.getQueryParam("ssl_capath") );
356 if( ! ca_path.empty())
358 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
359 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
361 s.setCertificateAuthoritiesPath(ca_path);
364 Pathname client_cert( url.getQueryParam("ssl_clientcert") );
365 if( ! client_cert.empty())
367 if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
368 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientcert file"));
370 s.setClientCertificatePath(client_cert);
372 Pathname client_key( url.getQueryParam("ssl_clientkey") );
373 if( ! client_key.empty())
375 if( !PathInfo(client_key).isFile() || !client_key.absolute())
376 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
378 s.setClientKeyPath(client_key);
381 param = url.getQueryParam( "proxy" );
382 if ( ! param.empty() )
384 if ( param == EXPLICITLY_NO_PROXY ) {
385 // Workaround TransferSettings shortcoming: With an
386 // empty proxy string, code will continue to look for
387 // valid proxy settings. So set proxy to some non-empty
388 // string, to indicate it has been explicitly disabled.
389 s.setProxy(EXPLICITLY_NO_PROXY);
390 s.setProxyEnabled(false);
393 string proxyport( url.getQueryParam( "proxyport" ) );
394 if ( ! proxyport.empty() ) {
395 param += ":" + proxyport;
398 s.setProxyEnabled(true);
402 param = url.getQueryParam( "proxyuser" );
403 if ( ! param.empty() )
405 s.setProxyUsername(param);
406 s.setProxyPassword(url.getQueryParam( "proxypass" ));
409 // HTTP authentication type
410 param = url.getQueryParam("auth");
411 if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
415 CurlAuthData::auth_type_str2long(param); // check if we know it
417 catch (MediaException & ex_r)
419 DBG << "Rethrowing as MediaUnauthorizedException.";
420 ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
422 s.setAuthType(param);
426 param = url.getQueryParam("head_requests");
427 if( !param.empty() && param == "no" )
428 s.setHeadRequestsAllowed(false);
432 * Reads the system proxy configuration and fills the settings
433 * structure proxy information
435 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
437 ProxyInfo proxy_info;
438 if ( proxy_info.useProxyFor( url ) )
440 // We must extract any 'user:pass' from the proxy url
441 // otherwise they won't make it into curl (.curlrc wins).
443 Url u( proxy_info.proxy( url ) );
444 s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
445 // don't overwrite explicit auth settings
446 if ( s.proxyUsername().empty() )
448 s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
449 s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
451 s.setProxyEnabled( true );
453 catch (...) {} // no proxy if URL is malformed
457 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
460 * initialized only once, this gets the anonymous id
461 * from the target, which we pass in the http header
463 static const char *const anonymousIdHeader()
465 // we need to add the release and identifier to the
467 // The target could be not initialized, and then this information
469 static const std::string _value(
470 str::trim( str::form(
471 "X-ZYpp-AnonymousId: %s",
472 Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
474 return _value.c_str();
478 * initialized only once, this gets the distribution flavor
479 * from the target, which we pass in the http header
481 static const char *const distributionFlavorHeader()
483 // we need to add the release and identifier to the
485 // The target could be not initialized, and then this information
487 static const std::string _value(
488 str::trim( str::form(
489 "X-ZYpp-DistributionFlavor: %s",
490 Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
492 return _value.c_str();
496 * initialized only once, this gets the agent string
497 * which also includes the curl version
499 static const char *const agentString()
501 // we need to add the release and identifier to the
503 // The target could be not initialized, and then this information
505 static const std::string _value(
507 "ZYpp %s (curl %s) %s"
509 , curl_version_info(CURLVERSION_NOW)->version
510 , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
513 return _value.c_str();
516 // we use this define to unbloat code as this C setting option
517 // and catching exception is done frequently.
518 /** \todo deprecate SET_OPTION and use the typed versions below. */
519 #define SET_OPTION(opt,val) do { \
520 ret = curl_easy_setopt ( _curl, opt, val ); \
522 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
526 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
527 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
528 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
530 MediaCurl::MediaCurl( const Url & url_r,
531 const Pathname & attach_point_hint_r )
532 : MediaHandler( url_r, attach_point_hint_r,
533 "/", // urlpath at attachpoint
534 true ), // does_download
538 _curlError[0] = '\0';
541 MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
545 if( !attachPoint().empty())
547 PathInfo ainfo(attachPoint());
548 Pathname apath(attachPoint() + "XXXXXX");
549 char *atemp = ::strdup( apath.asString().c_str());
551 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
552 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
554 WAR << "attach point " << ainfo.path()
555 << " is not useable for " << url_r.getScheme() << endl;
556 setAttachPoint("", true);
558 else if( atest != NULL)
566 Url MediaCurl::clearQueryString(const Url &url) const
569 curlUrl.setUsername( "" );
570 curlUrl.setPassword( "" );
571 curlUrl.setPathParams( "" );
572 curlUrl.setFragment( "" );
573 curlUrl.delQueryParam("cookies");
574 curlUrl.delQueryParam("proxy");
575 curlUrl.delQueryParam("proxyport");
576 curlUrl.delQueryParam("proxyuser");
577 curlUrl.delQueryParam("proxypass");
578 curlUrl.delQueryParam("ssl_capath");
579 curlUrl.delQueryParam("ssl_verify");
580 curlUrl.delQueryParam("ssl_clientcert");
581 curlUrl.delQueryParam("timeout");
582 curlUrl.delQueryParam("auth");
583 curlUrl.delQueryParam("username");
584 curlUrl.delQueryParam("password");
585 curlUrl.delQueryParam("mediahandler");
586 curlUrl.delQueryParam("credentials");
587 curlUrl.delQueryParam("head_requests");
591 TransferSettings & MediaCurl::settings()
597 void MediaCurl::setCookieFile( const Pathname &fileName )
599 _cookieFile = fileName;
602 ///////////////////////////////////////////////////////////////////
604 void MediaCurl::checkProtocol(const Url &url) const
606 curl_version_info_data *curl_info = NULL;
607 curl_info = curl_version_info(CURLVERSION_NOW);
608 // curl_info does not need any free (is static)
609 if (curl_info->protocols)
611 const char * const *proto;
612 std::string scheme( url.getScheme());
614 for(proto=curl_info->protocols; !found && *proto; ++proto)
616 if( scheme == std::string((const char *)*proto))
621 std::string msg("Unsupported protocol '");
624 ZYPP_THROW(MediaBadUrlException(_url, msg));
629 void MediaCurl::setupEasy()
632 char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
633 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
636 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
637 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
638 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
642 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
643 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
645 ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
648 SET_OPTION(CURLOPT_FAILONERROR, 1L);
649 SET_OPTION(CURLOPT_NOSIGNAL, 1L);
651 // create non persistant settings
652 // so that we don't add headers twice
653 TransferSettings vol_settings(_settings);
655 // add custom headers for download.opensuse.org (bsc#955801)
656 if ( _url.getHost() == "download.opensuse.org" )
658 vol_settings.addHeader(anonymousIdHeader());
659 vol_settings.addHeader(distributionFlavorHeader());
661 vol_settings.addHeader("Pragma:");
663 _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
664 _settings.setConnectTimeout(CONNECT_TIMEOUT);
666 _settings.setUserAgentString(agentString());
668 // fill some settings from url query parameters
671 fillSettingsFromUrl(_url, _settings);
673 catch ( const MediaException &e )
678 // if the proxy was not set (or explicitly unset) by url, then look...
679 if ( _settings.proxy().empty() )
681 // ...at the system proxy settings
682 fillSettingsSystemProxy(_url, _settings);
688 SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
689 // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
690 // just in case curl does not trigger its progress callback frequently
692 if ( _settings.timeout() )
694 SET_OPTION(CURLOPT_TIMEOUT, 3600L);
697 // follow any Location: header that the server sends as part of
698 // an HTTP header (#113275)
699 SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
700 // 3 redirects seem to be too few in some cases (bnc #465532)
701 SET_OPTION(CURLOPT_MAXREDIRS, 6L);
703 if ( _url.getScheme() == "https" )
705 #if CURLVERSION_AT_LEAST(7,19,4)
706 // restrict following of redirections from https to https only
707 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
710 if( _settings.verifyPeerEnabled() ||
711 _settings.verifyHostEnabled() )
713 SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
716 if( ! _settings.clientCertificatePath().empty() )
718 SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
720 if( ! _settings.clientKeyPath().empty() )
722 SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
725 #ifdef CURLSSLOPT_ALLOW_BEAST
727 ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
730 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
733 SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
734 SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
735 // bnc#903405 - POODLE: libzypp should only talk TLS
736 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
739 SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
741 /*---------------------------------------------------------------*
742 CURLOPT_USERPWD: [user name]:[password]
744 Url::username/password -> CURLOPT_USERPWD
745 If not provided, anonymous FTP identification
746 *---------------------------------------------------------------*/
748 if ( _settings.userPassword().size() )
750 SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
751 string use_auth = _settings.authType();
752 if (use_auth.empty())
753 use_auth = "digest,basic"; // our default
754 long auth = CurlAuthData::auth_type_str2long(use_auth);
755 if( auth != CURLAUTH_NONE)
757 DBG << "Enabling HTTP authentication methods: " << use_auth
758 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
759 SET_OPTION(CURLOPT_HTTPAUTH, auth);
763 if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
765 DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
766 SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
767 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
768 /*---------------------------------------------------------------*
769 * CURLOPT_PROXYUSERPWD: [user name]:[password]
771 * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
772 * If not provided, $HOME/.curlrc is evaluated
773 *---------------------------------------------------------------*/
775 string proxyuserpwd = _settings.proxyUserPassword();
777 if ( proxyuserpwd.empty() )
780 CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
781 if ( curlconf.proxyuserpwd.empty() )
782 DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
785 proxyuserpwd = curlconf.proxyuserpwd;
786 DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
791 DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
794 if ( ! proxyuserpwd.empty() )
796 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
799 #if CURLVERSION_AT_LEAST(7,19,4)
800 else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
802 // Explicitly disabled in URL (see fillSettingsFromUrl()).
803 // This should also prevent libcurl from looking into the environment.
804 DBG << "Proxy: explicitly NOPROXY" << endl;
805 SET_OPTION(CURLOPT_NOPROXY, "*");
810 DBG << "Proxy: not explicitly set" << endl;
811 DBG << "Proxy: libcurl may look into the environment" << endl;
815 if ( _settings.minDownloadSpeed() != 0 )
817 SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
818 // default to 10 seconds at low speed
819 SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
822 #if CURLVERSION_AT_LEAST(7,15,5)
823 if ( _settings.maxDownloadSpeed() != 0 )
824 SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
827 /*---------------------------------------------------------------*
828 *---------------------------------------------------------------*/
830 _currentCookieFile = _cookieFile.asString();
831 if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
832 SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
834 MIL << "No cookies requested" << endl;
835 SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
836 SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
837 SET_OPTION(CURLOPT_NOPROGRESS, 0L);
839 #if CURLVERSION_AT_LEAST(7,18,0)
841 SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
843 // append settings custom headers to curl
844 for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
845 it != vol_settings.headersEnd();
848 // MIL << "HEADER " << *it << std::endl;
850 _customHeaders = curl_slist_append(_customHeaders, it->c_str());
851 if ( !_customHeaders )
852 ZYPP_THROW(MediaCurlInitException(_url));
855 SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
858 ///////////////////////////////////////////////////////////////////
861 void MediaCurl::attachTo (bool next)
864 ZYPP_THROW(MediaNotSupportedException(_url));
866 if ( !_url.isValid() )
867 ZYPP_THROW(MediaBadUrlException(_url));
870 if( !isUseableAttachPoint(attachPoint()))
872 std::string mountpoint = createAttachPoint().asString();
874 if( mountpoint.empty())
875 ZYPP_THROW( MediaBadAttachPointException(url()));
877 setAttachPoint( mountpoint, true);
880 disconnectFrom(); // clean _curl if needed
881 _curl = curl_easy_init();
883 ZYPP_THROW(MediaCurlInitException(_url));
889 catch (Exception & ex)
895 // FIXME: need a derived class to propelly compare url's
896 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
897 setMediaSource(media);
901 MediaCurl::checkAttachPoint(const Pathname &apoint) const
903 return MediaHandler::checkAttachPoint( apoint, true, true);
906 ///////////////////////////////////////////////////////////////////
908 void MediaCurl::disconnectFrom()
910 if ( _customHeaders )
912 curl_slist_free_all(_customHeaders);
918 curl_easy_cleanup( _curl );
923 ///////////////////////////////////////////////////////////////////
925 void MediaCurl::releaseFrom( const std::string & ejectDev )
930 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
932 // Simply extend the URLs pathname. An 'absolute' URL path
933 // is achieved by encoding the leading '/' in an URL path:
934 // URL: ftp://user@server -> ~user
935 // URL: ftp://user@server/ -> ~user
936 // URL: ftp://user@server// -> ~user
937 // URL: ftp://user@server/%2F -> /
938 // ^- this '/' is just a separator
940 newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
944 ///////////////////////////////////////////////////////////////////
946 void MediaCurl::getFile(const Pathname & filename , const ByteCount &expectedFileSize_r) const
948 // Use absolute file name to prevent access of files outside of the
949 // hierarchy below the attach point.
950 getFileCopy(filename, localPath(filename).absolutename(), expectedFileSize_r);
953 ///////////////////////////////////////////////////////////////////
955 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target, const ByteCount &expectedFileSize_r ) const
957 callback::SendReport<DownloadProgressReport> report;
959 Url fileurl(getFileUrl(filename));
967 doGetFileCopy(filename, target, report, expectedFileSize_r);
970 // retry with proper authentication data
971 catch (MediaUnauthorizedException & ex_r)
973 if(authenticate(ex_r.hint(), !retry))
977 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
981 // unexpected exception
982 catch (MediaException & excpt_r)
984 // FIXME: error number fix
985 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
986 ZYPP_RETHROW(excpt_r);
991 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
994 ///////////////////////////////////////////////////////////////////
996 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
1004 return doGetDoesFileExist( filename );
1006 // authentication problem, retry with proper authentication data
1007 catch (MediaUnauthorizedException & ex_r)
1009 if(authenticate(ex_r.hint(), !retry))
1014 // unexpected exception
1015 catch (MediaException & excpt_r)
1017 ZYPP_RETHROW(excpt_r);
1025 ///////////////////////////////////////////////////////////////////
1027 void MediaCurl::evaluateCurlCode(const Pathname &filename,
1029 bool timeout_reached) const
1034 if (filename.empty())
1037 url = getFileUrl(filename);
1044 case CURLE_UNSUPPORTED_PROTOCOL:
1045 case CURLE_URL_MALFORMAT:
1046 case CURLE_URL_MALFORMAT_USER:
1049 case CURLE_LOGIN_DENIED:
1051 MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
1053 case CURLE_HTTP_RETURNED_ERROR:
1055 long httpReturnCode = 0;
1056 CURLcode infoRet = curl_easy_getinfo( _curl,
1057 CURLINFO_RESPONSE_CODE,
1059 if ( infoRet == CURLE_OK )
1061 string msg = "HTTP response: " + str::numstring( httpReturnCode );
1062 switch ( httpReturnCode )
1066 string auth_hint = getAuthHint();
1068 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1069 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1071 ZYPP_THROW(MediaUnauthorizedException(
1072 url, "Login failed.", _curlError, auth_hint
1076 case 502: // bad gateway (bnc #1070851)
1077 case 503: // service temporarily unavailable (bnc #462545)
1078 ZYPP_THROW(MediaTemporaryProblemException(url));
1079 case 504: // gateway timeout
1080 ZYPP_THROW(MediaTimeoutException(url));
1084 if (url.asString().find("novell.com") != string::npos)
1085 msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1086 ZYPP_THROW(MediaForbiddenException(url, msg403));
1090 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1093 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1094 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1098 string msg = "Unable to retrieve HTTP response:";
1099 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1100 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1104 case CURLE_FTP_COULDNT_RETR_FILE:
1105 #if CURLVERSION_AT_LEAST(7,16,0)
1106 case CURLE_REMOTE_FILE_NOT_FOUND:
1108 case CURLE_FTP_ACCESS_DENIED:
1109 case CURLE_TFTP_NOTFOUND:
1110 err = "File not found";
1111 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1113 case CURLE_BAD_PASSWORD_ENTERED:
1114 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1115 err = "Login failed";
1117 case CURLE_COULDNT_RESOLVE_PROXY:
1118 case CURLE_COULDNT_RESOLVE_HOST:
1119 case CURLE_COULDNT_CONNECT:
1120 case CURLE_FTP_CANT_GET_HOST:
1121 err = "Connection failed";
1123 case CURLE_WRITE_ERROR:
1124 err = "Write error";
1126 case CURLE_PARTIAL_FILE:
1127 case CURLE_OPERATION_TIMEDOUT:
1128 timeout_reached = true; // fall though to TimeoutException
1130 case CURLE_ABORTED_BY_CALLBACK:
1131 if( timeout_reached )
1133 err = "Timeout reached";
1134 ZYPP_THROW(MediaTimeoutException(url));
1141 case CURLE_SSL_PEER_CERTIFICATE:
1143 err = "Curl error " + str::numstring( code );
1147 // uhm, no 0 code but unknown curl exception
1148 ZYPP_THROW(MediaCurlException(url, err, _curlError));
1150 catch (const MediaException & excpt_r)
1152 ZYPP_RETHROW(excpt_r);
1157 // actually the code is 0, nothing happened
1161 ///////////////////////////////////////////////////////////////////
1163 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1165 DBG << filename.asString() << endl;
1168 ZYPP_THROW(MediaBadUrlException(_url));
1170 if(_url.getHost().empty())
1171 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1173 Url url(getFileUrl(filename));
1175 DBG << "URL: " << url.asString() << endl;
1176 // Use URL without options and without username and passwd
1177 // (some proxies dislike them in the URL).
1178 // Curl seems to need the just scheme, hostname and a path;
1179 // the rest was already passed as curl options (in attachTo).
1180 Url curlUrl( clearQueryString(url) );
1183 // See also Bug #154197 and ftp url definition in RFC 1738:
1184 // The url "ftp://user@host/foo/bar/file" contains a path,
1185 // that is relative to the user's home.
1186 // The url "ftp://user@host//foo/bar/file" (or also with
1187 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1188 // contains an absolute path.
1190 string urlBuffer( curlUrl.asString());
1191 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1192 urlBuffer.c_str() );
1194 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1197 // instead of returning no data with NOBODY, we return
1198 // little data, that works with broken servers, and
1199 // works for ftp as well, because retrieving only headers
1200 // ftp will return always OK code ?
1201 // See http://curl.haxx.se/docs/knownbugs.html #58
1202 if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1203 _settings.headRequestsAllowed() )
1204 ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1206 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1209 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1210 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1211 /* yes, this is why we never got to get NOBODY working before,
1212 because setting it changes this option too, and we also
1214 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1216 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1217 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1220 AutoFILE file { ::fopen( "/dev/null", "w" ) };
1222 ERR << "fopen failed for /dev/null" << endl;
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 );
1232 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1234 ZYPP_THROW(MediaWriteException("/dev/null"));
1237 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, (*file) );
1239 std::string err( _curlError);
1240 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1241 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1242 /* yes, this is why we never got to get NOBODY working before,
1243 because setting it changes this option too, and we also
1245 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1247 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1249 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1251 ZYPP_THROW(MediaCurlSetOptException(url, err));
1254 CURLcode ok = curl_easy_perform( _curl );
1255 MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1257 // reset curl settings
1258 if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1260 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1262 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1265 /* yes, this is why we never got to get NOBODY working before,
1266 because setting it changes this option too, and we also
1268 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1270 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1272 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1278 // for FTP we set different options
1279 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1281 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1285 // as we are not having user interaction, the user can't cancel
1286 // the file existence checking, a callback or timeout return code
1287 // will be always a timeout.
1289 evaluateCurlCode( filename, ok, true /* timeout */);
1291 catch ( const MediaFileNotFoundException &e ) {
1292 // if the file did not exist then we can return false
1295 catch ( const MediaException &e ) {
1296 // some error, we are not sure about file existence, rethrw
1300 return ( ok == CURLE_OK );
1303 ///////////////////////////////////////////////////////////////////
1306 #if DETECT_DIR_INDEX
1307 bool MediaCurl::detectDirIndex() const
1309 if(_url.getScheme() != "http" && _url.getScheme() != "https")
1312 // try to check the effective url and set the not_a_file flag
1313 // if the url path ends with a "/", what usually means, that
1314 // we've received a directory index (index.html content).
1316 // Note: This may be dangerous and break file retrieving in
1317 // case of some server redirections ... ?
1319 bool not_a_file = false;
1321 CURLcode ret = curl_easy_getinfo( _curl,
1322 CURLINFO_EFFECTIVE_URL,
1324 if ( ret == CURLE_OK && ptr != NULL)
1329 std::string path( eurl.getPathName());
1330 if( !path.empty() && path != "/" && *path.rbegin() == '/')
1332 DBG << "Effective url ("
1334 << ") seems to provide the index of a directory"
1346 ///////////////////////////////////////////////////////////////////
1348 void MediaCurl::doGetFileCopy(const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1350 Pathname dest = target.absolutename();
1351 if( assert_dir( dest.dirname() ) )
1353 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1354 ZYPP_THROW( MediaSystemException(getFileUrl(filename), "System error on " + dest.dirname().asString()) );
1357 ManagedFile destNew { target.extend( ".new.zypp.XXXXXX" ) };
1360 AutoFREE<char> buf { ::strdup( (*destNew).c_str() ) };
1363 ERR << "out of memory for temp file name" << endl;
1364 ZYPP_THROW(MediaSystemException(getFileUrl(filename), "out of memory for temp file name"));
1367 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1370 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1371 ZYPP_THROW(MediaWriteException(destNew));
1373 destNew = ManagedFile( (*buf), filesystem::unlink );
1375 file = ::fdopen( tmp_fd, "we" );
1378 ERR << "fopen failed for file '" << destNew << "'" << endl;
1379 ZYPP_THROW(MediaWriteException(destNew));
1381 tmp_fd.resetDispose(); // don't close it here! ::fdopen moved ownership to file
1384 DBG << "dest: " << dest << endl;
1385 DBG << "temp: " << destNew << endl;
1387 // set IFMODSINCE time condition (no download if not modified)
1388 if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1390 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1391 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1395 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1396 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1400 doGetFileCopyFile(filename, dest, file, report, expectedFileSize_r, options);
1402 catch (Exception &e)
1404 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1405 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1409 long httpReturnCode = 0;
1410 CURLcode infoRet = curl_easy_getinfo(_curl,
1411 CURLINFO_RESPONSE_CODE,
1413 bool modified = true;
1414 if (infoRet == CURLE_OK)
1416 DBG << "HTTP response: " + str::numstring(httpReturnCode);
1417 if ( httpReturnCode == 304
1418 || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1420 DBG << " Not modified.";
1427 WAR << "Could not get the reponse code." << endl;
1430 if (modified || infoRet != CURLE_OK)
1433 if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1435 ERR << "Failed to chmod file " << destNew << endl;
1438 file.resetDispose(); // we're going to close it manually here
1439 if ( ::fclose( file ) )
1441 ERR << "Fclose failed for file '" << destNew << "'" << endl;
1442 ZYPP_THROW(MediaWriteException(destNew));
1445 // move the temp file into dest
1446 if ( rename( destNew, dest ) != 0 ) {
1447 ERR << "Rename failed" << endl;
1448 ZYPP_THROW(MediaWriteException(dest));
1450 destNew.resetDispose(); // no more need to unlink it
1453 DBG << "done: " << PathInfo(dest) << endl;
1456 ///////////////////////////////////////////////////////////////////
1458 void MediaCurl::doGetFileCopyFile(const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, const ByteCount &expectedFileSize_r, RequestOptions options ) const
1460 DBG << filename.asString() << endl;
1463 ZYPP_THROW(MediaBadUrlException(_url));
1465 if(_url.getHost().empty())
1466 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1468 Url url(getFileUrl(filename));
1470 DBG << "URL: " << url.asString() << endl;
1471 // Use URL without options and without username and passwd
1472 // (some proxies dislike them in the URL).
1473 // Curl seems to need the just scheme, hostname and a path;
1474 // the rest was already passed as curl options (in attachTo).
1475 Url curlUrl( clearQueryString(url) );
1478 // See also Bug #154197 and ftp url definition in RFC 1738:
1479 // The url "ftp://user@host/foo/bar/file" contains a path,
1480 // that is relative to the user's home.
1481 // The url "ftp://user@host//foo/bar/file" (or also with
1482 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1483 // contains an absolute path.
1485 string urlBuffer( curlUrl.asString());
1486 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1487 urlBuffer.c_str() );
1489 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1492 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1494 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1497 // Set callback and perform.
1498 ProgressData progressData(_curl, _settings.timeout(), url, expectedFileSize_r, &report);
1499 if (!(options & OPTION_NO_REPORT_START))
1500 report->start(url, dest);
1501 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1502 WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1505 ret = curl_easy_perform( _curl );
1506 #if CURLVERSION_AT_LEAST(7,19,4)
1507 // bnc#692260: If the client sends a request with an If-Modified-Since header
1508 // with a future date for the server, the server may respond 200 sending a
1510 // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1511 if ( ftell(file) == 0 && ret == 0 )
1513 long httpReturnCode = 33;
1514 if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1516 long conditionUnmet = 33;
1517 if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1519 WAR << "TIMECONDITION unmet - retry without." << endl;
1520 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1521 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1522 ret = curl_easy_perform( _curl );
1528 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1529 WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1534 ERR << "curl error: " << ret << ": " << _curlError
1535 << ", temp file size " << ftell(file)
1536 << " bytes." << endl;
1538 // the timeout is determined by the progress data object
1539 // which holds whether the timeout was reached or not,
1540 // otherwise it would be a user cancel
1543 if ( progressData.fileSizeExceeded )
1544 ZYPP_THROW(MediaFileSizeExceededException(url, progressData._expectedFileSize));
1546 evaluateCurlCode( filename, ret, progressData.reached );
1548 catch ( const MediaException &e ) {
1549 // some error, we are not sure about file existence, rethrw
1554 #if DETECT_DIR_INDEX
1555 if (!ret && detectDirIndex())
1557 ZYPP_THROW(MediaNotAFileException(_url, filename));
1559 #endif // DETECT_DIR_INDEX
1562 ///////////////////////////////////////////////////////////////////
1564 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1566 filesystem::DirContent content;
1567 getDirInfo( content, dirname, /*dots*/false );
1569 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1570 Pathname filename = dirname + it->name;
1573 switch ( it->type ) {
1574 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1575 case filesystem::FT_FILE:
1576 getFile( filename, 0 );
1578 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1580 getDir( filename, recurse_r );
1582 res = assert_dir( localPath( filename ) );
1584 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1589 // don't provide devices, sockets, etc.
1595 ///////////////////////////////////////////////////////////////////
1597 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1598 const Pathname & dirname, bool dots ) const
1600 getDirectoryYast( retlist, dirname, dots );
1603 ///////////////////////////////////////////////////////////////////
1605 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1606 const Pathname & dirname, bool dots ) const
1608 getDirectoryYast( retlist, dirname, dots );
1611 ///////////////////////////////////////////////////////////////////
1613 int MediaCurl::aliveCallback( void *clientp, double /*dltotal*/, double dlnow, double /*ultotal*/, double /*ulnow*/ )
1615 ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1618 // Do not propagate dltotal in alive callbacks. MultiCurl uses this to
1619 // prevent a percentage raise while downloading a metalink file. Download
1620 // activity however is indicated by propagating the download rate (via dlnow).
1621 pdata->updateStats( 0.0, dlnow );
1622 return pdata->reportProgress();
1627 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
1629 ProgressData *pdata = reinterpret_cast<ProgressData *>( clientp );
1632 // work around curl bug that gives us old data
1633 long httpReturnCode = 0;
1634 if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1635 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1637 pdata->updateStats( dltotal, dlnow );
1638 return pdata->reportProgress();
1643 CURL *MediaCurl::progressCallback_getcurl( void *clientp )
1645 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1646 return pdata ? pdata->curl : 0;
1649 ///////////////////////////////////////////////////////////////////
1651 string MediaCurl::getAuthHint() const
1653 long auth_info = CURLAUTH_NONE;
1656 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1658 if(infoRet == CURLE_OK)
1660 return CurlAuthData::auth_type_long2str(auth_info);
1667 * MediaMultiCurl needs to reset the expected filesize in case a metalink file is downloaded
1668 * otherwise this function should not be called
1670 void MediaCurl::resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
1672 ProgressData *data = reinterpret_cast<ProgressData *>(clientp);
1674 data->_expectedFileSize = expectedFileSize;
1678 ///////////////////////////////////////////////////////////////////
1680 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1682 //! \todo need a way to pass different CredManagerOptions here
1683 Target_Ptr target = zypp::getZYpp()->getTarget();
1684 CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1685 CurlAuthData_Ptr credentials;
1687 // get stored credentials
1688 AuthData_Ptr cmcred = cm.getCred(_url);
1690 if (cmcred && firstTry)
1692 credentials.reset(new CurlAuthData(*cmcred));
1693 DBG << "got stored credentials:" << endl << *credentials << endl;
1695 // if not found, ask user
1699 CurlAuthData_Ptr curlcred;
1700 curlcred.reset(new CurlAuthData());
1701 callback::SendReport<AuthenticationReport> auth_report;
1703 // preset the username if present in current url
1704 if (!_url.getUsername().empty() && firstTry)
1705 curlcred->setUsername(_url.getUsername());
1706 // if CM has found some credentials, preset the username from there
1708 curlcred->setUsername(cmcred->username());
1710 // indicate we have no good credentials from CM
1713 string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1715 // set available authentication types from the exception
1716 // might be needed in prompt
1717 curlcred->setAuthType(availAuthTypes);
1720 if (auth_report->prompt(_url, prompt_msg, *curlcred))
1722 DBG << "callback answer: retry" << endl
1723 << "CurlAuthData: " << *curlcred << endl;
1725 if (curlcred->valid())
1727 credentials = curlcred;
1728 // if (credentials->username() != _url.getUsername())
1729 // _url.setUsername(credentials->username());
1731 * \todo find a way to save the url with changed username
1732 * back to repoinfo or dont store urls with username
1733 * (and either forbid more repos with the same url and different
1734 * user, or return a set of credentials from CM and try them one
1741 DBG << "callback answer: cancel" << endl;
1745 // set username and password
1748 // HACK, why is this const?
1749 const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1750 const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1752 // set username and password
1753 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1754 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1756 // set available authentication types from the exception
1757 if (credentials->authType() == CURLAUTH_NONE)
1758 credentials->setAuthType(availAuthTypes);
1760 // set auth type (seems this must be set _after_ setting the userpwd)
1761 if (credentials->authType() != CURLAUTH_NONE)
1763 // FIXME: only overwrite if not empty?
1764 const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1765 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1766 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1771 credentials->setUrl(_url);
1772 cm.addCred(*credentials);
1783 } // namespace media