• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/350788890): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9 
10 #include <limits.h>
11 
12 #include <optional>
13 
14 #include "base/check.h"
15 #include "base/check_op.h"
16 #include "url/url_canon.h"
17 #include "url/url_canon_internal.h"
18 #include "url/url_features.h"
19 #include "url/url_parse_internal.h"
20 
21 namespace url {
22 
23 namespace {
24 
25 enum CharacterFlags {
26   // Pass through unchanged, whether escaped or not. This doesn't
27   // actually set anything so you can't OR it to check, it's just to make the
28   // table below more clear when any other flag is not set.
29   PASS = 0,
30 
31   // This character requires special handling in DoPartialPathInternal. Doing
32   // this test
33   // first allows us to filter out the common cases of regular characters that
34   // can be directly copied.
35   SPECIAL = 1,
36 
37   // This character must be escaped in the canonical output. Note that all
38   // escaped chars also have the "special" bit set so that the code that looks
39   // for this is triggered. Not valid with PASS or ESCAPE
40   ESCAPE_BIT = 2,
41   ESCAPE = ESCAPE_BIT | SPECIAL,
42 };
43 
44 // This table contains one of the above flag values. Note some flags are more
45 // than one bits because they also turn on the "special" flag. Special is the
46 // only flag that may be combined with others.
47 //
48 // This table was used to be designed to match exactly what IE did with the
49 // characters, however, which doesn't comply with the URL Standard as of Dec
50 // 2023. See https://crbug.com/1509295.
51 //
52 // Dot is even more special, and the escaped version is handled specially by
53 // IsDot. Therefore, we don't need the "escape" flag. We just need the "special"
54 // bit.
55 //
56 // clang-format off
57 const unsigned char kPathCharLookup[0x100] = {
58 //   NULL     control chars...
59      ESCAPE , ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,
60 //   control chars...
61      ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,
62 //   ' '      !        "        #        $        %        &        '        (        )        *        +        ,        -        .        /
63      ESCAPE,  PASS,    ESCAPE,  ESCAPE,  PASS,    ESCAPE,  PASS,    PASS,    PASS,    PASS,    PASS,    PASS,    PASS,    PASS    ,SPECIAL, PASS,
64 //   0        1        2        3        4        5        6        7        8        9        :        ;        <        =        >        ?
65      PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS,    PASS,    ESCAPE,  PASS,    ESCAPE,  ESCAPE,
66 //   @        A        B        C        D        E        F        G        H        I        J        K        L        M        N        O
67      PASS,    PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,
68 //   P        Q        R        S        T        U        V        W        X        Y        Z        [        \        ]        ^        _
69      PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS,    ESCAPE,  PASS,    ESCAPE,  PASS    ,
70 //   `        a        b        c        d        e        f        g        h        i        j        k        l        m        n        o
71      ESCAPE,  PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,
72 //   p        q        r        s        t        u        v        w        x        y        z        {        |        }        ~        <NBSP>
73      PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,PASS    ,ESCAPE,  ESCAPE,  ESCAPE,  PASS    ,ESCAPE,
74 //   ...all the high-bit characters are escaped
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      ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE,  ESCAPE};
83 // clang-format on
84 
85 enum DotDisposition {
86   // The given dot is just part of a filename and is not special.
87   NOT_A_DIRECTORY,
88 
89   // The given dot is the current directory.
90   DIRECTORY_CUR,
91 
92   // The given dot is the first of a double dot that should take us up one.
93   DIRECTORY_UP
94 };
95 
96 // When the path resolver finds a dot, this function is called with the
97 // character following that dot to see what it is. The return value
98 // indicates what type this dot is (see above). This code handles the case
99 // where the dot is at the end of the input.
100 //
101 // |*consumed_len| will contain the number of characters in the input that
102 // express what we found.
103 //
104 // If the input is "../foo", |after_dot| = 1, |end| = 6, and
105 // at the end, |*consumed_len| = 2 for the "./" this function consumed. The
106 // original dot length should be handled by the caller.
107 template <typename CHAR>
ClassifyAfterDot(const CHAR * spec,size_t after_dot,size_t end,size_t * consumed_len)108 DotDisposition ClassifyAfterDot(const CHAR* spec,
109                                 size_t after_dot,
110                                 size_t end,
111                                 size_t* consumed_len) {
112   if (after_dot == end) {
113     // Single dot at the end.
114     *consumed_len = 0;
115     return DIRECTORY_CUR;
116   }
117   if (IsSlashOrBackslash(spec[after_dot])) {
118     // Single dot followed by a slash.
119     *consumed_len = 1;  // Consume the slash
120     return DIRECTORY_CUR;
121   }
122 
123   size_t second_dot_len = IsDot(spec, after_dot, end);
124   if (second_dot_len) {
125     size_t after_second_dot = after_dot + second_dot_len;
126     if (after_second_dot == end) {
127       // Double dot at the end.
128       *consumed_len = second_dot_len;
129       return DIRECTORY_UP;
130     }
131     if (IsSlashOrBackslash(spec[after_second_dot])) {
132       // Double dot followed by a slash.
133       *consumed_len = second_dot_len + 1;
134       return DIRECTORY_UP;
135     }
136   }
137 
138   // The dots are followed by something else, not a directory.
139   *consumed_len = 0;
140   return NOT_A_DIRECTORY;
141 }
142 
143 // Rewinds the output to the previous slash. It is assumed that the output
144 // ends with a slash and this doesn't count (we call this when we are
145 // appending directory paths, so the previous path component has and ending
146 // slash).
147 //
148 // This will stop at the first slash (assumed to be at position
149 // |path_begin_in_output| and not go any higher than that. Some web pages
150 // do ".." too many times, so we need to handle that brokenness.
151 //
152 // It searches for a literal slash rather than including a backslash as well
153 // because it is run only on the canonical output.
154 //
155 // The output is guaranteed to end in a slash when this function completes.
BackUpToPreviousSlash(size_t path_begin_in_output,CanonOutput * output)156 void BackUpToPreviousSlash(size_t path_begin_in_output, CanonOutput* output) {
157   CHECK(output->length() > 0);
158   CHECK(path_begin_in_output < output->length());
159 
160   size_t i = output->length() - 1;
161   DCHECK(output->at(i) == '/');
162   if (i == path_begin_in_output)
163     return;  // We're at the first slash, nothing to do.
164 
165   // Now back up (skipping the trailing slash) until we find another slash.
166   do {
167     --i;
168   } while (output->at(i) != '/' && i > path_begin_in_output);
169 
170   // Now shrink the output to just include that last slash we found.
171   output->set_length(i + 1);
172 }
173 
174 // Canonicalizes and appends the given path to the output. It assumes that if
175 // the input path starts with a slash, it should be copied to the output.
176 //
177 // If there are already path components (this mode is used when appending
178 // relative paths for resolving), it assumes that the output already has
179 // a trailing slash and that if the input begins with a slash, it should be
180 // copied to the output.
181 //
182 // We do not collapse multiple slashes in a row to a single slash. It seems
183 // no web browsers do this, and we don't want incompatibilities, even though
184 // it would be correct for most systems.
185 template <typename CHAR, typename UCHAR>
DoPartialPathInternal(const CHAR * spec,const Component & path,size_t path_begin_in_output,CanonMode canon_mode,CanonOutput * output)186 bool DoPartialPathInternal(const CHAR* spec,
187                            const Component& path,
188                            size_t path_begin_in_output,
189                            CanonMode canon_mode,
190                            CanonOutput* output) {
191   if (path.is_empty())
192     return true;
193 
194   size_t end = static_cast<size_t>(path.end());
195 
196   bool success = true;
197   for (size_t i = static_cast<size_t>(path.begin); i < end; i++) {
198     UCHAR uch = static_cast<UCHAR>(spec[i]);
199     if (sizeof(CHAR) > 1 && uch >= 0x80) {
200       // We only need to test wide input for having non-ASCII characters. For
201       // narrow input, we'll always just use the lookup table. We don't try to
202       // do anything tricky with decoding/validating UTF-8. This function will
203       // read one or two UTF-16 characters and append the output as UTF-8. This
204       // call will be removed in 8-bit mode.
205       success &= AppendUTF8EscapedChar(spec, &i, end, output);
206     } else {
207       // Normal ASCII character or 8-bit input, use the lookup table.
208       unsigned char out_ch = static_cast<unsigned char>(uch);
209       unsigned char flags = kPathCharLookup[out_ch];
210       if (flags & SPECIAL) {
211         // Needs special handling of some sort.
212         size_t dotlen;
213         if ((dotlen = IsDot(spec, i, end)) > 0) {
214           // See if this dot was preceded by a slash in the output.
215           //
216           // Note that we check this in the case of dots so we don't have to
217           // special case slashes. Since slashes are much more common than
218           // dots, this actually increases performance measurably (though
219           // slightly).
220           if (output->length() > path_begin_in_output &&
221               output->at(output->length() - 1) == '/') {
222             // Slash followed by a dot, check to see if this is means relative
223             size_t consumed_len;
224             switch (ClassifyAfterDot<CHAR>(spec, i + dotlen, end,
225                                            &consumed_len)) {
226               case NOT_A_DIRECTORY:
227                 // Copy the dot to the output, it means nothing special.
228                 output->push_back('.');
229                 i += dotlen - 1;
230                 break;
231               case DIRECTORY_CUR:  // Current directory, just skip the input.
232                 i += dotlen + consumed_len - 1;
233                 break;
234               case DIRECTORY_UP:
235                 BackUpToPreviousSlash(path_begin_in_output, output);
236                 i += dotlen + consumed_len - 1;
237                 break;
238             }
239           } else {
240             // This dot is not preceded by a slash, it is just part of some
241             // file name.
242             output->push_back('.');
243             i += dotlen - 1;
244           }
245 
246         } else if (out_ch == '\\') {
247           if (canon_mode == CanonMode::kSpecialURL ||
248               canon_mode == CanonMode::kFileURL) {
249             // Backslashes are path separators in special URLs.
250             //
251             // URL Standard: https://url.spec.whatwg.org/#path-state
252             // > 1. url is special and c is U+005C (\)
253             //
254             // Convert backslashes to forward slashes.
255             output->push_back('/');
256           } else {
257             output->push_back(out_ch);
258           }
259         } else if (out_ch == '%') {
260           // Handle escape sequences.
261           unsigned char unused_unescaped_value;
262           if (DecodeEscaped(spec, &i, end, &unused_unescaped_value)) {
263             // Valid escape sequence. We should just copy it exactly.
264             output->push_back('%');
265             output->push_back(static_cast<char>(spec[i - 1]));
266             output->push_back(static_cast<char>(spec[i]));
267           } else {
268             // Invalid escape sequence. IE7+ rejects any URLs with such
269             // sequences, while other browsers pass them through unchanged. We
270             // use the permissive behavior.
271             // TODO(brettw): Consider testing IE's strict behavior, which would
272             // allow removing the code to handle nested escapes above.
273             output->push_back('%');
274           }
275         } else if (flags & ESCAPE_BIT) {
276           // This character should be escaped.
277           AppendEscapedChar(out_ch, output);
278         }
279       } else {
280         // Nothing special about this character, just append it.
281         output->push_back(out_ch);
282       }
283     }
284   }
285   return success;
286 }
287 
288 // Perform the same logic as in DoPartialPathInternal(), but updates the
289 // publicly exposed CanonOutput structure similar to DoPath().  Returns
290 // true if successful.
291 template <typename CHAR, typename UCHAR>
DoPartialPath(const CHAR * spec,const Component & path,CanonOutput * output,Component * out_path)292 bool DoPartialPath(const CHAR* spec,
293                    const Component& path,
294                    CanonOutput* output,
295                    Component* out_path) {
296   out_path->begin = output->length();
297   bool success = DoPartialPathInternal<CHAR, UCHAR>(
298       spec, path, out_path->begin,
299       // TODO(crbug.com/40063064): Support Non-special URLs.
300       CanonMode::kSpecialURL, output);
301   out_path->len = output->length() - out_path->begin;
302   return success;
303 }
304 
305 template <typename CHAR, typename UCHAR>
DoPath(const CHAR * spec,const Component & path,CanonMode canon_mode,CanonOutput * output,Component * out_path)306 bool DoPath(const CHAR* spec,
307             const Component& path,
308             CanonMode canon_mode,
309             CanonOutput* output,
310             Component* out_path) {
311   // URL Standard:
312   // - https://url.spec.whatwg.org/#path-start-state
313   // - https://url.spec.whatwg.org/#path-state
314 
315   bool success = true;
316   out_path->begin = output->length();
317   if (path.is_nonempty()) {
318     // Write out an initial slash if the input has none. If we just parse a URL
319     // and then canonicalize it, it will of course have a slash already. This
320     // check is for the replacement and relative URL resolving cases of file
321     // URLs.
322     if (!IsSlashOrBackslash(spec[path.begin])) {
323       output->push_back('/');
324     }
325 
326     success = DoPartialPathInternal<CHAR, UCHAR>(spec, path, out_path->begin,
327                                                  canon_mode, output);
328   } else if (canon_mode == CanonMode::kSpecialURL ||
329              canon_mode == CanonMode::kFileURL) {
330     // No input, canonical path is a slash for special URLs, but it is empty for
331     // non-special URLs.
332     //
333     // Implementation note:
334     //
335     // According to the URL Standard, for non-special URLs whose parsed path is
336     // empty, such as "git://host", the state-machine finishes in the
337     // `path-start-state` without entering the `path-state`. As a result, the
338     // url's path remains an empty array. Therefore, no slash should be
339     // appended.
340     output->push_back('/');
341   }
342   out_path->len = output->length() - out_path->begin;
343   return success;
344 }
345 
346 }  // namespace
347 
CanonicalizePath(const char * spec,const Component & path,CanonMode canon_mode,CanonOutput * output,Component * out_path)348 bool CanonicalizePath(const char* spec,
349                       const Component& path,
350                       CanonMode canon_mode,
351                       CanonOutput* output,
352                       Component* out_path) {
353   return DoPath<char, unsigned char>(spec, path, canon_mode, output, out_path);
354 }
355 
CanonicalizePath(const char16_t * spec,const Component & path,CanonMode canon_mode,CanonOutput * output,Component * out_path)356 bool CanonicalizePath(const char16_t* spec,
357                       const Component& path,
358                       CanonMode canon_mode,
359                       CanonOutput* output,
360                       Component* out_path) {
361   return DoPath<char16_t, char16_t>(spec, path, canon_mode, output, out_path);
362 }
363 
CanonicalizePath(const char * spec,const Component & path,CanonOutput * output,Component * out_path)364 bool CanonicalizePath(const char* spec,
365                       const Component& path,
366                       CanonOutput* output,
367                       Component* out_path) {
368   return DoPath<char, unsigned char>(spec, path, CanonMode::kSpecialURL, output,
369                                      out_path);
370 }
371 
CanonicalizePath(const char16_t * spec,const Component & path,CanonOutput * output,Component * out_path)372 bool CanonicalizePath(const char16_t* spec,
373                       const Component& path,
374                       CanonOutput* output,
375                       Component* out_path) {
376   return DoPath<char16_t, char16_t>(spec, path, CanonMode::kSpecialURL, output,
377                                     out_path);
378 }
379 
CanonicalizePartialPath(const char * spec,const Component & path,CanonOutput * output,Component * out_path)380 bool CanonicalizePartialPath(const char* spec,
381                              const Component& path,
382                              CanonOutput* output,
383                              Component* out_path) {
384   return DoPartialPath<char, unsigned char>(spec, path, output, out_path);
385 }
386 
CanonicalizePartialPath(const char16_t * spec,const Component & path,CanonOutput * output,Component * out_path)387 bool CanonicalizePartialPath(const char16_t* spec,
388                              const Component& path,
389                              CanonOutput* output,
390                              Component* out_path) {
391   return DoPartialPath<char16_t, char16_t>(spec, path, output, out_path);
392 }
393 
CanonicalizePartialPathInternal(const char * spec,const Component & path,size_t path_begin_in_output,CanonMode canon_mode,CanonOutput * output)394 bool CanonicalizePartialPathInternal(const char* spec,
395                                      const Component& path,
396                                      size_t path_begin_in_output,
397                                      CanonMode canon_mode,
398                                      CanonOutput* output) {
399   return DoPartialPathInternal<char, unsigned char>(
400       spec, path, path_begin_in_output, canon_mode, output);
401 }
402 
CanonicalizePartialPathInternal(const char16_t * spec,const Component & path,size_t path_begin_in_output,CanonMode canon_mode,CanonOutput * output)403 bool CanonicalizePartialPathInternal(const char16_t* spec,
404                                      const Component& path,
405                                      size_t path_begin_in_output,
406                                      CanonMode canon_mode,
407                                      CanonOutput* output) {
408   return DoPartialPathInternal<char16_t, char16_t>(
409       spec, path, path_begin_in_output, canon_mode, output);
410 }
411 
412 }  // namespace url
413