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