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