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