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/Sysconfig.h"
20 #include "zypp/base/Gettext.h"
22 #include "zypp/media/MediaCurl.h"
23 #include "zypp/media/proxyinfo/ProxyInfos.h"
24 #include "zypp/media/ProxyInfo.h"
25 #include "zypp/media/MediaUserAuth.h"
26 #include "zypp/thread/Once.h"
28 #include <sys/types.h>
30 #include <sys/mount.h>
34 #include <boost/format.hpp>
36 #define DETECT_DIR_INDEX 0
37 #define CONNECT_TIMEOUT 60
38 #define TRANSFER_TIMEOUT 60 * 3
39 #define TRANSFER_TIMEOUT_MAX 60 * 60
43 using namespace zypp::base;
47 zypp::thread::OnceFlag g_InitOnceFlag = PTHREAD_ONCE_INIT;
48 zypp::thread::OnceFlag g_FreeOnceFlag = PTHREAD_ONCE_INIT;
50 extern "C" void _do_free_once()
52 curl_global_cleanup();
55 extern "C" void globalFreeOnce()
57 zypp::thread::callOnce(g_FreeOnceFlag, _do_free_once);
60 extern "C" void _do_init_once()
62 CURLcode ret = curl_global_init( CURL_GLOBAL_ALL );
65 WAR << "curl global init failed" << endl;
69 // register at exit handler ?
70 // this may cause trouble, because we can protect it
71 // against ourself only.
72 // if the app sets an atexit handler as well, it will
73 // cause a double free while the second of them runs.
75 //std::atexit( globalFreeOnce);
78 inline void globalInitOnce()
80 zypp::thread::callOnce(g_InitOnceFlag, _do_init_once);
83 int log_curl(CURL *curl, curl_infotype info,
84 char *ptr, size_t len, void *max_lvl)
90 case CURLINFO_TEXT: lvl = 1; pfx = "*"; break;
91 case CURLINFO_HEADER_IN: lvl = 2; pfx = "<"; break;
92 case CURLINFO_HEADER_OUT: lvl = 2; pfx = ">"; break;
95 if( lvl > 0 && max_lvl != NULL && lvl <= *((long *)max_lvl))
97 std::string msg(ptr, len);
98 std::list<std::string> lines;
99 std::list<std::string>::const_iterator line;
100 zypp::str::split(msg, std::back_inserter(lines), "\r\n");
101 for(line = lines.begin(); line != lines.end(); ++line)
103 DBG << pfx << " " << *line << endl;
116 ProgressData(const long _timeout, const zypp::Url &_url = zypp::Url(),
117 callback::SendReport<DownloadProgressReport> *_report=NULL)
128 callback::SendReport<DownloadProgressReport> *report;
136 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
137 std::string MediaCurl::_agent = "Novell ZYPP Installer";
139 ///////////////////////////////////////////////////////////////////
141 static inline void escape( string & str_r,
142 const char char_r, const string & escaped_r ) {
143 for ( string::size_type pos = str_r.find( char_r );
144 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
145 str_r.replace( pos, 1, escaped_r );
149 static inline string escapedPath( string path_r ) {
150 escape( path_r, ' ', "%20" );
154 static inline string unEscape( string text_r ) {
155 char * tmp = curl_unescape( text_r.c_str(), 0 );
161 ///////////////////////////////////////////////////////////////////
163 // CLASS NAME : MediaCurl
165 ///////////////////////////////////////////////////////////////////
167 MediaCurl::MediaCurl( const Url & url_r,
168 const Pathname & attach_point_hint_r )
169 : MediaHandler( url_r, attach_point_hint_r,
170 "/", // urlpath at attachpoint
171 true ), // does_download
174 _curlError[0] = '\0';
177 MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
181 if( !attachPoint().empty())
183 PathInfo ainfo(attachPoint());
184 Pathname apath(attachPoint() + "XXXXXX");
185 char *atemp = ::strdup( apath.asString().c_str());
187 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
188 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
190 WAR << "attach point " << ainfo.path()
191 << " is not useable for " << url_r.getScheme() << endl;
192 setAttachPoint("", true);
194 else if( atest != NULL)
202 void MediaCurl::setCookieFile( const Pathname &fileName )
204 _cookieFile = fileName;
207 ///////////////////////////////////////////////////////////////////
210 // METHOD NAME : MediaCurl::attachTo
211 // METHOD TYPE : PMError
213 // DESCRIPTION : Asserted that not already attached, and attachPoint is a directory.
215 void MediaCurl::attachTo (bool next)
218 ZYPP_THROW(MediaNotSupportedException(_url));
220 if ( !_url.isValid() )
221 ZYPP_THROW(MediaBadUrlException(_url));
223 curl_version_info_data *curl_info = NULL;
224 curl_info = curl_version_info(CURLVERSION_NOW);
225 // curl_info does not need any free (is static)
226 if (curl_info->protocols)
228 const char * const *proto;
229 std::string scheme( _url.getScheme());
231 for(proto=curl_info->protocols; !found && *proto; ++proto)
233 if( scheme == std::string((const char *)*proto))
238 std::string msg("Unsupported protocol '");
241 ZYPP_THROW(MediaBadUrlException(_url, msg));
245 if( !isUseableAttachPoint(attachPoint()))
247 std::string mountpoint = createAttachPoint().asString();
249 if( mountpoint.empty())
250 ZYPP_THROW( MediaBadAttachPointException(url()));
252 setAttachPoint( mountpoint, true);
255 disconnectFrom(); // clean _curl if needed
256 _curl = curl_easy_init();
258 ZYPP_THROW(MediaCurlInitException(_url));
262 char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
263 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
266 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1);
267 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
268 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
272 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
275 ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
278 ret = curl_easy_setopt( _curl, CURLOPT_FAILONERROR, true );
281 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
284 ret = curl_easy_setopt( _curl, CURLOPT_NOSIGNAL, 1 );
287 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
294 _xfer_timeout = TRANSFER_TIMEOUT;
296 std::string param(_url.getQueryParam("timeout"));
299 long num = str::strtonum<long>( param);
300 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
308 ret = curl_easy_setopt( _curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
311 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
314 if ( _url.getScheme() == "http" ) {
315 // follow any Location: header that the server sends as part of
316 // an HTTP header (#113275)
317 ret = curl_easy_setopt ( _curl, CURLOPT_FOLLOWLOCATION, true );
320 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
322 ret = curl_easy_setopt ( _curl, CURLOPT_MAXREDIRS, 3L );
325 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
327 ret = curl_easy_setopt ( _curl, CURLOPT_USERAGENT, _agent.c_str() );
330 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
334 if ( _url.getScheme() == "https" )
336 bool verify_peer = false;
337 bool verify_host = false;
339 std::string verify( _url.getQueryParam("ssl_verify"));
340 if( verify.empty() ||
354 std::vector<std::string> flags;
355 std::vector<std::string>::const_iterator flag;
356 str::split( verify, std::back_inserter(flags), ",");
357 for(flag = flags.begin(); flag != flags.end(); ++flag)
371 ZYPP_THROW(MediaBadUrlException(_url, "Unknown ssl_verify flag"));
376 _ca_path = Pathname(_url.getQueryParam("ssl_capath")).asString();
377 if( _ca_path.empty())
379 _ca_path = "/etc/ssl/certs/";
382 if( !PathInfo(_ca_path).isDir() || !Pathname(_ca_path).absolute())
385 ZYPP_THROW(MediaBadUrlException(_url, "Invalid ssl_capath path"));
388 if( verify_peer || verify_host)
390 ret = curl_easy_setopt( _curl, CURLOPT_CAPATH, _ca_path.c_str());
393 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
397 ret = curl_easy_setopt( _curl, CURLOPT_SSL_VERIFYPEER, verify_peer ? 1L : 0L);
400 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
402 ret = curl_easy_setopt( _curl, CURLOPT_SSL_VERIFYHOST, verify_host ? 2L : 0L);
405 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
408 ret = curl_easy_setopt ( _curl, CURLOPT_USERAGENT, _agent.c_str() );
411 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
416 /*---------------------------------------------------------------*
417 CURLOPT_USERPWD: [user name]:[password]
419 Url::username/password -> CURLOPT_USERPWD
420 If not provided, anonymous FTP identification
421 *---------------------------------------------------------------*/
423 if ( _url.getUsername().empty() ) {
424 if ( _url.getScheme() == "ftp" ) {
425 string id = "yast2@";
427 DBG << "Anonymous FTP identification: '" << id << "'" << endl;
428 _userpwd = "anonymous:" + id;
431 _userpwd = _url.getUsername();
432 if ( _url.getPassword().size() ) {
433 _userpwd += ":" + _url.getPassword();
437 if ( _userpwd.size() ) {
438 _userpwd = unEscape( _userpwd );
439 ret = curl_easy_setopt( _curl, CURLOPT_USERPWD, _userpwd.c_str() );
442 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
445 // HTTP authentication type
446 if(_url.getScheme() == "http" || _url.getScheme() == "https")
448 string use_auth = _url.getQueryParam("auth");
449 if( use_auth.empty())
450 use_auth = "digest,basic";
454 long auth = CurlAuthData::auth_type_str2long(use_auth);
455 if( auth != CURLAUTH_NONE)
457 DBG << "Enabling HTTP authentication methods: " << use_auth
458 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
460 ret = curl_easy_setopt( _curl, CURLOPT_HTTPAUTH, auth);
463 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
467 catch (MediaException & ex_r)
469 string auth_hint = getAuthHint();
471 DBG << "Rethrowing as MediaUnauthorizedException. auth hint: '"
472 << auth_hint << "'" << endl;
474 ZYPP_THROW(MediaUnauthorizedException(
475 _url, ex_r.msg(), _curlError, auth_hint
481 /*---------------------------------------------------------------*
482 CURLOPT_PROXY: host[:port]
484 Url::option(proxy and proxyport) -> CURLOPT_PROXY
485 If not provided, /etc/sysconfig/proxy is evaluated
486 *---------------------------------------------------------------*/
488 _proxy = _url.getQueryParam( "proxy" );
490 if ( ! _proxy.empty() ) {
491 string proxyport( _url.getQueryParam( "proxyport" ) );
492 if ( ! proxyport.empty() ) {
493 _proxy += ":" + proxyport;
497 ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
499 if ( proxy_info.enabled())
501 bool useproxy = true;
503 std::list<std::string> nope = proxy_info.noProxy();
504 for (ProxyInfo::NoProxyIterator it = proxy_info.noProxyBegin();
505 it != proxy_info.noProxyEnd();
508 std::string host( str::toLower(_url.getHost()));
509 std::string temp( str::toLower(*it));
511 // no proxy if it points to a suffix
512 // preceeded by a '.', that maches
513 // the trailing portion of the host.
514 if( temp.size() > 1 && temp.at(0) == '.')
516 if(host.size() > temp.size() &&
517 host.compare(host.size() - temp.size(), temp.size(), temp) == 0)
519 DBG << "NO_PROXY: '" << *it << "' matches host '"
520 << host << "'" << endl;
526 // no proxy if we have an exact match
529 DBG << "NO_PROXY: '" << *it << "' matches host '"
530 << host << "'" << endl;
537 _proxy = proxy_info.proxy(_url.getScheme());
543 DBG << "Proxy: " << (_proxy.empty() ? "-none-" : _proxy) << endl;
545 if ( ! _proxy.empty() ) {
547 ret = curl_easy_setopt( _curl, CURLOPT_PROXY, _proxy.c_str() );
550 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
553 /*---------------------------------------------------------------*
554 CURLOPT_PROXYUSERPWD: [user name]:[password]
556 Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
557 If not provided, $HOME/.curlrc is evaluated
558 *---------------------------------------------------------------*/
560 _proxyuserpwd = _url.getQueryParam( "proxyuser" );
562 if ( ! _proxyuserpwd.empty() ) {
564 string proxypassword( _url.getQueryParam( "proxypassword" ) );
565 if ( ! proxypassword.empty() ) {
566 _proxyuserpwd += ":" + proxypassword;
570 char *home = getenv("HOME");
573 Pathname curlrcFile = string( home ) + string( "/.curlrc" );
575 PathInfo h_info(string(home), PathInfo::LSTAT);
576 PathInfo c_info(curlrcFile, PathInfo::LSTAT);
578 if( h_info.isDir() && h_info.owner() == getuid() &&
579 c_info.isFile() && c_info.owner() == getuid())
581 map<string,string> rc_data = base::sysconfig::read( curlrcFile );
583 map<string,string>::const_iterator it = rc_data.find("proxy-user");
584 if (it != rc_data.end())
585 _proxyuserpwd = it->second;
589 WAR << "Not allowed to parse '" << curlrcFile
590 << "': bad file owner" << std::endl;
595 _proxyuserpwd = unEscape( _proxyuserpwd );
596 ret = curl_easy_setopt( _curl, CURLOPT_PROXYUSERPWD, _proxyuserpwd.c_str() );
599 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
603 /*---------------------------------------------------------------*
604 *---------------------------------------------------------------*/
606 _currentCookieFile = _cookieFile.asString();
608 ret = curl_easy_setopt( _curl, CURLOPT_COOKIEFILE,
609 _currentCookieFile.c_str() );
612 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
615 ret = curl_easy_setopt( _curl, CURLOPT_COOKIEJAR,
616 _currentCookieFile.c_str() );
619 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
622 ret = curl_easy_setopt( _curl, CURLOPT_PROGRESSFUNCTION,
626 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
629 ret = curl_easy_setopt( _curl, CURLOPT_NOPROGRESS, false );
632 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
635 // FIXME: need a derived class to propelly compare url's
636 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
637 setMediaSource(media);
641 MediaCurl::checkAttachPoint(const Pathname &apoint) const
643 return MediaHandler::checkAttachPoint( apoint, true, true);
646 ///////////////////////////////////////////////////////////////////
649 // METHOD NAME : MediaCurl::disconnectFrom
650 // METHOD TYPE : PMError
652 void MediaCurl::disconnectFrom()
656 curl_easy_cleanup( _curl );
661 ///////////////////////////////////////////////////////////////////
664 // METHOD NAME : MediaCurl::releaseFrom
665 // METHOD TYPE : PMError
667 // DESCRIPTION : Asserted that media is attached.
669 void MediaCurl::releaseFrom( bool eject )
675 ///////////////////////////////////////////////////////////////////
677 // METHOD NAME : MediaCurl::getFile
678 // METHOD TYPE : PMError
681 void MediaCurl::getFile( const Pathname & filename ) const
683 // Use absolute file name to prevent access of files outside of the
684 // hierarchy below the attach point.
685 getFileCopy(filename, localPath(filename).absolutename());
689 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
691 callback::SendReport<DownloadProgressReport> report;
696 CurlAuthData auth_data;
702 doGetFileCopy(filename, target, report);
705 // retry with proper authentication data
706 catch (MediaUnauthorizedException & ex_r)
708 callback::SendReport<AuthenticationReport> auth_report;
710 if (!_url.getUsername().empty() && !retry)
711 auth_data.setUserName(_url.getUsername());
714 if (retry || !_url.getUsername().empty())
715 prompt_msg = _("Invalid user name or password.");
717 prompt_msg = boost::str(boost::format(
718 _("Authentication required for '%s'")) % _url.asString());
720 // set available authentication types from the exception
721 auth_data.setAuthType(ex_r.hint());
723 if (auth_report->prompt(_url, prompt_msg, auth_data))
725 DBG << "callback answer: retry" << endl
726 << "CurlAuthData: " << auth_data << endl;
728 if (auth_data.valid()) {
729 _userpwd = auth_data.getUserPwd();
731 // set username and password
732 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _userpwd.c_str());
733 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
736 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, auth_data.authType());
737 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
744 DBG << "callback answer: cancel" << endl;
745 report->finish(url, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.msg());
749 // unexpected exception
750 catch (MediaException & excpt_r)
752 // FIXME: this will not match the first URL
753 // FIXME: error number fix
754 report->finish(url, zypp::media::DownloadProgressReport::NOT_FOUND, excpt_r.msg());
755 ZYPP_RETHROW(excpt_r);
760 report->finish(url, zypp::media::DownloadProgressReport::NO_ERROR, "");
763 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
766 CurlAuthData auth_data;
772 return doGetDoesFileExist( filename );
774 // authentication problem, retry with proper authentication data
775 catch (MediaUnauthorizedException & ex_r)
777 callback::SendReport<AuthenticationReport> auth_report;
779 if (!_url.getUsername().empty() && !retry)
780 auth_data.setUserName(_url.getUsername());
783 if (retry || !_url.getUsername().empty())
784 prompt_msg = _("Invalid user name or password.");
786 prompt_msg = boost::str(boost::format(
787 _("Authentication required for '%s'")) % _url.asString());
789 // set available authentication types from the exception
790 auth_data.setAuthType(ex_r.hint());
792 if (auth_report->prompt(_url, prompt_msg, auth_data))
794 DBG << "callback answer: retry" << endl
795 << "CurlAuthData: " << auth_data << endl;
797 if (auth_data.valid()) {
798 _userpwd = auth_data.getUserPwd();
800 // set username and password
801 CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _userpwd.c_str());
802 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
805 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, auth_data.authType());
806 if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
813 DBG << "callback answer: cancel" << endl;
817 // unexpected exception
818 catch (MediaException & excpt_r)
820 ZYPP_RETHROW(excpt_r);
828 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
830 DBG << filename.asString() << endl;
833 ZYPP_THROW(MediaBadUrlException(_url));
835 if(_url.getHost().empty())
836 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
838 string path = _url.getPathName();
839 if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
840 filename.absolute() ) {
841 // If url has a path with trailing slash, remove the leading slash from
842 // the absolute file name
843 path += filename.asString().substr( 1, filename.asString().size() - 1 );
844 } else if ( filename.relative() ) {
845 // Add trailing slash to path, if not already there
846 if ( !path.empty() && *path.rbegin() != '/' ) path += "/";
847 // Remove "./" from begin of relative file name
848 path += filename.asString().substr( 2, filename.asString().size() - 2 );
850 path += filename.asString();
854 url.setPathName( path );
856 DBG << "URL: " << url.asString() << endl;
857 // Use URL without options and without username and passwd
858 // (some proxies dislike them in the URL).
859 // Curl seems to need the just scheme, hostname and a path;
860 // the rest was already passed as curl options (in attachTo).
863 // Use asString + url::ViewOptions instead?
864 curlUrl.setUsername( "" );
865 curlUrl.setPassword( "" );
866 curlUrl.setPathParams( "" );
867 curlUrl.setQueryString( "" );
868 curlUrl.setFragment( "" );
871 // See also Bug #154197 and ftp url definition in RFC 1738:
872 // The url "ftp://user@host/foo/bar/file" contains a path,
873 // that is relative to the user's home.
874 // The url "ftp://user@host//foo/bar/file" (or also with
875 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
876 // contains an absolute path.
878 string urlBuffer( curlUrl.asString());
879 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
882 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
885 // set no data, because we only want to check if the file exists
886 //ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1 );
888 // ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
891 // instead of returning no data with NOBODY, we return
892 // little data, that works with broken servers, and
893 // works for ftp as well, because retrieving only headers
894 // ftp will return always OK code ?
895 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
897 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
900 FILE *file = ::fopen( "/dev/null", "w" );
903 ERR << "fopen failed for /dev/null" << endl;
904 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
906 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
908 ZYPP_THROW(MediaWriteException("/dev/null"));
911 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
914 std::string err( _curlError);
915 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
917 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
919 ZYPP_THROW(MediaCurlSetOptException(url, err));
921 // Set callback and perform.
922 //ProgressData progressData(_xfer_timeout, url, &report);
923 //report->start(url, dest);
924 //if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
925 // WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
928 CURLcode ok = curl_easy_perform( _curl );
929 MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
931 // reset curl settings
932 ret = curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
935 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
945 bool err_file_not_found = false;
948 case CURLE_FTP_COULDNT_RETR_FILE:
949 case CURLE_FTP_ACCESS_DENIED:
950 err_file_not_found = true;
952 case CURLE_HTTP_RETURNED_ERROR:
954 long httpReturnCode = 0;
955 CURLcode infoRet = curl_easy_getinfo( _curl,
956 CURLINFO_RESPONSE_CODE,
958 if ( infoRet == CURLE_OK )
960 string msg = "HTTP response: " +
961 str::numstring( httpReturnCode );
962 if ( httpReturnCode == 401 )
964 std::string auth_hint = getAuthHint();
966 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
967 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
969 ZYPP_THROW(MediaUnauthorizedException(
970 url, "Login failed.", _curlError, auth_hint
974 if ( httpReturnCode == 404)
976 err_file_not_found = true;
981 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
982 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
986 string msg = "Unable to retrieve HTTP response:";
988 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
989 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
993 case CURLE_UNSUPPORTED_PROTOCOL:
994 case CURLE_URL_MALFORMAT:
995 case CURLE_URL_MALFORMAT_USER:
996 case CURLE_BAD_PASSWORD_ENTERED:
997 case CURLE_FTP_USER_PASSWORD_INCORRECT:
998 case CURLE_COULDNT_RESOLVE_PROXY:
999 case CURLE_COULDNT_RESOLVE_HOST:
1000 case CURLE_COULDNT_CONNECT:
1001 case CURLE_FTP_CANT_GET_HOST:
1002 case CURLE_WRITE_ERROR:
1003 case CURLE_ABORTED_BY_CALLBACK:
1004 case CURLE_SSL_PEER_CERTIFICATE:
1006 err = curl_easy_strerror(ok);
1008 err = "Unrecognized error";
1012 if( err_file_not_found)
1014 // file does not exists
1019 // there was an error
1020 ZYPP_THROW(MediaCurlException(url, string(), _curlError));
1023 catch (const MediaException & excpt_r)
1025 ZYPP_RETHROW(excpt_r);
1030 return ( ok == CURLE_OK );
1031 //if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1032 // WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1036 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report) const
1038 DBG << filename.asString() << endl;
1041 ZYPP_THROW(MediaBadUrlException(_url));
1043 if(_url.getHost().empty())
1044 ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1046 string path = _url.getPathName();
1047 if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
1048 filename.absolute() ) {
1049 // If url has a path with trailing slash, remove the leading slash from
1050 // the absolute file name
1051 path += filename.asString().substr( 1, filename.asString().size() - 1 );
1052 } else if ( filename.relative() ) {
1053 // Add trailing slash to path, if not already there
1054 if (path.empty()) path = "/";
1055 else if (*path.rbegin() != '/' ) path += "/";
1056 // Remove "./" from begin of relative file name
1057 path += filename.asString().substr( 2, filename.asString().size() - 2 );
1059 path += filename.asString();
1063 url.setPathName( path );
1065 Pathname dest = target.absolutename();
1066 if( assert_dir( dest.dirname() ) )
1068 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1069 ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1072 DBG << "URL: " << url.asString() << endl;
1073 // Use URL without options and without username and passwd
1074 // (some proxies dislike them in the URL).
1075 // Curl seems to need the just scheme, hostname and a path;
1076 // the rest was already passed as curl options (in attachTo).
1079 // Use asString + url::ViewOptions instead?
1080 curlUrl.setUsername( "" );
1081 curlUrl.setPassword( "" );
1082 curlUrl.setPathParams( "" );
1083 curlUrl.setQueryString( "" );
1084 curlUrl.setFragment( "" );
1087 // See also Bug #154197 and ftp url definition in RFC 1738:
1088 // The url "ftp://user@host/foo/bar/file" contains a path,
1089 // that is relative to the user's home.
1090 // The url "ftp://user@host//foo/bar/file" (or also with
1091 // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1092 // contains an absolute path.
1094 string urlBuffer( curlUrl.asString());
1095 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1096 urlBuffer.c_str() );
1098 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1101 string destNew = target.asString() + ".new.zypp.XXXXXX";
1102 char *buf = ::strdup( destNew.c_str());
1105 ERR << "out of memory for temp file name" << endl;
1106 ZYPP_THROW(MediaSystemException(
1107 url, "out of memory for temp file name"
1111 int tmp_fd = ::mkstemp( buf );
1115 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1116 ZYPP_THROW(MediaWriteException(destNew));
1121 FILE *file = ::fdopen( tmp_fd, "w" );
1124 filesystem::unlink( destNew );
1125 ERR << "fopen failed for file '" << destNew << "'" << endl;
1126 ZYPP_THROW(MediaWriteException(destNew));
1129 DBG << "dest: " << dest << endl;
1130 DBG << "temp: " << destNew << endl;
1132 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1135 filesystem::unlink( destNew );
1136 ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1139 // Set callback and perform.
1140 ProgressData progressData(_xfer_timeout, url, &report);
1141 report->start(url, dest);
1142 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1143 WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1146 ret = curl_easy_perform( _curl );
1148 if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1149 WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1153 ERR << "curl error: " << ret << ": " << _curlError
1154 << ", temp file size " << PathInfo(destNew).size()
1155 << " byte." << endl;
1158 filesystem::unlink( destNew );
1162 bool err_file_not_found = false;
1164 case CURLE_UNSUPPORTED_PROTOCOL:
1165 case CURLE_URL_MALFORMAT:
1166 case CURLE_URL_MALFORMAT_USER:
1168 case CURLE_HTTP_RETURNED_ERROR:
1170 long httpReturnCode = 0;
1171 CURLcode infoRet = curl_easy_getinfo( _curl,
1172 CURLINFO_RESPONSE_CODE,
1174 if ( infoRet == CURLE_OK ) {
1175 string msg = "HTTP response: " +
1176 str::numstring( httpReturnCode );
1177 if ( httpReturnCode == 401 )
1179 std::string auth_hint = getAuthHint();
1181 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1182 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1184 ZYPP_THROW(MediaUnauthorizedException(
1185 url, "Login failed.", _curlError, auth_hint
1189 if ( httpReturnCode == 404)
1191 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1195 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1196 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1200 string msg = "Unable to retrieve HTTP response:";
1202 DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1203 ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1207 case CURLE_FTP_COULDNT_RETR_FILE:
1208 case CURLE_FTP_ACCESS_DENIED:
1209 err = "File not found";
1210 err_file_not_found = true;
1212 case CURLE_BAD_PASSWORD_ENTERED:
1213 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1214 err = "Login failed";
1216 case CURLE_COULDNT_RESOLVE_PROXY:
1217 case CURLE_COULDNT_RESOLVE_HOST:
1218 case CURLE_COULDNT_CONNECT:
1219 case CURLE_FTP_CANT_GET_HOST:
1220 err = "Connection failed";
1222 case CURLE_WRITE_ERROR:
1223 err = "Write error";
1225 case CURLE_ABORTED_BY_CALLBACK:
1226 if( progressData.reached)
1228 err = "Timeout reached";
1235 case CURLE_SSL_PEER_CERTIFICATE:
1237 err = "Unrecognized error";
1240 if( err_file_not_found)
1242 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1246 ZYPP_THROW(MediaCurlException(url, err, _curlError));
1249 catch (const MediaException & excpt_r)
1251 ZYPP_RETHROW(excpt_r);
1254 #if DETECT_DIR_INDEX
1256 if(curlUrl.getScheme() == "http" ||
1257 curlUrl.getScheme() == "https")
1260 // try to check the effective url and set the not_a_file flag
1261 // if the url path ends with a "/", what usually means, that
1262 // we've received a directory index (index.html content).
1264 // Note: This may be dangerous and break file retrieving in
1265 // case of some server redirections ... ?
1267 bool not_a_file = false;
1269 CURLcode ret = curl_easy_getinfo( _curl,
1270 CURLINFO_EFFECTIVE_URL,
1272 if ( ret == CURLE_OK && ptr != NULL)
1277 std::string path( eurl.getPathName());
1278 if( !path.empty() && path != "/" && *path.rbegin() == '/')
1280 DBG << "Effective url ("
1282 << ") seems to provide the index of a directory"
1294 filesystem::unlink( destNew );
1295 ZYPP_THROW(MediaNotAFileException(_url, filename));
1298 #endif // DETECT_DIR_INDEX
1300 if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1302 ERR << "Failed to chmod file " << destNew << endl;
1306 if ( rename( destNew, dest ) != 0 ) {
1307 ERR << "Rename failed" << endl;
1308 ZYPP_THROW(MediaWriteException(dest));
1310 DBG << "done: " << PathInfo(dest) << endl;
1314 ///////////////////////////////////////////////////////////////////
1317 // METHOD NAME : MediaCurl::getDir
1318 // METHOD TYPE : PMError
1320 // DESCRIPTION : Asserted that media is attached
1322 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1324 filesystem::DirContent content;
1325 getDirInfo( content, dirname, /*dots*/false );
1327 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1328 Pathname filename = dirname + it->name;
1331 switch ( it->type ) {
1332 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1333 case filesystem::FT_FILE:
1334 getFile( filename );
1336 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1338 getDir( filename, recurse_r );
1340 res = assert_dir( localPath( filename ) );
1342 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
1347 // don't provide devices, sockets, etc.
1353 ///////////////////////////////////////////////////////////////////
1356 // METHOD NAME : MediaCurl::getDirInfo
1357 // METHOD TYPE : PMError
1359 // DESCRIPTION : Asserted that media is attached and retlist is empty.
1361 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1362 const Pathname & dirname, bool dots ) const
1364 getDirectoryYast( retlist, dirname, dots );
1367 ///////////////////////////////////////////////////////////////////
1370 // METHOD NAME : MediaCurl::getDirInfo
1371 // METHOD TYPE : PMError
1373 // DESCRIPTION : Asserted that media is attached and retlist is empty.
1375 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1376 const Pathname & dirname, bool dots ) const
1378 getDirectoryYast( retlist, dirname, dots );
1381 ///////////////////////////////////////////////////////////////////
1384 // METHOD NAME : MediaCurl::progressCallback
1385 // METHOD TYPE : int
1387 // DESCRIPTION : Progress callback triggered from MediaCurl::getFile
1389 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow,
1390 double ultotal, double ulnow )
1392 ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1395 // send progress report first, abort transfer if requested
1398 if (! (*(pdata->report))->progress(int( dlnow * 100 / dltotal ), pdata->url))
1400 return 1; // abort transfer
1404 // check if we there is a timeout set
1405 if( pdata->timeout > 0)
1407 time_t now = time(NULL);
1410 bool progress = false;
1412 // reset time of last change in case initial time()
1413 // failed or the time was adjusted (goes backward)
1414 if( pdata->ltime <= 0 || pdata->ltime > now)
1417 // update download data if changed, mark progress
1418 if( dlnow != pdata->dload)
1421 pdata->dload = dlnow;
1424 // update upload data if changed, mark progress
1425 if( ulnow != pdata->uload)
1428 pdata->uload = ulnow;
1432 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1434 pdata->reached = true;
1435 return 1; // aborts transfer
1443 string MediaCurl::getAuthHint() const
1445 long auth_info = CURLAUTH_NONE;
1448 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1450 if(infoRet == CURLE_OK)
1452 return CurlAuthData::auth_type_long2str(auth_info);
1458 } // namespace media