acquire-worker.cc 17 KB

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