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>
57 void updateStats( curl_off_t dltotal = 0.0, curl_off_t dlnow = 0.0 );
80 {
return _file.value(); }
136 if ( dlnow && dlnow !=
_dnlNow )
186 auto written = fwrite( ptr, 1, bytes,
_file );
198 const std::string & err_r,
199 const std::string & msg_r )
220#define SET_OPTION(opt,val) do { \
221 ret = curl_easy_setopt ( curl, opt, val ); \
223 ZYPP_THROW(MediaCurlSetOptException(_origin.at(rData.mirror).url(), _curlError)); \
227#define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
228#define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
229#define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
232 const Pathname & attach_point_hint_r )
238 _multi = curl_multi_init();
242 MIL <<
"MediaCurl::MediaCurl(" << origin_r.
authority().
url() <<
", " << attach_point_hint_r <<
")" << endl;
250 char *atemp = ::strdup( apath.
asString().c_str());
253 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
255 WAR <<
"attach point " << ainfo.
path()
259 else if( atest != NULL)
269 try {
release(); }
catch(...) {}
271 curl_multi_cleanup(
_multi);
290 curl_version_info_data *curl_info = NULL;
291 curl_info = curl_version_info(CURLVERSION_NOW);
293 if (curl_info->protocols)
295 const char *
const *proto =
nullptr;
296 std::string scheme(
url.getScheme());
298 for(proto=curl_info->protocols; !found && *proto; ++proto)
300 if( scheme == std::string((
const char *)*proto))
305 std::string msg(
"Unsupported protocol '");
315 CURL *curl = rData.
curl;
318 curl_easy_reset ( curl );
323 CURLcode ret = curl_easy_setopt( curl, CURLOPT_ERRORBUFFER,
_curlError );
334 case 4:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
break;
335 case 6:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
break;
377#ifdef CURLSSLOPT_ALLOW_BEAST
379 ret = curl_easy_setopt( curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
388 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
403 if ( cred && cred->valid() ) {
420 std::string use_auth = settings.
authType();
421 if (use_auth.empty())
422 use_auth =
"digest,basic";
424 if( auth != CURLAUTH_NONE)
426 DBG <<
"Enabling HTTP authentication methods: " << use_auth
427 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
434 DBG <<
"Proxy: '" << settings.
proxy() <<
"'" << endl;
436 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
446 if ( proxyuserpwd.empty() )
451 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
455 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
460 DBG <<
"Proxy: using provided proxy-user '" << settings.
proxyUsername() <<
"'" << endl;
463 if ( ! proxyuserpwd.empty() )
468#if CURLVERSION_AT_LEAST(7,19,4)
473 DBG <<
"Proxy: explicitly NOPROXY" << endl;
479 DBG <<
"Proxy: not explicitly set, libcurl may look into the environment" << endl;
490#if CURLVERSION_AT_LEAST(7,15,5)
502 const auto &cookieFileParam =
_origin.at(rData.
mirror).url().getQueryParam(
"cookies" );
503 if ( !cookieFileParam.empty() &&
str::strToBool( cookieFileParam,
true ) )
506 MIL <<
"No cookies requested" << endl;
511#if CURLVERSION_AT_LEAST(7,18,0)
521 for (
const auto &header : settings.
headers() ) {
554 auto that =
const_cast<MediaCurl *
>(
this);
555 std::exception_ptr lastErr;
557 for (
unsigned mirr : mirrOrder ) {
559 return that->getFileCopyFromMirror ( mirr, srcFile,
target );
578 const auto &filename = srcFile.
filename();
584 auto &endpoint =
_origin[mirror];
587 AutoDispose<CURL*> curl( curl_easy_init(), []( CURL *hdl ) {
if ( hdl ) { curl_easy_cleanup(hdl); } } );
590 rData.mirror = mirror;
591 rData.curl = curl.
value ();
593 if( !endpoint.url().isValid() )
596 if( endpoint.url().getHost().empty() )
601 bool firstAuth =
true;
602 unsigned internalTry = 0;
603 static constexpr unsigned maxInternalTry = 3;
610 if( assert_dir( dest.
dirname() ) )
612 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
622 ERR <<
"out of memory for temp file name" << endl;
626 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
629 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
634 file = ::fdopen( tmp_fd,
"we" );
637 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
643 DBG <<
"dest: " << dest << endl;
644 DBG <<
"temp: " << destNew << endl;
651 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
652 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(
target).mtime());
656 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
657 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, 0L);
661 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
662 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, 0L);
683 std::string urlBuffer( curlUrl.
asString());
684 CURLcode ret = curl_easy_setopt( curl, CURLOPT_URL,
693 ret = curl_easy_setopt( curl, CURLOPT_WRITEDATA, &progressData );
703 report->start(fileurl, dest);
705 if ( curl_easy_setopt( curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
706 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
714 #if CURLVERSION_AT_LEAST(7,19,4)
719 if ( ftell(file) == 0 && ret == 0 )
721 long httpReturnCode = 33;
722 if ( curl_easy_getinfo( curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
724 long conditionUnmet = 33;
725 if ( curl_easy_getinfo( curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
727 WAR <<
"TIMECONDITION unmet - retry without." << endl;
728 curl_easy_setopt( curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
729 curl_easy_setopt( curl, CURLOPT_TIMEVALUE, 0L);
736 if ( curl_easy_setopt( curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
737 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
742 <<
", temp file size " << ftell(file)
743 <<
" bytes." << endl;
755 long httpReturnCode = 0;
756 CURLcode infoRet = curl_easy_getinfo(curl,
757 CURLINFO_RESPONSE_CODE,
759 bool modified =
true;
760 if (infoRet == CURLE_OK)
763 if ( httpReturnCode == 304
764 || ( httpReturnCode == 213 && (endpoint.url().getScheme() ==
"ftp" || endpoint.url().getScheme() ==
"tftp") ) )
766 DBG <<
" Not modified.";
773 WAR <<
"Could not get the response code." << endl;
776 if (modified || infoRet != CURLE_OK)
781 ERR <<
"Failed to chmod file " << destNew << endl;
785 if ( ::fclose( file ) )
787 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
792 if ( rename( destNew, dest ) != 0 ) {
793 ERR <<
"Rename failed" << endl;
817 if ( internalTry < maxInternalTry ) {
844 auto that =
const_cast<MediaCurl *
>(
this);
846 std::exception_ptr lastErr;
849 return that->doGetDoesFileExist( i, filename );
874 bool timeout_reached)
const
880 if (filename.
empty())
881 url = baseMirr.url();
889 case CURLE_UNSUPPORTED_PROTOCOL:
890 err =
" Unsupported protocol";
893 err +=
" or redirect (";
898 case CURLE_URL_MALFORMAT:
899 case CURLE_URL_MALFORMAT_USER:
902 case CURLE_LOGIN_DENIED:
906 case CURLE_HTTP_RETURNED_ERROR:
908 long httpReturnCode = 0;
909 CURLcode infoRet = curl_easy_getinfo( rData.
curl,
910 CURLINFO_RESPONSE_CODE,
912 if ( infoRet == CURLE_OK )
914 std::string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
915 switch ( httpReturnCode )
921 DBG << msg <<
" Login failed (URL: " <<
url.asString() <<
")" << std::endl;
922 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
937 if (
url.getHost().find(
".suse.com") != std::string::npos )
938 msg403 =
_(
"Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
939 else if (
url.asString().find(
"novell.com") != std::string::npos)
940 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
948 DBG << msg <<
" (URL: " <<
url.asString() <<
")" << std::endl;
953 std::string msg =
"Unable to retrieve HTTP response:";
954 DBG << msg <<
" (URL: " <<
url.asString() <<
")" << std::endl;
959 case CURLE_FTP_COULDNT_RETR_FILE:
960#if CURLVERSION_AT_LEAST(7,16,0)
961 case CURLE_REMOTE_FILE_NOT_FOUND:
963 case CURLE_FTP_ACCESS_DENIED:
964 case CURLE_TFTP_NOTFOUND:
965 err =
"File not found";
968 case CURLE_BAD_PASSWORD_ENTERED:
969 case CURLE_FTP_USER_PASSWORD_INCORRECT:
970 err =
"Login failed";
972 case CURLE_COULDNT_RESOLVE_PROXY:
973 case CURLE_COULDNT_RESOLVE_HOST:
974 case CURLE_COULDNT_CONNECT:
975 case CURLE_FTP_CANT_GET_HOST:
976 err =
"Connection failed";
978 case CURLE_WRITE_ERROR:
981 case CURLE_PARTIAL_FILE:
982 case CURLE_OPERATION_TIMEDOUT:
983 timeout_reached =
true;
985 case CURLE_ABORTED_BY_CALLBACK:
986 if( timeout_reached )
988 err =
"Timeout reached";
1018 AutoDispose<CURL*> curl( curl_easy_init(), []( CURL *hdl ) {
if ( hdl ) { curl_easy_cleanup(hdl); } } );
1020 rData.mirror = mirror;
1021 rData.curl = curl.
value ();
1023 auto &endpoint =
_origin[mirror];
1025 if( !endpoint.url().isValid() )
1028 if( endpoint.url().getHost().empty() )
1033 DBG <<
"URL: " <<
url.asString() << endl;
1048 std::string urlBuffer( curlUrl.
asString());
1051 bool canRetry =
true;
1052 bool firstAuth =
true;
1055 while ( canRetry ) {
1059 CURLcode ret = curl_easy_setopt( curl, CURLOPT_URL,
1060 urlBuffer.c_str() );
1065 AutoFILE file { ::fopen(
"/dev/null",
"w" ) };
1067 ERR <<
"fopen failed for /dev/null" << endl;
1071 ret = curl_easy_setopt( curl, CURLOPT_WRITEDATA, (*file) );
1082 const bool doHeadRequest = (endpoint.url().getScheme() ==
"http" || endpoint.url().getScheme() ==
"https") && settings.headRequestsAllowed();
1083 if ( doHeadRequest ) {
1084 curl_easy_setopt( curl, CURLOPT_NOBODY, 1L );
1086 curl_easy_setopt( curl, CURLOPT_RANGE,
"0-1" );
1091 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1103 if (
authenticate( endpoint.url(), settings, e.hint(), firstAuth ) ) {
1111 return ( ok == CURLE_OK );
1139 long httpReturnCode = 0;
1140 if ( curl_easy_getinfo( pdata->
curl(), CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 ) {
1141 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1153 return pdata->
writeBytes ( ptr, size * nmemb );
1162 long auth_info = CURLAUTH_NONE;
1165 curl_easy_getinfo(curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1167 if(infoRet == CURLE_OK)
1194 CURL *curl = rData.
curl;
1203 if ( curl_multi_add_handle(
_multi, curl ) != CURLM_OK )
1211 if (mcode != CURLM_OK)
1214 bool canContinue =
true;
1215 while ( canContinue ) {
1217 CURLMsg *msg =
nullptr;
1219 while ((msg = curl_multi_info_read(
_multi, &nqueue)) != 0) {
1220 if ( msg->msg != CURLMSG_DONE )
continue;
1221 if ( msg->easy_handle != curl )
continue;
1223 return msg->data.result;
1227 std::vector<GPollFD> requestedFds = _curlHelper.
socks;
1236 if (mcode != CURLM_OK)
1240 if (mcode != CURLM_OK)
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
#define ZYPP_FWD_CURRENT_EXCPT()
Drops a logline and returns the current Exception as a std::exception_ptr.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
reference value() const
Reference to the Tp object.
void resetDispose()
Set no dispose function.
Store and operate with byte count.
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.
Manages a data source characterized by an authoritative URL and a list of mirror URLs.
const OriginEndpoint & authority() const
const zypp::Url & url() const
ProgressData()
Ctor no range [0,0](0).
std::string getScheme() const
Returns the scheme name of the URL.
std::string asString() const
Returns a default string representation of the Url object.
static ZConfig & instance()
Singleton ctor.
Wrapper class for stat/lstat.
const Pathname & path() const
Return current Pathname.
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.
#define EXPLICITLY_NO_PROXY
size_t log_redirects_curl(char *ptr, size_t size, size_t nmemb, void *userdata)
void globalInitCurlOnce()
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)
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() ).
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)
bool strToBool(const C_Str &str, bool default_r)
Parse str into a bool depending on the default value.
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.
AutoDispose< void > OnScopeExit
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.
ByteCount bytesWritten() const
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)
ByteCount _bytesWritten
Bytes actually written into the file.
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
size_t writeBytes(char *ptr, ByteCount bytes)
curl_off_t _dnlTotal
Bytes to download or 0 if unknown.
ProgressData(AutoFILE file, CURL *curl, time_t timeout=0, zypp::Url url=zypp::Url(), zypp::ByteCount expectedFileSize_r=0, zypp::callback::SendReport< zypp::media::DownloadProgressReport > *_report=nullptr)
time_t _timeStart
Start total stats.
AutoDispose<int> calling close
AutoDispose<FILE*> calling fclose