34 #include <sys/types.h>
36 #include <sys/mount.h>
40 #include <boost/format.hpp>
42 #define DETECT_DIR_INDEX 0
43 #define CONNECT_TIMEOUT 60
44 #define TRANSFER_TIMEOUT_MAX 60 * 60
46 #define EXPLICITLY_NO_PROXY "_none_"
48 #undef CURLVERSION_AT_LEAST
49 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
59 extern "C" void _do_free_once()
61 curl_global_cleanup();
64 extern "C" void globalFreeOnce()
69 extern "C" void _do_init_once()
71 CURLcode ret = curl_global_init( CURL_GLOBAL_ALL );
74 WAR <<
"curl global init failed" << endl;
87 inline void globalInitOnce()
92 int log_curl(CURL *
curl, curl_infotype info,
93 char *ptr,
size_t len,
void *max_lvl)
99 case CURLINFO_TEXT: lvl = 1; pfx =
"*";
break;
100 case CURLINFO_HEADER_IN: lvl = 2; pfx =
"<";
break;
101 case CURLINFO_HEADER_OUT: lvl = 2; pfx =
">";
break;
104 if( lvl > 0 && max_lvl != NULL && lvl <= *((
long *)max_lvl))
106 std::string msg(ptr, len);
107 std::list<std::string> lines;
108 std::list<std::string>::const_iterator line;
110 for(line = lines.begin(); line != lines.end(); ++line)
112 DBG << pfx <<
" " << *line << endl;
120 void *ptr,
size_t size,
size_t nmemb,
void *stream)
124 char * lstart = (
char *)ptr, * lend = (
char *)ptr;
126 size_t max = size * nmemb;
127 while (pos + 1 < max)
130 for (lstart = lend; *lend !=
'\n' && pos < max; ++lend, ++pos);
133 string line(lstart, lend);
134 if (line.find(
"Location") != string::npos)
136 DBG <<
"redirecting to " << line << endl;
161 callback::SendReport<DownloadProgressReport> *_report=NULL)
178 callback::SendReport<DownloadProgressReport> *
report;
198 inline void escape(
string & str_r,
199 const char char_r,
const string & escaped_r ) {
201 pos != string::npos; pos = str_r.find( char_r, pos ) ) {
202 str_r.replace( pos, 1, escaped_r );
206 inline string escapedPath(
string path_r ) {
207 escape( path_r,
' ',
"%20" );
211 inline string unEscape(
string text_r ) {
212 char * tmp = curl_unescape( text_r.c_str(), 0 );
229 long num = str::strtonum<long>(param);
253 if( verify.empty() ||
259 else if( verify ==
"no")
266 std::vector<std::string> flags;
267 std::vector<std::string>::const_iterator flag;
268 str::split( verify, std::back_inserter(flags),
",");
269 for(flag = flags.begin(); flag != flags.end(); ++flag)
273 else if( *flag ==
"peer")
282 if( ! ca_path.empty())
284 if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
291 if( ! client_cert.empty())
293 if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
300 if ( ! param.empty() )
312 if ( ! proxyport.empty() ) {
313 param +=
":" + proxyport;
321 if ( ! param.empty() )
333 CurlAuthData::auth_type_str2long(param);
337 DBG <<
"Rethrowing as MediaUnauthorizedException.";
345 if( !param.empty() && param ==
"no" )
362 s.
setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
375 Pathname MediaCurl::_cookieFile =
"/var/lib/YaST2/cookies";
387 static const std::string
_value(
389 "X-ZYpp-AnonymousId: %s",
390 Target::anonymousUniqueId( Pathname() ).c_str() ) )
392 return _value.c_str();
405 static const std::string
_value(
407 "X-ZYpp-DistributionFlavor: %s",
408 Target::distributionFlavor( Pathname() ).c_str() ) )
410 return _value.c_str();
423 static const std::string
_value(
425 "ZYpp %s (curl %s) %s"
427 , curl_version_info(CURLVERSION_NOW)->version
428 , Target::targetDistribution( Pathname() ).c_str()
431 return _value.c_str();
437 #define SET_OPTION(opt,val) do { \
438 ret = curl_easy_setopt ( _curl, opt, val ); \
440 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
444 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
445 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
446 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
448 MediaCurl::MediaCurl(
const Url & url_r,
449 const Pathname & attach_point_hint_r )
459 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
467 char *atemp = ::strdup( apath.asString().c_str());
469 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
470 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
472 WAR <<
"attach point " << ainfo.path()
473 <<
" is not useable for " << url_r.
getScheme() << endl;
476 else if( atest != NULL)
524 curl_version_info_data *curl_info = NULL;
525 curl_info = curl_version_info(CURLVERSION_NOW);
527 if (curl_info->protocols)
529 const char *
const *proto;
532 for(proto=curl_info->protocols; !found && *proto; ++proto)
534 if( scheme == std::string((
const char *)*proto))
539 std::string msg(
"Unsupported protocol '");
550 char *ptr = getenv(
"ZYPP_MEDIA_CURL_DEBUG");
551 _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
554 curl_easy_setopt(
_curl, CURLOPT_VERBOSE, 1L);
555 curl_easy_setopt(
_curl, CURLOPT_DEBUGFUNCTION, log_curl);
560 curl_easy_setopt(
_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
561 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
620 #if CURLVERSION_AT_LEAST(7,19,4)
622 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
636 #ifdef CURLSSLOPT_ALLOW_BEAST
638 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
647 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
663 if (use_auth.empty())
664 use_auth =
"digest,basic";
666 if( auth != CURLAUTH_NONE)
668 DBG <<
"Enabling HTTP authentication methods: " << use_auth
669 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
678 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
688 if ( proxyuserpwd.empty() )
693 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
697 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
705 if ( ! proxyuserpwd.empty() )
707 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
710 #if CURLVERSION_AT_LEAST(7,19,4)
715 DBG <<
"Proxy: explicitly NOPROXY" << endl;
721 DBG <<
"Proxy: not explicitly set" << endl;
722 DBG <<
"Proxy: libcurl may look into the environment" << endl;
733 #if CURLVERSION_AT_LEAST(7,15,5)
745 MIL <<
"No cookies requested" << endl;
750 #if CURLVERSION_AT_LEAST(7,18,0)
755 for ( TransferSettings::Headers::const_iterator it = vol_settings.
headersBegin();
785 if( mountpoint.empty())
792 _curl = curl_easy_init();
829 curl_easy_cleanup(
_curl );
940 bool timeout_reached )
const
945 if (filename.empty())
954 case CURLE_UNSUPPORTED_PROTOCOL:
955 case CURLE_URL_MALFORMAT:
956 case CURLE_URL_MALFORMAT_USER:
959 case CURLE_LOGIN_DENIED:
963 case CURLE_HTTP_RETURNED_ERROR:
965 long httpReturnCode = 0;
966 CURLcode infoRet = curl_easy_getinfo(
_curl,
967 CURLINFO_RESPONSE_CODE,
969 if ( infoRet == CURLE_OK )
971 string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
972 switch ( httpReturnCode )
978 DBG << msg <<
" Login failed (URL: " << url.
asString() <<
")" << std::endl;
979 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
993 if (url.
asString().find(
"novell.com") != string::npos)
994 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1001 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1006 string msg =
"Unable to retrieve HTTP response:";
1007 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1012 case CURLE_FTP_COULDNT_RETR_FILE:
1013 #if CURLVERSION_AT_LEAST(7,16,0)
1014 case CURLE_REMOTE_FILE_NOT_FOUND:
1016 case CURLE_FTP_ACCESS_DENIED:
1017 case CURLE_TFTP_NOTFOUND:
1018 err =
"File not found";
1021 case CURLE_BAD_PASSWORD_ENTERED:
1022 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1023 err =
"Login failed";
1025 case CURLE_COULDNT_RESOLVE_PROXY:
1026 case CURLE_COULDNT_RESOLVE_HOST:
1027 case CURLE_COULDNT_CONNECT:
1028 case CURLE_FTP_CANT_GET_HOST:
1029 err =
"Connection failed";
1031 case CURLE_WRITE_ERROR:
1032 err =
"Write error";
1034 case CURLE_PARTIAL_FILE:
1035 case CURLE_OPERATION_TIMEDOUT:
1036 timeout_reached =
true;
1038 case CURLE_ABORTED_BY_CALLBACK:
1039 if( timeout_reached )
1041 err =
"Timeout reached";
1049 case CURLE_SSL_PEER_CERTIFICATE:
1051 err =
"Unrecognized error";
1073 DBG << filename.asString() << endl;
1098 string urlBuffer( curlUrl.
asString());
1099 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1100 urlBuffer.c_str() );
1112 ret = curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
1114 ret = curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
1117 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1118 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1124 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1128 FILE *file = ::fopen(
"/dev/null",
"w" );
1130 ERR <<
"fopen failed for /dev/null" << endl;
1131 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1132 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1138 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1145 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1149 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1150 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1156 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1163 CURLcode ok = curl_easy_perform(
_curl );
1164 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1169 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1179 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L);
1188 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL);
1213 return ( ok == CURLE_OK );
1219 #if DETECT_DIR_INDEX
1232 bool not_a_file =
false;
1234 CURLcode ret = curl_easy_getinfo(
_curl,
1235 CURLINFO_EFFECTIVE_URL,
1237 if ( ret == CURLE_OK && ptr != NULL)
1242 std::string path( eurl.getPathName());
1243 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1245 DBG <<
"Effective url ("
1247 <<
") seems to provide the index of a directory"
1263 Pathname dest = target.absolutename();
1266 DBG <<
"assert_dir " << dest.dirname() <<
" failed" << endl;
1270 string destNew = target.asString() +
".new.zypp.XXXXXX";
1271 char *buf = ::strdup( destNew.c_str());
1274 ERR <<
"out of memory for temp file name" << endl;
1279 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1283 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1289 FILE *file = ::fdopen( tmp_fd,
"we" );
1293 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1297 DBG <<
"dest: " << dest << endl;
1298 DBG <<
"temp: " << destNew << endl;
1303 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1304 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)PathInfo(target).mtime());
1308 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1309 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1319 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1320 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1324 long httpReturnCode = 0;
1325 CURLcode infoRet = curl_easy_getinfo(
_curl,
1326 CURLINFO_RESPONSE_CODE,
1328 bool modified =
true;
1329 if (infoRet == CURLE_OK)
1332 if ( httpReturnCode == 304
1335 DBG <<
" Not modified.";
1342 WAR <<
"Could not get the reponse code." << endl;
1345 if (modified || infoRet != CURLE_OK)
1350 ERR <<
"Failed to chmod file " << destNew << endl;
1352 if (::fclose( file ))
1354 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1358 if (
rename( destNew, dest ) != 0 ) {
1359 ERR <<
"Rename failed" << endl;
1370 DBG <<
"done: " << PathInfo(dest) << endl;
1377 DBG << filename.asString() << endl;
1402 string urlBuffer( curlUrl.
asString());
1403 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1404 urlBuffer.c_str() );
1409 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1417 report->start(url, dest);
1418 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1419 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1422 ret = curl_easy_perform(
_curl );
1423 #if CURLVERSION_AT_LEAST(7,19,4)
1428 if ( ftell(file) == 0 && ret == 0 )
1430 long httpReturnCode = 33;
1431 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1433 long conditionUnmet = 33;
1434 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1436 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1437 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1438 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1439 ret = curl_easy_perform(
_curl );
1445 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1446 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1452 <<
", temp file size " << ftell(file)
1453 <<
" bytes." << endl;
1467 #if DETECT_DIR_INDEX
1472 #endif // DETECT_DIR_INDEX
1482 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1483 Pathname filename = dirname + it->name;
1486 switch ( it->type ) {
1493 getDir( filename, recurse_r );
1497 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1511 const Pathname & dirname,
bool dots )
const
1519 const Pathname & dirname,
bool dots )
const
1527 double dltotal,
double dlnow,
1528 double ultotal,
double ulnow)
1530 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1534 long httpReturnCode = 0;
1535 if (curl_easy_getinfo(pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode) != CURLE_OK || httpReturnCode == 0)
1538 time_t now = time(NULL);
1543 if( pdata->ltime <= 0 || pdata->ltime > now)
1551 if (dlnow > 0 || ulnow > 0)
1553 dif = (now - pdata->ltime);
1554 dif = dif > 0 ? dif : 0;
1565 if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1566 pdata->drate_avg = (dlnow / pdata->secs);
1570 pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1571 pdata->dload_period = dlnow;
1578 if (!(*(pdata->report))->progress(
int( dltotal ? dlnow * 100 / dltotal : 0 ),
1581 pdata->drate_period))
1588 if( pdata->timeout > 0)
1592 bool progress =
false;
1595 if( dlnow != pdata->dload)
1598 pdata->dload = dlnow;
1602 if( ulnow != pdata->uload)
1605 pdata->uload = ulnow;
1609 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1611 pdata->reached =
true;
1622 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1623 return pdata ? pdata->curl : 0;
1630 long auth_info = CURLAUTH_NONE;
1633 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1635 if(infoRet == CURLE_OK)
1648 Target_Ptr target = zypp::getZYpp()->getTarget();
1655 if (cmcred && firstTry)
1658 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1673 curlcred->setUsername(cmcred->username());
1678 string prompt_msg = boost::str(boost::format(
1684 curlcred->setAuthType(availAuthTypes);
1687 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1689 DBG <<
"callback answer: retry" << endl
1690 <<
"CurlAuthData: " << *curlcred << endl;
1692 if (curlcred->valid())
1694 credentials = curlcred;
1708 DBG <<
"callback answer: cancel" << endl;
1724 if (credentials->authType() == CURLAUTH_NONE)
1725 credentials->setAuthType(availAuthTypes);
1728 if (credentials->authType() != CURLAUTH_NONE)
1732 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1738 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).
unsigned split(const C_Str &line_r, _OutputIterator result_r, const C_Str &sepchars_r=" \t")
Split line_r into words.
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.
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.
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.