private-install.cc 35 KB

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