1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <limits.h>
6
7 #include "base/check.h"
8 #include "base/check_op.h"
9 #include "third_party/abseil-cpp/absl/types/optional.h"
10 #include "url/url_canon.h"
11 #include "url/url_canon_internal.h"
12 #include "url/url_parse_internal.h"
13
14 namespace url {
15
16 namespace {
17
18 enum CharacterFlags {
19 // Pass through unchanged, whether escaped or unescaped. This doesn't
20 // actually set anything so you can't OR it to check, it's just to make the
21 // table below more clear when neither ESCAPE or UNESCAPE is set.
22 PASS = 0,
23
24 // This character requires special handling in DoPartialPathInternal. Doing
25 // this test
26 // first allows us to filter out the common cases of regular characters that
27 // can be directly copied.
28 SPECIAL = 1,
29
30 // This character must be escaped in the canonical output. Note that all
31 // escaped chars also have the "special" bit set so that the code that looks
32 // for this is triggered. Not valid with PASS or ESCAPE
33 ESCAPE_BIT = 2,
34 ESCAPE = ESCAPE_BIT | SPECIAL,
35
36 // This character must be unescaped in canonical output. Not valid with
37 // ESCAPE or PASS. We DON'T set the SPECIAL flag since if we encounter these
38 // characters unescaped, they should just be copied.
39 UNESCAPE = 4,
40
41 // This character is disallowed in URLs. Note that the "special" bit is also
42 // set to trigger handling.
43 INVALID_BIT = 8,
44 INVALID = INVALID_BIT | SPECIAL,
45 };
46
47 // This table contains one of the above flag values. Note some flags are more
48 // than one bits because they also turn on the "special" flag. Special is the
49 // only flag that may be combined with others.
50 //
51 // This table is designed to match exactly what IE does with the characters.
52 //
53 // Dot is even more special, and the escaped version is handled specially by
54 // IsDot. Therefore, we don't need the "escape" flag, and even the "unescape"
55 // bit is never handled (we just need the "special") bit.
56 const unsigned char kPathCharLookup[0x100] = {
57 // NULL control chars...
58 INVALID, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
59 // control chars...
60 ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
61 // ' ' ! " # $ % & ' ( ) * + , - . /
62 ESCAPE, PASS, ESCAPE, ESCAPE, PASS, ESCAPE, PASS, PASS, PASS, PASS, PASS, PASS, PASS, UNESCAPE,SPECIAL, PASS,
63 // 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
64 UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,PASS, PASS, ESCAPE, PASS, ESCAPE, ESCAPE,
65 // @ A B C D E F G H I J K L M N O
66 PASS, UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,
67 // P Q R S T U V W X Y Z [ \ ] ^ _
68 UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,PASS, ESCAPE, PASS, ESCAPE, UNESCAPE,
69 // ` a b c d e f g h i j k l m n o
70 ESCAPE, UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,
71 // p q r s t u v w x y z { | } ~ <NBSP>
72 UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,ESCAPE, ESCAPE, ESCAPE, UNESCAPE,ESCAPE,
73 // ...all the high-bit characters are escaped
74 ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
75 ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
76 ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
77 ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
78 ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
79 ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
80 ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
81 ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE};
82
83 enum DotDisposition {
84 // The given dot is just part of a filename and is not special.
85 NOT_A_DIRECTORY,
86
87 // The given dot is the current directory.
88 DIRECTORY_CUR,
89
90 // The given dot is the first of a double dot that should take us up one.
91 DIRECTORY_UP
92 };
93
94 // When the path resolver finds a dot, this function is called with the
95 // character following that dot to see what it is. The return value
96 // indicates what type this dot is (see above). This code handles the case
97 // where the dot is at the end of the input.
98 //
99 // |*consumed_len| will contain the number of characters in the input that
100 // express what we found.
101 //
102 // If the input is "../foo", |after_dot| = 1, |end| = 6, and
103 // at the end, |*consumed_len| = 2 for the "./" this function consumed. The
104 // original dot length should be handled by the caller.
105 template <typename CHAR>
ClassifyAfterDot(const CHAR * spec,size_t after_dot,size_t end,size_t * consumed_len)106 DotDisposition ClassifyAfterDot(const CHAR* spec,
107 size_t after_dot,
108 size_t end,
109 size_t* consumed_len) {
110 if (after_dot == end) {
111 // Single dot at the end.
112 *consumed_len = 0;
113 return DIRECTORY_CUR;
114 }
115 if (IsURLSlash(spec[after_dot])) {
116 // Single dot followed by a slash.
117 *consumed_len = 1; // Consume the slash
118 return DIRECTORY_CUR;
119 }
120
121 size_t second_dot_len = IsDot(spec, after_dot, end);
122 if (second_dot_len) {
123 size_t after_second_dot = after_dot + second_dot_len;
124 if (after_second_dot == end) {
125 // Double dot at the end.
126 *consumed_len = second_dot_len;
127 return DIRECTORY_UP;
128 }
129 if (IsURLSlash(spec[after_second_dot])) {
130 // Double dot followed by a slash.
131 *consumed_len = second_dot_len + 1;
132 return DIRECTORY_UP;
133 }
134 }
135
136 // The dots are followed by something else, not a directory.
137 *consumed_len = 0;
138 return NOT_A_DIRECTORY;
139 }
140
141 // Rewinds the output to the previous slash. It is assumed that the output
142 // ends with a slash and this doesn't count (we call this when we are
143 // appending directory paths, so the previous path component has and ending
144 // slash).
145 //
146 // This will stop at the first slash (assumed to be at position
147 // |path_begin_in_output| and not go any higher than that. Some web pages
148 // do ".." too many times, so we need to handle that brokenness.
149 //
150 // It searches for a literal slash rather than including a backslash as well
151 // because it is run only on the canonical output.
152 //
153 // The output is guaranteed to end in a slash when this function completes.
BackUpToPreviousSlash(size_t path_begin_in_output,CanonOutput * output)154 void BackUpToPreviousSlash(size_t path_begin_in_output, CanonOutput* output) {
155 CHECK(output->length() > 0);
156 CHECK(path_begin_in_output < output->length());
157
158 size_t i = output->length() - 1;
159 DCHECK(output->at(i) == '/');
160 if (i == path_begin_in_output)
161 return; // We're at the first slash, nothing to do.
162
163 // Now back up (skipping the trailing slash) until we find another slash.
164 do {
165 --i;
166 } while (output->at(i) != '/' && i > path_begin_in_output);
167
168 // Now shrink the output to just include that last slash we found.
169 output->set_length(i + 1);
170 }
171
172 // Looks for problematic nested escape sequences and escapes the output as
173 // needed to ensure they can't be misinterpreted.
174 //
175 // Our concern is that in input escape sequence that's invalid because it
176 // contains nested escape sequences might look valid once those are unescaped.
177 // For example, "%%300" is not a valid escape sequence, but after unescaping the
178 // inner "%30" this becomes "%00" which is valid. Leaving this in the output
179 // string can result in callers re-canonicalizing the string and unescaping this
180 // sequence, thus resulting in something fundamentally different than the
181 // original input here. This can cause a variety of problems.
182 //
183 // This function is called after we've just unescaped a sequence that's within
184 // two output characters of a previous '%' that we know didn't begin a valid
185 // escape sequence in the input string. We look for whether the output is going
186 // to turn into a valid escape sequence, and if so, convert the initial '%' into
187 // an escaped "%25" so the output can't be misinterpreted.
188 //
189 // |spec| is the input string we're canonicalizing.
190 // |next_input_index| is the index of the next unprocessed character in |spec|.
191 // |input_len| is the length of |spec|.
192 // |last_invalid_percent_index| is the index in |output| of a previously-seen
193 // '%' character. The caller knows this '%' character isn't followed by a valid
194 // escape sequence in the input string.
195 // |output| is the canonicalized output thus far. The caller guarantees this
196 // ends with a '%' followed by one or two characters, and the '%' is the one
197 // pointed to by |last_invalid_percent_index|. The last character in the string
198 // was just unescaped.
199 template <typename CHAR>
CheckForNestedEscapes(const CHAR * spec,size_t next_input_index,size_t input_len,size_t last_invalid_percent_index,CanonOutput * output)200 void CheckForNestedEscapes(const CHAR* spec,
201 size_t next_input_index,
202 size_t input_len,
203 size_t last_invalid_percent_index,
204 CanonOutput* output) {
205 const size_t length = output->length();
206 const char last_unescaped_char = output->at(length - 1);
207
208 // If |output| currently looks like "%c", we need to try appending the next
209 // input character to see if this will result in a problematic escape
210 // sequence. Note that this won't trigger on the first nested escape of a
211 // two-escape sequence like "%%30%30" -- we'll allow the conversion to
212 // "%0%30" -- but the second nested escape will be caught by this function
213 // when it's called again in that case.
214 const bool append_next_char = last_invalid_percent_index == length - 2;
215 if (append_next_char) {
216 // If the input doesn't contain a 7-bit character next, this case won't be a
217 // problem.
218 if ((next_input_index == input_len) || (spec[next_input_index] >= 0x80))
219 return;
220 output->push_back(static_cast<char>(spec[next_input_index]));
221 }
222
223 // Now output ends like "%cc". Try to unescape this.
224 size_t begin = last_invalid_percent_index;
225 unsigned char temp;
226 if (DecodeEscaped(output->data(), &begin, output->length(), &temp)) {
227 // New escape sequence found. Overwrite the characters following the '%'
228 // with "25", and push_back() the one or two characters that were following
229 // the '%' when we were called.
230 if (!append_next_char)
231 output->push_back(output->at(last_invalid_percent_index + 1));
232 output->set(last_invalid_percent_index + 1, '2');
233 output->set(last_invalid_percent_index + 2, '5');
234 output->push_back(last_unescaped_char);
235 } else if (append_next_char) {
236 // Not a valid escape sequence, but we still need to undo appending the next
237 // source character so the caller can process it normally.
238 output->set_length(length);
239 }
240 }
241
242 // Canonicalizes and appends the given path to the output. It assumes that if
243 // the input path starts with a slash, it should be copied to the output.
244 //
245 // If there are already path components (this mode is used when appending
246 // relative paths for resolving), it assumes that the output already has
247 // a trailing slash and that if the input begins with a slash, it should be
248 // copied to the output.
249 //
250 // We do not collapse multiple slashes in a row to a single slash. It seems
251 // no web browsers do this, and we don't want incompatibilities, even though
252 // it would be correct for most systems.
253 template <typename CHAR, typename UCHAR>
DoPartialPathInternal(const CHAR * spec,const Component & path,size_t path_begin_in_output,CanonOutput * output)254 bool DoPartialPathInternal(const CHAR* spec,
255 const Component& path,
256 size_t path_begin_in_output,
257 CanonOutput* output) {
258 if (path.is_empty())
259 return true;
260
261 size_t end = static_cast<size_t>(path.end());
262
263 // We use this variable to minimize the amount of work done when unescaping --
264 // we'll only call CheckForNestedEscapes() when this points at one of the last
265 // couple of characters in |output|.
266 absl::optional<size_t> last_invalid_percent_index;
267
268 bool success = true;
269 for (size_t i = static_cast<size_t>(path.begin); i < end; i++) {
270 UCHAR uch = static_cast<UCHAR>(spec[i]);
271 if (sizeof(CHAR) > 1 && uch >= 0x80) {
272 // We only need to test wide input for having non-ASCII characters. For
273 // narrow input, we'll always just use the lookup table. We don't try to
274 // do anything tricky with decoding/validating UTF-8. This function will
275 // read one or two UTF-16 characters and append the output as UTF-8. This
276 // call will be removed in 8-bit mode.
277 success &= AppendUTF8EscapedChar(spec, &i, end, output);
278 } else {
279 // Normal ASCII character or 8-bit input, use the lookup table.
280 unsigned char out_ch = static_cast<unsigned char>(uch);
281 unsigned char flags = kPathCharLookup[out_ch];
282 if (flags & SPECIAL) {
283 // Needs special handling of some sort.
284 size_t dotlen;
285 if ((dotlen = IsDot(spec, i, end)) > 0) {
286 // See if this dot was preceded by a slash in the output.
287 //
288 // Note that we check this in the case of dots so we don't have to
289 // special case slashes. Since slashes are much more common than
290 // dots, this actually increases performance measurably (though
291 // slightly).
292 if (output->length() > path_begin_in_output &&
293 output->at(output->length() - 1) == '/') {
294 // Slash followed by a dot, check to see if this is means relative
295 size_t consumed_len;
296 switch (ClassifyAfterDot<CHAR>(spec, i + dotlen, end,
297 &consumed_len)) {
298 case NOT_A_DIRECTORY:
299 // Copy the dot to the output, it means nothing special.
300 output->push_back('.');
301 i += dotlen - 1;
302 break;
303 case DIRECTORY_CUR: // Current directory, just skip the input.
304 i += dotlen + consumed_len - 1;
305 break;
306 case DIRECTORY_UP:
307 BackUpToPreviousSlash(path_begin_in_output, output);
308 if (last_invalid_percent_index >= output->length()) {
309 last_invalid_percent_index = absl::nullopt;
310 }
311 i += dotlen + consumed_len - 1;
312 break;
313 }
314 } else {
315 // This dot is not preceded by a slash, it is just part of some
316 // file name.
317 output->push_back('.');
318 i += dotlen - 1;
319 }
320
321 } else if (out_ch == '\\') {
322 // Convert backslashes to forward slashes
323 output->push_back('/');
324
325 } else if (out_ch == '%') {
326 // Handle escape sequences.
327 unsigned char unescaped_value;
328 if (DecodeEscaped(spec, &i, end, &unescaped_value)) {
329 // Valid escape sequence, see if we keep, reject, or unescape it.
330 // Note that at this point DecodeEscape() will have advanced |i| to
331 // the last character of the escape sequence.
332 char unescaped_flags = kPathCharLookup[unescaped_value];
333
334 if (unescaped_flags & UNESCAPE) {
335 // This escaped value shouldn't be escaped. Try to copy it.
336 output->push_back(unescaped_value);
337 // If we just unescaped a value within 2 output characters of the
338 // '%' from a previously-detected invalid escape sequence, we
339 // might have an input string with problematic nested escape
340 // sequences; detect and fix them.
341 if (last_invalid_percent_index.has_value() &&
342 ((last_invalid_percent_index.value() + 3) >=
343 output->length())) {
344 CheckForNestedEscapes(spec, i + 1, end,
345 last_invalid_percent_index.value(),
346 output);
347 }
348 } else {
349 // Either this is an invalid escaped character, or it's a valid
350 // escaped character we should keep escaped. In the first case we
351 // should just copy it exactly and remember the error. In the
352 // second we also copy exactly in case the server is sensitive to
353 // changing the case of any hex letters.
354 output->push_back('%');
355 output->push_back(static_cast<char>(spec[i - 1]));
356 output->push_back(static_cast<char>(spec[i]));
357 if (unescaped_flags & INVALID_BIT)
358 success = false;
359 }
360 } else {
361 // Invalid escape sequence. IE7+ rejects any URLs with such
362 // sequences, while other browsers pass them through unchanged. We
363 // use the permissive behavior.
364 // TODO(brettw): Consider testing IE's strict behavior, which would
365 // allow removing the code to handle nested escapes above.
366 last_invalid_percent_index = output->length();
367 output->push_back('%');
368 }
369
370 } else if (flags & INVALID_BIT) {
371 // For NULLs, etc. fail.
372 AppendEscapedChar(out_ch, output);
373 success = false;
374
375 } else if (flags & ESCAPE_BIT) {
376 // This character should be escaped.
377 AppendEscapedChar(out_ch, output);
378 }
379 } else {
380 // Nothing special about this character, just append it.
381 output->push_back(out_ch);
382 }
383 }
384 }
385 return success;
386 }
387
388 // Perform the same logic as in DoPartialPathInternal(), but updates the
389 // publicly exposed CanonOutput structure similar to DoPath(). Returns
390 // true if successful.
391 template <typename CHAR, typename UCHAR>
DoPartialPath(const CHAR * spec,const Component & path,CanonOutput * output,Component * out_path)392 bool DoPartialPath(const CHAR* spec,
393 const Component& path,
394 CanonOutput* output,
395 Component* out_path) {
396 out_path->begin = output->length();
397 bool success =
398 DoPartialPathInternal<CHAR, UCHAR>(spec, path, out_path->begin, output);
399 out_path->len = output->length() - out_path->begin;
400 return success;
401 }
402
403 template<typename CHAR, typename UCHAR>
DoPath(const CHAR * spec,const Component & path,CanonOutput * output,Component * out_path)404 bool DoPath(const CHAR* spec,
405 const Component& path,
406 CanonOutput* output,
407 Component* out_path) {
408 bool success = true;
409 out_path->begin = output->length();
410 if (path.is_nonempty()) {
411 // Write out an initial slash if the input has none. If we just parse a URL
412 // and then canonicalize it, it will of course have a slash already. This
413 // check is for the replacement and relative URL resolving cases of file
414 // URLs.
415 if (!IsURLSlash(spec[path.begin]))
416 output->push_back('/');
417
418 success =
419 DoPartialPathInternal<CHAR, UCHAR>(spec, path, out_path->begin, output);
420 } else {
421 // No input, canonical path is a slash.
422 output->push_back('/');
423 }
424 out_path->len = output->length() - out_path->begin;
425 return success;
426 }
427
428 } // namespace
429
CanonicalizePath(const char * spec,const Component & path,CanonOutput * output,Component * out_path)430 bool CanonicalizePath(const char* spec,
431 const Component& path,
432 CanonOutput* output,
433 Component* out_path) {
434 return DoPath<char, unsigned char>(spec, path, output, out_path);
435 }
436
CanonicalizePath(const char16_t * spec,const Component & path,CanonOutput * output,Component * out_path)437 bool CanonicalizePath(const char16_t* spec,
438 const Component& path,
439 CanonOutput* output,
440 Component* out_path) {
441 return DoPath<char16_t, char16_t>(spec, path, output, out_path);
442 }
443
CanonicalizePartialPath(const char * spec,const Component & path,CanonOutput * output,Component * out_path)444 bool CanonicalizePartialPath(const char* spec,
445 const Component& path,
446 CanonOutput* output,
447 Component* out_path) {
448 return DoPartialPath<char, unsigned char>(spec, path, output, out_path);
449 }
450
CanonicalizePartialPath(const char16_t * spec,const Component & path,CanonOutput * output,Component * out_path)451 bool CanonicalizePartialPath(const char16_t* spec,
452 const Component& path,
453 CanonOutput* output,
454 Component* out_path) {
455 return DoPartialPath<char16_t, char16_t>(spec, path, output, out_path);
456 }
457
CanonicalizePartialPathInternal(const char * spec,const Component & path,size_t path_begin_in_output,CanonOutput * output)458 bool CanonicalizePartialPathInternal(const char* spec,
459 const Component& path,
460 size_t path_begin_in_output,
461 CanonOutput* output) {
462 return DoPartialPathInternal<char, unsigned char>(
463 spec, path, path_begin_in_output, output);
464 }
465
CanonicalizePartialPathInternal(const char16_t * spec,const Component & path,size_t path_begin_in_output,CanonOutput * output)466 bool CanonicalizePartialPathInternal(const char16_t* spec,
467 const Component& path,
468 size_t path_begin_in_output,
469 CanonOutput* output) {
470 return DoPartialPathInternal<char16_t, char16_t>(
471 spec, path, path_begin_in_output, output);
472 }
473
474 } // namespace url
475