17 #include <zypp/base/Logger.h> 18 #include <zypp/ExternalProgram.h> 19 #include <zypp/base/String.h> 20 #include <zypp/base/Gettext.h> 21 #include <zypp-core/parser/Sysconfig> 22 #include <zypp/base/Gettext.h> 25 #include <zypp-core/zyppng/base/private/linuxhelpers_p.h> 27 #include <zypp-curl/ProxyInfo> 28 #include <zypp-curl/auth/CurlAuthData> 29 #include <zypp-media/auth/CredentialManager> 30 #include <zypp-curl/CurlConfig> 38 #include <sys/types.h> 40 #include <sys/mount.h> 54 using TimePoint = std::chrono::steady_clock::time_point;
57 :
_oldRec { Distributor::instance().getReceiver() }
58 , _isOptional { isOptional }
62 {
if (
_oldRec ) Distributor::instance().setReceiver( *
_oldRec );
else Distributor::instance().noReceiver(); }
74 void start(
const Url & file_r, Pathname localfile_r )
override 80 _startLocalfile = std::move(localfile_r);
83 _oldRec->start( file_r, localfile_r );
86 bool progress(
int value_r,
const Url & file_r,
double dbps_avg_r = -1,
double dbps_current_r = -1 )
override 90 if ( not ( value_r || dbps_avg_r || dbps_current_r ) )
96 static constexpr std::chrono::milliseconds maxfequency { 100 };
97 TimePoint now { TimePoint::clock::now() };
98 TimePoint::duration elapsed { now - _lastProgressSent };
99 if ( elapsed < maxfequency )
101 _lastProgressSent = now;
102 return _oldRec->progress( value_r, file_r, dbps_avg_r, dbps_current_r );
107 if ( not
_oldRec || notStarted() )
return ABORT;
108 return _oldRec->problem( file_r, error_r, description_r );
111 void finish(
const Url & file_r,
Error error_r,
const std::string & reason_r )
override 113 if ( not
_oldRec || notStarted() )
return;
114 _oldRec->finish( file_r, error_r, reason_r );
120 {
return _isOptional; }
126 _oldRec->start( std::move(_startFile), std::move(_startLocalfile) );
145 void updateStats( curl_off_t dltotal = 0.0, curl_off_t dlnow = 0.0 );
147 int reportProgress()
const;
153 {
return _timeoutReached; }
156 {
return _fileSizeExceeded; }
159 {
return _expectedFileSize; }
162 { _expectedFileSize = newval_r; }
173 time_t _timeStart = 0;
174 time_t _timeLast = 0;
178 curl_off_t _dnlTotal = 0.0;
179 curl_off_t _dnlLast = 0.0;
180 curl_off_t _dnlNow = 0.0;
184 double _drateTotal= 0.0;
185 double _drateLast = 0.0;
193 , _timeout( timeout )
194 , _timeoutReached( false )
195 , _fileSizeExceeded ( false )
196 , _expectedFileSize( expectedFileSize_r )
208 if ( dlnow && dlnow !=
_dnlNow )
262 "X-ZYpp-AnonymousId: %s",
276 "X-ZYpp-DistributionFlavor: %s",
291 , curl_version_info(CURLVERSION_NOW)->version
304 const std::string & err_r,
305 const std::string & msg_r )
321 Pathname MediaCurl::_cookieFile =
"/var/lib/YaST2/cookies";
326 #define SET_OPTION(opt,val) do { \ 327 ret = curl_easy_setopt ( _curl, opt, val ); \ 329 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \ 333 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val) 334 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val) 335 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val) 337 MediaCurl::MediaCurl(
const Url & url_r,
338 const Pathname & attach_point_hint_r )
347 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
355 char *atemp = ::strdup( apath.
asString().c_str());
358 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
360 WAR <<
"attach point " << ainfo.
path()
361 <<
" is not useable for " << url_r.
getScheme() << endl;
364 else if( atest != NULL)
386 curl_version_info_data *curl_info = NULL;
387 curl_info = curl_version_info(CURLVERSION_NOW);
389 if (curl_info->protocols)
391 const char *
const *proto;
394 for(proto=curl_info->protocols; !found && *proto; ++proto)
396 if( scheme == std::string((
const char *)*proto))
401 std::string msg(
"Unsupported protocol '");
415 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
457 case 4:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
break;
458 case 6:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
break;
500 #ifdef CURLSSLOPT_ALLOW_BEAST 502 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
511 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
529 if ( cred && cred->valid() ) {
547 if (use_auth.empty())
548 use_auth =
"digest,basic";
550 if( auth != CURLAUTH_NONE)
552 DBG <<
"Enabling HTTP authentication methods: " << use_auth
553 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
562 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
572 if ( proxyuserpwd.empty() )
577 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
581 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
589 if ( ! proxyuserpwd.empty() )
594 #if CURLVERSION_AT_LEAST(7,19,4) 599 DBG <<
"Proxy: explicitly NOPROXY" << endl;
605 DBG <<
"Proxy: not explicitly set" << endl;
606 DBG <<
"Proxy: libcurl may look into the environment" << endl;
617 #if CURLVERSION_AT_LEAST(7,15,5) 631 MIL <<
"No cookies requested" << endl;
636 #if CURLVERSION_AT_LEAST(7,18,0) 642 for (
const auto &header : vol_settings.
headers() ) {
668 _curl = curl_easy_init();
706 try { curl_easy_cleanup(
_curl ); }
733 const auto &filename = srcFile.
filename();
741 bool firstAuth =
true;
742 unsigned internalTry = 0;
743 static constexpr
unsigned maxInternalTry = 3;
768 if ( internalTry < maxInternalTry ) {
825 bool timeout_reached)
const 830 if (filename.
empty())
839 case CURLE_UNSUPPORTED_PROTOCOL:
840 err =
" Unsupported protocol";
843 err +=
" or redirect (";
848 case CURLE_URL_MALFORMAT:
849 case CURLE_URL_MALFORMAT_USER:
852 case CURLE_LOGIN_DENIED:
856 case CURLE_HTTP_RETURNED_ERROR:
858 long httpReturnCode = 0;
859 CURLcode infoRet = curl_easy_getinfo(
_curl,
860 CURLINFO_RESPONSE_CODE,
862 if ( infoRet == CURLE_OK )
864 std::string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
865 switch ( httpReturnCode )
871 DBG << msg <<
" Login failed (URL: " <<
url.
asString() <<
")" << std::endl;
872 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
887 if (
url.
getHost().find(
".suse.com") != std::string::npos )
888 msg403 =
_(
"Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
889 else if (
url.
asString().find(
"novell.com") != std::string::npos)
890 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
903 std::string msg =
"Unable to retrieve HTTP response:";
909 case CURLE_FTP_COULDNT_RETR_FILE:
910 #if CURLVERSION_AT_LEAST(7,16,0) 911 case CURLE_REMOTE_FILE_NOT_FOUND:
913 case CURLE_FTP_ACCESS_DENIED:
914 case CURLE_TFTP_NOTFOUND:
915 err =
"File not found";
918 case CURLE_BAD_PASSWORD_ENTERED:
919 case CURLE_FTP_USER_PASSWORD_INCORRECT:
920 err =
"Login failed";
922 case CURLE_COULDNT_RESOLVE_PROXY:
923 case CURLE_COULDNT_RESOLVE_HOST:
924 case CURLE_COULDNT_CONNECT:
925 case CURLE_FTP_CANT_GET_HOST:
926 err =
"Connection failed";
928 case CURLE_WRITE_ERROR:
931 case CURLE_PARTIAL_FILE:
932 case CURLE_OPERATION_TIMEDOUT:
933 timeout_reached =
true;
935 case CURLE_ABORTED_BY_CALLBACK:
936 if( timeout_reached )
938 err =
"Timeout reached";
949 case CURLE_HTTP2_STREAM:
999 std::string urlBuffer( curlUrl.
asString());
1000 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1001 urlBuffer.c_str() );
1013 struct TempSetHeadRequest
1015 TempSetHeadRequest( CURL * curl_r,
bool doHttpHeadRequest_r )
1017 , _doHttpHeadRequest { doHttpHeadRequest_r }
1019 if ( _doHttpHeadRequest ) {
1020 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
1022 curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
1025 ~TempSetHeadRequest() {
1026 if ( _doHttpHeadRequest ) {
1027 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1033 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1035 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1040 bool _doHttpHeadRequest;
1044 AutoFILE file { ::fopen(
"/dev/null",
"w" ) };
1046 ERR <<
"fopen failed for /dev/null" << endl;
1050 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, (*file) );
1056 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1073 return ( ok == CURLE_OK );
1083 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
1093 ERR <<
"out of memory for temp file name" << endl;
1097 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1100 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1105 file = ::fdopen( tmp_fd,
"we" );
1108 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1111 tmp_fd.resetDispose();
1114 DBG <<
"dest: " << dest << endl;
1115 DBG <<
"temp: " << destNew << endl;
1120 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1121 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(target).mtime());
1125 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1126 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1134 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1135 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1139 long httpReturnCode = 0;
1140 CURLcode infoRet = curl_easy_getinfo(
_curl,
1141 CURLINFO_RESPONSE_CODE,
1143 bool modified =
true;
1144 if (infoRet == CURLE_OK)
1147 if ( httpReturnCode == 304
1150 DBG <<
" Not modified.";
1157 WAR <<
"Could not get the response code." << endl;
1160 if (modified || infoRet != CURLE_OK)
1165 ERR <<
"Failed to chmod file " << destNew << endl;
1169 if ( ::fclose( file ) )
1171 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1176 if (
rename( destNew, dest ) != 0 ) {
1177 ERR <<
"Rename failed" << endl;
1180 destNew.resetDispose();
1216 std::string urlBuffer( curlUrl.
asString());
1217 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1218 urlBuffer.c_str() );
1223 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1231 report->start(
url, dest);
1232 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1233 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1237 #if CURLVERSION_AT_LEAST(7,19,4) 1242 if ( ftell(file) == 0 && ret == 0 )
1244 long httpReturnCode = 33;
1245 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1247 long conditionUnmet = 33;
1248 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1250 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1251 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1252 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1259 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1260 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1266 <<
", temp file size " << ftell(file)
1267 <<
" bytes." << endl;
1274 if ( progressData.fileSizeExceeded() )
1293 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1294 Pathname filename = dirname + it->name;
1297 switch ( it->type ) {
1304 getDir( filename, recurse_r );
1308 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1322 const Pathname & dirname,
bool dots )
const 1330 const Pathname & dirname,
bool dots )
const 1357 long httpReturnCode = 0;
1358 if ( curl_easy_getinfo( pdata->
curl(), CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1359 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1370 return pdata ? pdata->
curl() : 0;
1377 long auth_info = CURLAUTH_NONE;
1380 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1382 if(infoRet == CURLE_OK)
1412 ,[](
auto &releaseMe ){
if (releaseMe._multi) curl_multi_cleanup(releaseMe._multi); }
1415 if (!cMulti->_multi)
1422 if ( curl_multi_add_handle( cMulti->_multi,
_curl ) != CURLM_OK )
1426 OnScopeExit autoRemove([&](){ curl_multi_remove_handle( cMulti->_multi,
_curl ); });
1429 CURLMcode mcode = _curlHelper.handleTimout();
1430 if (mcode != CURLM_OK)
1433 bool canContinue =
true;
1434 while ( canContinue ) {
1437 std::vector<GPollFD> requestedFds = _curlHelper.socks;
1445 CURLMcode mcode = _curlHelper.handleTimout();
1446 if (mcode != CURLM_OK)
1449 CURLMcode mcode = _curlHelper.handleSocketActions( requestedFds );
1450 if (mcode != CURLM_OK)
1456 while ((msg = curl_multi_info_read( cMulti->_multi, &nqueue)) != 0) {
1457 if ( msg->msg != CURLMSG_DONE )
continue;
1458 if ( msg->easy_handle !=
_curl )
continue;
1460 return msg->data.result;
1477 if (cmcred && firstTry)
1480 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1495 curlcred->setUsername(cmcred->username());
1504 curlcred->setAuthType(availAuthTypes);
1507 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1509 DBG <<
"callback answer: retry" << endl
1510 <<
"CurlAuthData: " << *curlcred << endl;
1512 if (curlcred->valid())
1514 credentials = curlcred;
1528 DBG <<
"callback answer: cancel" << endl;
1544 if (credentials->authType() == CURLAUTH_NONE)
1545 credentials->setAuthType(availAuthTypes);
1548 if (credentials->authType() != CURLAUTH_NONE)
1552 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1558 credentials->setUrl(
_url);
std::string getScheme() const
Returns the scheme name of the URL.
void globalInitCurlOnce()
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
std::string targetDistribution() const
This is register.target attribute of the installed base product.
bool progress(int value_r, const Url &file_r, double dbps_avg_r=-1, double dbps_current_r=-1) override
Download progress.
size_t log_redirects_curl(char *ptr, size_t size, size_t nmemb, void *userdata)
ProgressData()
Ctor no range [0,0](0).
const Pathname & path() const
Return current Pathname.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
static ZConfig & instance()
Singleton ctor.
std::chrono::steady_clock::time_point TimePoint
ByteCount _expectedFileSize
const char * distributionFlavorHeader()
Store and operate with byte count.
void reportend() override
~OptionalDownloadProgressReport()
Pathname extend(const std::string &r) const
Append string r to the last component of the path.
int reportProgress() const
Url clearQueryString(const Url &url)
void start(const Url &file_r, Pathname localfile_r) override
const char * anonymousIdHeader()
const char * c_str() const
String representation.
void addHistory(const std::string &msg_r)
Add some message text to the history.
Action problem(const Url &file_r, Error error_r, const std::string &description_r) override
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
bool timeoutReached() const
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
AutoDispose<int> calling ::close
bool fileSizeExceeded() const
int ZYPP_MEDIA_CURL_IPRESOLVE()
4/6 to force IPv4/v6
void reportbegin() override
bool empty() const
Test for an empty path.
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
int assert_file_mode(const Pathname &path, unsigned mode)
Like assert_file but enforce mode even if the file already exists.
std::string asString() const
Returns a default string representation of the Url object.
std::string getQueryParam(const std::string ¶m, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
Bottleneck filtering all DownloadProgressReport issued from Media[Muli]Curl.
std::string trim(const std::string &s, const Trim trim_r)
void finish(const Url &file_r, Error error_r, const std::string &reason_r) override
int unlink(const Pathname &path)
Like 'unlink'.
const std::string & asString() const
String representation.
int rename(const Pathname &oldpath, const Pathname &newpath)
Like 'rename'.
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Pathname dirname() const
Return all but the last component od this path.
std::list< DirEntry > DirContent
Returned by readdir.
void fillSettingsFromUrl(const Url &url, media::TransferSettings &s)
Fills the settings structure using options passed on the url for example ?timeout=x&proxy=foo.
bool isValid() const
Verifies the Url.
void expectedFileSize(ByteCount newval_r)
std::string numstring(char n, int w=0)
const char * agentString()
void resetDispose()
Set no dispose function.
TimePoint _lastProgressSent
int _dnlPercent
Percent completed or 0 if _dnlTotal is unknown.
#define LIBZYPP_VERSION_STRING
int rmdir(const Pathname &path)
Like 'rmdir'.
Pathname absolutename() const
Return this path, adding a leading '/' if relative.
Base class for Exception.
curl_off_t _dnlNow
Bytes downloaded now.
curl_off_t _dnlTotal
Bytes to download or 0 if unknown.
double _drateLast
Download rate in last period.
std::string curlUnEscape(std::string text_r)
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
time_t _timeStart
Start total stats.
void setupZYPP_MEDIA_CURL_DEBUG(CURL *curl)
Setup CURLOPT_VERBOSE and CURLOPT_DEBUGFUNCTION according to env::ZYPP_MEDIA_CURL_DEBUG.
Typesafe passing of user data via callbacks.
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
Wrapper class for ::stat/::lstat.
curl_off_t _dnlLast
Bytes downloaded at period start.
void report(const UserData &userData_r=UserData()) override
The most generic way of sending/receiving data.
AutoDispose<FILE*> calling ::fclose
void fillSettingsSystemProxy(const Url &url, media::TransferSettings &s)
Reads the system proxy configuration and fills the settings structure proxy information.
double _drateTotal
Download rate so far.
std::string anonymousUniqueId() const
anonymous unique id
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
time_t _timeRcv
Start of no-data timeout.
#define EXPLICITLY_NO_PROXY
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...
void updateStats(curl_off_t dltotal=0.0, curl_off_t dlnow=0.0)
Easy-to use interface to the ZYPP dependency resolver.
std::string distributionFlavor() const
This is flavor attribute of the installed base product but does not require the target to be loaded a...
OptionalDownloadProgressReport(bool isOptional=false)
ByteCount expectedFileSize() const
CURLcode setCurlRedirProtocols(CURL *curl)
time_t _timeLast
Start last period(~1sec)
const char * c_str() const
zypp::callback::SendReport< zypp::media::DownloadProgressReport > * report
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.