acquire-worker.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. ItemDone();
  219. pkgAcquire::Item *Owner = Itm->Owner;
  220. pkgAcquire::ItemDesc Desc = *Itm;
  221. // Change the status so that it can be dequeued
  222. Owner->Status = pkgAcquire::Item::StatIdle;
  223. // Mark the item as done (taking care of all queues)
  224. // and then put it in the main queue again
  225. OwnerQ->ItemDone(Itm);
  226. OwnerQ->Owner->Enqueue(Desc);
  227. if (Log != 0)
  228. Log->Done(Desc);
  229. break;
  230. }
  231. // 200 URI Start
  232. case 200:
  233. {
  234. if (Itm == 0)
  235. {
  236. _error->Error("Method gave invalid 200 URI Start message");
  237. break;
  238. }
  239. CurrentItem = Itm;
  240. CurrentSize = 0;
  241. TotalSize = strtoull(LookupTag(Message,"Size","0").c_str(), NULL, 10);
  242. ResumePoint = strtoull(LookupTag(Message,"Resume-Point","0").c_str(), NULL, 10);
  243. Itm->Owner->Start(Message,strtoull(LookupTag(Message,"Size","0").c_str(), NULL, 10));
  244. // Display update before completion
  245. if (Log != 0 && Log->MorePulses == true)
  246. Log->Pulse(Itm->Owner->GetOwner());
  247. if (Log != 0)
  248. Log->Fetch(*Itm);
  249. break;
  250. }
  251. // 201 URI Done
  252. case 201:
  253. {
  254. if (Itm == 0)
  255. {
  256. _error->Error("Method gave invalid 201 URI Done message");
  257. break;
  258. }
  259. pkgAcquire::Item *Owner = Itm->Owner;
  260. pkgAcquire::ItemDesc Desc = *Itm;
  261. // Display update before completion
  262. if (Log != 0 && Log->MorePulses == true)
  263. Log->Pulse(Owner->GetOwner());
  264. OwnerQ->ItemDone(Itm);
  265. unsigned long long const ServerSize = strtoull(LookupTag(Message,"Size","0").c_str(), NULL, 10);
  266. if (TotalSize != 0 && ServerSize != TotalSize)
  267. _error->Warning("Size of file %s is not what the server reported %s %llu",
  268. Owner->DestFile.c_str(), LookupTag(Message,"Size","0").c_str(),TotalSize);
  269. // see if there is a hash to verify
  270. string RecivedHash;
  271. HashString expectedHash(Owner->HashSum());
  272. if(!expectedHash.empty())
  273. {
  274. string hashTag = expectedHash.HashType()+"-Hash";
  275. string hashSum = LookupTag(Message, hashTag.c_str());
  276. if(!hashSum.empty())
  277. RecivedHash = expectedHash.HashType() + ":" + hashSum;
  278. if(_config->FindB("Debug::pkgAcquire::Auth", false) == true)
  279. {
  280. clog << "201 URI Done: " << Owner->DescURI() << endl
  281. << "RecivedHash: " << RecivedHash << endl
  282. << "ExpectedHash: " << expectedHash.toStr()
  283. << endl << endl;
  284. }
  285. }
  286. Owner->Done(Message, ServerSize, RecivedHash.c_str(), Config);
  287. ItemDone();
  288. // Log that we are done
  289. if (Log != 0)
  290. {
  291. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true ||
  292. StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
  293. {
  294. /* Hide 'hits' for local only sources - we also manage to
  295. hide gets */
  296. if (Config->LocalOnly == false)
  297. Log->IMSHit(Desc);
  298. }
  299. else
  300. Log->Done(Desc);
  301. }
  302. break;
  303. }
  304. // 400 URI Failure
  305. case 400:
  306. {
  307. if (Itm == 0)
  308. {
  309. _error->Error("Method gave invalid 400 URI Failure message");
  310. break;
  311. }
  312. // Display update before completion
  313. if (Log != 0 && Log->MorePulses == true)
  314. Log->Pulse(Itm->Owner->GetOwner());
  315. pkgAcquire::Item *Owner = Itm->Owner;
  316. pkgAcquire::ItemDesc Desc = *Itm;
  317. OwnerQ->ItemDone(Itm);
  318. // set some status
  319. if(LookupTag(Message,"FailReason") == "Timeout" ||
  320. LookupTag(Message,"FailReason") == "TmpResolveFailure" ||
  321. LookupTag(Message,"FailReason") == "ResolveFailure" ||
  322. LookupTag(Message,"FailReason") == "ConnectionRefused")
  323. Owner->Status = pkgAcquire::Item::StatTransientNetworkError;
  324. Owner->Failed(Message,Config);
  325. ItemDone();
  326. if (Log != 0)
  327. Log->Fail(Desc);
  328. break;
  329. }
  330. // 401 General Failure
  331. case 401:
  332. _error->Error("Method %s General failure: %s",Access.c_str(),LookupTag(Message,"Message").c_str());
  333. break;
  334. // 403 Media Change
  335. case 403:
  336. MediaChange(Message);
  337. break;
  338. }
  339. }
  340. return true;
  341. }
  342. /*}}}*/
  343. // Worker::Capabilities - 100 Capabilities handler /*{{{*/
  344. // ---------------------------------------------------------------------
  345. /* This parses the capabilities message and dumps it into the configuration
  346. structure. */
  347. bool pkgAcquire::Worker::Capabilities(string Message)
  348. {
  349. if (Config == 0)
  350. return true;
  351. Config->Version = LookupTag(Message,"Version");
  352. Config->SingleInstance = StringToBool(LookupTag(Message,"Single-Instance"),false);
  353. Config->Pipeline = StringToBool(LookupTag(Message,"Pipeline"),false);
  354. Config->SendConfig = StringToBool(LookupTag(Message,"Send-Config"),false);
  355. Config->LocalOnly = StringToBool(LookupTag(Message,"Local-Only"),false);
  356. Config->NeedsCleanup = StringToBool(LookupTag(Message,"Needs-Cleanup"),false);
  357. Config->Removable = StringToBool(LookupTag(Message,"Removable"),false);
  358. // Some debug text
  359. if (Debug == true)
  360. {
  361. clog << "Configured access method " << Config->Access << endl;
  362. clog << "Version:" << Config->Version <<
  363. " SingleInstance:" << Config->SingleInstance <<
  364. " Pipeline:" << Config->Pipeline <<
  365. " SendConfig:" << Config->SendConfig <<
  366. " LocalOnly: " << Config->LocalOnly <<
  367. " NeedsCleanup: " << Config->NeedsCleanup <<
  368. " Removable: " << Config->Removable << endl;
  369. }
  370. return true;
  371. }
  372. /*}}}*/
  373. // Worker::MediaChange - Request a media change /*{{{*/
  374. // ---------------------------------------------------------------------
  375. /* */
  376. bool pkgAcquire::Worker::MediaChange(string Message)
  377. {
  378. int status_fd = _config->FindI("APT::Status-Fd",-1);
  379. if(status_fd > 0)
  380. {
  381. string Media = LookupTag(Message,"Media");
  382. string Drive = LookupTag(Message,"Drive");
  383. ostringstream msg,status;
  384. ioprintf(msg,_("Please insert the disc labeled: "
  385. "'%s' "
  386. "in the drive '%s' and press enter."),
  387. Media.c_str(),Drive.c_str());
  388. status << "media-change: " // message
  389. << Media << ":" // media
  390. << Drive << ":" // drive
  391. << msg.str() // l10n message
  392. << endl;
  393. std::string const dlstatus = status.str();
  394. FileFd::Write(status_fd, dlstatus.c_str(), dlstatus.size());
  395. }
  396. if (Log == 0 || Log->MediaChange(LookupTag(Message,"Media"),
  397. LookupTag(Message,"Drive")) == false)
  398. {
  399. char S[300];
  400. snprintf(S,sizeof(S),"603 Media Changed\nFailed: true\n\n");
  401. if (Debug == true)
  402. clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
  403. OutQueue += S;
  404. OutReady = true;
  405. return true;
  406. }
  407. char S[300];
  408. snprintf(S,sizeof(S),"603 Media Changed\n\n");
  409. if (Debug == true)
  410. clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
  411. OutQueue += S;
  412. OutReady = true;
  413. return true;
  414. }
  415. /*}}}*/
  416. // Worker::SendConfiguration - Send the config to the method /*{{{*/
  417. // ---------------------------------------------------------------------
  418. /* */
  419. bool pkgAcquire::Worker::SendConfiguration()
  420. {
  421. if (Config->SendConfig == false)
  422. return true;
  423. if (OutFd == -1)
  424. return false;
  425. /* Write out all of the configuration directives by walking the
  426. configuration tree */
  427. std::ostringstream Message;
  428. Message << "601 Configuration\n";
  429. _config->Dump(Message, NULL, "Config-Item: %F=%V\n", false);
  430. Message << '\n';
  431. if (Debug == true)
  432. clog << " -> " << Access << ':' << QuoteString(Message.str(),"\n") << endl;
  433. OutQueue += Message.str();
  434. OutReady = true;
  435. return true;
  436. }
  437. /*}}}*/
  438. // Worker::QueueItem - Add an item to the outbound queue /*{{{*/
  439. // ---------------------------------------------------------------------
  440. /* Send a URI Acquire message to the method */
  441. bool pkgAcquire::Worker::QueueItem(pkgAcquire::Queue::QItem *Item)
  442. {
  443. if (OutFd == -1)
  444. return false;
  445. string Message = "600 URI Acquire\n";
  446. Message.reserve(300);
  447. Message += "URI: " + Item->URI;
  448. Message += "\nFilename: " + Item->Owner->DestFile;
  449. Message += Item->Owner->Custom600Headers();
  450. Message += "\n\n";
  451. if (Debug == true)
  452. clog << " -> " << Access << ':' << QuoteString(Message,"\n") << endl;
  453. OutQueue += Message;
  454. OutReady = true;
  455. return true;
  456. }
  457. /*}}}*/
  458. // Worker::OutFdRead - Out bound FD is ready /*{{{*/
  459. // ---------------------------------------------------------------------
  460. /* */
  461. bool pkgAcquire::Worker::OutFdReady()
  462. {
  463. int Res;
  464. do
  465. {
  466. Res = write(OutFd,OutQueue.c_str(),OutQueue.length());
  467. }
  468. while (Res < 0 && errno == EINTR);
  469. if (Res <= 0)
  470. return MethodFailure();
  471. OutQueue.erase(0,Res);
  472. if (OutQueue.empty() == true)
  473. OutReady = false;
  474. return true;
  475. }
  476. /*}}}*/
  477. // Worker::InFdRead - In bound FD is ready /*{{{*/
  478. // ---------------------------------------------------------------------
  479. /* */
  480. bool pkgAcquire::Worker::InFdReady()
  481. {
  482. if (ReadMessages() == false)
  483. return false;
  484. RunMessages();
  485. return true;
  486. }
  487. /*}}}*/
  488. // Worker::MethodFailure - Called when the method fails /*{{{*/
  489. // ---------------------------------------------------------------------
  490. /* This is called when the method is belived to have failed, probably because
  491. read returned -1. */
  492. bool pkgAcquire::Worker::MethodFailure()
  493. {
  494. _error->Error("Method %s has died unexpectedly!",Access.c_str());
  495. // do not reap the child here to show meaningfull error to the user
  496. ExecWait(Process,Access.c_str(),false);
  497. Process = -1;
  498. close(InFd);
  499. close(OutFd);
  500. InFd = -1;
  501. OutFd = -1;
  502. OutReady = false;
  503. InReady = false;
  504. OutQueue = string();
  505. MessageQueue.erase(MessageQueue.begin(),MessageQueue.end());
  506. return false;
  507. }
  508. /*}}}*/
  509. // Worker::Pulse - Called periodically /*{{{*/
  510. // ---------------------------------------------------------------------
  511. /* */
  512. void pkgAcquire::Worker::Pulse()
  513. {
  514. if (CurrentItem == 0)
  515. return;
  516. struct stat Buf;
  517. if (stat(CurrentItem->Owner->DestFile.c_str(),&Buf) != 0)
  518. return;
  519. CurrentSize = Buf.st_size;
  520. // Hmm? Should not happen...
  521. if (CurrentSize > TotalSize && TotalSize != 0)
  522. TotalSize = CurrentSize;
  523. }
  524. /*}}}*/
  525. // Worker::ItemDone - Called when the current item is finished /*{{{*/
  526. // ---------------------------------------------------------------------
  527. /* */
  528. void pkgAcquire::Worker::ItemDone()
  529. {
  530. CurrentItem = 0;
  531. CurrentSize = 0;
  532. TotalSize = 0;
  533. Status = string();
  534. }
  535. /*}}}*/