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