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;
159 ProgressData( CURL *_curl, time_t _timeout = 0,
const Url & _url = Url(),
160 callback::SendReport<DownloadProgressReport> *_report =
nullptr )
172 callback::SendReport<DownloadProgressReport> *
report;
188 void updateStats(
double dltotal = 0.0,
double dlnow = 0.0 )
190 time_t now = _timeNow = time(0);
193 if ( dltotal && dltotal != _dnlTotal )
196 if ( dlnow && dlnow != _dnlNow )
201 else if ( !_dnlNow && !_dnlTotal )
209 if ( !_timeStart || _timeStart > now )
210 _timeStart = _timeLast = _timeRcv = now;
214 reached = ( (now -
_timeRcv) > timeout );
218 _dnlPercent = int(_dnlNow * 100 / _dnlTotal);
221 _drateTotal = _dnlNow / std::max(
int(now - _timeStart), 1 );
223 if ( _timeLast < now )
225 _drateLast = (_dnlNow -
_dnlLast) /
int(now - _timeLast);
230 else if ( _timeStart == _timeLast )
234 int reportProgress()
const 238 if ( report && !(*report)->progress( _dnlPercent, url, _drateTotal, _drateLast ) )
262 inline void escape(
string & str_r,
263 const char char_r,
const string & escaped_r ) {
265 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
266 str_r.replace( pos, 1, escaped_r );
270 inline string escapedPath(
string path_r ) {
271 escape( path_r,
' ',
"%20" );
275 inline string unEscape(
string text_r ) {
276 char * tmp = curl_unescape( text_r.c_str(), 0 );
293 long num = str::strtonum<long>(param);
317 if( verify.empty() ||
323 else if( verify ==
"no")
330 std::vector<std::string> flags;
331 std::vector<std::string>::const_iterator flag;
332 str::split( verify, std::back_inserter(flags),
",");
333 for(flag = flags.begin(); flag != flags.end(); ++flag)
337 else if( *flag ==
"peer")
346 if( ! ca_path.empty())
355 if( ! client_cert.empty())
363 if( ! client_key.empty())
372 if ( ! param.empty() )
384 if ( ! proxyport.empty() ) {
385 param +=
":" + proxyport;
393 if ( ! param.empty() )
405 CurlAuthData::auth_type_str2long(param);
409 DBG <<
"Rethrowing as MediaUnauthorizedException.";
417 if( !param.empty() && param ==
"no" )
434 s.
setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
447 Pathname MediaCurl::_cookieFile =
"/var/lib/YaST2/cookies";
459 static const std::string
_value(
461 "X-ZYpp-AnonymousId: %s",
462 Target::anonymousUniqueId(
Pathname() ).c_str() ) )
464 return _value.c_str();
477 static const std::string
_value(
479 "X-ZYpp-DistributionFlavor: %s",
480 Target::distributionFlavor(
Pathname() ).c_str() ) )
482 return _value.c_str();
495 static const std::string
_value(
497 "ZYpp %s (curl %s) %s" 499 , curl_version_info(CURLVERSION_NOW)->version
500 , Target::targetDistribution(
Pathname() ).c_str()
503 return _value.c_str();
509 #define SET_OPTION(opt,val) do { \ 510 ret = curl_easy_setopt ( _curl, opt, val ); \ 512 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \ 516 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val) 517 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val) 518 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val) 520 MediaCurl::MediaCurl(
const Url & url_r,
521 const Pathname & attach_point_hint_r )
531 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
539 char *atemp = ::strdup( apath.
asString().c_str());
542 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
544 WAR <<
"attach point " << ainfo.
path()
545 <<
" is not useable for " << url_r.
getScheme() << endl;
548 else if( atest != NULL)
596 curl_version_info_data *curl_info = NULL;
597 curl_info = curl_version_info(CURLVERSION_NOW);
599 if (curl_info->protocols)
601 const char *
const *proto;
604 for(proto=curl_info->protocols; !found && *proto; ++proto)
606 if( scheme == std::string((
const char *)*proto))
611 std::string msg(
"Unsupported protocol '");
622 char *ptr = getenv(
"ZYPP_MEDIA_CURL_DEBUG");
623 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
626 curl_easy_setopt(
_curl, CURLOPT_VERBOSE, 1L);
627 curl_easy_setopt(
_curl, CURLOPT_DEBUGFUNCTION, log_curl);
632 curl_easy_setopt(
_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
633 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
695 #if CURLVERSION_AT_LEAST(7,19,4) 697 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
715 #ifdef CURLSSLOPT_ALLOW_BEAST 717 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
726 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
742 if (use_auth.empty())
743 use_auth =
"digest,basic";
745 if( auth != CURLAUTH_NONE)
747 DBG <<
"Enabling HTTP authentication methods: " << use_auth
748 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
757 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
767 if ( proxyuserpwd.empty() )
772 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
776 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
784 if ( ! proxyuserpwd.empty() )
786 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
789 #if CURLVERSION_AT_LEAST(7,19,4) 794 DBG <<
"Proxy: explicitly NOPROXY" << endl;
800 DBG <<
"Proxy: not explicitly set" << endl;
801 DBG <<
"Proxy: libcurl may look into the environment" << endl;
812 #if CURLVERSION_AT_LEAST(7,15,5) 824 MIL <<
"No cookies requested" << endl;
829 #if CURLVERSION_AT_LEAST(7,18,0) 834 for ( TransferSettings::Headers::const_iterator it = vol_settings.
headersBegin();
866 _curl = curl_easy_init();
903 curl_easy_cleanup(
_curl );
1014 bool timeout_reached )
const 1019 if (filename.
empty())
1028 case CURLE_UNSUPPORTED_PROTOCOL:
1029 case CURLE_URL_MALFORMAT:
1030 case CURLE_URL_MALFORMAT_USER:
1033 case CURLE_LOGIN_DENIED:
1037 case CURLE_HTTP_RETURNED_ERROR:
1039 long httpReturnCode = 0;
1040 CURLcode infoRet = curl_easy_getinfo(
_curl,
1041 CURLINFO_RESPONSE_CODE,
1043 if ( infoRet == CURLE_OK )
1045 string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
1046 switch ( httpReturnCode )
1052 DBG << msg <<
" Login failed (URL: " << url.
asString() <<
")" << std::endl;
1053 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
1067 if (url.
asString().find(
"novell.com") != string::npos)
1068 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1075 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1080 string msg =
"Unable to retrieve HTTP response:";
1081 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1086 case CURLE_FTP_COULDNT_RETR_FILE:
1087 #if CURLVERSION_AT_LEAST(7,16,0) 1088 case CURLE_REMOTE_FILE_NOT_FOUND:
1090 case CURLE_FTP_ACCESS_DENIED:
1091 case CURLE_TFTP_NOTFOUND:
1092 err =
"File not found";
1095 case CURLE_BAD_PASSWORD_ENTERED:
1096 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1097 err =
"Login failed";
1099 case CURLE_COULDNT_RESOLVE_PROXY:
1100 case CURLE_COULDNT_RESOLVE_HOST:
1101 case CURLE_COULDNT_CONNECT:
1102 case CURLE_FTP_CANT_GET_HOST:
1103 err =
"Connection failed";
1105 case CURLE_WRITE_ERROR:
1106 err =
"Write error";
1108 case CURLE_PARTIAL_FILE:
1109 case CURLE_OPERATION_TIMEDOUT:
1110 timeout_reached =
true;
1112 case CURLE_ABORTED_BY_CALLBACK:
1113 if( timeout_reached )
1115 err =
"Timeout reached";
1123 case CURLE_SSL_PEER_CERTIFICATE:
1172 string urlBuffer( curlUrl.
asString());
1173 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1174 urlBuffer.c_str() );
1186 ret = curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
1188 ret = curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
1191 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1192 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1198 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1202 FILE *file = ::fopen(
"/dev/null",
"w" );
1204 ERR <<
"fopen failed for /dev/null" << endl;
1205 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1206 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1212 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1219 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1223 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1224 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1230 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1237 CURLcode ok = curl_easy_perform(
_curl );
1238 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1243 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1253 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L);
1262 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL);
1287 return ( ok == CURLE_OK );
1293 #if DETECT_DIR_INDEX 1306 bool not_a_file =
false;
1308 CURLcode ret = curl_easy_getinfo(
_curl,
1309 CURLINFO_EFFECTIVE_URL,
1311 if ( ret == CURLE_OK && ptr != NULL)
1317 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1319 DBG <<
"Effective url (" 1321 <<
") seems to provide the index of a directory" 1340 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
1344 string destNew = target.
asString() +
".new.zypp.XXXXXX";
1345 char *buf = ::strdup( destNew.c_str());
1348 ERR <<
"out of memory for temp file name" << endl;
1353 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1357 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1363 FILE *file = ::fdopen( tmp_fd,
"we" );
1367 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1371 DBG <<
"dest: " << dest << endl;
1372 DBG <<
"temp: " << destNew << endl;
1377 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1378 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(target).mtime());
1382 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1383 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1393 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1394 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1398 long httpReturnCode = 0;
1399 CURLcode infoRet = curl_easy_getinfo(
_curl,
1400 CURLINFO_RESPONSE_CODE,
1402 bool modified =
true;
1403 if (infoRet == CURLE_OK)
1406 if ( httpReturnCode == 304
1409 DBG <<
" Not modified.";
1416 WAR <<
"Could not get the reponse code." << endl;
1419 if (modified || infoRet != CURLE_OK)
1424 ERR <<
"Failed to chmod file " << destNew << endl;
1426 if (::fclose( file ))
1428 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1432 if (
rename( destNew, dest ) != 0 ) {
1433 ERR <<
"Rename failed" << endl;
1476 string urlBuffer( curlUrl.
asString());
1477 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1478 urlBuffer.c_str() );
1483 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1491 report->start(url, dest);
1492 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1493 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1496 ret = curl_easy_perform(
_curl );
1497 #if CURLVERSION_AT_LEAST(7,19,4) 1502 if ( ftell(file) == 0 && ret == 0 )
1504 long httpReturnCode = 33;
1505 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1507 long conditionUnmet = 33;
1508 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1510 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1511 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1512 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1513 ret = curl_easy_perform(
_curl );
1519 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1520 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1526 <<
", temp file size " << ftell(file)
1527 <<
" bytes." << endl;
1541 #if DETECT_DIR_INDEX 1546 #endif // DETECT_DIR_INDEX 1556 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1557 Pathname filename = dirname + it->name;
1560 switch ( it->type ) {
1567 getDir( filename, recurse_r );
1571 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1585 const Pathname & dirname,
bool dots )
const 1593 const Pathname & dirname,
bool dots )
const 1602 ProgressData *pdata =
reinterpret_cast<ProgressData *
>( clientp );
1608 pdata->updateStats( 0.0, dlnow );
1609 return pdata->reportProgress();
1616 ProgressData *pdata =
reinterpret_cast<ProgressData *
>( clientp );
1620 long httpReturnCode = 0;
1621 if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1622 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1624 pdata->updateStats( dltotal, dlnow );
1625 return pdata->reportProgress();
1632 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1633 return pdata ? pdata->curl : 0;
1640 long auth_info = CURLAUTH_NONE;
1643 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1645 if(infoRet == CURLE_OK)
1658 Target_Ptr target = zypp::getZYpp()->getTarget();
1665 if (cmcred && firstTry)
1668 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1683 curlcred->setUsername(cmcred->username());
1692 curlcred->setAuthType(availAuthTypes);
1695 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1697 DBG <<
"callback answer: retry" << endl
1698 <<
"CurlAuthData: " << *curlcred << endl;
1700 if (curlcred->valid())
1702 credentials = curlcred;
1716 DBG <<
"callback answer: cancel" << endl;
1732 if (credentials->authType() == CURLAUTH_NONE)
1733 credentials->setAuthType(availAuthTypes);
1736 if (credentials->authType() != CURLAUTH_NONE)
1740 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1746 credentials->setUrl(
_url);
std::string getScheme() const
Returns the scheme name of the 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'.
const Pathname & path() const
Return current Pathname.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
static ZConfig & instance()
Singleton ctor.
Flag to request encoded string(s).
const char * c_str() const
String representation.
void setPathParams(const std::string ¶ms)
Set the path parameters.
pthread_once_t OnceFlag
The OnceFlag variable type.
void setUsername(const std::string &user, EEncoding eflag=zypp::url::E_DECODED)
Set the username in the URL authority.
unsigned split(const C_Str &line_r, TOutputIterator result_r, const C_Str &sepchars_r=" \)
Split line_r into words.
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.
bool empty() const
Test for an empty path.
#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.
std::string asString() const
Returns a default string representation of the Url object.
std::string escape(const C_Str &str_r, const char sep_r)
Escape desired character c using a backslash.
std::string getQueryParam(const std::string ¶m, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
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'.
const std::string & asString() const
String representation.
int rename(const Pathname &oldpath, const Pathname &newpath)
Like 'rename'.
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Pathname dirname() const
Return all but the last component od this path.
std::list< DirEntry > DirContent
Returned by readdir.
bool isValid() const
Verifies the Url.
std::string numstring(char n, int w=0)
int rmdir(const Pathname &path)
Like 'rmdir'.
Pathname absolutename() const
Return this path, adding a leading '/' if relative.
Base class for Exception.
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.
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
Wrapper class for ::stat/::lstat.
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
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.
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.
const std::string & msg() const
Return the message string provided to the ctor.