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