acquire-worker.cc 18 KB

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