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();
186 ProgressData( CURL *_curl, time_t _timeout = 0,
const Url & _url = Url(),
187 callback::SendReport<DownloadProgressReport> *_report =
nullptr )
199 callback::SendReport<DownloadProgressReport> *
report;
215 void updateStats(
double dltotal = 0.0,
double dlnow = 0.0 )
223 if ( dlnow && dlnow !=
_dnlNow )
261 int reportProgress()
const 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 );
317 std::string param(
url.getQueryParam(
"timeout"));
320 long num = str::strtonum<long>(param);
325 if ( !
url.getUsername().empty() )
328 if (
url.getPassword().size() )
334 if ( (
url.getScheme() ==
"ftp" ||
url.getScheme() ==
"tftp" ) && s.
username().empty() )
338 if (
url.getScheme() ==
"https" )
343 std::string verify(
url.getQueryParam(
"ssl_verify"));
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")
372 Pathname ca_path(
url.getQueryParam(
"ssl_capath") );
373 if( ! ca_path.empty())
381 Pathname client_cert(
url.getQueryParam(
"ssl_clientcert") );
382 if( ! client_cert.empty())
389 Pathname client_key(
url.getQueryParam(
"ssl_clientkey") );
390 if( ! client_key.empty())
398 param =
url.getQueryParam(
"proxy" );
399 if ( ! param.empty() )
410 string proxyport(
url.getQueryParam(
"proxyport" ) );
411 if ( ! proxyport.empty() ) {
412 param +=
":" + proxyport;
419 param =
url.getQueryParam(
"proxyuser" );
420 if ( ! param.empty() )
427 param =
url.getQueryParam(
"auth");
428 if (!param.empty() && (
url.getScheme() ==
"http" ||
url.getScheme() ==
"https"))
432 CurlAuthData::auth_type_str2long(param);
436 DBG <<
"Rethrowing as MediaUnauthorizedException.";
443 param =
url.getQueryParam(
"head_requests");
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() ) )
504 static const std::string
_value(
506 "X-ZYpp-DistributionFlavor: %s",
507 Target::distributionFlavor(
Pathname() ).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()
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());
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 );
1056 bool timeout_reached )
const 1061 if (filename.
empty())
1069 case CURLE_UNSUPPORTED_PROTOCOL:
1070 case CURLE_URL_MALFORMAT:
1071 case CURLE_URL_MALFORMAT_USER:
1074 case CURLE_LOGIN_DENIED:
1078 case CURLE_HTTP_RETURNED_ERROR:
1080 long httpReturnCode = 0;
1081 CURLcode infoRet = curl_easy_getinfo(
_curl,
1082 CURLINFO_RESPONSE_CODE,
1084 if ( infoRet == CURLE_OK )
1086 string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
1087 switch ( httpReturnCode )
1093 DBG << msg <<
" Login failed (URL: " <<
url.
asString() <<
")" << std::endl;
1094 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
1108 if (
url.
asString().find(
"novell.com") != string::npos)
1109 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1122 string msg =
"Unable to retrieve HTTP response:";
1128 case CURLE_FTP_COULDNT_RETR_FILE:
1129 #if CURLVERSION_AT_LEAST(7,16,0) 1130 case CURLE_REMOTE_FILE_NOT_FOUND:
1132 case CURLE_FTP_ACCESS_DENIED:
1133 case CURLE_TFTP_NOTFOUND:
1134 err =
"File not found";
1137 case CURLE_BAD_PASSWORD_ENTERED:
1138 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1139 err =
"Login failed";
1141 case CURLE_COULDNT_RESOLVE_PROXY:
1142 case CURLE_COULDNT_RESOLVE_HOST:
1143 case CURLE_COULDNT_CONNECT:
1144 case CURLE_FTP_CANT_GET_HOST:
1145 err =
"Connection failed";
1147 case CURLE_WRITE_ERROR:
1148 err =
"Write error";
1150 case CURLE_PARTIAL_FILE:
1151 case CURLE_OPERATION_TIMEDOUT:
1152 timeout_reached =
true;
1154 case CURLE_ABORTED_BY_CALLBACK:
1155 if( timeout_reached )
1157 err =
"Timeout reached";
1165 case CURLE_SSL_PEER_CERTIFICATE:
1210 string urlBuffer( curlUrl.
asString());
1211 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1212 urlBuffer.c_str() );
1224 ret = curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
1226 ret = curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
1229 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1230 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1236 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1240 FILE *file = ::fopen(
"/dev/null",
"w" );
1242 ERR <<
"fopen failed for /dev/null" << endl;
1243 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1244 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1250 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1257 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1261 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1262 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1268 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1275 CURLcode ok = curl_easy_perform(
_curl );
1276 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1281 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1291 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L);
1300 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL);
1325 return ( ok == CURLE_OK );
1331 #if DETECT_DIR_INDEX 1344 bool not_a_file =
false;
1346 CURLcode ret = curl_easy_getinfo(
_curl,
1347 CURLINFO_EFFECTIVE_URL,
1349 if ( ret == CURLE_OK && ptr != NULL)
1354 std::string path( eurl.getPathName());
1355 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1357 DBG <<
"Effective url (" 1359 <<
") seems to provide the index of a directory" 1378 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
1382 string destNew = target.
asString() +
".new.zypp.XXXXXX";
1383 char *buf = ::strdup( destNew.c_str());
1386 ERR <<
"out of memory for temp file name" << endl;
1391 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1395 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1401 FILE *file = ::fdopen( tmp_fd,
"we" );
1405 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1409 DBG <<
"dest: " << dest << endl;
1410 DBG <<
"temp: " << destNew << endl;
1415 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1416 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(target).mtime());
1420 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1421 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1431 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1432 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1436 long httpReturnCode = 0;
1437 CURLcode infoRet = curl_easy_getinfo(
_curl,
1438 CURLINFO_RESPONSE_CODE,
1440 bool modified =
true;
1441 if (infoRet == CURLE_OK)
1444 if ( httpReturnCode == 304
1447 DBG <<
" Not modified.";
1454 WAR <<
"Could not get the reponse code." << endl;
1457 if (modified || infoRet != CURLE_OK)
1462 ERR <<
"Failed to chmod file " << destNew << endl;
1464 if (::fclose( file ))
1466 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1470 if (
rename( destNew, dest ) != 0 ) {
1471 ERR <<
"Rename failed" << endl;
1514 string urlBuffer( curlUrl.
asString());
1515 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1516 urlBuffer.c_str() );
1521 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1530 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1531 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1534 ret = curl_easy_perform(
_curl );
1535 #if CURLVERSION_AT_LEAST(7,19,4) 1540 if ( ftell(file) == 0 && ret == 0 )
1542 long httpReturnCode = 33;
1543 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1545 long conditionUnmet = 33;
1546 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1548 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1549 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1550 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1551 ret = curl_easy_perform(
_curl );
1557 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1558 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1564 <<
", temp file size " << ftell(file)
1565 <<
" bytes." << endl;
1579 #if DETECT_DIR_INDEX 1584 #endif // DETECT_DIR_INDEX 1594 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1595 Pathname filename = dirname + it->name;
1598 switch ( it->type ) {
1605 getDir( filename, recurse_r );
1609 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1623 const Pathname & dirname,
bool dots )
const 1631 const Pathname & dirname,
bool dots )
const 1640 ProgressData *pdata =
reinterpret_cast<ProgressData *
>( clientp );
1646 pdata->updateStats( 0.0, dlnow );
1647 return pdata->reportProgress();
1654 ProgressData *pdata =
reinterpret_cast<ProgressData *
>( clientp );
1658 long httpReturnCode = 0;
1659 if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1660 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1662 pdata->updateStats( dltotal, dlnow );
1663 return pdata->reportProgress();
1670 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1671 return pdata ? pdata->curl : 0;
1678 long auth_info = CURLAUTH_NONE;
1681 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1683 if(infoRet == CURLE_OK)
1702 if (cmcred && firstTry)
1705 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1720 curlcred->setUsername(cmcred->username());
1729 curlcred->setAuthType(availAuthTypes);
1732 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1734 DBG <<
"callback answer: retry" << endl
1735 <<
"CurlAuthData: " << *curlcred << endl;
1737 if (curlcred->valid())
1739 credentials = curlcred;
1753 DBG <<
"callback answer: cancel" << endl;
1769 if (credentials->authType() == CURLAUTH_NONE)
1770 credentials->setAuthType(availAuthTypes);
1773 if (credentials->authType() != CURLAUTH_NONE)
1777 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1783 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.
int ZYPP_MEDIA_CURL_IPRESOLVE()
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.
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.