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