]> git.saurik.com Git - apt.git/blob - apt-pkg/policy.cc
370819e0bc9ea4a9c14e034adc4f767a75789b1f
[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
30 #include <ctype.h>
31 #include <stddef.h>
32 #include <string.h>
33 #include <string>
34 #include <vector>
35 #include <iostream>
36 #include <sstream>
37
38 #include <apti18n.h>
39 /*}}}*/
40
41 using namespace std;
42
43 // Policy::Init - Startup and bind to a cache /*{{{*/
44 // ---------------------------------------------------------------------
45 /* Set the defaults for operation. The default mode with no loaded policy
46 file matches the V0 policy engine. */
47 pkgPolicy::pkgPolicy(pkgCache *Owner) : Pins(0), PFPriority(0), Cache(Owner)
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 SPtrArray<bool> Fixed = new bool[Cache->HeaderP->PackageFileCount];
102 memset(Fixed,0,sizeof(*Fixed)*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 // Look for a package pin and evaluate it.
135 signed Max = GetPriority(Pkg);
136 pkgCache::VerIterator Pref = GetMatch(Pkg);
137
138 // Alternatives in case we can not find our package pin (Bug#512318).
139 signed MaxAlt = 0;
140 pkgCache::VerIterator PrefAlt;
141
142 // no package = no candidate version
143 if (Pkg.end() == true)
144 return Pref;
145
146 // packages with a pin lower than 0 have no newer candidate than the current version
147 if (Max < 0)
148 return Pkg.CurrentVer();
149
150 /* Falling through to the default version.. Setting Max to zero
151 effectively excludes everything <= 0 which are the non-automatic
152 priorities.. The status file is given a prio of 100 which will exclude
153 not-automatic sources, except in a single shot not-installed mode.
154
155 The user pin is subject to the same priority rules as default
156 selections. Thus there are two ways to create a pin - a pin that
157 tracks the default when the default is taken away, and a permanent
158 pin that stays at that setting.
159 */
160 bool PrefSeen = false;
161 for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
162 {
163 /* Lets see if this version is the installed version */
164 bool instVer = (Pkg.CurrentVer() == Ver);
165
166 if (Pref == Ver)
167 PrefSeen = true;
168
169 for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
170 {
171 /* If this is the status file, and the current version is not the
172 version in the status file (ie it is not installed, or somesuch)
173 then it is not a candidate for installation, ever. This weeds
174 out bogus entries that may be due to config-file states, or
175 other. */
176 if (VF.File().Flagged(pkgCache::Flag::NotSource) && instVer == false)
177 continue;
178
179 signed Prio = PFPriority[VF.File()->ID];
180 if (Prio > Max)
181 {
182 Pref = Ver;
183 Max = Prio;
184 PrefSeen = true;
185 }
186 if (Prio > MaxAlt)
187 {
188 PrefAlt = Ver;
189 MaxAlt = Prio;
190 }
191 }
192
193 if (instVer == true && Max < 1000)
194 {
195 /* Not having seen the Pref yet means we have a specific pin below 1000
196 on a version below the current installed one, so ignore the specific pin
197 as this would be a downgrade otherwise */
198 if (PrefSeen == false || Pref.end() == true)
199 {
200 Pref = Ver;
201 PrefSeen = true;
202 }
203 /* Elevate our current selection (or the status file itself) so that only
204 a downgrade can override it from now on */
205 Max = 999;
206
207 // Fast path optimize.
208 if (StatusOverride == false)
209 break;
210 }
211 }
212 // If we do not find our candidate, use the one with the highest pin.
213 // This means that if there is a version available with pin > 0; there
214 // will always be a candidate (Closes: #512318)
215 if (!Pref.IsGood() && MaxAlt > 0)
216 Pref = PrefAlt;
217
218 return Pref;
219 }
220 /*}}}*/
221 // Policy::CreatePin - Create an entry in the pin table.. /*{{{*/
222 // ---------------------------------------------------------------------
223 /* For performance we have 3 tables, the default table, the main cache
224 table (hashed to the cache). A blank package name indicates the pin
225 belongs to the default table. Order of insertion matters here, the
226 earlier defaults override later ones. */
227 void pkgPolicy::CreatePin(pkgVersionMatch::MatchType Type,string Name,
228 string Data,signed short Priority)
229 {
230 if (Name.empty() == true)
231 {
232 Pin *P = &*Defaults.insert(Defaults.end(),Pin());
233 P->Type = Type;
234 P->Priority = Priority;
235 P->Data = Data;
236 return;
237 }
238
239 size_t found = Name.rfind(':');
240 string Arch;
241 if (found != string::npos) {
242 Arch = Name.substr(found+1);
243 Name.erase(found);
244 }
245
246 // Allow pinning by wildcards
247 // TODO: Maybe we should always prefer specific pins over non-
248 // specific ones.
249 if (Name[0] == '/' || Name.find_first_of("*[?") != string::npos)
250 {
251 pkgVersionMatch match(Data, Type);
252 for (pkgCache::GrpIterator G = Cache->GrpBegin(); G.end() != true; ++G)
253 if (match.ExpressionMatches(Name, G.Name()))
254 {
255 if (Arch.empty() == false)
256 CreatePin(Type, string(G.Name()).append(":").append(Arch), Data, Priority);
257 else
258 CreatePin(Type, G.Name(), Data, Priority);
259 }
260 return;
261 }
262
263 // find the package (group) this pin applies to
264 pkgCache::GrpIterator Grp = Cache->FindGrp(Name);
265 bool matched = false;
266 if (Grp.end() == false)
267 {
268 std::string MatchingArch;
269 if (Arch.empty() == true)
270 MatchingArch = Cache->NativeArch();
271 else
272 MatchingArch = Arch;
273 APT::CacheFilter::PackageArchitectureMatchesSpecification pams(MatchingArch);
274 for (pkgCache::PkgIterator Pkg = Grp.PackageList(); Pkg.end() != true; Pkg = Grp.NextPkg(Pkg))
275 {
276 if (pams(Pkg.Arch()) == false)
277 continue;
278 Pin *P = Pins + Pkg->ID;
279 // the first specific stanza for a package is the ruler,
280 // all others need to be ignored
281 if (P->Type != pkgVersionMatch::None)
282 P = &*Unmatched.insert(Unmatched.end(),PkgPin(Pkg.FullName()));
283 P->Type = Type;
284 P->Priority = Priority;
285 P->Data = Data;
286 matched = true;
287
288 // Find matching version(s) and copy the pin into it
289 pkgVersionMatch Match(P->Data,P->Type);
290 for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() != true; Ver++)
291 {
292 if (Match.VersionMatches(Ver)) {
293 Pin *VP = VerPins + Ver->ID;
294 if (VP->Type == pkgVersionMatch::None)
295 *VP = *P;
296 }
297 }
298 }
299 }
300
301 if (matched == false)
302 {
303 PkgPin *P = &*Unmatched.insert(Unmatched.end(),PkgPin(Name));
304 if (Arch.empty() == false)
305 P->Pkg.append(":").append(Arch);
306 P->Type = Type;
307 P->Priority = Priority;
308 P->Data = Data;
309 return;
310 }
311 }
312 /*}}}*/
313 // Policy::GetMatch - Get the matching version for a package pin /*{{{*/
314 // ---------------------------------------------------------------------
315 /* */
316 pkgCache::VerIterator pkgPolicy::GetMatch(pkgCache::PkgIterator const &Pkg)
317 {
318 const Pin &PPkg = Pins[Pkg->ID];
319 if (PPkg.Type == pkgVersionMatch::None)
320 return pkgCache::VerIterator(*Pkg.Cache());
321
322 pkgVersionMatch Match(PPkg.Data,PPkg.Type);
323 return Match.Find(Pkg);
324 }
325 /*}}}*/
326 // Policy::GetPriority - Get the priority of the package pin /*{{{*/
327 // ---------------------------------------------------------------------
328 /* */
329 APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgIterator const &Pkg)
330 {
331 if (Pins[Pkg->ID].Type != pkgVersionMatch::None)
332 return Pins[Pkg->ID].Priority;
333 return 0;
334 }
335 APT_PURE signed short pkgPolicy::GetPriority(pkgCache::VerIterator const &Ver)
336 {
337 if (VerPins[Ver->ID].Type != pkgVersionMatch::None)
338 return VerPins[Ver->ID].Priority;
339 return 0;
340 }
341 APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgFileIterator const &File)
342 {
343 return PFPriority[File->ID];
344 }
345 /*}}}*/
346 // PreferenceSection class - Overriding the default TrimRecord method /*{{{*/
347 // ---------------------------------------------------------------------
348 /* The preference file is a user generated file so the parser should
349 therefore be a bit more friendly by allowing comments and new lines
350 all over the place rather than forcing a special format */
351 class PreferenceSection : public pkgTagSection
352 {
353 void TrimRecord(bool /*BeforeRecord*/, const char* &End)
354 {
355 for (; Stop < End && (Stop[0] == '\n' || Stop[0] == '\r' || Stop[0] == '#'); Stop++)
356 if (Stop[0] == '#')
357 Stop = (const char*) memchr(Stop,'\n',End-Stop);
358 }
359 };
360 /*}}}*/
361 // ReadPinDir - Load the pin files from this dir into a Policy /*{{{*/
362 // ---------------------------------------------------------------------
363 /* This will load each pin file in the given dir into a Policy. If the
364 given dir is empty the dir set in Dir::Etc::PreferencesParts is used.
365 Note also that this method will issue a warning if the dir does not
366 exists but it will return true in this case! */
367 bool ReadPinDir(pkgPolicy &Plcy,string Dir)
368 {
369 if (Dir.empty() == true)
370 Dir = _config->FindDir("Dir::Etc::PreferencesParts");
371
372 if (DirectoryExists(Dir) == false)
373 {
374 _error->WarningE("DirectoryExists",_("Unable to read %s"),Dir.c_str());
375 return true;
376 }
377
378 vector<string> const List = GetListOfFilesInDir(Dir, "pref", true, true);
379
380 // Read the files
381 for (vector<string>::const_iterator I = List.begin(); I != List.end(); ++I)
382 if (ReadPinFile(Plcy, *I) == false)
383 return false;
384 return true;
385 }
386 /*}}}*/
387 // ReadPinFile - Load the pin file into a Policy /*{{{*/
388 // ---------------------------------------------------------------------
389 /* I'd like to see the preferences file store more than just pin information
390 but right now that is the only stuff I have to store. Later there will
391 have to be some kind of combined super parser to get the data into all
392 the right classes.. */
393 bool ReadPinFile(pkgPolicy &Plcy,string File)
394 {
395 if (File.empty() == true)
396 File = _config->FindFile("Dir::Etc::Preferences");
397
398 if (RealFileExists(File) == false)
399 return true;
400
401 FileFd Fd(File,FileFd::ReadOnly);
402 pkgTagFile TF(&Fd);
403 if (_error->PendingError() == true)
404 return false;
405
406 PreferenceSection Tags;
407 while (TF.Step(Tags) == true)
408 {
409 // can happen when there are only comments in a record
410 if (Tags.Count() == 0)
411 continue;
412
413 string Name = Tags.FindS("Package");
414 if (Name.empty() == true)
415 return _error->Error(_("Invalid record in the preferences file %s, no Package header"), File.c_str());
416 if (Name == "*")
417 Name = string();
418
419 const char *Start;
420 const char *End;
421 if (Tags.Find("Pin",Start,End) == false)
422 continue;
423
424 const char *Word = Start;
425 for (; Word != End && isspace(*Word) == 0; Word++);
426
427 // Parse the type..
428 pkgVersionMatch::MatchType Type;
429 if (stringcasecmp(Start,Word,"version") == 0 && Name.empty() == false)
430 Type = pkgVersionMatch::Version;
431 else if (stringcasecmp(Start,Word,"release") == 0)
432 Type = pkgVersionMatch::Release;
433 else if (stringcasecmp(Start,Word,"origin") == 0)
434 Type = pkgVersionMatch::Origin;
435 else
436 {
437 _error->Warning(_("Did not understand pin type %s"),string(Start,Word).c_str());
438 continue;
439 }
440 for (; Word != End && isspace(*Word) != 0; Word++);
441
442 short int priority = Tags.FindI("Pin-Priority", 0);
443 if (priority == 0)
444 {
445 _error->Warning(_("No priority (or zero) specified for pin"));
446 continue;
447 }
448
449 istringstream s(Name);
450 string pkg;
451 while(!s.eof())
452 {
453 s >> pkg;
454 Plcy.CreatePin(Type, pkg, string(Word,End),priority);
455 };
456 }
457
458 Plcy.InitDefaults();
459 return true;
460 }
461 /*}}}*/
462
463 pkgPolicy::~pkgPolicy() {delete [] PFPriority; delete [] Pins; delete [] VerPins; }