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, const long _timeout, const zypp::Url &_url = zypp::Url(),
160 callback::SendReport<DownloadProgressReport> *_report=NULL)
177 callback::SendReport<DownloadProgressReport> *report;
178 // download rate of the last period (cca 1 sec)
180 // bytes downloaded at the start of the last period
182 // seconds from the start of the download
184 // average download rate
186 // last time the progress was reported
188 // bytes downloaded at the moment the progress was last reported
190 // bytes uploaded at the moment the progress was last reported
195 ///////////////////////////////////////////////////////////////////
197 inline void escape( string & str_r,
198 const char char_r, const string & escaped_r ) {
199 for ( string::size_type pos = str_r.find( char_r );
200 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
201 str_r.replace( pos, 1, escaped_r );
205 inline string escapedPath( string path_r ) {
206 escape( path_r, ' ', "%20" );
210 inline string unEscape( string text_r ) {
211 char * tmp = curl_unescape( text_r.c_str(), 0 );
220 * Fills the settings structure using options passed on the url
221 * for example ?timeout=x&proxy=foo
223 void fillSettingsFromUrl( const Url &url, TransferSettings &s )
225 std::string param(url.getQueryParam("timeout"));
228 long num = str::strtonum<long>(param);
229 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
233 if ( ! url.getUsername().empty() )
235 s.setUsername(url.getUsername());
236 if ( url.getPassword().size() )
237 s.setPassword(url.getPassword());
241 // if there is no username, set anonymous auth
242 if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
243 s.setAnonymousAuth();
246 if ( url.getScheme() == "https" )
248 s.setVerifyPeerEnabled(false);
249 s.setVerifyHostEnabled(false);
251 std::string verify( url.getQueryParam("ssl_verify"));
252 if( verify.empty() ||
255 s.setVerifyPeerEnabled(true);
256 s.setVerifyHostEnabled(true);
258 else if( verify == "no")
260 s.setVerifyPeerEnabled(false);
261 s.setVerifyHostEnabled(false);
265 std::vector<std::string> flags;
266 std::vector<std::string>::const_iterator flag;
267 str::split( verify, std::back_inserter(flags), ",");
268 for(flag = flags.begin(); flag != flags.end(); ++flag)
271 s.setVerifyHostEnabled(true);
272 else if( *flag == "peer")
273 s.setVerifyPeerEnabled(true);
275 ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
280 Pathname ca_path( url.getQueryParam("ssl_capath") );
281 if( ! ca_path.empty())
283 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
284 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
286 s.setCertificateAuthoritiesPath(ca_path);
289 Pathname client_cert( url.getQueryParam("ssl_clientcert") );
290 if( ! client_cert.empty())
292 if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
293 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientcert file"));
295 s.setClientCertificatePath(client_cert);
297 Pathname client_key( url.getQueryParam("ssl_clientkey") );
298 if( ! client_key.empty())
300 if( !PathInfo(client_key).isFile() || !client_key.absolute())
301 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
303 s.setClientKeyPath(client_key);
306 param = url.getQueryParam( "proxy" );
307 if ( ! param.empty() )
309 if ( param == EXPLICITLY_NO_PROXY ) {
310 // Workaround TransferSettings shortcoming: With an
311 // empty proxy string, code will continue to look for
312 // valid proxy settings. So set proxy to some non-empty
313 // string, to indicate it has been explicitly disabled.
314 s.setProxy(EXPLICITLY_NO_PROXY);
315 s.setProxyEnabled(false);
318 string proxyport( url.getQueryParam( "proxyport" ) );
319 if ( ! proxyport.empty() ) {
320 param += ":" + proxyport;
323 s.setProxyEnabled(true);
327 param = url.getQueryParam( "proxyuser" );
328 if ( ! param.empty() )
330 s.setProxyUsername(param);
331 s.setProxyPassword(url.getQueryParam( "proxypass" ));
334 // HTTP authentication type
335 param = url.getQueryParam("auth");
336 if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
340 CurlAuthData::auth_type_str2long(param); // check if we know it
342 catch (MediaException & ex_r)
344 DBG << "Rethrowing as MediaUnauthorizedException.";
345 ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
347 s.setAuthType(param);
351 param = url.getQueryParam("head_requests");
352 if( !param.empty() && param == "no" )
353 s.setHeadRequestsAllowed(false);
357 * Reads the system proxy configuration and fills the settings
358 * structure proxy information
360 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
362 ProxyInfo proxy_info;
363 if ( proxy_info.useProxyFor( url ) )
365 // We must extract any 'user:pass' from the proxy url
366 // otherwise they won't make it into curl (.curlrc wins).
368 Url u( proxy_info.proxy( url ) );
369 s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
370 // don't overwrite explicit auth settings
371 if ( s.proxyUsername().empty() )
373 s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
374 s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
376 s.setProxyEnabled( true );
378 catch (...) {} // no proxy if URL is malformed
382 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
385 * initialized only once, this gets the anonymous id
386 * from the target, which we pass in the http header
388 static const char *const anonymousIdHeader()
390 // we need to add the release and identifier to the
392 // The target could be not initialized, and then this information
394 static const std::string _value(
395 str::trim( str::form(
396 "X-ZYpp-AnonymousId: %s",
397 Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
399 return _value.c_str();
403 * initialized only once, this gets the distribution flavor
404 * from the target, which we pass in the http header
406 static const char *const distributionFlavorHeader()
408 // we need to add the release and identifier to the
410 // The target could be not initialized, and then this information
412 static const std::string _value(
413 str::trim( str::form(
414 "X-ZYpp-DistributionFlavor: %s",
415 Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
417 return _value.c_str();
421 * initialized only once, this gets the agent string
422 * which also includes the curl version
424 static const char *const agentString()
426 // we need to add the release and identifier to the
428 // The target could be not initialized, and then this information
430 static const std::string _value(
432 "ZYpp %s (curl %s) %s"
434 , curl_version_info(CURLVERSION_NOW)->version
435 , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
438 return _value.c_str();
441 // we use this define to unbloat code as this C setting option
442 // and catching exception is done frequently.
443 /** \todo deprecate SET_OPTION and use the typed versions below. */
444 #define SET_OPTION(opt,val) do { \
445 ret = curl_easy_setopt ( _curl, opt, val ); \
447 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
451 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
452 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
453 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
455 MediaCurl::MediaCurl( const Url & url_r,
456 const Pathname & attach_point_hint_r )
457 : MediaHandler( url_r, attach_point_hint_r,
458 "/", // urlpath at attachpoint
459 true ), // does_download
463 _curlError[0] = '\0';
466 MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
470 if( !attachPoint().empty())
472 PathInfo ainfo(attachPoint());
473 Pathname apath(attachPoint() + "XXXXXX");
474 char *atemp = ::strdup( apath.asString().c_str());
476 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
477 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
479 WAR << "attach point " << ainfo.path()
480 << " is not useable for " << url_r.getScheme() << endl;
481 setAttachPoint("", true);
483 else if( atest != NULL)
491 Url MediaCurl::clearQueryString(const Url &url) const
494 curlUrl.setUsername( "" );
495 curlUrl.setPassword( "" );
496 curlUrl.setPathParams( "" );
497 curlUrl.setFragment( "" );
498 curlUrl.delQueryParam("cookies");
499 curlUrl.delQueryParam("proxy");
500 curlUrl.delQueryParam("proxyport");
501 curlUrl.delQueryParam("proxyuser");
502 curlUrl.delQueryParam("proxypass");
503 curlUrl.delQueryParam("ssl_capath");
504 curlUrl.delQueryParam("ssl_verify");
505 curlUrl.delQueryParam("ssl_clientcert");
506 curlUrl.delQueryParam("timeout");
507 curlUrl.delQueryParam("auth");
508 curlUrl.delQueryParam("username");
509 curlUrl.delQueryParam("password");
510 curlUrl.delQueryParam("mediahandler");
511 curlUrl.delQueryParam("credentials");
512 curlUrl.delQueryParam("head_requests");
516 TransferSettings & MediaCurl::settings()
522 void MediaCurl::setCookieFile( const Pathname &fileName )
524 _cookieFile = fileName;
527 ///////////////////////////////////////////////////////////////////
529 void MediaCurl::checkProtocol(const Url &url) const
531 curl_version_info_data *curl_info = NULL;
532 curl_info = curl_version_info(CURLVERSION_NOW);
533 // curl_info does not need any free (is static)
534 if (curl_info->protocols)
536 const char * const *proto;
537 std::string scheme( url.getScheme());
539 for(proto=curl_info->protocols; !found && *proto; ++proto)
541 if( scheme == std::string((const char *)*proto))
546 std::string msg("Unsupported protocol '");
549 ZYPP_THROW(MediaBadUrlException(_url, msg));
554 void MediaCurl::setupEasy()
557 char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
558 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
561 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
562 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
563 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
567 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
568 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
570 ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
573 SET_OPTION(CURLOPT_FAILONERROR, 1L);
574 SET_OPTION(CURLOPT_NOSIGNAL, 1L);
576 // create non persistant settings
577 // so that we don't add headers twice
578 TransferSettings vol_settings(_settings);
580 // add custom headers for download.opensuse.org (bsc#955801)
581 if ( _url.getHost() == "download.opensuse.org" )
583 vol_settings.addHeader(anonymousIdHeader());
584 vol_settings.addHeader(distributionFlavorHeader());
586 vol_settings.addHeader("Pragma:");
588 _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
589 _settings.setConnectTimeout(CONNECT_TIMEOUT);
591 _settings.setUserAgentString(agentString());
593 // fill some settings from url query parameters
596 fillSettingsFromUrl(_url, _settings);
598 catch ( const MediaException &e )
603 // if the proxy was not set (or explicitly unset) by url, then look...
604 if ( _settings.proxy().empty() )
606 // ...at the system proxy settings
607 fillSettingsSystemProxy(_url, _settings);
613 SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
614 // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
615 // just in case curl does not trigger its progress callback frequently
617 if ( _settings.timeout() )
619 SET_OPTION(CURLOPT_TIMEOUT, 3600L);
622 // follow any Location: header that the server sends as part of
623 // an HTTP header (#113275)
624 SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
625 // 3 redirects seem to be too few in some cases (bnc #465532)
626 SET_OPTION(CURLOPT_MAXREDIRS, 6L);
628 if ( _url.getScheme() == "https" )
630 #if CURLVERSION_AT_LEAST(7,19,4)
631 // restrict following of redirections from https to https only
632 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
635 if( _settings.verifyPeerEnabled() ||
636 _settings.verifyHostEnabled() )
638 SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
641 if( ! _settings.clientCertificatePath().empty() )
643 SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
645 if( ! _settings.clientKeyPath().empty() )
647 SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
650 #ifdef CURLSSLOPT_ALLOW_BEAST
652 ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
655 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
658 SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
659 SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
660 // bnc#903405 - POODLE: libzypp should only talk TLS
661 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
664 SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
666 /*---------------------------------------------------------------*
667 CURLOPT_USERPWD: [user name]:[password]
669 Url::username/password -> CURLOPT_USERPWD
670 If not provided, anonymous FTP identification
671 *---------------------------------------------------------------*/
673 if ( _settings.userPassword().size() )
675 SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
676 string use_auth = _settings.authType();
677 if (use_auth.empty())
678 use_auth = "digest,basic"; // our default
679 long auth = CurlAuthData::auth_type_str2long(use_auth);
680 if( auth != CURLAUTH_NONE)
682 DBG << "Enabling HTTP authentication methods: " << use_auth
683 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
684 SET_OPTION(CURLOPT_HTTPAUTH, auth);
688 if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
690 DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
691 SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
692 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
693 /*---------------------------------------------------------------*
694 * CURLOPT_PROXYUSERPWD: [user name]:[password]
696 * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
697 * If not provided, $HOME/.curlrc is evaluated
698 *---------------------------------------------------------------*/
700 string proxyuserpwd = _settings.proxyUserPassword();
702 if ( proxyuserpwd.empty() )
705 CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
706 if ( curlconf.proxyuserpwd.empty() )
707 DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
710 proxyuserpwd = curlconf.proxyuserpwd;
711 DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
716 DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
719 if ( ! proxyuserpwd.empty() )
721 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
724 #if CURLVERSION_AT_LEAST(7,19,4)
725 else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
727 // Explicitly disabled in URL (see fillSettingsFromUrl()).
728 // This should also prevent libcurl from looking into the environment.
729 DBG << "Proxy: explicitly NOPROXY" << endl;
730 SET_OPTION(CURLOPT_NOPROXY, "*");
735 DBG << "Proxy: not explicitly set" << endl;
736 DBG << "Proxy: libcurl may look into the environment" << endl;
740 if ( _settings.minDownloadSpeed() != 0 )
742 SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
743 // default to 10 seconds at low speed
744 SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
747 #if CURLVERSION_AT_LEAST(7,15,5)
748 if ( _settings.maxDownloadSpeed() != 0 )
749 SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
752 /*---------------------------------------------------------------*
753 *---------------------------------------------------------------*/
755 _currentCookieFile = _cookieFile.asString();
756 if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
757 SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
759 MIL << "No cookies requested" << endl;
760 SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
761 SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
762 SET_OPTION(CURLOPT_NOPROGRESS, 0L);
764 #if CURLVERSION_AT_LEAST(7,18,0)
766 SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
768 // append settings custom headers to curl
769 for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
770 it != vol_settings.headersEnd();
773 // MIL << "HEADER " << *it << std::endl;
775 _customHeaders = curl_slist_append(_customHeaders, it->c_str());
776 if ( !_customHeaders )
777 ZYPP_THROW(MediaCurlInitException(_url));
780 SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
783 ///////////////////////////////////////////////////////////////////
786 void MediaCurl::attachTo (bool next)
789 ZYPP_THROW(MediaNotSupportedException(_url));
791 if ( !_url.isValid() )
792 ZYPP_THROW(MediaBadUrlException(_url));
795 if( !isUseableAttachPoint( attachPoint() ) )
797 setAttachPoint( createAttachPoint(), true );
800 disconnectFrom(); // clean _curl if needed
801 _curl = curl_easy_init();
803 ZYPP_THROW(MediaCurlInitException(_url));
809 catch (Exception & ex)
815 // FIXME: need a derived class to propelly compare url's
816 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
817 setMediaSource(media);
821 MediaCurl::checkAttachPoint(const Pathname &apoint) const
823 return MediaHandler::checkAttachPoint( apoint, true, true);
826 ///////////////////////////////////////////////////////////////////
828 void MediaCurl::disconnectFrom()
830 if ( _customHeaders )
832 curl_slist_free_all(_customHeaders);
838 curl_easy_cleanup( _curl );
843 ///////////////////////////////////////////////////////////////////
845 void MediaCurl::releaseFrom( const std::string & ejectDev )
850 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
852 // Simply extend the URLs pathname. An 'absolute' URL path
853 // is achieved by encoding the leading '/' in an URL path:
854 // URL: ftp://user@server -> ~user
855 // URL: ftp://user@server/ -> ~user
856 // URL: ftp://user@server// -> ~user
857 // URL: ftp://user@server/%2F -> /
858 // ^- this '/' is just a separator
860 newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
864 ///////////////////////////////////////////////////////////////////
866 void MediaCurl::getFile( const Pathname & filename ) const
868 // Use absolute file name to prevent access of files outside of the
869 // hierarchy below the attach point.
870 getFileCopy(filename, localPath(filename).absolutename());
873 ///////////////////////////////////////////////////////////////////
875 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
877 callback::SendReport<DownloadProgressReport> report;
879 Url fileurl(getFileUrl(filename));
887 doGetFileCopy(filename, target, report);
890 // retry with proper authentication data
891 catch (MediaUnauthorizedException & ex_r)
893 if(authenticate(ex_r.hint(), !retry))
897 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
901 // unexpected exception
902 catch (MediaException & excpt_r)
904 // FIXME: error number fix
905 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
906 ZYPP_RETHROW(excpt_r);
911 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
914 ///////////////////////////////////////////////////////////////////
916 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
924 return doGetDoesFileExist( filename );
926 // authentication problem, retry with proper authentication data
927 catch (MediaUnauthorizedException & ex_r)
929 if(authenticate(ex_r.hint(), !retry))
934 // unexpected exception
935 catch (MediaException & excpt_r)
937 ZYPP_RETHROW(excpt_r);
945 ///////////////////////////////////////////////////////////////////
947 void MediaCurl::evaluateCurlCode( const Pathname &filename,
949 bool timeout_reached ) const
954 if (filename.empty())
957 url = getFileUrl(filename);
963 case CURLE_UNSUPPORTED_PROTOCOL:
964 case CURLE_URL_MALFORMAT:
965 case CURLE_URL_MALFORMAT_USER:
968 case CURLE_LOGIN_DENIED:
970 MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
972 case CURLE_HTTP_RETURNED_ERROR:
974 long httpReturnCode = 0;
975 CURLcode infoRet = curl_easy_getinfo( _curl,
976 CURLINFO_RESPONSE_CODE,
978 if ( infoRet == CURLE_OK )
980 string msg = "HTTP response: " + str::numstring( httpReturnCode );
981 switch ( httpReturnCode )
985 string auth_hint = getAuthHint();
987 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
988 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
990 ZYPP_THROW(MediaUnauthorizedException(
991 url, "Login failed.", _curlError, auth_hint
995 case 503: // service temporarily unavailable (bnc #462545)
996 ZYPP_THROW(MediaTemporaryProblemException(url));
997 case 504: // gateway timeout
998 ZYPP_THROW(MediaTimeoutException(url));
1002 if (url.asString().find("novell.com") != string::npos)
1003 msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1004 ZYPP_THROW(MediaForbiddenException(url, msg403));
1007 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1010 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1011 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1015 string msg = "Unable to retrieve HTTP response:";
1016 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1017 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1021 case CURLE_FTP_COULDNT_RETR_FILE:
1022 #if CURLVERSION_AT_LEAST(7,16,0)
1023 case CURLE_REMOTE_FILE_NOT_FOUND:
1025 case CURLE_FTP_ACCESS_DENIED:
1026 case CURLE_TFTP_NOTFOUND:
1027 err = "File not found";
1028 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1030 case CURLE_BAD_PASSWORD_ENTERED:
1031 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1032 err = "Login failed";
1034 case CURLE_COULDNT_RESOLVE_PROXY:
1035 case CURLE_COULDNT_RESOLVE_HOST:
1036 case CURLE_COULDNT_CONNECT:
1037 case CURLE_FTP_CANT_GET_HOST:
1038 err = "Connection failed";
1040 case CURLE_WRITE_ERROR:
1041 err = "Write error";
1043 case CURLE_PARTIAL_FILE:
1044 case CURLE_OPERATION_TIMEDOUT:
1045 timeout_reached = true; // fall though to TimeoutException
1047 case CURLE_ABORTED_BY_CALLBACK:
1048 if( timeout_reached )
1050 err = "Timeout reached";
1051 ZYPP_THROW(MediaTimeoutException(url));
1058 case CURLE_SSL_PEER_CERTIFICATE:
1060 err = "Curl error " + str::numstring( code );
1064 // uhm, no 0 code but unknown curl exception
1065 ZYPP_THROW(MediaCurlException(url, err, _curlError));
1067 catch (const MediaException & excpt_r)
1069 ZYPP_RETHROW(excpt_r);
1074 // actually the code is 0, nothing happened
1078 ///////////////////////////////////////////////////////////////////
1080 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1082 DBG << filename.asString() << endl;
1085 ZYPP_THROW(MediaBadUrlException(_url));
1087 if(_url.getHost().empty())
1088 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1090 Url url(getFileUrl(filename));
1092 DBG << "URL: " << url.asString() << endl;
1093 // Use URL without options and without username and passwd
1094 // (some proxies dislike them in the URL).
1095 // Curl seems to need the just scheme, hostname and a path;
1096 // the rest was already passed as curl options (in attachTo).
1097 Url curlUrl( clearQueryString(url) );
1100 // See also Bug #154197 and ftp url definition in RFC 1738:
1101 // The url "ftp://user@host/foo/bar/file" contains a path,
1102 // that is relative to the user's home.
1103 // The url "ftp://user@host//foo/bar/file" (or also with
1104 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1105 // contains an absolute path.
1107 string urlBuffer( curlUrl.asString());
1108 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1109 urlBuffer.c_str() );
1111 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1114 // instead of returning no data with NOBODY, we return
1115 // little data, that works with broken servers, and
1116 // works for ftp as well, because retrieving only headers
1117 // ftp will return always OK code ?
1118 // See http://curl.haxx.se/docs/knownbugs.html #58
1119 if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1120 _settings.headRequestsAllowed() )
1121 ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1123 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1126 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1127 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1128 /* yes, this is why we never got to get NOBODY working before,
1129 because setting it changes this option too, and we also
1131 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1133 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1134 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1137 FILE *file = ::fopen( "/dev/null", "w" );
1139 ERR << "fopen failed for /dev/null" << endl;
1140 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1141 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1142 /* yes, this is why we never got to get NOBODY working before,
1143 because setting it changes this option too, and we also
1145 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1147 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1149 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1151 ZYPP_THROW(MediaWriteException("/dev/null"));
1154 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1157 std::string err( _curlError);
1158 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1159 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1160 /* yes, this is why we never got to get NOBODY working before,
1161 because setting it changes this option too, and we also
1163 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1165 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1167 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1169 ZYPP_THROW(MediaCurlSetOptException(url, err));
1172 CURLcode ok = curl_easy_perform( _curl );
1173 MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1175 // reset curl settings
1176 if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1178 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1180 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1183 /* yes, this is why we never got to get NOBODY working before,
1184 because setting it changes this option too, and we also
1186 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1188 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1190 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1196 // for FTP we set different options
1197 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1199 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1203 // if the code is not zero, close the file
1207 // as we are not having user interaction, the user can't cancel
1208 // the file existence checking, a callback or timeout return code
1209 // will be always a timeout.
1211 evaluateCurlCode( filename, ok, true /* timeout */);
1213 catch ( const MediaFileNotFoundException &e ) {
1214 // if the file did not exist then we can return false
1217 catch ( const MediaException &e ) {
1218 // some error, we are not sure about file existence, rethrw
1222 return ( ok == CURLE_OK );
1225 ///////////////////////////////////////////////////////////////////
1228 #if DETECT_DIR_INDEX
1229 bool MediaCurl::detectDirIndex() const
1231 if(_url.getScheme() != "http" && _url.getScheme() != "https")
1234 // try to check the effective url and set the not_a_file flag
1235 // if the url path ends with a "/", what usually means, that
1236 // we've received a directory index (index.html content).
1238 // Note: This may be dangerous and break file retrieving in
1239 // case of some server redirections ... ?
1241 bool not_a_file = false;
1243 CURLcode ret = curl_easy_getinfo( _curl,
1244 CURLINFO_EFFECTIVE_URL,
1246 if ( ret == CURLE_OK && ptr != NULL)
1251 std::string path( eurl.getPathName());
1252 if( !path.empty() && path != "/" && *path.rbegin() == '/')
1254 DBG << "Effective url ("
1256 << ") seems to provide the index of a directory"
1268 ///////////////////////////////////////////////////////////////////
1270 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1272 Pathname dest = target.absolutename();
1273 if( assert_dir( dest.dirname() ) )
1275 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1276 Url url(getFileUrl(filename));
1277 ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1279 string destNew = target.asString() + ".new.zypp.XXXXXX";
1280 char *buf = ::strdup( destNew.c_str());
1283 ERR << "out of memory for temp file name" << endl;
1284 Url url(getFileUrl(filename));
1285 ZYPP_THROW(MediaSystemException(url, "out of memory for temp file name"));
1288 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1292 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1293 ZYPP_THROW(MediaWriteException(destNew));
1298 FILE *file = ::fdopen( tmp_fd, "we" );
1301 filesystem::unlink( destNew );
1302 ERR << "fopen failed for file '" << destNew << "'" << endl;
1303 ZYPP_THROW(MediaWriteException(destNew));
1306 DBG << "dest: " << dest << endl;
1307 DBG << "temp: " << destNew << endl;
1309 // set IFMODSINCE time condition (no download if not modified)
1310 if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1312 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1313 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1317 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1318 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1322 doGetFileCopyFile(filename, dest, file, report, options);
1324 catch (Exception &e)
1327 filesystem::unlink( destNew );
1328 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1329 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1333 long httpReturnCode = 0;
1334 CURLcode infoRet = curl_easy_getinfo(_curl,
1335 CURLINFO_RESPONSE_CODE,
1337 bool modified = true;
1338 if (infoRet == CURLE_OK)
1340 DBG << "HTTP response: " + str::numstring(httpReturnCode);
1341 if ( httpReturnCode == 304
1342 || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1344 DBG << " Not modified.";
1351 WAR << "Could not get the reponse code." << endl;
1354 if (modified || infoRet != CURLE_OK)
1357 if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1359 ERR << "Failed to chmod file " << destNew << endl;
1361 if (::fclose( file ))
1363 ERR << "Fclose failed for file '" << destNew << "'" << endl;
1364 ZYPP_THROW(MediaWriteException(destNew));
1366 // move the temp file into dest
1367 if ( rename( destNew, dest ) != 0 ) {
1368 ERR << "Rename failed" << endl;
1369 ZYPP_THROW(MediaWriteException(dest));
1374 // close and remove the temp file
1376 filesystem::unlink( destNew );
1379 DBG << "done: " << PathInfo(dest) << endl;
1382 ///////////////////////////////////////////////////////////////////
1384 void MediaCurl::doGetFileCopyFile( const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1386 DBG << filename.asString() << endl;
1389 ZYPP_THROW(MediaBadUrlException(_url));
1391 if(_url.getHost().empty())
1392 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1394 Url url(getFileUrl(filename));
1396 DBG << "URL: " << url.asString() << endl;
1397 // Use URL without options and without username and passwd
1398 // (some proxies dislike them in the URL).
1399 // Curl seems to need the just scheme, hostname and a path;
1400 // the rest was already passed as curl options (in attachTo).
1401 Url curlUrl( clearQueryString(url) );
1404 // See also Bug #154197 and ftp url definition in RFC 1738:
1405 // The url "ftp://user@host/foo/bar/file" contains a path,
1406 // that is relative to the user's home.
1407 // The url "ftp://user@host//foo/bar/file" (or also with
1408 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1409 // contains an absolute path.
1411 string urlBuffer( curlUrl.asString());
1412 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1413 urlBuffer.c_str() );
1415 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1418 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1420 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1423 // Set callback and perform.
1424 ProgressData progressData(_curl, _settings.timeout(), url, &report);
1425 if (!(options & OPTION_NO_REPORT_START))
1426 report->start(url, dest);
1427 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1428 WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1431 ret = curl_easy_perform( _curl );
1432 #if CURLVERSION_AT_LEAST(7,19,4)
1433 // bnc#692260: If the client sends a request with an If-Modified-Since header
1434 // with a future date for the server, the server may respond 200 sending a
1436 // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1437 if ( ftell(file) == 0 && ret == 0 )
1439 long httpReturnCode = 33;
1440 if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1442 long conditionUnmet = 33;
1443 if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1445 WAR << "TIMECONDITION unmet - retry without." << endl;
1446 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1447 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1448 ret = curl_easy_perform( _curl );
1454 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1455 WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1460 ERR << "curl error: " << ret << ": " << _curlError
1461 << ", temp file size " << ftell(file)
1462 << " bytes." << endl;
1464 // the timeout is determined by the progress data object
1465 // which holds whether the timeout was reached or not,
1466 // otherwise it would be a user cancel
1468 evaluateCurlCode( filename, ret, progressData.reached);
1470 catch ( const MediaException &e ) {
1471 // some error, we are not sure about file existence, rethrw
1476 #if DETECT_DIR_INDEX
1477 if (!ret && detectDirIndex())
1479 ZYPP_THROW(MediaNotAFileException(_url, filename));
1481 #endif // DETECT_DIR_INDEX
1484 ///////////////////////////////////////////////////////////////////
1486 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1488 filesystem::DirContent content;
1489 getDirInfo( content, dirname, /*dots*/false );
1491 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1492 Pathname filename = dirname + it->name;
1495 switch ( it->type ) {
1496 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1497 case filesystem::FT_FILE:
1498 getFile( filename );
1500 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1502 getDir( filename, recurse_r );
1504 res = assert_dir( localPath( filename ) );
1506 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1511 // don't provide devices, sockets, etc.
1517 ///////////////////////////////////////////////////////////////////
1519 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1520 const Pathname & dirname, bool dots ) const
1522 getDirectoryYast( retlist, dirname, dots );
1525 ///////////////////////////////////////////////////////////////////
1527 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1528 const Pathname & dirname, bool dots ) const
1530 getDirectoryYast( retlist, dirname, dots );
1533 ///////////////////////////////////////////////////////////////////
1535 int MediaCurl::progressCallback( void *clientp,
1536 double dltotal, double dlnow,
1537 double ultotal, double ulnow)
1539 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1542 // work around curl bug that gives us old data
1543 long httpReturnCode = 0;
1544 if (curl_easy_getinfo(pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode) != CURLE_OK || httpReturnCode == 0)
1547 time_t now = time(NULL);
1550 // reset time of last change in case initial time()
1551 // failed or the time was adjusted (goes backward)
1552 if( pdata->ltime <= 0 || pdata->ltime > now)
1557 // start time counting as soon as first data arrives
1558 // (skip the connection / redirection time at begin)
1560 if (dlnow > 0 || ulnow > 0)
1562 dif = (now - pdata->ltime);
1563 dif = dif > 0 ? dif : 0;
1568 // update the drate_avg and drate_period only after a second has passed
1569 // (this callback is called much more often than a second)
1570 // otherwise the values would be far from accurate when measuring
1571 // the time in seconds
1572 //! \todo more accurate download rate computationn, e.g. compute average value from last 5 seconds, or work with milliseconds instead of seconds
1574 if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1575 pdata->drate_avg = (dlnow / pdata->secs);
1579 pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1580 pdata->dload_period = dlnow;
1584 // send progress report first, abort transfer if requested
1587 if (!(*(pdata->report))->progress(int( dltotal ? dlnow * 100 / dltotal : 0 ),
1590 pdata->drate_period))
1592 return 1; // abort transfer
1596 // check if we there is a timeout set
1597 if( pdata->timeout > 0)
1601 bool progress = false;
1603 // update download data if changed, mark progress
1604 if( dlnow != pdata->dload)
1607 pdata->dload = dlnow;
1610 // update upload data if changed, mark progress
1611 if( ulnow != pdata->uload)
1614 pdata->uload = ulnow;
1618 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1620 pdata->reached = true;
1621 return 1; // aborts transfer
1629 CURL *MediaCurl::progressCallback_getcurl( void *clientp )
1631 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1632 return pdata ? pdata->curl : 0;
1635 ///////////////////////////////////////////////////////////////////
1637 string MediaCurl::getAuthHint() const
1639 long auth_info = CURLAUTH_NONE;
1642 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1644 if(infoRet == CURLE_OK)
1646 return CurlAuthData::auth_type_long2str(auth_info);
1652 ///////////////////////////////////////////////////////////////////
1654 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1656 //! \todo need a way to pass different CredManagerOptions here
1657 Target_Ptr target = zypp::getZYpp()->getTarget();
1658 CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1659 CurlAuthData_Ptr credentials;
1661 // get stored credentials
1662 AuthData_Ptr cmcred = cm.getCred(_url);
1664 if (cmcred && firstTry)
1666 credentials.reset(new CurlAuthData(*cmcred));
1667 DBG << "got stored credentials:" << endl << *credentials << endl;
1669 // if not found, ask user
1673 CurlAuthData_Ptr curlcred;
1674 curlcred.reset(new CurlAuthData());
1675 callback::SendReport<AuthenticationReport> auth_report;
1677 // preset the username if present in current url
1678 if (!_url.getUsername().empty() && firstTry)
1679 curlcred->setUsername(_url.getUsername());
1680 // if CM has found some credentials, preset the username from there
1682 curlcred->setUsername(cmcred->username());
1684 // indicate we have no good credentials from CM
1687 string prompt_msg = str::Format(_("Authentication required for '%s'")) % _url.asString();
1689 // set available authentication types from the exception
1690 // might be needed in prompt
1691 curlcred->setAuthType(availAuthTypes);
1694 if (auth_report->prompt(_url, prompt_msg, *curlcred))
1696 DBG << "callback answer: retry" << endl
1697 << "CurlAuthData: " << *curlcred << endl;
1699 if (curlcred->valid())
1701 credentials = curlcred;
1702 // if (credentials->username() != _url.getUsername())
1703 // _url.setUsername(credentials->username());
1705 * \todo find a way to save the url with changed username
1706 * back to repoinfo or dont store urls with username
1707 * (and either forbid more repos with the same url and different
1708 * user, or return a set of credentials from CM and try them one
1715 DBG << "callback answer: cancel" << endl;
1719 // set username and password
1722 // HACK, why is this const?
1723 const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1724 const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1726 // set username and password
1727 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1728 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1730 // set available authentication types from the exception
1731 if (credentials->authType() == CURLAUTH_NONE)
1732 credentials->setAuthType(availAuthTypes);
1734 // set auth type (seems this must be set _after_ setting the userpwd)
1735 if (credentials->authType() != CURLAUTH_NONE)
1737 // FIXME: only overwrite if not empty?
1738 const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1739 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1740 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1745 credentials->setUrl(_url);
1746 cm.addCred(*credentials);
1757 } // namespace media