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