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
49 using namespace zypp::base;
53 zypp::thread::OnceFlag g_InitOnceFlag = PTHREAD_ONCE_INIT;
54 zypp::thread::OnceFlag g_FreeOnceFlag = PTHREAD_ONCE_INIT;
56 extern "C" void _do_free_once()
58 curl_global_cleanup();
61 extern "C" void globalFreeOnce()
63 zypp::thread::callOnce(g_FreeOnceFlag, _do_free_once);
66 extern "C" void _do_init_once()
68 CURLcode ret = curl_global_init( CURL_GLOBAL_ALL );
71 WAR << "curl global init failed" << endl;
75 // register at exit handler ?
76 // this may cause trouble, because we can protect it
77 // against ourself only.
78 // if the app sets an atexit handler as well, it will
79 // cause a double free while the second of them runs.
81 //std::atexit( globalFreeOnce);
84 inline void globalInitOnce()
86 zypp::thread::callOnce(g_InitOnceFlag, _do_init_once);
89 int log_curl(CURL *curl, curl_infotype info,
90 char *ptr, size_t len, void *max_lvl)
96 case CURLINFO_TEXT: lvl = 1; pfx = "*"; break;
97 case CURLINFO_HEADER_IN: lvl = 2; pfx = "<"; break;
98 case CURLINFO_HEADER_OUT: lvl = 2; pfx = ">"; break;
101 if( lvl > 0 && max_lvl != NULL && lvl <= *((long *)max_lvl))
103 std::string msg(ptr, len);
104 std::list<std::string> lines;
105 std::list<std::string>::const_iterator line;
106 zypp::str::split(msg, std::back_inserter(lines), "\r\n");
107 for(line = lines.begin(); line != lines.end(); ++line)
109 DBG << pfx << " " << *line << endl;
117 void *ptr, size_t size, size_t nmemb, void *stream)
119 // INT << "got header: " << string((char *)ptr, ((char*)ptr) + size*nmemb) << endl;
121 char * lstart = (char *)ptr, * lend = (char *)ptr;
123 size_t max = size * nmemb;
124 while (pos + 1 < max)
127 for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
129 // look for "Location"
130 string line(lstart, lend);
131 if (line.find("Location") != string::npos)
133 DBG << "redirecting to " << line << endl;
137 // continue with the next line
157 ProgressData(const long _timeout, const zypp::Url &_url = zypp::Url(),
158 callback::SendReport<DownloadProgressReport> *_report=NULL)
173 callback::SendReport<DownloadProgressReport> *report;
174 // download rate of the last period (cca 1 sec)
176 // bytes downloaded at the start of the last period
178 // seconds from the start of the download
180 // average download rate
182 // last time the progress was reported
184 // bytes downloaded at the moment the progress was last reported
186 // bytes uploaded at the moment the progress was last reported
191 ///////////////////////////////////////////////////////////////////
193 inline void escape( string & str_r,
194 const char char_r, const string & escaped_r ) {
195 for ( string::size_type pos = str_r.find( char_r );
196 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
197 str_r.replace( pos, 1, escaped_r );
201 inline string escapedPath( string path_r ) {
202 escape( path_r, ' ', "%20" );
206 inline string unEscape( string text_r ) {
207 char * tmp = curl_unescape( text_r.c_str(), 0 );
216 * Fills the settings structure using options passed on the url
217 * for example ?timeout=x&proxy=foo
219 void fillSettingsFromUrl( const Url &url, TransferSettings &s )
221 std::string param(url.getQueryParam("timeout"));
224 long num = str::strtonum<long>(param);
225 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
229 if ( ! url.getUsername().empty() )
231 s.setUsername(url.getUsername());
232 if ( url.getPassword().size() )
233 s.setPassword(url.getPassword());
237 // if there is no username, set anonymous auth
238 if ( url.getScheme() == "ftp" && s.username().empty() )
239 s.setAnonymousAuth();
242 if ( url.getScheme() == "https" )
244 s.setVerifyPeerEnabled(false);
245 s.setVerifyHostEnabled(false);
247 std::string verify( url.getQueryParam("ssl_verify"));
248 if( verify.empty() ||
251 s.setVerifyPeerEnabled(true);
252 s.setVerifyHostEnabled(true);
254 else if( verify == "no")
256 s.setVerifyPeerEnabled(false);
257 s.setVerifyHostEnabled(false);
261 std::vector<std::string> flags;
262 std::vector<std::string>::const_iterator flag;
263 str::split( verify, std::back_inserter(flags), ",");
264 for(flag = flags.begin(); flag != flags.end(); ++flag)
267 s.setVerifyHostEnabled(true);
268 else if( *flag == "peer")
269 s.setVerifyPeerEnabled(true);
271 ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
276 Pathname ca_path = Pathname(url.getQueryParam("ssl_capath")).asString();
277 if( ! ca_path.empty())
279 if( !PathInfo(ca_path).isDir() || !Pathname(ca_path).absolute())
280 ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
282 s.setCertificateAuthoritiesPath(ca_path);
285 string proxy = url.getQueryParam( "proxy" );
286 if ( ! proxy.empty() )
288 if ( proxy == "_none_" ) {
289 s.setProxyEnabled(false);
292 string proxyport( url.getQueryParam( "proxyport" ) );
293 if ( ! proxyport.empty() ) {
294 proxy += ":" + proxyport;
297 s.setProxyEnabled(true);
301 // HTTP authentication type
302 string use_auth = url.getQueryParam("auth");
303 if (!use_auth.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
307 CurlAuthData::auth_type_str2long(use_auth); // check if we know it
309 catch (MediaException & ex_r)
311 DBG << "Rethrowing as MediaUnauthorizedException.";
312 ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
314 s.setAuthType(use_auth);
318 std::string head_requests( url.getQueryParam("head_requests"));
319 if( !head_requests.empty() && head_requests == "no")
320 s.setHeadRequestsAllowed(false);
324 * Reads the system proxy configuration and fills the settings
325 * structure proxy information
327 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
329 ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
330 s.setProxyEnabled( proxy_info.useProxyFor( url ) );
331 if ( s.proxyEnabled() )
332 s.setProxy(proxy_info.proxy(url.getScheme()));
335 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
338 * initialized only once, this gets the anonymous id
339 * from the target, which we pass in the http header
341 static const char *const anonymousIdHeader()
343 // we need to add the release and identifier to the
345 // The target could be not initialized, and then this information
347 static const std::string _value(
348 str::trim( str::form(
349 "X-ZYpp-AnonymousId: %s",
350 Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
352 return _value.c_str();
356 * initialized only once, this gets the distribution flavor
357 * from the target, which we pass in the http header
359 static const char *const distributionFlavorHeader()
361 // we need to add the release and identifier to the
363 // The target could be not initialized, and then this information
365 static const std::string _value(
366 str::trim( str::form(
367 "X-ZYpp-DistributionFlavor: %s",
368 Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
370 return _value.c_str();
374 * initialized only once, this gets the agent string
375 * which also includes the curl version
377 static const char *const agentString()
379 // we need to add the release and identifier to the
381 // The target could be not initialized, and then this information
383 static const std::string _value(
385 "ZYpp %s (curl %s) %s"
387 , curl_version_info(CURLVERSION_NOW)->version
388 , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
391 return _value.c_str();
394 // we use this define to unbloat code as this C setting option
395 // and catching exception is done frequently.
396 /** \todo deprecate SET_OPTION and use the typed versions below. */
397 #define SET_OPTION(opt,val) do { \
398 ret = curl_easy_setopt ( _curl, opt, val ); \
400 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
404 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
405 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
406 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
408 MediaCurl::MediaCurl( const Url & url_r,
409 const Pathname & attach_point_hint_r )
410 : MediaHandler( url_r, attach_point_hint_r,
411 "/", // urlpath at attachpoint
412 true ), // does_download
416 _curlError[0] = '\0';
419 MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
423 if( !attachPoint().empty())
425 PathInfo ainfo(attachPoint());
426 Pathname apath(attachPoint() + "XXXXXX");
427 char *atemp = ::strdup( apath.asString().c_str());
429 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
430 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
432 WAR << "attach point " << ainfo.path()
433 << " is not useable for " << url_r.getScheme() << endl;
434 setAttachPoint("", true);
436 else if( atest != NULL)
444 Url MediaCurl::clearQueryString(const Url &url) const
447 curlUrl.setUsername( "" );
448 curlUrl.setPassword( "" );
449 curlUrl.setPathParams( "" );
450 curlUrl.setFragment( "" );
451 curlUrl.delQueryParam("cookies");
452 curlUrl.delQueryParam("proxy");
453 curlUrl.delQueryParam("proxyport");
454 curlUrl.delQueryParam("proxyuser");
455 curlUrl.delQueryParam("proxypass");
456 curlUrl.delQueryParam("ssl_capath");
457 curlUrl.delQueryParam("ssl_verify");
458 curlUrl.delQueryParam("timeout");
459 curlUrl.delQueryParam("auth");
460 curlUrl.delQueryParam("username");
461 curlUrl.delQueryParam("password");
462 curlUrl.delQueryParam("mediahandler");
466 TransferSettings & MediaCurl::settings()
472 void MediaCurl::setCookieFile( const Pathname &fileName )
474 _cookieFile = fileName;
477 ///////////////////////////////////////////////////////////////////
479 void MediaCurl::checkProtocol(const Url &url) const
481 curl_version_info_data *curl_info = NULL;
482 curl_info = curl_version_info(CURLVERSION_NOW);
483 // curl_info does not need any free (is static)
484 if (curl_info->protocols)
486 const char * const *proto;
487 std::string scheme( url.getScheme());
489 for(proto=curl_info->protocols; !found && *proto; ++proto)
491 if( scheme == std::string((const char *)*proto))
496 std::string msg("Unsupported protocol '");
499 ZYPP_THROW(MediaBadUrlException(_url, msg));
504 void MediaCurl::setupEasy()
507 char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
508 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
511 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
512 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
513 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
517 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
518 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
520 ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
523 SET_OPTION(CURLOPT_FAILONERROR, 1L);
524 SET_OPTION(CURLOPT_NOSIGNAL, 1L);
526 // create non persistant settings
527 // so that we don't add headers twice
528 TransferSettings vol_settings(_settings);
530 // add custom headers
531 vol_settings.addHeader(anonymousIdHeader());
532 vol_settings.addHeader(distributionFlavorHeader());
533 vol_settings.addHeader("Pragma:");
535 _settings.setTimeout(TRANSFER_TIMEOUT);
536 _settings.setConnectTimeout(CONNECT_TIMEOUT);
538 _settings.setUserAgentString(agentString());
540 // fill some settings from url query parameters
543 fillSettingsFromUrl(_url, _settings);
545 catch ( const MediaException &e )
551 // if the proxy was not set by url, then look
552 if ( _settings.proxy().empty() )
554 // at the system proxy settings
555 fillSettingsSystemProxy(_url, _settings);
558 DBG << "Proxy: " << (_settings.proxy().empty() ? "-none-" : _settings.proxy()) << endl;
563 SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
565 // follow any Location: header that the server sends as part of
566 // an HTTP header (#113275)
567 SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
568 // 3 redirects seem to be too few in some cases (bnc #465532)
569 SET_OPTION(CURLOPT_MAXREDIRS, 6L);
571 if ( _url.getScheme() == "https" )
573 // restrict following of redirections from https to https only
574 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
576 if( _settings.verifyPeerEnabled() ||
577 _settings.verifyHostEnabled() )
579 SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
582 SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
583 SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
586 SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
588 /*---------------------------------------------------------------*
589 CURLOPT_USERPWD: [user name]:[password]
591 Url::username/password -> CURLOPT_USERPWD
592 If not provided, anonymous FTP identification
593 *---------------------------------------------------------------*/
595 if ( _settings.userPassword().size() )
597 SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
598 string use_auth = _settings.authType();
599 if (use_auth.empty())
600 use_auth = "digest,basic"; // our default
601 long auth = CurlAuthData::auth_type_str2long(use_auth);
602 if( auth != CURLAUTH_NONE)
604 DBG << "Enabling HTTP authentication methods: " << use_auth
605 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
606 SET_OPTION(CURLOPT_HTTPAUTH, auth);
610 if ( _settings.proxyEnabled() )
612 if ( ! _settings.proxy().empty() )
614 SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
615 /*---------------------------------------------------------------*
616 CURLOPT_PROXYUSERPWD: [user name]:[password]
618 Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
619 If not provided, $HOME/.curlrc is evaluated
620 *---------------------------------------------------------------*/
622 string proxyuserpwd = _settings.proxyUserPassword();
624 if ( proxyuserpwd.empty() )
627 CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
628 if (curlconf.proxyuserpwd.empty())
629 DBG << "~/.curlrc does not contain the proxy-user option" << endl;
632 proxyuserpwd = curlconf.proxyuserpwd;
633 DBG << "using proxy-user from ~/.curlrc" << endl;
637 proxyuserpwd = unEscape( proxyuserpwd );
638 if ( ! proxyuserpwd.empty() )
639 SET_OPTION(CURLOPT_PROXYUSERPWD, proxyuserpwd.c_str());
644 SET_OPTION(CURLOPT_NOPROXY, "*");
648 if ( _settings.minDownloadSpeed() != 0 )
650 SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
651 // default to 10 seconds at low speed
652 SET_OPTION(CURLOPT_LOW_SPEED_TIME, 10L);
655 if ( _settings.maxDownloadSpeed() != 0 )
656 SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
658 /*---------------------------------------------------------------*
659 *---------------------------------------------------------------*/
661 _currentCookieFile = _cookieFile.asString();
662 if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
663 SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
665 MIL << "No cookies requested" << endl;
666 SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
667 SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
668 SET_OPTION(CURLOPT_NOPROGRESS, 0L);
671 SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
673 // append settings custom headers to curl
674 for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
675 it != vol_settings.headersEnd();
678 MIL << "HEADER " << *it << std::endl;
680 _customHeaders = curl_slist_append(_customHeaders, it->c_str());
681 if ( !_customHeaders )
682 ZYPP_THROW(MediaCurlInitException(_url));
685 SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
688 ///////////////////////////////////////////////////////////////////
691 void MediaCurl::attachTo (bool next)
694 ZYPP_THROW(MediaNotSupportedException(_url));
696 if ( !_url.isValid() )
697 ZYPP_THROW(MediaBadUrlException(_url));
700 if( !isUseableAttachPoint(attachPoint()))
702 std::string mountpoint = createAttachPoint().asString();
704 if( mountpoint.empty())
705 ZYPP_THROW( MediaBadAttachPointException(url()));
707 setAttachPoint( mountpoint, true);
710 disconnectFrom(); // clean _curl if needed
711 _curl = curl_easy_init();
713 ZYPP_THROW(MediaCurlInitException(_url));
719 catch (Exception & ex)
725 // FIXME: need a derived class to propelly compare url's
726 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
727 setMediaSource(media);
731 MediaCurl::checkAttachPoint(const Pathname &apoint) const
733 return MediaHandler::checkAttachPoint( apoint, true, true);
736 ///////////////////////////////////////////////////////////////////
738 void MediaCurl::disconnectFrom()
740 if ( _customHeaders )
742 curl_slist_free_all(_customHeaders);
748 curl_easy_cleanup( _curl );
753 ///////////////////////////////////////////////////////////////////
755 void MediaCurl::releaseFrom( const std::string & ejectDev )
760 Url MediaCurl::getFileUrl(const Pathname & filename) const
763 string path = _url.getPathName();
764 if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
765 filename.absolute() )
767 // If url has a path with trailing slash, remove the leading slash from
768 // the absolute file name
769 path += filename.asString().substr( 1, filename.asString().size() - 1 );
771 else if ( filename.relative() )
773 // Add trailing slash to path, if not already there
774 if (path.empty()) path = "/";
775 else if (*path.rbegin() != '/' ) path += "/";
776 // Remove "./" from begin of relative file name
777 path += filename.asString().substr( 2, filename.asString().size() - 2 );
781 path += filename.asString();
784 newurl.setPathName(path);
788 ///////////////////////////////////////////////////////////////////
790 void MediaCurl::getFile( const Pathname & filename ) const
792 // Use absolute file name to prevent access of files outside of the
793 // hierarchy below the attach point.
794 getFileCopy(filename, localPath(filename).absolutename());
797 ///////////////////////////////////////////////////////////////////
799 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
801 callback::SendReport<DownloadProgressReport> report;
803 Url fileurl(getFileUrl(filename));
811 doGetFileCopy(filename, target, report);
814 // retry with proper authentication data
815 catch (MediaUnauthorizedException & ex_r)
817 if(authenticate(ex_r.hint(), !retry))
821 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
825 // unexpected exception
826 catch (MediaException & excpt_r)
828 // FIXME: error number fix
829 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
830 ZYPP_RETHROW(excpt_r);
835 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
838 ///////////////////////////////////////////////////////////////////
840 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
848 return doGetDoesFileExist( filename );
850 // authentication problem, retry with proper authentication data
851 catch (MediaUnauthorizedException & ex_r)
853 if(authenticate(ex_r.hint(), !retry))
858 // unexpected exception
859 catch (MediaException & excpt_r)
861 ZYPP_RETHROW(excpt_r);
869 ///////////////////////////////////////////////////////////////////
871 void MediaCurl::evaluateCurlCode( const Pathname &filename,
873 bool timeout_reached ) const
878 if (filename.empty())
881 url = getFileUrl(filename);
887 case CURLE_UNSUPPORTED_PROTOCOL:
888 case CURLE_URL_MALFORMAT:
889 case CURLE_URL_MALFORMAT_USER:
891 case CURLE_LOGIN_DENIED:
893 MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
895 case CURLE_HTTP_RETURNED_ERROR:
897 long httpReturnCode = 0;
898 CURLcode infoRet = curl_easy_getinfo( _curl,
899 CURLINFO_RESPONSE_CODE,
901 if ( infoRet == CURLE_OK )
903 string msg = "HTTP response: " + str::numstring( httpReturnCode );
904 switch ( httpReturnCode )
908 string auth_hint = getAuthHint();
910 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
911 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
913 ZYPP_THROW(MediaUnauthorizedException(
914 url, "Login failed.", _curlError, auth_hint
918 case 503: // service temporarily unavailable (bnc #462545)
919 ZYPP_THROW(MediaTemporaryProblemException(url));
920 case 504: // gateway timeout
921 ZYPP_THROW(MediaTimeoutException(url));
925 if (url.asString().find("novell.com") != string::npos)
926 msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
927 ZYPP_THROW(MediaForbiddenException(url, msg403));
930 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
933 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
934 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
938 string msg = "Unable to retrieve HTTP response:";
939 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
940 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
944 case CURLE_FTP_COULDNT_RETR_FILE:
945 case CURLE_FTP_ACCESS_DENIED:
946 err = "File not found";
947 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
949 case CURLE_BAD_PASSWORD_ENTERED:
950 case CURLE_FTP_USER_PASSWORD_INCORRECT:
951 err = "Login failed";
953 case CURLE_COULDNT_RESOLVE_PROXY:
954 case CURLE_COULDNT_RESOLVE_HOST:
955 case CURLE_COULDNT_CONNECT:
956 case CURLE_FTP_CANT_GET_HOST:
957 err = "Connection failed";
959 case CURLE_WRITE_ERROR:
962 case CURLE_PARTIAL_FILE:
963 case CURLE_ABORTED_BY_CALLBACK:
964 case CURLE_OPERATION_TIMEDOUT:
967 err = "Timeout reached";
968 ZYPP_THROW(MediaTimeoutException(url));
975 case CURLE_SSL_PEER_CERTIFICATE:
977 err = "Unrecognized error";
981 // uhm, no 0 code but unknown curl exception
982 ZYPP_THROW(MediaCurlException(url, err, _curlError));
984 catch (const MediaException & excpt_r)
986 ZYPP_RETHROW(excpt_r);
991 // actually the code is 0, nothing happened
995 ///////////////////////////////////////////////////////////////////
997 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
999 DBG << filename.asString() << endl;
1002 ZYPP_THROW(MediaBadUrlException(_url));
1004 if(_url.getHost().empty())
1005 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1007 Url url(getFileUrl(filename));
1009 DBG << "URL: " << url.asString() << endl;
1010 // Use URL without options and without username and passwd
1011 // (some proxies dislike them in the URL).
1012 // Curl seems to need the just scheme, hostname and a path;
1013 // the rest was already passed as curl options (in attachTo).
1014 Url curlUrl( clearQueryString(url) );
1017 // See also Bug #154197 and ftp url definition in RFC 1738:
1018 // The url "ftp://user@host/foo/bar/file" contains a path,
1019 // that is relative to the user's home.
1020 // The url "ftp://user@host//foo/bar/file" (or also with
1021 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1022 // contains an absolute path.
1024 string urlBuffer( curlUrl.asString());
1025 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1026 urlBuffer.c_str() );
1028 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1031 // instead of returning no data with NOBODY, we return
1032 // little data, that works with broken servers, and
1033 // works for ftp as well, because retrieving only headers
1034 // ftp will return always OK code ?
1035 // See http://curl.haxx.se/docs/knownbugs.html #58
1036 if ( (_url.getScheme() == "http" || _url.getScheme() == "https") &&
1037 _settings.headRequestsAllowed() )
1038 ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1040 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1043 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1044 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1045 /* yes, this is why we never got to get NOBODY working before,
1046 because setting it changes this option too, and we also
1048 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1050 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1051 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1054 FILE *file = ::fopen( "/dev/null", "w" );
1057 ERR << "fopen failed for /dev/null" << endl;
1058 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1059 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1060 /* yes, this is why we never got to get NOBODY working before,
1061 because setting it changes this option too, and we also
1063 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1065 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1067 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1069 ZYPP_THROW(MediaWriteException("/dev/null"));
1072 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1075 std::string err( _curlError);
1076 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1077 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1078 /* yes, this is why we never got to get NOBODY working before,
1079 because setting it changes this option too, and we also
1081 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1083 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1085 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1087 ZYPP_THROW(MediaCurlSetOptException(url, err));
1090 CURLcode ok = curl_easy_perform( _curl );
1091 MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1093 // reset curl settings
1094 if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1096 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1098 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1101 /* yes, this is why we never got to get NOBODY working before,
1102 because setting it changes this option too, and we also
1104 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1106 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1108 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1114 // for FTP we set different options
1115 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1117 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1121 // if the code is not zero, close the file
1125 // as we are not having user interaction, the user can't cancel
1126 // the file existence checking, a callback or timeout return code
1127 // will be always a timeout.
1129 evaluateCurlCode( filename, ok, true /* timeout */);
1131 catch ( const MediaFileNotFoundException &e ) {
1132 // if the file did not exist then we can return false
1135 catch ( const MediaException &e ) {
1136 // some error, we are not sure about file existence, rethrw
1140 return ( ok == CURLE_OK );
1143 ///////////////////////////////////////////////////////////////////
1146 #if DETECT_DIR_INDEX
1147 bool MediaCurl::detectDirIndex() const
1149 if(_url.getScheme() != "http" && _url.getScheme() != "https")
1152 // try to check the effective url and set the not_a_file flag
1153 // if the url path ends with a "/", what usually means, that
1154 // we've received a directory index (index.html content).
1156 // Note: This may be dangerous and break file retrieving in
1157 // case of some server redirections ... ?
1159 bool not_a_file = false;
1161 CURLcode ret = curl_easy_getinfo( _curl,
1162 CURLINFO_EFFECTIVE_URL,
1164 if ( ret == CURLE_OK && ptr != NULL)
1169 std::string path( eurl.getPathName());
1170 if( !path.empty() && path != "/" && *path.rbegin() == '/')
1172 DBG << "Effective url ("
1174 << ") seems to provide the index of a directory"
1186 ///////////////////////////////////////////////////////////////////
1188 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1190 Pathname dest = target.absolutename();
1191 if( assert_dir( dest.dirname() ) )
1193 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1194 Url url(getFileUrl(filename));
1195 ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1197 string destNew = target.asString() + ".new.zypp.XXXXXX";
1198 char *buf = ::strdup( destNew.c_str());
1201 ERR << "out of memory for temp file name" << endl;
1202 Url url(getFileUrl(filename));
1203 ZYPP_THROW(MediaSystemException(url, "out of memory for temp file name"));
1206 int tmp_fd = ::mkstemp( buf );
1210 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1211 ZYPP_THROW(MediaWriteException(destNew));
1216 FILE *file = ::fdopen( tmp_fd, "w" );
1219 filesystem::unlink( destNew );
1220 ERR << "fopen failed for file '" << destNew << "'" << endl;
1221 ZYPP_THROW(MediaWriteException(destNew));
1224 DBG << "dest: " << dest << endl;
1225 DBG << "temp: " << destNew << endl;
1227 // set IFMODSINCE time condition (no download if not modified)
1228 if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1230 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1231 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1235 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1236 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1240 doGetFileCopyFile(filename, dest, file, report, options);
1242 catch (Exception &e)
1245 filesystem::unlink( destNew );
1246 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1247 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1251 long httpReturnCode = 0;
1252 CURLcode infoRet = curl_easy_getinfo(_curl,
1253 CURLINFO_RESPONSE_CODE,
1255 bool modified = true;
1256 if (infoRet == CURLE_OK)
1258 DBG << "HTTP response: " + str::numstring(httpReturnCode);
1259 if ( httpReturnCode == 304
1260 || ( httpReturnCode == 213 && _url.getScheme() == "ftp" ) ) // not modified
1262 DBG << " Not modified.";
1269 WAR << "Could not get the reponse code." << endl;
1272 if (modified || infoRet != CURLE_OK)
1275 if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1277 ERR << "Failed to chmod file " << destNew << endl;
1279 if (::fclose( file ))
1281 ERR << "Fclose failed for file '" << destNew << "'" << endl;
1282 ZYPP_THROW(MediaWriteException(destNew));
1284 // move the temp file into dest
1285 if ( rename( destNew, dest ) != 0 ) {
1286 ERR << "Rename failed" << endl;
1287 ZYPP_THROW(MediaWriteException(dest));
1292 // close and remove the temp file
1294 filesystem::unlink( destNew );
1297 DBG << "done: " << PathInfo(dest) << endl;
1300 ///////////////////////////////////////////////////////////////////
1302 void MediaCurl::doGetFileCopyFile( const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1304 DBG << filename.asString() << endl;
1307 ZYPP_THROW(MediaBadUrlException(_url));
1309 if(_url.getHost().empty())
1310 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1312 Url url(getFileUrl(filename));
1314 DBG << "URL: " << url.asString() << endl;
1315 // Use URL without options and without username and passwd
1316 // (some proxies dislike them in the URL).
1317 // Curl seems to need the just scheme, hostname and a path;
1318 // the rest was already passed as curl options (in attachTo).
1319 Url curlUrl( clearQueryString(url) );
1322 // See also Bug #154197 and ftp url definition in RFC 1738:
1323 // The url "ftp://user@host/foo/bar/file" contains a path,
1324 // that is relative to the user's home.
1325 // The url "ftp://user@host//foo/bar/file" (or also with
1326 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1327 // contains an absolute path.
1329 string urlBuffer( curlUrl.asString());
1330 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1331 urlBuffer.c_str() );
1333 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1336 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1338 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1341 // Set callback and perform.
1342 ProgressData progressData(_settings.timeout(), url, &report);
1343 if (!(options & OPTION_NO_REPORT_START))
1344 report->start(url, dest);
1345 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1346 WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1349 ret = curl_easy_perform( _curl );
1351 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1352 WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1357 ERR << "curl error: " << ret << ": " << _curlError
1358 << ", temp file size " << ftell(file)
1359 << " bytes." << endl;
1361 // the timeout is determined by the progress data object
1362 // which holds wheter the timeout was reached or not,
1363 // otherwise it would be a user cancel
1365 evaluateCurlCode( filename, ret, progressData.reached);
1367 catch ( const MediaException &e ) {
1368 // some error, we are not sure about file existence, rethrw
1373 #if DETECT_DIR_INDEX
1374 if (!ret && detectDirIndex())
1376 ZYPP_THROW(MediaNotAFileException(_url, filename));
1378 #endif // DETECT_DIR_INDEX
1381 ///////////////////////////////////////////////////////////////////
1383 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1385 filesystem::DirContent content;
1386 getDirInfo( content, dirname, /*dots*/false );
1388 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1389 Pathname filename = dirname + it->name;
1392 switch ( it->type ) {
1393 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1394 case filesystem::FT_FILE:
1395 getFile( filename );
1397 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1399 getDir( filename, recurse_r );
1401 res = assert_dir( localPath( filename ) );
1403 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1408 // don't provide devices, sockets, etc.
1414 ///////////////////////////////////////////////////////////////////
1416 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1417 const Pathname & dirname, bool dots ) const
1419 getDirectoryYast( retlist, dirname, dots );
1422 ///////////////////////////////////////////////////////////////////
1424 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1425 const Pathname & dirname, bool dots ) const
1427 getDirectoryYast( retlist, dirname, dots );
1430 ///////////////////////////////////////////////////////////////////
1432 int MediaCurl::progressCallback( void *clientp,
1433 double dltotal, double dlnow,
1434 double ultotal, double ulnow)
1436 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1439 time_t now = time(NULL);
1442 // reset time of last change in case initial time()
1443 // failed or the time was adjusted (goes backward)
1444 if( pdata->ltime <= 0 || pdata->ltime > now)
1449 // start time counting as soon as first data arrives
1450 // (skip the connection / redirection time at begin)
1452 if (dlnow > 0 || ulnow > 0)
1454 dif = (now - pdata->ltime);
1455 dif = dif > 0 ? dif : 0;
1460 // update the drate_avg and drate_period only after a second has passed
1461 // (this callback is called much more often than a second)
1462 // otherwise the values would be far from accurate when measuring
1463 // the time in seconds
1464 //! \todo more accurate download rate computationn, e.g. compute average value from last 5 seconds, or work with milliseconds instead of seconds
1466 if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1467 pdata->drate_avg = (dlnow / pdata->secs);
1471 pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1472 pdata->dload_period = dlnow;
1476 // send progress report first, abort transfer if requested
1479 if (!(*(pdata->report))->progress(int( dltotal ? dlnow * 100 / dltotal : 0 ),
1482 pdata->drate_period))
1484 return 1; // abort transfer
1488 // check if we there is a timeout set
1489 if( pdata->timeout > 0)
1493 bool progress = false;
1495 // update download data if changed, mark progress
1496 if( dlnow != pdata->dload)
1499 pdata->dload = dlnow;
1502 // update upload data if changed, mark progress
1503 if( ulnow != pdata->uload)
1506 pdata->uload = ulnow;
1510 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1512 pdata->reached = true;
1513 return 1; // aborts transfer
1521 ///////////////////////////////////////////////////////////////////
1523 string MediaCurl::getAuthHint() const
1525 long auth_info = CURLAUTH_NONE;
1528 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1530 if(infoRet == CURLE_OK)
1532 return CurlAuthData::auth_type_long2str(auth_info);
1538 ///////////////////////////////////////////////////////////////////
1540 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1542 //! \todo need a way to pass different CredManagerOptions here
1543 Target_Ptr target = zypp::getZYpp()->getTarget();
1544 CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1545 CurlAuthData_Ptr credentials;
1547 // get stored credentials
1548 AuthData_Ptr cmcred = cm.getCred(_url);
1550 if (cmcred && firstTry)
1552 credentials.reset(new CurlAuthData(*cmcred));
1553 DBG << "got stored credentials:" << endl << *credentials << endl;
1555 // if not found, ask user
1559 CurlAuthData_Ptr curlcred;
1560 curlcred.reset(new CurlAuthData());
1561 callback::SendReport<AuthenticationReport> auth_report;
1563 // preset the username if present in current url
1564 if (!_url.getUsername().empty() && firstTry)
1565 curlcred->setUsername(_url.getUsername());
1566 // if CM has found some credentials, preset the username from there
1568 curlcred->setUsername(cmcred->username());
1570 // indicate we have no good credentials from CM
1573 string prompt_msg = boost::str(boost::format(
1574 //!\todo add comma to the message for the next release
1575 _("Authentication required for '%s'")) % _url.asString());
1577 // set available authentication types from the exception
1578 // might be needed in prompt
1579 curlcred->setAuthType(availAuthTypes);
1582 if (auth_report->prompt(_url, prompt_msg, *curlcred))
1584 DBG << "callback answer: retry" << endl
1585 << "CurlAuthData: " << *curlcred << endl;
1587 if (curlcred->valid())
1589 credentials = curlcred;
1590 // if (credentials->username() != _url.getUsername())
1591 // _url.setUsername(credentials->username());
1593 * \todo find a way to save the url with changed username
1594 * back to repoinfo or dont store urls with username
1595 * (and either forbid more repos with the same url and different
1596 * user, or return a set of credentials from CM and try them one
1603 DBG << "callback answer: cancel" << endl;
1607 // set username and password
1610 // HACK, why is this const?
1611 const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1612 const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1614 // set username and password
1615 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1616 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1618 // set available authentication types from the exception
1619 if (credentials->authType() == CURLAUTH_NONE)
1620 credentials->setAuthType(availAuthTypes);
1622 // set auth type (seems this must be set _after_ setting the userpwd)
1623 if (credentials->authType() != CURLAUTH_NONE)
1625 // FIXME: only overwrite if not empty?
1626 const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1627 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1628 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1633 credentials->setUrl(_url);
1634 cm.addCred(*credentials);
1645 } // namespace media