File: url_pattern_util.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (275 lines) | stat: -rw-r--r-- 8,629 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "components/url_pattern/url_pattern_util.h"

#include <ranges>
#include <string_view>

#include "base/numerics/safe_conversions.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "url/url_util.h"

namespace url_pattern {
namespace {

std::string StdStringFromCanonOutput(const url::CanonOutput& output,
                                     const url::Component& component) {
  return std::string(output.data() + component.begin, component.len);
}

bool ContainsForbiddenHostnameCodePoint(std::string_view input) {
  // The full list of forbidden code points is defined at:
  //
  //  https://url.spec.whatwg.org/#forbidden-host-code-point
  //
  // We only check the code points the chromium URL parser incorrectly permits.
  // See: crbug.com/1065667#c18
  return std::ranges::any_of(input, [](char c) {
    return c == ' ' || c == '#' || c == ':' || c == '<' || c == '>' ||
           c == '@' || c == '[' || c == ']' || c == '|';
  });
}

}  // namespace

base::expected<std::string, absl::Status> ProtocolEncodeCallback(
    std::string_view input) {
  if (input.empty()) {
    return std::string();
  }

  url::RawCanonOutputT<char> canon_output;
  url::Component component;

  bool result = url::CanonicalizeScheme(input, &canon_output, &component);

  if (!result) {
    return base::unexpected(absl::InvalidArgumentError(
        base::StrCat({"Invalid protocol '", input, "'."})));
  }

  return StdStringFromCanonOutput(canon_output, component);
}

base::expected<std::string, absl::Status> UsernameEncodeCallback(
    std::string_view input) {
  if (input.empty()) {
    return std::string();
  }

  url::RawCanonOutputT<char> canon_output;
  url::Component username_component;
  url::Component password_component;

  bool result =
      url::CanonicalizeUserInfo(input, std::string_view(), &canon_output,
                                &username_component, &password_component);

  if (!result) {
    return base::unexpected(absl::InvalidArgumentError(
        base::StrCat({"Invalid username pattern '", input, "'."})));
  }

  return StdStringFromCanonOutput(canon_output, username_component);
}

base::expected<std::string, absl::Status> PasswordEncodeCallback(
    std::string_view input) {
  if (input.empty()) {
    return std::string();
  }

  url::RawCanonOutputT<char> canon_output;
  url::Component username_component;
  url::Component password_component;

  bool result =
      url::CanonicalizeUserInfo(std::string_view(), input, &canon_output,
                                &username_component, &password_component);

  if (!result) {
    return base::unexpected(absl::InvalidArgumentError(
        base::StrCat({"Invalid password pattern '", input, "'."})));
  }

  return StdStringFromCanonOutput(canon_output, password_component);
}

base::expected<std::string, absl::Status> IPv6HostnameEncodeCallback(
    std::string_view input) {
  std::string result;
  result.reserve(input.size());
  // This implements a light validation and canonicalization of IPv6 hostname
  // content.  Ideally we would use the URL parser's hostname canonicalizer
  // here, but that is too strict for the encoding callback.  The callback may
  // see only bits and pieces of the hostname pattern; e.g. for `[:address]` it
  // sees the `[` and `]` strings as separate calls.  Since the full URL
  // hostname parser wants to completely parse IPv6 hostnames, this will always
  // trigger an error.  Therefore, to allow pattern syntax within IPv6 brackets
  // we simply check for valid characters and lowercase any hex digits.
  for (size_t i = 0; i < input.size(); ++i) {
    char c = input[i];
    if (!base::IsHexDigit(c) && c != '[' && c != ']' && c != ':') {
      return base::unexpected(absl::InvalidArgumentError(
          base::StrCat({"Invalid IPv6 hostname character '",
                        std::string_view(&c, 1), "' in '", input, "'."})));
    }
    result += base::ToLowerASCII(c);
  }
  return result;
}

base::expected<std::string, absl::Status> HostnameEncodeCallback(
    std::string_view input) {
  if (input.empty()) {
    return std::string();
  }

  // Due to crbug.com/1065667 the url::CanonicalizeHost() call below will
  // permit and possibly encode some illegal code points.  Since we want
  // to ultimately fix that in the future we don't want to encourage more
  // use of these characters in URLPattern.  Therefore we apply an additional
  // restrictive check for these forbidden code points.
  //
  // TODO(crbug.com/40124263): Remove this check after the URL parser is fixed.
  if (ContainsForbiddenHostnameCodePoint(input)) {
    return base::unexpected(absl::InvalidArgumentError(
        base::StrCat({"Invalid hostname pattern '", input, "'."})));
  }

  url::RawCanonOutputT<char> canon_output;
  url::Component component;

  bool result = url::CanonicalizeHost(
      input.data(), url::Component(0, base::checked_cast<int>(input.size())),
      &canon_output, &component);

  if (!result) {
    return base::unexpected(absl::InvalidArgumentError(
        base::StrCat({"Invalid hostname pattern '", input, "'."})));
  }

  return StdStringFromCanonOutput(canon_output, component);
}

base::expected<std::string, absl::Status> PortEncodeCallback(
    std::string_view input) {
  if (input.empty()) {
    return std::string();
  }

  url::RawCanonOutputT<char> canon_output;
  url::Component component;

  bool result = url::CanonicalizePort(
      input.data(), url::Component(0, base::checked_cast<int>(input.size())),
      url::PORT_UNSPECIFIED, &canon_output, &component);

  if (!result) {
    return base::unexpected(absl::InvalidArgumentError(
        base::StrCat({"Invalid port pattern '", input, "'."})));
  }

  return StdStringFromCanonOutput(canon_output, component);
}

base::expected<std::string, absl::Status> StandardURLPathnameEncodeCallback(
    std::string_view input) {
  if (input.empty()) {
    return std::string();
  }

  url::RawCanonOutputT<char> canon_output;
  url::Component component;

  bool result = url::CanonicalizePartialPath(
      input.data(), url::Component(0, base::checked_cast<int>(input.size())),
      &canon_output, &component);

  if (!result) {
    return base::unexpected(absl::InvalidArgumentError(
        base::StrCat({"Invalid pathname pattern '", input, "'."})));
  }

  return StdStringFromCanonOutput(canon_output, component);
}

base::expected<std::string, absl::Status> PathURLPathnameEncodeCallback(
    std::string_view input) {
  if (input.empty()) {
    return std::string();
  }

  url::RawCanonOutputT<char> canon_output;
  url::Component component;

  url::CanonicalizePathURLPath(
      input.data(), url::Component(0, base::checked_cast<int>(input.size())),
      &canon_output, &component);

  return StdStringFromCanonOutput(canon_output, component);
}

base::expected<std::string, absl::Status> SearchEncodeCallback(
    std::string_view input) {
  if (input.empty()) {
    return std::string();
  }

  url::RawCanonOutputT<char> canon_output;
  url::Component component;

  url::CanonicalizeQuery(input, /*converter=*/nullptr, &canon_output,
                         &component);

  return StdStringFromCanonOutput(canon_output, component);
}

base::expected<std::string, absl::Status> HashEncodeCallback(
    std::string_view input) {
  if (input.empty()) {
    return std::string();
  }

  url::RawCanonOutputT<char> canon_output;
  url::Component component;

  url::CanonicalizeRef(input, &canon_output, &component);

  return StdStringFromCanonOutput(canon_output, component);
}

// Utility method to determine if a particular hostname pattern should be
// treated as an IPv6 hostname.  This implements a simple and fast heuristic
// looking for a leading `[`.  It is intended to catch the most common cases
// with minimum overhead.
bool TreatAsIPv6Hostname(std::string_view pattern_utf8) {
  // The `[` string cannot be a valid IPv6 hostname.  We need at least two
  // characters to represent `[*`.
  if (pattern_utf8.size() < 2) {
    return false;
  }

  if (pattern_utf8[0] == '[') {
    return true;
  }

  // We do a bit of extra work to detect brackets behind an escape and
  // within a grouping.
  if ((pattern_utf8[0] == '\\' || pattern_utf8[0] == '{') &&
      pattern_utf8[1] == '[') {
    return true;
  }

  return false;
}

}  // namespace url_pattern