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