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