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-curl/ProxyInfo> 26 #include <zypp-curl/auth/CurlAuthData> 27 #include <zypp-media/auth/CredentialManager> 28 #include <zypp-curl/CurlConfig> 35 #include <sys/types.h> 37 #include <sys/mount.h> 51 using TimePoint = std::chrono::steady_clock::time_point;
54 :
_oldRec { Distributor::instance().getReceiver() }
55 , _isOptional { isOptional }
59 {
if (
_oldRec ) Distributor::instance().setReceiver( *
_oldRec );
else Distributor::instance().noReceiver(); }
71 void start(
const Url & file_r, Pathname localfile_r )
override 77 _startLocalfile = std::move(localfile_r);
80 _oldRec->start( file_r, localfile_r );
83 bool progress(
int value_r,
const Url & file_r,
double dbps_avg_r = -1,
double dbps_current_r = -1 )
override 87 if ( not ( value_r || dbps_avg_r || dbps_current_r ) )
93 static constexpr std::chrono::milliseconds maxfequency { 100 };
94 TimePoint now { TimePoint::clock::now() };
95 TimePoint::duration elapsed { now - _lastProgressSent };
96 if ( elapsed < maxfequency )
98 _lastProgressSent = now;
99 return _oldRec->progress( value_r, file_r, dbps_avg_r, dbps_current_r );
104 if ( not
_oldRec || notStarted() )
return ABORT;
105 return _oldRec->problem( file_r, error_r, description_r );
108 void finish(
const Url & file_r,
Error error_r,
const std::string & reason_r )
override 110 if ( not
_oldRec || notStarted() )
return;
111 _oldRec->finish( file_r, error_r, reason_r );
117 {
return _isOptional; }
123 _oldRec->start( std::move(_startFile), std::move(_startLocalfile) );
142 void updateStats(
double dltotal = 0.0,
double dlnow = 0.0 );
144 int reportProgress()
const;
150 {
return _timeoutReached; }
153 {
return _fileSizeExceeded; }
156 {
return _expectedFileSize; }
159 { _expectedFileSize = newval_r; }
170 time_t _timeStart = 0;
171 time_t _timeLast = 0;
175 double _dnlTotal = 0.0;
176 double _dnlLast = 0.0;
177 double _dnlNow = 0.0;
181 double _drateTotal= 0.0;
182 double _drateLast = 0.0;
190 , _timeout( timeout )
191 , _timeoutReached( false )
192 , _fileSizeExceeded ( false )
193 , _expectedFileSize( expectedFileSize_r )
205 if ( dlnow && dlnow !=
_dnlNow )
257 static const std::string
_value(
259 "X-ZYpp-AnonymousId: %s",
271 static const std::string
_value(
273 "X-ZYpp-DistributionFlavor: %s",
287 "ZYpp " LIBZYPP_VERSION_STRING
" (curl %s) %s" 288 , curl_version_info(CURLVERSION_NOW)->version
301 const std::string & err_r,
302 const std::string & msg_r )
318 Pathname MediaCurl::_cookieFile =
"/var/lib/YaST2/cookies";
323 #define SET_OPTION(opt,val) do { \ 324 ret = curl_easy_setopt ( _curl, opt, val ); \ 326 ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \ 330 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val) 331 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val) 332 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val) 334 MediaCurl::MediaCurl(
const Url & url_r,
335 const Pathname & attach_point_hint_r )
344 MIL <<
"MediaCurl::MediaCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
352 char *atemp = ::strdup( apath.
asString().c_str());
355 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
357 WAR <<
"attach point " << ainfo.
path()
358 <<
" is not useable for " << url_r.
getScheme() << endl;
361 else if( atest != NULL)
383 curl_version_info_data *curl_info = NULL;
384 curl_info = curl_version_info(CURLVERSION_NOW);
386 if (curl_info->protocols)
388 const char *
const *proto;
391 for(proto=curl_info->protocols; !found && *proto; ++proto)
393 if( scheme == std::string((
const char *)*proto))
398 std::string msg(
"Unsupported protocol '");
412 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_ERRORBUFFER,
_curlError );
454 case 4:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
break;
455 case 6:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
break;
478 #if CURLVERSION_AT_LEAST(7,19,4) 481 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
483 SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
501 #ifdef CURLSSLOPT_ALLOW_BEAST 503 ret = curl_easy_setopt(
_curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
512 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
530 if ( cred && cred->valid() ) {
548 if (use_auth.empty())
549 use_auth =
"digest,basic";
551 if( auth != CURLAUTH_NONE)
553 DBG <<
"Enabling HTTP authentication methods: " << use_auth
554 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
563 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
573 if ( proxyuserpwd.empty() )
578 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
582 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
590 if ( ! proxyuserpwd.empty() )
595 #if CURLVERSION_AT_LEAST(7,19,4) 600 DBG <<
"Proxy: explicitly NOPROXY" << endl;
606 DBG <<
"Proxy: not explicitly set" << endl;
607 DBG <<
"Proxy: libcurl may look into the environment" << endl;
618 #if CURLVERSION_AT_LEAST(7,15,5) 631 MIL <<
"No cookies requested" << endl;
636 #if CURLVERSION_AT_LEAST(7,18,0) 641 for (
const auto &header : vol_settings.
headers() )
671 _curl = curl_easy_init();
709 try { curl_easy_cleanup(
_curl ); }
736 const auto &filename = srcFile.
filename();
744 bool firstAuth =
true;
745 unsigned internalTry = 0;
746 static constexpr
unsigned maxInternalTry = 3;
771 if ( internalTry < maxInternalTry ) {
828 bool timeout_reached)
const 833 if (filename.
empty())
842 case CURLE_UNSUPPORTED_PROTOCOL:
843 err =
" Unsupported protocol";
846 err +=
" or redirect (";
851 case CURLE_URL_MALFORMAT:
852 case CURLE_URL_MALFORMAT_USER:
855 case CURLE_LOGIN_DENIED:
859 case CURLE_HTTP_RETURNED_ERROR:
861 long httpReturnCode = 0;
862 CURLcode infoRet = curl_easy_getinfo(
_curl,
863 CURLINFO_RESPONSE_CODE,
865 if ( infoRet == CURLE_OK )
867 std::string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
868 switch ( httpReturnCode )
874 DBG << msg <<
" Login failed (URL: " <<
url.
asString() <<
")" << std::endl;
875 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
890 if (
url.
getHost().find(
".suse.com") != std::string::npos )
891 msg403 =
_(
"Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
892 else if (
url.
asString().find(
"novell.com") != std::string::npos)
893 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
906 std::string msg =
"Unable to retrieve HTTP response:";
912 case CURLE_FTP_COULDNT_RETR_FILE:
913 #if CURLVERSION_AT_LEAST(7,16,0) 914 case CURLE_REMOTE_FILE_NOT_FOUND:
916 case CURLE_FTP_ACCESS_DENIED:
917 case CURLE_TFTP_NOTFOUND:
918 err =
"File not found";
921 case CURLE_BAD_PASSWORD_ENTERED:
922 case CURLE_FTP_USER_PASSWORD_INCORRECT:
923 err =
"Login failed";
925 case CURLE_COULDNT_RESOLVE_PROXY:
926 case CURLE_COULDNT_RESOLVE_HOST:
927 case CURLE_COULDNT_CONNECT:
928 case CURLE_FTP_CANT_GET_HOST:
929 err =
"Connection failed";
931 case CURLE_WRITE_ERROR:
934 case CURLE_PARTIAL_FILE:
935 case CURLE_OPERATION_TIMEDOUT:
936 timeout_reached =
true;
938 case CURLE_ABORTED_BY_CALLBACK:
939 if( timeout_reached )
941 err =
"Timeout reached";
952 case CURLE_HTTP2_STREAM:
1002 std::string urlBuffer( curlUrl.
asString());
1003 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1004 urlBuffer.c_str() );
1016 struct TempSetHeadRequest
1018 TempSetHeadRequest( CURL * curl_r,
bool doHttpHeadRequest_r )
1020 , _doHttpHeadRequest { doHttpHeadRequest_r }
1022 if ( _doHttpHeadRequest ) {
1023 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 1L );
1025 curl_easy_setopt(
_curl, CURLOPT_RANGE,
"0-1" );
1028 ~TempSetHeadRequest() {
1029 if ( _doHttpHeadRequest ) {
1030 curl_easy_setopt(
_curl, CURLOPT_NOBODY, 0L);
1036 curl_easy_setopt(
_curl, CURLOPT_HTTPGET, 1L );
1038 curl_easy_setopt(
_curl, CURLOPT_RANGE, NULL );
1043 bool _doHttpHeadRequest;
1047 AutoFILE file { ::fopen(
"/dev/null",
"w" ) };
1049 ERR <<
"fopen failed for /dev/null" << endl;
1053 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, (*file) );
1058 CURLcode ok = curl_easy_perform(
_curl );
1059 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1076 return ( ok == CURLE_OK );
1086 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
1096 ERR <<
"out of memory for temp file name" << endl;
1100 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1103 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1108 file = ::fdopen( tmp_fd,
"we" );
1111 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1114 tmp_fd.resetDispose();
1117 DBG <<
"dest: " << dest << endl;
1118 DBG <<
"temp: " << destNew << endl;
1123 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1124 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(target).mtime());
1128 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1129 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1137 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1138 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1142 long httpReturnCode = 0;
1143 CURLcode infoRet = curl_easy_getinfo(
_curl,
1144 CURLINFO_RESPONSE_CODE,
1146 bool modified =
true;
1147 if (infoRet == CURLE_OK)
1150 if ( httpReturnCode == 304
1153 DBG <<
" Not modified.";
1160 WAR <<
"Could not get the response code." << endl;
1163 if (modified || infoRet != CURLE_OK)
1168 ERR <<
"Failed to chmod file " << destNew << endl;
1172 if ( ::fclose( file ) )
1174 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1179 if (
rename( destNew, dest ) != 0 ) {
1180 ERR <<
"Rename failed" << endl;
1183 destNew.resetDispose();
1219 std::string urlBuffer( curlUrl.
asString());
1220 CURLcode ret = curl_easy_setopt(
_curl, CURLOPT_URL,
1221 urlBuffer.c_str() );
1226 ret = curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, file );
1234 report->start(
url, dest);
1235 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1236 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1239 ret = curl_easy_perform(
_curl );
1240 #if CURLVERSION_AT_LEAST(7,19,4) 1245 if ( ftell(file) == 0 && ret == 0 )
1247 long httpReturnCode = 33;
1248 if ( curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1250 long conditionUnmet = 33;
1251 if ( curl_easy_getinfo(
_curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1253 WAR <<
"TIMECONDITION unmet - retry without." << endl;
1254 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1255 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1256 ret = curl_easy_perform(
_curl );
1262 if ( curl_easy_setopt(
_curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1263 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
1269 <<
", temp file size " << ftell(file)
1270 <<
" bytes." << endl;
1277 if ( progressData.fileSizeExceeded() )
1296 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1297 Pathname filename = dirname + it->name;
1300 switch ( it->type ) {
1307 getDir( filename, recurse_r );
1311 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
1325 const Pathname & dirname,
bool dots )
const 1333 const Pathname & dirname,
bool dots )
const 1360 long httpReturnCode = 0;
1361 if ( curl_easy_getinfo( pdata->
curl(), CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1362 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1373 return pdata ? pdata->
curl() : 0;
1380 long auth_info = CURLAUTH_NONE;
1383 curl_easy_getinfo(
_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1385 if(infoRet == CURLE_OK)
1416 if (cmcred && firstTry)
1419 DBG <<
"got stored credentials:" << endl << *credentials << endl;
1434 curlcred->setUsername(cmcred->username());
1443 curlcred->setAuthType(availAuthTypes);
1446 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
1448 DBG <<
"callback answer: retry" << endl
1449 <<
"CurlAuthData: " << *curlcred << endl;
1451 if (curlcred->valid())
1453 credentials = curlcred;
1467 DBG <<
"callback answer: cancel" << endl;
1483 if (credentials->authType() == CURLAUTH_NONE)
1484 credentials->setAuthType(availAuthTypes);
1487 if (credentials->authType() != CURLAUTH_NONE)
1491 ret = curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, credentials->authType());
1497 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.
double _dnlTotal
Bytes to download or 0 if unknown.
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.
double _dnlLast
Bytes downloaded at period start.
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.
std::string rtrim(const std::string &s)
TimePoint _lastProgressSent
int _dnlPercent
Percent completed or 0 if _dnlTotal is unknown.
int rmdir(const Pathname &path)
Like 'rmdir'.
Pathname absolutename() const
Return this path, adding a leading '/' if relative.
Base class for Exception.
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.
double _dnlNow
Bytes downloaded now.
Wrapper class for ::stat/::lstat.
void report(const UserData &userData_r=UserData()) override
The most generic way of sending/receiving data.
AutoDispose<FILE*> calling ::fclose
void updateStats(double dltotal=0.0, double dlnow=0.0)
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
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
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.