apt-get.cc 56 KB

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