policy.cc 14 KB

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