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