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)
529 curl_version_info_data *curl_info = NULL;
530 curl_info = curl_version_info(CURLVERSION_NOW);
532 if (curl_info->protocols)
534 const char *
const *proto;
537 for(proto=curl_info->protocols; !found && *proto; ++proto)
539 if( scheme == std::string((
const char *)*proto))
544 std::string msg(
"Unsupported protocol '");
555 char *ptr = getenv(
"ZYPP_MEDIA_CURL_DEBUG");
556 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
559 curl_easy_setopt(
_curl, CURLOPT_VERBOSE, 1L);
560 curl_easy_setopt(
_curl, CURLOPT_DEBUGFUNCTION, log_curl);
565 curl_easy_setopt(
_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
566 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
625 #if CURLVERSION_AT_LEAST(7,19,4)
627 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
645 #ifdef CURLSSLOPT_ALLOW_BEAST
647 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
656 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
672 if (use_auth.empty())
673 use_auth =
"digest,basic";
675 if( auth != CURLAUTH_NONE)
677 DBG <<
"Enabling HTTP authentication methods: " << use_auth
678 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
687 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
697 if ( proxyuserpwd.empty() )
702 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
706 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
714 if ( ! proxyuserpwd.empty() )
716 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
719 #if CURLVERSION_AT_LEAST(7,19,4)
724 DBG <<
"Proxy: explicitly NOPROXY" << endl;
731 DBG <<
"Proxy: not explicitly set" << endl;
742 #if CURLVERSION_AT_LEAST(7,15,5)
754 MIL <<
"No cookies requested" << endl;
759 #if CURLVERSION_AT_LEAST(7,18,0)
764 for ( TransferSettings::Headers::const_iterator it = vol_settings.
headersBegin();
794 if( mountpoint.empty())
801 _curl = curl_easy_init();
838 curl_easy_cleanup(
_curl );
859 if ( path.empty() || path ==
"/" )
861 path = filename_r.absolutename().
asString();
863 else if ( *path.rbegin() ==
'/' )
865 path += filename_r.absolutename().asString().substr(1);
869 path += filename_r.absolutename().asString();
961 bool timeout_reached )
const
966 if (filename.empty())
975 case CURLE_UNSUPPORTED_PROTOCOL:
976 case CURLE_URL_MALFORMAT:
977 case CURLE_URL_MALFORMAT_USER:
980 case CURLE_LOGIN_DENIED:
984 case CURLE_HTTP_RETURNED_ERROR:
986 long httpReturnCode = 0;
987 CURLcode infoRet = curl_easy_getinfo(
_curl,
988 CURLINFO_RESPONSE_CODE,
990 if ( infoRet == CURLE_OK )
992 string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
993 switch ( httpReturnCode )
999 DBG << msg <<
" Login failed (URL: " << url.
asString() <<
")" << std::endl;
1000 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
1014 if (url.
asString().find(
"novell.com") != string::npos)
1015 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1022 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1027 string msg =
"Unable to retrieve HTTP response:";
1028 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1033 case CURLE_FTP_COULDNT_RETR_FILE:
1034 #if CURLVERSION_AT_LEAST(7,16,0)
1035 case CURLE_REMOTE_FILE_NOT_FOUND:
1037 case CURLE_FTP_ACCESS_DENIED:
1038 case CURLE_TFTP_NOTFOUND:
1039 err =
"File not found";
1042 case CURLE_BAD_PASSWORD_ENTERED:
1043 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1044 err =
"Login failed";
1046 case CURLE_COULDNT_RESOLVE_PROXY:
1047 case CURLE_COULDNT_RESOLVE_HOST:
1048 case CURLE_COULDNT_CONNECT:
1049 case CURLE_FTP_CANT_GET_HOST:
1050 err =
"Connection failed";
1052 case CURLE_WRITE_ERROR:
1053 err =
"Write error";
1055 case CURLE_PARTIAL_FILE:
1056 case CURLE_OPERATION_TIMEDOUT:
1057 timeout_reached =
true;
1059 case CURLE_ABORTED_BY_CALLBACK:
1060 if( timeout_reached )
1062 err =
"Timeout reached";
1070 case CURLE_SSL_PEER_CERTIFICATE:
1072 err =
"Unrecognized error";
1094 DBG << filename.asString() << endl;
1119 string urlBuffer( curlUrl.
asString());
1120 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1121 urlBuffer.c_str() );
1133 ret = curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
1135 ret = curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
1138 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1139 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1145 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1149 FILE *file = ::fopen(
"/dev/null",
"w" );
1151 ERR <<
"fopen failed for /dev/null" << endl;
1152 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1153 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1159 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1166 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1170 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1171 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1177 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1184 CURLcode ok = curl_easy_perform(
_curl );
1185 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1190 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1200 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L);
1209 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL);
1234 return ( ok == CURLE_OK );
1240 #if DETECT_DIR_INDEX
1253 bool not_a_file =
false;
1255 CURLcode ret = curl_easy_getinfo(
_curl,
1256 CURLINFO_EFFECTIVE_URL,
1258 if ( ret == CURLE_OK && ptr != NULL)
1263 std::string path( eurl.getPathName());
1264 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1266 DBG <<
"Effective url ("
1268 <<
") seems to provide the index of a directory"
1284 Pathname dest = target.absolutename();
1287 DBG <<
"assert_dir " << dest.dirname() <<
" failed" << endl;
1291 string destNew = target.asString() +
".new.zypp.XXXXXX";
1292 char *buf = ::strdup( destNew.c_str());
1295 ERR <<
"out of memory for temp file name" << endl;
1300 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1304 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1310 FILE *file = ::fdopen( tmp_fd,
"we" );
1314 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1318 DBG <<
"dest: " << dest << endl;
1319 DBG <<
"temp: " << destNew << endl;
1324 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1325 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)PathInfo(target).mtime());
1329 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1330 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1340 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1341 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1345 long httpReturnCode = 0;
1346 CURLcode infoRet = curl_easy_getinfo(
_curl,
1347 CURLINFO_RESPONSE_CODE,
1349 bool modified =
true;
1350 if (infoRet == CURLE_OK)
1353 if ( httpReturnCode == 304
1356 DBG <<
" Not modified.";
1363 WAR <<
"Could not get the reponse code." << endl;
1366 if (modified || infoRet != CURLE_OK)
1371 ERR <<
"Failed to chmod file " << destNew << endl;
1373 if (::fclose( file ))
1375 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1379 if (
rename( destNew, dest ) != 0 ) {
1380 ERR <<
"Rename failed" << endl;
1391 DBG <<
"done: " << PathInfo(dest) << endl;
1398 DBG << filename.asString() << endl;
1423 string urlBuffer( curlUrl.
asString());
1424 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1425 urlBuffer.c_str() );
1430 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1438 report->start(url, dest);
1439 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1440 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1443 ret = curl_easy_perform(
_curl );
1444 #if CURLVERSION_AT_LEAST(7,19,4)
1449 if ( ftell(file) == 0 && ret == 0 )
1451 long httpReturnCode = 33;
1452 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1454 long conditionUnmet = 33;
1455 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1457 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1458 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1459 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1460 ret = curl_easy_perform(
_curl );
1466 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1467 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1473 <<
", temp file size " << ftell(file)
1474 <<
" bytes." << endl;
1488 #if DETECT_DIR_INDEX
1493 #endif // DETECT_DIR_INDEX
1503 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1504 Pathname filename = dirname + it->name;
1507 switch ( it->type ) {
1514 getDir( filename, recurse_r );
1518 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1532 const Pathname & dirname,
bool dots )
const
1540 const Pathname & dirname,
bool dots )
const
1548 double dltotal,
double dlnow,
1549 double ultotal,
double ulnow)
1551 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1555 long httpReturnCode = 0;
1556 if (curl_easy_getinfo(pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode) != CURLE_OK || httpReturnCode == 0)
1559 time_t now = time(NULL);
1564 if( pdata->ltime <= 0 || pdata->ltime > now)
1572 if (dlnow > 0 || ulnow > 0)
1574 dif = (now - pdata->ltime);
1575 dif = dif > 0 ? dif : 0;
1586 if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1587 pdata->drate_avg = (dlnow / pdata->secs);
1591 pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1592 pdata->dload_period = dlnow;
1599 if (!(*(pdata->report))->progress(
int( dltotal ? dlnow * 100 / dltotal : 0 ),
1602 pdata->drate_period))
1609 if( pdata->timeout > 0)
1613 bool progress =
false;
1616 if( dlnow != pdata->dload)
1619 pdata->dload = dlnow;
1623 if( ulnow != pdata->uload)
1626 pdata->uload = ulnow;
1630 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1632 pdata->reached =
true;
1643 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1644 return pdata ? pdata->curl : 0;
1651 long auth_info = CURLAUTH_NONE;
1654 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1656 if(infoRet == CURLE_OK)
1669 Target_Ptr target = zypp::getZYpp()->getTarget();
1676 if (cmcred && firstTry)
1679 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1694 curlcred->setUsername(cmcred->username());
1699 string prompt_msg = boost::str(boost::format(
1705 curlcred->setAuthType(availAuthTypes);
1708 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1710 DBG <<
"callback answer: retry" << endl
1711 <<
"CurlAuthData: " << *curlcred << endl;
1713 if (curlcred->valid())
1715 credentials = curlcred;
1729 DBG <<
"callback answer: cancel" << endl;
1745 if (credentials->authType() == CURLAUTH_NONE)
1746 credentials->setAuthType(availAuthTypes);
1749 if (credentials->authType() != CURLAUTH_NONE)
1753 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1759 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).
unsigned split(const C_Str &line_r, _OutputIterator result_r, const C_Str &sepchars_r=" \t")
Split line_r into words.
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.
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.
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.
#define _(MSG)
Return translated text.
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)
std::string form(const char *format,...)
Printf style construction of std::string.
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.