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