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