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