13#include <zypp-core/ng/base/EventDispatcher>
15#include <zypp-core/ng/core/String>
18#include <zypp-curl/CurlConfig>
19#include <zypp-curl/auth/CurlAuthData>
20#include <zypp-media/MediaConfig>
31#include <boost/variant.hpp>
32#include <boost/variant/polymorphic_get.hpp>
38 static size_t nwr_headerCallback (
char *ptr,
size_t size,
size_t nmemb,
void *userdata ) {
45 static size_t nwr_writeCallback (
char *ptr,
size_t size,
size_t nmemb,
void *userdata ) {
54 template<
class T>
struct always_false : std::false_type {};
78 ,
_headers(
std::unique_ptr< curl_slist, decltype (&curl_slist_free_all) >( nullptr, &curl_slist_free_all ) )
112 if ( urlScheme ==
"http" || urlScheme ==
"https" )
153 const auto &cHeaders =
_dispatcher->hostSpecificHeaders();
154 if (
auto i = cHeaders.find(
_url.
getHost()); i != cHeaders.end() ) {
155 for (
const auto &[key, value] : i->second ) {
166 case 4:
setCurlOption( CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
break;
167 case 6:
setCurlOption( CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6 );
break;
171 setCurlOption( CURLOPT_HEADERFUNCTION, &nwr_headerCallback );
186 if ( urlScheme ==
"https" )
207#ifdef CURLSSLOPT_ALLOW_BEAST
209 setCurlOption( CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
238 if (use_auth.empty())
239 use_auth =
"digest,basic";
241 if( auth != CURLAUTH_NONE)
243 DBG <<
_easyHandle <<
" " <<
"Enabling HTTP authentication methods: " << use_auth
244 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
253 setCurlOption(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
264 if ( proxyuserpwd.empty() )
269 DBG <<
_easyHandle <<
" " <<
"Proxy: ~/.curlrc does not contain the proxy-user option" << std::endl;
273 DBG <<
_easyHandle <<
" " <<
"Proxy: using proxy-user from ~/.curlrc" << std::endl;
281 if ( ! proxyuserpwd.empty() )
286#if CURLVERSION_AT_LEAST(7,19,4)
291 DBG <<
_easyHandle <<
" " <<
"Proxy: explicitly NOPROXY" << std::endl;
305#if CURLVERSION_AT_LEAST(7,15,5)
317#if CURLVERSION_AT_LEAST(7,18,0)
324 for (
const auto &header : locSet.
headers() ) {
325 if ( !z_func()->addRequestHeader( header.c_str() ) )
337 return ( elem1._start < elem2._start );
341 if (
auto initState = std::get_if<pending_t>(&
_runningMode) ) {
344 initState->_partialHelper = std::make_unique<CurlMultiPartHandler>(
350 helper = initState->_partialHelper.get();
352 }
else if (
auto pendingState = std::get_if<prepareNextRangeBatch_t>(&
_runningMode) ) {
353 helper = pendingState->_partialHelper.get();
355 errBuf =
"Request is in invalid state to call setupHandle";
377 auto rmode = std::get_if<NetworkRequestPrivate::running_t>( &
_runningMode );
379 DBG <<
_easyHandle <<
"Can only create output file in running mode" << std::endl;
383 if ( !rmode->_outFile ) {
384 std::string openMode =
"w+b";
395 if ( !rmode->_outFile ) {
408 auto rmode = std::get_if<NetworkRequestPrivate::running_t>( &
_runningMode );
409 if ( rmode->_partialHelper )
return rmode->_partialHelper->canRecover();
415 auto rmode = std::get_if<NetworkRequestPrivate::running_t>( &
_runningMode );
417 errBuf =
"NetworkRequestPrivate::prepareToContinue called in invalid state";
421 if ( rmode->_partialHelper && rmode->_partialHelper->hasMoreWork() ) {
427 auto &prepMode = std::get<prepareNextRangeBatch_t>(
_runningMode);
428 if ( !prepMode._partialHelper->prepareToContinue() ) {
429 errBuf = prepMode._partialHelper->lastErrorMessage();
433 if ( hadRangeFail ) {
441 MIL <<
_easyHandle <<
" curl_easy_reset after hadRangeFail" << std::endl;
448 errBuf =
"Request has no more work";
456 return std::any_of(
_requestedRanges.begin(),
_requestedRanges.end(), [](
const auto &range ){ return range._rangeState == CurlMultiPartHandler::Pending; });
461 bool isRangeContinuation = std::holds_alternative<prepareNextRangeBatch_t>(
_runningMode );
462 if ( isRangeContinuation ) {
463 MIL <<
_easyHandle <<
" " <<
"Continuing a previously started range batch." << std::endl;
471 if ( m._activityTimer ) {
474 m._activityTimer->start(
static_cast<uint64_t
>(
_settings.
timeout() * 1000 ) );
477 if ( !isRangeContinuation )
483 if ( std::holds_alternative<running_t>(
_runningMode) ) {
485 if ( rmode._partialHelper )
486 rmode._partialHelper->finalize();
493 resState.
_result = std::move(err);
495 if ( std::holds_alternative<running_t>(
_runningMode) ) {
504 if ( !rmode._partialHelper->verifyData() ){
511 if ( fseek( rmode._outFile, 0, SEEK_SET ) != 0 ) {
514 constexpr size_t bufSize = 4096;
516 while(
auto cnt = fread(buf, 1, bufSize, rmode._outFile ) > 0 ) {
528 if ( calcSum != expSum ) {
537 rmode._outFile.reset();
562 std::map<std::string, boost::any> extraInfo;
563 extraInfo.insert( {
"requestUrl",
_url } );
575 if ( std::holds_alternative<running_t>(
_runningMode ) ){
577 if ( rmode._activityTimer && rmode._activityTimer->isRunning() )
578 rmode._activityTimer->start();
588 if ( !std::holds_alternative<running_t>(that->
_runningMode) ){
589 DBG << that->
_easyHandle <<
" " <<
"Curl progress callback was called in invalid state "<< that->z_func()->state() << std::endl;
592 auto &rmode = std::get<running_t>( that->
_runningMode );
597 rmode._isInCallback =
true;
598 if ( rmode._lastProgressNow != dlnow ) {
599 rmode._lastProgressNow = dlnow;
600 that->
_sigProgress.emit( *that->z_func(), dltotal, dlnow, ultotal, ulnow );
602 rmode._isInCallback =
false;
604 return rmode._cachedResult ? CURLE_ABORTED_BY_CALLBACK : CURLE_OK;
617 std::string_view hdr( ptr, bytes );
619 hdr.remove_prefix( std::min( hdr.find_first_not_of(
" \t\r\n"), hdr.size() ) );
620 const auto lastNonWhitespace = hdr.find_last_not_of(
" \t\r\n");
621 if ( lastNonWhitespace != hdr.npos )
622 hdr.remove_suffix( hdr.size() - (lastNonWhitespace + 1) );
624 hdr = std::string_view();
626 if ( !std::holds_alternative<running_t>(
_runningMode) ){
627 DBG <<
_easyHandle <<
" " <<
"Curl headerfunction callback was called in invalid state "<< z_func()->state() << std::endl;
635 const auto &repSize = rmode._partialHelper->reportedFileSize ();
641 if ( zypp::strv::hasPrefixCI( hdr,
"HTTP/" ) ) {
644 (void)curl_easy_getinfo(
_easyHandle, CURLINFO_RESPONSE_CODE, &statuscode);
650 }
else if ( zypp::strv::hasPrefixCI( hdr,
"Location:" ) ) {
654 }
else if ( zypp::strv::hasPrefixCI( hdr,
"Content-Length:") ) {
656 auto str = std::string ( lenStr.data(), lenStr.length() );
659 DBG <<
_easyHandle <<
" " <<
"Got Content-Length Header: " << len << std::endl;
681 if ( !std::holds_alternative<running_t>(
_runningMode) ){
682 DBG <<
_easyHandle <<
" " <<
"Curl writefunction callback was called in invalid state "<< z_func()->state() << std::endl;
693 if ( fseek( rmode._outFile, *offset, SEEK_SET ) != 0 ) {
695 "Unable to set output file pointer." );
698 rmode._currentFileOffset = *offset;
702 const auto &repSize = rmode._partialHelper->reportedFileSize ();
715 auto written = fwrite( data, 1, max, rmode._outFile );
724 rmode._currentFileOffset += written;
727 rmode._downloaded += written;
735 auto rmode = std::get_if<NetworkRequestPrivate::running_t>( &
_runningMode );
736 if ( !rmode || !rmode->_partialHelper || !rmode->_partialHelper->hasError() )
740 if ( rmode->_cachedResult )
744 MIL_MEDIA <<
_easyHandle <<
" Multipart handler announced error code " << lastErr.toString () << std::endl;
745 rmode->_cachedResult = lastErr;
759 if ( d->_dispatcher )
760 d->_dispatcher->cancel( *
this,
"Request destroyed while still running" );
770 return d_func()->_expectedFileSize;
777 if (
state() ==
Pending && triggerReschedule && d->_dispatcher )
778 d->_dispatcher->reschedule();
783 return d_func()->_priority;
788 d_func()->_options = opt;
793 return d_func()->_options;
802 d->_requestedRanges.push_back(
Range::make( start, len, std::move(digest), std::move( expectedChkSum ), std::move( userData ), digestCompareLen, chksumpad ) );
811 d->_requestedRanges.push_back( std::move(range) );
812 auto &rng = d->_requestedRanges.back();
814 rng.bytesWritten = 0;
816 rng._digest->reset();
830 ._fileDigest = std::move(fDig),
841 d->_requestedRanges.clear();
846 const auto mystate =
state();
852 std::vector<Range> failed;
853 for (
auto &r : d->_requestedRanges ) {
855 failed.push_back( r.clone() );
863 return d_func()->_requestedRanges;
868 return d_func()->_lastRedirect;
873 return d_func()->_easyHandle;
878 const auto myerr =
error();
879 const auto mystate =
state();
885 auto getMeasurement = [ this ](
const CURLINFO info, std::chrono::microseconds &
target ){
886 using FPSeconds = std::chrono::duration<double, std::chrono::seconds::period>;
888 const auto res = curl_easy_getinfo( d_func()->_easyHandle, info, &val );
889 if ( CURLE_OK == res ) {
890 target = std::chrono::duration_cast<std::chrono::microseconds>( FPSeconds(val) );
894 getMeasurement( CURLINFO_NAMELOOKUP_TIME, t.
namelookup );
895 getMeasurement( CURLINFO_CONNECT_TIME, t.
connect);
896 getMeasurement( CURLINFO_APPCONNECT_TIME, t.
appconnect);
897 getMeasurement( CURLINFO_PRETRANSFER_TIME , t.
pretransfer);
898 getMeasurement( CURLINFO_TOTAL_TIME, t.
total);
899 getMeasurement( CURLINFO_REDIRECT_TIME, t.
redirect);
908 if ( !std::holds_alternative<NetworkRequestPrivate::running_t>( d->_runningMode) )
911 const auto &rmode = std::get<NetworkRequestPrivate::running_t>( d->_runningMode );
917 return d_func()->_url;
931 return d_func()->_targetFile;
939 d->_targetFile = path;
944 return d_func()->_fMode;
952 d->_fMode = std::move( mode );
958 if ( curl_easy_getinfo( d_func()->_easyHandle, CURLINFO_CONTENT_TYPE, &ptr ) == CURLE_OK && ptr )
959 return std::string(ptr);
960 return std::string();
967 if constexpr (std::is_same_v<T, NetworkRequestPrivate::pending_t> || std::is_same_v<T, NetworkRequestPrivate::prepareNextRangeBatch_t> )
969 else if constexpr (std::is_same_v<T, NetworkRequestPrivate::running_t>
970 || std::is_same_v<T, NetworkRequestPrivate::finished_t>)
971 return arg._contentLenght;
973 static_assert(always_false<T>::value,
"Unhandled state type");
974 }, d_func()->_runningMode);
981 if constexpr (std::is_same_v<T, NetworkRequestPrivate::pending_t>)
983 else if constexpr (std::is_same_v<T, NetworkRequestPrivate::running_t>
984 || std::is_same_v<T, NetworkRequestPrivate::prepareNextRangeBatch_t>
985 || std::is_same_v<T, NetworkRequestPrivate::finished_t>)
986 return arg._downloaded;
988 static_assert(always_false<T>::value,
"Unhandled state type");
989 }, d_func()->_runningMode);
994 return d_func()->_settings;
999 return std::visit([
this](
auto& arg) {
1001 if constexpr (std::is_same_v<T, NetworkRequestPrivate::pending_t>)
1003 else if constexpr (std::is_same_v<T, NetworkRequestPrivate::running_t> || std::is_same_v<T, NetworkRequestPrivate::prepareNextRangeBatch_t> )
1005 else if constexpr (std::is_same_v<T, NetworkRequestPrivate::finished_t>) {
1006 if ( std::get<NetworkRequestPrivate::finished_t>( d_func()->_runningMode )._result.isError() )
1012 static_assert(always_false<T>::value,
"Unhandled state type");
1013 }, d_func()->_runningMode);
1018 const auto s =
state();
1021 return std::get<NetworkRequestPrivate::finished_t>( d_func()->_runningMode)._result;
1027 return std::string();
1041 curl_slist *res = curl_slist_append( d->_headers ? d->_headers.get() :
nullptr, header.c_str() );
1046 d->_headers = std::unique_ptr< curl_slist, decltype (&curl_slist_free_all) >( res, &curl_slist_free_all );
1053 return d_func()->_currentCookieFile;
1058 d_func()->_currentCookieFile = std::move(
cookieFile);
1063 return d_func()->_sigStarted;
1068 return d_func()->_sigBytesDownloaded;
1073 return d_func()->_sigProgress;
1078 return d_func()->_sigFinished;
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Store and operate with byte count.
static const Unit B
1 Byte
Compute Message Digests (MD5, SHA1 etc).
bool create(const std::string &name)
initialize creation of a new message digest
Base class for Exception.
std::string asString() const
Error message provided by dumpOn as string.
std::string getScheme() const
Returns the scheme name of the URL.
std::string asString() const
Returns a default string representation of the Url object.
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
const char * c_str() const
String representation.
const std::string & asString() const
String representation.
bool empty() const
Test for an empty path.
The CurlMultiPartHandler class.
const std::string & lastErrorMessage() const
static zyppng::NetworkRequestError customError(NetworkRequestError::Type t, std::string &&errorMsg="", std::map< std::string, boost::any > &&extraInfo={})
The NetworkRequestError class Represents a error that occured in.
Type type() const
type Returns the type of the error
std::string nativeErrorString() const
bool isError() const
isError Will return true if this is a actual error
size_t headerfunction(char *ptr, size_t bytes) override
std::optional< FileVerifyInfo > _fileVerification
The digest for the full file.
enum zyppng::NetworkRequestPrivate::ProtocolMode _protocolMode
void notifyErrorCodeChanged() override
zypp::Pathname _targetFile
void resetActivityTimer()
zypp::Pathname _currentCookieFile
Signal< void(NetworkRequest &req, zypp::ByteCount count)> _sigBytesDownloaded
NetworkRequestDispatcher * _dispatcher
std::vector< NetworkRequest::Range > _requestedRanges
the requested ranges that need to be downloaded
size_t writefunction(char *ptr, std::optional< off_t > offset, size_t bytes) override
static int curlProgressCallback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
std::string errorMessage() const
Signal< void(NetworkRequest &req)> _sigStarted
NetworkRequest::FileMode _fMode
std::variant< pending_t, running_t, prepareNextRangeBatch_t, finished_t > _runningMode
bool initialize(std::string &errBuf)
void onActivityTimeout(Timer &)
Signal< void(NetworkRequest &req, off_t dltotal, off_t dlnow, off_t ultotal, off_t ulnow)> _sigProgress
std::string _lastRedirect
to log/report redirections
NetworkRequest::Options _options
bool prepareToContinue(std::string &errBuf)
void setResult(NetworkRequestError &&err)
~NetworkRequestPrivate() override
std::array< char, CURL_ERROR_SIZE+1 > _errorBuf
bool setupHandle(std::string &errBuf)
NetworkRequestPrivate(Url &&url, zypp::Pathname &&targetFile, NetworkRequest::FileMode fMode, NetworkRequest &p)
TransferSettings _settings
void setCurlOption(CURLoption opt, T data)
zypp::ByteCount _expectedFileSize
Signal< void(NetworkRequest &req, const NetworkRequestError &err)> _sigFinished
std::unique_ptr< curl_slist, decltype(&curl_slist_free_all) > _headers
bool setExpectedFileChecksum(const zypp::CheckSum &expected)
zypp::ByteCount reportedByteCount() const
Returns the number of bytes that are reported from the backend as the full download size,...
const zypp::Pathname & targetFilePath() const
Returns the target filename path.
zypp::ByteCount downloadedByteCount() const
Returns the number of already downloaded bytes as reported by the backend.
void resetRequestRanges()
void setUrl(const Url &url)
This will change the URL of the request.
void setExpectedFileSize(zypp::ByteCount expectedFileSize)
void setPriority(Priority prio, bool triggerReschedule=true)
std::vector< char > peekData(off_t offset, size_t count) const
std::string contentType() const
Returns the content type as reported from the server.
void setFileOpenMode(FileMode mode)
Sets the file open mode to mode.
bool addRequestHeader(const std::string &header)
~NetworkRequest() override
void setOptions(Options opt)
FileMode fileOpenMode() const
Returns the currently configured file open mode.
zypp::ByteCount expectedFileSize() const
bool hasError() const
Checks if there was a error with the request.
State state() const
Returns the current state the HttpDownloadRequest is in.
SignalProxy< void(NetworkRequest &req, const NetworkRequestError &err)> sigFinished()
Signals that the download finished.
SignalProxy< void(NetworkRequest &req, zypp::ByteCount count)> sigBytesDownloaded()
Signals that new data has been downloaded, this is only the payload and does not include control data...
std::optional< Timings > timings() const
After the request is finished query the timings that were collected during download.
std::string extendedErrorString() const
In some cases, curl can provide extended error information collected at runtime.
NetworkRequest(Url url, zypp::Pathname targetFile, FileMode fMode=WriteExclusive)
Priority priority() const
NetworkRequestError error() const
Returns the last set Error.
void setTargetFilePath(const zypp::Pathname &path)
Changes the target file path of the download.
const zypp::Pathname & cookieFile() const
void * nativeHandle() const
void setCookieFile(zypp::Pathname cookieFile)
void addRequestRange(size_t start, size_t len=0, std::optional< zypp::Digest > &&digest={}, CheckSumBytes expectedChkSum=CheckSumBytes(), std::any userData=std::any(), std::optional< size_t > digestCompareLen={}, std::optional< size_t > chksumpad={})
std::vector< Range > failedRanges() const
const std::vector< Range > & requestedRanges() const
SignalProxy< void(NetworkRequest &req)> sigStarted()
Signals that the dispatcher dequeued the request and actually starts downloading data.
SignalProxy< void(NetworkRequest &req, off_t dltotal, off_t dlnow, off_t ultotal, off_t ulnow)> sigProgress()
Signals if there was data read from the download.
TransferSettings & transferSettings()
CurlMultiPartHandler::Range Range
const std::string & lastRedirectInfo() const
The Timer class provides repetitive and single-shot timers.
SignalProxy< void(Timer &t)> sigExpired()
This signal is always emitted when the timer expires.
uint64_t remaining() const
uint64_t interval() const
#define EXPLICITLY_NO_PROXY
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)
typename decay< T >::type decay_t
String related utilities and Regular expression matching.
int ZYPP_MEDIA_CURL_IPRESOLVE()
4/6 to force IPv4/v6
Types and functions for filesystem operations.
int assert_file_mode(const Pathname &path, unsigned mode)
Like assert_file but enforce mode even if the file already exists.
std::vector< char > peek_data_fd(FILE *fd, off_t offset, size_t count)
TInt strtonum(const C_Str &str)
Parsing numbers from string.
Easy-to use interface to the ZYPP dependency resolver.
std::string asString(const Patch::Category &obj)
relates: Patch::Category string representation.
T trim(StrType &&s, const Trim trim_r)
zypp::media::TransferSettings TransferSettings
std::string strerr_cxx(const int err=-1)
ZYPP_IMPL_PRIVATE(UnixSignalSource)
static Range make(size_t start, size_t len=0, std::optional< zypp::Digest > &&digest={}, CheckSumBytes &&expectedChkSum=CheckSumBytes(), std::any &&userData=std::any(), std::optional< size_t > digestCompareLen={}, std::optional< size_t > _dataBlockPadding={})
NetworkRequestError _result
zypp::ByteCount _contentLenght
std::unique_ptr< CurlMultiPartHandler > _partialHelper
running_t(pending_t &&prevState)
std::chrono::microseconds appconnect
std::chrono::microseconds redirect
std::chrono::microseconds pretransfer
std::chrono::microseconds total
std::chrono::microseconds namelookup
std::chrono::microseconds connect