]> git.saurik.com Git - apt.git/blame - apt-pkg/policy.cc
versionmatch: Extract version match checking out of Find()
[apt.git] / apt-pkg / policy.cc
CommitLineData
b2e465d6
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
56298634 3// $Id: policy.cc,v 1.10 2003/08/12 00:17:37 mdz Exp $
b2e465d6
AL
4/* ######################################################################
5
6 Package Version Policy implementation
3f732aa6 7
b2e465d6
AL
8 This is just a really simple wrapper around pkgVersionMatch with
9 some added goodies to manage the list of things..
3f732aa6
DK
10
11 See man apt_preferences for what value means what.
12
b2e465d6
AL
13 ##################################################################### */
14 /*}}}*/
15// Include Files /*{{{*/
ea542140
DK
16#include<config.h>
17
b2e465d6
AL
18#include <apt-pkg/policy.h>
19#include <apt-pkg/configuration.h>
9ed80cdd 20#include <apt-pkg/cachefilter.h>
b2e465d6
AL
21#include <apt-pkg/tagfile.h>
22#include <apt-pkg/strutl.h>
46e39c8e 23#include <apt-pkg/fileutl.h>
b2e465d6
AL
24#include <apt-pkg/error.h>
25#include <apt-pkg/sptr.h>
453b82a3
DK
26#include <apt-pkg/cacheiterators.h>
27#include <apt-pkg/pkgcache.h>
28#include <apt-pkg/versionmatch.h>
46e39c8e 29
453b82a3
DK
30#include <ctype.h>
31#include <stddef.h>
32#include <string.h>
33#include <string>
34#include <vector>
e7b470ee 35#include <iostream>
1c62ab24 36#include <sstream>
ea542140
DK
37
38#include <apti18n.h>
b2e465d6
AL
39 /*}}}*/
40
e7b470ee
AL
41using namespace std;
42
b2e465d6
AL
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. */
47pkgPolicy::pkgPolicy(pkgCache *Owner) : Pins(0), PFPriority(0), Cache(Owner)
48{
3f732aa6 49 if (Owner == 0)
c55b8a54 50 return;
b2e465d6
AL
51 PFPriority = new signed short[Owner->Head().PackageFileCount];
52 Pins = new Pin[Owner->Head().PackageCount];
9fb02ab0 53 VerPins = new Pin[Owner->Head().VersionCount];
b2e465d6
AL
54
55 for (unsigned long I = 0; I != Owner->Head().PackageCount; I++)
56 Pins[I].Type = pkgVersionMatch::None;
9fb02ab0
JAK
57 for (unsigned long I = 0; I != Owner->Head().VersionCount; I++)
58 VerPins[I].Type = pkgVersionMatch::None;
b2e465d6
AL
59
60 // The config file has a master override.
61 string DefRel = _config->Find("APT::Default-Release");
62 if (DefRel.empty() == false)
a3bbbab7
DK
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 {
b07aeb1a
DK
69 if (vm.ExpressionMatches(DefRel, F.Archive()) ||
70 vm.ExpressionMatches(DefRel, F.Codename()) ||
71 vm.ExpressionMatches(DefRel, F.Version()) ||
061c58b6 72 (DefRel.length() > 2 && DefRel[1] == '='))
a3bbbab7
DK
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 }
b2e465d6
AL
80 InitDefaults();
81}
82 /*}}}*/
83// Policy::InitDefaults - Compute the default selections /*{{{*/
84// ---------------------------------------------------------------------
85/* */
86bool pkgPolicy::InitDefaults()
87{
88 // Initialize the priorities based on the status of the package file
f7f0d6c7 89 for (pkgCache::PkgFileIterator I = Cache->FileBegin(); I != Cache->FileEnd(); ++I)
b2e465d6
AL
90 {
91 PFPriority[I->ID] = 500;
b07aeb1a 92 if (I.Flagged(pkgCache::Flag::NotSource))
b2e465d6 93 PFPriority[I->ID] = 100;
b07aeb1a 94 else if (I.Flagged(pkgCache::Flag::ButAutomaticUpgrades))
5ed56f93 95 PFPriority[I->ID] = 100;
b07aeb1a 96 else if (I.Flagged(pkgCache::Flag::NotAutomatic))
5ed56f93 97 PFPriority[I->ID] = 1;
b2e465d6
AL
98 }
99
100 // Apply the defaults..
20ebd488 101 SPtrArray<bool> Fixed = new bool[Cache->HeaderP->PackageFileCount];
b2e465d6 102 memset(Fixed,0,sizeof(*Fixed)*Cache->HeaderP->PackageFileCount);
b2e465d6 103 StatusOverride = false;
ab640001 104 for (vector<Pin>::const_iterator I = Defaults.begin(); I != Defaults.end(); ++I)
b2e465d6
AL
105 {
106 pkgVersionMatch Match(I->Data,I->Type);
f7f0d6c7 107 for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
b2e465d6 108 {
ab640001 109 if (Fixed[F->ID] == false && Match.FileMatch(F) == true)
b2e465d6 110 {
ab640001
DK
111 PFPriority[F->ID] = I->Priority;
112
3f732aa6 113 if (PFPriority[F->ID] >= 1000)
b2e465d6 114 StatusOverride = true;
ab640001 115
b2e465d6 116 Fixed[F->ID] = true;
ab640001
DK
117 }
118 }
b2e465d6
AL
119 }
120
121 if (_config->FindB("Debug::pkgPolicy",false) == true)
f7f0d6c7 122 for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
ab640001
DK
123 std::clog << "Prio of " << F.FileName() << ' ' << PFPriority[F->ID] << std::endl;
124
125 return true;
b2e465d6
AL
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. */
9ee8287e 132pkgCache::VerIterator pkgPolicy::GetCandidateVer(pkgCache::PkgIterator const &Pkg)
b2e465d6 133{
b2e465d6 134 // Look for a package pin and evaluate it.
af87ab54
AL
135 signed Max = GetPriority(Pkg);
136 pkgCache::VerIterator Pref = GetMatch(Pkg);
e7b470ee 137
8f5525e9
JAK
138 // Alternatives in case we can not find our package pin (Bug#512318).
139 signed MaxAlt = 0;
140 pkgCache::VerIterator PrefAlt;
141
9f5bf66a
DK
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
b2e465d6
AL
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.
3f732aa6 154
b2e465d6
AL
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 */
16808002 160 bool PrefSeen = false;
f7f0d6c7 161 for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
10639577 162 {
9ee8287e
DK
163 /* Lets see if this version is the installed version */
164 bool instVer = (Pkg.CurrentVer() == Ver);
9ee8287e 165
16808002
DK
166 if (Pref == Ver)
167 PrefSeen = true;
168
f7f0d6c7 169 for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
b2e465d6 170 {
6aeda9fa
AL
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. */
b07aeb1a 176 if (VF.File().Flagged(pkgCache::Flag::NotSource) && instVer == false)
6aeda9fa 177 continue;
9ee8287e 178
b2e465d6
AL
179 signed Prio = PFPriority[VF.File()->ID];
180 if (Prio > Max)
181 {
182 Pref = Ver;
183 Max = Prio;
16808002 184 PrefSeen = true;
8f5525e9
JAK
185 }
186 if (Prio > MaxAlt)
187 {
188 PrefAlt = Ver;
189 MaxAlt = Prio;
16808002
DK
190 }
191 }
192
9ee8287e 193 if (instVer == true && Max < 1000)
b2e465d6 194 {
16808002
DK
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 }
3f732aa6
DK
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;
16808002 206
b2e465d6
AL
207 // Fast path optimize.
208 if (StatusOverride == false)
209 break;
16808002 210 }
b2e465d6 211 }
8f5525e9
JAK
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;
9ee8287e 217
b2e465d6
AL
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. */
227void pkgPolicy::CreatePin(pkgVersionMatch::MatchType Type,string Name,
228 string Data,signed short Priority)
229{
b2e465d6 230 if (Name.empty() == true)
b2e465d6 231 {
00c6e1a3 232 Pin *P = &*Defaults.insert(Defaults.end(),Pin());
4a6d2163
DK
233 P->Type = Type;
234 P->Priority = Priority;
235 P->Data = Data;
236 return;
237 }
00c6e1a3
MV
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
1a4c9766
JAK
246 // Allow pinning by wildcards
247 // TODO: Maybe we should always prefer specific pins over non-
248 // specific ones.
a8d7c101
DK
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()))
00c6e1a3
MV
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 }
1a4c9766
JAK
260 return;
261 }
4a6d2163 262
00c6e1a3 263 // find the package (group) this pin applies to
9ed80cdd
DK
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 }
00c6e1a3
MV
288 }
289
9ed80cdd 290 if (matched == false)
4a6d2163 291 {
00c6e1a3
MV
292 PkgPin *P = &*Unmatched.insert(Unmatched.end(),PkgPin(Name));
293 if (Arch.empty() == false)
294 P->Pkg.append(":").append(Arch);
295 P->Type = Type;
296 P->Priority = Priority;
297 P->Data = Data;
298 return;
299 }
b2e465d6
AL
300}
301 /*}}}*/
af87ab54
AL
302// Policy::GetMatch - Get the matching version for a package pin /*{{{*/
303// ---------------------------------------------------------------------
304/* */
9ee8287e 305pkgCache::VerIterator pkgPolicy::GetMatch(pkgCache::PkgIterator const &Pkg)
af87ab54
AL
306{
307 const Pin &PPkg = Pins[Pkg->ID];
9ee8287e
DK
308 if (PPkg.Type == pkgVersionMatch::None)
309 return pkgCache::VerIterator(*Pkg.Cache());
310
311 pkgVersionMatch Match(PPkg.Data,PPkg.Type);
312 return Match.Find(Pkg);
af87ab54
AL
313}
314 /*}}}*/
315// Policy::GetPriority - Get the priority of the package pin /*{{{*/
316// ---------------------------------------------------------------------
317/* */
a02db58f 318APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgIterator const &Pkg)
af87ab54
AL
319{
320 if (Pins[Pkg->ID].Type != pkgVersionMatch::None)
af87ab54 321 return Pins[Pkg->ID].Priority;
af87ab54 322 return 0;
6d38011b 323}
9fb02ab0
JAK
324APT_PURE signed short pkgPolicy::GetPriority(pkgCache::VerIterator const &Ver)
325{
326 if (VerPins[Ver->ID].Type != pkgVersionMatch::None)
327 return VerPins[Ver->ID].Priority;
328 return 0;
329}
a02db58f 330APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgFileIterator const &File)
6d38011b
DK
331{
332 return PFPriority[File->ID];
af87ab54
AL
333}
334 /*}}}*/
81e9789b
MV
335// PreferenceSection class - Overriding the default TrimRecord method /*{{{*/
336// ---------------------------------------------------------------------
337/* The preference file is a user generated file so the parser should
338 therefore be a bit more friendly by allowing comments and new lines
339 all over the place rather than forcing a special format */
340class PreferenceSection : public pkgTagSection
341{
65512241 342 void TrimRecord(bool /*BeforeRecord*/, const char* &End)
81e9789b
MV
343 {
344 for (; Stop < End && (Stop[0] == '\n' || Stop[0] == '\r' || Stop[0] == '#'); Stop++)
345 if (Stop[0] == '#')
346 Stop = (const char*) memchr(Stop,'\n',End-Stop);
347 }
348};
349 /*}}}*/
ef1dff93
DK
350// ReadPinDir - Load the pin files from this dir into a Policy /*{{{*/
351// ---------------------------------------------------------------------
6009e60d
DK
352/* This will load each pin file in the given dir into a Policy. If the
353 given dir is empty the dir set in Dir::Etc::PreferencesParts is used.
354 Note also that this method will issue a warning if the dir does not
355 exists but it will return true in this case! */
e68ca100
JAK
356bool ReadPinDir(pkgPolicy &Plcy,string Dir)
357{
358 if (Dir.empty() == true)
359 Dir = _config->FindDir("Dir::Etc::PreferencesParts");
360
448eaf8b 361 if (DirectoryExists(Dir) == false)
6009e60d 362 {
448eaf8b 363 _error->WarningE("DirectoryExists",_("Unable to read %s"),Dir.c_str());
6009e60d
DK
364 return true;
365 }
366
b39c1859 367 vector<string> const List = GetListOfFilesInDir(Dir, "pref", true, true);
e68ca100
JAK
368
369 // Read the files
f7f0d6c7 370 for (vector<string>::const_iterator I = List.begin(); I != List.end(); ++I)
e68ca100
JAK
371 if (ReadPinFile(Plcy, *I) == false)
372 return false;
373 return true;
374}
81e9789b 375 /*}}}*/
b2e465d6
AL
376// ReadPinFile - Load the pin file into a Policy /*{{{*/
377// ---------------------------------------------------------------------
378/* I'd like to see the preferences file store more than just pin information
379 but right now that is the only stuff I have to store. Later there will
380 have to be some kind of combined super parser to get the data into all
381 the right classes.. */
382bool ReadPinFile(pkgPolicy &Plcy,string File)
383{
384 if (File.empty() == true)
385 File = _config->FindFile("Dir::Etc::Preferences");
386
36f1098a 387 if (RealFileExists(File) == false)
b2e465d6
AL
388 return true;
389
390 FileFd Fd(File,FileFd::ReadOnly);
391 pkgTagFile TF(&Fd);
392 if (_error->PendingError() == true)
393 return false;
394
81e9789b 395 PreferenceSection Tags;
b2e465d6
AL
396 while (TF.Step(Tags) == true)
397 {
75ab11ae
MV
398 // can happen when there are only comments in a record
399 if (Tags.Count() == 0)
400 continue;
401
b2e465d6
AL
402 string Name = Tags.FindS("Package");
403 if (Name.empty() == true)
e68ca100 404 return _error->Error(_("Invalid record in the preferences file %s, no Package header"), File.c_str());
b2e465d6
AL
405 if (Name == "*")
406 Name = string();
407
408 const char *Start;
409 const char *End;
410 if (Tags.Find("Pin",Start,End) == false)
411 continue;
412
413 const char *Word = Start;
414 for (; Word != End && isspace(*Word) == 0; Word++);
415
416 // Parse the type..
417 pkgVersionMatch::MatchType Type;
418 if (stringcasecmp(Start,Word,"version") == 0 && Name.empty() == false)
419 Type = pkgVersionMatch::Version;
420 else if (stringcasecmp(Start,Word,"release") == 0)
421 Type = pkgVersionMatch::Release;
422 else if (stringcasecmp(Start,Word,"origin") == 0)
423 Type = pkgVersionMatch::Origin;
424 else
425 {
426 _error->Warning(_("Did not understand pin type %s"),string(Start,Word).c_str());
427 continue;
428 }
429 for (; Word != End && isspace(*Word) != 0; Word++);
430
56298634
AL
431 short int priority = Tags.FindI("Pin-Priority", 0);
432 if (priority == 0)
433 {
434 _error->Warning(_("No priority (or zero) specified for pin"));
435 continue;
436 }
437
1c62ab24
MV
438 istringstream s(Name);
439 string pkg;
440 while(!s.eof())
441 {
442 s >> pkg;
443 Plcy.CreatePin(Type, pkg, string(Word,End),priority);
444 };
b2e465d6
AL
445 }
446
447 Plcy.InitDefaults();
448 return true;
449}
450 /*}}}*/
c8a4ce6c 451
9fb02ab0 452pkgPolicy::~pkgPolicy() {delete [] PFPriority; delete [] Pins; delete [] VerPins; }