acquire-worker.cc 17 KB

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