policy.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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/cacheiterators.h>
  21. #include <apt-pkg/pkgcache.h>
  22. #include <apt-pkg/versionmatch.h>
  23. #include <apt-pkg/version.h>
  24. #include <ctype.h>
  25. #include <stddef.h>
  26. #include <string.h>
  27. #include <string>
  28. #include <vector>
  29. #include <iostream>
  30. #include <apti18n.h>
  31. /*}}}*/
  32. using namespace std;
  33. // Policy::Init - Startup and bind to a cache /*{{{*/
  34. // ---------------------------------------------------------------------
  35. /* Set the defaults for operation. The default mode with no loaded policy
  36. file matches the V0 policy engine. */
  37. pkgPolicy::pkgPolicy(pkgCache *Owner) : Pins(nullptr), VerPins(nullptr),
  38. PFPriority(nullptr), Cache(Owner), d(NULL)
  39. {
  40. if (Owner == 0)
  41. return;
  42. PFPriority = new signed short[Owner->Head().PackageFileCount];
  43. Pins = new Pin[Owner->Head().PackageCount];
  44. VerPins = new Pin[Owner->Head().VersionCount];
  45. for (unsigned long I = 0; I != Owner->Head().PackageCount; I++)
  46. Pins[I].Type = pkgVersionMatch::None;
  47. for (unsigned long I = 0; I != Owner->Head().VersionCount; I++)
  48. VerPins[I].Type = pkgVersionMatch::None;
  49. // The config file has a master override.
  50. string DefRel = _config->Find("APT::Default-Release");
  51. if (DefRel.empty() == false)
  52. {
  53. bool found = false;
  54. // FIXME: make ExpressionMatches static to use it here easily
  55. pkgVersionMatch vm("", pkgVersionMatch::None);
  56. for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
  57. {
  58. if (vm.ExpressionMatches(DefRel, F.Archive()) ||
  59. vm.ExpressionMatches(DefRel, F.Codename()) ||
  60. vm.ExpressionMatches(DefRel, F.Version()) ||
  61. (DefRel.length() > 2 && DefRel[1] == '='))
  62. found = true;
  63. }
  64. if (found == false)
  65. _error->Error(_("The value '%s' is invalid for APT::Default-Release as such a release is not available in the sources"), DefRel.c_str());
  66. else
  67. CreatePin(pkgVersionMatch::Release,"",DefRel,990);
  68. }
  69. InitDefaults();
  70. }
  71. /*}}}*/
  72. // Policy::InitDefaults - Compute the default selections /*{{{*/
  73. // ---------------------------------------------------------------------
  74. /* */
  75. bool pkgPolicy::InitDefaults()
  76. {
  77. // Initialize the priorities based on the status of the package file
  78. for (pkgCache::PkgFileIterator I = Cache->FileBegin(); I != Cache->FileEnd(); ++I)
  79. {
  80. PFPriority[I->ID] = 500;
  81. if (I.Flagged(pkgCache::Flag::NotSource))
  82. PFPriority[I->ID] = 100;
  83. else if (I.Flagged(pkgCache::Flag::ButAutomaticUpgrades))
  84. PFPriority[I->ID] = 100;
  85. else if (I.Flagged(pkgCache::Flag::NotAutomatic))
  86. PFPriority[I->ID] = 1;
  87. }
  88. // Apply the defaults..
  89. std::unique_ptr<bool[]> Fixed(new bool[Cache->HeaderP->PackageFileCount]);
  90. memset(Fixed.get(),0,sizeof(Fixed[0])*Cache->HeaderP->PackageFileCount);
  91. StatusOverride = false;
  92. for (vector<Pin>::const_iterator I = Defaults.begin(); I != Defaults.end(); ++I)
  93. {
  94. pkgVersionMatch Match(I->Data,I->Type);
  95. for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
  96. {
  97. if (Fixed[F->ID] == false && Match.FileMatch(F) == true)
  98. {
  99. PFPriority[F->ID] = I->Priority;
  100. if (PFPriority[F->ID] >= 1000)
  101. StatusOverride = true;
  102. Fixed[F->ID] = true;
  103. }
  104. }
  105. }
  106. if (_config->FindB("Debug::pkgPolicy",false) == true)
  107. for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
  108. std::clog << "Prio of " << F.FileName() << ' ' << PFPriority[F->ID] << std::endl;
  109. return true;
  110. }
  111. /*}}}*/
  112. // Policy::GetCandidateVer - Get the candidate install version /*{{{*/
  113. // ---------------------------------------------------------------------
  114. /* Evaluate the package pins and the default list to deteremine what the
  115. best package is. */
  116. pkgCache::VerIterator pkgPolicy::GetCandidateVer(pkgCache::PkgIterator const &Pkg)
  117. {
  118. if (_config->FindI("APT::Policy", 1) >= 1) {
  119. return GetCandidateVerNew(Pkg);
  120. }
  121. // Look for a package pin and evaluate it.
  122. signed Max = GetPriority(Pkg);
  123. pkgCache::VerIterator Pref = GetMatch(Pkg);
  124. // Alternatives in case we can not find our package pin (Bug#512318).
  125. signed MaxAlt = 0;
  126. pkgCache::VerIterator PrefAlt;
  127. // no package = no candidate version
  128. if (Pkg.end() == true)
  129. return Pref;
  130. // packages with a pin lower than 0 have no newer candidate than the current version
  131. if (Max < 0)
  132. return Pkg.CurrentVer();
  133. /* Falling through to the default version.. Setting Max to zero
  134. effectively excludes everything <= 0 which are the non-automatic
  135. priorities.. The status file is given a prio of 100 which will exclude
  136. not-automatic sources, except in a single shot not-installed mode.
  137. The user pin is subject to the same priority rules as default
  138. selections. Thus there are two ways to create a pin - a pin that
  139. tracks the default when the default is taken away, and a permanent
  140. pin that stays at that setting.
  141. */
  142. bool PrefSeen = false;
  143. for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
  144. {
  145. /* Lets see if this version is the installed version */
  146. bool instVer = (Pkg.CurrentVer() == Ver);
  147. if (Pref == Ver)
  148. PrefSeen = true;
  149. for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
  150. {
  151. /* If this is the status file, and the current version is not the
  152. version in the status file (ie it is not installed, or somesuch)
  153. then it is not a candidate for installation, ever. This weeds
  154. out bogus entries that may be due to config-file states, or
  155. other. */
  156. if (VF.File().Flagged(pkgCache::Flag::NotSource) && instVer == false)
  157. continue;
  158. signed Prio = PFPriority[VF.File()->ID];
  159. if (Prio > Max)
  160. {
  161. Pref = Ver;
  162. Max = Prio;
  163. PrefSeen = true;
  164. }
  165. if (Prio > MaxAlt)
  166. {
  167. PrefAlt = Ver;
  168. MaxAlt = Prio;
  169. }
  170. }
  171. if (instVer == true && Max < 1000)
  172. {
  173. /* Not having seen the Pref yet means we have a specific pin below 1000
  174. on a version below the current installed one, so ignore the specific pin
  175. as this would be a downgrade otherwise */
  176. if (PrefSeen == false || Pref.end() == true)
  177. {
  178. Pref = Ver;
  179. PrefSeen = true;
  180. }
  181. /* Elevate our current selection (or the status file itself) so that only
  182. a downgrade can override it from now on */
  183. Max = 999;
  184. // Fast path optimize.
  185. if (StatusOverride == false)
  186. break;
  187. }
  188. }
  189. // If we do not find our candidate, use the one with the highest pin.
  190. // This means that if there is a version available with pin > 0; there
  191. // will always be a candidate (Closes: #512318)
  192. if (!Pref.IsGood() && MaxAlt > 0)
  193. Pref = PrefAlt;
  194. return Pref;
  195. }
  196. // Policy::GetCandidateVer - Get the candidate install version /*{{{*/
  197. // ---------------------------------------------------------------------
  198. /* Evaluate the package pins and the default list to deteremine what the
  199. best package is. */
  200. pkgCache::VerIterator pkgPolicy::GetCandidateVerNew(pkgCache::PkgIterator const &Pkg)
  201. {
  202. // TODO: Replace GetCandidateVer()
  203. pkgCache::VerIterator cand;
  204. pkgCache::VerIterator cur = Pkg.CurrentVer();
  205. int candPriority = -1;
  206. pkgVersioningSystem *vs = Cache->VS;
  207. for (pkgCache::VerIterator ver = Pkg.VersionList(); ver.end() == false; ver++) {
  208. int priority = GetPriority(ver);
  209. if (priority == 0 || priority <= candPriority)
  210. continue;
  211. // TODO: Maybe optimize to not compare versions
  212. if (!cur.end() && priority < 1000
  213. && (vs->CmpVersion(ver.VerStr(), cur.VerStr()) < 0))
  214. continue;
  215. candPriority = priority;
  216. cand = ver;
  217. }
  218. return cand;
  219. }
  220. /*}}}*/
  221. // Policy::CreatePin - Create an entry in the pin table.. /*{{{*/
  222. // ---------------------------------------------------------------------
  223. /* For performance we have 3 tables, the default table, the main cache
  224. table (hashed to the cache). A blank package name indicates the pin
  225. belongs to the default table. Order of insertion matters here, the
  226. earlier defaults override later ones. */
  227. void pkgPolicy::CreatePin(pkgVersionMatch::MatchType Type,string Name,
  228. string Data,signed short Priority)
  229. {
  230. if (Name.empty() == true)
  231. {
  232. Pin *P = &*Defaults.insert(Defaults.end(),Pin());
  233. P->Type = Type;
  234. P->Priority = Priority;
  235. P->Data = Data;
  236. return;
  237. }
  238. size_t found = Name.rfind(':');
  239. string Arch;
  240. if (found != string::npos) {
  241. Arch = Name.substr(found+1);
  242. Name.erase(found);
  243. }
  244. // Allow pinning by wildcards
  245. // TODO: Maybe we should always prefer specific pins over non-
  246. // specific ones.
  247. if (Name[0] == '/' || Name.find_first_of("*[?") != string::npos)
  248. {
  249. pkgVersionMatch match(Data, Type);
  250. for (pkgCache::GrpIterator G = Cache->GrpBegin(); G.end() != true; ++G)
  251. if (match.ExpressionMatches(Name, G.Name()))
  252. {
  253. if (Arch.empty() == false)
  254. CreatePin(Type, string(G.Name()).append(":").append(Arch), Data, Priority);
  255. else
  256. CreatePin(Type, G.Name(), Data, Priority);
  257. }
  258. return;
  259. }
  260. // find the package (group) this pin applies to
  261. pkgCache::GrpIterator Grp = Cache->FindGrp(Name);
  262. bool matched = false;
  263. if (Grp.end() == false)
  264. {
  265. std::string MatchingArch;
  266. if (Arch.empty() == true)
  267. MatchingArch = Cache->NativeArch();
  268. else
  269. MatchingArch = Arch;
  270. APT::CacheFilter::PackageArchitectureMatchesSpecification pams(MatchingArch);
  271. for (pkgCache::PkgIterator Pkg = Grp.PackageList(); Pkg.end() != true; Pkg = Grp.NextPkg(Pkg))
  272. {
  273. if (pams(Pkg.Arch()) == false)
  274. continue;
  275. Pin *P = Pins + Pkg->ID;
  276. // the first specific stanza for a package is the ruler,
  277. // all others need to be ignored
  278. if (P->Type != pkgVersionMatch::None)
  279. P = &*Unmatched.insert(Unmatched.end(),PkgPin(Pkg.FullName()));
  280. P->Type = Type;
  281. P->Priority = Priority;
  282. P->Data = Data;
  283. matched = true;
  284. // Find matching version(s) and copy the pin into it
  285. pkgVersionMatch Match(P->Data,P->Type);
  286. for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() != true; Ver++)
  287. {
  288. if (Match.VersionMatches(Ver)) {
  289. Pin *VP = VerPins + Ver->ID;
  290. if (VP->Type == pkgVersionMatch::None)
  291. *VP = *P;
  292. }
  293. }
  294. }
  295. }
  296. if (matched == false)
  297. {
  298. PkgPin *P = &*Unmatched.insert(Unmatched.end(),PkgPin(Name));
  299. if (Arch.empty() == false)
  300. P->Pkg.append(":").append(Arch);
  301. P->Type = Type;
  302. P->Priority = Priority;
  303. P->Data = Data;
  304. return;
  305. }
  306. }
  307. /*}}}*/
  308. // Policy::GetMatch - Get the matching version for a package pin /*{{{*/
  309. // ---------------------------------------------------------------------
  310. /* */
  311. pkgCache::VerIterator pkgPolicy::GetMatch(pkgCache::PkgIterator const &Pkg)
  312. {
  313. const Pin &PPkg = Pins[Pkg->ID];
  314. if (PPkg.Type == pkgVersionMatch::None)
  315. return pkgCache::VerIterator(*Pkg.Cache());
  316. pkgVersionMatch Match(PPkg.Data,PPkg.Type);
  317. return Match.Find(Pkg);
  318. }
  319. /*}}}*/
  320. // Policy::GetPriority - Get the priority of the package pin /*{{{*/
  321. // ---------------------------------------------------------------------
  322. /* */
  323. APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgIterator const &Pkg)
  324. {
  325. if (Pins[Pkg->ID].Type != pkgVersionMatch::None)
  326. return Pins[Pkg->ID].Priority;
  327. return 0;
  328. }
  329. APT_PURE signed short pkgPolicy::GetPriority(pkgCache::VerIterator const &Ver, bool ConsiderFiles)
  330. {
  331. if (VerPins[Ver->ID].Type != pkgVersionMatch::None)
  332. return VerPins[Ver->ID].Priority;
  333. if (!ConsiderFiles)
  334. return 0;
  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. int priority = Tags.FindI("Pin-Priority", 0);
  427. if (priority < std::numeric_limits<short>::min() ||
  428. priority > std::numeric_limits<short>::max() ||
  429. _error->PendingError()) {
  430. return _error->Error(_("%s: Value %s is outside the range of valid pin priorities (%d to %d)"),
  431. File.c_str(), Tags.FindS("Pin-Priority").c_str(),
  432. std::numeric_limits<short>::min(),
  433. std::numeric_limits<short>::max());
  434. }
  435. if (priority == 0)
  436. {
  437. return _error->Error(_("No priority (or zero) specified for pin"));
  438. }
  439. istringstream s(Name);
  440. string pkg;
  441. while(!s.eof())
  442. {
  443. s >> pkg;
  444. Plcy.CreatePin(Type, pkg, string(Word,End),priority);
  445. };
  446. }
  447. Plcy.InitDefaults();
  448. return true;
  449. }
  450. /*}}}*/
  451. pkgPolicy::~pkgPolicy() {delete [] PFPriority; delete [] Pins; delete [] VerPins; }