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