Improved message
[ntk/apt.git] / cmdline / apt-get.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Description /*{{{*/
3 // $Id: apt-get.cc,v 1.86 1999/10/27 05:00:25 jgg 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/dpkgpm.h>
36 #include <apt-pkg/strutl.h>
37 #include <apt-pkg/clean.h>
38 #include <apt-pkg/srcrecords.h>
39 #include <apt-pkg/version.h>
40 #include <apt-pkg/cachefile.h>
41
42 #include <config.h>
43
44 #include "acqprogress.h"
45
46 #include <fstream.h>
47 #include <termios.h>
48 #include <sys/ioctl.h>
49 #include <sys/stat.h>
50 #include <sys/vfs.h>
51 #include <signal.h>
52 #include <unistd.h>
53 #include <stdio.h>
54 #include <errno.h>
55 #include <regex.h>
56 #include <sys/wait.h>
57 /*}}}*/
58
59 ostream c0out;
60 ostream c1out;
61 ostream c2out;
62 ofstream devnull("/dev/null");
63 unsigned int ScreenWidth = 80;
64
65 // class CacheFile - Cover class for some dependency cache functions /*{{{*/
66 // ---------------------------------------------------------------------
67 /* */
68 class CacheFile : public pkgCacheFile
69 {
70 static pkgCache *SortCache;
71 static int NameComp(const void *a,const void *b);
72
73 public:
74 pkgCache::Package **List;
75
76 void Sort();
77 bool CheckDeps(bool AllowBroken = false);
78 bool Open(bool WithLock = true)
79 {
80 OpTextProgress Prog(*_config);
81 if (pkgCacheFile::Open(Prog,WithLock) == false)
82 return false;
83 Sort();
84 return true;
85 };
86 CacheFile() : List(0) {};
87 };
88 /*}}}*/
89
90 // YnPrompt - Yes No Prompt. /*{{{*/
91 // ---------------------------------------------------------------------
92 /* Returns true on a Yes.*/
93 bool YnPrompt()
94 {
95 if (_config->FindB("APT::Get::Assume-Yes",false) == true)
96 {
97 c1out << 'Y' << endl;
98 return true;
99 }
100
101 char C = 0;
102 char Jnk = 0;
103 read(STDIN_FILENO,&C,1);
104 while (C != '\n' && Jnk != '\n') read(STDIN_FILENO,&Jnk,1);
105
106 if (!(C == 'Y' || C == 'y' || C == '\n' || C == '\r'))
107 return false;
108 return true;
109 }
110 /*}}}*/
111 // AnalPrompt - Annoying Yes No Prompt. /*{{{*/
112 // ---------------------------------------------------------------------
113 /* Returns true on a Yes.*/
114 bool AnalPrompt(const char *Text)
115 {
116 char Buf[1024];
117 cin.getline(Buf,sizeof(Buf));
118 if (strcmp(Buf,Text) == 0)
119 return true;
120 return false;
121 }
122 /*}}}*/
123 // ShowList - Show a list /*{{{*/
124 // ---------------------------------------------------------------------
125 /* This prints out a string of space seperated words with a title and
126 a two space indent line wraped to the current screen width. */
127 bool ShowList(ostream &out,string Title,string List)
128 {
129 if (List.empty() == true)
130 return true;
131
132 // Acount for the leading space
133 int ScreenWidth = ::ScreenWidth - 3;
134
135 out << Title << endl;
136 string::size_type Start = 0;
137 while (Start < List.size())
138 {
139 string::size_type End;
140 if (Start + ScreenWidth >= List.size())
141 End = List.size();
142 else
143 End = List.rfind(' ',Start+ScreenWidth);
144
145 if (End == string::npos || End < Start)
146 End = Start + ScreenWidth;
147 out << " " << string(List,Start,End - Start) << endl;
148 Start = End + 1;
149 }
150 return false;
151 }
152 /*}}}*/
153 // ShowBroken - Debugging aide /*{{{*/
154 // ---------------------------------------------------------------------
155 /* This prints out the names of all the packages that are broken along
156 with the name of each each broken dependency and a quite version
157 description. */
158 void ShowBroken(ostream &out,CacheFile &Cache,bool Now)
159 {
160 out << "Sorry, but the following packages have unmet dependencies:" << endl;
161 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
162 {
163 pkgCache::PkgIterator I(Cache,Cache.List[J]);
164
165 if (Cache[I].InstBroken() == false)
166 continue;
167
168 // Print out each package and the failed dependencies
169 out <<" " << I.Name() << ":";
170 unsigned Indent = strlen(I.Name()) + 3;
171 bool First = true;
172 if (Cache[I].InstVerIter(Cache).end() == true)
173 {
174 cout << endl;
175 continue;
176 }
177
178 for (pkgCache::DepIterator D = Cache[I].InstVerIter(Cache).DependsList(); D.end() == false;)
179 {
180 // Compute a single dependency element (glob or)
181 pkgCache::DepIterator Start;
182 pkgCache::DepIterator End;
183 D.GlobOr(Start,End);
184
185 if (Cache->IsImportantDep(End) == false ||
186 (Cache[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall)
187 continue;
188
189 bool FirstOr = true;
190 while (1)
191 {
192 if (First == false)
193 for (unsigned J = 0; J != Indent; J++)
194 out << ' ';
195 First = false;
196
197 if (FirstOr == false)
198 {
199 for (unsigned J = 0; J != strlen(End.DepType()) + 3; J++)
200 out << ' ';
201 }
202 else
203 out << ' ' << End.DepType() << ": ";
204 FirstOr = false;
205
206 out << Start.TargetPkg().Name();
207
208 // Show a quick summary of the version requirements
209 if (Start.TargetVer() != 0)
210 out << " (" << Start.CompType() << " " << Start.TargetVer() <<
211 ")";
212
213 /* Show a summary of the target package if possible. In the case
214 of virtual packages we show nothing */
215 pkgCache::PkgIterator Targ = Start.TargetPkg();
216 if (Targ->ProvidesList == 0)
217 {
218 out << " but ";
219 pkgCache::VerIterator Ver = Cache[Targ].InstVerIter(Cache);
220 if (Ver.end() == false)
221 out << Ver.VerStr() << (Now?" is installed":" is to be installed");
222 else
223 {
224 if (Cache[Targ].CandidateVerIter(Cache).end() == true)
225 {
226 if (Targ->ProvidesList == 0)
227 out << "it is not installable";
228 else
229 out << "it is a virtual package";
230 }
231 else
232 out << (Now?"it is not installed":"it is not going to be installed");
233 }
234 }
235
236 if (Start != End)
237 cout << " or";
238 out << endl;
239
240 if (Start == End)
241 break;
242 Start++;
243 }
244 }
245 }
246 }
247 /*}}}*/
248 // ShowNew - Show packages to newly install /*{{{*/
249 // ---------------------------------------------------------------------
250 /* */
251 void ShowNew(ostream &out,CacheFile &Cache)
252 {
253 /* Print out a list of packages that are going to be removed extra
254 to what the user asked */
255 string List;
256 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
257 {
258 pkgCache::PkgIterator I(Cache,Cache.List[J]);
259 if (Cache[I].NewInstall() == true)
260 List += string(I.Name()) + " ";
261 }
262
263 ShowList(out,"The following NEW packages will be installed:",List);
264 }
265 /*}}}*/
266 // ShowDel - Show packages to delete /*{{{*/
267 // ---------------------------------------------------------------------
268 /* */
269 void ShowDel(ostream &out,CacheFile &Cache)
270 {
271 /* Print out a list of packages that are going to be removed extra
272 to what the user asked */
273 string List;
274 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
275 {
276 pkgCache::PkgIterator I(Cache,Cache.List[J]);
277 if (Cache[I].Delete() == true)
278 {
279 if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
280 List += string(I.Name()) + "* ";
281 else
282 List += string(I.Name()) + " ";
283 }
284 }
285
286 ShowList(out,"The following packages will be REMOVED:",List);
287 }
288 /*}}}*/
289 // ShowKept - Show kept packages /*{{{*/
290 // ---------------------------------------------------------------------
291 /* */
292 void ShowKept(ostream &out,CacheFile &Cache)
293 {
294 string List;
295 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
296 {
297 pkgCache::PkgIterator I(Cache,Cache.List[J]);
298
299 // Not interesting
300 if (Cache[I].Upgrade() == true || Cache[I].Upgradable() == false ||
301 I->CurrentVer == 0 || Cache[I].Delete() == true)
302 continue;
303
304 List += string(I.Name()) + " ";
305 }
306 ShowList(out,"The following packages have been kept back",List);
307 }
308 /*}}}*/
309 // ShowUpgraded - Show upgraded packages /*{{{*/
310 // ---------------------------------------------------------------------
311 /* */
312 void ShowUpgraded(ostream &out,CacheFile &Cache)
313 {
314 string List;
315 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
316 {
317 pkgCache::PkgIterator I(Cache,Cache.List[J]);
318
319 // Not interesting
320 if (Cache[I].Upgrade() == false || Cache[I].NewInstall() == true)
321 continue;
322
323 List += string(I.Name()) + " ";
324 }
325 ShowList(out,"The following packages will be upgraded",List);
326 }
327 /*}}}*/
328 // ShowHold - Show held but changed packages /*{{{*/
329 // ---------------------------------------------------------------------
330 /* */
331 bool ShowHold(ostream &out,CacheFile &Cache)
332 {
333 string List;
334 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
335 {
336 pkgCache::PkgIterator I(Cache,Cache.List[J]);
337 if (Cache[I].InstallVer != (pkgCache::Version *)I.CurrentVer() &&
338 I->SelectedState == pkgCache::State::Hold)
339 List += string(I.Name()) + " ";
340 }
341
342 return ShowList(out,"The following held packages will be changed:",List);
343 }
344 /*}}}*/
345 // ShowEssential - Show an essential package warning /*{{{*/
346 // ---------------------------------------------------------------------
347 /* This prints out a warning message that is not to be ignored. It shows
348 all essential packages and their dependents that are to be removed.
349 It is insanely risky to remove the dependents of an essential package! */
350 bool ShowEssential(ostream &out,CacheFile &Cache)
351 {
352 string List;
353 bool *Added = new bool[Cache->HeaderP->PackageCount];
354 for (unsigned int I = 0; I != Cache->HeaderP->PackageCount; I++)
355 Added[I] = false;
356
357 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
358 {
359 pkgCache::PkgIterator I(Cache,Cache.List[J]);
360 if ((I->Flags & pkgCache::Flag::Essential) != pkgCache::Flag::Essential)
361 continue;
362
363 // The essential package is being removed
364 if (Cache[I].Delete() == true)
365 {
366 if (Added[I->ID] == false)
367 {
368 Added[I->ID] = true;
369 List += string(I.Name()) + " ";
370 }
371 }
372
373 if (I->CurrentVer == 0)
374 continue;
375
376 // Print out any essential package depenendents that are to be removed
377 for (pkgDepCache::DepIterator D = I.CurrentVer().DependsList(); D.end() == false; D++)
378 {
379 // Skip everything but depends
380 if (D->Type != pkgCache::Dep::PreDepends &&
381 D->Type != pkgCache::Dep::Depends)
382 continue;
383
384 pkgCache::PkgIterator P = D.SmartTargetPkg();
385 if (Cache[P].Delete() == true)
386 {
387 if (Added[P->ID] == true)
388 continue;
389 Added[P->ID] = true;
390
391 char S[300];
392 sprintf(S,"%s (due to %s) ",P.Name(),I.Name());
393 List += S;
394 }
395 }
396 }
397
398 delete [] Added;
399 if (List.empty() == false)
400 out << "WARNING: The following essential packages will be removed" << endl;
401 return ShowList(out,"This should NOT be done unless you know exactly what you are doing!",List);
402 }
403 /*}}}*/
404 // Stats - Show some statistics /*{{{*/
405 // ---------------------------------------------------------------------
406 /* */
407 void Stats(ostream &out,pkgDepCache &Dep)
408 {
409 unsigned long Upgrade = 0;
410 unsigned long Install = 0;
411 unsigned long ReInstall = 0;
412 for (pkgCache::PkgIterator I = Dep.PkgBegin(); I.end() == false; I++)
413 {
414 if (Dep[I].NewInstall() == true)
415 Install++;
416 else
417 if (Dep[I].Upgrade() == true)
418 Upgrade++;
419 if (Dep[I].Delete() == false && (Dep[I].iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
420 ReInstall++;
421 }
422
423 out << Upgrade << " packages upgraded, " <<
424 Install << " newly installed, ";
425 if (ReInstall != 0)
426 out << ReInstall << " reinstalled, ";
427 out << Dep.DelCount() << " to remove and " <<
428 Dep.KeepCount() << " not upgraded." << endl;
429
430 if (Dep.BadCount() != 0)
431 out << Dep.BadCount() << " packages not fully installed or removed." << endl;
432 }
433 /*}}}*/
434
435 // CacheFile::NameComp - QSort compare by name /*{{{*/
436 // ---------------------------------------------------------------------
437 /* */
438 pkgCache *CacheFile::SortCache = 0;
439 int CacheFile::NameComp(const void *a,const void *b)
440 {
441 if (*(pkgCache::Package **)a == 0 || *(pkgCache::Package **)b == 0)
442 return *(pkgCache::Package **)a - *(pkgCache::Package **)b;
443
444 const pkgCache::Package &A = **(pkgCache::Package **)a;
445 const pkgCache::Package &B = **(pkgCache::Package **)b;
446
447 return strcmp(SortCache->StrP + A.Name,SortCache->StrP + B.Name);
448 }
449 /*}}}*/
450 // CacheFile::Sort - Sort by name /*{{{*/
451 // ---------------------------------------------------------------------
452 /* */
453 void CacheFile::Sort()
454 {
455 delete [] List;
456 List = new pkgCache::Package *[Cache->Head().PackageCount];
457 memset(List,0,sizeof(*List)*Cache->Head().PackageCount);
458 pkgCache::PkgIterator I = Cache->PkgBegin();
459 for (;I.end() != true; I++)
460 List[I->ID] = I;
461
462 SortCache = *this;
463 qsort(List,Cache->Head().PackageCount,sizeof(*List),NameComp);
464 }
465 /*}}}*/
466 // CacheFile::Open - Open the cache file /*{{{*/
467 // ---------------------------------------------------------------------
468 /* This routine generates the caches and then opens the dependency cache
469 and verifies that the system is OK. */
470 bool CacheFile::CheckDeps(bool AllowBroken)
471 {
472 if (_error->PendingError() == true)
473 return false;
474
475 // Check that the system is OK
476 if (Cache->DelCount() != 0 || Cache->InstCount() != 0)
477 return _error->Error("Internal Error, non-zero counts");
478
479 // Apply corrections for half-installed packages
480 if (pkgApplyStatus(*Cache) == false)
481 return false;
482
483 // Nothing is broken
484 if (Cache->BrokenCount() == 0 || AllowBroken == true)
485 return true;
486
487 // Attempt to fix broken things
488 if (_config->FindB("APT::Get::Fix-Broken",false) == true)
489 {
490 c1out << "Correcting dependencies..." << flush;
491 if (pkgFixBroken(*Cache) == false || Cache->BrokenCount() != 0)
492 {
493 c1out << " failed." << endl;
494 ShowBroken(c1out,*this,true);
495
496 return _error->Error("Unable to correct dependencies");
497 }
498 if (pkgMinimizeUpgrade(*Cache) == false)
499 return _error->Error("Unable to minimize the upgrade set");
500
501 c1out << " Done" << endl;
502 }
503 else
504 {
505 c1out << "You might want to run `apt-get -f install' to correct these." << endl;
506 ShowBroken(c1out,*this,true);
507
508 return _error->Error("Unmet dependencies. Try using -f.");
509 }
510
511 return true;
512 }
513 /*}}}*/
514
515 // InstallPackages - Actually download and install the packages /*{{{*/
516 // ---------------------------------------------------------------------
517 /* This displays the informative messages describing what is going to
518 happen and then calls the download routines */
519 bool InstallPackages(CacheFile &Cache,bool ShwKept,bool Ask = true,bool Saftey = true)
520 {
521 if (_config->FindB("APT::Get::Purge",false) == true)
522 {
523 pkgCache::PkgIterator I = Cache->PkgBegin();
524 for (; I.end() == false; I++)
525 {
526 if (I.Purge() == false && Cache[I].Mode == pkgDepCache::ModeDelete)
527 Cache->MarkDelete(I,true);
528 }
529 }
530
531 bool Fail = false;
532 bool Essential = false;
533
534 // Show all the various warning indicators
535 ShowDel(c1out,Cache);
536 ShowNew(c1out,Cache);
537 if (ShwKept == true)
538 ShowKept(c1out,Cache);
539 Fail |= !ShowHold(c1out,Cache);
540 if (_config->FindB("APT::Get::Show-Upgraded",false) == true)
541 ShowUpgraded(c1out,Cache);
542 Essential = !ShowEssential(c1out,Cache);
543 Fail |= Essential;
544 Stats(c1out,Cache);
545
546 // Sanity check
547 if (Cache->BrokenCount() != 0)
548 {
549 ShowBroken(c1out,Cache,false);
550 return _error->Error("Internal Error, InstallPackages was called with broken packages!");
551 }
552
553 if (Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
554 Cache->BadCount() == 0)
555 return true;
556
557 // Run the simulator ..
558 if (_config->FindB("APT::Get::Simulate") == true)
559 {
560 pkgSimulate PM(Cache);
561 pkgPackageManager::OrderResult Res = PM.DoInstall();
562 if (Res == pkgPackageManager::Failed)
563 return false;
564 if (Res != pkgPackageManager::Completed)
565 return _error->Error("Internal Error, Ordering didn't finish");
566 return true;
567 }
568
569 // Create the text record parser
570 pkgRecords Recs(Cache);
571 if (_error->PendingError() == true)
572 return false;
573
574 // Lock the archive directory
575 FileFd Lock;
576 if (_config->FindB("Debug::NoLocking",false) == false)
577 {
578 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
579 if (_error->PendingError() == true)
580 return _error->Error("Unable to lock the download directory");
581 }
582
583 // Create the download object
584 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
585 pkgAcquire Fetcher(&Stat);
586
587 // Read the source list
588 pkgSourceList List;
589 if (List.ReadMainList() == false)
590 return _error->Error("The list of sources could not be read.");
591
592 // Create the package manager and prepare to download
593 pkgDPkgPM PM(Cache);
594 if (PM.GetArchives(&Fetcher,&List,&Recs) == false ||
595 _error->PendingError() == true)
596 return false;
597
598 // Display statistics
599 unsigned long FetchBytes = Fetcher.FetchNeeded();
600 unsigned long FetchPBytes = Fetcher.PartialPresent();
601 unsigned long DebBytes = Fetcher.TotalNeeded();
602 if (DebBytes != Cache->DebSize())
603 {
604 c0out << DebBytes << ',' << Cache->DebSize() << endl;
605 c0out << "How odd.. The sizes didn't match, email apt@packages.debian.org" << endl;
606 }
607
608 // Number of bytes
609 c1out << "Need to get ";
610 if (DebBytes != FetchBytes)
611 c1out << SizeToStr(FetchBytes) << "B/" << SizeToStr(DebBytes) << 'B';
612 else
613 c1out << SizeToStr(DebBytes) << 'B';
614
615 c1out << " of archives. After unpacking ";
616
617 // Check for enough free space
618 struct statfs Buf;
619 string OutputDir = _config->FindDir("Dir::Cache::Archives");
620 if (statfs(OutputDir.c_str(),&Buf) != 0)
621 return _error->Errno("statfs","Couldn't determine free space in %s",
622 OutputDir.c_str());
623 if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
624 return _error->Error("Sorry, you don't have enough free space in %s to hold all the .debs.",
625 OutputDir.c_str());
626
627 // Size delta
628 if (Cache->UsrSize() >= 0)
629 c1out << SizeToStr(Cache->UsrSize()) << "B will be used." << endl;
630 else
631 c1out << SizeToStr(-1*Cache->UsrSize()) << "B will be freed." << endl;
632
633 if (_error->PendingError() == true)
634 return false;
635
636 // Fail safe check
637 if (_config->FindI("quiet",0) >= 2 ||
638 _config->FindB("APT::Get::Assume-Yes",false) == true)
639 {
640 if (Fail == true && _config->FindB("APT::Get::Force-Yes",false) == false)
641 return _error->Error("There are problems and -y was used without --force-yes");
642 }
643
644 if (Essential == true && Saftey == true)
645 {
646 c2out << "You are about to do something potentially harmful" << endl;
647 c2out << "To continue type in the phrase 'Yes, I understand this may be bad'" << endl;
648 c2out << " ?] " << flush;
649 if (AnalPrompt("Yes, I understand this may be bad") == false)
650 {
651 c2out << "Abort." << endl;
652 exit(1);
653 }
654 }
655 else
656 {
657 // Prompt to continue
658 if (Ask == true || Fail == true)
659 {
660 if (_config->FindI("quiet",0) < 2 &&
661 _config->FindB("APT::Get::Assume-Yes",false) == false)
662 {
663 c2out << "Do you want to continue? [Y/n] " << flush;
664
665 if (YnPrompt() == false)
666 {
667 c2out << "Abort." << endl;
668 exit(1);
669 }
670 }
671 }
672 }
673
674 // Just print out the uris an exit if the --print-uris flag was used
675 if (_config->FindB("APT::Get::Print-URIs") == true)
676 {
677 pkgAcquire::UriIterator I = Fetcher.UriBegin();
678 for (; I != Fetcher.UriEnd(); I++)
679 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
680 I->Owner->FileSize << ' ' << I->Owner->MD5Sum() << endl;
681 return true;
682 }
683
684 // Run it
685 while (1)
686 {
687 if (_config->FindB("APT::Get::No-Download",false) == false)
688 if (Fetcher.Run() == pkgAcquire::Failed)
689 return false;
690
691 // Print out errors
692 bool Failed = false;
693 bool Transient = false;
694 for (pkgAcquire::Item **I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
695 {
696 if ((*I)->Status == pkgAcquire::Item::StatDone &&
697 (*I)->Complete == true)
698 continue;
699
700 if ((*I)->Status == pkgAcquire::Item::StatIdle)
701 {
702 Transient = true;
703 // Failed = true;
704 continue;
705 }
706
707 cerr << "Failed to fetch " << (*I)->DescURI() << endl;
708 cerr << " " << (*I)->ErrorText << endl;
709 Failed = true;
710 }
711
712 /* If we are in no download mode and missing files then there were
713 'failures' then the user must specify -m. Furthermore, there
714 is no such thing as a transient error in no-download mode! */
715 if (Transient == true &&
716 _config->FindB("APT::Get::No-Download",false) == true)
717 {
718 Transient = false;
719 Failed = true;
720 }
721
722 if (_config->FindB("APT::Get::Download-Only",false) == true)
723 {
724 if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
725 return _error->Error("Some files failed to download");
726 return true;
727 }
728
729 if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
730 {
731 return _error->Error("Unable to fetch some archives, maybe try with --fix-missing?");
732 }
733
734 if (Transient == true && Failed == true)
735 return _error->Error("--fix-missing and media swapping is not currently supported");
736
737 // Try to deal with missing package files
738 if (Failed == true && PM.FixMissing() == false)
739 {
740 cerr << "Unable to correct missing packages." << endl;
741 return _error->Error("Aborting Install.");
742 }
743
744 Cache.ReleaseLock();
745 pkgPackageManager::OrderResult Res = PM.DoInstall();
746 if (Res == pkgPackageManager::Failed || _error->PendingError() == true)
747 return false;
748 if (Res == pkgPackageManager::Completed)
749 return true;
750
751 // Reload the fetcher object and loop again for media swapping
752 Fetcher.Shutdown();
753 if (PM.GetArchives(&Fetcher,&List,&Recs) == false)
754 return false;
755 }
756 }
757 /*}}}*/
758 // TryToInstall - Try to install a single package /*{{{*/
759 // ---------------------------------------------------------------------
760 /* This used to be inlined in DoInstall, but with the advent of regex package
761 name matching it was split out.. */
762 bool TryToInstall(pkgCache::PkgIterator Pkg,pkgDepCache &Cache,
763 pkgProblemResolver &Fix,bool Remove,bool BrokenFix,
764 unsigned int &ExpectedInst,bool AllowFail = true)
765 {
766 /* This is a pure virtual package and there is a single available
767 provides */
768 if (Cache[Pkg].CandidateVer == 0 && Pkg->ProvidesList != 0 &&
769 Pkg.ProvidesList()->NextProvides == 0)
770 {
771 pkgCache::PkgIterator Tmp = Pkg.ProvidesList().OwnerPkg();
772 c1out << "Note, installing " << Tmp.Name() << " instead of " << Pkg.Name() << endl;
773 Pkg = Tmp;
774 }
775
776 // Handle the no-upgrade case
777 if (_config->FindB("APT::Get::no-upgrade",false) == true &&
778 Pkg->CurrentVer != 0)
779 {
780 if (AllowFail == true)
781 c1out << "Skipping " << Pkg.Name() << ", it is already installed and no-upgrade is set." << endl;
782 return true;
783 }
784
785 // Check if there is something at all to install
786 pkgDepCache::StateCache &State = Cache[Pkg];
787 if (State.CandidateVer == 0)
788 {
789 if (AllowFail == false)
790 return false;
791
792 if (Pkg->ProvidesList != 0)
793 {
794 c1out << "Package " << Pkg.Name() << " is a virtual package provided by:" << endl;
795
796 pkgCache::PrvIterator I = Pkg.ProvidesList();
797 for (; I.end() == false; I++)
798 {
799 pkgCache::PkgIterator Pkg = I.OwnerPkg();
800
801 if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer())
802 {
803 if (Cache[Pkg].Install() == true && Cache[Pkg].NewInstall() == false)
804 c1out << " " << Pkg.Name() << " " << I.OwnerVer().VerStr() <<
805 " [Installed]"<< endl;
806 else
807 c1out << " " << Pkg.Name() << " " << I.OwnerVer().VerStr() << endl;
808 }
809 }
810 c1out << "You should explicitly select one to install." << endl;
811 }
812 else
813 {
814 c1out << "Package " << Pkg.Name() << " has no available version, but exists in the database." << endl;
815 c1out << "This typically means that the package was mentioned in a dependency and " << endl;
816 c1out << "never uploaded, has been obsoleted or is not available with the contents " << endl;
817 c1out << "of sources.list" << endl;
818
819 string List;
820 pkgCache::DepIterator Dep = Pkg.RevDependsList();
821 for (; Dep.end() == false; Dep++)
822 {
823 if (Dep->Type != pkgCache::Dep::Replaces)
824 continue;
825 List += string(Dep.ParentPkg().Name()) + " ";
826 }
827 ShowList(c1out,"However the following packages replace it:",List);
828 }
829
830 _error->Error("Package %s has no installation candidate",Pkg.Name());
831 return false;
832 }
833
834 Fix.Clear(Pkg);
835 Fix.Protect(Pkg);
836 if (Remove == true)
837 {
838 Fix.Remove(Pkg);
839 Cache.MarkDelete(Pkg,_config->FindB("APT::Get::Purge",false));
840 return true;
841 }
842
843 // Install it
844 Cache.MarkInstall(Pkg,false);
845 if (State.Install() == false)
846 {
847 if (_config->FindB("APT::Get::ReInstall",false) == true)
848 {
849 if (Pkg->CurrentVer == 0 || Pkg.CurrentVer().Downloadable() == false)
850 c1out << "Sorry, re-installation of " << Pkg.Name() << " is not possible, it cannot be downloaded" << endl;
851 else
852 Cache.SetReInstall(Pkg,true);
853 }
854 else
855 {
856 if (AllowFail == true)
857 c1out << "Sorry, " << Pkg.Name() << " is already the newest version" << endl;
858 }
859 }
860 else
861 ExpectedInst++;
862
863 // Install it with autoinstalling enabled.
864 if (State.InstBroken() == true && BrokenFix == false)
865 Cache.MarkInstall(Pkg,true);
866 return true;
867 }
868 /*}}}*/
869
870 // DoUpdate - Update the package lists /*{{{*/
871 // ---------------------------------------------------------------------
872 /* */
873 bool DoUpdate(CommandLine &)
874 {
875 // Get the source list
876 pkgSourceList List;
877 if (List.ReadMainList() == false)
878 return false;
879
880 // Lock the list directory
881 FileFd Lock;
882 if (_config->FindB("Debug::NoLocking",false) == false)
883 {
884 Lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
885 if (_error->PendingError() == true)
886 return _error->Error("Unable to lock the list directory");
887 }
888
889 // Create the download object
890 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
891 pkgAcquire Fetcher(&Stat);
892
893 // Populate it with the source selection
894 pkgSourceList::const_iterator I;
895 for (I = List.begin(); I != List.end(); I++)
896 {
897 new pkgAcqIndex(&Fetcher,I);
898 if (_error->PendingError() == true)
899 return false;
900 }
901
902 // Run it
903 if (Fetcher.Run() == pkgAcquire::Failed)
904 return false;
905
906 bool Failed = false;
907 for (pkgAcquire::Item **I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
908 {
909 if ((*I)->Status == pkgAcquire::Item::StatDone)
910 continue;
911
912 (*I)->Finished();
913
914 cerr << "Failed to fetch " << (*I)->DescURI() << endl;
915 cerr << " " << (*I)->ErrorText << endl;
916 Failed = true;
917 }
918
919 // Clean out any old list files
920 if (_config->FindB("APT::Get::List-Cleanup",false) == false)
921 {
922 if (Fetcher.Clean(_config->FindDir("Dir::State::lists")) == false ||
923 Fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/") == false)
924 return false;
925 }
926
927 // Prepare the cache.
928 CacheFile Cache;
929 if (Cache.Open() == false)
930 return false;
931
932 if (Failed == true)
933 return _error->Error("Some index files failed to download, they have been ignored, or old ones used instead.");
934 return true;
935 }
936 /*}}}*/
937 // DoUpgrade - Upgrade all packages /*{{{*/
938 // ---------------------------------------------------------------------
939 /* Upgrade all packages without installing new packages or erasing old
940 packages */
941 bool DoUpgrade(CommandLine &CmdL)
942 {
943 CacheFile Cache;
944 if (Cache.Open() == false || Cache.CheckDeps() == false)
945 return false;
946
947 // Do the upgrade
948 if (pkgAllUpgrade(Cache) == false)
949 {
950 ShowBroken(c1out,Cache,false);
951 return _error->Error("Internal Error, AllUpgrade broke stuff");
952 }
953
954 return InstallPackages(Cache,true);
955 }
956 /*}}}*/
957 // DoInstall - Install packages from the command line /*{{{*/
958 // ---------------------------------------------------------------------
959 /* Install named packages */
960 bool DoInstall(CommandLine &CmdL)
961 {
962 CacheFile Cache;
963 if (Cache.Open() == false || Cache.CheckDeps(CmdL.FileSize() != 1) == false)
964 return false;
965
966 // Enter the special broken fixing mode if the user specified arguments
967 bool BrokenFix = false;
968 if (Cache->BrokenCount() != 0)
969 BrokenFix = true;
970
971 unsigned int ExpectedInst = 0;
972 unsigned int Packages = 0;
973 pkgProblemResolver Fix(Cache);
974
975 bool DefRemove = false;
976 if (strcasecmp(CmdL.FileList[0],"remove") == 0)
977 DefRemove = true;
978
979 for (const char **I = CmdL.FileList + 1; *I != 0; I++)
980 {
981 // Duplicate the string
982 unsigned int Length = strlen(*I);
983 char S[300];
984 if (Length >= sizeof(S))
985 continue;
986 strcpy(S,*I);
987
988 // See if we are removing the package
989 bool Remove = DefRemove;
990 while (Cache->FindPkg(S).end() == true)
991 {
992 // Handle an optional end tag indicating what to do
993 if (S[Length - 1] == '-')
994 {
995 Remove = true;
996 S[--Length] = 0;
997 continue;
998 }
999
1000 if (S[Length - 1] == '+')
1001 {
1002 Remove = false;
1003 S[--Length] = 0;
1004 continue;
1005 }
1006 break;
1007 }
1008
1009 // Locate the package
1010 pkgCache::PkgIterator Pkg = Cache->FindPkg(S);
1011 Packages++;
1012 if (Pkg.end() == true)
1013 {
1014 // Check if the name is a regex
1015 const char *I;
1016 for (I = S; *I != 0; I++)
1017 if (*I == '.' || *I == '?' || *I == '*')
1018 break;
1019 if (*I == 0)
1020 return _error->Error("Couldn't find package %s",S);
1021
1022 // Regexs must always be confirmed
1023 ExpectedInst += 1000;
1024
1025 // Compile the regex pattern
1026 regex_t Pattern;
1027 if (regcomp(&Pattern,S,REG_EXTENDED | REG_ICASE |
1028 REG_NOSUB) != 0)
1029 return _error->Error("Regex compilation error");
1030
1031 // Run over the matches
1032 bool Hit = false;
1033 for (Pkg = Cache->PkgBegin(); Pkg.end() == false; Pkg++)
1034 {
1035 if (regexec(&Pattern,Pkg.Name(),0,0,0) != 0)
1036 continue;
1037
1038 Hit |= TryToInstall(Pkg,Cache,Fix,Remove,BrokenFix,
1039 ExpectedInst,false);
1040 }
1041 regfree(&Pattern);
1042
1043 if (Hit == false)
1044 return _error->Error("Couldn't find package %s",S);
1045 }
1046 else
1047 {
1048 if (TryToInstall(Pkg,Cache,Fix,Remove,BrokenFix,ExpectedInst) == false)
1049 return false;
1050 }
1051 }
1052
1053 /* If we are in the Broken fixing mode we do not attempt to fix the
1054 problems. This is if the user invoked install without -f and gave
1055 packages */
1056 if (BrokenFix == true && Cache->BrokenCount() != 0)
1057 {
1058 c1out << "You might want to run `apt-get -f install' to correct these:" << endl;
1059 ShowBroken(c1out,Cache,false);
1060
1061 return _error->Error("Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).");
1062 }
1063
1064 // Call the scored problem resolver
1065 Fix.InstallProtect();
1066 if (Fix.Resolve(true) == false)
1067 _error->Discard();
1068
1069 // Now we check the state of the packages,
1070 if (Cache->BrokenCount() != 0)
1071 {
1072 c1out << "Some packages could not be installed. This may mean that you have" << endl;
1073 c1out << "requested an impossible situation or if you are using the unstable" << endl;
1074 c1out << "distribution that some required packages have not yet been created" << endl;
1075 c1out << "or been moved out of Incoming." << endl;
1076 if (Packages == 1)
1077 {
1078 c1out << endl;
1079 c1out << "Since you only requested a single operation it is extremely likely that" << endl;
1080 c1out << "the package is simply not installable and a bug report against" << endl;
1081 c1out << "that package should be filed." << endl;
1082 }
1083
1084 c1out << "The following information may help to resolve the situation:" << endl;
1085 c1out << endl;
1086 ShowBroken(c1out,Cache,false);
1087 return _error->Error("Sorry, broken packages");
1088 }
1089
1090 /* Print out a list of packages that are going to be installed extra
1091 to what the user asked */
1092 if (Cache->InstCount() != ExpectedInst)
1093 {
1094 string List;
1095 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
1096 {
1097 pkgCache::PkgIterator I(Cache,Cache.List[J]);
1098 if ((*Cache)[I].Install() == false)
1099 continue;
1100
1101 const char **J;
1102 for (J = CmdL.FileList + 1; *J != 0; J++)
1103 if (strcmp(*J,I.Name()) == 0)
1104 break;
1105
1106 if (*J == 0)
1107 List += string(I.Name()) + " ";
1108 }
1109
1110 ShowList(c1out,"The following extra packages will be installed:",List);
1111 }
1112
1113 // See if we need to prompt
1114 if (Cache->InstCount() == ExpectedInst && Cache->DelCount() == 0)
1115 return InstallPackages(Cache,false,false);
1116
1117 return InstallPackages(Cache,false);
1118 }
1119 /*}}}*/
1120 // DoDistUpgrade - Automatic smart upgrader /*{{{*/
1121 // ---------------------------------------------------------------------
1122 /* Intelligent upgrader that will install and remove packages at will */
1123 bool DoDistUpgrade(CommandLine &CmdL)
1124 {
1125 CacheFile Cache;
1126 if (Cache.Open() == false || Cache.CheckDeps() == false)
1127 return false;
1128
1129 c0out << "Calculating Upgrade... " << flush;
1130 if (pkgDistUpgrade(*Cache) == false)
1131 {
1132 c0out << "Failed" << endl;
1133 ShowBroken(c1out,Cache,false);
1134 return false;
1135 }
1136
1137 c0out << "Done" << endl;
1138
1139 return InstallPackages(Cache,true);
1140 }
1141 /*}}}*/
1142 // DoDSelectUpgrade - Do an upgrade by following dselects selections /*{{{*/
1143 // ---------------------------------------------------------------------
1144 /* Follows dselect's selections */
1145 bool DoDSelectUpgrade(CommandLine &CmdL)
1146 {
1147 CacheFile Cache;
1148 if (Cache.Open() == false || Cache.CheckDeps() == false)
1149 return false;
1150
1151 // Install everything with the install flag set
1152 pkgCache::PkgIterator I = Cache->PkgBegin();
1153 for (;I.end() != true; I++)
1154 {
1155 /* Install the package only if it is a new install, the autoupgrader
1156 will deal with the rest */
1157 if (I->SelectedState == pkgCache::State::Install)
1158 Cache->MarkInstall(I,false);
1159 }
1160
1161 /* Now install their deps too, if we do this above then order of
1162 the status file is significant for | groups */
1163 for (I = Cache->PkgBegin();I.end() != true; I++)
1164 {
1165 /* Install the package only if it is a new install, the autoupgrader
1166 will deal with the rest */
1167 if (I->SelectedState == pkgCache::State::Install)
1168 Cache->MarkInstall(I,true);
1169 }
1170
1171 // Apply erasures now, they override everything else.
1172 for (I = Cache->PkgBegin();I.end() != true; I++)
1173 {
1174 // Remove packages
1175 if (I->SelectedState == pkgCache::State::DeInstall ||
1176 I->SelectedState == pkgCache::State::Purge)
1177 Cache->MarkDelete(I,I->SelectedState == pkgCache::State::Purge);
1178 }
1179
1180 /* Resolve any problems that dselect created, allupgrade cannot handle
1181 such things. We do so quite agressively too.. */
1182 if (Cache->BrokenCount() != 0)
1183 {
1184 pkgProblemResolver Fix(Cache);
1185
1186 // Hold back held packages.
1187 if (_config->FindB("APT::Ingore-Hold",false) == false)
1188 {
1189 for (pkgCache::PkgIterator I = Cache->PkgBegin(); I.end() == false; I++)
1190 {
1191 if (I->SelectedState == pkgCache::State::Hold)
1192 {
1193 Fix.Protect(I);
1194 Cache->MarkKeep(I);
1195 }
1196 }
1197 }
1198
1199 if (Fix.Resolve() == false)
1200 {
1201 ShowBroken(c1out,Cache,false);
1202 return _error->Error("Internal Error, problem resolver broke stuff");
1203 }
1204 }
1205
1206 // Now upgrade everything
1207 if (pkgAllUpgrade(Cache) == false)
1208 {
1209 ShowBroken(c1out,Cache,false);
1210 return _error->Error("Internal Error, problem resolver broke stuff");
1211 }
1212
1213 return InstallPackages(Cache,false);
1214 }
1215 /*}}}*/
1216 // DoClean - Remove download archives /*{{{*/
1217 // ---------------------------------------------------------------------
1218 /* */
1219 bool DoClean(CommandLine &CmdL)
1220 {
1221 // Lock the archive directory
1222 FileFd Lock;
1223 if (_config->FindB("Debug::NoLocking",false) == false)
1224 {
1225 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
1226 if (_error->PendingError() == true)
1227 return _error->Error("Unable to lock the download directory");
1228 }
1229
1230 pkgAcquire Fetcher;
1231 Fetcher.Clean(_config->FindDir("Dir::Cache::archives"));
1232 Fetcher.Clean(_config->FindDir("Dir::Cache::archives") + "partial/");
1233 return true;
1234 }
1235 /*}}}*/
1236 // DoAutoClean - Smartly remove downloaded archives /*{{{*/
1237 // ---------------------------------------------------------------------
1238 /* This is similar to clean but it only purges things that cannot be
1239 downloaded, that is old versions of cached packages. */
1240 class LogCleaner : public pkgArchiveCleaner
1241 {
1242 protected:
1243 virtual void Erase(const char *File,string Pkg,string Ver,struct stat &St)
1244 {
1245 cout << "Del " << Pkg << " " << Ver << " [" << SizeToStr(St.st_size) << "B]" << endl;
1246
1247 if (_config->FindB("APT::Get::Simulate") == false)
1248 unlink(File);
1249 };
1250 };
1251
1252 bool DoAutoClean(CommandLine &CmdL)
1253 {
1254 // Lock the archive directory
1255 FileFd Lock;
1256 if (_config->FindB("Debug::NoLocking",false) == false)
1257 {
1258 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
1259 if (_error->PendingError() == true)
1260 return _error->Error("Unable to lock the download directory");
1261 }
1262
1263 CacheFile Cache;
1264 if (Cache.Open() == false)
1265 return false;
1266
1267 LogCleaner Cleaner;
1268
1269 return Cleaner.Go(_config->FindDir("Dir::Cache::archives"),*Cache) &&
1270 Cleaner.Go(_config->FindDir("Dir::Cache::archives") + "partial/",*Cache);
1271 }
1272 /*}}}*/
1273 // DoCheck - Perform the check operation /*{{{*/
1274 // ---------------------------------------------------------------------
1275 /* Opening automatically checks the system, this command is mostly used
1276 for debugging */
1277 bool DoCheck(CommandLine &CmdL)
1278 {
1279 CacheFile Cache;
1280 Cache.Open();
1281 Cache.CheckDeps();
1282
1283 return true;
1284 }
1285 /*}}}*/
1286 // DoSource - Fetch a source archive /*{{{*/
1287 // ---------------------------------------------------------------------
1288 /* Fetch souce packages */
1289 struct DscFile
1290 {
1291 string Package;
1292 string Version;
1293 string Dsc;
1294 };
1295
1296 bool DoSource(CommandLine &CmdL)
1297 {
1298 CacheFile Cache;
1299 if (Cache.Open(false) == false)
1300 return false;
1301
1302 if (CmdL.FileSize() <= 1)
1303 return _error->Error("Must specify at least one package to fetch source for");
1304
1305 // Read the source list
1306 pkgSourceList List;
1307 if (List.ReadMainList() == false)
1308 return _error->Error("The list of sources could not be read.");
1309
1310 // Create the text record parsers
1311 pkgRecords Recs(Cache);
1312 pkgSrcRecords SrcRecs(List);
1313 if (_error->PendingError() == true)
1314 return false;
1315
1316 // Create the download object
1317 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
1318 pkgAcquire Fetcher(&Stat);
1319
1320 DscFile *Dsc = new DscFile[CmdL.FileSize()];
1321
1322 // Load the requestd sources into the fetcher
1323 unsigned J = 0;
1324 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
1325 {
1326 string Src;
1327
1328 /* Lookup the version of the package we would install if we were to
1329 install a version and determine the source package name, then look
1330 in the archive for a source package of the same name. In theory
1331 we could stash the version string as well and match that too but
1332 today there aren't multi source versions in the archive. */
1333 pkgCache::PkgIterator Pkg = Cache->FindPkg(*I);
1334 if (Pkg.end() == false)
1335 {
1336 pkgCache::VerIterator Ver = Cache->GetCandidateVer(Pkg);
1337 if (Ver.end() == false)
1338 {
1339 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1340 Src = Parse.SourcePkg();
1341 }
1342 }
1343
1344 // No source package name..
1345 if (Src.empty() == true)
1346 Src = *I;
1347
1348 // The best hit
1349 pkgSrcRecords::Parser *Last = 0;
1350 unsigned long Offset = 0;
1351 string Version;
1352 bool IsMatch = false;
1353
1354 // Iterate over all of the hits
1355 pkgSrcRecords::Parser *Parse;
1356 SrcRecs.Restart();
1357 while ((Parse = SrcRecs.Find(Src.c_str(),false)) != 0)
1358 {
1359 string Ver = Parse->Version();
1360
1361 // Skip name mismatches
1362 if (IsMatch == true && Parse->Package() != Src)
1363 continue;
1364
1365 // Newer version or an exact match
1366 if (Last == 0 || pkgVersionCompare(Version,Ver) < 0 ||
1367 (Parse->Package() == Src && IsMatch == false))
1368 {
1369 IsMatch = Parse->Package() == Src;
1370 Last = Parse;
1371 Offset = Parse->Offset();
1372 Version = Ver;
1373 }
1374 }
1375
1376 if (Last == 0)
1377 return _error->Error("Unable to find a source package for %s",Src.c_str());
1378
1379 // Back track
1380 vector<pkgSrcRecords::File> Lst;
1381 if (Last->Jump(Offset) == false || Last->Files(Lst) == false)
1382 return false;
1383
1384 // Load them into the fetcher
1385 for (vector<pkgSrcRecords::File>::const_iterator I = Lst.begin();
1386 I != Lst.end(); I++)
1387 {
1388 // Try to guess what sort of file it is we are getting.
1389 string Comp;
1390 if (I->Path.find(".dsc") != string::npos)
1391 {
1392 Comp = "dsc";
1393 Dsc[J].Package = Last->Package();
1394 Dsc[J].Version = Last->Version();
1395 Dsc[J].Dsc = flNotDir(I->Path);
1396 }
1397
1398 if (I->Path.find(".tar.gz") != string::npos)
1399 Comp = "tar";
1400 if (I->Path.find(".diff.gz") != string::npos)
1401 Comp = "diff";
1402
1403 // Diff only mode only fetches .diff files
1404 if (_config->FindB("APT::Get::Diff-Only",false) == true &&
1405 Comp != "diff")
1406 continue;
1407
1408 // Tar only mode only fetches .tar files
1409 if (_config->FindB("APT::Get::Tar-Only",false) == true &&
1410 Comp != "tar")
1411 continue;
1412
1413 new pkgAcqFile(&Fetcher,Last->Source()->ArchiveURI(I->Path),
1414 I->MD5Hash,I->Size,Last->Source()->SourceInfo(Src,
1415 Last->Version(),Comp),Src);
1416 }
1417 }
1418
1419 // Display statistics
1420 unsigned long FetchBytes = Fetcher.FetchNeeded();
1421 unsigned long FetchPBytes = Fetcher.PartialPresent();
1422 unsigned long DebBytes = Fetcher.TotalNeeded();
1423
1424 // Check for enough free space
1425 struct statfs Buf;
1426 string OutputDir = ".";
1427 if (statfs(OutputDir.c_str(),&Buf) != 0)
1428 return _error->Errno("statfs","Couldn't determine free space in %s",
1429 OutputDir.c_str());
1430 if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
1431 return _error->Error("Sorry, you don't have enough free space in %s",
1432 OutputDir.c_str());
1433
1434 // Number of bytes
1435 c1out << "Need to get ";
1436 if (DebBytes != FetchBytes)
1437 c1out << SizeToStr(FetchBytes) << "B/" << SizeToStr(DebBytes) << 'B';
1438 else
1439 c1out << SizeToStr(DebBytes) << 'B';
1440 c1out << " of source archives." << endl;
1441
1442 if (_config->FindB("APT::Get::Simulate",false) == true)
1443 {
1444 for (unsigned I = 0; I != J; I++)
1445 cout << "Fetch Source " << Dsc[I].Package << endl;
1446 return true;
1447 }
1448
1449 // Just print out the uris an exit if the --print-uris flag was used
1450 if (_config->FindB("APT::Get::Print-URIs") == true)
1451 {
1452 pkgAcquire::UriIterator I = Fetcher.UriBegin();
1453 for (; I != Fetcher.UriEnd(); I++)
1454 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
1455 I->Owner->FileSize << ' ' << I->Owner->MD5Sum() << endl;
1456 return true;
1457 }
1458
1459 // Run it
1460 if (Fetcher.Run() == pkgAcquire::Failed)
1461 return false;
1462
1463 // Print error messages
1464 bool Failed = false;
1465 for (pkgAcquire::Item **I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
1466 {
1467 if ((*I)->Status == pkgAcquire::Item::StatDone &&
1468 (*I)->Complete == true)
1469 continue;
1470
1471 cerr << "Failed to fetch " << (*I)->DescURI() << endl;
1472 cerr << " " << (*I)->ErrorText << endl;
1473 Failed = true;
1474 }
1475 if (Failed == true)
1476 return _error->Error("Failed to fetch some archives.");
1477
1478 if (_config->FindB("APT::Get::Download-only",false) == true)
1479 return true;
1480
1481 // Unpack the sources
1482 pid_t Process = ExecFork();
1483
1484 if (Process == 0)
1485 {
1486 for (unsigned I = 0; I != J; I++)
1487 {
1488 string Dir = Dsc[I].Package + '-' + pkgBaseVersion(Dsc[I].Version.c_str());
1489
1490 // Diff only mode only fetches .diff files
1491 if (_config->FindB("APT::Get::Diff-Only",false) == true ||
1492 _config->FindB("APT::Get::Tar-Only",false) == true)
1493 continue;
1494
1495 // See if the package is already unpacked
1496 struct stat Stat;
1497 if (stat(Dir.c_str(),&Stat) == 0 &&
1498 S_ISDIR(Stat.st_mode) != 0)
1499 {
1500 c0out << "Skipping unpack of already unpacked source in " << Dir << endl;
1501 }
1502 else
1503 {
1504 // Call dpkg-source
1505 char S[500];
1506 snprintf(S,sizeof(S),"%s -x %s",
1507 _config->Find("Dir::Bin::dpkg-source","dpkg-source").c_str(),
1508 Dsc[I].Dsc.c_str());
1509 if (system(S) != 0)
1510 {
1511 cerr << "Unpack command '" << S << "' failed." << endl;
1512 _exit(1);
1513 }
1514 }
1515
1516 // Try to compile it with dpkg-buildpackage
1517 if (_config->FindB("APT::Get::Compile",false) == true)
1518 {
1519 // Call dpkg-buildpackage
1520 char S[500];
1521 snprintf(S,sizeof(S),"cd %s && %s %s",
1522 Dir.c_str(),
1523 _config->Find("Dir::Bin::dpkg-buildpackage","dpkg-buildpackage").c_str(),
1524 _config->Find("DPkg::Build-Options","-b -uc").c_str());
1525
1526 if (system(S) != 0)
1527 {
1528 cerr << "Build command '" << S << "' failed." << endl;
1529 _exit(1);
1530 }
1531 }
1532 }
1533
1534 _exit(0);
1535 }
1536
1537 // Wait for the subprocess
1538 int Status = 0;
1539 while (waitpid(Process,&Status,0) != Process)
1540 {
1541 if (errno == EINTR)
1542 continue;
1543 return _error->Errno("waitpid","Couldn't wait for subprocess");
1544 }
1545
1546 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1547 return _error->Error("Child process failed");
1548
1549 return true;
1550 }
1551 /*}}}*/
1552
1553 // ShowHelp - Show a help screen /*{{{*/
1554 // ---------------------------------------------------------------------
1555 /* */
1556 bool ShowHelp(CommandLine &CmdL)
1557 {
1558 cout << PACKAGE << ' ' << VERSION << " for " << ARCHITECTURE <<
1559 " compiled on " << __DATE__ << " " << __TIME__ << endl;
1560 if (_config->FindB("version") == true)
1561 return 100;
1562
1563 cout << "Usage: apt-get [options] command" << endl;
1564 cout << " apt-get [options] install pkg1 [pkg2 ...]" << endl;
1565 cout << endl;
1566 cout << "apt-get is a simple command line interface for downloading and" << endl;
1567 cout << "installing packages. The most frequently used commands are update" << endl;
1568 cout << "and install." << endl;
1569 cout << endl;
1570 cout << "Commands:" << endl;
1571 cout << " update - Retrieve new lists of packages" << endl;
1572 cout << " upgrade - Perform an upgrade" << endl;
1573 cout << " install - Install new packages (pkg is libc6 not libc6.deb)" << endl;
1574 cout << " remove - Remove packages" << endl;
1575 cout << " source - Download source archives" << endl;
1576 cout << " dist-upgrade - Distribution upgrade, see apt-get(8)" << endl;
1577 cout << " dselect-upgrade - Follow dselect selections" << endl;
1578 cout << " clean - Erase downloaded archive files" << endl;
1579 cout << " autoclean - Erase old downloaded archive files" << endl;
1580 cout << " check - Verify that there are no broken dependencies" << endl;
1581 cout << endl;
1582 cout << "Options:" << endl;
1583 cout << " -h This help text." << endl;
1584 cout << " -q Loggable output - no progress indicator" << endl;
1585 cout << " -qq No output except for errors" << endl;
1586 cout << " -d Download only - do NOT install or unpack archives" << endl;
1587 cout << " -s No-act. Perform ordering simulation" << endl;
1588 cout << " -y Assume Yes to all queries and do not prompt" << endl;
1589 cout << " -f Attempt to continue if the integrity check fails" << endl;
1590 cout << " -m Attempt to continue if archives are unlocatable" << endl;
1591 cout << " -u Show a list of upgraded packages as well" << endl;
1592 cout << " -b Build the source package after fetching it" << endl;
1593 cout << " -c=? Read this configuration file" << endl;
1594 cout << " -o=? Set an arbitary configuration option, eg -o dir::cache=/tmp" << endl;
1595 cout << "See the apt-get(8), sources.list(5) and apt.conf(5) manual" << endl;
1596 cout << "pages for more information and options." << endl;
1597 return 100;
1598 }
1599 /*}}}*/
1600 // GetInitialize - Initialize things for apt-get /*{{{*/
1601 // ---------------------------------------------------------------------
1602 /* */
1603 void GetInitialize()
1604 {
1605 _config->Set("quiet",0);
1606 _config->Set("help",false);
1607 _config->Set("APT::Get::Download-Only",false);
1608 _config->Set("APT::Get::Simulate",false);
1609 _config->Set("APT::Get::Assume-Yes",false);
1610 _config->Set("APT::Get::Fix-Broken",false);
1611 _config->Set("APT::Get::Force-Yes",false);
1612 _config->Set("APT::Get::APT::Get::No-List-Cleanup",true);
1613 }
1614 /*}}}*/
1615 // SigWinch - Window size change signal handler /*{{{*/
1616 // ---------------------------------------------------------------------
1617 /* */
1618 void SigWinch(int)
1619 {
1620 // Riped from GNU ls
1621 #ifdef TIOCGWINSZ
1622 struct winsize ws;
1623
1624 if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col >= 5)
1625 ScreenWidth = ws.ws_col - 1;
1626 #endif
1627 }
1628 /*}}}*/
1629
1630 int main(int argc,const char *argv[])
1631 {
1632 CommandLine::Args Args[] = {
1633 {'h',"help","help",0},
1634 {'v',"version","version",0},
1635 {'q',"quiet","quiet",CommandLine::IntLevel},
1636 {'q',"silent","quiet",CommandLine::IntLevel},
1637 {'d',"download-only","APT::Get::Download-Only",0},
1638 {'b',"compile","APT::Get::Compile",0},
1639 {'b',"build","APT::Get::Compile",0},
1640 {'s',"simulate","APT::Get::Simulate",0},
1641 {'s',"just-print","APT::Get::Simulate",0},
1642 {'s',"recon","APT::Get::Simulate",0},
1643 {'s',"no-act","APT::Get::Simulate",0},
1644 {'y',"yes","APT::Get::Assume-Yes",0},
1645 {'y',"assume-yes","APT::Get::Assume-Yes",0},
1646 {'f',"fix-broken","APT::Get::Fix-Broken",0},
1647 {'u',"show-upgraded","APT::Get::Show-Upgraded",0},
1648 {'m',"ignore-missing","APT::Get::Fix-Missing",0},
1649 {0,"no-download","APT::Get::No-Download",0},
1650 {0,"fix-missing","APT::Get::Fix-Missing",0},
1651 {0,"ignore-hold","APT::Ingore-Hold",0},
1652 {0,"no-upgrade","APT::Get::no-upgrade",0},
1653 {0,"force-yes","APT::Get::force-yes",0},
1654 {0,"print-uris","APT::Get::Print-URIs",0},
1655 {0,"diff-only","APT::Get::Diff-Only",0},
1656 {0,"tar-only","APT::Get::tar-Only",0},
1657 {0,"purge","APT::Get::Purge",0},
1658 {0,"list-cleanup","APT::Get::List-Cleanup",0},
1659 {0,"reinstall","APT::Get::ReInstall",0},
1660 {'c',"config-file",0,CommandLine::ConfigFile},
1661 {'o',"option",0,CommandLine::ArbItem},
1662 {0,0,0,0}};
1663 CommandLine::Dispatch Cmds[] = {{"update",&DoUpdate},
1664 {"upgrade",&DoUpgrade},
1665 {"install",&DoInstall},
1666 {"remove",&DoInstall},
1667 {"dist-upgrade",&DoDistUpgrade},
1668 {"dselect-upgrade",&DoDSelectUpgrade},
1669 {"clean",&DoClean},
1670 {"autoclean",&DoAutoClean},
1671 {"check",&DoCheck},
1672 {"source",&DoSource},
1673 {"help",&ShowHelp},
1674 {0,0}};
1675
1676 // Parse the command line and initialize the package library
1677 CommandLine CmdL(Args,_config);
1678 if (pkgInitialize(*_config) == false ||
1679 CmdL.Parse(argc,argv) == false)
1680 {
1681 _error->DumpErrors();
1682 return 100;
1683 }
1684
1685 // See if the help should be shown
1686 if (_config->FindB("help") == true ||
1687 _config->FindB("version") == true ||
1688 CmdL.FileSize() == 0)
1689 return ShowHelp(CmdL);
1690
1691 // Deal with stdout not being a tty
1692 if (ttyname(STDOUT_FILENO) == 0 && _config->FindI("quiet",0) < 1)
1693 _config->Set("quiet","1");
1694
1695 // Setup the output streams
1696 c0out.rdbuf(cout.rdbuf());
1697 c1out.rdbuf(cout.rdbuf());
1698 c2out.rdbuf(cout.rdbuf());
1699 if (_config->FindI("quiet",0) > 0)
1700 c0out.rdbuf(devnull.rdbuf());
1701 if (_config->FindI("quiet",0) > 1)
1702 c1out.rdbuf(devnull.rdbuf());
1703
1704 // Setup the signals
1705 signal(SIGPIPE,SIG_IGN);
1706 signal(SIGWINCH,SigWinch);
1707 SigWinch(0);
1708
1709 // Match the operation
1710 CmdL.DispatchArg(Cmds);
1711
1712 // Print any errors or warnings found during parsing
1713 if (_error->empty() == false)
1714 {
1715 bool Errors = _error->PendingError();
1716 _error->DumpErrors();
1717 return Errors == true?100:0;
1718 }
1719
1720 return 0;
1721 }