policy.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: policy.cc,v 1.10 2003/08/12 00:17:37 mdz Exp $
  4. /* ######################################################################
  5. Package Version Policy implementation
  6. This is just a really simple wrapper around pkgVersionMatch with
  7. some added goodies to manage the list of things..
  8. See man apt_preferences for what value means what.
  9. ##################################################################### */
  10. /*}}}*/
  11. // Include Files /*{{{*/
  12. #include<config.h>
  13. #include <apt-pkg/policy.h>
  14. #include <apt-pkg/configuration.h>
  15. #include <apt-pkg/cachefilter.h>
  16. #include <apt-pkg/tagfile.h>
  17. #include <apt-pkg/strutl.h>
  18. #include <apt-pkg/fileutl.h>
  19. #include <apt-pkg/error.h>
  20. #include <apt-pkg/sptr.h>
  21. #include <apt-pkg/cacheiterators.h>
  22. #include <apt-pkg/pkgcache.h>
  23. #include <apt-pkg/versionmatch.h>
  24. #include <apt-pkg/version.h>
  25. #include <ctype.h>
  26. #include <stddef.h>
  27. #include <string.h>
  28. #include <string>
  29. #include <vector>
  30. #include <iostream>
  31. #include <sstream>
  32. #include <apti18n.h>
  33. /*}}}*/
  34. using namespace std;
  35. // Policy::Init - Startup and bind to a cache /*{{{*/
  36. // ---------------------------------------------------------------------
  37. /* Set the defaults for operation. The default mode with no loaded policy
  38. file matches the V0 policy engine. */
  39. pkgPolicy::pkgPolicy(pkgCache *Owner) : Pins(nullptr), VerPins(nullptr),
  40. PFPriority(nullptr), Cache(Owner), d(NULL)
  41. {
  42. if (Owner == 0)
  43. return;
  44. PFPriority = new signed short[Owner->Head().PackageFileCount];
  45. Pins = new Pin[Owner->Head().PackageCount];
  46. VerPins = new Pin[Owner->Head().VersionCount];
  47. for (unsigned long I = 0; I != Owner->Head().PackageCount; I++)
  48. Pins[I].Type = pkgVersionMatch::None;
  49. for (unsigned long I = 0; I != Owner->Head().VersionCount; I++)
  50. VerPins[I].Type = pkgVersionMatch::None;
  51. // The config file has a master override.
  52. string DefRel = _config->Find("APT::Default-Release");
  53. if (DefRel.empty() == false)
  54. {
  55. bool found = false;
  56. // FIXME: make ExpressionMatches static to use it here easily
  57. pkgVersionMatch vm("", pkgVersionMatch::None);
  58. for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
  59. {
  60. if (vm.ExpressionMatches(DefRel, F.Archive()) ||
  61. vm.ExpressionMatches(DefRel, F.Codename()) ||
  62. vm.ExpressionMatches(DefRel, F.Version()) ||
  63. (DefRel.length() > 2 && DefRel[1] == '='))
  64. found = true;
  65. }
  66. if (found == false)
  67. _error->Error(_("The value '%s' is invalid for APT::Default-Release as such a release is not available in the sources"), DefRel.c_str());
  68. else
  69. CreatePin(pkgVersionMatch::Release,"",DefRel,990);
  70. }
  71. InitDefaults();
  72. }
  73. /*}}}*/
  74. // Policy::InitDefaults - Compute the default selections /*{{{*/
  75. // ---------------------------------------------------------------------
  76. /* */
  77. bool pkgPolicy::InitDefaults()
  78. {
  79. // Initialize the priorities based on the status of the package file
  80. for (pkgCache::PkgFileIterator I = Cache->FileBegin(); I != Cache->FileEnd(); ++I)
  81. {
  82. PFPriority[I->ID] = 500;
  83. if (I.Flagged(pkgCache::Flag::NotSource))
  84. PFPriority[I->ID] = 100;
  85. else if (I.Flagged(pkgCache::Flag::ButAutomaticUpgrades))
  86. PFPriority[I->ID] = 100;
  87. else if (I.Flagged(pkgCache::Flag::NotAutomatic))
  88. PFPriority[I->ID] = 1;
  89. }
  90. // Apply the defaults..
  91. SPtrArray<bool> Fixed = new bool[Cache->HeaderP->PackageFileCount];
  92. memset(Fixed,0,sizeof(*Fixed)*Cache->HeaderP->PackageFileCount);
  93. StatusOverride = false;
  94. for (vector<Pin>::const_iterator I = Defaults.begin(); I != Defaults.end(); ++I)
  95. {
  96. pkgVersionMatch Match(I->Data,I->Type);
  97. for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
  98. {
  99. if (Fixed[F->ID] == false && Match.FileMatch(F) == true)
  100. {
  101. PFPriority[F->ID] = I->Priority;
  102. if (PFPriority[F->ID] >= 1000)
  103. StatusOverride = true;
  104. Fixed[F->ID] = true;
  105. }
  106. }
  107. }
  108. if (_config->FindB("Debug::pkgPolicy",false) == true)
  109. for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
  110. std::clog << "Prio of " << F.FileName() << ' ' << PFPriority[F->ID] << std::endl;
  111. return true;
  112. }
  113. /*}}}*/
  114. // Policy::GetCandidateVer - Get the candidate install version /*{{{*/
  115. // ---------------------------------------------------------------------
  116. /* Evaluate the package pins and the default list to deteremine what the
  117. best package is. */
  118. pkgCache::VerIterator pkgPolicy::GetCandidateVer(pkgCache::PkgIterator const &Pkg)
  119. {
  120. if (_config->FindI("APT::Policy", 1) >= 1) {
  121. return GetCandidateVerNew(Pkg);
  122. }
  123. // Look for a package pin and evaluate it.
  124. signed Max = GetPriority(Pkg);
  125. pkgCache::VerIterator Pref = GetMatch(Pkg);
  126. // Alternatives in case we can not find our package pin (Bug#512318).
  127. signed MaxAlt = 0;
  128. pkgCache::VerIterator PrefAlt;
  129. // no package = no candidate version
  130. if (Pkg.end() == true)
  131. return Pref;
  132. // packages with a pin lower than 0 have no newer candidate than the current version
  133. if (Max < 0)
  134. return Pkg.CurrentVer();
  135. /* Falling through to the default version.. Setting Max to zero
  136. effectively excludes everything <= 0 which are the non-automatic
  137. priorities.. The status file is given a prio of 100 which will exclude
  138. not-automatic sources, except in a single shot not-installed mode.
  139. The user pin is subject to the same priority rules as default
  140. selections. Thus there are two ways to create a pin - a pin that
  141. tracks the default when the default is taken away, and a permanent
  142. pin that stays at that setting.
  143. */
  144. bool PrefSeen = false;
  145. for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
  146. {
  147. /* Lets see if this version is the installed version */
  148. bool instVer = (Pkg.CurrentVer() == Ver);
  149. if (Pref == Ver)
  150. PrefSeen = true;
  151. for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
  152. {
  153. /* If this is the status file, and the current version is not the
  154. version in the status file (ie it is not installed, or somesuch)
  155. then it is not a candidate for installation, ever. This weeds
  156. out bogus entries that may be due to config-file states, or
  157. other. */
  158. if (VF.File().Flagged(pkgCache::Flag::NotSource) && instVer == false)
  159. continue;
  160. signed Prio = PFPriority[VF.File()->ID];
  161. if (Prio > Max)
  162. {
  163. Pref = Ver;
  164. Max = Prio;
  165. PrefSeen = true;
  166. }
  167. if (Prio > MaxAlt)
  168. {
  169. PrefAlt = Ver;
  170. MaxAlt = Prio;
  171. }
  172. }
  173. if (instVer == true && Max < 1000)
  174. {
  175. /* Not having seen the Pref yet means we have a specific pin below 1000
  176. on a version below the current installed one, so ignore the specific pin
  177. as this would be a downgrade otherwise */
  178. if (PrefSeen == false || Pref.end() == true)
  179. {
  180. Pref = Ver;
  181. PrefSeen = true;
  182. }
  183. /* Elevate our current selection (or the status file itself) so that only
  184. a downgrade can override it from now on */
  185. Max = 999;
  186. // Fast path optimize.
  187. if (StatusOverride == false)
  188. break;
  189. }
  190. }
  191. // If we do not find our candidate, use the one with the highest pin.
  192. // This means that if there is a version available with pin > 0; there
  193. // will always be a candidate (Closes: #512318)
  194. if (!Pref.IsGood() && MaxAlt > 0)
  195. Pref = PrefAlt;
  196. return Pref;
  197. }
  198. // Policy::GetCandidateVer - Get the candidate install version /*{{{*/
  199. // ---------------------------------------------------------------------
  200. /* Evaluate the package pins and the default list to deteremine what the
  201. best package is. */
  202. pkgCache::VerIterator pkgPolicy::GetCandidateVerNew(pkgCache::PkgIterator const &Pkg)
  203. {
  204. // TODO: Replace GetCandidateVer()
  205. pkgCache::VerIterator cand;
  206. pkgCache::VerIterator cur = Pkg.CurrentVer();
  207. int candPriority = -1;
  208. pkgVersioningSystem *vs = Cache->VS;
  209. for (pkgCache::VerIterator ver = Pkg.VersionList(); ver.end() == false; ver++) {
  210. int priority = GetPriority(ver);
  211. if (priority == 0 || priority <= candPriority)
  212. continue;
  213. // TODO: Maybe optimize to not compare versions
  214. if (!cur.end() && priority < 1000
  215. && (vs->CmpVersion(ver.VerStr(), cur.VerStr()) < 0))
  216. continue;
  217. candPriority = priority;
  218. cand = ver;
  219. }
  220. return cand;
  221. }
  222. /*}}}*/
  223. // Policy::CreatePin - Create an entry in the pin table.. /*{{{*/
  224. // ---------------------------------------------------------------------
  225. /* For performance we have 3 tables, the default table, the main cache
  226. table (hashed to the cache). A blank package name indicates the pin
  227. belongs to the default table. Order of insertion matters here, the
  228. earlier defaults override later ones. */
  229. void pkgPolicy::CreatePin(pkgVersionMatch::MatchType Type,string Name,
  230. string Data,signed short Priority)
  231. {
  232. if (Name.empty() == true)
  233. {
  234. Pin *P = &*Defaults.insert(Defaults.end(),Pin());
  235. P->Type = Type;
  236. P->Priority = Priority;
  237. P->Data = Data;
  238. return;
  239. }
  240. size_t found = Name.rfind(':');
  241. string Arch;
  242. if (found != string::npos) {
  243. Arch = Name.substr(found+1);
  244. Name.erase(found);
  245. }
  246. // Allow pinning by wildcards
  247. // TODO: Maybe we should always prefer specific pins over non-
  248. // specific ones.
  249. if (Name[0] == '/' || Name.find_first_of("*[?") != string::npos)
  250. {
  251. pkgVersionMatch match(Data, Type);
  252. for (pkgCache::GrpIterator G = Cache->GrpBegin(); G.end() != true; ++G)
  253. if (match.ExpressionMatches(Name, G.Name()))
  254. {
  255. if (Arch.empty() == false)
  256. CreatePin(Type, string(G.Name()).append(":").append(Arch), Data, Priority);
  257. else
  258. CreatePin(Type, G.Name(), Data, Priority);
  259. }
  260. return;
  261. }
  262. // find the package (group) this pin applies to
  263. pkgCache::GrpIterator Grp = Cache->FindGrp(Name);
  264. bool matched = false;
  265. if (Grp.end() == false)
  266. {
  267. std::string MatchingArch;
  268. if (Arch.empty() == true)
  269. MatchingArch = Cache->NativeArch();
  270. else
  271. MatchingArch = Arch;
  272. APT::CacheFilter::PackageArchitectureMatchesSpecification pams(MatchingArch);
  273. for (pkgCache::PkgIterator Pkg = Grp.PackageList(); Pkg.end() != true; Pkg = Grp.NextPkg(Pkg))
  274. {
  275. if (pams(Pkg.Arch()) == false)
  276. continue;
  277. Pin *P = Pins + Pkg->ID;
  278. // the first specific stanza for a package is the ruler,
  279. // all others need to be ignored
  280. if (P->Type != pkgVersionMatch::None)
  281. P = &*Unmatched.insert(Unmatched.end(),PkgPin(Pkg.FullName()));
  282. P->Type = Type;
  283. P->Priority = Priority;
  284. P->Data = Data;
  285. matched = true;
  286. // Find matching version(s) and copy the pin into it
  287. pkgVersionMatch Match(P->Data,P->Type);
  288. for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() != true; Ver++)
  289. {
  290. if (Match.VersionMatches(Ver)) {
  291. Pin *VP = VerPins + Ver->ID;
  292. if (VP->Type == pkgVersionMatch::None)
  293. *VP = *P;
  294. }
  295. }
  296. }
  297. }
  298. if (matched == false)
  299. {
  300. PkgPin *P = &*Unmatched.insert(Unmatched.end(),PkgPin(Name));
  301. if (Arch.empty() == false)
  302. P->Pkg.append(":").append(Arch);
  303. P->Type = Type;
  304. P->Priority = Priority;
  305. P->Data = Data;
  306. return;
  307. }
  308. }
  309. /*}}}*/
  310. // Policy::GetMatch - Get the matching version for a package pin /*{{{*/
  311. // ---------------------------------------------------------------------
  312. /* */
  313. pkgCache::VerIterator pkgPolicy::GetMatch(pkgCache::PkgIterator const &Pkg)
  314. {
  315. const Pin &PPkg = Pins[Pkg->ID];
  316. if (PPkg.Type == pkgVersionMatch::None)
  317. return pkgCache::VerIterator(*Pkg.Cache());
  318. pkgVersionMatch Match(PPkg.Data,PPkg.Type);
  319. return Match.Find(Pkg);
  320. }
  321. /*}}}*/
  322. // Policy::GetPriority - Get the priority of the package pin /*{{{*/
  323. // ---------------------------------------------------------------------
  324. /* */
  325. APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgIterator const &Pkg)
  326. {
  327. if (Pins[Pkg->ID].Type != pkgVersionMatch::None)
  328. return Pins[Pkg->ID].Priority;
  329. return 0;
  330. }
  331. APT_PURE signed short pkgPolicy::GetPriority(pkgCache::VerIterator const &Ver)
  332. {
  333. if (VerPins[Ver->ID].Type != pkgVersionMatch::None)
  334. return VerPins[Ver->ID].Priority;
  335. int priority = std::numeric_limits<int>::min();
  336. for (pkgCache::VerFileIterator file = Ver.FileList(); file.end() == false; file++)
  337. {
  338. /* If this is the status file, and the current version is not the
  339. version in the status file (ie it is not installed, or somesuch)
  340. then it is not a candidate for installation, ever. This weeds
  341. out bogus entries that may be due to config-file states, or
  342. other. */
  343. if (file.File().Flagged(pkgCache::Flag::NotSource) && Ver.ParentPkg().CurrentVer() != Ver) {
  344. // Ignore
  345. } else if (GetPriority(file.File()) > priority) {
  346. priority = GetPriority(file.File());
  347. }
  348. }
  349. return priority == std::numeric_limits<int>::min() ? 0 : priority;
  350. }
  351. APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgFileIterator const &File)
  352. {
  353. return PFPriority[File->ID];
  354. }
  355. /*}}}*/
  356. // ReadPinDir - Load the pin files from this dir into a Policy /*{{{*/
  357. // ---------------------------------------------------------------------
  358. /* This will load each pin file in the given dir into a Policy. If the
  359. given dir is empty the dir set in Dir::Etc::PreferencesParts is used.
  360. Note also that this method will issue a warning if the dir does not
  361. exists but it will return true in this case! */
  362. bool ReadPinDir(pkgPolicy &Plcy,string Dir)
  363. {
  364. if (Dir.empty() == true)
  365. Dir = _config->FindDir("Dir::Etc::PreferencesParts");
  366. if (DirectoryExists(Dir) == false)
  367. {
  368. _error->WarningE("DirectoryExists",_("Unable to read %s"),Dir.c_str());
  369. return true;
  370. }
  371. vector<string> const List = GetListOfFilesInDir(Dir, "pref", true, true);
  372. // Read the files
  373. for (vector<string>::const_iterator I = List.begin(); I != List.end(); ++I)
  374. if (ReadPinFile(Plcy, *I) == false)
  375. return false;
  376. return true;
  377. }
  378. /*}}}*/
  379. // ReadPinFile - Load the pin file into a Policy /*{{{*/
  380. // ---------------------------------------------------------------------
  381. /* I'd like to see the preferences file store more than just pin information
  382. but right now that is the only stuff I have to store. Later there will
  383. have to be some kind of combined super parser to get the data into all
  384. the right classes.. */
  385. bool ReadPinFile(pkgPolicy &Plcy,string File)
  386. {
  387. if (File.empty() == true)
  388. File = _config->FindFile("Dir::Etc::Preferences");
  389. if (RealFileExists(File) == false)
  390. return true;
  391. FileFd Fd(File,FileFd::ReadOnly);
  392. pkgTagFile TF(&Fd);
  393. if (_error->PendingError() == true)
  394. return false;
  395. pkgUserTagSection Tags;
  396. while (TF.Step(Tags) == true)
  397. {
  398. // can happen when there are only comments in a record
  399. if (Tags.Count() == 0)
  400. continue;
  401. string Name = Tags.FindS("Package");
  402. if (Name.empty() == true)
  403. return _error->Error(_("Invalid record in the preferences file %s, no Package header"), File.c_str());
  404. if (Name == "*")
  405. Name = string();
  406. const char *Start;
  407. const char *End;
  408. if (Tags.Find("Pin",Start,End) == false)
  409. continue;
  410. const char *Word = Start;
  411. for (; Word != End && isspace(*Word) == 0; Word++);
  412. // Parse the type..
  413. pkgVersionMatch::MatchType Type;
  414. if (stringcasecmp(Start,Word,"version") == 0 && Name.empty() == false)
  415. Type = pkgVersionMatch::Version;
  416. else if (stringcasecmp(Start,Word,"release") == 0)
  417. Type = pkgVersionMatch::Release;
  418. else if (stringcasecmp(Start,Word,"origin") == 0)
  419. Type = pkgVersionMatch::Origin;
  420. else
  421. {
  422. _error->Warning(_("Did not understand pin type %s"),string(Start,Word).c_str());
  423. continue;
  424. }
  425. for (; Word != End && isspace(*Word) != 0; Word++);
  426. short int priority = Tags.FindI("Pin-Priority", 0);
  427. if (priority == 0)
  428. {
  429. _error->Warning(_("No priority (or zero) specified for pin"));
  430. continue;
  431. }
  432. istringstream s(Name);
  433. string pkg;
  434. while(!s.eof())
  435. {
  436. s >> pkg;
  437. Plcy.CreatePin(Type, pkg, string(Word,End),priority);
  438. };
  439. }
  440. Plcy.InitDefaults();
  441. return true;
  442. }
  443. /*}}}*/
  444. pkgPolicy::~pkgPolicy() {delete [] PFPriority; delete [] Pins; delete [] VerPins; }