policy.cc 17 KB

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