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