You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

991 lines
36 KiB

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