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 );
565 that->deprioritizeMirror( mirr );
581 const auto &filename = srcFile.
filename();
587 auto &endpoint =
_origin[mirror];
590 AutoDispose<CURL*> curl( curl_easy_init(), []( CURL *hdl ) {
if ( hdl ) { curl_easy_cleanup(hdl); } } );
593 rData.mirror = mirror;
594 rData.curl = curl.
value ();
596 if( !endpoint.url().isValid() )
599 if( endpoint.url().getHost().empty() )
604 bool firstAuth =
true;
605 unsigned internalTry = 0;
606 static constexpr unsigned maxInternalTry = 3;
613 if( assert_dir( dest.
dirname() ) )
615 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
625 ERR <<
"out of memory for temp file name" << endl;
629 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
632 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
637 file = ::fdopen( tmp_fd,
"we" );
640 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
646 DBG <<
"dest: " << dest << endl;
647 DBG <<
"temp: " << destNew << endl;
654 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
655 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(
target).mtime());
659 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
660 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, 0L);
664 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
665 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, 0L);
686 std::string urlBuffer( curlUrl.
asString());
687 CURLcode ret = curl_easy_setopt( curl, CURLOPT_URL,
696 ret = curl_easy_setopt( curl, CURLOPT_WRITEDATA, &progressData );
706 report->start(fileurl, dest);
708 if ( curl_easy_setopt( curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
709 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
717 #if CURLVERSION_AT_LEAST(7,19,4)
722 if ( ftell(file) == 0 && ret == 0 )
724 long httpReturnCode = 33;
725 if ( curl_easy_getinfo( curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
727 long conditionUnmet = 33;
728 if ( curl_easy_getinfo( curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
730 WAR <<
"TIMECONDITION unmet - retry without." << endl;
731 curl_easy_setopt( curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
732 curl_easy_setopt( curl, CURLOPT_TIMEVALUE, 0L);
739 if ( curl_easy_setopt( curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
740 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
745 <<
", temp file size " << ftell(file)
746 <<
" bytes." << endl;
758 long httpReturnCode = 0;
759 CURLcode infoRet = curl_easy_getinfo(curl,
760 CURLINFO_RESPONSE_CODE,
762 bool modified =
true;
763 if (infoRet == CURLE_OK)
766 if ( httpReturnCode == 304
767 || ( httpReturnCode == 213 && (endpoint.url().getScheme() ==
"ftp" || endpoint.url().getScheme() ==
"tftp") ) )
769 DBG <<
" Not modified.";
776 WAR <<
"Could not get the response code." << endl;
779 if (modified || infoRet != CURLE_OK)
784 ERR <<
"Failed to chmod file " << destNew << endl;
788 if ( ::fclose( file ) )
790 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
795 if ( rename( destNew, dest ) != 0 ) {
796 ERR <<
"Rename failed" << endl;
820 if ( internalTry < maxInternalTry ) {
847 auto that =
const_cast<MediaCurl *
>(
this);
849 std::exception_ptr lastErr;
852 return that->doGetDoesFileExist( i, filename );
858 that->deprioritizeMirror( i );
880 bool timeout_reached)
const
886 if (filename.
empty())
887 url = baseMirr.url();
895 case CURLE_UNSUPPORTED_PROTOCOL:
896 err =
" Unsupported protocol";
899 err +=
" or redirect (";
904 case CURLE_URL_MALFORMAT:
905 case CURLE_URL_MALFORMAT_USER:
908 case CURLE_LOGIN_DENIED:
912 case CURLE_HTTP_RETURNED_ERROR:
914 long httpReturnCode = 0;
915 CURLcode infoRet = curl_easy_getinfo( rData.
curl,
916 CURLINFO_RESPONSE_CODE,
918 if ( infoRet == CURLE_OK )
920 std::string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
921 switch ( httpReturnCode )
927 DBG << msg <<
" Login failed (URL: " <<
url.asString() <<
")" << std::endl;
928 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
943 if (
url.getHost().find(
".suse.com") != std::string::npos )
944 msg403 =
_(
"Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
945 else if (
url.asString().find(
"novell.com") != std::string::npos)
946 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
954 DBG << msg <<
" (URL: " <<
url.asString() <<
")" << std::endl;
959 std::string msg =
"Unable to retrieve HTTP response:";
960 DBG << msg <<
" (URL: " <<
url.asString() <<
")" << std::endl;
965 case CURLE_FTP_COULDNT_RETR_FILE:
966#if CURLVERSION_AT_LEAST(7,16,0)
967 case CURLE_REMOTE_FILE_NOT_FOUND:
969 case CURLE_FTP_ACCESS_DENIED:
970 case CURLE_TFTP_NOTFOUND:
971 err =
"File not found";
974 case CURLE_BAD_PASSWORD_ENTERED:
975 case CURLE_FTP_USER_PASSWORD_INCORRECT:
976 err =
"Login failed";
978 case CURLE_COULDNT_RESOLVE_PROXY:
979 case CURLE_COULDNT_RESOLVE_HOST:
980 case CURLE_COULDNT_CONNECT:
981 case CURLE_FTP_CANT_GET_HOST:
982 err =
"Connection failed";
984 case CURLE_WRITE_ERROR:
987 case CURLE_PARTIAL_FILE:
988 case CURLE_OPERATION_TIMEDOUT:
989 timeout_reached =
true;
991 case CURLE_ABORTED_BY_CALLBACK:
992 if( timeout_reached )
994 err =
"Timeout reached";
1024 AutoDispose<CURL*> curl( curl_easy_init(), []( CURL *hdl ) {
if ( hdl ) { curl_easy_cleanup(hdl); } } );
1026 rData.mirror = mirror;
1027 rData.curl = curl.
value ();
1029 auto &endpoint =
_origin[mirror];
1031 if( !endpoint.url().isValid() )
1034 if( endpoint.url().getHost().empty() )
1039 DBG <<
"URL: " <<
url.asString() << endl;
1054 std::string urlBuffer( curlUrl.
asString());
1057 bool canRetry =
true;
1058 bool firstAuth =
true;
1061 while ( canRetry ) {
1065 CURLcode ret = curl_easy_setopt( curl, CURLOPT_URL,
1066 urlBuffer.c_str() );
1071 AutoFILE file { ::fopen(
"/dev/null",
"w" ) };
1073 ERR <<
"fopen failed for /dev/null" << endl;
1077 ret = curl_easy_setopt( curl, CURLOPT_WRITEDATA, (*file) );
1088 const bool doHeadRequest = (endpoint.url().getScheme() ==
"http" || endpoint.url().getScheme() ==
"https") && settings.headRequestsAllowed();
1089 if ( doHeadRequest ) {
1090 curl_easy_setopt( curl, CURLOPT_NOBODY, 1L );
1092 curl_easy_setopt( curl, CURLOPT_RANGE,
"0-1" );
1097 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1109 if (
authenticate( endpoint.url(), settings, e.hint(), firstAuth ) ) {
1117 return ( ok == CURLE_OK );
1145 long httpReturnCode = 0;
1146 if ( curl_easy_getinfo( pdata->
curl(), CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 ) {
1147 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1159 return pdata->
writeBytes ( ptr, size * nmemb );
1168 long auth_info = CURLAUTH_NONE;
1171 curl_easy_getinfo(curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1173 if(infoRet == CURLE_OK)
1200 CURL *curl = rData.
curl;
1209 if ( curl_multi_add_handle(
_multi, curl ) != CURLM_OK )
1217 if (mcode != CURLM_OK)
1220 bool canContinue =
true;
1221 while ( canContinue ) {
1223 CURLMsg *msg =
nullptr;
1225 while ((msg = curl_multi_info_read(
_multi, &nqueue)) != 0) {
1226 if ( msg->msg != CURLMSG_DONE )
continue;
1227 if ( msg->easy_handle != curl )
continue;
1229 return msg->data.result;
1233 std::vector<GPollFD> requestedFds = _curlHelper.
socks;
1242 if (mcode != CURLM_OK)
1246 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