acquire.cc 43 KB

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