policy.cc 12 KB

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