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.
 
 
 
 
 
 

1084 lines
39 KiB

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