xref: /aosp_15_r20/external/cronet/url/third_party/mozilla/url_parse.h (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 #ifndef URL_THIRD_PARTY_MOZILLA_URL_PARSE_H_
6 #define URL_THIRD_PARTY_MOZILLA_URL_PARSE_H_
7 
8 #include <iosfwd>
9 #include <string_view>
10 
11 #include "base/check.h"
12 #include "base/component_export.h"
13 
14 namespace url {
15 
16 // Represents the different behavior between parsing special URLs
17 // (https://url.spec.whatwg.org/#is-special) and parsing URLs which are not
18 // special.
19 //
20 // Examples:
21 // - Special URLs: "https://host/path", "ftp://host/path"
22 // - Non Special URLs: "about:blank", "data:xxx", "git://host/path"
23 enum class ParserMode { kSpecialURL, kNonSpecialURL };
24 
25 // Component ------------------------------------------------------------------
26 
27 // Represents a substring for URL parsing.
28 struct Component {
ComponentComponent29   Component() : begin(0), len(-1) {}
30 
31   // Normal constructor: takes an offset and a length.
ComponentComponent32   Component(int b, int l) : begin(b), len(l) {}
33 
endComponent34   int end() const {
35     return begin + len;
36   }
37 
38   // Returns true if this component is valid, meaning the length is given.
39   // Valid components may be empty to record the fact that they exist.
is_validComponent40   bool is_valid() const { return len >= 0; }
41 
42   // Determine if the component is empty or not. Empty means the length is
43   // zero or the component is invalid.
is_emptyComponent44   bool is_empty() const { return len <= 0; }
is_nonemptyComponent45   bool is_nonempty() const { return len > 0; }
46 
resetComponent47   void reset() {
48     begin = 0;
49     len = -1;
50   }
51 
52   bool operator==(const Component& other) const {
53     return begin == other.begin && len == other.len;
54   }
55 
56   // Returns a string_view using `source` as a backend.
57   template <typename CharT>
as_string_view_onComponent58   std::basic_string_view<CharT> as_string_view_on(const CharT* source) const {
59     DCHECK(is_valid());
60     return std::basic_string_view(&source[begin], len);
61   }
62 
63   int begin;  // Byte offset in the string of this component.
64   int len;    // Will be -1 if the component is unspecified.
65 };
66 
67 // Permit printing Components by CHECK macros.
68 COMPONENT_EXPORT(URL)
69 std::ostream& operator<<(std::ostream& os, const Component& component);
70 
71 // Helper that returns a component created with the given begin and ending
72 // points. The ending point is non-inclusive.
MakeRange(int begin,int end)73 inline Component MakeRange(int begin, int end) {
74   return Component(begin, end - begin);
75 }
76 
77 // Parsed ---------------------------------------------------------------------
78 
79 // A structure that holds the identified parts of an input URL. This structure
80 // does NOT store the URL itself. The caller will have to store the URL text
81 // and its corresponding Parsed structure separately.
82 //
83 // Typical usage would be:
84 //
85 //    Parsed parsed;
86 //    Component scheme;
87 //    if (!ExtractScheme(url, url_len, &scheme))
88 //      return I_CAN_NOT_FIND_THE_SCHEME_DUDE;
89 //
90 //    if (IsStandardScheme(url, scheme))  // Not provided by this component
91 //      ParseStandardURL(url, url_len, &parsed);
92 //    else if (IsFileURL(url, scheme))    // Not provided by this component
93 //      ParseFileURL(url, url_len, &parsed);
94 //    else
95 //      ParsePathURL(url, url_len, &parsed);
96 //
COMPONENT_EXPORT(URL)97 struct COMPONENT_EXPORT(URL) Parsed {
98   // Identifies different components.
99   enum ComponentType {
100     SCHEME,
101     USERNAME,
102     PASSWORD,
103     HOST,
104     PORT,
105     PATH,
106     QUERY,
107     REF,
108   };
109 
110   // The default constructor is sufficient for the components, but inner_parsed_
111   // requires special handling.
112   Parsed();
113   Parsed(const Parsed&);
114   Parsed& operator=(const Parsed&);
115   ~Parsed();
116 
117   // Returns the length of the URL (the end of the last component).
118   //
119   // Note that for some invalid, non-canonical URLs, this may not be the length
120   // of the string. For example "http://": the parsed structure will only
121   // contain an entry for the four-character scheme, and it doesn't know about
122   // the "://". For all other last-components, it will return the real length.
123   int Length() const;
124 
125   // Returns the number of characters before the given component if it exists,
126   // or where the component would be if it did exist. This will return the
127   // string length if the component would be appended to the end.
128   //
129   // Note that this can get a little funny for the port, query, and ref
130   // components which have a delimiter that is not counted as part of the
131   // component. The |include_delimiter| flag controls if you want this counted
132   // as part of the component or not when the component exists.
133   //
134   // This example shows the difference between the two flags for two of these
135   // delimited components that is present (the port and query) and one that
136   // isn't (the reference). The components that this flag affects are marked
137   // with a *.
138   //                 0         1         2
139   //                 012345678901234567890
140   // Example input:  http://foo:80/?query
141   //              include_delim=true,  ...=false  ("<-" indicates different)
142   //      SCHEME: 0                    0
143   //    USERNAME: 5                    5
144   //    PASSWORD: 5                    5
145   //        HOST: 7                    7
146   //       *PORT: 10                   11 <-
147   //        PATH: 13                   13
148   //      *QUERY: 14                   15 <-
149   //        *REF: 20                   20
150   //
151   int CountCharactersBefore(ComponentType type, bool include_delimiter) const;
152 
153   // Scheme without the colon: "http://foo"/ would have a scheme of "http".
154   // The length will be -1 if no scheme is specified ("foo.com"), or 0 if there
155   // is a colon but no scheme (":foo"). Note that the scheme is not guaranteed
156   // to start at the beginning of the string if there are preceeding whitespace
157   // or control characters.
158   Component scheme;
159 
160   // Username. Specified in URLs with an @ sign before the host. See |password|
161   Component username;
162 
163   // Password. The length will be -1 if unspecified, 0 if specified but empty.
164   // Not all URLs with a username have a password, as in "http://me@host/".
165   // The password is separated form the username with a colon, as in
166   // "http://me:secret@host/"
167   Component password;
168 
169   // Host name.
170   //
171   // For non-special URLs, the length will be -1 unless "//" (two consecutive
172   // slashes) follows the scheme part. This corresponds to "url's host is null"
173   // in URL Standard (https://url.spec.whatwg.org/#concept-url-host).
174   //
175   // Examples:
176   // - "git:/path" => The length is -1.
177   //
178   // The length can be 0 for non-special URLs when a host is the empty string,
179   // but not null.
180   //
181   // Examples:
182   // - "git:///path" => The length is 0.
183   Component host;
184 
185   // Port number.
186   Component port;
187 
188   // Path, this is everything following the host name, stopping at the query of
189   // ref delimiter (if any). Length will be -1 if unspecified. This includes
190   // the preceeding slash, so the path on http://www.google.com/asdf" is
191   // "/asdf". As a result, it is impossible to have a 0 length path, it will
192   // be -1 in cases like "http://host?foo".
193   // Note that we treat backslashes the same as slashes.
194   //
195   // For non-special URLs which have an empty path, e.g. "git://host", or an
196   // empty opaque path, e.g. "git:", path will be -1. See
197   // https://crbug.com/1416006.
198   Component path;
199 
200   // Stuff between the ? and the # after the path. This does not include the
201   // preceeding ? character. Length will be -1 if unspecified, 0 if there is
202   // a question mark but no query string.
203   Component query;
204 
205   // Indicated by a #, this is everything following the hash sign (not
206   // including it). If there are multiple hash signs, we'll use the last one.
207   // Length will be -1 if there is no hash sign, or 0 if there is one but
208   // nothing follows it.
209   Component ref;
210 
211   // The URL spec from the character after the scheme: until the end of the
212   // URL, regardless of the scheme. This is mostly useful for 'opaque' non-
213   // hierarchical schemes like data: and javascript: as a convient way to get
214   // the string with the scheme stripped off.
215   Component GetContent() const;
216 
217   // True if the URL's source contained a raw `<` character, and whitespace was
218   // removed from the URL during parsing
219   //
220   // TODO(mkwst): Link this to something in a spec if
221   // https://github.com/whatwg/url/pull/284 lands.
222   bool potentially_dangling_markup = false;
223 
224   // True if the URL has an opaque path. See
225   // https://url.spec.whatwg.org/#url-opaque-path.
226   // Only non-special URLs can have an opaque path.
227   //
228   // Examples: "data:xxx", "custom:opaque path"
229   //
230   // Note: Non-special URLs like "data:/xxx" and "custom://host/path" don't have
231   // an opaque path because '/' (slash) character follows "scheme:" part.
232   bool has_opaque_path = false;
233 
234   // This is used for nested URL types, currently only filesystem.  If you
235   // parse a filesystem URL, the resulting Parsed will have a nested
236   // inner_parsed_ to hold the parsed inner URL's component information.
237   // For all other url types [including the inner URL], it will be NULL.
238   Parsed* inner_parsed() const {
239     return inner_parsed_;
240   }
241 
242   void set_inner_parsed(const Parsed& inner_parsed) {
243     if (!inner_parsed_)
244       inner_parsed_ = new Parsed(inner_parsed);
245     else
246       *inner_parsed_ = inner_parsed;
247   }
248 
249   void clear_inner_parsed() {
250     if (inner_parsed_) {
251       delete inner_parsed_;
252       inner_parsed_ = nullptr;
253     }
254   }
255 
256  private:
257   // This object is owned and managed by this struct.
258   Parsed* inner_parsed_ = nullptr;
259 };
260 
261 // Permits printing `Parsed` in gtest.
262 COMPONENT_EXPORT(URL)
263 std::ostream& operator<<(std::ostream& os, const Parsed& parsed);
264 
265 // Initialization functions ---------------------------------------------------
266 //
267 // These functions parse the given URL, filling in all of the structure's
268 // components. These functions can not fail, they will always do their best
269 // at interpreting the input given.
270 //
271 // The string length of the URL MUST be specified, we do not check for NULLs
272 // at any point in the process, and will actually handle embedded NULLs.
273 //
274 // IMPORTANT: These functions do NOT hang on to the given pointer or copy it
275 // in any way. See the comment above the struct.
276 //
277 // The 8-bit versions require UTF-8 encoding.
278 
279 // StandardURL is for when the scheme is known, such as "https:", "ftp:".
280 // This is defined as "special" in URL Standard.
281 // See https://url.spec.whatwg.org/#is-special
282 COMPONENT_EXPORT(URL)
283 void ParseStandardURL(const char* url, int url_len, Parsed* parsed);
284 COMPONENT_EXPORT(URL)
285 void ParseStandardURL(const char16_t* url, int url_len, Parsed* parsed);
286 
287 // Non-special URL is for when the scheme is not special, such as "about:",
288 // "javascript:". See https://url.spec.whatwg.org/#is-not-special
289 COMPONENT_EXPORT(URL)
290 void ParseNonSpecialURL(const char* url, int url_len, Parsed* parsed);
291 COMPONENT_EXPORT(URL)
292 void ParseNonSpecialURL(const char16_t* url, int url_len, Parsed* parsed);
293 
294 // PathURL is for when the scheme is known not to have an authority (host)
295 // section but that aren't file URLs either. The scheme is parsed, and
296 // everything after the scheme is considered as the path. This is used for
297 // things like "about:" and "javascript:"
298 //
299 // Historically, this is used to parse non-special URLs, but this should be
300 // removed after StandardCompliantNonSpecialSchemeURLParsing is enabled by
301 // default.
302 COMPONENT_EXPORT(URL)
303 void ParsePathURL(const char* url,
304                   int url_len,
305                   bool trim_path_end,
306                   Parsed* parsed);
307 COMPONENT_EXPORT(URL)
308 void ParsePathURL(const char16_t* url,
309                   int url_len,
310                   bool trim_path_end,
311                   Parsed* parsed);
312 
313 // FileURL is for file URLs. There are some special rules for interpreting
314 // these.
315 COMPONENT_EXPORT(URL)
316 void ParseFileURL(const char* url, int url_len, Parsed* parsed);
317 COMPONENT_EXPORT(URL)
318 void ParseFileURL(const char16_t* url, int url_len, Parsed* parsed);
319 
320 // Filesystem URLs are structured differently than other URLs.
321 COMPONENT_EXPORT(URL) Parsed ParseFileSystemURL(std::string_view url);
322 COMPONENT_EXPORT(URL) Parsed ParseFileSystemURL(std::u16string_view url);
323 
324 // MailtoURL is for mailto: urls. They are made up scheme,path,query
325 COMPONENT_EXPORT(URL) Parsed ParseMailtoURL(std::string_view url);
326 COMPONENT_EXPORT(URL) Parsed ParseMailtoURL(std::u16string_view url);
327 
328 // Helper functions -----------------------------------------------------------
329 
330 // Locates the scheme according to the URL  parser's rules. This function is
331 // designed so the caller can find the scheme and call the correct Init*
332 // function according to their known scheme types.
333 //
334 // It also does not perform any validation on the scheme.
335 //
336 // This function will return true if the scheme is found and will put the
337 // scheme's range into *scheme. False means no scheme could be found. Note
338 // that a URL beginning with a colon has a scheme, but it is empty, so this
339 // function will return true but *scheme will = (0,0).
340 //
341 // The scheme is found by skipping spaces and control characters at the
342 // beginning, and taking everything from there to the first colon to be the
343 // scheme. The character at scheme.end() will be the colon (we may enhance
344 // this to handle full width colons or something, so don't count on the
345 // actual character value). The character at scheme.end()+1 will be the
346 // beginning of the rest of the URL, be it the authority or the path (or the
347 // end of the string).
348 //
349 // The 8-bit version requires UTF-8 encoding.
350 COMPONENT_EXPORT(URL)
351 bool ExtractScheme(std::string_view url, Component* scheme);
352 COMPONENT_EXPORT(URL)
353 bool ExtractScheme(std::u16string_view url, Component* scheme);
354 // Deprecated (crbug.com/325408566): Prefer using the overloads above.
355 COMPONENT_EXPORT(URL)
356 bool ExtractScheme(const char* url, int url_len, Component* scheme);
357 COMPONENT_EXPORT(URL)
358 bool ExtractScheme(const char16_t* url, int url_len, Component* scheme);
359 
360 // Returns true if ch is a character that terminates the authority segment
361 // of a URL.
362 COMPONENT_EXPORT(URL)
363 bool IsAuthorityTerminator(char16_t ch, ParserMode parser_mode);
364 
365 // Deprecated. Please pass `ParserMode` explicitly.
366 //
367 // These functions are also used in net/third_party code. So removing these
368 // functions requires several steps.
369 COMPONENT_EXPORT(URL)
370 void ParseAuthority(const char* spec,
371                     const Component& auth,
372                     Component* username,
373                     Component* password,
374                     Component* hostname,
375                     Component* port_num);
376 COMPONENT_EXPORT(URL)
377 void ParseAuthority(const char16_t* spec,
378                     const Component& auth,
379                     Component* username,
380                     Component* password,
381                     Component* hostname,
382                     Component* port_num);
383 
384 // Does a best effort parse of input `spec`, in range `auth`. If a particular
385 // component is not found, it will be set to invalid. `ParserMode` is used to
386 // determine the appropriate authority terminator. See `IsAuthorityTerminator`
387 // for details.
388 COMPONENT_EXPORT(URL)
389 void ParseAuthority(const char* spec,
390                     const Component& auth,
391                     ParserMode parser_mode,
392                     Component* username,
393                     Component* password,
394                     Component* hostname,
395                     Component* port_num);
396 COMPONENT_EXPORT(URL)
397 void ParseAuthority(const char16_t* spec,
398                     const Component& auth,
399                     ParserMode parser_mode,
400                     Component* username,
401                     Component* password,
402                     Component* hostname,
403                     Component* port_num);
404 
405 // Computes the integer port value from the given port component. The port
406 // component should have been identified by one of the init functions on
407 // |Parsed| for the given input url.
408 //
409 // The return value will be a positive integer between 0 and 64K, or one of
410 // the two special values below.
411 enum SpecialPort { PORT_UNSPECIFIED = -1, PORT_INVALID = -2 };
412 COMPONENT_EXPORT(URL) int ParsePort(const char* url, const Component& port);
413 COMPONENT_EXPORT(URL)
414 int ParsePort(const char16_t* url, const Component& port);
415 
416 // Extracts the range of the file name in the given url. The path must
417 // already have been computed by the parse function, and the matching URL
418 // and extracted path are provided to this function. The filename is
419 // defined as being everything from the last slash/backslash of the path
420 // to the end of the path.
421 //
422 // The file name will be empty if the path is empty or there is nothing
423 // following the last slash.
424 //
425 // The 8-bit version requires UTF-8 encoding.
426 COMPONENT_EXPORT(URL)
427 void ExtractFileName(const char* url,
428                      const Component& path,
429                      Component* file_name);
430 COMPONENT_EXPORT(URL)
431 void ExtractFileName(const char16_t* url,
432                      const Component& path,
433                      Component* file_name);
434 
435 // Extract the first key/value from the range defined by |*query|. Updates
436 // |*query| to start at the end of the extracted key/value pair. This is
437 // designed for use in a loop: you can keep calling it with the same query
438 // object and it will iterate over all items in the query.
439 //
440 // Some key/value pairs may have the key, the value, or both be empty (for
441 // example, the query string "?&"). These will be returned. Note that an empty
442 // last parameter "foo.com?" or foo.com?a&" will not be returned, this case
443 // is the same as "done."
444 //
445 // The initial query component should not include the '?' (this is the default
446 // for parsed URLs).
447 //
448 // If no key/value are found |*key| and |*value| will be unchanged and it will
449 // return false.
450 
451 COMPONENT_EXPORT(URL)
452 bool ExtractQueryKeyValue(std::string_view url,
453                           Component* query,
454                           Component* key,
455                           Component* value);
456 COMPONENT_EXPORT(URL)
457 bool ExtractQueryKeyValue(std::u16string_view url,
458                           Component* query,
459                           Component* key,
460                           Component* value);
461 
462 }  // namespace url
463 
464 #endif  // URL_THIRD_PARTY_MOZILLA_URL_PARSE_H_
465