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