policy.cc 15 KB

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