acquire.cc 43 KB

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