apt-get.cc 55 KB

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