libzypp 17.31.2
MediaMultiCurl.cc
Go to the documentation of this file.
1/*---------------------------------------------------------------------\
2| ____ _ __ __ ___ |
3| |__ / \ / / . \ . \ |
4| / / \ V /| _/ _/ |
5| / /__ | | | | | | |
6| /_____||_| |_| |_| |
7| |
8\---------------------------------------------------------------------*/
13#include <ctype.h>
14#include <sys/types.h>
15#include <signal.h>
16#include <sys/wait.h>
17#include <netdb.h>
18#include <arpa/inet.h>
19
20#include <vector>
21#include <iostream>
22#include <algorithm>
23
24
25#include <zypp/ZConfig.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>
32
33using std::endl;
34using namespace zypp::base;
35
36#undef CURLVERSION_AT_LEAST
37#define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
38
39namespace zypp {
40 namespace media {
41
42
44
45
46class multifetchrequest;
47
48// Hack: we derive from MediaCurl just to get the storage space for
49// settings, url, curlerrors and the like
50
52 friend class multifetchrequest;
53
54public:
55 multifetchworker(int no, multifetchrequest &request, const Url &url);
57 void nextjob();
58 void run();
59 bool checkChecksum();
60 bool recheckChecksum();
61 void disableCompetition();
62
63 void checkdns();
64 void adddnsfd(fd_set &rset, int &maxfd);
65 void dnsevent(fd_set &rset);
66
68
69 int _state;
71
72 size_t _blkno;
73 off_t _blkstart;
74 size_t _blksize;
76
79 off_t _received;
80
81 double _avgspeed;
82 double _maxspeed;
83
85
86private:
87 void stealjob();
88
89 size_t writefunction(void *ptr, size_t size);
90 static size_t _writefunction(void *ptr, size_t size, size_t nmemb, void *stream);
91
92 size_t headerfunction(char *ptr, size_t size);
93 static size_t _headerfunction(void *ptr, size_t size, size_t nmemb, void *stream);
94
96 int _pass;
97 std::string _urlbuf;
98 off_t _off;
99 size_t _size;
101
102 pid_t _pid;
104};
105
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
113
114
115
117public:
118 multifetchrequest(const MediaMultiCurl *context, const Pathname &filename, const Url &baseurl, CURLM *multi, FILE *fp, callback::SendReport<DownloadProgressReport> *report, MediaBlockList *blklist, off_t filesize);
120
121 void run(std::vector<Url> &urllist);
122
123protected:
124
125 static size_t makeBlksize ( size_t filesize );
126
127 friend class multifetchworker;
128
132
133 FILE *_fp;
135 MediaBlockList *_blklist;
137
138 CURLM *_multi;
139
140 std::list<multifetchworker *> _workers;
143
144 size_t _blkno;
145 size_t _defaultBlksize = 0; //< The blocksize to use if the metalink file does not specify one
146 off_t _blkoff;
155
158
162
163public:
164 double _timeout;
166 double _maxspeed;
168};
169
170constexpr auto MIN_REQ_MIRRS = 4;
171constexpr auto MAXURLS = 10;
172
174
175static double
177{
178 struct timeval tv;
179 if (gettimeofday(&tv, NULL))
180 return 0;
181 return tv.tv_sec + tv.tv_usec / 1000000.;
182}
183
184size_t
185multifetchworker::writefunction(void *ptr, size_t size)
186{
187 size_t len, cnt;
188 if (_state == WORKER_BROKEN)
189 return size ? 0 : 1;
190
191 double now = currentTime();
192
193 len = size > _size ? _size : size;
194 if (!len)
195 {
196 // kill this job?
197 return size;
198 }
199
200 if (_blkstart && _off == _blkstart)
201 {
202 // make sure that the server replied with "partial content"
203 // for http requests
204 char *effurl;
205 (void)curl_easy_getinfo(_curl, CURLINFO_EFFECTIVE_URL, &effurl);
206 if (effurl && !strncasecmp(effurl, "http", 4))
207 {
208 long statuscode = 0;
209 (void)curl_easy_getinfo(_curl, CURLINFO_RESPONSE_CODE, &statuscode);
210 if (statuscode != 206)
211 return size ? 0 : 1;
212 }
213 }
214
215 _blkreceived += len;
216 _received += len;
217
218 _request->_lastprogress = now;
219
220 if (_state == WORKER_DISCARD || !_request->_fp)
221 {
222 // block is no longer needed
223 // still calculate the checksum so that we can throw out bad servers
224 if (_request->_blklist)
225 _dig.update((const char *)ptr, len);
226 _off += len;
227 _size -= len;
228 return size;
229 }
230 if (fseeko(_request->_fp, _off, SEEK_SET))
231 return size ? 0 : 1;
232 cnt = fwrite(ptr, 1, len, _request->_fp);
233 if (cnt > 0)
234 {
235 _request->_fetchedsize += cnt;
236 if (_request->_blklist)
237 _dig.update((const char *)ptr, cnt);
238 _off += cnt;
239 _size -= cnt;
240 if (cnt == len)
241 return size;
242 }
243 return cnt;
244}
245
246size_t
247multifetchworker::_writefunction(void *ptr, size_t size, size_t nmemb, void *stream)
248{
249 multifetchworker *me = reinterpret_cast<multifetchworker *>(stream);
250 return me->writefunction(ptr, size * nmemb);
251}
252
253size_t
255{
256 size_t l = size;
257 if (l > 9 && !strncasecmp(p, "Location:", 9))
258 {
259 std::string line(p + 9, l - 9);
260 if (line[l - 10] == '\r')
261 line.erase(l - 10, 1);
262 XXX << "#" << _workerno << ": redirecting to" << line << endl;
263 return size;
264 }
265 if (l <= 14 || l >= 128 || strncasecmp(p, "Content-Range:", 14) != 0)
266 return size;
267 p += 14;
268 l -= 14;
269 while (l && (*p == ' ' || *p == '\t'))
270 p++, l--;
271 if (l < 6 || strncasecmp(p, "bytes", 5))
272 return size;
273 p += 5;
274 l -= 5;
275 char buf[128];
276 memcpy(buf, p, l);
277 buf[l] = 0;
278 unsigned long long start, off, filesize;
279 if (sscanf(buf, "%llu-%llu/%llu", &start, &off, &filesize) != 3)
280 return size;
281 if (_request->_filesize == (off_t)-1)
282 {
283 WAR << "#" << _workerno << ": setting request filesize to " << filesize << endl;
284 _request->_filesize = filesize;
285 if (_request->_totalsize == 0 && !_request->_blklist)
286 _request->_totalsize = filesize;
287 }
288 if (_request->_filesize != (off_t)filesize)
289 {
290 XXX << "#" << _workerno << ": filesize mismatch" << endl;
292 strncpy(_curlError, "filesize mismatch", CURL_ERROR_SIZE);
293 }
294 return size;
295}
296
297size_t
298multifetchworker::_headerfunction(void *ptr, size_t size, size_t nmemb, void *stream)
299{
300 multifetchworker *me = reinterpret_cast<multifetchworker *>(stream);
301 return me->headerfunction((char *)ptr, size * nmemb);
302}
303
305: MediaCurl(url, Pathname())
306{
307 _workerno = no;
308 _request = &request;
310 _competing = false;
311 _off = _blkstart = 0;
312 _size = _blksize = 0;
313 _pass = 0;
314 _blkno = 0;
315 _pid = 0;
316 _dnspipe = -1;
317 _blkreceived = 0;
318 _received = 0;
319 _blkstarttime = 0;
320 _avgspeed = 0;
321 _sleepuntil = 0;
323 _noendrange = false;
324
325 Url curlUrl( clearQueryString(url) );
326 _urlbuf = curlUrl.asString();
328 if (_curl)
329 XXX << "reused worker from pool" << endl;
330 if (!_curl && !(_curl = curl_easy_init()))
331 {
333 strncpy(_curlError, "curl_easy_init failed", CURL_ERROR_SIZE);
334 return;
335 }
336 try
337 {
338 setupEasy();
339 }
340 catch (Exception &ex)
341 {
342 curl_easy_cleanup(_curl);
343 _curl = 0;
345 strncpy(_curlError, "curl_easy_setopt failed", CURL_ERROR_SIZE);
346 return;
347 }
348 curl_easy_setopt(_curl, CURLOPT_PRIVATE, this);
349 curl_easy_setopt(_curl, CURLOPT_URL, _urlbuf.c_str());
350 curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, &_writefunction);
351 curl_easy_setopt(_curl, CURLOPT_WRITEDATA, this);
352 if (_request->_filesize == off_t(-1) || !_request->_blklist || !_request->_blklist->haveChecksum(0))
353 {
354 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, &_headerfunction);
355 curl_easy_setopt(_curl, CURLOPT_HEADERDATA, this);
356 }
357 // if this is the same host copy authorization
358 // (the host check is also what curl does when doing a redirect)
359 // (note also that unauthorized exceptions are thrown with the request host)
361 {
362 _settings.setUsername(_request->_context->_settings.username());
363 _settings.setPassword(_request->_context->_settings.password());
364 _settings.setAuthType(_request->_context->_settings.authType());
365 if ( _settings.userPassword().size() )
366 {
367 curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
368 std::string use_auth = _settings.authType();
369 if (use_auth.empty())
370 use_auth = "digest,basic"; // our default
371 long auth = CurlAuthData::auth_type_str2long(use_auth);
372 if( auth != CURLAUTH_NONE)
373 {
374 XXX << "#" << _workerno << ": Enabling HTTP authentication methods: " << use_auth
375 << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
376 curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, auth);
377 }
378 }
379 }
380 checkdns();
381}
382
384{
385 if (_curl)
386 {
388 curl_multi_remove_handle(_request->_multi, _curl);
390 {
391#if CURLVERSION_AT_LEAST(7,15,5)
392 curl_easy_setopt(_curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)0);
393#endif
394 curl_easy_setopt(_curl, CURLOPT_PRIVATE, (void *)0);
395 curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, (void *)0);
396 curl_easy_setopt(_curl, CURLOPT_WRITEDATA, (void *)0);
397 curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, (void *)0);
398 curl_easy_setopt(_curl, CURLOPT_HEADERDATA, (void *)0);
400 }
401 else
402 curl_easy_cleanup(_curl);
403 _curl = 0;
404 }
405 if (_pid)
406 {
407 kill(_pid, SIGKILL);
408 int status;
409 while (waitpid(_pid, &status, 0) == -1)
410 if (errno != EINTR)
411 break;
412 _pid = 0;
413 }
414 if (_dnspipe != -1)
415 {
416 close(_dnspipe);
417 _dnspipe = -1;
418 }
419 // the destructor in MediaCurl doesn't call disconnect() if
420 // the media is not attached, so we do it here manually
422}
423
424static inline bool env_isset(std::string name)
425{
426 const char *s = getenv(name.c_str());
427 return s && *s ? true : false;
428}
429
430void
432{
433 std::string host = _url.getHost();
434
435 if (host.empty())
436 return;
437
438 if (_request->_context->isDNSok(host))
439 return;
440
441 // no need to do dns checking for numeric hosts
442 char addrbuf[128];
443 if (inet_pton(AF_INET, host.c_str(), addrbuf) == 1)
444 return;
445 if (inet_pton(AF_INET6, host.c_str(), addrbuf) == 1)
446 return;
447
448 // no need to do dns checking if we use a proxy
449 if (!_settings.proxy().empty())
450 return;
451 if (env_isset("all_proxy") || env_isset("ALL_PROXY"))
452 return;
453 std::string schemeproxy = _url.getScheme() + "_proxy";
454 if (env_isset(schemeproxy))
455 return;
456 if (schemeproxy != "http_proxy")
457 {
458 std::transform(schemeproxy.begin(), schemeproxy.end(), schemeproxy.begin(), ::toupper);
459 if (env_isset(schemeproxy))
460 return;
461 }
462
463 XXX << "checking DNS lookup of " << host << endl;
464 int pipefds[2];
465 if (pipe(pipefds))
466 {
468 strncpy(_curlError, "DNS pipe creation failed", CURL_ERROR_SIZE);
469 return;
470 }
471 _pid = fork();
472 if (_pid == pid_t(-1))
473 {
474 close(pipefds[0]);
475 close(pipefds[1]);
476 _pid = 0;
478 strncpy(_curlError, "DNS checker fork failed", CURL_ERROR_SIZE);
479 return;
480 }
481 else if (_pid == 0)
482 {
483 close(pipefds[0]);
484 // XXX: close all other file descriptors
485 struct addrinfo *ai, aihints;
486 memset(&aihints, 0, sizeof(aihints));
487 aihints.ai_family = PF_UNSPEC;
488 int tstsock = socket(PF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
489 if (tstsock == -1)
490 aihints.ai_family = PF_INET;
491 else
492 close(tstsock);
493 aihints.ai_socktype = SOCK_STREAM;
494 aihints.ai_flags = AI_CANONNAME;
495 unsigned int connecttimeout = _request->_connect_timeout;
496 if (connecttimeout)
497 alarm(connecttimeout);
498 signal(SIGALRM, SIG_DFL);
499 if (getaddrinfo(host.c_str(), NULL, &aihints, &ai))
500 _exit(1);
501 _exit(0);
502 }
503 close(pipefds[1]);
504 _dnspipe = pipefds[0];
506}
507
508void
509multifetchworker::adddnsfd(fd_set &rset, int &maxfd)
510{
511 if (_state != WORKER_LOOKUP)
512 return;
513 FD_SET(_dnspipe, &rset);
514 if (maxfd < _dnspipe)
515 maxfd = _dnspipe;
516}
517
518void
520{
521
522 if (_state != WORKER_LOOKUP || !FD_ISSET(_dnspipe, &rset))
523 return;
524 int status;
525 while (waitpid(_pid, &status, 0) == -1)
526 {
527 if (errno != EINTR)
528 return;
529 }
530 _pid = 0;
531 if (_dnspipe != -1)
532 {
533 close(_dnspipe);
534 _dnspipe = -1;
535 }
536 if (!WIFEXITED(status))
537 {
539 strncpy(_curlError, "DNS lookup failed", CURL_ERROR_SIZE);
541 return;
542 }
543 int exitcode = WEXITSTATUS(status);
544 XXX << "#" << _workerno << ": DNS lookup returned " << exitcode << endl;
545 if (exitcode != 0)
546 {
548 strncpy(_curlError, "DNS lookup failed", CURL_ERROR_SIZE);
550 return;
551 }
553 nextjob();
554}
555
556bool
558{
559 // XXX << "checkChecksum block " << _blkno << endl;
560 if (!_blksize || !_request->_blklist)
561 return true;
562 return _request->_blklist->verifyDigest(_blkno, _dig);
563}
564
565bool
567{
568 // XXX << "recheckChecksum block " << _blkno << endl;
569 if (!_request->_fp || !_blksize || !_request->_blklist)
570 return true;
571 if (fseeko(_request->_fp, _blkstart, SEEK_SET))
572 return false;
573 char buf[4096];
574 size_t l = _blksize;
575 _request->_blklist->createDigest(_dig); // resets digest
576 while (l)
577 {
578 size_t cnt = l > sizeof(buf) ? sizeof(buf) : l;
579 if (fread(buf, cnt, 1, _request->_fp) != 1)
580 return false;
581 _dig.update(buf, cnt);
582 l -= cnt;
583 }
584 return _request->_blklist->verifyDigest(_blkno, _dig);
585}
586
587
588void
590{
591 if (!_request->_stealing)
592 {
593 XXX << "start stealing!" << endl;
594 _request->_stealing = true;
595 }
596 multifetchworker *best = 0;
597 std::list<multifetchworker *>::iterator workeriter = _request->_workers.begin();
598 double now = 0;
599 for (; workeriter != _request->_workers.end(); ++workeriter)
600 {
601 multifetchworker *worker = *workeriter;
602 if (worker == this)
603 continue;
604 if (worker->_pass == -1)
605 continue; // do not steal!
606 if (worker->_state == WORKER_DISCARD || worker->_state == WORKER_DONE || worker->_state == WORKER_SLEEP || !worker->_blksize)
607 continue; // do not steal finished jobs
608 if (!worker->_avgspeed && worker->_blkreceived)
609 {
610 if (!now)
611 now = currentTime();
612 if (now > worker->_blkstarttime)
613 worker->_avgspeed = worker->_blkreceived / (now - worker->_blkstarttime);
614 }
615 if (!best || best->_pass > worker->_pass)
616 {
617 best = worker;
618 continue;
619 }
620 if (best->_pass < worker->_pass)
621 continue;
622 // if it is the same block, we want to know the best worker, otherwise the worst
623 if (worker->_blkstart == best->_blkstart)
624 {
625 if ((worker->_blksize - worker->_blkreceived) * best->_avgspeed < (best->_blksize - best->_blkreceived) * worker->_avgspeed)
626 best = worker;
627 }
628 else
629 {
630 if ((worker->_blksize - worker->_blkreceived) * best->_avgspeed > (best->_blksize - best->_blkreceived) * worker->_avgspeed)
631 best = worker;
632 }
633 }
634 if (!best)
635 {
638 _request->_finished = true;
639 return;
640 }
641 // do not sleep twice
642 if (_state != WORKER_SLEEP)
643 {
644 if (!_avgspeed && _blkreceived)
645 {
646 if (!now)
647 now = currentTime();
648 if (now > _blkstarttime)
650 }
651
652 // lets see if we should sleep a bit
653 XXX << "me #" << _workerno << ": " << _avgspeed << ", size " << best->_blksize << endl;
654 XXX << "best #" << best->_workerno << ": " << best->_avgspeed << ", size " << (best->_blksize - best->_blkreceived) << endl;
655 if (_avgspeed && best->_avgspeed && best->_blksize - best->_blkreceived > 0 &&
656 (best->_blksize - best->_blkreceived) * _avgspeed < best->_blksize * best->_avgspeed)
657 {
658 if (!now)
659 now = currentTime();
660 double sl = (best->_blksize - best->_blkreceived) / best->_avgspeed * 2;
661 if (sl > 1)
662 sl = 1;
663 XXX << "#" << _workerno << ": going to sleep for " << sl * 1000 << " ms" << endl;
664 _sleepuntil = now + sl;
667 return;
668 }
669 }
670
671 _competing = true;
672 best->_competing = true;
673 _blkstart = best->_blkstart;
674 _blksize = best->_blksize;
675 best->_pass++;
676 _pass = best->_pass;
677 _blkno = best->_blkno;
678 run();
679}
680
681void
683{
684 std::list<multifetchworker *>::iterator workeriter = _request->_workers.begin();
685 for (; workeriter != _request->_workers.end(); ++workeriter)
686 {
687 multifetchworker *worker = *workeriter;
688 if (worker == this)
689 continue;
690 if (worker->_blkstart == _blkstart)
691 {
692 if (worker->_state == WORKER_FETCH)
693 worker->_state = WORKER_DISCARD;
694 worker->_pass = -1; /* do not steal this one, we already have it */
695 }
696 }
697}
698
699
700void
702{
703 const char *nochunk = getenv("ZYPP_NOCHUNK");
704 _noendrange = false;
705 if (_request->_stealing)
706 {
707 stealjob();
708 return;
709 }
710
711 MediaBlockList *blklist = _request->_blklist;
712 if (nochunk || !blklist)
713 {
715 if (_request->_filesize != off_t(-1))
716 {
717 if (nochunk) _blksize = _request->_filesize;
719 {
720 stealjob();
721 return;
722 }
726 }
727 DBG << "No BLOCKLIST falling back to chunk size: " << _request->_defaultBlksize << std::endl;
728 }
729 else
730 {
731 MediaBlock blk = blklist->getBlock(_request->_blkno);
732 while (_request->_blkoff >= (off_t)(blk.off + blk.size))
733 {
734 if (++_request->_blkno == blklist->numBlocks())
735 {
736 stealjob();
737 return;
738 }
739 blk = blklist->getBlock(_request->_blkno);
740 _request->_blkoff = blk.off;
741 }
742 _blksize = blk.off + blk.size - _request->_blkoff;
743 if (_blksize > _request->_defaultBlksize && !blklist->haveChecksum(_request->_blkno)) {
744 DBG << "Block: "<< _request->_blkno << " has no checksum falling back to default blocksize: " << _request->_defaultBlksize << std::endl;
746 }
747 }
751 run();
752}
753
754void
756{
757 char rangebuf[128];
758
760 return; // just in case...
761 if (_noendrange)
762 sprintf(rangebuf, "%llu-", (unsigned long long)_blkstart);
763 else
764 sprintf(rangebuf, "%llu-%llu", (unsigned long long)_blkstart, (unsigned long long)_blkstart + _blksize - 1);
765 XXX << "#" << _workerno << ": BLK " << _blkno << ":" << rangebuf << " " << _url << endl;
766 if (curl_easy_setopt(_curl, CURLOPT_RANGE, !_noendrange || _blkstart != 0 ? rangebuf : (char *)0) != CURLE_OK)
767 {
770 strncpy(_curlError, "curl_easy_setopt range failed", CURL_ERROR_SIZE);
771 return;
772 }
773 if (curl_multi_add_handle(_request->_multi, _curl) != CURLM_OK)
774 {
777 strncpy(_curlError, "curl_multi_add_handle failed", CURL_ERROR_SIZE);
778 return;
779 }
780 _request->_havenewjob = true;
781 _off = _blkstart;
782 _size = _blksize;
783 if (_request->_blklist)
784 _request->_blklist->createDigest(_dig); // resets digest
786
787 double now = currentTime();
788 _blkstarttime = now;
789 _blkreceived = 0;
790}
791
792
794
795
796multifetchrequest::multifetchrequest(const MediaMultiCurl *context, const Pathname &filename, const Url &baseurl, CURLM *multi, FILE *fp, callback::SendReport<DownloadProgressReport> *report, MediaBlockList *blklist, off_t filesize) : _context(context), _filename(filename), _baseurl(baseurl)
797{
798 _fp = fp;
799 _report = report;
800 _blklist = blklist;
801 _filesize = filesize;
802 _defaultBlksize = makeBlksize( filesize );
803 _multi = multi;
804 _stealing = false;
805 _havenewjob = false;
806 _blkno = 0;
807 if (_blklist)
808 _blkoff = _blklist->getBlock(0).off;
809 else
810 _blkoff = 0;
811 _activeworkers = 0;
812 _lookupworkers = 0;
813 _sleepworkers = 0;
814 _minsleepuntil = 0;
815 _finished = false;
816 _fetchedsize = 0;
818 _totalsize = 0;
821 _periodavg = 0;
822 _timeout = 0;
824 _maxspeed = 0;
825 _maxworkers = 0;
826 if (blklist)
827 {
828 for (size_t blkno = 0; blkno < blklist->numBlocks(); blkno++)
829 {
830 MediaBlock blk = blklist->getBlock(blkno);
831 _totalsize += blk.size;
832 }
833 }
834 else if (filesize != off_t(-1))
835 _totalsize = filesize;
836}
837
839{
840 for (std::list<multifetchworker *>::iterator workeriter = _workers.begin(); workeriter != _workers.end(); ++workeriter)
841 {
842 multifetchworker *worker = *workeriter;
843 *workeriter = NULL;
844 delete worker;
845 }
846 _workers.clear();
847}
848
849void
850multifetchrequest::run(std::vector<Url> &urllist)
851{
852 int workerno = 0;
853 std::vector<Url>::iterator urliter = urllist.begin();
854 for (;;)
855 {
856 fd_set rset, wset, xset;
857 int maxfd, nqueue;
858
859 if (_finished)
860 {
861 XXX << "finished!" << endl;
862 break;
863 }
864
865 if ((int)_activeworkers < _maxworkers && urliter != urllist.end() && _workers.size() < MAXURLS)
866 {
867 // spawn another worker!
868 multifetchworker *worker = new multifetchworker(workerno++, *this, *urliter);
869 _workers.push_back(worker);
870 if (worker->_state != WORKER_BROKEN)
871 {
873 if (worker->_state != WORKER_LOOKUP)
874 {
875 worker->nextjob();
876 }
877 else
879 }
880 ++urliter;
881 continue;
882 }
883 if (!_activeworkers)
884 {
885 WAR << "No more active workers!" << endl;
886 // show the first worker error we find
887 for (std::list<multifetchworker *>::iterator workeriter = _workers.begin(); workeriter != _workers.end(); ++workeriter)
888 {
889 if ((*workeriter)->_state != WORKER_BROKEN)
890 continue;
891 ZYPP_THROW(MediaCurlException(_baseurl, "Server error", (*workeriter)->_curlError));
892 }
893 break;
894 }
895
896 FD_ZERO(&rset);
897 FD_ZERO(&wset);
898 FD_ZERO(&xset);
899
900 curl_multi_fdset(_multi, &rset, &wset, &xset, &maxfd);
901
902 if (_lookupworkers)
903 for (std::list<multifetchworker *>::iterator workeriter = _workers.begin(); workeriter != _workers.end(); ++workeriter)
904 (*workeriter)->adddnsfd(rset, maxfd);
905
906 timeval tv;
907 // if we added a new job we have to call multi_perform once
908 // to make it show up in the fd set. do not sleep in this case.
909 tv.tv_sec = 0;
910 tv.tv_usec = _havenewjob ? 0 : 200000;
912 {
913 if (_minsleepuntil == 0)
914 {
915 for (std::list<multifetchworker *>::iterator workeriter = _workers.begin(); workeriter != _workers.end(); ++workeriter)
916 {
917 multifetchworker *worker = *workeriter;
918 if (worker->_state != WORKER_SLEEP)
919 continue;
920 if (!_minsleepuntil || _minsleepuntil > worker->_sleepuntil)
921 _minsleepuntil = worker->_sleepuntil;
922 }
923 }
924 double sl = _minsleepuntil - currentTime();
925 if (sl < 0)
926 {
927 sl = 0;
928 _minsleepuntil = 0;
929 }
930 if (sl < .2)
931 tv.tv_usec = sl * 1000000;
932 }
933 int r = select(maxfd + 1, &rset, &wset, &xset, &tv);
934 if (r == -1 && errno != EINTR)
935 ZYPP_THROW(MediaCurlException(_baseurl, "select() failed", "unknown error"));
936 if (r != 0 && _lookupworkers)
937 for (std::list<multifetchworker *>::iterator workeriter = _workers.begin(); workeriter != _workers.end(); ++workeriter)
938 {
939 multifetchworker *worker = *workeriter;
940 if (worker->_state != WORKER_LOOKUP)
941 continue;
942 (*workeriter)->dnsevent(rset);
943 if (worker->_state != WORKER_LOOKUP)
945 }
946 _havenewjob = false;
947
948 // run curl
949 for (;;)
950 {
951 CURLMcode mcode;
952 int tasks;
953 mcode = curl_multi_perform(_multi, &tasks);
954 if (mcode == CURLM_CALL_MULTI_PERFORM)
955 continue;
956 if (mcode != CURLM_OK)
957 ZYPP_THROW(MediaCurlException(_baseurl, "curl_multi_perform", "unknown error"));
958 break;
959 }
960
961 double now = currentTime();
962
963 // update periodavg
964 if (now > _lastperiodstart + .5)
965 {
966 if (!_periodavg)
968 else
971 _lastperiodstart = now;
972 }
973
974 // wake up sleepers
975 if (_sleepworkers)
976 {
977 for (std::list<multifetchworker *>::iterator workeriter = _workers.begin(); workeriter != _workers.end(); ++workeriter)
978 {
979 multifetchworker *worker = *workeriter;
980 if (worker->_state != WORKER_SLEEP)
981 continue;
982 if (worker->_sleepuntil > now)
983 continue;
984 if (_minsleepuntil == worker->_sleepuntil)
985 _minsleepuntil = 0;
986 XXX << "#" << worker->_workerno << ": sleep done, wake up" << endl;
988 // nextjob chnages the state
989 worker->nextjob();
990 }
991 }
992
993 // collect all curl results, reschedule new jobs
994 CURLMsg *msg;
995 while ((msg = curl_multi_info_read(_multi, &nqueue)) != 0)
996 {
997 if (msg->msg != CURLMSG_DONE)
998 continue;
999 CURL *easy = msg->easy_handle;
1000 CURLcode cc = msg->data.result;
1001 multifetchworker *worker;
1002 if (curl_easy_getinfo(easy, CURLINFO_PRIVATE, &worker) != CURLE_OK)
1003 ZYPP_THROW(MediaCurlException(_baseurl, "curl_easy_getinfo", "unknown error"));
1004 if (worker->_blkreceived && now > worker->_blkstarttime)
1005 {
1006 if (worker->_avgspeed)
1007 worker->_avgspeed = (worker->_avgspeed + worker->_blkreceived / (now - worker->_blkstarttime)) / 2;
1008 else
1009 worker->_avgspeed = worker->_blkreceived / (now - worker->_blkstarttime);
1010 }
1011 XXX << "#" << worker->_workerno << ": BLK " << worker->_blkno << " done code " << cc << " speed " << worker->_avgspeed << endl;
1012 curl_multi_remove_handle(_multi, easy);
1013 if (cc == CURLE_HTTP_RETURNED_ERROR)
1014 {
1015 long statuscode = 0;
1016 (void)curl_easy_getinfo(easy, CURLINFO_RESPONSE_CODE, &statuscode);
1017 XXX << "HTTP status " << statuscode << endl;
1018 if (statuscode == 416 && !_blklist) /* Range error */
1019 {
1020 if (_filesize == off_t(-1))
1021 {
1022 if (!worker->_noendrange)
1023 {
1024 XXX << "#" << worker->_workerno << ": retrying with no end range" << endl;
1025 worker->_noendrange = true;
1026 worker->run();
1027 continue;
1028 }
1029 worker->_noendrange = false;
1030 worker->stealjob();
1031 continue;
1032 }
1033 if (worker->_blkstart >= _filesize)
1034 {
1035 worker->nextjob();
1036 continue;
1037 }
1038 }
1039 }
1040 if (cc == 0)
1041 {
1042 if (!worker->checkChecksum())
1043 {
1044 WAR << "#" << worker->_workerno << ": checksum error, disable worker" << endl;
1045 worker->_state = WORKER_BROKEN;
1046 strncpy(worker->_curlError, "checksum error", CURL_ERROR_SIZE);
1048 continue;
1049 }
1050 if (worker->_state == WORKER_FETCH)
1051 {
1052 if (worker->_competing)
1053 {
1054 worker->disableCompetition();
1055 // multiple workers wrote into this block. We already know that our
1056 // data was correct, but maybe some other worker overwrote our data
1057 // with something broken. Thus we have to re-check the block.
1058 if (!worker->recheckChecksum())
1059 {
1060 XXX << "#" << worker->_workerno << ": recheck checksum error, refetch block" << endl;
1061 // re-fetch! No need to worry about the bad workers,
1062 // they will now be set to DISCARD. At the end of their block
1063 // they will notice that they wrote bad data and go into BROKEN.
1064 worker->run();
1065 continue;
1066 }
1067 }
1068 _fetchedgoodsize += worker->_blksize;
1069 }
1070
1071 // make bad workers sleep a little
1072 double maxavg = 0;
1073 int maxworkerno = 0;
1074 int numbetter = 0;
1075 for (std::list<multifetchworker *>::iterator workeriter = _workers.begin(); workeriter != _workers.end(); ++workeriter)
1076 {
1077 multifetchworker *oworker = *workeriter;
1078 if (oworker->_state == WORKER_BROKEN)
1079 continue;
1080 if (oworker->_avgspeed > maxavg)
1081 {
1082 maxavg = oworker->_avgspeed;
1083 maxworkerno = oworker->_workerno;
1084 }
1085 if (oworker->_avgspeed > worker->_avgspeed)
1086 numbetter++;
1087 }
1088 if (maxavg && !_stealing)
1089 {
1090 double ratio = worker->_avgspeed / maxavg;
1091 ratio = 1 - ratio;
1092 if (numbetter < 3) // don't sleep that much if we're in the top two
1093 ratio = ratio * ratio;
1094 if (ratio > .01)
1095 {
1096 XXX << "#" << worker->_workerno << ": too slow ("<< ratio << ", " << worker->_avgspeed << ", #" << maxworkerno << ": " << maxavg << "), going to sleep for " << ratio * 1000 << " ms" << endl;
1097 worker->_sleepuntil = now + ratio;
1098 worker->_state = WORKER_SLEEP;
1099 _sleepworkers++;
1100 continue;
1101 }
1102 }
1103
1104 // do rate control (if requested)
1105 // should use periodavg, but that's not what libcurl does
1106 if (_maxspeed && now > _starttime)
1107 {
1108 double avg = _fetchedsize / (now - _starttime);
1109 avg = worker->_maxspeed * _maxspeed / avg;
1110 if (avg < _maxspeed / _maxworkers)
1111 avg = _maxspeed / _maxworkers;
1112 if (avg > _maxspeed)
1113 avg = _maxspeed;
1114 if (avg < 1024)
1115 avg = 1024;
1116 worker->_maxspeed = avg;
1117#if CURLVERSION_AT_LEAST(7,15,5)
1118 curl_easy_setopt(worker->_curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)(avg));
1119#endif
1120 }
1121
1122 worker->nextjob();
1123 }
1124 else
1125 {
1126 worker->_state = WORKER_BROKEN;
1128 if (!_activeworkers && !(urliter != urllist.end() && _workers.size() < MAXURLS))
1129 {
1130 // end of workers reached! goodbye!
1131 worker->evaluateCurlCode(Pathname(), cc, false);
1132 }
1133 }
1134
1135 if ( _filesize > 0 && _fetchedgoodsize > _filesize ) {
1136 ZYPP_THROW(MediaFileSizeExceededException(_baseurl, _filesize));
1137 }
1138 }
1139
1140 // send report
1141 if (_report)
1142 {
1143 int percent = _totalsize ? (100 * (_fetchedgoodsize + _fetchedsize)) / (_totalsize + _fetchedsize) : 0;
1144
1145 double avg = 0;
1146 if (now > _starttime)
1147 avg = _fetchedsize / (now - _starttime);
1148 if (!(*(_report))->progress(percent, _baseurl, avg, _lastperiodstart == _starttime ? avg : _periodavg))
1149 ZYPP_THROW(MediaCurlException(_baseurl, "User abort", "cancelled"));
1150 }
1151
1152 if (_timeout && now - _lastprogress > _timeout)
1153 break;
1154 }
1155
1156 if (!_finished)
1157 ZYPP_THROW(MediaTimeoutException(_baseurl));
1158
1159 // print some download stats
1160 WAR << "overall result" << endl;
1161 for (std::list<multifetchworker *>::iterator workeriter = _workers.begin(); workeriter != _workers.end(); ++workeriter)
1162 {
1163 multifetchworker *worker = *workeriter;
1164 WAR << "#" << worker->_workerno << ": state: " << worker->_state << " received: " << worker->_received << " url: " << worker->_url << endl;
1165 }
1166}
1167
1168inline size_t multifetchrequest::makeBlksize ( size_t filesize )
1169{
1170 // this case should never happen because we never start a multi download if we do not know the filesize beforehand
1171 if ( filesize == 0 ) return 2 * 1024 * 1024;
1172 else if ( filesize < 2*256*1024 ) return filesize;
1173 else if ( filesize < 8*1024*1024 ) return 256*1024;
1174 else if ( filesize < 256*1024*1024 ) return 1024*1024;
1175 return 4*1024*1024;
1176}
1177
1179
1180
1181MediaMultiCurl::MediaMultiCurl(const Url &url_r, const Pathname & attach_point_hint_r)
1182 : MediaCurl(url_r, attach_point_hint_r)
1183{
1184 MIL << "MediaMultiCurl::MediaMultiCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
1185 _multi = 0;
1187}
1188
1190{
1192 {
1193 curl_slist_free_all(_customHeadersMetalink);
1195 }
1196 if (_multi)
1197 {
1198 curl_multi_cleanup(_multi);
1199 _multi = 0;
1200 }
1201 std::map<std::string, CURL *>::iterator it;
1202 for (it = _easypool.begin(); it != _easypool.end(); it++)
1203 {
1204 CURL *easy = it->second;
1205 if (easy)
1206 {
1207 curl_easy_cleanup(easy);
1208 it->second = NULL;
1209 }
1210 }
1211}
1212
1214{
1216
1218 {
1219 curl_slist_free_all(_customHeadersMetalink);
1221 }
1222 struct curl_slist *sl = _customHeaders;
1223 for (; sl; sl = sl->next)
1224 _customHeadersMetalink = curl_slist_append(_customHeadersMetalink, sl->data);
1225 _customHeadersMetalink = curl_slist_append(_customHeadersMetalink, "Accept: */*, application/metalink+xml, application/metalink4+xml");
1226}
1227
1228static bool looks_like_metalink_fd(int fd)
1229{
1230 char buf[256], *p;
1231 int l;
1232 while ((l = pread(fd, buf, sizeof(buf) - 1, (off_t)0)) == -1 && errno == EINTR)
1233 ;
1234 if (l == -1)
1235 return 0;
1236 buf[l] = 0;
1237 p = buf;
1238 while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
1239 p++;
1240 if (!strncasecmp(p, "<?xml", 5))
1241 {
1242 while (*p && *p != '>')
1243 p++;
1244 if (*p == '>')
1245 p++;
1246 while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
1247 p++;
1248 }
1249 bool ret = !strncasecmp(p, "<metalink", 9) ? true : false;
1250 return ret;
1251}
1252
1253static bool looks_like_metalink(const Pathname & file)
1254{
1255 int fd;
1256 if ((fd = open(file.asString().c_str(), O_RDONLY|O_CLOEXEC)) == -1)
1257 return false;
1258 bool ret = looks_like_metalink_fd(fd);
1259 close(fd);
1260 DBG << "looks_like_metalink(" << file << "): " << ret << endl;
1261 return ret;
1262}
1263
1264// here we try to suppress all progress coming from a metalink download
1265// bsc#1021291: Nevertheless send alive trigger (without stats), so UIs
1266// are able to abort a hanging metalink download via callback response.
1267int MediaMultiCurl::progressCallback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
1268{
1270 if (!_curl)
1271 return MediaCurl::aliveCallback(clientp, dltotal, dlnow, ultotal, ulnow);
1272
1273 // bsc#408814: Don't report any sizes before we don't have data on disk. Data reported
1274 // due to redirection etc. are not interesting, but may disturb filesize checks.
1275 FILE *fp = 0;
1276 if ( curl_easy_getinfo( _curl, CURLINFO_PRIVATE, &fp ) != CURLE_OK || !fp )
1277 return MediaCurl::aliveCallback( clientp, dltotal, dlnow, ultotal, ulnow );
1278 if ( ftell( fp ) == 0 )
1279 return MediaCurl::aliveCallback( clientp, dltotal, 0.0, ultotal, ulnow );
1280
1281 // (no longer needed due to the filesize check above?)
1282 // work around curl bug that gives us old data
1283 long httpReturnCode = 0;
1284 if (curl_easy_getinfo(_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) != CURLE_OK || httpReturnCode == 0)
1285 return MediaCurl::aliveCallback(clientp, dltotal, dlnow, ultotal, ulnow);
1286
1287 char *ptr = NULL;
1288 bool ismetalink = false;
1289 if (curl_easy_getinfo(_curl, CURLINFO_CONTENT_TYPE, &ptr) == CURLE_OK && ptr)
1290 {
1291 std::string ct = std::string(ptr);
1292 if (ct.find("application/metalink+xml") == 0 || ct.find("application/metalink4+xml") == 0)
1293 ismetalink = true;
1294 }
1295 if (!ismetalink && dlnow < 256)
1296 {
1297 // can't tell yet, ...
1298 return MediaCurl::aliveCallback(clientp, dltotal, dlnow, ultotal, ulnow);
1299 }
1300 if (!ismetalink)
1301 {
1302 fflush(fp);
1303 ismetalink = looks_like_metalink_fd(fileno(fp));
1304 DBG << "looks_like_metalink_fd: " << ismetalink << endl;
1305 }
1306 if (ismetalink)
1307 {
1308 // this is a metalink file change the expected filesize
1310 // we're downloading the metalink file. Just trigger aliveCallbacks
1311 curl_easy_setopt(_curl, CURLOPT_PROGRESSFUNCTION, &MediaCurl::aliveCallback);
1312 return MediaCurl::aliveCallback(clientp, dltotal, dlnow, ultotal, ulnow);
1313 }
1314 curl_easy_setopt(_curl, CURLOPT_PROGRESSFUNCTION, &MediaCurl::progressCallback);
1315 return MediaCurl::progressCallback(clientp, dltotal, dlnow, ultotal, ulnow);
1316}
1317
1318void MediaMultiCurl::doGetFileCopy( const OnMediaLocation &srcFile , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1319{
1320 Pathname dest = target.absolutename();
1321 if( assert_dir( dest.dirname() ) )
1322 {
1323 DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1324 ZYPP_THROW( MediaSystemException(getFileUrl(srcFile.filename()), "System error on " + dest.dirname().asString()) );
1325 }
1326
1327 ManagedFile destNew { target.extend( ".new.zypp.XXXXXX" ) };
1328 AutoFILE file;
1329 {
1330 AutoFREE<char> buf { ::strdup( (*destNew).c_str() ) };
1331 if( ! buf )
1332 {
1333 ERR << "out of memory for temp file name" << endl;
1334 ZYPP_THROW(MediaSystemException(getFileUrl(srcFile.filename()), "out of memory for temp file name"));
1335 }
1336
1337 AutoFD tmp_fd { ::mkostemp( buf, O_CLOEXEC ) };
1338 if( tmp_fd == -1 )
1339 {
1340 ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1341 ZYPP_THROW(MediaWriteException(destNew));
1342 }
1343 destNew = ManagedFile( (*buf), filesystem::unlink );
1344
1345 file = ::fdopen( tmp_fd, "we" );
1346 if ( ! file )
1347 {
1348 ERR << "fopen failed for file '" << destNew << "'" << endl;
1349 ZYPP_THROW(MediaWriteException(destNew));
1350 }
1351 tmp_fd.resetDispose(); // don't close it here! ::fdopen moved ownership to file
1352 }
1353
1354 DBG << "dest: " << dest << endl;
1355 DBG << "temp: " << destNew << endl;
1356
1357 // set IFMODSINCE time condition (no download if not modified)
1358 if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1359 {
1360 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1361 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1362 }
1363 else
1364 {
1365 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1366 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1367 }
1368 // change header to include Accept: metalink
1369 curl_easy_setopt(_curl, CURLOPT_HTTPHEADER, _customHeadersMetalink);
1370 // change to our own progress funcion
1371 curl_easy_setopt(_curl, CURLOPT_PROGRESSFUNCTION, &progressCallback);
1372 curl_easy_setopt(_curl, CURLOPT_PRIVATE, (*file) ); // important to pass the FILE* explicitly (passing through varargs)
1373 try
1374 {
1375 MediaCurl::doGetFileCopyFile( srcFile, dest, file, report, options );
1376 }
1377 catch (Exception &ex)
1378 {
1379 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1380 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1381 curl_easy_setopt(_curl, CURLOPT_HTTPHEADER, _customHeaders);
1382 curl_easy_setopt(_curl, CURLOPT_PRIVATE, (void *)0);
1383 ZYPP_RETHROW(ex);
1384 }
1385 curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1386 curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1387 curl_easy_setopt(_curl, CURLOPT_HTTPHEADER, _customHeaders);
1388 curl_easy_setopt(_curl, CURLOPT_PRIVATE, (void *)0);
1389 long httpReturnCode = 0;
1390 CURLcode infoRet = curl_easy_getinfo(_curl, CURLINFO_RESPONSE_CODE, &httpReturnCode);
1391 if (infoRet == CURLE_OK)
1392 {
1393 DBG << "HTTP response: " + str::numstring(httpReturnCode) << endl;
1394 if ( httpReturnCode == 304
1395 || ( httpReturnCode == 213 && _url.getScheme() == "ftp" ) ) // not modified
1396 {
1397 DBG << "not modified: " << PathInfo(dest) << endl;
1398 return;
1399 }
1400 }
1401 else
1402 {
1403 WAR << "Could not get the response code." << endl;
1404 }
1405
1406 bool ismetalink = false;
1407
1408 char *ptr = NULL;
1409 if (curl_easy_getinfo(_curl, CURLINFO_CONTENT_TYPE, &ptr) == CURLE_OK && ptr)
1410 {
1411 std::string ct = std::string(ptr);
1412 if (ct.find("application/metalink+xml") == 0 || ct.find("application/metalink4+xml") == 0)
1413 ismetalink = true;
1414 }
1415
1416 if (!ismetalink)
1417 {
1418 // some proxies do not store the content type, so also look at the file to find
1419 // out if we received a metalink (bnc#649925)
1420 fflush(file);
1421 if (looks_like_metalink(destNew))
1422 ismetalink = true;
1423 }
1424
1425 if (ismetalink)
1426 {
1427 bool userabort = false;
1428 Pathname failedFile = ZConfig::instance().repoCachePath() / "MultiCurl.failed";
1429 file = nullptr; // explicitly close destNew before the parser reads it.
1430 try
1431 {
1432 MetaLinkParser mlp;
1433 mlp.parse(destNew);
1434 MediaBlockList bl = mlp.getBlockList();
1435
1436 /*
1437 * gihub issue libzipp:#277 Multicurl backend breaks with MirrorCache and Metalink with unknown filesize.
1438 * Fall back to a normal download if we have no knowledge about the filesize we want to download.
1439 */
1440 if ( !bl.haveFilesize() && ! srcFile.downloadSize() ) {
1441 XXX << "No filesize in metalink file and no expected filesize, aborting multicurl." << std::endl;
1442 ZYPP_THROW( MediaException("Multicurl requires filesize but none was provided.") );
1443 }
1444
1445 std::vector<Url> urls = mlp.getUrls();
1446 /*
1447 * bsc#1191609 In certain locations we do not receive a suitable number of metalink mirrors, and might even
1448 * download chunks serially from one and the same server. In those cases we need to fall back to a normal download.
1449 */
1450 if ( urls.size() < MIN_REQ_MIRRS ) {
1451 ZYPP_THROW( MediaException("Multicurl enabled but not enough mirrors provided") );
1452 }
1453
1454 XXX << bl << endl;
1455 file = fopen((*destNew).c_str(), "w+e");
1456 if (!file)
1457 ZYPP_THROW(MediaWriteException(destNew));
1458 if (PathInfo(target).isExist())
1459 {
1460 XXX << "reusing blocks from file " << target << endl;
1461 bl.reuseBlocks(file, target.asString());
1462 XXX << bl << endl;
1463 }
1464 if (bl.haveChecksum(1) && PathInfo(failedFile).isExist())
1465 {
1466 XXX << "reusing blocks from file " << failedFile << endl;
1467 bl.reuseBlocks(file, failedFile.asString());
1468 XXX << bl << endl;
1469 filesystem::unlink(failedFile);
1470 }
1471 Pathname df = srcFile.deltafile();
1472 if (!df.empty())
1473 {
1474 XXX << "reusing blocks from file " << df << endl;
1475 bl.reuseBlocks(file, df.asString());
1476 XXX << bl << endl;
1477 }
1478 try
1479 {
1480 multifetch(srcFile.filename(), file, &urls, &report, &bl, srcFile.downloadSize());
1481 }
1482 catch (MediaCurlException &ex)
1483 {
1484 userabort = ex.errstr() == "User abort";
1485 ZYPP_RETHROW(ex);
1486 }
1487 }
1488 catch (MediaFileSizeExceededException &ex) {
1489 ZYPP_RETHROW(ex);
1490 }
1491 catch (Exception &ex)
1492 {
1493 // something went wrong. fall back to normal download
1494 file = nullptr; // explicitly close destNew before moving it
1495 if (PathInfo(destNew).size() >= 63336)
1496 {
1497 ::unlink(failedFile.asString().c_str());
1498 filesystem::hardlinkCopy(destNew, failedFile);
1499 }
1500 if (userabort)
1501 {
1502 ZYPP_RETHROW(ex);
1503 }
1504 file = fopen((*destNew).c_str(), "w+e");
1505 if (!file)
1506 ZYPP_THROW(MediaWriteException(destNew));
1507 MediaCurl::doGetFileCopyFile(srcFile, dest, file, report, options | OPTION_NO_REPORT_START);
1508 }
1509 }
1510
1511 if (::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 )))
1512 {
1513 ERR << "Failed to chmod file " << destNew << endl;
1514 }
1515
1516 file.resetDispose(); // we're going to close it manually here
1517 if (::fclose(file))
1518 {
1519 filesystem::unlink(destNew);
1520 ERR << "Fclose failed for file '" << destNew << "'" << endl;
1521 ZYPP_THROW(MediaWriteException(destNew));
1522 }
1523
1524 if ( rename( destNew, dest ) != 0 )
1525 {
1526 ERR << "Rename failed" << endl;
1527 ZYPP_THROW(MediaWriteException(dest));
1528 }
1529 destNew.resetDispose(); // no more need to unlink it
1530
1531 DBG << "done: " << PathInfo(dest) << endl;
1532}
1533
1534void MediaMultiCurl::multifetch(const Pathname & filename, FILE *fp, std::vector<Url> *urllist, callback::SendReport<DownloadProgressReport> *report, MediaBlockList *blklist, off_t filesize) const
1535{
1536 Url baseurl(getFileUrl(filename));
1537 if (blklist && filesize == off_t(-1) && blklist->haveFilesize())
1538 filesize = blklist->getFilesize();
1539 if (blklist && !blklist->haveBlocks() && filesize != 0)
1540 blklist = 0;
1541 if (blklist && (filesize == 0 || !blklist->numBlocks()))
1542 {
1543 checkFileDigest(baseurl, fp, blklist);
1544 return;
1545 }
1546 if (filesize == 0)
1547 return;
1548 if (!_multi)
1549 {
1550 _multi = curl_multi_init();
1551 if (!_multi)
1552 ZYPP_THROW(MediaCurlInitException(baseurl));
1553 }
1554
1555 multifetchrequest req(this, filename, baseurl, _multi, fp, report, blklist, filesize);
1556 req._timeout = _settings.timeout();
1557 req._connect_timeout = _settings.connectTimeout();
1558 req._maxspeed = _settings.maxDownloadSpeed();
1559 req._maxworkers = _settings.maxConcurrentConnections();
1560 if (req._maxworkers > MAXURLS)
1561 req._maxworkers = MAXURLS;
1562 if (req._maxworkers <= 0)
1563 req._maxworkers = 1;
1564 std::vector<Url> myurllist;
1565 for (std::vector<Url>::iterator urliter = urllist->begin(); urliter != urllist->end(); ++urliter)
1566 {
1567 try
1568 {
1569 std::string scheme = urliter->getScheme();
1570 if (scheme == "http" || scheme == "https" || scheme == "ftp" || scheme == "tftp")
1571 {
1572 checkProtocol(*urliter);
1573 myurllist.push_back(internal::propagateQueryParams(*urliter, _url));
1574 }
1575 }
1576 catch (...)
1577 {
1578 }
1579 }
1580 if (!myurllist.size())
1581 myurllist.push_back(baseurl);
1582 req.run(myurllist);
1583 checkFileDigest(baseurl, fp, blklist);
1584}
1585
1586void MediaMultiCurl::checkFileDigest(Url &url, FILE *fp, MediaBlockList *blklist) const
1587{
1588 if (!blklist || !blklist->haveFileChecksum())
1589 return;
1590 if (fseeko(fp, off_t(0), SEEK_SET))
1591 ZYPP_THROW(MediaCurlException(url, "fseeko", "seek error"));
1592 Digest dig;
1593 blklist->createFileDigest(dig);
1594 char buf[4096];
1595 size_t l;
1596 while ((l = fread(buf, 1, sizeof(buf), fp)) > 0)
1597 dig.update(buf, l);
1598 if (!blklist->verifyFileDigest(dig))
1599 ZYPP_THROW(MediaCurlException(url, "file verification failed", "checksum error"));
1600}
1601
1602bool MediaMultiCurl::isDNSok(const std::string &host) const
1603{
1604 return _dnsok.find(host) == _dnsok.end() ? false : true;
1605}
1606
1607void MediaMultiCurl::setDNSok(const std::string &host) const
1608{
1609 _dnsok.insert(host);
1610}
1611
1612CURL *MediaMultiCurl::fromEasyPool(const std::string &host) const
1613{
1614 if (_easypool.find(host) == _easypool.end())
1615 return 0;
1616 CURL *ret = _easypool[host];
1617 _easypool.erase(host);
1618 return ret;
1619}
1620
1621void MediaMultiCurl::toEasyPool(const std::string &host, CURL *easy) const
1622{
1623 CURL *oldeasy = _easypool[host];
1624 _easypool[host] = easy;
1625 if (oldeasy)
1626 curl_easy_cleanup(oldeasy);
1627}
1628
1629 } // namespace media
1630} // namespace zypp
std::optional< KeyManagerCtx > _context
Definition: KeyRing.cc:157
#define WORKER_STARTING
#define WORKER_DISCARD
#define WORKER_DONE
#define WORKER_LOOKUP
#define WORKER_FETCH
#define WORKER_SLEEP
#define WORKER_BROKEN
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
Definition: AutoDispose.h:94
void resetDispose()
Set no dispose function.
Definition: AutoDispose.h:180
Store and operate with byte count.
Definition: ByteCount.h:31
static const Unit MB
1000^2 Byte
Definition: ByteCount.h:60
std::string asString(unsigned field_width_r=0, unsigned unit_width_r=1) const
Auto selected Unit and precision.
Definition: ByteCount.h:133
Compute Message Digests (MD5, SHA1 etc)
Definition: Digest.h:36
bool update(const char *bytes, size_t len)
feed data into digest computation algorithm
Definition: Digest.cc:248
Base class for Exception.
Definition: Exception.h:146
Describes a resource file located on a medium.
const ByteCount & downloadSize() const
The size of the resource on the server.
const Pathname & filename() const
The path to the resource on the medium.
const Pathname & deltafile() const
The existing deltafile that can be used to reduce download size ( zchunk or metalink )
Url manipulation class.
Definition: Url.h:92
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:533
std::string asString() const
Returns a default string representation of the Url object.
Definition: Url.cc:497
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
Definition: Url.cc:588
Pathname repoCachePath() const
Path where the caches are kept (/var/cache/zypp)
Definition: ZConfig.cc:940
static ZConfig & instance()
Singleton ctor.
Definition: ZConfig.cc:823
Wrapper class for stat/lstat.
Definition: PathInfo.h:221
Pathname extend(const std::string &r) const
Append string r to the last component of the path.
Definition: Pathname.h:173
Pathname dirname() const
Return all but the last component od this path.
Definition: Pathname.h:124
const std::string & asString() const
String representation.
Definition: Pathname.h:91
Pathname absolutename() const
Return this path, adding a leading '/' if relative.
Definition: Pathname.h:139
Implementation class for FTP, HTTP and HTTPS MediaHandler.
Definition: MediaCurl.h:32
virtual void setupEasy()
initializes the curl easy handle with the data from the url
Definition: MediaCurl.cc:302
Url getFileUrl(const Pathname &filename) const
concatenate the attach url and the filename to a complete download url
Definition: MediaCurl.cc:629
@ OPTION_NO_IFMODSINCE
to not add a IFMODSINCE header if target exists
Definition: MediaCurl.h:43
@ OPTION_NO_REPORT_START
do not send a start ProgressReport
Definition: MediaCurl.h:45
static void resetExpectedFileSize(void *clientp, const ByteCount &expectedFileSize)
MediaMultiCurl needs to reset the expected filesize in case a metalink file is downloaded otherwise t...
Definition: MediaCurl.cc:1384
static int aliveCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
Definition: MediaCurl.cc:1327
static int progressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
Callback reporting download progress.
Definition: MediaCurl.cc:1341
Url clearQueryString(const Url &url) const
Definition: MediaCurl.cc:265
char _curlError[CURL_ERROR_SIZE]
Definition: MediaCurl.h:174
void doGetFileCopyFile(const OnMediaLocation &srcFile, const Pathname &dest, FILE *file, callback::SendReport< DownloadProgressReport > &report, RequestOptions options=OPTION_NONE) const
Definition: MediaCurl.cc:1171
void checkProtocol(const Url &url) const
check the url is supported by the curl library
Definition: MediaCurl.cc:277
void evaluateCurlCode(const zypp::Pathname &filename, CURLcode code, bool timeout) const
Evaluates a curl return code and throws the right MediaException filename Filename being downloaded c...
Definition: MediaCurl.cc:734
static CURL * progressCallback_getcurl(void *clientp)
Definition: MediaCurl.cc:1357
virtual void disconnectFrom() override
Definition: MediaCurl.cc:605
curl_slist * _customHeaders
Definition: MediaCurl.h:175
Url url() const
Url used.
Definition: MediaHandler.h:503
const Url _url
Url to handle.
Definition: MediaHandler.h:113
virtual void setupEasy() override
initializes the curl easy handle with the data from the url
std::map< std::string, CURL * > _easypool
curl_slist * _customHeadersMetalink
void multifetch(const Pathname &filename, FILE *fp, std::vector< Url > *urllist, callback::SendReport< DownloadProgressReport > *report=0, MediaBlockList *blklist=0, off_t filesize=off_t(-1)) const
static int progressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
void setDNSok(const std::string &host) const
MediaMultiCurl(const Url &url_r, const Pathname &attach_point_hint_r)
std::set< std::string > _dnsok
bool isDNSok(const std::string &host) const
CURL * fromEasyPool(const std::string &host) const
virtual void doGetFileCopy(const OnMediaLocation &srcFile, const Pathname &targetFilename, callback::SendReport< DownloadProgressReport > &_report, RequestOptions options=OPTION_NONE) const override
void checkFileDigest(Url &url, FILE *fp, MediaBlockList *blklist) const
void toEasyPool(const std::string &host, CURL *easy) const
callback::SendReport< DownloadProgressReport > * _report
void run(std::vector< Url > &urllist)
std::list< multifetchworker * > _workers
multifetchrequest(const MediaMultiCurl *context, const Pathname &filename, const Url &baseurl, CURLM *multi, FILE *fp, callback::SendReport< DownloadProgressReport > *report, MediaBlockList *blklist, off_t filesize)
static size_t makeBlksize(size_t filesize)
const MediaMultiCurl * _context
size_t headerfunction(char *ptr, size_t size)
multifetchworker(int no, multifetchrequest &request, const Url &url)
multifetchrequest * _request
size_t writefunction(void *ptr, size_t size)
static size_t _writefunction(void *ptr, size_t size, size_t nmemb, void *stream)
static size_t _headerfunction(void *ptr, size_t size, size_t nmemb, void *stream)
void adddnsfd(fd_set &rset, int &maxfd)
mode_t applyUmaskTo(mode_t mode_r)
Modify mode_r according to the current umask ( mode_r & ~getUmask() ).
Definition: PathInfo.h:789
int unlink(const Pathname &path)
Like 'unlink'.
Definition: PathInfo.cc:700
int hardlinkCopy(const Pathname &oldpath, const Pathname &newpath)
Create newpath as hardlink or copy of oldpath.
Definition: PathInfo.cc:883
static bool looks_like_metalink(const Pathname &file)
static bool looks_like_metalink_fd(int fd)
constexpr auto MAXURLS
static bool env_isset(std::string name)
static double currentTime()
constexpr auto MIN_REQ_MIRRS
std::string numstring(char n, int w=0)
Definition: String.h:289
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:2
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
Definition: ManagedFile.h:27
AutoDispose<int> calling ::close
Definition: AutoDispose.h:301
AutoDispose<FILE*> calling ::fclose
Definition: AutoDispose.h:312
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:440
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:428
#define DBG
Definition: Logger.h:95
#define MIL
Definition: Logger.h:96
#define ERR
Definition: Logger.h:98
#define WAR
Definition: Logger.h:97
#define XXX
Definition: Logger.h:94