14 #include <sys/types.h>
18 #include <arpa/inet.h>
26 #include <zypp/base/Logger.h>
28 #include <zypp-curl/parser/MetaLinkParser>
29 #include <zypp/ManagedFile.h>
30 #include <zypp-curl/private/curlhelper_p.h>
31 #include <zypp-curl/auth/CurlAuthData>
36 #undef CURLVERSION_AT_LEAST
37 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
46 class multifetchrequest;
60 bool recheckChecksum();
61 void disableCompetition();
64 void adddnsfd(fd_set &rset,
int &maxfd);
65 void dnsevent(fd_set &rset);
89 size_t writefunction(
void *ptr,
size_t size);
90 static size_t _writefunction(
void *ptr,
size_t size,
size_t nmemb,
void *stream);
92 size_t headerfunction(
char *ptr,
size_t size);
93 static size_t _headerfunction(
void *ptr,
size_t size,
size_t nmemb,
void *stream);
106 #define WORKER_STARTING 0
107 #define WORKER_LOOKUP 1
108 #define WORKER_FETCH 2
109 #define WORKER_DISCARD 3
110 #define WORKER_DONE 4
111 #define WORKER_SLEEP 5
112 #define WORKER_BROKEN 6
121 void run(std::vector<Url> &urllist);
176 if (gettimeofday(&tv, NULL))
178 return tv.tv_sec + tv.tv_usec / 1000000.;
182 multifetchworker::writefunction(
void *ptr,
size_t size)
190 len = size > _size ? _size : size;
197 if (_blkstart && _off == _blkstart)
202 (void)curl_easy_getinfo(_curl, CURLINFO_EFFECTIVE_URL, &effurl);
203 if (effurl && !strncasecmp(effurl,
"http", 4))
206 (void)curl_easy_getinfo(_curl, CURLINFO_RESPONSE_CODE, &statuscode);
207 if (statuscode != 206)
215 _request->_lastprogress = now;
221 if (_request->_blklist)
222 _dig.update((
const char *)ptr, len);
227 if (fseeko(_request->_fp, _off, SEEK_SET))
229 cnt = fwrite(ptr, 1, len, _request->_fp);
232 _request->_fetchedsize += cnt;
233 if (_request->_blklist)
234 _dig.update((
const char *)ptr, cnt);
244 multifetchworker::_writefunction(
void *ptr,
size_t size,
size_t nmemb,
void *stream)
251 multifetchworker::headerfunction(
char *p,
size_t size)
254 if (l > 9 && !strncasecmp(p,
"Location:", 9))
256 std::string line(p + 9, l - 9);
257 if (line[l - 10] ==
'\r')
258 line.erase(l - 10, 1);
259 XXX <<
"#" << _workerno <<
": redirecting to" << line << endl;
262 if (l <= 14 || l >= 128 || strncasecmp(p,
"Content-Range:", 14) != 0)
266 while (l && (*p ==
' ' || *p ==
'\t'))
268 if (l < 6 || strncasecmp(p,
"bytes", 5))
275 unsigned long long start, off, filesize;
276 if (sscanf(buf,
"%llu-%llu/%llu", &start, &off, &filesize) != 3)
278 if (_request->_filesize == (off_t)-1)
280 WAR <<
"#" << _workerno <<
": setting request filesize to " << filesize << endl;
281 _request->_filesize = filesize;
282 if (_request->_totalsize == 0 && !_request->_blklist)
283 _request->_totalsize = filesize;
285 if (_request->_filesize != (off_t)filesize)
287 XXX <<
"#" << _workerno <<
": filesize mismatch" << endl;
289 strncpy(_curlError,
"filesize mismatch", CURL_ERROR_SIZE);
295 multifetchworker::_headerfunction(
void *ptr,
size_t size,
size_t nmemb,
void *stream)
326 XXX <<
"reused worker from pool" << endl;
330 strncpy(
_curlError,
"curl_easy_init failed", CURL_ERROR_SIZE);
339 curl_easy_cleanup(
_curl);
342 strncpy(
_curlError,
"curl_easy_setopt failed", CURL_ERROR_SIZE);
345 curl_easy_setopt(
_curl, CURLOPT_PRIVATE,
this);
348 curl_easy_setopt(
_curl, CURLOPT_WRITEDATA,
this);
352 curl_easy_setopt(
_curl, CURLOPT_HEADERDATA,
this);
364 curl_easy_setopt(
_curl, CURLOPT_USERPWD,
_settings.userPassword().c_str());
365 std::string use_auth =
_settings.authType();
366 if (use_auth.empty())
367 use_auth =
"digest,basic";
368 long auth = CurlAuthData::auth_type_str2long(use_auth);
369 if( auth != CURLAUTH_NONE)
371 XXX <<
"#" <<
_workerno <<
": Enabling HTTP authentication methods: " << use_auth
372 <<
" (CURLOPT_HTTPAUTH=" << auth <<
")" << std::endl;
373 curl_easy_setopt(
_curl, CURLOPT_HTTPAUTH, auth);
388 #if CURLVERSION_AT_LEAST(7,15,5)
389 curl_easy_setopt(
_curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)0);
391 curl_easy_setopt(
_curl, CURLOPT_PRIVATE, (
void *)0);
392 curl_easy_setopt(
_curl, CURLOPT_WRITEFUNCTION, (
void *)0);
393 curl_easy_setopt(
_curl, CURLOPT_WRITEDATA, (
void *)0);
394 curl_easy_setopt(
_curl, CURLOPT_HEADERFUNCTION, (
void *)0);
395 curl_easy_setopt(
_curl, CURLOPT_HEADERDATA, (
void *)0);
399 curl_easy_cleanup(
_curl);
406 while (waitpid(
_pid, &status, 0) == -1)
423 const char *s = getenv(name.c_str());
424 return s && *s ? true :
false;
440 if (inet_pton(AF_INET, host.c_str(), addrbuf) == 1)
442 if (inet_pton(AF_INET6, host.c_str(), addrbuf) == 1)
453 if (schemeproxy !=
"http_proxy")
455 std::transform(schemeproxy.begin(), schemeproxy.end(), schemeproxy.begin(), ::toupper);
460 XXX <<
"checking DNS lookup of " << host << endl;
465 strncpy(
_curlError,
"DNS pipe creation failed", CURL_ERROR_SIZE);
469 if (
_pid == pid_t(-1))
475 strncpy(
_curlError,
"DNS checker fork failed", CURL_ERROR_SIZE);
482 struct addrinfo *ai, aihints;
483 memset(&aihints, 0,
sizeof(aihints));
484 aihints.ai_family = PF_UNSPEC;
485 int tstsock = socket(PF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
487 aihints.ai_family = PF_INET;
490 aihints.ai_socktype = SOCK_STREAM;
491 aihints.ai_flags = AI_CANONNAME;
494 alarm(connecttimeout);
495 signal(SIGALRM, SIG_DFL);
496 if (getaddrinfo(host.c_str(), NULL, &aihints, &ai))
522 while (waitpid(
_pid, &status, 0) == -1)
533 if (!WIFEXITED(status))
536 strncpy(
_curlError,
"DNS lookup failed", CURL_ERROR_SIZE);
540 int exitcode = WEXITSTATUS(status);
541 XXX <<
"#" <<
_workerno <<
": DNS lookup returned " << exitcode << endl;
545 strncpy(
_curlError,
"DNS lookup failed", CURL_ERROR_SIZE);
575 size_t cnt = l >
sizeof(buf) ?
sizeof(buf) : l;
590 XXX <<
"start stealing!" << endl;
594 std::list<multifetchworker *>::iterator workeriter =
_request->
_workers.begin();
601 if (worker->
_pass == -1)
660 XXX <<
"#" <<
_workerno <<
": going to sleep for " << sl * 1000 <<
" ms" << endl;
681 std::list<multifetchworker *>::iterator workeriter =
_request->
_workers.begin();
754 sprintf(rangebuf,
"%llu-", (
unsigned long long)
_blkstart);
762 strncpy(
_curlError,
"curl_easy_setopt range failed", CURL_ERROR_SIZE);
769 strncpy(
_curlError,
"curl_multi_add_handle failed", CURL_ERROR_SIZE);
819 for (
size_t blkno = 0; blkno < blklist->numBlocks(); blkno++)
821 MediaBlock blk = blklist->getBlock(blkno);
825 else if (filesize != off_t(-1))
831 for (std::list<multifetchworker *>::iterator workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
844 std::vector<Url>::iterator urliter = urllist.begin();
847 fd_set rset, wset, xset;
852 XXX <<
"finished!" << endl;
876 WAR <<
"No more active workers!" << endl;
878 for (std::list<multifetchworker *>::iterator workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
891 curl_multi_fdset(
_multi, &rset, &wset, &xset, &maxfd);
894 for (std::list<multifetchworker *>::iterator workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
895 (*workeriter)->adddnsfd(rset, maxfd);
906 for (std::list<multifetchworker *>::iterator workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
922 tv.tv_usec = sl * 1000000;
924 int r = select(maxfd + 1, &rset, &wset, &xset, &tv);
925 if (r == -1 && errno != EINTR)
928 for (std::list<multifetchworker *>::iterator workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
944 mcode = curl_multi_perform(
_multi, &tasks);
945 if (mcode == CURLM_CALL_MULTI_PERFORM)
947 if (mcode != CURLM_OK)
968 for (std::list<multifetchworker *>::iterator workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
977 XXX <<
"#" << worker->
_workerno <<
": sleep done, wake up" << endl;
986 while ((msg = curl_multi_info_read(
_multi, &nqueue)) != 0)
988 if (msg->msg != CURLMSG_DONE)
990 CURL *easy = msg->easy_handle;
991 CURLcode cc = msg->data.result;
993 if (curl_easy_getinfo(easy, CURLINFO_PRIVATE, &worker) != CURLE_OK)
1003 curl_multi_remove_handle(
_multi, easy);
1004 if (cc == CURLE_HTTP_RETURNED_ERROR)
1006 long statuscode = 0;
1007 (void)curl_easy_getinfo(easy, CURLINFO_RESPONSE_CODE, &statuscode);
1008 XXX <<
"HTTP status " << statuscode << endl;
1009 if (statuscode == 416 && !
_blklist)
1015 XXX <<
"#" << worker->
_workerno <<
": retrying with no end range" << endl;
1035 WAR <<
"#" << worker->
_workerno <<
": checksum error, disable worker" << endl;
1037 strncpy(worker->
_curlError,
"checksum error", CURL_ERROR_SIZE);
1051 XXX <<
"#" << worker->
_workerno <<
": recheck checksum error, refetch block" << endl;
1064 int maxworkerno = 0;
1066 for (std::list<multifetchworker *>::iterator workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
1081 double ratio = worker->
_avgspeed / maxavg;
1084 ratio = ratio * ratio;
1087 XXX <<
"#" << worker->
_workerno <<
": too slow ("<< ratio <<
", " << worker->
_avgspeed <<
", #" << maxworkerno <<
": " << maxavg <<
"), going to sleep for " << ratio * 1000 <<
" ms" << endl;
1108 #if CURLVERSION_AT_LEAST(7,15,5)
1109 curl_easy_setopt(worker->
_curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)(avg));
1151 WAR <<
"overall result" << endl;
1152 for (std::list<multifetchworker *>::iterator workeriter =
_workers.begin(); workeriter !=
_workers.end(); ++workeriter)
1166 MIL <<
"MediaMultiCurl::MediaMultiCurl(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
1180 curl_multi_cleanup(
_multi);
1183 std::map<std::string, CURL *>::iterator it;
1186 CURL *easy = it->second;
1189 curl_easy_cleanup(easy);
1205 for (; sl; sl = sl->next)
1214 while ((l = pread(fd, buf,
sizeof(buf) - 1, (off_t)0)) == -1 && errno == EINTR)
1220 while (*p ==
' ' || *p ==
'\t' || *p ==
'\r' || *p ==
'\n')
1222 if (!strncasecmp(p,
"<?xml", 5))
1224 while (*p && *p !=
'>')
1228 while (*p ==
' ' || *p ==
'\t' || *p ==
'\r' || *p ==
'\n')
1231 bool ret = !strncasecmp(p,
"<metalink", 9) ? true :
false;
1238 if ((fd = open(file.
asString().c_str(), O_RDONLY|O_CLOEXEC)) == -1)
1242 DBG <<
"looks_like_metalink(" << file <<
"): " << ret << endl;
1258 if ( curl_easy_getinfo(
_curl, CURLINFO_PRIVATE, &fp ) != CURLE_OK || !fp )
1260 if ( ftell( fp ) == 0 )
1265 long httpReturnCode = 0;
1266 if (curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0)
1270 bool ismetalink =
false;
1271 if (curl_easy_getinfo(
_curl, CURLINFO_CONTENT_TYPE, &ptr) == CURLE_OK && ptr)
1273 std::string ct = std::string(ptr);
1274 if (ct.find(
"application/metalink+xml") == 0 || ct.find(
"application/metalink4+xml") == 0)
1277 if (!ismetalink && dlnow < 256)
1286 DBG <<
"looks_like_metalink_fd: " << ismetalink << endl;
1305 DBG <<
"assert_dir " << dest.
dirname() <<
" failed" << endl;
1315 ERR <<
"out of memory for temp file name" << endl;
1319 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1322 ERR <<
"mkstemp failed for file '" << destNew <<
"'" << endl;
1327 file = ::fdopen( tmp_fd,
"we" );
1330 ERR <<
"fopen failed for file '" << destNew <<
"'" << endl;
1333 tmp_fd.resetDispose();
1336 DBG <<
"dest: " << dest << endl;
1337 DBG <<
"temp: " << destNew << endl;
1342 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1343 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, (
long)
PathInfo(target).mtime());
1347 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1348 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1354 curl_easy_setopt(
_curl, CURLOPT_PRIVATE, (*file) );
1361 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1362 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1364 curl_easy_setopt(
_curl, CURLOPT_PRIVATE, (
void *)0);
1367 curl_easy_setopt(
_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1368 curl_easy_setopt(
_curl, CURLOPT_TIMEVALUE, 0L);
1370 curl_easy_setopt(
_curl, CURLOPT_PRIVATE, (
void *)0);
1371 long httpReturnCode = 0;
1372 CURLcode infoRet = curl_easy_getinfo(
_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode);
1373 if (infoRet == CURLE_OK)
1376 if ( httpReturnCode == 304
1379 DBG <<
"not modified: " <<
PathInfo(dest) << endl;
1385 WAR <<
"Could not get the response code." << endl;
1388 bool ismetalink =
false;
1391 if (curl_easy_getinfo(
_curl, CURLINFO_CONTENT_TYPE, &ptr) == CURLE_OK && ptr)
1393 std::string ct = std::string(ptr);
1394 if (ct.find(
"application/metalink+xml") == 0 || ct.find(
"application/metalink4+xml") == 0)
1409 bool userabort =
false;
1416 MediaBlockList bl = mlp.getBlockList();
1422 if ( !bl.haveFilesize() && ! srcFile.
downloadSize() ) {
1423 XXX <<
"No filesize in metalink file and no expected filesize, aborting multicurl." << std::endl;
1424 ZYPP_THROW( MediaException(
"Multicurl requires filesize but none was provided.") );
1427 std::vector<Url> urls = mlp.getUrls();
1433 ZYPP_THROW( MediaException(
"Multicurl enabled but not enough mirrors provided") );
1437 file = fopen((*destNew).c_str(),
"w+e");
1442 XXX <<
"reusing blocks from file " << target << endl;
1443 bl.reuseBlocks(file, target.
asString());
1446 if (bl.haveChecksum(1) &&
PathInfo(failedFile).isExist())
1448 XXX <<
"reusing blocks from file " << failedFile << endl;
1449 bl.reuseBlocks(file, failedFile.
asString());
1456 XXX <<
"reusing blocks from file " <<
df << endl;
1464 catch (MediaCurlException &ex)
1466 userabort = ex.errstr() ==
"User abort";
1470 catch (MediaFileSizeExceededException &ex) {
1477 if (
PathInfo(destNew).size() >= 63336)
1486 file = fopen((*destNew).c_str(),
"w+e");
1495 ERR <<
"Failed to chmod file " << destNew << endl;
1502 ERR <<
"Fclose failed for file '" << destNew <<
"'" << endl;
1506 if (
rename( destNew, dest ) != 0 )
1508 ERR <<
"Rename failed" << endl;
1511 destNew.resetDispose();
1519 if (blklist && filesize == off_t(-1) && blklist->haveFilesize())
1520 filesize = blklist->getFilesize();
1521 if (blklist && !blklist->haveBlocks() && filesize != 0)
1523 if (blklist && (filesize == 0 || !blklist->numBlocks()))
1532 _multi = curl_multi_init();
1546 std::vector<Url> myurllist;
1547 for (std::vector<Url>::iterator urliter = urllist->begin(); urliter != urllist->end(); ++urliter)
1551 std::string scheme = urliter->getScheme();
1552 if (scheme ==
"http" || scheme ==
"https" || scheme ==
"ftp" || scheme ==
"tftp")
1555 myurllist.push_back(internal::propagateQueryParams(*urliter,
_url));
1562 if (!myurllist.size())
1563 myurllist.push_back(baseurl);
1570 if (!blklist || !blklist->haveFileChecksum())
1572 if (fseeko(fp, off_t(0), SEEK_SET))
1573 ZYPP_THROW(MediaCurlException(
url,
"fseeko",
"seek error"));
1575 blklist->createFileDigest(dig);
1578 while ((l = fread(buf, 1,
sizeof(buf), fp)) > 0)
1580 if (!blklist->verifyFileDigest(dig))
1581 ZYPP_THROW(MediaCurlException(
url,
"file verification failed",
"checksum error"));
1586 return _dnsok.find(host) ==
_dnsok.end() ? false :
true;
1608 curl_easy_cleanup(oldeasy);
std::optional< KeyManagerCtx > _context
AutoDispose< void * > _state
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
void resetDispose()
Set no dispose function.
Store and operate with byte count.
static const Unit MB
1000^2 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
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.
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
ByteCount df(const Pathname &path_r)
Report free disk space on a mounted file system.
int unlink(const Pathname &path)
Like 'unlink'.
int rename(const Pathname &oldpath, const Pathname &newpath)
Like 'rename'.
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
int hardlinkCopy(const Pathname &oldpath, const Pathname &newpath)
Create newpath as hardlink or copy of oldpath.
std::string numstring(char n, int w=0)
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<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.