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