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