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 string proxyport( url.getQueryParam( "proxyport" ) );
289 if ( ! proxyport.empty() ) {
290 proxy += ":" + proxyport;
293 s.setProxyEnabled(true);
298 * Reads the system proxy configuration and fills the settings
299 * structure proxy information
301 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
303 ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
304 s.setProxyEnabled( proxy_info.useProxyFor( url ) );
305 if ( s.proxyEnabled() )
306 s.setProxy(proxy_info.proxy(url.getScheme()));
309 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
312 * initialized only once, this gets the anonymous id
313 * from the target, which we pass in the http header
315 static const char *const anonymousIdHeader()
317 // we need to add the release and identifier to the
319 // The target could be not initialized, and then this information
321 static const std::string _value(
322 str::trim( str::form(
323 "X-ZYpp-AnonymousId: %s",
324 Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
326 return _value.c_str();
330 * initialized only once, this gets the distribution flavor
331 * from the target, which we pass in the http header
333 static const char *const distributionFlavorHeader()
335 // we need to add the release and identifier to the
337 // The target could be not initialized, and then this information
339 static const std::string _value(
340 str::trim( str::form(
341 "X-ZYpp-DistributionFlavor: %s",
342 Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
344 return _value.c_str();
348 * initialized only once, this gets the agent string
349 * which also includes the curl version
351 static const char *const agentString()
353 // we need to add the release and identifier to the
355 // The target could be not initialized, and then this information
357 static const std::string _value(
359 "ZYpp %s (curl %s) %s"
361 , curl_version_info(CURLVERSION_NOW)->version
362 , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
365 return _value.c_str();
368 // we use this define to unbloat code as this C setting option
369 // and catching exception is done frequently.
370 #define SET_OPTION(opt,val) { \
371 ret = curl_easy_setopt ( _curl, opt, val ); \
374 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
378 MediaCurl::MediaCurl( const Url & url_r,
379 const Pathname & attach_point_hint_r )
380 : MediaHandler( url_r, attach_point_hint_r,
381 "/", // urlpath at attachpoint
382 true ), // does_download
386 _curlError[0] = '\0';
389 MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
393 if( !attachPoint().empty())
395 PathInfo ainfo(attachPoint());
396 Pathname apath(attachPoint() + "XXXXXX");
397 char *atemp = ::strdup( apath.asString().c_str());
399 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
400 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
402 WAR << "attach point " << ainfo.path()
403 << " is not useable for " << url_r.getScheme() << endl;
404 setAttachPoint("", true);
406 else if( atest != NULL)
414 void MediaCurl::setCookieFile( const Pathname &fileName )
416 _cookieFile = fileName;
419 ///////////////////////////////////////////////////////////////////
421 void MediaCurl::attachTo (bool next)
424 ZYPP_THROW(MediaNotSupportedException(_url));
426 if ( !_url.isValid() )
427 ZYPP_THROW(MediaBadUrlException(_url));
430 CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
432 curl_version_info_data *curl_info = NULL;
433 curl_info = curl_version_info(CURLVERSION_NOW);
434 // curl_info does not need any free (is static)
435 if (curl_info->protocols)
437 const char * const *proto;
438 std::string scheme( _url.getScheme());
440 for(proto=curl_info->protocols; !found && *proto; ++proto)
442 if( scheme == std::string((const char *)*proto))
447 std::string msg("Unsupported protocol '");
450 ZYPP_THROW(MediaBadUrlException(_url, msg));
454 if( !isUseableAttachPoint(attachPoint()))
456 std::string mountpoint = createAttachPoint().asString();
458 if( mountpoint.empty())
459 ZYPP_THROW( MediaBadAttachPointException(url()));
461 setAttachPoint( mountpoint, true);
464 disconnectFrom(); // clean _curl if needed
465 _curl = curl_easy_init();
467 ZYPP_THROW(MediaCurlInitException(_url));
471 char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
472 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
475 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1);
476 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
477 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
481 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
483 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
486 ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
489 SET_OPTION(CURLOPT_FAILONERROR,true);
490 SET_OPTION(CURLOPT_NOSIGNAL, 1);
492 // reset settings in case we are re-attaching
495 // add custom headers
496 _settings.addHeader(anonymousIdHeader());
497 _settings.addHeader(distributionFlavorHeader());
498 _settings.addHeader("Pragma:");
500 _settings.setTimeout(TRANSFER_TIMEOUT);
501 _settings.setConnectTimeout(CONNECT_TIMEOUT);
503 _settings.setUserAgentString(agentString());
505 // fill some settings from url query parameters
508 fillSettingsFromUrl(_url, _settings);
510 catch ( const MediaException &e )
516 // if the proxy was not set by url, then look
517 if ( _settings.proxy().empty() )
519 // at the system proxy settings
520 fillSettingsSystemProxy(_url, _settings);
523 DBG << "Proxy: " << (_settings.proxy().empty() ? "-none-" : _settings.proxy()) << endl;
528 SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
530 // follow any Location: header that the server sends as part of
531 // an HTTP header (#113275)
532 SET_OPTION(CURLOPT_FOLLOWLOCATION, true);
533 // 3 redirects seem to be too few in some cases (bnc #465532)
534 SET_OPTION(CURLOPT_MAXREDIRS, 6L);
536 if ( _url.getScheme() == "https" )
538 // restrict following of redirections from https to https only
539 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
541 if( _settings.verifyPeerEnabled() ||
542 _settings.verifyHostEnabled() )
544 SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
547 SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
548 SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
551 SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
553 /*---------------------------------------------------------------*
554 CURLOPT_USERPWD: [user name]:[password]
556 Url::username/password -> CURLOPT_USERPWD
557 If not provided, anonymous FTP identification
558 *---------------------------------------------------------------*/
560 if ( _settings.userPassword().size() )
562 SET_OPTION(CURLOPT_USERPWD, unEscape(_settings.userPassword()).c_str());
564 //FIXME, we leave this here for now, as it does not make sense yet
565 // to refactor it to the fill settings from url function
567 // HTTP authentication type
568 if(_url.getScheme() == "http" || _url.getScheme() == "https")
570 string use_auth = _url.getQueryParam("auth");
571 if( use_auth.empty())
572 use_auth = "digest,basic";
576 long auth = CurlAuthData::auth_type_str2long(use_auth);
577 if( auth != CURLAUTH_NONE)
579 DBG << "Enabling HTTP authentication methods: " << use_auth
580 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
582 SET_OPTION(CURLOPT_HTTPAUTH, auth);
585 catch (MediaException & ex_r)
587 string auth_hint = getAuthHint();
589 DBG << "Rethrowing as MediaUnauthorizedException. auth hint: '"
590 << auth_hint << "'" << endl;
592 ZYPP_THROW(MediaUnauthorizedException(
593 _url, ex_r.msg(), _curlError, auth_hint
599 if ( _settings.proxyEnabled() )
601 if ( ! _settings.proxy().empty() )
603 SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
604 /*---------------------------------------------------------------*
605 CURLOPT_PROXYUSERPWD: [user name]:[password]
607 Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
608 If not provided, $HOME/.curlrc is evaluated
609 *---------------------------------------------------------------*/
611 string proxyuserpwd = _settings.proxyUserPassword();
613 if ( proxyuserpwd.empty() )
615 if (curlconf.proxyuserpwd.empty())
616 DBG << "~/.curlrc does not contain the proxy-user option" << endl;
619 proxyuserpwd = curlconf.proxyuserpwd;
620 DBG << "using proxy-user from ~/.curlrc" << endl;
624 proxyuserpwd = unEscape( proxyuserpwd );
625 if ( ! proxyuserpwd.empty() )
626 SET_OPTION(CURLOPT_PROXYUSERPWD, proxyuserpwd.c_str());
631 if ( _settings.minDownloadSpeed() != 0 )
633 SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
634 // default to 10 seconds at low speed
635 SET_OPTION(CURLOPT_LOW_SPEED_TIME, 10);
638 if ( _settings.maxDownloadSpeed() != 0 )
639 SET_OPTION(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
641 /*---------------------------------------------------------------*
642 *---------------------------------------------------------------*/
644 _currentCookieFile = _cookieFile.asString();
645 SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
646 SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
647 SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
648 SET_OPTION(CURLOPT_NOPROGRESS, false );
651 SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1 );
653 // append settings custom headers to curl
654 for ( TransferSettings::Headers::const_iterator it = _settings.headersBegin();
655 it != _settings.headersEnd();
659 _customHeaders = curl_slist_append(_customHeaders, it->c_str());
660 if ( !_customHeaders )
661 ZYPP_THROW(MediaCurlInitException(_url));
664 SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
666 // FIXME: need a derived class to propelly compare url's
667 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
668 setMediaSource(media);
672 MediaCurl::checkAttachPoint(const Pathname &apoint) const
674 return MediaHandler::checkAttachPoint( apoint, true, true);
677 ///////////////////////////////////////////////////////////////////
679 void MediaCurl::disconnectFrom()
681 if ( _customHeaders )
683 curl_slist_free_all(_customHeaders);
689 curl_easy_cleanup( _curl );
694 ///////////////////////////////////////////////////////////////////
696 void MediaCurl::releaseFrom( const std::string & ejectDev )
701 static Url getFileUrl(const Url & url, const Pathname & filename)
704 string path = url.getPathName();
705 if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
706 filename.absolute() )
708 // If url has a path with trailing slash, remove the leading slash from
709 // the absolute file name
710 path += filename.asString().substr( 1, filename.asString().size() - 1 );
712 else if ( filename.relative() )
714 // Add trailing slash to path, if not already there
715 if (path.empty()) path = "/";
716 else if (*path.rbegin() != '/' ) path += "/";
717 // Remove "./" from begin of relative file name
718 path += filename.asString().substr( 2, filename.asString().size() - 2 );
722 path += filename.asString();
725 newurl.setPathName(path);
729 ///////////////////////////////////////////////////////////////////
731 void MediaCurl::getFile( const Pathname & filename ) const
733 // Use absolute file name to prevent access of files outside of the
734 // hierarchy below the attach point.
735 getFileCopy(filename, localPath(filename).absolutename());
738 ///////////////////////////////////////////////////////////////////
740 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
742 callback::SendReport<DownloadProgressReport> report;
744 Url fileurl(getFileUrl(_url, filename));
752 doGetFileCopy(filename, target, report);
755 // retry with proper authentication data
756 catch (MediaUnauthorizedException & ex_r)
758 if(authenticate(ex_r.hint(), !retry))
762 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
766 // unexpected exception
767 catch (MediaException & excpt_r)
769 // FIXME: error number fix
770 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
771 ZYPP_RETHROW(excpt_r);
776 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
779 ///////////////////////////////////////////////////////////////////
781 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
789 return doGetDoesFileExist( filename );
791 // authentication problem, retry with proper authentication data
792 catch (MediaUnauthorizedException & ex_r)
794 if(authenticate(ex_r.hint(), !retry))
799 // unexpected exception
800 catch (MediaException & excpt_r)
802 ZYPP_RETHROW(excpt_r);
810 ///////////////////////////////////////////////////////////////////
812 void MediaCurl::evaluateCurlCode( const Pathname &filename,
814 bool timeout_reached ) const
816 Url url(getFileUrl(_url, filename));
825 case CURLE_UNSUPPORTED_PROTOCOL:
826 case CURLE_URL_MALFORMAT:
827 case CURLE_URL_MALFORMAT_USER:
829 case CURLE_LOGIN_DENIED:
831 MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
833 case CURLE_HTTP_RETURNED_ERROR:
835 long httpReturnCode = 0;
836 CURLcode infoRet = curl_easy_getinfo( _curl,
837 CURLINFO_RESPONSE_CODE,
839 if ( infoRet == CURLE_OK )
841 string msg = "HTTP response: " + str::numstring( httpReturnCode );
842 switch ( httpReturnCode )
846 string auth_hint = getAuthHint();
848 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
849 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
851 ZYPP_THROW(MediaUnauthorizedException(
852 url, "Login failed.", _curlError, auth_hint
856 case 503: // service temporarily unavailable (bnc #462545)
857 ZYPP_THROW(MediaTemporaryProblemException(url));
858 case 504: // gateway timeout
859 ZYPP_THROW(MediaTimeoutException(url));
863 if (url.asString().find("novell.com") != string::npos)
864 msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
865 ZYPP_THROW(MediaForbiddenException(url, msg403));
868 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
871 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
872 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
876 string msg = "Unable to retrieve HTTP response:";
877 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
878 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
882 case CURLE_FTP_COULDNT_RETR_FILE:
883 case CURLE_FTP_ACCESS_DENIED:
884 err = "File not found";
885 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
887 case CURLE_BAD_PASSWORD_ENTERED:
888 case CURLE_FTP_USER_PASSWORD_INCORRECT:
889 err = "Login failed";
891 case CURLE_COULDNT_RESOLVE_PROXY:
892 case CURLE_COULDNT_RESOLVE_HOST:
893 case CURLE_COULDNT_CONNECT:
894 case CURLE_FTP_CANT_GET_HOST:
895 err = "Connection failed";
897 case CURLE_WRITE_ERROR:
900 case CURLE_ABORTED_BY_CALLBACK:
901 case CURLE_OPERATION_TIMEDOUT:
904 err = "Timeout reached";
905 ZYPP_THROW(MediaTimeoutException(url));
912 case CURLE_SSL_PEER_CERTIFICATE:
914 err = "Unrecognized error";
918 // uhm, no 0 code but unknown curl exception
919 ZYPP_THROW(MediaCurlException(url, err, _curlError));
921 catch (const MediaException & excpt_r)
923 ZYPP_RETHROW(excpt_r);
928 // actually the code is 0, nothing happened
932 ///////////////////////////////////////////////////////////////////
934 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
936 DBG << filename.asString() << endl;
939 ZYPP_THROW(MediaBadUrlException(_url));
941 if(_url.getHost().empty())
942 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
944 Url url(getFileUrl(_url, filename));
946 DBG << "URL: " << url.asString() << endl;
947 // Use URL without options and without username and passwd
948 // (some proxies dislike them in the URL).
949 // Curl seems to need the just scheme, hostname and a path;
950 // the rest was already passed as curl options (in attachTo).
953 // Use asString + url::ViewOptions instead?
954 curlUrl.setUsername( "" );
955 curlUrl.setPassword( "" );
956 curlUrl.setPathParams( "" );
957 curlUrl.setQueryString( "" );
958 curlUrl.setFragment( "" );
961 // See also Bug #154197 and ftp url definition in RFC 1738:
962 // The url "ftp://user@host/foo/bar/file" contains a path,
963 // that is relative to the user's home.
964 // The url "ftp://user@host//foo/bar/file" (or also with
965 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
966 // contains an absolute path.
968 string urlBuffer( curlUrl.asString());
969 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
972 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
975 // instead of returning no data with NOBODY, we return
976 // little data, that works with broken servers, and
977 // works for ftp as well, because retrieving only headers
978 // ftp will return always OK code ?
979 // See http://curl.haxx.se/docs/knownbugs.html #58
980 if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
981 ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1 );
983 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
986 curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
987 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
988 /* yes, this is why we never got to get NOBODY working before,
989 because setting it changes this option too, and we also
991 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
993 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
994 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
997 FILE *file = ::fopen( "/dev/null", "w" );
1000 ERR << "fopen failed for /dev/null" << endl;
1001 curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
1002 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1003 /* yes, this is why we never got to get NOBODY working before,
1004 because setting it changes this option too, and we also
1006 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1008 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
1010 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1012 ZYPP_THROW(MediaWriteException("/dev/null"));
1015 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1018 std::string err( _curlError);
1019 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1020 curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
1021 /* yes, this is why we never got to get NOBODY working before,
1022 because setting it changes this option too, and we also
1024 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1026 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
1028 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1030 ZYPP_THROW(MediaCurlSetOptException(url, err));
1033 CURLcode ok = curl_easy_perform( _curl );
1034 MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1036 // reset curl settings
1037 if ( _url.getScheme() == "http" || _url.getScheme() == "https" )
1039 curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
1041 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1044 /* yes, this is why we never got to get NOBODY working before,
1045 because setting it changes this option too, and we also
1047 See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1049 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1);
1051 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1057 // for FTP we set different options
1058 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1060 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1064 // if the code is not zero, close the file
1068 // as we are not having user interaction, the user can't cancel
1069 // the file existence checking, a callback or timeout return code
1070 // will be always a timeout.
1072 evaluateCurlCode( filename, ok, true /* timeout */);
1074 catch ( const MediaFileNotFoundException &e ) {
1075 // if the file did not exist then we can return false
1078 catch ( const MediaException &e ) {
1079 // some error, we are not sure about file existence, rethrw
1083 return ( ok == CURLE_OK );
1086 ///////////////////////////////////////////////////////////////////
1088 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1090 DBG << filename.asString() << endl;
1093 ZYPP_THROW(MediaBadUrlException(_url));
1095 if(_url.getHost().empty())
1096 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1098 Url url(getFileUrl(_url, filename));
1100 Pathname dest = target.absolutename();
1101 if( assert_dir( dest.dirname() ) )
1103 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1104 ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1107 DBG << "URL: " << url.asString() << endl;
1108 // Use URL without options and without username and passwd
1109 // (some proxies dislike them in the URL).
1110 // Curl seems to need the just scheme, hostname and a path;
1111 // the rest was already passed as curl options (in attachTo).
1114 // Use asString + url::ViewOptions instead?
1115 curlUrl.setUsername( "" );
1116 curlUrl.setPassword( "" );
1117 curlUrl.setPathParams( "" );
1118 curlUrl.setQueryString( "" );
1119 curlUrl.setFragment( "" );
1122 // See also Bug #154197 and ftp url definition in RFC 1738:
1123 // The url "ftp://user@host/foo/bar/file" contains a path,
1124 // that is relative to the user's home.
1125 // The url "ftp://user@host//foo/bar/file" (or also with
1126 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1127 // contains an absolute path.
1129 string urlBuffer( curlUrl.asString());
1130 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1131 urlBuffer.c_str() );
1133 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1136 // set IFMODSINCE time condition (no download if not modified)
1137 if( PathInfo(target).isExist() )
1139 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1140 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, PathInfo(target).mtime());
1144 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1145 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0);
1148 string destNew = target.asString() + ".new.zypp.XXXXXX";
1149 char *buf = ::strdup( destNew.c_str());
1152 ERR << "out of memory for temp file name" << endl;
1153 ZYPP_THROW(MediaSystemException(
1154 url, "out of memory for temp file name"
1158 int tmp_fd = ::mkstemp( buf );
1162 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1163 ZYPP_THROW(MediaWriteException(destNew));
1168 FILE *file = ::fdopen( tmp_fd, "w" );
1171 filesystem::unlink( destNew );
1172 ERR << "fopen failed for file '" << destNew << "'" << endl;
1173 ZYPP_THROW(MediaWriteException(destNew));
1176 DBG << "dest: " << dest << endl;
1177 DBG << "temp: " << destNew << endl;
1179 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1182 filesystem::unlink( destNew );
1183 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1186 // Set callback and perform.
1187 ProgressData progressData(_settings.timeout(), url, &report);
1188 report->start(url, dest);
1189 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1190 WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1193 ret = curl_easy_perform( _curl );
1195 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1196 WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1201 ERR << "curl error: " << ret << ": " << _curlError
1202 << ", temp file size " << PathInfo(destNew).size()
1203 << " byte." << endl;
1206 filesystem::unlink( destNew );
1208 // the timeout is determined by the progress data object
1209 // which holds wheter the timeout was reached or not,
1210 // otherwise it would be a user cancel
1212 evaluateCurlCode( filename, ret, progressData.reached);
1214 catch ( const MediaException &e ) {
1215 // some error, we are not sure about file existence, rethrw
1220 #if DETECT_DIR_INDEX
1222 if(curlUrl.getScheme() == "http" ||
1223 curlUrl.getScheme() == "https")
1226 // try to check the effective url and set the not_a_file flag
1227 // if the url path ends with a "/", what usually means, that
1228 // we've received a directory index (index.html content).
1230 // Note: This may be dangerous and break file retrieving in
1231 // case of some server redirections ... ?
1233 bool not_a_file = false;
1235 CURLcode ret = curl_easy_getinfo( _curl,
1236 CURLINFO_EFFECTIVE_URL,
1238 if ( ret == CURLE_OK && ptr != NULL)
1243 std::string path( eurl.getPathName());
1244 if( !path.empty() && path != "/" && *path.rbegin() == '/')
1246 DBG << "Effective url ("
1248 << ") seems to provide the index of a directory"
1260 filesystem::unlink( destNew );
1261 ZYPP_THROW(MediaNotAFileException(_url, filename));
1264 #endif // DETECT_DIR_INDEX
1266 long httpReturnCode = 0;
1267 CURLcode infoRet = curl_easy_getinfo(_curl,
1268 CURLINFO_RESPONSE_CODE,
1270 bool modified = true;
1271 if (infoRet == CURLE_OK)
1273 DBG << "HTTP response: " + str::numstring(httpReturnCode);
1274 if ( httpReturnCode == 304
1275 || ( httpReturnCode == 213 && _url.getScheme() == "ftp" ) ) // not modified
1277 DBG << " Not modified.";
1284 WAR << "Could not get the reponse code." << endl;
1287 if (modified || infoRet != CURLE_OK)
1290 if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1292 ERR << "Failed to chmod file " << destNew << endl;
1296 // move the temp file into dest
1297 if ( rename( destNew, dest ) != 0 ) {
1298 ERR << "Rename failed" << endl;
1299 ZYPP_THROW(MediaWriteException(dest));
1304 // close and remove the temp file
1306 filesystem::unlink( destNew );
1309 DBG << "done: " << PathInfo(dest) << endl;
1312 ///////////////////////////////////////////////////////////////////
1314 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1316 filesystem::DirContent content;
1317 getDirInfo( content, dirname, /*dots*/false );
1319 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1320 Pathname filename = dirname + it->name;
1323 switch ( it->type ) {
1324 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1325 case filesystem::FT_FILE:
1326 getFile( filename );
1328 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1330 getDir( filename, recurse_r );
1332 res = assert_dir( localPath( filename ) );
1334 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1339 // don't provide devices, sockets, etc.
1345 ///////////////////////////////////////////////////////////////////
1347 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1348 const Pathname & dirname, bool dots ) const
1350 getDirectoryYast( retlist, dirname, dots );
1353 ///////////////////////////////////////////////////////////////////
1355 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1356 const Pathname & dirname, bool dots ) const
1358 getDirectoryYast( retlist, dirname, dots );
1361 ///////////////////////////////////////////////////////////////////
1363 int MediaCurl::progressCallback( void *clientp,
1364 double dltotal, double dlnow,
1365 double ultotal, double ulnow)
1367 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1370 time_t now = time(NULL);
1373 // reset time of last change in case initial time()
1374 // failed or the time was adjusted (goes backward)
1375 if( pdata->ltime <= 0 || pdata->ltime > now)
1380 // start time counting as soon as first data arrives
1381 // (skip the connection / redirection time at begin)
1383 if (dlnow > 0 || ulnow > 0)
1385 dif = (now - pdata->ltime);
1386 dif = dif > 0 ? dif : 0;
1391 // update the drate_avg and drate_period only after a second has passed
1392 // (this callback is called much more often than a second)
1393 // otherwise the values would be far from accurate when measuring
1394 // the time in seconds
1395 //! \todo more accurate download rate computationn, e.g. compute average value from last 5 seconds, or work with milliseconds instead of seconds
1397 if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1398 pdata->drate_avg = (dlnow / pdata->secs);
1402 pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1403 pdata->dload_period = dlnow;
1407 // send progress report first, abort transfer if requested
1410 if (!(*(pdata->report))->progress(int( dlnow * 100 / dltotal ),
1413 pdata->drate_period))
1415 return 1; // abort transfer
1419 // check if we there is a timeout set
1420 if( pdata->timeout > 0)
1424 bool progress = false;
1426 // update download data if changed, mark progress
1427 if( dlnow != pdata->dload)
1430 pdata->dload = dlnow;
1433 // update upload data if changed, mark progress
1434 if( ulnow != pdata->uload)
1437 pdata->uload = ulnow;
1441 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1443 pdata->reached = true;
1444 return 1; // aborts transfer
1452 ///////////////////////////////////////////////////////////////////
1454 string MediaCurl::getAuthHint() const
1456 long auth_info = CURLAUTH_NONE;
1459 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1461 if(infoRet == CURLE_OK)
1463 return CurlAuthData::auth_type_long2str(auth_info);
1469 ///////////////////////////////////////////////////////////////////
1471 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1473 //! \todo need a way to pass different CredManagerOptions here
1474 Target_Ptr target = zypp::getZYpp()->getTarget();
1475 CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1476 CurlAuthData_Ptr credentials;
1478 // get stored credentials
1479 AuthData_Ptr cmcred = cm.getCred(_url);
1481 if (cmcred && firstTry)
1483 credentials.reset(new CurlAuthData(*cmcred));
1484 DBG << "got stored credentials:" << endl << *credentials << endl;
1486 // if not found, ask user
1490 CurlAuthData_Ptr curlcred;
1491 curlcred.reset(new CurlAuthData());
1492 callback::SendReport<AuthenticationReport> auth_report;
1494 // preset the username if present in current url
1495 if (!_url.getUsername().empty() && firstTry)
1496 curlcred->setUsername(_url.getUsername());
1497 // if CM has found some credentials, preset the username from there
1499 curlcred->setUsername(cmcred->username());
1501 // indicate we have no good credentials from CM
1504 string prompt_msg = boost::str(boost::format(
1505 //!\todo add comma to the message for the next release
1506 _("Authentication required for '%s'")) % _url.asString());
1508 // set available authentication types from the exception
1509 // might be needed in prompt
1510 curlcred->setAuthType(availAuthTypes);
1513 if (auth_report->prompt(_url, prompt_msg, *curlcred))
1515 DBG << "callback answer: retry" << endl
1516 << "CurlAuthData: " << *curlcred << endl;
1518 if (curlcred->valid())
1520 credentials = curlcred;
1521 // if (credentials->username() != _url.getUsername())
1522 // _url.setUsername(credentials->username());
1524 * \todo find a way to save the url with changed username
1525 * back to repoinfo or dont store urls with username
1526 * (and either forbid more repos with the same url and different
1527 * user, or return a set of credentials from CM and try them one
1534 DBG << "callback answer: cancel" << endl;
1538 // set username and password
1541 // HACK, why is this const?
1542 const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1543 const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1545 // set username and password
1546 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1547 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1549 // set available authentication types from the exception
1550 if (credentials->authType() == CURLAUTH_NONE)
1551 credentials->setAuthType(availAuthTypes);
1553 // set auth type (seems this must be set _after_ setting the userpwd
1554 if (credentials->authType() != CURLAUTH_NONE)
1556 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1557 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1562 credentials->setUrl(_url);
1563 cm.addCred(*credentials);
1574 } // namespace media