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_MAX 60 * 60
46 #define EXPLICITLY_NO_PROXY "_none_"
48 #undef CURLVERSION_AT_LEAST
49 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
52 using namespace zypp::base;
59 extern "C" void _do_free_once()
61 curl_global_cleanup();
64 extern "C" void globalFreeOnce()
69 extern "C" void _do_init_once()
71 CURLcode ret = curl_global_init( CURL_GLOBAL_ALL );
74 WAR <<
"curl global init failed" << endl;
87 inline void globalInitOnce()
92 int log_curl(CURL *
curl, curl_infotype info,
93 char *ptr,
size_t len,
void *max_lvl)
99 case CURLINFO_TEXT: lvl = 1; pfx =
"*";
break;
100 case CURLINFO_HEADER_IN: lvl = 2; pfx =
"<";
break;
101 case CURLINFO_HEADER_OUT: lvl = 2; pfx =
">";
break;
104 if( lvl > 0 && max_lvl != NULL && lvl <= *((
long *)max_lvl))
106 std::string msg(ptr, len);
107 std::list<std::string> lines;
108 std::list<std::string>::const_iterator line;
110 for(line = lines.begin(); line != lines.end(); ++line)
112 DBG << pfx <<
" " << *line << endl;
120 void *ptr,
size_t size,
size_t nmemb,
void *stream)
124 char * lstart = (
char *)ptr, * lend = (
char *)ptr;
126 size_t max = size * nmemb;
127 while (pos + 1 < max)
130 for (lstart = lend; *lend !=
'\n' && pos < max; ++lend, ++pos);
133 string line(lstart, lend);
134 if (line.find(
"Location") != string::npos)
136 DBG <<
"redirecting to " << line << endl;
161 callback::SendReport<DownloadProgressReport> *_report=NULL)
178 callback::SendReport<DownloadProgressReport> *
report;
198 inline void escape(
string & str_r,
199 const char char_r,
const string & escaped_r ) {
201 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
202 str_r.replace( pos, 1, escaped_r );
206 inline string escapedPath(
string path_r ) {
207 escape( path_r,
' ',
"%20" );
211 inline string unEscape(
string text_r ) {
212 char * tmp = curl_unescape( text_r.c_str(), 0 );
229 long num = str::strtonum<long>(param);
253 if( verify.empty() ||
259 else if( verify ==
"no")
266 std::vector<std::string> flags;
267 std::vector<std::string>::const_iterator flag;
268 str::split( verify, std::back_inserter(flags),
",");
269 for(flag = flags.begin(); flag != flags.end(); ++flag)
273 else if( *flag ==
"peer")
282 if( ! ca_path.empty())
284 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
291 if( ! client_cert.empty())
293 if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
299 if( ! client_key.empty())
301 if( !PathInfo(client_key).isFile() || !client_key.absolute())
308 if ( ! param.empty() )
320 if ( ! proxyport.empty() ) {
321 param +=
":" + proxyport;
329 if ( ! param.empty() )
341 CurlAuthData::auth_type_str2long(param);
345 DBG <<
"Rethrowing as MediaUnauthorizedException.";
353 if( !param.empty() && param ==
"no" )
370 s.
setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
383 Pathname MediaCurl::_cookieFile =
"/var/lib/YaST2/cookies";
395 static const std::string
_value(
397 "X-ZYpp-AnonymousId: %s",
398 Target::anonymousUniqueId( Pathname() ).c_str() ) )
400 return _value.c_str();
413 static const std::string
_value(
415 "X-ZYpp-DistributionFlavor: %s",
416 Target::distributionFlavor( Pathname() ).c_str() ) )
418 return _value.c_str();
431 static const std::string
_value(
433 "ZYpp %s (curl %s) %s"
435 , curl_version_info(CURLVERSION_NOW)->version
436 , Target::targetDistribution( Pathname() ).c_str()
439 return _value.c_str();
445 #define SET_OPTION(opt,val) do { \
446 ret = curl_easy_setopt ( _curl, opt, val ); \
448 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
452 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
453 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
454 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
456 MediaCurl::MediaCurl(
const Url & url_r,
457 const Pathname & attach_point_hint_r )
467 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
475 char *atemp = ::strdup( apath.asString().c_str());
477 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
478 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
480 WAR <<
"attach point " << ainfo.path()
481 <<
" is not useable for " << url_r.
getScheme() << endl;
484 else if( atest != NULL)
532 curl_version_info_data *curl_info = NULL;
533 curl_info = curl_version_info(CURLVERSION_NOW);
535 if (curl_info->protocols)
537 const char *
const *proto;
540 for(proto=curl_info->protocols; !found && *proto; ++proto)
542 if( scheme == std::string((
const char *)*proto))
547 std::string msg(
"Unsupported protocol '");
558 char *ptr = getenv(
"ZYPP_MEDIA_CURL_DEBUG");
559 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
562 curl_easy_setopt(
_curl, CURLOPT_VERBOSE, 1L);
563 curl_easy_setopt(
_curl, CURLOPT_DEBUGFUNCTION, log_curl);
568 curl_easy_setopt(
_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
569 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
628 #if CURLVERSION_AT_LEAST(7,19,4)
630 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
648 #ifdef CURLSSLOPT_ALLOW_BEAST
650 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
659 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
675 if (use_auth.empty())
676 use_auth =
"digest,basic";
678 if( auth != CURLAUTH_NONE)
680 DBG <<
"Enabling HTTP authentication methods: " << use_auth
681 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
690 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
700 if ( proxyuserpwd.empty() )
705 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
709 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
717 if ( ! proxyuserpwd.empty() )
719 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
722 #if CURLVERSION_AT_LEAST(7,19,4)
727 DBG <<
"Proxy: explicitly NOPROXY" << endl;
733 DBG <<
"Proxy: not explicitly set" << endl;
734 DBG <<
"Proxy: libcurl may look into the environment" << endl;
745 #if CURLVERSION_AT_LEAST(7,15,5)
757 MIL <<
"No cookies requested" << endl;
762 #if CURLVERSION_AT_LEAST(7,18,0)
767 for ( TransferSettings::Headers::const_iterator it = vol_settings.
headersBegin();
797 if( mountpoint.empty())
804 _curl = curl_easy_init();
841 curl_easy_cleanup(
_curl );
952 bool timeout_reached )
const
957 if (filename.empty())
966 case CURLE_UNSUPPORTED_PROTOCOL:
967 case CURLE_URL_MALFORMAT:
968 case CURLE_URL_MALFORMAT_USER:
971 case CURLE_LOGIN_DENIED:
975 case CURLE_HTTP_RETURNED_ERROR:
977 long httpReturnCode = 0;
978 CURLcode infoRet = curl_easy_getinfo(
_curl,
979 CURLINFO_RESPONSE_CODE,
981 if ( infoRet == CURLE_OK )
983 string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
984 switch ( httpReturnCode )
990 DBG << msg <<
" Login failed (URL: " << url.
asString() <<
")" << std::endl;
991 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
1005 if (url.
asString().find(
"novell.com") != string::npos)
1006 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1013 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1018 string msg =
"Unable to retrieve HTTP response:";
1019 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1024 case CURLE_FTP_COULDNT_RETR_FILE:
1025 #if CURLVERSION_AT_LEAST(7,16,0)
1026 case CURLE_REMOTE_FILE_NOT_FOUND:
1028 case CURLE_FTP_ACCESS_DENIED:
1029 case CURLE_TFTP_NOTFOUND:
1030 err =
"File not found";
1033 case CURLE_BAD_PASSWORD_ENTERED:
1034 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1035 err =
"Login failed";
1037 case CURLE_COULDNT_RESOLVE_PROXY:
1038 case CURLE_COULDNT_RESOLVE_HOST:
1039 case CURLE_COULDNT_CONNECT:
1040 case CURLE_FTP_CANT_GET_HOST:
1041 err =
"Connection failed";
1043 case CURLE_WRITE_ERROR:
1044 err =
"Write error";
1046 case CURLE_PARTIAL_FILE:
1047 case CURLE_OPERATION_TIMEDOUT:
1048 timeout_reached =
true;
1050 case CURLE_ABORTED_BY_CALLBACK:
1051 if( timeout_reached )
1053 err =
"Timeout reached";
1061 case CURLE_SSL_PEER_CERTIFICATE:
1063 err =
"Unrecognized error";
1085 DBG << filename.asString() << endl;
1110 string urlBuffer( curlUrl.
asString());
1111 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1112 urlBuffer.c_str() );
1124 ret = curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
1126 ret = curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
1129 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1130 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1136 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1140 FILE *file = ::fopen(
"/dev/null",
"w" );
1142 ERR <<
"fopen failed for /dev/null" << endl;
1143 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1144 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1150 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1157 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1161 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1162 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1168 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1175 CURLcode ok = curl_easy_perform(
_curl );
1176 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1181 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1191 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L);
1200 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL);
1225 return ( ok == CURLE_OK );
1231 #if DETECT_DIR_INDEX
1244 bool not_a_file =
false;
1246 CURLcode ret = curl_easy_getinfo(
_curl,
1247 CURLINFO_EFFECTIVE_URL,
1249 if ( ret == CURLE_OK && ptr != NULL)
1254 std::string path( eurl.getPathName());
1255 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1257 DBG <<
"Effective url ("
1259 <<
") seems to provide the index of a directory"
1275 Pathname dest = target.absolutename();
1278 DBG <<
"assert_dir " << dest.dirname() <<
" failed" << endl;
1282 string destNew = target.asString() +
".new.zypp.XXXXXX";
1283 char *buf = ::strdup( destNew.c_str());
1286 ERR <<
"out of memory for temp file name" << endl;
1291 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1295 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1301 FILE *file = ::fdopen( tmp_fd,
"we" );
1305 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1309 DBG <<
"dest: " << dest << endl;
1310 DBG <<
"temp: " << destNew << endl;
1315 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1316 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)PathInfo(target).mtime());
1320 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1321 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1331 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1332 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1336 long httpReturnCode = 0;
1337 CURLcode infoRet = curl_easy_getinfo(
_curl,
1338 CURLINFO_RESPONSE_CODE,
1340 bool modified =
true;
1341 if (infoRet == CURLE_OK)
1344 if ( httpReturnCode == 304
1347 DBG <<
" Not modified.";
1354 WAR <<
"Could not get the reponse code." << endl;
1357 if (modified || infoRet != CURLE_OK)
1362 ERR <<
"Failed to chmod file " << destNew << endl;
1364 if (::fclose( file ))
1366 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1370 if (
rename( destNew, dest ) != 0 ) {
1371 ERR <<
"Rename failed" << endl;
1382 DBG <<
"done: " << PathInfo(dest) << endl;
1389 DBG << filename.asString() << endl;
1414 string urlBuffer( curlUrl.
asString());
1415 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1416 urlBuffer.c_str() );
1421 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1429 report->start(url, dest);
1430 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1431 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1434 ret = curl_easy_perform(
_curl );
1435 #if CURLVERSION_AT_LEAST(7,19,4)
1440 if ( ftell(file) == 0 && ret == 0 )
1442 long httpReturnCode = 33;
1443 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1445 long conditionUnmet = 33;
1446 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1448 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1449 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1450 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1451 ret = curl_easy_perform(
_curl );
1457 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1458 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1464 <<
", temp file size " << ftell(file)
1465 <<
" bytes." << endl;
1479 #if DETECT_DIR_INDEX
1484 #endif // DETECT_DIR_INDEX
1494 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1495 Pathname filename = dirname + it->name;
1498 switch ( it->type ) {
1505 getDir( filename, recurse_r );
1509 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1523 const Pathname & dirname,
bool dots )
const
1531 const Pathname & dirname,
bool dots )
const
1539 double dltotal,
double dlnow,
1540 double ultotal,
double ulnow)
1542 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1546 long httpReturnCode = 0;
1547 if (curl_easy_getinfo(pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode) != CURLE_OK || httpReturnCode == 0)
1550 time_t now = time(NULL);
1555 if( pdata->ltime <= 0 || pdata->ltime > now)
1563 if (dlnow > 0 || ulnow > 0)
1565 dif = (now - pdata->ltime);
1566 dif = dif > 0 ? dif : 0;
1577 if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1578 pdata->drate_avg = (dlnow / pdata->secs);
1582 pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1583 pdata->dload_period = dlnow;
1590 if (!(*(pdata->report))->progress(
int( dltotal ? dlnow * 100 / dltotal : 0 ),
1593 pdata->drate_period))
1600 if( pdata->timeout > 0)
1604 bool progress =
false;
1607 if( dlnow != pdata->dload)
1610 pdata->dload = dlnow;
1614 if( ulnow != pdata->uload)
1617 pdata->uload = ulnow;
1621 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1623 pdata->reached =
true;
1634 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1635 return pdata ? pdata->curl : 0;
1642 long auth_info = CURLAUTH_NONE;
1645 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1647 if(infoRet == CURLE_OK)
1660 Target_Ptr target = zypp::getZYpp()->getTarget();
1667 if (cmcred && firstTry)
1670 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1685 curlcred->setUsername(cmcred->username());
1690 string prompt_msg = boost::str(boost::format(
1696 curlcred->setAuthType(availAuthTypes);
1699 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1701 DBG <<
"callback answer: retry" << endl
1702 <<
"CurlAuthData: " << *curlcred << endl;
1704 if (curlcred->valid())
1706 credentials = curlcred;
1720 DBG <<
"callback answer: cancel" << endl;
1736 if (credentials->authType() == CURLAUTH_NONE)
1737 credentials->setAuthType(availAuthTypes);
1740 if (credentials->authType() != CURLAUTH_NONE)
1744 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1750 credentials->setUrl(
_url);
void setPassword(const std::string &pass, EEncoding eflag=zypp::url::E_DECODED)
Set the password in the URL authority.
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
static ZConfig & instance()
Singleton ctor.
const std::string & msg() const
Return the message string provided to the ctor.
Flag to request encoded string(s).
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
std::string escape(const C_Str &str_r, const char sep_r)
Escape desired character c using a backslash.
void setPathParams(const std::string ¶ms)
Set the path parameters.
pthread_once_t OnceFlag
The OnceFlag variable type.
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.
void setUsername(const std::string &user, EEncoding eflag=zypp::url::E_DECODED)
Set the username in the URL authority.
bool isValid() const
Verifies the Url.
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
void setFragment(const std::string &fragment, EEncoding eflag=zypp::url::E_DECODED)
Set the fragment string in the URL.
std::string asString() const
Returns a default string representation of the Url object.
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
void setPathName(const std::string &path, EEncoding eflag=zypp::url::E_DECODED)
Set the path name.
unsigned split(const C_Str &line_r, TOutputIterator result_r, const C_Str &sepchars_r=" \t")
Split line_r into words.
void callOnce(OnceFlag &flag, void(*func)())
Call once function.
std::string trim(const std::string &s, const Trim trim_r)
int unlink(const Pathname &path)
Like 'unlink'.
int rename(const Pathname &oldpath, const Pathname &newpath)
Like 'rename'.
std::list< DirEntry > DirContent
Returned by readdir.
std::string getQueryParam(const std::string ¶m, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
std::string numstring(char n, int w=0)
int rmdir(const Pathname &path)
Like 'rmdir'.
Base class for Exception.
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
std::string getScheme() const
Returns the scheme name of the URL.
std::string getPassword(EEncoding eflag=zypp::url::E_DECODED) const
Returns the password from the URL authority.
void delQueryParam(const std::string ¶m)
remove the specified query parameter.