]> git.saurik.com Git - apt.git/blob - apt-pkg/policy.cc
Simply ignore cruft in the status files, do not treat it as prio 0
[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 See man apt_preferences for what value means what.
12
13 ##################################################################### */
14 /*}}}*/
15 // Include Files /*{{{*/
16 #include<config.h>
17
18 #include <apt-pkg/policy.h>
19 #include <apt-pkg/configuration.h>
20 #include <apt-pkg/cachefilter.h>
21 #include <apt-pkg/tagfile.h>
22 #include <apt-pkg/strutl.h>
23 #include <apt-pkg/fileutl.h>
24 #include <apt-pkg/error.h>
25 #include <apt-pkg/sptr.h>
26 #include <apt-pkg/cacheiterators.h>
27 #include <apt-pkg/pkgcache.h>
28 #include <apt-pkg/versionmatch.h>
29 #include <apt-pkg/version.h>
30
31 #include <ctype.h>
32 #include <stddef.h>
33 #include <string.h>
34 #include <string>
35 #include <vector>
36 #include <iostream>
37 #include <sstream>
38
39 #include <apti18n.h>
40 /*}}}*/
41
42 using namespace std;
43
44 // Policy::Init - Startup and bind to a cache /*{{{*/
45 // ---------------------------------------------------------------------
46 /* Set the defaults for operation. The default mode with no loaded policy
47 file matches the V0 policy engine. */
48 pkgPolicy::pkgPolicy(pkgCache *Owner) : Pins(nullptr), VerPins(nullptr),
49 PFPriority(nullptr), Cache(Owner), d(NULL)
50 {
51 if (Owner == 0)
52 return;
53 PFPriority = new signed short[Owner->Head().PackageFileCount];
54 Pins = new Pin[Owner->Head().PackageCount];
55 VerPins = new Pin[Owner->Head().VersionCount];
56
57 for (unsigned long I = 0; I != Owner->Head().PackageCount; I++)
58 Pins[I].Type = pkgVersionMatch::None;
59 for (unsigned long I = 0; I != Owner->Head().VersionCount; I++)
60 VerPins[I].Type = pkgVersionMatch::None;
61
62 // The config file has a master override.
63 string DefRel = _config->Find("APT::Default-Release");
64 if (DefRel.empty() == false)
65 {
66 bool found = false;
67 // FIXME: make ExpressionMatches static to use it here easily
68 pkgVersionMatch vm("", pkgVersionMatch::None);
69 for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
70 {
71 if (vm.ExpressionMatches(DefRel, F.Archive()) ||
72 vm.ExpressionMatches(DefRel, F.Codename()) ||
73 vm.ExpressionMatches(DefRel, F.Version()) ||
74 (DefRel.length() > 2 && DefRel[1] == '='))
75 found = true;
76 }
77 if (found == false)
78 _error->Error(_("The value '%s' is invalid for APT::Default-Release as such a release is not available in the sources"), DefRel.c_str());
79 else
80 CreatePin(pkgVersionMatch::Release,"",DefRel,990);
81 }
82 InitDefaults();
83 }
84 /*}}}*/
85 // Policy::InitDefaults - Compute the default selections /*{{{*/
86 // ---------------------------------------------------------------------
87 /* */
88 bool pkgPolicy::InitDefaults()
89 {
90 // Initialize the priorities based on the status of the package file
91 for (pkgCache::PkgFileIterator I = Cache->FileBegin(); I != Cache->FileEnd(); ++I)
92 {
93 PFPriority[I->ID] = 500;
94 if (I.Flagged(pkgCache::Flag::NotSource))
95 PFPriority[I->ID] = 100;
96 else if (I.Flagged(pkgCache::Flag::ButAutomaticUpgrades))
97 PFPriority[I->ID] = 100;
98 else if (I.Flagged(pkgCache::Flag::NotAutomatic))
99 PFPriority[I->ID] = 1;
100 }
101
102 // Apply the defaults..
103 SPtrArray<bool> Fixed = new bool[Cache->HeaderP->PackageFileCount];
104 memset(Fixed,0,sizeof(*Fixed)*Cache->HeaderP->PackageFileCount);
105 StatusOverride = false;
106 for (vector<Pin>::const_iterator I = Defaults.begin(); I != Defaults.end(); ++I)
107 {
108 pkgVersionMatch Match(I->Data,I->Type);
109 for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
110 {
111 if (Fixed[F->ID] == false && Match.FileMatch(F) == true)
112 {
113 PFPriority[F->ID] = I->Priority;
114
115 if (PFPriority[F->ID] >= 1000)
116 StatusOverride = true;
117
118 Fixed[F->ID] = true;
119 }
120 }
121 }
122
123 if (_config->FindB("Debug::pkgPolicy",false) == true)
124 for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
125 std::clog << "Prio of " << F.FileName() << ' ' << PFPriority[F->ID] << std::endl;
126
127 return true;
128 }
129 /*}}}*/
130 // Policy::GetCandidateVer - Get the candidate install version /*{{{*/
131 // ---------------------------------------------------------------------
132 /* Evaluate the package pins and the default list to deteremine what the
133 best package is. */
134 pkgCache::VerIterator pkgPolicy::GetCandidateVer(pkgCache::PkgIterator const &Pkg)
135 {
136 if (_config->FindI("APT::Policy", 1) >= 1) {
137 return GetCandidateVerNew(Pkg);
138 }
139
140 // Look for a package pin and evaluate it.
141 signed Max = GetPriority(Pkg);
142 pkgCache::VerIterator Pref = GetMatch(Pkg);
143
144 // Alternatives in case we can not find our package pin (Bug#512318).
145 signed MaxAlt = 0;
146 pkgCache::VerIterator PrefAlt;
147
148 // no package = no candidate version
149 if (Pkg.end() == true)
150 return Pref;
151
152 // packages with a pin lower than 0 have no newer candidate than the current version
153 if (Max < 0)
154 return Pkg.CurrentVer();
155
156 /* Falling through to the default version.. Setting Max to zero
157 effectively excludes everything <= 0 which are the non-automatic
158 priorities.. The status file is given a prio of 100 which will exclude
159 not-automatic sources, except in a single shot not-installed mode.
160
161 The user pin is subject to the same priority rules as default
162 selections. Thus there are two ways to create a pin - a pin that
163 tracks the default when the default is taken away, and a permanent
164 pin that stays at that setting.
165 */
166 bool PrefSeen = false;
167 for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
168 {
169 /* Lets see if this version is the installed version */
170 bool instVer = (Pkg.CurrentVer() == Ver);
171
172 if (Pref == Ver)
173 PrefSeen = true;
174
175 for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
176 {
177 /* If this is the status file, and the current version is not the
178 version in the status file (ie it is not installed, or somesuch)
179 then it is not a candidate for installation, ever. This weeds
180 out bogus entries that may be due to config-file states, or
181 other. */
182 if (VF.File().Flagged(pkgCache::Flag::NotSource) && instVer == false)
183 continue;
184
185 signed Prio = PFPriority[VF.File()->ID];
186 if (Prio > Max)
187 {
188 Pref = Ver;
189 Max = Prio;
190 PrefSeen = true;
191 }
192 if (Prio > MaxAlt)
193 {
194 PrefAlt = Ver;
195 MaxAlt = Prio;
196 }
197 }
198
199 if (instVer == true && Max < 1000)
200 {
201 /* Not having seen the Pref yet means we have a specific pin below 1000
202 on a version below the current installed one, so ignore the specific pin
203 as this would be a downgrade otherwise */
204 if (PrefSeen == false || Pref.end() == true)
205 {
206 Pref = Ver;
207 PrefSeen = true;
208 }
209 /* Elevate our current selection (or the status file itself) so that only
210 a downgrade can override it from now on */
211 Max = 999;
212
213 // Fast path optimize.
214 if (StatusOverride == false)
215 break;
216 }
217 }
218 // If we do not find our candidate, use the one with the highest pin.
219 // This means that if there is a version available with pin > 0; there
220 // will always be a candidate (Closes: #512318)
221 if (!Pref.IsGood() && MaxAlt > 0)
222 Pref = PrefAlt;
223
224 return Pref;
225 }
226
227 // Policy::GetCandidateVer - Get the candidate install version /*{{{*/
228 // ---------------------------------------------------------------------
229 /* Evaluate the package pins and the default list to deteremine what the
230 best package is. */
231 pkgCache::VerIterator pkgPolicy::GetCandidateVerNew(pkgCache::PkgIterator const &Pkg)
232 {
233 // TODO: Replace GetCandidateVer()
234 pkgCache::VerIterator cand;
235 pkgCache::VerIterator cur = Pkg.CurrentVer();
236 int candPriority = -1;
237 pkgVersioningSystem *vs = Cache->VS;
238
239 for (pkgCache::VerIterator ver = Pkg.VersionList(); ver.end() == false; ver++) {
240 int priority = GetPriority(ver);
241
242 if (priority == 0 || priority <= candPriority)
243 continue;
244
245 // TODO: Maybe optimize to not compare versions
246 if (!cur.end() && priority < 1000
247 && (vs->CmpVersion(ver.VerStr(), cur.VerStr()) < 0))
248 continue;
249
250 candPriority = priority;
251 cand = ver;
252 }
253
254 return cand;
255 }
256 /*}}}*/
257 // Policy::CreatePin - Create an entry in the pin table.. /*{{{*/
258 // ---------------------------------------------------------------------
259 /* For performance we have 3 tables, the default table, the main cache
260 table (hashed to the cache). A blank package name indicates the pin
261 belongs to the default table. Order of insertion matters here, the
262 earlier defaults override later ones. */
263 void pkgPolicy::CreatePin(pkgVersionMatch::MatchType Type,string Name,
264 string Data,signed short Priority)
265 {
266 if (Name.empty() == true)
267 {
268 Pin *P = &*Defaults.insert(Defaults.end(),Pin());
269 P->Type = Type;
270 P->Priority = Priority;
271 P->Data = Data;
272 return;
273 }
274
275 size_t found = Name.rfind(':');
276 string Arch;
277 if (found != string::npos) {
278 Arch = Name.substr(found+1);
279 Name.erase(found);
280 }
281
282 // Allow pinning by wildcards
283 // TODO: Maybe we should always prefer specific pins over non-
284 // specific ones.
285 if (Name[0] == '/' || Name.find_first_of("*[?") != string::npos)
286 {
287 pkgVersionMatch match(Data, Type);
288 for (pkgCache::GrpIterator G = Cache->GrpBegin(); G.end() != true; ++G)
289 if (match.ExpressionMatches(Name, G.Name()))
290 {
291 if (Arch.empty() == false)
292 CreatePin(Type, string(G.Name()).append(":").append(Arch), Data, Priority);
293 else
294 CreatePin(Type, G.Name(), Data, Priority);
295 }
296 return;
297 }
298
299 // find the package (group) this pin applies to
300 pkgCache::GrpIterator Grp = Cache->FindGrp(Name);
301 bool matched = false;
302 if (Grp.end() == false)
303 {
304 std::string MatchingArch;
305 if (Arch.empty() == true)
306 MatchingArch = Cache->NativeArch();
307 else
308 MatchingArch = Arch;
309 APT::CacheFilter::PackageArchitectureMatchesSpecification pams(MatchingArch);
310 for (pkgCache::PkgIterator Pkg = Grp.PackageList(); Pkg.end() != true; Pkg = Grp.NextPkg(Pkg))
311 {
312 if (pams(Pkg.Arch()) == false)
313 continue;
314 Pin *P = Pins + Pkg->ID;
315 // the first specific stanza for a package is the ruler,
316 // all others need to be ignored
317 if (P->Type != pkgVersionMatch::None)
318 P = &*Unmatched.insert(Unmatched.end(),PkgPin(Pkg.FullName()));
319 P->Type = Type;
320 P->Priority = Priority;
321 P->Data = Data;
322 matched = true;
323
324 // Find matching version(s) and copy the pin into it
325 pkgVersionMatch Match(P->Data,P->Type);
326 for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() != true; Ver++)
327 {
328 if (Match.VersionMatches(Ver)) {
329 Pin *VP = VerPins + Ver->ID;
330 if (VP->Type == pkgVersionMatch::None)
331 *VP = *P;
332 }
333 }
334 }
335 }
336
337 if (matched == false)
338 {
339 PkgPin *P = &*Unmatched.insert(Unmatched.end(),PkgPin(Name));
340 if (Arch.empty() == false)
341 P->Pkg.append(":").append(Arch);
342 P->Type = Type;
343 P->Priority = Priority;
344 P->Data = Data;
345 return;
346 }
347 }
348 /*}}}*/
349 // Policy::GetMatch - Get the matching version for a package pin /*{{{*/
350 // ---------------------------------------------------------------------
351 /* */
352 pkgCache::VerIterator pkgPolicy::GetMatch(pkgCache::PkgIterator const &Pkg)
353 {
354 const Pin &PPkg = Pins[Pkg->ID];
355 if (PPkg.Type == pkgVersionMatch::None)
356 return pkgCache::VerIterator(*Pkg.Cache());
357
358 pkgVersionMatch Match(PPkg.Data,PPkg.Type);
359 return Match.Find(Pkg);
360 }
361 /*}}}*/
362 // Policy::GetPriority - Get the priority of the package pin /*{{{*/
363 // ---------------------------------------------------------------------
364 /* */
365 APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgIterator const &Pkg)
366 {
367 if (Pins[Pkg->ID].Type != pkgVersionMatch::None)
368 return Pins[Pkg->ID].Priority;
369 return 0;
370 }
371 APT_PURE signed short pkgPolicy::GetPriority(pkgCache::VerIterator const &Ver)
372 {
373 if (VerPins[Ver->ID].Type != pkgVersionMatch::None)
374 return VerPins[Ver->ID].Priority;
375
376
377 int priority = std::numeric_limits<int>::min();
378 for (pkgCache::VerFileIterator file = Ver.FileList(); file.end() == false; file++)
379 {
380 /* If this is the status file, and the current version is not the
381 version in the status file (ie it is not installed, or somesuch)
382 then it is not a candidate for installation, ever. This weeds
383 out bogus entries that may be due to config-file states, or
384 other. */
385 if (file.File().Flagged(pkgCache::Flag::NotSource) && Ver.ParentPkg().CurrentVer() != Ver) {
386 // Ignore
387 } else if (GetPriority(file.File()) > priority) {
388 priority = GetPriority(file.File());
389 }
390 }
391
392 return priority == std::numeric_limits<int>::min() ? 0 : priority;
393 }
394 APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgFileIterator const &File)
395 {
396 return PFPriority[File->ID];
397 }
398 /*}}}*/
399 // ReadPinDir - Load the pin files from this dir into a Policy /*{{{*/
400 // ---------------------------------------------------------------------
401 /* This will load each pin file in the given dir into a Policy. If the
402 given dir is empty the dir set in Dir::Etc::PreferencesParts is used.
403 Note also that this method will issue a warning if the dir does not
404 exists but it will return true in this case! */
405 bool ReadPinDir(pkgPolicy &Plcy,string Dir)
406 {
407 if (Dir.empty() == true)
408 Dir = _config->FindDir("Dir::Etc::PreferencesParts");
409
410 if (DirectoryExists(Dir) == false)
411 {
412 _error->WarningE("DirectoryExists",_("Unable to read %s"),Dir.c_str());
413 return true;
414 }
415
416 vector<string> const List = GetListOfFilesInDir(Dir, "pref", true, true);
417
418 // Read the files
419 for (vector<string>::const_iterator I = List.begin(); I != List.end(); ++I)
420 if (ReadPinFile(Plcy, *I) == false)
421 return false;
422 return true;
423 }
424 /*}}}*/
425 // ReadPinFile - Load the pin file into a Policy /*{{{*/
426 // ---------------------------------------------------------------------
427 /* I'd like to see the preferences file store more than just pin information
428 but right now that is the only stuff I have to store. Later there will
429 have to be some kind of combined super parser to get the data into all
430 the right classes.. */
431 bool ReadPinFile(pkgPolicy &Plcy,string File)
432 {
433 if (File.empty() == true)
434 File = _config->FindFile("Dir::Etc::Preferences");
435
436 if (RealFileExists(File) == false)
437 return true;
438
439 FileFd Fd(File,FileFd::ReadOnly);
440 pkgTagFile TF(&Fd);
441 if (_error->PendingError() == true)
442 return false;
443
444 pkgUserTagSection Tags;
445 while (TF.Step(Tags) == true)
446 {
447 // can happen when there are only comments in a record
448 if (Tags.Count() == 0)
449 continue;
450
451 string Name = Tags.FindS("Package");
452 if (Name.empty() == true)
453 return _error->Error(_("Invalid record in the preferences file %s, no Package header"), File.c_str());
454 if (Name == "*")
455 Name = string();
456
457 const char *Start;
458 const char *End;
459 if (Tags.Find("Pin",Start,End) == false)
460 continue;
461
462 const char *Word = Start;
463 for (; Word != End && isspace(*Word) == 0; Word++);
464
465 // Parse the type..
466 pkgVersionMatch::MatchType Type;
467 if (stringcasecmp(Start,Word,"version") == 0 && Name.empty() == false)
468 Type = pkgVersionMatch::Version;
469 else if (stringcasecmp(Start,Word,"release") == 0)
470 Type = pkgVersionMatch::Release;
471 else if (stringcasecmp(Start,Word,"origin") == 0)
472 Type = pkgVersionMatch::Origin;
473 else
474 {
475 _error->Warning(_("Did not understand pin type %s"),string(Start,Word).c_str());
476 continue;
477 }
478 for (; Word != End && isspace(*Word) != 0; Word++);
479
480 short int priority = Tags.FindI("Pin-Priority", 0);
481 if (priority == 0)
482 {
483 _error->Warning(_("No priority (or zero) specified for pin"));
484 continue;
485 }
486
487 istringstream s(Name);
488 string pkg;
489 while(!s.eof())
490 {
491 s >> pkg;
492 Plcy.CreatePin(Type, pkg, string(Word,End),priority);
493 };
494 }
495
496 Plcy.InitDefaults();
497 return true;
498 }
499 /*}}}*/
500
501 pkgPolicy::~pkgPolicy() {delete [] PFPriority; delete [] Pins; delete [] VerPins; }