policy.cc 15 KB

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