acquire-worker.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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 <algorithm>
  22. #include <string>
  23. #include <vector>
  24. #include <iostream>
  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 <sstream>
  32. #include <apti18n.h>
  33. /*}}}*/
  34. using namespace std;
  35. // Worker::Worker - Constructor for Queue startup /*{{{*/
  36. pkgAcquire::Worker::Worker(Queue *Q, MethodConfig *Cnf, pkgAcquireStatus *log) :
  37. d(NULL), OwnerQ(Q), Log(log), Config(Cnf), Access(Cnf->Access),
  38. CurrentItem(nullptr), CurrentSize(0), TotalSize(0)
  39. {
  40. Construct();
  41. }
  42. /*}}}*/
  43. // Worker::Worker - Constructor for method config startup /*{{{*/
  44. pkgAcquire::Worker::Worker(MethodConfig *Cnf) : Worker(nullptr, Cnf, nullptr)
  45. {
  46. }
  47. /*}}}*/
  48. // Worker::Construct - Constructor helper /*{{{*/
  49. // ---------------------------------------------------------------------
  50. /* */
  51. void pkgAcquire::Worker::Construct()
  52. {
  53. NextQueue = 0;
  54. NextAcquire = 0;
  55. Process = -1;
  56. InFd = -1;
  57. OutFd = -1;
  58. OutReady = false;
  59. InReady = false;
  60. Debug = _config->FindB("Debug::pkgAcquire::Worker",false);
  61. }
  62. /*}}}*/
  63. // Worker::~Worker - Destructor /*{{{*/
  64. // ---------------------------------------------------------------------
  65. /* */
  66. pkgAcquire::Worker::~Worker()
  67. {
  68. close(InFd);
  69. close(OutFd);
  70. if (Process > 0)
  71. {
  72. /* Closing of stdin is the signal to exit and die when the process
  73. indicates it needs cleanup */
  74. if (Config->NeedsCleanup == false)
  75. kill(Process,SIGINT);
  76. ExecWait(Process,Access.c_str(),true);
  77. }
  78. }
  79. /*}}}*/
  80. // Worker::Start - Start the worker process /*{{{*/
  81. // ---------------------------------------------------------------------
  82. /* This forks the method and inits the communication channel */
  83. bool pkgAcquire::Worker::Start()
  84. {
  85. // Get the method path
  86. string Method = _config->FindDir("Dir::Bin::Methods") + Access;
  87. if (FileExists(Method) == false)
  88. {
  89. _error->Error(_("The method driver %s could not be found."),Method.c_str());
  90. if (Access == "https")
  91. _error->Notice(_("Is the package %s installed?"), "apt-transport-https");
  92. return false;
  93. }
  94. if (Debug == true)
  95. clog << "Starting method '" << Method << '\'' << endl;
  96. // Create the pipes
  97. int Pipes[4] = {-1,-1,-1,-1};
  98. if (pipe(Pipes) != 0 || pipe(Pipes+2) != 0)
  99. {
  100. _error->Errno("pipe","Failed to create IPC pipe to subprocess");
  101. for (int I = 0; I != 4; I++)
  102. close(Pipes[I]);
  103. return false;
  104. }
  105. for (int I = 0; I != 4; I++)
  106. SetCloseExec(Pipes[I],true);
  107. // Fork off the process
  108. Process = ExecFork();
  109. if (Process == 0)
  110. {
  111. // Setup the FDs
  112. dup2(Pipes[1],STDOUT_FILENO);
  113. dup2(Pipes[2],STDIN_FILENO);
  114. SetCloseExec(STDOUT_FILENO,false);
  115. SetCloseExec(STDIN_FILENO,false);
  116. SetCloseExec(STDERR_FILENO,false);
  117. const char *Args[2];
  118. Args[0] = Method.c_str();
  119. Args[1] = 0;
  120. execv(Args[0],(char **)Args);
  121. cerr << "Failed to exec method " << Args[0] << endl;
  122. _exit(100);
  123. }
  124. // Fix up our FDs
  125. InFd = Pipes[0];
  126. OutFd = Pipes[3];
  127. SetNonBlock(Pipes[0],true);
  128. SetNonBlock(Pipes[3],true);
  129. close(Pipes[1]);
  130. close(Pipes[2]);
  131. OutReady = false;
  132. InReady = true;
  133. // Read the configuration data
  134. if (WaitFd(InFd) == false ||
  135. ReadMessages() == false)
  136. return _error->Error(_("Method %s did not start correctly"),Method.c_str());
  137. RunMessages();
  138. if (OwnerQ != 0)
  139. SendConfiguration();
  140. return true;
  141. }
  142. /*}}}*/
  143. // Worker::ReadMessages - Read all pending messages into the list /*{{{*/
  144. // ---------------------------------------------------------------------
  145. /* */
  146. bool pkgAcquire::Worker::ReadMessages()
  147. {
  148. if (::ReadMessages(InFd,MessageQueue) == false)
  149. return MethodFailure();
  150. return true;
  151. }
  152. /*}}}*/
  153. // Worker::RunMessage - Empty the message queue /*{{{*/
  154. // ---------------------------------------------------------------------
  155. /* This takes the messages from the message queue and runs them through
  156. the parsers in order. */
  157. enum class APT_HIDDEN MessageType {
  158. CAPABILITIES = 100,
  159. LOG = 101,
  160. STATUS = 102,
  161. REDIRECT = 103,
  162. WARNING = 104,
  163. URI_START = 200,
  164. URI_DONE = 201,
  165. URI_FAILURE = 400,
  166. GENERAL_FAILURE = 401,
  167. MEDIA_CHANGE = 403
  168. };
  169. static bool isDoomedItem(pkgAcquire::Item const * const Itm)
  170. {
  171. auto const TransItm = dynamic_cast<pkgAcqTransactionItem const * const>(Itm);
  172. if (TransItm == nullptr)
  173. return false;
  174. return TransItm->TransactionManager->State != pkgAcqTransactionItem::TransactionStarted;
  175. }
  176. bool pkgAcquire::Worker::RunMessages()
  177. {
  178. while (MessageQueue.empty() == false)
  179. {
  180. string Message = MessageQueue.front();
  181. MessageQueue.erase(MessageQueue.begin());
  182. if (Debug == true)
  183. clog << " <- " << Access << ':' << QuoteString(Message,"\n") << endl;
  184. // Fetch the message number
  185. char *End;
  186. MessageType const Number = static_cast<MessageType>(strtoul(Message.c_str(),&End,10));
  187. if (End == Message.c_str())
  188. return _error->Error("Invalid message from method %s: %s",Access.c_str(),Message.c_str());
  189. string URI = LookupTag(Message,"URI");
  190. pkgAcquire::Queue::QItem *Itm = NULL;
  191. if (URI.empty() == false)
  192. Itm = OwnerQ->FindItem(URI,this);
  193. if (Itm != NULL)
  194. {
  195. // update used mirror
  196. string UsedMirror = LookupTag(Message,"UsedMirror", "");
  197. if (UsedMirror.empty() == false)
  198. {
  199. for (pkgAcquire::Queue::QItem::owner_iterator O = Itm->Owners.begin(); O != Itm->Owners.end(); ++O)
  200. (*O)->UsedMirror = UsedMirror;
  201. if (Itm->Description.find(" ") != string::npos)
  202. Itm->Description.replace(0, Itm->Description.find(" "), UsedMirror);
  203. }
  204. }
  205. // Determine the message number and dispatch
  206. switch (Number)
  207. {
  208. case MessageType::CAPABILITIES:
  209. if (Capabilities(Message) == false)
  210. return _error->Error("Unable to process Capabilities message from %s",Access.c_str());
  211. break;
  212. case MessageType::LOG:
  213. if (Debug == true)
  214. clog << " <- (log) " << LookupTag(Message,"Message") << endl;
  215. break;
  216. case MessageType::STATUS:
  217. Status = LookupTag(Message,"Message");
  218. break;
  219. case MessageType::REDIRECT:
  220. {
  221. if (Itm == nullptr)
  222. {
  223. _error->Error("Method gave invalid 103 Redirect message");
  224. break;
  225. }
  226. std::string const NewURI = LookupTag(Message,"New-URI",URI.c_str());
  227. Itm->URI = NewURI;
  228. ItemDone();
  229. // Change the status so that it can be dequeued
  230. for (auto const &O: Itm->Owners)
  231. O->Status = pkgAcquire::Item::StatIdle;
  232. // Mark the item as done (taking care of all queues)
  233. // and then put it in the main queue again
  234. std::vector<Item*> const ItmOwners = Itm->Owners;
  235. OwnerQ->ItemDone(Itm);
  236. Itm = nullptr;
  237. for (auto const &Owner: ItmOwners)
  238. {
  239. pkgAcquire::ItemDesc &desc = Owner->GetItemDesc();
  240. if (Log != nullptr)
  241. Log->Done(desc);
  242. // if we change site, treat it as a mirror change
  243. if (URI::SiteOnly(NewURI) != URI::SiteOnly(desc.URI))
  244. {
  245. auto const firstSpace = desc.Description.find(" ");
  246. if (firstSpace != std::string::npos)
  247. {
  248. std::string const OldSite = desc.Description.substr(0, firstSpace);
  249. if (likely(APT::String::Startswith(desc.URI, OldSite)))
  250. {
  251. std::string const OldExtra = desc.URI.substr(OldSite.length() + 1);
  252. if (likely(APT::String::Endswith(NewURI, OldExtra)))
  253. {
  254. std::string const NewSite = NewURI.substr(0, NewURI.length() - OldExtra.length());
  255. Owner->UsedMirror = URI::ArchiveOnly(NewSite);
  256. desc.Description.replace(0, firstSpace, Owner->UsedMirror);
  257. }
  258. }
  259. }
  260. }
  261. desc.URI = NewURI;
  262. if (isDoomedItem(Owner) == false)
  263. OwnerQ->Owner->Enqueue(desc);
  264. }
  265. break;
  266. }
  267. case MessageType::WARNING:
  268. _error->Warning("%s: %s", Itm->Owner->DescURI().c_str(), LookupTag(Message,"Message").c_str());
  269. break;
  270. case MessageType::URI_START:
  271. {
  272. if (Itm == nullptr)
  273. {
  274. _error->Error("Method gave invalid 200 URI Start message");
  275. break;
  276. }
  277. CurrentItem = Itm;
  278. CurrentSize = 0;
  279. TotalSize = strtoull(LookupTag(Message,"Size","0").c_str(), NULL, 10);
  280. ResumePoint = strtoull(LookupTag(Message,"Resume-Point","0").c_str(), NULL, 10);
  281. for (auto const Owner: Itm->Owners)
  282. {
  283. Owner->Start(Message, TotalSize);
  284. // Display update before completion
  285. if (Log != nullptr)
  286. {
  287. if (Log->MorePulses == true)
  288. Log->Pulse(Owner->GetOwner());
  289. Log->Fetch(Owner->GetItemDesc());
  290. }
  291. }
  292. break;
  293. }
  294. case MessageType::URI_DONE:
  295. {
  296. if (Itm == nullptr)
  297. {
  298. _error->Error("Method gave invalid 201 URI Done message");
  299. break;
  300. }
  301. PrepareFiles("201::URIDone", Itm);
  302. // Display update before completion
  303. if (Log != 0 && Log->MorePulses == true)
  304. for (pkgAcquire::Queue::QItem::owner_iterator O = Itm->Owners.begin(); O != Itm->Owners.end(); ++O)
  305. Log->Pulse((*O)->GetOwner());
  306. HashStringList ReceivedHashes;
  307. {
  308. std::string const givenfilename = LookupTag(Message, "Filename");
  309. std::string const filename = givenfilename.empty() ? Itm->Owner->DestFile : givenfilename;
  310. // see if we got hashes to verify
  311. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  312. {
  313. std::string const tagname = std::string(*type) + "-Hash";
  314. std::string const hashsum = LookupTag(Message, tagname.c_str());
  315. if (hashsum.empty() == false)
  316. ReceivedHashes.push_back(HashString(*type, hashsum));
  317. }
  318. // not all methods always sent Hashes our way
  319. if (ReceivedHashes.usable() == false)
  320. {
  321. HashStringList const ExpectedHashes = Itm->GetExpectedHashes();
  322. if (ExpectedHashes.usable() == true && RealFileExists(filename))
  323. {
  324. Hashes calc(ExpectedHashes);
  325. FileFd file(filename, FileFd::ReadOnly, FileFd::None);
  326. calc.AddFD(file);
  327. ReceivedHashes = calc.GetHashStringList();
  328. }
  329. }
  330. // only local files can refer other filenames and counting them as fetched would be unfair
  331. if (Log != NULL && Itm->Owner->Complete == false && Itm->Owner->Local == false && givenfilename == filename)
  332. Log->Fetched(ReceivedHashes.FileSize(),atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  333. }
  334. std::vector<Item*> const ItmOwners = Itm->Owners;
  335. OwnerQ->ItemDone(Itm);
  336. Itm = NULL;
  337. bool const isIMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false) ||
  338. StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false);
  339. for (auto const Owner: ItmOwners)
  340. {
  341. HashStringList const ExpectedHashes = Owner->GetExpectedHashes();
  342. if(_config->FindB("Debug::pkgAcquire::Auth", false) == true)
  343. {
  344. std::clog << "201 URI Done: " << Owner->DescURI() << endl
  345. << "ReceivedHash:" << endl;
  346. for (HashStringList::const_iterator hs = ReceivedHashes.begin(); hs != ReceivedHashes.end(); ++hs)
  347. std::clog << "\t- " << hs->toStr() << std::endl;
  348. std::clog << "ExpectedHash:" << endl;
  349. for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
  350. std::clog << "\t- " << hs->toStr() << std::endl;
  351. std::clog << endl;
  352. }
  353. // decide if what we got is what we expected
  354. bool consideredOkay = false;
  355. if (ExpectedHashes.usable())
  356. {
  357. if (ReceivedHashes.usable() == false)
  358. {
  359. /* IMS-Hits can't be checked here as we will have uncompressed file,
  360. but the hashes for the compressed file. What we have was good through
  361. so all we have to ensure later is that we are not stalled. */
  362. consideredOkay = isIMSHit;
  363. }
  364. else if (ReceivedHashes == ExpectedHashes)
  365. consideredOkay = true;
  366. else
  367. consideredOkay = false;
  368. }
  369. else if (Owner->HashesRequired() == true)
  370. consideredOkay = false;
  371. else
  372. {
  373. consideredOkay = true;
  374. // even if the hashes aren't usable to declare something secure
  375. // we can at least use them to declare it an integrity failure
  376. if (ExpectedHashes.empty() == false && ReceivedHashes != ExpectedHashes && _config->Find("Acquire::ForceHash").empty())
  377. consideredOkay = false;
  378. }
  379. if (consideredOkay == true)
  380. consideredOkay = Owner->VerifyDone(Message, Config);
  381. else // hashsum mismatch
  382. Owner->Status = pkgAcquire::Item::StatAuthError;
  383. if (consideredOkay == true)
  384. {
  385. if (isDoomedItem(Owner) == false)
  386. Owner->Done(Message, ReceivedHashes, Config);
  387. if (Log != nullptr)
  388. {
  389. if (isIMSHit)
  390. Log->IMSHit(Owner->GetItemDesc());
  391. else
  392. Log->Done(Owner->GetItemDesc());
  393. }
  394. }
  395. else
  396. {
  397. if (isDoomedItem(Owner) == false)
  398. {
  399. Message.append("\nFailReason: HashSumMismatch");
  400. Owner->Failed(Message,Config);
  401. }
  402. if (Log != nullptr)
  403. Log->Fail(Owner->GetItemDesc());
  404. }
  405. }
  406. ItemDone();
  407. break;
  408. }
  409. case MessageType::URI_FAILURE:
  410. {
  411. if (Itm == nullptr)
  412. {
  413. std::string const msg = LookupTag(Message,"Message");
  414. _error->Error("Method gave invalid 400 URI Failure message: %s", msg.c_str());
  415. break;
  416. }
  417. PrepareFiles("400::URIFailure", Itm);
  418. // Display update before completion
  419. if (Log != nullptr && Log->MorePulses == true)
  420. for (pkgAcquire::Queue::QItem::owner_iterator O = Itm->Owners.begin(); O != Itm->Owners.end(); ++O)
  421. Log->Pulse((*O)->GetOwner());
  422. std::vector<Item*> const ItmOwners = Itm->Owners;
  423. OwnerQ->ItemDone(Itm);
  424. Itm = nullptr;
  425. bool errTransient = false, errAuthErr = false;
  426. {
  427. std::string const failReason = LookupTag(Message, "FailReason");
  428. {
  429. auto const reasons = { "Timeout", "ConnectionRefused",
  430. "ConnectionTimedOut", "ResolveFailure", "TmpResolveFailure" };
  431. errTransient = std::find(std::begin(reasons), std::end(reasons), failReason) != std::end(reasons);
  432. }
  433. if (errTransient == false)
  434. {
  435. auto const reasons = { "HashSumMismatch", "MaximumSizeExceeded" };
  436. errAuthErr = std::find(std::begin(reasons), std::end(reasons), failReason) != std::end(reasons);
  437. }
  438. }
  439. for (auto const Owner: ItmOwners)
  440. {
  441. if (errAuthErr && Owner->GetExpectedHashes().empty() == false)
  442. Owner->Status = pkgAcquire::Item::StatAuthError;
  443. else if (errTransient)
  444. Owner->Status = pkgAcquire::Item::StatTransientNetworkError;
  445. if (isDoomedItem(Owner) == false)
  446. Owner->Failed(Message,Config);
  447. if (Log != nullptr)
  448. Log->Fail(Owner->GetItemDesc());
  449. }
  450. ItemDone();
  451. break;
  452. }
  453. case MessageType::GENERAL_FAILURE:
  454. _error->Error("Method %s General failure: %s",Access.c_str(),LookupTag(Message,"Message").c_str());
  455. break;
  456. case MessageType::MEDIA_CHANGE:
  457. MediaChange(Message);
  458. break;
  459. }
  460. }
  461. return true;
  462. }
  463. /*}}}*/
  464. // Worker::Capabilities - 100 Capabilities handler /*{{{*/
  465. // ---------------------------------------------------------------------
  466. /* This parses the capabilities message and dumps it into the configuration
  467. structure. */
  468. bool pkgAcquire::Worker::Capabilities(string Message)
  469. {
  470. if (Config == 0)
  471. return true;
  472. Config->Version = LookupTag(Message,"Version");
  473. Config->SingleInstance = StringToBool(LookupTag(Message,"Single-Instance"),false);
  474. Config->Pipeline = StringToBool(LookupTag(Message,"Pipeline"),false);
  475. Config->SendConfig = StringToBool(LookupTag(Message,"Send-Config"),false);
  476. Config->LocalOnly = StringToBool(LookupTag(Message,"Local-Only"),false);
  477. Config->NeedsCleanup = StringToBool(LookupTag(Message,"Needs-Cleanup"),false);
  478. Config->Removable = StringToBool(LookupTag(Message,"Removable"),false);
  479. // Some debug text
  480. if (Debug == true)
  481. {
  482. clog << "Configured access method " << Config->Access << endl;
  483. clog << "Version:" << Config->Version <<
  484. " SingleInstance:" << Config->SingleInstance <<
  485. " Pipeline:" << Config->Pipeline <<
  486. " SendConfig:" << Config->SendConfig <<
  487. " LocalOnly: " << Config->LocalOnly <<
  488. " NeedsCleanup: " << Config->NeedsCleanup <<
  489. " Removable: " << Config->Removable << endl;
  490. }
  491. return true;
  492. }
  493. /*}}}*/
  494. // Worker::MediaChange - Request a media change /*{{{*/
  495. // ---------------------------------------------------------------------
  496. /* */
  497. bool pkgAcquire::Worker::MediaChange(string Message)
  498. {
  499. int status_fd = _config->FindI("APT::Status-Fd",-1);
  500. if(status_fd > 0)
  501. {
  502. string Media = LookupTag(Message,"Media");
  503. string Drive = LookupTag(Message,"Drive");
  504. ostringstream msg,status;
  505. ioprintf(msg,_("Please insert the disc labeled: "
  506. "'%s' "
  507. "in the drive '%s' and press [Enter]."),
  508. Media.c_str(),Drive.c_str());
  509. status << "media-change: " // message
  510. << Media << ":" // media
  511. << Drive << ":" // drive
  512. << msg.str() // l10n message
  513. << endl;
  514. std::string const dlstatus = status.str();
  515. FileFd::Write(status_fd, dlstatus.c_str(), dlstatus.size());
  516. }
  517. if (Log == 0 || Log->MediaChange(LookupTag(Message,"Media"),
  518. LookupTag(Message,"Drive")) == false)
  519. {
  520. char S[300];
  521. snprintf(S,sizeof(S),"603 Media Changed\nFailed: true\n\n");
  522. if (Debug == true)
  523. clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
  524. OutQueue += S;
  525. OutReady = true;
  526. return true;
  527. }
  528. char S[300];
  529. snprintf(S,sizeof(S),"603 Media Changed\n\n");
  530. if (Debug == true)
  531. clog << " -> " << Access << ':' << QuoteString(S,"\n") << endl;
  532. OutQueue += S;
  533. OutReady = true;
  534. return true;
  535. }
  536. /*}}}*/
  537. // Worker::SendConfiguration - Send the config to the method /*{{{*/
  538. // ---------------------------------------------------------------------
  539. /* */
  540. bool pkgAcquire::Worker::SendConfiguration()
  541. {
  542. if (Config->SendConfig == false)
  543. return true;
  544. if (OutFd == -1)
  545. return false;
  546. /* Write out all of the configuration directives by walking the
  547. configuration tree */
  548. std::ostringstream Message;
  549. Message << "601 Configuration\n";
  550. _config->Dump(Message, NULL, "Config-Item: %F=%V\n", false);
  551. Message << '\n';
  552. if (Debug == true)
  553. clog << " -> " << Access << ':' << QuoteString(Message.str(),"\n") << endl;
  554. OutQueue += Message.str();
  555. OutReady = true;
  556. return true;
  557. }
  558. /*}}}*/
  559. // Worker::QueueItem - Add an item to the outbound queue /*{{{*/
  560. // ---------------------------------------------------------------------
  561. /* Send a URI Acquire message to the method */
  562. bool pkgAcquire::Worker::QueueItem(pkgAcquire::Queue::QItem *Item)
  563. {
  564. if (OutFd == -1)
  565. return false;
  566. string Message = "600 URI Acquire\n";
  567. Message.reserve(300);
  568. Message += "URI: " + Item->URI;
  569. Message += "\nFilename: " + Item->Owner->DestFile;
  570. HashStringList const hsl = Item->GetExpectedHashes();
  571. for (HashStringList::const_iterator hs = hsl.begin(); hs != hsl.end(); ++hs)
  572. Message += "\nExpected-" + hs->HashType() + ": " + hs->HashValue();
  573. if (hsl.FileSize() == 0)
  574. {
  575. unsigned long long FileSize = Item->GetMaximumSize();
  576. if(FileSize > 0)
  577. {
  578. string MaximumSize;
  579. strprintf(MaximumSize, "%llu", FileSize);
  580. Message += "\nMaximum-Size: " + MaximumSize;
  581. }
  582. }
  583. Item->SyncDestinationFiles();
  584. Message += Item->Custom600Headers();
  585. Message += "\n\n";
  586. if (RealFileExists(Item->Owner->DestFile))
  587. {
  588. std::string const SandboxUser = _config->Find("APT::Sandbox::User");
  589. ChangeOwnerAndPermissionOfFile("Item::QueueURI", Item->Owner->DestFile.c_str(),
  590. SandboxUser.c_str(), "root", 0600);
  591. }
  592. if (Debug == true)
  593. clog << " -> " << Access << ':' << QuoteString(Message,"\n") << endl;
  594. OutQueue += Message;
  595. OutReady = true;
  596. return true;
  597. }
  598. /*}}}*/
  599. // Worker::OutFdRead - Out bound FD is ready /*{{{*/
  600. // ---------------------------------------------------------------------
  601. /* */
  602. bool pkgAcquire::Worker::OutFdReady()
  603. {
  604. int Res;
  605. do
  606. {
  607. Res = write(OutFd,OutQueue.c_str(),OutQueue.length());
  608. }
  609. while (Res < 0 && errno == EINTR);
  610. if (Res <= 0)
  611. return MethodFailure();
  612. OutQueue.erase(0,Res);
  613. if (OutQueue.empty() == true)
  614. OutReady = false;
  615. return true;
  616. }
  617. /*}}}*/
  618. // Worker::InFdRead - In bound FD is ready /*{{{*/
  619. // ---------------------------------------------------------------------
  620. /* */
  621. bool pkgAcquire::Worker::InFdReady()
  622. {
  623. if (ReadMessages() == false)
  624. return false;
  625. RunMessages();
  626. return true;
  627. }
  628. /*}}}*/
  629. // Worker::MethodFailure - Called when the method fails /*{{{*/
  630. // ---------------------------------------------------------------------
  631. /* This is called when the method is believed to have failed, probably because
  632. read returned -1. */
  633. bool pkgAcquire::Worker::MethodFailure()
  634. {
  635. _error->Error("Method %s has died unexpectedly!",Access.c_str());
  636. // do not reap the child here to show meaningfull error to the user
  637. ExecWait(Process,Access.c_str(),false);
  638. Process = -1;
  639. close(InFd);
  640. close(OutFd);
  641. InFd = -1;
  642. OutFd = -1;
  643. OutReady = false;
  644. InReady = false;
  645. OutQueue = string();
  646. MessageQueue.erase(MessageQueue.begin(),MessageQueue.end());
  647. return false;
  648. }
  649. /*}}}*/
  650. // Worker::Pulse - Called periodically /*{{{*/
  651. // ---------------------------------------------------------------------
  652. /* */
  653. void pkgAcquire::Worker::Pulse()
  654. {
  655. if (CurrentItem == 0)
  656. return;
  657. struct stat Buf;
  658. if (stat(CurrentItem->Owner->DestFile.c_str(),&Buf) != 0)
  659. return;
  660. CurrentSize = Buf.st_size;
  661. }
  662. /*}}}*/
  663. // Worker::ItemDone - Called when the current item is finished /*{{{*/
  664. // ---------------------------------------------------------------------
  665. /* */
  666. void pkgAcquire::Worker::ItemDone()
  667. {
  668. CurrentItem = 0;
  669. CurrentSize = 0;
  670. TotalSize = 0;
  671. Status = string();
  672. }
  673. /*}}}*/
  674. void pkgAcquire::Worker::PrepareFiles(char const * const caller, pkgAcquire::Queue::QItem const * const Itm)/*{{{*/
  675. {
  676. if (RealFileExists(Itm->Owner->DestFile))
  677. {
  678. ChangeOwnerAndPermissionOfFile(caller, Itm->Owner->DestFile.c_str(), "root", "root", 0644);
  679. std::string const filename = Itm->Owner->DestFile;
  680. for (pkgAcquire::Queue::QItem::owner_iterator O = Itm->Owners.begin(); O != Itm->Owners.end(); ++O)
  681. {
  682. pkgAcquire::Item const * const Owner = *O;
  683. if (Owner->DestFile == filename || filename == "/dev/null")
  684. continue;
  685. RemoveFile("PrepareFiles", Owner->DestFile);
  686. if (link(filename.c_str(), Owner->DestFile.c_str()) != 0)
  687. {
  688. // different mounts can't happen for us as we download to lists/ by default,
  689. // but if the system is reused by others the locations can potentially be on
  690. // different disks, so use symlink as poor-men replacement.
  691. // FIXME: Real copying as last fallback, but that is costly, so offload to a method preferable
  692. if (symlink(filename.c_str(), Owner->DestFile.c_str()) != 0)
  693. _error->Error("Can't create (sym)link of file %s to %s", filename.c_str(), Owner->DestFile.c_str());
  694. }
  695. }
  696. }
  697. else
  698. {
  699. for (pkgAcquire::Queue::QItem::owner_iterator O = Itm->Owners.begin(); O != Itm->Owners.end(); ++O)
  700. RemoveFile("PrepareFiles", (*O)->DestFile);
  701. }
  702. }
  703. /*}}}*/