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