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