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