Coverage Report

Created: 2026-11-21 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/proc/self/cwd/pagespeed/kernel/packs/matcher.cc
Line
Count
Source
1
// SPDX-License-Identifier: Apache-2.0
2
// Copyright (c) 2024-2026 We-Amp B.V.
3
4
#include "pagespeed/kernel/packs/matcher.h"
5
6
#include <algorithm>
7
#include <cstddef>
8
9
#include "absl/strings/ascii.h"
10
#include "absl/strings/str_cat.h"
11
#include "pagespeed/kernel/packs/url_norm.h"
12
13
namespace pagespeed::packs {
14
15
71.4k
absl::StatusOr<Glob> CompileGlob(std::string_view text) {
16
71.4k
  if (text.empty()) return absl::InvalidArgumentError("glob is empty");
17
71.4k
  if (text.size() > kMaxGlobBytes) {
18
30
    return absl::InvalidArgumentError(
19
30
        absl::StrCat("glob is longer than ", kMaxGlobBytes, " bytes"));
20
30
  }
21
71.4k
  if (text.front() != '/') {
22
55
    return absl::InvalidArgumentError("glob must start with '/'");
23
55
  }
24
71.3k
  std::string pattern = "(?s)";
25
1.80M
  for (size_t i = 0; i < text.size();) {
26
1.73M
    const char c = text[i];
27
1.73M
    if (c == '?' || c == '#' || static_cast<unsigned char>(c) <= 0x20 ||
28
1.73M
        static_cast<unsigned char>(c) == 0x7f) {
29
59
      return absl::InvalidArgumentError(
30
59
          absl::StrCat("glob contains the character at offset ", i,
31
59
                       " which cannot appear in a URL path"));
32
59
    }
33
1.73M
    if (c == '*') {
34
80.5k
      size_t run = 1;
35
137k
      while (i + run < text.size() && text[i + run] == '*') ++run;
36
80.5k
      if (run > 2) {
37
11
        return absl::InvalidArgumentError(
38
11
            "glob contains '***'; use '*' or '**'");
39
11
      }
40
80.4k
      pattern += run == 1 ? "[^/]*" : ".*";
41
80.4k
      i += run;
42
1.65M
    } else {
43
1.65M
      pattern += RE2::QuoteMeta(std::string_view(&text[i], 1));
44
1.65M
      ++i;
45
1.65M
    }
46
1.73M
  }
47
71.3k
  auto re = std::make_shared<const RE2>(pattern, MakeRegexOptions());
48
71.3k
  if (!re->ok()) {
49
0
    return absl::InvalidArgumentError(
50
0
        absl::StrCat("glob does not compile: ", re->error()));
51
0
  }
52
71.3k
  Glob glob;
53
71.3k
  glob.text = std::string(text);
54
71.3k
  glob.pattern = std::move(pattern);
55
71.3k
  glob.regex = std::move(re);
56
71.3k
  return glob;
57
71.3k
}
58
59
absl::StatusOr<std::shared_ptr<const RE2::Set>> CompileGlobSet(
60
9.45k
    const std::vector<Glob>& globs) {
61
9.45k
  auto set = std::make_shared<RE2::Set>(MakeRegexOptions(), RE2::ANCHOR_BOTH);
62
62.8k
  for (const Glob& g : globs) {
63
62.8k
    std::string error;
64
62.8k
    if (set->Add(g.pattern, &error) < 0) {
65
0
      return absl::InvalidArgumentError(
66
0
          absl::StrCat("glob \"", g.text, "\" does not compile: ", error));
67
0
    }
68
62.8k
  }
69
9.45k
  if (!set->Compile()) {
70
0
    return absl::InvalidArgumentError(
71
0
        "the globs together exceed the regex memory budget");
72
0
  }
73
9.45k
  return std::shared_ptr<const RE2::Set>(std::move(set));
74
9.45k
}
75
76
0
bool MatchGlob(const Glob& glob, std::string_view path) {
77
0
  return glob.regex != nullptr && RE2::FullMatch(path, *glob.regex);
78
0
}
79
80
58.0k
std::string NormalizeHost(std::string_view host) {
81
58.0k
  std::string_view h = host;
82
58.0k
  if (!h.empty() && h.front() == '[') {
83
0
    const size_t close = h.find(']');
84
0
    if (close != std::string_view::npos) h = h.substr(0, close + 1);
85
58.0k
  } else {
86
58.0k
    const size_t colon = h.rfind(':');
87
58.0k
    if (colon != std::string_view::npos) h = h.substr(0, colon);
88
58.0k
  }
89
58.0k
  std::string out = absl::AsciiStrToLower(h);
90
58.0k
  if (out.size() > 1 && out.back() == '.') out.pop_back();
91
58.0k
  return out;
92
58.0k
}
93
94
29.0k
bool SiteMatchesHost(const Site& site, std::string_view normalized_host) {
95
29.0k
  if (!site.wildcard) return normalized_host == site.host;
96
  // "*.example.org" matches "a.example.org" and "a.b.example.org" only.
97
0
  if (normalized_host.size() <= site.host.size() + 1) return false;
98
0
  const size_t split = normalized_host.size() - site.host.size();
99
0
  return normalized_host[split - 1] == '.' &&
100
0
         normalized_host.substr(split) == site.host;
101
0
}
102
103
29.0k
const Site* FindSite(const Pack& pack, std::string_view host) {
104
29.0k
  const std::string h = NormalizeHost(host);
105
29.0k
  const Site* best = nullptr;
106
29.0k
  for (const Site& site : pack.sites) {
107
29.0k
    if (!SiteMatchesHost(site, h)) continue;
108
    // An exact host beats a wildcard; among wildcards the longer suffix wins.
109
29.0k
    const bool better = best == nullptr || (!site.wildcard && best->wildcard) ||
110
0
                        (site.wildcard && best->wildcard &&
111
0
                         site.host.size() > best->host.size());
112
29.0k
    if (better) best = &site;
113
29.0k
  }
114
29.0k
  return best;
115
29.0k
}
116
117
std::optional<std::vector<std::string>> MatchRulePath(const Rule& rule,
118
435k
                                                      std::string_view path) {
119
435k
  const RuleMatch& m = rule.match;
120
435k
  auto any_match = [&](const std::shared_ptr<const RE2::Set>& set,
121
435k
                       const std::vector<Glob>& globs) {
122
435k
    if (set != nullptr) {
123
435k
      RE2::Set::ErrorInfo info;
124
435k
      if (set->Match(path, nullptr, &info)) return true;
125
      // "No match" is only trustworthy when the automaton ran to the end.
126
297k
      if (info.kind == RE2::Set::kNoError) return false;
127
297k
    }
128
0
    for (const Glob& g : globs) {
129
0
      if (MatchGlob(g, path)) return true;
130
0
    }
131
0
    return false;
132
0
  };
133
435k
  if (!any_match(m.paths_set, m.paths)) return std::nullopt;
134
137k
  if (!m.exclude_paths.empty() && any_match(m.exclude_set, m.exclude_paths)) {
135
0
    return std::nullopt;
136
0
  }
137
138
137k
  std::vector<std::string> captures;
139
137k
  if (m.path_regex != nullptr) {
140
11.1k
    const int groups = std::min(m.path_regex_groups, kMaxCaptureRefs);
141
11.1k
    std::vector<std::string_view> sub(static_cast<size_t>(groups) + 1);
142
11.1k
    if (!m.path_regex->Match(path, 0, path.size(), RE2::ANCHOR_BOTH, sub.data(),
143
11.1k
                             static_cast<int>(sub.size()))) {
144
0
      return std::nullopt;
145
0
    }
146
33.5k
    for (int i = 1; i <= groups; ++i) {
147
22.3k
      captures.emplace_back(sub[static_cast<size_t>(i)]);
148
22.3k
    }
149
11.1k
  }
150
137k
  return captures;
151
137k
}
152
153
Selection SelectRules(const Pack& pack, std::string_view host,
154
29.0k
                      std::string_view path) {
155
29.0k
  Selection sel;
156
29.0k
  sel.site = FindSite(pack, host);
157
29.0k
  if (sel.site == nullptr) return sel;
158
435k
  for (const Rule& rule : pack.rules) {
159
435k
    if (!rule.enabled) continue;
160
435k
    if (rule.kind == nullptr) continue;  // hand-built rule without a kind
161
435k
    auto captures = MatchRulePath(rule, path);
162
435k
    if (!captures.has_value()) continue;
163
137k
    auto& slot = sel.by_kind[KindIndex(rule.kind)];
164
137k
    if (slot.has_value()) {
165
0
      sel.shadowed.push_back(&rule);
166
137k
    } else {
167
137k
      slot = RuleHit{&rule, *std::move(captures)};
168
137k
    }
169
137k
  }
170
29.0k
  return sel;
171
29.0k
}
172
173
const std::string* LookupTableValue(const ValueTable& table,
174
                                    std::string_view path,
175
9.88k
                                    std::string_view query) {
176
9.88k
  if (!query.empty()) {
177
4.02k
    auto it = table.find(absl::StrCat(path, "?", query));
178
4.02k
    if (it != table.end()) return &it->second;
179
4.02k
  }
180
9.88k
  auto it = table.find(path);
181
9.88k
  return it == table.end() ? nullptr : &it->second;
182
9.88k
}
183
184
const HreflangCluster* FindCluster(const Pack& pack,
185
0
                                   std::string_view page_url) {
186
0
  const auto norm = NormUrl(page_url);
187
0
  if (!norm.has_value()) return nullptr;
188
0
  auto it = pack.cluster_index.find(*norm);
189
0
  return it == pack.cluster_index.end() ? nullptr
190
0
                                        : &pack.hreflang_clusters[it->second];
191
0
}
192
193
}  // namespace pagespeed::packs