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