acquire-worker.cc 25 KB

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