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