acquire.cc 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  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. void pkgAcquire::Enqueue(ItemDesc &Item)
  251. {
  252. // Determine which queue to put the item in
  253. const MethodConfig *Config;
  254. string Name = QueueName(Item.URI,Config);
  255. if (Name.empty() == true)
  256. return;
  257. // Find the queue structure
  258. Queue *I = Queues;
  259. for (; I != 0 && I->Name != Name; I = I->Next);
  260. if (I == 0)
  261. {
  262. I = new Queue(Name,this);
  263. I->Next = Queues;
  264. Queues = I;
  265. if (Running == true)
  266. I->Startup();
  267. }
  268. // See if this is a local only URI
  269. if (Config->LocalOnly == true && Item.Owner->Complete == false)
  270. Item.Owner->Local = true;
  271. Item.Owner->Status = Item::StatIdle;
  272. // Queue it into the named queue
  273. if(I->Enqueue(Item))
  274. ToFetch++;
  275. // Some trace stuff
  276. if (Debug == true)
  277. {
  278. clog << "Fetching " << Item.URI << endl;
  279. clog << " to " << Item.Owner->DestFile << endl;
  280. clog << " Queue is: " << Name << endl;
  281. }
  282. }
  283. /*}}}*/
  284. // Acquire::Dequeue - Remove an item from all queues /*{{{*/
  285. // ---------------------------------------------------------------------
  286. /* This is called when an item is finished being fetched. It removes it
  287. from all the queues */
  288. void pkgAcquire::Dequeue(Item *Itm)
  289. {
  290. Queue *I = Queues;
  291. bool Res = false;
  292. if (Debug == true)
  293. clog << "Dequeuing " << Itm->DestFile << endl;
  294. for (; I != 0; I = I->Next)
  295. {
  296. if (I->Dequeue(Itm))
  297. {
  298. Res = true;
  299. if (Debug == true)
  300. clog << "Dequeued from " << I->Name << endl;
  301. }
  302. }
  303. if (Res == true)
  304. ToFetch--;
  305. }
  306. /*}}}*/
  307. // Acquire::QueueName - Return the name of the queue for this URI /*{{{*/
  308. // ---------------------------------------------------------------------
  309. /* The string returned depends on the configuration settings and the
  310. method parameters. Given something like http://foo.org/bar it can
  311. return http://foo.org or http */
  312. string pkgAcquire::QueueName(string Uri,MethodConfig const *&Config)
  313. {
  314. URI U(Uri);
  315. Config = GetConfig(U.Access);
  316. if (Config == 0)
  317. return string();
  318. /* Single-Instance methods get exactly one queue per URI. This is
  319. also used for the Access queue method */
  320. if (Config->SingleInstance == true || QueueMode == QueueAccess)
  321. return U.Access;
  322. string AccessSchema = U.Access + ':',
  323. FullQueueName = AccessSchema + U.Host;
  324. unsigned int Instances = 0, SchemaLength = AccessSchema.length();
  325. Queue *I = Queues;
  326. for (; I != 0; I = I->Next) {
  327. // if the queue already exists, re-use it
  328. if (I->Name == FullQueueName)
  329. return FullQueueName;
  330. if (I->Name.compare(0, SchemaLength, AccessSchema) == 0)
  331. Instances++;
  332. }
  333. if (Debug) {
  334. clog << "Found " << Instances << " instances of " << U.Access << endl;
  335. }
  336. if (Instances >= (unsigned int)_config->FindI("Acquire::QueueHost::Limit",10))
  337. return U.Access;
  338. return FullQueueName;
  339. }
  340. /*}}}*/
  341. // Acquire::GetConfig - Fetch the configuration information /*{{{*/
  342. // ---------------------------------------------------------------------
  343. /* This locates the configuration structure for an access method. If
  344. a config structure cannot be found a Worker will be created to
  345. retrieve it */
  346. pkgAcquire::MethodConfig *pkgAcquire::GetConfig(string Access)
  347. {
  348. // Search for an existing config
  349. MethodConfig *Conf;
  350. for (Conf = Configs; Conf != 0; Conf = Conf->Next)
  351. if (Conf->Access == Access)
  352. return Conf;
  353. // Create the new config class
  354. Conf = new MethodConfig;
  355. Conf->Access = Access;
  356. Conf->Next = Configs;
  357. Configs = Conf;
  358. // Create the worker to fetch the configuration
  359. Worker Work(Conf);
  360. if (Work.Start() == false)
  361. return 0;
  362. /* if a method uses DownloadLimit, we switch to SingleInstance mode */
  363. if(_config->FindI("Acquire::"+Access+"::Dl-Limit",0) > 0)
  364. Conf->SingleInstance = true;
  365. return Conf;
  366. }
  367. /*}}}*/
  368. // Acquire::SetFds - Deal with readable FDs /*{{{*/
  369. // ---------------------------------------------------------------------
  370. /* Collect FDs that have activity monitors into the fd sets */
  371. void pkgAcquire::SetFds(int &Fd,fd_set *RSet,fd_set *WSet)
  372. {
  373. for (Worker *I = Workers; I != 0; I = I->NextAcquire)
  374. {
  375. if (I->InReady == true && I->InFd >= 0)
  376. {
  377. if (Fd < I->InFd)
  378. Fd = I->InFd;
  379. FD_SET(I->InFd,RSet);
  380. }
  381. if (I->OutReady == true && I->OutFd >= 0)
  382. {
  383. if (Fd < I->OutFd)
  384. Fd = I->OutFd;
  385. FD_SET(I->OutFd,WSet);
  386. }
  387. }
  388. }
  389. /*}}}*/
  390. // Acquire::RunFds - Deal with active FDs /*{{{*/
  391. // ---------------------------------------------------------------------
  392. /* Dispatch active FDs over to the proper workers. It is very important
  393. that a worker never be erased while this is running! The queue class
  394. should never erase a worker except during shutdown processing. */
  395. void pkgAcquire::RunFds(fd_set *RSet,fd_set *WSet)
  396. {
  397. for (Worker *I = Workers; I != 0; I = I->NextAcquire)
  398. {
  399. if (I->InFd >= 0 && FD_ISSET(I->InFd,RSet) != 0)
  400. I->InFdReady();
  401. if (I->OutFd >= 0 && FD_ISSET(I->OutFd,WSet) != 0)
  402. I->OutFdReady();
  403. }
  404. }
  405. /*}}}*/
  406. // Acquire::Run - Run the fetch sequence /*{{{*/
  407. // ---------------------------------------------------------------------
  408. /* This runs the queues. It manages a select loop for all of the
  409. Worker tasks. The workers interact with the queues and items to
  410. manage the actual fetch. */
  411. static bool IsAccessibleBySandboxUser(std::string const &filename, bool const ReadWrite)
  412. {
  413. // you would think this is easily to answer with faccessat, right? Wrong!
  414. // It e.g. gets groups wrong, so the only thing which works reliable is trying
  415. // to open the file we want to open later on…
  416. if (unlikely(filename.empty()))
  417. return true;
  418. if (ReadWrite == false)
  419. {
  420. errno = 0;
  421. // can we read a file? Note that non-existing files are "fine"
  422. int const fd = open(filename.c_str(), O_RDONLY | O_CLOEXEC);
  423. if (fd == -1 && errno == EACCES)
  424. return false;
  425. close(fd);
  426. return true;
  427. }
  428. else
  429. {
  430. // the file might not exist yet and even if it does we will fix permissions,
  431. // so important is here just that the directory it is in allows that
  432. std::string const dirname = flNotFile(filename);
  433. if (unlikely(dirname.empty()))
  434. return true;
  435. char const * const filetag = ".apt-acquire-privs-test.XXXXXX";
  436. std::string const tmpfile_tpl = flCombine(dirname, filetag);
  437. std::unique_ptr<char, decltype(std::free) *> tmpfile { strdup(tmpfile_tpl.c_str()), std::free };
  438. int const fd = mkstemp(tmpfile.get());
  439. if (fd == -1 && errno == EACCES)
  440. return false;
  441. RemoveFile("IsAccessibleBySandboxUser", tmpfile.get());
  442. close(fd);
  443. return true;
  444. }
  445. }
  446. static void CheckDropPrivsMustBeDisabled(pkgAcquire const &Fetcher)
  447. {
  448. if(getuid() != 0)
  449. return;
  450. std::string const SandboxUser = _config->Find("APT::Sandbox::User");
  451. if (SandboxUser.empty() || SandboxUser == "root")
  452. return;
  453. struct passwd const * const pw = getpwnam(SandboxUser.c_str());
  454. if (pw == NULL)
  455. return;
  456. gid_t const old_euid = geteuid();
  457. gid_t const old_egid = getegid();
  458. long const ngroups_max = sysconf(_SC_NGROUPS_MAX);
  459. std::unique_ptr<gid_t[]> old_gidlist(new gid_t[ngroups_max]);
  460. if (unlikely(old_gidlist == NULL))
  461. return;
  462. ssize_t old_gidlist_nr;
  463. if ((old_gidlist_nr = getgroups(ngroups_max, old_gidlist.get())) < 0)
  464. {
  465. _error->FatalE("getgroups", "getgroups %lu failed", ngroups_max);
  466. old_gidlist[0] = 0;
  467. old_gidlist_nr = 1;
  468. }
  469. if (setgroups(1, &pw->pw_gid))
  470. _error->FatalE("setgroups", "setgroups %u failed", pw->pw_gid);
  471. if (setegid(pw->pw_gid) != 0)
  472. _error->FatalE("setegid", "setegid %u failed", pw->pw_gid);
  473. if (seteuid(pw->pw_uid) != 0)
  474. _error->FatalE("seteuid", "seteuid %u failed", pw->pw_uid);
  475. for (pkgAcquire::ItemCIterator I = Fetcher.ItemsBegin();
  476. I != Fetcher.ItemsEnd(); ++I)
  477. {
  478. // no need to drop privileges for a complete file
  479. if ((*I)->Complete == true)
  480. continue;
  481. // if destination file is inaccessible all hope is lost for privilege dropping
  482. if (IsAccessibleBySandboxUser((*I)->DestFile, true) == false)
  483. {
  484. _error->WarningE("pkgAcquire::Run", _("Can't drop privileges for downloading as file '%s' couldn't be accessed by user '%s'."),
  485. (*I)->DestFile.c_str(), SandboxUser.c_str());
  486. _config->Set("APT::Sandbox::User", "");
  487. break;
  488. }
  489. // if its the source file (e.g. local sources) we might be lucky
  490. // by dropping the dropping only for some methods.
  491. URI const source = (*I)->DescURI();
  492. if (source.Access == "file" || source.Access == "copy")
  493. {
  494. std::string const conf = "Binary::" + source.Access + "::APT::Sandbox::User";
  495. if (_config->Exists(conf) == true)
  496. continue;
  497. if (IsAccessibleBySandboxUser(source.Path, false) == false)
  498. {
  499. _error->NoticeE("pkgAcquire::Run", _("Can't drop privileges for downloading as file '%s' couldn't be accessed by user '%s'."),
  500. source.Path.c_str(), SandboxUser.c_str());
  501. _config->CndSet("Binary::file::APT::Sandbox::User", "root");
  502. _config->CndSet("Binary::copy::APT::Sandbox::User", "root");
  503. }
  504. }
  505. }
  506. if (seteuid(old_euid) != 0)
  507. _error->FatalE("seteuid", "seteuid %u failed", old_euid);
  508. if (setegid(old_egid) != 0)
  509. _error->FatalE("setegid", "setegid %u failed", old_egid);
  510. if (setgroups(old_gidlist_nr, old_gidlist.get()))
  511. _error->FatalE("setgroups", "setgroups %u failed", 0);
  512. }
  513. pkgAcquire::RunResult pkgAcquire::Run(int PulseIntervall)
  514. {
  515. _error->PushToStack();
  516. CheckDropPrivsMustBeDisabled(*this);
  517. Running = true;
  518. for (Queue *I = Queues; I != 0; I = I->Next)
  519. I->Startup();
  520. if (Log != 0)
  521. Log->Start();
  522. bool WasCancelled = false;
  523. // Run till all things have been acquired
  524. struct timeval tv;
  525. tv.tv_sec = 0;
  526. tv.tv_usec = PulseIntervall;
  527. while (ToFetch > 0)
  528. {
  529. fd_set RFds;
  530. fd_set WFds;
  531. int Highest = 0;
  532. FD_ZERO(&RFds);
  533. FD_ZERO(&WFds);
  534. SetFds(Highest,&RFds,&WFds);
  535. int Res;
  536. do
  537. {
  538. Res = select(Highest+1,&RFds,&WFds,0,&tv);
  539. }
  540. while (Res < 0 && errno == EINTR);
  541. if (Res < 0)
  542. {
  543. _error->Errno("select","Select has failed");
  544. break;
  545. }
  546. RunFds(&RFds,&WFds);
  547. // Timeout, notify the log class
  548. if (Res == 0 || (Log != 0 && Log->Update == true))
  549. {
  550. tv.tv_usec = PulseIntervall;
  551. for (Worker *I = Workers; I != 0; I = I->NextAcquire)
  552. I->Pulse();
  553. if (Log != 0 && Log->Pulse(this) == false)
  554. {
  555. WasCancelled = true;
  556. break;
  557. }
  558. }
  559. }
  560. if (Log != 0)
  561. Log->Stop();
  562. // Shut down the acquire bits
  563. Running = false;
  564. for (Queue *I = Queues; I != 0; I = I->Next)
  565. I->Shutdown(false);
  566. // Shut down the items
  567. for (ItemIterator I = Items.begin(); I != Items.end(); ++I)
  568. (*I)->Finished();
  569. bool const newError = _error->PendingError();
  570. _error->MergeWithStack();
  571. if (newError)
  572. return Failed;
  573. if (WasCancelled)
  574. return Cancelled;
  575. return Continue;
  576. }
  577. /*}}}*/
  578. // Acquire::Bump - Called when an item is dequeued /*{{{*/
  579. // ---------------------------------------------------------------------
  580. /* This routine bumps idle queues in hopes that they will be able to fetch
  581. the dequeued item */
  582. void pkgAcquire::Bump()
  583. {
  584. for (Queue *I = Queues; I != 0; I = I->Next)
  585. I->Bump();
  586. }
  587. /*}}}*/
  588. // Acquire::WorkerStep - Step to the next worker /*{{{*/
  589. // ---------------------------------------------------------------------
  590. /* Not inlined to advoid including acquire-worker.h */
  591. pkgAcquire::Worker *pkgAcquire::WorkerStep(Worker *I)
  592. {
  593. return I->NextAcquire;
  594. }
  595. /*}}}*/
  596. // Acquire::Clean - Cleans a directory /*{{{*/
  597. // ---------------------------------------------------------------------
  598. /* This is a bit simplistic, it looks at every file in the dir and sees
  599. if it is part of the download set. */
  600. bool pkgAcquire::Clean(string Dir)
  601. {
  602. // non-existing directories are by definition clean…
  603. if (DirectoryExists(Dir) == false)
  604. return true;
  605. if(Dir == "/")
  606. return _error->Error(_("Clean of %s is not supported"), Dir.c_str());
  607. DIR *D = opendir(Dir.c_str());
  608. if (D == 0)
  609. return _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
  610. string StartDir = SafeGetCWD();
  611. if (chdir(Dir.c_str()) != 0)
  612. {
  613. closedir(D);
  614. return _error->Errno("chdir",_("Unable to change to %s"),Dir.c_str());
  615. }
  616. for (struct dirent *Dir = readdir(D); Dir != 0; Dir = readdir(D))
  617. {
  618. // Skip some files..
  619. if (strcmp(Dir->d_name,"lock") == 0 ||
  620. strcmp(Dir->d_name,"partial") == 0 ||
  621. strcmp(Dir->d_name,"lost+found") == 0 ||
  622. strcmp(Dir->d_name,".") == 0 ||
  623. strcmp(Dir->d_name,"..") == 0)
  624. continue;
  625. // Look in the get list
  626. ItemCIterator I = Items.begin();
  627. for (; I != Items.end(); ++I)
  628. if (flNotDir((*I)->DestFile) == Dir->d_name)
  629. break;
  630. // Nothing found, nuke it
  631. if (I == Items.end())
  632. RemoveFile("Clean", Dir->d_name);
  633. };
  634. closedir(D);
  635. if (chdir(StartDir.c_str()) != 0)
  636. return _error->Errno("chdir",_("Unable to change to %s"),StartDir.c_str());
  637. return true;
  638. }
  639. /*}}}*/
  640. // Acquire::TotalNeeded - Number of bytes to fetch /*{{{*/
  641. // ---------------------------------------------------------------------
  642. /* This is the total number of bytes needed */
  643. APT_PURE unsigned long long pkgAcquire::TotalNeeded()
  644. {
  645. return std::accumulate(ItemsBegin(), ItemsEnd(), 0,
  646. [](unsigned long long const T, Item const * const I) {
  647. return T + I->FileSize;
  648. });
  649. }
  650. /*}}}*/
  651. // Acquire::FetchNeeded - Number of bytes needed to get /*{{{*/
  652. // ---------------------------------------------------------------------
  653. /* This is the number of bytes that is not local */
  654. APT_PURE unsigned long long pkgAcquire::FetchNeeded()
  655. {
  656. return std::accumulate(ItemsBegin(), ItemsEnd(), 0,
  657. [](unsigned long long const T, Item const * const I) {
  658. if (I->Local == false)
  659. return T + I->FileSize;
  660. else
  661. return T;
  662. });
  663. }
  664. /*}}}*/
  665. // Acquire::PartialPresent - Number of partial bytes we already have /*{{{*/
  666. // ---------------------------------------------------------------------
  667. /* This is the number of bytes that is not local */
  668. APT_PURE unsigned long long pkgAcquire::PartialPresent()
  669. {
  670. return std::accumulate(ItemsBegin(), ItemsEnd(), 0,
  671. [](unsigned long long const T, Item const * const I) {
  672. if (I->Local == false)
  673. return T + I->PartialSize;
  674. else
  675. return T;
  676. });
  677. }
  678. /*}}}*/
  679. // Acquire::UriBegin - Start iterator for the uri list /*{{{*/
  680. // ---------------------------------------------------------------------
  681. /* */
  682. pkgAcquire::UriIterator pkgAcquire::UriBegin()
  683. {
  684. return UriIterator(Queues);
  685. }
  686. /*}}}*/
  687. // Acquire::UriEnd - End iterator for the uri list /*{{{*/
  688. // ---------------------------------------------------------------------
  689. /* */
  690. pkgAcquire::UriIterator pkgAcquire::UriEnd()
  691. {
  692. return UriIterator(0);
  693. }
  694. /*}}}*/
  695. // Acquire::MethodConfig::MethodConfig - Constructor /*{{{*/
  696. // ---------------------------------------------------------------------
  697. /* */
  698. pkgAcquire::MethodConfig::MethodConfig() : d(NULL), Next(0), SingleInstance(false),
  699. Pipeline(false), SendConfig(false), LocalOnly(false), NeedsCleanup(false),
  700. Removable(false)
  701. {
  702. }
  703. /*}}}*/
  704. // Queue::Queue - Constructor /*{{{*/
  705. // ---------------------------------------------------------------------
  706. /* */
  707. pkgAcquire::Queue::Queue(string const &name,pkgAcquire * const owner) : d(NULL), Next(0),
  708. Name(name), Items(0), Workers(0), Owner(owner), PipeDepth(0), MaxPipeDepth(1)
  709. {
  710. }
  711. /*}}}*/
  712. // Queue::~Queue - Destructor /*{{{*/
  713. // ---------------------------------------------------------------------
  714. /* */
  715. pkgAcquire::Queue::~Queue()
  716. {
  717. Shutdown(true);
  718. while (Items != 0)
  719. {
  720. QItem *Jnk = Items;
  721. Items = Items->Next;
  722. delete Jnk;
  723. }
  724. }
  725. /*}}}*/
  726. // Queue::Enqueue - Queue an item to the queue /*{{{*/
  727. // ---------------------------------------------------------------------
  728. /* */
  729. bool pkgAcquire::Queue::Enqueue(ItemDesc &Item)
  730. {
  731. QItem **I = &Items;
  732. // move to the end of the queue and check for duplicates here
  733. HashStringList const hsl = Item.Owner->GetExpectedHashes();
  734. for (; *I != 0; I = &(*I)->Next)
  735. if (Item.URI == (*I)->URI || hsl == (*I)->Owner->GetExpectedHashes())
  736. {
  737. if (_config->FindB("Debug::pkgAcquire::Worker",false) == true)
  738. std::cerr << " @ Queue: Action combined for " << Item.URI << " and " << (*I)->URI << std::endl;
  739. (*I)->Owners.push_back(Item.Owner);
  740. Item.Owner->Status = (*I)->Owner->Status;
  741. return false;
  742. }
  743. // Create a new item
  744. QItem *Itm = new QItem;
  745. *Itm = Item;
  746. Itm->Next = 0;
  747. *I = Itm;
  748. Item.Owner->QueueCounter++;
  749. if (Items->Next == 0)
  750. Cycle();
  751. return true;
  752. }
  753. /*}}}*/
  754. // Queue::Dequeue - Remove an item from the queue /*{{{*/
  755. // ---------------------------------------------------------------------
  756. /* We return true if we hit something */
  757. bool pkgAcquire::Queue::Dequeue(Item *Owner)
  758. {
  759. if (Owner->Status == pkgAcquire::Item::StatFetching)
  760. return _error->Error("Tried to dequeue a fetching object");
  761. bool Res = false;
  762. QItem **I = &Items;
  763. for (; *I != 0;)
  764. {
  765. if (Owner == (*I)->Owner)
  766. {
  767. QItem *Jnk= *I;
  768. *I = (*I)->Next;
  769. Owner->QueueCounter--;
  770. delete Jnk;
  771. Res = true;
  772. }
  773. else
  774. I = &(*I)->Next;
  775. }
  776. return Res;
  777. }
  778. /*}}}*/
  779. // Queue::Startup - Start the worker processes /*{{{*/
  780. // ---------------------------------------------------------------------
  781. /* It is possible for this to be called with a pre-existing set of
  782. workers. */
  783. bool pkgAcquire::Queue::Startup()
  784. {
  785. if (Workers == 0)
  786. {
  787. URI U(Name);
  788. pkgAcquire::MethodConfig *Cnf = Owner->GetConfig(U.Access);
  789. if (Cnf == 0)
  790. return false;
  791. Workers = new Worker(this,Cnf,Owner->Log);
  792. Owner->Add(Workers);
  793. if (Workers->Start() == false)
  794. return false;
  795. /* When pipelining we commit 10 items. This needs to change when we
  796. added other source retry to have cycle maintain a pipeline depth
  797. on its own. */
  798. if (Cnf->Pipeline == true)
  799. MaxPipeDepth = _config->FindI("Acquire::Max-Pipeline-Depth",10);
  800. else
  801. MaxPipeDepth = 1;
  802. }
  803. return Cycle();
  804. }
  805. /*}}}*/
  806. // Queue::Shutdown - Shutdown the worker processes /*{{{*/
  807. // ---------------------------------------------------------------------
  808. /* If final is true then all workers are eliminated, otherwise only workers
  809. that do not need cleanup are removed */
  810. bool pkgAcquire::Queue::Shutdown(bool Final)
  811. {
  812. // Delete all of the workers
  813. pkgAcquire::Worker **Cur = &Workers;
  814. while (*Cur != 0)
  815. {
  816. pkgAcquire::Worker *Jnk = *Cur;
  817. if (Final == true || Jnk->GetConf()->NeedsCleanup == false)
  818. {
  819. *Cur = Jnk->NextQueue;
  820. Owner->Remove(Jnk);
  821. delete Jnk;
  822. }
  823. else
  824. Cur = &(*Cur)->NextQueue;
  825. }
  826. return true;
  827. }
  828. /*}}}*/
  829. // Queue::FindItem - Find a URI in the item list /*{{{*/
  830. // ---------------------------------------------------------------------
  831. /* */
  832. pkgAcquire::Queue::QItem *pkgAcquire::Queue::FindItem(string URI,pkgAcquire::Worker *Owner)
  833. {
  834. for (QItem *I = Items; I != 0; I = I->Next)
  835. if (I->URI == URI && I->Worker == Owner)
  836. return I;
  837. return 0;
  838. }
  839. /*}}}*/
  840. // Queue::ItemDone - Item has been completed /*{{{*/
  841. // ---------------------------------------------------------------------
  842. /* The worker signals this which causes the item to be removed from the
  843. queue. If this is the last queue instance then it is removed from the
  844. main queue too.*/
  845. bool pkgAcquire::Queue::ItemDone(QItem *Itm)
  846. {
  847. PipeDepth--;
  848. for (QItem::owner_iterator O = Itm->Owners.begin(); O != Itm->Owners.end(); ++O)
  849. {
  850. if ((*O)->Status == pkgAcquire::Item::StatFetching)
  851. (*O)->Status = pkgAcquire::Item::StatDone;
  852. }
  853. if (Itm->Owner->QueueCounter <= 1)
  854. Owner->Dequeue(Itm->Owner);
  855. else
  856. {
  857. Dequeue(Itm->Owner);
  858. Owner->Bump();
  859. }
  860. return Cycle();
  861. }
  862. /*}}}*/
  863. // Queue::Cycle - Queue new items into the method /*{{{*/
  864. // ---------------------------------------------------------------------
  865. /* This locates a new idle item and sends it to the worker. If pipelining
  866. is enabled then it keeps the pipe full. */
  867. bool pkgAcquire::Queue::Cycle()
  868. {
  869. if (Items == 0 || Workers == 0)
  870. return true;
  871. if (PipeDepth < 0)
  872. return _error->Error("Pipedepth failure");
  873. // Look for a queable item
  874. QItem *I = Items;
  875. while (PipeDepth < (signed)MaxPipeDepth)
  876. {
  877. for (; I != 0; I = I->Next)
  878. if (I->Owner->Status == pkgAcquire::Item::StatIdle)
  879. break;
  880. // Nothing to do, queue is idle.
  881. if (I == 0)
  882. return true;
  883. I->Worker = Workers;
  884. for (auto const &O: I->Owners)
  885. O->Status = pkgAcquire::Item::StatFetching;
  886. PipeDepth++;
  887. if (Workers->QueueItem(I) == false)
  888. return false;
  889. }
  890. return true;
  891. }
  892. /*}}}*/
  893. // Queue::Bump - Fetch any pending objects if we are idle /*{{{*/
  894. // ---------------------------------------------------------------------
  895. /* This is called when an item in multiple queues is dequeued */
  896. void pkgAcquire::Queue::Bump()
  897. {
  898. Cycle();
  899. }
  900. /*}}}*/
  901. HashStringList pkgAcquire::Queue::QItem::GetExpectedHashes() const /*{{{*/
  902. {
  903. /* each Item can have multiple owners and each owner might have different
  904. hashes, even if that is unlikely in practice and if so at least some
  905. owners will later fail. There is one situation through which is not a
  906. failure and still needs this handling: Two owners who expect the same
  907. file, but one owner only knows the SHA1 while the other only knows SHA256. */
  908. HashStringList superhsl;
  909. for (pkgAcquire::Queue::QItem::owner_iterator O = Owners.begin(); O != Owners.end(); ++O)
  910. {
  911. HashStringList const hsl = (*O)->GetExpectedHashes();
  912. if (hsl.usable() == false)
  913. continue;
  914. if (superhsl.usable() == false)
  915. superhsl = hsl;
  916. else
  917. {
  918. // we merge both lists - if we find disagreement send no hashes
  919. HashStringList::const_iterator hs = hsl.begin();
  920. for (; hs != hsl.end(); ++hs)
  921. if (superhsl.push_back(*hs) == false)
  922. break;
  923. if (hs != hsl.end())
  924. {
  925. superhsl.clear();
  926. break;
  927. }
  928. }
  929. }
  930. return superhsl;
  931. }
  932. /*}}}*/
  933. APT_PURE unsigned long long pkgAcquire::Queue::QItem::GetMaximumSize() const /*{{{*/
  934. {
  935. unsigned long long Maximum = std::numeric_limits<unsigned long long>::max();
  936. for (auto const &O: Owners)
  937. {
  938. if (O->FileSize == 0)
  939. continue;
  940. Maximum = std::min(Maximum, O->FileSize);
  941. }
  942. if (Maximum == std::numeric_limits<unsigned long long>::max())
  943. return 0;
  944. return Maximum;
  945. }
  946. /*}}}*/
  947. void pkgAcquire::Queue::QItem::SyncDestinationFiles() const /*{{{*/
  948. {
  949. /* ensure that the first owner has the best partial file of all and
  950. the rest have (potentially dangling) symlinks to it so that
  951. everything (like progress reporting) finds it easily */
  952. std::string superfile = Owner->DestFile;
  953. off_t supersize = 0;
  954. for (pkgAcquire::Queue::QItem::owner_iterator O = Owners.begin(); O != Owners.end(); ++O)
  955. {
  956. if ((*O)->DestFile == superfile)
  957. continue;
  958. struct stat file;
  959. if (lstat((*O)->DestFile.c_str(),&file) == 0)
  960. {
  961. if ((file.st_mode & S_IFREG) == 0)
  962. RemoveFile("SyncDestinationFiles", (*O)->DestFile);
  963. else if (supersize < file.st_size)
  964. {
  965. supersize = file.st_size;
  966. RemoveFile("SyncDestinationFiles", superfile);
  967. rename((*O)->DestFile.c_str(), superfile.c_str());
  968. }
  969. else
  970. RemoveFile("SyncDestinationFiles", (*O)->DestFile);
  971. if (symlink(superfile.c_str(), (*O)->DestFile.c_str()) != 0)
  972. {
  973. ; // not a problem per-se and no real alternative
  974. }
  975. }
  976. }
  977. }
  978. /*}}}*/
  979. std::string pkgAcquire::Queue::QItem::Custom600Headers() const /*{{{*/
  980. {
  981. /* The others are relatively easy to merge, but this one?
  982. Lets not merge and see how far we can run with it…
  983. Likely, nobody will ever notice as all the items will
  984. be of the same class and hence generate the same headers. */
  985. return Owner->Custom600Headers();
  986. }
  987. /*}}}*/
  988. // AcquireStatus::pkgAcquireStatus - Constructor /*{{{*/
  989. // ---------------------------------------------------------------------
  990. /* */
  991. pkgAcquireStatus::pkgAcquireStatus() : d(NULL), Percent(-1), Update(true), MorePulses(false)
  992. {
  993. Start();
  994. }
  995. /*}}}*/
  996. // AcquireStatus::Pulse - Called periodically /*{{{*/
  997. // ---------------------------------------------------------------------
  998. /* This computes some internal state variables for the derived classes to
  999. use. It generates the current downloaded bytes and total bytes to download
  1000. as well as the current CPS estimate. */
  1001. bool pkgAcquireStatus::Pulse(pkgAcquire *Owner)
  1002. {
  1003. TotalBytes = 0;
  1004. CurrentBytes = 0;
  1005. TotalItems = 0;
  1006. CurrentItems = 0;
  1007. // Compute the total number of bytes to fetch
  1008. unsigned int Unknown = 0;
  1009. unsigned int Count = 0;
  1010. bool UnfetchedReleaseFiles = false;
  1011. for (pkgAcquire::ItemCIterator I = Owner->ItemsBegin();
  1012. I != Owner->ItemsEnd();
  1013. ++I, ++Count)
  1014. {
  1015. TotalItems++;
  1016. if ((*I)->Status == pkgAcquire::Item::StatDone)
  1017. ++CurrentItems;
  1018. // Totally ignore local items
  1019. if ((*I)->Local == true)
  1020. continue;
  1021. // see if the method tells us to expect more
  1022. TotalItems += (*I)->ExpectedAdditionalItems;
  1023. // check if there are unfetched Release files
  1024. if ((*I)->Complete == false && (*I)->ExpectedAdditionalItems > 0)
  1025. UnfetchedReleaseFiles = true;
  1026. TotalBytes += (*I)->FileSize;
  1027. if ((*I)->Complete == true)
  1028. CurrentBytes += (*I)->FileSize;
  1029. if ((*I)->FileSize == 0 && (*I)->Complete == false)
  1030. ++Unknown;
  1031. }
  1032. // Compute the current completion
  1033. unsigned long long ResumeSize = 0;
  1034. for (pkgAcquire::Worker *I = Owner->WorkersBegin(); I != 0;
  1035. I = Owner->WorkerStep(I))
  1036. {
  1037. if (I->CurrentItem != 0 && I->CurrentItem->Owner->Complete == false)
  1038. {
  1039. CurrentBytes += I->CurrentSize;
  1040. ResumeSize += I->ResumePoint;
  1041. // Files with unknown size always have 100% completion
  1042. if (I->CurrentItem->Owner->FileSize == 0 &&
  1043. I->CurrentItem->Owner->Complete == false)
  1044. TotalBytes += I->CurrentSize;
  1045. }
  1046. }
  1047. // Normalize the figures and account for unknown size downloads
  1048. if (TotalBytes <= 0)
  1049. TotalBytes = 1;
  1050. if (Unknown == Count)
  1051. TotalBytes = Unknown;
  1052. // Wha?! Is not supposed to happen.
  1053. if (CurrentBytes > TotalBytes)
  1054. CurrentBytes = TotalBytes;
  1055. // debug
  1056. if (_config->FindB("Debug::acquire::progress", false) == true)
  1057. std::clog << " Bytes: "
  1058. << SizeToStr(CurrentBytes) << " / " << SizeToStr(TotalBytes)
  1059. << std::endl;
  1060. // Compute the CPS
  1061. struct timeval NewTime;
  1062. gettimeofday(&NewTime,0);
  1063. if ((NewTime.tv_sec - Time.tv_sec == 6 && NewTime.tv_usec > Time.tv_usec) ||
  1064. NewTime.tv_sec - Time.tv_sec > 6)
  1065. {
  1066. double Delta = NewTime.tv_sec - Time.tv_sec +
  1067. (NewTime.tv_usec - Time.tv_usec)/1000000.0;
  1068. // Compute the CPS value
  1069. if (Delta < 0.01)
  1070. CurrentCPS = 0;
  1071. else
  1072. CurrentCPS = ((CurrentBytes - ResumeSize) - LastBytes)/Delta;
  1073. LastBytes = CurrentBytes - ResumeSize;
  1074. ElapsedTime = (unsigned long long)Delta;
  1075. Time = NewTime;
  1076. }
  1077. double const OldPercent = Percent;
  1078. // calculate the percentage, if we have too little data assume 1%
  1079. if (TotalBytes > 0 && UnfetchedReleaseFiles)
  1080. Percent = 0;
  1081. else
  1082. // use both files and bytes because bytes can be unreliable
  1083. Percent = (0.8 * (CurrentBytes/float(TotalBytes)*100.0) +
  1084. 0.2 * (CurrentItems/float(TotalItems)*100.0));
  1085. double const DiffPercent = Percent - OldPercent;
  1086. if (DiffPercent < 0.001 && _config->FindB("Acquire::Progress::Diffpercent", false) == true)
  1087. return true;
  1088. int fd = _config->FindI("APT::Status-Fd",-1);
  1089. if(fd > 0)
  1090. {
  1091. ostringstream status;
  1092. char msg[200];
  1093. long i = CurrentItems < TotalItems ? CurrentItems + 1 : CurrentItems;
  1094. unsigned long long ETA = 0;
  1095. if(CurrentCPS > 0)
  1096. ETA = (TotalBytes - CurrentBytes) / CurrentCPS;
  1097. // only show the ETA if it makes sense
  1098. if (ETA > 0 && ETA < 172800 /* two days */ )
  1099. snprintf(msg,sizeof(msg), _("Retrieving file %li of %li (%s remaining)"), i, TotalItems, TimeToStr(ETA).c_str());
  1100. else
  1101. snprintf(msg,sizeof(msg), _("Retrieving file %li of %li"), i, TotalItems);
  1102. // build the status str
  1103. status << "dlstatus:" << i
  1104. << ":" << std::setprecision(3) << Percent
  1105. << ":" << msg
  1106. << endl;
  1107. std::string const dlstatus = status.str();
  1108. FileFd::Write(fd, dlstatus.c_str(), dlstatus.size());
  1109. }
  1110. return true;
  1111. }
  1112. /*}}}*/
  1113. // AcquireStatus::Start - Called when the download is started /*{{{*/
  1114. // ---------------------------------------------------------------------
  1115. /* We just reset the counters */
  1116. void pkgAcquireStatus::Start()
  1117. {
  1118. gettimeofday(&Time,0);
  1119. gettimeofday(&StartTime,0);
  1120. LastBytes = 0;
  1121. CurrentCPS = 0;
  1122. CurrentBytes = 0;
  1123. TotalBytes = 0;
  1124. FetchedBytes = 0;
  1125. ElapsedTime = 0;
  1126. TotalItems = 0;
  1127. CurrentItems = 0;
  1128. }
  1129. /*}}}*/
  1130. // AcquireStatus::Stop - Finished downloading /*{{{*/
  1131. // ---------------------------------------------------------------------
  1132. /* This accurately computes the elapsed time and the total overall CPS. */
  1133. void pkgAcquireStatus::Stop()
  1134. {
  1135. // Compute the CPS and elapsed time
  1136. struct timeval NewTime;
  1137. gettimeofday(&NewTime,0);
  1138. double Delta = NewTime.tv_sec - StartTime.tv_sec +
  1139. (NewTime.tv_usec - StartTime.tv_usec)/1000000.0;
  1140. // Compute the CPS value
  1141. if (Delta < 0.01)
  1142. CurrentCPS = 0;
  1143. else
  1144. CurrentCPS = FetchedBytes/Delta;
  1145. LastBytes = CurrentBytes;
  1146. ElapsedTime = (unsigned long long)Delta;
  1147. }
  1148. /*}}}*/
  1149. // AcquireStatus::Fetched - Called when a byte set has been fetched /*{{{*/
  1150. // ---------------------------------------------------------------------
  1151. /* This is used to get accurate final transfer rate reporting. */
  1152. void pkgAcquireStatus::Fetched(unsigned long long Size,unsigned long long Resume)
  1153. {
  1154. FetchedBytes += Size - Resume;
  1155. }
  1156. /*}}}*/
  1157. pkgAcquire::UriIterator::UriIterator(pkgAcquire::Queue *Q) : d(NULL), CurQ(Q), CurItem(0)
  1158. {
  1159. while (CurItem == 0 && CurQ != 0)
  1160. {
  1161. CurItem = CurQ->Items;
  1162. CurQ = CurQ->Next;
  1163. }
  1164. }
  1165. APT_CONST pkgAcquire::UriIterator::~UriIterator() {}
  1166. APT_CONST pkgAcquire::MethodConfig::~MethodConfig() {}
  1167. APT_CONST pkgAcquireStatus::~pkgAcquireStatus() {}