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"
33 #include <sys/types.h>
35 #include <sys/mount.h>
39 #include <boost/format.hpp>
41 #define DETECT_DIR_INDEX 0
42 #define CONNECT_TIMEOUT 60
43 #define TRANSFER_TIMEOUT 60 * 3
44 #define TRANSFER_TIMEOUT_MAX 60 * 60
46 #define EXPLICITLY_NO_PROXY "_none_"
48 #undef CURLVERSION_AT_LEAST
49 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
52 using namespace zypp::base;
56 zypp::thread::OnceFlag g_InitOnceFlag = PTHREAD_ONCE_INIT;
57 zypp::thread::OnceFlag g_FreeOnceFlag = PTHREAD_ONCE_INIT;
59 extern "C" void _do_free_once()
61 curl_global_cleanup();
64 extern "C" void globalFreeOnce()
66 zypp::thread::callOnce(g_FreeOnceFlag, _do_free_once);
69 extern "C" void _do_init_once()
71 CURLcode ret = curl_global_init( CURL_GLOBAL_ALL );
74 WAR << "curl global init failed" << endl;
78 // register at exit handler ?
79 // this may cause trouble, because we can protect it
80 // against ourself only.
81 // if the app sets an atexit handler as well, it will
82 // cause a double free while the second of them runs.
84 //std::atexit( globalFreeOnce);
87 inline void globalInitOnce()
89 zypp::thread::callOnce(g_InitOnceFlag, _do_init_once);
92 int log_curl(CURL *curl, curl_infotype info,
93 char *ptr, size_t len, void *max_lvl)
99 case CURLINFO_TEXT: lvl = 1; pfx = "*"; break;
100 case CURLINFO_HEADER_IN: lvl = 2; pfx = "<"; break;
101 case CURLINFO_HEADER_OUT: lvl = 2; pfx = ">"; break;
104 if( lvl > 0 && max_lvl != NULL && lvl <= *((long *)max_lvl))
106 std::string msg(ptr, len);
107 std::list<std::string> lines;
108 std::list<std::string>::const_iterator line;
109 zypp::str::split(msg, std::back_inserter(lines), "\r\n");
110 for(line = lines.begin(); line != lines.end(); ++line)
112 DBG << pfx << " " << *line << endl;
120 void *ptr, size_t size, size_t nmemb, void *stream)
122 // INT << "got header: " << string((char *)ptr, ((char*)ptr) + size*nmemb) << endl;
124 char * lstart = (char *)ptr, * lend = (char *)ptr;
126 size_t max = size * nmemb;
127 while (pos + 1 < max)
130 for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
132 // look for "Location"
133 string line(lstart, lend);
134 if (line.find("Location") != string::npos)
136 DBG << "redirecting to " << line << endl;
140 // continue with the next line
160 ProgressData(CURL *_curl, const long _timeout, const zypp::Url &_url = zypp::Url(),
161 callback::SendReport<DownloadProgressReport> *_report=NULL)
178 callback::SendReport<DownloadProgressReport> *report;
179 // download rate of the last period (cca 1 sec)
181 // bytes downloaded at the start of the last period
183 // seconds from the start of the download
185 // average download rate
187 // last time the progress was reported
189 // bytes downloaded at the moment the progress was last reported
191 // bytes uploaded at the moment the progress was last reported
196 ///////////////////////////////////////////////////////////////////
198 inline void escape( string & str_r,
199 const char char_r, const string & escaped_r ) {
200 for ( string::size_type pos = str_r.find( char_r );
201 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
202 str_r.replace( pos, 1, escaped_r );
206 inline string escapedPath( string path_r ) {
207 escape( path_r, ' ', "%20" );
211 inline string unEscape( string text_r ) {
212 char * tmp = curl_unescape( text_r.c_str(), 0 );
221 * Fills the settings structure using options passed on the url
222 * for example ?timeout=x&proxy=foo
224 void fillSettingsFromUrl( const Url &url, TransferSettings &s )
226 std::string param(url.getQueryParam("timeout"));
229 long num = str::strtonum<long>(param);
230 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
234 if ( ! url.getUsername().empty() )
236 s.setUsername(url.getUsername());
237 if ( url.getPassword().size() )
238 s.setPassword(url.getPassword());
242 // if there is no username, set anonymous auth
243 if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
244 s.setAnonymousAuth();
247 if ( url.getScheme() == "https" )
249 s.setVerifyPeerEnabled(false);
250 s.setVerifyHostEnabled(false);
252 std::string verify( url.getQueryParam("ssl_verify"));
253 if( verify.empty() ||
256 s.setVerifyPeerEnabled(true);
257 s.setVerifyHostEnabled(true);
259 else if( verify == "no")
261 s.setVerifyPeerEnabled(false);
262 s.setVerifyHostEnabled(false);
266 std::vector<std::string> flags;
267 std::vector<std::string>::const_iterator flag;
268 str::split( verify, std::back_inserter(flags), ",");
269 for(flag = flags.begin(); flag != flags.end(); ++flag)
272 s.setVerifyHostEnabled(true);
273 else if( *flag == "peer")
274 s.setVerifyPeerEnabled(true);
276 ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
281 Pathname ca_path( url.getQueryParam("ssl_capath") );
282 if( ! ca_path.empty())
284 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
285 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
287 s.setCertificateAuthoritiesPath(ca_path);
290 param = url.getQueryParam( "proxy" );
291 if ( ! param.empty() )
293 if ( param == EXPLICITLY_NO_PROXY ) {
294 // Workaround TransferSettings shortcoming: With an
295 // empty proxy string, code will continue to look for
296 // valid proxy settings. So set proxy to some non-empty
297 // string, to indicate it has been explicitly disabled.
298 s.setProxy(EXPLICITLY_NO_PROXY);
299 s.setProxyEnabled(false);
302 string proxyport( url.getQueryParam( "proxyport" ) );
303 if ( ! proxyport.empty() ) {
304 param += ":" + proxyport;
307 s.setProxyEnabled(true);
311 param = url.getQueryParam( "proxyuser" );
312 if ( ! param.empty() )
314 s.setProxyUsername(param);
315 s.setProxyPassword(url.getQueryParam( "proxypass" ));
318 // HTTP authentication type
319 param = url.getQueryParam("auth");
320 if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
324 CurlAuthData::auth_type_str2long(param); // check if we know it
326 catch (MediaException & ex_r)
328 DBG << "Rethrowing as MediaUnauthorizedException.";
329 ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
331 s.setAuthType(param);
335 param = url.getQueryParam("head_requests");
336 if( !param.empty() && param == "no" )
337 s.setHeadRequestsAllowed(false);
341 * Reads the system proxy configuration and fills the settings
342 * structure proxy information
344 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
346 ProxyInfo proxy_info;
347 if ( proxy_info.useProxyFor( url ) )
349 // We must extract any 'user:pass' from the proxy url
350 // otherwise they won't make it into curl (.curlrc wins).
352 Url u( proxy_info.proxy( url ) );
353 s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
354 // don't overwrite explicit auth settings
355 if ( s.proxyUsername().empty() )
357 s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
358 s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
360 s.setProxyEnabled( true );
362 catch (...) {} // no proxy if URL is malformed
366 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
369 * initialized only once, this gets the anonymous id
370 * from the target, which we pass in the http header
372 static const char *const anonymousIdHeader()
374 // we need to add the release and identifier to the
376 // The target could be not initialized, and then this information
378 static const std::string _value(
379 str::trim( str::form(
380 "X-ZYpp-AnonymousId: %s",
381 Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
383 return _value.c_str();
387 * initialized only once, this gets the distribution flavor
388 * from the target, which we pass in the http header
390 static const char *const distributionFlavorHeader()
392 // we need to add the release and identifier to the
394 // The target could be not initialized, and then this information
396 static const std::string _value(
397 str::trim( str::form(
398 "X-ZYpp-DistributionFlavor: %s",
399 Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
401 return _value.c_str();
405 * initialized only once, this gets the agent string
406 * which also includes the curl version
408 static const char *const agentString()
410 // we need to add the release and identifier to the
412 // The target could be not initialized, and then this information
414 static const std::string _value(
416 "ZYpp %s (curl %s) %s"
418 , curl_version_info(CURLVERSION_NOW)->version
419 , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
422 return _value.c_str();
425 // we use this define to unbloat code as this C setting option
426 // and catching exception is done frequently.
427 /** \todo deprecate SET_OPTION and use the typed versions below. */
428 #define SET_OPTION(opt,val) do { \
429 ret = curl_easy_setopt ( _curl, opt, val ); \
431 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
435 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
436 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
437 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
439 MediaCurl::MediaCurl( const Url & url_r,
440 const Pathname & attach_point_hint_r )
441 : MediaHandler( url_r, attach_point_hint_r,
442 "/", // urlpath at attachpoint
443 true ), // does_download
447 _curlError[0] = '\0';
450 MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
454 if( !attachPoint().empty())
456 PathInfo ainfo(attachPoint());
457 Pathname apath(attachPoint() + "XXXXXX");
458 char *atemp = ::strdup( apath.asString().c_str());
460 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
461 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
463 WAR << "attach point " << ainfo.path()
464 << " is not useable for " << url_r.getScheme() << endl;
465 setAttachPoint("", true);
467 else if( atest != NULL)
475 Url MediaCurl::clearQueryString(const Url &url) const
478 curlUrl.setUsername( "" );
479 curlUrl.setPassword( "" );
480 curlUrl.setPathParams( "" );
481 curlUrl.setFragment( "" );
482 curlUrl.delQueryParam("cookies");
483 curlUrl.delQueryParam("proxy");
484 curlUrl.delQueryParam("proxyport");
485 curlUrl.delQueryParam("proxyuser");
486 curlUrl.delQueryParam("proxypass");
487 curlUrl.delQueryParam("ssl_capath");
488 curlUrl.delQueryParam("ssl_verify");
489 curlUrl.delQueryParam("timeout");
490 curlUrl.delQueryParam("auth");
491 curlUrl.delQueryParam("username");
492 curlUrl.delQueryParam("password");
493 curlUrl.delQueryParam("mediahandler");
497 TransferSettings & MediaCurl::settings()
503 void MediaCurl::setCookieFile( const Pathname &fileName )
505 _cookieFile = fileName;
508 ///////////////////////////////////////////////////////////////////
510 void MediaCurl::checkProtocol(const Url &url) const
512 curl_version_info_data *curl_info = NULL;
513 curl_info = curl_version_info(CURLVERSION_NOW);
514 // curl_info does not need any free (is static)
515 if (curl_info->protocols)
517 const char * const *proto;
518 std::string scheme( url.getScheme());
520 for(proto=curl_info->protocols; !found && *proto; ++proto)
522 if( scheme == std::string((const char *)*proto))
527 std::string msg("Unsupported protocol '");
530 ZYPP_THROW(MediaBadUrlException(_url, msg));
535 void MediaCurl::setupEasy()
538 char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
539 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
542 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
543 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
544 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
548 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
549 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
551 ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
554 SET_OPTION(CURLOPT_FAILONERROR, 1L);
555 SET_OPTION(CURLOPT_NOSIGNAL, 1L);
557 // create non persistant settings
558 // so that we don't add headers twice
559 TransferSettings vol_settings(_settings);
561 // add custom headers
562 vol_settings.addHeader(anonymousIdHeader());
563 vol_settings.addHeader(distributionFlavorHeader());
564 vol_settings.addHeader("Pragma:");
566 _settings.setTimeout(TRANSFER_TIMEOUT);
567 _settings.setConnectTimeout(CONNECT_TIMEOUT);
569 _settings.setUserAgentString(agentString());
571 // fill some settings from url query parameters
574 fillSettingsFromUrl(_url, _settings);
576 catch ( const MediaException &e )
581 // if the proxy was not set (or explicitly unset) by url, then look...
582 if ( _settings.proxy().empty() )
584 // ...at the system proxy settings
585 fillSettingsSystemProxy(_url, _settings);
591 SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
593 // follow any Location: header that the server sends as part of
594 // an HTTP header (#113275)
595 SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
596 // 3 redirects seem to be too few in some cases (bnc #465532)
597 SET_OPTION(CURLOPT_MAXREDIRS, 6L);
599 if ( _url.getScheme() == "https" )
601 #if CURLVERSION_AT_LEAST(7,19,4)
602 // restrict following of redirections from https to https only
603 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
606 if( _settings.verifyPeerEnabled() ||
607 _settings.verifyHostEnabled() )
609 SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
612 #ifdef CURLSSLOPT_ALLOW_BEAST
614 ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
617 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
620 SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
621 SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
624 SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
626 /*---------------------------------------------------------------*
627 CURLOPT_USERPWD: [user name]:[password]
629 Url::username/password -> CURLOPT_USERPWD
630 If not provided, anonymous FTP identification
631 *---------------------------------------------------------------*/
633 if ( _settings.userPassword().size() )
635 SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
636 string use_auth = _settings.authType();
637 if (use_auth.empty())
638 use_auth = "digest,basic"; // our default
639 long auth = CurlAuthData::auth_type_str2long(use_auth);
640 if( auth != CURLAUTH_NONE)
642 DBG << "Enabling HTTP authentication methods: " << use_auth
643 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
644 SET_OPTION(CURLOPT_HTTPAUTH, auth);
648 if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
650 DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
651 SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
652 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
653 /*---------------------------------------------------------------*
654 * CURLOPT_PROXYUSERPWD: [user name]:[password]
656 * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
657 * If not provided, $HOME/.curlrc is evaluated
658 *---------------------------------------------------------------*/
660 string proxyuserpwd = _settings.proxyUserPassword();
662 if ( proxyuserpwd.empty() )
665 CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
666 if ( curlconf.proxyuserpwd.empty() )
667 DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
670 proxyuserpwd = curlconf.proxyuserpwd;
671 DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
676 DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
679 if ( ! proxyuserpwd.empty() )
681 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
684 #if CURLVERSION_AT_LEAST(7,19,4)
685 else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
687 // Explicitly disabled in URL (see fillSettingsFromUrl()).
688 // This should also prevent libcurl from looking into the environment.
689 DBG << "Proxy: explicitly NOPROXY" << endl;
690 SET_OPTION(CURLOPT_NOPROXY, "*");
695 // libcurl may look into the enviroanment
696 DBG << "Proxy: not explicitly set" << endl;
700 if ( _settings.minDownloadSpeed() != 0 )
702 SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
703 // default to 10 seconds at low speed
704 SET_OPTION(CURLOPT_LOW_SPEED_TIME, 10L);
707 #if CURLVERSION_AT_LEAST(7,15,5)
708 if ( _settings.maxDownloadSpeed() != 0 )
709 SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
712 /*---------------------------------------------------------------*
713 *---------------------------------------------------------------*/
715 _currentCookieFile = _cookieFile.asString();
716 if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
717 SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
719 MIL << "No cookies requested" << endl;
720 SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
721 SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
722 SET_OPTION(CURLOPT_NOPROGRESS, 0L);
724 #if CURLVERSION_AT_LEAST(7,18,0)
726 SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
728 // append settings custom headers to curl
729 for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
730 it != vol_settings.headersEnd();
733 // MIL << "HEADER " << *it << std::endl;
735 _customHeaders = curl_slist_append(_customHeaders, it->c_str());
736 if ( !_customHeaders )
737 ZYPP_THROW(MediaCurlInitException(_url));
740 SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
743 ///////////////////////////////////////////////////////////////////
746 void MediaCurl::attachTo (bool next)
749 ZYPP_THROW(MediaNotSupportedException(_url));
751 if ( !_url.isValid() )
752 ZYPP_THROW(MediaBadUrlException(_url));
755 if( !isUseableAttachPoint(attachPoint()))
757 std::string mountpoint = createAttachPoint().asString();
759 if( mountpoint.empty())
760 ZYPP_THROW( MediaBadAttachPointException(url()));
762 setAttachPoint( mountpoint, true);
765 disconnectFrom(); // clean _curl if needed
766 _curl = curl_easy_init();
768 ZYPP_THROW(MediaCurlInitException(_url));
774 catch (Exception & ex)
780 // FIXME: need a derived class to propelly compare url's
781 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
782 setMediaSource(media);
786 MediaCurl::checkAttachPoint(const Pathname &apoint) const
788 return MediaHandler::checkAttachPoint( apoint, true, true);
791 ///////////////////////////////////////////////////////////////////
793 void MediaCurl::disconnectFrom()
795 if ( _customHeaders )
797 curl_slist_free_all(_customHeaders);
803 curl_easy_cleanup( _curl );
808 ///////////////////////////////////////////////////////////////////
810 void MediaCurl::releaseFrom( const std::string & ejectDev )
815 Url MediaCurl::getFileUrl(const Pathname & filename) const
818 string path = _url.getPathName();
819 if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
820 filename.absolute() )
822 // If url has a path with trailing slash, remove the leading slash from
823 // the absolute file name
824 path += filename.asString().substr( 1, filename.asString().size() - 1 );
826 else if ( filename.relative() )
828 // Add trailing slash to path, if not already there
829 if (path.empty()) path = "/";
830 else if (*path.rbegin() != '/' ) path += "/";
831 // Remove "./" from begin of relative file name
832 path += filename.asString().substr( 2, filename.asString().size() - 2 );
836 path += filename.asString();
839 newurl.setPathName(path);
843 ///////////////////////////////////////////////////////////////////
845 void MediaCurl::getFile( const Pathname & filename ) const
847 // Use absolute file name to prevent access of files outside of the
848 // hierarchy below the attach point.
849 getFileCopy(filename, localPath(filename).absolutename());
852 ///////////////////////////////////////////////////////////////////
854 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
856 callback::SendReport<DownloadProgressReport> report;
858 Url fileurl(getFileUrl(filename));
866 doGetFileCopy(filename, target, report);
869 // retry with proper authentication data
870 catch (MediaUnauthorizedException & ex_r)
872 if(authenticate(ex_r.hint(), !retry))
876 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
880 // unexpected exception
881 catch (MediaException & excpt_r)
883 // FIXME: error number fix
884 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
885 ZYPP_RETHROW(excpt_r);
890 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
893 ///////////////////////////////////////////////////////////////////
895 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
903 return doGetDoesFileExist( filename );
905 // authentication problem, retry with proper authentication data
906 catch (MediaUnauthorizedException & ex_r)
908 if(authenticate(ex_r.hint(), !retry))
913 // unexpected exception
914 catch (MediaException & excpt_r)
916 ZYPP_RETHROW(excpt_r);
924 ///////////////////////////////////////////////////////////////////
926 void MediaCurl::evaluateCurlCode( const Pathname &filename,
928 bool timeout_reached ) const
933 if (filename.empty())
936 url = getFileUrl(filename);
942 case CURLE_UNSUPPORTED_PROTOCOL:
943 case CURLE_URL_MALFORMAT:
944 case CURLE_URL_MALFORMAT_USER:
947 case CURLE_LOGIN_DENIED:
949 MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
951 case CURLE_HTTP_RETURNED_ERROR:
953 long httpReturnCode = 0;
954 CURLcode infoRet = curl_easy_getinfo( _curl,
955 CURLINFO_RESPONSE_CODE,
957 if ( infoRet == CURLE_OK )
959 string msg = "HTTP response: " + str::numstring( httpReturnCode );
960 switch ( httpReturnCode )
964 string auth_hint = getAuthHint();
966 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
967 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
969 ZYPP_THROW(MediaUnauthorizedException(
970 url, "Login failed.", _curlError, auth_hint
974 case 503: // service temporarily unavailable (bnc #462545)
975 ZYPP_THROW(MediaTemporaryProblemException(url));
976 case 504: // gateway timeout
977 ZYPP_THROW(MediaTimeoutException(url));
981 if (url.asString().find("novell.com") != string::npos)
982 msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
983 ZYPP_THROW(MediaForbiddenException(url, msg403));
986 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
989 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
990 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
994 string msg = "Unable to retrieve HTTP response:";
995 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
996 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1000 case CURLE_FTP_COULDNT_RETR_FILE:
1001 #if CURLVERSION_AT_LEAST(7,16,0)
1002 case CURLE_REMOTE_FILE_NOT_FOUND:
1004 case CURLE_FTP_ACCESS_DENIED:
1005 err = "File not found";
1006 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1008 case CURLE_BAD_PASSWORD_ENTERED:
1009 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1010 err = "Login failed";
1012 case CURLE_COULDNT_RESOLVE_PROXY:
1013 case CURLE_COULDNT_RESOLVE_HOST:
1014 case CURLE_COULDNT_CONNECT:
1015 case CURLE_FTP_CANT_GET_HOST:
1016 err = "Connection failed";
1018 case CURLE_WRITE_ERROR:
1019 err = "Write error";
1021 case CURLE_PARTIAL_FILE:
1022 case CURLE_OPERATION_TIMEDOUT:
1023 timeout_reached = true; // fall though to TimeoutException
1025 case CURLE_ABORTED_BY_CALLBACK:
1026 if( timeout_reached )
1028 err = "Timeout reached";
1029 ZYPP_THROW(MediaTimeoutException(url));
1036 case CURLE_SSL_PEER_CERTIFICATE:
1038 err = "Unrecognized error";
1042 // uhm, no 0 code but unknown curl exception
1043 ZYPP_THROW(MediaCurlException(url, err, _curlError));
1045 catch (const MediaException & excpt_r)
1047 ZYPP_RETHROW(excpt_r);
1052 // actually the code is 0, nothing happened
1056 ///////////////////////////////////////////////////////////////////
1058 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1060 DBG << filename.asString() << endl;
1063 ZYPP_THROW(MediaBadUrlException(_url));
1065 if(_url.getHost().empty())
1066 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1068 Url url(getFileUrl(filename));
1070 DBG << "URL: " << url.asString() << endl;
1071 // Use URL without options and without username and passwd
1072 // (some proxies dislike them in the URL).
1073 // Curl seems to need the just scheme, hostname and a path;
1074 // the rest was already passed as curl options (in attachTo).
1075 Url curlUrl( clearQueryString(url) );
1078 // See also Bug #154197 and ftp url definition in RFC 1738:
1079 // The url "ftp://user@host/foo/bar/file" contains a path,
1080 // that is relative to the user's home.
1081 // The url "ftp://user@host//foo/bar/file" (or also with
1082 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1083 // contains an absolute path.
1085 string urlBuffer( curlUrl.asString());
1086 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1087 urlBuffer.c_str() );
1089 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1092 // instead of returning no data with NOBODY, we return
1093 // little data, that works with broken servers, and
1094 // works for ftp as well, because retrieving only headers
1095 // ftp will return always OK code ?
1096 // See http://curl.haxx.se/docs/knownbugs.html #58
1097 if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1098 _settings.headRequestsAllowed() )
1099 ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1101 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1104 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1105 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1106 /* yes, this is why we never got to get NOBODY working before,
1107 because setting it changes this option too, and we also
1109 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1111 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1112 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1115 FILE *file = ::fopen( "/dev/null", "w" );
1117 ERR << "fopen failed for /dev/null" << endl;
1118 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1119 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1120 /* yes, this is why we never got to get NOBODY working before,
1121 because setting it changes this option too, and we also
1123 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1125 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1127 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1129 ZYPP_THROW(MediaWriteException("/dev/null"));
1132 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1135 std::string err( _curlError);
1136 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1137 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1138 /* yes, this is why we never got to get NOBODY working before,
1139 because setting it changes this option too, and we also
1141 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1143 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1145 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1147 ZYPP_THROW(MediaCurlSetOptException(url, err));
1150 CURLcode ok = curl_easy_perform( _curl );
1151 MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1153 // reset curl settings
1154 if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1156 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1158 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1161 /* yes, this is why we never got to get NOBODY working before,
1162 because setting it changes this option too, and we also
1164 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1166 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1168 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1174 // for FTP we set different options
1175 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1177 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1181 // if the code is not zero, close the file
1185 // as we are not having user interaction, the user can't cancel
1186 // the file existence checking, a callback or timeout return code
1187 // will be always a timeout.
1189 evaluateCurlCode( filename, ok, true /* timeout */);
1191 catch ( const MediaFileNotFoundException &e ) {
1192 // if the file did not exist then we can return false
1195 catch ( const MediaException &e ) {
1196 // some error, we are not sure about file existence, rethrw
1200 return ( ok == CURLE_OK );
1203 ///////////////////////////////////////////////////////////////////
1206 #if DETECT_DIR_INDEX
1207 bool MediaCurl::detectDirIndex() const
1209 if(_url.getScheme() != "http" && _url.getScheme() != "https")
1212 // try to check the effective url and set the not_a_file flag
1213 // if the url path ends with a "/", what usually means, that
1214 // we've received a directory index (index.html content).
1216 // Note: This may be dangerous and break file retrieving in
1217 // case of some server redirections ... ?
1219 bool not_a_file = false;
1221 CURLcode ret = curl_easy_getinfo( _curl,
1222 CURLINFO_EFFECTIVE_URL,
1224 if ( ret == CURLE_OK && ptr != NULL)
1229 std::string path( eurl.getPathName());
1230 if( !path.empty() && path != "/" && *path.rbegin() == '/')
1232 DBG << "Effective url ("
1234 << ") seems to provide the index of a directory"
1246 ///////////////////////////////////////////////////////////////////
1248 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1250 Pathname dest = target.absolutename();
1251 if( assert_dir( dest.dirname() ) )
1253 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1254 Url url(getFileUrl(filename));
1255 ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1257 string destNew = target.asString() + ".new.zypp.XXXXXX";
1258 char *buf = ::strdup( destNew.c_str());
1261 ERR << "out of memory for temp file name" << endl;
1262 Url url(getFileUrl(filename));
1263 ZYPP_THROW(MediaSystemException(url, "out of memory for temp file name"));
1266 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1270 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1271 ZYPP_THROW(MediaWriteException(destNew));
1276 FILE *file = ::fdopen( tmp_fd, "we" );
1279 filesystem::unlink( destNew );
1280 ERR << "fopen failed for file '" << destNew << "'" << endl;
1281 ZYPP_THROW(MediaWriteException(destNew));
1284 DBG << "dest: " << dest << endl;
1285 DBG << "temp: " << destNew << endl;
1287 // set IFMODSINCE time condition (no download if not modified)
1288 if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1290 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1291 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1295 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1296 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1300 doGetFileCopyFile(filename, dest, file, report, options);
1302 catch (Exception &e)
1305 filesystem::unlink( destNew );
1306 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1307 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1311 long httpReturnCode = 0;
1312 CURLcode infoRet = curl_easy_getinfo(_curl,
1313 CURLINFO_RESPONSE_CODE,
1315 bool modified = true;
1316 if (infoRet == CURLE_OK)
1318 DBG << "HTTP response: " + str::numstring(httpReturnCode);
1319 if ( httpReturnCode == 304
1320 || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1322 DBG << " Not modified.";
1329 WAR << "Could not get the reponse code." << endl;
1332 if (modified || infoRet != CURLE_OK)
1335 if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1337 ERR << "Failed to chmod file " << destNew << endl;
1339 if (::fclose( file ))
1341 ERR << "Fclose failed for file '" << destNew << "'" << endl;
1342 ZYPP_THROW(MediaWriteException(destNew));
1344 // move the temp file into dest
1345 if ( rename( destNew, dest ) != 0 ) {
1346 ERR << "Rename failed" << endl;
1347 ZYPP_THROW(MediaWriteException(dest));
1352 // close and remove the temp file
1354 filesystem::unlink( destNew );
1357 DBG << "done: " << PathInfo(dest) << endl;
1360 ///////////////////////////////////////////////////////////////////
1362 void MediaCurl::doGetFileCopyFile( const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1364 DBG << filename.asString() << endl;
1367 ZYPP_THROW(MediaBadUrlException(_url));
1369 if(_url.getHost().empty())
1370 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1372 Url url(getFileUrl(filename));
1374 DBG << "URL: " << url.asString() << endl;
1375 // Use URL without options and without username and passwd
1376 // (some proxies dislike them in the URL).
1377 // Curl seems to need the just scheme, hostname and a path;
1378 // the rest was already passed as curl options (in attachTo).
1379 Url curlUrl( clearQueryString(url) );
1382 // See also Bug #154197 and ftp url definition in RFC 1738:
1383 // The url "ftp://user@host/foo/bar/file" contains a path,
1384 // that is relative to the user's home.
1385 // The url "ftp://user@host//foo/bar/file" (or also with
1386 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1387 // contains an absolute path.
1389 string urlBuffer( curlUrl.asString());
1390 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1391 urlBuffer.c_str() );
1393 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1396 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1398 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1401 // Set callback and perform.
1402 ProgressData progressData(_curl, _settings.timeout(), url, &report);
1403 if (!(options & OPTION_NO_REPORT_START))
1404 report->start(url, dest);
1405 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1406 WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1409 ret = curl_easy_perform( _curl );
1410 #if CURLVERSION_AT_LEAST(7,19,4)
1411 // bnc#692260: If the client sends a request with an If-Modified-Since header
1412 // with a future date for the server, the server may respond 200 sending a
1414 // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1415 if ( ftell(file) == 0 && ret == 0 )
1417 long httpReturnCode = 33;
1418 if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1420 long conditionUnmet = 33;
1421 if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1423 WAR << "TIMECONDITION unmet - retry without." << endl;
1424 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1425 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1426 ret = curl_easy_perform( _curl );
1432 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1433 WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1438 ERR << "curl error: " << ret << ": " << _curlError
1439 << ", temp file size " << ftell(file)
1440 << " bytes." << endl;
1442 // the timeout is determined by the progress data object
1443 // which holds wheter the timeout was reached or not,
1444 // otherwise it would be a user cancel
1446 evaluateCurlCode( filename, ret, progressData.reached);
1448 catch ( const MediaException &e ) {
1449 // some error, we are not sure about file existence, rethrw
1454 #if DETECT_DIR_INDEX
1455 if (!ret && detectDirIndex())
1457 ZYPP_THROW(MediaNotAFileException(_url, filename));
1459 #endif // DETECT_DIR_INDEX
1462 ///////////////////////////////////////////////////////////////////
1464 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1466 filesystem::DirContent content;
1467 getDirInfo( content, dirname, /*dots*/false );
1469 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1470 Pathname filename = dirname + it->name;
1473 switch ( it->type ) {
1474 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1475 case filesystem::FT_FILE:
1476 getFile( filename );
1478 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1480 getDir( filename, recurse_r );
1482 res = assert_dir( localPath( filename ) );
1484 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1489 // don't provide devices, sockets, etc.
1495 ///////////////////////////////////////////////////////////////////
1497 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1498 const Pathname & dirname, bool dots ) const
1500 getDirectoryYast( retlist, dirname, dots );
1503 ///////////////////////////////////////////////////////////////////
1505 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1506 const Pathname & dirname, bool dots ) const
1508 getDirectoryYast( retlist, dirname, dots );
1511 ///////////////////////////////////////////////////////////////////
1513 int MediaCurl::progressCallback( void *clientp,
1514 double dltotal, double dlnow,
1515 double ultotal, double ulnow)
1517 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1520 // work around curl bug that gives us old data
1521 long httpReturnCode = 0;
1522 if (curl_easy_getinfo(pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode) != CURLE_OK || httpReturnCode == 0)
1525 time_t now = time(NULL);
1528 // reset time of last change in case initial time()
1529 // failed or the time was adjusted (goes backward)
1530 if( pdata->ltime <= 0 || pdata->ltime > now)
1535 // start time counting as soon as first data arrives
1536 // (skip the connection / redirection time at begin)
1538 if (dlnow > 0 || ulnow > 0)
1540 dif = (now - pdata->ltime);
1541 dif = dif > 0 ? dif : 0;
1546 // update the drate_avg and drate_period only after a second has passed
1547 // (this callback is called much more often than a second)
1548 // otherwise the values would be far from accurate when measuring
1549 // the time in seconds
1550 //! \todo more accurate download rate computationn, e.g. compute average value from last 5 seconds, or work with milliseconds instead of seconds
1552 if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1553 pdata->drate_avg = (dlnow / pdata->secs);
1557 pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1558 pdata->dload_period = dlnow;
1562 // send progress report first, abort transfer if requested
1565 if (!(*(pdata->report))->progress(int( dltotal ? dlnow * 100 / dltotal : 0 ),
1568 pdata->drate_period))
1570 return 1; // abort transfer
1574 // check if we there is a timeout set
1575 if( pdata->timeout > 0)
1579 bool progress = false;
1581 // update download data if changed, mark progress
1582 if( dlnow != pdata->dload)
1585 pdata->dload = dlnow;
1588 // update upload data if changed, mark progress
1589 if( ulnow != pdata->uload)
1592 pdata->uload = ulnow;
1596 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1598 pdata->reached = true;
1599 return 1; // aborts transfer
1607 CURL *MediaCurl::progressCallback_getcurl( void *clientp )
1609 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1610 return pdata ? pdata->curl : 0;
1613 ///////////////////////////////////////////////////////////////////
1615 string MediaCurl::getAuthHint() const
1617 long auth_info = CURLAUTH_NONE;
1620 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1622 if(infoRet == CURLE_OK)
1624 return CurlAuthData::auth_type_long2str(auth_info);
1630 ///////////////////////////////////////////////////////////////////
1632 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1634 //! \todo need a way to pass different CredManagerOptions here
1635 Target_Ptr target = zypp::getZYpp()->getTarget();
1636 CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1637 CurlAuthData_Ptr credentials;
1639 // get stored credentials
1640 AuthData_Ptr cmcred = cm.getCred(_url);
1642 if (cmcred && firstTry)
1644 credentials.reset(new CurlAuthData(*cmcred));
1645 DBG << "got stored credentials:" << endl << *credentials << endl;
1647 // if not found, ask user
1651 CurlAuthData_Ptr curlcred;
1652 curlcred.reset(new CurlAuthData());
1653 callback::SendReport<AuthenticationReport> auth_report;
1655 // preset the username if present in current url
1656 if (!_url.getUsername().empty() && firstTry)
1657 curlcred->setUsername(_url.getUsername());
1658 // if CM has found some credentials, preset the username from there
1660 curlcred->setUsername(cmcred->username());
1662 // indicate we have no good credentials from CM
1665 string prompt_msg = boost::str(boost::format(
1666 //!\todo add comma to the message for the next release
1667 _("Authentication required for '%s'")) % _url.asString());
1669 // set available authentication types from the exception
1670 // might be needed in prompt
1671 curlcred->setAuthType(availAuthTypes);
1674 if (auth_report->prompt(_url, prompt_msg, *curlcred))
1676 DBG << "callback answer: retry" << endl
1677 << "CurlAuthData: " << *curlcred << endl;
1679 if (curlcred->valid())
1681 credentials = curlcred;
1682 // if (credentials->username() != _url.getUsername())
1683 // _url.setUsername(credentials->username());
1685 * \todo find a way to save the url with changed username
1686 * back to repoinfo or dont store urls with username
1687 * (and either forbid more repos with the same url and different
1688 * user, or return a set of credentials from CM and try them one
1695 DBG << "callback answer: cancel" << endl;
1699 // set username and password
1702 // HACK, why is this const?
1703 const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1704 const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1706 // set username and password
1707 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1708 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1710 // set available authentication types from the exception
1711 if (credentials->authType() == CURLAUTH_NONE)
1712 credentials->setAuthType(availAuthTypes);
1714 // set auth type (seems this must be set _after_ setting the userpwd)
1715 if (credentials->authType() != CURLAUTH_NONE)
1717 // FIXME: only overwrite if not empty?
1718 const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1719 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1720 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1725 credentials->setUrl(_url);
1726 cm.addCred(*credentials);
1737 } // namespace media