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