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