]> git.saurik.com Git - apt.git/blame_incremental - cmdline/apt-get.cc
cleanup the debian/rules file a bit
[apt.git] / cmdline / apt-get.cc
... / ...
CommitLineData
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
3// $Id: apt-get.cc,v 1.156 2004/08/28 01:05:16 mdz Exp $
4/* ######################################################################
5
6 apt-get - Cover for dpkg
7
8 This is an allout cover for dpkg implementing a safer front end. It is
9 based largely on libapt-pkg.
10
11 The syntax is different,
12 apt-get [opt] command [things]
13 Where command is:
14 update - Resyncronize the package files from their sources
15 upgrade - Smart-Download the newest versions of all packages
16 dselect-upgrade - Follows dselect's changes to the Status: field
17 and installes new and removes old packages
18 dist-upgrade - Powerfull upgrader designed to handle the issues with
19 a new distribution.
20 install - Download and install a given package (by name, not by .deb)
21 check - Update the package cache and check for broken packages
22 clean - Erase the .debs downloaded to /var/cache/apt/archives and
23 the partial dir too
24
25 ##################################################################### */
26 /*}}}*/
27// Include Files /*{{{*/
28#define _LARGEFILE_SOURCE
29#define _LARGEFILE64_SOURCE
30
31#include <apt-pkg/aptconfiguration.h>
32#include <apt-pkg/error.h>
33#include <apt-pkg/cmndline.h>
34#include <apt-pkg/init.h>
35#include <apt-pkg/depcache.h>
36#include <apt-pkg/sourcelist.h>
37#include <apt-pkg/algorithms.h>
38#include <apt-pkg/acquire-item.h>
39#include <apt-pkg/strutl.h>
40#include <apt-pkg/clean.h>
41#include <apt-pkg/srcrecords.h>
42#include <apt-pkg/version.h>
43#include <apt-pkg/cachefile.h>
44#include <apt-pkg/cacheset.h>
45#include <apt-pkg/sptr.h>
46#include <apt-pkg/md5.h>
47#include <apt-pkg/versionmatch.h>
48
49#include <config.h>
50#include <apti18n.h>
51
52#include "acqprogress.h"
53
54#include <set>
55#include <locale.h>
56#include <langinfo.h>
57#include <fstream>
58#include <termios.h>
59#include <sys/ioctl.h>
60#include <sys/stat.h>
61#include <sys/statfs.h>
62#include <sys/statvfs.h>
63#include <signal.h>
64#include <unistd.h>
65#include <stdio.h>
66#include <errno.h>
67#include <regex.h>
68#include <sys/wait.h>
69#include <sstream>
70
71#define statfs statfs64
72#define statvfs statvfs64
73 /*}}}*/
74
75#define RAMFS_MAGIC 0x858458f6
76
77using namespace std;
78
79ostream c0out(0);
80ostream c1out(0);
81ostream c2out(0);
82ofstream devnull("/dev/null");
83unsigned int ScreenWidth = 80 - 1; /* - 1 for the cursor */
84
85// class CacheFile - Cover class for some dependency cache functions /*{{{*/
86// ---------------------------------------------------------------------
87/* */
88class CacheFile : public pkgCacheFile
89{
90 static pkgCache *SortCache;
91 static int NameComp(const void *a,const void *b);
92
93 public:
94 pkgCache::Package **List;
95
96 void Sort();
97 bool CheckDeps(bool AllowBroken = false);
98 bool BuildCaches(bool WithLock = true)
99 {
100 OpTextProgress Prog(*_config);
101 if (pkgCacheFile::BuildCaches(&Prog,WithLock) == false)
102 return false;
103 return true;
104 }
105 bool Open(bool WithLock = true)
106 {
107 OpTextProgress Prog(*_config);
108 if (pkgCacheFile::Open(&Prog,WithLock) == false)
109 return false;
110 Sort();
111
112 return true;
113 };
114 bool OpenForInstall()
115 {
116 if (_config->FindB("APT::Get::Print-URIs") == true)
117 return Open(false);
118 else
119 return Open(true);
120 }
121 CacheFile() : List(0) {};
122 ~CacheFile() {
123 delete[] List;
124 }
125};
126 /*}}}*/
127
128// YnPrompt - Yes No Prompt. /*{{{*/
129// ---------------------------------------------------------------------
130/* Returns true on a Yes.*/
131bool YnPrompt(bool Default=true)
132{
133 if (_config->FindB("APT::Get::Assume-Yes",false) == true)
134 {
135 c1out << _("Y") << endl;
136 return true;
137 }
138
139 char response[1024] = "";
140 cin.getline(response, sizeof(response));
141
142 if (!cin)
143 return false;
144
145 if (strlen(response) == 0)
146 return Default;
147
148 regex_t Pattern;
149 int Res;
150
151 Res = regcomp(&Pattern, nl_langinfo(YESEXPR),
152 REG_EXTENDED|REG_ICASE|REG_NOSUB);
153
154 if (Res != 0) {
155 char Error[300];
156 regerror(Res,&Pattern,Error,sizeof(Error));
157 return _error->Error(_("Regex compilation error - %s"),Error);
158 }
159
160 Res = regexec(&Pattern, response, 0, NULL, 0);
161 if (Res == 0)
162 return true;
163 return false;
164}
165 /*}}}*/
166// AnalPrompt - Annoying Yes No Prompt. /*{{{*/
167// ---------------------------------------------------------------------
168/* Returns true on a Yes.*/
169bool AnalPrompt(const char *Text)
170{
171 char Buf[1024];
172 cin.getline(Buf,sizeof(Buf));
173 if (strcmp(Buf,Text) == 0)
174 return true;
175 return false;
176}
177 /*}}}*/
178// ShowList - Show a list /*{{{*/
179// ---------------------------------------------------------------------
180/* This prints out a string of space separated words with a title and
181 a two space indent line wraped to the current screen width. */
182bool ShowList(ostream &out,string Title,string List,string VersionsList)
183{
184 if (List.empty() == true)
185 return true;
186 // trim trailing space
187 int NonSpace = List.find_last_not_of(' ');
188 if (NonSpace != -1)
189 {
190 List = List.erase(NonSpace + 1);
191 if (List.empty() == true)
192 return true;
193 }
194
195 // Acount for the leading space
196 int ScreenWidth = ::ScreenWidth - 3;
197
198 out << Title << endl;
199 string::size_type Start = 0;
200 string::size_type VersionsStart = 0;
201 while (Start < List.size())
202 {
203 if(_config->FindB("APT::Get::Show-Versions",false) == true &&
204 VersionsList.size() > 0) {
205 string::size_type End;
206 string::size_type VersionsEnd;
207
208 End = List.find(' ',Start);
209 VersionsEnd = VersionsList.find('\n', VersionsStart);
210
211 out << " " << string(List,Start,End - Start) << " (" <<
212 string(VersionsList,VersionsStart,VersionsEnd - VersionsStart) <<
213 ")" << endl;
214
215 if (End == string::npos || End < Start)
216 End = Start + ScreenWidth;
217
218 Start = End + 1;
219 VersionsStart = VersionsEnd + 1;
220 } else {
221 string::size_type End;
222
223 if (Start + ScreenWidth >= List.size())
224 End = List.size();
225 else
226 End = List.rfind(' ',Start+ScreenWidth);
227
228 if (End == string::npos || End < Start)
229 End = Start + ScreenWidth;
230 out << " " << string(List,Start,End - Start) << endl;
231 Start = End + 1;
232 }
233 }
234
235 return false;
236}
237 /*}}}*/
238// ShowBroken - Debugging aide /*{{{*/
239// ---------------------------------------------------------------------
240/* This prints out the names of all the packages that are broken along
241 with the name of each each broken dependency and a quite version
242 description.
243
244 The output looks like:
245 The following packages have unmet dependencies:
246 exim: Depends: libc6 (>= 2.1.94) but 2.1.3-10 is to be installed
247 Depends: libldap2 (>= 2.0.2-2) but it is not going to be installed
248 Depends: libsasl7 but it is not going to be installed
249 */
250void ShowBroken(ostream &out,CacheFile &Cache,bool Now)
251{
252 out << _("The following packages have unmet dependencies:") << endl;
253 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
254 {
255 pkgCache::PkgIterator I(Cache,Cache.List[J]);
256
257 if (Now == true)
258 {
259 if (Cache[I].NowBroken() == false)
260 continue;
261 }
262 else
263 {
264 if (Cache[I].InstBroken() == false)
265 continue;
266 }
267
268 // Print out each package and the failed dependencies
269 out << " " << I.FullName(true) << " :";
270 unsigned const Indent = I.FullName(true).size() + 3;
271 bool First = true;
272 pkgCache::VerIterator Ver;
273
274 if (Now == true)
275 Ver = I.CurrentVer();
276 else
277 Ver = Cache[I].InstVerIter(Cache);
278
279 if (Ver.end() == true)
280 {
281 out << endl;
282 continue;
283 }
284
285 for (pkgCache::DepIterator D = Ver.DependsList(); D.end() == false;)
286 {
287 // Compute a single dependency element (glob or)
288 pkgCache::DepIterator Start;
289 pkgCache::DepIterator End;
290 D.GlobOr(Start,End); // advances D
291
292 if (Cache->IsImportantDep(End) == false)
293 continue;
294
295 if (Now == true)
296 {
297 if ((Cache[End] & pkgDepCache::DepGNow) == pkgDepCache::DepGNow)
298 continue;
299 }
300 else
301 {
302 if ((Cache[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall)
303 continue;
304 }
305
306 bool FirstOr = true;
307 while (1)
308 {
309 if (First == false)
310 for (unsigned J = 0; J != Indent; J++)
311 out << ' ';
312 First = false;
313
314 if (FirstOr == false)
315 {
316 for (unsigned J = 0; J != strlen(End.DepType()) + 3; J++)
317 out << ' ';
318 }
319 else
320 out << ' ' << End.DepType() << ": ";
321 FirstOr = false;
322
323 out << Start.TargetPkg().FullName(true);
324
325 // Show a quick summary of the version requirements
326 if (Start.TargetVer() != 0)
327 out << " (" << Start.CompType() << " " << Start.TargetVer() << ")";
328
329 /* Show a summary of the target package if possible. In the case
330 of virtual packages we show nothing */
331 pkgCache::PkgIterator Targ = Start.TargetPkg();
332 if (Targ->ProvidesList == 0)
333 {
334 out << ' ';
335 pkgCache::VerIterator Ver = Cache[Targ].InstVerIter(Cache);
336 if (Now == true)
337 Ver = Targ.CurrentVer();
338
339 if (Ver.end() == false)
340 {
341 if (Now == true)
342 ioprintf(out,_("but %s is installed"),Ver.VerStr());
343 else
344 ioprintf(out,_("but %s is to be installed"),Ver.VerStr());
345 }
346 else
347 {
348 if (Cache[Targ].CandidateVerIter(Cache).end() == true)
349 {
350 if (Targ->ProvidesList == 0)
351 out << _("but it is not installable");
352 else
353 out << _("but it is a virtual package");
354 }
355 else
356 out << (Now?_("but it is not installed"):_("but it is not going to be installed"));
357 }
358 }
359
360 if (Start != End)
361 out << _(" or");
362 out << endl;
363
364 if (Start == End)
365 break;
366 Start++;
367 }
368 }
369 }
370}
371 /*}}}*/
372// ShowNew - Show packages to newly install /*{{{*/
373// ---------------------------------------------------------------------
374/* */
375void ShowNew(ostream &out,CacheFile &Cache)
376{
377 /* Print out a list of packages that are going to be installed extra
378 to what the user asked */
379 string List;
380 string VersionsList;
381 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
382 {
383 pkgCache::PkgIterator I(Cache,Cache.List[J]);
384 if (Cache[I].NewInstall() == true) {
385 if (Cache[I].CandidateVerIter(Cache).Pseudo() == true)
386 continue;
387 List += I.FullName(true) + " ";
388 VersionsList += string(Cache[I].CandVersion) + "\n";
389 }
390 }
391
392 ShowList(out,_("The following NEW packages will be installed:"),List,VersionsList);
393}
394 /*}}}*/
395// ShowDel - Show packages to delete /*{{{*/
396// ---------------------------------------------------------------------
397/* */
398void ShowDel(ostream &out,CacheFile &Cache)
399{
400 /* Print out a list of packages that are going to be removed extra
401 to what the user asked */
402 string List;
403 string VersionsList;
404 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
405 {
406 pkgCache::PkgIterator I(Cache,Cache.List[J]);
407 if (Cache[I].Delete() == true)
408 {
409 if (Cache[I].CandidateVerIter(Cache).Pseudo() == true)
410 continue;
411 if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
412 List += I.FullName(true) + "* ";
413 else
414 List += I.FullName(true) + " ";
415
416 VersionsList += string(Cache[I].CandVersion)+ "\n";
417 }
418 }
419
420 ShowList(out,_("The following packages will be REMOVED:"),List,VersionsList);
421}
422 /*}}}*/
423// ShowKept - Show kept packages /*{{{*/
424// ---------------------------------------------------------------------
425/* */
426void ShowKept(ostream &out,CacheFile &Cache)
427{
428 string List;
429 string VersionsList;
430 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
431 {
432 pkgCache::PkgIterator I(Cache,Cache.List[J]);
433
434 // Not interesting
435 if (Cache[I].Upgrade() == true || Cache[I].Upgradable() == false ||
436 I->CurrentVer == 0 || Cache[I].Delete() == true)
437 continue;
438
439 List += I.FullName(true) + " ";
440 VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
441 }
442 ShowList(out,_("The following packages have been kept back:"),List,VersionsList);
443}
444 /*}}}*/
445// ShowUpgraded - Show upgraded packages /*{{{*/
446// ---------------------------------------------------------------------
447/* */
448void ShowUpgraded(ostream &out,CacheFile &Cache)
449{
450 string List;
451 string VersionsList;
452 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
453 {
454 pkgCache::PkgIterator I(Cache,Cache.List[J]);
455
456 // Not interesting
457 if (Cache[I].Upgrade() == false || Cache[I].NewInstall() == true)
458 continue;
459 if (Cache[I].CandidateVerIter(Cache).Pseudo() == true)
460 continue;
461
462 List += I.FullName(true) + " ";
463 VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
464 }
465 ShowList(out,_("The following packages will be upgraded:"),List,VersionsList);
466}
467 /*}}}*/
468// ShowDowngraded - Show downgraded packages /*{{{*/
469// ---------------------------------------------------------------------
470/* */
471bool ShowDowngraded(ostream &out,CacheFile &Cache)
472{
473 string List;
474 string VersionsList;
475 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
476 {
477 pkgCache::PkgIterator I(Cache,Cache.List[J]);
478
479 // Not interesting
480 if (Cache[I].Downgrade() == false || Cache[I].NewInstall() == true)
481 continue;
482 if (Cache[I].CandidateVerIter(Cache).Pseudo() == true)
483 continue;
484
485 List += I.FullName(true) + " ";
486 VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
487 }
488 return ShowList(out,_("The following packages will be DOWNGRADED:"),List,VersionsList);
489}
490 /*}}}*/
491// ShowHold - Show held but changed packages /*{{{*/
492// ---------------------------------------------------------------------
493/* */
494bool ShowHold(ostream &out,CacheFile &Cache)
495{
496 string List;
497 string VersionsList;
498 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
499 {
500 pkgCache::PkgIterator I(Cache,Cache.List[J]);
501 if (Cache[I].InstallVer != (pkgCache::Version *)I.CurrentVer() &&
502 I->SelectedState == pkgCache::State::Hold) {
503 List += I.FullName(true) + " ";
504 VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
505 }
506 }
507
508 return ShowList(out,_("The following held packages will be changed:"),List,VersionsList);
509}
510 /*}}}*/
511// ShowEssential - Show an essential package warning /*{{{*/
512// ---------------------------------------------------------------------
513/* This prints out a warning message that is not to be ignored. It shows
514 all essential packages and their dependents that are to be removed.
515 It is insanely risky to remove the dependents of an essential package! */
516bool ShowEssential(ostream &out,CacheFile &Cache)
517{
518 string List;
519 string VersionsList;
520 bool *Added = new bool[Cache->Head().PackageCount];
521 for (unsigned int I = 0; I != Cache->Head().PackageCount; I++)
522 Added[I] = false;
523
524 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
525 {
526 pkgCache::PkgIterator I(Cache,Cache.List[J]);
527 if ((I->Flags & pkgCache::Flag::Essential) != pkgCache::Flag::Essential &&
528 (I->Flags & pkgCache::Flag::Important) != pkgCache::Flag::Important)
529 continue;
530
531 // The essential package is being removed
532 if (Cache[I].Delete() == true)
533 {
534 if (Added[I->ID] == false)
535 {
536 Added[I->ID] = true;
537 List += I.FullName(true) + " ";
538 //VersionsList += string(Cache[I].CurVersion) + "\n"; ???
539 }
540 }
541
542 if (I->CurrentVer == 0)
543 continue;
544
545 // Print out any essential package depenendents that are to be removed
546 for (pkgCache::DepIterator D = I.CurrentVer().DependsList(); D.end() == false; D++)
547 {
548 // Skip everything but depends
549 if (D->Type != pkgCache::Dep::PreDepends &&
550 D->Type != pkgCache::Dep::Depends)
551 continue;
552
553 pkgCache::PkgIterator P = D.SmartTargetPkg();
554 if (Cache[P].Delete() == true)
555 {
556 if (Added[P->ID] == true)
557 continue;
558 Added[P->ID] = true;
559
560 char S[300];
561 snprintf(S,sizeof(S),_("%s (due to %s) "),P.FullName(true).c_str(),I.FullName(true).c_str());
562 List += S;
563 //VersionsList += "\n"; ???
564 }
565 }
566 }
567
568 delete [] Added;
569 return ShowList(out,_("WARNING: The following essential packages will be removed.\n"
570 "This should NOT be done unless you know exactly what you are doing!"),List,VersionsList);
571}
572
573 /*}}}*/
574// Stats - Show some statistics /*{{{*/
575// ---------------------------------------------------------------------
576/* */
577void Stats(ostream &out,pkgDepCache &Dep)
578{
579 unsigned long Upgrade = 0;
580 unsigned long Downgrade = 0;
581 unsigned long Install = 0;
582 unsigned long ReInstall = 0;
583 for (pkgCache::PkgIterator I = Dep.PkgBegin(); I.end() == false; I++)
584 {
585 if (pkgCache::VerIterator(Dep, Dep[I].CandidateVer).Pseudo() == true)
586 continue;
587
588 if (Dep[I].NewInstall() == true)
589 Install++;
590 else
591 {
592 if (Dep[I].Upgrade() == true)
593 Upgrade++;
594 else
595 if (Dep[I].Downgrade() == true)
596 Downgrade++;
597 }
598
599 if (Dep[I].Delete() == false && (Dep[I].iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
600 ReInstall++;
601 }
602
603 ioprintf(out,_("%lu upgraded, %lu newly installed, "),
604 Upgrade,Install);
605
606 if (ReInstall != 0)
607 ioprintf(out,_("%lu reinstalled, "),ReInstall);
608 if (Downgrade != 0)
609 ioprintf(out,_("%lu downgraded, "),Downgrade);
610
611 ioprintf(out,_("%lu to remove and %lu not upgraded.\n"),
612 Dep.DelCount(),Dep.KeepCount());
613
614 if (Dep.BadCount() != 0)
615 ioprintf(out,_("%lu not fully installed or removed.\n"),
616 Dep.BadCount());
617}
618 /*}}}*/
619// CacheSetHelperAPTGet - responsible for message telling from the CacheSets/*{{{*/
620class CacheSetHelperAPTGet : public APT::CacheSetHelper {
621 /** \brief stream message should be printed to */
622 std::ostream &out;
623 /** \brief were things like Task or RegEx used to select packages? */
624 bool explicitlyNamed;
625
626 APT::PackageSet virtualPkgs;
627
628public:
629 CacheSetHelperAPTGet(std::ostream &out) : APT::CacheSetHelper(true), out(out) {
630 explicitlyNamed = true;
631 }
632
633 virtual void showTaskSelection(APT::PackageSet const &pkgset, string const &pattern) {
634 for (APT::PackageSet::const_iterator Pkg = pkgset.begin(); Pkg != pkgset.end(); ++Pkg)
635 ioprintf(out, _("Note, selecting '%s' for task '%s'\n"),
636 Pkg.FullName(true).c_str(), pattern.c_str());
637 explicitlyNamed = false;
638 }
639 virtual void showRegExSelection(APT::PackageSet const &pkgset, string const &pattern) {
640 for (APT::PackageSet::const_iterator Pkg = pkgset.begin(); Pkg != pkgset.end(); ++Pkg)
641 ioprintf(out, _("Note, selecting '%s' for regex '%s'\n"),
642 Pkg.FullName(true).c_str(), pattern.c_str());
643 explicitlyNamed = false;
644 }
645 virtual void showSelectedVersion(pkgCache::PkgIterator const &Pkg, pkgCache::VerIterator const Ver,
646 string const &ver, bool const &verIsRel) {
647 if (ver != Ver.VerStr())
648 ioprintf(out, _("Selected version '%s' (%s) for '%s'\n"),
649 Ver.VerStr(), Ver.RelStr().c_str(), Pkg.FullName(true).c_str());
650 }
651
652 bool showVirtualPackageErrors(pkgCacheFile &Cache) {
653 if (virtualPkgs.empty() == true)
654 return true;
655 for (APT::PackageSet::const_iterator Pkg = virtualPkgs.begin();
656 Pkg != virtualPkgs.end(); ++Pkg) {
657 if (Pkg->ProvidesList != 0) {
658 ioprintf(c1out,_("Package %s is a virtual package provided by:\n"),
659 Pkg.FullName(true).c_str());
660
661 pkgCache::PrvIterator I = Pkg.ProvidesList();
662 unsigned short provider = 0;
663 for (; I.end() == false; ++I) {
664 pkgCache::PkgIterator Pkg = I.OwnerPkg();
665
666 if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer()) {
667 out << " " << Pkg.FullName(true) << " " << I.OwnerVer().VerStr();
668 if (Cache[Pkg].Install() == true && Cache[Pkg].NewInstall() == false)
669 out << _(" [Installed]");
670 out << endl;
671 ++provider;
672 }
673 }
674 // if we found no candidate which provide this package, show non-candidates
675 if (provider == 0)
676 for (I = Pkg.ProvidesList(); I.end() == false; I++)
677 out << " " << I.OwnerPkg().FullName(true) << " " << I.OwnerVer().VerStr()
678 << _(" [Not candidate version]") << endl;
679 else
680 out << _("You should explicitly select one to install.") << endl;
681 } else {
682 ioprintf(out,
683 _("Package %s is not available, but is referred to by another package.\n"
684 "This may mean that the package is missing, has been obsoleted, or\n"
685 "is only available from another source\n"),Pkg.FullName(true).c_str());
686
687 string List;
688 string VersionsList;
689 SPtrArray<bool> Seen = new bool[Cache.GetPkgCache()->Head().PackageCount];
690 memset(Seen,0,Cache.GetPkgCache()->Head().PackageCount*sizeof(*Seen));
691 for (pkgCache::DepIterator Dep = Pkg.RevDependsList();
692 Dep.end() == false; Dep++) {
693 if (Dep->Type != pkgCache::Dep::Replaces)
694 continue;
695 if (Seen[Dep.ParentPkg()->ID] == true)
696 continue;
697 Seen[Dep.ParentPkg()->ID] = true;
698 List += Dep.ParentPkg().FullName(true) + " ";
699 //VersionsList += string(Dep.ParentPkg().CurVersion) + "\n"; ???
700 }
701 ShowList(out,_("However the following packages replace it:"),List,VersionsList);
702 }
703 out << std::endl;
704 }
705 return false;
706 }
707
708 virtual pkgCache::VerIterator canNotFindCandidateVer(pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg) {
709 APT::VersionSet const verset = tryVirtualPackage(Cache, Pkg, APT::VersionSet::CANDIDATE);
710 if (verset.empty() == false)
711 return *(verset.begin());
712 if (ShowError == true) {
713 _error->Error(_("Package '%s' has no installation candidate"),Pkg.FullName(true).c_str());
714 virtualPkgs.insert(Pkg);
715 }
716 return pkgCache::VerIterator(Cache, 0);
717 }
718
719 virtual pkgCache::VerIterator canNotFindNewestVer(pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg) {
720 APT::VersionSet const verset = tryVirtualPackage(Cache, Pkg, APT::VersionSet::NEWEST);
721 if (verset.empty() == false)
722 return *(verset.begin());
723 if (ShowError == true)
724 ioprintf(out, _("Virtual packages like '%s' can't be removed\n"), Pkg.FullName(true).c_str());
725 return pkgCache::VerIterator(Cache, 0);
726 }
727
728 APT::VersionSet tryVirtualPackage(pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg,
729 APT::VersionSet::Version const &select) {
730 /* This is a pure virtual package and there is a single available
731 candidate providing it. */
732 if (unlikely(Cache[Pkg].CandidateVer != 0) || Pkg->ProvidesList == 0)
733 return APT::VersionSet();
734
735 pkgCache::PkgIterator Prov;
736 bool found_one = false;
737 for (pkgCache::PrvIterator P = Pkg.ProvidesList(); P; ++P) {
738 pkgCache::VerIterator const PVer = P.OwnerVer();
739 pkgCache::PkgIterator const PPkg = PVer.ParentPkg();
740
741 /* Ignore versions that are not a candidate. */
742 if (Cache[PPkg].CandidateVer != PVer)
743 continue;
744
745 if (found_one == false) {
746 Prov = PPkg;
747 found_one = true;
748 } else if (PPkg != Prov) {
749 found_one = false; // we found at least two
750 break;
751 }
752 }
753
754 if (found_one == true) {
755 ioprintf(out, _("Note, selecting '%s' instead of '%s'\n"),
756 Prov.FullName(true).c_str(), Pkg.FullName(true).c_str());
757 return APT::VersionSet::FromPackage(Cache, Prov, select, *this);
758 }
759 return APT::VersionSet();
760 }
761
762 inline bool allPkgNamedExplicitly() const { return explicitlyNamed; }
763
764};
765 /*}}}*/
766// TryToInstall - Mark a package for installation /*{{{*/
767struct TryToInstall {
768 pkgCacheFile* Cache;
769 pkgProblemResolver* Fix;
770 bool FixBroken;
771 unsigned long AutoMarkChanged;
772 APT::PackageSet doAutoInstallLater;
773
774 TryToInstall(pkgCacheFile &Cache, pkgProblemResolver &PM, bool const &FixBroken) : Cache(&Cache), Fix(&PM),
775 FixBroken(FixBroken), AutoMarkChanged(0) {};
776
777 void operator() (pkgCache::VerIterator const &Ver) {
778 pkgCache::PkgIterator Pkg = Ver.ParentPkg();
779
780 Cache->GetDepCache()->SetCandidateVersion(Ver);
781 pkgDepCache::StateCache &State = (*Cache)[Pkg];
782
783 // Handle the no-upgrade case
784 if (_config->FindB("APT::Get::upgrade",true) == false && Pkg->CurrentVer != 0)
785 ioprintf(c1out,_("Skipping %s, it is already installed and upgrade is not set.\n"),
786 Pkg.FullName(true).c_str());
787 // Ignore request for install if package would be new
788 else if (_config->FindB("APT::Get::Only-Upgrade", false) == true && Pkg->CurrentVer == 0)
789 ioprintf(c1out,_("Skipping %s, it is not installed and only upgrades are requested.\n"),
790 Pkg.FullName(true).c_str());
791 else {
792 Fix->Clear(Pkg);
793 Fix->Protect(Pkg);
794 Cache->GetDepCache()->MarkInstall(Pkg,false);
795
796 if (State.Install() == false) {
797 if (_config->FindB("APT::Get::ReInstall",false) == true) {
798 if (Pkg->CurrentVer == 0 || Pkg.CurrentVer().Downloadable() == false)
799 ioprintf(c1out,_("Reinstallation of %s is not possible, it cannot be downloaded.\n"),
800 Pkg.FullName(true).c_str());
801 else
802 Cache->GetDepCache()->SetReInstall(Pkg, true);
803 } else
804 ioprintf(c1out,_("%s is already the newest version.\n"),
805 Pkg.FullName(true).c_str());
806 }
807
808 // Install it with autoinstalling enabled (if we not respect the minial
809 // required deps or the policy)
810 if (FixBroken == false)
811 doAutoInstallLater.insert(Pkg);
812 }
813
814 // see if we need to fix the auto-mark flag
815 // e.g. apt-get install foo
816 // where foo is marked automatic
817 if (State.Install() == false &&
818 (State.Flags & pkgCache::Flag::Auto) &&
819 _config->FindB("APT::Get::ReInstall",false) == false &&
820 _config->FindB("APT::Get::Only-Upgrade",false) == false &&
821 _config->FindB("APT::Get::Download-Only",false) == false)
822 {
823 ioprintf(c1out,_("%s set to manually installed.\n"),
824 Pkg.FullName(true).c_str());
825 Cache->GetDepCache()->MarkAuto(Pkg,false);
826 AutoMarkChanged++;
827 }
828 }
829
830 void doAutoInstall() {
831 for (APT::PackageSet::const_iterator P = doAutoInstallLater.begin();
832 P != doAutoInstallLater.end(); ++P) {
833 pkgDepCache::StateCache &State = (*Cache)[P];
834 if (State.InstBroken() == false && State.InstPolicyBroken() == false)
835 continue;
836 Cache->GetDepCache()->MarkInstall(P, true);
837 }
838 doAutoInstallLater.clear();
839 }
840};
841 /*}}}*/
842// TryToRemove - Mark a package for removal /*{{{*/
843struct TryToRemove {
844 pkgCacheFile* Cache;
845 pkgProblemResolver* Fix;
846 bool FixBroken;
847 bool PurgePkgs;
848 unsigned long AutoMarkChanged;
849
850 TryToRemove(pkgCacheFile &Cache, pkgProblemResolver &PM) : Cache(&Cache), Fix(&PM),
851 PurgePkgs(_config->FindB("APT::Get::Purge", false)) {};
852
853 void operator() (pkgCache::VerIterator const &Ver)
854 {
855 pkgCache::PkgIterator Pkg = Ver.ParentPkg();
856
857 Fix->Clear(Pkg);
858 Fix->Protect(Pkg);
859 Fix->Remove(Pkg);
860
861 if ((Pkg->CurrentVer == 0 && PurgePkgs == false) ||
862 (PurgePkgs == true && Pkg->CurrentState == pkgCache::State::NotInstalled))
863 ioprintf(c1out,_("Package %s is not installed, so not removed\n"),Pkg.FullName(true).c_str());
864 else
865 Cache->GetDepCache()->MarkDelete(Pkg, PurgePkgs);
866 }
867};
868 /*}}}*/
869// CacheFile::NameComp - QSort compare by name /*{{{*/
870// ---------------------------------------------------------------------
871/* */
872pkgCache *CacheFile::SortCache = 0;
873int CacheFile::NameComp(const void *a,const void *b)
874{
875 if (*(pkgCache::Package **)a == 0 || *(pkgCache::Package **)b == 0)
876 return *(pkgCache::Package **)a - *(pkgCache::Package **)b;
877
878 const pkgCache::Package &A = **(pkgCache::Package **)a;
879 const pkgCache::Package &B = **(pkgCache::Package **)b;
880
881 return strcmp(SortCache->StrP + A.Name,SortCache->StrP + B.Name);
882}
883 /*}}}*/
884// CacheFile::Sort - Sort by name /*{{{*/
885// ---------------------------------------------------------------------
886/* */
887void CacheFile::Sort()
888{
889 delete [] List;
890 List = new pkgCache::Package *[Cache->Head().PackageCount];
891 memset(List,0,sizeof(*List)*Cache->Head().PackageCount);
892 pkgCache::PkgIterator I = Cache->PkgBegin();
893 for (;I.end() != true; I++)
894 List[I->ID] = I;
895
896 SortCache = *this;
897 qsort(List,Cache->Head().PackageCount,sizeof(*List),NameComp);
898}
899 /*}}}*/
900// CacheFile::CheckDeps - Open the cache file /*{{{*/
901// ---------------------------------------------------------------------
902/* This routine generates the caches and then opens the dependency cache
903 and verifies that the system is OK. */
904bool CacheFile::CheckDeps(bool AllowBroken)
905{
906 bool FixBroken = _config->FindB("APT::Get::Fix-Broken",false);
907
908 if (_error->PendingError() == true)
909 return false;
910
911 // Check that the system is OK
912 if (DCache->DelCount() != 0 || DCache->InstCount() != 0)
913 return _error->Error("Internal error, non-zero counts");
914
915 // Apply corrections for half-installed packages
916 if (pkgApplyStatus(*DCache) == false)
917 return false;
918
919 if (_config->FindB("APT::Get::Fix-Policy-Broken",false) == true)
920 {
921 FixBroken = true;
922 if ((DCache->PolicyBrokenCount() > 0))
923 {
924 // upgrade all policy-broken packages with ForceImportantDeps=True
925 for (pkgCache::PkgIterator I = Cache->PkgBegin(); !I.end(); I++)
926 if ((*DCache)[I].NowPolicyBroken() == true)
927 DCache->MarkInstall(I,true,0, false, true);
928 }
929 }
930
931 // Nothing is broken
932 if (DCache->BrokenCount() == 0 || AllowBroken == true)
933 return true;
934
935 // Attempt to fix broken things
936 if (FixBroken == true)
937 {
938 c1out << _("Correcting dependencies...") << flush;
939 if (pkgFixBroken(*DCache) == false || DCache->BrokenCount() != 0)
940 {
941 c1out << _(" failed.") << endl;
942 ShowBroken(c1out,*this,true);
943
944 return _error->Error(_("Unable to correct dependencies"));
945 }
946 if (pkgMinimizeUpgrade(*DCache) == false)
947 return _error->Error(_("Unable to minimize the upgrade set"));
948
949 c1out << _(" Done") << endl;
950 }
951 else
952 {
953 c1out << _("You might want to run 'apt-get -f install' to correct these.") << endl;
954 ShowBroken(c1out,*this,true);
955
956 return _error->Error(_("Unmet dependencies. Try using -f."));
957 }
958
959 return true;
960}
961 /*}}}*/
962// CheckAuth - check if each download comes form a trusted source /*{{{*/
963// ---------------------------------------------------------------------
964/* */
965static bool CheckAuth(pkgAcquire& Fetcher)
966{
967 string UntrustedList;
968 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I < Fetcher.ItemsEnd(); ++I)
969 {
970 if (!(*I)->IsTrusted())
971 {
972 UntrustedList += string((*I)->ShortDesc()) + " ";
973 }
974 }
975
976 if (UntrustedList == "")
977 {
978 return true;
979 }
980
981 ShowList(c2out,_("WARNING: The following packages cannot be authenticated!"),UntrustedList,"");
982
983 if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
984 {
985 c2out << _("Authentication warning overridden.\n");
986 return true;
987 }
988
989 if (_config->FindI("quiet",0) < 2
990 && _config->FindB("APT::Get::Assume-Yes",false) == false)
991 {
992 c2out << _("Install these packages without verification [y/N]? ") << flush;
993 if (!YnPrompt(false))
994 return _error->Error(_("Some packages could not be authenticated"));
995
996 return true;
997 }
998 else if (_config->FindB("APT::Get::Force-Yes",false) == true)
999 {
1000 return true;
1001 }
1002
1003 return _error->Error(_("There are problems and -y was used without --force-yes"));
1004}
1005 /*}}}*/
1006// InstallPackages - Actually download and install the packages /*{{{*/
1007// ---------------------------------------------------------------------
1008/* This displays the informative messages describing what is going to
1009 happen and then calls the download routines */
1010bool InstallPackages(CacheFile &Cache,bool ShwKept,bool Ask = true,
1011 bool Safety = true)
1012{
1013 if (_config->FindB("APT::Get::Purge",false) == true)
1014 {
1015 pkgCache::PkgIterator I = Cache->PkgBegin();
1016 for (; I.end() == false; I++)
1017 {
1018 if (I.Purge() == false && Cache[I].Mode == pkgDepCache::ModeDelete)
1019 Cache->MarkDelete(I,true);
1020 }
1021 }
1022
1023 bool Fail = false;
1024 bool Essential = false;
1025
1026 // Show all the various warning indicators
1027 ShowDel(c1out,Cache);
1028 ShowNew(c1out,Cache);
1029 if (ShwKept == true)
1030 ShowKept(c1out,Cache);
1031 Fail |= !ShowHold(c1out,Cache);
1032 if (_config->FindB("APT::Get::Show-Upgraded",true) == true)
1033 ShowUpgraded(c1out,Cache);
1034 Fail |= !ShowDowngraded(c1out,Cache);
1035 if (_config->FindB("APT::Get::Download-Only",false) == false)
1036 Essential = !ShowEssential(c1out,Cache);
1037 Fail |= Essential;
1038 Stats(c1out,Cache);
1039
1040 // Sanity check
1041 if (Cache->BrokenCount() != 0)
1042 {
1043 ShowBroken(c1out,Cache,false);
1044 return _error->Error(_("Internal error, InstallPackages was called with broken packages!"));
1045 }
1046
1047 if (Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
1048 Cache->BadCount() == 0)
1049 return true;
1050
1051 // No remove flag
1052 if (Cache->DelCount() != 0 && _config->FindB("APT::Get::Remove",true) == false)
1053 return _error->Error(_("Packages need to be removed but remove is disabled."));
1054
1055 // Run the simulator ..
1056 if (_config->FindB("APT::Get::Simulate") == true)
1057 {
1058 pkgSimulate PM(Cache);
1059 int status_fd = _config->FindI("APT::Status-Fd",-1);
1060 pkgPackageManager::OrderResult Res = PM.DoInstall(status_fd);
1061 if (Res == pkgPackageManager::Failed)
1062 return false;
1063 if (Res != pkgPackageManager::Completed)
1064 return _error->Error(_("Internal error, Ordering didn't finish"));
1065 return true;
1066 }
1067
1068 // Create the text record parser
1069 pkgRecords Recs(Cache);
1070 if (_error->PendingError() == true)
1071 return false;
1072
1073 // Create the download object
1074 pkgAcquire Fetcher;
1075 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
1076 if (_config->FindB("APT::Get::Print-URIs", false) == true)
1077 {
1078 // force a hashsum for compatibility reasons
1079 _config->CndSet("Acquire::ForceHash", "md5sum");
1080 }
1081 else if (Fetcher.Setup(&Stat, _config->FindDir("Dir::Cache::Archives")) == false)
1082 return false;
1083
1084 // Read the source list
1085 if (Cache.BuildSourceList() == false)
1086 return false;
1087 pkgSourceList *List = Cache.GetSourceList();
1088
1089 // Create the package manager and prepare to download
1090 SPtr<pkgPackageManager> PM= _system->CreatePM(Cache);
1091 if (PM->GetArchives(&Fetcher,List,&Recs) == false ||
1092 _error->PendingError() == true)
1093 return false;
1094
1095 // Display statistics
1096 unsigned long long FetchBytes = Fetcher.FetchNeeded();
1097 unsigned long long FetchPBytes = Fetcher.PartialPresent();
1098 unsigned long long DebBytes = Fetcher.TotalNeeded();
1099 if (DebBytes != Cache->DebSize())
1100 {
1101 c0out << DebBytes << ',' << Cache->DebSize() << endl;
1102 c0out << _("How odd.. The sizes didn't match, email apt@packages.debian.org") << endl;
1103 }
1104
1105 // Number of bytes
1106 if (DebBytes != FetchBytes)
1107 //TRANSLATOR: The required space between number and unit is already included
1108 // in the replacement strings, so %sB will be correctly translate in e.g. 1,5 MB
1109 ioprintf(c1out,_("Need to get %sB/%sB of archives.\n"),
1110 SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
1111 else if (DebBytes != 0)
1112 //TRANSLATOR: The required space between number and unit is already included
1113 // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
1114 ioprintf(c1out,_("Need to get %sB of archives.\n"),
1115 SizeToStr(DebBytes).c_str());
1116
1117 // Size delta
1118 if (Cache->UsrSize() >= 0)
1119 //TRANSLATOR: The required space between number and unit is already included
1120 // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
1121 ioprintf(c1out,_("After this operation, %sB of additional disk space will be used.\n"),
1122 SizeToStr(Cache->UsrSize()).c_str());
1123 else
1124 //TRANSLATOR: The required space between number and unit is already included
1125 // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
1126 ioprintf(c1out,_("After this operation, %sB disk space will be freed.\n"),
1127 SizeToStr(-1*Cache->UsrSize()).c_str());
1128
1129 if (_error->PendingError() == true)
1130 return false;
1131
1132 /* Check for enough free space, but only if we are actually going to
1133 download */
1134 if (_config->FindB("APT::Get::Print-URIs") == false &&
1135 _config->FindB("APT::Get::Download",true) == true)
1136 {
1137 struct statvfs Buf;
1138 string OutputDir = _config->FindDir("Dir::Cache::Archives");
1139 if (statvfs(OutputDir.c_str(),&Buf) != 0) {
1140 if (errno == EOVERFLOW)
1141 return _error->WarningE("statvfs",_("Couldn't determine free space in %s"),
1142 OutputDir.c_str());
1143 else
1144 return _error->Errno("statvfs",_("Couldn't determine free space in %s"),
1145 OutputDir.c_str());
1146 } else if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
1147 {
1148 struct statfs Stat;
1149 if (statfs(OutputDir.c_str(),&Stat) != 0
1150#if HAVE_STRUCT_STATFS_F_TYPE
1151 || unsigned(Stat.f_type) != RAMFS_MAGIC
1152#endif
1153 )
1154 return _error->Error(_("You don't have enough free space in %s."),
1155 OutputDir.c_str());
1156 }
1157 }
1158
1159 // Fail safe check
1160 if (_config->FindI("quiet",0) >= 2 ||
1161 _config->FindB("APT::Get::Assume-Yes",false) == true)
1162 {
1163 if (Fail == true && _config->FindB("APT::Get::Force-Yes",false) == false)
1164 return _error->Error(_("There are problems and -y was used without --force-yes"));
1165 }
1166
1167 if (Essential == true && Safety == true)
1168 {
1169 if (_config->FindB("APT::Get::Trivial-Only",false) == true)
1170 return _error->Error(_("Trivial Only specified but this is not a trivial operation."));
1171
1172 const char *Prompt = _("Yes, do as I say!");
1173 ioprintf(c2out,
1174 _("You are about to do something potentially harmful.\n"
1175 "To continue type in the phrase '%s'\n"
1176 " ?] "),Prompt);
1177 c2out << flush;
1178 if (AnalPrompt(Prompt) == false)
1179 {
1180 c2out << _("Abort.") << endl;
1181 exit(1);
1182 }
1183 }
1184 else
1185 {
1186 // Prompt to continue
1187 if (Ask == true || Fail == true)
1188 {
1189 if (_config->FindB("APT::Get::Trivial-Only",false) == true)
1190 return _error->Error(_("Trivial Only specified but this is not a trivial operation."));
1191
1192 if (_config->FindI("quiet",0) < 2 &&
1193 _config->FindB("APT::Get::Assume-Yes",false) == false)
1194 {
1195 c2out << _("Do you want to continue [Y/n]? ") << flush;
1196
1197 if (YnPrompt() == false)
1198 {
1199 c2out << _("Abort.") << endl;
1200 exit(1);
1201 }
1202 }
1203 }
1204 }
1205
1206 // Just print out the uris an exit if the --print-uris flag was used
1207 if (_config->FindB("APT::Get::Print-URIs") == true)
1208 {
1209 pkgAcquire::UriIterator I = Fetcher.UriBegin();
1210 for (; I != Fetcher.UriEnd(); I++)
1211 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
1212 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
1213 return true;
1214 }
1215
1216 if (!CheckAuth(Fetcher))
1217 return false;
1218
1219 /* Unlock the dpkg lock if we are not going to be doing an install
1220 after. */
1221 if (_config->FindB("APT::Get::Download-Only",false) == true)
1222 _system->UnLock();
1223
1224 // Run it
1225 while (1)
1226 {
1227 bool Transient = false;
1228 if (_config->FindB("APT::Get::Download",true) == false)
1229 {
1230 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I < Fetcher.ItemsEnd();)
1231 {
1232 if ((*I)->Local == true)
1233 {
1234 I++;
1235 continue;
1236 }
1237
1238 // Close the item and check if it was found in cache
1239 (*I)->Finished();
1240 if ((*I)->Complete == false)
1241 Transient = true;
1242
1243 // Clear it out of the fetch list
1244 delete *I;
1245 I = Fetcher.ItemsBegin();
1246 }
1247 }
1248
1249 if (Fetcher.Run() == pkgAcquire::Failed)
1250 return false;
1251
1252 // Print out errors
1253 bool Failed = false;
1254 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
1255 {
1256 if ((*I)->Status == pkgAcquire::Item::StatDone &&
1257 (*I)->Complete == true)
1258 continue;
1259
1260 if ((*I)->Status == pkgAcquire::Item::StatIdle)
1261 {
1262 Transient = true;
1263 // Failed = true;
1264 continue;
1265 }
1266
1267 fprintf(stderr,_("Failed to fetch %s %s\n"),(*I)->DescURI().c_str(),
1268 (*I)->ErrorText.c_str());
1269 Failed = true;
1270 }
1271
1272 /* If we are in no download mode and missing files and there were
1273 'failures' then the user must specify -m. Furthermore, there
1274 is no such thing as a transient error in no-download mode! */
1275 if (Transient == true &&
1276 _config->FindB("APT::Get::Download",true) == false)
1277 {
1278 Transient = false;
1279 Failed = true;
1280 }
1281
1282 if (_config->FindB("APT::Get::Download-Only",false) == true)
1283 {
1284 if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
1285 return _error->Error(_("Some files failed to download"));
1286 c1out << _("Download complete and in download only mode") << endl;
1287 return true;
1288 }
1289
1290 if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
1291 {
1292 return _error->Error(_("Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?"));
1293 }
1294
1295 if (Transient == true && Failed == true)
1296 return _error->Error(_("--fix-missing and media swapping is not currently supported"));
1297
1298 // Try to deal with missing package files
1299 if (Failed == true && PM->FixMissing() == false)
1300 {
1301 cerr << _("Unable to correct missing packages.") << endl;
1302 return _error->Error(_("Aborting install."));
1303 }
1304
1305 _system->UnLock();
1306 int status_fd = _config->FindI("APT::Status-Fd",-1);
1307 pkgPackageManager::OrderResult Res = PM->DoInstall(status_fd);
1308 if (Res == pkgPackageManager::Failed || _error->PendingError() == true)
1309 return false;
1310 if (Res == pkgPackageManager::Completed)
1311 break;
1312
1313 // Reload the fetcher object and loop again for media swapping
1314 Fetcher.Shutdown();
1315 if (PM->GetArchives(&Fetcher,List,&Recs) == false)
1316 return false;
1317
1318 _system->Lock();
1319 }
1320
1321 std::set<std::string> const disappearedPkgs = PM->GetDisappearedPackages();
1322 if (disappearedPkgs.empty() == true)
1323 return true;
1324
1325 string disappear;
1326 for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
1327 d != disappearedPkgs.end(); ++d)
1328 disappear.append(*d).append(" ");
1329
1330 ShowList(c1out, P_("The following package disappeared from your system as\n"
1331 "all files have been overwritten by other packages:",
1332 "The following packages disappeared from your system as\n"
1333 "all files have been overwritten by other packages:", disappearedPkgs.size()), disappear, "");
1334 c0out << _("Note: This is done automatic and on purpose by dpkg.") << std::endl;
1335
1336 return true;
1337}
1338 /*}}}*/
1339// TryToInstallBuildDep - Try to install a single package /*{{{*/
1340// ---------------------------------------------------------------------
1341/* This used to be inlined in DoInstall, but with the advent of regex package
1342 name matching it was split out.. */
1343bool TryToInstallBuildDep(pkgCache::PkgIterator Pkg,pkgCacheFile &Cache,
1344 pkgProblemResolver &Fix,bool Remove,bool BrokenFix,
1345 bool AllowFail = true)
1346{
1347 if (Cache[Pkg].CandidateVer == 0 && Pkg->ProvidesList != 0)
1348 {
1349 CacheSetHelperAPTGet helper(c1out);
1350 helper.showErrors(AllowFail == false);
1351 pkgCache::VerIterator Ver = helper.canNotFindNewestVer(Cache, Pkg);
1352 if (Ver.end() == false)
1353 Pkg = Ver.ParentPkg();
1354 else if (helper.showVirtualPackageErrors(Cache) == false)
1355 return AllowFail;
1356 }
1357
1358 if (Remove == true)
1359 {
1360 TryToRemove RemoveAction(Cache, Fix);
1361 RemoveAction(Pkg.VersionList());
1362 } else if (Cache[Pkg].CandidateVer != 0) {
1363 TryToInstall InstallAction(Cache, Fix, BrokenFix);
1364 InstallAction(Cache[Pkg].CandidateVerIter(Cache));
1365 InstallAction.doAutoInstall();
1366 } else
1367 return AllowFail;
1368
1369 return true;
1370}
1371 /*}}}*/
1372// FindSrc - Find a source record /*{{{*/
1373// ---------------------------------------------------------------------
1374/* */
1375pkgSrcRecords::Parser *FindSrc(const char *Name,pkgRecords &Recs,
1376 pkgSrcRecords &SrcRecs,string &Src,
1377 pkgDepCache &Cache)
1378{
1379 string VerTag;
1380 string DefRel = _config->Find("APT::Default-Release");
1381 string TmpSrc = Name;
1382
1383 // extract the version/release from the pkgname
1384 const size_t found = TmpSrc.find_last_of("/=");
1385 if (found != string::npos) {
1386 if (TmpSrc[found] == '/')
1387 DefRel = TmpSrc.substr(found+1);
1388 else
1389 VerTag = TmpSrc.substr(found+1);
1390 TmpSrc = TmpSrc.substr(0,found);
1391 }
1392
1393 /* Lookup the version of the package we would install if we were to
1394 install a version and determine the source package name, then look
1395 in the archive for a source package of the same name. */
1396 bool MatchSrcOnly = _config->FindB("APT::Get::Only-Source");
1397 const pkgCache::PkgIterator Pkg = Cache.FindPkg(TmpSrc);
1398 if (MatchSrcOnly == false && Pkg.end() == false)
1399 {
1400 if(VerTag.empty() == false || DefRel.empty() == false)
1401 {
1402 bool fuzzy = false;
1403 // we have a default release, try to locate the pkg. we do it like
1404 // this because GetCandidateVer() will not "downgrade", that means
1405 // "apt-get source -t stable apt" won't work on a unstable system
1406 for (pkgCache::VerIterator Ver = Pkg.VersionList();; Ver++)
1407 {
1408 // try first only exact matches, later fuzzy matches
1409 if (Ver.end() == true)
1410 {
1411 if (fuzzy == true)
1412 break;
1413 fuzzy = true;
1414 Ver = Pkg.VersionList();
1415 // exit right away from the Pkg.VersionList() loop if we
1416 // don't have any versions
1417 if (Ver.end() == true)
1418 break;
1419 }
1420 // We match against a concrete version (or a part of this version)
1421 if (VerTag.empty() == false &&
1422 (fuzzy == true || Cache.VS().CmpVersion(VerTag, Ver.VerStr()) != 0) && // exact match
1423 (fuzzy == false || strncmp(VerTag.c_str(), Ver.VerStr(), VerTag.size()) != 0)) // fuzzy match
1424 continue;
1425
1426 for (pkgCache::VerFileIterator VF = Ver.FileList();
1427 VF.end() == false; VF++)
1428 {
1429 /* If this is the status file, and the current version is not the
1430 version in the status file (ie it is not installed, or somesuch)
1431 then it is not a candidate for installation, ever. This weeds
1432 out bogus entries that may be due to config-file states, or
1433 other. */
1434 if ((VF.File()->Flags & pkgCache::Flag::NotSource) ==
1435 pkgCache::Flag::NotSource && Pkg.CurrentVer() != Ver)
1436 continue;
1437
1438 // or we match against a release
1439 if(VerTag.empty() == false ||
1440 (VF.File().Archive() != 0 && VF.File().Archive() == DefRel) ||
1441 (VF.File().Codename() != 0 && VF.File().Codename() == DefRel))
1442 {
1443 pkgRecords::Parser &Parse = Recs.Lookup(VF);
1444 Src = Parse.SourcePkg();
1445 // no SourcePkg name, so it is the "binary" name
1446 if (Src.empty() == true)
1447 Src = TmpSrc;
1448 // the Version we have is possibly fuzzy or includes binUploads,
1449 // so we use the Version of the SourcePkg (empty if same as package)
1450 VerTag = Parse.SourceVer();
1451 if (VerTag.empty() == true)
1452 VerTag = Ver.VerStr();
1453 break;
1454 }
1455 }
1456 if (Src.empty() == false)
1457 break;
1458 }
1459 if (Src.empty() == true)
1460 {
1461 // Sources files have no codename information
1462 if (VerTag.empty() == true && DefRel.empty() == false)
1463 {
1464 _error->Error(_("Ignore unavailable target release '%s' of package '%s'"), DefRel.c_str(), TmpSrc.c_str());
1465 return 0;
1466 }
1467 }
1468 }
1469 if (Src.empty() == true)
1470 {
1471 // if we don't have found a fitting package yet so we will
1472 // choose a good candidate and proceed with that.
1473 // Maybe we will find a source later on with the right VerTag
1474 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
1475 if (Ver.end() == false)
1476 {
1477 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1478 Src = Parse.SourcePkg();
1479 if (VerTag.empty() == true)
1480 VerTag = Parse.SourceVer();
1481 }
1482 }
1483 }
1484
1485 if (Src.empty() == true)
1486 Src = TmpSrc;
1487 else
1488 {
1489 /* if we have a source pkg name, make sure to only search
1490 for srcpkg names, otherwise apt gets confused if there
1491 is a binary package "pkg1" and a source package "pkg1"
1492 with the same name but that comes from different packages */
1493 MatchSrcOnly = true;
1494 if (Src != TmpSrc)
1495 {
1496 ioprintf(c1out, _("Picking '%s' as source package instead of '%s'\n"), Src.c_str(), TmpSrc.c_str());
1497 }
1498 }
1499
1500 // The best hit
1501 pkgSrcRecords::Parser *Last = 0;
1502 unsigned long Offset = 0;
1503 string Version;
1504
1505 /* Iterate over all of the hits, which includes the resulting
1506 binary packages in the search */
1507 pkgSrcRecords::Parser *Parse;
1508 while (true)
1509 {
1510 SrcRecs.Restart();
1511 while ((Parse = SrcRecs.Find(Src.c_str(), MatchSrcOnly)) != 0)
1512 {
1513 const string Ver = Parse->Version();
1514
1515 // Ignore all versions which doesn't fit
1516 if (VerTag.empty() == false &&
1517 Cache.VS().CmpVersion(VerTag, Ver) != 0) // exact match
1518 continue;
1519
1520 // Newer version or an exact match? Save the hit
1521 if (Last == 0 || Cache.VS().CmpVersion(Version,Ver) < 0) {
1522 Last = Parse;
1523 Offset = Parse->Offset();
1524 Version = Ver;
1525 }
1526
1527 // was the version check above an exact match? If so, we don't need to look further
1528 if (VerTag.empty() == false && VerTag.size() == Ver.size())
1529 break;
1530 }
1531 if (Last != 0 || VerTag.empty() == true)
1532 break;
1533 //if (VerTag.empty() == false && Last == 0)
1534 _error->Error(_("Ignore unavailable version '%s' of package '%s'"), VerTag.c_str(), TmpSrc.c_str());
1535 return 0;
1536 }
1537
1538 if (Last == 0 || Last->Jump(Offset) == false)
1539 return 0;
1540
1541 return Last;
1542}
1543 /*}}}*/
1544// DoUpdate - Update the package lists /*{{{*/
1545// ---------------------------------------------------------------------
1546/* */
1547bool DoUpdate(CommandLine &CmdL)
1548{
1549 if (CmdL.FileSize() != 1)
1550 return _error->Error(_("The update command takes no arguments"));
1551
1552 CacheFile Cache;
1553
1554 // Get the source list
1555 if (Cache.BuildSourceList() == false)
1556 return false;
1557 pkgSourceList *List = Cache.GetSourceList();
1558
1559 // Create the progress
1560 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
1561
1562 // Just print out the uris an exit if the --print-uris flag was used
1563 if (_config->FindB("APT::Get::Print-URIs") == true)
1564 {
1565 // force a hashsum for compatibility reasons
1566 _config->CndSet("Acquire::ForceHash", "md5sum");
1567
1568 // get a fetcher
1569 pkgAcquire Fetcher;
1570 if (Fetcher.Setup(&Stat) == false)
1571 return false;
1572
1573 // Populate it with the source selection and get all Indexes
1574 // (GetAll=true)
1575 if (List->GetIndexes(&Fetcher,true) == false)
1576 return false;
1577
1578 pkgAcquire::UriIterator I = Fetcher.UriBegin();
1579 for (; I != Fetcher.UriEnd(); I++)
1580 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
1581 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
1582 return true;
1583 }
1584
1585 // do the work
1586 if (_config->FindB("APT::Get::Download",true) == true)
1587 ListUpdate(Stat, *List);
1588
1589 // Rebuild the cache.
1590 if (Cache.BuildCaches() == false)
1591 return false;
1592
1593 return true;
1594}
1595 /*}}}*/
1596// DoAutomaticRemove - Remove all automatic unused packages /*{{{*/
1597// ---------------------------------------------------------------------
1598/* Remove unused automatic packages */
1599bool DoAutomaticRemove(CacheFile &Cache)
1600{
1601 bool Debug = _config->FindI("Debug::pkgAutoRemove",false);
1602 bool doAutoRemove = _config->FindB("APT::Get::AutomaticRemove", false);
1603 bool hideAutoRemove = _config->FindB("APT::Get::HideAutoRemove");
1604
1605 pkgDepCache::ActionGroup group(*Cache);
1606 if(Debug)
1607 std::cout << "DoAutomaticRemove()" << std::endl;
1608
1609 // we don't want to autoremove and we don't want to see it, so why calculating?
1610 if (doAutoRemove == false && hideAutoRemove == true)
1611 return true;
1612
1613 if (doAutoRemove == true &&
1614 _config->FindB("APT::Get::Remove",true) == false)
1615 {
1616 c1out << _("We are not supposed to delete stuff, can't start "
1617 "AutoRemover") << std::endl;
1618 return false;
1619 }
1620
1621 bool purgePkgs = _config->FindB("APT::Get::Purge", false);
1622 bool smallList = (hideAutoRemove == false &&
1623 strcasecmp(_config->Find("APT::Get::HideAutoRemove","").c_str(),"small") == 0);
1624
1625 string autoremovelist, autoremoveversions;
1626 unsigned long autoRemoveCount = 0;
1627 // look over the cache to see what can be removed
1628 for (pkgCache::PkgIterator Pkg = Cache->PkgBegin(); ! Pkg.end(); ++Pkg)
1629 {
1630 if (Cache[Pkg].Garbage)
1631 {
1632 if(Pkg.CurrentVer() != 0 || Cache[Pkg].Install())
1633 if(Debug)
1634 std::cout << "We could delete %s" << Pkg.FullName(true).c_str() << std::endl;
1635
1636 if (doAutoRemove)
1637 {
1638 if(Pkg.CurrentVer() != 0 &&
1639 Pkg->CurrentState != pkgCache::State::ConfigFiles)
1640 Cache->MarkDelete(Pkg, purgePkgs);
1641 else
1642 Cache->MarkKeep(Pkg, false, false);
1643 }
1644 else
1645 {
1646 // only show stuff in the list that is not yet marked for removal
1647 if(Cache[Pkg].Delete() == false)
1648 {
1649 ++autoRemoveCount;
1650 // we don't need to fill the strings if we don't need them
1651 if (smallList == false)
1652 {
1653 autoremovelist += Pkg.FullName(true) + " ";
1654 autoremoveversions += string(Cache[Pkg].CandVersion) + "\n";
1655 }
1656 }
1657 }
1658 }
1659 }
1660 // if we don't remove them, we should show them!
1661 if (doAutoRemove == false && (autoremovelist.empty() == false || autoRemoveCount != 0))
1662 {
1663 if (smallList == false)
1664 ShowList(c1out, P_("The following package was automatically installed and is no longer required:",
1665 "The following packages were automatically installed and are no longer required:",
1666 autoRemoveCount), autoremovelist, autoremoveversions);
1667 else
1668 ioprintf(c1out, P_("%lu package was automatically installed and is no longer required.\n",
1669 "%lu packages were automatically installed and are no longer required.\n", autoRemoveCount), autoRemoveCount);
1670 c1out << _("Use 'apt-get autoremove' to remove them.") << std::endl;
1671 }
1672 // Now see if we had destroyed anything (if we had done anything)
1673 else if (Cache->BrokenCount() != 0)
1674 {
1675 c1out << _("Hmm, seems like the AutoRemover destroyed something which really\n"
1676 "shouldn't happen. Please file a bug report against apt.") << endl;
1677 c1out << endl;
1678 c1out << _("The following information may help to resolve the situation:") << endl;
1679 c1out << endl;
1680 ShowBroken(c1out,Cache,false);
1681
1682 return _error->Error(_("Internal Error, AutoRemover broke stuff"));
1683 }
1684 return true;
1685}
1686 /*}}}*/
1687// DoUpgrade - Upgrade all packages /*{{{*/
1688// ---------------------------------------------------------------------
1689/* Upgrade all packages without installing new packages or erasing old
1690 packages */
1691bool DoUpgrade(CommandLine &CmdL)
1692{
1693 CacheFile Cache;
1694 if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
1695 return false;
1696
1697 // Do the upgrade
1698 if (pkgAllUpgrade(Cache) == false)
1699 {
1700 ShowBroken(c1out,Cache,false);
1701 return _error->Error(_("Internal error, AllUpgrade broke stuff"));
1702 }
1703
1704 return InstallPackages(Cache,true);
1705}
1706 /*}}}*/
1707// DoInstall - Install packages from the command line /*{{{*/
1708// ---------------------------------------------------------------------
1709/* Install named packages */
1710bool DoInstall(CommandLine &CmdL)
1711{
1712 CacheFile Cache;
1713 if (Cache.OpenForInstall() == false ||
1714 Cache.CheckDeps(CmdL.FileSize() != 1) == false)
1715 return false;
1716
1717 // Enter the special broken fixing mode if the user specified arguments
1718 bool BrokenFix = false;
1719 if (Cache->BrokenCount() != 0)
1720 BrokenFix = true;
1721
1722 pkgProblemResolver Fix(Cache);
1723
1724 static const unsigned short MOD_REMOVE = 1;
1725 static const unsigned short MOD_INSTALL = 2;
1726
1727 unsigned short fallback = MOD_INSTALL;
1728 if (strcasecmp(CmdL.FileList[0],"remove") == 0)
1729 fallback = MOD_REMOVE;
1730 else if (strcasecmp(CmdL.FileList[0], "purge") == 0)
1731 {
1732 _config->Set("APT::Get::Purge", true);
1733 fallback = MOD_REMOVE;
1734 }
1735 else if (strcasecmp(CmdL.FileList[0], "autoremove") == 0)
1736 {
1737 _config->Set("APT::Get::AutomaticRemove", "true");
1738 fallback = MOD_REMOVE;
1739 }
1740
1741 std::list<APT::VersionSet::Modifier> mods;
1742 mods.push_back(APT::VersionSet::Modifier(MOD_INSTALL, "+",
1743 APT::VersionSet::Modifier::POSTFIX, APT::VersionSet::CANDIDATE));
1744 mods.push_back(APT::VersionSet::Modifier(MOD_REMOVE, "-",
1745 APT::VersionSet::Modifier::POSTFIX, APT::VersionSet::NEWEST));
1746 CacheSetHelperAPTGet helper(c0out);
1747 std::map<unsigned short, APT::VersionSet> verset = APT::VersionSet::GroupedFromCommandLine(Cache,
1748 CmdL.FileList + 1, mods, fallback, helper);
1749
1750 if (_error->PendingError() == true)
1751 {
1752 helper.showVirtualPackageErrors(Cache);
1753 return false;
1754 }
1755
1756 unsigned short order[] = { 0, 0, 0 };
1757 if (fallback == MOD_INSTALL) {
1758 order[0] = MOD_INSTALL;
1759 order[1] = MOD_REMOVE;
1760 } else {
1761 order[0] = MOD_REMOVE;
1762 order[1] = MOD_INSTALL;
1763 }
1764
1765 TryToInstall InstallAction(Cache, Fix, BrokenFix);
1766 TryToRemove RemoveAction(Cache, Fix);
1767
1768 // new scope for the ActionGroup
1769 {
1770 pkgDepCache::ActionGroup group(Cache);
1771
1772 for (unsigned short i = 0; order[i] != 0; ++i)
1773 {
1774 if (order[i] == MOD_INSTALL) {
1775 InstallAction = std::for_each(verset[MOD_INSTALL].begin(), verset[MOD_INSTALL].end(), InstallAction);
1776 InstallAction.doAutoInstall();
1777 }
1778 else if (order[i] == MOD_REMOVE)
1779 RemoveAction = std::for_each(verset[MOD_REMOVE].begin(), verset[MOD_REMOVE].end(), RemoveAction);
1780 }
1781
1782 if (_error->PendingError() == true)
1783 return false;
1784
1785 /* If we are in the Broken fixing mode we do not attempt to fix the
1786 problems. This is if the user invoked install without -f and gave
1787 packages */
1788 if (BrokenFix == true && Cache->BrokenCount() != 0)
1789 {
1790 c1out << _("You might want to run 'apt-get -f install' to correct these:") << endl;
1791 ShowBroken(c1out,Cache,false);
1792
1793 return _error->Error(_("Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution)."));
1794 }
1795
1796 // Call the scored problem resolver
1797 Fix.InstallProtect();
1798 if (Fix.Resolve(true) == false)
1799 _error->Discard();
1800
1801 // Now we check the state of the packages,
1802 if (Cache->BrokenCount() != 0)
1803 {
1804 c1out <<
1805 _("Some packages could not be installed. This may mean that you have\n"
1806 "requested an impossible situation or if you are using the unstable\n"
1807 "distribution that some required packages have not yet been created\n"
1808 "or been moved out of Incoming.") << endl;
1809 /*
1810 if (Packages == 1)
1811 {
1812 c1out << endl;
1813 c1out <<
1814 _("Since you only requested a single operation it is extremely likely that\n"
1815 "the package is simply not installable and a bug report against\n"
1816 "that package should be filed.") << endl;
1817 }
1818 */
1819
1820 c1out << _("The following information may help to resolve the situation:") << endl;
1821 c1out << endl;
1822 ShowBroken(c1out,Cache,false);
1823 return _error->Error(_("Broken packages"));
1824 }
1825 }
1826 if (!DoAutomaticRemove(Cache))
1827 return false;
1828
1829 /* Print out a list of packages that are going to be installed extra
1830 to what the user asked */
1831 if (Cache->InstCount() != verset[MOD_INSTALL].size())
1832 {
1833 string List;
1834 string VersionsList;
1835 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
1836 {
1837 pkgCache::PkgIterator I(Cache,Cache.List[J]);
1838 if ((*Cache)[I].Install() == false)
1839 continue;
1840
1841 const char **J;
1842 for (J = CmdL.FileList + 1; *J != 0; J++)
1843 if (strcmp(*J,I.Name()) == 0)
1844 break;
1845
1846 if (*J == 0) {
1847 List += I.FullName(true) + " ";
1848 VersionsList += string(Cache[I].CandVersion) + "\n";
1849 }
1850 }
1851
1852 ShowList(c1out,_("The following extra packages will be installed:"),List,VersionsList);
1853 }
1854
1855 /* Print out a list of suggested and recommended packages */
1856 {
1857 string SuggestsList, RecommendsList, List;
1858 string SuggestsVersions, RecommendsVersions;
1859 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
1860 {
1861 pkgCache::PkgIterator Pkg(Cache,Cache.List[J]);
1862
1863 /* Just look at the ones we want to install */
1864 if ((*Cache)[Pkg].Install() == false)
1865 continue;
1866
1867 // get the recommends/suggests for the candidate ver
1868 pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
1869 for (pkgCache::DepIterator D = CV.DependsList(); D.end() == false; )
1870 {
1871 pkgCache::DepIterator Start;
1872 pkgCache::DepIterator End;
1873 D.GlobOr(Start,End); // advances D
1874
1875 // FIXME: we really should display a or-group as a or-group to the user
1876 // the problem is that ShowList is incapable of doing this
1877 string RecommendsOrList,RecommendsOrVersions;
1878 string SuggestsOrList,SuggestsOrVersions;
1879 bool foundInstalledInOrGroup = false;
1880 for(;;)
1881 {
1882 /* Skip if package is installed already, or is about to be */
1883 string target = Start.TargetPkg().FullName(true) + " ";
1884 pkgCache::PkgIterator const TarPkg = Start.TargetPkg();
1885 if (TarPkg->SelectedState == pkgCache::State::Install ||
1886 TarPkg->SelectedState == pkgCache::State::Hold ||
1887 Cache[Start.TargetPkg()].Install())
1888 {
1889 foundInstalledInOrGroup=true;
1890 break;
1891 }
1892
1893 /* Skip if we already saw it */
1894 if (int(SuggestsList.find(target)) != -1 || int(RecommendsList.find(target)) != -1)
1895 {
1896 foundInstalledInOrGroup=true;
1897 break;
1898 }
1899
1900 // this is a dep on a virtual pkg, check if any package that provides it
1901 // should be installed
1902 if(Start.TargetPkg().ProvidesList() != 0)
1903 {
1904 pkgCache::PrvIterator I = Start.TargetPkg().ProvidesList();
1905 for (; I.end() == false; I++)
1906 {
1907 pkgCache::PkgIterator Pkg = I.OwnerPkg();
1908 if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer() &&
1909 Pkg.CurrentVer() != 0)
1910 foundInstalledInOrGroup=true;
1911 }
1912 }
1913
1914 if (Start->Type == pkgCache::Dep::Suggests)
1915 {
1916 SuggestsOrList += target;
1917 SuggestsOrVersions += string(Cache[Start.TargetPkg()].CandVersion) + "\n";
1918 }
1919
1920 if (Start->Type == pkgCache::Dep::Recommends)
1921 {
1922 RecommendsOrList += target;
1923 RecommendsOrVersions += string(Cache[Start.TargetPkg()].CandVersion) + "\n";
1924 }
1925
1926 if (Start >= End)
1927 break;
1928 Start++;
1929 }
1930
1931 if(foundInstalledInOrGroup == false)
1932 {
1933 RecommendsList += RecommendsOrList;
1934 RecommendsVersions += RecommendsOrVersions;
1935 SuggestsList += SuggestsOrList;
1936 SuggestsVersions += SuggestsOrVersions;
1937 }
1938
1939 }
1940 }
1941
1942 ShowList(c1out,_("Suggested packages:"),SuggestsList,SuggestsVersions);
1943 ShowList(c1out,_("Recommended packages:"),RecommendsList,RecommendsVersions);
1944
1945 }
1946
1947 // if nothing changed in the cache, but only the automark information
1948 // we write the StateFile here, otherwise it will be written in
1949 // cache.commit()
1950 if (InstallAction.AutoMarkChanged > 0 &&
1951 Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
1952 Cache->BadCount() == 0 &&
1953 _config->FindB("APT::Get::Simulate",false) == false)
1954 Cache->writeStateFile(NULL);
1955
1956 // See if we need to prompt
1957 // FIXME: check if really the packages in the set are going to be installed
1958 if (Cache->InstCount() == verset[MOD_INSTALL].size() && Cache->DelCount() == 0)
1959 return InstallPackages(Cache,false,false);
1960
1961 return InstallPackages(Cache,false);
1962}
1963
1964/* mark packages as automatically/manually installed. */
1965bool DoMarkAuto(CommandLine &CmdL)
1966{
1967 bool Action = true;
1968 int AutoMarkChanged = 0;
1969 OpTextProgress progress;
1970 CacheFile Cache;
1971 if (Cache.Open() == false)
1972 return false;
1973
1974 if (strcasecmp(CmdL.FileList[0],"markauto") == 0)
1975 Action = true;
1976 else if (strcasecmp(CmdL.FileList[0],"unmarkauto") == 0)
1977 Action = false;
1978
1979 for (const char **I = CmdL.FileList + 1; *I != 0; I++)
1980 {
1981 const char *S = *I;
1982 // Locate the package
1983 pkgCache::PkgIterator Pkg = Cache->FindPkg(S);
1984 if (Pkg.end() == true) {
1985 return _error->Error(_("Couldn't find package %s"),S);
1986 }
1987 else
1988 {
1989 if (!Action)
1990 ioprintf(c1out,_("%s set to manually installed.\n"), Pkg.Name());
1991 else
1992 ioprintf(c1out,_("%s set to automatically installed.\n"),
1993 Pkg.Name());
1994
1995 Cache->MarkAuto(Pkg,Action);
1996 AutoMarkChanged++;
1997 }
1998 }
1999 if (AutoMarkChanged && ! _config->FindB("APT::Get::Simulate",false))
2000 return Cache->writeStateFile(NULL);
2001 return false;
2002}
2003 /*}}}*/
2004// DoDistUpgrade - Automatic smart upgrader /*{{{*/
2005// ---------------------------------------------------------------------
2006/* Intelligent upgrader that will install and remove packages at will */
2007bool DoDistUpgrade(CommandLine &CmdL)
2008{
2009 CacheFile Cache;
2010 if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
2011 return false;
2012
2013 c0out << _("Calculating upgrade... ") << flush;
2014 if (pkgDistUpgrade(*Cache) == false)
2015 {
2016 c0out << _("Failed") << endl;
2017 ShowBroken(c1out,Cache,false);
2018 return false;
2019 }
2020
2021 c0out << _("Done") << endl;
2022
2023 return InstallPackages(Cache,true);
2024}
2025 /*}}}*/
2026// DoDSelectUpgrade - Do an upgrade by following dselects selections /*{{{*/
2027// ---------------------------------------------------------------------
2028/* Follows dselect's selections */
2029bool DoDSelectUpgrade(CommandLine &CmdL)
2030{
2031 CacheFile Cache;
2032 if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
2033 return false;
2034
2035 pkgDepCache::ActionGroup group(Cache);
2036
2037 // Install everything with the install flag set
2038 pkgCache::PkgIterator I = Cache->PkgBegin();
2039 for (;I.end() != true; I++)
2040 {
2041 /* Install the package only if it is a new install, the autoupgrader
2042 will deal with the rest */
2043 if (I->SelectedState == pkgCache::State::Install)
2044 Cache->MarkInstall(I,false);
2045 }
2046
2047 /* Now install their deps too, if we do this above then order of
2048 the status file is significant for | groups */
2049 for (I = Cache->PkgBegin();I.end() != true; I++)
2050 {
2051 /* Install the package only if it is a new install, the autoupgrader
2052 will deal with the rest */
2053 if (I->SelectedState == pkgCache::State::Install)
2054 Cache->MarkInstall(I,true);
2055 }
2056
2057 // Apply erasures now, they override everything else.
2058 for (I = Cache->PkgBegin();I.end() != true; I++)
2059 {
2060 // Remove packages
2061 if (I->SelectedState == pkgCache::State::DeInstall ||
2062 I->SelectedState == pkgCache::State::Purge)
2063 Cache->MarkDelete(I,I->SelectedState == pkgCache::State::Purge);
2064 }
2065
2066 /* Resolve any problems that dselect created, allupgrade cannot handle
2067 such things. We do so quite agressively too.. */
2068 if (Cache->BrokenCount() != 0)
2069 {
2070 pkgProblemResolver Fix(Cache);
2071
2072 // Hold back held packages.
2073 if (_config->FindB("APT::Ignore-Hold",false) == false)
2074 {
2075 for (pkgCache::PkgIterator I = Cache->PkgBegin(); I.end() == false; I++)
2076 {
2077 if (I->SelectedState == pkgCache::State::Hold)
2078 {
2079 Fix.Protect(I);
2080 Cache->MarkKeep(I);
2081 }
2082 }
2083 }
2084
2085 if (Fix.Resolve() == false)
2086 {
2087 ShowBroken(c1out,Cache,false);
2088 return _error->Error(_("Internal error, problem resolver broke stuff"));
2089 }
2090 }
2091
2092 // Now upgrade everything
2093 if (pkgAllUpgrade(Cache) == false)
2094 {
2095 ShowBroken(c1out,Cache,false);
2096 return _error->Error(_("Internal error, problem resolver broke stuff"));
2097 }
2098
2099 return InstallPackages(Cache,false);
2100}
2101 /*}}}*/
2102// DoClean - Remove download archives /*{{{*/
2103// ---------------------------------------------------------------------
2104/* */
2105bool DoClean(CommandLine &CmdL)
2106{
2107 if (_config->FindB("APT::Get::Simulate") == true)
2108 {
2109 cout << "Del " << _config->FindDir("Dir::Cache::archives") << "* " <<
2110 _config->FindDir("Dir::Cache::archives") << "partial/*" << endl;
2111 return true;
2112 }
2113
2114 // Lock the archive directory
2115 FileFd Lock;
2116 if (_config->FindB("Debug::NoLocking",false) == false)
2117 {
2118 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
2119 if (_error->PendingError() == true)
2120 return _error->Error(_("Unable to lock the download directory"));
2121 }
2122
2123 pkgAcquire Fetcher;
2124 Fetcher.Clean(_config->FindDir("Dir::Cache::archives"));
2125 Fetcher.Clean(_config->FindDir("Dir::Cache::archives") + "partial/");
2126 return true;
2127}
2128 /*}}}*/
2129// DoAutoClean - Smartly remove downloaded archives /*{{{*/
2130// ---------------------------------------------------------------------
2131/* This is similar to clean but it only purges things that cannot be
2132 downloaded, that is old versions of cached packages. */
2133class LogCleaner : public pkgArchiveCleaner
2134{
2135 protected:
2136 virtual void Erase(const char *File,string Pkg,string Ver,struct stat &St)
2137 {
2138 c1out << "Del " << Pkg << " " << Ver << " [" << SizeToStr(St.st_size) << "B]" << endl;
2139
2140 if (_config->FindB("APT::Get::Simulate") == false)
2141 unlink(File);
2142 };
2143};
2144
2145bool DoAutoClean(CommandLine &CmdL)
2146{
2147 // Lock the archive directory
2148 FileFd Lock;
2149 if (_config->FindB("Debug::NoLocking",false) == false)
2150 {
2151 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
2152 if (_error->PendingError() == true)
2153 return _error->Error(_("Unable to lock the download directory"));
2154 }
2155
2156 CacheFile Cache;
2157 if (Cache.Open() == false)
2158 return false;
2159
2160 LogCleaner Cleaner;
2161
2162 return Cleaner.Go(_config->FindDir("Dir::Cache::archives"),*Cache) &&
2163 Cleaner.Go(_config->FindDir("Dir::Cache::archives") + "partial/",*Cache);
2164}
2165 /*}}}*/
2166// DoCheck - Perform the check operation /*{{{*/
2167// ---------------------------------------------------------------------
2168/* Opening automatically checks the system, this command is mostly used
2169 for debugging */
2170bool DoCheck(CommandLine &CmdL)
2171{
2172 CacheFile Cache;
2173 Cache.Open();
2174 Cache.CheckDeps();
2175
2176 return true;
2177}
2178 /*}}}*/
2179// DoSource - Fetch a source archive /*{{{*/
2180// ---------------------------------------------------------------------
2181/* Fetch souce packages */
2182struct DscFile
2183{
2184 string Package;
2185 string Version;
2186 string Dsc;
2187};
2188
2189bool DoSource(CommandLine &CmdL)
2190{
2191 CacheFile Cache;
2192 if (Cache.Open(false) == false)
2193 return false;
2194
2195 if (CmdL.FileSize() <= 1)
2196 return _error->Error(_("Must specify at least one package to fetch source for"));
2197
2198 // Read the source list
2199 if (Cache.BuildSourceList() == false)
2200 return false;
2201 pkgSourceList *List = Cache.GetSourceList();
2202
2203 // Create the text record parsers
2204 pkgRecords Recs(Cache);
2205 pkgSrcRecords SrcRecs(*List);
2206 if (_error->PendingError() == true)
2207 return false;
2208
2209 // Create the download object
2210 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
2211 pkgAcquire Fetcher;
2212 if (Fetcher.Setup(&Stat) == false)
2213 return false;
2214
2215 DscFile *Dsc = new DscFile[CmdL.FileSize()];
2216
2217 // insert all downloaded uris into this set to avoid downloading them
2218 // twice
2219 set<string> queued;
2220
2221 // Diff only mode only fetches .diff files
2222 bool const diffOnly = _config->FindB("APT::Get::Diff-Only", false);
2223 // Tar only mode only fetches .tar files
2224 bool const tarOnly = _config->FindB("APT::Get::Tar-Only", false);
2225 // Dsc only mode only fetches .dsc files
2226 bool const dscOnly = _config->FindB("APT::Get::Dsc-Only", false);
2227
2228 // Load the requestd sources into the fetcher
2229 unsigned J = 0;
2230 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
2231 {
2232 string Src;
2233 pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,*Cache);
2234
2235 if (Last == 0)
2236 return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
2237
2238 string srec = Last->AsStr();
2239 string::size_type pos = srec.find("\nVcs-");
2240 while (pos != string::npos)
2241 {
2242 pos += strlen("\nVcs-");
2243 string vcs = srec.substr(pos,srec.find(":",pos)-pos);
2244 if(vcs == "Browser")
2245 {
2246 pos = srec.find("\nVcs-", pos);
2247 continue;
2248 }
2249 pos += vcs.length()+2;
2250 string::size_type epos = srec.find("\n", pos);
2251 string uri = srec.substr(pos,epos-pos).c_str();
2252 ioprintf(c1out, _("NOTICE: '%s' packaging is maintained in "
2253 "the '%s' version control system at:\n"
2254 "%s\n"),
2255 Src.c_str(), vcs.c_str(), uri.c_str());
2256 if(vcs == "Bzr")
2257 ioprintf(c1out,_("Please use:\n"
2258 "bzr get %s\n"
2259 "to retrieve the latest (possibly unreleased) "
2260 "updates to the package.\n"),
2261 uri.c_str());
2262 break;
2263 }
2264
2265 // Back track
2266 vector<pkgSrcRecords::File> Lst;
2267 if (Last->Files(Lst) == false)
2268 return false;
2269
2270 // Load them into the fetcher
2271 for (vector<pkgSrcRecords::File>::const_iterator I = Lst.begin();
2272 I != Lst.end(); I++)
2273 {
2274 // Try to guess what sort of file it is we are getting.
2275 if (I->Type == "dsc")
2276 {
2277 Dsc[J].Package = Last->Package();
2278 Dsc[J].Version = Last->Version();
2279 Dsc[J].Dsc = flNotDir(I->Path);
2280 }
2281
2282 // Handle the only options so that multiple can be used at once
2283 if (diffOnly == true || tarOnly == true || dscOnly == true)
2284 {
2285 if ((diffOnly == true && I->Type == "diff") ||
2286 (tarOnly == true && I->Type == "tar") ||
2287 (dscOnly == true && I->Type == "dsc"))
2288 ; // Fine, we want this file downloaded
2289 else
2290 continue;
2291 }
2292
2293 // don't download the same uri twice (should this be moved to
2294 // the fetcher interface itself?)
2295 if(queued.find(Last->Index().ArchiveURI(I->Path)) != queued.end())
2296 continue;
2297 queued.insert(Last->Index().ArchiveURI(I->Path));
2298
2299 // check if we have a file with that md5 sum already localy
2300 if(!I->MD5Hash.empty() && FileExists(flNotDir(I->Path)))
2301 {
2302 FileFd Fd(flNotDir(I->Path), FileFd::ReadOnly);
2303 MD5Summation sum;
2304 sum.AddFD(Fd.Fd(), Fd.Size());
2305 Fd.Close();
2306 if((string)sum.Result() == I->MD5Hash)
2307 {
2308 ioprintf(c1out,_("Skipping already downloaded file '%s'\n"),
2309 flNotDir(I->Path).c_str());
2310 continue;
2311 }
2312 }
2313
2314 new pkgAcqFile(&Fetcher,Last->Index().ArchiveURI(I->Path),
2315 I->MD5Hash,I->Size,
2316 Last->Index().SourceInfo(*Last,*I),Src);
2317 }
2318 }
2319
2320 // Display statistics
2321 unsigned long long FetchBytes = Fetcher.FetchNeeded();
2322 unsigned long long FetchPBytes = Fetcher.PartialPresent();
2323 unsigned long long DebBytes = Fetcher.TotalNeeded();
2324
2325 // Check for enough free space
2326 struct statvfs Buf;
2327 string OutputDir = ".";
2328 if (statvfs(OutputDir.c_str(),&Buf) != 0) {
2329 if (errno == EOVERFLOW)
2330 return _error->WarningE("statvfs",_("Couldn't determine free space in %s"),
2331 OutputDir.c_str());
2332 else
2333 return _error->Errno("statvfs",_("Couldn't determine free space in %s"),
2334 OutputDir.c_str());
2335 } else if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
2336 {
2337 struct statfs Stat;
2338 if (statfs(OutputDir.c_str(),&Stat) != 0
2339#if HAVE_STRUCT_STATFS_F_TYPE
2340 || unsigned(Stat.f_type) != RAMFS_MAGIC
2341#endif
2342 )
2343 return _error->Error(_("You don't have enough free space in %s"),
2344 OutputDir.c_str());
2345 }
2346
2347 // Number of bytes
2348 if (DebBytes != FetchBytes)
2349 //TRANSLATOR: The required space between number and unit is already included
2350 // in the replacement strings, so %sB will be correctly translate in e.g. 1,5 MB
2351 ioprintf(c1out,_("Need to get %sB/%sB of source archives.\n"),
2352 SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
2353 else
2354 //TRANSLATOR: The required space between number and unit is already included
2355 // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
2356 ioprintf(c1out,_("Need to get %sB of source archives.\n"),
2357 SizeToStr(DebBytes).c_str());
2358
2359 if (_config->FindB("APT::Get::Simulate",false) == true)
2360 {
2361 for (unsigned I = 0; I != J; I++)
2362 ioprintf(cout,_("Fetch source %s\n"),Dsc[I].Package.c_str());
2363 delete[] Dsc;
2364 return true;
2365 }
2366
2367 // Just print out the uris an exit if the --print-uris flag was used
2368 if (_config->FindB("APT::Get::Print-URIs") == true)
2369 {
2370 pkgAcquire::UriIterator I = Fetcher.UriBegin();
2371 for (; I != Fetcher.UriEnd(); I++)
2372 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
2373 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
2374 delete[] Dsc;
2375 return true;
2376 }
2377
2378 // Run it
2379 if (Fetcher.Run() == pkgAcquire::Failed)
2380 return false;
2381
2382 // Print error messages
2383 bool Failed = false;
2384 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
2385 {
2386 if ((*I)->Status == pkgAcquire::Item::StatDone &&
2387 (*I)->Complete == true)
2388 continue;
2389
2390 fprintf(stderr,_("Failed to fetch %s %s\n"),(*I)->DescURI().c_str(),
2391 (*I)->ErrorText.c_str());
2392 Failed = true;
2393 }
2394 if (Failed == true)
2395 return _error->Error(_("Failed to fetch some archives."));
2396
2397 if (_config->FindB("APT::Get::Download-only",false) == true)
2398 {
2399 c1out << _("Download complete and in download only mode") << endl;
2400 delete[] Dsc;
2401 return true;
2402 }
2403
2404 // Unpack the sources
2405 pid_t Process = ExecFork();
2406
2407 if (Process == 0)
2408 {
2409 bool const fixBroken = _config->FindB("APT::Get::Fix-Broken", false);
2410 for (unsigned I = 0; I != J; I++)
2411 {
2412 string Dir = Dsc[I].Package + '-' + Cache->VS().UpstreamVersion(Dsc[I].Version.c_str());
2413
2414 // Diff only mode only fetches .diff files
2415 if (_config->FindB("APT::Get::Diff-Only",false) == true ||
2416 _config->FindB("APT::Get::Tar-Only",false) == true ||
2417 Dsc[I].Dsc.empty() == true)
2418 continue;
2419
2420 // See if the package is already unpacked
2421 struct stat Stat;
2422 if (fixBroken == false && stat(Dir.c_str(),&Stat) == 0 &&
2423 S_ISDIR(Stat.st_mode) != 0)
2424 {
2425 ioprintf(c0out ,_("Skipping unpack of already unpacked source in %s\n"),
2426 Dir.c_str());
2427 }
2428 else
2429 {
2430 // Call dpkg-source
2431 char S[500];
2432 snprintf(S,sizeof(S),"%s -x %s",
2433 _config->Find("Dir::Bin::dpkg-source","dpkg-source").c_str(),
2434 Dsc[I].Dsc.c_str());
2435 if (system(S) != 0)
2436 {
2437 fprintf(stderr,_("Unpack command '%s' failed.\n"),S);
2438 fprintf(stderr,_("Check if the 'dpkg-dev' package is installed.\n"));
2439 _exit(1);
2440 }
2441 }
2442
2443 // Try to compile it with dpkg-buildpackage
2444 if (_config->FindB("APT::Get::Compile",false) == true)
2445 {
2446 // Call dpkg-buildpackage
2447 char S[500];
2448 snprintf(S,sizeof(S),"cd %s && %s %s",
2449 Dir.c_str(),
2450 _config->Find("Dir::Bin::dpkg-buildpackage","dpkg-buildpackage").c_str(),
2451 _config->Find("DPkg::Build-Options","-b -uc").c_str());
2452
2453 if (system(S) != 0)
2454 {
2455 fprintf(stderr,_("Build command '%s' failed.\n"),S);
2456 _exit(1);
2457 }
2458 }
2459 }
2460
2461 _exit(0);
2462 }
2463 delete[] Dsc;
2464
2465 // Wait for the subprocess
2466 int Status = 0;
2467 while (waitpid(Process,&Status,0) != Process)
2468 {
2469 if (errno == EINTR)
2470 continue;
2471 return _error->Errno("waitpid","Couldn't wait for subprocess");
2472 }
2473
2474 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
2475 return _error->Error(_("Child process failed"));
2476
2477 return true;
2478}
2479 /*}}}*/
2480// DoBuildDep - Install/removes packages to satisfy build dependencies /*{{{*/
2481// ---------------------------------------------------------------------
2482/* This function will look at the build depends list of the given source
2483 package and install the necessary packages to make it true, or fail. */
2484bool DoBuildDep(CommandLine &CmdL)
2485{
2486 CacheFile Cache;
2487 if (Cache.Open(true) == false)
2488 return false;
2489
2490 if (CmdL.FileSize() <= 1)
2491 return _error->Error(_("Must specify at least one package to check builddeps for"));
2492
2493 // Read the source list
2494 if (Cache.BuildSourceList() == false)
2495 return false;
2496 pkgSourceList *List = Cache.GetSourceList();
2497
2498 // Create the text record parsers
2499 pkgRecords Recs(Cache);
2500 pkgSrcRecords SrcRecs(*List);
2501 if (_error->PendingError() == true)
2502 return false;
2503
2504 // Create the download object
2505 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
2506 pkgAcquire Fetcher;
2507 if (Fetcher.Setup(&Stat) == false)
2508 return false;
2509
2510 unsigned J = 0;
2511 bool const StripMultiArch = APT::Configuration::getArchitectures().size() <= 1;
2512 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
2513 {
2514 string Src;
2515 pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,*Cache);
2516 if (Last == 0)
2517 return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
2518
2519 // Process the build-dependencies
2520 vector<pkgSrcRecords::Parser::BuildDepRec> BuildDeps;
2521 if (Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only", false), StripMultiArch) == false)
2522 return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
2523
2524 // Also ensure that build-essential packages are present
2525 Configuration::Item const *Opts = _config->Tree("APT::Build-Essential");
2526 if (Opts)
2527 Opts = Opts->Child;
2528 for (; Opts; Opts = Opts->Next)
2529 {
2530 if (Opts->Value.empty() == true)
2531 continue;
2532
2533 pkgSrcRecords::Parser::BuildDepRec rec;
2534 rec.Package = Opts->Value;
2535 rec.Type = pkgSrcRecords::Parser::BuildDependIndep;
2536 rec.Op = 0;
2537 BuildDeps.push_back(rec);
2538 }
2539
2540 if (BuildDeps.size() == 0)
2541 {
2542 ioprintf(c1out,_("%s has no build depends.\n"),Src.c_str());
2543 continue;
2544 }
2545
2546 // Install the requested packages
2547 vector <pkgSrcRecords::Parser::BuildDepRec>::iterator D;
2548 pkgProblemResolver Fix(Cache);
2549 bool skipAlternatives = false; // skip remaining alternatives in an or group
2550 for (D = BuildDeps.begin(); D != BuildDeps.end(); D++)
2551 {
2552 bool hasAlternatives = (((*D).Op & pkgCache::Dep::Or) == pkgCache::Dep::Or);
2553
2554 if (skipAlternatives == true)
2555 {
2556 if (!hasAlternatives)
2557 skipAlternatives = false; // end of or group
2558 continue;
2559 }
2560
2561 if ((*D).Type == pkgSrcRecords::Parser::BuildConflict ||
2562 (*D).Type == pkgSrcRecords::Parser::BuildConflictIndep)
2563 {
2564 pkgCache::PkgIterator Pkg = Cache->FindPkg((*D).Package);
2565 // Build-conflicts on unknown packages are silently ignored
2566 if (Pkg.end() == true)
2567 continue;
2568
2569 pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
2570
2571 /*
2572 * Remove if we have an installed version that satisfies the
2573 * version criteria
2574 */
2575 if (IV.end() == false &&
2576 Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
2577 TryToInstallBuildDep(Pkg,Cache,Fix,true,false);
2578 }
2579 else // BuildDep || BuildDepIndep
2580 {
2581 pkgCache::PkgIterator Pkg = Cache->FindPkg((*D).Package);
2582 if (_config->FindB("Debug::BuildDeps",false) == true)
2583 cout << "Looking for " << (*D).Package << "...\n";
2584
2585 if (Pkg.end() == true)
2586 {
2587 if (_config->FindB("Debug::BuildDeps",false) == true)
2588 cout << " (not found)" << (*D).Package << endl;
2589
2590 if (hasAlternatives)
2591 continue;
2592
2593 return _error->Error(_("%s dependency for %s cannot be satisfied "
2594 "because the package %s cannot be found"),
2595 Last->BuildDepType((*D).Type),Src.c_str(),
2596 (*D).Package.c_str());
2597 }
2598
2599 /*
2600 * if there are alternatives, we've already picked one, so skip
2601 * the rest
2602 *
2603 * TODO: this means that if there's a build-dep on A|B and B is
2604 * installed, we'll still try to install A; more importantly,
2605 * if A is currently broken, we cannot go back and try B. To fix
2606 * this would require we do a Resolve cycle for each package we
2607 * add to the install list. Ugh
2608 */
2609
2610 /*
2611 * If this is a virtual package, we need to check the list of
2612 * packages that provide it and see if any of those are
2613 * installed
2614 */
2615 pkgCache::PrvIterator Prv = Pkg.ProvidesList();
2616 for (; Prv.end() != true; Prv++)
2617 {
2618 if (_config->FindB("Debug::BuildDeps",false) == true)
2619 cout << " Checking provider " << Prv.OwnerPkg().FullName() << endl;
2620
2621 if ((*Cache)[Prv.OwnerPkg()].InstVerIter(*Cache).end() == false)
2622 break;
2623 }
2624
2625 // Get installed version and version we are going to install
2626 pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
2627
2628 if ((*D).Version[0] != '\0') {
2629 // Versioned dependency
2630
2631 pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
2632
2633 for (; CV.end() != true; CV++)
2634 {
2635 if (Cache->VS().CheckDep(CV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
2636 break;
2637 }
2638 if (CV.end() == true)
2639 {
2640 if (hasAlternatives)
2641 {
2642 continue;
2643 }
2644 else
2645 {
2646 return _error->Error(_("%s dependency for %s cannot be satisfied "
2647 "because no available versions of package %s "
2648 "can satisfy version requirements"),
2649 Last->BuildDepType((*D).Type),Src.c_str(),
2650 (*D).Package.c_str());
2651 }
2652 }
2653 }
2654 else
2655 {
2656 // Only consider virtual packages if there is no versioned dependency
2657 if (Prv.end() == false)
2658 {
2659 if (_config->FindB("Debug::BuildDeps",false) == true)
2660 cout << " Is provided by installed package " << Prv.OwnerPkg().FullName() << endl;
2661 skipAlternatives = hasAlternatives;
2662 continue;
2663 }
2664 }
2665
2666 if (IV.end() == false)
2667 {
2668 if (_config->FindB("Debug::BuildDeps",false) == true)
2669 cout << " Is installed\n";
2670
2671 if (Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
2672 {
2673 skipAlternatives = hasAlternatives;
2674 continue;
2675 }
2676
2677 if (_config->FindB("Debug::BuildDeps",false) == true)
2678 cout << " ...but the installed version doesn't meet the version requirement\n";
2679
2680 if (((*D).Op & pkgCache::Dep::LessEq) == pkgCache::Dep::LessEq)
2681 {
2682 return _error->Error(_("Failed to satisfy %s dependency for %s: Installed package %s is too new"),
2683 Last->BuildDepType((*D).Type),
2684 Src.c_str(),
2685 Pkg.FullName(true).c_str());
2686 }
2687 }
2688
2689
2690 if (_config->FindB("Debug::BuildDeps",false) == true)
2691 cout << " Trying to install " << (*D).Package << endl;
2692
2693 if (TryToInstallBuildDep(Pkg,Cache,Fix,false,false) == true)
2694 {
2695 // We successfully installed something; skip remaining alternatives
2696 skipAlternatives = hasAlternatives;
2697 if(_config->FindB("APT::Get::Build-Dep-Automatic", false) == true)
2698 Cache->MarkAuto(Pkg, true);
2699 continue;
2700 }
2701 else if (hasAlternatives)
2702 {
2703 if (_config->FindB("Debug::BuildDeps",false) == true)
2704 cout << " Unsatisfiable, trying alternatives\n";
2705 continue;
2706 }
2707 else
2708 {
2709 return _error->Error(_("Failed to satisfy %s dependency for %s: %s"),
2710 Last->BuildDepType((*D).Type),
2711 Src.c_str(),
2712 (*D).Package.c_str());
2713 }
2714 }
2715 }
2716
2717 Fix.InstallProtect();
2718 if (Fix.Resolve(true) == false)
2719 _error->Discard();
2720
2721 // Now we check the state of the packages,
2722 if (Cache->BrokenCount() != 0)
2723 {
2724 ShowBroken(cout, Cache, false);
2725 return _error->Error(_("Build-dependencies for %s could not be satisfied."),*I);
2726 }
2727 }
2728
2729 if (InstallPackages(Cache, false, true) == false)
2730 return _error->Error(_("Failed to process build dependencies"));
2731 return true;
2732}
2733 /*}}}*/
2734// DoMoo - Never Ask, Never Tell /*{{{*/
2735// ---------------------------------------------------------------------
2736/* */
2737bool DoMoo(CommandLine &CmdL)
2738{
2739 cout <<
2740 " (__) \n"
2741 " (oo) \n"
2742 " /------\\/ \n"
2743 " / | || \n"
2744 " * /\\---/\\ \n"
2745 " ~~ ~~ \n"
2746 "....\"Have you mooed today?\"...\n";
2747
2748 return true;
2749}
2750 /*}}}*/
2751// ShowHelp - Show a help screen /*{{{*/
2752// ---------------------------------------------------------------------
2753/* */
2754bool ShowHelp(CommandLine &CmdL)
2755{
2756 ioprintf(cout,_("%s %s for %s compiled on %s %s\n"),PACKAGE,VERSION,
2757 COMMON_ARCH,__DATE__,__TIME__);
2758
2759 if (_config->FindB("version") == true)
2760 {
2761 cout << _("Supported modules:") << endl;
2762
2763 for (unsigned I = 0; I != pkgVersioningSystem::GlobalListLen; I++)
2764 {
2765 pkgVersioningSystem *VS = pkgVersioningSystem::GlobalList[I];
2766 if (_system != 0 && _system->VS == VS)
2767 cout << '*';
2768 else
2769 cout << ' ';
2770 cout << "Ver: " << VS->Label << endl;
2771
2772 /* Print out all the packaging systems that will work with
2773 this VS */
2774 for (unsigned J = 0; J != pkgSystem::GlobalListLen; J++)
2775 {
2776 pkgSystem *Sys = pkgSystem::GlobalList[J];
2777 if (_system == Sys)
2778 cout << '*';
2779 else
2780 cout << ' ';
2781 if (Sys->VS->TestCompatibility(*VS) == true)
2782 cout << "Pkg: " << Sys->Label << " (Priority " << Sys->Score(*_config) << ")" << endl;
2783 }
2784 }
2785
2786 for (unsigned I = 0; I != pkgSourceList::Type::GlobalListLen; I++)
2787 {
2788 pkgSourceList::Type *Type = pkgSourceList::Type::GlobalList[I];
2789 cout << " S.L: '" << Type->Name << "' " << Type->Label << endl;
2790 }
2791
2792 for (unsigned I = 0; I != pkgIndexFile::Type::GlobalListLen; I++)
2793 {
2794 pkgIndexFile::Type *Type = pkgIndexFile::Type::GlobalList[I];
2795 cout << " Idx: " << Type->Label << endl;
2796 }
2797
2798 return true;
2799 }
2800
2801 cout <<
2802 _("Usage: apt-get [options] command\n"
2803 " apt-get [options] install|remove pkg1 [pkg2 ...]\n"
2804 " apt-get [options] source pkg1 [pkg2 ...]\n"
2805 "\n"
2806 "apt-get is a simple command line interface for downloading and\n"
2807 "installing packages. The most frequently used commands are update\n"
2808 "and install.\n"
2809 "\n"
2810 "Commands:\n"
2811 " update - Retrieve new lists of packages\n"
2812 " upgrade - Perform an upgrade\n"
2813 " install - Install new packages (pkg is libc6 not libc6.deb)\n"
2814 " remove - Remove packages\n"
2815 " autoremove - Remove automatically all unused packages\n"
2816 " purge - Remove packages and config files\n"
2817 " source - Download source archives\n"
2818 " build-dep - Configure build-dependencies for source packages\n"
2819 " dist-upgrade - Distribution upgrade, see apt-get(8)\n"
2820 " dselect-upgrade - Follow dselect selections\n"
2821 " clean - Erase downloaded archive files\n"
2822 " autoclean - Erase old downloaded archive files\n"
2823 " check - Verify that there are no broken dependencies\n"
2824 " markauto - Mark the given packages as automatically installed\n"
2825 " unmarkauto - Mark the given packages as manually installed\n"
2826 "\n"
2827 "Options:\n"
2828 " -h This help text.\n"
2829 " -q Loggable output - no progress indicator\n"
2830 " -qq No output except for errors\n"
2831 " -d Download only - do NOT install or unpack archives\n"
2832 " -s No-act. Perform ordering simulation\n"
2833 " -y Assume Yes to all queries and do not prompt\n"
2834 " -f Attempt to correct a system with broken dependencies in place\n"
2835 " -m Attempt to continue if archives are unlocatable\n"
2836 " -u Show a list of upgraded packages as well\n"
2837 " -b Build the source package after fetching it\n"
2838 " -V Show verbose version numbers\n"
2839 " -c=? Read this configuration file\n"
2840 " -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp\n"
2841 "See the apt-get(8), sources.list(5) and apt.conf(5) manual\n"
2842 "pages for more information and options.\n"
2843 " This APT has Super Cow Powers.\n");
2844 return true;
2845}
2846 /*}}}*/
2847// SigWinch - Window size change signal handler /*{{{*/
2848// ---------------------------------------------------------------------
2849/* */
2850void SigWinch(int)
2851{
2852 // Riped from GNU ls
2853#ifdef TIOCGWINSZ
2854 struct winsize ws;
2855
2856 if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col >= 5)
2857 ScreenWidth = ws.ws_col - 1;
2858#endif
2859}
2860 /*}}}*/
2861int main(int argc,const char *argv[]) /*{{{*/
2862{
2863 CommandLine::Args Args[] = {
2864 {'h',"help","help",0},
2865 {'v',"version","version",0},
2866 {'V',"verbose-versions","APT::Get::Show-Versions",0},
2867 {'q',"quiet","quiet",CommandLine::IntLevel},
2868 {'q',"silent","quiet",CommandLine::IntLevel},
2869 {'d',"download-only","APT::Get::Download-Only",0},
2870 {'b',"compile","APT::Get::Compile",0},
2871 {'b',"build","APT::Get::Compile",0},
2872 {'s',"simulate","APT::Get::Simulate",0},
2873 {'s',"just-print","APT::Get::Simulate",0},
2874 {'s',"recon","APT::Get::Simulate",0},
2875 {'s',"dry-run","APT::Get::Simulate",0},
2876 {'s',"no-act","APT::Get::Simulate",0},
2877 {'y',"yes","APT::Get::Assume-Yes",0},
2878 {'y',"assume-yes","APT::Get::Assume-Yes",0},
2879 {'f',"fix-broken","APT::Get::Fix-Broken",0},
2880 {'u',"show-upgraded","APT::Get::Show-Upgraded",0},
2881 {'m',"ignore-missing","APT::Get::Fix-Missing",0},
2882 {'t',"target-release","APT::Default-Release",CommandLine::HasArg},
2883 {'t',"default-release","APT::Default-Release",CommandLine::HasArg},
2884 {0,"download","APT::Get::Download",0},
2885 {0,"fix-missing","APT::Get::Fix-Missing",0},
2886 {0,"ignore-hold","APT::Ignore-Hold",0},
2887 {0,"upgrade","APT::Get::upgrade",0},
2888 {0,"only-upgrade","APT::Get::Only-Upgrade",0},
2889 {0,"force-yes","APT::Get::force-yes",0},
2890 {0,"print-uris","APT::Get::Print-URIs",0},
2891 {0,"diff-only","APT::Get::Diff-Only",0},
2892 {0,"debian-only","APT::Get::Diff-Only",0},
2893 {0,"tar-only","APT::Get::Tar-Only",0},
2894 {0,"dsc-only","APT::Get::Dsc-Only",0},
2895 {0,"purge","APT::Get::Purge",0},
2896 {0,"list-cleanup","APT::Get::List-Cleanup",0},
2897 {0,"reinstall","APT::Get::ReInstall",0},
2898 {0,"trivial-only","APT::Get::Trivial-Only",0},
2899 {0,"remove","APT::Get::Remove",0},
2900 {0,"only-source","APT::Get::Only-Source",0},
2901 {0,"arch-only","APT::Get::Arch-Only",0},
2902 {0,"auto-remove","APT::Get::AutomaticRemove",0},
2903 {0,"allow-unauthenticated","APT::Get::AllowUnauthenticated",0},
2904 {0,"install-recommends","APT::Install-Recommends",CommandLine::Boolean},
2905 {0,"fix-policy","APT::Get::Fix-Policy-Broken",0},
2906 {'c',"config-file",0,CommandLine::ConfigFile},
2907 {'o',"option",0,CommandLine::ArbItem},
2908 {0,0,0,0}};
2909 CommandLine::Dispatch Cmds[] = {{"update",&DoUpdate},
2910 {"upgrade",&DoUpgrade},
2911 {"install",&DoInstall},
2912 {"remove",&DoInstall},
2913 {"purge",&DoInstall},
2914 {"autoremove",&DoInstall},
2915 {"markauto",&DoMarkAuto},
2916 {"unmarkauto",&DoMarkAuto},
2917 {"dist-upgrade",&DoDistUpgrade},
2918 {"dselect-upgrade",&DoDSelectUpgrade},
2919 {"build-dep",&DoBuildDep},
2920 {"clean",&DoClean},
2921 {"autoclean",&DoAutoClean},
2922 {"check",&DoCheck},
2923 {"source",&DoSource},
2924 {"moo",&DoMoo},
2925 {"help",&ShowHelp},
2926 {0,0}};
2927
2928 // Set up gettext support
2929 setlocale(LC_ALL,"");
2930 textdomain(PACKAGE);
2931
2932 // Parse the command line and initialize the package library
2933 CommandLine CmdL(Args,_config);
2934 if (pkgInitConfig(*_config) == false ||
2935 CmdL.Parse(argc,argv) == false ||
2936 pkgInitSystem(*_config,_system) == false)
2937 {
2938 if (_config->FindB("version") == true)
2939 ShowHelp(CmdL);
2940
2941 _error->DumpErrors();
2942 return 100;
2943 }
2944
2945 // See if the help should be shown
2946 if (_config->FindB("help") == true ||
2947 _config->FindB("version") == true ||
2948 CmdL.FileSize() == 0)
2949 {
2950 ShowHelp(CmdL);
2951 return 0;
2952 }
2953
2954 // simulate user-friendly if apt-get has no root privileges
2955 if (getuid() != 0 && _config->FindB("APT::Get::Simulate") == true)
2956 {
2957 if (_config->FindB("APT::Get::Show-User-Simulation-Note",true) == true)
2958 cout << _("NOTE: This is only a simulation!\n"
2959 " apt-get needs root privileges for real execution.\n"
2960 " Keep also in mind that locking is deactivated,\n"
2961 " so don't depend on the relevance to the real current situation!"
2962 ) << std::endl;
2963 _config->Set("Debug::NoLocking",true);
2964 }
2965
2966 // Deal with stdout not being a tty
2967 if (!isatty(STDOUT_FILENO) && _config->FindI("quiet", -1) == -1)
2968 _config->Set("quiet","1");
2969
2970 // Setup the output streams
2971 c0out.rdbuf(cout.rdbuf());
2972 c1out.rdbuf(cout.rdbuf());
2973 c2out.rdbuf(cout.rdbuf());
2974 if (_config->FindI("quiet",0) > 0)
2975 c0out.rdbuf(devnull.rdbuf());
2976 if (_config->FindI("quiet",0) > 1)
2977 c1out.rdbuf(devnull.rdbuf());
2978
2979 // Setup the signals
2980 signal(SIGPIPE,SIG_IGN);
2981 signal(SIGWINCH,SigWinch);
2982 SigWinch(0);
2983
2984 // Match the operation
2985 CmdL.DispatchArg(Cmds);
2986
2987 // Print any errors or warnings found during parsing
2988 bool const Errors = _error->PendingError();
2989 if (_config->FindI("quiet",0) > 0)
2990 _error->DumpErrors();
2991 else
2992 _error->DumpErrors(GlobalError::DEBUG);
2993 return Errors == true ? 100 : 0;
2994}
2995 /*}}}*/