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)
51 using namespace zypp::base;
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 callback::SendReport<DownloadProgressReport> *_report=NULL)
177 callback::SendReport<DownloadProgressReport> *
report;
197 inline void escape(
string & str_r,
198 const char char_r,
const string & escaped_r ) {
200 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
201 str_r.replace( pos, 1, escaped_r );
205 inline string escapedPath(
string path_r ) {
206 escape( path_r,
' ',
"%20" );
210 inline string unEscape(
string text_r ) {
211 char * tmp = curl_unescape( text_r.c_str(), 0 );
228 long num = str::strtonum<long>(param);
252 if( verify.empty() ||
258 else if( verify ==
"no")
265 std::vector<std::string> flags;
266 std::vector<std::string>::const_iterator flag;
267 str::split( verify, std::back_inserter(flags),
",");
268 for(flag = flags.begin(); flag != flags.end(); ++flag)
272 else if( *flag ==
"peer")
281 if( ! ca_path.empty())
283 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
290 if( ! client_cert.empty())
292 if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
298 if( ! client_key.empty())
300 if( !PathInfo(client_key).isFile() || !client_key.absolute())
307 if ( ! param.empty() )
319 if ( ! proxyport.empty() ) {
320 param +=
":" + proxyport;
328 if ( ! param.empty() )
340 CurlAuthData::auth_type_str2long(param);
344 DBG <<
"Rethrowing as MediaUnauthorizedException.";
352 if( !param.empty() && param ==
"no" )
369 s.
setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
382 Pathname MediaCurl::_cookieFile =
"/var/lib/YaST2/cookies";
394 static const std::string
_value(
396 "X-ZYpp-AnonymousId: %s",
397 Target::anonymousUniqueId( Pathname() ).c_str() ) )
399 return _value.c_str();
412 static const std::string
_value(
414 "X-ZYpp-DistributionFlavor: %s",
415 Target::distributionFlavor( Pathname() ).c_str() ) )
417 return _value.c_str();
430 static const std::string
_value(
432 "ZYpp %s (curl %s) %s"
434 , curl_version_info(CURLVERSION_NOW)->version
435 , Target::targetDistribution( Pathname() ).c_str()
438 return _value.c_str();
444 #define SET_OPTION(opt,val) do { \
445 ret = curl_easy_setopt ( _curl, opt, val ); \
447 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
451 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
452 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
453 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
455 MediaCurl::MediaCurl(
const Url & url_r,
456 const Pathname & attach_point_hint_r )
466 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
474 char *atemp = ::strdup( apath.asString().c_str());
476 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
477 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
479 WAR <<
"attach point " << ainfo.path()
480 <<
" is not useable for " << url_r.
getScheme() << endl;
483 else if( atest != NULL)
531 curl_version_info_data *curl_info = NULL;
532 curl_info = curl_version_info(CURLVERSION_NOW);
534 if (curl_info->protocols)
536 const char *
const *proto;
539 for(proto=curl_info->protocols; !found && *proto; ++proto)
541 if( scheme == std::string((
const char *)*proto))
546 std::string msg(
"Unsupported protocol '");
557 char *ptr = getenv(
"ZYPP_MEDIA_CURL_DEBUG");
558 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
561 curl_easy_setopt(
_curl, CURLOPT_VERBOSE, 1L);
562 curl_easy_setopt(
_curl, CURLOPT_DEBUGFUNCTION, log_curl);
567 curl_easy_setopt(
_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
568 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
627 #if CURLVERSION_AT_LEAST(7,19,4)
629 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
647 #ifdef CURLSSLOPT_ALLOW_BEAST
649 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
658 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
674 if (use_auth.empty())
675 use_auth =
"digest,basic";
677 if( auth != CURLAUTH_NONE)
679 DBG <<
"Enabling HTTP authentication methods: " << use_auth
680 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
689 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
699 if ( proxyuserpwd.empty() )
704 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
708 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
716 if ( ! proxyuserpwd.empty() )
718 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
721 #if CURLVERSION_AT_LEAST(7,19,4)
726 DBG <<
"Proxy: explicitly NOPROXY" << endl;
732 DBG <<
"Proxy: not explicitly set" << endl;
733 DBG <<
"Proxy: libcurl may look into the environment" << endl;
744 #if CURLVERSION_AT_LEAST(7,15,5)
756 MIL <<
"No cookies requested" << endl;
761 #if CURLVERSION_AT_LEAST(7,18,0)
766 for ( TransferSettings::Headers::const_iterator it = vol_settings.
headersBegin();
796 if( mountpoint.empty())
803 _curl = curl_easy_init();
840 curl_easy_cleanup(
_curl );
951 bool timeout_reached )
const
956 if (filename.empty())
965 case CURLE_UNSUPPORTED_PROTOCOL:
966 case CURLE_URL_MALFORMAT:
967 case CURLE_URL_MALFORMAT_USER:
970 case CURLE_LOGIN_DENIED:
974 case CURLE_HTTP_RETURNED_ERROR:
976 long httpReturnCode = 0;
977 CURLcode infoRet = curl_easy_getinfo(
_curl,
978 CURLINFO_RESPONSE_CODE,
980 if ( infoRet == CURLE_OK )
982 string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
983 switch ( httpReturnCode )
989 DBG << msg <<
" Login failed (URL: " << url.
asString() <<
")" << std::endl;
990 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
1004 if (url.
asString().find(
"novell.com") != string::npos)
1005 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1012 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1017 string msg =
"Unable to retrieve HTTP response:";
1018 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1023 case CURLE_FTP_COULDNT_RETR_FILE:
1024 #if CURLVERSION_AT_LEAST(7,16,0)
1025 case CURLE_REMOTE_FILE_NOT_FOUND:
1027 case CURLE_FTP_ACCESS_DENIED:
1028 case CURLE_TFTP_NOTFOUND:
1029 err =
"File not found";
1032 case CURLE_BAD_PASSWORD_ENTERED:
1033 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1034 err =
"Login failed";
1036 case CURLE_COULDNT_RESOLVE_PROXY:
1037 case CURLE_COULDNT_RESOLVE_HOST:
1038 case CURLE_COULDNT_CONNECT:
1039 case CURLE_FTP_CANT_GET_HOST:
1040 err =
"Connection failed";
1042 case CURLE_WRITE_ERROR:
1043 err =
"Write error";
1045 case CURLE_PARTIAL_FILE:
1046 case CURLE_OPERATION_TIMEDOUT:
1047 timeout_reached =
true;
1049 case CURLE_ABORTED_BY_CALLBACK:
1050 if( timeout_reached )
1052 err =
"Timeout reached";
1060 case CURLE_SSL_PEER_CERTIFICATE:
1062 err =
"Unrecognized error";
1084 DBG << filename.asString() << endl;
1109 string urlBuffer( curlUrl.
asString());
1110 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1111 urlBuffer.c_str() );
1123 ret = curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
1125 ret = curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
1128 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1129 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1135 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1139 FILE *file = ::fopen(
"/dev/null",
"w" );
1141 ERR <<
"fopen failed for /dev/null" << endl;
1142 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1143 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1149 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1156 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1160 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1161 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1167 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1174 CURLcode ok = curl_easy_perform(
_curl );
1175 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1180 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1190 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L);
1199 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL);
1224 return ( ok == CURLE_OK );
1230 #if DETECT_DIR_INDEX
1243 bool not_a_file =
false;
1245 CURLcode ret = curl_easy_getinfo(
_curl,
1246 CURLINFO_EFFECTIVE_URL,
1248 if ( ret == CURLE_OK && ptr != NULL)
1253 std::string path( eurl.getPathName());
1254 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1256 DBG <<
"Effective url ("
1258 <<
") seems to provide the index of a directory"
1274 Pathname dest = target.absolutename();
1277 DBG <<
"assert_dir " << dest.dirname() <<
" failed" << endl;
1281 string destNew = target.asString() +
".new.zypp.XXXXXX";
1282 char *buf = ::strdup( destNew.c_str());
1285 ERR <<
"out of memory for temp file name" << endl;
1290 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1294 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1300 FILE *file = ::fdopen( tmp_fd,
"we" );
1304 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1308 DBG <<
"dest: " << dest << endl;
1309 DBG <<
"temp: " << destNew << endl;
1314 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1315 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)PathInfo(target).mtime());
1319 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1320 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1330 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1331 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1335 long httpReturnCode = 0;
1336 CURLcode infoRet = curl_easy_getinfo(
_curl,
1337 CURLINFO_RESPONSE_CODE,
1339 bool modified =
true;
1340 if (infoRet == CURLE_OK)
1343 if ( httpReturnCode == 304
1346 DBG <<
" Not modified.";
1353 WAR <<
"Could not get the reponse code." << endl;
1356 if (modified || infoRet != CURLE_OK)
1361 ERR <<
"Failed to chmod file " << destNew << endl;
1363 if (::fclose( file ))
1365 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1369 if (
rename( destNew, dest ) != 0 ) {
1370 ERR <<
"Rename failed" << endl;
1381 DBG <<
"done: " << PathInfo(dest) << endl;
1388 DBG << filename.asString() << endl;
1413 string urlBuffer( curlUrl.
asString());
1414 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1415 urlBuffer.c_str() );
1420 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1428 report->start(url, dest);
1429 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1430 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1433 ret = curl_easy_perform(
_curl );
1434 #if CURLVERSION_AT_LEAST(7,19,4)
1439 if ( ftell(file) == 0 && ret == 0 )
1441 long httpReturnCode = 33;
1442 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1444 long conditionUnmet = 33;
1445 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1447 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1448 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1449 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1450 ret = curl_easy_perform(
_curl );
1456 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1457 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1463 <<
", temp file size " << ftell(file)
1464 <<
" bytes." << endl;
1478 #if DETECT_DIR_INDEX
1483 #endif // DETECT_DIR_INDEX
1493 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1494 Pathname filename = dirname + it->name;
1497 switch ( it->type ) {
1504 getDir( filename, recurse_r );
1508 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1522 const Pathname & dirname,
bool dots )
const
1530 const Pathname & dirname,
bool dots )
const
1538 double dltotal,
double dlnow,
1539 double ultotal,
double ulnow)
1541 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1545 long httpReturnCode = 0;
1546 if (curl_easy_getinfo(pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode) != CURLE_OK || httpReturnCode == 0)
1549 time_t now = time(NULL);
1554 if( pdata->ltime <= 0 || pdata->ltime > now)
1562 if (dlnow > 0 || ulnow > 0)
1564 dif = (now - pdata->ltime);
1565 dif = dif > 0 ? dif : 0;
1576 if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1577 pdata->drate_avg = (dlnow / pdata->secs);
1581 pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1582 pdata->dload_period = dlnow;
1589 if (!(*(pdata->report))->progress(
int( dltotal ? dlnow * 100 / dltotal : 0 ),
1592 pdata->drate_period))
1599 if( pdata->timeout > 0)
1603 bool progress =
false;
1606 if( dlnow != pdata->dload)
1609 pdata->dload = dlnow;
1613 if( ulnow != pdata->uload)
1616 pdata->uload = ulnow;
1620 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1622 pdata->reached =
true;
1633 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1634 return pdata ? pdata->curl : 0;
1641 long auth_info = CURLAUTH_NONE;
1644 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1646 if(infoRet == CURLE_OK)
1659 Target_Ptr target = zypp::getZYpp()->getTarget();
1666 if (cmcred && firstTry)
1669 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1684 curlcred->setUsername(cmcred->username());
1693 curlcred->setAuthType(availAuthTypes);
1696 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1698 DBG <<
"callback answer: retry" << endl
1699 <<
"CurlAuthData: " << *curlcred << endl;
1701 if (curlcred->valid())
1703 credentials = curlcred;
1717 DBG <<
"callback answer: cancel" << endl;
1733 if (credentials->authType() == CURLAUTH_NONE)
1734 credentials->setAuthType(availAuthTypes);
1737 if (credentials->authType() != CURLAUTH_NONE)
1741 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1747 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.
#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'.
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.
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.