apt-get.cc 56 KB

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