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