acquire.cc 39 KB

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