34 #include <sys/types.h> 36 #include <sys/mount.h> 41 #define DETECT_DIR_INDEX 0 42 #define CONNECT_TIMEOUT 60 43 #define TRANSFER_TIMEOUT_MAX 60 * 60 45 #define EXPLICITLY_NO_PROXY "_none_" 47 #undef CURLVERSION_AT_LEAST 48 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O) 58 extern "C" void _do_free_once()
60 curl_global_cleanup();
63 extern "C" void globalFreeOnce()
68 extern "C" void _do_init_once()
70 CURLcode ret = curl_global_init( CURL_GLOBAL_ALL );
73 WAR <<
"curl global init failed" << endl;
86 inline void globalInitOnce()
91 int log_curl(CURL *
curl, curl_infotype info,
92 char *ptr,
size_t len,
void *max_lvl)
98 case CURLINFO_TEXT: lvl = 1; pfx =
"*";
break;
99 case CURLINFO_HEADER_IN: lvl = 2; pfx =
"<";
break;
100 case CURLINFO_HEADER_OUT: lvl = 2; pfx =
">";
break;
103 if( lvl > 0 && max_lvl != NULL && lvl <= *((
long *)max_lvl))
105 std::string msg(ptr, len);
106 std::list<std::string> lines;
107 std::list<std::string>::const_iterator line;
109 for(line = lines.begin(); line != lines.end(); ++line)
111 DBG << pfx <<
" " << *line << endl;
119 void *ptr,
size_t size,
size_t nmemb,
void *stream)
123 char * lstart = (
char *)ptr, * lend = (
char *)ptr;
125 size_t max = size * nmemb;
126 while (pos + 1 < max)
129 for (lstart = lend; *lend !=
'\n' && pos < max; ++lend, ++pos);
132 string line(lstart, lend);
133 if (line.find(
"Location") != string::npos)
135 DBG <<
"redirecting to " << line << endl;
160 inline int getZYPP_MEDIA_CURL_IPRESOLVE()
163 if (
const char * envp = getenv(
"ZYPP_MEDIA_CURL_IPRESOLVE" ) )
165 WAR <<
"env set: $ZYPP_MEDIA_CURL_IPRESOLVE='" << envp <<
"'" << endl;
166 if ( strcmp( envp,
"4" ) == 0 ) ret = 4;
167 else if ( strcmp( envp,
"6" ) == 0 ) ret = 6;
175 static int _v = getZYPP_MEDIA_CURL_IPRESOLVE();
199 callback::SendReport<DownloadProgressReport> *
report;
215 void updateStats(
double dltotal = 0.0,
double dlnow = 0.0 )
217 time_t now = _timeNow = time(0);
220 if ( dltotal && dltotal != _dnlTotal )
223 if ( dlnow && dlnow != _dnlNow )
228 else if ( !_dnlNow && !_dnlTotal )
236 if ( !_timeStart || _timeStart > now )
237 _timeStart = _timeLast = _timeRcv = now;
241 reached = ( (now -
_timeRcv) > timeout );
245 _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
248 _drateTotal = _dnlNow / std::max(
int(now - _timeStart), 1 );
250 if ( _timeLast < now )
252 _drateLast = (_dnlNow -
_dnlLast) /
int(now - _timeLast);
257 else if ( _timeStart == _timeLast )
261 int reportProgress()
const 265 if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
289 inline void escape(
string & str_r,
290 const char char_r,
const string & escaped_r ) {
292 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
293 str_r.replace( pos, 1, escaped_r );
297 inline string escapedPath(
string path_r ) {
298 escape( path_r,
' ',
"%20" );
302 inline string unEscape(
string text_r ) {
303 char * tmp = curl_unescape( text_r.c_str(), 0 );
320 long num = str::strtonum<long>(param);
344 if( verify.empty() ||
350 else if( verify ==
"no")
357 std::vector<std::string> flags;
358 std::vector<std::string>::const_iterator flag;
359 str::split( verify, std::back_inserter(flags),
",");
360 for(flag = flags.begin(); flag != flags.end(); ++flag)
364 else if( *flag ==
"peer")
373 if( ! ca_path.empty())
375 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
382 if( ! client_cert.empty())
384 if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
390 if( ! client_key.empty())
392 if( !PathInfo(client_key).isFile() || !client_key.absolute())
399 if ( ! param.empty() )
411 if ( ! proxyport.empty() ) {
412 param +=
":" + proxyport;
420 if ( ! param.empty() )
432 CurlAuthData::auth_type_str2long(param);
436 DBG <<
"Rethrowing as MediaUnauthorizedException.";
444 if( !param.empty() && param ==
"no" )
461 s.
setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
474 Pathname MediaCurl::_cookieFile =
"/var/lib/YaST2/cookies";
486 static const std::string
_value(
488 "X-ZYpp-AnonymousId: %s",
489 Target::anonymousUniqueId( Pathname() ).c_str() ) )
491 return _value.c_str();
504 static const std::string
_value(
506 "X-ZYpp-DistributionFlavor: %s",
507 Target::distributionFlavor( Pathname() ).c_str() ) )
509 return _value.c_str();
522 static const std::string
_value(
524 "ZYpp %s (curl %s) %s" 526 , curl_version_info(CURLVERSION_NOW)->version
527 , Target::targetDistribution( Pathname() ).c_str()
530 return _value.c_str();
536 #define SET_OPTION(opt,val) do { \ 537 ret = curl_easy_setopt ( _curl, opt, val ); \ 539 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \ 543 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val) 544 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val) 545 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val) 547 MediaCurl::MediaCurl(
const Url & url_r,
548 const Pathname & attach_point_hint_r )
558 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
566 char *atemp = ::strdup( apath.asString().c_str());
568 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
569 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
571 WAR <<
"attach point " << ainfo.path()
572 <<
" is not useable for " << url_r.
getScheme() << endl;
575 else if( atest != NULL)
623 curl_version_info_data *curl_info = NULL;
624 curl_info = curl_version_info(CURLVERSION_NOW);
626 if (curl_info->protocols)
628 const char *
const *proto;
631 for(proto=curl_info->protocols; !found && *proto; ++proto)
633 if( scheme == std::string((
const char *)*proto))
638 std::string msg(
"Unsupported protocol '");
649 char *ptr = getenv(
"ZYPP_MEDIA_CURL_DEBUG");
650 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
653 curl_easy_setopt(
_curl, CURLOPT_VERBOSE, 1L);
654 curl_easy_setopt(
_curl, CURLOPT_DEBUGFUNCTION, log_curl);
659 curl_easy_setopt(
_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
660 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
707 case 4:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
break;
708 case 6:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
break;
732 #if CURLVERSION_AT_LEAST(7,19,4) 734 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
752 #ifdef CURLSSLOPT_ALLOW_BEAST 754 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
763 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
779 if (use_auth.empty())
780 use_auth =
"digest,basic";
782 if( auth != CURLAUTH_NONE)
784 DBG <<
"Enabling HTTP authentication methods: " << use_auth
785 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
794 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
804 if ( proxyuserpwd.empty() )
809 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
813 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
821 if ( ! proxyuserpwd.empty() )
823 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
826 #if CURLVERSION_AT_LEAST(7,19,4) 831 DBG <<
"Proxy: explicitly NOPROXY" << endl;
837 DBG <<
"Proxy: not explicitly set" << endl;
838 DBG <<
"Proxy: libcurl may look into the environment" << endl;
849 #if CURLVERSION_AT_LEAST(7,15,5) 861 MIL <<
"No cookies requested" << endl;
866 #if CURLVERSION_AT_LEAST(7,18,0) 871 for ( TransferSettings::Headers::const_iterator it = vol_settings.
headersBegin();
903 _curl = curl_easy_init();
940 curl_easy_cleanup(
_curl );
1051 bool timeout_reached )
const 1056 if (filename.empty())
1064 case CURLE_UNSUPPORTED_PROTOCOL:
1065 case CURLE_URL_MALFORMAT:
1066 case CURLE_URL_MALFORMAT_USER:
1069 case CURLE_LOGIN_DENIED:
1073 case CURLE_HTTP_RETURNED_ERROR:
1075 long httpReturnCode = 0;
1076 CURLcode infoRet = curl_easy_getinfo(
_curl,
1077 CURLINFO_RESPONSE_CODE,
1079 if ( infoRet == CURLE_OK )
1081 string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
1082 switch ( httpReturnCode )
1088 DBG << msg <<
" Login failed (URL: " << url.
asString() <<
")" << std::endl;
1089 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
1103 if (url.
asString().find(
"novell.com") != string::npos)
1104 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1112 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1117 string msg =
"Unable to retrieve HTTP response:";
1118 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1123 case CURLE_FTP_COULDNT_RETR_FILE:
1124 #if CURLVERSION_AT_LEAST(7,16,0) 1125 case CURLE_REMOTE_FILE_NOT_FOUND:
1127 case CURLE_FTP_ACCESS_DENIED:
1128 case CURLE_TFTP_NOTFOUND:
1129 err =
"File not found";
1132 case CURLE_BAD_PASSWORD_ENTERED:
1133 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1134 err =
"Login failed";
1136 case CURLE_COULDNT_RESOLVE_PROXY:
1137 case CURLE_COULDNT_RESOLVE_HOST:
1138 case CURLE_COULDNT_CONNECT:
1139 case CURLE_FTP_CANT_GET_HOST:
1140 err =
"Connection failed";
1142 case CURLE_WRITE_ERROR:
1143 err =
"Write error";
1145 case CURLE_PARTIAL_FILE:
1146 case CURLE_OPERATION_TIMEDOUT:
1147 timeout_reached =
true;
1149 case CURLE_ABORTED_BY_CALLBACK:
1150 if( timeout_reached )
1152 err =
"Timeout reached";
1160 case CURLE_SSL_PEER_CERTIFICATE:
1180 DBG << filename.asString() << endl;
1205 string urlBuffer( curlUrl.
asString());
1206 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1207 urlBuffer.c_str() );
1219 ret = curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
1221 ret = curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
1224 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1225 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1231 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1235 FILE *file = ::fopen(
"/dev/null",
"w" );
1237 ERR <<
"fopen failed for /dev/null" << endl;
1238 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1239 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1245 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1252 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1256 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1257 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1263 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1270 CURLcode ok = curl_easy_perform(
_curl );
1271 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1276 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1286 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L);
1295 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL);
1320 return ( ok == CURLE_OK );
1326 #if DETECT_DIR_INDEX 1339 bool not_a_file =
false;
1341 CURLcode ret = curl_easy_getinfo(
_curl,
1342 CURLINFO_EFFECTIVE_URL,
1344 if ( ret == CURLE_OK && ptr != NULL)
1350 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1352 DBG <<
"Effective url (" 1354 <<
") seems to provide the index of a directory" 1370 Pathname dest = target.absolutename();
1373 DBG <<
"assert_dir " << dest.dirname() <<
" failed" << endl;
1377 string destNew = target.asString() +
".new.zypp.XXXXXX";
1378 char *buf = ::strdup( destNew.c_str());
1381 ERR <<
"out of memory for temp file name" << endl;
1386 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1390 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1396 FILE *file = ::fdopen( tmp_fd,
"we" );
1400 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1404 DBG <<
"dest: " << dest << endl;
1405 DBG <<
"temp: " << destNew << endl;
1410 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1411 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)PathInfo(target).mtime());
1415 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1416 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1426 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1427 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1431 long httpReturnCode = 0;
1432 CURLcode infoRet = curl_easy_getinfo(
_curl,
1433 CURLINFO_RESPONSE_CODE,
1435 bool modified =
true;
1436 if (infoRet == CURLE_OK)
1439 if ( httpReturnCode == 304
1442 DBG <<
" Not modified.";
1449 WAR <<
"Could not get the reponse code." << endl;
1452 if (modified || infoRet != CURLE_OK)
1457 ERR <<
"Failed to chmod file " << destNew << endl;
1459 if (::fclose( file ))
1461 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1465 if (
rename( destNew, dest ) != 0 ) {
1466 ERR <<
"Rename failed" << endl;
1477 DBG <<
"done: " << PathInfo(dest) << endl;
1484 DBG << filename.asString() << endl;
1509 string urlBuffer( curlUrl.
asString());
1510 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1511 urlBuffer.c_str() );
1516 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1524 report->start(url, dest);
1525 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1526 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1529 ret = curl_easy_perform(
_curl );
1530 #if CURLVERSION_AT_LEAST(7,19,4) 1535 if ( ftell(file) == 0 && ret == 0 )
1537 long httpReturnCode = 33;
1538 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1540 long conditionUnmet = 33;
1541 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1543 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1544 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1545 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1546 ret = curl_easy_perform(
_curl );
1552 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1553 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1559 <<
", temp file size " << ftell(file)
1560 <<
" bytes." << endl;
1574 #if DETECT_DIR_INDEX 1579 #endif // DETECT_DIR_INDEX 1589 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1590 Pathname filename = dirname + it->name;
1593 switch ( it->type ) {
1600 getDir( filename, recurse_r );
1604 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1618 const Pathname & dirname,
bool dots )
const 1626 const Pathname & dirname,
bool dots )
const 1635 ProgressData *pdata =
reinterpret_cast<ProgressData *
>( clientp );
1641 pdata->updateStats( 0.0, dlnow );
1642 return pdata->reportProgress();
1649 ProgressData *pdata =
reinterpret_cast<ProgressData *
>( clientp );
1653 long httpReturnCode = 0;
1654 if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1655 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1657 pdata->updateStats( dltotal, dlnow );
1658 return pdata->reportProgress();
1665 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1666 return pdata ? pdata->curl : 0;
1673 long auth_info = CURLAUTH_NONE;
1676 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1678 if(infoRet == CURLE_OK)
1691 Target_Ptr target = zypp::getZYpp()->getTarget();
1698 if (cmcred && firstTry)
1701 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1716 curlcred->setUsername(cmcred->username());
1725 curlcred->setAuthType(availAuthTypes);
1728 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1730 DBG <<
"callback answer: retry" << endl
1731 <<
"CurlAuthData: " << *curlcred << endl;
1733 if (curlcred->valid())
1735 credentials = curlcred;
1749 DBG <<
"callback answer: cancel" << endl;
1765 if (credentials->authType() == CURLAUTH_NONE)
1766 credentials->setAuthType(availAuthTypes);
1769 if (credentials->authType() != CURLAUTH_NONE)
1773 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1779 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.
int ZYPP_MEDIA_CURL_IPRESOLVE()
#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'.
Maintain [min,max] and counter (value) for progress counting.
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.
Easy-to use interface to the ZYPP dependency resolver.
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.