acquire-worker.cc 18 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.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. _error->Error("Method gave invalid 400 URI Failure message");
  329. break;
  330. }
  331. // Display update before completion
  332. if (Log != 0 && Log->MorePulses == true)
  333. Log->Pulse(Itm->Owner->GetOwner());
  334. pkgAcquire::Item *Owner = Itm->Owner;
  335. pkgAcquire::ItemDesc Desc = *Itm;
  336. OwnerQ->ItemDone(Itm);
  337. // set some status
  338. if(LookupTag(Message,"FailReason") == "Timeout" ||
  339. LookupTag(Message,"FailReason") == "TmpResolveFailure" ||
  340. LookupTag(Message,"FailReason") == "ResolveFailure" ||
  341. LookupTag(Message,"FailReason") == "ConnectionRefused")
  342. Owner->Status = pkgAcquire::Item::StatTransientNetworkError;
  343. Owner->Failed(Message,Config);
  344. ItemDone();
  345. if (Log != 0)
  346. Log->Fail(Desc);
  347. break;
  348. }
  349. // 401 General Failure
  350. case 401:
  351. _error->Error("Method %s General failure: %s",Access.c_str(),LookupTag(Message,"Message").c_str());
  352. break;
  353. // 403 Media Change
  354. case 403:
  355. MediaChange(Message);
  356. break;
  357. }
  358. }
  359. return true;
  360. }
  361. /*}}}*/
  362. // Worker::Capabilities - 100 Capabilities handler /*{{{*/
  363. // ---------------------------------------------------------------------
  364. /* This parses the capabilities message and dumps it into the configuration
  365. structure. */
  366. bool pkgAcquire::Worker::Capabilities(string Message)
  367. {
  368. if (Config == 0)
  369. return true;
  370. Config->Version = LookupTag(Message,"Version");
  371. Config->SingleInstance = StringToBool(LookupTag(Message,"Single-Instance"),false);
  372. Config->Pipeline = StringToBool(LookupTag(Message,"Pipeline"),false);
  373. Config->SendConfig = StringToBool(LookupTag(Message,"Send-Config"),false);
  374. Config->LocalOnly = StringToBool(LookupTag(Message,"Local-Only"),false);
  375. Config->NeedsCleanup = StringToBool(LookupTag(Message,"Needs-Cleanup"),false);
  376. Config->Removable = StringToBool(LookupTag(Message,"Removable"),false);
  377. // Some debug text
  378. if (Debug == true)
  379. {
  380. clog << "Configured access method " << Config->Access << endl;
  381. clog << "Version:" << Config->Version <<
  382. " SingleInstance:" << Config->SingleInstance <<
  383. " Pipeline:" << Config->Pipeline <<
  384. " SendConfig:" << Config->SendConfig <<
  385. " LocalOnly: " << Config->LocalOnly <<
  386. " NeedsCleanup: " << Config->NeedsCleanup <<
  387. " Removable: " << Config->Removable << endl;
  388. }
  389. return true;
  390. }
  391. /*}}}*/
  392. // Worker::MediaChange - Request a media change /*{{{*/
  393. // ---------------------------------------------------------------------
  394. /* */
  395. bool pkgAcquire::Worker::MediaChange(string Message)
  396. {
  397. int status_fd = _config->FindI("APT::Status-Fd",-1);
  398. if(status_fd > 0)
  399. {
  400. string Media = LookupTag(Message,"Media");
  401. string Drive = LookupTag(Message,"Drive");
  402. ostringstream msg,status;
  403. ioprintf(msg,_("Please insert the disc labeled: "
  404. "'%s' "
  405. "in the drive '%s' and press enter."),
  406. Media.c_str(),Drive.c_str());
  407. status << "media-change: " // message
  408. << Media << ":" // media
  409. << Drive << ":" // drive
  410. << msg.str() // l10n message
  411. << endl;
  412. std::string const dlstatus = status.str();
  413. FileFd::Write(status_fd, dlstatus.c_str(), dlstatus.size());
  414. }
  415. if (Log == 0 || Log->MediaChange(LookupTag(Message,"Media"),
  416. LookupTag(Message,"Drive")) == false)
  417. {
  418. char S[300];
  419. snprintf(S,sizeof(S),"603 Media Changed\nFailed: true\n\n");
  420. if (Debug == true)
  421. clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
  422. OutQueue += S;
  423. OutReady = true;
  424. return true;
  425. }
  426. char S[300];
  427. snprintf(S,sizeof(S),"603 Media Changed\n\n");
  428. if (Debug == true)
  429. clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
  430. OutQueue += S;
  431. OutReady = true;
  432. return true;
  433. }
  434. /*}}}*/
  435. // Worker::SendConfiguration - Send the config to the method /*{{{*/
  436. // ---------------------------------------------------------------------
  437. /* */
  438. bool pkgAcquire::Worker::SendConfiguration()
  439. {
  440. if (Config->SendConfig == false)
  441. return true;
  442. if (OutFd == -1)
  443. return false;
  444. /* Write out all of the configuration directives by walking the
  445. configuration tree */
  446. std::ostringstream Message;
  447. Message << "601 Configuration\n";
  448. _config->Dump(Message, NULL, "Config-Item: %F=%V\n", false);
  449. Message << '\n';
  450. if (Debug == true)
  451. clog << " -> " << Access << ':' << QuoteString(Message.str(),"\n") << endl;
  452. OutQueue += Message.str();
  453. OutReady = true;
  454. return true;
  455. }
  456. /*}}}*/
  457. // Worker::QueueItem - Add an item to the outbound queue /*{{{*/
  458. // ---------------------------------------------------------------------
  459. /* Send a URI Acquire message to the method */
  460. bool pkgAcquire::Worker::QueueItem(pkgAcquire::Queue::QItem *Item)
  461. {
  462. if (OutFd == -1)
  463. return false;
  464. string Message = "600 URI Acquire\n";
  465. Message.reserve(300);
  466. Message += "URI: " + Item->URI;
  467. Message += "\nFilename: " + Item->Owner->DestFile;
  468. Message += Item->Owner->Custom600Headers();
  469. Message += "\n\n";
  470. if (Debug == true)
  471. clog << " -> " << Access << ':' << QuoteString(Message,"\n") << endl;
  472. OutQueue += Message;
  473. OutReady = true;
  474. return true;
  475. }
  476. /*}}}*/
  477. // Worker::OutFdRead - Out bound FD is ready /*{{{*/
  478. // ---------------------------------------------------------------------
  479. /* */
  480. bool pkgAcquire::Worker::OutFdReady()
  481. {
  482. int Res;
  483. do
  484. {
  485. Res = write(OutFd,OutQueue.c_str(),OutQueue.length());
  486. }
  487. while (Res < 0 && errno == EINTR);
  488. if (Res <= 0)
  489. return MethodFailure();
  490. OutQueue.erase(0,Res);
  491. if (OutQueue.empty() == true)
  492. OutReady = false;
  493. return true;
  494. }
  495. /*}}}*/
  496. // Worker::InFdRead - In bound FD is ready /*{{{*/
  497. // ---------------------------------------------------------------------
  498. /* */
  499. bool pkgAcquire::Worker::InFdReady()
  500. {
  501. if (ReadMessages() == false)
  502. return false;
  503. RunMessages();
  504. return true;
  505. }
  506. /*}}}*/
  507. // Worker::MethodFailure - Called when the method fails /*{{{*/
  508. // ---------------------------------------------------------------------
  509. /* This is called when the method is believed to have failed, probably because
  510. read returned -1. */
  511. bool pkgAcquire::Worker::MethodFailure()
  512. {
  513. _error->Error("Method %s has died unexpectedly!",Access.c_str());
  514. // do not reap the child here to show meaningfull error to the user
  515. ExecWait(Process,Access.c_str(),false);
  516. Process = -1;
  517. close(InFd);
  518. close(OutFd);
  519. InFd = -1;
  520. OutFd = -1;
  521. OutReady = false;
  522. InReady = false;
  523. OutQueue = string();
  524. MessageQueue.erase(MessageQueue.begin(),MessageQueue.end());
  525. return false;
  526. }
  527. /*}}}*/
  528. // Worker::Pulse - Called periodically /*{{{*/
  529. // ---------------------------------------------------------------------
  530. /* */
  531. void pkgAcquire::Worker::Pulse()
  532. {
  533. if (CurrentItem == 0)
  534. return;
  535. struct stat Buf;
  536. if (stat(CurrentItem->Owner->DestFile.c_str(),&Buf) != 0)
  537. return;
  538. CurrentSize = Buf.st_size;
  539. // Hmm? Should not happen...
  540. if (CurrentSize > TotalSize && TotalSize != 0)
  541. TotalSize = CurrentSize;
  542. }
  543. /*}}}*/
  544. // Worker::ItemDone - Called when the current item is finished /*{{{*/
  545. // ---------------------------------------------------------------------
  546. /* */
  547. void pkgAcquire::Worker::ItemDone()
  548. {
  549. CurrentItem = 0;
  550. CurrentSize = 0;
  551. TotalSize = 0;
  552. Status = string();
  553. }
  554. /*}}}*/