use a static FileFd::Write overload to reduce duplication of write()-retry code
[ntk/apt.git] / apt-pkg / acquire-worker.cc
CommitLineData
0118833a
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
24a0d63a 3// $Id: acquire-worker.cc,v 1.34 2001/05/22 04:42:54 jgg Exp $
0118833a
AL
4/* ######################################################################
5
6 Acquire Worker
7
3b5421b4
AL
8 The worker process can startup either as a Configuration prober
9 or as a queue runner. As a configuration prober it only reads the
10 configuration message and
11
0118833a
AL
12 ##################################################################### */
13 /*}}}*/
14// Include Files /*{{{*/
ea542140
DK
15#include <config.h>
16
0118833a 17#include <apt-pkg/acquire-worker.h>
0a8a80e5 18#include <apt-pkg/acquire-item.h>
3b5421b4
AL
19#include <apt-pkg/configuration.h>
20#include <apt-pkg/error.h>
21#include <apt-pkg/fileutl.h>
cdcc6d34 22#include <apt-pkg/strutl.h>
3b5421b4 23
24a0d63a 24#include <iostream>
80a26ed1 25#include <sstream>
24a0d63a 26#include <fstream>
ea542140 27
8267fe24 28#include <sys/stat.h>
3b5421b4 29#include <unistd.h>
b0db36b1 30#include <fcntl.h>
3b5421b4 31#include <signal.h>
542ec555 32#include <stdio.h>
b0db36b1 33#include <errno.h>
ea542140
DK
34
35#include <apti18n.h>
3b5421b4
AL
36 /*}}}*/
37
24a0d63a
AL
38using namespace std;
39
3b5421b4
AL
40// Worker::Worker - Constructor for Queue startup /*{{{*/
41// ---------------------------------------------------------------------
42/* */
8267fe24
AL
43pkgAcquire::Worker::Worker(Queue *Q,MethodConfig *Cnf,
44 pkgAcquireStatus *Log) : Log(Log)
3b5421b4
AL
45{
46 OwnerQ = Q;
0a8a80e5
AL
47 Config = Cnf;
48 Access = Cnf->Access;
49 CurrentItem = 0;
18ef0a78
AL
50 TotalSize = 0;
51 CurrentSize = 0;
52
3b5421b4
AL
53 Construct();
54}
55 /*}}}*/
56// Worker::Worker - Constructor for method config startup /*{{{*/
57// ---------------------------------------------------------------------
58/* */
59pkgAcquire::Worker::Worker(MethodConfig *Cnf)
60{
61 OwnerQ = 0;
62 Config = Cnf;
63 Access = Cnf->Access;
0a8a80e5 64 CurrentItem = 0;
18ef0a78
AL
65 TotalSize = 0;
66 CurrentSize = 0;
0a8a80e5 67
3b5421b4
AL
68 Construct();
69}
70 /*}}}*/
71// Worker::Construct - Constructor helper /*{{{*/
72// ---------------------------------------------------------------------
73/* */
74void pkgAcquire::Worker::Construct()
75{
0a8a80e5
AL
76 NextQueue = 0;
77 NextAcquire = 0;
3b5421b4
AL
78 Process = -1;
79 InFd = -1;
80 OutFd = -1;
0a8a80e5
AL
81 OutReady = false;
82 InReady = false;
3b5421b4
AL
83 Debug = _config->FindB("Debug::pkgAcquire::Worker",false);
84}
85 /*}}}*/
86// Worker::~Worker - Destructor /*{{{*/
87// ---------------------------------------------------------------------
88/* */
89pkgAcquire::Worker::~Worker()
90{
91 close(InFd);
92 close(OutFd);
93
94 if (Process > 0)
0a8a80e5 95 {
8e5fc8f5
AL
96 /* Closing of stdin is the signal to exit and die when the process
97 indicates it needs cleanup */
98 if (Config->NeedsCleanup == false)
99 kill(Process,SIGINT);
ddc1d8d0 100 ExecWait(Process,Access.c_str(),true);
0a8a80e5 101 }
3b5421b4
AL
102}
103 /*}}}*/
104// Worker::Start - Start the worker process /*{{{*/
105// ---------------------------------------------------------------------
106/* This forks the method and inits the communication channel */
107bool pkgAcquire::Worker::Start()
108{
109 // Get the method path
110 string Method = _config->FindDir("Dir::Bin::Methods") + Access;
111 if (FileExists(Method) == false)
b2e465d6 112 return _error->Error(_("The method driver %s could not be found."),Method.c_str());
3b5421b4
AL
113
114 if (Debug == true)
115 clog << "Starting method '" << Method << '\'' << endl;
116
117 // Create the pipes
118 int Pipes[4] = {-1,-1,-1,-1};
119 if (pipe(Pipes) != 0 || pipe(Pipes+2) != 0)
120 {
121 _error->Errno("pipe","Failed to create IPC pipe to subprocess");
122 for (int I = 0; I != 4; I++)
123 close(Pipes[I]);
124 return false;
125 }
8b89e57f 126 for (int I = 0; I != 4; I++)
4490f2de 127 SetCloseExec(Pipes[I],true);
8b89e57f 128
3b5421b4 129 // Fork off the process
54676e1a 130 Process = ExecFork();
3b5421b4
AL
131 if (Process == 0)
132 {
133 // Setup the FDs
134 dup2(Pipes[1],STDOUT_FILENO);
135 dup2(Pipes[2],STDIN_FILENO);
3b5421b4
AL
136 SetCloseExec(STDOUT_FILENO,false);
137 SetCloseExec(STDIN_FILENO,false);
138 SetCloseExec(STDERR_FILENO,false);
139
140 const char *Args[2];
141 Args[0] = Method.c_str();
142 Args[1] = 0;
143 execv(Args[0],(char **)Args);
144 cerr << "Failed to exec method " << Args[0] << endl;
0dbb95d8 145 _exit(100);
3b5421b4
AL
146 }
147
148 // Fix up our FDs
149 InFd = Pipes[0];
150 OutFd = Pipes[3];
151 SetNonBlock(Pipes[0],true);
152 SetNonBlock(Pipes[3],true);
153 close(Pipes[1]);
154 close(Pipes[2]);
0a8a80e5
AL
155 OutReady = false;
156 InReady = true;
3b5421b4
AL
157
158 // Read the configuration data
159 if (WaitFd(InFd) == false ||
160 ReadMessages() == false)
b2e465d6 161 return _error->Error(_("Method %s did not start correctly"),Method.c_str());
3b5421b4
AL
162
163 RunMessages();
8b89e57f
AL
164 if (OwnerQ != 0)
165 SendConfiguration();
3b5421b4
AL
166
167 return true;
168}
169 /*}}}*/
170// Worker::ReadMessages - Read all pending messages into the list /*{{{*/
171// ---------------------------------------------------------------------
0a8a80e5 172/* */
3b5421b4
AL
173bool pkgAcquire::Worker::ReadMessages()
174{
0a8a80e5
AL
175 if (::ReadMessages(InFd,MessageQueue) == false)
176 return MethodFailure();
3b5421b4
AL
177 return true;
178}
179 /*}}}*/
3b5421b4
AL
180// Worker::RunMessage - Empty the message queue /*{{{*/
181// ---------------------------------------------------------------------
182/* This takes the messages from the message queue and runs them through
183 the parsers in order. */
184bool pkgAcquire::Worker::RunMessages()
185{
186 while (MessageQueue.empty() == false)
187 {
188 string Message = MessageQueue.front();
189 MessageQueue.erase(MessageQueue.begin());
0a8a80e5
AL
190
191 if (Debug == true)
192 clog << " <- " << Access << ':' << QuoteString(Message,"\n") << endl;
3b5421b4
AL
193
194 // Fetch the message number
195 char *End;
196 int Number = strtol(Message.c_str(),&End,10);
197 if (End == Message.c_str())
198 return _error->Error("Invalid message from method %s: %s",Access.c_str(),Message.c_str());
199
c88edf1d
AL
200 string URI = LookupTag(Message,"URI");
201 pkgAcquire::Queue::QItem *Itm = 0;
202 if (URI.empty() == false)
203 Itm = OwnerQ->FindItem(URI,this);
196fd136
MV
204
205 // update used mirror
206 string UsedMirror = LookupTag(Message,"UsedMirror", "");
207 if (!UsedMirror.empty() &&
208 Itm &&
209 Itm->Description.find(" ") != string::npos)
210 {
211 Itm->Description.replace(0, Itm->Description.find(" "), UsedMirror);
212 // FIXME: will we need this as well?
213 //Itm->ShortDesc = UsedMirror;
214 }
bfd22fc0 215
3b5421b4
AL
216 // Determine the message number and dispatch
217 switch (Number)
218 {
0a8a80e5 219 // 100 Capabilities
3b5421b4
AL
220 case 100:
221 if (Capabilities(Message) == false)
222 return _error->Error("Unable to process Capabilities message from %s",Access.c_str());
223 break;
0a8a80e5
AL
224
225 // 101 Log
226 case 101:
227 if (Debug == true)
228 clog << " <- (log) " << LookupTag(Message,"Message") << endl;
229 break;
230
231 // 102 Status
232 case 102:
233 Status = LookupTag(Message,"Message");
234 break;
235
15d7e515
MV
236 // 103 Redirect
237 case 103:
238 {
239 if (Itm == 0)
240 {
241 _error->Error("Method gave invalid 103 Redirect message");
242 break;
243 }
244
245 string NewURI = LookupTag(Message,"New-URI",URI.c_str());
246 Itm->URI = NewURI;
247 break;
248 }
249
0a8a80e5
AL
250 // 200 URI Start
251 case 200:
c88edf1d
AL
252 {
253 if (Itm == 0)
254 {
93bf083d 255 _error->Error("Method gave invalid 200 URI Start message");
c88edf1d
AL
256 break;
257 }
8267fe24 258
c88edf1d
AL
259 CurrentItem = Itm;
260 CurrentSize = 0;
650faab0
DK
261 TotalSize = strtoull(LookupTag(Message,"Size","0").c_str(), NULL, 10);
262 ResumePoint = strtoull(LookupTag(Message,"Resume-Point","0").c_str(), NULL, 10);
263 Itm->Owner->Start(Message,strtoull(LookupTag(Message,"Size","0").c_str(), NULL, 10));
8b75eb1c 264
c5ccf175
AL
265 // Display update before completion
266 if (Log != 0 && Log->MorePulses == true)
267 Log->Pulse(Itm->Owner->GetOwner());
268
8267fe24
AL
269 if (Log != 0)
270 Log->Fetch(*Itm);
271
c88edf1d
AL
272 break;
273 }
0a8a80e5
AL
274
275 // 201 URI Done
276 case 201:
c88edf1d
AL
277 {
278 if (Itm == 0)
279 {
93bf083d 280 _error->Error("Method gave invalid 201 URI Done message");
c88edf1d
AL
281 break;
282 }
c5ccf175 283
bfd22fc0 284 pkgAcquire::Item *Owner = Itm->Owner;
8267fe24 285 pkgAcquire::ItemDesc Desc = *Itm;
c5ccf175
AL
286
287 // Display update before completion
288 if (Log != 0 && Log->MorePulses == true)
289 Log->Pulse(Owner->GetOwner());
290
be4401bf 291 OwnerQ->ItemDone(Itm);
650faab0 292 unsigned long long const ServerSize = strtoull(LookupTag(Message,"Size","0").c_str(), NULL, 10);
378fcbd6 293 if (TotalSize != 0 && ServerSize != TotalSize)
73da43e9 294 _error->Warning("Size of file %s is not what the server reported %s %llu",
378fcbd6 295 Owner->DestFile.c_str(), LookupTag(Message,"Size","0").c_str(),TotalSize);
bdae53f1 296
8a8feb29
MV
297 // see if there is a hash to verify
298 string RecivedHash;
299 HashString expectedHash(Owner->HashSum());
300 if(!expectedHash.empty())
301 {
302 string hashTag = expectedHash.HashType()+"-Hash";
95f45727
MV
303 string hashSum = LookupTag(Message, hashTag.c_str());
304 if(!hashSum.empty())
305 RecivedHash = expectedHash.HashType() + ":" + hashSum;
8a8feb29
MV
306 if(_config->FindB("Debug::pkgAcquire::Auth", false) == true)
307 {
308 clog << "201 URI Done: " << Owner->DescURI() << endl
309 << "RecivedHash: " << RecivedHash << endl
310 << "ExpectedHash: " << expectedHash.toStr()
311 << endl << endl;
312 }
313 }
378fcbd6 314 Owner->Done(Message, ServerSize, RecivedHash.c_str(), Config);
8267fe24
AL
315 ItemDone();
316
317 // Log that we are done
318 if (Log != 0)
319 {
320 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true ||
321 StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
c46824ce
AL
322 {
323 /* Hide 'hits' for local only sources - we also manage to
324 hide gets */
325 if (Config->LocalOnly == false)
326 Log->IMSHit(Desc);
327 }
8267fe24
AL
328 else
329 Log->Done(Desc);
18ef0a78 330 }
c88edf1d
AL
331 break;
332 }
0a8a80e5
AL
333
334 // 400 URI Failure
335 case 400:
c88edf1d
AL
336 {
337 if (Itm == 0)
338 {
93bf083d 339 _error->Error("Method gave invalid 400 URI Failure message");
c88edf1d
AL
340 break;
341 }
342
c5ccf175
AL
343 // Display update before completion
344 if (Log != 0 && Log->MorePulses == true)
345 Log->Pulse(Itm->Owner->GetOwner());
346
bfd22fc0 347 pkgAcquire::Item *Owner = Itm->Owner;
8267fe24 348 pkgAcquire::ItemDesc Desc = *Itm;
c88edf1d 349 OwnerQ->ItemDone(Itm);
7e5f33eb
MV
350
351 // set some status
352 if(LookupTag(Message,"FailReason") == "Timeout" ||
353 LookupTag(Message,"FailReason") == "TmpResolveFailure" ||
f0983ff2 354 LookupTag(Message,"FailReason") == "ResolveFailure" ||
7e5f33eb
MV
355 LookupTag(Message,"FailReason") == "ConnectionRefused")
356 Owner->Status = pkgAcquire::Item::StatTransientNetworkError;
357
7d8afa39 358 Owner->Failed(Message,Config);
8267fe24 359 ItemDone();
7d8afa39 360
8267fe24
AL
361 if (Log != 0)
362 Log->Fail(Desc);
7d8afa39 363
c88edf1d
AL
364 break;
365 }
0a8a80e5
AL
366
367 // 401 General Failure
368 case 401:
b2e465d6 369 _error->Error("Method %s General failure: %s",Access.c_str(),LookupTag(Message,"Message").c_str());
0a8a80e5 370 break;
542ec555
AL
371
372 // 403 Media Change
373 case 403:
374 MediaChange(Message);
375 break;
3b5421b4
AL
376 }
377 }
378 return true;
379}
380 /*}}}*/
381// Worker::Capabilities - 100 Capabilities handler /*{{{*/
382// ---------------------------------------------------------------------
383/* This parses the capabilities message and dumps it into the configuration
384 structure. */
385bool pkgAcquire::Worker::Capabilities(string Message)
386{
387 if (Config == 0)
388 return true;
389
390 Config->Version = LookupTag(Message,"Version");
391 Config->SingleInstance = StringToBool(LookupTag(Message,"Single-Instance"),false);
0a8a80e5
AL
392 Config->Pipeline = StringToBool(LookupTag(Message,"Pipeline"),false);
393 Config->SendConfig = StringToBool(LookupTag(Message,"Send-Config"),false);
e331f6ed 394 Config->LocalOnly = StringToBool(LookupTag(Message,"Local-Only"),false);
8e5fc8f5 395 Config->NeedsCleanup = StringToBool(LookupTag(Message,"Needs-Cleanup"),false);
459681d3 396 Config->Removable = StringToBool(LookupTag(Message,"Removable"),false);
3b5421b4
AL
397
398 // Some debug text
399 if (Debug == true)
400 {
401 clog << "Configured access method " << Config->Access << endl;
459681d3
AL
402 clog << "Version:" << Config->Version <<
403 " SingleInstance:" << Config->SingleInstance <<
404 " Pipeline:" << Config->Pipeline <<
405 " SendConfig:" << Config->SendConfig <<
406 " LocalOnly: " << Config->LocalOnly <<
407 " NeedsCleanup: " << Config->NeedsCleanup <<
408 " Removable: " << Config->Removable << endl;
3b5421b4
AL
409 }
410
542ec555
AL
411 return true;
412}
413 /*}}}*/
414// Worker::MediaChange - Request a media change /*{{{*/
415// ---------------------------------------------------------------------
416/* */
417bool pkgAcquire::Worker::MediaChange(string Message)
418{
80a26ed1
MV
419 int status_fd = _config->FindI("APT::Status-Fd",-1);
420 if(status_fd > 0)
421 {
422 string Media = LookupTag(Message,"Media");
423 string Drive = LookupTag(Message,"Drive");
424 ostringstream msg,status;
1a82c63e
MV
425 ioprintf(msg,_("Please insert the disc labeled: "
426 "'%s' "
427 "in the drive '%s' and press enter."),
428 Media.c_str(),Drive.c_str());
80a26ed1 429 status << "media-change: " // message
1a82c63e
MV
430 << Media << ":" // media
431 << Drive << ":" // drive
432 << msg.str() // l10n message
80a26ed1 433 << endl;
31bda500
DK
434
435 std::string const dlstatus = status.str();
d68d65ad 436 FileFd::Write(status_fd, dlstatus.c_str(), dlstatus.size());
80a26ed1
MV
437 }
438
542ec555
AL
439 if (Log == 0 || Log->MediaChange(LookupTag(Message,"Media"),
440 LookupTag(Message,"Drive")) == false)
441 {
442 char S[300];
96bc43c4 443 snprintf(S,sizeof(S),"603 Media Changed\nFailed: true\n\n");
542ec555
AL
444 if (Debug == true)
445 clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
446 OutQueue += S;
447 OutReady = true;
448 return true;
449 }
450
451 char S[300];
96bc43c4 452 snprintf(S,sizeof(S),"603 Media Changed\n\n");
542ec555
AL
453 if (Debug == true)
454 clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
455 OutQueue += S;
456 OutReady = true;
3b5421b4
AL
457 return true;
458}
0118833a 459 /*}}}*/
0a8a80e5
AL
460// Worker::SendConfiguration - Send the config to the method /*{{{*/
461// ---------------------------------------------------------------------
462/* */
463bool pkgAcquire::Worker::SendConfiguration()
464{
465 if (Config->SendConfig == false)
466 return true;
467
468 if (OutFd == -1)
469 return false;
470
471 string Message = "601 Configuration\n";
472 Message.reserve(2000);
473
474 /* Write out all of the configuration directives by walking the
475 configuration tree */
476 const Configuration::Item *Top = _config->Tree(0);
477 for (; Top != 0;)
478 {
479 if (Top->Value.empty() == false)
480 {
b2e465d6 481 string Line = "Config-Item: " + QuoteString(Top->FullTag(),"=\"\n") + "=";
0a8a80e5
AL
482 Line += QuoteString(Top->Value,"\n") + '\n';
483 Message += Line;
484 }
485
486 if (Top->Child != 0)
487 {
488 Top = Top->Child;
489 continue;
490 }
491
492 while (Top != 0 && Top->Next == 0)
493 Top = Top->Parent;
494 if (Top != 0)
495 Top = Top->Next;
496 }
497 Message += '\n';
498
499 if (Debug == true)
500 clog << " -> " << Access << ':' << QuoteString(Message,"\n") << endl;
501 OutQueue += Message;
502 OutReady = true;
503
504 return true;
505}
506 /*}}}*/
507// Worker::QueueItem - Add an item to the outbound queue /*{{{*/
508// ---------------------------------------------------------------------
509/* Send a URI Acquire message to the method */
510bool pkgAcquire::Worker::QueueItem(pkgAcquire::Queue::QItem *Item)
511{
512 if (OutFd == -1)
513 return false;
514
515 string Message = "600 URI Acquire\n";
516 Message.reserve(300);
517 Message += "URI: " + Item->URI;
518 Message += "\nFilename: " + Item->Owner->DestFile;
519 Message += Item->Owner->Custom600Headers();
520 Message += "\n\n";
521
522 if (Debug == true)
523 clog << " -> " << Access << ':' << QuoteString(Message,"\n") << endl;
524 OutQueue += Message;
525 OutReady = true;
526
527 return true;
528}
529 /*}}}*/
530// Worker::OutFdRead - Out bound FD is ready /*{{{*/
531// ---------------------------------------------------------------------
532/* */
533bool pkgAcquire::Worker::OutFdReady()
534{
d68d65ad 535 if (FileFd::Write(OutFd,OutQueue.c_str(),OutQueue.length()) == false)
0a8a80e5 536 return MethodFailure();
0a8a80e5 537
d68d65ad 538 OutQueue.clear();
0a8a80e5
AL
539 if (OutQueue.empty() == true)
540 OutReady = false;
541
542 return true;
543}
544 /*}}}*/
545// Worker::InFdRead - In bound FD is ready /*{{{*/
546// ---------------------------------------------------------------------
547/* */
548bool pkgAcquire::Worker::InFdReady()
549{
550 if (ReadMessages() == false)
551 return false;
552 RunMessages();
553 return true;
554}
555 /*}}}*/
556// Worker::MethodFailure - Called when the method fails /*{{{*/
557// ---------------------------------------------------------------------
558/* This is called when the method is belived to have failed, probably because
559 read returned -1. */
560bool pkgAcquire::Worker::MethodFailure()
561{
76d97c26
AL
562 _error->Error("Method %s has died unexpectedly!",Access.c_str());
563
ab7f4d7c
MV
564 // do not reap the child here to show meaningfull error to the user
565 ExecWait(Process,Access.c_str(),false);
0a8a80e5
AL
566 Process = -1;
567 close(InFd);
568 close(OutFd);
569 InFd = -1;
570 OutFd = -1;
571 OutReady = false;
572 InReady = false;
573 OutQueue = string();
574 MessageQueue.erase(MessageQueue.begin(),MessageQueue.end());
575
576 return false;
577}
578 /*}}}*/
8267fe24
AL
579// Worker::Pulse - Called periodically /*{{{*/
580// ---------------------------------------------------------------------
581/* */
582void pkgAcquire::Worker::Pulse()
583{
584 if (CurrentItem == 0)
585 return;
542ec555 586
8267fe24
AL
587 struct stat Buf;
588 if (stat(CurrentItem->Owner->DestFile.c_str(),&Buf) != 0)
589 return;
590 CurrentSize = Buf.st_size;
18ef0a78
AL
591
592 // Hmm? Should not happen...
593 if (CurrentSize > TotalSize && TotalSize != 0)
594 TotalSize = CurrentSize;
8267fe24
AL
595}
596 /*}}}*/
597// Worker::ItemDone - Called when the current item is finished /*{{{*/
598// ---------------------------------------------------------------------
599/* */
600void pkgAcquire::Worker::ItemDone()
601{
602 CurrentItem = 0;
603 CurrentSize = 0;
604 TotalSize = 0;
605 Status = string();
606}
607 /*}}}*/