acquire.cc 40 KB

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