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