You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1487 lines
46 KiB

  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. /* ######################################################################
  4. Acquire - File Acquiration
  5. The core element for the schedule system is the concept of a named
  6. queue. Each queue is unique and each queue has a name derived from the
  7. URI. The degree of paralization can be controlled by how the queue
  8. name is derived from the URI.
  9. ##################################################################### */
  10. /*}}}*/
  11. // Include Files /*{{{*/
  12. #include <config.h>
  13. #include <apt-pkg/acquire-item.h>
  14. #include <apt-pkg/acquire-worker.h>
  15. #include <apt-pkg/acquire.h>
  16. #include <apt-pkg/configuration.h>
  17. #include <apt-pkg/error.h>
  18. #include <apt-pkg/fileutl.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <algorithm>
  21. #include <chrono>
  22. #include <iomanip>
  23. #include <iostream>
  24. #include <memory>
  25. #include <numeric>
  26. #include <sstream>
  27. #include <string>
  28. #include <vector>
  29. #include <cmath>
  30. #include <dirent.h>
  31. #include <errno.h>
  32. #include <fcntl.h>
  33. #include <grp.h>
  34. #include <pwd.h>
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. #include <sys/select.h>
  39. #include <sys/stat.h>
  40. #include <sys/time.h>
  41. #include <unistd.h>
  42. #include <apti18n.h>
  43. /*}}}*/
  44. using namespace std;
  45. // Acquire::pkgAcquire - Constructor /*{{{*/
  46. // ---------------------------------------------------------------------
  47. /* We grab some runtime state from the configuration space */
  48. pkgAcquire::pkgAcquire() : LockFD(-1), d(NULL), Queues(0), Workers(0), Configs(0), Log(NULL), ToFetch(0),
  49. Debug(_config->FindB("Debug::pkgAcquire",false)),
  50. Running(false)
  51. {
  52. Initialize();
  53. }
  54. pkgAcquire::pkgAcquire(pkgAcquireStatus *Progress) : LockFD(-1), d(NULL), Queues(0), Workers(0),
  55. Configs(0), Log(NULL), ToFetch(0),
  56. Debug(_config->FindB("Debug::pkgAcquire",false)),
  57. Running(false)
  58. {
  59. Initialize();
  60. SetLog(Progress);
  61. }
  62. void pkgAcquire::Initialize()
  63. {
  64. string const Mode = _config->Find("Acquire::Queue-Mode","host");
  65. if (strcasecmp(Mode.c_str(),"host") == 0)
  66. QueueMode = QueueHost;
  67. if (strcasecmp(Mode.c_str(),"access") == 0)
  68. QueueMode = QueueAccess;
  69. }
  70. /*}}}*/
  71. // Acquire::GetLock - lock directory and prepare for action /*{{{*/
  72. static bool SetupAPTPartialDirectory(std::string const &grand, std::string const &parent, std::string const &postfix, mode_t const mode)
  73. {
  74. if (_config->FindB("Debug::SetupAPTPartialDirectory::AssumeGood", false))
  75. return true;
  76. std::string const partial = parent + postfix;
  77. bool const partialExists = DirectoryExists(partial);
  78. if (partialExists == false)
  79. {
  80. mode_t const old_umask = umask(S_IWGRP | S_IWOTH);
  81. bool const creation_fail = (CreateAPTDirectoryIfNeeded(grand, partial) == false &&
  82. CreateAPTDirectoryIfNeeded(parent, partial) == false);
  83. umask(old_umask);
  84. if (creation_fail == true)
  85. return false;
  86. }
  87. std::string const SandboxUser = _config->Find("APT::Sandbox::User");
  88. if (getuid() == 0)
  89. {
  90. if (SandboxUser.empty() == false && SandboxUser != "root") // if we aren't root, we can't chown, so don't try it
  91. {
  92. struct passwd const * const pw = getpwnam(SandboxUser.c_str());
  93. struct group const * const gr = getgrnam(ROOT_GROUP);
  94. if (pw != NULL && gr != NULL)
  95. {
  96. // chown the partial dir
  97. if(chown(partial.c_str(), pw->pw_uid, gr->gr_gid) != 0)
  98. _error->WarningE("SetupAPTPartialDirectory", "chown to %s:root of directory %s failed", SandboxUser.c_str(), partial.c_str());
  99. }
  100. }
  101. if (chmod(partial.c_str(), mode) != 0)
  102. _error->WarningE("SetupAPTPartialDirectory", "chmod 0700 of directory %s failed", partial.c_str());
  103. }
  104. else if (chmod(partial.c_str(), mode) != 0)
  105. {
  106. // if we haven't created the dir and aren't root, it is kinda expected that chmod doesn't work
  107. if (partialExists == false)
  108. _error->WarningE("SetupAPTPartialDirectory", "chmod 0700 of directory %s failed", partial.c_str());
  109. }
  110. _error->PushToStack();
  111. // remove 'old' FAILED files to stop us from collecting them for no reason
  112. for (auto const &Failed: GetListOfFilesInDir(partial, "FAILED", false, false))
  113. RemoveFile("SetupAPTPartialDirectory", Failed);
  114. _error->RevertToStack();
  115. return true;
  116. }
  117. bool pkgAcquire::Setup(pkgAcquireStatus *Progress, string const &Lock)
  118. {
  119. Log = Progress;
  120. if (Lock.empty())
  121. {
  122. string const listDir = _config->FindDir("Dir::State::lists");
  123. if (SetupAPTPartialDirectory(_config->FindDir("Dir::State"), listDir, "partial", 0700) == false)
  124. return _error->Errno("Acquire", _("List directory %s is missing."), (listDir + "partial").c_str());
  125. if (SetupAPTPartialDirectory(_config->FindDir("Dir::State"), listDir, "auxfiles", 0755) == false)
  126. {
  127. // not being able to create lists/auxfiles isn't critical as we will use a tmpdir then
  128. }
  129. string const archivesDir = _config->FindDir("Dir::Cache::Archives");
  130. if (SetupAPTPartialDirectory(_config->FindDir("Dir::Cache"), archivesDir, "partial", 0700) == false)
  131. return _error->Errno("Acquire", _("Archives directory %s is missing."), (archivesDir + "partial").c_str());
  132. return true;
  133. }
  134. return GetLock(Lock);
  135. }
  136. bool pkgAcquire::GetLock(std::string const &Lock)
  137. {
  138. if (Lock.empty() == true)
  139. return false;
  140. // check for existence and possibly create auxiliary directories
  141. string const listDir = _config->FindDir("Dir::State::lists");
  142. string const archivesDir = _config->FindDir("Dir::Cache::Archives");
  143. if (Lock == listDir)
  144. {
  145. if (SetupAPTPartialDirectory(_config->FindDir("Dir::State"), listDir, "partial", 0700) == false)
  146. return _error->Errno("Acquire", _("List directory %s is missing."), (listDir + "partial").c_str());
  147. }
  148. if (Lock == archivesDir)
  149. {
  150. if (SetupAPTPartialDirectory(_config->FindDir("Dir::Cache"), archivesDir, "partial", 0700) == false)
  151. return _error->Errno("Acquire", _("Archives directory %s is missing."), (archivesDir + "partial").c_str());
  152. }
  153. if (Lock == listDir || Lock == archivesDir)
  154. {
  155. if (SetupAPTPartialDirectory(_config->FindDir("Dir::State"), listDir, "auxfiles", 0755) == false)
  156. {
  157. // not being able to create lists/auxfiles isn't critical as we will use a tmpdir then
  158. }
  159. }
  160. if (_config->FindB("Debug::NoLocking", false) == true)
  161. return true;
  162. // Lock the directory this acquire object will work in
  163. if (LockFD != -1)
  164. close(LockFD);
  165. LockFD = ::GetLock(flCombine(Lock, "lock"));
  166. if (LockFD == -1)
  167. return _error->Error(_("Unable to lock directory %s"), Lock.c_str());
  168. return true;
  169. }
  170. /*}}}*/
  171. // Acquire::~pkgAcquire - Destructor /*{{{*/
  172. // ---------------------------------------------------------------------
  173. /* Free our memory, clean up the queues (destroy the workers) */
  174. pkgAcquire::~pkgAcquire()
  175. {
  176. Shutdown();
  177. if (LockFD != -1)
  178. close(LockFD);
  179. while (Configs != 0)
  180. {
  181. MethodConfig *Jnk = Configs;
  182. Configs = Configs->Next;
  183. delete Jnk;
  184. }
  185. }
  186. /*}}}*/
  187. // Acquire::Shutdown - Clean out the acquire object /*{{{*/
  188. // ---------------------------------------------------------------------
  189. /* */
  190. void pkgAcquire::Shutdown()
  191. {
  192. while (Items.empty() == false)
  193. {
  194. if (Items[0]->Status == Item::StatFetching)
  195. Items[0]->Status = Item::StatError;
  196. delete Items[0];
  197. }
  198. while (Queues != 0)
  199. {
  200. Queue *Jnk = Queues;
  201. Queues = Queues->Next;
  202. delete Jnk;
  203. }
  204. }
  205. /*}}}*/
  206. // Acquire::Add - Add a new item /*{{{*/
  207. // ---------------------------------------------------------------------
  208. /* This puts an item on the acquire list. This list is mainly for tracking
  209. item status */
  210. void pkgAcquire::Add(Item *Itm)
  211. {
  212. Items.push_back(Itm);
  213. }
  214. /*}}}*/
  215. // Acquire::Remove - Remove a item /*{{{*/
  216. // ---------------------------------------------------------------------
  217. /* Remove an item from the acquire list. This is usually not used.. */
  218. void pkgAcquire::Remove(Item *Itm)
  219. {
  220. Dequeue(Itm);
  221. for (ItemIterator I = Items.begin(); I != Items.end();)
  222. {
  223. if (*I == Itm)
  224. {
  225. Items.erase(I);
  226. I = Items.begin();
  227. }
  228. else
  229. ++I;
  230. }
  231. }
  232. /*}}}*/
  233. // Acquire::Add - Add a worker /*{{{*/
  234. // ---------------------------------------------------------------------
  235. /* A list of workers is kept so that the select loop can direct their FD
  236. usage. */
  237. void pkgAcquire::Add(Worker *Work)
  238. {
  239. Work->NextAcquire = Workers;
  240. Workers = Work;
  241. }
  242. /*}}}*/
  243. // Acquire::Remove - Remove a worker /*{{{*/
  244. // ---------------------------------------------------------------------
  245. /* A worker has died. This can not be done while the select loop is running
  246. as it would require that RunFds could handling a changing list state and
  247. it can't.. */
  248. void pkgAcquire::Remove(Worker *Work)
  249. {
  250. if (Running == true)
  251. abort();
  252. Worker **I = &Workers;
  253. for (; *I != 0;)
  254. {
  255. if (*I == Work)
  256. *I = (*I)->NextAcquire;
  257. else
  258. I = &(*I)->NextAcquire;
  259. }
  260. }
  261. /*}}}*/
  262. // Acquire::Enqueue - Queue an URI for fetching /*{{{*/
  263. // ---------------------------------------------------------------------
  264. /* This is the entry point for an item. An item calls this function when
  265. it is constructed which creates a queue (based on the current queue
  266. mode) and puts the item in that queue. If the system is running then
  267. the queue might be started. */
  268. static bool CheckForBadItemAndFailIt(pkgAcquire::Item * const Item,
  269. pkgAcquire::MethodConfig const * const Config, pkgAcquireStatus * const Log)
  270. {
  271. auto SavedDesc = Item->GetItemDesc();
  272. if (Item->IsRedirectionLoop(SavedDesc.URI))
  273. {
  274. std::string const Message = "400 URI Failure"
  275. "\nURI: " + SavedDesc.URI +
  276. "\nFilename: " + Item->DestFile +
  277. "\nFailReason: RedirectionLoop";
  278. Item->Status = pkgAcquire::Item::StatError;
  279. Item->Failed(Message, Config);
  280. if (Log != nullptr)
  281. Log->Fail(SavedDesc);
  282. return true;
  283. }
  284. HashStringList const hsl = Item->GetExpectedHashes();
  285. if (hsl.usable() == false && Item->HashesRequired() &&
  286. _config->Exists("Acquire::ForceHash") == false)
  287. {
  288. std::string const Message = "400 URI Failure"
  289. "\nURI: " + SavedDesc.URI +
  290. "\nFilename: " + Item->DestFile +
  291. "\nFailReason: WeakHashSums";
  292. Item->Status = pkgAcquire::Item::StatAuthError;
  293. Item->Failed(Message, Config);
  294. if (Log != nullptr)
  295. Log->Fail(SavedDesc);
  296. return true;
  297. }
  298. return false;
  299. }
  300. void pkgAcquire::Enqueue(ItemDesc &Item)
  301. {
  302. // Determine which queue to put the item in
  303. const MethodConfig *Config;
  304. string Name = QueueName(Item.URI,Config);
  305. if (Name.empty() == true)
  306. {
  307. Item.Owner->Status = pkgAcquire::Item::StatError;
  308. return;
  309. }
  310. /* the check for running avoids that we produce errors
  311. in logging before we actually have started, which would
  312. be easier to implement but would confuse users/implementations
  313. so we check the items skipped here in #Startup */
  314. if (Running && CheckForBadItemAndFailIt(Item.Owner, Config, Log))
  315. return;
  316. // Find the queue structure
  317. Queue *I = Queues;
  318. for (; I != 0 && I->Name != Name; I = I->Next);
  319. if (I == 0)
  320. {
  321. I = new Queue(Name,this);
  322. I->Next = Queues;
  323. Queues = I;
  324. if (Running == true)
  325. I->Startup();
  326. }
  327. // See if this is a local only URI
  328. if (Config->LocalOnly == true && Item.Owner->Complete == false)
  329. Item.Owner->Local = true;
  330. Item.Owner->Status = Item::StatIdle;
  331. // Queue it into the named queue
  332. if(I->Enqueue(Item))
  333. ToFetch++;
  334. // Some trace stuff
  335. if (Debug == true)
  336. {
  337. clog << "Fetching " << Item.URI << endl;
  338. clog << " to " << Item.Owner->DestFile << endl;
  339. clog << " Queue is: " << Name << endl;
  340. }
  341. }
  342. /*}}}*/
  343. // Acquire::Dequeue - Remove an item from all queues /*{{{*/
  344. // ---------------------------------------------------------------------
  345. /* This is called when an item is finished being fetched. It removes it
  346. from all the queues */
  347. void pkgAcquire::Dequeue(Item *Itm)
  348. {
  349. Queue *I = Queues;
  350. bool Res = false;
  351. if (Debug == true)
  352. clog << "Dequeuing " << Itm->DestFile << endl;
  353. for (; I != 0; I = I->Next)
  354. {
  355. if (I->Dequeue(Itm))
  356. {
  357. Res = true;
  358. if (Debug == true)
  359. clog << "Dequeued from " << I->Name << endl;
  360. }
  361. }
  362. if (Res == true)
  363. ToFetch--;
  364. }
  365. /*}}}*/
  366. // Acquire::QueueName - Return the name of the queue for this URI /*{{{*/
  367. // ---------------------------------------------------------------------
  368. /* The string returned depends on the configuration settings and the
  369. method parameters. Given something like http://foo.org/bar it can
  370. return http://foo.org or http */
  371. string pkgAcquire::QueueName(string Uri,MethodConfig const *&Config)
  372. {
  373. URI U(Uri);
  374. Config = GetConfig(U.Access);
  375. if (Config == 0)
  376. return string();
  377. /* Single-Instance methods get exactly one queue per URI. This is
  378. also used for the Access queue method */
  379. if (Config->SingleInstance == true || QueueMode == QueueAccess)
  380. return U.Access;
  381. string AccessSchema = U.Access + ':';
  382. string FullQueueName;
  383. if (U.Host.empty())
  384. {
  385. long existing = 0;
  386. // check how many queues exist already and reuse empty ones
  387. for (Queue const *I = Queues; I != 0; I = I->Next)
  388. if (I->Name.compare(0, AccessSchema.length(), AccessSchema) == 0)
  389. {
  390. if (I->Items == nullptr)
  391. return I->Name;
  392. ++existing;
  393. }
  394. #ifdef _SC_NPROCESSORS_ONLN
  395. long cpuCount = sysconf(_SC_NPROCESSORS_ONLN) * 2;
  396. #else
  397. long cpuCount = 10;
  398. #endif
  399. cpuCount = _config->FindI("Acquire::QueueHost::Limit", cpuCount);
  400. if (cpuCount <= 0 || existing < cpuCount)
  401. strprintf(FullQueueName, "%s%ld", AccessSchema.c_str(), existing);
  402. else
  403. {
  404. long const randomQueue = random() % cpuCount;
  405. strprintf(FullQueueName, "%s%ld", AccessSchema.c_str(), randomQueue);
  406. }
  407. if (Debug)
  408. clog << "Chose random queue " << FullQueueName << " for " << Uri << endl;
  409. } else
  410. {
  411. FullQueueName = AccessSchema + U.Host;
  412. }
  413. unsigned int Instances = 0, SchemaLength = AccessSchema.length();
  414. Queue *I = Queues;
  415. for (; I != 0; I = I->Next) {
  416. // if the queue already exists, re-use it
  417. if (I->Name == FullQueueName)
  418. return FullQueueName;
  419. if (I->Name.compare(0, SchemaLength, AccessSchema) == 0)
  420. Instances++;
  421. }
  422. if (Debug) {
  423. clog << "Found " << Instances << " instances of " << U.Access << endl;
  424. }
  425. if (Instances >= static_cast<decltype(Instances)>(_config->FindI("Acquire::QueueHost::Limit",10)))
  426. return U.Access;
  427. return FullQueueName;
  428. }
  429. /*}}}*/
  430. // Acquire::GetConfig - Fetch the configuration information /*{{{*/
  431. // ---------------------------------------------------------------------
  432. /* This locates the configuration structure for an access method. If
  433. a config structure cannot be found a Worker will be created to
  434. retrieve it */
  435. pkgAcquire::MethodConfig *pkgAcquire::GetConfig(string Access)
  436. {
  437. // Search for an existing config
  438. MethodConfig *Conf;
  439. for (Conf = Configs; Conf != 0; Conf = Conf->Next)
  440. if (Conf->Access == Access)
  441. return Conf;
  442. // Create the new config class
  443. Conf = new MethodConfig;
  444. Conf->Access = Access;
  445. // Create the worker to fetch the configuration
  446. Worker Work(Conf);
  447. if (Work.Start() == false)
  448. {
  449. delete Conf;
  450. return nullptr;
  451. }
  452. Conf->Next = Configs;
  453. Configs = Conf;
  454. /* if a method uses DownloadLimit, we switch to SingleInstance mode */
  455. if(_config->FindI("Acquire::"+Access+"::Dl-Limit",0) > 0)
  456. Conf->SingleInstance = true;
  457. return Conf;
  458. }
  459. /*}}}*/
  460. // Acquire::SetFds - Deal with readable FDs /*{{{*/
  461. // ---------------------------------------------------------------------
  462. /* Collect FDs that have activity monitors into the fd sets */
  463. void pkgAcquire::SetFds(int &Fd,fd_set *RSet,fd_set *WSet)
  464. {
  465. for (Worker *I = Workers; I != 0; I = I->NextAcquire)
  466. {
  467. if (I->InReady == true && I->InFd >= 0)
  468. {
  469. if (Fd < I->InFd)
  470. Fd = I->InFd;
  471. FD_SET(I->InFd,RSet);
  472. }
  473. if (I->OutReady == true && I->OutFd >= 0)
  474. {
  475. if (Fd < I->OutFd)
  476. Fd = I->OutFd;
  477. FD_SET(I->OutFd,WSet);
  478. }
  479. }
  480. }
  481. /*}}}*/
  482. // Acquire::RunFds - compatibility remove on next abi/api break /*{{{*/
  483. void pkgAcquire::RunFds(fd_set *RSet,fd_set *WSet)
  484. {
  485. RunFdsSane(RSet, WSet);
  486. }
  487. /*}}}*/
  488. // Acquire::RunFdsSane - Deal with active FDs /*{{{*/
  489. // ---------------------------------------------------------------------
  490. /* Dispatch active FDs over to the proper workers. It is very important
  491. that a worker never be erased while this is running! The queue class
  492. should never erase a worker except during shutdown processing. */
  493. bool pkgAcquire::RunFdsSane(fd_set *RSet,fd_set *WSet)
  494. {
  495. bool Res = true;
  496. for (Worker *I = Workers; I != 0; I = I->NextAcquire)
  497. {
  498. if (I->InFd >= 0 && FD_ISSET(I->InFd,RSet) != 0)
  499. Res &= I->InFdReady();
  500. if (I->OutFd >= 0 && FD_ISSET(I->OutFd,WSet) != 0)
  501. Res &= I->OutFdReady();
  502. }
  503. return Res;
  504. }
  505. /*}}}*/
  506. // Acquire::Run - Run the fetch sequence /*{{{*/
  507. // ---------------------------------------------------------------------
  508. /* This runs the queues. It manages a select loop for all of the
  509. Worker tasks. The workers interact with the queues and items to
  510. manage the actual fetch. */
  511. static bool IsAccessibleBySandboxUser(std::string const &filename, bool const ReadWrite)
  512. {
  513. // you would think this is easily to answer with faccessat, right? Wrong!
  514. // It e.g. gets groups wrong, so the only thing which works reliable is trying
  515. // to open the file we want to open later on…
  516. if (unlikely(filename.empty()))
  517. return true;
  518. if (ReadWrite == false)
  519. {
  520. errno = 0;
  521. // can we read a file? Note that non-existing files are "fine"
  522. int const fd = open(filename.c_str(), O_RDONLY | O_CLOEXEC);
  523. if (fd == -1 && errno == EACCES)
  524. return false;
  525. close(fd);
  526. return true;
  527. }
  528. else
  529. {
  530. // the file might not exist yet and even if it does we will fix permissions,
  531. // so important is here just that the directory it is in allows that
  532. std::string const dirname = flNotFile(filename);
  533. if (unlikely(dirname.empty()))
  534. return true;
  535. char const * const filetag = ".apt-acquire-privs-test.XXXXXX";
  536. std::string const tmpfile_tpl = flCombine(dirname, filetag);
  537. std::unique_ptr<char, decltype(std::free) *> tmpfile { strdup(tmpfile_tpl.c_str()), std::free };
  538. int const fd = mkstemp(tmpfile.get());
  539. if (fd == -1 && errno == EACCES)
  540. return false;
  541. RemoveFile("IsAccessibleBySandboxUser", tmpfile.get());
  542. close(fd);
  543. return true;
  544. }
  545. }
  546. static void CheckDropPrivsMustBeDisabled(pkgAcquire const &Fetcher)
  547. {
  548. if(getuid() != 0)
  549. return;
  550. std::string const SandboxUser = _config->Find("APT::Sandbox::User");
  551. if (SandboxUser.empty() || SandboxUser == "root")
  552. return;
  553. struct passwd const * const pw = getpwnam(SandboxUser.c_str());
  554. if (pw == NULL)
  555. {
  556. _error->Warning(_("No sandbox user '%s' on the system, can not drop privileges"), SandboxUser.c_str());
  557. _config->Set("APT::Sandbox::User", "");
  558. return;
  559. }
  560. gid_t const old_euid = geteuid();
  561. gid_t const old_egid = getegid();
  562. long const ngroups_max = sysconf(_SC_NGROUPS_MAX);
  563. std::unique_ptr<gid_t[]> old_gidlist(new gid_t[ngroups_max]);
  564. if (unlikely(old_gidlist == NULL))
  565. return;
  566. ssize_t old_gidlist_nr;
  567. if ((old_gidlist_nr = getgroups(ngroups_max, old_gidlist.get())) < 0)
  568. {
  569. _error->FatalE("getgroups", "getgroups %lu failed", ngroups_max);
  570. old_gidlist[0] = 0;
  571. old_gidlist_nr = 1;
  572. }
  573. if (setgroups(1, &pw->pw_gid))
  574. _error->FatalE("setgroups", "setgroups %u failed", pw->pw_gid);
  575. if (setegid(pw->pw_gid) != 0)
  576. _error->FatalE("setegid", "setegid %u failed", pw->pw_gid);
  577. if (seteuid(pw->pw_uid) != 0)
  578. _error->FatalE("seteuid", "seteuid %u failed", pw->pw_uid);
  579. for (pkgAcquire::ItemCIterator I = Fetcher.ItemsBegin();
  580. I != Fetcher.ItemsEnd(); ++I)
  581. {
  582. // no need to drop privileges for a complete file
  583. if ((*I)->Complete == true || (*I)->Status != pkgAcquire::Item::StatIdle)
  584. continue;
  585. // if destination file is inaccessible all hope is lost for privilege dropping
  586. if (IsAccessibleBySandboxUser((*I)->DestFile, true) == false)
  587. {
  588. _error->WarningE("pkgAcquire::Run", _("Download is performed unsandboxed as root as file '%s' couldn't be accessed by user '%s'."),
  589. (*I)->DestFile.c_str(), SandboxUser.c_str());
  590. _config->Set("APT::Sandbox::User", "");
  591. break;
  592. }
  593. // if its the source file (e.g. local sources) we might be lucky
  594. // by dropping the dropping only for some methods.
  595. URI const source = (*I)->DescURI();
  596. if (source.Access == "file" || source.Access == "copy")
  597. {
  598. std::string const conf = "Binary::" + source.Access + "::APT::Sandbox::User";
  599. if (_config->Exists(conf) == true)
  600. continue;
  601. if (IsAccessibleBySandboxUser(source.Path, false) == false)
  602. {
  603. _error->NoticeE("pkgAcquire::Run", _("Download is performed unsandboxed as root as file '%s' couldn't be accessed by user '%s'."),
  604. source.Path.c_str(), SandboxUser.c_str());
  605. _config->CndSet("Binary::file::APT::Sandbox::User", "root");
  606. _config->CndSet("Binary::copy::APT::Sandbox::User", "root");
  607. }
  608. }
  609. }
  610. if (seteuid(old_euid) != 0)
  611. _error->FatalE("seteuid", "seteuid %u failed", old_euid);
  612. if (setegid(old_egid) != 0)
  613. _error->FatalE("setegid", "setegid %u failed", old_egid);
  614. if (setgroups(old_gidlist_nr, old_gidlist.get()))
  615. _error->FatalE("setgroups", "setgroups %u failed", 0);
  616. }
  617. pkgAcquire::RunResult pkgAcquire::Run(int PulseIntervall)
  618. {
  619. _error->PushToStack();
  620. CheckDropPrivsMustBeDisabled(*this);
  621. Running = true;
  622. for (Queue *I = Queues; I != 0; I = I->Next)
  623. I->Startup();
  624. if (Log != 0)
  625. Log->Start();
  626. bool WasCancelled = false;
  627. // Run till all things have been acquired
  628. struct timeval tv;
  629. tv.tv_sec = 0;
  630. tv.tv_usec = PulseIntervall;
  631. while (ToFetch > 0)
  632. {
  633. fd_set RFds;
  634. fd_set WFds;
  635. int Highest = 0;
  636. FD_ZERO(&RFds);
  637. FD_ZERO(&WFds);
  638. SetFds(Highest,&RFds,&WFds);
  639. int Res;
  640. do
  641. {
  642. Res = select(Highest+1,&RFds,&WFds,0,&tv);
  643. }
  644. while (Res < 0 && errno == EINTR);
  645. if (Res < 0)
  646. {
  647. _error->Errno("select","Select has failed");
  648. break;
  649. }
  650. if(RunFdsSane(&RFds,&WFds) == false)
  651. break;
  652. // Timeout, notify the log class
  653. if (Res == 0 || (Log != 0 && Log->Update == true))
  654. {
  655. tv.tv_usec = PulseIntervall;
  656. for (Worker *I = Workers; I != 0; I = I->NextAcquire)
  657. I->Pulse();
  658. if (Log != 0 && Log->Pulse(this) == false)
  659. {
  660. WasCancelled = true;
  661. break;
  662. }
  663. }
  664. }
  665. if (Log != 0)
  666. Log->Stop();
  667. // Shut down the acquire bits
  668. Running = false;
  669. for (Queue *I = Queues; I != 0; I = I->Next)
  670. I->Shutdown(false);
  671. // Shut down the items
  672. for (ItemIterator I = Items.begin(); I != Items.end(); ++I)
  673. (*I)->Finished();
  674. bool const newError = _error->PendingError();
  675. _error->MergeWithStack();
  676. if (newError)
  677. return Failed;
  678. if (WasCancelled)
  679. return Cancelled;
  680. return Continue;
  681. }
  682. /*}}}*/
  683. // Acquire::Bump - Called when an item is dequeued /*{{{*/
  684. // ---------------------------------------------------------------------
  685. /* This routine bumps idle queues in hopes that they will be able to fetch
  686. the dequeued item */
  687. void pkgAcquire::Bump()
  688. {
  689. for (Queue *I = Queues; I != 0; I = I->Next)
  690. I->Bump();
  691. }
  692. /*}}}*/
  693. // Acquire::WorkerStep - Step to the next worker /*{{{*/
  694. // ---------------------------------------------------------------------
  695. /* Not inlined to advoid including acquire-worker.h */
  696. pkgAcquire::Worker *pkgAcquire::WorkerStep(Worker *I)
  697. {
  698. return I->NextAcquire;
  699. }
  700. /*}}}*/
  701. // Acquire::Clean - Cleans a directory /*{{{*/
  702. // ---------------------------------------------------------------------
  703. /* This is a bit simplistic, it looks at every file in the dir and sees
  704. if it is part of the download set. */
  705. bool pkgAcquire::Clean(string Dir)
  706. {
  707. // non-existing directories are by definition clean…
  708. if (DirectoryExists(Dir) == false)
  709. return true;
  710. if(Dir == "/")
  711. return _error->Error(_("Clean of %s is not supported"), Dir.c_str());
  712. int const dirfd = open(Dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
  713. if (dirfd == -1)
  714. return _error->Errno("open",_("Unable to read %s"),Dir.c_str());
  715. DIR * const D = fdopendir(dirfd);
  716. if (D == nullptr)
  717. return _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
  718. for (struct dirent *E = readdir(D); E != nullptr; E = readdir(D))
  719. {
  720. // Skip some entries
  721. if (strcmp(E->d_name, "lock") == 0 ||
  722. strcmp(E->d_name, "partial") == 0 ||
  723. strcmp(E->d_name, "auxfiles") == 0 ||
  724. strcmp(E->d_name, "lost+found") == 0 ||
  725. strcmp(E->d_name, ".") == 0 ||
  726. strcmp(E->d_name, "..") == 0)
  727. continue;
  728. // Look in the get list and if not found nuke
  729. if (std::any_of(Items.cbegin(), Items.cend(),
  730. [&E](pkgAcquire::Item const * const I) {
  731. return flNotDir(I->DestFile) == E->d_name;
  732. }) == false)
  733. {
  734. RemoveFileAt("pkgAcquire::Clean", dirfd, E->d_name);
  735. }
  736. }
  737. closedir(D);
  738. return true;
  739. }
  740. /*}}}*/
  741. // Acquire::TotalNeeded - Number of bytes to fetch /*{{{*/
  742. // ---------------------------------------------------------------------
  743. /* This is the total number of bytes needed */
  744. APT_PURE unsigned long long pkgAcquire::TotalNeeded()
  745. {
  746. return std::accumulate(ItemsBegin(), ItemsEnd(), 0llu,
  747. [](unsigned long long const T, Item const * const I) {
  748. return T + I->FileSize;
  749. });
  750. }
  751. /*}}}*/
  752. // Acquire::FetchNeeded - Number of bytes needed to get /*{{{*/
  753. // ---------------------------------------------------------------------
  754. /* This is the number of bytes that is not local */
  755. APT_PURE unsigned long long pkgAcquire::FetchNeeded()
  756. {
  757. return std::accumulate(ItemsBegin(), ItemsEnd(), 0llu,
  758. [](unsigned long long const T, Item const * const I) {
  759. if (I->Local == false)
  760. return T + I->FileSize;
  761. else
  762. return T;
  763. });
  764. }
  765. /*}}}*/
  766. // Acquire::PartialPresent - Number of partial bytes we already have /*{{{*/
  767. // ---------------------------------------------------------------------
  768. /* This is the number of bytes that is not local */
  769. APT_PURE unsigned long long pkgAcquire::PartialPresent()
  770. {
  771. return std::accumulate(ItemsBegin(), ItemsEnd(), 0llu,
  772. [](unsigned long long const T, Item const * const I) {
  773. if (I->Local == false)
  774. return T + I->PartialSize;
  775. else
  776. return T;
  777. });
  778. }
  779. /*}}}*/
  780. // Acquire::UriBegin - Start iterator for the uri list /*{{{*/
  781. // ---------------------------------------------------------------------
  782. /* */
  783. pkgAcquire::UriIterator pkgAcquire::UriBegin()
  784. {
  785. return UriIterator(Queues);
  786. }
  787. /*}}}*/
  788. // Acquire::UriEnd - End iterator for the uri list /*{{{*/
  789. // ---------------------------------------------------------------------
  790. /* */
  791. pkgAcquire::UriIterator pkgAcquire::UriEnd()
  792. {
  793. return UriIterator(0);
  794. }
  795. /*}}}*/
  796. // Acquire::MethodConfig::MethodConfig - Constructor /*{{{*/
  797. class pkgAcquire::MethodConfig::Private
  798. {
  799. public:
  800. bool AuxRequests = false;
  801. };
  802. pkgAcquire::MethodConfig::MethodConfig() : d(new Private()), Next(0), SingleInstance(false),
  803. Pipeline(false), SendConfig(false), LocalOnly(false), NeedsCleanup(false),
  804. Removable(false)
  805. {
  806. }
  807. /*}}}*/
  808. bool pkgAcquire::MethodConfig::GetAuxRequests() const /*{{{*/
  809. {
  810. return d->AuxRequests;
  811. }
  812. /*}}}*/
  813. void pkgAcquire::MethodConfig::SetAuxRequests(bool const value) /*{{{*/
  814. {
  815. d->AuxRequests = value;
  816. }
  817. /*}}}*/
  818. // Queue::Queue - Constructor /*{{{*/
  819. // ---------------------------------------------------------------------
  820. /* */
  821. pkgAcquire::Queue::Queue(string const &name,pkgAcquire * const owner) : d(NULL), Next(0),
  822. Name(name), Items(0), Workers(0), Owner(owner), PipeDepth(0), MaxPipeDepth(1)
  823. {
  824. }
  825. /*}}}*/
  826. // Queue::~Queue - Destructor /*{{{*/
  827. // ---------------------------------------------------------------------
  828. /* */
  829. pkgAcquire::Queue::~Queue()
  830. {
  831. Shutdown(true);
  832. while (Items != 0)
  833. {
  834. QItem *Jnk = Items;
  835. Items = Items->Next;
  836. delete Jnk;
  837. }
  838. }
  839. /*}}}*/
  840. // Queue::Enqueue - Queue an item to the queue /*{{{*/
  841. // ---------------------------------------------------------------------
  842. /* */
  843. bool pkgAcquire::Queue::Enqueue(ItemDesc &Item)
  844. {
  845. // MetaKeysMatch checks whether the two items have no non-matching
  846. // meta-keys. If the items are not transaction items, it returns
  847. // true, so other items can still be merged.
  848. auto MetaKeysMatch = [](pkgAcquire::ItemDesc const &A, pkgAcquire::Queue::QItem const *B) {
  849. auto OwnerA = dynamic_cast<pkgAcqTransactionItem*>(A.Owner);
  850. if (OwnerA == nullptr)
  851. return true;
  852. for (auto const & OwnerBUncast : B->Owners) {
  853. auto OwnerB = dynamic_cast<pkgAcqTransactionItem*>(OwnerBUncast);
  854. if (OwnerB != nullptr && OwnerA->GetMetaKey() != OwnerB->GetMetaKey())
  855. return false;
  856. }
  857. return true;
  858. };
  859. QItem **OptimalI = &Items;
  860. QItem **I = &Items;
  861. // move to the end of the queue and check for duplicates here
  862. for (; *I != 0; ) {
  863. if (Item.URI == (*I)->URI && MetaKeysMatch(Item, *I))
  864. {
  865. if (_config->FindB("Debug::pkgAcquire::Worker",false) == true)
  866. std::cerr << " @ Queue: Action combined for " << Item.URI << " and " << (*I)->URI << std::endl;
  867. (*I)->Owners.push_back(Item.Owner);
  868. Item.Owner->Status = (*I)->Owner->Status;
  869. return false;
  870. }
  871. // Determine the optimal position to insert: before anything with a
  872. // higher priority.
  873. int priority = (*I)->GetPriority();
  874. I = &(*I)->Next;
  875. if (priority >= Item.Owner->Priority()) {
  876. OptimalI = I;
  877. }
  878. }
  879. // Create a new item
  880. QItem *Itm = new QItem;
  881. *Itm = Item;
  882. Itm->Next = *OptimalI;
  883. *OptimalI = Itm;
  884. Item.Owner->QueueCounter++;
  885. if (Items->Next == 0)
  886. Cycle();
  887. return true;
  888. }
  889. /*}}}*/
  890. // Queue::Dequeue - Remove an item from the queue /*{{{*/
  891. // ---------------------------------------------------------------------
  892. /* We return true if we hit something */
  893. bool pkgAcquire::Queue::Dequeue(Item *Owner)
  894. {
  895. if (Owner->Status == pkgAcquire::Item::StatFetching)
  896. return _error->Error("Tried to dequeue a fetching object");
  897. bool Res = false;
  898. QItem **I = &Items;
  899. for (; *I != 0;)
  900. {
  901. if (Owner == (*I)->Owner)
  902. {
  903. QItem *Jnk= *I;
  904. *I = (*I)->Next;
  905. Owner->QueueCounter--;
  906. delete Jnk;
  907. Res = true;
  908. }
  909. else
  910. I = &(*I)->Next;
  911. }
  912. return Res;
  913. }
  914. /*}}}*/
  915. // Queue::Startup - Start the worker processes /*{{{*/
  916. // ---------------------------------------------------------------------
  917. /* It is possible for this to be called with a pre-existing set of
  918. workers. */
  919. bool pkgAcquire::Queue::Startup()
  920. {
  921. if (Workers == 0)
  922. {
  923. URI U(Name);
  924. pkgAcquire::MethodConfig * const Cnf = Owner->GetConfig(U.Access);
  925. if (unlikely(Cnf == nullptr))
  926. return false;
  927. // now-running twin of the pkgAcquire::Enqueue call
  928. for (QItem *I = Items; I != 0; )
  929. {
  930. auto const INext = I->Next;
  931. for (auto &&O: I->Owners)
  932. CheckForBadItemAndFailIt(O, Cnf, Owner->Log);
  933. // if an item failed, it will be auto-dequeued invalidation our I here
  934. I = INext;
  935. }
  936. Workers = new Worker(this,Cnf,Owner->Log);
  937. Owner->Add(Workers);
  938. if (Workers->Start() == false)
  939. return false;
  940. /* When pipelining we commit 10 items. This needs to change when we
  941. added other source retry to have cycle maintain a pipeline depth
  942. on its own. */
  943. if (Cnf->Pipeline == true)
  944. MaxPipeDepth = _config->FindI("Acquire::Max-Pipeline-Depth",10);
  945. else
  946. MaxPipeDepth = 1;
  947. }
  948. return Cycle();
  949. }
  950. /*}}}*/
  951. // Queue::Shutdown - Shutdown the worker processes /*{{{*/
  952. // ---------------------------------------------------------------------
  953. /* If final is true then all workers are eliminated, otherwise only workers
  954. that do not need cleanup are removed */
  955. bool pkgAcquire::Queue::Shutdown(bool Final)
  956. {
  957. // Delete all of the workers
  958. pkgAcquire::Worker **Cur = &Workers;
  959. while (*Cur != 0)
  960. {
  961. pkgAcquire::Worker *Jnk = *Cur;
  962. if (Final == true || Jnk->GetConf()->NeedsCleanup == false)
  963. {
  964. *Cur = Jnk->NextQueue;
  965. Owner->Remove(Jnk);
  966. delete Jnk;
  967. }
  968. else
  969. Cur = &(*Cur)->NextQueue;
  970. }
  971. return true;
  972. }
  973. /*}}}*/
  974. // Queue::FindItem - Find a URI in the item list /*{{{*/
  975. // ---------------------------------------------------------------------
  976. /* */
  977. pkgAcquire::Queue::QItem *pkgAcquire::Queue::FindItem(string URI,pkgAcquire::Worker *Owner)
  978. {
  979. for (QItem *I = Items; I != 0; I = I->Next)
  980. if (I->URI == URI && I->Worker == Owner)
  981. return I;
  982. return 0;
  983. }
  984. /*}}}*/
  985. // Queue::ItemDone - Item has been completed /*{{{*/
  986. // ---------------------------------------------------------------------
  987. /* The worker signals this which causes the item to be removed from the
  988. queue. If this is the last queue instance then it is removed from the
  989. main queue too.*/
  990. bool pkgAcquire::Queue::ItemDone(QItem *Itm)
  991. {
  992. PipeDepth--;
  993. for (QItem::owner_iterator O = Itm->Owners.begin(); O != Itm->Owners.end(); ++O)
  994. {
  995. if ((*O)->Status == pkgAcquire::Item::StatFetching)
  996. (*O)->Status = pkgAcquire::Item::StatDone;
  997. }
  998. if (Itm->Owner->QueueCounter <= 1)
  999. Owner->Dequeue(Itm->Owner);
  1000. else
  1001. {
  1002. Dequeue(Itm->Owner);
  1003. Owner->Bump();
  1004. }
  1005. return Cycle();
  1006. }
  1007. /*}}}*/
  1008. // Queue::Cycle - Queue new items into the method /*{{{*/
  1009. // ---------------------------------------------------------------------
  1010. /* This locates a new idle item and sends it to the worker. If pipelining
  1011. is enabled then it keeps the pipe full. */
  1012. bool pkgAcquire::Queue::Cycle()
  1013. {
  1014. if (Items == 0 || Workers == 0)
  1015. return true;
  1016. if (PipeDepth < 0)
  1017. return _error->Error("Pipedepth failure");
  1018. // Look for a queable item
  1019. QItem *I = Items;
  1020. int ActivePriority = 0;
  1021. while (PipeDepth < static_cast<decltype(PipeDepth)>(MaxPipeDepth))
  1022. {
  1023. for (; I != 0; I = I->Next) {
  1024. if (I->Owner->Status == pkgAcquire::Item::StatFetching)
  1025. ActivePriority = std::max(ActivePriority, I->GetPriority());
  1026. if (I->Owner->Status == pkgAcquire::Item::StatIdle)
  1027. break;
  1028. }
  1029. // Nothing to do, queue is idle.
  1030. if (I == 0)
  1031. return true;
  1032. // This item has a lower priority than stuff in the pipeline, pretend
  1033. // the queue is idle
  1034. if (I->GetPriority() < ActivePriority)
  1035. return true;
  1036. I->Worker = Workers;
  1037. for (auto const &O: I->Owners)
  1038. O->Status = pkgAcquire::Item::StatFetching;
  1039. PipeDepth++;
  1040. if (Workers->QueueItem(I) == false)
  1041. return false;
  1042. }
  1043. return true;
  1044. }
  1045. /*}}}*/
  1046. // Queue::Bump - Fetch any pending objects if we are idle /*{{{*/
  1047. // ---------------------------------------------------------------------
  1048. /* This is called when an item in multiple queues is dequeued */
  1049. void pkgAcquire::Queue::Bump()
  1050. {
  1051. Cycle();
  1052. }
  1053. /*}}}*/
  1054. HashStringList pkgAcquire::Queue::QItem::GetExpectedHashes() const /*{{{*/
  1055. {
  1056. /* each Item can have multiple owners and each owner might have different
  1057. hashes, even if that is unlikely in practice and if so at least some
  1058. owners will later fail. There is one situation through which is not a
  1059. failure and still needs this handling: Two owners who expect the same
  1060. file, but one owner only knows the SHA1 while the other only knows SHA256. */
  1061. HashStringList superhsl;
  1062. for (pkgAcquire::Queue::QItem::owner_iterator O = Owners.begin(); O != Owners.end(); ++O)
  1063. {
  1064. HashStringList const hsl = (*O)->GetExpectedHashes();
  1065. // we merge both lists - if we find disagreement send no hashes
  1066. HashStringList::const_iterator hs = hsl.begin();
  1067. for (; hs != hsl.end(); ++hs)
  1068. if (superhsl.push_back(*hs) == false)
  1069. break;
  1070. if (hs != hsl.end())
  1071. {
  1072. superhsl.clear();
  1073. break;
  1074. }
  1075. }
  1076. return superhsl;
  1077. }
  1078. /*}}}*/
  1079. APT_PURE unsigned long long pkgAcquire::Queue::QItem::GetMaximumSize() const /*{{{*/
  1080. {
  1081. unsigned long long Maximum = std::numeric_limits<unsigned long long>::max();
  1082. for (auto const &O: Owners)
  1083. {
  1084. if (O->FileSize == 0)
  1085. continue;
  1086. Maximum = std::min(Maximum, O->FileSize);
  1087. }
  1088. if (Maximum == std::numeric_limits<unsigned long long>::max())
  1089. return 0;
  1090. return Maximum;
  1091. }
  1092. /*}}}*/
  1093. APT_PURE int pkgAcquire::Queue::QItem::GetPriority() const /*{{{*/
  1094. {
  1095. int Priority = 0;
  1096. for (auto const &O: Owners)
  1097. Priority = std::max(Priority, O->Priority());
  1098. return Priority;
  1099. }
  1100. /*}}}*/
  1101. void pkgAcquire::Queue::QItem::SyncDestinationFiles() const /*{{{*/
  1102. {
  1103. /* ensure that the first owner has the best partial file of all and
  1104. the rest have (potentially dangling) symlinks to it so that
  1105. everything (like progress reporting) finds it easily */
  1106. std::string superfile = Owner->DestFile;
  1107. off_t supersize = 0;
  1108. for (pkgAcquire::Queue::QItem::owner_iterator O = Owners.begin(); O != Owners.end(); ++O)
  1109. {
  1110. if ((*O)->DestFile == superfile)
  1111. continue;
  1112. struct stat file;
  1113. if (lstat((*O)->DestFile.c_str(),&file) == 0)
  1114. {
  1115. if ((file.st_mode & S_IFREG) == 0)
  1116. RemoveFile("SyncDestinationFiles", (*O)->DestFile);
  1117. else if (supersize < file.st_size)
  1118. {
  1119. supersize = file.st_size;
  1120. RemoveFile("SyncDestinationFiles", superfile);
  1121. rename((*O)->DestFile.c_str(), superfile.c_str());
  1122. }
  1123. else
  1124. RemoveFile("SyncDestinationFiles", (*O)->DestFile);
  1125. if (symlink(superfile.c_str(), (*O)->DestFile.c_str()) != 0)
  1126. {
  1127. ; // not a problem per-se and no real alternative
  1128. }
  1129. }
  1130. }
  1131. }
  1132. /*}}}*/
  1133. std::string pkgAcquire::Queue::QItem::Custom600Headers() const /*{{{*/
  1134. {
  1135. /* The others are relatively easy to merge, but this one?
  1136. Lets not merge and see how far we can run with it…
  1137. Likely, nobody will ever notice as all the items will
  1138. be of the same class and hence generate the same headers. */
  1139. return Owner->Custom600Headers();
  1140. }
  1141. /*}}}*/
  1142. // AcquireStatus::pkgAcquireStatus - Constructor /*{{{*/
  1143. // ---------------------------------------------------------------------
  1144. /* */
  1145. pkgAcquireStatus::pkgAcquireStatus() : d(NULL), Percent(-1), Update(true), MorePulses(false)
  1146. {
  1147. Start();
  1148. }
  1149. /*}}}*/
  1150. // AcquireStatus::Pulse - Called periodically /*{{{*/
  1151. // ---------------------------------------------------------------------
  1152. /* This computes some internal state variables for the derived classes to
  1153. use. It generates the current downloaded bytes and total bytes to download
  1154. as well as the current CPS estimate. */
  1155. static struct timeval GetTimevalFromSteadyClock()
  1156. {
  1157. auto const Time = std::chrono::steady_clock::now().time_since_epoch();
  1158. auto const Time_sec = std::chrono::duration_cast<std::chrono::seconds>(Time);
  1159. auto const Time_usec = std::chrono::duration_cast<std::chrono::microseconds>(Time - Time_sec);
  1160. return { Time_sec.count(), Time_usec.count() };
  1161. }
  1162. bool pkgAcquireStatus::Pulse(pkgAcquire *Owner)
  1163. {
  1164. TotalBytes = 0;
  1165. CurrentBytes = 0;
  1166. TotalItems = 0;
  1167. CurrentItems = 0;
  1168. // Compute the total number of bytes to fetch
  1169. unsigned int Unknown = 0;
  1170. unsigned int Count = 0;
  1171. bool ExpectAdditionalItems = false;
  1172. for (pkgAcquire::ItemCIterator I = Owner->ItemsBegin();
  1173. I != Owner->ItemsEnd();
  1174. ++I, ++Count)
  1175. {
  1176. TotalItems++;
  1177. if ((*I)->Status == pkgAcquire::Item::StatDone)
  1178. ++CurrentItems;
  1179. // do we expect to acquire more files than we know of yet?
  1180. if ((*I)->ExpectedAdditionalItems > 0)
  1181. ExpectAdditionalItems = true;
  1182. TotalBytes += (*I)->FileSize;
  1183. if ((*I)->Complete == true)
  1184. CurrentBytes += (*I)->FileSize;
  1185. if ((*I)->FileSize == 0 && (*I)->Complete == false)
  1186. ++Unknown;
  1187. }
  1188. // Compute the current completion
  1189. unsigned long long ResumeSize = 0;
  1190. for (pkgAcquire::Worker *I = Owner->WorkersBegin(); I != 0;
  1191. I = Owner->WorkerStep(I))
  1192. {
  1193. if (I->CurrentItem != 0 && I->CurrentItem->Owner->Complete == false)
  1194. {
  1195. CurrentBytes += I->CurrentSize;
  1196. ResumeSize += I->ResumePoint;
  1197. // Files with unknown size always have 100% completion
  1198. if (I->CurrentItem->Owner->FileSize == 0 &&
  1199. I->CurrentItem->Owner->Complete == false)
  1200. TotalBytes += I->CurrentSize;
  1201. }
  1202. }
  1203. // Normalize the figures and account for unknown size downloads
  1204. if (TotalBytes <= 0)
  1205. TotalBytes = 1;
  1206. if (Unknown == Count)
  1207. TotalBytes = Unknown;
  1208. // Wha?! Is not supposed to happen.
  1209. if (CurrentBytes > TotalBytes)
  1210. CurrentBytes = TotalBytes;
  1211. // Compute the CPS
  1212. struct timeval NewTime = GetTimevalFromSteadyClock();
  1213. if ((NewTime.tv_sec - Time.tv_sec == 6 && NewTime.tv_usec > Time.tv_usec) ||
  1214. NewTime.tv_sec - Time.tv_sec > 6)
  1215. {
  1216. std::chrono::duration<double> Delta =
  1217. std::chrono::seconds(NewTime.tv_sec - Time.tv_sec) +
  1218. std::chrono::microseconds(NewTime.tv_sec - Time.tv_usec);
  1219. // Compute the CPS value
  1220. if (Delta < std::chrono::milliseconds(10))
  1221. CurrentCPS = 0;
  1222. else
  1223. CurrentCPS = ((CurrentBytes - ResumeSize) - LastBytes)/ Delta.count();
  1224. LastBytes = CurrentBytes - ResumeSize;
  1225. ElapsedTime = llround(Delta.count());
  1226. Time = NewTime;
  1227. }
  1228. double const OldPercent = Percent;
  1229. // calculate the percentage, if we have too little data assume 1%
  1230. if (ExpectAdditionalItems)
  1231. Percent = 0;
  1232. else
  1233. // use both files and bytes because bytes can be unreliable
  1234. Percent = (0.8 * (CurrentBytes/double(TotalBytes)*100.0) +
  1235. 0.2 * (CurrentItems/double(TotalItems)*100.0));
  1236. // debug
  1237. if (_config->FindB("Debug::acquire::progress", false) == true)
  1238. {
  1239. std::clog
  1240. << "["
  1241. << std::setw(5) << std::setprecision(4) << std::showpoint << Percent
  1242. << "]"
  1243. << " Bytes: "
  1244. << SizeToStr(CurrentBytes) << " / " << SizeToStr(TotalBytes)
  1245. << " # Files: "
  1246. << CurrentItems << " / " << TotalItems
  1247. << std::endl;
  1248. }
  1249. double const DiffPercent = Percent - OldPercent;
  1250. if (DiffPercent < 0.001 && _config->FindB("Acquire::Progress::Diffpercent", false) == true)
  1251. return true;
  1252. int fd = _config->FindI("APT::Status-Fd",-1);
  1253. if(fd > 0)
  1254. {
  1255. ostringstream status;
  1256. unsigned long long ETA = 0;
  1257. if(CurrentCPS > 0 && TotalBytes > CurrentBytes)
  1258. ETA = (TotalBytes - CurrentBytes) / CurrentCPS;
  1259. std::string msg;
  1260. long i = CurrentItems < TotalItems ? CurrentItems + 1 : CurrentItems;
  1261. // only show the ETA if it makes sense
  1262. if (ETA > 0 && ETA < std::chrono::seconds(std::chrono::hours(24 * 2)).count())
  1263. strprintf(msg, _("Retrieving file %li of %li (%s remaining)"), i, TotalItems, TimeToStr(ETA).c_str());
  1264. else
  1265. strprintf(msg, _("Retrieving file %li of %li"), i, TotalItems);
  1266. // build the status str
  1267. std::ostringstream str;
  1268. str.imbue(std::locale::classic());
  1269. str.precision(4);
  1270. str << "dlstatus" << ':' << std::fixed << i << ':' << Percent << ':' << msg << '\n';
  1271. auto const dlstatus = str.str();
  1272. FileFd::Write(fd, dlstatus.data(), dlstatus.size());
  1273. }
  1274. return true;
  1275. }
  1276. /*}}}*/
  1277. // AcquireStatus::Start - Called when the download is started /*{{{*/
  1278. // ---------------------------------------------------------------------
  1279. /* We just reset the counters */
  1280. void pkgAcquireStatus::Start()
  1281. {
  1282. Time = StartTime = GetTimevalFromSteadyClock();
  1283. LastBytes = 0;
  1284. CurrentCPS = 0;
  1285. CurrentBytes = 0;
  1286. TotalBytes = 0;
  1287. FetchedBytes = 0;
  1288. ElapsedTime = 0;
  1289. TotalItems = 0;
  1290. CurrentItems = 0;
  1291. }
  1292. /*}}}*/
  1293. // AcquireStatus::Stop - Finished downloading /*{{{*/
  1294. // ---------------------------------------------------------------------
  1295. /* This accurately computes the elapsed time and the total overall CPS. */
  1296. void pkgAcquireStatus::Stop()
  1297. {
  1298. // Compute the CPS and elapsed time
  1299. struct timeval NewTime = GetTimevalFromSteadyClock();
  1300. std::chrono::duration<double> Delta =
  1301. std::chrono::seconds(NewTime.tv_sec - StartTime.tv_sec) +
  1302. std::chrono::microseconds(NewTime.tv_sec - StartTime.tv_usec);
  1303. // Compute the CPS value
  1304. if (Delta < std::chrono::milliseconds(10))
  1305. CurrentCPS = 0;
  1306. else
  1307. CurrentCPS = FetchedBytes / Delta.count();
  1308. LastBytes = CurrentBytes;
  1309. ElapsedTime = llround(Delta.count());
  1310. }
  1311. /*}}}*/
  1312. // AcquireStatus::Fetched - Called when a byte set has been fetched /*{{{*/
  1313. // ---------------------------------------------------------------------
  1314. /* This is used to get accurate final transfer rate reporting. */
  1315. void pkgAcquireStatus::Fetched(unsigned long long Size,unsigned long long Resume)
  1316. {
  1317. FetchedBytes += Size - Resume;
  1318. }
  1319. /*}}}*/
  1320. bool pkgAcquireStatus::ReleaseInfoChanges(metaIndex const * const LastRelease, metaIndex const * const CurrentRelease, std::vector<ReleaseInfoChange> &&Changes)/*{{{*/
  1321. {
  1322. auto const virt = dynamic_cast<pkgAcquireStatus2*>(this);
  1323. if (virt != nullptr)
  1324. return virt->ReleaseInfoChanges(LastRelease, CurrentRelease, std::move(Changes));
  1325. return ReleaseInfoChangesAsGlobalErrors(std::move(Changes));
  1326. }
  1327. /*}}}*/
  1328. bool pkgAcquireStatus::ReleaseInfoChangesAsGlobalErrors(std::vector<ReleaseInfoChange> &&Changes)/*{{{*/
  1329. {
  1330. bool AllOkay = true;
  1331. for (auto const &c: Changes)
  1332. if (c.DefaultAction)
  1333. _error->Notice("%s", c.Message.c_str());
  1334. else
  1335. {
  1336. _error->Error("%s", c.Message.c_str());
  1337. AllOkay = false;
  1338. }
  1339. return AllOkay;
  1340. }
  1341. /*}}}*/
  1342. bool pkgAcquireStatus2::ReleaseInfoChanges(metaIndex const * const, metaIndex const * const, std::vector<ReleaseInfoChange> &&Changes)
  1343. {
  1344. return ReleaseInfoChangesAsGlobalErrors(std::move(Changes));
  1345. }
  1346. pkgAcquireStatus2::pkgAcquireStatus2() : pkgAcquireStatus() {}
  1347. pkgAcquireStatus2::~pkgAcquireStatus2() {}
  1348. pkgAcquire::UriIterator::UriIterator(pkgAcquire::Queue *Q) : d(NULL), CurQ(Q), CurItem(0)
  1349. {
  1350. while (CurItem == 0 && CurQ != 0)
  1351. {
  1352. CurItem = CurQ->Items;
  1353. CurQ = CurQ->Next;
  1354. }
  1355. }
  1356. pkgAcquire::UriIterator::~UriIterator() {}
  1357. pkgAcquire::MethodConfig::~MethodConfig() {}
  1358. pkgAcquireStatus::~pkgAcquireStatus() {}