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