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