33 #include <sys/types.h>
35 #include <sys/mount.h>
40 #define DETECT_DIR_INDEX 0
41 #define CONNECT_TIMEOUT 60
42 #define TRANSFER_TIMEOUT_MAX 60 * 60
44 #define EXPLICITLY_NO_PROXY "_none_"
46 #undef CURLVERSION_AT_LEAST
47 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
50 using namespace zypp::base;
54 inline void globalInitOnce()
57 static bool once __attribute__ ((__unused__)) = ( [] {
58 if ( curl_global_init( CURL_GLOBAL_ALL ) != 0 )
59 WAR <<
"curl global init failed" << endl;
63 int log_curl(CURL *
curl, curl_infotype info,
64 char *ptr,
size_t len,
void *max_lvl)
70 case CURLINFO_TEXT: lvl = 1; pfx =
"*";
break;
71 case CURLINFO_HEADER_IN: lvl = 2; pfx =
"<";
break;
72 case CURLINFO_HEADER_OUT: lvl = 2; pfx =
">";
break;
75 if( lvl > 0 && max_lvl != NULL && lvl <= *((
long *)max_lvl))
77 std::string msg(ptr, len);
78 std::list<std::string> lines;
79 std::list<std::string>::const_iterator line;
81 for(line = lines.begin(); line != lines.end(); ++line)
83 DBG << pfx <<
" " << *line << endl;
89 static size_t log_redirects_curl(
char *ptr,
size_t size,
size_t nmemb,
void *userdata)
93 char * lstart = ptr, * lend = ptr;
95 size_t max = size * nmemb;
99 for (lstart = lend; *lend !=
'\n' && pos < max; ++lend, ++pos);
102 if ( lstart[0] ==
'L'
110 && lstart[8] ==
':' )
112 std::string line { lstart, *(lend-1)==
'\r' ? lend-1 : lend };
113 DBG <<
"redirecting to " << line << endl;
115 *
reinterpret_cast<std::string *
>( userdata ) = line;
141 inline int getZYPP_MEDIA_CURL_IPRESOLVE()
144 if (
const char * envp = getenv(
"ZYPP_MEDIA_CURL_IPRESOLVE" ) )
146 WAR <<
"env set: $ZYPP_MEDIA_CURL_IPRESOLVE='" << envp <<
"'" << endl;
147 if ( strcmp( envp,
"4" ) == 0 ) ret = 4;
148 else if ( strcmp( envp,
"6" ) == 0 ) ret = 6;
156 static int _v = getZYPP_MEDIA_CURL_IPRESOLVE();
167 ProgressData( CURL *_curl, time_t _timeout = 0,
const Url & _url = Url(),
168 ByteCount expectedFileSize_r = 0,
169 callback::SendReport<DownloadProgressReport> *_report =
nullptr )
184 callback::SendReport<DownloadProgressReport> *
report;
201 void updateStats(
double dltotal = 0.0,
double dlnow = 0.0 )
209 if ( dlnow && dlnow !=
_dnlNow )
250 int reportProgress()
const
280 inline void escape(
string & str_r,
281 const char char_r,
const string & escaped_r ) {
283 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
284 str_r.replace( pos, 1, escaped_r );
288 inline string escapedPath(
string path_r ) {
289 escape( path_r,
' ',
"%20" );
293 inline string unEscape(
string text_r ) {
294 char * tmp = curl_unescape( text_r.c_str(), 0 );
311 long num = str::strtonum<long>(param);
335 if( verify.empty() ||
341 else if( verify ==
"no")
348 std::vector<std::string> flags;
349 std::vector<std::string>::const_iterator flag;
350 str::split( verify, std::back_inserter(flags),
",");
351 for(flag = flags.begin(); flag != flags.end(); ++flag)
355 else if( *flag ==
"peer")
364 if( ! ca_path.empty())
366 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
373 if( ! client_cert.empty())
375 if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
381 if( ! client_key.empty())
383 if( !PathInfo(client_key).isFile() || !client_key.absolute())
390 if ( ! param.empty() )
402 if ( ! proxyport.empty() ) {
403 param +=
":" + proxyport;
411 if ( ! param.empty() )
423 CurlAuthData::auth_type_str2long(param);
427 DBG <<
"Rethrowing as MediaUnauthorizedException.";
435 if( !param.empty() && param ==
"no" )
452 s.
setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
465 Pathname MediaCurl::_cookieFile =
"/var/lib/YaST2/cookies";
477 static const std::string
_value(
479 "X-ZYpp-AnonymousId: %s",
480 Target::anonymousUniqueId( Pathname() ).c_str() ) )
482 return _value.c_str();
495 static const std::string
_value(
497 "X-ZYpp-DistributionFlavor: %s",
498 Target::distributionFlavor( Pathname() ).c_str() ) )
500 return _value.c_str();
513 static const std::string
_value(
515 "ZYpp %s (curl %s) %s"
517 , curl_version_info(CURLVERSION_NOW)->version
518 , Target::targetDistribution( Pathname() ).c_str()
521 return _value.c_str();
527 #define SET_OPTION(opt,val) do { \
528 ret = curl_easy_setopt ( _curl, opt, val ); \
530 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
534 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
535 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
536 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
538 MediaCurl::MediaCurl(
const Url & url_r,
539 const Pathname & attach_point_hint_r )
549 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
557 char *atemp = ::strdup( apath.asString().c_str());
559 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
560 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
562 WAR <<
"attach point " << ainfo.path()
563 <<
" is not useable for " << url_r.
getScheme() << endl;
566 else if( atest != NULL)
614 curl_version_info_data *curl_info = NULL;
615 curl_info = curl_version_info(CURLVERSION_NOW);
617 if (curl_info->protocols)
619 const char *
const *proto;
622 for(proto=curl_info->protocols; !found && *proto; ++proto)
624 if( scheme == std::string((
const char *)*proto))
629 std::string msg(
"Unsupported protocol '");
640 char *ptr = getenv(
"ZYPP_MEDIA_CURL_DEBUG");
641 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
644 curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
645 curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
646 curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &
_curlDebug);
650 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
652 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER,
_curlError );
699 case 4:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
break;
700 case 6:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
break;
724 #if CURLVERSION_AT_LEAST(7,19,4)
726 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
728 #if CURLVERSION_AT_LEAST(7,60,0) // SLE15+
729 SET_OPTION( CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS );
747 #ifdef CURLSSLOPT_ALLOW_BEAST
749 ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
758 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
774 if (use_auth.empty())
775 use_auth =
"digest,basic";
777 if( auth != CURLAUTH_NONE)
779 DBG <<
"Enabling HTTP authentication methods: " << use_auth
780 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
789 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
799 if ( proxyuserpwd.empty() )
804 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
808 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
816 if ( ! proxyuserpwd.empty() )
818 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
821 #if CURLVERSION_AT_LEAST(7,19,4)
826 DBG <<
"Proxy: explicitly NOPROXY" << endl;
832 DBG <<
"Proxy: not explicitly set" << endl;
833 DBG <<
"Proxy: libcurl may look into the environment" << endl;
844 #if CURLVERSION_AT_LEAST(7,15,5)
856 MIL <<
"No cookies requested" << endl;
861 #if CURLVERSION_AT_LEAST(7,18,0)
866 for ( TransferSettings::Headers::const_iterator it = vol_settings.
headersBegin();
898 _curl = curl_easy_init();
935 curl_easy_cleanup( _curl );
1051 bool timeout_reached)
const
1056 if (filename.empty())
1065 case CURLE_UNSUPPORTED_PROTOCOL:
1066 err =
" Unsupported protocol";
1069 err +=
" or redirect (";
1074 case CURLE_URL_MALFORMAT:
1075 case CURLE_URL_MALFORMAT_USER:
1078 case CURLE_LOGIN_DENIED:
1082 case CURLE_HTTP_RETURNED_ERROR:
1084 long httpReturnCode = 0;
1085 CURLcode infoRet = curl_easy_getinfo( _curl,
1086 CURLINFO_RESPONSE_CODE,
1088 if ( infoRet == CURLE_OK )
1090 string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
1091 switch ( httpReturnCode )
1097 DBG << msg <<
" Login failed (URL: " << url.
asString() <<
")" << std::endl;
1098 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
1113 if ( url.
getHost().find(
".suse.com") != string::npos )
1114 msg403 =
_(
"Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
1115 else if (url.
asString().find(
"novell.com") != string::npos)
1116 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1124 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1129 string msg =
"Unable to retrieve HTTP response:";
1130 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1135 case CURLE_FTP_COULDNT_RETR_FILE:
1136 #if CURLVERSION_AT_LEAST(7,16,0)
1137 case CURLE_REMOTE_FILE_NOT_FOUND:
1139 case CURLE_FTP_ACCESS_DENIED:
1140 case CURLE_TFTP_NOTFOUND:
1141 err =
"File not found";
1144 case CURLE_BAD_PASSWORD_ENTERED:
1145 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1146 err =
"Login failed";
1148 case CURLE_COULDNT_RESOLVE_PROXY:
1149 case CURLE_COULDNT_RESOLVE_HOST:
1150 case CURLE_COULDNT_CONNECT:
1151 case CURLE_FTP_CANT_GET_HOST:
1152 err =
"Connection failed";
1154 case CURLE_WRITE_ERROR:
1155 err =
"Write error";
1157 case CURLE_PARTIAL_FILE:
1158 case CURLE_OPERATION_TIMEDOUT:
1159 timeout_reached =
true;
1161 case CURLE_ABORTED_BY_CALLBACK:
1162 if( timeout_reached )
1164 err =
"Timeout reached";
1172 case CURLE_SSL_PEER_CERTIFICATE:
1192 DBG << filename.asString() << endl;
1218 string urlBuffer( curlUrl.
asString());
1219 CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1220 urlBuffer.c_str() );
1232 ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1234 ret = curl_easy_setopt( _curl, CURLOPT_RANGE,
"0-1" );
1237 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1238 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1244 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1248 AutoFILE file { ::fopen(
"/dev/null",
"w" ) };
1250 ERR <<
"fopen failed for /dev/null" << endl;
1251 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1252 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1258 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1265 ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, (*file) );
1268 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1269 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1275 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1282 CURLcode ok = curl_easy_perform( _curl );
1283 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1288 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1298 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1307 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1328 return ( ok == CURLE_OK );
1334 #if DETECT_DIR_INDEX
1347 bool not_a_file =
false;
1349 CURLcode ret = curl_easy_getinfo( _curl,
1350 CURLINFO_EFFECTIVE_URL,
1352 if ( ret == CURLE_OK && ptr != NULL)
1357 std::string path( eurl.getPathName());
1358 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1360 DBG <<
"Effective url ("
1362 <<
") seems to provide the index of a directory"
1378 Pathname dest = target.absolutename();
1381 DBG <<
"assert_dir " << dest.dirname() <<
" failed" << endl;
1385 ManagedFile destNew { target.extend(
".new.zypp.XXXXXX" ) };
1391 ERR <<
"out of memory for temp file name" << endl;
1395 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1398 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1403 file = ::fdopen( tmp_fd,
"we" );
1406 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1409 tmp_fd.resetDispose();
1412 DBG <<
"dest: " << dest << endl;
1413 DBG <<
"temp: " << destNew << endl;
1418 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1419 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (
long)PathInfo(target).mtime());
1423 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1424 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1432 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1433 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1437 long httpReturnCode = 0;
1438 CURLcode infoRet = curl_easy_getinfo(_curl,
1439 CURLINFO_RESPONSE_CODE,
1441 bool modified =
true;
1442 if (infoRet == CURLE_OK)
1445 if ( httpReturnCode == 304
1448 DBG <<
" Not modified.";
1455 WAR <<
"Could not get the reponse code." << endl;
1458 if (modified || infoRet != CURLE_OK)
1463 ERR <<
"Failed to chmod file " << destNew << endl;
1467 if ( ::fclose( file ) )
1469 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1474 if (
rename( destNew, dest ) != 0 ) {
1475 ERR <<
"Rename failed" << endl;
1478 destNew.resetDispose();
1481 DBG <<
"done: " << PathInfo(dest) << endl;
1488 DBG << filename.asString() << 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 );
1529 report->start(url, dest);
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;
1572 if ( progressData.fileSizeExceeded )
1584 #if DETECT_DIR_INDEX
1589 #endif // DETECT_DIR_INDEX
1599 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1600 Pathname filename = dirname + it->name;
1603 switch ( it->type ) {
1610 getDir( filename, recurse_r );
1614 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1628 const Pathname & dirname,
bool dots )
const
1636 const Pathname & dirname,
bool dots )
const
1645 ProgressData *pdata =
reinterpret_cast<ProgressData *
>( clientp );
1651 pdata->updateStats( 0.0, dlnow );
1652 return pdata->reportProgress();
1659 ProgressData *pdata =
reinterpret_cast<ProgressData *
>( clientp );
1663 long httpReturnCode = 0;
1664 if ( curl_easy_getinfo( pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1665 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1667 pdata->updateStats( dltotal, dlnow );
1668 return pdata->reportProgress();
1675 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1676 return pdata ? pdata->curl : 0;
1683 long auth_info = CURLAUTH_NONE;
1686 curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1688 if(infoRet == CURLE_OK)
1702 ProgressData *data =
reinterpret_cast<ProgressData *
>(clientp);
1704 data->_expectedFileSize = expectedFileSize;
1719 if (cmcred && firstTry)
1722 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1737 curlcred->setUsername(cmcred->username());
1746 curlcred->setAuthType(availAuthTypes);
1749 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1751 DBG <<
"callback answer: retry" << endl
1752 <<
"CurlAuthData: " << *curlcred << endl;
1754 if (curlcred->valid())
1756 credentials = curlcred;
1770 DBG <<
"callback answer: cancel" << endl;
1786 if (credentials->authType() == CURLAUTH_NONE)
1787 credentials->setAuthType(availAuthTypes);
1790 if (credentials->authType() != CURLAUTH_NONE)
1794 ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1800 credentials->setUrl(
_url);