QT1 license exception
[ntk/apt.git] / cmdline / apt-get.cc
CommitLineData
5ec427c2
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
8b067c22 3// $Id: apt-get.cc,v 1.88 1999/11/16 03:16:34 jgg Exp $
5ec427c2
AL
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 /*{{{*/
0a8e3465
AL
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>
0a8e3465 33#include <apt-pkg/algorithms.h>
0919e3f9 34#include <apt-pkg/acquire-item.h>
03e39e59 35#include <apt-pkg/dpkgpm.h>
cdcc6d34 36#include <apt-pkg/strutl.h>
1bc849af 37#include <apt-pkg/clean.h>
36375005
AL
38#include <apt-pkg/srcrecords.h>
39#include <apt-pkg/version.h>
2d11135a 40#include <apt-pkg/cachefile.h>
0a8e3465
AL
41
42#include <config.h>
43
0919e3f9
AL
44#include "acqprogress.h"
45
0a8e3465 46#include <fstream.h>
d7827aca
AL
47#include <termios.h>
48#include <sys/ioctl.h>
1bc849af 49#include <sys/stat.h>
138d4b3d 50#include <sys/vfs.h>
d7827aca 51#include <signal.h>
65a1e968 52#include <unistd.h>
3e3221ba 53#include <stdio.h>
d6e79b75 54#include <errno.h>
c373c37a 55#include <regex.h>
54676e1a 56#include <sys/wait.h>
0a8e3465
AL
57 /*}}}*/
58
59ostream c0out;
60ostream c1out;
61ostream c2out;
62ofstream devnull("/dev/null");
63unsigned int ScreenWidth = 80;
64
1089ca89
AL
65// class CacheFile - Cover class for some dependency cache functions /*{{{*/
66// ---------------------------------------------------------------------
67/* */
68class 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
a6568219
AL
90// YnPrompt - Yes No Prompt. /*{{{*/
91// ---------------------------------------------------------------------
92/* Returns true on a Yes.*/
93bool YnPrompt()
94{
95 if (_config->FindB("APT::Get::Assume-Yes",false) == true)
96 {
738309d6 97 c1out << 'Y' << endl;
a6568219
AL
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 /*}}}*/
6f86c974
AL
111// AnalPrompt - Annoying Yes No Prompt. /*{{{*/
112// ---------------------------------------------------------------------
113/* Returns true on a Yes.*/
114bool 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 /*}}}*/
0a8e3465
AL
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. */
83d89a9f 127bool ShowList(ostream &out,string Title,string List)
0a8e3465
AL
128{
129 if (List.empty() == true)
83d89a9f 130 return true;
0a8e3465
AL
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 }
83d89a9f 150 return false;
0a8e3465
AL
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. */
421c8d10 158void ShowBroken(ostream &out,CacheFile &Cache,bool Now)
0a8e3465 159{
30e1eab5 160 out << "Sorry, but the following packages have unmet dependencies:" << endl;
1089ca89 161 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 162 {
1089ca89
AL
163 pkgCache::PkgIterator I(Cache,Cache.List[J]);
164
303a1703
AL
165 if (Cache[I].InstBroken() == false)
166 continue;
167
168 // Print out each package and the failed dependencies
169 out <<" " << I.Name() << ":";
648e3cb4 170 unsigned Indent = strlen(I.Name()) + 3;
303a1703
AL
171 bool First = true;
172 if (Cache[I].InstVerIter(Cache).end() == true)
0a8e3465 173 {
303a1703
AL
174 cout << endl;
175 continue;
176 }
177
30e1eab5 178 for (pkgCache::DepIterator D = Cache[I].InstVerIter(Cache).DependsList(); D.end() == false;)
303a1703 179 {
30e1eab5
AL
180 // Compute a single dependency element (glob or)
181 pkgCache::DepIterator Start;
182 pkgCache::DepIterator End;
183 D.GlobOr(Start,End);
76fbce56 184
1089ca89 185 if (Cache->IsImportantDep(End) == false ||
30e1eab5 186 (Cache[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall)
303a1703 187 continue;
cc718e9a 188
648e3cb4
AL
189 bool FirstOr = true;
190 while (1)
0a8e3465 191 {
648e3cb4
AL
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 }
0a8e3465 202 else
648e3cb4
AL
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)
7e798dd7 217 {
648e3cb4
AL
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
303a1703 223 {
648e3cb4
AL
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 }
303a1703 231 else
648e3cb4
AL
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 }
303a1703 244 }
0a8e3465
AL
245 }
246}
247 /*}}}*/
248// ShowNew - Show packages to newly install /*{{{*/
249// ---------------------------------------------------------------------
250/* */
1089ca89 251void ShowNew(ostream &out,CacheFile &Cache)
0a8e3465
AL
252{
253 /* Print out a list of packages that are going to be removed extra
254 to what the user asked */
0a8e3465 255 string List;
1089ca89
AL
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)
0a8e3465 260 List += string(I.Name()) + " ";
1089ca89
AL
261 }
262
0a8e3465
AL
263 ShowList(out,"The following NEW packages will be installed:",List);
264}
265 /*}}}*/
266// ShowDel - Show packages to delete /*{{{*/
267// ---------------------------------------------------------------------
268/* */
1089ca89 269void ShowDel(ostream &out,CacheFile &Cache)
0a8e3465
AL
270{
271 /* Print out a list of packages that are going to be removed extra
272 to what the user asked */
0a8e3465 273 string List;
1089ca89 274 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
fc4b5c9f 275 {
1089ca89
AL
276 pkgCache::PkgIterator I(Cache,Cache.List[J]);
277 if (Cache[I].Delete() == true)
fc4b5c9f 278 {
1089ca89 279 if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
fc4b5c9f
AL
280 List += string(I.Name()) + "* ";
281 else
282 List += string(I.Name()) + " ";
283 }
284 }
3d615484 285
0a8e3465
AL
286 ShowList(out,"The following packages will be REMOVED:",List);
287}
288 /*}}}*/
289// ShowKept - Show kept packages /*{{{*/
290// ---------------------------------------------------------------------
291/* */
f292686b 292void ShowKept(ostream &out,CacheFile &Cache)
0a8e3465 293{
0a8e3465 294 string List;
f292686b 295 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 296 {
f292686b
AL
297 pkgCache::PkgIterator I(Cache,Cache.List[J]);
298
0a8e3465 299 // Not interesting
f292686b
AL
300 if (Cache[I].Upgrade() == true || Cache[I].Upgradable() == false ||
301 I->CurrentVer == 0 || Cache[I].Delete() == true)
0a8e3465
AL
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/* */
1089ca89 312void ShowUpgraded(ostream &out,CacheFile &Cache)
0a8e3465 313{
0a8e3465 314 string List;
1089ca89 315 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 316 {
1089ca89
AL
317 pkgCache::PkgIterator I(Cache,Cache.List[J]);
318
0a8e3465 319 // Not interesting
1089ca89 320 if (Cache[I].Upgrade() == false || Cache[I].NewInstall() == true)
0a8e3465
AL
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/* */
1089ca89 331bool ShowHold(ostream &out,CacheFile &Cache)
0a8e3465 332{
0a8e3465 333 string List;
1089ca89 334 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 335 {
1089ca89
AL
336 pkgCache::PkgIterator I(Cache,Cache.List[J]);
337 if (Cache[I].InstallVer != (pkgCache::Version *)I.CurrentVer() &&
0a8e3465
AL
338 I->SelectedState == pkgCache::State::Hold)
339 List += string(I.Name()) + " ";
340 }
341
83d89a9f 342 return ShowList(out,"The following held packages will be changed:",List);
0a8e3465
AL
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! */
1089ca89 350bool ShowEssential(ostream &out,CacheFile &Cache)
0a8e3465 351{
0a8e3465 352 string List;
1089ca89
AL
353 bool *Added = new bool[Cache->HeaderP->PackageCount];
354 for (unsigned int I = 0; I != Cache->HeaderP->PackageCount; I++)
0a8e3465
AL
355 Added[I] = false;
356
1089ca89 357 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 358 {
1089ca89 359 pkgCache::PkgIterator I(Cache,Cache.List[J]);
0a8e3465
AL
360 if ((I->Flags & pkgCache::Flag::Essential) != pkgCache::Flag::Essential)
361 continue;
362
363 // The essential package is being removed
1089ca89 364 if (Cache[I].Delete() == true)
0a8e3465
AL
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 {
3e3221ba
AL
379 // Skip everything but depends
380 if (D->Type != pkgCache::Dep::PreDepends &&
381 D->Type != pkgCache::Dep::Depends)
382 continue;
383
0a8e3465 384 pkgCache::PkgIterator P = D.SmartTargetPkg();
1089ca89 385 if (Cache[P].Delete() == true)
0a8e3465
AL
386 {
387 if (Added[P->ID] == true)
388 continue;
389 Added[P->ID] = true;
3e3221ba
AL
390
391 char S[300];
392 sprintf(S,"%s (due to %s) ",P.Name(),I.Name());
393 List += S;
0a8e3465
AL
394 }
395 }
396 }
397
83d89a9f 398 delete [] Added;
0a8e3465
AL
399 if (List.empty() == false)
400 out << "WARNING: The following essential packages will be removed" << endl;
83d89a9f 401 return ShowList(out,"This should NOT be done unless you know exactly what you are doing!",List);
0a8e3465
AL
402}
403 /*}}}*/
404// Stats - Show some statistics /*{{{*/
405// ---------------------------------------------------------------------
406/* */
407void Stats(ostream &out,pkgDepCache &Dep)
408{
409 unsigned long Upgrade = 0;
410 unsigned long Install = 0;
d0c59649 411 unsigned long ReInstall = 0;
0a8e3465
AL
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++;
d0c59649
AL
419 if (Dep[I].Delete() == false && (Dep[I].iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
420 ReInstall++;
0a8e3465
AL
421 }
422
423 out << Upgrade << " packages upgraded, " <<
d0c59649
AL
424 Install << " newly installed, ";
425 if (ReInstall != 0)
426 out << ReInstall << " reinstalled, ";
427 out << Dep.DelCount() << " to remove and " <<
0a8e3465
AL
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
1089ca89 435// CacheFile::NameComp - QSort compare by name /*{{{*/
0a8e3465
AL
436// ---------------------------------------------------------------------
437/* */
1089ca89
AL
438pkgCache *CacheFile::SortCache = 0;
439int CacheFile::NameComp(const void *a,const void *b)
0a8e3465 440{
8508b1df
AL
441 if (*(pkgCache::Package **)a == 0 || *(pkgCache::Package **)b == 0)
442 return *(pkgCache::Package **)a - *(pkgCache::Package **)b;
0a8e3465 443
1089ca89
AL
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/* */
453void 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}
0a8e3465
AL
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. */
2d11135a 470bool CacheFile::CheckDeps(bool AllowBroken)
0a8e3465 471{
d38b7b3d
AL
472 if (_error->PendingError() == true)
473 return false;
0a8e3465 474
0a8e3465
AL
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
7c57fe64 484 if (Cache->BrokenCount() == 0 || AllowBroken == true)
0a8e3465
AL
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;
421c8d10 494 ShowBroken(c1out,*this,true);
0a8e3465
AL
495
496 return _error->Error("Unable to correct dependencies");
497 }
7e798dd7
AL
498 if (pkgMinimizeUpgrade(*Cache) == false)
499 return _error->Error("Unable to minimize the upgrade set");
0a8e3465
AL
500
501 c1out << " Done" << endl;
502 }
503 else
504 {
505 c1out << "You might want to run `apt-get -f install' to correct these." << endl;
421c8d10 506 ShowBroken(c1out,*this,true);
0a8e3465
AL
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 */
6f86c974 519bool InstallPackages(CacheFile &Cache,bool ShwKept,bool Ask = true,bool Saftey = true)
0a8e3465 520{
fc4b5c9f
AL
521 if (_config->FindB("APT::Get::Purge",false) == true)
522 {
523 pkgCache::PkgIterator I = Cache->PkgBegin();
524 for (; I.end() == false; I++)
d556d1a1
AL
525 {
526 if (I.Purge() == false && Cache[I].Mode == pkgDepCache::ModeDelete)
527 Cache->MarkDelete(I,true);
528 }
fc4b5c9f
AL
529 }
530
83d89a9f 531 bool Fail = false;
6f86c974 532 bool Essential = false;
83d89a9f 533
a6568219 534 // Show all the various warning indicators
0a8e3465
AL
535 ShowDel(c1out,Cache);
536 ShowNew(c1out,Cache);
537 if (ShwKept == true)
538 ShowKept(c1out,Cache);
7a215bee 539 Fail |= !ShowHold(c1out,Cache);
0a8e3465
AL
540 if (_config->FindB("APT::Get::Show-Upgraded",false) == true)
541 ShowUpgraded(c1out,Cache);
6f86c974
AL
542 Essential = !ShowEssential(c1out,Cache);
543 Fail |= Essential;
0a8e3465
AL
544 Stats(c1out,Cache);
545
546 // Sanity check
d38b7b3d 547 if (Cache->BrokenCount() != 0)
0a8e3465 548 {
421c8d10 549 ShowBroken(c1out,Cache,false);
0a8e3465
AL
550 return _error->Error("Internal Error, InstallPackages was called with broken packages!");
551 }
552
d0c59649 553 if (Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
d38b7b3d 554 Cache->BadCount() == 0)
c60d151b 555 return true;
03e39e59 556
d150b09d
AL
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
03e39e59
AL
561 // Run the simulator ..
562 if (_config->FindB("APT::Get::Simulate") == true)
563 {
564 pkgSimulate PM(Cache);
281daf46
AL
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;
03e39e59
AL
571 }
572
573 // Create the text record parser
574 pkgRecords Recs(Cache);
83d89a9f
AL
575 if (_error->PendingError() == true)
576 return false;
577
d38b7b3d 578 // Lock the archive directory
36375005 579 FileFd Lock;
d38b7b3d
AL
580 if (_config->FindB("Debug::NoLocking",false) == false)
581 {
36375005 582 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
d38b7b3d
AL
583 if (_error->PendingError() == true)
584 return _error->Error("Unable to lock the download directory");
585 }
03e39e59
AL
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
30e1eab5 597 pkgDPkgPM PM(Cache);
424c3bc0
AL
598 if (PM.GetArchives(&Fetcher,&List,&Recs) == false ||
599 _error->PendingError() == true)
03e39e59
AL
600 return false;
601
7a1b1f8b 602 // Display statistics
a6568219 603 unsigned long FetchBytes = Fetcher.FetchNeeded();
6b1ff003 604 unsigned long FetchPBytes = Fetcher.PartialPresent();
a6568219 605 unsigned long DebBytes = Fetcher.TotalNeeded();
d38b7b3d
AL
606 if (DebBytes != Cache->DebSize())
607 {
608 c0out << DebBytes << ',' << Cache->DebSize() << endl;
a6568219 609 c0out << "How odd.. The sizes didn't match, email apt@packages.debian.org" << endl;
d38b7b3d 610 }
138d4b3d 611
7a1b1f8b 612 // Number of bytes
fc9d4b7b 613 c1out << "Need to get ";
a6568219 614 if (DebBytes != FetchBytes)
314037ba 615 c1out << SizeToStr(FetchBytes) << "B/" << SizeToStr(DebBytes) << 'B';
a6568219 616 else
314037ba 617 c1out << SizeToStr(DebBytes) << 'B';
a6568219
AL
618
619 c1out << " of archives. After unpacking ";
31a0531d
AL
620
621 // Check for enough free space
622 struct statfs Buf;
623 string OutputDir = _config->FindDir("Dir::Cache::Archives");
624 if (statfs(OutputDir.c_str(),&Buf) != 0)
625 return _error->Errno("statfs","Couldn't determine free space in %s",
626 OutputDir.c_str());
627 if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
628 return _error->Error("Sorry, you don't have enough free space in %s to hold all the .debs.",
629 OutputDir.c_str());
a6568219 630
7a1b1f8b 631 // Size delta
d38b7b3d 632 if (Cache->UsrSize() >= 0)
314037ba 633 c1out << SizeToStr(Cache->UsrSize()) << "B will be used." << endl;
a6568219 634 else
314037ba 635 c1out << SizeToStr(-1*Cache->UsrSize()) << "B will be freed." << endl;
a6568219
AL
636
637 if (_error->PendingError() == true)
638 return false;
639
83d89a9f 640 // Fail safe check
0c95c765
AL
641 if (_config->FindI("quiet",0) >= 2 ||
642 _config->FindB("APT::Get::Assume-Yes",false) == true)
83d89a9f
AL
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 }
83d89a9f 647
6f86c974
AL
648 if (Essential == true && Saftey == true)
649 {
d150b09d
AL
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
6f86c974 653 c2out << "You are about to do something potentially harmful" << endl;
36375005 654 c2out << "To continue type in the phrase 'Yes, I understand this may be bad'" << endl;
6f86c974 655 c2out << " ?] " << flush;
36375005 656 if (AnalPrompt("Yes, I understand this may be bad") == false)
6f86c974
AL
657 {
658 c2out << "Abort." << endl;
a6568219 659 exit(1);
6f86c974
AL
660 }
661 }
662 else
d150b09d 663 {
6f86c974 664 // Prompt to continue
38262e68 665 if (Ask == true || Fail == true)
6f86c974 666 {
d150b09d
AL
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
0c95c765 670 if (_config->FindI("quiet",0) < 2 &&
6f86c974 671 _config->FindB("APT::Get::Assume-Yes",false) == false)
0c95c765 672 {
6f86c974
AL
673 c2out << "Do you want to continue? [Y/n] " << flush;
674
0c95c765
AL
675 if (YnPrompt() == false)
676 {
677 c2out << "Abort." << endl;
678 exit(1);
679 }
680 }
6f86c974
AL
681 }
682 }
683
36375005 684 // Just print out the uris an exit if the --print-uris flag was used
f7a08e33
AL
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 }
83d89a9f 693
03e39e59 694 // Run it
281daf46 695 while (1)
30e1eab5 696 {
281daf46 697 if (_config->FindB("APT::Get::No-Download",false) == false)
8e5fc8f5 698 if (Fetcher.Run() == pkgAcquire::Failed)
281daf46 699 return false;
30e1eab5 700
281daf46
AL
701 // Print out errors
702 bool Failed = false;
703 bool Transient = false;
704 for (pkgAcquire::Item **I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
f01fe790 705 {
281daf46
AL
706 if ((*I)->Status == pkgAcquire::Item::StatDone &&
707 (*I)->Complete == true)
708 continue;
709
281daf46
AL
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;
f01fe790 719 Failed = true;
f01fe790 720 }
5ec427c2
AL
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 }
f01fe790 731
281daf46
AL
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
8195ae46 739 if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
f01fe790 740 {
281daf46 741 return _error->Error("Unable to fetch some archives, maybe try with --fix-missing?");
f01fe790
AL
742 }
743
281daf46
AL
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 }
0a8e3465
AL
766}
767 /*}}}*/
c373c37a
AL
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.. */
772bool 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, installing " << 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 (State.CandidateVer == 0)
798 {
799 if (AllowFail == false)
800 return false;
801
802 if (Pkg->ProvidesList != 0)
803 {
804 c1out << "Package " << Pkg.Name() << " is a virtual package provided by:" << endl;
805
806 pkgCache::PrvIterator I = Pkg.ProvidesList();
807 for (; I.end() == false; I++)
808 {
809 pkgCache::PkgIterator Pkg = I.OwnerPkg();
810
811 if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer())
812 {
813 if (Cache[Pkg].Install() == true && Cache[Pkg].NewInstall() == false)
814 c1out << " " << Pkg.Name() << " " << I.OwnerVer().VerStr() <<
815 " [Installed]"<< endl;
816 else
817 c1out << " " << Pkg.Name() << " " << I.OwnerVer().VerStr() << endl;
818 }
819 }
820 c1out << "You should explicitly select one to install." << endl;
821 }
822 else
823 {
824 c1out << "Package " << Pkg.Name() << " has no available version, but exists in the database." << endl;
825 c1out << "This typically means that the package was mentioned in a dependency and " << endl;
dca1e241
AL
826 c1out << "never uploaded, has been obsoleted or is not available with the contents " << endl;
827 c1out << "of sources.list" << endl;
c373c37a
AL
828
829 string List;
830 pkgCache::DepIterator Dep = Pkg.RevDependsList();
831 for (; Dep.end() == false; Dep++)
832 {
833 if (Dep->Type != pkgCache::Dep::Replaces)
834 continue;
835 List += string(Dep.ParentPkg().Name()) + " ";
836 }
837 ShowList(c1out,"However the following packages replace it:",List);
838 }
839
840 _error->Error("Package %s has no installation candidate",Pkg.Name());
841 return false;
842 }
61d6a8de
AL
843
844 Fix.Clear(Pkg);
c373c37a
AL
845 Fix.Protect(Pkg);
846 if (Remove == true)
847 {
848 Fix.Remove(Pkg);
849 Cache.MarkDelete(Pkg,_config->FindB("APT::Get::Purge",false));
850 return true;
851 }
852
853 // Install it
854 Cache.MarkInstall(Pkg,false);
855 if (State.Install() == false)
856 {
d0c59649
AL
857 if (_config->FindB("APT::Get::ReInstall",false) == true)
858 {
859 if (Pkg->CurrentVer == 0 || Pkg.CurrentVer().Downloadable() == false)
860 c1out << "Sorry, re-installation of " << Pkg.Name() << " is not possible, it cannot be downloaded" << endl;
861 else
862 Cache.SetReInstall(Pkg,true);
863 }
864 else
865 {
866 if (AllowFail == true)
867 c1out << "Sorry, " << Pkg.Name() << " is already the newest version" << endl;
868 }
c373c37a
AL
869 }
870 else
871 ExpectedInst++;
872
873 // Install it with autoinstalling enabled.
874 if (State.InstBroken() == true && BrokenFix == false)
875 Cache.MarkInstall(Pkg,true);
876 return true;
877}
878 /*}}}*/
0a8e3465
AL
879
880// DoUpdate - Update the package lists /*{{{*/
881// ---------------------------------------------------------------------
882/* */
0919e3f9 883bool DoUpdate(CommandLine &)
0a8e3465 884{
0919e3f9
AL
885 // Get the source list
886 pkgSourceList List;
887 if (List.ReadMainList() == false)
888 return false;
889
d38b7b3d 890 // Lock the list directory
36375005 891 FileFd Lock;
d38b7b3d
AL
892 if (_config->FindB("Debug::NoLocking",false) == false)
893 {
36375005 894 Lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
d38b7b3d
AL
895 if (_error->PendingError() == true)
896 return _error->Error("Unable to lock the list directory");
897 }
898
0919e3f9
AL
899 // Create the download object
900 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
901 pkgAcquire Fetcher(&Stat);
902
903 // Populate it with the source selection
904 pkgSourceList::const_iterator I;
905 for (I = List.begin(); I != List.end(); I++)
906 {
907 new pkgAcqIndex(&Fetcher,I);
908 if (_error->PendingError() == true)
909 return false;
910 }
911
912 // Run it
024d1123 913 if (Fetcher.Run() == pkgAcquire::Failed)
0919e3f9
AL
914 return false;
915
9df71a5b
AL
916 bool Failed = false;
917 for (pkgAcquire::Item **I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
918 {
919 if ((*I)->Status == pkgAcquire::Item::StatDone)
920 continue;
921
922 (*I)->Finished();
923
eecf9bf7
AL
924 cerr << "Failed to fetch " << (*I)->DescURI() << endl;
925 cerr << " " << (*I)->ErrorText << endl;
9df71a5b
AL
926 Failed = true;
927 }
928
7a7fa5f0 929 // Clean out any old list files
9df71a5b
AL
930 if (_config->FindB("APT::Get::List-Cleanup",false) == false)
931 {
932 if (Fetcher.Clean(_config->FindDir("Dir::State::lists")) == false ||
933 Fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/") == false)
934 return false;
935 }
7a7fa5f0 936
0919e3f9
AL
937 // Prepare the cache.
938 CacheFile Cache;
a65cbe33 939 if (Cache.Open() == false)
0919e3f9
AL
940 return false;
941
9df71a5b
AL
942 if (Failed == true)
943 return _error->Error("Some index files failed to download, they have been ignored, or old ones used instead.");
0919e3f9 944 return true;
0a8e3465
AL
945}
946 /*}}}*/
947// DoUpgrade - Upgrade all packages /*{{{*/
948// ---------------------------------------------------------------------
949/* Upgrade all packages without installing new packages or erasing old
950 packages */
951bool DoUpgrade(CommandLine &CmdL)
952{
953 CacheFile Cache;
2d11135a 954 if (Cache.Open() == false || Cache.CheckDeps() == false)
0a8e3465
AL
955 return false;
956
957 // Do the upgrade
0a8e3465
AL
958 if (pkgAllUpgrade(Cache) == false)
959 {
421c8d10 960 ShowBroken(c1out,Cache,false);
0a8e3465
AL
961 return _error->Error("Internal Error, AllUpgrade broke stuff");
962 }
963
964 return InstallPackages(Cache,true);
965}
966 /*}}}*/
967// DoInstall - Install packages from the command line /*{{{*/
968// ---------------------------------------------------------------------
969/* Install named packages */
970bool DoInstall(CommandLine &CmdL)
971{
972 CacheFile Cache;
2d11135a 973 if (Cache.Open() == false || Cache.CheckDeps(CmdL.FileSize() != 1) == false)
0a8e3465
AL
974 return false;
975
7c57fe64
AL
976 // Enter the special broken fixing mode if the user specified arguments
977 bool BrokenFix = false;
978 if (Cache->BrokenCount() != 0)
979 BrokenFix = true;
980
a6568219
AL
981 unsigned int ExpectedInst = 0;
982 unsigned int Packages = 0;
0a8e3465
AL
983 pkgProblemResolver Fix(Cache);
984
303a1703
AL
985 bool DefRemove = false;
986 if (strcasecmp(CmdL.FileList[0],"remove") == 0)
987 DefRemove = true;
988
0a8e3465
AL
989 for (const char **I = CmdL.FileList + 1; *I != 0; I++)
990 {
991 // Duplicate the string
992 unsigned int Length = strlen(*I);
993 char S[300];
994 if (Length >= sizeof(S))
995 continue;
996 strcpy(S,*I);
997
998 // See if we are removing the package
303a1703 999 bool Remove = DefRemove;
fc4b5c9f 1000 while (Cache->FindPkg(S).end() == true)
0a8e3465 1001 {
2c3bc8bb
AL
1002 // Handle an optional end tag indicating what to do
1003 if (S[Length - 1] == '-')
1004 {
1005 Remove = true;
1006 S[--Length] = 0;
fc4b5c9f 1007 continue;
2c3bc8bb 1008 }
fc4b5c9f 1009
2c3bc8bb
AL
1010 if (S[Length - 1] == '+')
1011 {
1012 Remove = false;
1013 S[--Length] = 0;
fc4b5c9f 1014 continue;
2c3bc8bb 1015 }
fc4b5c9f 1016 break;
303a1703 1017 }
0a8e3465
AL
1018
1019 // Locate the package
1020 pkgCache::PkgIterator Pkg = Cache->FindPkg(S);
303a1703 1021 Packages++;
0a8e3465 1022 if (Pkg.end() == true)
2c3bc8bb 1023 {
c373c37a
AL
1024 // Check if the name is a regex
1025 const char *I;
1026 for (I = S; *I != 0; I++)
1027 if (*I == '.' || *I == '?' || *I == '*')
1028 break;
1029 if (*I == 0)
1030 return _error->Error("Couldn't find package %s",S);
303a1703 1031
c373c37a
AL
1032 // Regexs must always be confirmed
1033 ExpectedInst += 1000;
1034
1035 // Compile the regex pattern
1036 regex_t Pattern;
1037 if (regcomp(&Pattern,S,REG_EXTENDED | REG_ICASE |
1038 REG_NOSUB) != 0)
1039 return _error->Error("Regex compilation error");
1040
1041 // Run over the matches
1042 bool Hit = false;
1043 for (Pkg = Cache->PkgBegin(); Pkg.end() == false; Pkg++)
303a1703 1044 {
c373c37a
AL
1045 if (regexec(&Pattern,Pkg.Name(),0,0,0) != 0)
1046 continue;
07801a6d 1047
c373c37a
AL
1048 Hit |= TryToInstall(Pkg,Cache,Fix,Remove,BrokenFix,
1049 ExpectedInst,false);
303a1703 1050 }
c373c37a 1051 regfree(&Pattern);
303a1703 1052
c373c37a
AL
1053 if (Hit == false)
1054 return _error->Error("Couldn't find package %s",S);
0a8e3465 1055 }
0a8e3465 1056 else
c373c37a
AL
1057 {
1058 if (TryToInstall(Pkg,Cache,Fix,Remove,BrokenFix,ExpectedInst) == false)
1059 return false;
1060 }
0a8e3465
AL
1061 }
1062
7c57fe64
AL
1063 /* If we are in the Broken fixing mode we do not attempt to fix the
1064 problems. This is if the user invoked install without -f and gave
1065 packages */
1066 if (BrokenFix == true && Cache->BrokenCount() != 0)
1067 {
b5dc9785 1068 c1out << "You might want to run `apt-get -f install' to correct these:" << endl;
421c8d10 1069 ShowBroken(c1out,Cache,false);
7c57fe64 1070
b5dc9785 1071 return _error->Error("Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).");
7c57fe64
AL
1072 }
1073
0a8e3465 1074 // Call the scored problem resolver
303a1703 1075 Fix.InstallProtect();
0a8e3465
AL
1076 if (Fix.Resolve(true) == false)
1077 _error->Discard();
1078
1079 // Now we check the state of the packages,
1080 if (Cache->BrokenCount() != 0)
1081 {
303a1703
AL
1082 c1out << "Some packages could not be installed. This may mean that you have" << endl;
1083 c1out << "requested an impossible situation or if you are using the unstable" << endl;
1084 c1out << "distribution that some required packages have not yet been created" << endl;
1085 c1out << "or been moved out of Incoming." << endl;
1086 if (Packages == 1)
1087 {
1088 c1out << endl;
1089 c1out << "Since you only requested a single operation it is extremely likely that" << endl;
1090 c1out << "the package is simply not installable and a bug report against" << endl;
1091 c1out << "that package should be filed." << endl;
1092 }
1093
1094 c1out << "The following information may help to resolve the situation:" << endl;
1095 c1out << endl;
421c8d10 1096 ShowBroken(c1out,Cache,false);
0a8e3465
AL
1097 return _error->Error("Sorry, broken packages");
1098 }
1099
1100 /* Print out a list of packages that are going to be installed extra
1101 to what the user asked */
1102 if (Cache->InstCount() != ExpectedInst)
1103 {
1104 string List;
1089ca89 1105 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 1106 {
1089ca89 1107 pkgCache::PkgIterator I(Cache,Cache.List[J]);
0a8e3465
AL
1108 if ((*Cache)[I].Install() == false)
1109 continue;
1110
1111 const char **J;
1112 for (J = CmdL.FileList + 1; *J != 0; J++)
1113 if (strcmp(*J,I.Name()) == 0)
1114 break;
1115
1116 if (*J == 0)
1117 List += string(I.Name()) + " ";
1118 }
1119
1120 ShowList(c1out,"The following extra packages will be installed:",List);
1121 }
1122
03e39e59 1123 // See if we need to prompt
2c3bc8bb 1124 if (Cache->InstCount() == ExpectedInst && Cache->DelCount() == 0)
2c3bc8bb 1125 return InstallPackages(Cache,false,false);
2c3bc8bb 1126
03e39e59 1127 return InstallPackages(Cache,false);
0a8e3465
AL
1128}
1129 /*}}}*/
1130// DoDistUpgrade - Automatic smart upgrader /*{{{*/
1131// ---------------------------------------------------------------------
1132/* Intelligent upgrader that will install and remove packages at will */
1133bool DoDistUpgrade(CommandLine &CmdL)
1134{
1135 CacheFile Cache;
2d11135a 1136 if (Cache.Open() == false || Cache.CheckDeps() == false)
0a8e3465
AL
1137 return false;
1138
1139 c0out << "Calculating Upgrade... " << flush;
1140 if (pkgDistUpgrade(*Cache) == false)
1141 {
1142 c0out << "Failed" << endl;
421c8d10 1143 ShowBroken(c1out,Cache,false);
0a8e3465
AL
1144 return false;
1145 }
1146
1147 c0out << "Done" << endl;
1148
1149 return InstallPackages(Cache,true);
1150}
1151 /*}}}*/
1152// DoDSelectUpgrade - Do an upgrade by following dselects selections /*{{{*/
1153// ---------------------------------------------------------------------
1154/* Follows dselect's selections */
1155bool DoDSelectUpgrade(CommandLine &CmdL)
1156{
1157 CacheFile Cache;
2d11135a 1158 if (Cache.Open() == false || Cache.CheckDeps() == false)
0a8e3465
AL
1159 return false;
1160
1161 // Install everything with the install flag set
1162 pkgCache::PkgIterator I = Cache->PkgBegin();
1163 for (;I.end() != true; I++)
1164 {
1165 /* Install the package only if it is a new install, the autoupgrader
1166 will deal with the rest */
1167 if (I->SelectedState == pkgCache::State::Install)
1168 Cache->MarkInstall(I,false);
1169 }
1170
1171 /* Now install their deps too, if we do this above then order of
1172 the status file is significant for | groups */
1173 for (I = Cache->PkgBegin();I.end() != true; I++)
1174 {
1175 /* Install the package only if it is a new install, the autoupgrader
1176 will deal with the rest */
1177 if (I->SelectedState == pkgCache::State::Install)
2f45c76a 1178 Cache->MarkInstall(I,true);
0a8e3465
AL
1179 }
1180
1181 // Apply erasures now, they override everything else.
1182 for (I = Cache->PkgBegin();I.end() != true; I++)
1183 {
1184 // Remove packages
1185 if (I->SelectedState == pkgCache::State::DeInstall ||
1186 I->SelectedState == pkgCache::State::Purge)
d556d1a1 1187 Cache->MarkDelete(I,I->SelectedState == pkgCache::State::Purge);
0a8e3465
AL
1188 }
1189
2f45c76a
AL
1190 /* Resolve any problems that dselect created, allupgrade cannot handle
1191 such things. We do so quite agressively too.. */
1192 if (Cache->BrokenCount() != 0)
1193 {
1194 pkgProblemResolver Fix(Cache);
1195
1196 // Hold back held packages.
1197 if (_config->FindB("APT::Ingore-Hold",false) == false)
1198 {
1199 for (pkgCache::PkgIterator I = Cache->PkgBegin(); I.end() == false; I++)
1200 {
1201 if (I->SelectedState == pkgCache::State::Hold)
1202 {
1203 Fix.Protect(I);
1204 Cache->MarkKeep(I);
1205 }
1206 }
1207 }
1208
1209 if (Fix.Resolve() == false)
1210 {
421c8d10 1211 ShowBroken(c1out,Cache,false);
2f45c76a
AL
1212 return _error->Error("Internal Error, problem resolver broke stuff");
1213 }
1214 }
1215
1216 // Now upgrade everything
0a8e3465
AL
1217 if (pkgAllUpgrade(Cache) == false)
1218 {
421c8d10 1219 ShowBroken(c1out,Cache,false);
2f45c76a 1220 return _error->Error("Internal Error, problem resolver broke stuff");
0a8e3465
AL
1221 }
1222
1223 return InstallPackages(Cache,false);
1224}
1225 /*}}}*/
1226// DoClean - Remove download archives /*{{{*/
1227// ---------------------------------------------------------------------
1228/* */
1229bool DoClean(CommandLine &CmdL)
1230{
8b067c22
AL
1231 if (_config->FindB("APT::Get::Simulate") == true)
1232 {
1233 cout << "Del " << _config->FindDir("Dir::Cache::archives") << "* " <<
1234 _config->FindDir("Dir::Cache::archives") << "partial/*" << endl;
1235 return true;
1236 }
1237
1b6d659c
AL
1238 // Lock the archive directory
1239 FileFd Lock;
1240 if (_config->FindB("Debug::NoLocking",false) == false)
1241 {
1242 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
1243 if (_error->PendingError() == true)
1244 return _error->Error("Unable to lock the download directory");
1245 }
1246
7a1b1f8b
AL
1247 pkgAcquire Fetcher;
1248 Fetcher.Clean(_config->FindDir("Dir::Cache::archives"));
1249 Fetcher.Clean(_config->FindDir("Dir::Cache::archives") + "partial/");
0a8e3465
AL
1250 return true;
1251}
1252 /*}}}*/
1bc849af
AL
1253// DoAutoClean - Smartly remove downloaded archives /*{{{*/
1254// ---------------------------------------------------------------------
1255/* This is similar to clean but it only purges things that cannot be
1256 downloaded, that is old versions of cached packages. */
65a1e968
AL
1257class LogCleaner : public pkgArchiveCleaner
1258{
1259 protected:
1260 virtual void Erase(const char *File,string Pkg,string Ver,struct stat &St)
1261 {
314037ba 1262 cout << "Del " << Pkg << " " << Ver << " [" << SizeToStr(St.st_size) << "B]" << endl;
c1e78ee5
AL
1263
1264 if (_config->FindB("APT::Get::Simulate") == false)
1265 unlink(File);
65a1e968
AL
1266 };
1267};
1268
1bc849af
AL
1269bool DoAutoClean(CommandLine &CmdL)
1270{
1b6d659c
AL
1271 // Lock the archive directory
1272 FileFd Lock;
1273 if (_config->FindB("Debug::NoLocking",false) == false)
1274 {
1275 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
1276 if (_error->PendingError() == true)
1277 return _error->Error("Unable to lock the download directory");
1278 }
1279
1bc849af 1280 CacheFile Cache;
2d11135a 1281 if (Cache.Open() == false)
1bc849af
AL
1282 return false;
1283
65a1e968 1284 LogCleaner Cleaner;
1bc849af
AL
1285
1286 return Cleaner.Go(_config->FindDir("Dir::Cache::archives"),*Cache) &&
1287 Cleaner.Go(_config->FindDir("Dir::Cache::archives") + "partial/",*Cache);
1288}
1289 /*}}}*/
0a8e3465
AL
1290// DoCheck - Perform the check operation /*{{{*/
1291// ---------------------------------------------------------------------
1292/* Opening automatically checks the system, this command is mostly used
1293 for debugging */
1294bool DoCheck(CommandLine &CmdL)
1295{
1296 CacheFile Cache;
1297 Cache.Open();
2d11135a 1298 Cache.CheckDeps();
0a8e3465
AL
1299
1300 return true;
1301}
1302 /*}}}*/
36375005
AL
1303// DoSource - Fetch a source archive /*{{{*/
1304// ---------------------------------------------------------------------
2d11135a 1305/* Fetch souce packages */
fb0ee66e
AL
1306struct DscFile
1307{
1308 string Package;
1309 string Version;
1310 string Dsc;
1311};
1312
36375005
AL
1313bool DoSource(CommandLine &CmdL)
1314{
1315 CacheFile Cache;
2d11135a 1316 if (Cache.Open(false) == false)
36375005
AL
1317 return false;
1318
2d11135a
AL
1319 if (CmdL.FileSize() <= 1)
1320 return _error->Error("Must specify at least one package to fetch source for");
1321
36375005
AL
1322 // Read the source list
1323 pkgSourceList List;
1324 if (List.ReadMainList() == false)
1325 return _error->Error("The list of sources could not be read.");
1326
1327 // Create the text record parsers
1328 pkgRecords Recs(Cache);
1329 pkgSrcRecords SrcRecs(List);
1330 if (_error->PendingError() == true)
1331 return false;
1332
1333 // Create the download object
1334 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
1335 pkgAcquire Fetcher(&Stat);
fb0ee66e
AL
1336
1337 DscFile *Dsc = new DscFile[CmdL.FileSize()];
36375005
AL
1338
1339 // Load the requestd sources into the fetcher
fb0ee66e
AL
1340 unsigned J = 0;
1341 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
36375005
AL
1342 {
1343 string Src;
0a8e3465 1344
36375005
AL
1345 /* Lookup the version of the package we would install if we were to
1346 install a version and determine the source package name, then look
1347 in the archive for a source package of the same name. In theory
1348 we could stash the version string as well and match that too but
1349 today there aren't multi source versions in the archive. */
1350 pkgCache::PkgIterator Pkg = Cache->FindPkg(*I);
1351 if (Pkg.end() == false)
1352 {
1353 pkgCache::VerIterator Ver = Cache->GetCandidateVer(Pkg);
1354 if (Ver.end() == false)
1355 {
1356 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1357 Src = Parse.SourcePkg();
1358 }
1359 }
1360
1361 // No source package name..
1362 if (Src.empty() == true)
1363 Src = *I;
1364
1365 // The best hit
1366 pkgSrcRecords::Parser *Last = 0;
1367 unsigned long Offset = 0;
1368 string Version;
73c2c61b 1369 bool IsMatch = false;
36375005
AL
1370
1371 // Iterate over all of the hits
1372 pkgSrcRecords::Parser *Parse;
1373 SrcRecs.Restart();
1374 while ((Parse = SrcRecs.Find(Src.c_str(),false)) != 0)
1375 {
1376 string Ver = Parse->Version();
73c2c61b
AL
1377
1378 // Skip name mismatches
1379 if (IsMatch == true && Parse->Package() != Src)
1380 continue;
1381
1382 // Newer version or an exact match
1383 if (Last == 0 || pkgVersionCompare(Version,Ver) < 0 ||
1384 (Parse->Package() == Src && IsMatch == false))
36375005 1385 {
73c2c61b 1386 IsMatch = Parse->Package() == Src;
36375005
AL
1387 Last = Parse;
1388 Offset = Parse->Offset();
1389 Version = Ver;
1390 }
1391 }
1392
1393 if (Last == 0)
1394 return _error->Error("Unable to find a source package for %s",Src.c_str());
1395
1396 // Back track
1397 vector<pkgSrcRecords::File> Lst;
1398 if (Last->Jump(Offset) == false || Last->Files(Lst) == false)
1399 return false;
1400
1401 // Load them into the fetcher
1402 for (vector<pkgSrcRecords::File>::const_iterator I = Lst.begin();
1403 I != Lst.end(); I++)
1404 {
1405 // Try to guess what sort of file it is we are getting.
1406 string Comp;
1407 if (I->Path.find(".dsc") != string::npos)
fb0ee66e 1408 {
36375005 1409 Comp = "dsc";
fb0ee66e
AL
1410 Dsc[J].Package = Last->Package();
1411 Dsc[J].Version = Last->Version();
1412 Dsc[J].Dsc = flNotDir(I->Path);
1413 }
1414
36375005
AL
1415 if (I->Path.find(".tar.gz") != string::npos)
1416 Comp = "tar";
1417 if (I->Path.find(".diff.gz") != string::npos)
1418 Comp = "diff";
1419
17c0e8e1
AL
1420 // Diff only mode only fetches .diff files
1421 if (_config->FindB("APT::Get::Diff-Only",false) == true &&
1422 Comp != "diff")
1423 continue;
1424
1425 // Tar only mode only fetches .tar files
1426 if (_config->FindB("APT::Get::Tar-Only",false) == true &&
1427 Comp != "tar")
1428 continue;
1429
36375005
AL
1430 new pkgAcqFile(&Fetcher,Last->Source()->ArchiveURI(I->Path),
1431 I->MD5Hash,I->Size,Last->Source()->SourceInfo(Src,
1432 Last->Version(),Comp),Src);
1433 }
1434 }
1435
1436 // Display statistics
1437 unsigned long FetchBytes = Fetcher.FetchNeeded();
1438 unsigned long FetchPBytes = Fetcher.PartialPresent();
1439 unsigned long DebBytes = Fetcher.TotalNeeded();
1440
1441 // Check for enough free space
1442 struct statfs Buf;
1443 string OutputDir = ".";
1444 if (statfs(OutputDir.c_str(),&Buf) != 0)
1445 return _error->Errno("statfs","Couldn't determine free space in %s",
1446 OutputDir.c_str());
1447 if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
1448 return _error->Error("Sorry, you don't have enough free space in %s",
1449 OutputDir.c_str());
1450
1451 // Number of bytes
1452 c1out << "Need to get ";
1453 if (DebBytes != FetchBytes)
314037ba 1454 c1out << SizeToStr(FetchBytes) << "B/" << SizeToStr(DebBytes) << 'B';
36375005 1455 else
314037ba 1456 c1out << SizeToStr(DebBytes) << 'B';
36375005
AL
1457 c1out << " of source archives." << endl;
1458
2c0c53b3
AL
1459 if (_config->FindB("APT::Get::Simulate",false) == true)
1460 {
1461 for (unsigned I = 0; I != J; I++)
1462 cout << "Fetch Source " << Dsc[I].Package << endl;
1463 return true;
1464 }
1465
36375005
AL
1466 // Just print out the uris an exit if the --print-uris flag was used
1467 if (_config->FindB("APT::Get::Print-URIs") == true)
1468 {
1469 pkgAcquire::UriIterator I = Fetcher.UriBegin();
1470 for (; I != Fetcher.UriEnd(); I++)
1471 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
1472 I->Owner->FileSize << ' ' << I->Owner->MD5Sum() << endl;
1473 return true;
1474 }
1475
1476 // Run it
024d1123 1477 if (Fetcher.Run() == pkgAcquire::Failed)
36375005
AL
1478 return false;
1479
1480 // Print error messages
fb0ee66e 1481 bool Failed = false;
36375005
AL
1482 for (pkgAcquire::Item **I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
1483 {
1484 if ((*I)->Status == pkgAcquire::Item::StatDone &&
1485 (*I)->Complete == true)
1486 continue;
1487
1488 cerr << "Failed to fetch " << (*I)->DescURI() << endl;
1489 cerr << " " << (*I)->ErrorText << endl;
fb0ee66e 1490 Failed = true;
36375005 1491 }
fb0ee66e
AL
1492 if (Failed == true)
1493 return _error->Error("Failed to fetch some archives.");
1494
1495 if (_config->FindB("APT::Get::Download-only",false) == true)
1496 return true;
36375005 1497
fb0ee66e 1498 // Unpack the sources
54676e1a
AL
1499 pid_t Process = ExecFork();
1500
1501 if (Process == 0)
fb0ee66e 1502 {
54676e1a 1503 for (unsigned I = 0; I != J; I++)
fb0ee66e 1504 {
54676e1a 1505 string Dir = Dsc[I].Package + '-' + pkgBaseVersion(Dsc[I].Version.c_str());
fb0ee66e 1506
17c0e8e1
AL
1507 // Diff only mode only fetches .diff files
1508 if (_config->FindB("APT::Get::Diff-Only",false) == true ||
1509 _config->FindB("APT::Get::Tar-Only",false) == true)
1510 continue;
1511
54676e1a
AL
1512 // See if the package is already unpacked
1513 struct stat Stat;
1514 if (stat(Dir.c_str(),&Stat) == 0 &&
1515 S_ISDIR(Stat.st_mode) != 0)
1516 {
1517 c0out << "Skipping unpack of already unpacked source in " << Dir << endl;
1518 }
1519 else
1520 {
1521 // Call dpkg-source
1522 char S[500];
1523 snprintf(S,sizeof(S),"%s -x %s",
1524 _config->Find("Dir::Bin::dpkg-source","dpkg-source").c_str(),
1525 Dsc[I].Dsc.c_str());
1526 if (system(S) != 0)
1527 {
1528 cerr << "Unpack command '" << S << "' failed." << endl;
1529 _exit(1);
1530 }
1531 }
1532
1533 // Try to compile it with dpkg-buildpackage
1534 if (_config->FindB("APT::Get::Compile",false) == true)
1535 {
1536 // Call dpkg-buildpackage
1537 char S[500];
1538 snprintf(S,sizeof(S),"cd %s && %s %s",
1539 Dir.c_str(),
1540 _config->Find("Dir::Bin::dpkg-buildpackage","dpkg-buildpackage").c_str(),
1541 _config->Find("DPkg::Build-Options","-b -uc").c_str());
1542
1543 if (system(S) != 0)
1544 {
1545 cerr << "Build command '" << S << "' failed." << endl;
1546 _exit(1);
1547 }
1548 }
1549 }
1550
1551 _exit(0);
1552 }
1553
1554 // Wait for the subprocess
1555 int Status = 0;
1556 while (waitpid(Process,&Status,0) != Process)
1557 {
1558 if (errno == EINTR)
1559 continue;
1560 return _error->Errno("waitpid","Couldn't wait for subprocess");
1561 }
1562
1563 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1564 return _error->Error("Child process failed");
1565
36375005
AL
1566 return true;
1567}
1568 /*}}}*/
1569
0a8e3465
AL
1570// ShowHelp - Show a help screen /*{{{*/
1571// ---------------------------------------------------------------------
1572/* */
212ad54a 1573bool ShowHelp(CommandLine &CmdL)
0a8e3465
AL
1574{
1575 cout << PACKAGE << ' ' << VERSION << " for " << ARCHITECTURE <<
1576 " compiled on " << __DATE__ << " " << __TIME__ << endl;
04aa15a8
AL
1577 if (_config->FindB("version") == true)
1578 return 100;
1579
0a8e3465
AL
1580 cout << "Usage: apt-get [options] command" << endl;
1581 cout << " apt-get [options] install pkg1 [pkg2 ...]" << endl;
1582 cout << endl;
1583 cout << "apt-get is a simple command line interface for downloading and" << endl;
1584 cout << "installing packages. The most frequently used commands are update" << endl;
1585 cout << "and install." << endl;
1586 cout << endl;
1587 cout << "Commands:" << endl;
1588 cout << " update - Retrieve new lists of packages" << endl;
1589 cout << " upgrade - Perform an upgrade" << endl;
1590 cout << " install - Install new packages (pkg is libc6 not libc6.deb)" << endl;
303a1703 1591 cout << " remove - Remove packages" << endl;
4994560c 1592 cout << " source - Download source archives" << endl;
0a8e3465
AL
1593 cout << " dist-upgrade - Distribution upgrade, see apt-get(8)" << endl;
1594 cout << " dselect-upgrade - Follow dselect selections" << endl;
1595 cout << " clean - Erase downloaded archive files" << endl;
1bc849af 1596 cout << " autoclean - Erase old downloaded archive files" << endl;
0a8e3465
AL
1597 cout << " check - Verify that there are no broken dependencies" << endl;
1598 cout << endl;
1599 cout << "Options:" << endl;
c217f42a
AL
1600 cout << " -h This help text." << endl;
1601 cout << " -q Loggable output - no progress indicator" << endl;
0a8e3465
AL
1602 cout << " -qq No output except for errors" << endl;
1603 cout << " -d Download only - do NOT install or unpack archives" << endl;
1604 cout << " -s No-act. Perform ordering simulation" << endl;
1605 cout << " -y Assume Yes to all queries and do not prompt" << endl;
1606 cout << " -f Attempt to continue if the integrity check fails" << endl;
1607 cout << " -m Attempt to continue if archives are unlocatable" << endl;
1608 cout << " -u Show a list of upgraded packages as well" << endl;
b5dc9785 1609 cout << " -b Build the source package after fetching it" << endl;
0a8e3465 1610 cout << " -c=? Read this configuration file" << endl;
7974b907 1611 cout << " -o=? Set an arbitary configuration option, eg -o dir::cache=/tmp" << endl;
21ae3cae 1612 cout << "See the apt-get(8), sources.list(5) and apt.conf(5) manual" << endl;
fc4b5c9f 1613 cout << "pages for more information and options." << endl;
0a8e3465
AL
1614 return 100;
1615}
1616 /*}}}*/
1617// GetInitialize - Initialize things for apt-get /*{{{*/
1618// ---------------------------------------------------------------------
1619/* */
1620void GetInitialize()
1621{
1622 _config->Set("quiet",0);
1623 _config->Set("help",false);
1624 _config->Set("APT::Get::Download-Only",false);
1625 _config->Set("APT::Get::Simulate",false);
1626 _config->Set("APT::Get::Assume-Yes",false);
1627 _config->Set("APT::Get::Fix-Broken",false);
83d89a9f 1628 _config->Set("APT::Get::Force-Yes",false);
9df71a5b 1629 _config->Set("APT::Get::APT::Get::No-List-Cleanup",true);
0a8e3465
AL
1630}
1631 /*}}}*/
d7827aca
AL
1632// SigWinch - Window size change signal handler /*{{{*/
1633// ---------------------------------------------------------------------
1634/* */
1635void SigWinch(int)
1636{
1637 // Riped from GNU ls
1638#ifdef TIOCGWINSZ
1639 struct winsize ws;
1640
1641 if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col >= 5)
1642 ScreenWidth = ws.ws_col - 1;
1643#endif
1644}
1645 /*}}}*/
0a8e3465
AL
1646
1647int main(int argc,const char *argv[])
1648{
1649 CommandLine::Args Args[] = {
1650 {'h',"help","help",0},
04aa15a8 1651 {'v',"version","version",0},
0a8e3465
AL
1652 {'q',"quiet","quiet",CommandLine::IntLevel},
1653 {'q',"silent","quiet",CommandLine::IntLevel},
1654 {'d',"download-only","APT::Get::Download-Only",0},
fb0ee66e
AL
1655 {'b',"compile","APT::Get::Compile",0},
1656 {'b',"build","APT::Get::Compile",0},
d150b09d
AL
1657 {'s',"simulate","APT::Get::Simulate",0},
1658 {'s',"just-print","APT::Get::Simulate",0},
1659 {'s',"recon","APT::Get::Simulate",0},
1660 {'s',"no-act","APT::Get::Simulate",0},
1661 {'y',"yes","APT::Get::Assume-Yes",0},
0a8e3465
AL
1662 {'y',"assume-yes","APT::Get::Assume-Yes",0},
1663 {'f',"fix-broken","APT::Get::Fix-Broken",0},
1664 {'u',"show-upgraded","APT::Get::Show-Upgraded",0},
30e1eab5 1665 {'m',"ignore-missing","APT::Get::Fix-Missing",0},
ab559b35 1666 {0,"no-download","APT::Get::No-Download",0},
30e1eab5 1667 {0,"fix-missing","APT::Get::Fix-Missing",0},
c88edf1d 1668 {0,"ignore-hold","APT::Ingore-Hold",0},
83d89a9f
AL
1669 {0,"no-upgrade","APT::Get::no-upgrade",0},
1670 {0,"force-yes","APT::Get::force-yes",0},
f7a08e33 1671 {0,"print-uris","APT::Get::Print-URIs",0},
5fafc0ef
AL
1672 {0,"diff-only","APT::Get::Diff-Only",0},
1673 {0,"tar-only","APT::Get::tar-Only",0},
fc4b5c9f 1674 {0,"purge","APT::Get::Purge",0},
9df71a5b 1675 {0,"list-cleanup","APT::Get::List-Cleanup",0},
d0c59649 1676 {0,"reinstall","APT::Get::ReInstall",0},
d150b09d
AL
1677 {0,"trivial-only","APT::Get::Trivial-Only",0},
1678 {0,"no-remove","APT::Get::No-Remove",0},
0a8e3465
AL
1679 {'c',"config-file",0,CommandLine::ConfigFile},
1680 {'o',"option",0,CommandLine::ArbItem},
1681 {0,0,0,0}};
83d89a9f
AL
1682 CommandLine::Dispatch Cmds[] = {{"update",&DoUpdate},
1683 {"upgrade",&DoUpgrade},
1684 {"install",&DoInstall},
1685 {"remove",&DoInstall},
1686 {"dist-upgrade",&DoDistUpgrade},
1687 {"dselect-upgrade",&DoDSelectUpgrade},
1688 {"clean",&DoClean},
1bc849af 1689 {"autoclean",&DoAutoClean},
83d89a9f 1690 {"check",&DoCheck},
36375005 1691 {"source",&DoSource},
3d615484 1692 {"help",&ShowHelp},
83d89a9f 1693 {0,0}};
0a8e3465
AL
1694
1695 // Parse the command line and initialize the package library
1696 CommandLine CmdL(Args,_config);
1697 if (pkgInitialize(*_config) == false ||
1698 CmdL.Parse(argc,argv) == false)
1699 {
1700 _error->DumpErrors();
1701 return 100;
1702 }
1703
1704 // See if the help should be shown
1705 if (_config->FindB("help") == true ||
04aa15a8 1706 _config->FindB("version") == true ||
0a8e3465 1707 CmdL.FileSize() == 0)
3d615484 1708 return ShowHelp(CmdL);
0a8e3465 1709
a9a5908d
AL
1710 // Deal with stdout not being a tty
1711 if (ttyname(STDOUT_FILENO) == 0 && _config->FindI("quiet",0) < 1)
1712 _config->Set("quiet","1");
1713
0a8e3465
AL
1714 // Setup the output streams
1715 c0out.rdbuf(cout.rdbuf());
1716 c1out.rdbuf(cout.rdbuf());
1717 c2out.rdbuf(cout.rdbuf());
1718 if (_config->FindI("quiet",0) > 0)
1719 c0out.rdbuf(devnull.rdbuf());
1720 if (_config->FindI("quiet",0) > 1)
1721 c1out.rdbuf(devnull.rdbuf());
d7827aca
AL
1722
1723 // Setup the signals
1724 signal(SIGPIPE,SIG_IGN);
1725 signal(SIGWINCH,SigWinch);
1726 SigWinch(0);
0a8e3465
AL
1727
1728 // Match the operation
83d89a9f 1729 CmdL.DispatchArg(Cmds);
0a8e3465
AL
1730
1731 // Print any errors or warnings found during parsing
1732 if (_error->empty() == false)
1733 {
1734 bool Errors = _error->PendingError();
1735 _error->DumpErrors();
0a8e3465
AL
1736 return Errors == true?100:0;
1737 }
1738
1739 return 0;
1740}