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 );
120 if ( dlnow && dlnow !=
_dnlNow )
173 const std::string & err_r,
174 const std::string & msg_r )
195#define SET_OPTION(opt,val) do { \
196 ret = curl_easy_setopt ( curl, opt, val ); \
198 ZYPP_THROW(MediaCurlSetOptException(_origin.at(rData.mirror).url(), _curlError)); \
202#define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
203#define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
204#define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
207 const Pathname & attach_point_hint_r )
213 _multi = curl_multi_init();
217 MIL <<
"MediaCurl::MediaCurl(" << origin_r.
authority().
url() <<
", " << attach_point_hint_r <<
")" << endl;
225 char *atemp = ::strdup( apath.
asString().c_str());
228 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
230 WAR <<
"attach point " << ainfo.
path()
234 else if( atest != NULL)
244 try {
release(); }
catch(...) {}
246 curl_multi_cleanup(
_multi);
265 curl_version_info_data *curl_info = NULL;
266 curl_info = curl_version_info(CURLVERSION_NOW);
268 if (curl_info->protocols)
270 const char *
const *
proto =
nullptr;
271 std::string scheme(
url.getScheme());
275 if( scheme == std::string((
const char *)*
proto))
280 std::string msg(
"Unsupported protocol '");
290 CURL *curl = rData.
curl;
293 curl_easy_reset ( curl );
298 CURLcode ret = curl_easy_setopt( curl, CURLOPT_ERRORBUFFER,
_curlError );
309 case 4:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
break;
310 case 6:
SET_OPTION(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
break;
352#ifdef CURLSSLOPT_ALLOW_BEAST
354 ret = curl_easy_setopt( curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
363 SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
381 if ( cred && cred->valid() ) {
398 std::string use_auth = settings.
authType();
399 if (use_auth.empty())
400 use_auth =
"digest,basic";
402 if( auth != CURLAUTH_NONE)
404 DBG <<
"Enabling HTTP authentication methods: " << use_auth
405 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
412 DBG <<
"Proxy: '" << settings.
proxy() <<
"'" << endl;
414 SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
424 if ( proxyuserpwd.empty() )
429 DBG <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
433 DBG <<
"Proxy: using proxy-user from ~/.curlrc" << endl;
438 DBG <<
"Proxy: using provided proxy-user '" << settings.
proxyUsername() <<
"'" << endl;
441 if ( ! proxyuserpwd.empty() )
446#if CURLVERSION_AT_LEAST(7,19,4)
451 DBG <<
"Proxy: explicitly NOPROXY" << endl;
457 DBG <<
"Proxy: not explicitly set" << endl;
458 DBG <<
"Proxy: libcurl may look into the environment" << endl;
469#if CURLVERSION_AT_LEAST(7,15,5)
481 const auto &cookieFileParam =
_origin.at(rData.
mirror).url().getQueryParam(
"cookies" );
482 if ( !cookieFileParam.empty() &&
str::strToBool( cookieFileParam,
true ) )
485 MIL <<
"No cookies requested" << endl;
490#if CURLVERSION_AT_LEAST(7,18,0)
500 for (
const auto &header : settings.
headers() ) {
533 auto that =
const_cast<MediaCurl *
>(
this);
534 std::exception_ptr lastErr;
536 for (
unsigned mirr : mirrOrder ) {
538 return that->getFileCopyFromMirror ( mirr, srcFile,
target );
557 const auto &filename = srcFile.
filename();
566 AutoDispose<CURL*> curl( curl_easy_init(), []( CURL *hdl ) {
if ( hdl ) { curl_easy_cleanup(hdl); } } );
569 rData.mirror = mirror;
570 rData.curl = curl.
value ();
572 if( !myUrl.url().isValid() )
575 if( myUrl.url().getHost().empty() )
580 bool firstAuth =
true;
581 unsigned internalTry = 0;
582 static constexpr unsigned maxInternalTry = 3;
589 if( assert_dir( dest.
dirname() ) )
591 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
601 ERR <<
"out of memory for temp file name" << endl;
605 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
608 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
613 file = ::fdopen( tmp_fd,
"we" );
616 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
622 DBG <<
"dest: " << dest << endl;
623 DBG <<
"temp: " << destNew << endl;
630 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
631 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(
target).mtime());
635 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
636 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, 0L);
640 curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
641 curl_easy_setopt(curl, CURLOPT_TIMEVALUE, 0L);
662 std::string urlBuffer( curlUrl.
asString());
663 CURLcode ret = curl_easy_setopt( curl, CURLOPT_URL,
669 ret = curl_easy_setopt( curl, CURLOPT_WRITEDATA, file.
value() );
676 report->start(fileurl, dest);
678 if ( curl_easy_setopt( curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
679 WAR <<
"Can't set CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
683 #if CURLVERSION_AT_LEAST(7,19,4)
688 if ( ftell(file) == 0 && ret == 0 )
690 long httpReturnCode = 33;
691 if ( curl_easy_getinfo( curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
693 long conditionUnmet = 33;
694 if ( curl_easy_getinfo( curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
696 WAR <<
"TIMECONDITION unmet - retry without." << endl;
697 curl_easy_setopt( curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
698 curl_easy_setopt( curl, CURLOPT_TIMEVALUE, 0L);
705 if ( curl_easy_setopt( curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
706 WAR <<
"Can't unset CURLOPT_PROGRESSDATA: " <<
_curlError << endl;;
711 <<
", temp file size " << ftell(file)
712 <<
" bytes." << endl;
724 long httpReturnCode = 0;
725 CURLcode infoRet = curl_easy_getinfo(curl,
726 CURLINFO_RESPONSE_CODE,
728 bool modified =
true;
729 if (infoRet == CURLE_OK)
732 if ( httpReturnCode == 304
733 || ( httpReturnCode == 213 && (myUrl.url().getScheme() ==
"ftp" || myUrl.url().getScheme() ==
"tftp") ) )
735 DBG <<
" Not modified.";
742 WAR <<
"Could not get the response code." << endl;
745 if (modified || infoRet != CURLE_OK)
750 ERR <<
"Failed to chmod file " << destNew << endl;
754 if ( ::fclose( file ) )
756 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
761 if ( rename( destNew, dest ) != 0 ) {
762 ERR <<
"Rename failed" << endl;
787 if ( internalTry < maxInternalTry ) {
814 auto that =
const_cast<MediaCurl *
>(
this);
816 std::exception_ptr lastErr;
819 return that->doGetDoesFileExist( i, filename );
844 bool timeout_reached)
const
850 if (filename.
empty())
851 url = baseMirr.url();
859 case CURLE_UNSUPPORTED_PROTOCOL:
860 err =
" Unsupported protocol";
863 err +=
" or redirect (";
868 case CURLE_URL_MALFORMAT:
869 case CURLE_URL_MALFORMAT_USER:
872 case CURLE_LOGIN_DENIED:
876 case CURLE_HTTP_RETURNED_ERROR:
878 long httpReturnCode = 0;
879 CURLcode infoRet = curl_easy_getinfo( rData.
curl,
880 CURLINFO_RESPONSE_CODE,
882 if ( infoRet == CURLE_OK )
884 std::string msg =
"HTTP response: " +
str::numstring( httpReturnCode );
885 switch ( httpReturnCode )
891 DBG << msg <<
" Login failed (URL: " <<
url.asString() <<
")" << std::endl;
892 DBG <<
"MediaUnauthorizedException auth hint: '" << auth_hint <<
"'" << std::endl;
907 if (
url.getHost().find(
".suse.com") != std::string::npos )
908 msg403 =
_(
"Visit the SUSE Customer Center to check whether your registration is valid and has not expired.");
909 else if (
url.asString().find(
"novell.com") != std::string::npos)
910 msg403 =
_(
"Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
918 DBG << msg <<
" (URL: " <<
url.asString() <<
")" << std::endl;
923 std::string msg =
"Unable to retrieve HTTP response:";
924 DBG << msg <<
" (URL: " <<
url.asString() <<
")" << std::endl;
929 case CURLE_FTP_COULDNT_RETR_FILE:
930#if CURLVERSION_AT_LEAST(7,16,0)
931 case CURLE_REMOTE_FILE_NOT_FOUND:
933 case CURLE_FTP_ACCESS_DENIED:
934 case CURLE_TFTP_NOTFOUND:
935 err =
"File not found";
938 case CURLE_BAD_PASSWORD_ENTERED:
939 case CURLE_FTP_USER_PASSWORD_INCORRECT:
940 err =
"Login failed";
942 case CURLE_COULDNT_RESOLVE_PROXY:
943 case CURLE_COULDNT_RESOLVE_HOST:
944 case CURLE_COULDNT_CONNECT:
945 case CURLE_FTP_CANT_GET_HOST:
946 err =
"Connection failed";
948 case CURLE_WRITE_ERROR:
951 case CURLE_PARTIAL_FILE:
952 case CURLE_OPERATION_TIMEDOUT:
953 timeout_reached =
true;
955 case CURLE_ABORTED_BY_CALLBACK:
956 if( timeout_reached )
958 err =
"Timeout reached";
988 AutoDispose<CURL*> curl( curl_easy_init(), []( CURL *hdl ) {
if ( hdl ) { curl_easy_cleanup(hdl); } } );
990 rData.mirror = mirror;
991 rData.curl = curl.
value ();
995 if( !myUrl.url().isValid() )
998 if( myUrl.url().getHost().empty() )
1003 DBG <<
"URL: " <<
url.asString() << endl;
1018 std::string urlBuffer( curlUrl.
asString());
1021 bool canRetry =
true;
1022 bool firstAuth =
true;
1025 while ( canRetry ) {
1029 CURLcode ret = curl_easy_setopt( curl, CURLOPT_URL,
1030 urlBuffer.c_str() );
1035 AutoFILE file { ::fopen(
"/dev/null",
"w" ) };
1037 ERR <<
"fopen failed for /dev/null" << endl;
1041 ret = curl_easy_setopt( curl, CURLOPT_WRITEDATA, (*file) );
1052 const bool doHeadRequest = (myUrl.url().getScheme() ==
"http" || myUrl.url().getScheme() ==
"https") && settings.headRequestsAllowed();
1053 if ( doHeadRequest ) {
1054 curl_easy_setopt( curl, CURLOPT_NOBODY, 1L );
1056 curl_easy_setopt( curl, CURLOPT_RANGE,
"0-1" );
1061 MIL <<
"perform code: " << ok <<
" [ " << curl_easy_strerror(ok) <<
" ]" << endl;
1073 if (
authenticate( myUrl.url(), settings, e.hint(), firstAuth ) ) {
1081 return ( ok == CURLE_OK );
1109 long httpReturnCode = 0;
1110 if ( curl_easy_getinfo( pdata->
curl(), CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0 )
1111 return aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1122 return pdata ? pdata->
curl() : 0;
1129 long auth_info = CURLAUTH_NONE;
1132 curl_easy_getinfo(curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1134 if(infoRet == CURLE_OK)
1161 CURL *curl = rData.
curl;
1170 if ( curl_multi_add_handle(
_multi, curl ) != CURLM_OK )
1178 if (mcode != CURLM_OK)
1181 bool canContinue =
true;
1182 while ( canContinue ) {
1184 CURLMsg *msg =
nullptr;
1186 while ((msg = curl_multi_info_read(
_multi, &nqueue)) != 0) {
1187 if ( msg->msg != CURLMSG_DONE )
continue;
1188 if ( msg->easy_handle != curl )
continue;
1190 return msg->data.result;
1194 std::vector<GPollFD> requestedFds = _curlHelper.
socks;
1203 if (mcode != CURLM_OK)
1207 if (mcode != CURLM_OK)
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 _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
#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.