1 // -*- mode: cpp; mode: fold -*-
3 // $Id: policy.cc,v 1.10 2003/08/12 00:17:37 mdz Exp $
4 /* ######################################################################
6 Package Version Policy implementation
8 This is just a really simple wrapper around pkgVersionMatch with
9 some added goodies to manage the list of things..
11 See man apt_preferences for what value means what.
13 ##################################################################### */
15 // Include Files /*{{{*/
18 #include <apt-pkg/policy.h>
19 #include <apt-pkg/configuration.h>
20 #include <apt-pkg/cachefilter.h>
21 #include <apt-pkg/tagfile.h>
22 #include <apt-pkg/strutl.h>
23 #include <apt-pkg/fileutl.h>
24 #include <apt-pkg/error.h>
25 #include <apt-pkg/cacheiterators.h>
26 #include <apt-pkg/pkgcache.h>
27 #include <apt-pkg/versionmatch.h>
28 #include <apt-pkg/version.h>
42 // Policy::Init - Startup and bind to a cache /*{{{*/
43 // ---------------------------------------------------------------------
44 /* Set the defaults for operation. The default mode with no loaded policy
45 file matches the V0 policy engine. */
46 pkgPolicy::pkgPolicy(pkgCache
*Owner
) : Pins(nullptr), VerPins(nullptr),
47 PFPriority(nullptr), Cache(Owner
), d(NULL
)
51 PFPriority
= new signed short[Owner
->Head().PackageFileCount
];
52 Pins
= new Pin
[Owner
->Head().PackageCount
];
53 VerPins
= new Pin
[Owner
->Head().VersionCount
];
55 for (unsigned long I
= 0; I
!= Owner
->Head().PackageCount
; I
++)
56 Pins
[I
].Type
= pkgVersionMatch::None
;
57 for (unsigned long I
= 0; I
!= Owner
->Head().VersionCount
; I
++)
58 VerPins
[I
].Type
= pkgVersionMatch::None
;
60 // The config file has a master override.
61 string DefRel
= _config
->Find("APT::Default-Release");
62 if (DefRel
.empty() == false)
65 // FIXME: make ExpressionMatches static to use it here easily
66 pkgVersionMatch
vm("", pkgVersionMatch::None
);
67 for (pkgCache::PkgFileIterator F
= Cache
->FileBegin(); F
!= Cache
->FileEnd(); ++F
)
69 if (vm
.ExpressionMatches(DefRel
, F
.Archive()) ||
70 vm
.ExpressionMatches(DefRel
, F
.Codename()) ||
71 vm
.ExpressionMatches(DefRel
, F
.Version()) ||
72 (DefRel
.length() > 2 && DefRel
[1] == '='))
76 _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 CreatePin(pkgVersionMatch::Release
,"",DefRel
,990);
83 // Policy::InitDefaults - Compute the default selections /*{{{*/
84 // ---------------------------------------------------------------------
86 bool pkgPolicy::InitDefaults()
88 // Initialize the priorities based on the status of the package file
89 for (pkgCache::PkgFileIterator I
= Cache
->FileBegin(); I
!= Cache
->FileEnd(); ++I
)
91 PFPriority
[I
->ID
] = 500;
92 if (I
.Flagged(pkgCache::Flag::NotSource
))
93 PFPriority
[I
->ID
] = 100;
94 else if (I
.Flagged(pkgCache::Flag::ButAutomaticUpgrades
))
95 PFPriority
[I
->ID
] = 100;
96 else if (I
.Flagged(pkgCache::Flag::NotAutomatic
))
97 PFPriority
[I
->ID
] = 1;
100 // Apply the defaults..
101 std::unique_ptr
<bool[]> Fixed(new bool[Cache
->HeaderP
->PackageFileCount
]);
102 memset(Fixed
.get(),0,sizeof(Fixed
[0])*Cache
->HeaderP
->PackageFileCount
);
103 StatusOverride
= false;
104 for (vector
<Pin
>::const_iterator I
= Defaults
.begin(); I
!= Defaults
.end(); ++I
)
106 pkgVersionMatch
Match(I
->Data
,I
->Type
);
107 for (pkgCache::PkgFileIterator F
= Cache
->FileBegin(); F
!= Cache
->FileEnd(); ++F
)
109 if (Fixed
[F
->ID
] == false && Match
.FileMatch(F
) == true)
111 PFPriority
[F
->ID
] = I
->Priority
;
113 if (PFPriority
[F
->ID
] >= 1000)
114 StatusOverride
= true;
121 if (_config
->FindB("Debug::pkgPolicy",false) == true)
122 for (pkgCache::PkgFileIterator F
= Cache
->FileBegin(); F
!= Cache
->FileEnd(); ++F
)
123 std::clog
<< "Prio of " << F
.FileName() << ' ' << PFPriority
[F
->ID
] << std::endl
;
128 // Policy::GetCandidateVer - Get the candidate install version /*{{{*/
129 // ---------------------------------------------------------------------
130 /* Evaluate the package pins and the default list to deteremine what the
132 pkgCache::VerIterator
pkgPolicy::GetCandidateVer(pkgCache::PkgIterator
const &Pkg
)
134 if (_config
->FindI("APT::Policy", 1) >= 1) {
135 return GetCandidateVerNew(Pkg
);
138 // Look for a package pin and evaluate it.
139 signed Max
= GetPriority(Pkg
);
140 pkgCache::VerIterator Pref
= GetMatch(Pkg
);
142 // Alternatives in case we can not find our package pin (Bug#512318).
144 pkgCache::VerIterator PrefAlt
;
146 // no package = no candidate version
147 if (Pkg
.end() == true)
150 // packages with a pin lower than 0 have no newer candidate than the current version
152 return Pkg
.CurrentVer();
154 /* Falling through to the default version.. Setting Max to zero
155 effectively excludes everything <= 0 which are the non-automatic
156 priorities.. The status file is given a prio of 100 which will exclude
157 not-automatic sources, except in a single shot not-installed mode.
159 The user pin is subject to the same priority rules as default
160 selections. Thus there are two ways to create a pin - a pin that
161 tracks the default when the default is taken away, and a permanent
162 pin that stays at that setting.
164 bool PrefSeen
= false;
165 for (pkgCache::VerIterator Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
167 /* Lets see if this version is the installed version */
168 bool instVer
= (Pkg
.CurrentVer() == Ver
);
173 for (pkgCache::VerFileIterator VF
= Ver
.FileList(); VF
.end() == false; ++VF
)
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
180 if (VF
.File().Flagged(pkgCache::Flag::NotSource
) && instVer
== false)
183 signed Prio
= PFPriority
[VF
.File()->ID
];
197 if (instVer
== true && Max
< 1000)
199 /* Not having seen the Pref yet means we have a specific pin below 1000
200 on a version below the current installed one, so ignore the specific pin
201 as this would be a downgrade otherwise */
202 if (PrefSeen
== false || Pref
.end() == true)
207 /* Elevate our current selection (or the status file itself) so that only
208 a downgrade can override it from now on */
211 // Fast path optimize.
212 if (StatusOverride
== false)
216 // If we do not find our candidate, use the one with the highest pin.
217 // This means that if there is a version available with pin > 0; there
218 // will always be a candidate (Closes: #512318)
219 if (!Pref
.IsGood() && MaxAlt
> 0)
225 // Policy::GetCandidateVer - Get the candidate install version /*{{{*/
226 // ---------------------------------------------------------------------
227 /* Evaluate the package pins and the default list to deteremine what the
229 pkgCache::VerIterator
pkgPolicy::GetCandidateVerNew(pkgCache::PkgIterator
const &Pkg
)
231 // TODO: Replace GetCandidateVer()
232 pkgCache::VerIterator cand
;
233 pkgCache::VerIterator cur
= Pkg
.CurrentVer();
234 int candPriority
= -1;
235 pkgVersioningSystem
*vs
= Cache
->VS
;
237 for (pkgCache::VerIterator ver
= Pkg
.VersionList(); ver
.end() == false; ver
++) {
238 int priority
= GetPriority(ver
);
240 if (priority
== 0 || priority
<= candPriority
)
243 // TODO: Maybe optimize to not compare versions
244 if (!cur
.end() && priority
< 1000
245 && (vs
->CmpVersion(ver
.VerStr(), cur
.VerStr()) < 0))
248 candPriority
= priority
;
255 // Policy::CreatePin - Create an entry in the pin table.. /*{{{*/
256 // ---------------------------------------------------------------------
257 /* For performance we have 3 tables, the default table, the main cache
258 table (hashed to the cache). A blank package name indicates the pin
259 belongs to the default table. Order of insertion matters here, the
260 earlier defaults override later ones. */
261 void pkgPolicy::CreatePin(pkgVersionMatch::MatchType Type
,string Name
,
262 string Data
,signed short Priority
)
264 if (Name
.empty() == true)
266 Pin
*P
= &*Defaults
.insert(Defaults
.end(),Pin());
268 P
->Priority
= Priority
;
273 size_t found
= Name
.rfind(':');
275 if (found
!= string::npos
) {
276 Arch
= Name
.substr(found
+1);
280 // Allow pinning by wildcards
281 // TODO: Maybe we should always prefer specific pins over non-
283 if (Name
[0] == '/' || Name
.find_first_of("*[?") != string::npos
)
285 pkgVersionMatch
match(Data
, Type
);
286 for (pkgCache::GrpIterator G
= Cache
->GrpBegin(); G
.end() != true; ++G
)
287 if (match
.ExpressionMatches(Name
, G
.Name()))
289 if (Arch
.empty() == false)
290 CreatePin(Type
, string(G
.Name()).append(":").append(Arch
), Data
, Priority
);
292 CreatePin(Type
, G
.Name(), Data
, Priority
);
297 // find the package (group) this pin applies to
298 pkgCache::GrpIterator Grp
= Cache
->FindGrp(Name
);
299 bool matched
= false;
300 if (Grp
.end() == false)
302 std::string MatchingArch
;
303 if (Arch
.empty() == true)
304 MatchingArch
= Cache
->NativeArch();
307 APT::CacheFilter::PackageArchitectureMatchesSpecification
pams(MatchingArch
);
308 for (pkgCache::PkgIterator Pkg
= Grp
.PackageList(); Pkg
.end() != true; Pkg
= Grp
.NextPkg(Pkg
))
310 if (pams(Pkg
.Arch()) == false)
312 Pin
*P
= Pins
+ Pkg
->ID
;
313 // the first specific stanza for a package is the ruler,
314 // all others need to be ignored
315 if (P
->Type
!= pkgVersionMatch::None
)
316 P
= &*Unmatched
.insert(Unmatched
.end(),PkgPin(Pkg
.FullName()));
318 P
->Priority
= Priority
;
322 // Find matching version(s) and copy the pin into it
323 pkgVersionMatch
Match(P
->Data
,P
->Type
);
324 for (pkgCache::VerIterator Ver
= Pkg
.VersionList(); Ver
.end() != true; Ver
++)
326 if (Match
.VersionMatches(Ver
)) {
327 Pin
*VP
= VerPins
+ Ver
->ID
;
328 if (VP
->Type
== pkgVersionMatch::None
)
335 if (matched
== false)
337 PkgPin
*P
= &*Unmatched
.insert(Unmatched
.end(),PkgPin(Name
));
338 if (Arch
.empty() == false)
339 P
->Pkg
.append(":").append(Arch
);
341 P
->Priority
= Priority
;
347 // Policy::GetMatch - Get the matching version for a package pin /*{{{*/
348 // ---------------------------------------------------------------------
350 pkgCache::VerIterator
pkgPolicy::GetMatch(pkgCache::PkgIterator
const &Pkg
)
352 const Pin
&PPkg
= Pins
[Pkg
->ID
];
353 if (PPkg
.Type
== pkgVersionMatch::None
)
354 return pkgCache::VerIterator(*Pkg
.Cache());
356 pkgVersionMatch
Match(PPkg
.Data
,PPkg
.Type
);
357 return Match
.Find(Pkg
);
360 // Policy::GetPriority - Get the priority of the package pin /*{{{*/
361 // ---------------------------------------------------------------------
363 APT_PURE
signed short pkgPolicy::GetPriority(pkgCache::PkgIterator
const &Pkg
)
365 if (Pins
[Pkg
->ID
].Type
!= pkgVersionMatch::None
)
366 return Pins
[Pkg
->ID
].Priority
;
369 APT_PURE
signed short pkgPolicy::GetPriority(pkgCache::VerIterator
const &Ver
, bool ConsiderFiles
)
371 if (VerPins
[Ver
->ID
].Type
!= pkgVersionMatch::None
)
372 return VerPins
[Ver
->ID
].Priority
;
376 int priority
= std::numeric_limits
<int>::min();
377 for (pkgCache::VerFileIterator file
= Ver
.FileList(); file
.end() == false; file
++)
379 /* If this is the status file, and the current version is not the
380 version in the status file (ie it is not installed, or somesuch)
381 then it is not a candidate for installation, ever. This weeds
382 out bogus entries that may be due to config-file states, or
384 if (file
.File().Flagged(pkgCache::Flag::NotSource
) && Ver
.ParentPkg().CurrentVer() != Ver
) {
386 } else if (GetPriority(file
.File()) > priority
) {
387 priority
= GetPriority(file
.File());
391 return priority
== std::numeric_limits
<int>::min() ? 0 : priority
;
393 APT_PURE
signed short pkgPolicy::GetPriority(pkgCache::PkgFileIterator
const &File
)
395 return PFPriority
[File
->ID
];
398 // ReadPinDir - Load the pin files from this dir into a Policy /*{{{*/
399 // ---------------------------------------------------------------------
400 /* This will load each pin file in the given dir into a Policy. If the
401 given dir is empty the dir set in Dir::Etc::PreferencesParts is used.
402 Note also that this method will issue a warning if the dir does not
403 exists but it will return true in this case! */
404 bool ReadPinDir(pkgPolicy
&Plcy
,string Dir
)
406 if (Dir
.empty() == true)
407 Dir
= _config
->FindDir("Dir::Etc::PreferencesParts");
409 if (DirectoryExists(Dir
) == false)
411 _error
->WarningE("DirectoryExists",_("Unable to read %s"),Dir
.c_str());
415 vector
<string
> const List
= GetListOfFilesInDir(Dir
, "pref", true, true);
418 for (vector
<string
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
419 if (ReadPinFile(Plcy
, *I
) == false)
424 // ReadPinFile - Load the pin file into a Policy /*{{{*/
425 // ---------------------------------------------------------------------
426 /* I'd like to see the preferences file store more than just pin information
427 but right now that is the only stuff I have to store. Later there will
428 have to be some kind of combined super parser to get the data into all
429 the right classes.. */
430 bool ReadPinFile(pkgPolicy
&Plcy
,string File
)
432 if (File
.empty() == true)
433 File
= _config
->FindFile("Dir::Etc::Preferences");
435 if (RealFileExists(File
) == false)
438 FileFd
Fd(File
,FileFd::ReadOnly
);
440 if (_error
->PendingError() == true)
443 pkgUserTagSection Tags
;
444 while (TF
.Step(Tags
) == true)
446 // can happen when there are only comments in a record
447 if (Tags
.Count() == 0)
450 string Name
= Tags
.FindS("Package");
451 if (Name
.empty() == true)
452 return _error
->Error(_("Invalid record in the preferences file %s, no Package header"), File
.c_str());
458 if (Tags
.Find("Pin",Start
,End
) == false)
461 const char *Word
= Start
;
462 for (; Word
!= End
&& isspace(*Word
) == 0; Word
++);
465 pkgVersionMatch::MatchType Type
;
466 if (stringcasecmp(Start
,Word
,"version") == 0 && Name
.empty() == false)
467 Type
= pkgVersionMatch::Version
;
468 else if (stringcasecmp(Start
,Word
,"release") == 0)
469 Type
= pkgVersionMatch::Release
;
470 else if (stringcasecmp(Start
,Word
,"origin") == 0)
471 Type
= pkgVersionMatch::Origin
;
474 _error
->Warning(_("Did not understand pin type %s"),string(Start
,Word
).c_str());
477 for (; Word
!= End
&& isspace(*Word
) != 0; Word
++);
479 int priority
= Tags
.FindI("Pin-Priority", 0);
480 if (priority
< std::numeric_limits
<short>::min() ||
481 priority
> std::numeric_limits
<short>::max() ||
482 _error
->PendingError()) {
483 return _error
->Error(_("%s: Value %s is outside the range of valid pin priorities (%d to %d)"),
484 File
.c_str(), Tags
.FindS("Pin-Priority").c_str(),
485 std::numeric_limits
<short>::min(),
486 std::numeric_limits
<short>::max());
490 return _error
->Error(_("No priority (or zero) specified for pin"));
493 istringstream
s(Name
);
498 Plcy
.CreatePin(Type
, pkg
, string(Word
,End
),priority
);
507 pkgPolicy::~pkgPolicy() {delete [] PFPriority
; delete [] Pins
; delete [] VerPins
; }