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/sptr.h>
26 #include <apt-pkg/cacheiterators.h>
27 #include <apt-pkg/pkgcache.h>
28 #include <apt-pkg/versionmatch.h>
43 // Policy::Init - Startup and bind to a cache /*{{{*/
44 // ---------------------------------------------------------------------
45 /* Set the defaults for operation. The default mode with no loaded policy
46 file matches the V0 policy engine. */
47 pkgPolicy::pkgPolicy(pkgCache
*Owner
) : Pins(0), PFPriority(0), Cache(Owner
)
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 SPtrArray
<bool> Fixed
= new bool[Cache
->HeaderP
->PackageFileCount
];
102 memset(Fixed
,0,sizeof(*Fixed
)*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 // Look for a package pin and evaluate it.
135 signed Max
= GetPriority(Pkg
);
136 pkgCache::VerIterator Pref
= GetMatch(Pkg
);
138 // Alternatives in case we can not find our package pin (Bug#512318).
140 pkgCache::VerIterator PrefAlt
;
142 // no package = no candidate version
143 if (Pkg
.end() == true)
146 // packages with a pin lower than 0 have no newer candidate than the current version
148 return Pkg
.CurrentVer();
150 /* Falling through to the default version.. Setting Max to zero
151 effectively excludes everything <= 0 which are the non-automatic
152 priorities.. The status file is given a prio of 100 which will exclude
153 not-automatic sources, except in a single shot not-installed mode.
155 The user pin is subject to the same priority rules as default
156 selections. Thus there are two ways to create a pin - a pin that
157 tracks the default when the default is taken away, and a permanent
158 pin that stays at that setting.
160 bool PrefSeen
= false;
161 for (pkgCache::VerIterator Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
163 /* Lets see if this version is the installed version */
164 bool instVer
= (Pkg
.CurrentVer() == Ver
);
169 for (pkgCache::VerFileIterator VF
= Ver
.FileList(); VF
.end() == false; ++VF
)
171 /* If this is the status file, and the current version is not the
172 version in the status file (ie it is not installed, or somesuch)
173 then it is not a candidate for installation, ever. This weeds
174 out bogus entries that may be due to config-file states, or
176 if (VF
.File().Flagged(pkgCache::Flag::NotSource
) && instVer
== false)
179 signed Prio
= PFPriority
[VF
.File()->ID
];
193 if (instVer
== true && Max
< 1000)
195 /* Not having seen the Pref yet means we have a specific pin below 1000
196 on a version below the current installed one, so ignore the specific pin
197 as this would be a downgrade otherwise */
198 if (PrefSeen
== false || Pref
.end() == true)
203 /* Elevate our current selection (or the status file itself) so that only
204 a downgrade can override it from now on */
207 // Fast path optimize.
208 if (StatusOverride
== false)
212 // If we do not find our candidate, use the one with the highest pin.
213 // This means that if there is a version available with pin > 0; there
214 // will always be a candidate (Closes: #512318)
215 if (!Pref
.IsGood() && MaxAlt
> 0)
221 // Policy::CreatePin - Create an entry in the pin table.. /*{{{*/
222 // ---------------------------------------------------------------------
223 /* For performance we have 3 tables, the default table, the main cache
224 table (hashed to the cache). A blank package name indicates the pin
225 belongs to the default table. Order of insertion matters here, the
226 earlier defaults override later ones. */
227 void pkgPolicy::CreatePin(pkgVersionMatch::MatchType Type
,string Name
,
228 string Data
,signed short Priority
)
230 if (Name
.empty() == true)
232 Pin
*P
= &*Defaults
.insert(Defaults
.end(),Pin());
234 P
->Priority
= Priority
;
239 size_t found
= Name
.rfind(':');
241 if (found
!= string::npos
) {
242 Arch
= Name
.substr(found
+1);
246 // Allow pinning by wildcards
247 // TODO: Maybe we should always prefer specific pins over non-
249 if (Name
[0] == '/' || Name
.find_first_of("*[?") != string::npos
)
251 pkgVersionMatch
match(Data
, Type
);
252 for (pkgCache::GrpIterator G
= Cache
->GrpBegin(); G
.end() != true; ++G
)
253 if (match
.ExpressionMatches(Name
, G
.Name()))
255 if (Arch
.empty() == false)
256 CreatePin(Type
, string(G
.Name()).append(":").append(Arch
), Data
, Priority
);
258 CreatePin(Type
, G
.Name(), Data
, Priority
);
263 // find the package (group) this pin applies to
264 pkgCache::GrpIterator Grp
= Cache
->FindGrp(Name
);
265 bool matched
= false;
266 if (Grp
.end() == false)
268 std::string MatchingArch
;
269 if (Arch
.empty() == true)
270 MatchingArch
= Cache
->NativeArch();
273 APT::CacheFilter::PackageArchitectureMatchesSpecification
pams(MatchingArch
);
274 for (pkgCache::PkgIterator Pkg
= Grp
.PackageList(); Pkg
.end() != true; Pkg
= Grp
.NextPkg(Pkg
))
276 if (pams(Pkg
.Arch()) == false)
278 Pin
*P
= Pins
+ Pkg
->ID
;
279 // the first specific stanza for a package is the ruler,
280 // all others need to be ignored
281 if (P
->Type
!= pkgVersionMatch::None
)
282 P
= &*Unmatched
.insert(Unmatched
.end(),PkgPin(Pkg
.FullName()));
284 P
->Priority
= Priority
;
288 // Find matching version(s) and copy the pin into it
289 pkgVersionMatch
Match(P
->Data
,P
->Type
);
290 for (pkgCache::VerIterator Ver
= Pkg
.VersionList(); Ver
.end() != true; Ver
++)
292 if (Match
.VersionMatches(Ver
)) {
293 Pin
*VP
= VerPins
+ Ver
->ID
;
294 if (VP
->Type
== pkgVersionMatch::None
)
301 if (matched
== false)
303 PkgPin
*P
= &*Unmatched
.insert(Unmatched
.end(),PkgPin(Name
));
304 if (Arch
.empty() == false)
305 P
->Pkg
.append(":").append(Arch
);
307 P
->Priority
= Priority
;
313 // Policy::GetMatch - Get the matching version for a package pin /*{{{*/
314 // ---------------------------------------------------------------------
316 pkgCache::VerIterator
pkgPolicy::GetMatch(pkgCache::PkgIterator
const &Pkg
)
318 const Pin
&PPkg
= Pins
[Pkg
->ID
];
319 if (PPkg
.Type
== pkgVersionMatch::None
)
320 return pkgCache::VerIterator(*Pkg
.Cache());
322 pkgVersionMatch
Match(PPkg
.Data
,PPkg
.Type
);
323 return Match
.Find(Pkg
);
326 // Policy::GetPriority - Get the priority of the package pin /*{{{*/
327 // ---------------------------------------------------------------------
329 APT_PURE
signed short pkgPolicy::GetPriority(pkgCache::PkgIterator
const &Pkg
)
331 if (Pins
[Pkg
->ID
].Type
!= pkgVersionMatch::None
)
332 return Pins
[Pkg
->ID
].Priority
;
335 APT_PURE
signed short pkgPolicy::GetPriority(pkgCache::VerIterator
const &Ver
)
337 if (VerPins
[Ver
->ID
].Type
!= pkgVersionMatch::None
)
338 return VerPins
[Ver
->ID
].Priority
;
341 APT_PURE
signed short pkgPolicy::GetPriority(pkgCache::PkgFileIterator
const &File
)
343 return PFPriority
[File
->ID
];
346 // PreferenceSection class - Overriding the default TrimRecord method /*{{{*/
347 // ---------------------------------------------------------------------
348 /* The preference file is a user generated file so the parser should
349 therefore be a bit more friendly by allowing comments and new lines
350 all over the place rather than forcing a special format */
351 class PreferenceSection
: public pkgTagSection
353 void TrimRecord(bool /*BeforeRecord*/, const char* &End
)
355 for (; Stop
< End
&& (Stop
[0] == '\n' || Stop
[0] == '\r' || Stop
[0] == '#'); Stop
++)
357 Stop
= (const char*) memchr(Stop
,'\n',End
-Stop
);
361 // ReadPinDir - Load the pin files from this dir into a Policy /*{{{*/
362 // ---------------------------------------------------------------------
363 /* This will load each pin file in the given dir into a Policy. If the
364 given dir is empty the dir set in Dir::Etc::PreferencesParts is used.
365 Note also that this method will issue a warning if the dir does not
366 exists but it will return true in this case! */
367 bool ReadPinDir(pkgPolicy
&Plcy
,string Dir
)
369 if (Dir
.empty() == true)
370 Dir
= _config
->FindDir("Dir::Etc::PreferencesParts");
372 if (DirectoryExists(Dir
) == false)
374 _error
->WarningE("DirectoryExists",_("Unable to read %s"),Dir
.c_str());
378 vector
<string
> const List
= GetListOfFilesInDir(Dir
, "pref", true, true);
381 for (vector
<string
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
382 if (ReadPinFile(Plcy
, *I
) == false)
387 // ReadPinFile - Load the pin file into a Policy /*{{{*/
388 // ---------------------------------------------------------------------
389 /* I'd like to see the preferences file store more than just pin information
390 but right now that is the only stuff I have to store. Later there will
391 have to be some kind of combined super parser to get the data into all
392 the right classes.. */
393 bool ReadPinFile(pkgPolicy
&Plcy
,string File
)
395 if (File
.empty() == true)
396 File
= _config
->FindFile("Dir::Etc::Preferences");
398 if (RealFileExists(File
) == false)
401 FileFd
Fd(File
,FileFd::ReadOnly
);
403 if (_error
->PendingError() == true)
406 PreferenceSection Tags
;
407 while (TF
.Step(Tags
) == true)
409 // can happen when there are only comments in a record
410 if (Tags
.Count() == 0)
413 string Name
= Tags
.FindS("Package");
414 if (Name
.empty() == true)
415 return _error
->Error(_("Invalid record in the preferences file %s, no Package header"), File
.c_str());
421 if (Tags
.Find("Pin",Start
,End
) == false)
424 const char *Word
= Start
;
425 for (; Word
!= End
&& isspace(*Word
) == 0; Word
++);
428 pkgVersionMatch::MatchType Type
;
429 if (stringcasecmp(Start
,Word
,"version") == 0 && Name
.empty() == false)
430 Type
= pkgVersionMatch::Version
;
431 else if (stringcasecmp(Start
,Word
,"release") == 0)
432 Type
= pkgVersionMatch::Release
;
433 else if (stringcasecmp(Start
,Word
,"origin") == 0)
434 Type
= pkgVersionMatch::Origin
;
437 _error
->Warning(_("Did not understand pin type %s"),string(Start
,Word
).c_str());
440 for (; Word
!= End
&& isspace(*Word
) != 0; Word
++);
442 short int priority
= Tags
.FindI("Pin-Priority", 0);
445 _error
->Warning(_("No priority (or zero) specified for pin"));
449 istringstream
s(Name
);
454 Plcy
.CreatePin(Type
, pkg
, string(Word
,End
),priority
);
463 pkgPolicy::~pkgPolicy() {delete [] PFPriority
; delete [] Pins
; delete [] VerPins
; }