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