acquire-worker.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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 <config.h>
  13. #include <apt-pkg/acquire-worker.h>
  14. #include <apt-pkg/acquire-item.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/error.h>
  17. #include <apt-pkg/fileutl.h>
  18. #include <apt-pkg/strutl.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. #include <apti18n.h>
  29. /*}}}*/
  30. using namespace std;
  31. // Worker::Worker - Constructor for Queue startup /*{{{*/
  32. // ---------------------------------------------------------------------
  33. /* */
  34. pkgAcquire::Worker::Worker(Queue *Q,MethodConfig *Cnf,
  35. pkgAcquireStatus *Log) : Log(Log)
  36. {
  37. OwnerQ = Q;
  38. Config = Cnf;
  39. Access = Cnf->Access;
  40. CurrentItem = 0;
  41. TotalSize = 0;
  42. CurrentSize = 0;
  43. Construct();
  44. }
  45. /*}}}*/
  46. // Worker::Worker - Constructor for method config startup /*{{{*/
  47. // ---------------------------------------------------------------------
  48. /* */
  49. pkgAcquire::Worker::Worker(MethodConfig *Cnf)
  50. {
  51. OwnerQ = 0;
  52. Config = Cnf;
  53. Access = Cnf->Access;
  54. CurrentItem = 0;
  55. TotalSize = 0;
  56. CurrentSize = 0;
  57. Construct();
  58. }
  59. /*}}}*/
  60. // Worker::Construct - Constructor helper /*{{{*/
  61. // ---------------------------------------------------------------------
  62. /* */
  63. void pkgAcquire::Worker::Construct()
  64. {
  65. NextQueue = 0;
  66. NextAcquire = 0;
  67. Process = -1;
  68. InFd = -1;
  69. OutFd = -1;
  70. OutReady = false;
  71. InReady = false;
  72. Debug = _config->FindB("Debug::pkgAcquire::Worker",false);
  73. }
  74. /*}}}*/
  75. // Worker::~Worker - Destructor /*{{{*/
  76. // ---------------------------------------------------------------------
  77. /* */
  78. pkgAcquire::Worker::~Worker()
  79. {
  80. close(InFd);
  81. close(OutFd);
  82. if (Process > 0)
  83. {
  84. /* Closing of stdin is the signal to exit and die when the process
  85. indicates it needs cleanup */
  86. if (Config->NeedsCleanup == false)
  87. kill(Process,SIGINT);
  88. ExecWait(Process,Access.c_str(),true);
  89. }
  90. }
  91. /*}}}*/
  92. // Worker::Start - Start the worker process /*{{{*/
  93. // ---------------------------------------------------------------------
  94. /* This forks the method and inits the communication channel */
  95. bool pkgAcquire::Worker::Start()
  96. {
  97. // Get the method path
  98. string Method = _config->FindDir("Dir::Bin::Methods") + Access;
  99. if (FileExists(Method) == false)
  100. return _error->Error(_("The method driver %s could not be found."),Method.c_str());
  101. if (Debug == true)
  102. clog << "Starting method '" << Method << '\'' << endl;
  103. // Create the pipes
  104. int Pipes[4] = {-1,-1,-1,-1};
  105. if (pipe(Pipes) != 0 || pipe(Pipes+2) != 0)
  106. {
  107. _error->Errno("pipe","Failed to create IPC pipe to subprocess");
  108. for (int I = 0; I != 4; I++)
  109. close(Pipes[I]);
  110. return false;
  111. }
  112. for (int I = 0; I != 4; I++)
  113. SetCloseExec(Pipes[I],true);
  114. // Fork off the process
  115. Process = ExecFork();
  116. if (Process == 0)
  117. {
  118. // Setup the FDs
  119. dup2(Pipes[1],STDOUT_FILENO);
  120. dup2(Pipes[2],STDIN_FILENO);
  121. SetCloseExec(STDOUT_FILENO,false);
  122. SetCloseExec(STDIN_FILENO,false);
  123. SetCloseExec(STDERR_FILENO,false);
  124. const char *Args[2];
  125. Args[0] = Method.c_str();
  126. Args[1] = 0;
  127. execv(Args[0],(char **)Args);
  128. cerr << "Failed to exec method " << Args[0] << endl;
  129. _exit(100);
  130. }
  131. // Fix up our FDs
  132. InFd = Pipes[0];
  133. OutFd = Pipes[3];
  134. SetNonBlock(Pipes[0],true);
  135. SetNonBlock(Pipes[3],true);
  136. close(Pipes[1]);
  137. close(Pipes[2]);
  138. OutReady = false;
  139. InReady = true;
  140. // Read the configuration data
  141. if (WaitFd(InFd) == false ||
  142. ReadMessages() == false)
  143. return _error->Error(_("Method %s did not start correctly"),Method.c_str());
  144. RunMessages();
  145. if (OwnerQ != 0)
  146. SendConfiguration();
  147. return true;
  148. }
  149. /*}}}*/
  150. // Worker::ReadMessages - Read all pending messages into the list /*{{{*/
  151. // ---------------------------------------------------------------------
  152. /* */
  153. bool pkgAcquire::Worker::ReadMessages()
  154. {
  155. if (::ReadMessages(InFd,MessageQueue) == false)
  156. return MethodFailure();
  157. return true;
  158. }
  159. /*}}}*/
  160. // Worker::RunMessage - Empty the message queue /*{{{*/
  161. // ---------------------------------------------------------------------
  162. /* This takes the messages from the message queue and runs them through
  163. the parsers in order. */
  164. bool pkgAcquire::Worker::RunMessages()
  165. {
  166. while (MessageQueue.empty() == false)
  167. {
  168. string Message = MessageQueue.front();
  169. MessageQueue.erase(MessageQueue.begin());
  170. if (Debug == true)
  171. clog << " <- " << Access << ':' << QuoteString(Message,"\n") << endl;
  172. // Fetch the message number
  173. char *End;
  174. int Number = strtol(Message.c_str(),&End,10);
  175. if (End == Message.c_str())
  176. return _error->Error("Invalid message from method %s: %s",Access.c_str(),Message.c_str());
  177. string URI = LookupTag(Message,"URI");
  178. pkgAcquire::Queue::QItem *Itm = 0;
  179. if (URI.empty() == false)
  180. Itm = OwnerQ->FindItem(URI,this);
  181. // update used mirror
  182. string UsedMirror = LookupTag(Message,"UsedMirror", "");
  183. if (!UsedMirror.empty() &&
  184. Itm &&
  185. Itm->Description.find(" ") != string::npos)
  186. {
  187. Itm->Description.replace(0, Itm->Description.find(" "), UsedMirror);
  188. // FIXME: will we need this as well?
  189. //Itm->ShortDesc = UsedMirror;
  190. }
  191. // Determine the message number and dispatch
  192. switch (Number)
  193. {
  194. // 100 Capabilities
  195. case 100:
  196. if (Capabilities(Message) == false)
  197. return _error->Error("Unable to process Capabilities message from %s",Access.c_str());
  198. break;
  199. // 101 Log
  200. case 101:
  201. if (Debug == true)
  202. clog << " <- (log) " << LookupTag(Message,"Message") << endl;
  203. break;
  204. // 102 Status
  205. case 102:
  206. Status = LookupTag(Message,"Message");
  207. break;
  208. // 103 Redirect
  209. case 103:
  210. {
  211. if (Itm == 0)
  212. {
  213. _error->Error("Method gave invalid 103 Redirect message");
  214. break;
  215. }
  216. string NewURI = LookupTag(Message,"New-URI",URI.c_str());
  217. Itm->URI = NewURI;
  218. break;
  219. }
  220. // 200 URI Start
  221. case 200:
  222. {
  223. if (Itm == 0)
  224. {
  225. _error->Error("Method gave invalid 200 URI Start message");
  226. break;
  227. }
  228. CurrentItem = Itm;
  229. CurrentSize = 0;
  230. TotalSize = strtoull(LookupTag(Message,"Size","0").c_str(), NULL, 10);
  231. ResumePoint = strtoull(LookupTag(Message,"Resume-Point","0").c_str(), NULL, 10);
  232. Itm->Owner->Start(Message,strtoull(LookupTag(Message,"Size","0").c_str(), NULL, 10));
  233. // Display update before completion
  234. if (Log != 0 && Log->MorePulses == true)
  235. Log->Pulse(Itm->Owner->GetOwner());
  236. if (Log != 0)
  237. Log->Fetch(*Itm);
  238. break;
  239. }
  240. // 201 URI Done
  241. case 201:
  242. {
  243. if (Itm == 0)
  244. {
  245. _error->Error("Method gave invalid 201 URI Done message");
  246. break;
  247. }
  248. pkgAcquire::Item *Owner = Itm->Owner;
  249. pkgAcquire::ItemDesc Desc = *Itm;
  250. // Display update before completion
  251. if (Log != 0 && Log->MorePulses == true)
  252. Log->Pulse(Owner->GetOwner());
  253. OwnerQ->ItemDone(Itm);
  254. unsigned long long const ServerSize = strtoull(LookupTag(Message,"Size","0").c_str(), NULL, 10);
  255. if (TotalSize != 0 && ServerSize != TotalSize)
  256. _error->Warning("Size of file %s is not what the server reported %s %llu",
  257. Owner->DestFile.c_str(), LookupTag(Message,"Size","0").c_str(),TotalSize);
  258. // see if there is a hash to verify
  259. string RecivedHash;
  260. HashString expectedHash(Owner->HashSum());
  261. if(!expectedHash.empty())
  262. {
  263. string hashTag = expectedHash.HashType()+"-Hash";
  264. string hashSum = LookupTag(Message, hashTag.c_str());
  265. if(!hashSum.empty())
  266. RecivedHash = expectedHash.HashType() + ":" + hashSum;
  267. if(_config->FindB("Debug::pkgAcquire::Auth", false) == true)
  268. {
  269. clog << "201 URI Done: " << Owner->DescURI() << endl
  270. << "RecivedHash: " << RecivedHash << endl
  271. << "ExpectedHash: " << expectedHash.toStr()
  272. << endl << endl;
  273. }
  274. }
  275. Owner->Done(Message, ServerSize, 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. std::string const dlstatus = status.str();
  383. size_t done = 0;
  384. size_t todo = dlstatus.size();
  385. errno = 0;
  386. int res = 0;
  387. do
  388. {
  389. res = write(status_fd, dlstatus.c_str() + done, todo);
  390. if (res < 0 && errno == EINTR)
  391. continue;
  392. if (res < 0)
  393. break;
  394. done += res;
  395. todo -= res;
  396. }
  397. while (res > 0 && todo > 0);
  398. }
  399. if (Log == 0 || Log->MediaChange(LookupTag(Message,"Media"),
  400. LookupTag(Message,"Drive")) == false)
  401. {
  402. char S[300];
  403. snprintf(S,sizeof(S),"603 Media Changed\nFailed: true\n\n");
  404. if (Debug == true)
  405. clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
  406. OutQueue += S;
  407. OutReady = true;
  408. return true;
  409. }
  410. char S[300];
  411. snprintf(S,sizeof(S),"603 Media Changed\n\n");
  412. if (Debug == true)
  413. clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
  414. OutQueue += S;
  415. OutReady = true;
  416. return true;
  417. }
  418. /*}}}*/
  419. // Worker::SendConfiguration - Send the config to the method /*{{{*/
  420. // ---------------------------------------------------------------------
  421. /* */
  422. bool pkgAcquire::Worker::SendConfiguration()
  423. {
  424. if (Config->SendConfig == false)
  425. return true;
  426. if (OutFd == -1)
  427. return false;
  428. string Message = "601 Configuration\n";
  429. Message.reserve(2000);
  430. /* Write out all of the configuration directives by walking the
  431. configuration tree */
  432. const Configuration::Item *Top = _config->Tree(0);
  433. for (; Top != 0;)
  434. {
  435. if (Top->Value.empty() == false)
  436. {
  437. string Line = "Config-Item: " + QuoteString(Top->FullTag(),"=\"\n") + "=";
  438. Line += QuoteString(Top->Value,"\n") + '\n';
  439. Message += Line;
  440. }
  441. if (Top->Child != 0)
  442. {
  443. Top = Top->Child;
  444. continue;
  445. }
  446. while (Top != 0 && Top->Next == 0)
  447. Top = Top->Parent;
  448. if (Top != 0)
  449. Top = Top->Next;
  450. }
  451. Message += '\n';
  452. if (Debug == true)
  453. clog << " -> " << Access << ':' << QuoteString(Message,"\n") << endl;
  454. OutQueue += Message;
  455. OutReady = true;
  456. return true;
  457. }
  458. /*}}}*/
  459. // Worker::QueueItem - Add an item to the outbound queue /*{{{*/
  460. // ---------------------------------------------------------------------
  461. /* Send a URI Acquire message to the method */
  462. bool pkgAcquire::Worker::QueueItem(pkgAcquire::Queue::QItem *Item)
  463. {
  464. if (OutFd == -1)
  465. return false;
  466. string Message = "600 URI Acquire\n";
  467. Message.reserve(300);
  468. Message += "URI: " + Item->URI;
  469. Message += "\nFilename: " + Item->Owner->DestFile;
  470. Message += Item->Owner->Custom600Headers();
  471. Message += "\n\n";
  472. if (Debug == true)
  473. clog << " -> " << Access << ':' << QuoteString(Message,"\n") << endl;
  474. OutQueue += Message;
  475. OutReady = true;
  476. return true;
  477. }
  478. /*}}}*/
  479. // Worker::OutFdRead - Out bound FD is ready /*{{{*/
  480. // ---------------------------------------------------------------------
  481. /* */
  482. bool pkgAcquire::Worker::OutFdReady()
  483. {
  484. int Res;
  485. do
  486. {
  487. Res = write(OutFd,OutQueue.c_str(),OutQueue.length());
  488. }
  489. while (Res < 0 && errno == EINTR);
  490. if (Res <= 0)
  491. return MethodFailure();
  492. OutQueue.erase(0,Res);
  493. if (OutQueue.empty() == true)
  494. OutReady = false;
  495. return true;
  496. }
  497. /*}}}*/
  498. // Worker::InFdRead - In bound FD is ready /*{{{*/
  499. // ---------------------------------------------------------------------
  500. /* */
  501. bool pkgAcquire::Worker::InFdReady()
  502. {
  503. if (ReadMessages() == false)
  504. return false;
  505. RunMessages();
  506. return true;
  507. }
  508. /*}}}*/
  509. // Worker::MethodFailure - Called when the method fails /*{{{*/
  510. // ---------------------------------------------------------------------
  511. /* This is called when the method is belived to have failed, probably because
  512. read returned -1. */
  513. bool pkgAcquire::Worker::MethodFailure()
  514. {
  515. _error->Error("Method %s has died unexpectedly!",Access.c_str());
  516. // do not reap the child here to show meaningfull error to the user
  517. ExecWait(Process,Access.c_str(),false);
  518. Process = -1;
  519. close(InFd);
  520. close(OutFd);
  521. InFd = -1;
  522. OutFd = -1;
  523. OutReady = false;
  524. InReady = false;
  525. OutQueue = string();
  526. MessageQueue.erase(MessageQueue.begin(),MessageQueue.end());
  527. return false;
  528. }
  529. /*}}}*/
  530. // Worker::Pulse - Called periodically /*{{{*/
  531. // ---------------------------------------------------------------------
  532. /* */
  533. void pkgAcquire::Worker::Pulse()
  534. {
  535. if (CurrentItem == 0)
  536. return;
  537. struct stat Buf;
  538. if (stat(CurrentItem->Owner->DestFile.c_str(),&Buf) != 0)
  539. return;
  540. CurrentSize = Buf.st_size;
  541. // Hmm? Should not happen...
  542. if (CurrentSize > TotalSize && TotalSize != 0)
  543. TotalSize = CurrentSize;
  544. }
  545. /*}}}*/
  546. // Worker::ItemDone - Called when the current item is finished /*{{{*/
  547. // ---------------------------------------------------------------------
  548. /* */
  549. void pkgAcquire::Worker::ItemDone()
  550. {
  551. CurrentItem = 0;
  552. CurrentSize = 0;
  553. TotalSize = 0;
  554. Status = string();
  555. }
  556. /*}}}*/