Join with aliencode
[ntk/apt.git] / apt-pkg / acquire-worker.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Description /*{{{*/
3 // $Id: acquire-worker.cc,v 1.32 2001/02/20 07:03:17 jgg Exp $
4 /* ######################################################################
5
6 Acquire Worker
7
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
12 ##################################################################### */
13 /*}}}*/
14 // Include Files /*{{{*/
15 #ifdef __GNUG__
16 #pragma implementation "apt-pkg/acquire-worker.h"
17 #endif
18 #include <apt-pkg/acquire-worker.h>
19 #include <apt-pkg/acquire-item.h>
20 #include <apt-pkg/configuration.h>
21 #include <apt-pkg/error.h>
22 #include <apt-pkg/fileutl.h>
23 #include <apt-pkg/strutl.h>
24
25 #include <apti18n.h>
26
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <errno.h>
33 /*}}}*/
34
35 // Worker::Worker - Constructor for Queue startup /*{{{*/
36 // ---------------------------------------------------------------------
37 /* */
38 pkgAcquire::Worker::Worker(Queue *Q,MethodConfig *Cnf,
39 pkgAcquireStatus *Log) : Log(Log)
40 {
41 OwnerQ = Q;
42 Config = Cnf;
43 Access = Cnf->Access;
44 CurrentItem = 0;
45 TotalSize = 0;
46 CurrentSize = 0;
47
48 Construct();
49 }
50 /*}}}*/
51 // Worker::Worker - Constructor for method config startup /*{{{*/
52 // ---------------------------------------------------------------------
53 /* */
54 pkgAcquire::Worker::Worker(MethodConfig *Cnf)
55 {
56 OwnerQ = 0;
57 Config = Cnf;
58 Access = Cnf->Access;
59 CurrentItem = 0;
60 TotalSize = 0;
61 CurrentSize = 0;
62
63 Construct();
64 }
65 /*}}}*/
66 // Worker::Construct - Constructor helper /*{{{*/
67 // ---------------------------------------------------------------------
68 /* */
69 void pkgAcquire::Worker::Construct()
70 {
71 NextQueue = 0;
72 NextAcquire = 0;
73 Process = -1;
74 InFd = -1;
75 OutFd = -1;
76 OutReady = false;
77 InReady = false;
78 Debug = _config->FindB("Debug::pkgAcquire::Worker",false);
79 }
80 /*}}}*/
81 // Worker::~Worker - Destructor /*{{{*/
82 // ---------------------------------------------------------------------
83 /* */
84 pkgAcquire::Worker::~Worker()
85 {
86 close(InFd);
87 close(OutFd);
88
89 if (Process > 0)
90 {
91 /* Closing of stdin is the signal to exit and die when the process
92 indicates it needs cleanup */
93 if (Config->NeedsCleanup == false)
94 kill(Process,SIGINT);
95 ExecWait(Process,Access.c_str(),true);
96 }
97 }
98 /*}}}*/
99 // Worker::Start - Start the worker process /*{{{*/
100 // ---------------------------------------------------------------------
101 /* This forks the method and inits the communication channel */
102 bool pkgAcquire::Worker::Start()
103 {
104 // Get the method path
105 string Method = _config->FindDir("Dir::Bin::Methods") + Access;
106 if (FileExists(Method) == false)
107 return _error->Error(_("The method driver %s could not be found."),Method.c_str());
108
109 if (Debug == true)
110 clog << "Starting method '" << Method << '\'' << endl;
111
112 // Create the pipes
113 int Pipes[4] = {-1,-1,-1,-1};
114 if (pipe(Pipes) != 0 || pipe(Pipes+2) != 0)
115 {
116 _error->Errno("pipe","Failed to create IPC pipe to subprocess");
117 for (int I = 0; I != 4; I++)
118 close(Pipes[I]);
119 return false;
120 }
121 for (int I = 0; I != 4; I++)
122 SetCloseExec(Pipes[I],true);
123
124 // Fork off the process
125 Process = ExecFork();
126
127 // Spawn the subprocess
128 if (Process == 0)
129 {
130 // Setup the FDs
131 dup2(Pipes[1],STDOUT_FILENO);
132 dup2(Pipes[2],STDIN_FILENO);
133 dup2(((filebuf *)clog.rdbuf())->fd(),STDERR_FILENO);
134 SetCloseExec(STDOUT_FILENO,false);
135 SetCloseExec(STDIN_FILENO,false);
136 SetCloseExec(STDERR_FILENO,false);
137
138 const char *Args[2];
139 Args[0] = Method.c_str();
140 Args[1] = 0;
141 execv(Args[0],(char **)Args);
142 cerr << "Failed to exec method " << Args[0] << endl;
143 _exit(100);
144 }
145
146 // Fix up our FDs
147 InFd = Pipes[0];
148 OutFd = Pipes[3];
149 SetNonBlock(Pipes[0],true);
150 SetNonBlock(Pipes[3],true);
151 close(Pipes[1]);
152 close(Pipes[2]);
153 OutReady = false;
154 InReady = true;
155
156 // Read the configuration data
157 if (WaitFd(InFd) == false ||
158 ReadMessages() == false)
159 return _error->Error(_("Method %s did not start correctly"),Method.c_str());
160
161 RunMessages();
162 if (OwnerQ != 0)
163 SendConfiguration();
164
165 return true;
166 }
167 /*}}}*/
168 // Worker::ReadMessages - Read all pending messages into the list /*{{{*/
169 // ---------------------------------------------------------------------
170 /* */
171 bool pkgAcquire::Worker::ReadMessages()
172 {
173 if (::ReadMessages(InFd,MessageQueue) == false)
174 return MethodFailure();
175 return true;
176 }
177 /*}}}*/
178 // Worker::RunMessage - Empty the message queue /*{{{*/
179 // ---------------------------------------------------------------------
180 /* This takes the messages from the message queue and runs them through
181 the parsers in order. */
182 bool pkgAcquire::Worker::RunMessages()
183 {
184 while (MessageQueue.empty() == false)
185 {
186 string Message = MessageQueue.front();
187 MessageQueue.erase(MessageQueue.begin());
188
189 if (Debug == true)
190 clog << " <- " << Access << ':' << QuoteString(Message,"\n") << endl;
191
192 // Fetch the message number
193 char *End;
194 int Number = strtol(Message.c_str(),&End,10);
195 if (End == Message.c_str())
196 return _error->Error("Invalid message from method %s: %s",Access.c_str(),Message.c_str());
197
198 string URI = LookupTag(Message,"URI");
199 pkgAcquire::Queue::QItem *Itm = 0;
200 if (URI.empty() == false)
201 Itm = OwnerQ->FindItem(URI,this);
202
203 // Determine the message number and dispatch
204 switch (Number)
205 {
206 // 100 Capabilities
207 case 100:
208 if (Capabilities(Message) == false)
209 return _error->Error("Unable to process Capabilities message from %s",Access.c_str());
210 break;
211
212 // 101 Log
213 case 101:
214 if (Debug == true)
215 clog << " <- (log) " << LookupTag(Message,"Message") << endl;
216 break;
217
218 // 102 Status
219 case 102:
220 Status = LookupTag(Message,"Message");
221 break;
222
223 // 200 URI Start
224 case 200:
225 {
226 if (Itm == 0)
227 {
228 _error->Error("Method gave invalid 200 URI Start message");
229 break;
230 }
231
232 CurrentItem = Itm;
233 CurrentSize = 0;
234 TotalSize = atoi(LookupTag(Message,"Size","0").c_str());
235 ResumePoint = atoi(LookupTag(Message,"Resume-Point","0").c_str());
236 Itm->Owner->Start(Message,atoi(LookupTag(Message,"Size","0").c_str()));
237
238 // Display update before completion
239 if (Log != 0 && Log->MorePulses == true)
240 Log->Pulse(Itm->Owner->GetOwner());
241
242 if (Log != 0)
243 Log->Fetch(*Itm);
244
245 break;
246 }
247
248 // 201 URI Done
249 case 201:
250 {
251 if (Itm == 0)
252 {
253 _error->Error("Method gave invalid 201 URI Done message");
254 break;
255 }
256
257 pkgAcquire::Item *Owner = Itm->Owner;
258 pkgAcquire::ItemDesc Desc = *Itm;
259
260 // Display update before completion
261 if (Log != 0 && Log->MorePulses == true)
262 Log->Pulse(Owner->GetOwner());
263
264 OwnerQ->ItemDone(Itm);
265 if (TotalSize != 0 &&
266 (unsigned)atoi(LookupTag(Message,"Size","0").c_str()) != TotalSize)
267 _error->Warning("Bizarre Error - File size is not what the server reported %s %lu",
268 LookupTag(Message,"Size","0").c_str(),TotalSize);
269
270 Owner->Done(Message,atoi(LookupTag(Message,"Size","0").c_str()),
271 LookupTag(Message,"MD5-Hash"),Config);
272 ItemDone();
273
274 // Log that we are done
275 if (Log != 0)
276 {
277 if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true ||
278 StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
279 {
280 /* Hide 'hits' for local only sources - we also manage to
281 hide gets */
282 if (Config->LocalOnly == false)
283 Log->IMSHit(Desc);
284 }
285 else
286 Log->Done(Desc);
287 }
288 break;
289 }
290
291 // 400 URI Failure
292 case 400:
293 {
294 if (Itm == 0)
295 {
296 _error->Error("Method gave invalid 400 URI Failure message");
297 break;
298 }
299
300 // Display update before completion
301 if (Log != 0 && Log->MorePulses == true)
302 Log->Pulse(Itm->Owner->GetOwner());
303
304 pkgAcquire::Item *Owner = Itm->Owner;
305 pkgAcquire::ItemDesc Desc = *Itm;
306 OwnerQ->ItemDone(Itm);
307 Owner->Failed(Message,Config);
308 ItemDone();
309
310 if (Log != 0)
311 Log->Fail(Desc);
312
313 break;
314 }
315
316 // 401 General Failure
317 case 401:
318 _error->Error("Method %s General failure: %s",Access.c_str(),LookupTag(Message,"Message").c_str());
319 break;
320
321 // 403 Media Change
322 case 403:
323 MediaChange(Message);
324 break;
325 }
326 }
327 return true;
328 }
329 /*}}}*/
330 // Worker::Capabilities - 100 Capabilities handler /*{{{*/
331 // ---------------------------------------------------------------------
332 /* This parses the capabilities message and dumps it into the configuration
333 structure. */
334 bool pkgAcquire::Worker::Capabilities(string Message)
335 {
336 if (Config == 0)
337 return true;
338
339 Config->Version = LookupTag(Message,"Version");
340 Config->SingleInstance = StringToBool(LookupTag(Message,"Single-Instance"),false);
341 Config->Pipeline = StringToBool(LookupTag(Message,"Pipeline"),false);
342 Config->SendConfig = StringToBool(LookupTag(Message,"Send-Config"),false);
343 Config->LocalOnly = StringToBool(LookupTag(Message,"Local-Only"),false);
344 Config->NeedsCleanup = StringToBool(LookupTag(Message,"Needs-Cleanup"),false);
345 Config->Removable = StringToBool(LookupTag(Message,"Removable"),false);
346
347 // Some debug text
348 if (Debug == true)
349 {
350 clog << "Configured access method " << Config->Access << endl;
351 clog << "Version:" << Config->Version <<
352 " SingleInstance:" << Config->SingleInstance <<
353 " Pipeline:" << Config->Pipeline <<
354 " SendConfig:" << Config->SendConfig <<
355 " LocalOnly: " << Config->LocalOnly <<
356 " NeedsCleanup: " << Config->NeedsCleanup <<
357 " Removable: " << Config->Removable << endl;
358 }
359
360 return true;
361 }
362 /*}}}*/
363 // Worker::MediaChange - Request a media change /*{{{*/
364 // ---------------------------------------------------------------------
365 /* */
366 bool pkgAcquire::Worker::MediaChange(string Message)
367 {
368 if (Log == 0 || Log->MediaChange(LookupTag(Message,"Media"),
369 LookupTag(Message,"Drive")) == false)
370 {
371 char S[300];
372 sprintf(S,"603 Media Changed\nFailed: true\n\n");
373 if (Debug == true)
374 clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
375 OutQueue += S;
376 OutReady = true;
377 return true;
378 }
379
380 char S[300];
381 sprintf(S,"603 Media Changed\n\n");
382 if (Debug == true)
383 clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
384 OutQueue += S;
385 OutReady = true;
386 return true;
387 }
388 /*}}}*/
389 // Worker::SendConfiguration - Send the config to the method /*{{{*/
390 // ---------------------------------------------------------------------
391 /* */
392 bool pkgAcquire::Worker::SendConfiguration()
393 {
394 if (Config->SendConfig == false)
395 return true;
396
397 if (OutFd == -1)
398 return false;
399
400 string Message = "601 Configuration\n";
401 Message.reserve(2000);
402
403 /* Write out all of the configuration directives by walking the
404 configuration tree */
405 const Configuration::Item *Top = _config->Tree(0);
406 for (; Top != 0;)
407 {
408 if (Top->Value.empty() == false)
409 {
410 string Line = "Config-Item: " + QuoteString(Top->FullTag(),"=\"\n") + "=";
411 Line += QuoteString(Top->Value,"\n") + '\n';
412 Message += Line;
413 }
414
415 if (Top->Child != 0)
416 {
417 Top = Top->Child;
418 continue;
419 }
420
421 while (Top != 0 && Top->Next == 0)
422 Top = Top->Parent;
423 if (Top != 0)
424 Top = Top->Next;
425 }
426 Message += '\n';
427
428 if (Debug == true)
429 clog << " -> " << Access << ':' << QuoteString(Message,"\n") << endl;
430 OutQueue += Message;
431 OutReady = true;
432
433 return true;
434 }
435 /*}}}*/
436 // Worker::QueueItem - Add an item to the outbound queue /*{{{*/
437 // ---------------------------------------------------------------------
438 /* Send a URI Acquire message to the method */
439 bool pkgAcquire::Worker::QueueItem(pkgAcquire::Queue::QItem *Item)
440 {
441 if (OutFd == -1)
442 return false;
443
444 string Message = "600 URI Acquire\n";
445 Message.reserve(300);
446 Message += "URI: " + Item->URI;
447 Message += "\nFilename: " + Item->Owner->DestFile;
448 Message += Item->Owner->Custom600Headers();
449 Message += "\n\n";
450
451 if (Debug == true)
452 clog << " -> " << Access << ':' << QuoteString(Message,"\n") << endl;
453 OutQueue += Message;
454 OutReady = true;
455
456 return true;
457 }
458 /*}}}*/
459 // Worker::OutFdRead - Out bound FD is ready /*{{{*/
460 // ---------------------------------------------------------------------
461 /* */
462 bool pkgAcquire::Worker::OutFdReady()
463 {
464 int Res;
465 do
466 {
467 Res = write(OutFd,OutQueue.begin(),OutQueue.length());
468 }
469 while (Res < 0 && errno == EINTR);
470
471 if (Res <= 0)
472 return MethodFailure();
473
474 // Hmm.. this should never happen.
475 if (Res < 0)
476 return true;
477
478 OutQueue.erase(0,Res);
479 if (OutQueue.empty() == true)
480 OutReady = false;
481
482 return true;
483 }
484 /*}}}*/
485 // Worker::InFdRead - In bound FD is ready /*{{{*/
486 // ---------------------------------------------------------------------
487 /* */
488 bool pkgAcquire::Worker::InFdReady()
489 {
490 if (ReadMessages() == false)
491 return false;
492 RunMessages();
493 return true;
494 }
495 /*}}}*/
496 // Worker::MethodFailure - Called when the method fails /*{{{*/
497 // ---------------------------------------------------------------------
498 /* This is called when the method is belived to have failed, probably because
499 read returned -1. */
500 bool pkgAcquire::Worker::MethodFailure()
501 {
502 _error->Error("Method %s has died unexpectedly!",Access.c_str());
503
504 ExecWait(Process,Access.c_str(),true);
505 Process = -1;
506 close(InFd);
507 close(OutFd);
508 InFd = -1;
509 OutFd = -1;
510 OutReady = false;
511 InReady = false;
512 OutQueue = string();
513 MessageQueue.erase(MessageQueue.begin(),MessageQueue.end());
514
515 return false;
516 }
517 /*}}}*/
518 // Worker::Pulse - Called periodically /*{{{*/
519 // ---------------------------------------------------------------------
520 /* */
521 void pkgAcquire::Worker::Pulse()
522 {
523 if (CurrentItem == 0)
524 return;
525
526 struct stat Buf;
527 if (stat(CurrentItem->Owner->DestFile.c_str(),&Buf) != 0)
528 return;
529 CurrentSize = Buf.st_size;
530
531 // Hmm? Should not happen...
532 if (CurrentSize > TotalSize && TotalSize != 0)
533 TotalSize = CurrentSize;
534 }
535 /*}}}*/
536 // Worker::ItemDone - Called when the current item is finished /*{{{*/
537 // ---------------------------------------------------------------------
538 /* */
539 void pkgAcquire::Worker::ItemDone()
540 {
541 CurrentItem = 0;
542 CurrentSize = 0;
543 TotalSize = 0;
544 Status = string();
545 }
546 /*}}}*/