policy.cc 13 KB

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