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