]> git.saurik.com Git - apt.git/blob - apt-pkg/policy.cc
Release 1.4~beta1
[apt.git] / apt-pkg / policy.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Description /*{{{*/
3 // $Id: policy.cc,v 1.10 2003/08/12 00:17:37 mdz Exp $
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 See man apt_preferences for what value means what.
12
13 ##################################################################### */
14 /*}}}*/
15 // Include Files /*{{{*/
16 #include<config.h>
17
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>
29
30 #include <ctype.h>
31 #include <stddef.h>
32 #include <string.h>
33 #include <string>
34 #include <vector>
35 #include <iostream>
36 #include <sstream>
37
38 #include <apti18n.h>
39 /*}}}*/
40
41 using namespace std;
42
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)
49 {
50 if (Owner == 0)
51 return;
52 PFPriority = new signed short[Owner->Head().PackageFileCount];
53 Pins = new Pin[Owner->Head().PackageCount];
54 VerPins = new Pin[Owner->Head().VersionCount];
55
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;
60
61 // The config file has a master override.
62 string DefRel = _config->Find("APT::Default-Release");
63 if (DefRel.empty() == false)
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 {
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] == '='))
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 }
81 InitDefaults();
82 }
83 /*}}}*/
84 // Policy::InitDefaults - Compute the default selections /*{{{*/
85 // ---------------------------------------------------------------------
86 /* */
87 bool pkgPolicy::InitDefaults()
88 {
89 // Initialize the priorities based on the status of the package file
90 for (pkgCache::PkgFileIterator I = Cache->FileBegin(); I != Cache->FileEnd(); ++I)
91 {
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;
99 }
100
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)
106 {
107 pkgVersionMatch Match(I->Data,I->Type);
108 for (pkgCache::PkgFileIterator F = Cache->FileBegin(); F != Cache->FileEnd(); ++F)
109 {
110 if (Fixed[F->ID] == false && Match.FileMatch(F) == true)
111 {
112 PFPriority[F->ID] = I->Priority;
113
114 if (PFPriority[F->ID] >= 1000)
115 StatusOverride = true;
116
117 Fixed[F->ID] = true;
118 }
119 }
120 }
121
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;
125
126 return true;
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. */
133 pkgCache::VerIterator pkgPolicy::GetCandidateVer(pkgCache::PkgIterator const &Pkg)
134 {
135 pkgCache::VerIterator cand;
136 pkgCache::VerIterator cur = Pkg.CurrentVer();
137 int candPriority = -1;
138 pkgVersioningSystem *vs = Cache->VS;
139
140 for (pkgCache::VerIterator ver = Pkg.VersionList(); ver.end() == false; ++ver) {
141 int priority = GetPriority(ver, true);
142
143 if (priority == 0 || priority <= candPriority)
144 continue;
145
146 // TODO: Maybe optimize to not compare versions
147 if (!cur.end() && priority < 1000
148 && (vs->CmpVersion(ver.VerStr(), cur.VerStr()) < 0))
149 continue;
150
151 candPriority = priority;
152 cand = ver;
153 }
154
155 return cand;
156 }
157 /*}}}*/
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)
166 {
167 if (Name.empty() == true)
168 {
169 Pin *P = &*Defaults.insert(Defaults.end(),Pin());
170 P->Type = Type;
171 P->Priority = Priority;
172 P->Data = Data;
173 return;
174 }
175
176 size_t found = Name.rfind(':');
177 string Arch;
178 if (found != string::npos) {
179 Arch = Name.substr(found+1);
180 Name.erase(found);
181 }
182
183 // Allow pinning by wildcards - beware of package names looking like wildcards!
184 // TODO: Maybe we should always prefer specific pins over non-specific ones.
185 if ((Name[0] == '/' && Name[Name.length() - 1] == '/') || Name.find_first_of("*[?") != string::npos)
186 {
187 pkgVersionMatch match(Data, Type);
188 for (pkgCache::GrpIterator G = Cache->GrpBegin(); G.end() != true; ++G)
189 if (Name != G.Name() && match.ExpressionMatches(Name, G.Name()))
190 {
191 if (Arch.empty() == false)
192 CreatePin(Type, string(G.Name()).append(":").append(Arch), Data, Priority);
193 else
194 CreatePin(Type, G.Name(), Data, Priority);
195 }
196 return;
197 }
198
199 // find the package (group) this pin applies to
200 pkgCache::GrpIterator Grp = Cache->FindGrp(Name);
201 bool matched = false;
202 if (Grp.end() == false)
203 {
204 std::string MatchingArch;
205 if (Arch.empty() == true)
206 MatchingArch = Cache->NativeArch();
207 else
208 MatchingArch = Arch;
209 APT::CacheFilter::PackageArchitectureMatchesSpecification pams(MatchingArch);
210 for (pkgCache::PkgIterator Pkg = Grp.PackageList(); Pkg.end() != true; Pkg = Grp.NextPkg(Pkg))
211 {
212 if (pams(Pkg.Arch()) == false)
213 continue;
214 Pin *P = Pins + Pkg->ID;
215 // the first specific stanza for a package is the ruler,
216 // all others need to be ignored
217 if (P->Type != pkgVersionMatch::None)
218 P = &*Unmatched.insert(Unmatched.end(),PkgPin(Pkg.FullName()));
219 P->Type = Type;
220 P->Priority = Priority;
221 P->Data = Data;
222 matched = true;
223
224 // Find matching version(s) and copy the pin into it
225 pkgVersionMatch Match(P->Data,P->Type);
226 for (pkgCache::VerIterator Ver = Pkg.VersionList(); Ver.end() != true; ++Ver)
227 {
228 if (Match.VersionMatches(Ver)) {
229 Pin *VP = VerPins + Ver->ID;
230 if (VP->Type == pkgVersionMatch::None)
231 *VP = *P;
232 }
233 }
234 }
235 }
236
237 if (matched == false)
238 {
239 PkgPin *P = &*Unmatched.insert(Unmatched.end(),PkgPin(Name));
240 if (Arch.empty() == false)
241 P->Pkg.append(":").append(Arch);
242 P->Type = Type;
243 P->Priority = Priority;
244 P->Data = Data;
245 return;
246 }
247 }
248 /*}}}*/
249 // Policy::GetMatch - Get the matching version for a package pin /*{{{*/
250 // ---------------------------------------------------------------------
251 /* */
252 pkgCache::VerIterator pkgPolicy::GetMatch(pkgCache::PkgIterator const &Pkg)
253 {
254 const Pin &PPkg = Pins[Pkg->ID];
255 if (PPkg.Type == pkgVersionMatch::None)
256 return pkgCache::VerIterator(*Pkg.Cache());
257
258 pkgVersionMatch Match(PPkg.Data,PPkg.Type);
259 return Match.Find(Pkg);
260 }
261 /*}}}*/
262 // Policy::GetPriority - Get the priority of the package pin /*{{{*/
263 // ---------------------------------------------------------------------
264 /* */
265 APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgIterator const &Pkg)
266 {
267 if (Pins[Pkg->ID].Type != pkgVersionMatch::None)
268 return Pins[Pkg->ID].Priority;
269 return 0;
270 }
271 APT_PURE signed short pkgPolicy::GetPriority(pkgCache::VerIterator const &Ver, bool ConsiderFiles)
272 {
273 if (VerPins[Ver->ID].Type != pkgVersionMatch::None)
274 return VerPins[Ver->ID].Priority;
275 if (!ConsiderFiles)
276 return 0;
277
278 // priorities are short ints, but we want to pick a value outside the valid range here
279 auto priority = std::numeric_limits<signed int>::min();
280 for (pkgCache::VerFileIterator file = Ver.FileList(); file.end() == false; file++)
281 {
282 /* If this is the status file, and the current version is not the
283 version in the status file (ie it is not installed, or somesuch)
284 then it is not a candidate for installation, ever. This weeds
285 out bogus entries that may be due to config-file states, or
286 other. */
287 if (file.File().Flagged(pkgCache::Flag::NotSource) && Ver.ParentPkg().CurrentVer() != Ver)
288 priority = std::max(priority, static_cast<decltype(priority)>(-1));
289 else
290 priority = std::max(priority, static_cast<decltype(priority)>(GetPriority(file.File())));
291 }
292
293 return priority == std::numeric_limits<decltype(priority)>::min() ? 0 : priority;
294 }
295 APT_PURE signed short pkgPolicy::GetPriority(pkgCache::PkgFileIterator const &File)
296 {
297 return PFPriority[File->ID];
298 }
299 /*}}}*/
300 // ReadPinDir - Load the pin files from this dir into a Policy /*{{{*/
301 // ---------------------------------------------------------------------
302 /* This will load each pin file in the given dir into a Policy. If the
303 given dir is empty the dir set in Dir::Etc::PreferencesParts is used.
304 Note also that this method will issue a warning if the dir does not
305 exists but it will return true in this case! */
306 bool ReadPinDir(pkgPolicy &Plcy,string Dir)
307 {
308 if (Dir.empty() == true)
309 Dir = _config->FindDir("Dir::Etc::PreferencesParts", "/dev/null");
310
311 if (DirectoryExists(Dir) == false)
312 {
313 if (APT::String::Endswith(Dir, "/dev/null") == false)
314 _error->WarningE("DirectoryExists",_("Unable to read %s"),Dir.c_str());
315 return true;
316 }
317
318 _error->PushToStack();
319 vector<string> const List = GetListOfFilesInDir(Dir, "pref", true, true);
320 bool const PendingErrors = _error->PendingError();
321 _error->MergeWithStack();
322 if (PendingErrors)
323 return false;
324
325 // Read the files
326 for (vector<string>::const_iterator I = List.begin(); I != List.end(); ++I)
327 if (ReadPinFile(Plcy, *I) == false)
328 return false;
329 return true;
330 }
331 /*}}}*/
332 // ReadPinFile - Load the pin file into a Policy /*{{{*/
333 // ---------------------------------------------------------------------
334 /* I'd like to see the preferences file store more than just pin information
335 but right now that is the only stuff I have to store. Later there will
336 have to be some kind of combined super parser to get the data into all
337 the right classes.. */
338 bool ReadPinFile(pkgPolicy &Plcy,string File)
339 {
340 if (File.empty() == true)
341 File = _config->FindFile("Dir::Etc::Preferences");
342
343 if (RealFileExists(File) == false)
344 return true;
345
346 FileFd Fd(File,FileFd::ReadOnly);
347 pkgTagFile TF(&Fd, pkgTagFile::SUPPORT_COMMENTS);
348 if (Fd.IsOpen() == false || Fd.Failed())
349 return false;
350
351 pkgTagSection Tags;
352 while (TF.Step(Tags) == true)
353 {
354 // can happen when there are only comments in a record
355 if (Tags.Count() == 0)
356 continue;
357
358 string Name = Tags.FindS("Package");
359 if (Name.empty() == true)
360 return _error->Error(_("Invalid record in the preferences file %s, no Package header"), File.c_str());
361 if (Name == "*")
362 Name = string();
363
364 const char *Start;
365 const char *End;
366 if (Tags.Find("Pin",Start,End) == false)
367 continue;
368
369 const char *Word = Start;
370 for (; Word != End && isspace(*Word) == 0; Word++);
371
372 // Parse the type..
373 pkgVersionMatch::MatchType Type;
374 if (stringcasecmp(Start,Word,"version") == 0 && Name.empty() == false)
375 Type = pkgVersionMatch::Version;
376 else if (stringcasecmp(Start,Word,"release") == 0)
377 Type = pkgVersionMatch::Release;
378 else if (stringcasecmp(Start,Word,"origin") == 0)
379 Type = pkgVersionMatch::Origin;
380 else
381 {
382 _error->Warning(_("Did not understand pin type %s"),string(Start,Word).c_str());
383 continue;
384 }
385 for (; Word != End && isspace(*Word) != 0; Word++);
386
387 _error->PushToStack();
388 int const priority = Tags.FindI("Pin-Priority", 0);
389 bool const newError = _error->PendingError();
390 _error->MergeWithStack();
391 if (priority < std::numeric_limits<short>::min() ||
392 priority > std::numeric_limits<short>::max() ||
393 newError) {
394 return _error->Error(_("%s: Value %s is outside the range of valid pin priorities (%d to %d)"),
395 File.c_str(), Tags.FindS("Pin-Priority").c_str(),
396 std::numeric_limits<short>::min(),
397 std::numeric_limits<short>::max());
398 }
399 if (priority == 0)
400 {
401 return _error->Error(_("No priority (or zero) specified for pin"));
402 }
403
404 istringstream s(Name);
405 string pkg;
406 while(!s.eof())
407 {
408 s >> pkg;
409 Plcy.CreatePin(Type, pkg, string(Word,End),priority);
410 };
411 }
412
413 Plcy.InitDefaults();
414 return true;
415 }
416 /*}}}*/
417
418 pkgPolicy::~pkgPolicy() {delete [] PFPriority; delete [] Pins; delete [] VerPins; }