acquire-worker.cc 25 KB

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