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