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