acquire.cc 40 KB

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