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/ProxyInfos.h"
25 #include "zypp/media/ProxyInfo.h"
26 #include "zypp/media/MediaUserAuth.h"
27 #include "zypp/media/CredentialManager.h"
28 #include "zypp/media/CurlConfig.h"
29 #include "zypp/thread/Once.h"
30 #include "zypp/Target.h"
31 #include "zypp/ZYppFactory.h"
34 #include <sys/types.h>
36 #include <sys/mount.h>
40 #include <boost/format.hpp>
42 #define DETECT_DIR_INDEX 0
43 #define CONNECT_TIMEOUT 60
44 #define TRANSFER_TIMEOUT 60 * 3
45 #define TRANSFER_TIMEOUT_MAX 60 * 60
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(const long _timeout, const zypp::Url &_url = zypp::Url(),
160 callback::SendReport<DownloadProgressReport> *_report=NULL)
175 callback::SendReport<DownloadProgressReport> *report;
176 // download rate of the last period (cca 1 sec)
178 // bytes downloaded at the start of the last period
180 // seconds from the start of the download
182 // average download rate
184 // last time the progress was reported
186 // bytes downloaded at the moment the progress was last reported
188 // bytes uploaded at the moment the progress was last reported
193 ///////////////////////////////////////////////////////////////////
195 inline void escape( string & str_r,
196 const char char_r, const string & escaped_r ) {
197 for ( string::size_type pos = str_r.find( char_r );
198 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
199 str_r.replace( pos, 1, escaped_r );
203 inline string escapedPath( string path_r ) {
204 escape( path_r, ' ', "%20" );
208 inline string unEscape( string text_r ) {
209 char * tmp = curl_unescape( text_r.c_str(), 0 );
218 * Fills the settings structure using options passed on the url
219 * for example ?timeout=x&proxy=foo
221 void fillSettingsFromUrl( const Url &url, TransferSettings &s )
223 std::string param(url.getQueryParam("timeout"));
226 long num = str::strtonum<long>(param);
227 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
231 if ( ! url.getUsername().empty() )
233 s.setUsername(url.getUsername());
234 if ( url.getPassword().size() )
235 s.setPassword(url.getPassword());
239 // if there is no username, set anonymous auth
240 if ( url.getScheme() == "ftp" && s.username().empty() )
241 s.setAnonymousAuth();
244 if ( url.getScheme() == "https" )
246 s.setVerifyPeerEnabled(false);
247 s.setVerifyHostEnabled(false);
249 std::string verify( url.getQueryParam("ssl_verify"));
250 if( verify.empty() ||
253 s.setVerifyPeerEnabled(true);
254 s.setVerifyHostEnabled(true);
256 else if( verify == "no")
258 s.setVerifyPeerEnabled(false);
259 s.setVerifyHostEnabled(false);
263 std::vector<std::string> flags;
264 std::vector<std::string>::const_iterator flag;
265 str::split( verify, std::back_inserter(flags), ",");
266 for(flag = flags.begin(); flag != flags.end(); ++flag)
269 s.setVerifyHostEnabled(true);
270 else if( *flag == "peer")
271 s.setVerifyPeerEnabled(true);
273 ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
278 Pathname ca_path = Pathname(url.getQueryParam("ssl_capath")).asString();
279 if( ! ca_path.empty())
281 if( !PathInfo(ca_path).isDir() || !Pathname(ca_path).absolute())
282 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
284 s.setCertificateAuthoritiesPath(ca_path);
287 string proxy = url.getQueryParam( "proxy" );
288 if ( ! proxy.empty() )
290 if ( proxy == "_none_" ) {
291 s.setProxyEnabled(false);
294 string proxyport( url.getQueryParam( "proxyport" ) );
295 if ( ! proxyport.empty() ) {
296 proxy += ":" + proxyport;
299 s.setProxyEnabled(true);
303 // HTTP authentication type
304 string use_auth = url.getQueryParam("auth");
305 if (!use_auth.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
309 CurlAuthData::auth_type_str2long(use_auth); // check if we know it
311 catch (MediaException & ex_r)
313 DBG << "Rethrowing as MediaUnauthorizedException.";
314 ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
316 s.setAuthType(use_auth);
320 std::string head_requests( url.getQueryParam("head_requests"));
321 if( !head_requests.empty() && head_requests == "no")
322 s.setHeadRequestsAllowed(false);
326 * Reads the system proxy configuration and fills the settings
327 * structure proxy information
329 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
331 #ifdef _WITH_LIBPROXY_SUPPORT_
332 ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoLibproxy()));
334 ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
336 s.setProxyEnabled( proxy_info.useProxyFor( url ) );
337 if ( s.proxyEnabled() )
338 s.setProxy(proxy_info.proxy(url));
341 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
344 * initialized only once, this gets the anonymous id
345 * from the target, which we pass in the http header
347 static const char *const anonymousIdHeader()
349 // we need to add the release and identifier to the
351 // The target could be not initialized, and then this information
353 static const std::string _value(
354 str::trim( str::form(
355 "X-ZYpp-AnonymousId: %s",
356 Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
358 return _value.c_str();
362 * initialized only once, this gets the distribution flavor
363 * from the target, which we pass in the http header
365 static const char *const distributionFlavorHeader()
367 // we need to add the release and identifier to the
369 // The target could be not initialized, and then this information
371 static const std::string _value(
372 str::trim( str::form(
373 "X-ZYpp-DistributionFlavor: %s",
374 Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
376 return _value.c_str();
380 * initialized only once, this gets the agent string
381 * which also includes the curl version
383 static const char *const agentString()
385 // we need to add the release and identifier to the
387 // The target could be not initialized, and then this information
389 static const std::string _value(
391 "ZYpp %s (curl %s) %s"
393 , curl_version_info(CURLVERSION_NOW)->version
394 , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
397 return _value.c_str();
400 // we use this define to unbloat code as this C setting option
401 // and catching exception is done frequently.
402 /** \todo deprecate SET_OPTION and use the typed versions below. */
403 #define SET_OPTION(opt,val) do { \
404 ret = curl_easy_setopt ( _curl, opt, val ); \
406 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
410 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
411 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
412 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
414 MediaCurl::MediaCurl( const Url & url_r,
415 const Pathname & attach_point_hint_r )
416 : MediaHandler( url_r, attach_point_hint_r,
417 "/", // urlpath at attachpoint
418 true ), // does_download
422 _curlError[0] = '\0';
425 MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
429 if( !attachPoint().empty())
431 PathInfo ainfo(attachPoint());
432 Pathname apath(attachPoint() + "XXXXXX");
433 char *atemp = ::strdup( apath.asString().c_str());
435 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
436 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
438 WAR << "attach point " << ainfo.path()
439 << " is not useable for " << url_r.getScheme() << endl;
440 setAttachPoint("", true);
442 else if( atest != NULL)
450 Url MediaCurl::clearQueryString(const Url &url) const
453 curlUrl.setUsername( "" );
454 curlUrl.setPassword( "" );
455 curlUrl.setPathParams( "" );
456 curlUrl.setFragment( "" );
457 curlUrl.delQueryParam("cookies");
458 curlUrl.delQueryParam("proxy");
459 curlUrl.delQueryParam("proxyport");
460 curlUrl.delQueryParam("proxyuser");
461 curlUrl.delQueryParam("proxypass");
462 curlUrl.delQueryParam("ssl_capath");
463 curlUrl.delQueryParam("ssl_verify");
464 curlUrl.delQueryParam("timeout");
465 curlUrl.delQueryParam("auth");
466 curlUrl.delQueryParam("username");
467 curlUrl.delQueryParam("password");
468 curlUrl.delQueryParam("mediahandler");
472 TransferSettings & MediaCurl::settings()
478 void MediaCurl::setCookieFile( const Pathname &fileName )
480 _cookieFile = fileName;
483 ///////////////////////////////////////////////////////////////////
485 void MediaCurl::checkProtocol(const Url &url) const
487 curl_version_info_data *curl_info = NULL;
488 curl_info = curl_version_info(CURLVERSION_NOW);
489 // curl_info does not need any free (is static)
490 if (curl_info->protocols)
492 const char * const *proto;
493 std::string scheme( url.getScheme());
495 for(proto=curl_info->protocols; !found && *proto; ++proto)
497 if( scheme == std::string((const char *)*proto))
502 std::string msg("Unsupported protocol '");
505 ZYPP_THROW(MediaBadUrlException(_url, msg));
510 void MediaCurl::setupEasy()
513 char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
514 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
517 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
518 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
519 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
523 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
524 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
526 ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
529 SET_OPTION(CURLOPT_FAILONERROR, 1L);
530 SET_OPTION(CURLOPT_NOSIGNAL, 1L);
532 // create non persistant settings
533 // so that we don't add headers twice
534 TransferSettings vol_settings(_settings);
536 // add custom headers
537 vol_settings.addHeader(anonymousIdHeader());
538 vol_settings.addHeader(distributionFlavorHeader());
539 vol_settings.addHeader("Pragma:");
541 _settings.setTimeout(TRANSFER_TIMEOUT);
542 _settings.setConnectTimeout(CONNECT_TIMEOUT);
544 _settings.setUserAgentString(agentString());
546 // fill some settings from url query parameters
549 fillSettingsFromUrl(_url, _settings);
551 catch ( const MediaException &e )
557 // if the proxy was not set by url, then look
558 if ( _settings.proxy().empty() )
560 // at the system proxy settings
561 fillSettingsSystemProxy(_url, _settings);
564 DBG << "Proxy: " << (_settings.proxy().empty() ? "-none-" : _settings.proxy()) << endl;
569 SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
571 // follow any Location: header that the server sends as part of
572 // an HTTP header (#113275)
573 SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
574 // 3 redirects seem to be too few in some cases (bnc #465532)
575 SET_OPTION(CURLOPT_MAXREDIRS, 6L);
577 if ( _url.getScheme() == "https" )
579 #if CURLVERSION_AT_LEAST(7,19,4)
580 // restrict following of redirections from https to https only
581 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
584 if( _settings.verifyPeerEnabled() ||
585 _settings.verifyHostEnabled() )
587 SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
590 SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
591 SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
594 SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
596 /*---------------------------------------------------------------*
597 CURLOPT_USERPWD: [user name]:[password]
599 Url::username/password -> CURLOPT_USERPWD
600 If not provided, anonymous FTP identification
601 *---------------------------------------------------------------*/
603 if ( _settings.userPassword().size() )
605 SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
606 string use_auth = _settings.authType();
607 if (use_auth.empty())
608 use_auth = "digest,basic"; // our default
609 long auth = CurlAuthData::auth_type_str2long(use_auth);
610 if( auth != CURLAUTH_NONE)
612 DBG << "Enabling HTTP authentication methods: " << use_auth
613 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
614 SET_OPTION(CURLOPT_HTTPAUTH, auth);
618 if ( _settings.proxyEnabled() )
620 if ( ! _settings.proxy().empty() )
622 SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
623 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
624 /*---------------------------------------------------------------*
625 CURLOPT_PROXYUSERPWD: [user name]:[password]
627 Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
628 If not provided, $HOME/.curlrc is evaluated
629 *---------------------------------------------------------------*/
631 string proxyuserpwd = _settings.proxyUserPassword();
633 if ( proxyuserpwd.empty() )
636 CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
637 if (curlconf.proxyuserpwd.empty())
638 DBG << "~/.curlrc does not contain the proxy-user option" << endl;
641 proxyuserpwd = curlconf.proxyuserpwd;
642 DBG << "using proxy-user from ~/.curlrc" << endl;
646 proxyuserpwd = unEscape( proxyuserpwd );
647 if ( ! proxyuserpwd.empty() )
648 SET_OPTION(CURLOPT_PROXYUSERPWD, proxyuserpwd.c_str());
653 #if CURLVERSION_AT_LEAST(7,19,4)
654 SET_OPTION(CURLOPT_NOPROXY, "*");
659 if ( _settings.minDownloadSpeed() != 0 )
661 SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
662 // default to 10 seconds at low speed
663 SET_OPTION(CURLOPT_LOW_SPEED_TIME, 10L);
666 #if CURLVERSION_AT_LEAST(7,15,5)
667 if ( _settings.maxDownloadSpeed() != 0 )
668 SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
671 /*---------------------------------------------------------------*
672 *---------------------------------------------------------------*/
674 _currentCookieFile = _cookieFile.asString();
675 if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
676 SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
678 MIL << "No cookies requested" << endl;
679 SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
680 SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
681 SET_OPTION(CURLOPT_NOPROGRESS, 0L);
683 #if CURLVERSION_AT_LEAST(7,18,0)
685 SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
687 // append settings custom headers to curl
688 for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
689 it != vol_settings.headersEnd();
692 MIL << "HEADER " << *it << std::endl;
694 _customHeaders = curl_slist_append(_customHeaders, it->c_str());
695 if ( !_customHeaders )
696 ZYPP_THROW(MediaCurlInitException(_url));
699 SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
702 ///////////////////////////////////////////////////////////////////
705 void MediaCurl::attachTo (bool next)
708 ZYPP_THROW(MediaNotSupportedException(_url));
710 if ( !_url.isValid() )
711 ZYPP_THROW(MediaBadUrlException(_url));
714 if( !isUseableAttachPoint(attachPoint()))
716 std::string mountpoint = createAttachPoint().asString();
718 if( mountpoint.empty())
719 ZYPP_THROW( MediaBadAttachPointException(url()));
721 setAttachPoint( mountpoint, true);
724 disconnectFrom(); // clean _curl if needed
725 _curl = curl_easy_init();
727 ZYPP_THROW(MediaCurlInitException(_url));
733 catch (Exception & ex)
739 // FIXME: need a derived class to propelly compare url's
740 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
741 setMediaSource(media);
745 MediaCurl::checkAttachPoint(const Pathname &apoint) const
747 return MediaHandler::checkAttachPoint( apoint, true, true);
750 ///////////////////////////////////////////////////////////////////
752 void MediaCurl::disconnectFrom()
754 if ( _customHeaders )
756 curl_slist_free_all(_customHeaders);
762 curl_easy_cleanup( _curl );
767 ///////////////////////////////////////////////////////////////////
769 void MediaCurl::releaseFrom( const std::string & ejectDev )
774 Url MediaCurl::getFileUrl(const Pathname & filename) const
777 string path = _url.getPathName();
778 if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
779 filename.absolute() )
781 // If url has a path with trailing slash, remove the leading slash from
782 // the absolute file name
783 path += filename.asString().substr( 1, filename.asString().size() - 1 );
785 else if ( filename.relative() )
787 // Add trailing slash to path, if not already there
788 if (path.empty()) path = "/";
789 else if (*path.rbegin() != '/' ) path += "/";
790 // Remove "./" from begin of relative file name
791 path += filename.asString().substr( 2, filename.asString().size() - 2 );
795 path += filename.asString();
798 newurl.setPathName(path);
802 ///////////////////////////////////////////////////////////////////
804 void MediaCurl::getFile( const Pathname & filename ) const
806 // Use absolute file name to prevent access of files outside of the
807 // hierarchy below the attach point.
808 getFileCopy(filename, localPath(filename).absolutename());
811 ///////////////////////////////////////////////////////////////////
813 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
815 callback::SendReport<DownloadProgressReport> report;
817 Url fileurl(getFileUrl(filename));
825 doGetFileCopy(filename, target, report);
828 // retry with proper authentication data
829 catch (MediaUnauthorizedException & ex_r)
831 if(authenticate(ex_r.hint(), !retry))
835 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
839 // unexpected exception
840 catch (MediaException & excpt_r)
842 // FIXME: error number fix
843 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
844 ZYPP_RETHROW(excpt_r);
849 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
852 ///////////////////////////////////////////////////////////////////
854 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
862 return doGetDoesFileExist( filename );
864 // authentication problem, retry with proper authentication data
865 catch (MediaUnauthorizedException & ex_r)
867 if(authenticate(ex_r.hint(), !retry))
872 // unexpected exception
873 catch (MediaException & excpt_r)
875 ZYPP_RETHROW(excpt_r);
883 ///////////////////////////////////////////////////////////////////
885 void MediaCurl::evaluateCurlCode( const Pathname &filename,
887 bool timeout_reached ) const
892 if (filename.empty())
895 url = getFileUrl(filename);
901 case CURLE_UNSUPPORTED_PROTOCOL:
902 case CURLE_URL_MALFORMAT:
903 case CURLE_URL_MALFORMAT_USER:
906 case CURLE_LOGIN_DENIED:
908 MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
910 case CURLE_HTTP_RETURNED_ERROR:
912 long httpReturnCode = 0;
913 CURLcode infoRet = curl_easy_getinfo( _curl,
914 CURLINFO_RESPONSE_CODE,
916 if ( infoRet == CURLE_OK )
918 string msg = "HTTP response: " + str::numstring( httpReturnCode );
919 switch ( httpReturnCode )
923 string auth_hint = getAuthHint();
925 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
926 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
928 ZYPP_THROW(MediaUnauthorizedException(
929 url, "Login failed.", _curlError, auth_hint
933 case 503: // service temporarily unavailable (bnc #462545)
934 ZYPP_THROW(MediaTemporaryProblemException(url));
935 case 504: // gateway timeout
936 ZYPP_THROW(MediaTimeoutException(url));
940 if (url.asString().find("novell.com") != string::npos)
941 msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
942 ZYPP_THROW(MediaForbiddenException(url, msg403));
945 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
948 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
949 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
953 string msg = "Unable to retrieve HTTP response:";
954 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
955 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
959 case CURLE_FTP_COULDNT_RETR_FILE:
960 #if CURLVERSION_AT_LEAST(7,16,0)
961 case CURLE_REMOTE_FILE_NOT_FOUND:
963 case CURLE_FTP_ACCESS_DENIED:
964 err = "File not found";
965 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
967 case CURLE_BAD_PASSWORD_ENTERED:
968 case CURLE_FTP_USER_PASSWORD_INCORRECT:
969 err = "Login failed";
971 case CURLE_COULDNT_RESOLVE_PROXY:
972 case CURLE_COULDNT_RESOLVE_HOST:
973 case CURLE_COULDNT_CONNECT:
974 case CURLE_FTP_CANT_GET_HOST:
975 err = "Connection failed";
977 case CURLE_WRITE_ERROR:
980 case CURLE_PARTIAL_FILE:
981 case CURLE_ABORTED_BY_CALLBACK:
982 case CURLE_OPERATION_TIMEDOUT:
985 err = "Timeout reached";
986 ZYPP_THROW(MediaTimeoutException(url));
993 case CURLE_SSL_PEER_CERTIFICATE:
995 err = "Unrecognized error";
999 // uhm, no 0 code but unknown curl exception
1000 ZYPP_THROW(MediaCurlException(url, err, _curlError));
1002 catch (const MediaException & excpt_r)
1004 ZYPP_RETHROW(excpt_r);
1009 // actually the code is 0, nothing happened
1013 ///////////////////////////////////////////////////////////////////
1015 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1017 DBG << filename.asString() << endl;
1020 ZYPP_THROW(MediaBadUrlException(_url));
1022 if(_url.getHost().empty())
1023 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1025 Url url(getFileUrl(filename));
1027 DBG << "URL: " << url.asString() << endl;
1028 // Use URL without options and without username and passwd
1029 // (some proxies dislike them in the URL).
1030 // Curl seems to need the just scheme, hostname and a path;
1031 // the rest was already passed as curl options (in attachTo).
1032 Url curlUrl( clearQueryString(url) );
1035 // See also Bug #154197 and ftp url definition in RFC 1738:
1036 // The url "ftp://user@host/foo/bar/file" contains a path,
1037 // that is relative to the user's home.
1038 // The url "ftp://user@host//foo/bar/file" (or also with
1039 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1040 // contains an absolute path.
1042 string urlBuffer( curlUrl.asString());
1043 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1044 urlBuffer.c_str() );
1046 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1049 // instead of returning no data with NOBODY, we return
1050 // little data, that works with broken servers, and
1051 // works for ftp as well, because retrieving only headers
1052 // ftp will return always OK code ?
1053 // See http://curl.haxx.se/docs/knownbugs.html #58
1054 if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1055 _settings.headRequestsAllowed() )
1056 ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1058 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1061 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1062 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1063 /* yes, this is why we never got to get NOBODY working before,
1064 because setting it changes this option too, and we also
1066 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1068 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1069 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1072 FILE *file = ::fopen( "/dev/null", "w" );
1074 ERR << "fopen failed for /dev/null" << endl;
1075 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1076 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1077 /* yes, this is why we never got to get NOBODY working before,
1078 because setting it changes this option too, and we also
1080 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1082 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1084 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1086 ZYPP_THROW(MediaWriteException("/dev/null"));
1089 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1092 std::string err( _curlError);
1093 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1094 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1095 /* yes, this is why we never got to get NOBODY working before,
1096 because setting it changes this option too, and we also
1098 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1100 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1102 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1104 ZYPP_THROW(MediaCurlSetOptException(url, err));
1107 CURLcode ok = curl_easy_perform( _curl );
1108 MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1110 // reset curl settings
1111 if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1113 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1115 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1118 /* yes, this is why we never got to get NOBODY working before,
1119 because setting it changes this option too, and we also
1121 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1123 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1125 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1131 // for FTP we set different options
1132 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1134 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1138 // if the code is not zero, close the file
1142 // as we are not having user interaction, the user can't cancel
1143 // the file existence checking, a callback or timeout return code
1144 // will be always a timeout.
1146 evaluateCurlCode( filename, ok, true /* timeout */);
1148 catch ( const MediaFileNotFoundException &e ) {
1149 // if the file did not exist then we can return false
1152 catch ( const MediaException &e ) {
1153 // some error, we are not sure about file existence, rethrw
1157 return ( ok == CURLE_OK );
1160 ///////////////////////////////////////////////////////////////////
1163 #if DETECT_DIR_INDEX
1164 bool MediaCurl::detectDirIndex() const
1166 if(_url.getScheme() != "http" && _url.getScheme() != "https")
1169 // try to check the effective url and set the not_a_file flag
1170 // if the url path ends with a "/", what usually means, that
1171 // we've received a directory index (index.html content).
1173 // Note: This may be dangerous and break file retrieving in
1174 // case of some server redirections ... ?
1176 bool not_a_file = false;
1178 CURLcode ret = curl_easy_getinfo( _curl,
1179 CURLINFO_EFFECTIVE_URL,
1181 if ( ret == CURLE_OK && ptr != NULL)
1186 std::string path( eurl.getPathName());
1187 if( !path.empty() && path != "/" && *path.rbegin() == '/')
1189 DBG << "Effective url ("
1191 << ") seems to provide the index of a directory"
1203 ///////////////////////////////////////////////////////////////////
1205 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1207 Pathname dest = target.absolutename();
1208 if( assert_dir( dest.dirname() ) )
1210 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1211 Url url(getFileUrl(filename));
1212 ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1214 string destNew = target.asString() + ".new.zypp.XXXXXX";
1215 char *buf = ::strdup( destNew.c_str());
1218 ERR << "out of memory for temp file name" << endl;
1219 Url url(getFileUrl(filename));
1220 ZYPP_THROW(MediaSystemException(url, "out of memory for temp file name"));
1223 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1227 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1228 ZYPP_THROW(MediaWriteException(destNew));
1233 FILE *file = ::fdopen( tmp_fd, "we" );
1236 filesystem::unlink( destNew );
1237 ERR << "fopen failed for file '" << destNew << "'" << endl;
1238 ZYPP_THROW(MediaWriteException(destNew));
1241 DBG << "dest: " << dest << endl;
1242 DBG << "temp: " << destNew << endl;
1244 // set IFMODSINCE time condition (no download if not modified)
1245 if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1247 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1248 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1252 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1253 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1257 doGetFileCopyFile(filename, dest, file, report, options);
1259 catch (Exception &e)
1262 filesystem::unlink( destNew );
1263 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1264 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1268 long httpReturnCode = 0;
1269 CURLcode infoRet = curl_easy_getinfo(_curl,
1270 CURLINFO_RESPONSE_CODE,
1272 bool modified = true;
1273 if (infoRet == CURLE_OK)
1275 DBG << "HTTP response: " + str::numstring(httpReturnCode);
1276 if ( httpReturnCode == 304
1277 || ( httpReturnCode == 213 && _url.getScheme() == "ftp" ) ) // not modified
1279 DBG << " Not modified.";
1286 WAR << "Could not get the reponse code." << endl;
1289 if (modified || infoRet != CURLE_OK)
1292 if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1294 ERR << "Failed to chmod file " << destNew << endl;
1296 if (::fclose( file ))
1298 ERR << "Fclose failed for file '" << destNew << "'" << endl;
1299 ZYPP_THROW(MediaWriteException(destNew));
1301 // move the temp file into dest
1302 if ( rename( destNew, dest ) != 0 ) {
1303 ERR << "Rename failed" << endl;
1304 ZYPP_THROW(MediaWriteException(dest));
1309 // close and remove the temp file
1311 filesystem::unlink( destNew );
1314 DBG << "done: " << PathInfo(dest) << endl;
1317 ///////////////////////////////////////////////////////////////////
1319 void MediaCurl::doGetFileCopyFile( const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1321 DBG << filename.asString() << endl;
1324 ZYPP_THROW(MediaBadUrlException(_url));
1326 if(_url.getHost().empty())
1327 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1329 Url url(getFileUrl(filename));
1331 DBG << "URL: " << url.asString() << endl;
1332 // Use URL without options and without username and passwd
1333 // (some proxies dislike them in the URL).
1334 // Curl seems to need the just scheme, hostname and a path;
1335 // the rest was already passed as curl options (in attachTo).
1336 Url curlUrl( clearQueryString(url) );
1339 // See also Bug #154197 and ftp url definition in RFC 1738:
1340 // The url "ftp://user@host/foo/bar/file" contains a path,
1341 // that is relative to the user's home.
1342 // The url "ftp://user@host//foo/bar/file" (or also with
1343 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1344 // contains an absolute path.
1346 string urlBuffer( curlUrl.asString());
1347 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1348 urlBuffer.c_str() );
1350 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1353 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1355 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1358 // Set callback and perform.
1359 ProgressData progressData(_settings.timeout(), url, &report);
1360 if (!(options & OPTION_NO_REPORT_START))
1361 report->start(url, dest);
1362 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1363 WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1366 ret = curl_easy_perform( _curl );
1367 #if CURLVERSION_AT_LEAST(7,19,4)
1368 // bnc#692260: If the client sends a request with an If-Modified-Since header
1369 // with a future date for the server, the server may respond 200 sending a
1371 // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1372 if ( ftell(file) == 0 && ret == 0 )
1374 long httpReturnCode = 33;
1375 if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1377 long conditionUnmet = 33;
1378 if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1380 WAR << "TIMECONDITION unmet - retry without." << endl;
1381 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1382 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1383 ret = curl_easy_perform( _curl );
1389 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1390 WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1395 ERR << "curl error: " << ret << ": " << _curlError
1396 << ", temp file size " << ftell(file)
1397 << " bytes." << endl;
1399 // the timeout is determined by the progress data object
1400 // which holds wheter the timeout was reached or not,
1401 // otherwise it would be a user cancel
1403 evaluateCurlCode( filename, ret, progressData.reached);
1405 catch ( const MediaException &e ) {
1406 // some error, we are not sure about file existence, rethrw
1411 #if DETECT_DIR_INDEX
1412 if (!ret && detectDirIndex())
1414 ZYPP_THROW(MediaNotAFileException(_url, filename));
1416 #endif // DETECT_DIR_INDEX
1419 ///////////////////////////////////////////////////////////////////
1421 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1423 filesystem::DirContent content;
1424 getDirInfo( content, dirname, /*dots*/false );
1426 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1427 Pathname filename = dirname + it->name;
1430 switch ( it->type ) {
1431 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1432 case filesystem::FT_FILE:
1433 getFile( filename );
1435 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1437 getDir( filename, recurse_r );
1439 res = assert_dir( localPath( filename ) );
1441 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1446 // don't provide devices, sockets, etc.
1452 ///////////////////////////////////////////////////////////////////
1454 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1455 const Pathname & dirname, bool dots ) const
1457 getDirectoryYast( retlist, dirname, dots );
1460 ///////////////////////////////////////////////////////////////////
1462 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1463 const Pathname & dirname, bool dots ) const
1465 getDirectoryYast( retlist, dirname, dots );
1468 ///////////////////////////////////////////////////////////////////
1470 int MediaCurl::progressCallback( void *clientp,
1471 double dltotal, double dlnow,
1472 double ultotal, double ulnow)
1474 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1477 time_t now = time(NULL);
1480 // reset time of last change in case initial time()
1481 // failed or the time was adjusted (goes backward)
1482 if( pdata->ltime <= 0 || pdata->ltime > now)
1487 // start time counting as soon as first data arrives
1488 // (skip the connection / redirection time at begin)
1490 if (dlnow > 0 || ulnow > 0)
1492 dif = (now - pdata->ltime);
1493 dif = dif > 0 ? dif : 0;
1498 // update the drate_avg and drate_period only after a second has passed
1499 // (this callback is called much more often than a second)
1500 // otherwise the values would be far from accurate when measuring
1501 // the time in seconds
1502 //! \todo more accurate download rate computationn, e.g. compute average value from last 5 seconds, or work with milliseconds instead of seconds
1504 if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1505 pdata->drate_avg = (dlnow / pdata->secs);
1509 pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1510 pdata->dload_period = dlnow;
1514 // send progress report first, abort transfer if requested
1517 if (!(*(pdata->report))->progress(int( dltotal ? dlnow * 100 / dltotal : 0 ),
1520 pdata->drate_period))
1522 return 1; // abort transfer
1526 // check if we there is a timeout set
1527 if( pdata->timeout > 0)
1531 bool progress = false;
1533 // update download data if changed, mark progress
1534 if( dlnow != pdata->dload)
1537 pdata->dload = dlnow;
1540 // update upload data if changed, mark progress
1541 if( ulnow != pdata->uload)
1544 pdata->uload = ulnow;
1548 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1550 pdata->reached = true;
1551 return 1; // aborts transfer
1559 ///////////////////////////////////////////////////////////////////
1561 string MediaCurl::getAuthHint() const
1563 long auth_info = CURLAUTH_NONE;
1566 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1568 if(infoRet == CURLE_OK)
1570 return CurlAuthData::auth_type_long2str(auth_info);
1576 ///////////////////////////////////////////////////////////////////
1578 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1580 //! \todo need a way to pass different CredManagerOptions here
1581 Target_Ptr target = zypp::getZYpp()->getTarget();
1582 CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1583 CurlAuthData_Ptr credentials;
1585 // get stored credentials
1586 AuthData_Ptr cmcred = cm.getCred(_url);
1588 if (cmcred && firstTry)
1590 credentials.reset(new CurlAuthData(*cmcred));
1591 DBG << "got stored credentials:" << endl << *credentials << endl;
1593 // if not found, ask user
1597 CurlAuthData_Ptr curlcred;
1598 curlcred.reset(new CurlAuthData());
1599 callback::SendReport<AuthenticationReport> auth_report;
1601 // preset the username if present in current url
1602 if (!_url.getUsername().empty() && firstTry)
1603 curlcred->setUsername(_url.getUsername());
1604 // if CM has found some credentials, preset the username from there
1606 curlcred->setUsername(cmcred->username());
1608 // indicate we have no good credentials from CM
1611 string prompt_msg = boost::str(boost::format(
1612 //!\todo add comma to the message for the next release
1613 _("Authentication required for '%s'")) % _url.asString());
1615 // set available authentication types from the exception
1616 // might be needed in prompt
1617 curlcred->setAuthType(availAuthTypes);
1620 if (auth_report->prompt(_url, prompt_msg, *curlcred))
1622 DBG << "callback answer: retry" << endl
1623 << "CurlAuthData: " << *curlcred << endl;
1625 if (curlcred->valid())
1627 credentials = curlcred;
1628 // if (credentials->username() != _url.getUsername())
1629 // _url.setUsername(credentials->username());
1631 * \todo find a way to save the url with changed username
1632 * back to repoinfo or dont store urls with username
1633 * (and either forbid more repos with the same url and different
1634 * user, or return a set of credentials from CM and try them one
1641 DBG << "callback answer: cancel" << endl;
1645 // set username and password
1648 // HACK, why is this const?
1649 const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1650 const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1652 // set username and password
1653 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1654 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1656 // set available authentication types from the exception
1657 if (credentials->authType() == CURLAUTH_NONE)
1658 credentials->setAuthType(availAuthTypes);
1660 // set auth type (seems this must be set _after_ setting the userpwd)
1661 if (credentials->authType() != CURLAUTH_NONE)
1663 // FIXME: only overwrite if not empty?
1664 const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1665 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1666 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1671 credentials->setUrl(_url);
1672 cm.addCred(*credentials);
1683 } // namespace media