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