policy.cc 15 KB

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