]> git.saurik.com Git - apt.git/blame - cmdline/apt-get.cc
implement default apt-get file --release-info mode
[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
1e3f4083 18 dist-upgrade - Powerful upgrader designed to handle the issues with
5ec427c2
AL
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 /*{{{*/
ea542140
DK
28#include <config.h>
29
453b82a3
DK
30#include <apt-pkg/acquire-item.h>
31#include <apt-pkg/algorithms.h>
086bb6d7 32#include <apt-pkg/aptconfiguration.h>
453b82a3
DK
33#include <apt-pkg/cachefile.h>
34#include <apt-pkg/cacheset.h>
35#include <apt-pkg/clean.h>
0a8e3465 36#include <apt-pkg/cmndline.h>
453b82a3 37#include <apt-pkg/debmetaindex.h>
0a8e3465 38#include <apt-pkg/depcache.h>
453b82a3 39#include <apt-pkg/error.h>
472ff00e 40#include <apt-pkg/fileutl.h>
453b82a3
DK
41#include <apt-pkg/indexfile.h>
42#include <apt-pkg/indexrecords.h>
43#include <apt-pkg/init.h>
092ae175 44#include <apt-pkg/md5.h>
453b82a3 45#include <apt-pkg/metaindex.h>
472ff00e 46#include <apt-pkg/pkgrecords.h>
453b82a3
DK
47#include <apt-pkg/pkgsystem.h>
48#include <apt-pkg/progress.h>
49#include <apt-pkg/sourcelist.h>
50#include <apt-pkg/srcrecords.h>
51#include <apt-pkg/strutl.h>
52#include <apt-pkg/version.h>
53#include <apt-pkg/acquire.h>
54#include <apt-pkg/configuration.h>
55#include <apt-pkg/macros.h>
56#include <apt-pkg/pkgcache.h>
57#include <apt-pkg/cacheiterators.h>
82e369c4 58#include <apt-pkg/upgrade.h>
ffee1c2b 59
453b82a3
DK
60#include <apt-private/acqprogress.h>
61#include <apt-private/private-cacheset.h>
62#include <apt-private/private-cachefile.h>
63#include <apt-private/private-cmndline.h>
866893a6 64#include <apt-private/private-download.h>
b9179170 65#include <apt-private/private-install.h>
453b82a3
DK
66#include <apt-private/private-main.h>
67#include <apt-private/private-moo.h>
b9179170 68#include <apt-private/private-output.h>
b9179170 69#include <apt-private/private-update.h>
453b82a3 70#include <apt-private/private-upgrade.h>
cfacba52 71#include <apt-private/private-utils.h>
b9179170 72
453b82a3
DK
73#include <errno.h>
74#include <signal.h>
75#include <stddef.h>
76#include <stdio.h>
77#include <stdlib.h>
78#include <string.h>
a3f1d60c 79#include <sys/ioctl.h>
1bc849af 80#include <sys/stat.h>
b9179170 81#include <sys/wait.h>
453b82a3 82#include <unistd.h>
03aa0847
DK
83#include <pwd.h>
84#include <grp.h>
85
453b82a3
DK
86#include <algorithm>
87#include <fstream>
88#include <iostream>
8881b11e 89#include <sstream>
453b82a3
DK
90#include <set>
91#include <string>
92#include <vector>
5ec427c2 93
b9179170
MV
94#include <apti18n.h>
95 /*}}}*/
afb1e2e3 96
b9179170 97using namespace std;
642ebc1a 98
b8ad5512 99// TryToInstallBuildDep - Try to install a single package /*{{{*/
c373c37a
AL
100// ---------------------------------------------------------------------
101/* This used to be inlined in DoInstall, but with the advent of regex package
102 name matching it was split out.. */
c3ccac92 103static bool TryToInstallBuildDep(pkgCache::PkgIterator Pkg,pkgCacheFile &Cache,
c373c37a 104 pkgProblemResolver &Fix,bool Remove,bool BrokenFix,
70e706ad 105 bool AllowFail = true)
c373c37a 106{
21d4c9f1 107 if (Cache[Pkg].CandidateVer == 0 && Pkg->ProvidesList != 0)
c373c37a 108 {
21d4c9f1 109 CacheSetHelperAPTGet helper(c1out);
4caf8231 110 helper.showErrors(false);
21d4c9f1
DK
111 pkgCache::VerIterator Ver = helper.canNotFindNewestVer(Cache, Pkg);
112 if (Ver.end() == false)
113 Pkg = Ver.ParentPkg();
114 else if (helper.showVirtualPackageErrors(Cache) == false)
115 return AllowFail;
c373c37a 116 }
61d6a8de 117
ac321486
DK
118 if (_config->FindB("Debug::BuildDeps",false) == true)
119 {
120 if (Remove == true)
121 cout << " Trying to remove " << Pkg << endl;
122 else
123 cout << " Trying to install " << Pkg << endl;
124 }
125
c373c37a
AL
126 if (Remove == true)
127 {
71d73928 128 TryToRemove RemoveAction(Cache, &Fix);
21d4c9f1
DK
129 RemoveAction(Pkg.VersionList());
130 } else if (Cache[Pkg].CandidateVer != 0) {
71d73928 131 TryToInstall InstallAction(Cache, &Fix, BrokenFix);
21d4c9f1 132 InstallAction(Cache[Pkg].CandidateVerIter(Cache));
6806db8a 133 InstallAction.doAutoInstall();
21d4c9f1
DK
134 } else
135 return AllowFail;
60681f93 136
b2e465d6
AL
137 return true;
138}
139 /*}}}*/
7014e148
MV
140// GetReleaseForSourceRecord - Return Suite for the given srcrecord /*{{{*/
141// ---------------------------------------------------------------------
142/* */
c3ccac92 143static std::string GetReleaseForSourceRecord(pkgSourceList *SrcList,
7014e148
MV
144 pkgSrcRecords::Parser *Parse)
145{
146 // try to find release
147 const pkgIndexFile& CurrentIndexFile = Parse->Index();
148
149 for (pkgSourceList::const_iterator S = SrcList->begin();
150 S != SrcList->end(); ++S)
151 {
152 vector<pkgIndexFile *> *Indexes = (*S)->GetIndexFiles();
153 for (vector<pkgIndexFile *>::const_iterator IF = Indexes->begin();
154 IF != Indexes->end(); ++IF)
155 {
156 if (&CurrentIndexFile == (*IF))
157 {
f105aaba
DK
158 std::string const path = (*S)->LocalFileName();
159 if (path != "")
7014e148
MV
160 {
161 indexRecords records;
162 records.Load(path);
163 return records.GetSuite();
164 }
165 }
166 }
167 }
168 return "";
169}
170 /*}}}*/
b2e465d6
AL
171// FindSrc - Find a source record /*{{{*/
172// ---------------------------------------------------------------------
173/* */
765190e4 174#if APT_PKG_ABI >= 413
a221efc3 175static pkgSrcRecords::Parser *FindSrc(const char *Name,
765190e4
DK
176#else
177static pkgSrcRecords::Parser *FindSrc(const char *Name,pkgRecords &Recs,
178#endif
b2e465d6 179 pkgSrcRecords &SrcRecs,string &Src,
7014e148 180 CacheFile &CacheFile)
b2e465d6 181{
adf379e7
MV
182 string VerTag, UserRequestedVerTag;
183 string ArchTag = "";
7014e148 184 string RelTag = _config->Find("APT::Default-Release");
b2e465d6 185 string TmpSrc = Name;
7014e148 186 pkgDepCache *Cache = CacheFile.GetDepCache();
aca056a9 187
adf379e7
MV
188 // extract release
189 size_t found = TmpSrc.find_last_of("/");
190 if (found != string::npos)
191 {
192 RelTag = TmpSrc.substr(found+1);
193 TmpSrc = TmpSrc.substr(0,found);
194 }
195 // extract the version
196 found = TmpSrc.find_last_of("=");
197 if (found != string::npos)
198 {
199 VerTag = UserRequestedVerTag = TmpSrc.substr(found+1);
200 TmpSrc = TmpSrc.substr(0,found);
201 }
202 // extract arch
203 found = TmpSrc.find_last_of(":");
204 if (found != string::npos)
205 {
206 ArchTag = TmpSrc.substr(found+1);
ebf6c42d
DK
207 TmpSrc = TmpSrc.substr(0,found);
208 }
aca056a9 209
fb3dc579
MV
210 /* Lookup the version of the package we would install if we were to
211 install a version and determine the source package name, then look
212 in the archive for a source package of the same name. */
213 bool MatchSrcOnly = _config->FindB("APT::Get::Only-Source");
adf379e7
MV
214 pkgCache::PkgIterator Pkg;
215 if (ArchTag != "")
216 Pkg = Cache->FindPkg(TmpSrc, ArchTag);
217 else
218 Pkg = Cache->FindPkg(TmpSrc);
219
220 // if we can't find a package but the user qualified with a arch,
221 // error out here
222 if (Pkg.end() && ArchTag != "")
223 {
224 Src = Name;
225 _error->Error(_("Can not find a package for architecture '%s'"),
226 ArchTag.c_str());
227 return 0;
228 }
229
fb3dc579 230 if (MatchSrcOnly == false && Pkg.end() == false)
aca056a9 231 {
adf379e7 232 if(VerTag != "" || RelTag != "" || ArchTag != "")
aca056a9 233 {
e84adb76 234 bool fuzzy = false;
fb3dc579
MV
235 // we have a default release, try to locate the pkg. we do it like
236 // this because GetCandidateVer() will not "downgrade", that means
237 // "apt-get source -t stable apt" won't work on a unstable system
f7f0d6c7 238 for (pkgCache::VerIterator Ver = Pkg.VersionList();; ++Ver)
aca056a9 239 {
e84adb76
DK
240 // try first only exact matches, later fuzzy matches
241 if (Ver.end() == true)
242 {
243 if (fuzzy == true)
244 break;
245 fuzzy = true;
246 Ver = Pkg.VersionList();
259f688a
MV
247 // exit right away from the Pkg.VersionList() loop if we
248 // don't have any versions
249 if (Ver.end() == true)
250 break;
e84adb76 251 }
adf379e7 252
37f45a57
MV
253 // ignore arches that are not for us
254 if (ArchTag != "" && Ver.Arch() != ArchTag)
255 continue;
256
adf379e7
MV
257 // pick highest version for the arch unless the user wants
258 // something else
259 if (ArchTag != "" && VerTag == "" && RelTag == "")
adf379e7
MV
260 if(Cache->VS().CmpVersion(VerTag, Ver.VerStr()) < 0)
261 VerTag = Ver.VerStr();
adf379e7 262
e84adb76
DK
263 // We match against a concrete version (or a part of this version)
264 if (VerTag.empty() == false &&
7014e148 265 (fuzzy == true || Cache->VS().CmpVersion(VerTag, Ver.VerStr()) != 0) && // exact match
e84adb76
DK
266 (fuzzy == false || strncmp(VerTag.c_str(), Ver.VerStr(), VerTag.size()) != 0)) // fuzzy match
267 continue;
268
fb3dc579 269 for (pkgCache::VerFileIterator VF = Ver.FileList();
f7f0d6c7 270 VF.end() == false; ++VF)
aca056a9 271 {
fb3dc579
MV
272 /* If this is the status file, and the current version is not the
273 version in the status file (ie it is not installed, or somesuch)
274 then it is not a candidate for installation, ever. This weeds
275 out bogus entries that may be due to config-file states, or
276 other. */
277 if ((VF.File()->Flags & pkgCache::Flag::NotSource) ==
278 pkgCache::Flag::NotSource && Pkg.CurrentVer() != Ver)
279 continue;
280
fb3dc579
MV
281 // or we match against a release
282 if(VerTag.empty() == false ||
7014e148
MV
283 (VF.File().Archive() != 0 && VF.File().Archive() == RelTag) ||
284 (VF.File().Codename() != 0 && VF.File().Codename() == RelTag))
fb3dc579 285 {
e84adb76 286 // the Version we have is possibly fuzzy or includes binUploads,
765190e4
DK
287 // so we use the Version of the SourcePkg (empty if same as package)
288#if APT_PKG_ABI >= 413
289 Src = Ver.SourcePkgName();
a221efc3 290 VerTag = Ver.SourceVerStr();
765190e4
DK
291#else
292 pkgRecords::Parser &Parse = Recs.Lookup(VF);
293 Src = Parse.SourcePkg();
294 // no SourcePkg name, so it is the "binary" name
295 if (Src.empty() == true)
296 Src = TmpSrc;
297 VerTag = Parse.SourceVer();
298 if (VerTag.empty() == true)
299 VerTag = Ver.VerStr();
300#endif
fb3dc579
MV
301 break;
302 }
aca056a9 303 }
61690a7e
MV
304 if (Src.empty() == false)
305 break;
aca056a9 306 }
026f60e2 307 }
adf379e7 308
37f45a57
MV
309 if (Src == "" && ArchTag != "")
310 {
c9829e07
MV
311 if (VerTag != "")
312 _error->Error(_("Can not find a package '%s' with version '%s'"),
313 Pkg.FullName().c_str(), VerTag.c_str());
314 if (RelTag != "")
315 _error->Error(_("Can not find a package '%s' with release '%s'"),
316 Pkg.FullName().c_str(), RelTag.c_str());
37f45a57
MV
317 Src = Name;
318 return 0;
319 }
320
321
61690a7e 322 if (Src.empty() == true)
b2e465d6 323 {
61690a7e
MV
324 // if we don't have found a fitting package yet so we will
325 // choose a good candidate and proceed with that.
326 // Maybe we will find a source later on with the right VerTag
7014e148
MV
327 // or RelTag
328 pkgCache::VerIterator Ver = Cache->GetCandidateVer(Pkg);
fb3dc579 329 if (Ver.end() == false)
b2e465d6 330 {
765190e4 331#if APT_PKG_ABI >= 413
a221efc3
DK
332 if (strcmp(Ver.SourcePkgName(),Ver.ParentPkg().Name()) != 0)
333 Src = Ver.SourcePkgName();
334 if (VerTag.empty() == true && strcmp(Ver.SourceVerStr(),Ver.VerStr()) != 0)
335 VerTag = Ver.SourceVerStr();
765190e4
DK
336#else
337 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
338 Src = Parse.SourcePkg();
339 if (VerTag.empty() == true)
340 VerTag = Parse.SourceVer();
341#endif
b2e465d6 342 }
fb3dc579
MV
343 }
344 }
345
346 if (Src.empty() == true)
7014e148 347 {
fb3dc579 348 Src = TmpSrc;
7014e148 349 }
fb3dc579
MV
350 else
351 {
352 /* if we have a source pkg name, make sure to only search
353 for srcpkg names, otherwise apt gets confused if there
354 is a binary package "pkg1" and a source package "pkg1"
355 with the same name but that comes from different packages */
356 MatchSrcOnly = true;
357 if (Src != TmpSrc)
358 {
359 ioprintf(c1out, _("Picking '%s' as source package instead of '%s'\n"), Src.c_str(), TmpSrc.c_str());
360 }
b2e465d6 361 }
89ad8e7c 362
b2e465d6
AL
363 // The best hit
364 pkgSrcRecords::Parser *Last = 0;
365 unsigned long Offset = 0;
366 string Version;
7014e148 367 pkgSourceList *SrcList = CacheFile.GetSourceList();
89ad8e7c 368
b2e465d6
AL
369 /* Iterate over all of the hits, which includes the resulting
370 binary packages in the search */
371 pkgSrcRecords::Parser *Parse;
fb3dc579 372 while (true)
b2e465d6 373 {
fb3dc579
MV
374 SrcRecs.Restart();
375 while ((Parse = SrcRecs.Find(Src.c_str(), MatchSrcOnly)) != 0)
b2e465d6 376 {
fb3dc579
MV
377 const string Ver = Parse->Version();
378
7014e148 379 // See if we need to look for a specific release tag
65dcff55 380 if (RelTag != "" && UserRequestedVerTag == "")
7014e148
MV
381 {
382 const string Rel = GetReleaseForSourceRecord(SrcList, Parse);
383
384 if (Rel == RelTag)
385 {
7014e148
MV
386 Last = Parse;
387 Offset = Parse->Offset();
651ae5ce 388 Version = Ver;
7014e148
MV
389 }
390 }
391
fb3dc579 392 // Ignore all versions which doesn't fit
e84adb76 393 if (VerTag.empty() == false &&
7014e148 394 Cache->VS().CmpVersion(VerTag, Ver) != 0) // exact match
b2e465d6 395 continue;
fb3dc579
MV
396
397 // Newer version or an exact match? Save the hit
7014e148 398 if (Last == 0 || Cache->VS().CmpVersion(Version,Ver) < 0) {
fb3dc579
MV
399 Last = Parse;
400 Offset = Parse->Offset();
401 Version = Ver;
402 }
403
7014e148
MV
404 // was the version check above an exact match?
405 // If so, we don't need to look further
406 if (VerTag.empty() == false && (VerTag == Ver))
fb3dc579 407 break;
b2e465d6 408 }
65dcff55 409 if (UserRequestedVerTag == "" && Version != "" && RelTag != "")
bfa7bfc8 410 ioprintf(c1out, "Selected version '%s' (%s) for %s\n",
651ae5ce
MV
411 Version.c_str(), RelTag.c_str(), Src.c_str());
412
fb3dc579
MV
413 if (Last != 0 || VerTag.empty() == true)
414 break;
017d3f3b 415 _error->Error(_("Can not find version '%s' of package '%s'"), VerTag.c_str(), TmpSrc.c_str());
ddff663f 416 return 0;
b2e465d6 417 }
fb3dc579 418
ce6162be 419 if (Last == 0 || Last->Jump(Offset) == false)
b2e465d6 420 return 0;
fb3dc579 421
b2e465d6
AL
422 return Last;
423}
424 /*}}}*/
182a6a55 425/* mark packages as automatically/manually installed. {{{*/
c3ccac92 426static bool DoMarkAuto(CommandLine &CmdL)
d63a1458
JAK
427{
428 bool Action = true;
429 int AutoMarkChanged = 0;
430 OpTextProgress progress;
431 CacheFile Cache;
432 if (Cache.Open() == false)
433 return false;
434
435 if (strcasecmp(CmdL.FileList[0],"markauto") == 0)
436 Action = true;
437 else if (strcasecmp(CmdL.FileList[0],"unmarkauto") == 0)
438 Action = false;
439
440 for (const char **I = CmdL.FileList + 1; *I != 0; I++)
441 {
442 const char *S = *I;
443 // Locate the package
444 pkgCache::PkgIterator Pkg = Cache->FindPkg(S);
445 if (Pkg.end() == true) {
446 return _error->Error(_("Couldn't find package %s"),S);
447 }
448 else
449 {
450 if (!Action)
451 ioprintf(c1out,_("%s set to manually installed.\n"), Pkg.Name());
452 else
453 ioprintf(c1out,_("%s set to automatically installed.\n"),
454 Pkg.Name());
455
456 Cache->MarkAuto(Pkg,Action);
457 AutoMarkChanged++;
458 }
459 }
182a6a55
DK
460
461 _error->Notice(_("This command is deprecated. Please use 'apt-mark auto' and 'apt-mark manual' instead."));
462
d63a1458
JAK
463 if (AutoMarkChanged && ! _config->FindB("APT::Get::Simulate",false))
464 return Cache->writeStateFile(NULL);
465 return false;
466}
0a8e3465 467 /*}}}*/
0a8e3465
AL
468// DoDSelectUpgrade - Do an upgrade by following dselects selections /*{{{*/
469// ---------------------------------------------------------------------
470/* Follows dselect's selections */
65512241 471static bool DoDSelectUpgrade(CommandLine &)
0a8e3465
AL
472{
473 CacheFile Cache;
c37b9502 474 if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
0a8e3465
AL
475 return false;
476
a4decc40
MV
477 pkgDepCache::ActionGroup group(Cache);
478
0a8e3465
AL
479 // Install everything with the install flag set
480 pkgCache::PkgIterator I = Cache->PkgBegin();
f7f0d6c7 481 for (;I.end() != true; ++I)
0a8e3465
AL
482 {
483 /* Install the package only if it is a new install, the autoupgrader
484 will deal with the rest */
485 if (I->SelectedState == pkgCache::State::Install)
486 Cache->MarkInstall(I,false);
487 }
488
489 /* Now install their deps too, if we do this above then order of
490 the status file is significant for | groups */
f7f0d6c7 491 for (I = Cache->PkgBegin();I.end() != true; ++I)
0a8e3465
AL
492 {
493 /* Install the package only if it is a new install, the autoupgrader
494 will deal with the rest */
495 if (I->SelectedState == pkgCache::State::Install)
2f45c76a 496 Cache->MarkInstall(I,true);
0a8e3465
AL
497 }
498
499 // Apply erasures now, they override everything else.
f7f0d6c7 500 for (I = Cache->PkgBegin();I.end() != true; ++I)
0a8e3465
AL
501 {
502 // Remove packages
503 if (I->SelectedState == pkgCache::State::DeInstall ||
504 I->SelectedState == pkgCache::State::Purge)
d556d1a1 505 Cache->MarkDelete(I,I->SelectedState == pkgCache::State::Purge);
0a8e3465
AL
506 }
507
2f45c76a 508 /* Resolve any problems that dselect created, allupgrade cannot handle
1e3f4083 509 such things. We do so quite aggressively too.. */
2f45c76a
AL
510 if (Cache->BrokenCount() != 0)
511 {
512 pkgProblemResolver Fix(Cache);
513
514 // Hold back held packages.
b2e465d6 515 if (_config->FindB("APT::Ignore-Hold",false) == false)
2f45c76a 516 {
f7f0d6c7 517 for (pkgCache::PkgIterator I = Cache->PkgBegin(); I.end() == false; ++I)
2f45c76a
AL
518 {
519 if (I->SelectedState == pkgCache::State::Hold)
520 {
521 Fix.Protect(I);
522 Cache->MarkKeep(I);
523 }
524 }
525 }
526
527 if (Fix.Resolve() == false)
528 {
421c8d10 529 ShowBroken(c1out,Cache,false);
2a7e07c7 530 return _error->Error(_("Internal error, problem resolver broke stuff"));
2f45c76a
AL
531 }
532 }
533
534 // Now upgrade everything
67caa2e6 535 if (APT::Upgrade::Upgrade(Cache, APT::Upgrade::FORBID_REMOVE_PACKAGES | APT::Upgrade::FORBID_INSTALL_NEW_PACKAGES) == false)
0a8e3465 536 {
421c8d10 537 ShowBroken(c1out,Cache,false);
2a7e07c7 538 return _error->Error(_("Internal error, problem resolver broke stuff"));
0a8e3465
AL
539 }
540
541 return InstallPackages(Cache,false);
542}
543 /*}}}*/
544// DoClean - Remove download archives /*{{{*/
545// ---------------------------------------------------------------------
546/* */
65512241 547static bool DoClean(CommandLine &)
0a8e3465 548{
657ecd4a 549 std::string const archivedir = _config->FindDir("Dir::Cache::archives");
20e6965a 550 std::string const listsdir = _config->FindDir("Dir::state::lists");
657ecd4a 551
8b067c22
AL
552 if (_config->FindB("APT::Get::Simulate") == true)
553 {
20e6965a
DK
554 std::string const pkgcache = _config->FindFile("Dir::cache::pkgcache");
555 std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
657ecd4a 556 cout << "Del " << archivedir << "* " << archivedir << "partial/*"<< endl
20e6965a 557 << "Del " << listsdir << "partial/*" << endl
657ecd4a 558 << "Del " << pkgcache << " " << srcpkgcache << endl;
8b067c22
AL
559 return true;
560 }
20e6965a 561
7a1b1f8b 562 pkgAcquire Fetcher;
7e04a6bf 563 Fetcher.GetLock(archivedir);
657ecd4a
DK
564 Fetcher.Clean(archivedir);
565 Fetcher.Clean(archivedir + "partial/");
566
7e04a6bf 567 Fetcher.GetLock(listsdir);
20e6965a
DK
568 Fetcher.Clean(listsdir + "partial/");
569
8de79b68 570 pkgCacheFile::RemoveCaches();
657ecd4a 571
0a8e3465
AL
572 return true;
573}
574 /*}}}*/
1bc849af
AL
575// DoAutoClean - Smartly remove downloaded archives /*{{{*/
576// ---------------------------------------------------------------------
577/* This is similar to clean but it only purges things that cannot be
578 downloaded, that is old versions of cached packages. */
65a1e968
AL
579class LogCleaner : public pkgArchiveCleaner
580{
581 protected:
582 virtual void Erase(const char *File,string Pkg,string Ver,struct stat &St)
583 {
4cc8bab0 584 c1out << "Del " << Pkg << " " << Ver << " [" << SizeToStr(St.st_size) << "B]" << endl;
c1e78ee5
AL
585
586 if (_config->FindB("APT::Get::Simulate") == false)
587 unlink(File);
65a1e968
AL
588 };
589};
590
65512241 591static bool DoAutoClean(CommandLine &)
1bc849af 592{
1b6d659c
AL
593 // Lock the archive directory
594 FileFd Lock;
595 if (_config->FindB("Debug::NoLocking",false) == false)
596 {
de24f8ce
MV
597 int lock_fd = GetLock(_config->FindDir("Dir::Cache::Archives") + "lock");
598 if (lock_fd < 0)
b2e465d6 599 return _error->Error(_("Unable to lock the download directory"));
de24f8ce 600 Lock.Fd(lock_fd);
1b6d659c
AL
601 }
602
1bc849af 603 CacheFile Cache;
2d11135a 604 if (Cache.Open() == false)
1bc849af
AL
605 return false;
606
65a1e968 607 LogCleaner Cleaner;
1bc849af
AL
608
609 return Cleaner.Go(_config->FindDir("Dir::Cache::archives"),*Cache) &&
610 Cleaner.Go(_config->FindDir("Dir::Cache::archives") + "partial/",*Cache);
611}
612 /*}}}*/
0e3e112e
MV
613// DoDownload - download a binary /*{{{*/
614// ---------------------------------------------------------------------
c3ccac92 615static bool DoDownload(CommandLine &CmdL)
0e3e112e
MV
616{
617 CacheFile Cache;
618 if (Cache.ReadOnlyOpen() == false)
619 return false;
d57f6084 620
353c135e 621 APT::CacheSetHelper helper;
8f3594c3 622 APT::VersionSet verset = APT::VersionSet::FromCommandLine(Cache,
43acd019 623 CmdL.FileList + 1, APT::CacheSetHelper::CANDIDATE, helper);
0e3e112e
MV
624
625 if (verset.empty() == true)
626 return false;
627
dfad5bee 628 AcqTextStatus Stat(std::cout, ScreenWidth,_config->FindI("quiet",0));
04a54261 629 pkgAcquire Fetcher(&Stat);
42d41ddb 630
0e3e112e
MV
631 pkgRecords Recs(Cache);
632 pkgSourceList *SrcList = Cache.GetSourceList();
567785b9 633
d57f6084
DK
634 // reuse the usual acquire methods for deb files, but don't drop them into
635 // the usual directories - keep everything in the current directory
636 std::vector<std::string> storefile(verset.size());
637 std::string const cwd = SafeGetCWD();
638 _config->Set("Dir::Cache::Archives", cwd);
639 int i = 0;
8f3594c3 640 for (APT::VersionSet::const_iterator Ver = verset.begin();
d57f6084 641 Ver != verset.end(); ++Ver, ++i)
0e3e112e 642 {
d57f6084 643 pkgAcquire::Item *I = new pkgAcqArchive(&Fetcher, SrcList, &Recs, *Ver, storefile[i]);
03aa0847
DK
644 if (storefile[i].empty())
645 continue;
d57f6084
DK
646 std::string const filename = cwd + flNotDir(storefile[i]);
647 storefile[i].assign(filename);
648 I->DestFile.assign(filename);
0e3e112e
MV
649 }
650
42d41ddb
DK
651 // Just print out the uris and exit if the --print-uris flag was used
652 if (_config->FindB("APT::Get::Print-URIs") == true)
653 {
654 pkgAcquire::UriIterator I = Fetcher.UriBegin();
f7f0d6c7 655 for (; I != Fetcher.UriEnd(); ++I)
b0f4b486 656 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
42d41ddb
DK
657 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
658 return true;
659 }
660
460601d5
DK
661 // Disable drop-privs if "_apt" can not write to the target dir
662 CheckDropPrivsMustBeDisabled(Fetcher);
663
d57f6084
DK
664 if (_error->PendingError() == true || CheckAuth(Fetcher, false) == false)
665 return false;
666
667 bool Failed = false;
668 if (AcquireRun(Fetcher, 0, &Failed, NULL) == false)
669 return false;
670
671 // copy files in local sources to the current directory
672 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); ++I)
6ae22905
MV
673 {
674 std::string const filename = cwd + flNotDir((*I)->DestFile);
675 if ((*I)->Local == true &&
676 filename != (*I)->DestFile &&
677 (*I)->Status == pkgAcquire::Item::StatDone)
d57f6084 678 {
d57f6084
DK
679 std::ifstream src((*I)->DestFile.c_str(), std::ios::binary);
680 std::ofstream dst(filename.c_str(), std::ios::binary);
681 dst << src.rdbuf();
682 }
6ae22905 683 }
d57f6084 684 return Failed == false;
0e3e112e
MV
685}
686 /*}}}*/
0a8e3465
AL
687// DoCheck - Perform the check operation /*{{{*/
688// ---------------------------------------------------------------------
689/* Opening automatically checks the system, this command is mostly used
690 for debugging */
65512241 691static bool DoCheck(CommandLine &)
0a8e3465
AL
692{
693 CacheFile Cache;
694 Cache.Open();
2d11135a 695 Cache.CheckDeps();
0a8e3465
AL
696
697 return true;
698}
699 /*}}}*/
36375005
AL
700// DoSource - Fetch a source archive /*{{{*/
701// ---------------------------------------------------------------------
2d11135a 702/* Fetch souce packages */
fb0ee66e
AL
703struct DscFile
704{
705 string Package;
706 string Version;
707 string Dsc;
708};
709
c3ccac92 710static bool DoSource(CommandLine &CmdL)
36375005
AL
711{
712 CacheFile Cache;
2d11135a 713 if (Cache.Open(false) == false)
36375005
AL
714 return false;
715
2d11135a 716 if (CmdL.FileSize() <= 1)
b2e465d6 717 return _error->Error(_("Must specify at least one package to fetch source for"));
2d11135a 718
36375005 719 // Read the source list
1bb8cd67
DK
720 if (Cache.BuildSourceList() == false)
721 return false;
722 pkgSourceList *List = Cache.GetSourceList();
36375005
AL
723
724 // Create the text record parsers
765190e4
DK
725#if APT_PKG_ABI < 413
726 pkgRecords Recs(Cache);
727#endif
1bb8cd67 728 pkgSrcRecords SrcRecs(*List);
36375005
AL
729 if (_error->PendingError() == true)
730 return false;
731
732 // Create the download object
dfad5bee 733 AcqTextStatus Stat(std::cout, ScreenWidth,_config->FindI("quiet",0));
04a54261 734 pkgAcquire Fetcher(&Stat);
fb0ee66e 735
500dc070 736 SPtrArray<DscFile> Dsc = new DscFile[CmdL.FileSize()];
36375005 737
092ae175
MV
738 // insert all downloaded uris into this set to avoid downloading them
739 // twice
740 set<string> queued;
8545b536
DK
741
742 // Diff only mode only fetches .diff files
743 bool const diffOnly = _config->FindB("APT::Get::Diff-Only", false);
744 // Tar only mode only fetches .tar files
745 bool const tarOnly = _config->FindB("APT::Get::Tar-Only", false);
746 // Dsc only mode only fetches .dsc files
747 bool const dscOnly = _config->FindB("APT::Get::Dsc-Only", false);
748
36375005 749 // Load the requestd sources into the fetcher
fb0ee66e 750 unsigned J = 0;
a3f1d60c 751 std::string UntrustedList;
fb0ee66e 752 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
36375005
AL
753 {
754 string Src;
765190e4 755#if APT_PKG_ABI >= 413
a221efc3 756 pkgSrcRecords::Parser *Last = FindSrc(*I,SrcRecs,Src,Cache);
765190e4
DK
757#else
758 pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,Cache);
759#endif
6070a346 760 if (Last == 0) {
b2e465d6 761 return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
6070a346 762 }
a3f1d60c
MV
763
764 if (Last->Index().IsTrusted() == false)
765 UntrustedList += Src + " ";
36375005 766
3238423f
MV
767 string srec = Last->AsStr();
768 string::size_type pos = srec.find("\nVcs-");
774a6687 769 while (pos != string::npos)
3238423f
MV
770 {
771 pos += strlen("\nVcs-");
772 string vcs = srec.substr(pos,srec.find(":",pos)-pos);
774a6687
MV
773 if(vcs == "Browser")
774 {
775 pos = srec.find("\nVcs-", pos);
776 continue;
777 }
3238423f
MV
778 pos += vcs.length()+2;
779 string::size_type epos = srec.find("\n", pos);
780 string uri = srec.substr(pos,epos-pos).c_str();
b799e134 781 ioprintf(c1out, _("NOTICE: '%s' packaging is maintained in "
3238423f 782 "the '%s' version control system at:\n"
8756297c 783 "%s\n"),
3238423f
MV
784 Src.c_str(), vcs.c_str(), uri.c_str());
785 if(vcs == "Bzr")
927677f0 786 ioprintf(c1out,_("Please use:\n"
f3e3a2d4 787 "bzr branch %s\n"
3d513bbd 788 "to retrieve the latest (possibly unreleased) "
b799e134 789 "updates to the package.\n"),
3238423f 790 uri.c_str());
b799e134 791 break;
3238423f
MV
792 }
793
36375005 794 // Back track
3a2b39ee
DK
795 vector<pkgSrcRecords::File2> Lst;
796 if (Last->Files2(Lst) == false) {
36375005 797 return false;
6070a346 798 }
36375005
AL
799
800 // Load them into the fetcher
3a2b39ee 801 for (vector<pkgSrcRecords::File2>::const_iterator I = Lst.begin();
f7f0d6c7 802 I != Lst.end(); ++I)
36375005
AL
803 {
804 // Try to guess what sort of file it is we are getting.
b2e465d6 805 if (I->Type == "dsc")
fb0ee66e 806 {
fb0ee66e
AL
807 Dsc[J].Package = Last->Package();
808 Dsc[J].Version = Last->Version();
809 Dsc[J].Dsc = flNotDir(I->Path);
810 }
092ae175 811
8545b536
DK
812 // Handle the only options so that multiple can be used at once
813 if (diffOnly == true || tarOnly == true || dscOnly == true)
814 {
815 if ((diffOnly == true && I->Type == "diff") ||
816 (tarOnly == true && I->Type == "tar") ||
817 (dscOnly == true && I->Type == "dsc"))
818 ; // Fine, we want this file downloaded
819 else
820 continue;
821 }
1979e742 822
092ae175
MV
823 // don't download the same uri twice (should this be moved to
824 // the fetcher interface itself?)
825 if(queued.find(Last->Index().ArchiveURI(I->Path)) != queued.end())
826 continue;
827 queued.insert(Last->Index().ArchiveURI(I->Path));
cb6a2b3e 828
092ae175 829 // check if we have a file with that md5 sum already localy
1262d358
DK
830 std::string localFile = flNotDir(I->Path);
831 if (FileExists(localFile) == true)
832 if(I->Hashes.VerifyFile(localFile) == true)
092ae175 833 {
443cb67c 834 ioprintf(c1out,_("Skipping already downloaded file '%s'\n"),
1262d358 835 localFile.c_str());
092ae175
MV
836 continue;
837 }
1262d358
DK
838
839 // see if we have a hash (Acquire::ForceHash is the only way to have none)
b3501edb 840 if (I->Hashes.usable() == false && _config->FindB("APT::Get::AllowUnauthenticated",false) == false)
1262d358
DK
841 {
842 ioprintf(c1out, "Skipping download of file '%s' as requested hashsum is not available for authentication\n",
843 localFile.c_str());
844 continue;
092ae175
MV
845 }
846
b2e465d6 847 new pkgAcqFile(&Fetcher,Last->Index().ArchiveURI(I->Path),
d61960d9 848 I->Hashes, I->FileSize, Last->Index().SourceInfo(*Last,*I), Src);
36375005
AL
849 }
850 }
a3f1d60c 851
36375005 852 // Display statistics
3a882565
DK
853 unsigned long long FetchBytes = Fetcher.FetchNeeded();
854 unsigned long long FetchPBytes = Fetcher.PartialPresent();
855 unsigned long long DebBytes = Fetcher.TotalNeeded();
36375005 856
9c81f8de
DK
857 if (CheckFreeSpaceBeforeDownload(".", (FetchBytes - FetchPBytes)) == false)
858 return false;
859
36375005 860 // Number of bytes
36375005 861 if (DebBytes != FetchBytes)
4d8d8112
DK
862 //TRANSLATOR: The required space between number and unit is already included
863 // in the replacement strings, so %sB will be correctly translate in e.g. 1,5 MB
b2e465d6
AL
864 ioprintf(c1out,_("Need to get %sB/%sB of source archives.\n"),
865 SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
36375005 866 else
4d8d8112
DK
867 //TRANSLATOR: The required space between number and unit is already included
868 // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
b2e465d6
AL
869 ioprintf(c1out,_("Need to get %sB of source archives.\n"),
870 SizeToStr(DebBytes).c_str());
871
2c0c53b3
AL
872 if (_config->FindB("APT::Get::Simulate",false) == true)
873 {
874 for (unsigned I = 0; I != J; I++)
db0db9fe 875 ioprintf(cout,_("Fetch source %s\n"),Dsc[I].Package.c_str());
2c0c53b3
AL
876 return true;
877 }
460601d5 878
36375005
AL
879 // Just print out the uris an exit if the --print-uris flag was used
880 if (_config->FindB("APT::Get::Print-URIs") == true)
881 {
882 pkgAcquire::UriIterator I = Fetcher.UriBegin();
f7f0d6c7 883 for (; I != Fetcher.UriEnd(); ++I)
36375005 884 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
495e5cb2 885 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
36375005
AL
886 return true;
887 }
36375005 888
460601d5
DK
889 // Disable drop-privs if "_apt" can not write to the target dir
890 CheckDropPrivsMustBeDisabled(Fetcher);
891
892 // check authentication status of the source as well
893 if (UntrustedList != "" && !AuthPrompt(UntrustedList, false))
894 return false;
895
866893a6 896 // Run it
fb0ee66e 897 bool Failed = false;
866893a6 898 if (AcquireRun(Fetcher, 0, &Failed, NULL) == false || Failed == true)
6070a346 899 {
b2e465d6 900 return _error->Error(_("Failed to fetch some archives."));
6070a346
DK
901 }
902
fb0ee66e 903 if (_config->FindB("APT::Get::Download-only",false) == true)
b2e465d6
AL
904 {
905 c1out << _("Download complete and in download only mode") << endl;
fb0ee66e 906 return true;
b2e465d6
AL
907 }
908
fb0ee66e 909 // Unpack the sources
54676e1a
AL
910 pid_t Process = ExecFork();
911
912 if (Process == 0)
fb0ee66e 913 {
827d04d3 914 bool const fixBroken = _config->FindB("APT::Get::Fix-Broken", false);
f7f0d6c7 915 for (unsigned I = 0; I != J; ++I)
fb0ee66e 916 {
b2e465d6 917 string Dir = Dsc[I].Package + '-' + Cache->VS().UpstreamVersion(Dsc[I].Version.c_str());
fb0ee66e 918
17c0e8e1
AL
919 // Diff only mode only fetches .diff files
920 if (_config->FindB("APT::Get::Diff-Only",false) == true ||
a3eaf954
AL
921 _config->FindB("APT::Get::Tar-Only",false) == true ||
922 Dsc[I].Dsc.empty() == true)
17c0e8e1 923 continue;
a3eaf954 924
54676e1a
AL
925 // See if the package is already unpacked
926 struct stat Stat;
827d04d3 927 if (fixBroken == false && stat(Dir.c_str(),&Stat) == 0 &&
54676e1a
AL
928 S_ISDIR(Stat.st_mode) != 0)
929 {
b2e465d6
AL
930 ioprintf(c0out ,_("Skipping unpack of already unpacked source in %s\n"),
931 Dir.c_str());
54676e1a
AL
932 }
933 else
934 {
935 // Call dpkg-source
c53cf70d
DK
936 std::string const sourceopts = _config->Find("DPkg::Source-Options", "-x");
937 std::string S;
938 strprintf(S, "%s %s %s",
54676e1a 939 _config->Find("Dir::Bin::dpkg-source","dpkg-source").c_str(),
c53cf70d
DK
940 sourceopts.c_str(), Dsc[I].Dsc.c_str());
941 if (system(S.c_str()) != 0)
54676e1a 942 {
c53cf70d
DK
943 fprintf(stderr, _("Unpack command '%s' failed.\n"), S.c_str());
944 fprintf(stderr, _("Check if the 'dpkg-dev' package is installed.\n"));
54676e1a 945 _exit(1);
c53cf70d 946 }
54676e1a 947 }
c53cf70d 948
54676e1a
AL
949 // Try to compile it with dpkg-buildpackage
950 if (_config->FindB("APT::Get::Compile",false) == true)
951 {
234675b7
DK
952 string buildopts = _config->Find("APT::Get::Host-Architecture");
953 if (buildopts.empty() == false)
c5102538 954 buildopts = "-a" + buildopts + " ";
ce7f128c
DK
955
956 // get all active build profiles
957 std::string const profiles = APT::Configuration::getBuildProfilesString();
958 if (profiles.empty() == false)
959 buildopts.append(" -P").append(profiles).append(" ");
960
234675b7
DK
961 buildopts.append(_config->Find("DPkg::Build-Options","-b -uc"));
962
54676e1a 963 // Call dpkg-buildpackage
c53cf70d
DK
964 std::string S;
965 strprintf(S, "cd %s && %s %s",
54676e1a
AL
966 Dir.c_str(),
967 _config->Find("Dir::Bin::dpkg-buildpackage","dpkg-buildpackage").c_str(),
234675b7 968 buildopts.c_str());
c53cf70d
DK
969
970 if (system(S.c_str()) != 0)
54676e1a 971 {
c53cf70d 972 fprintf(stderr, _("Build command '%s' failed.\n"), S.c_str());
54676e1a 973 _exit(1);
c53cf70d
DK
974 }
975 }
54676e1a 976 }
c53cf70d 977
54676e1a
AL
978 _exit(0);
979 }
3a4477a4 980
54676e1a
AL
981 // Wait for the subprocess
982 int Status = 0;
983 while (waitpid(Process,&Status,0) != Process)
984 {
985 if (errno == EINTR)
986 continue;
987 return _error->Errno("waitpid","Couldn't wait for subprocess");
988 }
989
990 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
b2e465d6
AL
991 return _error->Error(_("Child process failed"));
992
993 return true;
994}
995 /*}}}*/
996// DoBuildDep - Install/removes packages to satisfy build dependencies /*{{{*/
997// ---------------------------------------------------------------------
998/* This function will look at the build depends list of the given source
999 package and install the necessary packages to make it true, or fail. */
c3ccac92 1000static bool DoBuildDep(CommandLine &CmdL)
b2e465d6
AL
1001{
1002 CacheFile Cache;
35180212
JAK
1003
1004 _config->Set("APT::Install-Recommends", false);
1005
b2e465d6
AL
1006 if (Cache.Open(true) == false)
1007 return false;
1008
1009 if (CmdL.FileSize() <= 1)
1010 return _error->Error(_("Must specify at least one package to check builddeps for"));
1011
1012 // Read the source list
1bb8cd67
DK
1013 if (Cache.BuildSourceList() == false)
1014 return false;
1015 pkgSourceList *List = Cache.GetSourceList();
54676e1a 1016
b2e465d6 1017 // Create the text record parsers
765190e4
DK
1018#if APT_PKG_ABI < 413
1019 pkgRecords Recs(Cache);
1020#endif
1bb8cd67 1021 pkgSrcRecords SrcRecs(*List);
b2e465d6
AL
1022 if (_error->PendingError() == true)
1023 return false;
1024
234675b7
DK
1025 bool StripMultiArch;
1026 string hostArch = _config->Find("APT::Get::Host-Architecture");
1027 if (hostArch.empty() == false)
1028 {
1029 std::vector<std::string> archs = APT::Configuration::getArchitectures();
1030 if (std::find(archs.begin(), archs.end(), hostArch) == archs.end())
1031 return _error->Error(_("No architecture information available for %s. See apt.conf(5) APT::Architectures for setup"), hostArch.c_str());
1032 StripMultiArch = false;
1033 }
1034 else
1035 StripMultiArch = true;
1036
b2e465d6
AL
1037 unsigned J = 0;
1038 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
1039 {
1040 string Src;
feab34c5 1041 pkgSrcRecords::Parser *Last = 0;
feab34c5 1042
a5bb5e1e
MV
1043 // an unpacked debian source tree
1044 using APT::String::Startswith;
1045 if ((Startswith(*I, "./") || Startswith(*I, "/")) &&
1046 DirectoryExists(*I))
77da39b9 1047 {
a5bb5e1e 1048 ioprintf(c1out, _("Note, using directory '%s' to get the build dependencies\n"), *I);
77da39b9
MV
1049 // FIXME: how can we make this more elegant?
1050 std::string TypeName = "debian/control File Source Index";
1051 pkgIndexFile::Type *Type = pkgIndexFile::Type::GetType(TypeName.c_str());
1052 if(Type != NULL)
1053 Last = Type->CreateSrcPkgParser(*I);
1054 }
a49e7948 1055 // if its a local file (e.g. .dsc) use this
77da39b9 1056 else if (FileExists(*I))
feab34c5 1057 {
a5bb5e1e
MV
1058 ioprintf(c1out, _("Note, using file '%s' to get the build dependencies\n"), *I);
1059
a49e7948
MV
1060 // see if we can get a parser for this pkgIndexFile type
1061 string TypeName = flExtension(*I) + " File Source Index";
1062 pkgIndexFile::Type *Type = pkgIndexFile::Type::GetType(TypeName.c_str());
1063 if(Type != NULL)
1064 Last = Type->CreateSrcPkgParser(*I);
feab34c5 1065 } else {
a49e7948 1066 // normal case, search the cache for the source file
765190e4
DK
1067#if APT_PKG_ABI >= 413
1068 Last = FindSrc(*I,SrcRecs,Src,Cache);
1069#else
1070 Last = FindSrc(*I,Recs,SrcRecs,Src,Cache);
1071#endif
feab34c5 1072 }
a49e7948 1073
b2e465d6
AL
1074 if (Last == 0)
1075 return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
1076
1077 // Process the build-dependencies
1078 vector<pkgSrcRecords::Parser::BuildDepRec> BuildDeps;
65f99834
DK
1079 // FIXME: Can't specify architecture to use for [wildcard] matching, so switch default arch temporary
1080 if (hostArch.empty() == false)
1081 {
1082 std::string nativeArch = _config->Find("APT::Architecture");
1083 _config->Set("APT::Architecture", hostArch);
1084 bool Success = Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only", false), StripMultiArch);
1085 _config->Set("APT::Architecture", nativeArch);
1086 if (Success == false)
1087 return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
1088 }
1089 else if (Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only", false), StripMultiArch) == false)
1090 return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
feab34c5 1091
7d6f9f8f
AL
1092 // Also ensure that build-essential packages are present
1093 Configuration::Item const *Opts = _config->Tree("APT::Build-Essential");
1094 if (Opts)
1095 Opts = Opts->Child;
1096 for (; Opts; Opts = Opts->Next)
1097 {
1098 if (Opts->Value.empty() == true)
1099 continue;
1100
1101 pkgSrcRecords::Parser::BuildDepRec rec;
1102 rec.Package = Opts->Value;
1103 rec.Type = pkgSrcRecords::Parser::BuildDependIndep;
1104 rec.Op = 0;
58d76831 1105 BuildDeps.push_back(rec);
7d6f9f8f
AL
1106 }
1107
f7f0d6c7 1108 if (BuildDeps.empty() == true)
b2e465d6
AL
1109 {
1110 ioprintf(c1out,_("%s has no build depends.\n"),Src.c_str());
1111 continue;
1112 }
234675b7 1113
b2e465d6 1114 // Install the requested packages
b2e465d6
AL
1115 vector <pkgSrcRecords::Parser::BuildDepRec>::iterator D;
1116 pkgProblemResolver Fix(Cache);
58d76831 1117 bool skipAlternatives = false; // skip remaining alternatives in an or group
f7f0d6c7 1118 for (D = BuildDeps.begin(); D != BuildDeps.end(); ++D)
b2e465d6 1119 {
58d76831
AL
1120 bool hasAlternatives = (((*D).Op & pkgCache::Dep::Or) == pkgCache::Dep::Or);
1121
1122 if (skipAlternatives == true)
1123 {
3fdb6f83
DK
1124 /*
1125 * if there are alternatives, we've already picked one, so skip
1126 * the rest
1127 *
1128 * TODO: this means that if there's a build-dep on A|B and B is
1129 * installed, we'll still try to install A; more importantly,
1130 * if A is currently broken, we cannot go back and try B. To fix
1131 * this would require we do a Resolve cycle for each package we
1132 * add to the install list. Ugh
1133 */
58d76831
AL
1134 if (!hasAlternatives)
1135 skipAlternatives = false; // end of or group
1136 continue;
1137 }
1138
aa2d22be
AL
1139 if ((*D).Type == pkgSrcRecords::Parser::BuildConflict ||
1140 (*D).Type == pkgSrcRecords::Parser::BuildConflictIndep)
d3fc0061 1141 {
e3a86238 1142 pkgCache::GrpIterator Grp = Cache->FindGrp((*D).Package);
aa2d22be 1143 // Build-conflicts on unknown packages are silently ignored
e3a86238 1144 if (Grp.end() == true)
aa2d22be
AL
1145 continue;
1146
e3a86238
DK
1147 for (pkgCache::PkgIterator Pkg = Grp.PackageList(); Pkg.end() == false; Pkg = Grp.NextPkg(Pkg))
1148 {
1149 pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
1150 /*
1151 * Remove if we have an installed version that satisfies the
1152 * version criteria
1153 */
1154 if (IV.end() == false &&
1155 Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
1156 TryToInstallBuildDep(Pkg,Cache,Fix,true,false);
1157 }
d3fc0061 1158 }
aa2d22be
AL
1159 else // BuildDep || BuildDepIndep
1160 {
58d76831
AL
1161 if (_config->FindB("Debug::BuildDeps",false) == true)
1162 cout << "Looking for " << (*D).Package << "...\n";
1163
234675b7
DK
1164 pkgCache::PkgIterator Pkg;
1165
1166 // Cross-Building?
c307a4f0 1167 if (StripMultiArch == false && D->Type != pkgSrcRecords::Parser::BuildDependIndep)
234675b7
DK
1168 {
1169 size_t const colon = D->Package.find(":");
666faa35
DK
1170 if (colon != string::npos)
1171 {
1172 if (strcmp(D->Package.c_str() + colon, ":any") == 0 || strcmp(D->Package.c_str() + colon, ":native") == 0)
1173 Pkg = Cache->FindPkg(D->Package.substr(0,colon));
1174 else
1175 Pkg = Cache->FindPkg(D->Package);
1176 }
234675b7 1177 else
666faa35 1178 Pkg = Cache->FindPkg(D->Package, hostArch);
234675b7 1179
234675b7 1180 // a bad version either is invalid or doesn't satify dependency
d5dea0be
DK
1181 #define BADVER(Ver) (Ver.end() == true || \
1182 (D->Version.empty() == false && \
1183 Cache->VS().CheckDep(Ver.VerStr(),D->Op,D->Version.c_str()) == false))
234675b7 1184
d5dea0be 1185 APT::VersionList verlist;
234675b7
DK
1186 if (Pkg.end() == false)
1187 {
d5dea0be
DK
1188 pkgCache::VerIterator Ver = (*Cache)[Pkg].InstVerIter(*Cache);
1189 if (BADVER(Ver) == false)
1190 verlist.insert(Ver);
1191 Ver = (*Cache)[Pkg].CandidateVerIter(*Cache);
1192 if (BADVER(Ver) == false)
1193 verlist.insert(Ver);
234675b7 1194 }
d5dea0be 1195 if (verlist.empty() == true)
234675b7 1196 {
666faa35
DK
1197 pkgCache::PkgIterator BuildPkg = Cache->FindPkg(D->Package, "native");
1198 if (BuildPkg.end() == false && Pkg != BuildPkg)
234675b7 1199 {
666faa35 1200 pkgCache::VerIterator Ver = (*Cache)[BuildPkg].InstVerIter(*Cache);
d5dea0be
DK
1201 if (BADVER(Ver) == false)
1202 verlist.insert(Ver);
666faa35 1203 Ver = (*Cache)[BuildPkg].CandidateVerIter(*Cache);
d5dea0be
DK
1204 if (BADVER(Ver) == false)
1205 verlist.insert(Ver);
234675b7
DK
1206 }
1207 }
d5dea0be
DK
1208 #undef BADVER
1209
1210 string forbidden;
1211 // We need to decide if host or build arch, so find a version we can look at
1212 APT::VersionList::const_iterator Ver = verlist.begin();
1213 for (; Ver != verlist.end(); ++Ver)
234675b7 1214 {
d5dea0be 1215 forbidden.clear();
737c7a7b
SL
1216 if (Ver->MultiArch == pkgCache::Version::None || Ver->MultiArch == pkgCache::Version::All)
1217 {
1218 if (colon == string::npos)
737c7a7b 1219 Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
a9a370d9
TG
1220 else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
1221 forbidden = "Multi-Arch: none";
666faa35
DK
1222 else if (strcmp(D->Package.c_str() + colon, ":native") == 0)
1223 Pkg = Ver.ParentPkg().Group().FindPkg("native");
737c7a7b 1224 }
234675b7
DK
1225 else if (Ver->MultiArch == pkgCache::Version::Same)
1226 {
737c7a7b 1227 if (colon == string::npos)
234675b7
DK
1228 Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
1229 else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
1230 forbidden = "Multi-Arch: same";
666faa35
DK
1231 else if (strcmp(D->Package.c_str() + colon, ":native") == 0)
1232 Pkg = Ver.ParentPkg().Group().FindPkg("native");
234675b7 1233 }
2a2a7ef4 1234 else if ((Ver->MultiArch & pkgCache::Version::Foreign) == pkgCache::Version::Foreign)
234675b7 1235 {
666faa35
DK
1236 if (colon == string::npos)
1237 Pkg = Ver.ParentPkg().Group().FindPkg("native");
1238 else if (strcmp(D->Package.c_str() + colon, ":any") == 0 ||
1239 strcmp(D->Package.c_str() + colon, ":native") == 0)
234675b7
DK
1240 forbidden = "Multi-Arch: foreign";
1241 }
2a2a7ef4 1242 else if ((Ver->MultiArch & pkgCache::Version::Allowed) == pkgCache::Version::Allowed)
234675b7
DK
1243 {
1244 if (colon == string::npos)
1245 Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
1246 else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
1247 {
1248 // prefer any installed over preferred non-installed architectures
1249 pkgCache::GrpIterator Grp = Ver.ParentPkg().Group();
1250 // we don't check for version here as we are better of with upgrading than remove and install
1251 for (Pkg = Grp.PackageList(); Pkg.end() == false; Pkg = Grp.NextPkg(Pkg))
1252 if (Pkg.CurrentVer().end() == false)
1253 break;
1254 if (Pkg.end() == true)
1255 Pkg = Grp.FindPreferredPkg(true);
1256 }
666faa35
DK
1257 else if (strcmp(D->Package.c_str() + colon, ":native") == 0)
1258 Pkg = Ver.ParentPkg().Group().FindPkg("native");
234675b7 1259 }
d5dea0be 1260
234675b7
DK
1261 if (forbidden.empty() == false)
1262 {
1263 if (_config->FindB("Debug::BuildDeps",false) == true)
d5dea0be
DK
1264 cout << D->Package.substr(colon, string::npos) << " is not allowed from " << forbidden << " package " << (*D).Package << " (" << Ver.VerStr() << ")" << endl;
1265 continue;
1266 }
1267
1268 //we found a good version
1269 break;
1270 }
1271 if (Ver == verlist.end())
1272 {
1273 if (_config->FindB("Debug::BuildDeps",false) == true)
1274 cout << " No multiarch info as we have no satisfying installed nor candidate for " << D->Package << " on build or host arch" << endl;
1275
1276 if (forbidden.empty() == false)
1277 {
234675b7
DK
1278 if (hasAlternatives)
1279 continue;
1280 return _error->Error(_("%s dependency for %s can't be satisfied "
1281 "because %s is not allowed on '%s' packages"),
1282 Last->BuildDepType(D->Type), Src.c_str(),
a9a370d9 1283 D->Package.c_str(), forbidden.c_str());
234675b7
DK
1284 }
1285 }
234675b7
DK
1286 }
1287 else
1288 Pkg = Cache->FindPkg(D->Package);
1289
727d8712 1290 if (Pkg.end() == true || (Pkg->VersionList == 0 && Pkg->ProvidesList == 0))
aa2d22be 1291 {
58d76831
AL
1292 if (_config->FindB("Debug::BuildDeps",false) == true)
1293 cout << " (not found)" << (*D).Package << endl;
1294
1295 if (hasAlternatives)
1296 continue;
1297
1298 return _error->Error(_("%s dependency for %s cannot be satisfied "
1299 "because the package %s cannot be found"),
1300 Last->BuildDepType((*D).Type),Src.c_str(),
1301 (*D).Package.c_str());
aa2d22be
AL
1302 }
1303
e5002e30 1304 pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
91bee655
DK
1305 if (IV.end() == false)
1306 {
1307 if (_config->FindB("Debug::BuildDeps",false) == true)
1308 cout << " Is installed\n";
e5002e30 1309
91bee655
DK
1310 if (D->Version.empty() == true ||
1311 Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
1312 {
1313 skipAlternatives = hasAlternatives;
1314 continue;
1315 }
cfa5659c 1316
91bee655
DK
1317 if (_config->FindB("Debug::BuildDeps",false) == true)
1318 cout << " ...but the installed version doesn't meet the version requirement\n";
58d76831 1319
91bee655
DK
1320 if (((*D).Op & pkgCache::Dep::LessEq) == pkgCache::Dep::LessEq)
1321 return _error->Error(_("Failed to satisfy %s dependency for %s: Installed package %s is too new"),
1322 Last->BuildDepType((*D).Type), Src.c_str(), Pkg.FullName(true).c_str());
1323 }
58d76831 1324
fe027879
DK
1325 // Only consider virtual packages if there is no versioned dependency
1326 if ((*D).Version.empty() == true)
1327 {
1328 /*
1329 * If this is a virtual package, we need to check the list of
1330 * packages that provide it and see if any of those are
1331 * installed
1332 */
1333 pkgCache::PrvIterator Prv = Pkg.ProvidesList();
f7f0d6c7 1334 for (; Prv.end() != true; ++Prv)
fe027879
DK
1335 {
1336 if (_config->FindB("Debug::BuildDeps",false) == true)
1337 cout << " Checking provider " << Prv.OwnerPkg().FullName() << endl;
58d76831 1338
fe027879
DK
1339 if ((*Cache)[Prv.OwnerPkg()].InstVerIter(*Cache).end() == false)
1340 break;
1341 }
58d76831 1342
fe027879
DK
1343 if (Prv.end() == false)
1344 {
1345 if (_config->FindB("Debug::BuildDeps",false) == true)
1346 cout << " Is provided by installed package " << Prv.OwnerPkg().FullName() << endl;
1347 skipAlternatives = hasAlternatives;
1348 continue;
1349 }
1350 }
2baf02ca
DK
1351 else // versioned dependency
1352 {
1353 pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
1354 if (CV.end() == true ||
1355 Cache->VS().CheckDep(CV.VerStr(),(*D).Op,(*D).Version.c_str()) == false)
1356 {
1357 if (hasAlternatives)
1358 continue;
1359 else if (CV.end() == false)
1360 return _error->Error(_("%s dependency for %s cannot be satisfied "
1361 "because candidate version of package %s "
1362 "can't satisfy version requirements"),
1363 Last->BuildDepType(D->Type), Src.c_str(),
1364 D->Package.c_str());
1365 else
1366 return _error->Error(_("%s dependency for %s cannot be satisfied "
1367 "because package %s has no candidate version"),
1368 Last->BuildDepType(D->Type), Src.c_str(),
1369 D->Package.c_str());
1370 }
1371 }
58d76831 1372
f1f874bd 1373 if (TryToInstallBuildDep(Pkg,Cache,Fix,false,false,false) == true)
58d76831
AL
1374 {
1375 // We successfully installed something; skip remaining alternatives
1376 skipAlternatives = hasAlternatives;
d59228b0 1377 if(_config->FindB("APT::Get::Build-Dep-Automatic", false) == true)
496a05c6 1378 Cache->MarkAuto(Pkg, true);
58d76831
AL
1379 continue;
1380 }
1381 else if (hasAlternatives)
1382 {
1383 if (_config->FindB("Debug::BuildDeps",false) == true)
1384 cout << " Unsatisfiable, trying alternatives\n";
1385 continue;
1386 }
1387 else
1388 {
1389 return _error->Error(_("Failed to satisfy %s dependency for %s: %s"),
1390 Last->BuildDepType((*D).Type),
1391 Src.c_str(),
1392 (*D).Package.c_str());
1393 }
b2e465d6
AL
1394 }
1395 }
f3c736f9 1396
b2e465d6
AL
1397 if (Fix.Resolve(true) == false)
1398 _error->Discard();
1399
1400 // Now we check the state of the packages,
1401 if (Cache->BrokenCount() != 0)
0dae8ac5
DK
1402 {
1403 ShowBroken(cout, Cache, false);
1404 return _error->Error(_("Build-dependencies for %s could not be satisfied."),*I);
1405 }
b2e465d6
AL
1406 }
1407
1408 if (InstallPackages(Cache, false, true) == false)
1409 return _error->Error(_("Failed to process build dependencies"));
36375005
AL
1410 return true;
1411}
1412 /*}}}*/
a53b07bb
MV
1413// GetChangelogPath - return a path pointing to a changelog file or dir /*{{{*/
1414// ---------------------------------------------------------------------
1415/* This returns a "path" string for the changelog url construction.
1416 * Please note that its not complete, it either needs a "/changelog"
1417 * appended (for the packages.debian.org/changelogs site) or a
1418 * ".changelog" (for third party sites that store the changelog in the
1419 * pool/ next to the deb itself)
1420 * Example return: "pool/main/a/apt/apt_0.8.8ubuntu3"
1421 */
a221efc3 1422static string GetChangelogPath(CacheFile &Cache,
a53b07bb
MV
1423 pkgCache::VerIterator Ver)
1424{
a53b07bb
MV
1425 pkgRecords Recs(Cache);
1426 pkgRecords::Parser &rec=Recs.Lookup(Ver.FileList());
a221efc3 1427 string path = flNotFile(rec.FileName());
765190e4 1428#if APT_PKG_ABI >= 413
a221efc3
DK
1429 path.append(Ver.SourcePkgName());
1430 path.append("_");
1431 path.append(StripEpoch(Ver.SourceVerStr()));
765190e4
DK
1432#else
1433 string srcpkg = rec.SourcePkg().empty() ? Ver.ParentPkg().Name() : rec.SourcePkg();
1434 string ver = Ver.VerStr();
1435 // if there is a source version it always wins
1436 if (rec.SourceVer() != "")
1437 ver = rec.SourceVer();
1438 path += srcpkg + "_" + StripEpoch(ver);
1439#endif
a53b07bb
MV
1440 return path;
1441}
1442 /*}}}*/
cdb9307c
MV
1443// GuessThirdPartyChangelogUri - return url /*{{{*/
1444// ---------------------------------------------------------------------
a53b07bb
MV
1445/* Contruct a changelog file path for third party sites that do not use
1446 * packages.debian.org/changelogs
1447 * This simply uses the ArchiveURI() of the source pkg and looks for
1448 * a .changelog file there, Example for "mediabuntu":
1449 * apt-get changelog mplayer-doc:
1450 * http://packages.medibuntu.org/pool/non-free/m/mplayer/mplayer_1.0~rc4~try1.dsfg1-1ubuntu1+medibuntu1.changelog
1451 */
c3ccac92 1452static bool GuessThirdPartyChangelogUri(CacheFile &Cache,
cdb9307c
MV
1453 pkgCache::VerIterator Ver,
1454 string &out_uri)
1455{
cdb9307c 1456 // get the binary deb server path
cdb9307c
MV
1457 pkgCache::VerFileIterator Vf = Ver.FileList();
1458 if (Vf.end() == true)
1459 return false;
1460 pkgCache::PkgFileIterator F = Vf.File();
1461 pkgIndexFile *index;
a53b07bb 1462 pkgSourceList *SrcList = Cache.GetSourceList();
cdb9307c
MV
1463 if(SrcList->FindIndex(F, index) == false)
1464 return false;
a53b07bb 1465
cdb9307c 1466 // get archive uri for the binary deb
a221efc3 1467 string path_without_dot_changelog = GetChangelogPath(Cache, Ver);
a53b07bb 1468 out_uri = index->ArchiveURI(path_without_dot_changelog + ".changelog");
cdb9307c
MV
1469
1470 // now strip away the filename and add srcpkg_srcver.changelog
cdb9307c
MV
1471 return true;
1472}
fcb144b9 1473 /*}}}*/
a4c40430
MV
1474// DownloadChangelog - Download the changelog /*{{{*/
1475// ---------------------------------------------------------------------
c3ccac92 1476static bool DownloadChangelog(CacheFile &CacheFile, pkgAcquire &Fetcher,
a53b07bb
MV
1477 pkgCache::VerIterator Ver, string targetfile)
1478/* Download a changelog file for the given package version to
1479 * targetfile. This will first try the server from Apt::Changelogs::Server
1480 * (http://packages.debian.org/changelogs by default) and if that gives
1481 * a 404 tries to get it from the archive directly (see
1482 * GuessThirdPartyChangelogUri for details how)
1483 */
a4c40430 1484{
a53b07bb 1485 // make the server root configurable
a221efc3 1486 string const server = _config->Find("Apt::Changelogs::Server",
a53b07bb 1487 "http://packages.debian.org/changelogs");
a221efc3
DK
1488 string const path = GetChangelogPath(CacheFile, Ver);
1489 string changelog_uri;
03aa0847
DK
1490 if (APT::String::Endswith(server, "/") == true)
1491 strprintf(changelog_uri, "%s%s/changelog", server.c_str(), path.c_str());
1492 else
1493 strprintf(changelog_uri, "%s/%s/changelog", server.c_str(), path.c_str());
fcb144b9
DK
1494 if (_config->FindB("APT::Get::Print-URIs", false) == true)
1495 {
1496 std::cout << '\'' << changelog_uri << '\'' << std::endl;
1497 return true;
1498 }
a221efc3 1499 pkgCache::PkgIterator const Pkg = Ver.ParentPkg();
fcb144b9 1500
a221efc3 1501 string descr;
88573174 1502 strprintf(descr, _("Changelog for %s (%s)"), Pkg.Name(), changelog_uri.c_str());
a53b07bb 1503 // queue it
03aa0847 1504 pkgAcquire::Item const * itm = new pkgAcqFile(&Fetcher, changelog_uri, "", 0, descr, Pkg.Name(), "ignored", targetfile);
d786352d 1505
460601d5
DK
1506 // Disable drop-privs if "_apt" can not write to the target dir
1507 CheckDropPrivsMustBeDisabled(Fetcher);
1508
fcb144b9
DK
1509 // try downloading it, if that fails, try third-party-changelogs location
1510 // FIXME: Fetcher.Run() is "Continue" even if I get a 404?!?
1511 Fetcher.Run();
03aa0847 1512 if (itm->Status != pkgAcquire::Item::StatDone)
cdb9307c
MV
1513 {
1514 string third_party_uri;
a221efc3 1515 if (GuessThirdPartyChangelogUri(CacheFile, Ver, third_party_uri))
cdb9307c 1516 {
88573174 1517 strprintf(descr, _("Changelog for %s (%s)"), Pkg.Name(), third_party_uri.c_str());
03aa0847 1518 itm = new pkgAcqFile(&Fetcher, third_party_uri, "", 0, descr, Pkg.Name(), "ignored", targetfile);
fcb144b9 1519 Fetcher.Run();
cdb9307c
MV
1520 }
1521 }
4a6fe09c 1522
03aa0847 1523 if (itm->Status == pkgAcquire::Item::StatDone)
18ae8b29 1524 return true;
a4c40430
MV
1525
1526 // error
18ae8b29 1527 return _error->Error("changelog download failed");
a4c40430
MV
1528}
1529 /*}}}*/
a4c40430
MV
1530// DoChangelog - Get changelog from the command line /*{{{*/
1531// ---------------------------------------------------------------------
c3ccac92 1532static bool DoChangelog(CommandLine &CmdL)
a4c40430
MV
1533{
1534 CacheFile Cache;
1535 if (Cache.ReadOnlyOpen() == false)
1536 return false;
1537
353c135e 1538 APT::CacheSetHelper helper;
c4cca791 1539 APT::VersionList verset = APT::VersionList::FromCommandLine(Cache,
43acd019 1540 CmdL.FileList + 1, APT::CacheSetHelper::CANDIDATE, helper);
72dd5bec
DK
1541 if (verset.empty() == true)
1542 return false;
a4c40430 1543 pkgAcquire Fetcher;
fcb144b9
DK
1544
1545 if (_config->FindB("APT::Get::Print-URIs", false) == true)
a98b6615
DH
1546 {
1547 bool Success = true;
c4cca791 1548 for (APT::VersionList::const_iterator Ver = verset.begin();
fcb144b9 1549 Ver != verset.end(); ++Ver)
a98b6615
DH
1550 Success &= DownloadChangelog(Cache, Fetcher, Ver, "");
1551 return Success;
1552 }
fcb144b9 1553
dfad5bee 1554 AcqTextStatus Stat(std::cout, ScreenWidth,_config->FindI("quiet",0));
04a54261 1555 Fetcher.SetLog(&Stat);
a4c40430 1556
72dd5bec
DK
1557 bool const downOnly = _config->FindB("APT::Get::Download-Only", false);
1558
1559 char tmpname[100];
68e01721 1560 const char* tmpdir = NULL;
72dd5bec
DK
1561 if (downOnly == false)
1562 {
68e01721
MV
1563 std::string systemTemp = GetTempDir();
1564 snprintf(tmpname, sizeof(tmpname), "%s/apt-changelog-XXXXXX",
1565 systemTemp.c_str());
72dd5bec
DK
1566 tmpdir = mkdtemp(tmpname);
1567 if (tmpdir == NULL)
1568 return _error->Errno("mkdtemp", "mkdtemp failed");
03aa0847
DK
1569
1570 std::string const SandboxUser = _config->Find("APT::Sandbox::User");
1571 if (getuid() == 0 && SandboxUser.empty() == false) // if we aren't root, we can't chown, so don't try it
1572 {
1573 struct passwd const * const pw = getpwnam(SandboxUser.c_str());
1574 struct group const * const gr = getgrnam("root");
1575 if (pw != NULL && gr != NULL)
1576 {
1577 // chown the tmp dir directory we use to the sandbox user
1578 if(chown(tmpdir, pw->pw_uid, gr->gr_gid) != 0)
1579 _error->WarningE("DoChangelog", "chown to %s:%s of directory %s failed", SandboxUser.c_str(), "root", tmpdir);
1580 }
1581 }
18ae8b29 1582 }
72dd5bec 1583
c4cca791 1584 for (APT::VersionList::const_iterator Ver = verset.begin();
a4c40430
MV
1585 Ver != verset.end();
1586 ++Ver)
1587 {
72dd5bec
DK
1588 string changelogfile;
1589 if (downOnly == false)
339bc464 1590 changelogfile.append(tmpname).append("/changelog");
72dd5bec
DK
1591 else
1592 changelogfile.append(Ver.ParentPkg().Name()).append(".changelog");
1593 if (DownloadChangelog(Cache, Fetcher, Ver, changelogfile) && downOnly == false)
1594 {
a4c40430 1595 DisplayFileInPager(changelogfile);
72dd5bec 1596 // cleanup temp file
03aa0847 1597 unlink(changelogfile.c_str());
72dd5bec 1598 }
a4c40430 1599 }
18ae8b29 1600 // clenaup tmp dir
72dd5bec
DK
1601 if (tmpdir != NULL)
1602 rmdir(tmpdir);
4a6fe09c 1603 return true;
a4c40430
MV
1604}
1605 /*}}}*/
8881b11e
DK
1606// DoFiles - Lists all IndexTargets /*{{{*/
1607static std::string format_key(std::string key)
1608{
1609 // deb822 is case-insensitive, but the human eye prefers candy
1610 std::transform(key.begin(), key.end(), key.begin(), ::tolower);
1611 key[0] = ::toupper(key[0]);
1612 size_t found = key.find("_uri");
1613 if (found != std::string::npos)
1614 key.replace(found, 4, "-URI");
1615 while ((found = key.find('_')) != std::string::npos)
1616 {
1617 key[found] = '-';
1618 key[found + 1] = ::toupper(key[found + 1]);
1619 }
1620 return key;
1621}
1622static bool DoFiles(CommandLine &CmdL)
1623{
1624 pkgCacheFile CacheFile;
1625 pkgSourceList *SrcList = CacheFile.GetSourceList();
1626
1627 if (SrcList == NULL)
1628 return false;
1629
1630 std::string const Format = _config->Find("APT::Get::Files::Format");
3fd89e62 1631 bool const ReleaseInfo = _config->FindB("APT::Get::Files::ReleaseInfo", true);
8881b11e
DK
1632 bool Filtered = CmdL.FileSize() > 1;
1633 for (pkgSourceList::const_iterator S = SrcList->begin(); S != SrcList->end(); ++S)
1634 {
1635 std::vector<IndexTarget> const targets = (*S)->GetIndexTargets();
1636 std::map<std::string, string> AddOptions;
3fd89e62
DK
1637 if (ReleaseInfo)
1638 {
1639 AddOptions.insert(std::make_pair("TRUSTED", ((*S)->IsTrusted() ? "yes" : "no")));
1640 pkgCache &Cache = *CacheFile.GetPkgCache();
1641 pkgCache::RlsFileIterator const RlsFile = (*S)->FindInCache(Cache, false);
1642 if (RlsFile.end())
1643 continue;
1644#define APT_RELEASE(X,Y) if (RlsFile.Y() != NULL) AddOptions.insert(std::make_pair(X, RlsFile.Y()))
1645 APT_RELEASE("CODENAME", Codename);
1646 APT_RELEASE("SUITE", Archive);
1647 APT_RELEASE("VERSION", Version);
1648 APT_RELEASE("ORIGIN", Origin);
1649 APT_RELEASE("LABEL", Label);
1650#undef APT_RELEASE
1651 }
8881b11e
DK
1652
1653 for (std::vector<IndexTarget>::const_iterator T = targets.begin(); T != targets.end(); ++T)
1654 {
3fd89e62
DK
1655 std::string filename = T->Option(ReleaseInfo ? IndexTarget::EXISTING_FILENAME : IndexTarget::FILENAME);
1656 if (filename.empty())
1657 continue;
1658
8881b11e
DK
1659 std::ostringstream stanza;
1660 if (Filtered || Format.empty())
1661 {
1662 stanza << "MetaKey: " << T->MetaKey << "\n"
1663 << "ShortDesc: " << T->ShortDesc << "\n"
1664 << "Description: " << T->Description << "\n"
1665 << "URI: " << T->URI << "\n"
3fd89e62 1666 << "Filename: " << filename << "\n"
8881b11e
DK
1667 << "Optional: " << (T->IsOptional ? "yes" : "no") << "\n";
1668 for (std::map<std::string,std::string>::const_iterator O = AddOptions.begin(); O != AddOptions.end(); ++O)
1669 stanza << format_key(O->first) << ": " << O->second << "\n";
1670 for (std::map<std::string,std::string>::const_iterator O = T->Options.begin(); O != T->Options.end(); ++O)
1671 stanza << format_key(O->first) << ": " << O->second << "\n";
1672 stanza << "\n";
1673
1674 if (Filtered)
1675 {
1676 // that is a bit crude, but good enough for now
1677 bool found = true;
1678 std::string haystack = std::string("\n") + stanza.str() + "\n";
1679 std::transform(haystack.begin(), haystack.end(), haystack.begin(), ::tolower);
1680 size_t const filesize = CmdL.FileSize() - 1;
1681 for (size_t i = 0; i != filesize; ++i)
1682 {
1683 std::string needle = std::string("\n") + CmdL.FileList[i + 1] + "\n";
1684 std::transform(needle.begin(), needle.end(), needle.begin(), ::tolower);
1685 if (haystack.find(needle) != std::string::npos)
1686 continue;
1687 found = false;
1688 break;
1689 }
1690 if (found == false)
1691 continue;
1692 }
1693 }
1694
1695 if (Format.empty())
1696 cout << stanza.str();
1697 else
1698 {
3fd89e62
DK
1699 std::string out = SubstVar(Format, "$(FILENAME)", filename);
1700 out = T->Format(out);
8881b11e
DK
1701 for (std::map<std::string,std::string>::const_iterator O = AddOptions.begin(); O != AddOptions.end(); ++O)
1702 out = SubstVar(out, std::string("$(") + O->first + ")", O->second);
1703 cout << out << std::endl;
1704 }
1705 }
1706 }
1707
1708 return true;
1709}
1710 /*}}}*/
0a8e3465
AL
1711// ShowHelp - Show a help screen /*{{{*/
1712// ---------------------------------------------------------------------
1713/* */
65512241 1714static bool ShowHelp(CommandLine &)
0a8e3465 1715{
249aec3b
JB
1716 ioprintf(cout, "%s %s (%s)\n", PACKAGE, PACKAGE_VERSION, COMMON_ARCH);
1717
04aa15a8 1718 if (_config->FindB("version") == true)
b2e465d6 1719 {
db0db9fe 1720 cout << _("Supported modules:") << endl;
249aec3b 1721
b2e465d6
AL
1722 for (unsigned I = 0; I != pkgVersioningSystem::GlobalListLen; I++)
1723 {
1724 pkgVersioningSystem *VS = pkgVersioningSystem::GlobalList[I];
1725 if (_system != 0 && _system->VS == VS)
1726 cout << '*';
1727 else
1728 cout << ' ';
1729 cout << "Ver: " << VS->Label << endl;
249aec3b 1730
b2e465d6
AL
1731 /* Print out all the packaging systems that will work with
1732 this VS */
1733 for (unsigned J = 0; J != pkgSystem::GlobalListLen; J++)
1734 {
1735 pkgSystem *Sys = pkgSystem::GlobalList[J];
1736 if (_system == Sys)
1737 cout << '*';
1738 else
1739 cout << ' ';
1740 if (Sys->VS->TestCompatibility(*VS) == true)
1741 cout << "Pkg: " << Sys->Label << " (Priority " << Sys->Score(*_config) << ")" << endl;
1742 }
1743 }
1744
1745 for (unsigned I = 0; I != pkgSourceList::Type::GlobalListLen; I++)
1746 {
1747 pkgSourceList::Type *Type = pkgSourceList::Type::GlobalList[I];
1748 cout << " S.L: '" << Type->Name << "' " << Type->Label << endl;
1749 }
1750
1751 for (unsigned I = 0; I != pkgIndexFile::Type::GlobalListLen; I++)
1752 {
1753 pkgIndexFile::Type *Type = pkgIndexFile::Type::GlobalList[I];
1754 cout << " Idx: " << Type->Label << endl;
1755 }
1756
1757 return true;
1758 }
1759
1760 cout <<
1761 _("Usage: apt-get [options] command\n"
1762 " apt-get [options] install|remove pkg1 [pkg2 ...]\n"
1763 " apt-get [options] source pkg1 [pkg2 ...]\n"
1764 "\n"
1765 "apt-get is a simple command line interface for downloading and\n"
1766 "installing packages. The most frequently used commands are update\n"
1767 "and install.\n"
1768 "\n"
1769 "Commands:\n"
1770 " update - Retrieve new lists of packages\n"
1771 " upgrade - Perform an upgrade\n"
1772 " install - Install new packages (pkg is libc6 not libc6.deb)\n"
1773 " remove - Remove packages\n"
12bffed7 1774 " autoremove - Remove automatically all unused packages\n"
73fc19d0 1775 " purge - Remove packages and config files\n"
b2e465d6
AL
1776 " source - Download source archives\n"
1777 " build-dep - Configure build-dependencies for source packages\n"
1778 " dist-upgrade - Distribution upgrade, see apt-get(8)\n"
1779 " dselect-upgrade - Follow dselect selections\n"
1780 " clean - Erase downloaded archive files\n"
1781 " autoclean - Erase old downloaded archive files\n"
1782 " check - Verify that there are no broken dependencies\n"
5f967f2d
MV
1783 " changelog - Download and display the changelog for the given package\n"
1784 " download - Download the binary package into the current directory\n"
b2e465d6
AL
1785 "\n"
1786 "Options:\n"
1787 " -h This help text.\n"
1788 " -q Loggable output - no progress indicator\n"
1789 " -qq No output except for errors\n"
1790 " -d Download only - do NOT install or unpack archives\n"
1791 " -s No-act. Perform ordering simulation\n"
1792 " -y Assume Yes to all queries and do not prompt\n"
0748d509 1793 " -f Attempt to correct a system with broken dependencies in place\n"
b2e465d6
AL
1794 " -m Attempt to continue if archives are unlocatable\n"
1795 " -u Show a list of upgraded packages as well\n"
1796 " -b Build the source package after fetching it\n"
ac625538 1797 " -V Show verbose version numbers\n"
b2e465d6 1798 " -c=? Read this configuration file\n"
a2884e32 1799 " -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp\n"
b2e465d6
AL
1800 "See the apt-get(8), sources.list(5) and apt.conf(5) manual\n"
1801 "pages for more information and options.\n"
1802 " This APT has Super Cow Powers.\n");
1803 return true;
d7827aca
AL
1804}
1805 /*}}}*/
92fcbfc1 1806int main(int argc,const char *argv[]) /*{{{*/
0a8e3465 1807{
83d89a9f
AL
1808 CommandLine::Dispatch Cmds[] = {{"update",&DoUpdate},
1809 {"upgrade",&DoUpgrade},
1810 {"install",&DoInstall},
1811 {"remove",&DoInstall},
24401c09 1812 {"purge",&DoInstall},
74a05226 1813 {"autoremove",&DoInstall},
d63a1458
JAK
1814 {"markauto",&DoMarkAuto},
1815 {"unmarkauto",&DoMarkAuto},
83d89a9f
AL
1816 {"dist-upgrade",&DoDistUpgrade},
1817 {"dselect-upgrade",&DoDSelectUpgrade},
b2e465d6 1818 {"build-dep",&DoBuildDep},
83d89a9f 1819 {"clean",&DoClean},
1bc849af 1820 {"autoclean",&DoAutoClean},
83d89a9f 1821 {"check",&DoCheck},
67111687 1822 {"source",&DoSource},
459b5f5d 1823 {"download",&DoDownload},
a4c40430 1824 {"changelog",&DoChangelog},
8881b11e 1825 {"files",&DoFiles},
b2e465d6 1826 {"moo",&DoMoo},
67111687 1827 {"help",&ShowHelp},
83d89a9f 1828 {0,0}};
67111687 1829
b9179170
MV
1830 std::vector<CommandLine::Args> Args = getCommandArgs("apt-get", CommandLine::GetCommand(Cmds, argc, argv));
1831
67111687
AL
1832 // Set up gettext support
1833 setlocale(LC_ALL,"");
1834 textdomain(PACKAGE);
1835
0a8e3465 1836 // Parse the command line and initialize the package library
ad7e0941
DK
1837 CommandLine CmdL;
1838 ParseCommandLine(CmdL, Cmds, Args.data(), &_config, &_system, argc, argv, ShowHelp);
55a5a46c 1839
b9179170
MV
1840 // see if we are in simulate mode
1841 CheckSimulateMode(CmdL);
55a5a46c 1842
3163087b
MV
1843 // Init the signals
1844 InitSignals();
1845
0a8e3465 1846 // Setup the output streams
b9179170 1847 InitOutput();
d7827aca 1848
0a8e3465 1849 // Match the operation
83d89a9f 1850 CmdL.DispatchArg(Cmds);
0a8e3465
AL
1851
1852 // Print any errors or warnings found during parsing
65beb572
DK
1853 bool const Errors = _error->PendingError();
1854 if (_config->FindI("quiet",0) > 0)
0a8e3465 1855 _error->DumpErrors();
65beb572
DK
1856 else
1857 _error->DumpErrors(GlobalError::DEBUG);
1858 return Errors == true ? 100 : 0;
0a8e3465 1859}
92fcbfc1 1860 /*}}}*/