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