You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

461 lines
15 KiB

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