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 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 );
630 #if CURLVERSION_AT_LEAST(7,19,4) 632 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
650 #ifdef CURLSSLOPT_ALLOW_BEAST 652 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
661 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
677 if (use_auth.empty())
678 use_auth =
"digest,basic";
680 if( auth != CURLAUTH_NONE)
682 DBG <<
"Enabling HTTP authentication methods: " << use_auth
683 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
692 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
702 if ( proxyuserpwd.empty() )
707 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
711 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
719 if ( ! proxyuserpwd.empty() )
721 SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
724 #if CURLVERSION_AT_LEAST(7,19,4) 729 DBG <<
"Proxy: explicitly NOPROXY" << endl;
735 DBG <<
"Proxy: not explicitly set" << endl;
736 DBG <<
"Proxy: libcurl may look into the environment" << endl;
747 #if CURLVERSION_AT_LEAST(7,15,5) 759 MIL <<
"No cookies requested" << endl;
764 #if CURLVERSION_AT_LEAST(7,18,0) 769 for ( TransferSettings::Headers::const_iterator it = vol_settings.
headersBegin();
799 if( mountpoint.empty())
806 _curl = curl_easy_init();
843 curl_easy_cleanup(
_curl );
954 bool timeout_reached )
const 959 if (filename.empty())
968 case CURLE_UNSUPPORTED_PROTOCOL:
969 case CURLE_URL_MALFORMAT:
970 case CURLE_URL_MALFORMAT_USER:
973 case CURLE_LOGIN_DENIED:
977 case CURLE_HTTP_RETURNED_ERROR:
979 long httpReturnCode = 0;
980 CURLcode infoRet = curl_easy_getinfo(
_curl,
981 CURLINFO_RESPONSE_CODE,
983 if ( infoRet == CURLE_OK )
985 string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
986 switch ( httpReturnCode )
992 DBG << msg <<
" Login failed (URL: " << url.
asString() <<
")" << std::endl;
993 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
1007 if (url.
asString().find(
"novell.com") != string::npos)
1008 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1015 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1020 string msg =
"Unable to retrieve HTTP response:";
1021 DBG << msg <<
" (URL: " << url.
asString() <<
")" << std::endl;
1026 case CURLE_FTP_COULDNT_RETR_FILE:
1027 #if CURLVERSION_AT_LEAST(7,16,0) 1028 case CURLE_REMOTE_FILE_NOT_FOUND:
1030 case CURLE_FTP_ACCESS_DENIED:
1031 case CURLE_TFTP_NOTFOUND:
1032 err =
"File not found";
1035 case CURLE_BAD_PASSWORD_ENTERED:
1036 case CURLE_FTP_USER_PASSWORD_INCORRECT:
1037 err =
"Login failed";
1039 case CURLE_COULDNT_RESOLVE_PROXY:
1040 case CURLE_COULDNT_RESOLVE_HOST:
1041 case CURLE_COULDNT_CONNECT:
1042 case CURLE_FTP_CANT_GET_HOST:
1043 err =
"Connection failed";
1045 case CURLE_WRITE_ERROR:
1046 err =
"Write error";
1048 case CURLE_PARTIAL_FILE:
1049 case CURLE_OPERATION_TIMEDOUT:
1050 timeout_reached =
true;
1052 case CURLE_ABORTED_BY_CALLBACK:
1053 if( timeout_reached )
1055 err =
"Timeout reached";
1063 case CURLE_SSL_PEER_CERTIFICATE:
1065 err =
"Unrecognized error";
1087 DBG << filename.asString() << endl;
1112 string urlBuffer( curlUrl.
asString());
1113 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1114 urlBuffer.c_str() );
1126 ret = curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
1128 ret = curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
1131 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1132 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1138 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1142 FILE *file = ::fopen(
"/dev/null",
"w" );
1144 ERR <<
"fopen failed for /dev/null" << endl;
1145 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1146 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1152 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1159 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1163 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1164 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1170 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1177 CURLcode ok = curl_easy_perform(
_curl );
1178 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1183 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1193 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L);
1202 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL);
1227 return ( ok == CURLE_OK );
1233 #if DETECT_DIR_INDEX 1246 bool not_a_file =
false;
1248 CURLcode ret = curl_easy_getinfo(
_curl,
1249 CURLINFO_EFFECTIVE_URL,
1251 if ( ret == CURLE_OK && ptr != NULL)
1257 if( !path.empty() && path !=
"/" && *path.rbegin() ==
'/')
1259 DBG <<
"Effective url (" 1261 <<
") seems to provide the index of a directory" 1277 Pathname dest = target.absolutename();
1280 DBG <<
"assert_dir " << dest.dirname() <<
" failed" << endl;
1284 string destNew = target.asString() +
".new.zypp.XXXXXX";
1285 char *buf = ::strdup( destNew.c_str());
1288 ERR <<
"out of memory for temp file name" << endl;
1293 int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1297 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1303 FILE *file = ::fdopen( tmp_fd,
"we" );
1307 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1311 DBG <<
"dest: " << dest << endl;
1312 DBG <<
"temp: " << destNew << endl;
1317 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1318 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)PathInfo(target).mtime());
1322 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1323 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1333 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1334 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1338 long httpReturnCode = 0;
1339 CURLcode infoRet = curl_easy_getinfo(
_curl,
1340 CURLINFO_RESPONSE_CODE,
1342 bool modified =
true;
1343 if (infoRet == CURLE_OK)
1346 if ( httpReturnCode == 304
1349 DBG <<
" Not modified.";
1356 WAR <<
"Could not get the reponse code." << endl;
1359 if (modified || infoRet != CURLE_OK)
1364 ERR <<
"Failed to chmod file " << destNew << endl;
1366 if (::fclose( file ))
1368 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1372 if (
rename( destNew, dest ) != 0 ) {
1373 ERR <<
"Rename failed" << endl;
1384 DBG <<
"done: " << PathInfo(dest) << endl;
1391 DBG << filename.asString() << endl;
1416 string urlBuffer( curlUrl.
asString());
1417 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1418 urlBuffer.c_str() );
1423 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1431 report->start(url, dest);
1432 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1433 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1436 ret = curl_easy_perform(
_curl );
1437 #if CURLVERSION_AT_LEAST(7,19,4) 1442 if ( ftell(file) == 0 && ret == 0 )
1444 long httpReturnCode = 33;
1445 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1447 long conditionUnmet = 33;
1448 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1450 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1451 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1452 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1453 ret = curl_easy_perform(
_curl );
1459 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1460 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1466 <<
", temp file size " << ftell(file)
1467 <<
" bytes." << endl;
1481 #if DETECT_DIR_INDEX 1486 #endif // DETECT_DIR_INDEX 1496 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1497 Pathname filename = dirname + it->name;
1500 switch ( it->type ) {
1507 getDir( filename, recurse_r );
1511 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1525 const Pathname & dirname,
bool dots )
const 1533 const Pathname & dirname,
bool dots )
const 1541 double dltotal,
double dlnow,
1542 double ultotal,
double ulnow)
1544 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1548 long httpReturnCode = 0;
1549 if (curl_easy_getinfo(pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode) != CURLE_OK || httpReturnCode == 0)
1552 time_t now = time(NULL);
1557 if( pdata->ltime <= 0 || pdata->ltime > now)
1565 if (dlnow > 0 || ulnow > 0)
1567 dif = (now - pdata->ltime);
1568 dif = dif > 0 ? dif : 0;
1579 if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1580 pdata->drate_avg = (dlnow / pdata->secs);
1584 pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1585 pdata->dload_period = dlnow;
1592 if (!(*(pdata->report))->progress(
int( dltotal ? dlnow * 100 / dltotal : 0 ),
1595 pdata->drate_period))
1602 if( pdata->timeout > 0)
1606 bool progress =
false;
1609 if( dlnow != pdata->dload)
1612 pdata->dload = dlnow;
1616 if( ulnow != pdata->uload)
1619 pdata->uload = ulnow;
1623 if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1625 pdata->reached =
true;
1636 ProgressData *pdata =
reinterpret_cast<ProgressData *
>(clientp);
1637 return pdata ? pdata->curl : 0;
1644 long auth_info = CURLAUTH_NONE;
1647 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1649 if(infoRet == CURLE_OK)
1662 Target_Ptr target = zypp::getZYpp()->getTarget();
1669 if (cmcred && firstTry)
1672 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1687 curlcred->setUsername(cmcred->username());
1696 curlcred->setAuthType(availAuthTypes);
1699 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1701 DBG <<
"callback answer: retry" << endl
1702 <<
"CurlAuthData: " << *curlcred << endl;
1704 if (curlcred->valid())
1706 credentials = curlcred;
1720 DBG <<
"callback answer: cancel" << endl;
1736 if (credentials->authType() == CURLAUTH_NONE)
1737 credentials->setAuthType(availAuthTypes);
1740 if (credentials->authType() != CURLAUTH_NONE)
1744 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1750 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.
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.