* cmdline/apt-get.cc:
[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 // TryToInstall - 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 TryToInstall(pkgCache::PkgIterator Pkg,pkgDepCache &Cache,
1081 pkgProblemResolver &Fix,bool Remove,bool BrokenFix,
1082 unsigned int &ExpectedInst,bool AllowFail = true)
1083 {
1084 /* This is a pure virtual package and there is a single available
1085 candidate providing it. */
1086 if (Cache[Pkg].CandidateVer == 0 && Pkg->ProvidesList != 0)
1087 {
1088 pkgCache::PkgIterator Prov;
1089 bool found_one = false;
1090
1091 for (pkgCache::PrvIterator P = Pkg.ProvidesList(); P; P++)
1092 {
1093 pkgCache::VerIterator const PVer = P.OwnerVer();
1094 pkgCache::PkgIterator const PPkg = PVer.ParentPkg();
1095
1096 /* Ignore versions that are not a candidate. */
1097 if (Cache[PPkg].CandidateVer != PVer)
1098 continue;
1099
1100 if (found_one == false)
1101 {
1102 Prov = PPkg;
1103 found_one = true;
1104 }
1105 else if (PPkg != Prov)
1106 {
1107 found_one = false; // we found at least two
1108 break;
1109 }
1110 }
1111
1112 if (found_one == true)
1113 {
1114 ioprintf(c1out,_("Note, selecting %s instead of %s\n"),
1115 Prov.FullName(true).c_str(),Pkg.FullName(true).c_str());
1116 Pkg = Prov;
1117 }
1118 }
1119
1120 // Handle the no-upgrade case
1121 if (_config->FindB("APT::Get::upgrade",true) == false &&
1122 Pkg->CurrentVer != 0)
1123 {
1124 if (AllowFail == true)
1125 ioprintf(c1out,_("Skipping %s, it is already installed and upgrade is not set.\n"),
1126 Pkg.FullName(true).c_str());
1127 return true;
1128 }
1129
1130 // Ignore request for install if package would be new
1131 if (_config->FindB("APT::Get::Only-Upgrade", false) == true &&
1132 Pkg->CurrentVer == 0)
1133 {
1134 if (AllowFail == true)
1135 ioprintf(c1out,_("Skipping %s, it is not installed and only upgrades are requested.\n"),
1136 Pkg.Name());
1137 return true;
1138 }
1139
1140 // Check if there is something at all to install
1141 pkgDepCache::StateCache &State = Cache[Pkg];
1142 if (Remove == true && Pkg->CurrentVer == 0)
1143 {
1144 Fix.Clear(Pkg);
1145 Fix.Protect(Pkg);
1146 Fix.Remove(Pkg);
1147
1148 /* We want to continue searching for regex hits, so we return false here
1149 otherwise this is not really an error. */
1150 if (AllowFail == false)
1151 return false;
1152
1153 ioprintf(c1out,_("Package %s is not installed, so not removed\n"),Pkg.FullName(true).c_str());
1154 return true;
1155 }
1156
1157 if (State.CandidateVer == 0 && Remove == false)
1158 {
1159 if (AllowFail == false)
1160 return false;
1161
1162 if (Pkg->ProvidesList != 0)
1163 {
1164 ioprintf(c1out,_("Package %s is a virtual package provided by:\n"),
1165 Pkg.FullName(true).c_str());
1166
1167 pkgCache::PrvIterator I = Pkg.ProvidesList();
1168 unsigned short provider = 0;
1169 for (; I.end() == false; I++)
1170 {
1171 pkgCache::PkgIterator Pkg = I.OwnerPkg();
1172
1173 if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer())
1174 {
1175 c1out << " " << Pkg.FullName(true) << " " << I.OwnerVer().VerStr();
1176 if (Cache[Pkg].Install() == true && Cache[Pkg].NewInstall() == false)
1177 c1out << _(" [Installed]");
1178 c1out << endl;
1179 ++provider;
1180 }
1181 }
1182 // if we found no candidate which provide this package, show non-candidates
1183 if (provider == 0)
1184 for (I = Pkg.ProvidesList(); I.end() == false; I++)
1185 c1out << " " << I.OwnerPkg().FullName(true) << " " << I.OwnerVer().VerStr()
1186 << _(" [Not candidate version]") << endl;
1187 else
1188 c1out << _("You should explicitly select one to install.") << endl;
1189 }
1190 else
1191 {
1192 ioprintf(c1out,
1193 _("Package %s is not available, but is referred to by another package.\n"
1194 "This may mean that the package is missing, has been obsoleted, or\n"
1195 "is only available from another source\n"),Pkg.FullName(true).c_str());
1196
1197 string List;
1198 string VersionsList;
1199 SPtrArray<bool> Seen = new bool[Cache.Head().PackageCount];
1200 memset(Seen,0,Cache.Head().PackageCount*sizeof(*Seen));
1201 pkgCache::DepIterator Dep = Pkg.RevDependsList();
1202 for (; Dep.end() == false; Dep++)
1203 {
1204 if (Dep->Type != pkgCache::Dep::Replaces)
1205 continue;
1206 if (Seen[Dep.ParentPkg()->ID] == true)
1207 continue;
1208 Seen[Dep.ParentPkg()->ID] = true;
1209 List += Dep.ParentPkg().FullName(true) + " ";
1210 //VersionsList += string(Dep.ParentPkg().CurVersion) + "\n"; ???
1211 }
1212 ShowList(c1out,_("However the following packages replace it:"),List,VersionsList);
1213 }
1214
1215 _error->Error(_("Package %s has no installation candidate"),Pkg.FullName(true).c_str());
1216 return false;
1217 }
1218
1219 Fix.Clear(Pkg);
1220 Fix.Protect(Pkg);
1221 if (Remove == true)
1222 {
1223 Fix.Remove(Pkg);
1224 Cache.MarkDelete(Pkg,_config->FindB("APT::Get::Purge",false));
1225 return true;
1226 }
1227
1228 // Install it
1229 Cache.MarkInstall(Pkg,false);
1230 if (State.Install() == false)
1231 {
1232 if (_config->FindB("APT::Get::ReInstall",false) == true)
1233 {
1234 if (Pkg->CurrentVer == 0 || Pkg.CurrentVer().Downloadable() == false)
1235 ioprintf(c1out,_("Reinstallation of %s is not possible, it cannot be downloaded.\n"),
1236 Pkg.FullName(true).c_str());
1237 else
1238 Cache.SetReInstall(Pkg,true);
1239 }
1240 else
1241 {
1242 if (AllowFail == true)
1243 ioprintf(c1out,_("%s is already the newest version.\n"),
1244 Pkg.FullName(true).c_str());
1245 }
1246 }
1247 else
1248 ExpectedInst++;
1249
1250 // Install it with autoinstalling enabled (if we not respect the minial
1251 // required deps or the policy)
1252 if ((State.InstBroken() == true || State.InstPolicyBroken() == true) && BrokenFix == false)
1253 Cache.MarkInstall(Pkg,true);
1254
1255 return true;
1256 }
1257 /*}}}*/
1258 // FindSrc - Find a source record /*{{{*/
1259 // ---------------------------------------------------------------------
1260 /* */
1261 pkgSrcRecords::Parser *FindSrc(const char *Name,pkgRecords &Recs,
1262 pkgSrcRecords &SrcRecs,string &Src,
1263 pkgDepCache &Cache)
1264 {
1265 string VerTag;
1266 string DefRel = _config->Find("APT::Default-Release");
1267 string TmpSrc = Name;
1268
1269 // extract the version/release from the pkgname
1270 const size_t found = TmpSrc.find_last_of("/=");
1271 if (found != string::npos) {
1272 if (TmpSrc[found] == '/')
1273 DefRel = TmpSrc.substr(found+1);
1274 else
1275 VerTag = TmpSrc.substr(found+1);
1276 TmpSrc = TmpSrc.substr(0,found);
1277 }
1278
1279 /* Lookup the version of the package we would install if we were to
1280 install a version and determine the source package name, then look
1281 in the archive for a source package of the same name. */
1282 bool MatchSrcOnly = _config->FindB("APT::Get::Only-Source");
1283 const pkgCache::PkgIterator Pkg = Cache.FindPkg(TmpSrc);
1284 if (MatchSrcOnly == false && Pkg.end() == false)
1285 {
1286 if(VerTag.empty() == false || DefRel.empty() == false)
1287 {
1288 bool fuzzy = false;
1289 // we have a default release, try to locate the pkg. we do it like
1290 // this because GetCandidateVer() will not "downgrade", that means
1291 // "apt-get source -t stable apt" won't work on a unstable system
1292 for (pkgCache::VerIterator Ver = Pkg.VersionList();; Ver++)
1293 {
1294 // try first only exact matches, later fuzzy matches
1295 if (Ver.end() == true)
1296 {
1297 if (fuzzy == true)
1298 break;
1299 fuzzy = true;
1300 Ver = Pkg.VersionList();
1301 // exit right away from the Pkg.VersionList() loop if we
1302 // don't have any versions
1303 if (Ver.end() == true)
1304 break;
1305 }
1306 // We match against a concrete version (or a part of this version)
1307 if (VerTag.empty() == false &&
1308 (fuzzy == true || Cache.VS().CmpVersion(VerTag, Ver.VerStr()) != 0) && // exact match
1309 (fuzzy == false || strncmp(VerTag.c_str(), Ver.VerStr(), VerTag.size()) != 0)) // fuzzy match
1310 continue;
1311
1312 for (pkgCache::VerFileIterator VF = Ver.FileList();
1313 VF.end() == false; VF++)
1314 {
1315 /* If this is the status file, and the current version is not the
1316 version in the status file (ie it is not installed, or somesuch)
1317 then it is not a candidate for installation, ever. This weeds
1318 out bogus entries that may be due to config-file states, or
1319 other. */
1320 if ((VF.File()->Flags & pkgCache::Flag::NotSource) ==
1321 pkgCache::Flag::NotSource && Pkg.CurrentVer() != Ver)
1322 continue;
1323
1324 // or we match against a release
1325 if(VerTag.empty() == false ||
1326 (VF.File().Archive() != 0 && VF.File().Archive() == DefRel) ||
1327 (VF.File().Codename() != 0 && VF.File().Codename() == DefRel))
1328 {
1329 pkgRecords::Parser &Parse = Recs.Lookup(VF);
1330 Src = Parse.SourcePkg();
1331 // no SourcePkg name, so it is the "binary" name
1332 if (Src.empty() == true)
1333 Src = TmpSrc;
1334 // the Version we have is possibly fuzzy or includes binUploads,
1335 // so we use the Version of the SourcePkg (empty if same as package)
1336 VerTag = Parse.SourceVer();
1337 if (VerTag.empty() == true)
1338 VerTag = Ver.VerStr();
1339 break;
1340 }
1341 }
1342 if (Src.empty() == false)
1343 break;
1344 }
1345 if (Src.empty() == true)
1346 {
1347 // Sources files have no codename information
1348 if (VerTag.empty() == true && DefRel.empty() == false)
1349 {
1350 _error->Error(_("Ignore unavailable target release '%s' of package '%s'"), DefRel.c_str(), TmpSrc.c_str());
1351 return 0;
1352 }
1353 }
1354 }
1355 if (Src.empty() == true)
1356 {
1357 // if we don't have found a fitting package yet so we will
1358 // choose a good candidate and proceed with that.
1359 // Maybe we will find a source later on with the right VerTag
1360 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
1361 if (Ver.end() == false)
1362 {
1363 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1364 Src = Parse.SourcePkg();
1365 if (VerTag.empty() == true)
1366 VerTag = Parse.SourceVer();
1367 }
1368 }
1369 }
1370
1371 if (Src.empty() == true)
1372 Src = TmpSrc;
1373 else
1374 {
1375 /* if we have a source pkg name, make sure to only search
1376 for srcpkg names, otherwise apt gets confused if there
1377 is a binary package "pkg1" and a source package "pkg1"
1378 with the same name but that comes from different packages */
1379 MatchSrcOnly = true;
1380 if (Src != TmpSrc)
1381 {
1382 ioprintf(c1out, _("Picking '%s' as source package instead of '%s'\n"), Src.c_str(), TmpSrc.c_str());
1383 }
1384 }
1385
1386 // The best hit
1387 pkgSrcRecords::Parser *Last = 0;
1388 unsigned long Offset = 0;
1389 string Version;
1390
1391 /* Iterate over all of the hits, which includes the resulting
1392 binary packages in the search */
1393 pkgSrcRecords::Parser *Parse;
1394 while (true)
1395 {
1396 SrcRecs.Restart();
1397 while ((Parse = SrcRecs.Find(Src.c_str(), MatchSrcOnly)) != 0)
1398 {
1399 const string Ver = Parse->Version();
1400
1401 // Ignore all versions which doesn't fit
1402 if (VerTag.empty() == false &&
1403 Cache.VS().CmpVersion(VerTag, Ver) != 0) // exact match
1404 continue;
1405
1406 // Newer version or an exact match? Save the hit
1407 if (Last == 0 || Cache.VS().CmpVersion(Version,Ver) < 0) {
1408 Last = Parse;
1409 Offset = Parse->Offset();
1410 Version = Ver;
1411 }
1412
1413 // was the version check above an exact match? If so, we don't need to look further
1414 if (VerTag.empty() == false && VerTag.size() == Ver.size())
1415 break;
1416 }
1417 if (Last != 0 || VerTag.empty() == true)
1418 break;
1419 //if (VerTag.empty() == false && Last == 0)
1420 _error->Error(_("Ignore unavailable version '%s' of package '%s'"), VerTag.c_str(), TmpSrc.c_str());
1421 return 0;
1422 }
1423
1424 if (Last == 0 || Last->Jump(Offset) == false)
1425 return 0;
1426
1427 return Last;
1428 }
1429 /*}}}*/
1430 // DoUpdate - Update the package lists /*{{{*/
1431 // ---------------------------------------------------------------------
1432 /* */
1433 bool DoUpdate(CommandLine &CmdL)
1434 {
1435 if (CmdL.FileSize() != 1)
1436 return _error->Error(_("The update command takes no arguments"));
1437
1438 // Get the source list
1439 pkgSourceList List;
1440 if (List.ReadMainList() == false)
1441 return false;
1442
1443 // Create the progress
1444 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
1445
1446 // Just print out the uris an exit if the --print-uris flag was used
1447 if (_config->FindB("APT::Get::Print-URIs") == true)
1448 {
1449 // force a hashsum for compatibility reasons
1450 _config->CndSet("Acquire::ForceHash", "md5sum");
1451
1452 // get a fetcher
1453 pkgAcquire Fetcher;
1454 if (Fetcher.Setup(&Stat) == false)
1455 return false;
1456
1457 // Populate it with the source selection and get all Indexes
1458 // (GetAll=true)
1459 if (List.GetIndexes(&Fetcher,true) == false)
1460 return false;
1461
1462 pkgAcquire::UriIterator I = Fetcher.UriBegin();
1463 for (; I != Fetcher.UriEnd(); I++)
1464 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
1465 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
1466 return true;
1467 }
1468
1469 // do the work
1470 CacheFile Cache;
1471 if (_config->FindB("APT::Get::Download",true) == true)
1472 ListUpdate(Stat, List);
1473
1474 // Rebuild the cache.
1475 if (Cache.BuildCaches() == false)
1476 return false;
1477
1478 return true;
1479 }
1480 /*}}}*/
1481 // DoAutomaticRemove - Remove all automatic unused packages /*{{{*/
1482 // ---------------------------------------------------------------------
1483 /* Remove unused automatic packages */
1484 bool DoAutomaticRemove(CacheFile &Cache)
1485 {
1486 bool Debug = _config->FindI("Debug::pkgAutoRemove",false);
1487 bool doAutoRemove = _config->FindB("APT::Get::AutomaticRemove", false);
1488 bool hideAutoRemove = _config->FindB("APT::Get::HideAutoRemove");
1489
1490 pkgDepCache::ActionGroup group(*Cache);
1491 if(Debug)
1492 std::cout << "DoAutomaticRemove()" << std::endl;
1493
1494 // we don't want to autoremove and we don't want to see it, so why calculating?
1495 if (doAutoRemove == false && hideAutoRemove == true)
1496 return true;
1497
1498 if (doAutoRemove == true &&
1499 _config->FindB("APT::Get::Remove",true) == false)
1500 {
1501 c1out << _("We are not supposed to delete stuff, can't start "
1502 "AutoRemover") << std::endl;
1503 return false;
1504 }
1505
1506 bool purgePkgs = _config->FindB("APT::Get::Purge", false);
1507 bool smallList = (hideAutoRemove == false &&
1508 strcasecmp(_config->Find("APT::Get::HideAutoRemove","").c_str(),"small") == 0);
1509
1510 string autoremovelist, autoremoveversions;
1511 unsigned long autoRemoveCount = 0;
1512 // look over the cache to see what can be removed
1513 for (pkgCache::PkgIterator Pkg = Cache->PkgBegin(); ! Pkg.end(); ++Pkg)
1514 {
1515 if (Cache[Pkg].Garbage)
1516 {
1517 if(Pkg.CurrentVer() != 0 || Cache[Pkg].Install())
1518 if(Debug)
1519 std::cout << "We could delete %s" << Pkg.FullName(true).c_str() << std::endl;
1520
1521 if (doAutoRemove)
1522 {
1523 if(Pkg.CurrentVer() != 0 &&
1524 Pkg->CurrentState != pkgCache::State::ConfigFiles)
1525 Cache->MarkDelete(Pkg, purgePkgs);
1526 else
1527 Cache->MarkKeep(Pkg, false, false);
1528 }
1529 else
1530 {
1531 // only show stuff in the list that is not yet marked for removal
1532 if(Cache[Pkg].Delete() == false)
1533 {
1534 ++autoRemoveCount;
1535 // we don't need to fill the strings if we don't need them
1536 if (smallList == false)
1537 {
1538 autoremovelist += Pkg.FullName(true) + " ";
1539 autoremoveversions += string(Cache[Pkg].CandVersion) + "\n";
1540 }
1541 }
1542 }
1543 }
1544 }
1545 // if we don't remove them, we should show them!
1546 if (doAutoRemove == false && (autoremovelist.empty() == false || autoRemoveCount != 0))
1547 {
1548 if (smallList == false)
1549 ShowList(c1out, P_("The following package is automatically installed and is no longer required:",
1550 "The following packages were automatically installed and are no longer required:",
1551 autoRemoveCount), autoremovelist, autoremoveversions);
1552 else
1553 ioprintf(c1out, P_("%lu package was automatically installed and is no longer required.\n",
1554 "%lu packages were automatically installed and are no longer required.\n", autoRemoveCount), autoRemoveCount);
1555 c1out << _("Use 'apt-get autoremove' to remove them.") << std::endl;
1556 }
1557 // Now see if we had destroyed anything (if we had done anything)
1558 else if (Cache->BrokenCount() != 0)
1559 {
1560 c1out << _("Hmm, seems like the AutoRemover destroyed something which really\n"
1561 "shouldn't happen. Please file a bug report against apt.") << endl;
1562 c1out << endl;
1563 c1out << _("The following information may help to resolve the situation:") << endl;
1564 c1out << endl;
1565 ShowBroken(c1out,Cache,false);
1566
1567 return _error->Error(_("Internal Error, AutoRemover broke stuff"));
1568 }
1569 return true;
1570 }
1571 /*}}}*/
1572 // DoUpgrade - Upgrade all packages /*{{{*/
1573 // ---------------------------------------------------------------------
1574 /* Upgrade all packages without installing new packages or erasing old
1575 packages */
1576 bool DoUpgrade(CommandLine &CmdL)
1577 {
1578 CacheFile Cache;
1579 if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
1580 return false;
1581
1582 // Do the upgrade
1583 if (pkgAllUpgrade(Cache) == false)
1584 {
1585 ShowBroken(c1out,Cache,false);
1586 return _error->Error(_("Internal error, AllUpgrade broke stuff"));
1587 }
1588
1589 return InstallPackages(Cache,true);
1590 }
1591 /*}}}*/
1592 // DoInstall - Install packages from the command line /*{{{*/
1593 // ---------------------------------------------------------------------
1594 /* Install named packages */
1595 bool DoInstall(CommandLine &CmdL)
1596 {
1597 CacheFile Cache;
1598 if (Cache.OpenForInstall() == false ||
1599 Cache.CheckDeps(CmdL.FileSize() != 1) == false)
1600 return false;
1601
1602 // Enter the special broken fixing mode if the user specified arguments
1603 bool BrokenFix = false;
1604 if (Cache->BrokenCount() != 0)
1605 BrokenFix = true;
1606
1607 unsigned int AutoMarkChanged = 0;
1608 unsigned int ExpectedInst = 0;
1609 pkgProblemResolver Fix(Cache);
1610
1611 unsigned short fallback = 0;
1612 if (strcasecmp(CmdL.FileList[0],"remove") == 0)
1613 fallback = 1;
1614 else if (strcasecmp(CmdL.FileList[0], "purge") == 0)
1615 {
1616 _config->Set("APT::Get::Purge", true);
1617 fallback = 1;
1618 }
1619 else if (strcasecmp(CmdL.FileList[0], "autoremove") == 0)
1620 {
1621 _config->Set("APT::Get::AutomaticRemove", "true");
1622 fallback = 1;
1623 }
1624 // new scope for the ActionGroup
1625 {
1626 // TODO: Howto get an ExpectedInst count ?
1627 pkgDepCache::ActionGroup group(Cache);
1628 std::list<APT::VersionSet::Modifier> mods;
1629 mods.push_back(APT::VersionSet::Modifier(0, "+",
1630 APT::VersionSet::Modifier::POSTFIX, APT::VersionSet::CANDINST));
1631 mods.push_back(APT::VersionSet::Modifier(1, "-",
1632 APT::VersionSet::Modifier::POSTFIX, APT::VersionSet::INSTCAND));
1633 std::map<unsigned short, APT::VersionSet> verset = APT::VersionSet::GroupedFromCommandLine(Cache,
1634 CmdL.FileList + 1, mods, fallback, c0out);
1635
1636 if (_error->PendingError() == true)
1637 return false;
1638
1639 for (APT::VersionSet::const_iterator Ver = verset[0].begin();
1640 Ver != verset[0].end(); ++Ver)
1641 {
1642 pkgCache::PkgIterator Pkg = Ver.ParentPkg();
1643 Cache->SetCandidateVersion(Ver);
1644
1645 if (TryToInstall(Pkg, Cache, Fix, false, BrokenFix, ExpectedInst) == false)
1646 return false;
1647
1648 // see if we need to fix the auto-mark flag
1649 // e.g. apt-get install foo
1650 // where foo is marked automatic
1651 if (Cache[Pkg].Install() == false &&
1652 (Cache[Pkg].Flags & pkgCache::Flag::Auto) &&
1653 _config->FindB("APT::Get::ReInstall",false) == false &&
1654 _config->FindB("APT::Get::Only-Upgrade",false) == false &&
1655 _config->FindB("APT::Get::Download-Only",false) == false)
1656 {
1657 ioprintf(c1out,_("%s set to manually installed.\n"),
1658 Pkg.FullName(true).c_str());
1659 Cache->MarkAuto(Pkg,false);
1660 AutoMarkChanged++;
1661 }
1662 }
1663
1664 for (APT::VersionSet::const_iterator Ver = verset[1].begin();
1665 Ver != verset[1].end(); ++Ver)
1666 {
1667 pkgCache::PkgIterator Pkg = Ver.ParentPkg();
1668
1669 if (TryToInstall(Pkg, Cache, Fix, true, BrokenFix, ExpectedInst) == false)
1670 return false;
1671 }
1672
1673 if (_error->PendingError() == true)
1674 return false;
1675
1676 /* If we are in the Broken fixing mode we do not attempt to fix the
1677 problems. This is if the user invoked install without -f and gave
1678 packages */
1679 if (BrokenFix == true && Cache->BrokenCount() != 0)
1680 {
1681 c1out << _("You might want to run 'apt-get -f install' to correct these:") << endl;
1682 ShowBroken(c1out,Cache,false);
1683
1684 return _error->Error(_("Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution)."));
1685 }
1686
1687 // Call the scored problem resolver
1688 Fix.InstallProtect();
1689 if (Fix.Resolve(true) == false)
1690 _error->Discard();
1691
1692 // Now we check the state of the packages,
1693 if (Cache->BrokenCount() != 0)
1694 {
1695 c1out <<
1696 _("Some packages could not be installed. This may mean that you have\n"
1697 "requested an impossible situation or if you are using the unstable\n"
1698 "distribution that some required packages have not yet been created\n"
1699 "or been moved out of Incoming.") << endl;
1700 /*
1701 if (Packages == 1)
1702 {
1703 c1out << endl;
1704 c1out <<
1705 _("Since you only requested a single operation it is extremely likely that\n"
1706 "the package is simply not installable and a bug report against\n"
1707 "that package should be filed.") << endl;
1708 }
1709 */
1710
1711 c1out << _("The following information may help to resolve the situation:") << endl;
1712 c1out << endl;
1713 ShowBroken(c1out,Cache,false);
1714 return _error->Error(_("Broken packages"));
1715 }
1716 }
1717 if (!DoAutomaticRemove(Cache))
1718 return false;
1719
1720 /* Print out a list of packages that are going to be installed extra
1721 to what the user asked */
1722 if (Cache->InstCount() != ExpectedInst)
1723 {
1724 string List;
1725 string VersionsList;
1726 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
1727 {
1728 pkgCache::PkgIterator I(Cache,Cache.List[J]);
1729 if ((*Cache)[I].Install() == false)
1730 continue;
1731
1732 const char **J;
1733 for (J = CmdL.FileList + 1; *J != 0; J++)
1734 if (strcmp(*J,I.Name()) == 0)
1735 break;
1736
1737 if (*J == 0) {
1738 List += I.FullName(true) + " ";
1739 VersionsList += string(Cache[I].CandVersion) + "\n";
1740 }
1741 }
1742
1743 ShowList(c1out,_("The following extra packages will be installed:"),List,VersionsList);
1744 }
1745
1746 /* Print out a list of suggested and recommended packages */
1747 {
1748 string SuggestsList, RecommendsList, List;
1749 string SuggestsVersions, RecommendsVersions;
1750 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
1751 {
1752 pkgCache::PkgIterator Pkg(Cache,Cache.List[J]);
1753
1754 /* Just look at the ones we want to install */
1755 if ((*Cache)[Pkg].Install() == false)
1756 continue;
1757
1758 // get the recommends/suggests for the candidate ver
1759 pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
1760 for (pkgCache::DepIterator D = CV.DependsList(); D.end() == false; )
1761 {
1762 pkgCache::DepIterator Start;
1763 pkgCache::DepIterator End;
1764 D.GlobOr(Start,End); // advances D
1765
1766 // FIXME: we really should display a or-group as a or-group to the user
1767 // the problem is that ShowList is incapable of doing this
1768 string RecommendsOrList,RecommendsOrVersions;
1769 string SuggestsOrList,SuggestsOrVersions;
1770 bool foundInstalledInOrGroup = false;
1771 for(;;)
1772 {
1773 /* Skip if package is installed already, or is about to be */
1774 string target = Start.TargetPkg().FullName(true) + " ";
1775 pkgCache::PkgIterator const TarPkg = Start.TargetPkg();
1776 if (TarPkg->SelectedState == pkgCache::State::Install ||
1777 TarPkg->SelectedState == pkgCache::State::Hold ||
1778 Cache[Start.TargetPkg()].Install())
1779 {
1780 foundInstalledInOrGroup=true;
1781 break;
1782 }
1783
1784 /* Skip if we already saw it */
1785 if (int(SuggestsList.find(target)) != -1 || int(RecommendsList.find(target)) != -1)
1786 {
1787 foundInstalledInOrGroup=true;
1788 break;
1789 }
1790
1791 // this is a dep on a virtual pkg, check if any package that provides it
1792 // should be installed
1793 if(Start.TargetPkg().ProvidesList() != 0)
1794 {
1795 pkgCache::PrvIterator I = Start.TargetPkg().ProvidesList();
1796 for (; I.end() == false; I++)
1797 {
1798 pkgCache::PkgIterator Pkg = I.OwnerPkg();
1799 if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer() &&
1800 Pkg.CurrentVer() != 0)
1801 foundInstalledInOrGroup=true;
1802 }
1803 }
1804
1805 if (Start->Type == pkgCache::Dep::Suggests)
1806 {
1807 SuggestsOrList += target;
1808 SuggestsOrVersions += string(Cache[Start.TargetPkg()].CandVersion) + "\n";
1809 }
1810
1811 if (Start->Type == pkgCache::Dep::Recommends)
1812 {
1813 RecommendsOrList += target;
1814 RecommendsOrVersions += string(Cache[Start.TargetPkg()].CandVersion) + "\n";
1815 }
1816
1817 if (Start >= End)
1818 break;
1819 Start++;
1820 }
1821
1822 if(foundInstalledInOrGroup == false)
1823 {
1824 RecommendsList += RecommendsOrList;
1825 RecommendsVersions += RecommendsOrVersions;
1826 SuggestsList += SuggestsOrList;
1827 SuggestsVersions += SuggestsOrVersions;
1828 }
1829
1830 }
1831 }
1832
1833 ShowList(c1out,_("Suggested packages:"),SuggestsList,SuggestsVersions);
1834 ShowList(c1out,_("Recommended packages:"),RecommendsList,RecommendsVersions);
1835
1836 }
1837
1838 // if nothing changed in the cache, but only the automark information
1839 // we write the StateFile here, otherwise it will be written in
1840 // cache.commit()
1841 if (AutoMarkChanged > 0 &&
1842 Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
1843 Cache->BadCount() == 0 &&
1844 _config->FindB("APT::Get::Simulate",false) == false)
1845 Cache->writeStateFile(NULL);
1846
1847 // See if we need to prompt
1848 if (Cache->InstCount() == ExpectedInst && Cache->DelCount() == 0)
1849 return InstallPackages(Cache,false,false);
1850
1851 return InstallPackages(Cache,false);
1852 }
1853
1854 /* mark packages as automatically/manually installed. */
1855 bool DoMarkAuto(CommandLine &CmdL)
1856 {
1857 bool Action = true;
1858 int AutoMarkChanged = 0;
1859 OpTextProgress progress;
1860 CacheFile Cache;
1861 if (Cache.Open() == false)
1862 return false;
1863
1864 if (strcasecmp(CmdL.FileList[0],"markauto") == 0)
1865 Action = true;
1866 else if (strcasecmp(CmdL.FileList[0],"unmarkauto") == 0)
1867 Action = false;
1868
1869 for (const char **I = CmdL.FileList + 1; *I != 0; I++)
1870 {
1871 const char *S = *I;
1872 // Locate the package
1873 pkgCache::PkgIterator Pkg = Cache->FindPkg(S);
1874 if (Pkg.end() == true) {
1875 return _error->Error(_("Couldn't find package %s"),S);
1876 }
1877 else
1878 {
1879 if (!Action)
1880 ioprintf(c1out,_("%s set to manually installed.\n"), Pkg.Name());
1881 else
1882 ioprintf(c1out,_("%s set to automatically installed.\n"),
1883 Pkg.Name());
1884
1885 Cache->MarkAuto(Pkg,Action);
1886 AutoMarkChanged++;
1887 }
1888 }
1889 if (AutoMarkChanged && ! _config->FindB("APT::Get::Simulate",false))
1890 return Cache->writeStateFile(NULL);
1891 return false;
1892 }
1893 /*}}}*/
1894 // DoDistUpgrade - Automatic smart upgrader /*{{{*/
1895 // ---------------------------------------------------------------------
1896 /* Intelligent upgrader that will install and remove packages at will */
1897 bool DoDistUpgrade(CommandLine &CmdL)
1898 {
1899 CacheFile Cache;
1900 if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
1901 return false;
1902
1903 c0out << _("Calculating upgrade... ") << flush;
1904 if (pkgDistUpgrade(*Cache) == false)
1905 {
1906 c0out << _("Failed") << endl;
1907 ShowBroken(c1out,Cache,false);
1908 return false;
1909 }
1910
1911 c0out << _("Done") << endl;
1912
1913 return InstallPackages(Cache,true);
1914 }
1915 /*}}}*/
1916 // DoDSelectUpgrade - Do an upgrade by following dselects selections /*{{{*/
1917 // ---------------------------------------------------------------------
1918 /* Follows dselect's selections */
1919 bool DoDSelectUpgrade(CommandLine &CmdL)
1920 {
1921 CacheFile Cache;
1922 if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
1923 return false;
1924
1925 pkgDepCache::ActionGroup group(Cache);
1926
1927 // Install everything with the install flag set
1928 pkgCache::PkgIterator I = Cache->PkgBegin();
1929 for (;I.end() != true; I++)
1930 {
1931 /* Install the package only if it is a new install, the autoupgrader
1932 will deal with the rest */
1933 if (I->SelectedState == pkgCache::State::Install)
1934 Cache->MarkInstall(I,false);
1935 }
1936
1937 /* Now install their deps too, if we do this above then order of
1938 the status file is significant for | groups */
1939 for (I = Cache->PkgBegin();I.end() != true; I++)
1940 {
1941 /* Install the package only if it is a new install, the autoupgrader
1942 will deal with the rest */
1943 if (I->SelectedState == pkgCache::State::Install)
1944 Cache->MarkInstall(I,true);
1945 }
1946
1947 // Apply erasures now, they override everything else.
1948 for (I = Cache->PkgBegin();I.end() != true; I++)
1949 {
1950 // Remove packages
1951 if (I->SelectedState == pkgCache::State::DeInstall ||
1952 I->SelectedState == pkgCache::State::Purge)
1953 Cache->MarkDelete(I,I->SelectedState == pkgCache::State::Purge);
1954 }
1955
1956 /* Resolve any problems that dselect created, allupgrade cannot handle
1957 such things. We do so quite agressively too.. */
1958 if (Cache->BrokenCount() != 0)
1959 {
1960 pkgProblemResolver Fix(Cache);
1961
1962 // Hold back held packages.
1963 if (_config->FindB("APT::Ignore-Hold",false) == false)
1964 {
1965 for (pkgCache::PkgIterator I = Cache->PkgBegin(); I.end() == false; I++)
1966 {
1967 if (I->SelectedState == pkgCache::State::Hold)
1968 {
1969 Fix.Protect(I);
1970 Cache->MarkKeep(I);
1971 }
1972 }
1973 }
1974
1975 if (Fix.Resolve() == false)
1976 {
1977 ShowBroken(c1out,Cache,false);
1978 return _error->Error(_("Internal error, problem resolver broke stuff"));
1979 }
1980 }
1981
1982 // Now upgrade everything
1983 if (pkgAllUpgrade(Cache) == false)
1984 {
1985 ShowBroken(c1out,Cache,false);
1986 return _error->Error(_("Internal error, problem resolver broke stuff"));
1987 }
1988
1989 return InstallPackages(Cache,false);
1990 }
1991 /*}}}*/
1992 // DoClean - Remove download archives /*{{{*/
1993 // ---------------------------------------------------------------------
1994 /* */
1995 bool DoClean(CommandLine &CmdL)
1996 {
1997 if (_config->FindB("APT::Get::Simulate") == true)
1998 {
1999 cout << "Del " << _config->FindDir("Dir::Cache::archives") << "* " <<
2000 _config->FindDir("Dir::Cache::archives") << "partial/*" << endl;
2001 return true;
2002 }
2003
2004 // Lock the archive directory
2005 FileFd Lock;
2006 if (_config->FindB("Debug::NoLocking",false) == false)
2007 {
2008 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
2009 if (_error->PendingError() == true)
2010 return _error->Error(_("Unable to lock the download directory"));
2011 }
2012
2013 pkgAcquire Fetcher;
2014 Fetcher.Clean(_config->FindDir("Dir::Cache::archives"));
2015 Fetcher.Clean(_config->FindDir("Dir::Cache::archives") + "partial/");
2016 return true;
2017 }
2018 /*}}}*/
2019 // DoAutoClean - Smartly remove downloaded archives /*{{{*/
2020 // ---------------------------------------------------------------------
2021 /* This is similar to clean but it only purges things that cannot be
2022 downloaded, that is old versions of cached packages. */
2023 class LogCleaner : public pkgArchiveCleaner
2024 {
2025 protected:
2026 virtual void Erase(const char *File,string Pkg,string Ver,struct stat &St)
2027 {
2028 c1out << "Del " << Pkg << " " << Ver << " [" << SizeToStr(St.st_size) << "B]" << endl;
2029
2030 if (_config->FindB("APT::Get::Simulate") == false)
2031 unlink(File);
2032 };
2033 };
2034
2035 bool DoAutoClean(CommandLine &CmdL)
2036 {
2037 // Lock the archive directory
2038 FileFd Lock;
2039 if (_config->FindB("Debug::NoLocking",false) == false)
2040 {
2041 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
2042 if (_error->PendingError() == true)
2043 return _error->Error(_("Unable to lock the download directory"));
2044 }
2045
2046 CacheFile Cache;
2047 if (Cache.Open() == false)
2048 return false;
2049
2050 LogCleaner Cleaner;
2051
2052 return Cleaner.Go(_config->FindDir("Dir::Cache::archives"),*Cache) &&
2053 Cleaner.Go(_config->FindDir("Dir::Cache::archives") + "partial/",*Cache);
2054 }
2055 /*}}}*/
2056 // DoCheck - Perform the check operation /*{{{*/
2057 // ---------------------------------------------------------------------
2058 /* Opening automatically checks the system, this command is mostly used
2059 for debugging */
2060 bool DoCheck(CommandLine &CmdL)
2061 {
2062 CacheFile Cache;
2063 Cache.Open();
2064 Cache.CheckDeps();
2065
2066 return true;
2067 }
2068 /*}}}*/
2069 // DoSource - Fetch a source archive /*{{{*/
2070 // ---------------------------------------------------------------------
2071 /* Fetch souce packages */
2072 struct DscFile
2073 {
2074 string Package;
2075 string Version;
2076 string Dsc;
2077 };
2078
2079 bool DoSource(CommandLine &CmdL)
2080 {
2081 CacheFile Cache;
2082 if (Cache.Open(false) == false)
2083 return false;
2084
2085 if (CmdL.FileSize() <= 1)
2086 return _error->Error(_("Must specify at least one package to fetch source for"));
2087
2088 // Read the source list
2089 pkgSourceList List;
2090 if (List.ReadMainList() == false)
2091 return _error->Error(_("The list of sources could not be read."));
2092
2093 // Create the text record parsers
2094 pkgRecords Recs(Cache);
2095 pkgSrcRecords SrcRecs(List);
2096 if (_error->PendingError() == true)
2097 return false;
2098
2099 // Create the download object
2100 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
2101 pkgAcquire Fetcher;
2102 if (Fetcher.Setup(&Stat) == false)
2103 return false;
2104
2105 DscFile *Dsc = new DscFile[CmdL.FileSize()];
2106
2107 // insert all downloaded uris into this set to avoid downloading them
2108 // twice
2109 set<string> queued;
2110
2111 // Diff only mode only fetches .diff files
2112 bool const diffOnly = _config->FindB("APT::Get::Diff-Only", false);
2113 // Tar only mode only fetches .tar files
2114 bool const tarOnly = _config->FindB("APT::Get::Tar-Only", false);
2115 // Dsc only mode only fetches .dsc files
2116 bool const dscOnly = _config->FindB("APT::Get::Dsc-Only", false);
2117
2118 // Load the requestd sources into the fetcher
2119 unsigned J = 0;
2120 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
2121 {
2122 string Src;
2123 pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,*Cache);
2124
2125 if (Last == 0)
2126 return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
2127
2128 string srec = Last->AsStr();
2129 string::size_type pos = srec.find("\nVcs-");
2130 while (pos != string::npos)
2131 {
2132 pos += strlen("\nVcs-");
2133 string vcs = srec.substr(pos,srec.find(":",pos)-pos);
2134 if(vcs == "Browser")
2135 {
2136 pos = srec.find("\nVcs-", pos);
2137 continue;
2138 }
2139 pos += vcs.length()+2;
2140 string::size_type epos = srec.find("\n", pos);
2141 string uri = srec.substr(pos,epos-pos).c_str();
2142 ioprintf(c1out, _("NOTICE: '%s' packaging is maintained in "
2143 "the '%s' version control system at:\n"
2144 "%s\n"),
2145 Src.c_str(), vcs.c_str(), uri.c_str());
2146 if(vcs == "Bzr")
2147 ioprintf(c1out,_("Please use:\n"
2148 "bzr get %s\n"
2149 "to retrieve the latest (possibly unreleased) "
2150 "updates to the package.\n"),
2151 uri.c_str());
2152 break;
2153 }
2154
2155 // Back track
2156 vector<pkgSrcRecords::File> Lst;
2157 if (Last->Files(Lst) == false)
2158 return false;
2159
2160 // Load them into the fetcher
2161 for (vector<pkgSrcRecords::File>::const_iterator I = Lst.begin();
2162 I != Lst.end(); I++)
2163 {
2164 // Try to guess what sort of file it is we are getting.
2165 if (I->Type == "dsc")
2166 {
2167 Dsc[J].Package = Last->Package();
2168 Dsc[J].Version = Last->Version();
2169 Dsc[J].Dsc = flNotDir(I->Path);
2170 }
2171
2172 // Handle the only options so that multiple can be used at once
2173 if (diffOnly == true || tarOnly == true || dscOnly == true)
2174 {
2175 if ((diffOnly == true && I->Type == "diff") ||
2176 (tarOnly == true && I->Type == "tar") ||
2177 (dscOnly == true && I->Type == "dsc"))
2178 ; // Fine, we want this file downloaded
2179 else
2180 continue;
2181 }
2182
2183 // don't download the same uri twice (should this be moved to
2184 // the fetcher interface itself?)
2185 if(queued.find(Last->Index().ArchiveURI(I->Path)) != queued.end())
2186 continue;
2187 queued.insert(Last->Index().ArchiveURI(I->Path));
2188
2189 // check if we have a file with that md5 sum already localy
2190 if(!I->MD5Hash.empty() && FileExists(flNotDir(I->Path)))
2191 {
2192 FileFd Fd(flNotDir(I->Path), FileFd::ReadOnly);
2193 MD5Summation sum;
2194 sum.AddFD(Fd.Fd(), Fd.Size());
2195 Fd.Close();
2196 if((string)sum.Result() == I->MD5Hash)
2197 {
2198 ioprintf(c1out,_("Skipping already downloaded file '%s'\n"),
2199 flNotDir(I->Path).c_str());
2200 continue;
2201 }
2202 }
2203
2204 new pkgAcqFile(&Fetcher,Last->Index().ArchiveURI(I->Path),
2205 I->MD5Hash,I->Size,
2206 Last->Index().SourceInfo(*Last,*I),Src);
2207 }
2208 }
2209
2210 // Display statistics
2211 unsigned long long FetchBytes = Fetcher.FetchNeeded();
2212 unsigned long long FetchPBytes = Fetcher.PartialPresent();
2213 unsigned long long DebBytes = Fetcher.TotalNeeded();
2214
2215 // Check for enough free space
2216 struct statvfs Buf;
2217 string OutputDir = ".";
2218 if (statvfs(OutputDir.c_str(),&Buf) != 0) {
2219 if (errno == EOVERFLOW)
2220 return _error->WarningE("statvfs",_("Couldn't determine free space in %s"),
2221 OutputDir.c_str());
2222 else
2223 return _error->Errno("statvfs",_("Couldn't determine free space in %s"),
2224 OutputDir.c_str());
2225 } else if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
2226 {
2227 struct statfs Stat;
2228 if (statfs(OutputDir.c_str(),&Stat) != 0
2229 #if HAVE_STRUCT_STATFS_F_TYPE
2230 || unsigned(Stat.f_type) != RAMFS_MAGIC
2231 #endif
2232 )
2233 return _error->Error(_("You don't have enough free space in %s"),
2234 OutputDir.c_str());
2235 }
2236
2237 // Number of bytes
2238 if (DebBytes != FetchBytes)
2239 ioprintf(c1out,_("Need to get %sB/%sB of source archives.\n"),
2240 SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
2241 else
2242 ioprintf(c1out,_("Need to get %sB of source archives.\n"),
2243 SizeToStr(DebBytes).c_str());
2244
2245 if (_config->FindB("APT::Get::Simulate",false) == true)
2246 {
2247 for (unsigned I = 0; I != J; I++)
2248 ioprintf(cout,_("Fetch source %s\n"),Dsc[I].Package.c_str());
2249 delete[] Dsc;
2250 return true;
2251 }
2252
2253 // Just print out the uris an exit if the --print-uris flag was used
2254 if (_config->FindB("APT::Get::Print-URIs") == true)
2255 {
2256 pkgAcquire::UriIterator I = Fetcher.UriBegin();
2257 for (; I != Fetcher.UriEnd(); I++)
2258 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
2259 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
2260 delete[] Dsc;
2261 return true;
2262 }
2263
2264 // Run it
2265 if (Fetcher.Run() == pkgAcquire::Failed)
2266 return false;
2267
2268 // Print error messages
2269 bool Failed = false;
2270 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
2271 {
2272 if ((*I)->Status == pkgAcquire::Item::StatDone &&
2273 (*I)->Complete == true)
2274 continue;
2275
2276 fprintf(stderr,_("Failed to fetch %s %s\n"),(*I)->DescURI().c_str(),
2277 (*I)->ErrorText.c_str());
2278 Failed = true;
2279 }
2280 if (Failed == true)
2281 return _error->Error(_("Failed to fetch some archives."));
2282
2283 if (_config->FindB("APT::Get::Download-only",false) == true)
2284 {
2285 c1out << _("Download complete and in download only mode") << endl;
2286 delete[] Dsc;
2287 return true;
2288 }
2289
2290 // Unpack the sources
2291 pid_t Process = ExecFork();
2292
2293 if (Process == 0)
2294 {
2295 bool const fixBroken = _config->FindB("APT::Get::Fix-Broken", false);
2296 for (unsigned I = 0; I != J; I++)
2297 {
2298 string Dir = Dsc[I].Package + '-' + Cache->VS().UpstreamVersion(Dsc[I].Version.c_str());
2299
2300 // Diff only mode only fetches .diff files
2301 if (_config->FindB("APT::Get::Diff-Only",false) == true ||
2302 _config->FindB("APT::Get::Tar-Only",false) == true ||
2303 Dsc[I].Dsc.empty() == true)
2304 continue;
2305
2306 // See if the package is already unpacked
2307 struct stat Stat;
2308 if (fixBroken == false && stat(Dir.c_str(),&Stat) == 0 &&
2309 S_ISDIR(Stat.st_mode) != 0)
2310 {
2311 ioprintf(c0out ,_("Skipping unpack of already unpacked source in %s\n"),
2312 Dir.c_str());
2313 }
2314 else
2315 {
2316 // Call dpkg-source
2317 char S[500];
2318 snprintf(S,sizeof(S),"%s -x %s",
2319 _config->Find("Dir::Bin::dpkg-source","dpkg-source").c_str(),
2320 Dsc[I].Dsc.c_str());
2321 if (system(S) != 0)
2322 {
2323 fprintf(stderr,_("Unpack command '%s' failed.\n"),S);
2324 fprintf(stderr,_("Check if the 'dpkg-dev' package is installed.\n"));
2325 _exit(1);
2326 }
2327 }
2328
2329 // Try to compile it with dpkg-buildpackage
2330 if (_config->FindB("APT::Get::Compile",false) == true)
2331 {
2332 // Call dpkg-buildpackage
2333 char S[500];
2334 snprintf(S,sizeof(S),"cd %s && %s %s",
2335 Dir.c_str(),
2336 _config->Find("Dir::Bin::dpkg-buildpackage","dpkg-buildpackage").c_str(),
2337 _config->Find("DPkg::Build-Options","-b -uc").c_str());
2338
2339 if (system(S) != 0)
2340 {
2341 fprintf(stderr,_("Build command '%s' failed.\n"),S);
2342 _exit(1);
2343 }
2344 }
2345 }
2346
2347 _exit(0);
2348 }
2349 delete[] Dsc;
2350
2351 // Wait for the subprocess
2352 int Status = 0;
2353 while (waitpid(Process,&Status,0) != Process)
2354 {
2355 if (errno == EINTR)
2356 continue;
2357 return _error->Errno("waitpid","Couldn't wait for subprocess");
2358 }
2359
2360 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
2361 return _error->Error(_("Child process failed"));
2362
2363 return true;
2364 }
2365 /*}}}*/
2366 // DoBuildDep - Install/removes packages to satisfy build dependencies /*{{{*/
2367 // ---------------------------------------------------------------------
2368 /* This function will look at the build depends list of the given source
2369 package and install the necessary packages to make it true, or fail. */
2370 bool DoBuildDep(CommandLine &CmdL)
2371 {
2372 CacheFile Cache;
2373 if (Cache.Open(true) == false)
2374 return false;
2375
2376 if (CmdL.FileSize() <= 1)
2377 return _error->Error(_("Must specify at least one package to check builddeps for"));
2378
2379 // Read the source list
2380 pkgSourceList List;
2381 if (List.ReadMainList() == false)
2382 return _error->Error(_("The list of sources could not be read."));
2383
2384 // Create the text record parsers
2385 pkgRecords Recs(Cache);
2386 pkgSrcRecords SrcRecs(List);
2387 if (_error->PendingError() == true)
2388 return false;
2389
2390 // Create the download object
2391 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
2392 pkgAcquire Fetcher;
2393 if (Fetcher.Setup(&Stat) == false)
2394 return false;
2395
2396 unsigned J = 0;
2397 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
2398 {
2399 string Src;
2400 pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,*Cache);
2401 if (Last == 0)
2402 return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
2403
2404 // Process the build-dependencies
2405 vector<pkgSrcRecords::Parser::BuildDepRec> BuildDeps;
2406 if (Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only",true)) == false)
2407 return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
2408
2409 // Also ensure that build-essential packages are present
2410 Configuration::Item const *Opts = _config->Tree("APT::Build-Essential");
2411 if (Opts)
2412 Opts = Opts->Child;
2413 for (; Opts; Opts = Opts->Next)
2414 {
2415 if (Opts->Value.empty() == true)
2416 continue;
2417
2418 pkgSrcRecords::Parser::BuildDepRec rec;
2419 rec.Package = Opts->Value;
2420 rec.Type = pkgSrcRecords::Parser::BuildDependIndep;
2421 rec.Op = 0;
2422 BuildDeps.push_back(rec);
2423 }
2424
2425 if (BuildDeps.size() == 0)
2426 {
2427 ioprintf(c1out,_("%s has no build depends.\n"),Src.c_str());
2428 continue;
2429 }
2430
2431 // Install the requested packages
2432 unsigned int ExpectedInst = 0;
2433 vector <pkgSrcRecords::Parser::BuildDepRec>::iterator D;
2434 pkgProblemResolver Fix(Cache);
2435 bool skipAlternatives = false; // skip remaining alternatives in an or group
2436 for (D = BuildDeps.begin(); D != BuildDeps.end(); D++)
2437 {
2438 bool hasAlternatives = (((*D).Op & pkgCache::Dep::Or) == pkgCache::Dep::Or);
2439
2440 if (skipAlternatives == true)
2441 {
2442 if (!hasAlternatives)
2443 skipAlternatives = false; // end of or group
2444 continue;
2445 }
2446
2447 if ((*D).Type == pkgSrcRecords::Parser::BuildConflict ||
2448 (*D).Type == pkgSrcRecords::Parser::BuildConflictIndep)
2449 {
2450 pkgCache::PkgIterator Pkg = Cache->FindPkg((*D).Package);
2451 // Build-conflicts on unknown packages are silently ignored
2452 if (Pkg.end() == true)
2453 continue;
2454
2455 pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
2456
2457 /*
2458 * Remove if we have an installed version that satisfies the
2459 * version criteria
2460 */
2461 if (IV.end() == false &&
2462 Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
2463 TryToInstall(Pkg,Cache,Fix,true,false,ExpectedInst);
2464 }
2465 else // BuildDep || BuildDepIndep
2466 {
2467 pkgCache::PkgIterator Pkg = Cache->FindPkg((*D).Package);
2468 if (_config->FindB("Debug::BuildDeps",false) == true)
2469 cout << "Looking for " << (*D).Package << "...\n";
2470
2471 if (Pkg.end() == true)
2472 {
2473 if (_config->FindB("Debug::BuildDeps",false) == true)
2474 cout << " (not found)" << (*D).Package << endl;
2475
2476 if (hasAlternatives)
2477 continue;
2478
2479 return _error->Error(_("%s dependency for %s cannot be satisfied "
2480 "because the package %s cannot be found"),
2481 Last->BuildDepType((*D).Type),Src.c_str(),
2482 (*D).Package.c_str());
2483 }
2484
2485 /*
2486 * if there are alternatives, we've already picked one, so skip
2487 * the rest
2488 *
2489 * TODO: this means that if there's a build-dep on A|B and B is
2490 * installed, we'll still try to install A; more importantly,
2491 * if A is currently broken, we cannot go back and try B. To fix
2492 * this would require we do a Resolve cycle for each package we
2493 * add to the install list. Ugh
2494 */
2495
2496 /*
2497 * If this is a virtual package, we need to check the list of
2498 * packages that provide it and see if any of those are
2499 * installed
2500 */
2501 pkgCache::PrvIterator Prv = Pkg.ProvidesList();
2502 for (; Prv.end() != true; Prv++)
2503 {
2504 if (_config->FindB("Debug::BuildDeps",false) == true)
2505 cout << " Checking provider " << Prv.OwnerPkg().FullName() << endl;
2506
2507 if ((*Cache)[Prv.OwnerPkg()].InstVerIter(*Cache).end() == false)
2508 break;
2509 }
2510
2511 // Get installed version and version we are going to install
2512 pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
2513
2514 if ((*D).Version[0] != '\0') {
2515 // Versioned dependency
2516
2517 pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
2518
2519 for (; CV.end() != true; CV++)
2520 {
2521 if (Cache->VS().CheckDep(CV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
2522 break;
2523 }
2524 if (CV.end() == true)
2525 {
2526 if (hasAlternatives)
2527 {
2528 continue;
2529 }
2530 else
2531 {
2532 return _error->Error(_("%s dependency for %s cannot be satisfied "
2533 "because no available versions of package %s "
2534 "can satisfy version requirements"),
2535 Last->BuildDepType((*D).Type),Src.c_str(),
2536 (*D).Package.c_str());
2537 }
2538 }
2539 }
2540 else
2541 {
2542 // Only consider virtual packages if there is no versioned dependency
2543 if (Prv.end() == false)
2544 {
2545 if (_config->FindB("Debug::BuildDeps",false) == true)
2546 cout << " Is provided by installed package " << Prv.OwnerPkg().FullName() << endl;
2547 skipAlternatives = hasAlternatives;
2548 continue;
2549 }
2550 }
2551
2552 if (IV.end() == false)
2553 {
2554 if (_config->FindB("Debug::BuildDeps",false) == true)
2555 cout << " Is installed\n";
2556
2557 if (Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
2558 {
2559 skipAlternatives = hasAlternatives;
2560 continue;
2561 }
2562
2563 if (_config->FindB("Debug::BuildDeps",false) == true)
2564 cout << " ...but the installed version doesn't meet the version requirement\n";
2565
2566 if (((*D).Op & pkgCache::Dep::LessEq) == pkgCache::Dep::LessEq)
2567 {
2568 return _error->Error(_("Failed to satisfy %s dependency for %s: Installed package %s is too new"),
2569 Last->BuildDepType((*D).Type),
2570 Src.c_str(),
2571 Pkg.FullName(true).c_str());
2572 }
2573 }
2574
2575
2576 if (_config->FindB("Debug::BuildDeps",false) == true)
2577 cout << " Trying to install " << (*D).Package << endl;
2578
2579 if (TryToInstall(Pkg,Cache,Fix,false,false,ExpectedInst) == true)
2580 {
2581 // We successfully installed something; skip remaining alternatives
2582 skipAlternatives = hasAlternatives;
2583 if(_config->FindB("APT::Get::Build-Dep-Automatic", false) == true)
2584 Cache->MarkAuto(Pkg, true);
2585 continue;
2586 }
2587 else if (hasAlternatives)
2588 {
2589 if (_config->FindB("Debug::BuildDeps",false) == true)
2590 cout << " Unsatisfiable, trying alternatives\n";
2591 continue;
2592 }
2593 else
2594 {
2595 return _error->Error(_("Failed to satisfy %s dependency for %s: %s"),
2596 Last->BuildDepType((*D).Type),
2597 Src.c_str(),
2598 (*D).Package.c_str());
2599 }
2600 }
2601 }
2602
2603 Fix.InstallProtect();
2604 if (Fix.Resolve(true) == false)
2605 _error->Discard();
2606
2607 // Now we check the state of the packages,
2608 if (Cache->BrokenCount() != 0)
2609 {
2610 ShowBroken(cout, Cache, false);
2611 return _error->Error(_("Build-dependencies for %s could not be satisfied."),*I);
2612 }
2613 }
2614
2615 if (InstallPackages(Cache, false, true) == false)
2616 return _error->Error(_("Failed to process build dependencies"));
2617 return true;
2618 }
2619 /*}}}*/
2620 // DoMoo - Never Ask, Never Tell /*{{{*/
2621 // ---------------------------------------------------------------------
2622 /* */
2623 bool DoMoo(CommandLine &CmdL)
2624 {
2625 cout <<
2626 " (__) \n"
2627 " (oo) \n"
2628 " /------\\/ \n"
2629 " / | || \n"
2630 " * /\\---/\\ \n"
2631 " ~~ ~~ \n"
2632 "....\"Have you mooed today?\"...\n";
2633
2634 return true;
2635 }
2636 /*}}}*/
2637 // ShowHelp - Show a help screen /*{{{*/
2638 // ---------------------------------------------------------------------
2639 /* */
2640 bool ShowHelp(CommandLine &CmdL)
2641 {
2642 ioprintf(cout,_("%s %s for %s compiled on %s %s\n"),PACKAGE,VERSION,
2643 COMMON_ARCH,__DATE__,__TIME__);
2644
2645 if (_config->FindB("version") == true)
2646 {
2647 cout << _("Supported modules:") << endl;
2648
2649 for (unsigned I = 0; I != pkgVersioningSystem::GlobalListLen; I++)
2650 {
2651 pkgVersioningSystem *VS = pkgVersioningSystem::GlobalList[I];
2652 if (_system != 0 && _system->VS == VS)
2653 cout << '*';
2654 else
2655 cout << ' ';
2656 cout << "Ver: " << VS->Label << endl;
2657
2658 /* Print out all the packaging systems that will work with
2659 this VS */
2660 for (unsigned J = 0; J != pkgSystem::GlobalListLen; J++)
2661 {
2662 pkgSystem *Sys = pkgSystem::GlobalList[J];
2663 if (_system == Sys)
2664 cout << '*';
2665 else
2666 cout << ' ';
2667 if (Sys->VS->TestCompatibility(*VS) == true)
2668 cout << "Pkg: " << Sys->Label << " (Priority " << Sys->Score(*_config) << ")" << endl;
2669 }
2670 }
2671
2672 for (unsigned I = 0; I != pkgSourceList::Type::GlobalListLen; I++)
2673 {
2674 pkgSourceList::Type *Type = pkgSourceList::Type::GlobalList[I];
2675 cout << " S.L: '" << Type->Name << "' " << Type->Label << endl;
2676 }
2677
2678 for (unsigned I = 0; I != pkgIndexFile::Type::GlobalListLen; I++)
2679 {
2680 pkgIndexFile::Type *Type = pkgIndexFile::Type::GlobalList[I];
2681 cout << " Idx: " << Type->Label << endl;
2682 }
2683
2684 return true;
2685 }
2686
2687 cout <<
2688 _("Usage: apt-get [options] command\n"
2689 " apt-get [options] install|remove pkg1 [pkg2 ...]\n"
2690 " apt-get [options] source pkg1 [pkg2 ...]\n"
2691 "\n"
2692 "apt-get is a simple command line interface for downloading and\n"
2693 "installing packages. The most frequently used commands are update\n"
2694 "and install.\n"
2695 "\n"
2696 "Commands:\n"
2697 " update - Retrieve new lists of packages\n"
2698 " upgrade - Perform an upgrade\n"
2699 " install - Install new packages (pkg is libc6 not libc6.deb)\n"
2700 " remove - Remove packages\n"
2701 " autoremove - Remove automatically all unused packages\n"
2702 " purge - Remove packages and config files\n"
2703 " source - Download source archives\n"
2704 " build-dep - Configure build-dependencies for source packages\n"
2705 " dist-upgrade - Distribution upgrade, see apt-get(8)\n"
2706 " dselect-upgrade - Follow dselect selections\n"
2707 " clean - Erase downloaded archive files\n"
2708 " autoclean - Erase old downloaded archive files\n"
2709 " check - Verify that there are no broken dependencies\n"
2710 " markauto - Mark the given packages as automatically installed\n"
2711 " unmarkauto - Mark the given packages as manually installed\n"
2712 "\n"
2713 "Options:\n"
2714 " -h This help text.\n"
2715 " -q Loggable output - no progress indicator\n"
2716 " -qq No output except for errors\n"
2717 " -d Download only - do NOT install or unpack archives\n"
2718 " -s No-act. Perform ordering simulation\n"
2719 " -y Assume Yes to all queries and do not prompt\n"
2720 " -f Attempt to correct a system with broken dependencies in place\n"
2721 " -m Attempt to continue if archives are unlocatable\n"
2722 " -u Show a list of upgraded packages as well\n"
2723 " -b Build the source package after fetching it\n"
2724 " -V Show verbose version numbers\n"
2725 " -c=? Read this configuration file\n"
2726 " -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp\n"
2727 "See the apt-get(8), sources.list(5) and apt.conf(5) manual\n"
2728 "pages for more information and options.\n"
2729 " This APT has Super Cow Powers.\n");
2730 return true;
2731 }
2732 /*}}}*/
2733 // GetInitialize - Initialize things for apt-get /*{{{*/
2734 // ---------------------------------------------------------------------
2735 /* */
2736 void GetInitialize()
2737 {
2738 _config->Set("quiet",0);
2739 _config->Set("help",false);
2740 _config->Set("APT::Get::Download-Only",false);
2741 _config->Set("APT::Get::Simulate",false);
2742 _config->Set("APT::Get::Assume-Yes",false);
2743 _config->Set("APT::Get::Fix-Broken",false);
2744 _config->Set("APT::Get::Force-Yes",false);
2745 _config->Set("APT::Get::List-Cleanup",true);
2746 _config->Set("APT::Get::AutomaticRemove",false);
2747 }
2748 /*}}}*/
2749 // SigWinch - Window size change signal handler /*{{{*/
2750 // ---------------------------------------------------------------------
2751 /* */
2752 void SigWinch(int)
2753 {
2754 // Riped from GNU ls
2755 #ifdef TIOCGWINSZ
2756 struct winsize ws;
2757
2758 if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col >= 5)
2759 ScreenWidth = ws.ws_col - 1;
2760 #endif
2761 }
2762 /*}}}*/
2763 int main(int argc,const char *argv[]) /*{{{*/
2764 {
2765 CommandLine::Args Args[] = {
2766 {'h',"help","help",0},
2767 {'v',"version","version",0},
2768 {'V',"verbose-versions","APT::Get::Show-Versions",0},
2769 {'q',"quiet","quiet",CommandLine::IntLevel},
2770 {'q',"silent","quiet",CommandLine::IntLevel},
2771 {'d',"download-only","APT::Get::Download-Only",0},
2772 {'b',"compile","APT::Get::Compile",0},
2773 {'b',"build","APT::Get::Compile",0},
2774 {'s',"simulate","APT::Get::Simulate",0},
2775 {'s',"just-print","APT::Get::Simulate",0},
2776 {'s',"recon","APT::Get::Simulate",0},
2777 {'s',"dry-run","APT::Get::Simulate",0},
2778 {'s',"no-act","APT::Get::Simulate",0},
2779 {'y',"yes","APT::Get::Assume-Yes",0},
2780 {'y',"assume-yes","APT::Get::Assume-Yes",0},
2781 {'f',"fix-broken","APT::Get::Fix-Broken",0},
2782 {'u',"show-upgraded","APT::Get::Show-Upgraded",0},
2783 {'m',"ignore-missing","APT::Get::Fix-Missing",0},
2784 {'t',"target-release","APT::Default-Release",CommandLine::HasArg},
2785 {'t',"default-release","APT::Default-Release",CommandLine::HasArg},
2786 {0,"download","APT::Get::Download",0},
2787 {0,"fix-missing","APT::Get::Fix-Missing",0},
2788 {0,"ignore-hold","APT::Ignore-Hold",0},
2789 {0,"upgrade","APT::Get::upgrade",0},
2790 {0,"only-upgrade","APT::Get::Only-Upgrade",0},
2791 {0,"force-yes","APT::Get::force-yes",0},
2792 {0,"print-uris","APT::Get::Print-URIs",0},
2793 {0,"diff-only","APT::Get::Diff-Only",0},
2794 {0,"debian-only","APT::Get::Diff-Only",0},
2795 {0,"tar-only","APT::Get::Tar-Only",0},
2796 {0,"dsc-only","APT::Get::Dsc-Only",0},
2797 {0,"purge","APT::Get::Purge",0},
2798 {0,"list-cleanup","APT::Get::List-Cleanup",0},
2799 {0,"reinstall","APT::Get::ReInstall",0},
2800 {0,"trivial-only","APT::Get::Trivial-Only",0},
2801 {0,"remove","APT::Get::Remove",0},
2802 {0,"only-source","APT::Get::Only-Source",0},
2803 {0,"arch-only","APT::Get::Arch-Only",0},
2804 {0,"auto-remove","APT::Get::AutomaticRemove",0},
2805 {0,"allow-unauthenticated","APT::Get::AllowUnauthenticated",0},
2806 {0,"install-recommends","APT::Install-Recommends",CommandLine::Boolean},
2807 {0,"fix-policy","APT::Get::Fix-Policy-Broken",0},
2808 {'c',"config-file",0,CommandLine::ConfigFile},
2809 {'o',"option",0,CommandLine::ArbItem},
2810 {0,0,0,0}};
2811 CommandLine::Dispatch Cmds[] = {{"update",&DoUpdate},
2812 {"upgrade",&DoUpgrade},
2813 {"install",&DoInstall},
2814 {"remove",&DoInstall},
2815 {"purge",&DoInstall},
2816 {"autoremove",&DoInstall},
2817 {"markauto",&DoMarkAuto},
2818 {"unmarkauto",&DoMarkAuto},
2819 {"dist-upgrade",&DoDistUpgrade},
2820 {"dselect-upgrade",&DoDSelectUpgrade},
2821 {"build-dep",&DoBuildDep},
2822 {"clean",&DoClean},
2823 {"autoclean",&DoAutoClean},
2824 {"check",&DoCheck},
2825 {"source",&DoSource},
2826 {"moo",&DoMoo},
2827 {"help",&ShowHelp},
2828 {0,0}};
2829
2830 // Set up gettext support
2831 setlocale(LC_ALL,"");
2832 textdomain(PACKAGE);
2833
2834 // Parse the command line and initialize the package library
2835 CommandLine CmdL(Args,_config);
2836 if (pkgInitConfig(*_config) == false ||
2837 CmdL.Parse(argc,argv) == false ||
2838 pkgInitSystem(*_config,_system) == false)
2839 {
2840 if (_config->FindB("version") == true)
2841 ShowHelp(CmdL);
2842
2843 _error->DumpErrors();
2844 return 100;
2845 }
2846
2847 // See if the help should be shown
2848 if (_config->FindB("help") == true ||
2849 _config->FindB("version") == true ||
2850 CmdL.FileSize() == 0)
2851 {
2852 ShowHelp(CmdL);
2853 return 0;
2854 }
2855
2856 // simulate user-friendly if apt-get has no root privileges
2857 if (getuid() != 0 && _config->FindB("APT::Get::Simulate") == true)
2858 {
2859 if (_config->FindB("APT::Get::Show-User-Simulation-Note",true) == true)
2860 cout << _("NOTE: This is only a simulation!\n"
2861 " apt-get needs root privileges for real execution.\n"
2862 " Keep also in mind that locking is deactivated,\n"
2863 " so don't depend on the relevance to the real current situation!"
2864 ) << std::endl;
2865 _config->Set("Debug::NoLocking",true);
2866 }
2867
2868 // Deal with stdout not being a tty
2869 if (!isatty(STDOUT_FILENO) && _config->FindI("quiet",0) < 1)
2870 _config->Set("quiet","1");
2871
2872 // Setup the output streams
2873 c0out.rdbuf(cout.rdbuf());
2874 c1out.rdbuf(cout.rdbuf());
2875 c2out.rdbuf(cout.rdbuf());
2876 if (_config->FindI("quiet",0) > 0)
2877 c0out.rdbuf(devnull.rdbuf());
2878 if (_config->FindI("quiet",0) > 1)
2879 c1out.rdbuf(devnull.rdbuf());
2880
2881 // Setup the signals
2882 signal(SIGPIPE,SIG_IGN);
2883 signal(SIGWINCH,SigWinch);
2884 SigWinch(0);
2885
2886 // Match the operation
2887 CmdL.DispatchArg(Cmds);
2888
2889 // Print any errors or warnings found during parsing
2890 if (_error->empty() == false)
2891 {
2892 bool Errors = _error->PendingError();
2893 _error->DumpErrors();
2894 return Errors == true?100:0;
2895 }
2896
2897 return 0;
2898 }
2899 /*}}}*/