acquire-worker.cc 19 KB

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