acquire-worker.cc 17 KB

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