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>
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(nullptr), VerPins(nullptr),
48 PFPriority(nullptr), Cache(Owner
), d(NULL
)
52 PFPriority
= new signed short[Owner
->Head().PackageFileCount
];
53 Pins
= new Pin
[Owner
->Head().PackageCount
];
54 VerPins
= new Pin
[Owner
->Head().VersionCount
];
56 for (unsigned long I
= 0; I
!= Owner
->Head().PackageCount
; I
++)
57 Pins
[I
].Type
= pkgVersionMatch::None
;
58 for (unsigned long I
= 0; I
!= Owner
->Head().VersionCount
; I
++)
59 VerPins
[I
].Type
= pkgVersionMatch::None
;
61 // The config file has a master override.
62 string DefRel
= _config
->Find("APT::Default-Release");
63 if (DefRel
.empty() == 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
)
70 if (vm
.ExpressionMatches(DefRel
, F
.Archive()) ||
71 vm
.ExpressionMatches(DefRel
, F
.Codename()) ||
72 vm
.ExpressionMatches(DefRel
, F
.Version()) ||
73 (DefRel
.length() > 2 && DefRel
[1] == '='))
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());
79 CreatePin(pkgVersionMatch::Release
,"",DefRel
,990);
84 // Policy::InitDefaults - Compute the default selections /*{{{*/
85 // ---------------------------------------------------------------------
87 bool pkgPolicy::InitDefaults()
89 // Initialize the priorities based on the status of the package file
90 for (pkgCache::PkgFileIterator I
= Cache
->FileBegin(); I
!= Cache
->FileEnd(); ++I
)
92 PFPriority
[I
->ID
] = 500;
93 if (I
.Flagged(pkgCache::Flag::NotSource
))
94 PFPriority
[I
->ID
] = 100;
95 else if (I
.Flagged(pkgCache::Flag::ButAutomaticUpgrades
))
96 PFPriority
[I
->ID
] = 100;
97 else if (I
.Flagged(pkgCache::Flag::NotAutomatic
))
98 PFPriority
[I
->ID
] = 1;
101 // Apply the defaults..
102 std::unique_ptr
<bool[]> Fixed(new bool[Cache
->HeaderP
->PackageFileCount
]);
103 memset(Fixed
.get(),0,sizeof(Fixed
[0])*Cache
->HeaderP
->PackageFileCount
);
104 StatusOverride
= false;
105 for (vector
<Pin
>::const_iterator I
= Defaults
.begin(); I
!= Defaults
.end(); ++I
)
107 pkgVersionMatch
Match(I
->Data
,I
->Type
);
108 for (pkgCache::PkgFileIterator F
= Cache
->FileBegin(); F
!= Cache
->FileEnd(); ++F
)
110 if (Fixed
[F
->ID
] == false && Match
.FileMatch(F
) == true)
112 PFPriority
[F
->ID
] = I
->Priority
;
114 if (PFPriority
[F
->ID
] >= 1000)
115 StatusOverride
= true;
122 if (_config
->FindB("Debug::pkgPolicy",false) == true)
123 for (pkgCache::PkgFileIterator F
= Cache
->FileBegin(); F
!= Cache
->FileEnd(); ++F
)
124 std::clog
<< "Prio of " << F
.FileName() << ' ' << PFPriority
[F
->ID
] << std::endl
;
129 // Policy::GetCandidateVer - Get the candidate install version /*{{{*/
130 // ---------------------------------------------------------------------
131 /* Evaluate the package pins and the default list to deteremine what the
133 pkgCache::VerIterator
pkgPolicy::GetCandidateVer(pkgCache::PkgIterator
const &Pkg
)
135 pkgCache::VerIterator cand
;
136 pkgCache::VerIterator cur
= Pkg
.CurrentVer();
137 int candPriority
= -1;
138 pkgVersioningSystem
*vs
= Cache
->VS
;
140 for (pkgCache::VerIterator ver
= Pkg
.VersionList(); ver
.end() == false; ++ver
) {
141 int priority
= GetPriority(ver
, true);
143 if (priority
== 0 || priority
<= candPriority
)
146 // TODO: Maybe optimize to not compare versions
147 if (!cur
.end() && priority
< 1000
148 && (vs
->CmpVersion(ver
.VerStr(), cur
.VerStr()) < 0))
151 candPriority
= priority
;
158 // Policy::CreatePin - Create an entry in the pin table.. /*{{{*/
159 // ---------------------------------------------------------------------
160 /* For performance we have 3 tables, the default table, the main cache
161 table (hashed to the cache). A blank package name indicates the pin
162 belongs to the default table. Order of insertion matters here, the
163 earlier defaults override later ones. */
164 void pkgPolicy::CreatePin(pkgVersionMatch::MatchType Type
,string Name
,
165 string Data
,signed short Priority
)
167 if (Name
.empty() == true)
169 Pin
*P
= &*Defaults
.insert(Defaults
.end(),Pin());
171 P
->Priority
= Priority
;
176 size_t found
= Name
.rfind(':');
178 if (found
!= string::npos
) {
179 Arch
= Name
.substr(found
+1);
183 // Allow pinning by wildcards
184 // TODO: Maybe we should always prefer specific pins over non-
186 if (Name
[0] == '/' || Name
.find_first_of("*[?") != string::npos
)
188 pkgVersionMatch
match(Data
, Type
);
189 for (pkgCache::GrpIterator G
= Cache
->GrpBegin(); G
.end() != true; ++G
)
190 if (match
.ExpressionMatches(Name
, G
.Name()))
192 if (Arch
.empty() == false)
193 CreatePin(Type
, string(G
.Name()).append(":").append(Arch
), Data
, Priority
);
195 CreatePin(Type
, G
.Name(), Data
, Priority
);
200 // find the package (group) this pin applies to
201 pkgCache::GrpIterator Grp
= Cache
->FindGrp(Name
);
202 bool matched
= false;
203 if (Grp
.end() == false)
205 std::string MatchingArch
;
206 if (Arch
.empty() == true)
207 MatchingArch
= Cache
->NativeArch();
210 APT::CacheFilter::PackageArchitectureMatchesSpecification
pams(MatchingArch
);
211 for (pkgCache::PkgIterator Pkg
= Grp
.PackageList(); Pkg
.end() != true; Pkg
= Grp
.NextPkg(Pkg
))
213 if (pams(Pkg
.Arch()) == false)
215 Pin
*P
= Pins
+ Pkg
->ID
;
216 // the first specific stanza for a package is the ruler,
217 // all others need to be ignored
218 if (P
->Type
!= pkgVersionMatch::None
)
219 P
= &*Unmatched
.insert(Unmatched
.end(),PkgPin(Pkg
.FullName()));
221 P
->Priority
= Priority
;
225 // Find matching version(s) and copy the pin into it
226 pkgVersionMatch
Match(P
->Data
,P
->Type
);
227 for (pkgCache::VerIterator Ver
= Pkg
.VersionList(); Ver
.end() != true; ++Ver
)
229 if (Match
.VersionMatches(Ver
)) {
230 Pin
*VP
= VerPins
+ Ver
->ID
;
231 if (VP
->Type
== pkgVersionMatch::None
)
238 if (matched
== false)
240 PkgPin
*P
= &*Unmatched
.insert(Unmatched
.end(),PkgPin(Name
));
241 if (Arch
.empty() == false)
242 P
->Pkg
.append(":").append(Arch
);
244 P
->Priority
= Priority
;
250 // Policy::GetMatch - Get the matching version for a package pin /*{{{*/
251 // ---------------------------------------------------------------------
253 pkgCache::VerIterator
pkgPolicy::GetMatch(pkgCache::PkgIterator
const &Pkg
)
255 const Pin
&PPkg
= Pins
[Pkg
->ID
];
256 if (PPkg
.Type
== pkgVersionMatch::None
)
257 return pkgCache::VerIterator(*Pkg
.Cache());
259 pkgVersionMatch
Match(PPkg
.Data
,PPkg
.Type
);
260 return Match
.Find(Pkg
);
263 // Policy::GetPriority - Get the priority of the package pin /*{{{*/
264 // ---------------------------------------------------------------------
266 APT_PURE
signed short pkgPolicy::GetPriority(pkgCache::PkgIterator
const &Pkg
)
268 if (Pins
[Pkg
->ID
].Type
!= pkgVersionMatch::None
)
269 return Pins
[Pkg
->ID
].Priority
;
272 APT_PURE
signed short pkgPolicy::GetPriority(pkgCache::VerIterator
const &Ver
, bool ConsiderFiles
)
274 if (VerPins
[Ver
->ID
].Type
!= pkgVersionMatch::None
)
275 return VerPins
[Ver
->ID
].Priority
;
279 // priorities are short ints, but we want to pick a value outside the valid range here
280 auto priority
= std::numeric_limits
<signed int>::min();
281 for (pkgCache::VerFileIterator file
= Ver
.FileList(); file
.end() == false; file
++)
283 /* If this is the status file, and the current version is not the
284 version in the status file (ie it is not installed, or somesuch)
285 then it is not a candidate for installation, ever. This weeds
286 out bogus entries that may be due to config-file states, or
288 if (file
.File().Flagged(pkgCache::Flag::NotSource
) && Ver
.ParentPkg().CurrentVer() != Ver
)
289 priority
= std::max(priority
, static_cast<decltype(priority
)>(-1));
291 priority
= std::max(priority
, static_cast<decltype(priority
)>(GetPriority(file
.File())));
294 return priority
== std::numeric_limits
<decltype(priority
)>::min() ? 0 : priority
;
296 APT_PURE
signed short pkgPolicy::GetPriority(pkgCache::PkgFileIterator
const &File
)
298 return PFPriority
[File
->ID
];
301 // ReadPinDir - Load the pin files from this dir into a Policy /*{{{*/
302 // ---------------------------------------------------------------------
303 /* This will load each pin file in the given dir into a Policy. If the
304 given dir is empty the dir set in Dir::Etc::PreferencesParts is used.
305 Note also that this method will issue a warning if the dir does not
306 exists but it will return true in this case! */
307 bool ReadPinDir(pkgPolicy
&Plcy
,string Dir
)
309 if (Dir
.empty() == true)
310 Dir
= _config
->FindDir("Dir::Etc::PreferencesParts");
312 if (DirectoryExists(Dir
) == false)
314 if (Dir
!= "/dev/null")
315 _error
->WarningE("DirectoryExists",_("Unable to read %s"),Dir
.c_str());
319 vector
<string
> const List
= GetListOfFilesInDir(Dir
, "pref", true, true);
322 for (vector
<string
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
323 if (ReadPinFile(Plcy
, *I
) == false)
328 // ReadPinFile - Load the pin file into a Policy /*{{{*/
329 // ---------------------------------------------------------------------
330 /* I'd like to see the preferences file store more than just pin information
331 but right now that is the only stuff I have to store. Later there will
332 have to be some kind of combined super parser to get the data into all
333 the right classes.. */
334 bool ReadPinFile(pkgPolicy
&Plcy
,string File
)
336 if (File
.empty() == true)
337 File
= _config
->FindFile("Dir::Etc::Preferences");
339 if (RealFileExists(File
) == false)
342 FileFd
Fd(File
,FileFd::ReadOnly
);
343 pkgTagFile
TF(&Fd
, pkgTagFile::SUPPORT_COMMENTS
);
344 if (Fd
.IsOpen() == false || Fd
.Failed())
348 while (TF
.Step(Tags
) == true)
350 // can happen when there are only comments in a record
351 if (Tags
.Count() == 0)
354 string Name
= Tags
.FindS("Package");
355 if (Name
.empty() == true)
356 return _error
->Error(_("Invalid record in the preferences file %s, no Package header"), File
.c_str());
362 if (Tags
.Find("Pin",Start
,End
) == false)
365 const char *Word
= Start
;
366 for (; Word
!= End
&& isspace(*Word
) == 0; Word
++);
369 pkgVersionMatch::MatchType Type
;
370 if (stringcasecmp(Start
,Word
,"version") == 0 && Name
.empty() == false)
371 Type
= pkgVersionMatch::Version
;
372 else if (stringcasecmp(Start
,Word
,"release") == 0)
373 Type
= pkgVersionMatch::Release
;
374 else if (stringcasecmp(Start
,Word
,"origin") == 0)
375 Type
= pkgVersionMatch::Origin
;
378 _error
->Warning(_("Did not understand pin type %s"),string(Start
,Word
).c_str());
381 for (; Word
!= End
&& isspace(*Word
) != 0; Word
++);
383 _error
->PushToStack();
384 int const priority
= Tags
.FindI("Pin-Priority", 0);
385 bool const newError
= _error
->PendingError();
386 _error
->MergeWithStack();
387 if (priority
< std::numeric_limits
<short>::min() ||
388 priority
> std::numeric_limits
<short>::max() ||
390 return _error
->Error(_("%s: Value %s is outside the range of valid pin priorities (%d to %d)"),
391 File
.c_str(), Tags
.FindS("Pin-Priority").c_str(),
392 std::numeric_limits
<short>::min(),
393 std::numeric_limits
<short>::max());
397 return _error
->Error(_("No priority (or zero) specified for pin"));
400 istringstream
s(Name
);
405 Plcy
.CreatePin(Type
, pkg
, string(Word
,End
),priority
);
414 pkgPolicy::~pkgPolicy() {delete [] PFPriority
; delete [] Pins
; delete [] VerPins
; }