22#include <zypp-core/parser/Sysconfig>
28#include <zypp-curl/ProxyInfo>
29#include <zypp-curl/auth/CurlAuthData>
30#include <zypp-media/auth/CredentialManager>
31#include <zypp-curl/CurlConfig>
55 using TimePoint = std::chrono::steady_clock::time_point;
84 void start(
const Url & file_r, Pathname localfile_r )
override
96 bool progress(
int value_r,
const Url & file_r,
double dbps_avg_r = -1,
double dbps_current_r = -1 )
override
100 if ( not ( value_r || dbps_avg_r || dbps_current_r ) )
106 static constexpr std::chrono::milliseconds maxfequency { 100 };
107 TimePoint now { TimePoint::clock::now() };
109 if ( elapsed < maxfequency )
112 return _oldRec->
progress( value_r, file_r, dbps_avg_r, dbps_current_r );
121 void finish(
const Url & file_r,
Error error_r,
const std::string & reason_r )
override
155 void updateStats( curl_off_t dltotal = 0.0, curl_off_t dlnow = 0.0 );
203 , _timeout( timeout )
204 , _timeoutReached( false )
205 , _fileSizeExceeded ( false )
206 , _expectedFileSize( expectedFileSize_r )
218 if ( dlnow && dlnow !=
_dnlNow )
272 "X-ZYpp-AnonymousId: %s",
286 "X-ZYpp-DistributionFlavor: %s",
300 "ZYpp " LIBZYPP_VERSION_STRING
" (curl %s) %s"
301 , curl_version_info(CURLVERSION_NOW)->version
314 const std::string & err_r,
315 const std::string & msg_r )
336#define SET_OPTION(opt,val) do { \
337 ret = curl_easy_setopt ( _curl, opt, val ); \
339 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
343#define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
344#define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
345#define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
348 const Pathname & attach_point_hint_r )
357 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
365 char *atemp = ::strdup( apath.
asString().c_str());
368 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
370 WAR <<
"attach point " << ainfo.
path()
371 <<
" is not useable for " << url_r.
getScheme() << endl;
374 else if( atest != NULL)
403 curl_version_info_data *curl_info = NULL;
404 curl_info = curl_version_info(CURLVERSION_NOW);
406 if (curl_info->protocols)
408 const char *
const *proto =
nullptr;
411 for(proto=curl_info->protocols; !found && *proto; ++proto)
413 if( scheme == std::string((
const char *)*proto))
418 std::string msg(
"Unsupported protocol '");
432 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
474 case 4:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
break;
475 case 6:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
break;
517#ifdef CURLSSLOPT_ALLOW_BEAST
519 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
528 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
546 if ( cred && cred->valid() ) {
564 if (use_auth.empty())
565 use_auth =
"digest,basic";
567 if( auth != CURLAUTH_NONE)
569 DBG <<
"Enabling HTTP authentication methods: " << use_auth
570 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
579 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
589 if ( proxyuserpwd.empty() )
594 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
598 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
606 if ( ! proxyuserpwd.empty() )
611#if CURLVERSION_AT_LEAST(7,19,4)
616 DBG <<
"Proxy: explicitly NOPROXY" << endl;
622 DBG <<
"Proxy: not explicitly set" << endl;
623 DBG <<
"Proxy: libcurl may look into the environment" << endl;
634#if CURLVERSION_AT_LEAST(7,15,5)
647 if ( !cookieFileParam.empty() &&
str::strToBool( cookieFileParam,
true ) )
650 MIL <<
"No cookies requested" << endl;
655#if CURLVERSION_AT_LEAST(7,18,0)
661 for (
const auto &header : vol_settings.
headers() ) {
687 _curl = curl_easy_init();
725 try { curl_easy_cleanup(
_curl ); }
752 const auto &filename = srcFile.
filename();
760 bool firstAuth =
true;
761 unsigned internalTry = 0;
762 static constexpr unsigned maxInternalTry = 3;
787 if ( internalTry < maxInternalTry ) {
844 bool timeout_reached)
const
849 if (filename.
empty())
858 case CURLE_UNSUPPORTED_PROTOCOL:
859 err =
" Unsupported protocol";
862 err +=
" or redirect (";
867 case CURLE_URL_MALFORMAT:
868 case CURLE_URL_MALFORMAT_USER:
871 case CURLE_LOGIN_DENIED:
875 case CURLE_HTTP_RETURNED_ERROR:
877 long httpReturnCode = 0;
878 CURLcode infoRet = curl_easy_getinfo(
_curl,
879 CURLINFO_RESPONSE_CODE,
881 if ( infoRet == CURLE_OK )
883 std::string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
884 switch ( httpReturnCode )
890 DBG << msg <<
" Login failed (URL: " <<
url.
asString() <<
")" << std::endl;
891 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
906 if (
url.
getHost().find(
".suse.com") != std::string::npos )
907 msg403 =
_(
"Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
908 else if (
url.
asString().find(
"novell.com") != std::string::npos)
909 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
922 std::string msg =
"Unable to retrieve HTTP response:";
928 case CURLE_FTP_COULDNT_RETR_FILE:
929#if CURLVERSION_AT_LEAST(7,16,0)
930 case CURLE_REMOTE_FILE_NOT_FOUND:
932 case CURLE_FTP_ACCESS_DENIED:
933 case CURLE_TFTP_NOTFOUND:
934 err =
"File not found";
937 case CURLE_BAD_PASSWORD_ENTERED:
938 case CURLE_FTP_USER_PASSWORD_INCORRECT:
939 err =
"Login failed";
941 case CURLE_COULDNT_RESOLVE_PROXY:
942 case CURLE_COULDNT_RESOLVE_HOST:
943 case CURLE_COULDNT_CONNECT:
944 case CURLE_FTP_CANT_GET_HOST:
945 err =
"Connection failed";
947 case CURLE_WRITE_ERROR:
950 case CURLE_PARTIAL_FILE:
951 case CURLE_OPERATION_TIMEDOUT:
952 timeout_reached =
true;
954 case CURLE_ABORTED_BY_CALLBACK:
955 if( timeout_reached )
957 err =
"Timeout reached";
1011 std::string urlBuffer( curlUrl.
asString());
1012 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1013 urlBuffer.c_str() );
1025 struct TempSetHeadRequest
1027 TempSetHeadRequest(CURL *curl_r,
bool doHttpHeadRequest_r)
1028 : _curl{curl_r}, _doHttpHeadRequest{doHttpHeadRequest_r} {
1029 if ( _doHttpHeadRequest ) {
1030 curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1032 curl_easy_setopt( _curl, CURLOPT_RANGE,
"0-1" );
1035 TempSetHeadRequest(
const TempSetHeadRequest &) =
delete;
1036 TempSetHeadRequest(TempSetHeadRequest &&) =
delete;
1037 TempSetHeadRequest &operator=(
const TempSetHeadRequest &) =
delete;
1038 TempSetHeadRequest &operator=(TempSetHeadRequest &&) =
delete;
1039 ~TempSetHeadRequest() {
1040 if ( _doHttpHeadRequest ) {
1041 curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1047 curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1049 curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1054 bool _doHttpHeadRequest;
1058 AutoFILE file { ::fopen(
"/dev/null",
"w" ) };
1060 ERR <<
"fopen failed for /dev/null" << endl;
1064 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, (*file) );
1070 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1087 return ( ok == CURLE_OK );
1095 if( assert_dir( dest.
dirname() ) )
1097 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
1107 ERR <<
"out of memory for temp file name" << endl;
1111 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1114 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1119 file = ::fdopen( tmp_fd,
"we" );
1122 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1125 tmp_fd.resetDispose();
1128 DBG <<
"dest: " << dest << endl;
1129 DBG <<
"temp: " << destNew << endl;
1134 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1135 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(target).mtime());
1139 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1140 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1148 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1149 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1153 long httpReturnCode = 0;
1154 CURLcode infoRet = curl_easy_getinfo(
_curl,
1155 CURLINFO_RESPONSE_CODE,
1157 bool modified =
true;
1158 if (infoRet == CURLE_OK)
1161 if ( httpReturnCode == 304
1164 DBG <<
" Not modified.";
1171 WAR <<
"Could not get the response code." << endl;
1174 if (modified || infoRet != CURLE_OK)
1179 ERR <<
"Failed to chmod file " << destNew << endl;
1183 if ( ::fclose( file ) )
1185 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1190 if ( rename( destNew, dest ) != 0 ) {
1191 ERR <<
"Rename failed" << endl;
1194 destNew.resetDispose();
1230 std::string urlBuffer( curlUrl.
asString());
1231 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1232 urlBuffer.c_str() );
1237 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1245 report->start(
url, dest);
1246 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1247 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1251#if CURLVERSION_AT_LEAST(7,19,4)
1256 if ( ftell(file) == 0 && ret == 0 )
1258 long httpReturnCode = 33;
1259 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1261 long conditionUnmet = 33;
1262 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1264 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1265 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1266 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1273 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1274 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1280 <<
", temp file size " << ftell(file)
1281 <<
" bytes." << endl;
1307 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1308 Pathname filename = dirname + it->name;
1311 switch ( it->type ) {
1318 getDir( filename, recurse_r );
1320 res = assert_dir(
localPath( filename ) );
1322 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1336 const Pathname & dirname,
bool dots )
const
1344 const Pathname & dirname,
bool dots )
const
1371 long httpReturnCode = 0;
1372 if ( curl_easy_getinfo( pdata->
curl(), CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1373 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1384 return pdata ? pdata->
curl() : 0;
1391 long auth_info = CURLAUTH_NONE;
1394 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1396 if(infoRet == CURLE_OK)
1426 ,[](
auto &releaseMe ){
if (releaseMe._multi) curl_multi_cleanup(releaseMe._multi); }
1429 if (!cMulti->_multi)
1436 if ( curl_multi_add_handle( cMulti->_multi,
_curl ) != CURLM_OK )
1440 OnScopeExit autoRemove([&](){ curl_multi_remove_handle( cMulti->_multi,
_curl ); });
1444 if (mcode != CURLM_OK)
1447 bool canContinue =
true;
1448 while ( canContinue ) {
1451 std::vector<GPollFD> requestedFds = _curlHelper.
socks;
1460 if (mcode != CURLM_OK)
1464 if (mcode != CURLM_OK)
1468 CURLMsg *msg =
nullptr;
1470 while ((msg = curl_multi_info_read( cMulti->_multi, &nqueue)) != 0) {
1471 if ( msg->msg != CURLMSG_DONE )
continue;
1472 if ( msg->easy_handle !=
_curl )
continue;
1474 return msg->data.result;
1491 if (cmcred && firstTry)
1494 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1509 curlcred->setUsername(cmcred->username());
1518 curlcred->setAuthType(availAuthTypes);
1521 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1523 DBG <<
"callback answer: retry" << endl
1524 <<
"CurlAuthData: " << *curlcred << endl;
1526 if (curlcred->valid())
1528 credentials = curlcred;
1542 DBG <<
"callback answer: cancel" << endl;
1558 if (credentials->authType() == CURLAUTH_NONE)
1559 credentials->setAuthType(availAuthTypes);
1562 if (credentials->authType() != CURLAUTH_NONE)
1566 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1572 credentials->setUrl(
_url);
void resetDispose()
Set no dispose function.
Store and operate with byte count.
Base class for Exception.
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
void addHistory(const std::string &msg_r)
Add some message text to the history.
const char * c_str() const
ProgressData()
Ctor no range [0,0](0).
std::string distributionFlavor() const
This is flavor attribute of the installed base product but does not require the target to be loaded a...
std::string anonymousUniqueId() const
anonymous unique id
std::string targetDistribution() const
This is register.target attribute of the installed base product.
std::string getScheme() const
Returns the scheme name of the URL.
std::string asString() const
Returns a default string representation of the Url object.
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.
std::string getQueryParam(const std::string ¶m, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
bool isValid() const
Verifies the Url.
static ZConfig & instance()
Singleton ctor.
Typesafe passing of user data via callbacks.
Wrapper class for stat/lstat.
const Pathname & path() const
Return current Pathname.
Pathname extend(const std::string &r) const
Append string r to the last component of the path.
Pathname dirname() const
Return all but the last component od this path.
const char * c_str() const
String representation.
const std::string & asString() const
String representation.
bool empty() const
Test for an empty path.
Pathname absolutename() const
Return this path, adding a leading '/' if relative.
#define EXPLICITLY_NO_PROXY
void fillSettingsFromUrl(const Url &url, media::TransferSettings &s)
Fills the settings structure using options passed on the url for example ?timeout=x&proxy=foo.
size_t log_redirects_curl(char *ptr, size_t size, size_t nmemb, void *userdata)
const char * anonymousIdHeader()
void globalInitCurlOnce()
const char * distributionFlavorHeader()
std::string curlUnEscape(const std::string &text_r)
void setupZYPP_MEDIA_CURL_DEBUG(CURL *curl)
Setup CURLOPT_VERBOSE and CURLOPT_DEBUGFUNCTION according to env::ZYPP_MEDIA_CURL_DEBUG.
CURLcode setCurlRedirProtocols(CURL *curl)
const char * agentString()
void fillSettingsSystemProxy(const Url &url, media::TransferSettings &s)
Reads the system proxy configuration and fills the settings structure proxy information.
Url clearQueryString(const Url &url)
int ZYPP_MEDIA_CURL_IPRESOLVE()
4/6 to force IPv4/v6
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
std::list< DirEntry > DirContent
Returned by readdir.
int assert_file_mode(const Pathname &path, unsigned mode)
Like assert_file but enforce mode even if the file already exists.
int unlink(const Pathname &path)
Like 'unlink'.
std::string numstring(char n, int w=0)
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
std::string trim(const std::string &s, const Trim trim_r)
int zypp_poll(std::vector< GPollFD > &fds, int timeout)
Small wrapper around g_poll that additionally listens to the shutdown FD returned by ZYpp::shutdownSi...
Easy-to use interface to the ZYPP dependency resolver.
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
CURLMcode handleSocketActions(const std::vector< GPollFD > &actionsFds, int first=0)
std::vector< GPollFD > socks
std::optional< long > timeout_ms
Bottleneck filtering all DownloadProgressReport issued from Media[Muli]Curl.
~OptionalDownloadProgressReport() override
void report(const UserData &userData_r=UserData()) override
The most generic way of sending/receiving data.
void reportbegin() override
void reportend() override
Action problem(const Url &file_r, Error error_r, const std::string &description_r) override
OptionalDownloadProgressReport & operator=(const OptionalDownloadProgressReport &)=delete
OptionalDownloadProgressReport(bool isOptional=false)
std::chrono::steady_clock::time_point TimePoint
OptionalDownloadProgressReport(OptionalDownloadProgressReport &&)=delete
void finish(const Url &file_r, Error error_r, const std::string &reason_r) override
TimePoint _lastProgressSent
bool progress(int value_r, const Url &file_r, double dbps_avg_r=-1, double dbps_current_r=-1) override
Download progress.
OptionalDownloadProgressReport(const OptionalDownloadProgressReport &)=delete
void start(const Url &file_r, Pathname localfile_r) override
ByteCount _expectedFileSize
curl_off_t _dnlNow
Bytes downloaded now.
int _dnlPercent
Percent completed or 0 if _dnlTotal is unknown.
time_t _timeRcv
Start of no-data timeout.
ByteCount expectedFileSize() const
time_t _timeLast
Start last period(~1sec)
int reportProgress() const
double _drateLast
Download rate in last period.
bool timeoutReached() const
void expectedFileSize(ByteCount newval_r)
curl_off_t _dnlLast
Bytes downloaded at period start.
bool fileSizeExceeded() const
void updateStats(curl_off_t dltotal=0.0, curl_off_t dlnow=0.0)
double _drateTotal
Download rate so far.
zypp::callback::SendReport< zypp::media::DownloadProgressReport > * report
curl_off_t _dnlTotal
Bytes to download or 0 if unknown.
time_t _timeStart
Start total stats.
ProgressData(CURL *curl, time_t timeout=0, zypp::Url url=zypp::Url(), zypp::ByteCount expectedFileSize_r=0, zypp::callback::SendReport< zypp::media::DownloadProgressReport > *_report=nullptr)
AutoDispose<int> calling ::close
AutoDispose<FILE*> calling ::fclose
static DistributeReport & instance()
void setReceiver(Receiver &rec_r)
virtual void reportbegin()
virtual void report(const UserData &userData_r=UserData())
The most generic way of sending/receiving data.
callback::UserData UserData
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.