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