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