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