26#include <zypp/ManagedFile.h>
28#include <zypp/base/Logger.h>
31#include <zypp-core/zyppng/base/private/linuxhelpers_p.h>
32#include <zypp-curl/parser/MetaLinkParser>
35#include <zypp-curl/auth/CurlAuthData>
42#undef CURLVERSION_AT_LEAST
43#define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
182 void adddnsfd( std::vector<GPollFD> &waitFds );
183 void dnsevent(
const std::vector<GPollFD> &waitFds );
214 size_t writefunction (
char *ptr, std::optional<off_t> offset,
size_t bytes )
override;
216 bool beginRange ( off_t range, std::string &cancelReason )
override;
217 bool finishedRange ( off_t range,
bool validated, std::string &cancelReason )
override;
232 void run(std::vector<Url> &urllist);
254 std::list< std::unique_ptr<multifetchworker> >
_workers;
293#if _POSIX_C_SOURCE >= 199309L
295 if ( clock_gettime( CLOCK_MONOTONIC, &ts) )
297 return ts.tv_sec + ts.tv_nsec / 1000000000.;
300 if (gettimeofday(&tv, NULL))
302 return tv.tv_sec + tv.tv_usec / 1000000.;
310 return bytes ? 0 : 1;
332 const auto &blk =
_blocks[*currRange];
333 off_t seekTo = blk.start + blk.bytesWritten;
338 return bytes ? 0 : 1;
350 const auto &currRangeState = stripeDesc.blockStates[stripeRangeOff];
353 cancelReason =
"Cancelled because stripe block is already finalized";
355 WAR <<
"#" <<
_workerno <<
": trying to start a range ("<<stripeRangeOff<<
"["<<
_blocks[workerRangeOff].start <<
" : "<<
_blocks[workerRangeOff].len<<
"]) that was already finalized, cancelling. Stealing was: " <<
_request->
_stealing << endl;
366 const auto &currRangeState = stripeDesc.blockStates[stripeRangeOff];
370 cancelReason =
"Block failed to validate";
397 if (l > 9 && !strncasecmp(p,
"Location:", 9)) {
398 std::string line(p + 9, l - 9);
399 if (line[l - 10] ==
'\r')
400 line.erase(l - 10, 1);
401 XXX <<
"#" <<
_workerno <<
": redirecting to" << line << endl;
407 XXX <<
"#" <<
_workerno <<
": filesize mismatch" << endl;
409 strncpy(
_curlError,
"filesize mismatch", CURL_ERROR_SIZE);
419, _maxspeed( request._maxspeed )
420, _request ( &request )
426 XXX <<
"reused worker from pool" << endl;
430 strncpy(
_curlError,
"curl_easy_init failed", CURL_ERROR_SIZE);
446 curl_easy_cleanup(
_curl);
449 strncpy(
_curlError,
"curl_easy_setopt failed", CURL_ERROR_SIZE);
452 curl_easy_setopt(
_curl, CURLOPT_PRIVATE,
this);
465 if (use_auth.empty())
466 use_auth =
"digest,basic";
468 if( auth != CURLAUTH_NONE)
470 XXX <<
"#" <<
_workerno <<
": Enabling HTTP authentication methods: " << use_auth
471 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
472 curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, auth);
487#if CURLVERSION_AT_LEAST(7,15,5)
488 curl_easy_setopt(
_curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)0);
490 curl_easy_setopt(
_curl, CURLOPT_PRIVATE, (
void *)0);
491 curl_easy_setopt(
_curl, CURLOPT_WRITEFUNCTION, (
void *)0);
492 curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, (
void *)0);
493 curl_easy_setopt(
_curl, CURLOPT_HEADERFUNCTION, (
void *)0);
494 curl_easy_setopt(
_curl, CURLOPT_HEADERDATA, (
void *)0);
498 curl_easy_cleanup(
_curl);
505 while (waitpid(
_pid, &status, 0) == -1)
522 const char *s = getenv(name.c_str());
523 return s && *s ? true :
false;
539 if (inet_pton(AF_INET, host.c_str(), addrbuf) == 1)
541 if (inet_pton(AF_INET6, host.c_str(), addrbuf) == 1)
552 if (schemeproxy !=
"http_proxy")
554 std::transform(schemeproxy.begin(), schemeproxy.end(), schemeproxy.begin(), ::toupper);
559 XXX <<
"checking DNS lookup of " << host << endl;
564 strncpy(
_curlError,
"DNS pipe creation failed", CURL_ERROR_SIZE);
568 if (
_pid == pid_t(-1))
574 strncpy(
_curlError,
"DNS checker fork failed", CURL_ERROR_SIZE);
581 struct addrinfo *ai, aihints;
582 memset(&aihints, 0,
sizeof(aihints));
583 aihints.ai_family = PF_UNSPEC;
584 int tstsock = socket(PF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
586 aihints.ai_family = PF_INET;
589 aihints.ai_socktype = SOCK_STREAM;
590 aihints.ai_flags = AI_CANONNAME;
593 alarm(connecttimeout);
594 signal(SIGALRM, SIG_DFL);
595 if (getaddrinfo(host.c_str(), NULL, &aihints, &ai))
613 .events = G_IO_IN | G_IO_HUP | G_IO_ERR,
621 bool hasEvent = std::any_of( waitFds.begin (), waitFds.end(),[
this](
const GPollFD &waitfd ){
622 return ( waitfd.fd == _dnspipe && waitfd.revents != 0 );
628 while (waitpid(
_pid, &status, 0) == -1)
639 if (!WIFEXITED(status))
642 strncpy(
_curlError,
"DNS lookup failed", CURL_ERROR_SIZE);
646 int exitcode = WEXITSTATUS(status);
647 XXX <<
"#" <<
_workerno <<
": DNS lookup returned " << exitcode << endl;
651 strncpy(
_curlError,
"DNS lookup failed", CURL_ERROR_SIZE);
665 auto &blk =
_blocks[workerRangeIdx];
681 size_t cnt = l >
sizeof(buf) ?
sizeof(buf) : l;
691 blk._digest = std::move(newDig);
706 std::optional<zypp::Digest> digest;
707 std::optional<size_t> relDigLen;
708 std::optional<size_t> blkSumPad;
713 relDigLen = sum.size( );
719 return MultiByteHandler::Range::make(
725 std::move(relDigLen),
726 std::move(blkSumPad) );
733 XXX <<
"start stealing!" << endl;
747 if (worker->
_pass == -1)
814 XXX <<
"#" <<
_workerno <<
": going to sleep for " << sl * 1000 <<
" ms" << endl;
871 for ( uint i = 0; i < stripeDesc.blocks.size(); i++ ) {
891 DBG <<
"#" <<
_workerno <<
"Done adding blocks to download, going to download: " <<
_blocks.size() <<
" nr of block with " <<
_datasize <<
" nr of bytes" << std::endl;
902 bool hadRangeFail =
_multiByteHandler->lastError() == MultiByteHandler::Code::RangeFail;
908 if ( hadRangeFail ) {
915 curl_easy_reset(
_curl );
940 strncpy(
_curlError,
"curl_multi_add_handle failed", CURL_ERROR_SIZE );
953 :
internal::CurlPollHelper::CurlPoll{ multi }
955 , _filename(filename)
959 , _blklist(
std::move(blklist))
960 , _filesize(filesize)
962 , _timeout(context->_settings.timeout())
963 , _connect_timeout(context->_settings.connectTimeout())
964 , _maxspeed(context->_settings.maxDownloadSpeed())
965 , _maxworkers(context->_settings.maxConcurrentConnections())
992 currStripeSize += blk.
size;
1007 std::vector<Url>::iterator urliter = urllist.begin();
1013 if (mcode != CURLM_OK)
1019 std::vector<GPollFD> waitFds;
1024 XXX <<
"finished!" << endl;
1031 _workers.push_back(std::make_unique<multifetchworker>(workerno++, *
this, *urliter));
1048 WAR <<
"No more active workers!" << endl;
1050 for (
auto workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
1060 for (
auto workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
1061 (*workeriter)->adddnsfd( waitFds );
1068 for (
auto workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter) {
1082 timeoutMs = sl * 1000;
1086 timeoutMs = std::min<long>( timeoutMs, _curlHelper.
timeout_ms.value() );
1088 dnsFdCount = waitFds.size();
1089 waitFds.insert( waitFds.end(), _curlHelper.
socks.begin(), _curlHelper.
socks.end() );
1095 for (
auto workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
1100 (*workeriter)->
dnsevent( waitFds );
1110 if (mcode != CURLM_OK)
1114 if (mcode != CURLM_OK)
1134 for (
auto workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
1143 XXX <<
"#" << worker->
_workerno <<
": sleep done, wake up" << endl;
1153 while ((msg = curl_multi_info_read(
_multi, &nqueue)) != 0)
1155 if (msg->msg != CURLMSG_DONE)
1157 CURL *easy = msg->easy_handle;
1158 CURLcode cc = msg->data.result;
1161 if (curl_easy_getinfo(easy, CURLINFO_PRIVATE, &worker) != CURLE_OK)
1172 curl_multi_remove_handle(
_multi, easy);
1174 const auto &setWorkerBroken = [&](
const std::string &
str = {} ){
1176 if ( !
str.empty () )
1187 WAR <<
"#" << worker->
_workerno <<
": has no multibyte handler, this is a bug" << endl;
1188 setWorkerBroken(
"Multibyte handler error");
1197 WAR <<
"#" << worker->
_workerno <<
": still has work to do or can recover from a error, continuing the job!" << endl;
1208 if ( cc != CURLE_OK ) {
1214 WAR <<
"#" << worker->
_workerno <<
": failed, but was set to discard, reusing for new requests" << endl;
1233 bool done = std::all_of( wrkerStripe.blockStates.begin(), wrkerStripe.blockStates.begin(), [](
const Stripe::RState s ) { return s == Stripe::FINALIZED; } );
1236 std::for_each( wrkerStripe.blockStates.begin(), wrkerStripe.blockStates.begin(), [](
Stripe::RState &s ) {
1237 if ( s != Stripe::FINALIZED)
1238 s = Stripe::PENDING;
1249 int maxworkerno = 0;
1251 for (
auto workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
1266 double ratio = worker->
_avgspeed / maxavg;
1269 ratio = ratio * ratio;
1272 XXX <<
"#" << worker->
_workerno <<
": too slow ("<< ratio <<
", " << worker->
_avgspeed <<
", #" << maxworkerno <<
": " << maxavg <<
"), going to sleep for " << ratio * 1000 <<
" ms" << endl;
1293#if CURLVERSION_AT_LEAST(7,15,5)
1294 curl_easy_setopt(worker->
_curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)(avg));
1326 WAR <<
"overall result" << endl;
1327 for (
auto workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
1345 MIL <<
"MediaMultiCurl::MediaMultiCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
1359 curl_multi_cleanup(
_multi);
1362 std::map<std::string, CURL *>::iterator it;
1365 CURL *easy = it->second;
1368 curl_easy_cleanup(easy);
1384 for (; sl; sl = sl->next)
1402 if ( curl_easy_getinfo(
_curl, CURLINFO_PRIVATE, &fp ) != CURLE_OK || !fp )
1404 if ( ftell( fp ) == 0 )
1409 long httpReturnCode = 0;
1410 if (curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0)
1414 bool ismetalink =
false;
1415 if (curl_easy_getinfo(
_curl, CURLINFO_CONTENT_TYPE, &ptr) == CURLE_OK && ptr)
1417 std::string ct = std::string(ptr);
1418 if (ct.find(
"application/x-zsync") == 0 || ct.find(
"application/metalink+xml") == 0 || ct.find(
"application/metalink4+xml") == 0)
1421 if (!ismetalink && dlnow < 256)
1430 DBG <<
"looks_like_meta_file: " << ismetalink << endl;
1447 if( assert_dir( dest.
dirname() ) )
1449 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
1459 ERR <<
"out of memory for temp file name" << endl;
1463 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1466 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1471 file = ::fdopen( tmp_fd,
"we" );
1474 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1477 tmp_fd.resetDispose();
1480 DBG <<
"dest: " << dest << endl;
1481 DBG <<
"temp: " << destNew << endl;
1486 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1487 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(target).mtime());
1491 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1492 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1498 curl_easy_setopt(
_curl, CURLOPT_PRIVATE, (*file) );
1505 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1506 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1508 curl_easy_setopt(
_curl, CURLOPT_PRIVATE, (
void *)0);
1511 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1512 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1514 curl_easy_setopt(
_curl, CURLOPT_PRIVATE, (
void *)0);
1515 long httpReturnCode = 0;
1516 CURLcode infoRet = curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode);
1517 if (infoRet == CURLE_OK)
1520 if ( httpReturnCode == 304
1523 DBG <<
"not modified: " <<
PathInfo(dest) << endl;
1529 WAR <<
"Could not get the response code." << endl;
1535 if (curl_easy_getinfo(
_curl, CURLINFO_CONTENT_TYPE, &ptr) == CURLE_OK && ptr)
1537 std::string ct = std::string(ptr);
1538 if (ct.find(
"application/x-zsync") == 0 )
1540 else if (ct.find(
"application/metalink+xml") == 0 || ct.find(
"application/metalink4+xml") == 0)
1554 bool userabort =
false;
1560 std::vector<Url> urls;
1563 parser.
parse( destNew );
1580 XXX <<
"With no blocks" << std::endl;
1587 XXX <<
"No filesize in metalink file and no expected filesize, aborting multicurl." << std::endl;
1592 Disabling
this workaround
for now, since we now
do zip ranges into bigger requests
1603 file = fopen((*destNew).c_str(),
"w+e");
1608 XXX <<
"reusing blocks from file " << target << endl;
1614 XXX <<
"reusing blocks from file " << failedFile << endl;
1622 XXX <<
"reusing blocks from file " << df << endl;
1632 userabort = ex.
errstr() ==
"User abort";
1643 WAR<<
"Failed to multifetch file " << ex <<
" falling back to single Curl download!" << std::endl;
1644 if (
PathInfo(destNew).size() >= 63336)
1646 ::unlink(failedFile.
asString().c_str());
1653 file = fopen((*destNew).c_str(),
"w+e");
1665 ERR <<
"Failed to chmod file " << destNew << endl;
1672 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1676 if ( rename( destNew, dest ) != 0 )
1678 ERR <<
"Rename failed" << endl;
1681 destNew.resetDispose();
1689 if (filesize == off_t(-1) && blklist.haveFilesize())
1690 filesize = blklist.getFilesize();
1691 if (!blklist.haveBlocks() && filesize != 0) {
1692 if ( filesize == -1 ) {
1697 MIL <<
"Generate blocklist, since there was none in the metalink file." << std::endl;
1702 while ( currOff < filesize ) {
1704 auto blksize = filesize - currOff ;
1705 if ( blksize > prefSize )
1708 blklist.addBlock( currOff, blksize );
1712 XXX <<
"Generated blocklist: " << std::endl << blklist << std::endl <<
" End blocklist " << std::endl;
1715 if (filesize == 0 || !blklist.numBlocks()) {
1724 _multi = curl_multi_init();
1730 std::vector<Url> myurllist;
1731 for (std::vector<Url>::iterator urliter = urllist->begin(); urliter != urllist->end(); ++urliter)
1735 std::string scheme = urliter->getScheme();
1736 if (scheme ==
"http" || scheme ==
"https" || scheme ==
"ftp" || scheme ==
"tftp")
1746 if (!myurllist.size())
1747 myurllist.push_back(baseurl);
1756 if (fseeko(fp, off_t(0), SEEK_SET))
1762 while ((l = fread(buf, 1,
sizeof(buf), fp)) > 0)
1770 return _dnsok.find(host) ==
_dnsok.end() ? false :
true;
1792 curl_easy_cleanup(oldeasy);
std::optional< KeyManagerCtx > _context
void resetDispose()
Set no dispose function.
Store and operate with byte count.
static const Unit MB
1000^2 Byte
SizeType blocks(ByteCount blocksize_r=K) const
Return number of blocks of size blocksize_r (default 1K).
static const Unit K
1024 Byte
std::string asString(unsigned field_width_r=0, unsigned unit_width_r=1) const
Auto selected Unit and precision.
Compute Message Digests (MD5, SHA1 etc)
bool update(const char *bytes, size_t len)
feed data into digest computation algorithm
Digest clone() const
Returns a clone of the current Digest and returns it.
Base class for Exception.
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.
Pathname repoCachePath() const
Path where the caches are kept (/var/cache/zypp)
static ZConfig & instance()
Singleton ctor.
Wrapper class for stat/lstat.
Pathname extend(const std::string &r) const
Append string r to the last component of the path.
Pathname dirname() const
Return all but the last component od this path.
const std::string & asString() const
String representation.
Pathname absolutename() const
Return this path, adding a leading '/' if relative.
The CurlMultiPartHandler class.
zypp::Url propagateQueryParams(zypp::Url url_r, const zypp::Url &template_r)
String related utilities and Regular expression matching.
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
int unlink(const Pathname &path)
Like 'unlink'.
int hardlinkCopy(const Pathname &oldpath, const Pathname &newpath)
Create newpath as hardlink or copy of oldpath.
std::string numstring(char n, int w=0)
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.
CURLMcode handleSocketActions(const std::vector< GPollFD > &actionsFds, int first=0)
std::vector< GPollFD > socks
std::optional< long > timeout_ms
AutoDispose<int> calling ::close
AutoDispose<FILE*> calling ::fclose
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.