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