policy.cc 14 KB

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