Add timeout support for https.
[ntk/apt.git] / cmdline / apt-get.cc
CommitLineData
5ec427c2
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
640c5d94 3// $Id: apt-get.cc,v 1.156 2004/08/28 01:05:16 mdz 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>
cdcc6d34 35#include <apt-pkg/strutl.h>
1bc849af 36#include <apt-pkg/clean.h>
36375005
AL
37#include <apt-pkg/srcrecords.h>
38#include <apt-pkg/version.h>
2d11135a 39#include <apt-pkg/cachefile.h>
b2e465d6 40#include <apt-pkg/sptr.h>
092ae175 41#include <apt-pkg/md5.h>
b2e465d6
AL
42#include <apt-pkg/versionmatch.h>
43
0a8e3465 44#include <config.h>
b2e465d6 45#include <apti18n.h>
0a8e3465 46
0919e3f9
AL
47#include "acqprogress.h"
48
092ae175 49#include <set>
233c2b66 50#include <locale.h>
c8ca0ce1 51#include <langinfo.h>
90f057fd 52#include <fstream>
d7827aca
AL
53#include <termios.h>
54#include <sys/ioctl.h>
1bc849af 55#include <sys/stat.h>
885d204b 56#include <sys/statfs.h>
101030ab 57#include <sys/statvfs.h>
d7827aca 58#include <signal.h>
65a1e968 59#include <unistd.h>
3e3221ba 60#include <stdio.h>
d6e79b75 61#include <errno.h>
c373c37a 62#include <regex.h>
54676e1a 63#include <sys/wait.h>
afb1e2e3 64#include <sstream>
0a8e3465
AL
65 /*}}}*/
66
885d204b
OS
67#define RAMFS_MAGIC 0x858458f6
68
076d01b0
AL
69using namespace std;
70
71ostream c0out(0);
72ostream c1out(0);
73ostream c2out(0);
0a8e3465 74ofstream devnull("/dev/null");
463870e4 75unsigned int ScreenWidth = 80 - 1; /* - 1 for the cursor */
0a8e3465 76
1089ca89
AL
77// class CacheFile - Cover class for some dependency cache functions /*{{{*/
78// ---------------------------------------------------------------------
79/* */
80class CacheFile : public pkgCacheFile
81{
82 static pkgCache *SortCache;
83 static int NameComp(const void *a,const void *b);
84
85 public:
86 pkgCache::Package **List;
87
88 void Sort();
89 bool CheckDeps(bool AllowBroken = false);
0077d829
AL
90 bool BuildCaches(bool WithLock = true)
91 {
92 OpTextProgress Prog(*_config);
93 if (pkgCacheFile::BuildCaches(Prog,WithLock) == false)
94 return false;
95 return true;
96 }
1089ca89
AL
97 bool Open(bool WithLock = true)
98 {
99 OpTextProgress Prog(*_config);
100 if (pkgCacheFile::Open(Prog,WithLock) == false)
101 return false;
102 Sort();
b2e465d6 103
1089ca89
AL
104 return true;
105 };
c37b9502
AL
106 bool OpenForInstall()
107 {
108 if (_config->FindB("APT::Get::Print-URIs") == true)
079a992d 109 return Open(false);
c37b9502 110 else
079a992d 111 return Open(true);
c37b9502 112 }
1089ca89
AL
113 CacheFile() : List(0) {};
114};
115 /*}}}*/
116
a6568219
AL
117// YnPrompt - Yes No Prompt. /*{{{*/
118// ---------------------------------------------------------------------
119/* Returns true on a Yes.*/
7db98ffc 120bool YnPrompt(bool Default=true)
a6568219
AL
121{
122 if (_config->FindB("APT::Get::Assume-Yes",false) == true)
123 {
10cda9fe 124 c1out << _("Y") << endl;
a6568219
AL
125 return true;
126 }
10cda9fe
AL
127
128 char response[1024] = "";
129 cin.getline(response, sizeof(response));
130
131 if (!cin)
b2e465d6 132 return false;
10cda9fe
AL
133
134 if (strlen(response) == 0)
7db98ffc 135 return Default;
10cda9fe
AL
136
137 regex_t Pattern;
138 int Res;
139
140 Res = regcomp(&Pattern, nl_langinfo(YESEXPR),
141 REG_EXTENDED|REG_ICASE|REG_NOSUB);
142
143 if (Res != 0) {
144 char Error[300];
145 regerror(Res,&Pattern,Error,sizeof(Error));
146 return _error->Error(_("Regex compilation error - %s"),Error);
147 }
a6568219 148
10cda9fe
AL
149 Res = regexec(&Pattern, response, 0, NULL, 0);
150 if (Res == 0)
151 return true;
152 return false;
a6568219
AL
153}
154 /*}}}*/
6f86c974
AL
155// AnalPrompt - Annoying Yes No Prompt. /*{{{*/
156// ---------------------------------------------------------------------
157/* Returns true on a Yes.*/
158bool AnalPrompt(const char *Text)
159{
160 char Buf[1024];
161 cin.getline(Buf,sizeof(Buf));
162 if (strcmp(Buf,Text) == 0)
163 return true;
164 return false;
165}
166 /*}}}*/
0a8e3465
AL
167// ShowList - Show a list /*{{{*/
168// ---------------------------------------------------------------------
b2e465d6 169/* This prints out a string of space separated words with a title and
0a8e3465 170 a two space indent line wraped to the current screen width. */
ac625538 171bool ShowList(ostream &out,string Title,string List,string VersionsList)
0a8e3465
AL
172{
173 if (List.empty() == true)
83d89a9f 174 return true;
4968036c
AL
175 // trim trailing space
176 int NonSpace = List.find_last_not_of(' ');
177 if (NonSpace != -1)
178 {
179 List = List.erase(NonSpace + 1);
180 if (List.empty() == true)
181 return true;
182 }
0a8e3465
AL
183
184 // Acount for the leading space
185 int ScreenWidth = ::ScreenWidth - 3;
186
187 out << Title << endl;
188 string::size_type Start = 0;
ac625538 189 string::size_type VersionsStart = 0;
0a8e3465
AL
190 while (Start < List.size())
191 {
ac625538
AL
192 if(_config->FindB("APT::Get::Show-Versions",false) == true &&
193 VersionsList.size() > 0) {
194 string::size_type End;
195 string::size_type VersionsEnd;
196
197 End = List.find(' ',Start);
198 VersionsEnd = VersionsList.find('\n', VersionsStart);
199
200 out << " " << string(List,Start,End - Start) << " (" <<
201 string(VersionsList,VersionsStart,VersionsEnd - VersionsStart) <<
202 ")" << endl;
03b9be80
AL
203
204 if (End == string::npos || End < Start)
205 End = Start + ScreenWidth;
206
ac625538
AL
207 Start = End + 1;
208 VersionsStart = VersionsEnd + 1;
209 } else {
210 string::size_type End;
211
212 if (Start + ScreenWidth >= List.size())
213 End = List.size();
214 else
215 End = List.rfind(' ',Start+ScreenWidth);
216
217 if (End == string::npos || End < Start)
218 End = Start + ScreenWidth;
219 out << " " << string(List,Start,End - Start) << endl;
220 Start = End + 1;
221 }
0a8e3465 222 }
ac625538 223
83d89a9f 224 return false;
0a8e3465
AL
225}
226 /*}}}*/
227// ShowBroken - Debugging aide /*{{{*/
228// ---------------------------------------------------------------------
229/* This prints out the names of all the packages that are broken along
230 with the name of each each broken dependency and a quite version
b2e465d6
AL
231 description.
232
233 The output looks like:
677cbcbc 234 The following packages have unmet dependencies:
b2e465d6
AL
235 exim: Depends: libc6 (>= 2.1.94) but 2.1.3-10 is to be installed
236 Depends: libldap2 (>= 2.0.2-2) but it is not going to be installed
237 Depends: libsasl7 but it is not going to be installed
238 */
421c8d10 239void ShowBroken(ostream &out,CacheFile &Cache,bool Now)
0a8e3465 240{
677cbcbc 241 out << _("The following packages have unmet dependencies:") << endl;
1089ca89 242 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 243 {
1089ca89
AL
244 pkgCache::PkgIterator I(Cache,Cache.List[J]);
245
079a992d
AL
246 if (Now == true)
247 {
248 if (Cache[I].NowBroken() == false)
249 continue;
250 }
251 else
252 {
253 if (Cache[I].InstBroken() == false)
254 continue;
255 }
256
303a1703
AL
257 // Print out each package and the failed dependencies
258 out <<" " << I.Name() << ":";
648e3cb4 259 unsigned Indent = strlen(I.Name()) + 3;
303a1703 260 bool First = true;
079a992d
AL
261 pkgCache::VerIterator Ver;
262
263 if (Now == true)
264 Ver = I.CurrentVer();
265 else
266 Ver = Cache[I].InstVerIter(Cache);
267
268 if (Ver.end() == true)
0a8e3465 269 {
079a992d 270 out << endl;
303a1703
AL
271 continue;
272 }
273
079a992d 274 for (pkgCache::DepIterator D = Ver.DependsList(); D.end() == false;)
303a1703 275 {
30e1eab5
AL
276 // Compute a single dependency element (glob or)
277 pkgCache::DepIterator Start;
278 pkgCache::DepIterator End;
d20333af 279 D.GlobOr(Start,End); // advances D
76fbce56 280
079a992d 281 if (Cache->IsImportantDep(End) == false)
303a1703 282 continue;
079a992d
AL
283
284 if (Now == true)
285 {
286 if ((Cache[End] & pkgDepCache::DepGNow) == pkgDepCache::DepGNow)
287 continue;
288 }
289 else
290 {
291 if ((Cache[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall)
292 continue;
293 }
294
648e3cb4
AL
295 bool FirstOr = true;
296 while (1)
0a8e3465 297 {
648e3cb4
AL
298 if (First == false)
299 for (unsigned J = 0; J != Indent; J++)
300 out << ' ';
301 First = false;
302
303 if (FirstOr == false)
304 {
305 for (unsigned J = 0; J != strlen(End.DepType()) + 3; J++)
306 out << ' ';
307 }
0a8e3465 308 else
648e3cb4
AL
309 out << ' ' << End.DepType() << ": ";
310 FirstOr = false;
311
312 out << Start.TargetPkg().Name();
313
314 // Show a quick summary of the version requirements
315 if (Start.TargetVer() != 0)
b2e465d6 316 out << " (" << Start.CompType() << " " << Start.TargetVer() << ")";
648e3cb4
AL
317
318 /* Show a summary of the target package if possible. In the case
319 of virtual packages we show nothing */
320 pkgCache::PkgIterator Targ = Start.TargetPkg();
321 if (Targ->ProvidesList == 0)
7e798dd7 322 {
b2e465d6 323 out << ' ';
648e3cb4 324 pkgCache::VerIterator Ver = Cache[Targ].InstVerIter(Cache);
f0ec51c2
AL
325 if (Now == true)
326 Ver = Targ.CurrentVer();
079a992d 327
648e3cb4 328 if (Ver.end() == false)
b2e465d6
AL
329 {
330 if (Now == true)
331 ioprintf(out,_("but %s is installed"),Ver.VerStr());
332 else
333 ioprintf(out,_("but %s is to be installed"),Ver.VerStr());
334 }
648e3cb4 335 else
303a1703 336 {
648e3cb4
AL
337 if (Cache[Targ].CandidateVerIter(Cache).end() == true)
338 {
339 if (Targ->ProvidesList == 0)
b2e465d6 340 out << _("but it is not installable");
648e3cb4 341 else
b2e465d6 342 out << _("but it is a virtual package");
648e3cb4 343 }
303a1703 344 else
b2e465d6 345 out << (Now?_("but it is not installed"):_("but it is not going to be installed"));
648e3cb4
AL
346 }
347 }
348
349 if (Start != End)
b2e465d6 350 out << _(" or");
648e3cb4
AL
351 out << endl;
352
353 if (Start == End)
354 break;
355 Start++;
356 }
303a1703 357 }
0a8e3465
AL
358 }
359}
360 /*}}}*/
361// ShowNew - Show packages to newly install /*{{{*/
362// ---------------------------------------------------------------------
363/* */
1089ca89 364void ShowNew(ostream &out,CacheFile &Cache)
0a8e3465 365{
89260e53 366 /* Print out a list of packages that are going to be installed extra
0a8e3465 367 to what the user asked */
0a8e3465 368 string List;
ac625538 369 string VersionsList;
1089ca89
AL
370 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
371 {
372 pkgCache::PkgIterator I(Cache,Cache.List[J]);
ac625538
AL
373 if (Cache[I].NewInstall() == true) {
374 List += string(I.Name()) + " ";
375 VersionsList += string(Cache[I].CandVersion) + "\n";
376 }
1089ca89
AL
377 }
378
ac625538 379 ShowList(out,_("The following NEW packages will be installed:"),List,VersionsList);
0a8e3465
AL
380}
381 /*}}}*/
382// ShowDel - Show packages to delete /*{{{*/
383// ---------------------------------------------------------------------
384/* */
1089ca89 385void ShowDel(ostream &out,CacheFile &Cache)
0a8e3465
AL
386{
387 /* Print out a list of packages that are going to be removed extra
388 to what the user asked */
0a8e3465 389 string List;
ac625538 390 string VersionsList;
1089ca89 391 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
fc4b5c9f 392 {
1089ca89
AL
393 pkgCache::PkgIterator I(Cache,Cache.List[J]);
394 if (Cache[I].Delete() == true)
fc4b5c9f 395 {
1089ca89 396 if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
fc4b5c9f
AL
397 List += string(I.Name()) + "* ";
398 else
399 List += string(I.Name()) + " ";
ac625538
AL
400
401 VersionsList += string(Cache[I].CandVersion)+ "\n";
fc4b5c9f
AL
402 }
403 }
3d615484 404
ac625538 405 ShowList(out,_("The following packages will be REMOVED:"),List,VersionsList);
0a8e3465
AL
406}
407 /*}}}*/
408// ShowKept - Show kept packages /*{{{*/
409// ---------------------------------------------------------------------
410/* */
f292686b 411void ShowKept(ostream &out,CacheFile &Cache)
0a8e3465 412{
0a8e3465 413 string List;
ac625538 414 string VersionsList;
f292686b 415 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 416 {
f292686b
AL
417 pkgCache::PkgIterator I(Cache,Cache.List[J]);
418
0a8e3465 419 // Not interesting
f292686b
AL
420 if (Cache[I].Upgrade() == true || Cache[I].Upgradable() == false ||
421 I->CurrentVer == 0 || Cache[I].Delete() == true)
0a8e3465
AL
422 continue;
423
424 List += string(I.Name()) + " ";
ac625538 425 VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
0a8e3465 426 }
aee7bceb 427 ShowList(out,_("The following packages have been kept back:"),List,VersionsList);
0a8e3465
AL
428}
429 /*}}}*/
430// ShowUpgraded - Show upgraded packages /*{{{*/
431// ---------------------------------------------------------------------
432/* */
1089ca89 433void ShowUpgraded(ostream &out,CacheFile &Cache)
0a8e3465 434{
0a8e3465 435 string List;
ac625538 436 string VersionsList;
1089ca89 437 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 438 {
1089ca89
AL
439 pkgCache::PkgIterator I(Cache,Cache.List[J]);
440
0a8e3465 441 // Not interesting
1089ca89 442 if (Cache[I].Upgrade() == false || Cache[I].NewInstall() == true)
0a8e3465
AL
443 continue;
444
445 List += string(I.Name()) + " ";
ac625538 446 VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
0a8e3465 447 }
aee7bceb 448 ShowList(out,_("The following packages will be upgraded:"),List,VersionsList);
b2e465d6
AL
449}
450 /*}}}*/
451// ShowDowngraded - Show downgraded packages /*{{{*/
452// ---------------------------------------------------------------------
453/* */
454bool ShowDowngraded(ostream &out,CacheFile &Cache)
455{
456 string List;
ac625538 457 string VersionsList;
b2e465d6
AL
458 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
459 {
460 pkgCache::PkgIterator I(Cache,Cache.List[J]);
461
462 // Not interesting
463 if (Cache[I].Downgrade() == false || Cache[I].NewInstall() == true)
464 continue;
465
466 List += string(I.Name()) + " ";
ac625538 467 VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
b2e465d6 468 }
aee7bceb 469 return ShowList(out,_("The following packages will be DOWNGRADED:"),List,VersionsList);
0a8e3465
AL
470}
471 /*}}}*/
472// ShowHold - Show held but changed packages /*{{{*/
473// ---------------------------------------------------------------------
474/* */
1089ca89 475bool ShowHold(ostream &out,CacheFile &Cache)
0a8e3465 476{
0a8e3465 477 string List;
ac625538 478 string VersionsList;
1089ca89 479 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 480 {
1089ca89
AL
481 pkgCache::PkgIterator I(Cache,Cache.List[J]);
482 if (Cache[I].InstallVer != (pkgCache::Version *)I.CurrentVer() &&
ac625538
AL
483 I->SelectedState == pkgCache::State::Hold) {
484 List += string(I.Name()) + " ";
485 VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
486 }
0a8e3465
AL
487 }
488
ac625538 489 return ShowList(out,_("The following held packages will be changed:"),List,VersionsList);
0a8e3465
AL
490}
491 /*}}}*/
492// ShowEssential - Show an essential package warning /*{{{*/
493// ---------------------------------------------------------------------
494/* This prints out a warning message that is not to be ignored. It shows
495 all essential packages and their dependents that are to be removed.
496 It is insanely risky to remove the dependents of an essential package! */
1089ca89 497bool ShowEssential(ostream &out,CacheFile &Cache)
0a8e3465 498{
0a8e3465 499 string List;
ac625538 500 string VersionsList;
b2e465d6
AL
501 bool *Added = new bool[Cache->Head().PackageCount];
502 for (unsigned int I = 0; I != Cache->Head().PackageCount; I++)
0a8e3465
AL
503 Added[I] = false;
504
1089ca89 505 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 506 {
1089ca89 507 pkgCache::PkgIterator I(Cache,Cache.List[J]);
b2e465d6
AL
508 if ((I->Flags & pkgCache::Flag::Essential) != pkgCache::Flag::Essential &&
509 (I->Flags & pkgCache::Flag::Important) != pkgCache::Flag::Important)
0a8e3465
AL
510 continue;
511
512 // The essential package is being removed
1089ca89 513 if (Cache[I].Delete() == true)
0a8e3465
AL
514 {
515 if (Added[I->ID] == false)
516 {
517 Added[I->ID] = true;
518 List += string(I.Name()) + " ";
ac625538 519 //VersionsList += string(Cache[I].CurVersion) + "\n"; ???
0a8e3465
AL
520 }
521 }
522
523 if (I->CurrentVer == 0)
524 continue;
525
526 // Print out any essential package depenendents that are to be removed
b2e465d6 527 for (pkgCache::DepIterator D = I.CurrentVer().DependsList(); D.end() == false; D++)
0a8e3465 528 {
3e3221ba
AL
529 // Skip everything but depends
530 if (D->Type != pkgCache::Dep::PreDepends &&
531 D->Type != pkgCache::Dep::Depends)
532 continue;
533
0a8e3465 534 pkgCache::PkgIterator P = D.SmartTargetPkg();
1089ca89 535 if (Cache[P].Delete() == true)
0a8e3465
AL
536 {
537 if (Added[P->ID] == true)
538 continue;
539 Added[P->ID] = true;
3e3221ba
AL
540
541 char S[300];
20ebd488 542 snprintf(S,sizeof(S),_("%s (due to %s) "),P.Name(),I.Name());
3e3221ba 543 List += S;
ac625538 544 //VersionsList += "\n"; ???
0a8e3465
AL
545 }
546 }
547 }
548
83d89a9f 549 delete [] Added;
080bf1be 550 return ShowList(out,_("WARNING: The following essential packages will be removed.\n"
ac625538 551 "This should NOT be done unless you know exactly what you are doing!"),List,VersionsList);
0a8e3465 552}
7db98ffc 553
0a8e3465
AL
554 /*}}}*/
555// Stats - Show some statistics /*{{{*/
556// ---------------------------------------------------------------------
557/* */
558void Stats(ostream &out,pkgDepCache &Dep)
559{
560 unsigned long Upgrade = 0;
b2e465d6 561 unsigned long Downgrade = 0;
0a8e3465 562 unsigned long Install = 0;
d0c59649 563 unsigned long ReInstall = 0;
0a8e3465
AL
564 for (pkgCache::PkgIterator I = Dep.PkgBegin(); I.end() == false; I++)
565 {
566 if (Dep[I].NewInstall() == true)
567 Install++;
568 else
b2e465d6 569 {
0a8e3465
AL
570 if (Dep[I].Upgrade() == true)
571 Upgrade++;
b2e465d6
AL
572 else
573 if (Dep[I].Downgrade() == true)
574 Downgrade++;
575 }
576
d0c59649
AL
577 if (Dep[I].Delete() == false && (Dep[I].iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
578 ReInstall++;
0a8e3465
AL
579 }
580
2adb5fda 581 ioprintf(out,_("%lu upgraded, %lu newly installed, "),
b2e465d6
AL
582 Upgrade,Install);
583
d0c59649 584 if (ReInstall != 0)
b2e465d6
AL
585 ioprintf(out,_("%lu reinstalled, "),ReInstall);
586 if (Downgrade != 0)
587 ioprintf(out,_("%lu downgraded, "),Downgrade);
0a8e3465 588
2d425135 589 ioprintf(out,_("%lu to remove and %lu not upgraded.\n"),
b2e465d6
AL
590 Dep.DelCount(),Dep.KeepCount());
591
0a8e3465 592 if (Dep.BadCount() != 0)
2adb5fda 593 ioprintf(out,_("%lu not fully installed or removed.\n"),
b2e465d6 594 Dep.BadCount());
0a8e3465
AL
595}
596 /*}}}*/
597
1089ca89 598// CacheFile::NameComp - QSort compare by name /*{{{*/
0a8e3465
AL
599// ---------------------------------------------------------------------
600/* */
1089ca89
AL
601pkgCache *CacheFile::SortCache = 0;
602int CacheFile::NameComp(const void *a,const void *b)
0a8e3465 603{
8508b1df
AL
604 if (*(pkgCache::Package **)a == 0 || *(pkgCache::Package **)b == 0)
605 return *(pkgCache::Package **)a - *(pkgCache::Package **)b;
0a8e3465 606
1089ca89
AL
607 const pkgCache::Package &A = **(pkgCache::Package **)a;
608 const pkgCache::Package &B = **(pkgCache::Package **)b;
609
610 return strcmp(SortCache->StrP + A.Name,SortCache->StrP + B.Name);
611}
612 /*}}}*/
613// CacheFile::Sort - Sort by name /*{{{*/
614// ---------------------------------------------------------------------
615/* */
616void CacheFile::Sort()
617{
618 delete [] List;
619 List = new pkgCache::Package *[Cache->Head().PackageCount];
620 memset(List,0,sizeof(*List)*Cache->Head().PackageCount);
621 pkgCache::PkgIterator I = Cache->PkgBegin();
622 for (;I.end() != true; I++)
623 List[I->ID] = I;
624
625 SortCache = *this;
626 qsort(List,Cache->Head().PackageCount,sizeof(*List),NameComp);
627}
0a8e3465 628 /*}}}*/
b2e465d6 629// CacheFile::CheckDeps - Open the cache file /*{{{*/
0a8e3465
AL
630// ---------------------------------------------------------------------
631/* This routine generates the caches and then opens the dependency cache
632 and verifies that the system is OK. */
2d11135a 633bool CacheFile::CheckDeps(bool AllowBroken)
0a8e3465 634{
4ef9a929
MV
635 bool FixBroken = _config->FindB("APT::Get::Fix-Broken",false);
636
d38b7b3d
AL
637 if (_error->PendingError() == true)
638 return false;
0a8e3465 639
0a8e3465 640 // Check that the system is OK
b2e465d6 641 if (DCache->DelCount() != 0 || DCache->InstCount() != 0)
db0db9fe 642 return _error->Error("Internal error, non-zero counts");
0a8e3465
AL
643
644 // Apply corrections for half-installed packages
b2e465d6 645 if (pkgApplyStatus(*DCache) == false)
0a8e3465
AL
646 return false;
647
4ef9a929
MV
648 if (_config->FindB("APT::Get::Fix-Policy-Broken",false) == true)
649 {
650 FixBroken = true;
651 if ((DCache->PolicyBrokenCount() > 0))
652 {
653 // upgrade all policy-broken packages with ForceImportantDeps=True
654 for (pkgCache::PkgIterator I = Cache->PkgBegin(); !I.end(); I++)
655 if ((*DCache)[I].NowPolicyBroken() == true)
7610bb3d 656 DCache->MarkInstall(I,true,0, false, true);
4ef9a929
MV
657 }
658 }
659
0a8e3465 660 // Nothing is broken
b2e465d6 661 if (DCache->BrokenCount() == 0 || AllowBroken == true)
0a8e3465
AL
662 return true;
663
664 // Attempt to fix broken things
4ef9a929 665 if (FixBroken == true)
0a8e3465 666 {
b2e465d6
AL
667 c1out << _("Correcting dependencies...") << flush;
668 if (pkgFixBroken(*DCache) == false || DCache->BrokenCount() != 0)
0a8e3465 669 {
b2e465d6 670 c1out << _(" failed.") << endl;
421c8d10 671 ShowBroken(c1out,*this,true);
0a8e3465 672
b2e465d6 673 return _error->Error(_("Unable to correct dependencies"));
0a8e3465 674 }
b2e465d6
AL
675 if (pkgMinimizeUpgrade(*DCache) == false)
676 return _error->Error(_("Unable to minimize the upgrade set"));
0a8e3465 677
b2e465d6 678 c1out << _(" Done") << endl;
0a8e3465
AL
679 }
680 else
681 {
b2e465d6 682 c1out << _("You might want to run `apt-get -f install' to correct these.") << endl;
421c8d10 683 ShowBroken(c1out,*this,true);
0a8e3465 684
b2e465d6 685 return _error->Error(_("Unmet dependencies. Try using -f."));
0a8e3465
AL
686 }
687
688 return true;
689}
7db98ffc
MZ
690
691static bool CheckAuth(pkgAcquire& Fetcher)
692{
693 string UntrustedList;
694 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I < Fetcher.ItemsEnd(); ++I)
695 {
696 if (!(*I)->IsTrusted())
697 {
698 UntrustedList += string((*I)->ShortDesc()) + " ";
699 }
700 }
701
702 if (UntrustedList == "")
703 {
704 return true;
705 }
706
707 ShowList(c2out,_("WARNING: The following packages cannot be authenticated!"),UntrustedList,"");
708
709 if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
710 {
2a7e07c7 711 c2out << _("Authentication warning overridden.\n");
7db98ffc
MZ
712 return true;
713 }
714
715 if (_config->FindI("quiet",0) < 2
716 && _config->FindB("APT::Get::Assume-Yes",false) == false)
717 {
db0db9fe 718 c2out << _("Install these packages without verification [y/N]? ") << flush;
7db98ffc
MZ
719 if (!YnPrompt(false))
720 return _error->Error(_("Some packages could not be authenticated"));
721
722 return true;
723 }
724 else if (_config->FindB("APT::Get::Force-Yes",false) == true)
725 {
726 return true;
727 }
728
729 return _error->Error(_("There are problems and -y was used without --force-yes"));
730}
731
732
0a8e3465
AL
733 /*}}}*/
734
735// InstallPackages - Actually download and install the packages /*{{{*/
736// ---------------------------------------------------------------------
737/* This displays the informative messages describing what is going to
738 happen and then calls the download routines */
a3eaf954 739bool InstallPackages(CacheFile &Cache,bool ShwKept,bool Ask = true,
80fbda96 740 bool Safety = true)
0a8e3465 741{
fc4b5c9f
AL
742 if (_config->FindB("APT::Get::Purge",false) == true)
743 {
744 pkgCache::PkgIterator I = Cache->PkgBegin();
745 for (; I.end() == false; I++)
d556d1a1
AL
746 {
747 if (I.Purge() == false && Cache[I].Mode == pkgDepCache::ModeDelete)
748 Cache->MarkDelete(I,true);
749 }
fc4b5c9f
AL
750 }
751
83d89a9f 752 bool Fail = false;
6f86c974 753 bool Essential = false;
83d89a9f 754
a6568219 755 // Show all the various warning indicators
0a8e3465
AL
756 ShowDel(c1out,Cache);
757 ShowNew(c1out,Cache);
758 if (ShwKept == true)
759 ShowKept(c1out,Cache);
7a215bee 760 Fail |= !ShowHold(c1out,Cache);
906fbf88 761 if (_config->FindB("APT::Get::Show-Upgraded",true) == true)
0a8e3465 762 ShowUpgraded(c1out,Cache);
b2e465d6 763 Fail |= !ShowDowngraded(c1out,Cache);
5d1d0738
AL
764 if (_config->FindB("APT::Get::Download-Only",false) == false)
765 Essential = !ShowEssential(c1out,Cache);
6f86c974 766 Fail |= Essential;
0a8e3465 767 Stats(c1out,Cache);
7db98ffc 768
0a8e3465 769 // Sanity check
d38b7b3d 770 if (Cache->BrokenCount() != 0)
0a8e3465 771 {
421c8d10 772 ShowBroken(c1out,Cache,false);
2a7e07c7 773 return _error->Error(_("Internal error, InstallPackages was called with broken packages!"));
0a8e3465
AL
774 }
775
d0c59649 776 if (Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
d38b7b3d 777 Cache->BadCount() == 0)
c60d151b 778 return true;
03e39e59 779
d150b09d 780 // No remove flag
b2e465d6 781 if (Cache->DelCount() != 0 && _config->FindB("APT::Get::Remove",true) == false)
db0db9fe 782 return _error->Error(_("Packages need to be removed but remove is disabled."));
d150b09d 783
03e39e59
AL
784 // Run the simulator ..
785 if (_config->FindB("APT::Get::Simulate") == true)
786 {
787 pkgSimulate PM(Cache);
2a7e07c7
MV
788 int status_fd = _config->FindI("APT::Status-Fd",-1);
789 pkgPackageManager::OrderResult Res = PM.DoInstall(status_fd);
281daf46
AL
790 if (Res == pkgPackageManager::Failed)
791 return false;
792 if (Res != pkgPackageManager::Completed)
2a7e07c7 793 return _error->Error(_("Internal error, Ordering didn't finish"));
281daf46 794 return true;
03e39e59
AL
795 }
796
797 // Create the text record parser
798 pkgRecords Recs(Cache);
83d89a9f
AL
799 if (_error->PendingError() == true)
800 return false;
801
d38b7b3d 802 // Lock the archive directory
36375005 803 FileFd Lock;
c37b9502
AL
804 if (_config->FindB("Debug::NoLocking",false) == false &&
805 _config->FindB("APT::Get::Print-URIs") == false)
d38b7b3d 806 {
36375005 807 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
d38b7b3d 808 if (_error->PendingError() == true)
b2e465d6 809 return _error->Error(_("Unable to lock the download directory"));
d38b7b3d 810 }
03e39e59
AL
811
812 // Create the download object
813 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
814 pkgAcquire Fetcher(&Stat);
815
816 // Read the source list
817 pkgSourceList List;
818 if (List.ReadMainList() == false)
b2e465d6 819 return _error->Error(_("The list of sources could not be read."));
03e39e59
AL
820
821 // Create the package manager and prepare to download
b2e465d6
AL
822 SPtr<pkgPackageManager> PM= _system->CreatePM(Cache);
823 if (PM->GetArchives(&Fetcher,&List,&Recs) == false ||
424c3bc0 824 _error->PendingError() == true)
03e39e59
AL
825 return false;
826
7a1b1f8b 827 // Display statistics
b2e465d6
AL
828 double FetchBytes = Fetcher.FetchNeeded();
829 double FetchPBytes = Fetcher.PartialPresent();
830 double DebBytes = Fetcher.TotalNeeded();
d38b7b3d
AL
831 if (DebBytes != Cache->DebSize())
832 {
833 c0out << DebBytes << ',' << Cache->DebSize() << endl;
2a7e07c7 834 c0out << _("How odd.. The sizes didn't match, email apt@packages.debian.org") << endl;
d38b7b3d 835 }
138d4b3d 836
7a1b1f8b 837 // Number of bytes
a6568219 838 if (DebBytes != FetchBytes)
ac7fd99c 839 ioprintf(c1out,_("Need to get %sB/%sB of archives.\n"),
b2e465d6 840 SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
813603a0 841 else if (DebBytes != 0)
ac7fd99c 842 ioprintf(c1out,_("Need to get %sB of archives.\n"),
b2e465d6
AL
843 SizeToStr(DebBytes).c_str());
844
10bb1f5f
AL
845 // Size delta
846 if (Cache->UsrSize() >= 0)
813603a0 847 ioprintf(c1out,_("After this operation, %sB of additional disk space will be used.\n"),
b2e465d6 848 SizeToStr(Cache->UsrSize()).c_str());
10bb1f5f 849 else
813603a0 850 ioprintf(c1out,_("After this operation, %sB disk space will be freed.\n"),
b2e465d6 851 SizeToStr(-1*Cache->UsrSize()).c_str());
10bb1f5f
AL
852
853 if (_error->PendingError() == true)
854 return false;
31a0531d 855
01b64152
AL
856 /* Check for enough free space, but only if we are actually going to
857 download */
18e20d63
AL
858 if (_config->FindB("APT::Get::Print-URIs") == false &&
859 _config->FindB("APT::Get::Download",true) == true)
01b64152
AL
860 {
861 struct statvfs Buf;
862 string OutputDir = _config->FindDir("Dir::Cache::Archives");
863 if (statvfs(OutputDir.c_str(),&Buf) != 0)
2a7e07c7 864 return _error->Errno("statvfs",_("Couldn't determine free space in %s"),
01b64152
AL
865 OutputDir.c_str());
866 if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
885d204b
OS
867 {
868 struct statfs Stat;
869 if (statfs(OutputDir.c_str(),&Stat) != 0 ||
870 unsigned(Stat.f_type) != RAMFS_MAGIC)
871 return _error->Error(_("You don't have enough free space in %s."),
872 OutputDir.c_str());
873 }
01b64152
AL
874 }
875
83d89a9f 876 // Fail safe check
0c95c765
AL
877 if (_config->FindI("quiet",0) >= 2 ||
878 _config->FindB("APT::Get::Assume-Yes",false) == true)
83d89a9f
AL
879 {
880 if (Fail == true && _config->FindB("APT::Get::Force-Yes",false) == false)
b2e465d6 881 return _error->Error(_("There are problems and -y was used without --force-yes"));
83d89a9f 882 }
83d89a9f 883
80fbda96 884 if (Essential == true && Safety == true)
6f86c974 885 {
d150b09d 886 if (_config->FindB("APT::Get::Trivial-Only",false) == true)
b2e465d6 887 return _error->Error(_("Trivial Only specified but this is not a trivial operation."));
d150b09d 888
b2e465d6
AL
889 const char *Prompt = _("Yes, do as I say!");
890 ioprintf(c2out,
080bf1be 891 _("You are about to do something potentially harmful.\n"
b2e465d6
AL
892 "To continue type in the phrase '%s'\n"
893 " ?] "),Prompt);
894 c2out << flush;
895 if (AnalPrompt(Prompt) == false)
6f86c974 896 {
b2e465d6 897 c2out << _("Abort.") << endl;
a6568219 898 exit(1);
6f86c974
AL
899 }
900 }
901 else
d150b09d 902 {
6f86c974 903 // Prompt to continue
38262e68 904 if (Ask == true || Fail == true)
6f86c974 905 {
d150b09d 906 if (_config->FindB("APT::Get::Trivial-Only",false) == true)
b2e465d6 907 return _error->Error(_("Trivial Only specified but this is not a trivial operation."));
d150b09d 908
0c95c765 909 if (_config->FindI("quiet",0) < 2 &&
6f86c974 910 _config->FindB("APT::Get::Assume-Yes",false) == false)
0c95c765 911 {
db0db9fe 912 c2out << _("Do you want to continue [Y/n]? ") << flush;
6f86c974 913
0c95c765
AL
914 if (YnPrompt() == false)
915 {
b2e465d6 916 c2out << _("Abort.") << endl;
0c95c765
AL
917 exit(1);
918 }
919 }
6f86c974
AL
920 }
921 }
922
36375005 923 // Just print out the uris an exit if the --print-uris flag was used
f7a08e33
AL
924 if (_config->FindB("APT::Get::Print-URIs") == true)
925 {
926 pkgAcquire::UriIterator I = Fetcher.UriBegin();
927 for (; I != Fetcher.UriEnd(); I++)
928 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
495e5cb2 929 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
f7a08e33
AL
930 return true;
931 }
b2e465d6 932
7db98ffc
MZ
933 if (!CheckAuth(Fetcher))
934 return false;
935
b2e465d6
AL
936 /* Unlock the dpkg lock if we are not going to be doing an install
937 after. */
938 if (_config->FindB("APT::Get::Download-Only",false) == true)
939 _system->UnLock();
83d89a9f 940
03e39e59 941 // Run it
281daf46 942 while (1)
30e1eab5 943 {
a3eaf954 944 bool Transient = false;
b2e465d6 945 if (_config->FindB("APT::Get::Download",true) == false)
a3eaf954 946 {
076d01b0 947 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I < Fetcher.ItemsEnd();)
a3eaf954
AL
948 {
949 if ((*I)->Local == true)
950 {
951 I++;
952 continue;
953 }
954
955 // Close the item and check if it was found in cache
956 (*I)->Finished();
957 if ((*I)->Complete == false)
958 Transient = true;
959
960 // Clear it out of the fetch list
961 delete *I;
962 I = Fetcher.ItemsBegin();
963 }
964 }
965
966 if (Fetcher.Run() == pkgAcquire::Failed)
967 return false;
30e1eab5 968
281daf46
AL
969 // Print out errors
970 bool Failed = false;
076d01b0 971 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
f01fe790 972 {
281daf46
AL
973 if ((*I)->Status == pkgAcquire::Item::StatDone &&
974 (*I)->Complete == true)
975 continue;
976
281daf46
AL
977 if ((*I)->Status == pkgAcquire::Item::StatIdle)
978 {
979 Transient = true;
980 // Failed = true;
981 continue;
982 }
a3eaf954 983
b2e465d6
AL
984 fprintf(stderr,_("Failed to fetch %s %s\n"),(*I)->DescURI().c_str(),
985 (*I)->ErrorText.c_str());
f01fe790 986 Failed = true;
f01fe790 987 }
5ec427c2 988
a3eaf954 989 /* If we are in no download mode and missing files and there were
5ec427c2
AL
990 'failures' then the user must specify -m. Furthermore, there
991 is no such thing as a transient error in no-download mode! */
a3eaf954 992 if (Transient == true &&
b2e465d6 993 _config->FindB("APT::Get::Download",true) == false)
5ec427c2
AL
994 {
995 Transient = false;
996 Failed = true;
997 }
f01fe790 998
281daf46
AL
999 if (_config->FindB("APT::Get::Download-Only",false) == true)
1000 {
1001 if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
b2e465d6
AL
1002 return _error->Error(_("Some files failed to download"));
1003 c1out << _("Download complete and in download only mode") << endl;
281daf46
AL
1004 return true;
1005 }
1006
8195ae46 1007 if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
f01fe790 1008 {
b2e465d6 1009 return _error->Error(_("Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?"));
f01fe790
AL
1010 }
1011
281daf46 1012 if (Transient == true && Failed == true)
b2e465d6 1013 return _error->Error(_("--fix-missing and media swapping is not currently supported"));
281daf46
AL
1014
1015 // Try to deal with missing package files
b2e465d6 1016 if (Failed == true && PM->FixMissing() == false)
281daf46 1017 {
b2e465d6 1018 cerr << _("Unable to correct missing packages.") << endl;
db0db9fe 1019 return _error->Error(_("Aborting install."));
281daf46 1020 }
afb1e2e3 1021
b2e465d6 1022 _system->UnLock();
2a7e07c7
MV
1023 int status_fd = _config->FindI("APT::Status-Fd",-1);
1024 pkgPackageManager::OrderResult Res = PM->DoInstall(status_fd);
281daf46
AL
1025 if (Res == pkgPackageManager::Failed || _error->PendingError() == true)
1026 return false;
1027 if (Res == pkgPackageManager::Completed)
1028 return true;
1029
1030 // Reload the fetcher object and loop again for media swapping
1031 Fetcher.Shutdown();
b2e465d6 1032 if (PM->GetArchives(&Fetcher,&List,&Recs) == false)
281daf46 1033 return false;
b2e465d6
AL
1034
1035 _system->Lock();
281daf46 1036 }
0a8e3465
AL
1037}
1038 /*}}}*/
c373c37a
AL
1039// TryToInstall - Try to install a single package /*{{{*/
1040// ---------------------------------------------------------------------
1041/* This used to be inlined in DoInstall, but with the advent of regex package
1042 name matching it was split out.. */
1043bool TryToInstall(pkgCache::PkgIterator Pkg,pkgDepCache &Cache,
1044 pkgProblemResolver &Fix,bool Remove,bool BrokenFix,
1045 unsigned int &ExpectedInst,bool AllowFail = true)
1046{
1047 /* This is a pure virtual package and there is a single available
1048 provides */
1049 if (Cache[Pkg].CandidateVer == 0 && Pkg->ProvidesList != 0 &&
1050 Pkg.ProvidesList()->NextProvides == 0)
1051 {
1052 pkgCache::PkgIterator Tmp = Pkg.ProvidesList().OwnerPkg();
b2e465d6
AL
1053 ioprintf(c1out,_("Note, selecting %s instead of %s\n"),
1054 Tmp.Name(),Pkg.Name());
c373c37a
AL
1055 Pkg = Tmp;
1056 }
1057
1058 // Handle the no-upgrade case
b2e465d6 1059 if (_config->FindB("APT::Get::upgrade",true) == false &&
c373c37a
AL
1060 Pkg->CurrentVer != 0)
1061 {
1062 if (AllowFail == true)
b2e465d6
AL
1063 ioprintf(c1out,_("Skipping %s, it is already installed and upgrade is not set.\n"),
1064 Pkg.Name());
c373c37a
AL
1065 return true;
1066 }
1067
1068 // Check if there is something at all to install
1069 pkgDepCache::StateCache &State = Cache[Pkg];
a146c927 1070 if (Remove == true && Pkg->CurrentVer == 0)
10bb1f5f 1071 {
d993b35d
AL
1072 Fix.Clear(Pkg);
1073 Fix.Protect(Pkg);
1074 Fix.Remove(Pkg);
1075
b2e465d6
AL
1076 /* We want to continue searching for regex hits, so we return false here
1077 otherwise this is not really an error. */
10bb1f5f 1078 if (AllowFail == false)
d993b35d
AL
1079 return false;
1080
1156d969 1081 ioprintf(c1out,_("Package %s is not installed, so not removed\n"),Pkg.Name());
b2e465d6 1082 return true;
10bb1f5f 1083 }
a146c927
AL
1084
1085 if (State.CandidateVer == 0 && Remove == false)
c373c37a
AL
1086 {
1087 if (AllowFail == false)
1088 return false;
1089
1090 if (Pkg->ProvidesList != 0)
1091 {
b2e465d6
AL
1092 ioprintf(c1out,_("Package %s is a virtual package provided by:\n"),
1093 Pkg.Name());
c373c37a
AL
1094
1095 pkgCache::PrvIterator I = Pkg.ProvidesList();
1096 for (; I.end() == false; I++)
1097 {
1098 pkgCache::PkgIterator Pkg = I.OwnerPkg();
1099
1100 if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer())
1101 {
1102 if (Cache[Pkg].Install() == true && Cache[Pkg].NewInstall() == false)
1103 c1out << " " << Pkg.Name() << " " << I.OwnerVer().VerStr() <<
b2e465d6 1104 _(" [Installed]") << endl;
c373c37a
AL
1105 else
1106 c1out << " " << Pkg.Name() << " " << I.OwnerVer().VerStr() << endl;
1107 }
1108 }
b2e465d6 1109 c1out << _("You should explicitly select one to install.") << endl;
c373c37a
AL
1110 }
1111 else
1112 {
b2e465d6 1113 ioprintf(c1out,
4c36e062
AL
1114 _("Package %s is not available, but is referred to by another package.\n"
1115 "This may mean that the package is missing, has been obsoleted, or\n"
1116 "is only available from another source\n"),Pkg.Name());
c373c37a
AL
1117
1118 string List;
ac625538 1119 string VersionsList;
c82ffeb6
AL
1120 SPtrArray<bool> Seen = new bool[Cache.Head().PackageCount];
1121 memset(Seen,0,Cache.Head().PackageCount*sizeof(*Seen));
c373c37a
AL
1122 pkgCache::DepIterator Dep = Pkg.RevDependsList();
1123 for (; Dep.end() == false; Dep++)
1124 {
1125 if (Dep->Type != pkgCache::Dep::Replaces)
1126 continue;
b2e465d6
AL
1127 if (Seen[Dep.ParentPkg()->ID] == true)
1128 continue;
1129 Seen[Dep.ParentPkg()->ID] = true;
c373c37a 1130 List += string(Dep.ParentPkg().Name()) + " ";
ac625538 1131 //VersionsList += string(Dep.ParentPkg().CurVersion) + "\n"; ???
c373c37a 1132 }
ac625538 1133 ShowList(c1out,_("However the following packages replace it:"),List,VersionsList);
c373c37a
AL
1134 }
1135
b2e465d6 1136 _error->Error(_("Package %s has no installation candidate"),Pkg.Name());
c373c37a
AL
1137 return false;
1138 }
61d6a8de
AL
1139
1140 Fix.Clear(Pkg);
70777d4b 1141 Fix.Protect(Pkg);
c373c37a
AL
1142 if (Remove == true)
1143 {
1144 Fix.Remove(Pkg);
1145 Cache.MarkDelete(Pkg,_config->FindB("APT::Get::Purge",false));
1146 return true;
1147 }
1148
1149 // Install it
1150 Cache.MarkInstall(Pkg,false);
1151 if (State.Install() == false)
1152 {
d0c59649
AL
1153 if (_config->FindB("APT::Get::ReInstall",false) == true)
1154 {
1155 if (Pkg->CurrentVer == 0 || Pkg.CurrentVer().Downloadable() == false)
677cbcbc 1156 ioprintf(c1out,_("Reinstallation of %s is not possible, it cannot be downloaded.\n"),
b2e465d6 1157 Pkg.Name());
d0c59649
AL
1158 else
1159 Cache.SetReInstall(Pkg,true);
1160 }
1161 else
1162 {
1163 if (AllowFail == true)
677cbcbc 1164 ioprintf(c1out,_("%s is already the newest version.\n"),
b2e465d6 1165 Pkg.Name());
d0c59649 1166 }
c373c37a
AL
1167 }
1168 else
1169 ExpectedInst++;
1170
60681f93
MV
1171 // Install it with autoinstalling enabled (if we not respect the minial
1172 // required deps or the policy)
1173 if ((State.InstBroken() == true || State.InstPolicyBroken() == true) && BrokenFix == false)
c373c37a 1174 Cache.MarkInstall(Pkg,true);
60681f93 1175
c373c37a
AL
1176 return true;
1177}
1178 /*}}}*/
b2e465d6
AL
1179// TryToChangeVer - Try to change a candidate version /*{{{*/
1180// ---------------------------------------------------------------------
1181/* */
1182bool TryToChangeVer(pkgCache::PkgIterator Pkg,pkgDepCache &Cache,
1183 const char *VerTag,bool IsRel)
1184{
d993b35d
AL
1185 pkgVersionMatch Match(VerTag,(IsRel == true?pkgVersionMatch::Release :
1186 pkgVersionMatch::Version));
b2e465d6
AL
1187
1188 pkgCache::VerIterator Ver = Match.Find(Pkg);
1189
1190 if (Ver.end() == true)
1191 {
1192 if (IsRel == true)
1193 return _error->Error(_("Release '%s' for '%s' was not found"),
1194 VerTag,Pkg.Name());
1195 return _error->Error(_("Version '%s' for '%s' was not found"),
1196 VerTag,Pkg.Name());
1197 }
1198
1199 if (strcmp(VerTag,Ver.VerStr()) != 0)
1200 {
1201 ioprintf(c1out,_("Selected version %s (%s) for %s\n"),
1202 Ver.VerStr(),Ver.RelStr().c_str(),Pkg.Name());
1203 }
1204
1205 Cache.SetCandidateVersion(Ver);
1206 return true;
1207}
1208 /*}}}*/
1209// FindSrc - Find a source record /*{{{*/
1210// ---------------------------------------------------------------------
1211/* */
1212pkgSrcRecords::Parser *FindSrc(const char *Name,pkgRecords &Recs,
1213 pkgSrcRecords &SrcRecs,string &Src,
1214 pkgDepCache &Cache)
1215{
1216 // We want to pull the version off the package specification..
1217 string VerTag;
1218 string TmpSrc = Name;
1219 string::size_type Slash = TmpSrc.rfind('=');
aca056a9 1220
ce6162be 1221 // honor default release
aca056a9 1222 string DefRel = _config->Find("APT::Default-Release");
aca056a9 1223 pkgCache::PkgIterator Pkg = Cache.FindPkg(TmpSrc);
aca056a9 1224
b2e465d6
AL
1225 if (Slash != string::npos)
1226 {
1227 VerTag = string(TmpSrc.begin() + Slash + 1,TmpSrc.end());
1228 TmpSrc = string(TmpSrc.begin(),TmpSrc.begin() + Slash);
aca056a9 1229 }
d5f38102 1230 else if(!Pkg.end() && DefRel.empty() == false)
aca056a9
MV
1231 {
1232 // we have a default release, try to locate the pkg. we do it like
1233 // this because GetCandidateVer() will not "downgrade", that means
1234 // "apt-get source -t stable apt" won't work on a unstable system
1235 for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() == false;
1236 Ver++)
1237 {
1238 for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false;
1239 VF++)
1240 {
1241 /* If this is the status file, and the current version is not the
1242 version in the status file (ie it is not installed, or somesuch)
1243 then it is not a candidate for installation, ever. This weeds
1244 out bogus entries that may be due to config-file states, or
1245 other. */
1246 if ((VF.File()->Flags & pkgCache::Flag::NotSource) ==
1247 pkgCache::Flag::NotSource && Pkg.CurrentVer() != Ver)
1248 continue;
1249
1250 //std::cout << VF.File().Archive() << std::endl;
d87116ef 1251 if(VF.File().Archive() && (VF.File().Archive() == DefRel))
aca056a9
MV
1252 {
1253 VerTag = Ver.VerStr();
1254 break;
1255 }
1256 }
026f60e2 1257 }
b2e465d6 1258 }
aca056a9 1259
b2e465d6
AL
1260 /* Lookup the version of the package we would install if we were to
1261 install a version and determine the source package name, then look
aca056a9
MV
1262 in the archive for a source package of the same name. */
1263 if (_config->FindB("APT::Get::Only-Source") == false)
b2e465d6 1264 {
b2e465d6
AL
1265 if (Pkg.end() == false)
1266 {
ce6162be 1267 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
b2e465d6
AL
1268 if (Ver.end() == false)
1269 {
1270 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1271 Src = Parse.SourcePkg();
1272 }
1273 }
1274 }
1275
1276 // No source package name..
1277 if (Src.empty() == true)
1278 Src = TmpSrc;
1279
1280 // The best hit
1281 pkgSrcRecords::Parser *Last = 0;
1282 unsigned long Offset = 0;
1283 string Version;
1284 bool IsMatch = false;
1285
1286 // If we are matching by version then we need exact matches to be happy
1287 if (VerTag.empty() == false)
1288 IsMatch = true;
1289
1290 /* Iterate over all of the hits, which includes the resulting
1291 binary packages in the search */
1292 pkgSrcRecords::Parser *Parse;
1293 SrcRecs.Restart();
1294 while ((Parse = SrcRecs.Find(Src.c_str(),false)) != 0)
1295 {
1296 string Ver = Parse->Version();
1297
1298 // Skip name mismatches
1299 if (IsMatch == true && Parse->Package() != Src)
1300 continue;
1301
1302 if (VerTag.empty() == false)
1303 {
1304 /* Don't want to fall through because we are doing exact version
1305 matching. */
1306 if (Cache.VS().CmpVersion(VerTag,Ver) != 0)
1307 continue;
1308
1309 Last = Parse;
1310 Offset = Parse->Offset();
1311 break;
1312 }
1313
1314 // Newer version or an exact match
1315 if (Last == 0 || Cache.VS().CmpVersion(Version,Ver) < 0 ||
1316 (Parse->Package() == Src && IsMatch == false))
1317 {
1318 IsMatch = Parse->Package() == Src;
1319 Last = Parse;
1320 Offset = Parse->Offset();
1321 Version = Ver;
1322 }
1323 }
1324
ce6162be 1325 if (Last == 0 || Last->Jump(Offset) == false)
b2e465d6
AL
1326 return 0;
1327
1328 return Last;
1329}
1330 /*}}}*/
0a8e3465
AL
1331
1332// DoUpdate - Update the package lists /*{{{*/
1333// ---------------------------------------------------------------------
1334/* */
b2e465d6 1335bool DoUpdate(CommandLine &CmdL)
0a8e3465 1336{
b2e465d6
AL
1337 if (CmdL.FileSize() != 1)
1338 return _error->Error(_("The update command takes no arguments"));
1339
0919e3f9
AL
1340 // Get the source list
1341 pkgSourceList List;
1342 if (List.ReadMainList() == false)
1343 return false;
1344
d38b7b3d 1345 // Lock the list directory
36375005 1346 FileFd Lock;
d38b7b3d
AL
1347 if (_config->FindB("Debug::NoLocking",false) == false)
1348 {
36375005 1349 Lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
d38b7b3d 1350 if (_error->PendingError() == true)
b2e465d6 1351 return _error->Error(_("Unable to lock the list directory"));
d38b7b3d
AL
1352 }
1353
89b70b5a 1354 // Create the progress
0919e3f9 1355 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
89b70b5a 1356
f0863b21
AL
1357 // Just print out the uris an exit if the --print-uris flag was used
1358 if (_config->FindB("APT::Get::Print-URIs") == true)
1359 {
89b70b5a
MV
1360 // get a fetcher
1361 pkgAcquire Fetcher(&Stat);
1362
7db98ffc
MZ
1363 // Populate it with the source selection and get all Indexes
1364 // (GetAll=true)
1365 if (List.GetIndexes(&Fetcher,true) == false)
1366 return false;
1367
f0863b21
AL
1368 pkgAcquire::UriIterator I = Fetcher.UriBegin();
1369 for (; I != Fetcher.UriEnd(); I++)
1370 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
495e5cb2 1371 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
f0863b21
AL
1372 return true;
1373 }
7db98ffc 1374
89b70b5a 1375 // do the work
0919e3f9 1376 CacheFile Cache;
760d4968 1377 bool res = ListUpdate(Stat, List);
89b70b5a
MV
1378
1379 // Rebuild the cache.
0077d829 1380 if (Cache.BuildCaches() == false)
0919e3f9
AL
1381 return false;
1382
1383 return true;
afb1e2e3
MV
1384}
1385 /*}}}*/
1386// DoAutomaticRemove - Remove all automatic unused packages /*{{{*/
1387// ---------------------------------------------------------------------
1388/* Remove unused automatic packages */
1389bool DoAutomaticRemove(CacheFile &Cache)
1390{
9d2938d4 1391 bool Debug = _config->FindI("Debug::pkgAutoRemove",false);
b255ff1a 1392 bool doAutoRemove = _config->FindB("APT::Get::AutomaticRemove", false);
7898bd97 1393 bool hideAutoRemove = _config->FindB("APT::Get::HideAutoRemove");
9d2938d4 1394 pkgDepCache::ActionGroup group(*Cache);
afb1e2e3 1395
9d2938d4 1396 if(Debug)
120365ce 1397 std::cout << "DoAutomaticRemove()" << std::endl;
afb1e2e3 1398
3d0de656
MV
1399 if (_config->FindB("APT::Get::Remove",true) == false &&
1400 doAutoRemove == true)
afb1e2e3 1401 {
3d0de656
MV
1402 c1out << _("We are not supposed to delete stuff, can't start "
1403 "AutoRemover") << std::endl;
1404 doAutoRemove = false;
1405 }
74a05226 1406
9d2938d4
MV
1407 string autoremovelist, autoremoveversions;
1408 // look over the cache to see what can be removed
1409 for (pkgCache::PkgIterator Pkg = Cache->PkgBegin(); ! Pkg.end(); ++Pkg)
afb1e2e3 1410 {
9d2938d4
MV
1411 if (Cache[Pkg].Garbage)
1412 {
1413 if(Pkg.CurrentVer() != 0 || Cache[Pkg].Install())
1414 if(Debug)
1415 std::cout << "We could delete %s" << Pkg.Name() << std::endl;
fd59a713
MV
1416
1417 // only show stuff in the list that is not yet marked for removal
1418 if(Cache[Pkg].Delete() == false)
1419 {
1420 autoremovelist += string(Pkg.Name()) + " ";
1421 autoremoveversions += string(Cache[Pkg].CandVersion) + "\n";
1422 }
3d0de656 1423 if (doAutoRemove)
9d2938d4
MV
1424 {
1425 if(Pkg.CurrentVer() != 0 &&
1426 Pkg->CurrentState != pkgCache::State::ConfigFiles)
74a05226 1427 Cache->MarkDelete(Pkg, _config->FindB("APT::Get::Purge", false));
9d2938d4 1428 else
74a05226 1429 Cache->MarkKeep(Pkg, false, false);
9d2938d4
MV
1430 }
1431 }
afb1e2e3 1432 }
7898bd97
MV
1433 if (!hideAutoRemove)
1434 ShowList(c1out, _("The following packages were automatically installed and are no longer required:"), autoremovelist, autoremoveversions);
1435 if (!doAutoRemove && !hideAutoRemove && autoremovelist.size() > 0)
9d2938d4 1436 c1out << _("Use 'apt-get autoremove' to remove them.") << std::endl;
afb1e2e3
MV
1437
1438 // Now see if we destroyed anything
1439 if (Cache->BrokenCount() != 0)
1440 {
1441 c1out << _("Hmm, seems like the AutoRemover destroyed something which really\n"
1442 "shouldn't happen. Please file a bug report against apt.") << endl;
1443 c1out << endl;
1444 c1out << _("The following information may help to resolve the situation:") << endl;
1445 c1out << endl;
1446 ShowBroken(c1out,Cache,false);
1447
1448 return _error->Error(_("Internal Error, AutoRemover broke stuff"));
1449 }
1450 return true;
db1e7193 1451}
74a05226 1452
db1e7193
MV
1453// DoUpgrade - Upgrade all packages /*{{{*/
1454// ---------------------------------------------------------------------
1455/* Upgrade all packages without installing new packages or erasing old
1456 packages */
1457bool DoUpgrade(CommandLine &CmdL)
1458{
1459 CacheFile Cache;
1460 if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
1461 return false;
1462
1463 // Do the upgrade
1464 if (pkgAllUpgrade(Cache) == false)
1465 {
1466 ShowBroken(c1out,Cache,false);
1467 return _error->Error(_("Internal error, AllUpgrade broke stuff"));
1468 }
1469
1470 return InstallPackages(Cache,true);
afb1e2e3
MV
1471}
1472 /*}}}*/
c158ff49
MV
1473// DoInstallTask - Install task from the command line /*{{{*/
1474// ---------------------------------------------------------------------
1475/* Install named task */
39cc1bbd
MV
1476bool TryInstallTask(pkgDepCache &Cache, pkgProblemResolver &Fix,
1477 bool BrokenFix,
1478 unsigned int& ExpectedInst,
394eadc8
MV
1479 const char *taskname,
1480 bool Remove)
c158ff49
MV
1481{
1482 const char *start, *end;
1483 pkgCache::PkgIterator Pkg;
39cc1bbd
MV
1484 char buf[64*1024];
1485 regex_t Pattern;
c158ff49 1486
39cc1bbd 1487 // get the records
c158ff49 1488 pkgRecords Recs(Cache);
c158ff49 1489
39cc1bbd
MV
1490 // build regexp for the task
1491 char S[300];
f03dd1e0
MV
1492 snprintf(S, sizeof(S), "^Task:.*[, ]%s([, ]|$)", taskname);
1493 if(regcomp(&Pattern,S, REG_EXTENDED | REG_NOSUB | REG_NEWLINE) != 0)
1494 return _error->Error("Failed to compile task regexp");
39cc1bbd
MV
1495
1496 bool found = false;
1497 bool res = true;
85bd111a
MV
1498
1499 // two runs, first ignore dependencies, second install any missing
1500 for(int IgnoreBroken=1; IgnoreBroken >= 0; IgnoreBroken--)
c158ff49 1501 {
85bd111a
MV
1502 for (Pkg = Cache.PkgBegin(); Pkg.end() == false; Pkg++)
1503 {
1504 pkgCache::VerIterator ver = Cache[Pkg].CandidateVerIter(Cache);
1505 if(ver.end())
1506 continue;
1507 pkgRecords::Parser &parser = Recs.Lookup(ver.FileList());
1508 parser.GetRec(start,end);
1509 strncpy(buf, start, end-start);
1510 buf[end-start] = 0x0;
1511 if (regexec(&Pattern,buf,0,0,0) != 0)
1512 continue;
1513 res &= TryToInstall(Pkg,Cache,Fix,Remove,IgnoreBroken,ExpectedInst);
1514 found = true;
1515 }
c158ff49 1516 }
c158ff49 1517
9dbe6ae4
MV
1518 // now let the problem resolver deal with any issues
1519 Fix.Resolve(true);
1520
39cc1bbd
MV
1521 if(!found)
1522 _error->Error(_("Couldn't find task %s"),taskname);
1523
1524 regfree(&Pattern);
1525 return res;
c158ff49
MV
1526}
1527
0a8e3465
AL
1528// DoInstall - Install packages from the command line /*{{{*/
1529// ---------------------------------------------------------------------
1530/* Install named packages */
1531bool DoInstall(CommandLine &CmdL)
1532{
1533 CacheFile Cache;
c37b9502
AL
1534 if (Cache.OpenForInstall() == false ||
1535 Cache.CheckDeps(CmdL.FileSize() != 1) == false)
0a8e3465
AL
1536 return false;
1537
7c57fe64
AL
1538 // Enter the special broken fixing mode if the user specified arguments
1539 bool BrokenFix = false;
1540 if (Cache->BrokenCount() != 0)
1541 BrokenFix = true;
1542
e4b74e4b 1543 unsigned int AutoMarkChanged = 0;
a6568219
AL
1544 unsigned int ExpectedInst = 0;
1545 unsigned int Packages = 0;
0a8e3465
AL
1546 pkgProblemResolver Fix(Cache);
1547
303a1703
AL
1548 bool DefRemove = false;
1549 if (strcasecmp(CmdL.FileList[0],"remove") == 0)
1550 DefRemove = true;
e47c7d16
MV
1551 else if (strcasecmp(CmdL.FileList[0], "purge") == 0)
1552 {
1553 _config->Set("APT::Get::Purge", true);
1554 DefRemove = true;
1555 }
74a05226 1556 else if (strcasecmp(CmdL.FileList[0], "autoremove") == 0)
0a8e3465 1557 {
54668e4e
MV
1558 _config->Set("APT::Get::AutomaticRemove", "true");
1559 DefRemove = true;
1560 }
54668e4e 1561 // new scope for the ActionGroup
0a8e3465 1562 {
54668e4e
MV
1563 pkgDepCache::ActionGroup group(Cache);
1564 for (const char **I = CmdL.FileList + 1; *I != 0; I++)
0a8e3465 1565 {
54668e4e
MV
1566 // Duplicate the string
1567 unsigned int Length = strlen(*I);
1568 char S[300];
1569 if (Length >= sizeof(S))
fc4b5c9f 1570 continue;
54668e4e
MV
1571 strcpy(S,*I);
1572
1573 // See if we are removing and special indicators..
1574 bool Remove = DefRemove;
1575 char *VerTag = 0;
1576 bool VerIsRel = false;
5a68ea79
MV
1577
1578 // this is a task!
1579 if (Length >= 1 && S[Length - 1] == '^')
1580 {
1581 S[--Length] = 0;
1582 // tasks must always be confirmed
1583 ExpectedInst += 1000;
1584 // see if we can install it
394eadc8 1585 TryInstallTask(Cache, Fix, BrokenFix, ExpectedInst, S, Remove);
5a68ea79
MV
1586 continue;
1587 }
1588
54668e4e 1589 while (Cache->FindPkg(S).end() == true)
b2e465d6 1590 {
54668e4e
MV
1591 // Handle an optional end tag indicating what to do
1592 if (Length >= 1 && S[Length - 1] == '-')
1593 {
1594 Remove = true;
1595 S[--Length] = 0;
1596 continue;
1597 }
b2e465d6 1598
54668e4e
MV
1599 if (Length >= 1 && S[Length - 1] == '+')
1600 {
1601 Remove = false;
1602 S[--Length] = 0;
1603 continue;
1604 }
b2e465d6 1605
54668e4e
MV
1606 char *Slash = strchr(S,'=');
1607 if (Slash != 0)
1608 {
1609 VerIsRel = false;
1610 *Slash = 0;
1611 VerTag = Slash + 1;
1612 }
c373c37a 1613
54668e4e
MV
1614 Slash = strchr(S,'/');
1615 if (Slash != 0)
1616 {
1617 VerIsRel = true;
1618 *Slash = 0;
1619 VerTag = Slash + 1;
1620 }
c373c37a 1621
54668e4e 1622 break;
b2e465d6 1623 }
54668e4e
MV
1624
1625 // Locate the package
1626 pkgCache::PkgIterator Pkg = Cache->FindPkg(S);
1627 Packages++;
1628 if (Pkg.end() == true)
303a1703 1629 {
54668e4e
MV
1630 // Check if the name is a regex
1631 const char *I;
1632 for (I = S; *I != 0; I++)
1633 if (*I == '?' || *I == '*' || *I == '|' ||
1634 *I == '[' || *I == '^' || *I == '$')
1635 break;
1636 if (*I == 0)
1637 return _error->Error(_("Couldn't find package %s"),S);
1638
1639 // Regexs must always be confirmed
1640 ExpectedInst += 1000;
1641
1642 // Compile the regex pattern
1643 regex_t Pattern;
1644 int Res;
1645 if ((Res = regcomp(&Pattern,S,REG_EXTENDED | REG_ICASE |
1646 REG_NOSUB)) != 0)
1647 {
1648 char Error[300];
1649 regerror(Res,&Pattern,Error,sizeof(Error));
1650 return _error->Error(_("Regex compilation error - %s"),Error);
1651 }
1652
1653 // Run over the matches
1654 bool Hit = false;
1655 for (Pkg = Cache->PkgBegin(); Pkg.end() == false; Pkg++)
1656 {
1657 if (regexec(&Pattern,Pkg.Name(),0,0,0) != 0)
1658 continue;
07801a6d 1659
54668e4e
MV
1660 ioprintf(c1out,_("Note, selecting %s for regex '%s'\n"),
1661 Pkg.Name(),S);
07801a6d 1662
54668e4e
MV
1663 if (VerTag != 0)
1664 if (TryToChangeVer(Pkg,Cache,VerTag,VerIsRel) == false)
1665 return false;
185091b7 1666
54668e4e
MV
1667 Hit |= TryToInstall(Pkg,Cache,Fix,Remove,BrokenFix,
1668 ExpectedInst,false);
1669 }
1670 regfree(&Pattern);
1671
1672 if (Hit == false)
1673 return _error->Error(_("Couldn't find package %s"),S);
1674 }
1675 else
1676 {
b2e465d6
AL
1677 if (VerTag != 0)
1678 if (TryToChangeVer(Pkg,Cache,VerTag,VerIsRel) == false)
1679 return false;
54668e4e 1680 if (TryToInstall(Pkg,Cache,Fix,Remove,BrokenFix,ExpectedInst) == false)
b2e465d6 1681 return false;
e4b74e4b
MV
1682
1683 // see if we need to fix the auto-mark flag
1684 // e.g. apt-get install foo
1685 // where foo is marked automatic
fd59a713
MV
1686 if(!Remove &&
1687 Cache[Pkg].Install() == false &&
085bedac
MV
1688 (Cache[Pkg].Flags & pkgCache::Flag::Auto) &&
1689 _config->FindB("APT::Get::ReInstall",false) == false)
e4b74e4b 1690 {
da543ed8 1691 ioprintf(c1out,_("%s set to manually installed.\n"),
e4b74e4b
MV
1692 Pkg.Name());
1693 Cache->MarkAuto(Pkg,false);
1694 AutoMarkChanged++;
1695 }
54668e4e
MV
1696 }
1697 }
0a8e3465 1698
54668e4e
MV
1699 /* If we are in the Broken fixing mode we do not attempt to fix the
1700 problems. This is if the user invoked install without -f and gave
1701 packages */
1702 if (BrokenFix == true && Cache->BrokenCount() != 0)
1703 {
1704 c1out << _("You might want to run `apt-get -f install' to correct these:") << endl;
1705 ShowBroken(c1out,Cache,false);
7c57fe64 1706
54668e4e
MV
1707 return _error->Error(_("Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution)."));
1708 }
7c57fe64 1709
54668e4e
MV
1710 // Call the scored problem resolver
1711 Fix.InstallProtect();
1712 if (Fix.Resolve(true) == false)
1713 _error->Discard();
0a8e3465 1714
54668e4e
MV
1715 // Now we check the state of the packages,
1716 if (Cache->BrokenCount() != 0)
303a1703 1717 {
b2e465d6 1718 c1out <<
54668e4e
MV
1719 _("Some packages could not be installed. This may mean that you have\n"
1720 "requested an impossible situation or if you are using the unstable\n"
1721 "distribution that some required packages have not yet been created\n"
1722 "or been moved out of Incoming.") << endl;
1723 if (Packages == 1)
1724 {
1725 c1out << endl;
1726 c1out <<
1727 _("Since you only requested a single operation it is extremely likely that\n"
1728 "the package is simply not installable and a bug report against\n"
1729 "that package should be filed.") << endl;
1730 }
303a1703 1731
54668e4e
MV
1732 c1out << _("The following information may help to resolve the situation:") << endl;
1733 c1out << endl;
1734 ShowBroken(c1out,Cache,false);
1735 return _error->Error(_("Broken packages"));
1736 }
120365ce 1737 }
5a68ea79
MV
1738 if (!DoAutomaticRemove(Cache))
1739 return false;
afb1e2e3 1740
0a8e3465
AL
1741 /* Print out a list of packages that are going to be installed extra
1742 to what the user asked */
1743 if (Cache->InstCount() != ExpectedInst)
1744 {
1745 string List;
ac625538 1746 string VersionsList;
1089ca89 1747 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
0a8e3465 1748 {
1089ca89 1749 pkgCache::PkgIterator I(Cache,Cache.List[J]);
0a8e3465
AL
1750 if ((*Cache)[I].Install() == false)
1751 continue;
1752
1753 const char **J;
1754 for (J = CmdL.FileList + 1; *J != 0; J++)
1755 if (strcmp(*J,I.Name()) == 0)
1756 break;
1757
ac625538 1758 if (*J == 0) {
0a8e3465 1759 List += string(I.Name()) + " ";
80fa0d8a
MV
1760 VersionsList += string(Cache[I].CandVersion) + "\n";
1761 }
0a8e3465
AL
1762 }
1763
ac625538 1764 ShowList(c1out,_("The following extra packages will be installed:"),List,VersionsList);
0a8e3465
AL
1765 }
1766
a7e41689
AL
1767 /* Print out a list of suggested and recommended packages */
1768 {
1769 string SuggestsList, RecommendsList, List;
72122b62 1770 string SuggestsVersions, RecommendsVersions;
a7e41689
AL
1771 for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
1772 {
29f37db8 1773 pkgCache::PkgIterator Pkg(Cache,Cache.List[J]);
a7e41689
AL
1774
1775 /* Just look at the ones we want to install */
29f37db8 1776 if ((*Cache)[Pkg].Install() == false)
a7e41689
AL
1777 continue;
1778
29f37db8
MV
1779 // get the recommends/suggests for the candidate ver
1780 pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
1781 for (pkgCache::DepIterator D = CV.DependsList(); D.end() == false; )
1782 {
1783 pkgCache::DepIterator Start;
1784 pkgCache::DepIterator End;
1785 D.GlobOr(Start,End); // advances D
1786
cd33a786
MV
1787 // FIXME: we really should display a or-group as a or-group to the user
1788 // the problem is that ShowList is incapable of doing this
29f37db8
MV
1789 string RecommendsOrList,RecommendsOrVersions;
1790 string SuggestsOrList,SuggestsOrVersions;
1791 bool foundInstalledInOrGroup = false;
1792 for(;;)
1793 {
1794 /* Skip if package is installed already, or is about to be */
1795 string target = string(Start.TargetPkg().Name()) + " ";
1796
1797 if ((*Start.TargetPkg()).SelectedState == pkgCache::State::Install
1798 || Cache[Start.TargetPkg()].Install())
1799 {
1800 foundInstalledInOrGroup=true;
1801 break;
1802 }
1803
1804 /* Skip if we already saw it */
1805 if (int(SuggestsList.find(target)) != -1 || int(RecommendsList.find(target)) != -1)
1806 {
1807 foundInstalledInOrGroup=true;
1808 break;
1809 }
1810
1811 // this is a dep on a virtual pkg, check if any package that provides it
1812 // should be installed
1813 if(Start.TargetPkg().ProvidesList() != 0)
1814 {
1815 pkgCache::PrvIterator I = Start.TargetPkg().ProvidesList();
1816 for (; I.end() == false; I++)
1817 {
1818 pkgCache::PkgIterator Pkg = I.OwnerPkg();
1819 if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer() &&
1820 Pkg.CurrentVer() != 0)
1821 foundInstalledInOrGroup=true;
1822 }
1823 }
1824
1825 if (Start->Type == pkgCache::Dep::Suggests)
1826 {
1827 SuggestsOrList += target;
1828 SuggestsOrVersions += string(Cache[Start.TargetPkg()].CandVersion) + "\n";
1829 }
1830
1831 if (Start->Type == pkgCache::Dep::Recommends)
1832 {
1833 RecommendsOrList += target;
1834 RecommendsOrVersions += string(Cache[Start.TargetPkg()].CandVersion) + "\n";
1835 }
1836
1837 if (Start >= End)
1838 break;
1839 Start++;
1840 }
1841
1842 if(foundInstalledInOrGroup == false)
1843 {
1844 RecommendsList += RecommendsOrList;
1845 RecommendsVersions += RecommendsOrVersions;
1846 SuggestsList += SuggestsOrList;
1847 SuggestsVersions += SuggestsOrVersions;
1848 }
1849
1850 }
a7e41689 1851 }
29f37db8 1852
72122b62
AL
1853 ShowList(c1out,_("Suggested packages:"),SuggestsList,SuggestsVersions);
1854 ShowList(c1out,_("Recommended packages:"),RecommendsList,RecommendsVersions);
a7e41689
AL
1855
1856 }
1857
e4b74e4b
MV
1858 // if nothing changed in the cache, but only the automark information
1859 // we write the StateFile here, otherwise it will be written in
1860 // cache.commit()
1861 if (AutoMarkChanged > 0 &&
1862 Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
1863 Cache->BadCount() == 0)
1864 Cache->writeStateFile(NULL);
1865
03e39e59 1866 // See if we need to prompt
2c3bc8bb 1867 if (Cache->InstCount() == ExpectedInst && Cache->DelCount() == 0)
2c3bc8bb 1868 return InstallPackages(Cache,false,false);
13e8426f 1869
03e39e59 1870 return InstallPackages(Cache,false);
0a8e3465
AL
1871}
1872 /*}}}*/
1873// DoDistUpgrade - Automatic smart upgrader /*{{{*/
1874// ---------------------------------------------------------------------
1875/* Intelligent upgrader that will install and remove packages at will */
1876bool DoDistUpgrade(CommandLine &CmdL)
1877{
1878 CacheFile Cache;
c37b9502 1879 if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
0a8e3465
AL
1880 return false;
1881
db0db9fe 1882 c0out << _("Calculating upgrade... ") << flush;
0a8e3465
AL
1883 if (pkgDistUpgrade(*Cache) == false)
1884 {
b2e465d6 1885 c0out << _("Failed") << endl;
421c8d10 1886 ShowBroken(c1out,Cache,false);
0a8e3465
AL
1887 return false;
1888 }
1889
b2e465d6 1890 c0out << _("Done") << endl;
0a8e3465
AL
1891
1892 return InstallPackages(Cache,true);
1893}
1894 /*}}}*/
1895// DoDSelectUpgrade - Do an upgrade by following dselects selections /*{{{*/
1896// ---------------------------------------------------------------------
1897/* Follows dselect's selections */
1898bool DoDSelectUpgrade(CommandLine &CmdL)
1899{
1900 CacheFile Cache;
c37b9502 1901 if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
0a8e3465
AL
1902 return false;
1903
a4decc40
MV
1904 pkgDepCache::ActionGroup group(Cache);
1905
0a8e3465
AL
1906 // Install everything with the install flag set
1907 pkgCache::PkgIterator I = Cache->PkgBegin();
1908 for (;I.end() != true; I++)
1909 {
1910 /* Install the package only if it is a new install, the autoupgrader
1911 will deal with the rest */
1912 if (I->SelectedState == pkgCache::State::Install)
1913 Cache->MarkInstall(I,false);
1914 }
1915
1916 /* Now install their deps too, if we do this above then order of
1917 the status file is significant for | groups */
1918 for (I = Cache->PkgBegin();I.end() != true; I++)
1919 {
1920 /* Install the package only if it is a new install, the autoupgrader
1921 will deal with the rest */
1922 if (I->SelectedState == pkgCache::State::Install)
2f45c76a 1923 Cache->MarkInstall(I,true);
0a8e3465
AL
1924 }
1925
1926 // Apply erasures now, they override everything else.
1927 for (I = Cache->PkgBegin();I.end() != true; I++)
1928 {
1929 // Remove packages
1930 if (I->SelectedState == pkgCache::State::DeInstall ||
1931 I->SelectedState == pkgCache::State::Purge)
d556d1a1 1932 Cache->MarkDelete(I,I->SelectedState == pkgCache::State::Purge);
0a8e3465
AL
1933 }
1934
2f45c76a
AL
1935 /* Resolve any problems that dselect created, allupgrade cannot handle
1936 such things. We do so quite agressively too.. */
1937 if (Cache->BrokenCount() != 0)
1938 {
1939 pkgProblemResolver Fix(Cache);
1940
1941 // Hold back held packages.
b2e465d6 1942 if (_config->FindB("APT::Ignore-Hold",false) == false)
2f45c76a
AL
1943 {
1944 for (pkgCache::PkgIterator I = Cache->PkgBegin(); I.end() == false; I++)
1945 {
1946 if (I->SelectedState == pkgCache::State::Hold)
1947 {
1948 Fix.Protect(I);
1949 Cache->MarkKeep(I);
1950 }
1951 }
1952 }
1953
1954 if (Fix.Resolve() == false)
1955 {
421c8d10 1956 ShowBroken(c1out,Cache,false);
2a7e07c7 1957 return _error->Error(_("Internal error, problem resolver broke stuff"));
2f45c76a
AL
1958 }
1959 }
1960
1961 // Now upgrade everything
0a8e3465
AL
1962 if (pkgAllUpgrade(Cache) == false)
1963 {
421c8d10 1964 ShowBroken(c1out,Cache,false);
2a7e07c7 1965 return _error->Error(_("Internal error, problem resolver broke stuff"));
0a8e3465
AL
1966 }
1967
1968 return InstallPackages(Cache,false);
1969}
1970 /*}}}*/
1971// DoClean - Remove download archives /*{{{*/
1972// ---------------------------------------------------------------------
1973/* */
1974bool DoClean(CommandLine &CmdL)
1975{
8b067c22
AL
1976 if (_config->FindB("APT::Get::Simulate") == true)
1977 {
1978 cout << "Del " << _config->FindDir("Dir::Cache::archives") << "* " <<
1979 _config->FindDir("Dir::Cache::archives") << "partial/*" << endl;
1980 return true;
1981 }
1982
1b6d659c
AL
1983 // Lock the archive directory
1984 FileFd Lock;
1985 if (_config->FindB("Debug::NoLocking",false) == false)
1986 {
1987 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
1988 if (_error->PendingError() == true)
b2e465d6 1989 return _error->Error(_("Unable to lock the download directory"));
1b6d659c
AL
1990 }
1991
7a1b1f8b
AL
1992 pkgAcquire Fetcher;
1993 Fetcher.Clean(_config->FindDir("Dir::Cache::archives"));
1994 Fetcher.Clean(_config->FindDir("Dir::Cache::archives") + "partial/");
0a8e3465
AL
1995 return true;
1996}
1997 /*}}}*/
1bc849af
AL
1998// DoAutoClean - Smartly remove downloaded archives /*{{{*/
1999// ---------------------------------------------------------------------
2000/* This is similar to clean but it only purges things that cannot be
2001 downloaded, that is old versions of cached packages. */
65a1e968
AL
2002class LogCleaner : public pkgArchiveCleaner
2003{
2004 protected:
2005 virtual void Erase(const char *File,string Pkg,string Ver,struct stat &St)
2006 {
4cc8bab0 2007 c1out << "Del " << Pkg << " " << Ver << " [" << SizeToStr(St.st_size) << "B]" << endl;
c1e78ee5
AL
2008
2009 if (_config->FindB("APT::Get::Simulate") == false)
2010 unlink(File);
65a1e968
AL
2011 };
2012};
2013
1bc849af
AL
2014bool DoAutoClean(CommandLine &CmdL)
2015{
1b6d659c
AL
2016 // Lock the archive directory
2017 FileFd Lock;
2018 if (_config->FindB("Debug::NoLocking",false) == false)
2019 {
2020 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
2021 if (_error->PendingError() == true)
b2e465d6 2022 return _error->Error(_("Unable to lock the download directory"));
1b6d659c
AL
2023 }
2024
1bc849af 2025 CacheFile Cache;
2d11135a 2026 if (Cache.Open() == false)
1bc849af
AL
2027 return false;
2028
65a1e968 2029 LogCleaner Cleaner;
1bc849af
AL
2030
2031 return Cleaner.Go(_config->FindDir("Dir::Cache::archives"),*Cache) &&
2032 Cleaner.Go(_config->FindDir("Dir::Cache::archives") + "partial/",*Cache);
2033}
2034 /*}}}*/
0a8e3465
AL
2035// DoCheck - Perform the check operation /*{{{*/
2036// ---------------------------------------------------------------------
2037/* Opening automatically checks the system, this command is mostly used
2038 for debugging */
2039bool DoCheck(CommandLine &CmdL)
2040{
2041 CacheFile Cache;
2042 Cache.Open();
2d11135a 2043 Cache.CheckDeps();
0a8e3465
AL
2044
2045 return true;
2046}
2047 /*}}}*/
36375005
AL
2048// DoSource - Fetch a source archive /*{{{*/
2049// ---------------------------------------------------------------------
2d11135a 2050/* Fetch souce packages */
fb0ee66e
AL
2051struct DscFile
2052{
2053 string Package;
2054 string Version;
2055 string Dsc;
2056};
2057
36375005
AL
2058bool DoSource(CommandLine &CmdL)
2059{
2060 CacheFile Cache;
2d11135a 2061 if (Cache.Open(false) == false)
36375005
AL
2062 return false;
2063
2d11135a 2064 if (CmdL.FileSize() <= 1)
b2e465d6 2065 return _error->Error(_("Must specify at least one package to fetch source for"));
2d11135a 2066
36375005
AL
2067 // Read the source list
2068 pkgSourceList List;
2069 if (List.ReadMainList() == false)
b2e465d6 2070 return _error->Error(_("The list of sources could not be read."));
36375005
AL
2071
2072 // Create the text record parsers
2073 pkgRecords Recs(Cache);
2074 pkgSrcRecords SrcRecs(List);
2075 if (_error->PendingError() == true)
2076 return false;
2077
2078 // Create the download object
2079 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
2080 pkgAcquire Fetcher(&Stat);
fb0ee66e
AL
2081
2082 DscFile *Dsc = new DscFile[CmdL.FileSize()];
36375005 2083
092ae175
MV
2084 // insert all downloaded uris into this set to avoid downloading them
2085 // twice
2086 set<string> queued;
36375005 2087 // Load the requestd sources into the fetcher
fb0ee66e
AL
2088 unsigned J = 0;
2089 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
36375005
AL
2090 {
2091 string Src;
b2e465d6 2092 pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,*Cache);
36375005
AL
2093
2094 if (Last == 0)
b2e465d6 2095 return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
36375005
AL
2096
2097 // Back track
2098 vector<pkgSrcRecords::File> Lst;
b2e465d6 2099 if (Last->Files(Lst) == false)
36375005
AL
2100 return false;
2101
2102 // Load them into the fetcher
2103 for (vector<pkgSrcRecords::File>::const_iterator I = Lst.begin();
2104 I != Lst.end(); I++)
2105 {
2106 // Try to guess what sort of file it is we are getting.
b2e465d6 2107 if (I->Type == "dsc")
fb0ee66e 2108 {
fb0ee66e
AL
2109 Dsc[J].Package = Last->Package();
2110 Dsc[J].Version = Last->Version();
2111 Dsc[J].Dsc = flNotDir(I->Path);
2112 }
2113
17c0e8e1
AL
2114 // Diff only mode only fetches .diff files
2115 if (_config->FindB("APT::Get::Diff-Only",false) == true &&
b2e465d6 2116 I->Type != "diff")
17c0e8e1
AL
2117 continue;
2118
2119 // Tar only mode only fetches .tar files
2120 if (_config->FindB("APT::Get::Tar-Only",false) == true &&
b2e465d6 2121 I->Type != "tar")
17c0e8e1 2122 continue;
092ae175 2123
1979e742
MV
2124 // Dsc only mode only fetches .dsc files
2125 if (_config->FindB("APT::Get::Dsc-Only",false) == true &&
2126 I->Type != "dsc")
2127 continue;
2128
092ae175
MV
2129 // don't download the same uri twice (should this be moved to
2130 // the fetcher interface itself?)
2131 if(queued.find(Last->Index().ArchiveURI(I->Path)) != queued.end())
2132 continue;
2133 queued.insert(Last->Index().ArchiveURI(I->Path));
2134
2135 // check if we have a file with that md5 sum already localy
2136 if(!I->MD5Hash.empty() && FileExists(flNotDir(I->Path)))
2137 {
2138 FileFd Fd(flNotDir(I->Path), FileFd::ReadOnly);
2139 MD5Summation sum;
2140 sum.AddFD(Fd.Fd(), Fd.Size());
2141 Fd.Close();
2142 if((string)sum.Result() == I->MD5Hash)
2143 {
443cb67c 2144 ioprintf(c1out,_("Skipping already downloaded file '%s'\n"),
092ae175
MV
2145 flNotDir(I->Path).c_str());
2146 continue;
2147 }
2148 }
2149
b2e465d6
AL
2150 new pkgAcqFile(&Fetcher,Last->Index().ArchiveURI(I->Path),
2151 I->MD5Hash,I->Size,
2152 Last->Index().SourceInfo(*Last,*I),Src);
36375005
AL
2153 }
2154 }
2155
2156 // Display statistics
b2e465d6
AL
2157 double FetchBytes = Fetcher.FetchNeeded();
2158 double FetchPBytes = Fetcher.PartialPresent();
2159 double DebBytes = Fetcher.TotalNeeded();
36375005
AL
2160
2161 // Check for enough free space
f332b62b 2162 struct statvfs Buf;
36375005 2163 string OutputDir = ".";
f332b62b 2164 if (statvfs(OutputDir.c_str(),&Buf) != 0)
2a7e07c7 2165 return _error->Errno("statvfs",_("Couldn't determine free space in %s"),
36375005
AL
2166 OutputDir.c_str());
2167 if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
885d204b
OS
2168 {
2169 struct statfs Stat;
2170 if (statfs(OutputDir.c_str(),&Stat) != 0 ||
2171 unsigned(Stat.f_type) != RAMFS_MAGIC)
2172 return _error->Error(_("You don't have enough free space in %s"),
2173 OutputDir.c_str());
2174 }
36375005
AL
2175
2176 // Number of bytes
36375005 2177 if (DebBytes != FetchBytes)
b2e465d6
AL
2178 ioprintf(c1out,_("Need to get %sB/%sB of source archives.\n"),
2179 SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
36375005 2180 else
b2e465d6
AL
2181 ioprintf(c1out,_("Need to get %sB of source archives.\n"),
2182 SizeToStr(DebBytes).c_str());
2183
2c0c53b3
AL
2184 if (_config->FindB("APT::Get::Simulate",false) == true)
2185 {
2186 for (unsigned I = 0; I != J; I++)
db0db9fe 2187 ioprintf(cout,_("Fetch source %s\n"),Dsc[I].Package.c_str());
2c0c53b3
AL
2188 return true;
2189 }
2190
36375005
AL
2191 // Just print out the uris an exit if the --print-uris flag was used
2192 if (_config->FindB("APT::Get::Print-URIs") == true)
2193 {
2194 pkgAcquire::UriIterator I = Fetcher.UriBegin();
2195 for (; I != Fetcher.UriEnd(); I++)
2196 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
495e5cb2 2197 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
36375005
AL
2198 return true;
2199 }
2200
2201 // Run it
024d1123 2202 if (Fetcher.Run() == pkgAcquire::Failed)
36375005
AL
2203 return false;
2204
2205 // Print error messages
fb0ee66e 2206 bool Failed = false;
076d01b0 2207 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
36375005
AL
2208 {
2209 if ((*I)->Status == pkgAcquire::Item::StatDone &&
2210 (*I)->Complete == true)
2211 continue;
2212
b2e465d6
AL
2213 fprintf(stderr,_("Failed to fetch %s %s\n"),(*I)->DescURI().c_str(),
2214 (*I)->ErrorText.c_str());
fb0ee66e 2215 Failed = true;
36375005 2216 }
fb0ee66e 2217 if (Failed == true)
b2e465d6 2218 return _error->Error(_("Failed to fetch some archives."));
fb0ee66e
AL
2219
2220 if (_config->FindB("APT::Get::Download-only",false) == true)
b2e465d6
AL
2221 {
2222 c1out << _("Download complete and in download only mode") << endl;
fb0ee66e 2223 return true;
b2e465d6
AL
2224 }
2225
fb0ee66e 2226 // Unpack the sources
54676e1a
AL
2227 pid_t Process = ExecFork();
2228
2229 if (Process == 0)
fb0ee66e 2230 {
54676e1a 2231 for (unsigned I = 0; I != J; I++)
fb0ee66e 2232 {
b2e465d6 2233 string Dir = Dsc[I].Package + '-' + Cache->VS().UpstreamVersion(Dsc[I].Version.c_str());
fb0ee66e 2234
17c0e8e1
AL
2235 // Diff only mode only fetches .diff files
2236 if (_config->FindB("APT::Get::Diff-Only",false) == true ||
a3eaf954
AL
2237 _config->FindB("APT::Get::Tar-Only",false) == true ||
2238 Dsc[I].Dsc.empty() == true)
17c0e8e1 2239 continue;
a3eaf954 2240
54676e1a
AL
2241 // See if the package is already unpacked
2242 struct stat Stat;
2243 if (stat(Dir.c_str(),&Stat) == 0 &&
2244 S_ISDIR(Stat.st_mode) != 0)
2245 {
b2e465d6
AL
2246 ioprintf(c0out ,_("Skipping unpack of already unpacked source in %s\n"),
2247 Dir.c_str());
54676e1a
AL
2248 }
2249 else
2250 {
2251 // Call dpkg-source
2252 char S[500];
2253 snprintf(S,sizeof(S),"%s -x %s",
2254 _config->Find("Dir::Bin::dpkg-source","dpkg-source").c_str(),
2255 Dsc[I].Dsc.c_str());
2256 if (system(S) != 0)
2257 {
b2e465d6 2258 fprintf(stderr,_("Unpack command '%s' failed.\n"),S);
14cd494a 2259 fprintf(stderr,_("Check if the 'dpkg-dev' package is installed.\n"));
54676e1a
AL
2260 _exit(1);
2261 }
2262 }
2263
2264 // Try to compile it with dpkg-buildpackage
2265 if (_config->FindB("APT::Get::Compile",false) == true)
2266 {
2267 // Call dpkg-buildpackage
2268 char S[500];
2269 snprintf(S,sizeof(S),"cd %s && %s %s",
2270 Dir.c_str(),
2271 _config->Find("Dir::Bin::dpkg-buildpackage","dpkg-buildpackage").c_str(),
2272 _config->Find("DPkg::Build-Options","-b -uc").c_str());
2273
2274 if (system(S) != 0)
2275 {
b2e465d6 2276 fprintf(stderr,_("Build command '%s' failed.\n"),S);
54676e1a
AL
2277 _exit(1);
2278 }
2279 }
2280 }
2281
2282 _exit(0);
2283 }
2284
2285 // Wait for the subprocess
2286 int Status = 0;
2287 while (waitpid(Process,&Status,0) != Process)
2288 {
2289 if (errno == EINTR)
2290 continue;
2291 return _error->Errno("waitpid","Couldn't wait for subprocess");
2292 }
2293
2294 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
b2e465d6
AL
2295 return _error->Error(_("Child process failed"));
2296
2297 return true;
2298}
2299 /*}}}*/
2300// DoBuildDep - Install/removes packages to satisfy build dependencies /*{{{*/
2301// ---------------------------------------------------------------------
2302/* This function will look at the build depends list of the given source
2303 package and install the necessary packages to make it true, or fail. */
2304bool DoBuildDep(CommandLine &CmdL)
2305{
2306 CacheFile Cache;
2307 if (Cache.Open(true) == false)
2308 return false;
2309
2310 if (CmdL.FileSize() <= 1)
2311 return _error->Error(_("Must specify at least one package to check builddeps for"));
2312
2313 // Read the source list
2314 pkgSourceList List;
2315 if (List.ReadMainList() == false)
2316 return _error->Error(_("The list of sources could not be read."));
54676e1a 2317
b2e465d6
AL
2318 // Create the text record parsers
2319 pkgRecords Recs(Cache);
2320 pkgSrcRecords SrcRecs(List);
2321 if (_error->PendingError() == true)
2322 return false;
2323
2324 // Create the download object
2325 AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
2326 pkgAcquire Fetcher(&Stat);
2327
2328 unsigned J = 0;
2329 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
2330 {
2331 string Src;
2332 pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,*Cache);
2333 if (Last == 0)
2334 return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
2335
2336 // Process the build-dependencies
2337 vector<pkgSrcRecords::Parser::BuildDepRec> BuildDeps;
45430cbf 2338 if (Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only",false)) == false)
b2e465d6
AL
2339 return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
2340
7d6f9f8f
AL
2341 // Also ensure that build-essential packages are present
2342 Configuration::Item const *Opts = _config->Tree("APT::Build-Essential");
2343 if (Opts)
2344 Opts = Opts->Child;
2345 for (; Opts; Opts = Opts->Next)
2346 {
2347 if (Opts->Value.empty() == true)
2348 continue;
2349
2350 pkgSrcRecords::Parser::BuildDepRec rec;
2351 rec.Package = Opts->Value;
2352 rec.Type = pkgSrcRecords::Parser::BuildDependIndep;
2353 rec.Op = 0;
58d76831 2354 BuildDeps.push_back(rec);
7d6f9f8f
AL
2355 }
2356
b2e465d6
AL
2357 if (BuildDeps.size() == 0)
2358 {
2359 ioprintf(c1out,_("%s has no build depends.\n"),Src.c_str());
2360 continue;
2361 }
2362
2363 // Install the requested packages
2364 unsigned int ExpectedInst = 0;
2365 vector <pkgSrcRecords::Parser::BuildDepRec>::iterator D;
2366 pkgProblemResolver Fix(Cache);
58d76831 2367 bool skipAlternatives = false; // skip remaining alternatives in an or group
b2e465d6
AL
2368 for (D = BuildDeps.begin(); D != BuildDeps.end(); D++)
2369 {
58d76831
AL
2370 bool hasAlternatives = (((*D).Op & pkgCache::Dep::Or) == pkgCache::Dep::Or);
2371
2372 if (skipAlternatives == true)
2373 {
2374 if (!hasAlternatives)
2375 skipAlternatives = false; // end of or group
2376 continue;
2377 }
2378
aa2d22be
AL
2379 if ((*D).Type == pkgSrcRecords::Parser::BuildConflict ||
2380 (*D).Type == pkgSrcRecords::Parser::BuildConflictIndep)
d3fc0061 2381 {
aa2d22be
AL
2382 pkgCache::PkgIterator Pkg = Cache->FindPkg((*D).Package);
2383 // Build-conflicts on unknown packages are silently ignored
2384 if (Pkg.end() == true)
2385 continue;
2386
2387 pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
2388
2389 /*
2390 * Remove if we have an installed version that satisfies the
2391 * version criteria
2392 */
2393 if (IV.end() == false &&
2394 Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
2395 TryToInstall(Pkg,Cache,Fix,true,false,ExpectedInst);
d3fc0061 2396 }
aa2d22be
AL
2397 else // BuildDep || BuildDepIndep
2398 {
2399 pkgCache::PkgIterator Pkg = Cache->FindPkg((*D).Package);
58d76831
AL
2400 if (_config->FindB("Debug::BuildDeps",false) == true)
2401 cout << "Looking for " << (*D).Package << "...\n";
2402
aa2d22be
AL
2403 if (Pkg.end() == true)
2404 {
58d76831
AL
2405 if (_config->FindB("Debug::BuildDeps",false) == true)
2406 cout << " (not found)" << (*D).Package << endl;
2407
2408 if (hasAlternatives)
2409 continue;
2410
2411 return _error->Error(_("%s dependency for %s cannot be satisfied "
2412 "because the package %s cannot be found"),
2413 Last->BuildDepType((*D).Type),Src.c_str(),
2414 (*D).Package.c_str());
aa2d22be
AL
2415 }
2416
2417 /*
2418 * if there are alternatives, we've already picked one, so skip
2419 * the rest
2420 *
2421 * TODO: this means that if there's a build-dep on A|B and B is
2422 * installed, we'll still try to install A; more importantly,
2423 * if A is currently broken, we cannot go back and try B. To fix
2424 * this would require we do a Resolve cycle for each package we
2425 * add to the install list. Ugh
2426 */
aa2d22be 2427
cfa5659c
AL
2428 /*
2429 * If this is a virtual package, we need to check the list of
2430 * packages that provide it and see if any of those are
2431 * installed
2432 */
2433 pkgCache::PrvIterator Prv = Pkg.ProvidesList();
a8a0fdcf
AL
2434 for (; Prv.end() != true; Prv++)
2435 {
58d76831
AL
2436 if (_config->FindB("Debug::BuildDeps",false) == true)
2437 cout << " Checking provider " << Prv.OwnerPkg().Name() << endl;
2438
cfa5659c
AL
2439 if ((*Cache)[Prv.OwnerPkg()].InstVerIter(*Cache).end() == false)
2440 break;
cb99271c 2441 }
e5002e30
AL
2442
2443 // Get installed version and version we are going to install
2444 pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
e5002e30 2445
58d76831
AL
2446 if ((*D).Version[0] != '\0') {
2447 // Versioned dependency
cb99271c
AL
2448
2449 pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
2450
2451 for (; CV.end() != true; CV++)
2452 {
2453 if (Cache->VS().CheckDep(CV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
2454 break;
2455 }
2456 if (CV.end() == true)
085bedac 2457 {
34e88622
AL
2458 if (hasAlternatives)
2459 {
2460 continue;
2461 }
2462 else
2463 {
cb99271c
AL
2464 return _error->Error(_("%s dependency for %s cannot be satisfied "
2465 "because no available versions of package %s "
2466 "can satisfy version requirements"),
2467 Last->BuildDepType((*D).Type),Src.c_str(),
2468 (*D).Package.c_str());
34e88622 2469 }
085bedac 2470 }
e5002e30 2471 }
58d76831
AL
2472 else
2473 {
2474 // Only consider virtual packages if there is no versioned dependency
2475 if (Prv.end() == false)
2476 {
2477 if (_config->FindB("Debug::BuildDeps",false) == true)
2478 cout << " Is provided by installed package " << Prv.OwnerPkg().Name() << endl;
2479 skipAlternatives = hasAlternatives;
2480 continue;
2481 }
2482 }
cfa5659c 2483
58d76831
AL
2484 if (IV.end() == false)
2485 {
2486 if (_config->FindB("Debug::BuildDeps",false) == true)
2487 cout << " Is installed\n";
2488
2489 if (Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
2490 {
2491 skipAlternatives = hasAlternatives;
2492 continue;
2493 }
2494
2495 if (_config->FindB("Debug::BuildDeps",false) == true)
2496 cout << " ...but the installed version doesn't meet the version requirement\n";
2497
2498 if (((*D).Op & pkgCache::Dep::LessEq) == pkgCache::Dep::LessEq)
2499 {
2500 return _error->Error(_("Failed to satisfy %s dependency for %s: Installed package %s is too new"),
2501 Last->BuildDepType((*D).Type),
2502 Src.c_str(),
2503 Pkg.Name());
2504 }
2505 }
2506
2507
2508 if (_config->FindB("Debug::BuildDeps",false) == true)
2509 cout << " Trying to install " << (*D).Package << endl;
2510
2511 if (TryToInstall(Pkg,Cache,Fix,false,false,ExpectedInst) == true)
2512 {
2513 // We successfully installed something; skip remaining alternatives
2514 skipAlternatives = hasAlternatives;
2515 continue;
2516 }
2517 else if (hasAlternatives)
2518 {
2519 if (_config->FindB("Debug::BuildDeps",false) == true)
2520 cout << " Unsatisfiable, trying alternatives\n";
2521 continue;
2522 }
2523 else
2524 {
2525 return _error->Error(_("Failed to satisfy %s dependency for %s: %s"),
2526 Last->BuildDepType((*D).Type),
2527 Src.c_str(),
2528 (*D).Package.c_str());
2529 }
b2e465d6
AL
2530 }
2531 }
2532
2533 Fix.InstallProtect();
2534 if (Fix.Resolve(true) == false)
2535 _error->Discard();
2536
2537 // Now we check the state of the packages,
2538 if (Cache->BrokenCount() != 0)
c33d7c4d 2539 return _error->Error(_("Build-dependencies for %s could not be satisfied."),*I);
b2e465d6
AL
2540 }
2541
2542 if (InstallPackages(Cache, false, true) == false)
2543 return _error->Error(_("Failed to process build dependencies"));
36375005
AL
2544 return true;
2545}
2546 /*}}}*/
2547
b2e465d6
AL
2548// DoMoo - Never Ask, Never Tell /*{{{*/
2549// ---------------------------------------------------------------------
2550/* */
2551bool DoMoo(CommandLine &CmdL)
2552{
2553 cout <<
2554 " (__) \n"
2555 " (oo) \n"
2556 " /------\\/ \n"
2557 " / | || \n"
2558 " * /\\---/\\ \n"
2559 " ~~ ~~ \n"
2560 "....\"Have you mooed today?\"...\n";
2561
2562 return true;
2563}
2564 /*}}}*/
0a8e3465
AL
2565// ShowHelp - Show a help screen /*{{{*/
2566// ---------------------------------------------------------------------
2567/* */
212ad54a 2568bool ShowHelp(CommandLine &CmdL)
0a8e3465 2569{
5b28c804
OS
2570 ioprintf(cout,_("%s %s for %s compiled on %s %s\n"),PACKAGE,VERSION,
2571 COMMON_ARCH,__DATE__,__TIME__);
b2e465d6 2572
04aa15a8 2573 if (_config->FindB("version") == true)
b2e465d6 2574 {
db0db9fe 2575 cout << _("Supported modules:") << endl;
b2e465d6
AL
2576
2577 for (unsigned I = 0; I != pkgVersioningSystem::GlobalListLen; I++)
2578 {
2579 pkgVersioningSystem *VS = pkgVersioningSystem::GlobalList[I];
2580 if (_system != 0 && _system->VS == VS)
2581 cout << '*';
2582 else
2583 cout << ' ';
2584 cout << "Ver: " << VS->Label << endl;
2585
2586 /* Print out all the packaging systems that will work with
2587 this VS */
2588 for (unsigned J = 0; J != pkgSystem::GlobalListLen; J++)
2589 {
2590 pkgSystem *Sys = pkgSystem::GlobalList[J];
2591 if (_system == Sys)
2592 cout << '*';
2593 else
2594 cout << ' ';
2595 if (Sys->VS->TestCompatibility(*VS) == true)
2596 cout << "Pkg: " << Sys->Label << " (Priority " << Sys->Score(*_config) << ")" << endl;
2597 }
2598 }
2599
2600 for (unsigned I = 0; I != pkgSourceList::Type::GlobalListLen; I++)
2601 {
2602 pkgSourceList::Type *Type = pkgSourceList::Type::GlobalList[I];
2603 cout << " S.L: '" << Type->Name << "' " << Type->Label << endl;
2604 }
2605
2606 for (unsigned I = 0; I != pkgIndexFile::Type::GlobalListLen; I++)
2607 {
2608 pkgIndexFile::Type *Type = pkgIndexFile::Type::GlobalList[I];
2609 cout << " Idx: " << Type->Label << endl;
2610 }
2611
2612 return true;
2613 }
2614
2615 cout <<
2616 _("Usage: apt-get [options] command\n"
2617 " apt-get [options] install|remove pkg1 [pkg2 ...]\n"
2618 " apt-get [options] source pkg1 [pkg2 ...]\n"
2619 "\n"
2620 "apt-get is a simple command line interface for downloading and\n"
2621 "installing packages. The most frequently used commands are update\n"
2622 "and install.\n"
2623 "\n"
2624 "Commands:\n"
2625 " update - Retrieve new lists of packages\n"
2626 " upgrade - Perform an upgrade\n"
2627 " install - Install new packages (pkg is libc6 not libc6.deb)\n"
2628 " remove - Remove packages\n"
12bffed7 2629 " autoremove - Remove automatically all unused packages\n"
e47c7d16 2630 " purge - Remove and purge packages\n"
b2e465d6
AL
2631 " source - Download source archives\n"
2632 " build-dep - Configure build-dependencies for source packages\n"
2633 " dist-upgrade - Distribution upgrade, see apt-get(8)\n"
2634 " dselect-upgrade - Follow dselect selections\n"
2635 " clean - Erase downloaded archive files\n"
2636 " autoclean - Erase old downloaded archive files\n"
2637 " check - Verify that there are no broken dependencies\n"
2638 "\n"
2639 "Options:\n"
2640 " -h This help text.\n"
2641 " -q Loggable output - no progress indicator\n"
2642 " -qq No output except for errors\n"
2643 " -d Download only - do NOT install or unpack archives\n"
2644 " -s No-act. Perform ordering simulation\n"
2645 " -y Assume Yes to all queries and do not prompt\n"
0748d509 2646 " -f Attempt to correct a system with broken dependencies in place\n"
b2e465d6
AL
2647 " -m Attempt to continue if archives are unlocatable\n"
2648 " -u Show a list of upgraded packages as well\n"
2649 " -b Build the source package after fetching it\n"
ac625538 2650 " -V Show verbose version numbers\n"
b2e465d6 2651 " -c=? Read this configuration file\n"
a2884e32 2652 " -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp\n"
b2e465d6
AL
2653 "See the apt-get(8), sources.list(5) and apt.conf(5) manual\n"
2654 "pages for more information and options.\n"
2655 " This APT has Super Cow Powers.\n");
2656 return true;
0a8e3465
AL
2657}
2658 /*}}}*/
2659// GetInitialize - Initialize things for apt-get /*{{{*/
2660// ---------------------------------------------------------------------
2661/* */
2662void GetInitialize()
2663{
2664 _config->Set("quiet",0);
2665 _config->Set("help",false);
2666 _config->Set("APT::Get::Download-Only",false);
2667 _config->Set("APT::Get::Simulate",false);
2668 _config->Set("APT::Get::Assume-Yes",false);
2669 _config->Set("APT::Get::Fix-Broken",false);
83d89a9f 2670 _config->Set("APT::Get::Force-Yes",false);
640c5d94 2671 _config->Set("APT::Get::List-Cleanup",true);
afb1e2e3 2672 _config->Set("APT::Get::AutomaticRemove",false);
0a8e3465
AL
2673}
2674 /*}}}*/
d7827aca
AL
2675// SigWinch - Window size change signal handler /*{{{*/
2676// ---------------------------------------------------------------------
2677/* */
2678void SigWinch(int)
2679{
2680 // Riped from GNU ls
2681#ifdef TIOCGWINSZ
2682 struct winsize ws;
2683
2684 if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col >= 5)
2685 ScreenWidth = ws.ws_col - 1;
2686#endif
2687}
2688 /*}}}*/
0a8e3465
AL
2689
2690int main(int argc,const char *argv[])
2691{
2692 CommandLine::Args Args[] = {
2693 {'h',"help","help",0},
04aa15a8 2694 {'v',"version","version",0},
ac625538 2695 {'V',"verbose-versions","APT::Get::Show-Versions",0},
0a8e3465
AL
2696 {'q',"quiet","quiet",CommandLine::IntLevel},
2697 {'q',"silent","quiet",CommandLine::IntLevel},
2698 {'d',"download-only","APT::Get::Download-Only",0},
fb0ee66e
AL
2699 {'b',"compile","APT::Get::Compile",0},
2700 {'b',"build","APT::Get::Compile",0},
d150b09d
AL
2701 {'s',"simulate","APT::Get::Simulate",0},
2702 {'s',"just-print","APT::Get::Simulate",0},
2703 {'s',"recon","APT::Get::Simulate",0},
6df23d2f 2704 {'s',"dry-run","APT::Get::Simulate",0},
d150b09d
AL
2705 {'s',"no-act","APT::Get::Simulate",0},
2706 {'y',"yes","APT::Get::Assume-Yes",0},
0a8e3465
AL
2707 {'y',"assume-yes","APT::Get::Assume-Yes",0},
2708 {'f',"fix-broken","APT::Get::Fix-Broken",0},
2709 {'u',"show-upgraded","APT::Get::Show-Upgraded",0},
30e1eab5 2710 {'m',"ignore-missing","APT::Get::Fix-Missing",0},
b2e465d6
AL
2711 {'t',"target-release","APT::Default-Release",CommandLine::HasArg},
2712 {'t',"default-release","APT::Default-Release",CommandLine::HasArg},
2713 {0,"download","APT::Get::Download",0},
30e1eab5 2714 {0,"fix-missing","APT::Get::Fix-Missing",0},
b2e465d6
AL
2715 {0,"ignore-hold","APT::Ignore-Hold",0},
2716 {0,"upgrade","APT::Get::upgrade",0},
83d89a9f 2717 {0,"force-yes","APT::Get::force-yes",0},
f7a08e33 2718 {0,"print-uris","APT::Get::Print-URIs",0},
5fafc0ef 2719 {0,"diff-only","APT::Get::Diff-Only",0},
1979e742
MV
2720 {0,"tar-only","APT::Get::Tar-Only",0},
2721 {0,"dsc-only","APT::Get::Dsc-Only",0},
fc4b5c9f 2722 {0,"purge","APT::Get::Purge",0},
9df71a5b 2723 {0,"list-cleanup","APT::Get::List-Cleanup",0},
d0c59649 2724 {0,"reinstall","APT::Get::ReInstall",0},
d150b09d 2725 {0,"trivial-only","APT::Get::Trivial-Only",0},
b2e465d6
AL
2726 {0,"remove","APT::Get::Remove",0},
2727 {0,"only-source","APT::Get::Only-Source",0},
45430cbf 2728 {0,"arch-only","APT::Get::Arch-Only",0},
f8ac1720 2729 {0,"auto-remove","APT::Get::AutomaticRemove",0},
7db98ffc 2730 {0,"allow-unauthenticated","APT::Get::AllowUnauthenticated",0},
e9ae3677 2731 {0,"install-recommends","APT::Install-Recommends",CommandLine::Boolean},
4ef9a929 2732 {0,"fix-policy","APT::Get::Fix-Policy-Broken",0},
0a8e3465
AL
2733 {'c',"config-file",0,CommandLine::ConfigFile},
2734 {'o',"option",0,CommandLine::ArbItem},
2735 {0,0,0,0}};
83d89a9f
AL
2736 CommandLine::Dispatch Cmds[] = {{"update",&DoUpdate},
2737 {"upgrade",&DoUpgrade},
2738 {"install",&DoInstall},
2739 {"remove",&DoInstall},
24401c09 2740 {"purge",&DoInstall},
74a05226 2741 {"autoremove",&DoInstall},
9efa2e91 2742 {"purge",&DoInstall},
83d89a9f
AL
2743 {"dist-upgrade",&DoDistUpgrade},
2744 {"dselect-upgrade",&DoDSelectUpgrade},
b2e465d6 2745 {"build-dep",&DoBuildDep},
83d89a9f 2746 {"clean",&DoClean},
1bc849af 2747 {"autoclean",&DoAutoClean},
83d89a9f 2748 {"check",&DoCheck},
67111687 2749 {"source",&DoSource},
b2e465d6 2750 {"moo",&DoMoo},
67111687 2751 {"help",&ShowHelp},
83d89a9f 2752 {0,0}};
67111687
AL
2753
2754 // Set up gettext support
2755 setlocale(LC_ALL,"");
2756 textdomain(PACKAGE);
2757
0a8e3465
AL
2758 // Parse the command line and initialize the package library
2759 CommandLine CmdL(Args,_config);
b2e465d6
AL
2760 if (pkgInitConfig(*_config) == false ||
2761 CmdL.Parse(argc,argv) == false ||
2762 pkgInitSystem(*_config,_system) == false)
0a8e3465 2763 {
b2e465d6
AL
2764 if (_config->FindB("version") == true)
2765 ShowHelp(CmdL);
2766
0a8e3465
AL
2767 _error->DumpErrors();
2768 return 100;
2769 }
2770
2771 // See if the help should be shown
2772 if (_config->FindB("help") == true ||
04aa15a8 2773 _config->FindB("version") == true ||
0a8e3465 2774 CmdL.FileSize() == 0)
b2e465d6
AL
2775 {
2776 ShowHelp(CmdL);
2777 return 0;
2778 }
67ff87bf 2779
a9a5908d 2780 // Deal with stdout not being a tty
00581c6b 2781 if (!isatty(STDOUT_FILENO) && _config->FindI("quiet",0) < 1)
a9a5908d 2782 _config->Set("quiet","1");
01b64152 2783
0a8e3465
AL
2784 // Setup the output streams
2785 c0out.rdbuf(cout.rdbuf());
2786 c1out.rdbuf(cout.rdbuf());
2787 c2out.rdbuf(cout.rdbuf());
2788 if (_config->FindI("quiet",0) > 0)
2789 c0out.rdbuf(devnull.rdbuf());
2790 if (_config->FindI("quiet",0) > 1)
2791 c1out.rdbuf(devnull.rdbuf());
d7827aca
AL
2792
2793 // Setup the signals
2794 signal(SIGPIPE,SIG_IGN);
2795 signal(SIGWINCH,SigWinch);
2796 SigWinch(0);
b2e465d6 2797
0a8e3465 2798 // Match the operation
83d89a9f 2799 CmdL.DispatchArg(Cmds);
0a8e3465
AL
2800
2801 // Print any errors or warnings found during parsing
2802 if (_error->empty() == false)
2803 {
2804 bool Errors = _error->PendingError();
2805 _error->DumpErrors();
0a8e3465
AL
2806 return Errors == true?100:0;
2807 }
2808
2809 return 0;
2810}