private-install.cc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. // Include Files /*{{{*/
  2. #include <config.h>
  3. #include <apt-pkg/acquire.h>
  4. #include <apt-pkg/acquire-item.h>
  5. #include <apt-pkg/algorithms.h>
  6. #include <apt-pkg/cachefile.h>
  7. #include <apt-pkg/cacheset.h>
  8. #include <apt-pkg/cmndline.h>
  9. #include <apt-pkg/depcache.h>
  10. #include <apt-pkg/error.h>
  11. #include <apt-pkg/fileutl.h>
  12. #include <apt-pkg/pkgrecords.h>
  13. #include <apt-pkg/pkgsystem.h>
  14. #include <apt-pkg/sptr.h>
  15. #include <apt-pkg/strutl.h>
  16. #include <apt-pkg/cacheiterators.h>
  17. #include <apt-pkg/configuration.h>
  18. #include <apt-pkg/macros.h>
  19. #include <apt-pkg/packagemanager.h>
  20. #include <apt-pkg/pkgcache.h>
  21. #include <apt-pkg/upgrade.h>
  22. #include <apt-pkg/install-progress.h>
  23. #include <apt-pkg/prettyprinters.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <algorithm>
  27. #include <iostream>
  28. #include <set>
  29. #include <vector>
  30. #include <map>
  31. #include <apt-private/acqprogress.h>
  32. #include <apt-private/private-install.h>
  33. #include <apt-private/private-cachefile.h>
  34. #include <apt-private/private-cacheset.h>
  35. #include <apt-private/private-download.h>
  36. #include <apt-private/private-output.h>
  37. #include <apti18n.h>
  38. /*}}}*/
  39. class pkgSourceList;
  40. bool CheckNothingBroken(CacheFile &Cache) /*{{{*/
  41. {
  42. // Now we check the state of the packages,
  43. if (Cache->BrokenCount() == 0)
  44. return true;
  45. c1out <<
  46. _("Some packages could not be installed. This may mean that you have\n"
  47. "requested an impossible situation or if you are using the unstable\n"
  48. "distribution that some required packages have not yet been created\n"
  49. "or been moved out of Incoming.") << std::endl;
  50. /*
  51. if (Packages == 1)
  52. {
  53. c1out << std::endl;
  54. c1out <<
  55. _("Since you only requested a single operation it is extremely likely that\n"
  56. "the package is simply not installable and a bug report against\n"
  57. "that package should be filed.") << std::endl;
  58. }
  59. */
  60. c1out << _("The following information may help to resolve the situation:") << std::endl;
  61. c1out << std::endl;
  62. ShowBroken(c1out,Cache,false);
  63. if (_error->PendingError() == true)
  64. return false;
  65. else
  66. return _error->Error(_("Broken packages"));
  67. }
  68. /*}}}*/
  69. // InstallPackages - Actually download and install the packages /*{{{*/
  70. // ---------------------------------------------------------------------
  71. /* This displays the informative messages describing what is going to
  72. happen and then calls the download routines */
  73. static void RemoveDownloadNeedingItemsFromFetcher(pkgAcquire &Fetcher, bool &Transient)
  74. {
  75. for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I < Fetcher.ItemsEnd();)
  76. {
  77. if ((*I)->Local == true)
  78. {
  79. ++I;
  80. continue;
  81. }
  82. // Close the item and check if it was found in cache
  83. (*I)->Finished();
  84. if ((*I)->Complete == false)
  85. Transient = true;
  86. // Clear it out of the fetch list
  87. delete *I;
  88. I = Fetcher.ItemsBegin();
  89. }
  90. }
  91. bool InstallPackages(CacheFile &Cache,bool ShwKept,bool Ask, bool Safety)
  92. {
  93. if (_config->FindB("APT::Get::Purge", false) == true)
  94. for (pkgCache::PkgIterator I = Cache->PkgBegin(); I.end() == false; ++I)
  95. if (Cache[I].Delete() == true && Cache[I].Purge() == false)
  96. Cache->MarkDelete(I,true);
  97. // Create the download object
  98. aptAcquireWithTextStatus Fetcher;
  99. if (_config->FindB("APT::Get::Print-URIs", false) == true)
  100. {
  101. // force a hashsum for compatibility reasons
  102. _config->CndSet("Acquire::ForceHash", "md5sum");
  103. }
  104. else if (Fetcher.GetLock(_config->FindDir("Dir::Cache::Archives")) == false)
  105. return false;
  106. // Read the source list
  107. if (Cache.BuildSourceList() == false)
  108. return false;
  109. pkgSourceList * const List = Cache.GetSourceList();
  110. // Create the text record parser
  111. pkgRecords Recs(Cache);
  112. if (_error->PendingError() == true)
  113. return false;
  114. // Create the package manager and prepare to download
  115. std::unique_ptr<pkgPackageManager> PM(_system->CreatePM(Cache));
  116. if (PM->GetArchives(&Fetcher,List,&Recs) == false ||
  117. _error->PendingError() == true)
  118. return false;
  119. if (_config->FindB("APT::Get::Fix-Missing",false) == true &&
  120. _config->FindB("APT::Get::Download",true) == false)
  121. {
  122. bool Missing = false;
  123. RemoveDownloadNeedingItemsFromFetcher(Fetcher, Missing);
  124. if (Missing)
  125. PM->FixMissing();
  126. Fetcher.Shutdown();
  127. if (PM->GetArchives(&Fetcher,List,&Recs) == false ||
  128. _error->PendingError() == true)
  129. return false;
  130. }
  131. // Show all the various warning indicators
  132. ShowDel(c1out,Cache);
  133. ShowNew(c1out,Cache);
  134. if (ShwKept == true)
  135. ShowKept(c1out,Cache);
  136. bool const Hold = !ShowHold(c1out,Cache);
  137. if (_config->FindB("APT::Get::Show-Upgraded",true) == true)
  138. ShowUpgraded(c1out,Cache);
  139. bool const Downgrade = !ShowDowngraded(c1out,Cache);
  140. bool Essential = false;
  141. if (_config->FindB("APT::Get::Download-Only",false) == false)
  142. Essential = !ShowEssential(c1out,Cache);
  143. Stats(c1out,Cache);
  144. // Sanity check
  145. if (Cache->BrokenCount() != 0)
  146. {
  147. ShowBroken(c1out,Cache,false);
  148. return _error->Error(_("Internal error, InstallPackages was called with broken packages!"));
  149. }
  150. if (Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
  151. Cache->BadCount() == 0)
  152. return true;
  153. // No remove flag
  154. if (Cache->DelCount() != 0 && _config->FindB("APT::Get::Remove",true) == false)
  155. return _error->Error(_("Packages need to be removed but remove is disabled."));
  156. // Fail safe check
  157. bool const Fail = (Essential || Downgrade || Hold);
  158. if (_config->FindI("quiet",0) >= 2 ||
  159. _config->FindB("APT::Get::Assume-Yes",false) == true)
  160. {
  161. if (_config->FindB("APT::Get::Force-Yes",false) == true) {
  162. _error->Warning(_("--force-yes is deprecated, use one of the options starting with --allow instead."));
  163. }
  164. if (Fail == true && _config->FindB("APT::Get::Force-Yes",false) == false) {
  165. if (Essential == true && _config->FindB("APT::Get::allow-remove-essential", false) == false)
  166. return _error->Error(_("Essential packages were removed and -y was used without --allow-remove-essential."));
  167. if (Downgrade == true && _config->FindB("APT::Get::allow-downgrades", false) == false)
  168. return _error->Error(_("Packages were downgraded and -y was used without --allow-downgrades."));
  169. if (Hold == true && _config->FindB("APT::Get::allow-change-held-packages", false) == false)
  170. return _error->Error(_("Held packages were changed and -y was used without --allow-change-held-packages."));
  171. }
  172. }
  173. // Run the simulator ..
  174. if (_config->FindB("APT::Get::Simulate") == true)
  175. {
  176. pkgSimulate PM(Cache);
  177. APT::Progress::PackageManager *progress = APT::Progress::PackageManagerProgressFactory();
  178. pkgPackageManager::OrderResult Res = PM.DoInstall(progress);
  179. delete progress;
  180. if (Res == pkgPackageManager::Failed)
  181. return false;
  182. if (Res != pkgPackageManager::Completed)
  183. return _error->Error(_("Internal error, Ordering didn't finish"));
  184. return true;
  185. }
  186. // Display statistics
  187. auto const FetchBytes = Fetcher.FetchNeeded();
  188. auto const FetchPBytes = Fetcher.PartialPresent();
  189. auto const DebBytes = Fetcher.TotalNeeded();
  190. if (DebBytes != Cache->DebSize())
  191. {
  192. c0out << DebBytes << ',' << Cache->DebSize() << std::endl;
  193. c0out << _("How odd... The sizes didn't match, email apt@packages.debian.org") << std::endl;
  194. }
  195. // Number of bytes
  196. if (DebBytes != FetchBytes)
  197. //TRANSLATOR: The required space between number and unit is already included
  198. // in the replacement strings, so %sB will be correctly translate in e.g. 1,5 MB
  199. ioprintf(c1out,_("Need to get %sB/%sB of archives.\n"),
  200. SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
  201. else if (DebBytes != 0)
  202. //TRANSLATOR: The required space between number and unit is already included
  203. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  204. ioprintf(c1out,_("Need to get %sB of archives.\n"),
  205. SizeToStr(DebBytes).c_str());
  206. // Size delta
  207. if (Cache->UsrSize() >= 0)
  208. //TRANSLATOR: The required space between number and unit is already included
  209. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  210. ioprintf(c1out,_("After this operation, %sB of additional disk space will be used.\n"),
  211. SizeToStr(Cache->UsrSize()).c_str());
  212. else
  213. //TRANSLATOR: The required space between number and unit is already included
  214. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  215. ioprintf(c1out,_("After this operation, %sB disk space will be freed.\n"),
  216. SizeToStr(-1*Cache->UsrSize()).c_str());
  217. if (CheckFreeSpaceBeforeDownload(_config->FindDir("Dir::Cache::Archives"), (FetchBytes - FetchPBytes)) == false)
  218. return false;
  219. if (_error->PendingError() == true)
  220. return false;
  221. // Just print out the uris an exit if the --print-uris flag was used
  222. if (_config->FindB("APT::Get::Print-URIs") == true)
  223. {
  224. pkgAcquire::UriIterator I = Fetcher.UriBegin();
  225. for (; I != Fetcher.UriEnd(); ++I)
  226. std::cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
  227. I->Owner->FileSize << ' ' << I->Owner->HashSum() << std::endl;
  228. return true;
  229. }
  230. if (Essential == true && Safety == true && _config->FindB("APT::Get::allow-remove-essential", false) == false)
  231. {
  232. if (_config->FindB("APT::Get::Trivial-Only",false) == true)
  233. return _error->Error(_("Trivial Only specified but this is not a trivial operation."));
  234. // TRANSLATOR: This string needs to be typed by the user as a confirmation, so be
  235. // careful with hard to type or special characters (like non-breaking spaces)
  236. const char *Prompt = _("Yes, do as I say!");
  237. std::string question;
  238. strprintf(question,
  239. _("You are about to do something potentially harmful.\n"
  240. "To continue type in the phrase '%s'\n"
  241. " ?] "),Prompt);
  242. if (AnalPrompt(question, Prompt) == false)
  243. {
  244. c2out << _("Abort.") << std::endl;
  245. exit(1);
  246. }
  247. }
  248. else
  249. {
  250. // Prompt to continue
  251. if (Ask == true || Fail == true)
  252. {
  253. if (_config->FindB("APT::Get::Trivial-Only",false) == true)
  254. return _error->Error(_("Trivial Only specified but this is not a trivial operation."));
  255. if (_config->FindI("quiet",0) < 2 &&
  256. _config->FindB("APT::Get::Assume-Yes",false) == false)
  257. {
  258. if (YnPrompt(_("Do you want to continue?")) == false)
  259. {
  260. c2out << _("Abort.") << std::endl;
  261. exit(1);
  262. }
  263. }
  264. }
  265. }
  266. if (!CheckAuth(Fetcher, true))
  267. return false;
  268. /* Unlock the dpkg lock if we are not going to be doing an install
  269. after. */
  270. if (_config->FindB("APT::Get::Download-Only",false) == true)
  271. _system->UnLock();
  272. // Run it
  273. bool Failed = false;
  274. while (1)
  275. {
  276. bool Transient = false;
  277. if (AcquireRun(Fetcher, 0, &Failed, &Transient) == false)
  278. return false;
  279. if (_config->FindB("APT::Get::Download-Only",false) == true)
  280. {
  281. if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
  282. return _error->Error(_("Some files failed to download"));
  283. c1out << _("Download complete and in download only mode") << std::endl;
  284. return true;
  285. }
  286. if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
  287. return _error->Error(_("Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?"));
  288. if (Transient == true && Failed == true)
  289. return _error->Error(_("--fix-missing and media swapping is not currently supported"));
  290. // Try to deal with missing package files
  291. if (Failed == true && PM->FixMissing() == false)
  292. {
  293. c2out << _("Unable to correct missing packages.") << std::endl;
  294. return _error->Error(_("Aborting install."));
  295. }
  296. auto const progress = APT::Progress::PackageManagerProgressFactory();
  297. _system->UnLock();
  298. pkgPackageManager::OrderResult const Res = PM->DoInstall(progress);
  299. delete progress;
  300. if (Res == pkgPackageManager::Failed || _error->PendingError() == true)
  301. return false;
  302. if (Res == pkgPackageManager::Completed)
  303. break;
  304. _system->Lock();
  305. // Reload the fetcher object and loop again for media swapping
  306. Fetcher.Shutdown();
  307. if (PM->GetArchives(&Fetcher,List,&Recs) == false)
  308. return false;
  309. Failed = false;
  310. if (_config->FindB("APT::Get::Download",true) == false)
  311. RemoveDownloadNeedingItemsFromFetcher(Fetcher, Failed);
  312. }
  313. std::set<std::string> const disappearedPkgs = PM->GetDisappearedPackages();
  314. if (disappearedPkgs.empty() == false)
  315. {
  316. ShowList(c1out, P_("The following package disappeared from your system as\n"
  317. "all files have been overwritten by other packages:",
  318. "The following packages disappeared from your system as\n"
  319. "all files have been overwritten by other packages:", disappearedPkgs.size()), disappearedPkgs,
  320. [](std::string const &Pkg) { return Pkg.empty() == false; },
  321. [](std::string const &Pkg) { return Pkg; },
  322. [](std::string const &) { return std::string(); });
  323. c0out << _("Note: This is done automatically and on purpose by dpkg.") << std::endl;
  324. }
  325. // cleanup downloaded debs
  326. if (_config->FindB("APT::Keep-Downloaded-Packages", true) == false)
  327. {
  328. std::string const archivedir = _config->FindDir("Dir::Cache::archives");
  329. for (auto I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); ++I)
  330. {
  331. if (flNotFile((*I)->DestFile) != archivedir || (*I)->Local)
  332. continue;
  333. RemoveFile("Keep-Downloaded-Packages=false", (*I)->DestFile);
  334. }
  335. }
  336. return true;
  337. }
  338. /*}}}*/
  339. // DoAutomaticRemove - Remove all automatic unused packages /*{{{*/
  340. // ---------------------------------------------------------------------
  341. /* Remove unused automatic packages */
  342. bool DoAutomaticRemove(CacheFile &Cache)
  343. {
  344. bool Debug = _config->FindI("Debug::pkgAutoRemove",false);
  345. bool doAutoRemove = _config->FindB("APT::Get::AutomaticRemove", false);
  346. bool hideAutoRemove = _config->FindB("APT::Get::HideAutoRemove");
  347. pkgDepCache::ActionGroup group(*Cache);
  348. if(Debug)
  349. std::cout << "DoAutomaticRemove()" << std::endl;
  350. if (doAutoRemove == true &&
  351. _config->FindB("APT::Get::Remove",true) == false)
  352. {
  353. c1out << _("We are not supposed to delete stuff, can't start "
  354. "AutoRemover") << std::endl;
  355. return false;
  356. }
  357. bool purgePkgs = _config->FindB("APT::Get::Purge", false);
  358. bool smallList = (hideAutoRemove == false &&
  359. strcasecmp(_config->Find("APT::Get::HideAutoRemove","").c_str(),"small") == 0);
  360. unsigned long autoRemoveCount = 0;
  361. APT::PackageSet tooMuch;
  362. SortedPackageUniverse Universe(Cache);
  363. // look over the cache to see what can be removed
  364. for (auto const &Pkg: Universe)
  365. {
  366. if (Cache[Pkg].Garbage)
  367. {
  368. if(Pkg.CurrentVer() != 0 || Cache[Pkg].Install())
  369. if(Debug)
  370. std::cout << "We could delete %s" << Pkg.FullName(true).c_str() << std::endl;
  371. if (doAutoRemove)
  372. {
  373. if(Pkg.CurrentVer() != 0 &&
  374. Pkg->CurrentState != pkgCache::State::ConfigFiles)
  375. Cache->MarkDelete(Pkg, purgePkgs, 0, false);
  376. else
  377. Cache->MarkKeep(Pkg, false, false);
  378. }
  379. else
  380. {
  381. // if the package is a new install and already garbage we don't need to
  382. // install it in the first place, so nuke it instead of show it
  383. if (Cache[Pkg].Install() == true && Pkg.CurrentVer() == 0)
  384. {
  385. tooMuch.insert(Pkg);
  386. Cache->MarkDelete(Pkg, false, 0, false);
  387. }
  388. // only show stuff in the list that is not yet marked for removal
  389. else if(hideAutoRemove == false && Cache[Pkg].Delete() == false)
  390. ++autoRemoveCount;
  391. }
  392. }
  393. }
  394. // we could have removed a new dependency of a garbage package,
  395. // so check if a reverse depends is broken and if so install it again.
  396. if (tooMuch.empty() == false && (Cache->BrokenCount() != 0 || Cache->PolicyBrokenCount() != 0))
  397. {
  398. bool Changed;
  399. do {
  400. Changed = false;
  401. for (APT::PackageSet::iterator Pkg = tooMuch.begin();
  402. Pkg != tooMuch.end(); ++Pkg)
  403. {
  404. APT::PackageSet too;
  405. too.insert(*Pkg);
  406. for (pkgCache::PrvIterator Prv = Cache[Pkg].CandidateVerIter(Cache).ProvidesList();
  407. Prv.end() == false; ++Prv)
  408. too.insert(Prv.ParentPkg());
  409. for (APT::PackageSet::const_iterator P = too.begin(); P != too.end(); ++P)
  410. {
  411. for (pkgCache::DepIterator R = P.RevDependsList();
  412. R.end() == false; ++R)
  413. {
  414. if (R.IsNegative() == true ||
  415. Cache->IsImportantDep(R) == false)
  416. continue;
  417. pkgCache::PkgIterator N = R.ParentPkg();
  418. if (N.end() == true || (N->CurrentVer == 0 && (*Cache)[N].Install() == false))
  419. continue;
  420. if (Debug == true)
  421. std::clog << "Save " << APT::PrettyPkg(Cache, Pkg) << " as another installed garbage package depends on it" << std::endl;
  422. Cache->MarkInstall(Pkg, false, 0, false);
  423. if (hideAutoRemove == false)
  424. ++autoRemoveCount;
  425. tooMuch.erase(Pkg);
  426. Changed = true;
  427. break;
  428. }
  429. if (Changed == true)
  430. break;
  431. }
  432. if (Changed == true)
  433. break;
  434. }
  435. } while (Changed == true);
  436. }
  437. // Now see if we had destroyed anything (if we had done anything)
  438. if (Cache->BrokenCount() != 0)
  439. {
  440. c1out << _("Hmm, seems like the AutoRemover destroyed something which really\n"
  441. "shouldn't happen. Please file a bug report against apt.") << std::endl;
  442. c1out << std::endl;
  443. c1out << _("The following information may help to resolve the situation:") << std::endl;
  444. c1out << std::endl;
  445. ShowBroken(c1out,Cache,false);
  446. return _error->Error(_("Internal Error, AutoRemover broke stuff"));
  447. }
  448. // if we don't remove them, we should show them!
  449. if (doAutoRemove == false && autoRemoveCount != 0)
  450. {
  451. if (smallList == false)
  452. {
  453. SortedPackageUniverse Universe(Cache);
  454. ShowList(c1out, P_("The following package was automatically installed and is no longer required:",
  455. "The following packages were automatically installed and are no longer required:",
  456. autoRemoveCount), Universe,
  457. [&Cache](pkgCache::PkgIterator const &Pkg) { return (*Cache)[Pkg].Garbage == true && (*Cache)[Pkg].Delete() == false; },
  458. &PrettyFullName, CandidateVersion(&Cache));
  459. }
  460. else
  461. ioprintf(c1out, P_("%lu package was automatically installed and is no longer required.\n",
  462. "%lu packages were automatically installed and are no longer required.\n", autoRemoveCount), autoRemoveCount);
  463. std::string autocmd = "apt autoremove";
  464. if (getenv("SUDO_USER") != NULL)
  465. autocmd = "sudo " + autocmd;
  466. ioprintf(c1out, P_("Use '%s' to remove it.", "Use '%s' to remove them.", autoRemoveCount), autocmd.c_str());
  467. c1out << std::endl;
  468. }
  469. return true;
  470. }
  471. /*}}}*/
  472. // DoCacheManipulationFromCommandLine /*{{{*/
  473. static const unsigned short MOD_REMOVE = 1;
  474. static const unsigned short MOD_INSTALL = 2;
  475. bool DoCacheManipulationFromCommandLine(CommandLine &CmdL, CacheFile &Cache, int UpgradeMode)
  476. {
  477. std::vector<const char*> VolatileCmdL;
  478. return DoCacheManipulationFromCommandLine(CmdL, VolatileCmdL, Cache, UpgradeMode);
  479. }
  480. bool DoCacheManipulationFromCommandLine(CommandLine &CmdL, std::vector<const char*> &VolatileCmdL, CacheFile &Cache, int UpgradeMode)
  481. {
  482. std::map<unsigned short, APT::VersionSet> verset;
  483. return DoCacheManipulationFromCommandLine(CmdL, VolatileCmdL, Cache, verset, UpgradeMode);
  484. }
  485. bool DoCacheManipulationFromCommandLine(CommandLine &CmdL, std::vector<const char*> &VolatileCmdL, CacheFile &Cache,
  486. std::map<unsigned short, APT::VersionSet> &verset, int UpgradeMode)
  487. {
  488. // Enter the special broken fixing mode if the user specified arguments
  489. bool BrokenFix = false;
  490. if (Cache->BrokenCount() != 0)
  491. BrokenFix = true;
  492. std::unique_ptr<pkgProblemResolver> Fix(nullptr);
  493. if (_config->FindB("APT::Get::CallResolver", true) == true)
  494. Fix.reset(new pkgProblemResolver(Cache));
  495. unsigned short fallback = MOD_INSTALL;
  496. if (strcasecmp(CmdL.FileList[0],"remove") == 0)
  497. fallback = MOD_REMOVE;
  498. else if (strcasecmp(CmdL.FileList[0], "purge") == 0)
  499. {
  500. _config->Set("APT::Get::Purge", true);
  501. fallback = MOD_REMOVE;
  502. }
  503. else if (strcasecmp(CmdL.FileList[0], "autoremove") == 0 ||
  504. strcasecmp(CmdL.FileList[0], "auto-remove") == 0)
  505. {
  506. _config->Set("APT::Get::AutomaticRemove", "true");
  507. fallback = MOD_REMOVE;
  508. }
  509. std::list<APT::VersionSet::Modifier> mods;
  510. mods.push_back(APT::VersionSet::Modifier(MOD_INSTALL, "+",
  511. APT::VersionSet::Modifier::POSTFIX, APT::CacheSetHelper::CANDIDATE));
  512. mods.push_back(APT::VersionSet::Modifier(MOD_REMOVE, "-",
  513. APT::VersionSet::Modifier::POSTFIX, APT::CacheSetHelper::NEWEST));
  514. CacheSetHelperAPTGet helper(c0out);
  515. verset = APT::VersionSet::GroupedFromCommandLine(Cache,
  516. CmdL.FileList + 1, mods, fallback, helper);
  517. for (auto const &I: VolatileCmdL)
  518. {
  519. pkgCache::PkgIterator const P = Cache->FindPkg(I);
  520. if (P.end())
  521. continue;
  522. // Set any version providing the .deb as the candidate.
  523. for (auto Prv = P.ProvidesList(); Prv.end() == false; Prv++)
  524. Cache.GetDepCache()->SetCandidateVersion(Prv.OwnerVer());
  525. // via cacheset to have our usual virtual handling
  526. APT::VersionContainerInterface::FromPackage(&(verset[MOD_INSTALL]), Cache, P, APT::CacheSetHelper::CANDIDATE, helper);
  527. }
  528. if (_error->PendingError() == true)
  529. {
  530. helper.showVirtualPackageErrors(Cache);
  531. return false;
  532. }
  533. TryToInstall InstallAction(Cache, Fix.get(), BrokenFix);
  534. TryToRemove RemoveAction(Cache, Fix.get());
  535. // new scope for the ActionGroup
  536. {
  537. pkgDepCache::ActionGroup group(Cache);
  538. unsigned short const order[] = { MOD_REMOVE, MOD_INSTALL, 0 };
  539. for (unsigned short i = 0; order[i] != 0; ++i)
  540. {
  541. if (order[i] == MOD_INSTALL)
  542. InstallAction = std::for_each(verset[MOD_INSTALL].begin(), verset[MOD_INSTALL].end(), InstallAction);
  543. else if (order[i] == MOD_REMOVE)
  544. RemoveAction = std::for_each(verset[MOD_REMOVE].begin(), verset[MOD_REMOVE].end(), RemoveAction);
  545. }
  546. if (Fix != NULL && _config->FindB("APT::Get::AutoSolving", true) == true)
  547. {
  548. InstallAction.propergateReleaseCandiateSwitching(helper.selectedByRelease, c0out);
  549. InstallAction.doAutoInstall();
  550. }
  551. if (_error->PendingError() == true)
  552. {
  553. return false;
  554. }
  555. /* If we are in the Broken fixing mode we do not attempt to fix the
  556. problems. This is if the user invoked install without -f and gave
  557. packages */
  558. if (BrokenFix == true && Cache->BrokenCount() != 0)
  559. {
  560. c1out << _("You might want to run 'apt-get -f install' to correct these:") << std::endl;
  561. ShowBroken(c1out,Cache,false);
  562. return _error->Error(_("Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution)."));
  563. }
  564. if (Fix != NULL)
  565. {
  566. // Call the scored problem resolver
  567. OpTextProgress Progress(*_config);
  568. bool const distUpgradeMode = strcmp(CmdL.FileList[0], "dist-upgrade") == 0 || strcmp(CmdL.FileList[0], "full-upgrade") == 0;
  569. bool resolver_fail = false;
  570. if (distUpgradeMode == true || UpgradeMode != APT::Upgrade::ALLOW_EVERYTHING)
  571. resolver_fail = APT::Upgrade::Upgrade(Cache, UpgradeMode, &Progress);
  572. else
  573. resolver_fail = Fix->Resolve(true, &Progress);
  574. if (resolver_fail == false && Cache->BrokenCount() == 0)
  575. return false;
  576. }
  577. if (CheckNothingBroken(Cache) == false)
  578. return false;
  579. }
  580. if (!DoAutomaticRemove(Cache))
  581. return false;
  582. // if nothing changed in the cache, but only the automark information
  583. // we write the StateFile here, otherwise it will be written in
  584. // cache.commit()
  585. if (InstallAction.AutoMarkChanged > 0 &&
  586. Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
  587. Cache->BadCount() == 0 &&
  588. _config->FindB("APT::Get::Simulate",false) == false)
  589. Cache->writeStateFile(NULL);
  590. return true;
  591. }
  592. /*}}}*/
  593. // DoInstall - Install packages from the command line /*{{{*/
  594. // ---------------------------------------------------------------------
  595. /* Install named packages */
  596. struct PkgIsExtraInstalled {
  597. pkgCacheFile * const Cache;
  598. APT::VersionSet const * const verset;
  599. PkgIsExtraInstalled(pkgCacheFile * const Cache, APT::VersionSet const * const Container) : Cache(Cache), verset(Container) {}
  600. bool operator() (pkgCache::PkgIterator const &Pkg)
  601. {
  602. if ((*Cache)[Pkg].Install() == false)
  603. return false;
  604. pkgCache::VerIterator const Cand = (*Cache)[Pkg].CandidateVerIter(*Cache);
  605. return verset->find(Cand) == verset->end();
  606. }
  607. };
  608. bool DoInstall(CommandLine &CmdL)
  609. {
  610. CacheFile Cache;
  611. std::vector<char const *> VolatileCmdL;
  612. Cache.GetSourceList()->AddVolatileFiles(CmdL, &VolatileCmdL);
  613. // then open the cache
  614. if (Cache.OpenForInstall() == false ||
  615. Cache.CheckDeps(CmdL.FileSize() != 1) == false)
  616. return false;
  617. std::map<unsigned short, APT::VersionSet> verset;
  618. if(!DoCacheManipulationFromCommandLine(CmdL, VolatileCmdL, Cache, verset, 0))
  619. return false;
  620. /* Print out a list of packages that are going to be installed extra
  621. to what the user asked */
  622. SortedPackageUniverse Universe(Cache);
  623. if (Cache->InstCount() != verset[MOD_INSTALL].size())
  624. ShowList(c1out, _("The following additional packages will be installed:"), Universe,
  625. PkgIsExtraInstalled(&Cache, &verset[MOD_INSTALL]),
  626. &PrettyFullName, CandidateVersion(&Cache));
  627. /* Print out a list of suggested and recommended packages */
  628. {
  629. std::list<std::string> Recommends, Suggests, SingleRecommends, SingleSuggests;
  630. for (auto const &Pkg: Universe)
  631. {
  632. /* Just look at the ones we want to install */
  633. if ((*Cache)[Pkg].Install() == false)
  634. continue;
  635. // get the recommends/suggests for the candidate ver
  636. pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
  637. for (pkgCache::DepIterator D = CV.DependsList(); D.end() == false; )
  638. {
  639. pkgCache::DepIterator Start;
  640. pkgCache::DepIterator End;
  641. D.GlobOr(Start,End); // advances D
  642. if (Start->Type != pkgCache::Dep::Recommends && Start->Type != pkgCache::Dep::Suggests)
  643. continue;
  644. {
  645. // Skip if we already saw this
  646. std::string target;
  647. for (pkgCache::DepIterator I = Start; I != D; ++I)
  648. {
  649. if (target.empty() == false)
  650. target.append(" | ");
  651. target.append(I.TargetPkg().FullName(true));
  652. }
  653. std::list<std::string> &Type = Start->Type == pkgCache::Dep::Recommends ? SingleRecommends : SingleSuggests;
  654. if (std::find(Type.begin(), Type.end(), target) != Type.end())
  655. continue;
  656. Type.push_back(target);
  657. }
  658. std::list<std::string> OrList;
  659. bool foundInstalledInOrGroup = false;
  660. for (pkgCache::DepIterator I = Start; I != D; ++I)
  661. {
  662. {
  663. // satisfying package is installed and not marked for deletion
  664. APT::VersionList installed = APT::VersionList::FromDependency(Cache, I, APT::CacheSetHelper::INSTALLED);
  665. if (std::find_if(installed.begin(), installed.end(),
  666. [&Cache](pkgCache::VerIterator const &Ver) { return Cache[Ver.ParentPkg()].Delete() == false; }) != installed.end())
  667. {
  668. foundInstalledInOrGroup = true;
  669. break;
  670. }
  671. }
  672. {
  673. // satisfying package is upgraded to/new install
  674. APT::VersionList upgrades = APT::VersionList::FromDependency(Cache, I, APT::CacheSetHelper::CANDIDATE);
  675. if (std::find_if(upgrades.begin(), upgrades.end(),
  676. [&Cache](pkgCache::VerIterator const &Ver) { return Cache[Ver.ParentPkg()].Upgrade(); }) != upgrades.end())
  677. {
  678. foundInstalledInOrGroup = true;
  679. break;
  680. }
  681. }
  682. if (OrList.empty())
  683. OrList.push_back(I.TargetPkg().FullName(true));
  684. else
  685. OrList.push_back("| " + I.TargetPkg().FullName(true));
  686. }
  687. if(foundInstalledInOrGroup == false)
  688. {
  689. std::list<std::string> &Type = Start->Type == pkgCache::Dep::Recommends ? Recommends : Suggests;
  690. std::move(OrList.begin(), OrList.end(), std::back_inserter(Type));
  691. }
  692. }
  693. }
  694. auto always_true = [](std::string const&) { return true; };
  695. auto string_ident = [](std::string const&str) { return str; };
  696. auto verbose_show_candidate =
  697. [&Cache](std::string str)
  698. {
  699. if (APT::String::Startswith(str, "| "))
  700. str.erase(0, 2);
  701. pkgCache::PkgIterator const Pkg = Cache->FindPkg(str);
  702. if (Pkg.end() == true)
  703. return "";
  704. return (*Cache)[Pkg].CandVersion;
  705. };
  706. ShowList(c1out,_("Suggested packages:"), Suggests,
  707. always_true, string_ident, verbose_show_candidate);
  708. ShowList(c1out,_("Recommended packages:"), Recommends,
  709. always_true, string_ident, verbose_show_candidate);
  710. }
  711. // See if we need to prompt
  712. // FIXME: check if really the packages in the set are going to be installed
  713. if (Cache->InstCount() == verset[MOD_INSTALL].size() && Cache->DelCount() == 0)
  714. return InstallPackages(Cache,false,false);
  715. return InstallPackages(Cache,false);
  716. }
  717. /*}}}*/
  718. // TryToInstall - Mark a package for installation /*{{{*/
  719. void TryToInstall::operator() (pkgCache::VerIterator const &Ver) {
  720. if (unlikely(Ver.end()))
  721. {
  722. _error->Fatal("The given version to TryToInstall is invalid!");
  723. return;
  724. }
  725. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  726. if (unlikely(Pkg.end()))
  727. {
  728. _error->Fatal("The given version to TryToInstall has an invalid parent package!");
  729. return;
  730. }
  731. Cache->GetDepCache()->SetCandidateVersion(Ver);
  732. pkgDepCache::StateCache &State = (*Cache)[Pkg];
  733. // Handle the no-upgrade case
  734. if (_config->FindB("APT::Get::upgrade",true) == false && Pkg->CurrentVer != 0)
  735. ioprintf(c1out,_("Skipping %s, it is already installed and upgrade is not set.\n"),
  736. Pkg.FullName(true).c_str());
  737. // Ignore request for install if package would be new
  738. else if (_config->FindB("APT::Get::Only-Upgrade", false) == true && Pkg->CurrentVer == 0)
  739. ioprintf(c1out,_("Skipping %s, it is not installed and only upgrades are requested.\n"),
  740. Pkg.FullName(true).c_str());
  741. else {
  742. if (Fix != NULL) {
  743. Fix->Clear(Pkg);
  744. Fix->Protect(Pkg);
  745. }
  746. Cache->GetDepCache()->MarkInstall(Pkg,false);
  747. if (State.Install() == false) {
  748. if (_config->FindB("APT::Get::ReInstall",false) == true) {
  749. if (Pkg->CurrentVer == 0 || Pkg.CurrentVer().Downloadable() == false)
  750. ioprintf(c1out,_("Reinstallation of %s is not possible, it cannot be downloaded.\n"),
  751. Pkg.FullName(true).c_str());
  752. else
  753. Cache->GetDepCache()->SetReInstall(Pkg, true);
  754. } else
  755. // TRANSLATORS: First string is package name, second is version
  756. ioprintf(c1out,_("%s is already the newest version (%s).\n"),
  757. Pkg.FullName(true).c_str(), Pkg.CurrentVer().VerStr());
  758. }
  759. // Install it with autoinstalling enabled (if we not respect the minial
  760. // required deps or the policy)
  761. if (FixBroken == false)
  762. doAutoInstallLater.insert(Pkg);
  763. }
  764. // see if we need to fix the auto-mark flag
  765. // e.g. apt-get install foo
  766. // where foo is marked automatic
  767. if (State.Install() == false &&
  768. (State.Flags & pkgCache::Flag::Auto) &&
  769. _config->FindB("APT::Get::ReInstall",false) == false &&
  770. _config->FindB("APT::Get::Only-Upgrade",false) == false &&
  771. _config->FindB("APT::Get::Download-Only",false) == false)
  772. {
  773. ioprintf(c1out,_("%s set to manually installed.\n"),
  774. Pkg.FullName(true).c_str());
  775. Cache->GetDepCache()->MarkAuto(Pkg,false);
  776. AutoMarkChanged++;
  777. }
  778. }
  779. /*}}}*/
  780. bool TryToInstall::propergateReleaseCandiateSwitching(std::list<std::pair<pkgCache::VerIterator, std::string> > const &start, std::ostream &out)/*{{{*/
  781. {
  782. for (std::list<std::pair<pkgCache::VerIterator, std::string> >::const_iterator s = start.begin();
  783. s != start.end(); ++s)
  784. Cache->GetDepCache()->SetCandidateVersion(s->first);
  785. bool Success = true;
  786. // the Changed list contains:
  787. // first: "new version"
  788. // second: "what-caused the change"
  789. std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> > Changed;
  790. for (std::list<std::pair<pkgCache::VerIterator, std::string> >::const_iterator s = start.begin();
  791. s != start.end(); ++s)
  792. {
  793. Changed.push_back(std::make_pair(s->first, pkgCache::VerIterator(*Cache)));
  794. // We continue here even if it failed to enhance the ShowBroken output
  795. Success &= Cache->GetDepCache()->SetCandidateRelease(s->first, s->second, Changed);
  796. }
  797. for (std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> >::const_iterator c = Changed.begin();
  798. c != Changed.end(); ++c)
  799. {
  800. if (c->second.end() == true)
  801. ioprintf(out, _("Selected version '%s' (%s) for '%s'\n"),
  802. c->first.VerStr(), c->first.RelStr().c_str(), c->first.ParentPkg().FullName(true).c_str());
  803. else if (c->first.ParentPkg()->Group != c->second.ParentPkg()->Group)
  804. {
  805. pkgCache::VerIterator V = (*Cache)[c->first.ParentPkg()].CandidateVerIter(*Cache);
  806. ioprintf(out, _("Selected version '%s' (%s) for '%s' because of '%s'\n"), V.VerStr(),
  807. V.RelStr().c_str(), V.ParentPkg().FullName(true).c_str(), c->second.ParentPkg().FullName(true).c_str());
  808. }
  809. }
  810. return Success;
  811. }
  812. /*}}}*/
  813. void TryToInstall::doAutoInstall() { /*{{{*/
  814. for (APT::PackageSet::const_iterator P = doAutoInstallLater.begin();
  815. P != doAutoInstallLater.end(); ++P) {
  816. pkgDepCache::StateCache &State = (*Cache)[P];
  817. if (State.InstBroken() == false && State.InstPolicyBroken() == false)
  818. continue;
  819. Cache->GetDepCache()->MarkInstall(P, true);
  820. }
  821. doAutoInstallLater.clear();
  822. }
  823. /*}}}*/
  824. // TryToRemove - Mark a package for removal /*{{{*/
  825. void TryToRemove::operator() (pkgCache::VerIterator const &Ver)
  826. {
  827. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  828. if (Fix != NULL)
  829. {
  830. Fix->Clear(Pkg);
  831. Fix->Protect(Pkg);
  832. Fix->Remove(Pkg);
  833. }
  834. if ((Pkg->CurrentVer == 0 && PurgePkgs == false) ||
  835. (PurgePkgs == true && Pkg->CurrentState == pkgCache::State::NotInstalled))
  836. {
  837. pkgCache::GrpIterator Grp = Pkg.Group();
  838. pkgCache::PkgIterator P = Grp.PackageList();
  839. for (; P.end() != true; P = Grp.NextPkg(P))
  840. {
  841. if (P == Pkg)
  842. continue;
  843. if (P->CurrentVer != 0 || (PurgePkgs == true && P->CurrentState != pkgCache::State::NotInstalled))
  844. {
  845. // TRANSLATORS: Note, this is not an interactive question
  846. ioprintf(c1out,_("Package '%s' is not installed, so not removed. Did you mean '%s'?\n"),
  847. Pkg.FullName(true).c_str(), P.FullName(true).c_str());
  848. break;
  849. }
  850. }
  851. if (P.end() == true)
  852. ioprintf(c1out,_("Package '%s' is not installed, so not removed\n"),Pkg.FullName(true).c_str());
  853. // MarkInstall refuses to install packages on hold
  854. Pkg->SelectedState = pkgCache::State::Hold;
  855. }
  856. else
  857. Cache->GetDepCache()->MarkDelete(Pkg, PurgePkgs);
  858. }
  859. /*}}}*/