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.
 
 
 
 
 
 

1384 lines
42 KiB

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