]> git.saurik.com Git - apt.git/blob - apt-pkg/deb/debmetaindex.cc
0c9cde620e048f4299ced4b48e890c4d31212678
[apt.git] / apt-pkg / deb / debmetaindex.cc
1 #include <config.h>
2
3 #include <apt-pkg/error.h>
4 #include <apt-pkg/debmetaindex.h>
5 #include <apt-pkg/debindexfile.h>
6 #include <apt-pkg/strutl.h>
7 #include <apt-pkg/fileutl.h>
8 #include <apt-pkg/acquire-item.h>
9 #include <apt-pkg/configuration.h>
10 #include <apt-pkg/aptconfiguration.h>
11 #include <apt-pkg/sourcelist.h>
12 #include <apt-pkg/hashes.h>
13 #include <apt-pkg/metaindex.h>
14 #include <apt-pkg/pkgcachegen.h>
15 #include <apt-pkg/tagfile.h>
16 #include <apt-pkg/gpgv.h>
17 #include <apt-pkg/macros.h>
18
19 #include <map>
20 #include <string>
21 #include <utility>
22 #include <vector>
23 #include <algorithm>
24 #include <sstream>
25
26 #include <sys/stat.h>
27 #include <string.h>
28
29 #include <apti18n.h>
30
31 class APT_HIDDEN debReleaseIndexPrivate /*{{{*/
32 {
33 public:
34 struct APT_HIDDEN debSectionEntry
35 {
36 std::string const sourcesEntry;
37 std::string const Name;
38 std::vector<std::string> const Targets;
39 std::vector<std::string> const Architectures;
40 std::vector<std::string> const Languages;
41 bool const UsePDiffs;
42 std::string const UseByHash;
43 };
44
45 std::vector<debSectionEntry> DebEntries;
46 std::vector<debSectionEntry> DebSrcEntries;
47
48 metaIndex::TriState CheckValidUntil;
49 time_t ValidUntilMin;
50 time_t ValidUntilMax;
51
52 std::vector<std::string> Architectures;
53 std::vector<std::string> NoSupportForAll;
54
55 debReleaseIndexPrivate() : CheckValidUntil(metaIndex::TRI_UNSET), ValidUntilMin(0), ValidUntilMax(0) {}
56 };
57 /*}}}*/
58 // ReleaseIndex::MetaIndex* - display helpers /*{{{*/
59 std::string debReleaseIndex::MetaIndexInfo(const char *Type) const
60 {
61 std::string Info = ::URI::ArchiveOnly(URI) + ' ';
62 if (Dist[Dist.size() - 1] == '/')
63 {
64 if (Dist != "/")
65 Info += Dist;
66 }
67 else
68 Info += Dist;
69 Info += " ";
70 Info += Type;
71 return Info;
72 }
73 std::string debReleaseIndex::Describe() const
74 {
75 return MetaIndexInfo("Release");
76 }
77
78 std::string debReleaseIndex::MetaIndexFile(const char *Type) const
79 {
80 return _config->FindDir("Dir::State::lists") +
81 URItoFileName(MetaIndexURI(Type));
82 }
83 static std::string constructMetaIndexURI(std::string URI, std::string const &Dist, char const * const Type)
84 {
85 if (Dist == "/")
86 ;
87 else if (Dist[Dist.size()-1] == '/')
88 URI += Dist;
89 else
90 URI += "dists/" + Dist + "/";
91 return URI + Type;
92 }
93 std::string debReleaseIndex::MetaIndexURI(const char *Type) const
94 {
95 return constructMetaIndexURI(URI, Dist, Type);
96 }
97 /*}}}*/
98 // ReleaseIndex Con- and Destructors /*{{{*/
99 debReleaseIndex::debReleaseIndex(std::string const &URI, std::string const &Dist) :
100 metaIndex(URI, Dist, "deb"), d(new debReleaseIndexPrivate())
101 {}
102 debReleaseIndex::debReleaseIndex(std::string const &URI, std::string const &Dist, bool const pTrusted) :
103 metaIndex(URI, Dist, "deb"), d(new debReleaseIndexPrivate())
104 {
105 Trusted = pTrusted ? TRI_YES : TRI_NO;
106 }
107 debReleaseIndex::~debReleaseIndex() {
108 if (d != NULL)
109 delete d;
110 }
111 /*}}}*/
112 // ReleaseIndex::GetIndexTargets /*{{{*/
113 static void GetIndexTargetsFor(char const * const Type, std::string const &URI, std::string const &Dist,
114 std::vector<debReleaseIndexPrivate::debSectionEntry> const &entries,
115 std::vector<IndexTarget> &IndexTargets)
116 {
117 bool const flatArchive = (Dist[Dist.length() - 1] == '/');
118 std::string baseURI = URI;
119 if (flatArchive)
120 {
121 if (Dist != "/")
122 baseURI += Dist;
123 }
124 else
125 baseURI += "dists/" + Dist + "/";
126 std::string const Release = (Dist == "/") ? "" : Dist;
127 std::string const Site = ::URI::ArchiveOnly(URI);
128
129 std::string DefCompressionTypes;
130 {
131 std::vector<std::string> types = APT::Configuration::getCompressionTypes();
132 if (types.empty() == false)
133 {
134 std::ostringstream os;
135 std::copy(types.begin(), types.end()-1, std::ostream_iterator<std::string>(os, " "));
136 os << *types.rbegin();
137 DefCompressionTypes = os.str();
138 }
139 }
140 std::string DefKeepCompressedAs;
141 {
142 std::vector<APT::Configuration::Compressor> comps = APT::Configuration::getCompressors();
143 if (comps.empty() == false)
144 {
145 std::sort(comps.begin(), comps.end(),
146 [](APT::Configuration::Compressor const &a, APT::Configuration::Compressor const &b) { return a.Cost < b.Cost; });
147 std::ostringstream os;
148 for (auto const &c : comps)
149 if (c.Cost != 0)
150 os << c.Extension.substr(1) << ' ';
151 DefKeepCompressedAs = os.str();
152 }
153 DefKeepCompressedAs += "uncompressed";
154 }
155
156 std::vector<std::string> const NativeArchs = { _config->Find("APT::Architecture"), "all" };
157 bool const GzipIndex = _config->FindB("Acquire::GzipIndexes", false);
158 for (std::vector<debReleaseIndexPrivate::debSectionEntry>::const_iterator E = entries.begin(); E != entries.end(); ++E)
159 {
160 for (std::vector<std::string>::const_iterator T = E->Targets.begin(); T != E->Targets.end(); ++T)
161 {
162 #define APT_T_CONFIG_STR(X, Y) _config->Find(std::string("Acquire::IndexTargets::") + Type + "::" + *T + "::" + (X), (Y))
163 #define APT_T_CONFIG_BOOL(X, Y) _config->FindB(std::string("Acquire::IndexTargets::") + Type + "::" + *T + "::" + (X), (Y))
164 std::string const tplMetaKey = APT_T_CONFIG_STR(flatArchive ? "flatMetaKey" : "MetaKey", "");
165 std::string const tplShortDesc = APT_T_CONFIG_STR("ShortDescription", "");
166 std::string const tplLongDesc = "$(SITE) " + APT_T_CONFIG_STR(flatArchive ? "flatDescription" : "Description", "");
167 std::string const tplIdentifier = APT_T_CONFIG_STR("Identifier", *T);
168 bool const IsOptional = APT_T_CONFIG_BOOL("Optional", true);
169 bool const KeepCompressed = APT_T_CONFIG_BOOL("KeepCompressed", GzipIndex);
170 bool const DefaultEnabled = APT_T_CONFIG_BOOL("DefaultEnabled", true);
171 bool const UsePDiffs = APT_T_CONFIG_BOOL("PDiffs", E->UsePDiffs);
172 std::string const UseByHash = APT_T_CONFIG_STR("By-Hash", E->UseByHash);
173 std::string const CompressionTypes = APT_T_CONFIG_STR("CompressionTypes", DefCompressionTypes);
174 std::string KeepCompressedAs = APT_T_CONFIG_STR("KeepCompressedAs", "");
175 std::string const FallbackOf = APT_T_CONFIG_STR("Fallback-Of", "");
176 #undef APT_T_CONFIG_BOOL
177 #undef APT_T_CONFIG_STR
178 if (tplMetaKey.empty())
179 continue;
180
181 if (KeepCompressedAs.empty())
182 KeepCompressedAs = DefKeepCompressedAs;
183 else
184 {
185 std::vector<std::string> const defKeep = VectorizeString(DefKeepCompressedAs, ' ');
186 std::vector<std::string> const valKeep = VectorizeString(KeepCompressedAs, ' ');
187 std::vector<std::string> keep;
188 for (auto const &val : valKeep)
189 {
190 if (val.empty())
191 continue;
192 if (std::find(defKeep.begin(), defKeep.end(), val) == defKeep.end())
193 continue;
194 keep.push_back(val);
195 }
196 if (std::find(keep.begin(), keep.end(), "uncompressed") == keep.end())
197 keep.push_back("uncompressed");
198 std::ostringstream os;
199 std::copy(keep.begin(), keep.end()-1, std::ostream_iterator<std::string>(os, " "));
200 os << *keep.rbegin();
201 KeepCompressedAs = os.str();
202 }
203
204 for (std::vector<std::string>::const_iterator L = E->Languages.begin(); L != E->Languages.end(); ++L)
205 {
206 if (*L == "none" && tplMetaKey.find("$(LANGUAGE)") != std::string::npos)
207 continue;
208
209 for (std::vector<std::string>::const_iterator A = E->Architectures.begin(); A != E->Architectures.end(); ++A)
210 {
211 for (auto const &NativeArch: NativeArchs)
212 {
213 constexpr static auto BreakPoint = "$(NATIVE_ARCHITECTURE)";
214 // available in templates
215 std::map<std::string, std::string> Options;
216 Options.insert(std::make_pair("SITE", Site));
217 Options.insert(std::make_pair("RELEASE", Release));
218 if (tplMetaKey.find("$(COMPONENT)") != std::string::npos)
219 Options.insert(std::make_pair("COMPONENT", E->Name));
220 if (tplMetaKey.find("$(LANGUAGE)") != std::string::npos)
221 Options.insert(std::make_pair("LANGUAGE", *L));
222 if (tplMetaKey.find("$(ARCHITECTURE)") != std::string::npos)
223 Options.insert(std::make_pair("ARCHITECTURE", *A));
224 else if (tplMetaKey.find("$(NATIVE_ARCHITECTURE)") != std::string::npos)
225 Options.insert(std::make_pair("ARCHITECTURE", NativeArch));
226 if (tplMetaKey.find("$(NATIVE_ARCHITECTURE)") != std::string::npos)
227 Options.insert(std::make_pair("NATIVE_ARCHITECTURE", NativeArch));
228
229 std::string MetaKey = tplMetaKey;
230 std::string ShortDesc = tplShortDesc;
231 std::string LongDesc = tplLongDesc;
232 std::string Identifier = tplIdentifier;
233 for (std::map<std::string, std::string>::const_iterator O = Options.begin(); O != Options.end(); ++O)
234 {
235 std::string const varname = "$(" + O->first + ")";
236 MetaKey = SubstVar(MetaKey, varname, O->second);
237 ShortDesc = SubstVar(ShortDesc, varname, O->second);
238 LongDesc = SubstVar(LongDesc, varname, O->second);
239 Identifier = SubstVar(Identifier, varname, O->second);
240 }
241
242 {
243 auto const dup = std::find_if(IndexTargets.begin(), IndexTargets.end(), [&](IndexTarget const &IT) {
244 return MetaKey == IT.MetaKey && baseURI == IT.Option(IndexTarget::BASE_URI) &&
245 E->sourcesEntry == IT.Option(IndexTarget::SOURCESENTRY) && *T == IT.Option(IndexTarget::CREATED_BY);
246 });
247 if (dup != IndexTargets.end())
248 {
249 if (tplMetaKey.find(BreakPoint) == std::string::npos)
250 break;
251 continue;
252 }
253 }
254
255 {
256 auto const dup = std::find_if(IndexTargets.begin(), IndexTargets.end(), [&](IndexTarget const &IT) {
257 return MetaKey == IT.MetaKey && baseURI == IT.Option(IndexTarget::BASE_URI) &&
258 E->sourcesEntry == IT.Option(IndexTarget::SOURCESENTRY) && *T != IT.Option(IndexTarget::CREATED_BY);
259 });
260 if (dup != IndexTargets.end())
261 {
262 std::string const dupT = dup->Option(IndexTarget::CREATED_BY);
263 std::string const dupEntry = dup->Option(IndexTarget::SOURCESENTRY);
264 //TRANSLATOR: an identifier like Packages; Releasefile key indicating
265 // a file like main/binary-amd64/Packages; another identifier like Contents;
266 // filename and linenumber of the sources.list entry currently parsed
267 _error->Warning(_("Target %s wants to acquire the same file (%s) as %s from source %s"),
268 T->c_str(), MetaKey.c_str(), dupT.c_str(), dupEntry.c_str());
269 if (tplMetaKey.find(BreakPoint) == std::string::npos)
270 break;
271 continue;
272 }
273 }
274
275 {
276 auto const dup = std::find_if(IndexTargets.begin(), IndexTargets.end(), [&](IndexTarget const &T) {
277 return MetaKey == T.MetaKey && baseURI == T.Option(IndexTarget::BASE_URI) &&
278 E->sourcesEntry != T.Option(IndexTarget::SOURCESENTRY);
279 });
280 if (dup != IndexTargets.end())
281 {
282 std::string const dupEntry = dup->Option(IndexTarget::SOURCESENTRY);
283 //TRANSLATOR: an identifier like Packages; Releasefile key indicating
284 // a file like main/binary-amd64/Packages; filename and linenumber of
285 // two sources.list entries
286 _error->Warning(_("Target %s (%s) is configured multiple times in %s and %s"),
287 T->c_str(), MetaKey.c_str(), dupEntry.c_str(), E->sourcesEntry.c_str());
288 if (tplMetaKey.find(BreakPoint) == std::string::npos)
289 break;
290 continue;
291 }
292 }
293
294 // not available in templates, but in the indextarget
295 Options.insert(std::make_pair("BASE_URI", baseURI));
296 Options.insert(std::make_pair("REPO_URI", URI));
297 Options.insert(std::make_pair("IDENTIFIER", Identifier));
298 Options.insert(std::make_pair("TARGET_OF", Type));
299 Options.insert(std::make_pair("CREATED_BY", *T));
300 Options.insert(std::make_pair("FALLBACK_OF", FallbackOf));
301 Options.insert(std::make_pair("PDIFFS", UsePDiffs ? "yes" : "no"));
302 Options.insert(std::make_pair("BY_HASH", UseByHash));
303 Options.insert(std::make_pair("DEFAULTENABLED", DefaultEnabled ? "yes" : "no"));
304 Options.insert(std::make_pair("COMPRESSIONTYPES", CompressionTypes));
305 Options.insert(std::make_pair("KEEPCOMPRESSEDAS", KeepCompressedAs));
306 Options.insert(std::make_pair("SOURCESENTRY", E->sourcesEntry));
307
308 bool IsOpt = IsOptional;
309 if (IsOpt == false)
310 {
311 auto const arch = Options.find("ARCHITECTURE");
312 if (arch != Options.end() && arch->second == "all")
313 IsOpt = true;
314 }
315
316 IndexTarget Target(
317 MetaKey,
318 ShortDesc,
319 LongDesc,
320 Options.find("BASE_URI")->second + MetaKey,
321 IsOpt,
322 KeepCompressed,
323 Options
324 );
325 IndexTargets.push_back(Target);
326
327 if (tplMetaKey.find(BreakPoint) == std::string::npos)
328 break;
329 }
330
331 if (tplMetaKey.find("$(ARCHITECTURE)") == std::string::npos)
332 break;
333
334 }
335
336 if (tplMetaKey.find("$(LANGUAGE)") == std::string::npos)
337 break;
338
339 }
340
341 }
342 }
343 }
344 std::vector<IndexTarget> debReleaseIndex::GetIndexTargets() const
345 {
346 std::vector<IndexTarget> IndexTargets;
347 GetIndexTargetsFor("deb-src", URI, Dist, d->DebSrcEntries, IndexTargets);
348 GetIndexTargetsFor("deb", URI, Dist, d->DebEntries, IndexTargets);
349 return IndexTargets;
350 }
351 /*}}}*/
352 void debReleaseIndex::AddComponent(std::string const &sourcesEntry, /*{{{*/
353 bool const isSrc, std::string const &Name,
354 std::vector<std::string> const &Targets,
355 std::vector<std::string> const &Architectures,
356 std::vector<std::string> Languages,
357 bool const usePDiffs, std::string const &useByHash)
358 {
359 if (Languages.empty() == true)
360 Languages.push_back("none");
361 debReleaseIndexPrivate::debSectionEntry const entry = {
362 sourcesEntry, Name, Targets, Architectures, Languages, usePDiffs, useByHash
363 };
364 if (isSrc)
365 d->DebSrcEntries.push_back(entry);
366 else
367 d->DebEntries.push_back(entry);
368 }
369 /*}}}*/
370
371 bool debReleaseIndex::Load(std::string const &Filename, std::string * const ErrorText)/*{{{*/
372 {
373 LoadedSuccessfully = TRI_NO;
374 FileFd Fd;
375 if (OpenMaybeClearSignedFile(Filename, Fd) == false)
376 return false;
377
378 pkgTagFile TagFile(&Fd, Fd.Size());
379 if (Fd.IsOpen() == false || Fd.Failed())
380 {
381 if (ErrorText != NULL)
382 strprintf(*ErrorText, _("Unable to parse Release file %s"),Filename.c_str());
383 return false;
384 }
385
386 pkgTagSection Section;
387 const char *Start, *End;
388 if (TagFile.Step(Section) == false)
389 {
390 if (ErrorText != NULL)
391 strprintf(*ErrorText, _("No sections in Release file %s"), Filename.c_str());
392 return false;
393 }
394 // FIXME: find better tag name
395 SupportsAcquireByHash = Section.FindB("Acquire-By-Hash", false);
396
397 Suite = Section.FindS("Suite");
398 Codename = Section.FindS("Codename");
399 {
400 std::string const archs = Section.FindS("Architectures");
401 if (archs.empty() == false)
402 d->Architectures = VectorizeString(archs, ' ');
403 }
404 {
405 std::string const targets = Section.FindS("No-Support-for-Architecture-all");
406 if (targets.empty() == false)
407 d->NoSupportForAll = VectorizeString(targets, ' ');
408 }
409
410 bool FoundHashSum = false;
411 bool FoundStrongHashSum = false;
412 auto const SupportedHashes = HashString::SupportedHashes();
413 for (int i=0; SupportedHashes[i] != NULL; i++)
414 {
415 if (!Section.Find(SupportedHashes[i], Start, End))
416 continue;
417
418 std::string Name;
419 std::string Hash;
420 unsigned long long Size;
421 while (Start < End)
422 {
423 if (!parseSumData(Start, End, Name, Hash, Size))
424 return false;
425
426 HashString const hs(SupportedHashes[i], Hash);
427 if (Entries.find(Name) == Entries.end())
428 {
429 metaIndex::checkSum *Sum = new metaIndex::checkSum;
430 Sum->MetaKeyFilename = Name;
431 Sum->Size = Size;
432 Sum->Hashes.FileSize(Size);
433 APT_IGNORE_DEPRECATED(Sum->Hash = hs;)
434 Entries[Name] = Sum;
435 }
436 Entries[Name]->Hashes.push_back(hs);
437 FoundHashSum = true;
438 if (FoundStrongHashSum == false && hs.usable() == true)
439 FoundStrongHashSum = true;
440 }
441 }
442
443 bool AuthPossible = false;
444 if(FoundHashSum == false)
445 _error->Warning(_("No Hash entry in Release file %s"), Filename.c_str());
446 else if(FoundStrongHashSum == false)
447 _error->Warning(_("No Hash entry in Release file %s which is considered strong enough for security purposes"), Filename.c_str());
448 else
449 AuthPossible = true;
450
451 std::string const StrDate = Section.FindS("Date");
452 if (RFC1123StrToTime(StrDate.c_str(), Date) == false)
453 {
454 _error->Warning( _("Invalid '%s' entry in Release file %s"), "Date", Filename.c_str());
455 Date = 0;
456 }
457
458 bool CheckValidUntil = _config->FindB("Acquire::Check-Valid-Until", true);
459 if (d->CheckValidUntil == metaIndex::TRI_NO)
460 CheckValidUntil = false;
461 else if (d->CheckValidUntil == metaIndex::TRI_YES)
462 CheckValidUntil = true;
463
464 if (CheckValidUntil == true)
465 {
466 std::string const Label = Section.FindS("Label");
467 std::string const StrValidUntil = Section.FindS("Valid-Until");
468
469 // if we have a Valid-Until header in the Release file, use it as default
470 if (StrValidUntil.empty() == false)
471 {
472 if(RFC1123StrToTime(StrValidUntil.c_str(), ValidUntil) == false)
473 {
474 if (ErrorText != NULL)
475 strprintf(*ErrorText, _("Invalid '%s' entry in Release file %s"), "Valid-Until", Filename.c_str());
476 return false;
477 }
478 }
479 // get the user settings for this archive and use what expires earlier
480 time_t MaxAge = d->ValidUntilMax;
481 if (MaxAge == 0)
482 {
483 MaxAge = _config->FindI("Acquire::Max-ValidTime", 0);
484 if (Label.empty() == false)
485 MaxAge = _config->FindI(("Acquire::Max-ValidTime::" + Label).c_str(), MaxAge);
486 }
487 time_t MinAge = d->ValidUntilMin;
488 if (MinAge == 0)
489 {
490 MinAge = _config->FindI("Acquire::Min-ValidTime", 0);
491 if (Label.empty() == false)
492 MinAge = _config->FindI(("Acquire::Min-ValidTime::" + Label).c_str(), MinAge);
493 }
494
495 if (MinAge != 0 || ValidUntil != 0 || MaxAge != 0)
496 {
497 if (MinAge != 0 && ValidUntil != 0) {
498 time_t const min_date = Date + MinAge;
499 if (ValidUntil < min_date)
500 ValidUntil = min_date;
501 }
502 if (MaxAge != 0 && Date != 0) {
503 time_t const max_date = Date + MaxAge;
504 if (ValidUntil == 0 || ValidUntil > max_date)
505 ValidUntil = max_date;
506 }
507 }
508 }
509
510 /* as the Release file is parsed only after it was verified, the Signed-By field
511 does not effect the current, but the "next" Release file */
512 auto Sign = Section.FindS("Signed-By");
513 if (Sign.empty() == false)
514 {
515 std::transform(Sign.begin(), Sign.end(), Sign.begin(), [&](char const c) {
516 return (isspace(c) == 0) ? c : ',';
517 });
518 auto fingers = VectorizeString(Sign, ',');
519 std::transform(fingers.begin(), fingers.end(), fingers.begin(), [&](std::string finger) {
520 std::transform(finger.begin(), finger.end(), finger.begin(), ::toupper);
521 if (finger.length() != 40 || finger.find_first_not_of("0123456789ABCDEF") != std::string::npos)
522 {
523 if (ErrorText != NULL)
524 strprintf(*ErrorText, _("Invalid '%s' entry in Release file %s"), "Signed-By", Filename.c_str());
525 return std::string();
526 }
527 return finger;
528 });
529 if (fingers.empty() == false && std::find(fingers.begin(), fingers.end(), "") == fingers.end())
530 {
531 std::stringstream os;
532 std::copy(fingers.begin(), fingers.end(), std::ostream_iterator<std::string>(os, ","));
533 SignedBy = os.str();
534 }
535 }
536
537 if (AuthPossible)
538 LoadedSuccessfully = TRI_YES;
539 return AuthPossible;
540 }
541 /*}}}*/
542 metaIndex * debReleaseIndex::UnloadedClone() const /*{{{*/
543 {
544 if (Trusted == TRI_NO)
545 return new debReleaseIndex(URI, Dist, false);
546 else if (Trusted == TRI_YES)
547 return new debReleaseIndex(URI, Dist, true);
548 else
549 return new debReleaseIndex(URI, Dist);
550 }
551 /*}}}*/
552 bool debReleaseIndex::parseSumData(const char *&Start, const char *End, /*{{{*/
553 std::string &Name, std::string &Hash, unsigned long long &Size)
554 {
555 Name = "";
556 Hash = "";
557 Size = 0;
558 /* Skip over the first blank */
559 while ((*Start == '\t' || *Start == ' ' || *Start == '\n' || *Start == '\r')
560 && Start < End)
561 Start++;
562 if (Start >= End)
563 return false;
564
565 /* Move EntryEnd to the end of the first entry (the hash) */
566 const char *EntryEnd = Start;
567 while ((*EntryEnd != '\t' && *EntryEnd != ' ')
568 && EntryEnd < End)
569 EntryEnd++;
570 if (EntryEnd == End)
571 return false;
572
573 Hash.append(Start, EntryEnd-Start);
574
575 /* Skip over intermediate blanks */
576 Start = EntryEnd;
577 while (*Start == '\t' || *Start == ' ')
578 Start++;
579 if (Start >= End)
580 return false;
581
582 EntryEnd = Start;
583 /* Find the end of the second entry (the size) */
584 while ((*EntryEnd != '\t' && *EntryEnd != ' ' )
585 && EntryEnd < End)
586 EntryEnd++;
587 if (EntryEnd == End)
588 return false;
589
590 Size = strtoull (Start, NULL, 10);
591
592 /* Skip over intermediate blanks */
593 Start = EntryEnd;
594 while (*Start == '\t' || *Start == ' ')
595 Start++;
596 if (Start >= End)
597 return false;
598
599 EntryEnd = Start;
600 /* Find the end of the third entry (the filename) */
601 while ((*EntryEnd != '\t' && *EntryEnd != ' ' &&
602 *EntryEnd != '\n' && *EntryEnd != '\r')
603 && EntryEnd < End)
604 EntryEnd++;
605
606 Name.append(Start, EntryEnd-Start);
607 Start = EntryEnd; //prepare for the next round
608 return true;
609 }
610 /*}}}*/
611
612 bool debReleaseIndex::GetIndexes(pkgAcquire *Owner, bool const &GetAll)/*{{{*/
613 {
614 #define APT_TARGET(X) IndexTarget("", X, MetaIndexInfo(X), MetaIndexURI(X), false, false, std::map<std::string,std::string>())
615 pkgAcqMetaClearSig * const TransactionManager = new pkgAcqMetaClearSig(Owner,
616 APT_TARGET("InRelease"), APT_TARGET("Release"), APT_TARGET("Release.gpg"), this);
617 #undef APT_TARGET
618 // special case for --print-uris
619 if (GetAll)
620 for (auto const &Target: GetIndexTargets())
621 if (Target.Option(IndexTarget::FALLBACK_OF).empty())
622 new pkgAcqIndex(Owner, TransactionManager, Target);
623
624 return true;
625 }
626 /*}}}*/
627 // ReleaseIndex::Set* TriState options /*{{{*/
628 bool debReleaseIndex::SetTrusted(TriState const pTrusted)
629 {
630 if (Trusted == TRI_UNSET)
631 Trusted = pTrusted;
632 else if (Trusted != pTrusted)
633 // TRANSLATOR: The first is an option name from sources.list manpage, the other two URI and Suite
634 return _error->Error(_("Conflicting values set for option %s regarding source %s %s"), "Trusted", URI.c_str(), Dist.c_str());
635 return true;
636 }
637 bool debReleaseIndex::SetCheckValidUntil(TriState const pCheckValidUntil)
638 {
639 if (d->CheckValidUntil == TRI_UNSET)
640 d->CheckValidUntil = pCheckValidUntil;
641 else if (d->CheckValidUntil != pCheckValidUntil)
642 return _error->Error(_("Conflicting values set for option %s regarding source %s %s"), "Check-Valid-Until", URI.c_str(), Dist.c_str());
643 return true;
644 }
645 bool debReleaseIndex::SetValidUntilMin(time_t const Valid)
646 {
647 if (d->ValidUntilMin == 0)
648 d->ValidUntilMin = Valid;
649 else if (d->ValidUntilMin != Valid)
650 return _error->Error(_("Conflicting values set for option %s regarding source %s %s"), "Min-ValidTime", URI.c_str(), Dist.c_str());
651 return true;
652 }
653 bool debReleaseIndex::SetValidUntilMax(time_t const Valid)
654 {
655 if (d->ValidUntilMax == 0)
656 d->ValidUntilMax = Valid;
657 else if (d->ValidUntilMax != Valid)
658 return _error->Error(_("Conflicting values set for option %s regarding source %s %s"), "Max-ValidTime", URI.c_str(), Dist.c_str());
659 return true;
660 }
661 bool debReleaseIndex::SetSignedBy(std::string const &pSignedBy)
662 {
663 if (SignedBy.empty() == true && pSignedBy.empty() == false)
664 {
665 if (pSignedBy[0] == '/') // no check for existence as we could be chrooting later or such things
666 SignedBy = pSignedBy; // absolute path to a keyring file
667 else
668 {
669 // we could go all fancy and allow short/long/string matches as gpgv/apt-key does,
670 // but fingerprints are harder to fake than the others and this option is set once,
671 // not interactively all the time so easy to type is not really a concern.
672 auto fingers = VectorizeString(pSignedBy, ',');
673 std::transform(fingers.begin(), fingers.end(), fingers.begin(), [&](std::string finger) {
674 std::transform(finger.begin(), finger.end(), finger.begin(), ::toupper);
675 if (finger.length() != 40 || finger.find_first_not_of("0123456789ABCDEF") != std::string::npos)
676 {
677 _error->Error(_("Invalid value set for option %s regarding source %s %s (%s)"), "Signed-By", URI.c_str(), Dist.c_str(), "not a fingerprint");
678 return std::string();
679 }
680 return finger;
681 });
682 std::stringstream os;
683 std::copy(fingers.begin(), fingers.end(), std::ostream_iterator<std::string>(os, ","));
684 SignedBy = os.str();
685 }
686 // Normalize the string: Remove trailing commas
687 while (SignedBy[SignedBy.size() - 1] == ',')
688 SignedBy.resize(SignedBy.size() - 1);
689 }
690 else {
691 // Only compare normalized strings
692 auto pSignedByView = APT::StringView(pSignedBy);
693 while (pSignedByView[pSignedByView.size() - 1] == ',')
694 pSignedByView = pSignedByView.substr(0, pSignedByView.size() - 1);
695 if (pSignedByView != SignedBy)
696 return _error->Error(_("Conflicting values set for option %s regarding source %s %s: %s != %s"), "Signed-By", URI.c_str(), Dist.c_str(), SignedBy.c_str(), pSignedByView.to_string().c_str());
697 }
698 return true;
699 }
700 /*}}}*/
701 // ReleaseIndex::IsTrusted /*{{{*/
702 bool debReleaseIndex::IsTrusted() const
703 {
704 if (Trusted == TRI_YES)
705 return true;
706 else if (Trusted == TRI_NO)
707 return false;
708
709
710 if(_config->FindB("APT::Authentication::TrustCDROM", false))
711 if(URI.substr(0,strlen("cdrom:")) == "cdrom:")
712 return true;
713
714 if (FileExists(MetaIndexFile("Release.gpg")))
715 return true;
716
717 return FileExists(MetaIndexFile("InRelease"));
718 }
719 /*}}}*/
720 bool debReleaseIndex::IsArchitectureSupported(std::string const &arch) const/*{{{*/
721 {
722 if (d->Architectures.empty())
723 return true;
724 return std::find(d->Architectures.begin(), d->Architectures.end(), arch) != d->Architectures.end();
725 }
726 /*}}}*/
727 bool debReleaseIndex::IsArchitectureAllSupportedFor(IndexTarget const &target) const/*{{{*/
728 {
729 if (d->NoSupportForAll.empty())
730 return true;
731 return std::find(d->NoSupportForAll.begin(), d->NoSupportForAll.end(), target.Option(IndexTarget::CREATED_BY)) == d->NoSupportForAll.end();
732 }
733 /*}}}*/
734 std::vector <pkgIndexFile *> *debReleaseIndex::GetIndexFiles() /*{{{*/
735 {
736 if (Indexes != NULL)
737 return Indexes;
738
739 Indexes = new std::vector<pkgIndexFile*>();
740 bool const istrusted = IsTrusted();
741 for (auto const &T: GetIndexTargets())
742 {
743 std::string const TargetName = T.Option(IndexTarget::CREATED_BY);
744 if (TargetName == "Packages")
745 Indexes->push_back(new debPackagesIndex(T, istrusted));
746 else if (TargetName == "Sources")
747 Indexes->push_back(new debSourcesIndex(T, istrusted));
748 else if (TargetName == "Translations")
749 Indexes->push_back(new debTranslationsIndex(T));
750 }
751 return Indexes;
752 }
753 /*}}}*/
754
755 static bool ReleaseFileName(debReleaseIndex const * const That, std::string &ReleaseFile)/*{{{*/
756 {
757 ReleaseFile = That->MetaIndexFile("InRelease");
758 bool releaseExists = false;
759 if (FileExists(ReleaseFile) == true)
760 releaseExists = true;
761 else
762 {
763 ReleaseFile = That->MetaIndexFile("Release");
764 if (FileExists(ReleaseFile))
765 releaseExists = true;
766 }
767 return releaseExists;
768 }
769 /*}}}*/
770 bool debReleaseIndex::Merge(pkgCacheGenerator &Gen,OpProgress * /*Prog*/) const/*{{{*/
771 {
772 std::string ReleaseFile;
773 bool const releaseExists = ReleaseFileName(this, ReleaseFile);
774
775 ::URI Tmp(URI);
776 if (Gen.SelectReleaseFile(ReleaseFile, Tmp.Host) == false)
777 return _error->Error("Problem with SelectReleaseFile %s", ReleaseFile.c_str());
778
779 if (releaseExists == false)
780 return true;
781
782 FileFd Rel;
783 // Beware: The 'Release' file might be clearsigned in case the
784 // signature for an 'InRelease' file couldn't be checked
785 if (OpenMaybeClearSignedFile(ReleaseFile, Rel) == false)
786 return false;
787
788 // Store the IMS information
789 pkgCache::RlsFileIterator File = Gen.GetCurRlsFile();
790 pkgCacheGenerator::Dynamic<pkgCache::RlsFileIterator> DynFile(File);
791 // Rel can't be used as this is potentially a temporary file
792 struct stat Buf;
793 if (stat(ReleaseFile.c_str(), &Buf) != 0)
794 return _error->Errno("fstat", "Unable to stat file %s", ReleaseFile.c_str());
795 File->Size = Buf.st_size;
796 File->mtime = Buf.st_mtime;
797
798 pkgTagFile TagFile(&Rel, Rel.Size());
799 pkgTagSection Section;
800 if (Rel.IsOpen() == false || Rel.Failed() || TagFile.Step(Section) == false)
801 return false;
802
803 std::string data;
804 #define APT_INRELEASE(TYPE, TAG, STORE) \
805 data = Section.FindS(TAG); \
806 if (data.empty() == false) \
807 { \
808 map_stringitem_t const storage = Gen.StoreString(pkgCacheGenerator::TYPE, data); \
809 if (storage == 0) return false; \
810 STORE = storage; \
811 }
812 APT_INRELEASE(MIXED, "Suite", File->Archive)
813 APT_INRELEASE(VERSIONNUMBER, "Version", File->Version)
814 APT_INRELEASE(MIXED, "Origin", File->Origin)
815 APT_INRELEASE(MIXED, "Codename", File->Codename)
816 APT_INRELEASE(MIXED, "Label", File->Label)
817 #undef APT_INRELEASE
818 Section.FindFlag("NotAutomatic", File->Flags, pkgCache::Flag::NotAutomatic);
819 Section.FindFlag("ButAutomaticUpgrades", File->Flags, pkgCache::Flag::ButAutomaticUpgrades);
820
821 return true;
822 }
823 /*}}}*/
824 // ReleaseIndex::FindInCache - Find this index /*{{{*/
825 pkgCache::RlsFileIterator debReleaseIndex::FindInCache(pkgCache &Cache, bool const ModifyCheck) const
826 {
827 std::string ReleaseFile;
828 bool const releaseExists = ReleaseFileName(this, ReleaseFile);
829
830 pkgCache::RlsFileIterator File = Cache.RlsFileBegin();
831 for (; File.end() == false; ++File)
832 {
833 if (File->FileName == 0 || ReleaseFile != File.FileName())
834 continue;
835
836 // empty means the file does not exist by "design"
837 if (ModifyCheck == false || (releaseExists == false && File->Size == 0))
838 return File;
839
840 struct stat St;
841 if (stat(File.FileName(),&St) != 0)
842 {
843 if (_config->FindB("Debug::pkgCacheGen", false))
844 std::clog << "ReleaseIndex::FindInCache - stat failed on " << File.FileName() << std::endl;
845 return pkgCache::RlsFileIterator(Cache);
846 }
847 if ((unsigned)St.st_size != File->Size || St.st_mtime != File->mtime)
848 {
849 if (_config->FindB("Debug::pkgCacheGen", false))
850 std::clog << "ReleaseIndex::FindInCache - size (" << St.st_size << " <> " << File->Size
851 << ") or mtime (" << St.st_mtime << " <> " << File->mtime
852 << ") doesn't match for " << File.FileName() << std::endl;
853 return pkgCache::RlsFileIterator(Cache);
854 }
855 return File;
856 }
857
858 return File;
859 }
860 /*}}}*/
861
862 static std::vector<std::string> parsePlusMinusOptions(std::string const &Name, /*{{{*/
863 std::map<std::string, std::string> const &Options, std::vector<std::string> const &defaultValues)
864 {
865 std::map<std::string, std::string>::const_iterator val = Options.find(Name);
866 std::vector<std::string> Values;
867 if (val != Options.end())
868 Values = VectorizeString(val->second, ',');
869 else
870 Values = defaultValues;
871
872 // all is a very special architecture users shouldn't be concerned with explicitly
873 if (Name == "arch" && std::find(Values.begin(), Values.end(), "all") == Values.end())
874 Values.push_back("all");
875
876 if ((val = Options.find(Name + "+")) != Options.end())
877 {
878 std::vector<std::string> const plus = VectorizeString(val->second, ',');
879 std::copy_if(plus.begin(), plus.end(), std::back_inserter(Values), [&Values](std::string const &v) {
880 return std::find(Values.begin(), Values.end(), v) == Values.end();
881 });
882 }
883 if ((val = Options.find(Name + "-")) != Options.end())
884 {
885 std::vector<std::string> const minus = VectorizeString(val->second, ',');
886 Values.erase(std::remove_if(Values.begin(), Values.end(), [&minus](std::string const &v) {
887 return std::find(minus.begin(), minus.end(), v) != minus.end();
888 }), Values.end());
889 }
890 return Values;
891 }
892 /*}}}*/
893 class APT_HIDDEN debSLTypeDebian : public pkgSourceList::Type /*{{{*/
894 {
895 metaIndex::TriState GetTriStateOption(std::map<std::string, std::string>const &Options, char const * const name) const
896 {
897 std::map<std::string, std::string>::const_iterator const opt = Options.find(name);
898 if (opt != Options.end())
899 return StringToBool(opt->second, false) ? metaIndex::TRI_YES : metaIndex::TRI_NO;
900 return metaIndex::TRI_DONTCARE;
901 }
902
903 time_t GetTimeOption(std::map<std::string, std::string>const &Options, char const * const name) const
904 {
905 std::map<std::string, std::string>::const_iterator const opt = Options.find(name);
906 if (opt == Options.end())
907 return 0;
908 return strtoull(opt->second.c_str(), NULL, 10);
909 }
910
911 protected:
912
913 bool CreateItemInternal(std::vector<metaIndex *> &List, std::string const &URI,
914 std::string const &Dist, std::string const &Section,
915 bool const &IsSrc, std::map<std::string, std::string> const &Options) const
916 {
917 debReleaseIndex * Deb = nullptr;
918 std::string const FileName = URItoFileName(constructMetaIndexURI(URI, Dist, "Release"));
919 for (auto const &I: List)
920 {
921 // We only worry about debian entries here
922 if (strcmp(I->GetType(), "deb") != 0)
923 continue;
924
925 auto const D = dynamic_cast<debReleaseIndex*>(I);
926 if (unlikely(D == nullptr))
927 continue;
928
929 /* This check ensures that there will be only one Release file
930 queued for all the Packages files and Sources files it
931 corresponds to. */
932 if (URItoFileName(D->MetaIndexURI("Release")) == FileName)
933 {
934 Deb = D;
935 break;
936 }
937 }
938
939 // No currently created Release file indexes this entry, so we create a new one.
940 if (Deb == nullptr)
941 {
942 Deb = new debReleaseIndex(URI, Dist);
943 List.push_back(Deb);
944 }
945
946 std::vector<std::string> const alltargets = _config->FindVector(std::string("Acquire::IndexTargets::") + Name, "", true);
947 std::vector<std::string> deftargets;
948 deftargets.reserve(alltargets.size());
949 std::copy_if(alltargets.begin(), alltargets.end(), std::back_inserter(deftargets), [&](std::string const &t) {
950 std::string c = "Acquire::IndexTargets::";
951 c.append(Name).append("::").append(t).append("::DefaultEnabled");
952 return _config->FindB(c, true);
953 });
954 std::vector<std::string> mytargets = parsePlusMinusOptions("target", Options, deftargets);
955 for (auto const &target : alltargets)
956 {
957 std::map<std::string, std::string>::const_iterator const opt = Options.find(target);
958 if (opt == Options.end())
959 continue;
960 auto const idMatch = [&](std::string const &t) {
961 return target == _config->Find(std::string("Acquire::IndexTargets::") + Name + "::" + t + "::Identifier", t);
962 };
963 if (StringToBool(opt->second))
964 std::copy_if(alltargets.begin(), alltargets.end(), std::back_inserter(mytargets), idMatch);
965 else
966 mytargets.erase(std::remove_if(mytargets.begin(), mytargets.end(), idMatch), mytargets.end());
967 }
968 // if we can't order it in a 1000 steps we give up… probably a cycle
969 for (auto i = 0; i < 1000; ++i)
970 {
971 bool Changed = false;
972 for (auto t = mytargets.begin(); t != mytargets.end(); ++t)
973 {
974 std::string const fallback = _config->Find(std::string("Acquire::IndexTargets::") + Name + "::" + *t + "::Fallback-Of");
975 if (fallback.empty())
976 continue;
977 auto const faller = std::find(mytargets.begin(), mytargets.end(), fallback);
978 if (faller == mytargets.end() || faller < t)
979 continue;
980 Changed = true;
981 auto const tv = *t;
982 mytargets.erase(t);
983 mytargets.emplace_back(tv);
984 }
985 if (Changed == false)
986 break;
987 }
988 // remove duplicates without changing the order (in first appearance)
989 {
990 std::set<std::string> seenOnce;
991 mytargets.erase(std::remove_if(mytargets.begin(), mytargets.end(), [&](std::string const &t) {
992 return seenOnce.insert(t).second == false;
993 }), mytargets.end());
994 }
995
996 bool UsePDiffs = _config->FindB("Acquire::PDiffs", true);
997 {
998 std::map<std::string, std::string>::const_iterator const opt = Options.find("pdiffs");
999 if (opt != Options.end())
1000 UsePDiffs = StringToBool(opt->second);
1001 }
1002
1003 std::string UseByHash = _config->Find("APT::Acquire::By-Hash", "yes");
1004 UseByHash = _config->Find("Acquire::By-Hash", UseByHash);
1005 {
1006 std::string const host = ::URI(URI).Host;
1007 UseByHash = _config->Find("APT::Acquire::" + host + "::By-Hash", UseByHash);
1008 UseByHash = _config->Find("Acquire::" + host + "::By-Hash", UseByHash);
1009 std::map<std::string, std::string>::const_iterator const opt = Options.find("by-hash");
1010 if (opt != Options.end())
1011 UseByHash = opt->second;
1012 }
1013
1014 auto const entry = Options.find("sourceslist-entry");
1015 Deb->AddComponent(
1016 entry->second,
1017 IsSrc,
1018 Section,
1019 mytargets,
1020 parsePlusMinusOptions("arch", Options, APT::Configuration::getArchitectures()),
1021 parsePlusMinusOptions("lang", Options, APT::Configuration::getLanguages(true)),
1022 UsePDiffs,
1023 UseByHash
1024 );
1025
1026 if (Deb->SetTrusted(GetTriStateOption(Options, "trusted")) == false ||
1027 Deb->SetCheckValidUntil(GetTriStateOption(Options, "check-valid-until")) == false ||
1028 Deb->SetValidUntilMax(GetTimeOption(Options, "valid-until-max")) == false ||
1029 Deb->SetValidUntilMin(GetTimeOption(Options, "valid-until-min")) == false)
1030 return false;
1031
1032 std::map<std::string, std::string>::const_iterator const signedby = Options.find("signed-by");
1033 if (signedby == Options.end())
1034 {
1035 bool alreadySet = false;
1036 std::string filename;
1037 if (ReleaseFileName(Deb, filename))
1038 {
1039 auto OldDeb = Deb->UnloadedClone();
1040 _error->PushToStack();
1041 OldDeb->Load(filename, nullptr);
1042 bool const goodLoad = _error->PendingError() == false;
1043 _error->RevertToStack();
1044 if (goodLoad)
1045 {
1046 if (OldDeb->GetValidUntil() > 0)
1047 {
1048 time_t const invalid_since = time(NULL) - OldDeb->GetValidUntil();
1049 if (invalid_since <= 0)
1050 {
1051 Deb->SetSignedBy(OldDeb->GetSignedBy());
1052 alreadySet = true;
1053 }
1054 }
1055 }
1056 delete OldDeb;
1057 }
1058 if (alreadySet == false && Deb->SetSignedBy("") == false)
1059 return false;
1060 }
1061 else
1062 {
1063 if (Deb->SetSignedBy(signedby->second) == false)
1064 return false;
1065 }
1066
1067 return true;
1068 }
1069
1070 debSLTypeDebian(char const * const Name, char const * const Label) : Type(Name, Label)
1071 {
1072 }
1073 };
1074 /*}}}*/
1075 class APT_HIDDEN debSLTypeDeb : public debSLTypeDebian /*{{{*/
1076 {
1077 public:
1078
1079 bool CreateItem(std::vector<metaIndex *> &List, std::string const &URI,
1080 std::string const &Dist, std::string const &Section,
1081 std::map<std::string, std::string> const &Options) const APT_OVERRIDE
1082 {
1083 return CreateItemInternal(List, URI, Dist, Section, false, Options);
1084 }
1085
1086 debSLTypeDeb() : debSLTypeDebian("deb", "Debian binary tree")
1087 {
1088 }
1089 };
1090 /*}}}*/
1091 class APT_HIDDEN debSLTypeDebSrc : public debSLTypeDebian /*{{{*/
1092 {
1093 public:
1094
1095 bool CreateItem(std::vector<metaIndex *> &List, std::string const &URI,
1096 std::string const &Dist, std::string const &Section,
1097 std::map<std::string, std::string> const &Options) const APT_OVERRIDE
1098 {
1099 return CreateItemInternal(List, URI, Dist, Section, true, Options);
1100 }
1101
1102 debSLTypeDebSrc() : debSLTypeDebian("deb-src", "Debian source tree")
1103 {
1104 }
1105 };
1106 /*}}}*/
1107
1108 APT_HIDDEN debSLTypeDeb _apt_DebType;
1109 APT_HIDDEN debSLTypeDebSrc _apt_DebSrcType;