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