]> git.saurik.com Git - apt.git/blob - cmdline/apt-get.cc
cef7d8c1477c08d57514e88a28fafcfe66d88484
[apt.git] / cmdline / apt-get.cc
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
96 using 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.. */
102 static 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 /*{{{*/
140 static 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 /* */
163 static 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. {{{*/
396 static 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 */
441 static 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 /* */
517 static 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. */
549 class 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
561 static 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 // ---------------------------------------------------------------------
585 static 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 AcqTextStatus Stat(std::cout, ScreenWidth,_config->FindI("quiet",0));
599 pkgAcquire Fetcher(&Stat);
600
601 pkgRecords Recs(Cache);
602 pkgSourceList *SrcList = Cache.GetSourceList();
603
604 // reuse the usual acquire methods for deb files, but don't drop them into
605 // the usual directories - keep everything in the current directory
606 std::vector<std::string> storefile(verset.size());
607 std::string const cwd = SafeGetCWD();
608 _config->Set("Dir::Cache::Archives", cwd);
609 int i = 0;
610 for (APT::VersionSet::const_iterator Ver = verset.begin();
611 Ver != verset.end(); ++Ver, ++i)
612 {
613 pkgAcquire::Item *I = new pkgAcqArchive(&Fetcher, SrcList, &Recs, *Ver, storefile[i]);
614 if (storefile[i].empty())
615 continue;
616 std::string const filename = cwd + flNotDir(storefile[i]);
617 storefile[i].assign(filename);
618 I->DestFile.assign(filename);
619 }
620
621 // Just print out the uris and exit if the --print-uris flag was used
622 if (_config->FindB("APT::Get::Print-URIs") == true)
623 {
624 pkgAcquire::UriIterator I = Fetcher.UriBegin();
625 for (; I != Fetcher.UriEnd(); ++I)
626 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
627 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
628 return true;
629 }
630
631 if (_error->PendingError() == true || CheckAuth(Fetcher, false) == false)
632 return false;
633
634 bool Failed = false;
635 if (AcquireRun(Fetcher, 0, &Failed, NULL) == false)
636 return false;
637
638 // copy files in local sources to the current directory
639 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); ++I)
640 {
641 std::string const filename = cwd + flNotDir((*I)->DestFile);
642 if ((*I)->Local == true &&
643 filename != (*I)->DestFile &&
644 (*I)->Status == pkgAcquire::Item::StatDone)
645 {
646 std::ifstream src((*I)->DestFile.c_str(), std::ios::binary);
647 std::ofstream dst(filename.c_str(), std::ios::binary);
648 dst << src.rdbuf();
649 }
650 }
651 return Failed == false;
652 }
653 /*}}}*/
654 // DoCheck - Perform the check operation /*{{{*/
655 // ---------------------------------------------------------------------
656 /* Opening automatically checks the system, this command is mostly used
657 for debugging */
658 static bool DoCheck(CommandLine &)
659 {
660 CacheFile Cache;
661 Cache.Open();
662 Cache.CheckDeps();
663
664 return true;
665 }
666 /*}}}*/
667 // DoSource - Fetch a source archive /*{{{*/
668 // ---------------------------------------------------------------------
669 /* Fetch souce packages */
670 struct DscFile
671 {
672 string Package;
673 string Version;
674 string Dsc;
675 };
676
677 static bool DoSource(CommandLine &CmdL)
678 {
679 CacheFile Cache;
680 if (Cache.Open(false) == false)
681 return false;
682
683 if (CmdL.FileSize() <= 1)
684 return _error->Error(_("Must specify at least one package to fetch source for"));
685
686 // Read the source list
687 if (Cache.BuildSourceList() == false)
688 return false;
689 pkgSourceList *List = Cache.GetSourceList();
690
691 // Create the text record parsers
692 pkgSrcRecords SrcRecs(*List);
693 if (_error->PendingError() == true)
694 return false;
695
696 // Create the download object
697 AcqTextStatus Stat(std::cout, ScreenWidth,_config->FindI("quiet",0));
698 pkgAcquire Fetcher(&Stat);
699
700 std::unique_ptr<DscFile[]> Dsc(new DscFile[CmdL.FileSize()]);
701
702 // insert all downloaded uris into this set to avoid downloading them
703 // twice
704 set<string> queued;
705
706 // Diff only mode only fetches .diff files
707 bool const diffOnly = _config->FindB("APT::Get::Diff-Only", false);
708 // Tar only mode only fetches .tar files
709 bool const tarOnly = _config->FindB("APT::Get::Tar-Only", false);
710 // Dsc only mode only fetches .dsc files
711 bool const dscOnly = _config->FindB("APT::Get::Dsc-Only", false);
712
713 // Load the requestd sources into the fetcher
714 unsigned J = 0;
715 std::vector<std::string> UntrustedList;
716 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
717 {
718 string Src;
719 pkgSrcRecords::Parser *Last = FindSrc(*I,SrcRecs,Src,Cache);
720 if (Last == 0) {
721 return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
722 }
723
724 if (Last->Index().IsTrusted() == false)
725 UntrustedList.push_back(Src);
726
727 string srec = Last->AsStr();
728 string::size_type pos = srec.find("\nVcs-");
729 while (pos != string::npos)
730 {
731 pos += strlen("\nVcs-");
732 string vcs = srec.substr(pos,srec.find(":",pos)-pos);
733 if(vcs == "Browser")
734 {
735 pos = srec.find("\nVcs-", pos);
736 continue;
737 }
738 pos += vcs.length()+2;
739 string::size_type epos = srec.find("\n", pos);
740 string const uri = srec.substr(pos,epos-pos);
741 ioprintf(c1out, _("NOTICE: '%s' packaging is maintained in "
742 "the '%s' version control system at:\n"
743 "%s\n"),
744 Src.c_str(), vcs.c_str(), uri.c_str());
745 std::string vcscmd;
746 if (vcs == "Bzr")
747 vcscmd = "bzr branch " + uri;
748 else if (vcs == "Git")
749 vcscmd = "git clone " + uri;
750
751 if (vcscmd.empty() == false)
752 ioprintf(c1out,_("Please use:\n%s\n"
753 "to retrieve the latest (possibly unreleased) "
754 "updates to the package.\n"),
755 vcscmd.c_str());
756 break;
757 }
758
759 // Back track
760 vector<pkgSrcRecords::File2> Lst;
761 if (Last->Files2(Lst) == false) {
762 return false;
763 }
764
765 // Load them into the fetcher
766 for (vector<pkgSrcRecords::File2>::const_iterator I = Lst.begin();
767 I != Lst.end(); ++I)
768 {
769 // Try to guess what sort of file it is we are getting.
770 if (I->Type == "dsc")
771 {
772 Dsc[J].Package = Last->Package();
773 Dsc[J].Version = Last->Version();
774 Dsc[J].Dsc = flNotDir(I->Path);
775 }
776
777 // Handle the only options so that multiple can be used at once
778 if (diffOnly == true || tarOnly == true || dscOnly == true)
779 {
780 if ((diffOnly == true && I->Type == "diff") ||
781 (tarOnly == true && I->Type == "tar") ||
782 (dscOnly == true && I->Type == "dsc"))
783 ; // Fine, we want this file downloaded
784 else
785 continue;
786 }
787
788 // don't download the same uri twice (should this be moved to
789 // the fetcher interface itself?)
790 if(queued.find(Last->Index().ArchiveURI(I->Path)) != queued.end())
791 continue;
792 queued.insert(Last->Index().ArchiveURI(I->Path));
793
794 // check if we have a file with that md5 sum already localy
795 std::string localFile = flNotDir(I->Path);
796 if (FileExists(localFile) == true)
797 if(I->Hashes.VerifyFile(localFile) == true)
798 {
799 ioprintf(c1out,_("Skipping already downloaded file '%s'\n"),
800 localFile.c_str());
801 continue;
802 }
803
804 // see if we have a hash (Acquire::ForceHash is the only way to have none)
805 if (I->Hashes.usable() == false && _config->FindB("APT::Get::AllowUnauthenticated",false) == false)
806 {
807 ioprintf(c1out, "Skipping download of file '%s' as requested hashsum is not available for authentication\n",
808 localFile.c_str());
809 continue;
810 }
811
812 new pkgAcqFile(&Fetcher,Last->Index().ArchiveURI(I->Path),
813 I->Hashes, I->FileSize, Last->Index().SourceInfo(*Last,*I), Src);
814 }
815 }
816
817 // Display statistics
818 unsigned long long FetchBytes = Fetcher.FetchNeeded();
819 unsigned long long FetchPBytes = Fetcher.PartialPresent();
820 unsigned long long DebBytes = Fetcher.TotalNeeded();
821
822 if (CheckFreeSpaceBeforeDownload(".", (FetchBytes - FetchPBytes)) == false)
823 return false;
824
825 // Number of bytes
826 if (DebBytes != FetchBytes)
827 //TRANSLATOR: The required space between number and unit is already included
828 // in the replacement strings, so %sB will be correctly translate in e.g. 1,5 MB
829 ioprintf(c1out,_("Need to get %sB/%sB of source archives.\n"),
830 SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
831 else
832 //TRANSLATOR: The required space between number and unit is already included
833 // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
834 ioprintf(c1out,_("Need to get %sB of source archives.\n"),
835 SizeToStr(DebBytes).c_str());
836
837 if (_config->FindB("APT::Get::Simulate",false) == true)
838 {
839 for (unsigned I = 0; I != J; I++)
840 ioprintf(cout,_("Fetch source %s\n"),Dsc[I].Package.c_str());
841 return true;
842 }
843
844 // Just print out the uris an exit if the --print-uris flag was used
845 if (_config->FindB("APT::Get::Print-URIs") == true)
846 {
847 pkgAcquire::UriIterator I = Fetcher.UriBegin();
848 for (; I != Fetcher.UriEnd(); ++I)
849 cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
850 I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
851 return true;
852 }
853
854 // check authentication status of the source as well
855 if (UntrustedList.empty() == false && AuthPrompt(UntrustedList, false) == false)
856 return false;
857
858 // Run it
859 bool Failed = false;
860 if (AcquireRun(Fetcher, 0, &Failed, NULL) == false || Failed == true)
861 {
862 return _error->Error(_("Failed to fetch some archives."));
863 }
864
865 if (_config->FindB("APT::Get::Download-only",false) == true)
866 {
867 c1out << _("Download complete and in download only mode") << endl;
868 return true;
869 }
870
871 // Unpack the sources
872 pid_t Process = ExecFork();
873
874 if (Process == 0)
875 {
876 bool const fixBroken = _config->FindB("APT::Get::Fix-Broken", false);
877 for (unsigned I = 0; I != J; ++I)
878 {
879 string Dir = Dsc[I].Package + '-' + Cache->VS().UpstreamVersion(Dsc[I].Version.c_str());
880
881 // Diff only mode only fetches .diff files
882 if (_config->FindB("APT::Get::Diff-Only",false) == true ||
883 _config->FindB("APT::Get::Tar-Only",false) == true ||
884 Dsc[I].Dsc.empty() == true)
885 continue;
886
887 // See if the package is already unpacked
888 struct stat Stat;
889 if (fixBroken == false && stat(Dir.c_str(),&Stat) == 0 &&
890 S_ISDIR(Stat.st_mode) != 0)
891 {
892 ioprintf(c0out ,_("Skipping unpack of already unpacked source in %s\n"),
893 Dir.c_str());
894 }
895 else
896 {
897 // Call dpkg-source
898 std::string const sourceopts = _config->Find("DPkg::Source-Options", "-x");
899 std::string S;
900 strprintf(S, "%s %s %s",
901 _config->Find("Dir::Bin::dpkg-source","dpkg-source").c_str(),
902 sourceopts.c_str(), Dsc[I].Dsc.c_str());
903 if (system(S.c_str()) != 0)
904 {
905 fprintf(stderr, _("Unpack command '%s' failed.\n"), S.c_str());
906 fprintf(stderr, _("Check if the 'dpkg-dev' package is installed.\n"));
907 _exit(1);
908 }
909 }
910
911 // Try to compile it with dpkg-buildpackage
912 if (_config->FindB("APT::Get::Compile",false) == true)
913 {
914 string buildopts = _config->Find("APT::Get::Host-Architecture");
915 if (buildopts.empty() == false)
916 buildopts = "-a" + buildopts + " ";
917
918 // get all active build profiles
919 std::string const profiles = APT::Configuration::getBuildProfilesString();
920 if (profiles.empty() == false)
921 buildopts.append(" -P").append(profiles).append(" ");
922
923 buildopts.append(_config->Find("DPkg::Build-Options","-b -uc"));
924
925 // Call dpkg-buildpackage
926 std::string S;
927 strprintf(S, "cd %s && %s %s",
928 Dir.c_str(),
929 _config->Find("Dir::Bin::dpkg-buildpackage","dpkg-buildpackage").c_str(),
930 buildopts.c_str());
931
932 if (system(S.c_str()) != 0)
933 {
934 fprintf(stderr, _("Build command '%s' failed.\n"), S.c_str());
935 _exit(1);
936 }
937 }
938 }
939
940 _exit(0);
941 }
942
943 return ExecWait(Process, "dpkg-source");
944 }
945 /*}}}*/
946 // DoBuildDep - Install/removes packages to satisfy build dependencies /*{{{*/
947 // ---------------------------------------------------------------------
948 /* This function will look at the build depends list of the given source
949 package and install the necessary packages to make it true, or fail. */
950 static bool DoBuildDep(CommandLine &CmdL)
951 {
952 CacheFile Cache;
953
954 _config->Set("APT::Install-Recommends", false);
955
956 bool WantLock = _config->FindB("APT::Get::Print-URIs", false) == false;
957
958 if (Cache.Open(WantLock) == false)
959 return false;
960
961 if (CmdL.FileSize() <= 1)
962 return _error->Error(_("Must specify at least one package to check builddeps for"));
963
964 // Read the source list
965 if (Cache.BuildSourceList() == false)
966 return false;
967 pkgSourceList *List = Cache.GetSourceList();
968
969 // Create the text record parsers
970 pkgSrcRecords SrcRecs(*List);
971 if (_error->PendingError() == true)
972 return false;
973
974 bool StripMultiArch;
975 string hostArch = _config->Find("APT::Get::Host-Architecture");
976 if (hostArch.empty() == false)
977 {
978 std::vector<std::string> archs = APT::Configuration::getArchitectures();
979 if (std::find(archs.begin(), archs.end(), hostArch) == archs.end())
980 return _error->Error(_("No architecture information available for %s. See apt.conf(5) APT::Architectures for setup"), hostArch.c_str());
981 StripMultiArch = false;
982 }
983 else
984 StripMultiArch = true;
985
986 unsigned J = 0;
987 for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
988 {
989 string Src;
990 pkgSrcRecords::Parser *Last = 0;
991 std::unique_ptr<pkgSrcRecords::Parser> LastOwner;
992
993 // an unpacked debian source tree
994 using APT::String::Startswith;
995 if ((Startswith(*I, "./") || Startswith(*I, "/")) &&
996 DirectoryExists(*I))
997 {
998 ioprintf(c1out, _("Note, using directory '%s' to get the build dependencies\n"), *I);
999 // FIXME: how can we make this more elegant?
1000 std::string TypeName = "Debian control file";
1001 pkgIndexFile::Type *Type = pkgIndexFile::Type::GetType(TypeName.c_str());
1002 if(Type != NULL)
1003 LastOwner.reset(Last = Type->CreateSrcPkgParser(*I));
1004 }
1005 // if its a local file (e.g. .dsc) use this
1006 else if (FileExists(*I))
1007 {
1008 ioprintf(c1out, _("Note, using file '%s' to get the build dependencies\n"), *I);
1009
1010 // see if we can get a parser for this pkgIndexFile type
1011 string TypeName = "Debian " + flExtension(*I) + " file";
1012 pkgIndexFile::Type *Type = pkgIndexFile::Type::GetType(TypeName.c_str());
1013 if(Type != NULL)
1014 LastOwner.reset(Last = Type->CreateSrcPkgParser(*I));
1015 } else {
1016 // normal case, search the cache for the source file
1017 Last = FindSrc(*I,SrcRecs,Src,Cache);
1018 }
1019
1020 if (Last == 0)
1021 return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
1022
1023 // Process the build-dependencies
1024 vector<pkgSrcRecords::Parser::BuildDepRec> BuildDeps;
1025 // FIXME: Can't specify architecture to use for [wildcard] matching, so switch default arch temporary
1026 if (hostArch.empty() == false)
1027 {
1028 std::string nativeArch = _config->Find("APT::Architecture");
1029 _config->Set("APT::Architecture", hostArch);
1030 bool Success = Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only", false), StripMultiArch);
1031 _config->Set("APT::Architecture", nativeArch);
1032 if (Success == false)
1033 return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
1034 }
1035 else if (Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only", false), StripMultiArch) == false)
1036 return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
1037
1038 // Also ensure that build-essential packages are present
1039 Configuration::Item const *Opts = _config->Tree("APT::Build-Essential");
1040 if (Opts)
1041 Opts = Opts->Child;
1042 for (; Opts; Opts = Opts->Next)
1043 {
1044 if (Opts->Value.empty() == true)
1045 continue;
1046
1047 pkgSrcRecords::Parser::BuildDepRec rec;
1048 rec.Package = Opts->Value;
1049 rec.Type = pkgSrcRecords::Parser::BuildDependIndep;
1050 rec.Op = 0;
1051 BuildDeps.push_back(rec);
1052 }
1053
1054 if (BuildDeps.empty() == true)
1055 {
1056 ioprintf(c1out,_("%s has no build depends.\n"),Src.c_str());
1057 continue;
1058 }
1059
1060 // Install the requested packages
1061 vector <pkgSrcRecords::Parser::BuildDepRec>::iterator D;
1062 pkgProblemResolver Fix(Cache);
1063 bool skipAlternatives = false; // skip remaining alternatives in an or group
1064 for (D = BuildDeps.begin(); D != BuildDeps.end(); ++D)
1065 {
1066 bool hasAlternatives = (((*D).Op & pkgCache::Dep::Or) == pkgCache::Dep::Or);
1067
1068 if (skipAlternatives == true)
1069 {
1070 /*
1071 * if there are alternatives, we've already picked one, so skip
1072 * the rest
1073 *
1074 * TODO: this means that if there's a build-dep on A|B and B is
1075 * installed, we'll still try to install A; more importantly,
1076 * if A is currently broken, we cannot go back and try B. To fix
1077 * this would require we do a Resolve cycle for each package we
1078 * add to the install list. Ugh
1079 */
1080 if (!hasAlternatives)
1081 skipAlternatives = false; // end of or group
1082 continue;
1083 }
1084
1085 if ((*D).Type == pkgSrcRecords::Parser::BuildConflict ||
1086 (*D).Type == pkgSrcRecords::Parser::BuildConflictIndep)
1087 {
1088 pkgCache::GrpIterator Grp = Cache->FindGrp((*D).Package);
1089 // Build-conflicts on unknown packages are silently ignored
1090 if (Grp.end() == true)
1091 continue;
1092
1093 for (pkgCache::PkgIterator Pkg = Grp.PackageList(); Pkg.end() == false; Pkg = Grp.NextPkg(Pkg))
1094 {
1095 pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
1096 /*
1097 * Remove if we have an installed version that satisfies the
1098 * version criteria
1099 */
1100 if (IV.end() == false &&
1101 Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
1102 TryToInstallBuildDep(Pkg,Cache,Fix,true,false);
1103 }
1104 }
1105 else // BuildDep || BuildDepIndep
1106 {
1107 if (_config->FindB("Debug::BuildDeps",false) == true)
1108 cout << "Looking for " << (*D).Package << "...\n";
1109
1110 pkgCache::PkgIterator Pkg;
1111
1112 // Cross-Building?
1113 if (StripMultiArch == false && D->Type != pkgSrcRecords::Parser::BuildDependIndep)
1114 {
1115 size_t const colon = D->Package.find(":");
1116 if (colon != string::npos)
1117 {
1118 if (strcmp(D->Package.c_str() + colon, ":any") == 0 || strcmp(D->Package.c_str() + colon, ":native") == 0)
1119 Pkg = Cache->FindPkg(D->Package.substr(0,colon));
1120 else
1121 Pkg = Cache->FindPkg(D->Package);
1122 }
1123 else
1124 Pkg = Cache->FindPkg(D->Package, hostArch);
1125
1126 // a bad version either is invalid or doesn't satify dependency
1127 #define BADVER(Ver) (Ver.end() == true || \
1128 (D->Version.empty() == false && \
1129 Cache->VS().CheckDep(Ver.VerStr(),D->Op,D->Version.c_str()) == false))
1130
1131 APT::VersionList verlist;
1132 if (Pkg.end() == false)
1133 {
1134 pkgCache::VerIterator Ver = (*Cache)[Pkg].InstVerIter(*Cache);
1135 if (BADVER(Ver) == false)
1136 verlist.insert(Ver);
1137 Ver = (*Cache)[Pkg].CandidateVerIter(*Cache);
1138 if (BADVER(Ver) == false)
1139 verlist.insert(Ver);
1140 }
1141 if (verlist.empty() == true)
1142 {
1143 pkgCache::PkgIterator BuildPkg = Cache->FindPkg(D->Package, "native");
1144 if (BuildPkg.end() == false && Pkg != BuildPkg)
1145 {
1146 pkgCache::VerIterator Ver = (*Cache)[BuildPkg].InstVerIter(*Cache);
1147 if (BADVER(Ver) == false)
1148 verlist.insert(Ver);
1149 Ver = (*Cache)[BuildPkg].CandidateVerIter(*Cache);
1150 if (BADVER(Ver) == false)
1151 verlist.insert(Ver);
1152 }
1153 }
1154 #undef BADVER
1155
1156 string forbidden;
1157 // We need to decide if host or build arch, so find a version we can look at
1158 APT::VersionList::const_iterator Ver = verlist.begin();
1159 for (; Ver != verlist.end(); ++Ver)
1160 {
1161 forbidden.clear();
1162 if (Ver->MultiArch == pkgCache::Version::No || Ver->MultiArch == pkgCache::Version::All)
1163 {
1164 if (colon == string::npos)
1165 Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
1166 else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
1167 forbidden = "Multi-Arch: no";
1168 else if (strcmp(D->Package.c_str() + colon, ":native") == 0)
1169 Pkg = Ver.ParentPkg().Group().FindPkg("native");
1170 }
1171 else if (Ver->MultiArch == pkgCache::Version::Same)
1172 {
1173 if (colon == string::npos)
1174 Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
1175 else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
1176 forbidden = "Multi-Arch: same";
1177 else if (strcmp(D->Package.c_str() + colon, ":native") == 0)
1178 Pkg = Ver.ParentPkg().Group().FindPkg("native");
1179 }
1180 else if ((Ver->MultiArch & pkgCache::Version::Foreign) == pkgCache::Version::Foreign)
1181 {
1182 if (colon == string::npos)
1183 Pkg = Ver.ParentPkg().Group().FindPkg("native");
1184 else if (strcmp(D->Package.c_str() + colon, ":any") == 0 ||
1185 strcmp(D->Package.c_str() + colon, ":native") == 0)
1186 forbidden = "Multi-Arch: foreign";
1187 }
1188 else if ((Ver->MultiArch & pkgCache::Version::Allowed) == pkgCache::Version::Allowed)
1189 {
1190 if (colon == string::npos)
1191 Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
1192 else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
1193 {
1194 // prefer any installed over preferred non-installed architectures
1195 pkgCache::GrpIterator Grp = Ver.ParentPkg().Group();
1196 // we don't check for version here as we are better of with upgrading than remove and install
1197 for (Pkg = Grp.PackageList(); Pkg.end() == false; Pkg = Grp.NextPkg(Pkg))
1198 if (Pkg.CurrentVer().end() == false)
1199 break;
1200 if (Pkg.end() == true)
1201 Pkg = Grp.FindPreferredPkg(true);
1202 }
1203 else if (strcmp(D->Package.c_str() + colon, ":native") == 0)
1204 Pkg = Ver.ParentPkg().Group().FindPkg("native");
1205 }
1206
1207 if (forbidden.empty() == false)
1208 {
1209 if (_config->FindB("Debug::BuildDeps",false) == true)
1210 cout << D->Package.substr(colon, string::npos) << " is not allowed from " << forbidden << " package " << (*D).Package << " (" << Ver.VerStr() << ")" << endl;
1211 continue;
1212 }
1213
1214 //we found a good version
1215 break;
1216 }
1217 if (Ver == verlist.end())
1218 {
1219 if (_config->FindB("Debug::BuildDeps",false) == true)
1220 cout << " No multiarch info as we have no satisfying installed nor candidate for " << D->Package << " on build or host arch" << endl;
1221
1222 if (forbidden.empty() == false)
1223 {
1224 if (hasAlternatives)
1225 continue;
1226 return _error->Error(_("%s dependency for %s can't be satisfied "
1227 "because %s is not allowed on '%s' packages"),
1228 Last->BuildDepType(D->Type), Src.c_str(),
1229 D->Package.c_str(), forbidden.c_str());
1230 }
1231 }
1232 }
1233 else
1234 Pkg = Cache->FindPkg(D->Package);
1235
1236 if (Pkg.end() == true || (Pkg->VersionList == 0 && Pkg->ProvidesList == 0))
1237 {
1238 if (_config->FindB("Debug::BuildDeps",false) == true)
1239 cout << " (not found)" << (*D).Package << endl;
1240
1241 if (hasAlternatives)
1242 continue;
1243
1244 return _error->Error(_("%s dependency for %s cannot be satisfied "
1245 "because the package %s cannot be found"),
1246 Last->BuildDepType((*D).Type),Src.c_str(),
1247 (*D).Package.c_str());
1248 }
1249
1250 pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
1251 if (IV.end() == false)
1252 {
1253 if (_config->FindB("Debug::BuildDeps",false) == true)
1254 cout << " Is installed\n";
1255
1256 if (D->Version.empty() == true ||
1257 Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
1258 {
1259 skipAlternatives = hasAlternatives;
1260 continue;
1261 }
1262
1263 if (_config->FindB("Debug::BuildDeps",false) == true)
1264 cout << " ...but the installed version doesn't meet the version requirement\n";
1265
1266 if (((*D).Op & pkgCache::Dep::LessEq) == pkgCache::Dep::LessEq)
1267 return _error->Error(_("Failed to satisfy %s dependency for %s: Installed package %s is too new"),
1268 Last->BuildDepType((*D).Type), Src.c_str(), Pkg.FullName(true).c_str());
1269 }
1270
1271 // Only consider virtual packages if there is no versioned dependency
1272 if ((*D).Version.empty() == true)
1273 {
1274 /*
1275 * If this is a virtual package, we need to check the list of
1276 * packages that provide it and see if any of those are
1277 * installed
1278 */
1279 pkgCache::PrvIterator Prv = Pkg.ProvidesList();
1280 for (; Prv.end() != true; ++Prv)
1281 {
1282 if (_config->FindB("Debug::BuildDeps",false) == true)
1283 cout << " Checking provider " << Prv.OwnerPkg().FullName() << endl;
1284
1285 if ((*Cache)[Prv.OwnerPkg()].InstVerIter(*Cache).end() == false)
1286 break;
1287 }
1288
1289 if (Prv.end() == false)
1290 {
1291 if (_config->FindB("Debug::BuildDeps",false) == true)
1292 cout << " Is provided by installed package " << Prv.OwnerPkg().FullName() << endl;
1293 skipAlternatives = hasAlternatives;
1294 continue;
1295 }
1296 }
1297 else // versioned dependency
1298 {
1299 pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
1300 if (CV.end() == true ||
1301 Cache->VS().CheckDep(CV.VerStr(),(*D).Op,(*D).Version.c_str()) == false)
1302 {
1303 if (hasAlternatives)
1304 continue;
1305 else if (CV.end() == false)
1306 return _error->Error(_("%s dependency for %s cannot be satisfied "
1307 "because candidate version of package %s "
1308 "can't satisfy version requirements"),
1309 Last->BuildDepType(D->Type), Src.c_str(),
1310 D->Package.c_str());
1311 else
1312 return _error->Error(_("%s dependency for %s cannot be satisfied "
1313 "because package %s has no candidate version"),
1314 Last->BuildDepType(D->Type), Src.c_str(),
1315 D->Package.c_str());
1316 }
1317 }
1318
1319 if (TryToInstallBuildDep(Pkg,Cache,Fix,false,false,false) == true)
1320 {
1321 // We successfully installed something; skip remaining alternatives
1322 skipAlternatives = hasAlternatives;
1323 if(_config->FindB("APT::Get::Build-Dep-Automatic", false) == true)
1324 Cache->MarkAuto(Pkg, true);
1325 continue;
1326 }
1327 else if (hasAlternatives)
1328 {
1329 if (_config->FindB("Debug::BuildDeps",false) == true)
1330 cout << " Unsatisfiable, trying alternatives\n";
1331 continue;
1332 }
1333 else
1334 {
1335 return _error->Error(_("Failed to satisfy %s dependency for %s: %s"),
1336 Last->BuildDepType((*D).Type),
1337 Src.c_str(),
1338 (*D).Package.c_str());
1339 }
1340 }
1341 }
1342
1343 if (Fix.Resolve(true) == false)
1344 _error->Discard();
1345
1346 // Now we check the state of the packages,
1347 if (Cache->BrokenCount() != 0)
1348 {
1349 ShowBroken(cout, Cache, false);
1350 return _error->Error(_("Build-dependencies for %s could not be satisfied."),*I);
1351 }
1352 }
1353
1354 if (InstallPackages(Cache, false, true) == false)
1355 return _error->Error(_("Failed to process build dependencies"));
1356 return true;
1357 }
1358 /*}}}*/
1359 // DoChangelog - Get changelog from the command line /*{{{*/
1360 static bool DoChangelog(CommandLine &CmdL)
1361 {
1362 CacheFile Cache;
1363 if (Cache.ReadOnlyOpen() == false)
1364 return false;
1365
1366 APT::CacheSetHelper helper;
1367 APT::VersionList verset = APT::VersionList::FromCommandLine(Cache,
1368 CmdL.FileList + 1, APT::CacheSetHelper::CANDIDATE, helper);
1369 if (verset.empty() == true)
1370 return false;
1371 pkgAcquire Fetcher;
1372 AcqTextStatus Stat(std::cout, ScreenWidth,_config->FindI("quiet",0));
1373 Fetcher.SetLog(&Stat);
1374
1375 bool const downOnly = _config->FindB("APT::Get::Download-Only", false);
1376 bool const printOnly = _config->FindB("APT::Get::Print-URIs", false);
1377
1378 for (APT::VersionList::const_iterator Ver = verset.begin();
1379 Ver != verset.end();
1380 ++Ver)
1381 {
1382 if (printOnly)
1383 new pkgAcqChangelog(&Fetcher, Ver, "/dev/null");
1384 else if (downOnly)
1385 new pkgAcqChangelog(&Fetcher, Ver, ".");
1386 else
1387 new pkgAcqChangelog(&Fetcher, Ver);
1388 }
1389
1390 if (printOnly == false)
1391 {
1392 bool Failed = false;
1393 if (AcquireRun(Fetcher, 0, &Failed, NULL) == false || Failed == true)
1394 return false;
1395 }
1396
1397 if (downOnly == false || printOnly == true)
1398 {
1399 bool Failed = false;
1400 for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); ++I)
1401 {
1402 if (printOnly)
1403 {
1404 if ((*I)->ErrorText.empty() == false)
1405 {
1406 Failed = true;
1407 _error->Error("%s", (*I)->ErrorText.c_str());
1408 }
1409 else
1410 cout << '\'' << (*I)->DescURI() << "' " << flNotDir((*I)->DestFile) << std::endl;
1411 }
1412 else
1413 DisplayFileInPager((*I)->DestFile);
1414 }
1415 return Failed == false;
1416 }
1417
1418 return true;
1419 }
1420 /*}}}*/
1421 // DoIndexTargets - Lists all IndexTargets /*{{{*/
1422 static std::string format_key(std::string key)
1423 {
1424 // deb822 is case-insensitive, but the human eye prefers candy
1425 std::transform(key.begin(), key.end(), key.begin(), ::tolower);
1426 key[0] = ::toupper(key[0]);
1427 size_t found = key.find("_uri");
1428 if (found != std::string::npos)
1429 key.replace(found, 4, "-URI");
1430 while ((found = key.find('_')) != std::string::npos)
1431 {
1432 key[found] = '-';
1433 key[found + 1] = ::toupper(key[found + 1]);
1434 }
1435 return key;
1436 }
1437 static bool DoIndexTargets(CommandLine &CmdL)
1438 {
1439 pkgCacheFile CacheFile;
1440 pkgSourceList *SrcList = CacheFile.GetSourceList();
1441
1442 if (SrcList == NULL)
1443 return false;
1444
1445 std::string const Format = _config->Find("APT::Get::IndexTargets::Format");
1446 bool const ReleaseInfo = _config->FindB("APT::Get::IndexTargets::ReleaseInfo", true);
1447 bool Filtered = CmdL.FileSize() > 1;
1448 for (pkgSourceList::const_iterator S = SrcList->begin(); S != SrcList->end(); ++S)
1449 {
1450 std::vector<IndexTarget> const targets = (*S)->GetIndexTargets();
1451 std::map<std::string, string> AddOptions;
1452 if (ReleaseInfo)
1453 {
1454 AddOptions.insert(std::make_pair("TRUSTED", ((*S)->IsTrusted() ? "yes" : "no")));
1455 pkgCache &Cache = *CacheFile.GetPkgCache();
1456 pkgCache::RlsFileIterator const RlsFile = (*S)->FindInCache(Cache, false);
1457 if (RlsFile.end())
1458 continue;
1459 #define APT_RELEASE(X,Y) if (RlsFile.Y() != NULL) AddOptions.insert(std::make_pair(X, RlsFile.Y()))
1460 APT_RELEASE("CODENAME", Codename);
1461 APT_RELEASE("SUITE", Archive);
1462 APT_RELEASE("VERSION", Version);
1463 APT_RELEASE("ORIGIN", Origin);
1464 APT_RELEASE("LABEL", Label);
1465 #undef APT_RELEASE
1466 }
1467
1468 for (std::vector<IndexTarget>::const_iterator T = targets.begin(); T != targets.end(); ++T)
1469 {
1470 std::string filename = T->Option(ReleaseInfo ? IndexTarget::EXISTING_FILENAME : IndexTarget::FILENAME);
1471 if (filename.empty())
1472 continue;
1473
1474 std::ostringstream stanza;
1475 if (Filtered || Format.empty())
1476 {
1477 stanza << "MetaKey: " << T->MetaKey << "\n"
1478 << "ShortDesc: " << T->ShortDesc << "\n"
1479 << "Description: " << T->Description << "\n"
1480 << "URI: " << T->URI << "\n"
1481 << "Filename: " << filename << "\n"
1482 << "Optional: " << (T->IsOptional ? "yes" : "no") << "\n"
1483 << "KeepCompressed: " << (T->KeepCompressed ? "yes" : "no") << "\n";
1484 for (std::map<std::string,std::string>::const_iterator O = AddOptions.begin(); O != AddOptions.end(); ++O)
1485 stanza << format_key(O->first) << ": " << O->second << "\n";
1486 for (std::map<std::string,std::string>::const_iterator O = T->Options.begin(); O != T->Options.end(); ++O)
1487 {
1488 if (O->first == "PDIFFS")
1489 stanza << "PDiffs: " << O->second << "\n";
1490 else if (O->first == "COMPRESSIONTYPES")
1491 stanza << "CompressionTypes: " << O->second << "\n";
1492 else if (O->first == "DEFAULTENABLED")
1493 stanza << "DefaultEnabled: " << O->second << "\n";
1494 else
1495 stanza << format_key(O->first) << ": " << O->second << "\n";
1496 }
1497 stanza << "\n";
1498
1499 if (Filtered)
1500 {
1501 // that is a bit crude, but good enough for now
1502 bool found = true;
1503 std::string haystack = std::string("\n") + stanza.str() + "\n";
1504 std::transform(haystack.begin(), haystack.end(), haystack.begin(), ::tolower);
1505 size_t const filesize = CmdL.FileSize() - 1;
1506 for (size_t i = 0; i != filesize; ++i)
1507 {
1508 std::string needle = std::string("\n") + CmdL.FileList[i + 1] + "\n";
1509 std::transform(needle.begin(), needle.end(), needle.begin(), ::tolower);
1510 if (haystack.find(needle) != std::string::npos)
1511 continue;
1512 found = false;
1513 break;
1514 }
1515 if (found == false)
1516 continue;
1517 }
1518 }
1519
1520 if (Format.empty())
1521 cout << stanza.str();
1522 else
1523 {
1524 std::string out = SubstVar(Format, "$(FILENAME)", filename);
1525 out = T->Format(out);
1526 for (std::map<std::string,std::string>::const_iterator O = AddOptions.begin(); O != AddOptions.end(); ++O)
1527 out = SubstVar(out, std::string("$(") + O->first + ")", O->second);
1528 cout << out << std::endl;
1529 }
1530 }
1531 }
1532
1533 return true;
1534 }
1535 /*}}}*/
1536 // ShowHelp - Show a help screen /*{{{*/
1537 // ---------------------------------------------------------------------
1538 /* */
1539 static bool ShowHelp(CommandLine &)
1540 {
1541 ioprintf(cout, "%s %s (%s)\n", PACKAGE, PACKAGE_VERSION, COMMON_ARCH);
1542
1543 if (_config->FindB("version") == true)
1544 {
1545 cout << _("Supported modules:") << endl;
1546
1547 for (unsigned I = 0; I != pkgVersioningSystem::GlobalListLen; I++)
1548 {
1549 pkgVersioningSystem *VS = pkgVersioningSystem::GlobalList[I];
1550 if (_system != 0 && _system->VS == VS)
1551 cout << '*';
1552 else
1553 cout << ' ';
1554 cout << "Ver: " << VS->Label << endl;
1555
1556 /* Print out all the packaging systems that will work with
1557 this VS */
1558 for (unsigned J = 0; J != pkgSystem::GlobalListLen; J++)
1559 {
1560 pkgSystem *Sys = pkgSystem::GlobalList[J];
1561 if (_system == Sys)
1562 cout << '*';
1563 else
1564 cout << ' ';
1565 if (Sys->VS->TestCompatibility(*VS) == true)
1566 cout << "Pkg: " << Sys->Label << " (Priority " << Sys->Score(*_config) << ")" << endl;
1567 }
1568 }
1569
1570 for (unsigned I = 0; I != pkgSourceList::Type::GlobalListLen; I++)
1571 {
1572 pkgSourceList::Type *Type = pkgSourceList::Type::GlobalList[I];
1573 cout << " S.L: '" << Type->Name << "' " << Type->Label << endl;
1574 }
1575
1576 for (unsigned I = 0; I != pkgIndexFile::Type::GlobalListLen; I++)
1577 {
1578 pkgIndexFile::Type *Type = pkgIndexFile::Type::GlobalList[I];
1579 cout << " Idx: " << Type->Label << endl;
1580 }
1581
1582 return true;
1583 }
1584
1585 cout <<
1586 _("Usage: apt-get [options] command\n"
1587 " apt-get [options] install|remove pkg1 [pkg2 ...]\n"
1588 " apt-get [options] source pkg1 [pkg2 ...]\n"
1589 "\n"
1590 "apt-get is a simple command line interface for downloading and\n"
1591 "installing packages. The most frequently used commands are update\n"
1592 "and install.\n"
1593 "\n"
1594 "Commands:\n"
1595 " update - Retrieve new lists of packages\n"
1596 " upgrade - Perform an upgrade\n"
1597 " install - Install new packages (pkg is libc6 not libc6.deb)\n"
1598 " remove - Remove packages\n"
1599 " autoremove - Remove automatically all unused packages\n"
1600 " purge - Remove packages and config files\n"
1601 " source - Download source archives\n"
1602 " build-dep - Configure build-dependencies for source packages\n"
1603 " dist-upgrade - Distribution upgrade, see apt-get(8)\n"
1604 " dselect-upgrade - Follow dselect selections\n"
1605 " clean - Erase downloaded archive files\n"
1606 " autoclean - Erase old downloaded archive files\n"
1607 " check - Verify that there are no broken dependencies\n"
1608 " changelog - Download and display the changelog for the given package\n"
1609 " download - Download the binary package into the current directory\n"
1610 "\n"
1611 "Options:\n"
1612 " -h This help text.\n"
1613 " -q Loggable output - no progress indicator\n"
1614 " -qq No output except for errors\n"
1615 " -d Download only - do NOT install or unpack archives\n"
1616 " -s No-act. Perform ordering simulation\n"
1617 " -y Assume Yes to all queries and do not prompt\n"
1618 " -f Attempt to correct a system with broken dependencies in place\n"
1619 " -m Attempt to continue if archives are unlocatable\n"
1620 " -u Show a list of upgraded packages as well\n"
1621 " -b Build the source package after fetching it\n"
1622 " -V Show verbose version numbers\n"
1623 " -c=? Read this configuration file\n"
1624 " -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp\n"
1625 "See the apt-get(8), sources.list(5) and apt.conf(5) manual\n"
1626 "pages for more information and options.\n"
1627 " This APT has Super Cow Powers.\n");
1628 return true;
1629 }
1630 /*}}}*/
1631 int main(int argc,const char *argv[]) /*{{{*/
1632 {
1633 CommandLine::Dispatch Cmds[] = {{"update",&DoUpdate},
1634 {"upgrade",&DoUpgrade},
1635 {"install",&DoInstall},
1636 {"remove",&DoInstall},
1637 {"purge",&DoInstall},
1638 {"autoremove",&DoInstall},
1639 {"auto-remove",&DoInstall},
1640 {"markauto",&DoMarkAuto},
1641 {"unmarkauto",&DoMarkAuto},
1642 {"dist-upgrade",&DoDistUpgrade},
1643 {"full-upgrade",&DoDistUpgrade},
1644 {"dselect-upgrade",&DoDSelectUpgrade},
1645 {"build-dep",&DoBuildDep},
1646 {"clean",&DoClean},
1647 {"autoclean",&DoAutoClean},
1648 {"auto-clean",&DoAutoClean},
1649 {"check",&DoCheck},
1650 {"source",&DoSource},
1651 {"download",&DoDownload},
1652 {"changelog",&DoChangelog},
1653 {"indextargets",&DoIndexTargets},
1654 {"moo",&DoMoo},
1655 {"help",&ShowHelp},
1656 {0,0}};
1657
1658 std::vector<CommandLine::Args> Args = getCommandArgs("apt-get", CommandLine::GetCommand(Cmds, argc, argv));
1659
1660 // Set up gettext support
1661 setlocale(LC_ALL,"");
1662 textdomain(PACKAGE);
1663
1664 // Parse the command line and initialize the package library
1665 CommandLine CmdL;
1666 ParseCommandLine(CmdL, Cmds, Args.data(), &_config, &_system, argc, argv, ShowHelp);
1667
1668 // see if we are in simulate mode
1669 CheckSimulateMode(CmdL);
1670
1671 // Init the signals
1672 InitSignals();
1673
1674 // Setup the output streams
1675 InitOutput();
1676
1677 // Match the operation
1678 CmdL.DispatchArg(Cmds);
1679
1680 // Print any errors or warnings found during parsing
1681 bool const Errors = _error->PendingError();
1682 if (_config->FindI("quiet",0) > 0)
1683 _error->DumpErrors();
1684 else
1685 _error->DumpErrors(GlobalError::DEBUG);
1686 return Errors == true ? 100 : 0;
1687 }
1688 /*}}}*/