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_URL_CANON_H_
6 #define URL_URL_CANON_H_
7
8 #include <stdlib.h>
9 #include <string.h>
10
11 #include <string_view>
12
13 #include "base/check_op.h"
14 #include "base/component_export.h"
15 #include "base/export_template.h"
16 #include "base/memory/raw_ptr_exclusion.h"
17 #include "base/numerics/clamped_math.h"
18 #include "url/third_party/mozilla/url_parse.h"
19
20 namespace url {
21
22 // Represents the different behavior between canonicalizing special URLs
23 // (https://url.spec.whatwg.org/#is-special) and canonicalizing URLs which are
24 // not special.
25 //
26 // Examples:
27 // - Special URLs: "https://host/path", "ftp://host/path"
28 // - Non Special URLs: "about:blank", "data:xxx", "git://host/path"
29 enum class CanonMode { kSpecialURL, kNonSpecialURL };
30
31 // Canonicalizer output
32 // -------------------------------------------------------
33
34 // Base class for the canonicalizer output, this maintains a buffer and
35 // supports simple resizing and append operations on it.
36 //
37 // It is VERY IMPORTANT that no virtual function calls be made on the common
38 // code path. We only have two virtual function calls, the destructor and a
39 // resize function that is called when the existing buffer is not big enough.
40 // The derived class is then in charge of setting up our buffer which we will
41 // manage.
42 template <typename T>
43 class CanonOutputT {
44 public:
45 CanonOutputT() = default;
46 virtual ~CanonOutputT() = default;
47
48 // Implemented to resize the buffer. This function should update the buffer
49 // pointer to point to the new buffer, and any old data up to |cur_len_| in
50 // the buffer must be copied over.
51 //
52 // The new size |sz| must be larger than buffer_len_.
53 virtual void Resize(size_t sz) = 0;
54
55 // Accessor for returning a character at a given position. The input offset
56 // must be in the valid range.
at(size_t offset)57 inline T at(size_t offset) const { return buffer_[offset]; }
58
59 // Sets the character at the given position. The given position MUST be less
60 // than the length().
set(size_t offset,T ch)61 inline void set(size_t offset, T ch) { buffer_[offset] = ch; }
62
63 // Returns the number of characters currently in the buffer.
length()64 inline size_t length() const { return cur_len_; }
65
66 // Returns the current capacity of the buffer. The length() is the number of
67 // characters that have been declared to be written, but the capacity() is
68 // the number that can be written without reallocation. If the caller must
69 // write many characters at once, it can make sure there is enough capacity,
70 // write the data, then use set_size() to declare the new length().
capacity()71 size_t capacity() const { return buffer_len_; }
72
73 // Returns the contents of the buffer as a string_view.
view()74 std::basic_string_view<T> view() const {
75 return std::basic_string_view<T>(data(), length());
76 }
77
78 // Called by the user of this class to get the output. The output will NOT
79 // be NULL-terminated. Call length() to get the
80 // length.
data()81 const T* data() const { return buffer_; }
data()82 T* data() { return buffer_; }
83
84 // Shortens the URL to the new length. Used for "backing up" when processing
85 // relative paths. This can also be used if an external function writes a lot
86 // of data to the buffer (when using the "Raw" version below) beyond the end,
87 // to declare the new length.
88 //
89 // This MUST NOT be used to expand the size of the buffer beyond capacity().
set_length(size_t new_len)90 void set_length(size_t new_len) { cur_len_ = new_len; }
91
92 // This is the most performance critical function, since it is called for
93 // every character.
push_back(T ch)94 void push_back(T ch) {
95 // In VC2005, putting this common case first speeds up execution
96 // dramatically because this branch is predicted as taken.
97 if (cur_len_ < buffer_len_) {
98 buffer_[cur_len_] = ch;
99 cur_len_++;
100 return;
101 }
102
103 // Grow the buffer to hold at least one more item. Hopefully we won't have
104 // to do this very often.
105 if (!Grow(1))
106 return;
107
108 // Actually do the insertion.
109 buffer_[cur_len_] = ch;
110 cur_len_++;
111 }
112
113 // Appends the given string to the output.
Append(const T * str,size_t str_len)114 void Append(const T* str, size_t str_len) {
115 if (str_len > buffer_len_ - cur_len_) {
116 if (!Grow(str_len - (buffer_len_ - cur_len_)))
117 return;
118 }
119 memcpy(buffer_ + cur_len_, str, str_len * sizeof(T));
120 cur_len_ += str_len;
121 }
122
Append(std::basic_string_view<T> str)123 void Append(std::basic_string_view<T> str) { Append(str.data(), str.size()); }
124
ReserveSizeIfNeeded(size_t estimated_size)125 void ReserveSizeIfNeeded(size_t estimated_size) {
126 // Reserve a bit extra to account for escaped chars.
127 if (estimated_size > buffer_len_)
128 Resize((base::ClampedNumeric<size_t>(estimated_size) + 8).RawValue());
129 }
130
131 // Insert `str` at `pos`. Used for post-processing non-special URL's pathname.
132 // Since this takes O(N), don't use this unless there is a strong reason.
Insert(size_t pos,std::basic_string_view<T> str)133 void Insert(size_t pos, std::basic_string_view<T> str) {
134 DCHECK_LE(pos, cur_len_);
135 std::basic_string<T> copy(view().substr(pos));
136 set_length(pos);
137 Append(str);
138 Append(copy);
139 }
140
141 protected:
142 // Grows the given buffer so that it can fit at least |min_additional|
143 // characters. Returns true if the buffer could be resized, false on OOM.
Grow(size_t min_additional)144 bool Grow(size_t min_additional) {
145 static const size_t kMinBufferLen = 16;
146 size_t new_len = (buffer_len_ == 0) ? kMinBufferLen : buffer_len_;
147 do {
148 if (new_len >= (1 << 30)) // Prevent overflow below.
149 return false;
150 new_len *= 2;
151 } while (new_len < buffer_len_ + min_additional);
152 Resize(new_len);
153 return true;
154 }
155
156 // `buffer_` is not a raw_ptr<...> for performance reasons (based on analysis
157 // of sampling profiler data).
158 RAW_PTR_EXCLUSION T* buffer_ = nullptr;
159 size_t buffer_len_ = 0;
160
161 // Used characters in the buffer.
162 size_t cur_len_ = 0;
163 };
164
165 // Simple implementation of the CanonOutput using new[]. This class
166 // also supports a static buffer so if it is allocated on the stack, most
167 // URLs can be canonicalized with no heap allocations.
168 template <typename T, int fixed_capacity = 1024>
169 class RawCanonOutputT : public CanonOutputT<T> {
170 public:
RawCanonOutputT()171 RawCanonOutputT() : CanonOutputT<T>() {
172 this->buffer_ = fixed_buffer_;
173 this->buffer_len_ = fixed_capacity;
174 }
~RawCanonOutputT()175 ~RawCanonOutputT() override {
176 if (this->buffer_ != fixed_buffer_)
177 delete[] this->buffer_;
178 }
179
Resize(size_t sz)180 void Resize(size_t sz) override {
181 T* new_buf = new T[sz];
182 memcpy(new_buf, this->buffer_,
183 sizeof(T) * (this->cur_len_ < sz ? this->cur_len_ : sz));
184 if (this->buffer_ != fixed_buffer_)
185 delete[] this->buffer_;
186 this->buffer_ = new_buf;
187 this->buffer_len_ = sz;
188 }
189
190 protected:
191 T fixed_buffer_[fixed_capacity];
192 };
193
194 // Explicitely instantiate commonly used instatiations.
195 extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL))
196 CanonOutputT<char>;
197 extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL))
198 CanonOutputT<char16_t>;
199
200 // Normally, all canonicalization output is in narrow characters. We support
201 // the templates so it can also be used internally if a wide buffer is
202 // required.
203 typedef CanonOutputT<char> CanonOutput;
204 typedef CanonOutputT<char16_t> CanonOutputW;
205
206 template <int fixed_capacity>
207 class RawCanonOutput : public RawCanonOutputT<char, fixed_capacity> {};
208 template <int fixed_capacity>
209 class RawCanonOutputW : public RawCanonOutputT<char16_t, fixed_capacity> {};
210
211 // Character set converter ----------------------------------------------------
212 //
213 // Converts query strings into a custom encoding. The embedder can supply an
214 // implementation of this class to interface with their own character set
215 // conversion libraries.
216 //
217 // Embedders will want to see the unit test for the ICU version.
218
COMPONENT_EXPORT(URL)219 class COMPONENT_EXPORT(URL) CharsetConverter {
220 public:
221 CharsetConverter() {}
222 virtual ~CharsetConverter() {}
223
224 // Converts the given input string from UTF-16 to whatever output format the
225 // converter supports. This is used only for the query encoding conversion,
226 // which does not fail. Instead, the converter should insert "invalid
227 // character" characters in the output for invalid sequences, and do the
228 // best it can.
229 //
230 // If the input contains a character not representable in the output
231 // character set, the converter should append the HTML entity sequence in
232 // decimal, (such as "你") with escaping of the ampersand, number
233 // sign, and semicolon (in the previous example it would be
234 // "%26%2320320%3B"). This rule is based on what IE does in this situation.
235 virtual void ConvertFromUTF16(const char16_t* input,
236 int input_len,
237 CanonOutput* output) = 0;
238 };
239
240 // Schemes --------------------------------------------------------------------
241
242 // Types of a scheme representing the requirements on the data represented by
243 // the authority component of a URL with the scheme.
244 enum SchemeType {
245 // The authority component of a URL with the scheme has the form
246 // "username:password@host:port". The username and password entries are
247 // optional; the host may not be empty. The default value of the port can be
248 // omitted in serialization. This type occurs with network schemes like http,
249 // https, and ftp.
250 SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION,
251 // The authority component of a URL with the scheme has the form "host:port",
252 // and does not include username or password. The default value of the port
253 // can be omitted in serialization. Used by inner URLs of filesystem URLs of
254 // origins with network hosts, from which the username and password are
255 // stripped.
256 SCHEME_WITH_HOST_AND_PORT,
257 // The authority component of an URL with the scheme has the form "host", and
258 // does not include port, username, or password. Used when the hosts are not
259 // network addresses; for example, schemes used internally by the browser.
260 SCHEME_WITH_HOST,
261 // A URL with the scheme doesn't have the authority component.
262 SCHEME_WITHOUT_AUTHORITY,
263 };
264
265 // Whitespace -----------------------------------------------------------------
266
267 // Searches for whitespace that should be removed from the middle of URLs, and
268 // removes it. Removed whitespace are tabs and newlines, but NOT spaces. Spaces
269 // are preserved, which is what most browsers do. A pointer to the output will
270 // be returned, and the length of that output will be in |output_len|.
271 //
272 // This should be called before parsing if whitespace removal is desired (which
273 // it normally is when you are canonicalizing).
274 //
275 // If no whitespace is removed, this function will not use the buffer and will
276 // return a pointer to the input, to avoid the extra copy. If modification is
277 // required, the given |buffer| will be used and the returned pointer will
278 // point to the beginning of the buffer.
279 //
280 // Therefore, callers should not use the buffer, since it may actually be empty,
281 // use the computed pointer and |*output_len| instead.
282 //
283 // If |input| contained both removable whitespace and a raw `<` character,
284 // |potentially_dangling_markup| will be set to `true`. Otherwise, it will be
285 // left untouched.
286 COMPONENT_EXPORT(URL)
287 const char* RemoveURLWhitespace(const char* input,
288 int input_len,
289 CanonOutputT<char>* buffer,
290 int* output_len,
291 bool* potentially_dangling_markup);
292 COMPONENT_EXPORT(URL)
293 const char16_t* RemoveURLWhitespace(const char16_t* input,
294 int input_len,
295 CanonOutputT<char16_t>* buffer,
296 int* output_len,
297 bool* potentially_dangling_markup);
298
299 // IDN ------------------------------------------------------------------------
300
301 // Converts the Unicode input representing a hostname to ASCII using IDN rules.
302 // The output must fall in the ASCII range, but will be encoded in UTF-16.
303 //
304 // On success, the output will be filled with the ASCII host name and it will
305 // return true. Unlike most other canonicalization functions, this assumes that
306 // the output is empty. The beginning of the host will be at offset 0, and
307 // the length of the output will be set to the length of the new host name.
308 //
309 // On error, returns false. The output in this case is undefined.
310 COMPONENT_EXPORT(URL)
311 bool IDNToASCII(std::u16string_view src, CanonOutputW* output);
312
313 // Piece-by-piece canonicalizers ----------------------------------------------
314 //
315 // These individual canonicalizers append the canonicalized versions of the
316 // corresponding URL component to the given CanonOutput. The spec and the
317 // previously-identified range of that component are the input. The range of
318 // the canonicalized component will be written to the output component.
319 //
320 // These functions all append to the output so they can be chained. Make sure
321 // the output is empty when you start.
322 //
323 // These functions returns boolean values indicating success. On failure, they
324 // will attempt to write something reasonable to the output so that, if
325 // displayed to the user, they will recognise it as something that's messed up.
326 // Nothing more should ever be done with these invalid URLs, however.
327
328 // Scheme: Appends the scheme and colon to the URL. The output component will
329 // indicate the range of characters up to but not including the colon.
330 //
331 // Canonical URLs always have a scheme. If the scheme is not present in the
332 // input, this will just write the colon to indicate an empty scheme. Does not
333 // append slashes which will be needed before any authority components for most
334 // URLs.
335 //
336 // The 8-bit version requires UTF-8 encoding.
337 COMPONENT_EXPORT(URL)
338 bool CanonicalizeScheme(const char* spec,
339 const Component& scheme,
340 CanonOutput* output,
341 Component* out_scheme);
342 COMPONENT_EXPORT(URL)
343 bool CanonicalizeScheme(const char16_t* spec,
344 const Component& scheme,
345 CanonOutput* output,
346 Component* out_scheme);
347
348 // User info: username/password. If present, this will add the delimiters so
349 // the output will be "<username>:<password>@" or "<username>@". Empty
350 // username/password pairs, or empty passwords, will get converted to
351 // nonexistent in the canonical version.
352 //
353 // The components for the username and password refer to ranges in the
354 // respective source strings. Usually, these will be the same string, which
355 // is legal as long as the two components don't overlap.
356 //
357 // The 8-bit version requires UTF-8 encoding.
358 COMPONENT_EXPORT(URL)
359 bool CanonicalizeUserInfo(const char* username_source,
360 const Component& username,
361 const char* password_source,
362 const Component& password,
363 CanonOutput* output,
364 Component* out_username,
365 Component* out_password);
366 COMPONENT_EXPORT(URL)
367 bool CanonicalizeUserInfo(const char16_t* username_source,
368 const Component& username,
369 const char16_t* password_source,
370 const Component& password,
371 CanonOutput* output,
372 Component* out_username,
373 Component* out_password);
374
375 // This structure holds detailed state exported from the IP/Host canonicalizers.
376 // Additional fields may be added as callers require them.
377 struct CanonHostInfo {
CanonHostInfoCanonHostInfo378 CanonHostInfo() : family(NEUTRAL), num_ipv4_components(0), out_host() {}
379
380 // Convenience function to test if family is an IP address.
IsIPAddressCanonHostInfo381 bool IsIPAddress() const { return family == IPV4 || family == IPV6; }
382
383 // This field summarizes how the input was classified by the canonicalizer.
384 enum Family {
385 NEUTRAL, // - Doesn't resemble an IP address. As far as the IP
386 // canonicalizer is concerned, it should be treated as a
387 // hostname.
388 BROKEN, // - Almost an IP, but was not canonicalized. This could be an
389 // IPv4 address where truncation occurred, or something
390 // containing the special characters :[] which did not parse
391 // as an IPv6 address. Never attempt to connect to this
392 // address, because it might actually succeed!
393 IPV4, // - Successfully canonicalized as an IPv4 address.
394 IPV6, // - Successfully canonicalized as an IPv6 address.
395 };
396 Family family;
397
398 // If |family| is IPV4, then this is the number of nonempty dot-separated
399 // components in the input text, from 1 to 4. If |family| is not IPV4,
400 // this value is undefined.
401 int num_ipv4_components;
402
403 // Location of host within the canonicalized output.
404 // CanonicalizeIPAddress() only sets this field if |family| is IPV4 or IPV6.
405 // CanonicalizeHostVerbose() always sets it.
406 Component out_host;
407
408 // |address| contains the parsed IP Address (if any) in its first
409 // AddressLength() bytes, in network order. If IsIPAddress() is false
410 // AddressLength() will return zero and the content of |address| is undefined.
411 unsigned char address[16];
412
413 // Convenience function to calculate the length of an IP address corresponding
414 // to the current IP version in |family|, if any. For use with |address|.
AddressLengthCanonHostInfo415 int AddressLength() const {
416 return family == IPV4 ? 4 : (family == IPV6 ? 16 : 0);
417 }
418 };
419
420 // Deprecated. Please call either CanonicalizeSpecialHost or
421 // CanonicalizeNonSpecialHost.
422 //
423 // TODO(crbug.com/1416006): Check the callers of these functions.
424 COMPONENT_EXPORT(URL)
425 bool CanonicalizeHost(const char* spec,
426 const Component& host,
427 CanonOutput* output,
428 Component* out_host);
429 COMPONENT_EXPORT(URL)
430 bool CanonicalizeHost(const char16_t* spec,
431 const Component& host,
432 CanonOutput* output,
433 Component* out_host);
434
435 // Host in special URLs.
436 //
437 // The 8-bit version requires UTF-8 encoding. Use this version when you only
438 // need to know whether canonicalization succeeded.
439 COMPONENT_EXPORT(URL)
440 bool CanonicalizeSpecialHost(const char* spec,
441 const Component& host,
442 CanonOutput& output,
443 Component& out_host);
444 COMPONENT_EXPORT(URL)
445 bool CanonicalizeSpecialHost(const char16_t* spec,
446 const Component& host,
447 CanonOutput& output,
448 Component& out_host);
449
450 // Deprecated. Please call either CanonicalizeSpecialHostVerbose or
451 // CanonicalizeNonSpecialHostVerbose.
452 //
453 // TODO(crbug.com/1416006): Check the callers of these functions.
454 COMPONENT_EXPORT(URL)
455 void CanonicalizeHostVerbose(const char* spec,
456 const Component& host,
457 CanonOutput* output,
458 CanonHostInfo* host_info);
459 COMPONENT_EXPORT(URL)
460 void CanonicalizeHostVerbose(const char16_t* spec,
461 const Component& host,
462 CanonOutput* output,
463 CanonHostInfo* host_info);
464
465 // Extended version of CanonicalizeSpecialHost, which returns additional
466 // information. Use this when you need to know whether the hostname was an IP
467 // address. A successful return is indicated by host_info->family != BROKEN. See
468 // the definition of CanonHostInfo above for details.
469 COMPONENT_EXPORT(URL)
470 void CanonicalizeSpecialHostVerbose(const char* spec,
471 const Component& host,
472 CanonOutput& output,
473 CanonHostInfo& host_info);
474 COMPONENT_EXPORT(URL)
475 void CanonicalizeSpecialHostVerbose(const char16_t* spec,
476 const Component& host,
477 CanonOutput& output,
478 CanonHostInfo& host_info);
479
480 // Canonicalizes a string according to the host canonicalization rules. Unlike
481 // CanonicalizeHost, this will not check for IP addresses which can change the
482 // meaning (and canonicalization) of the components. This means it is possible
483 // to call this for sub-components of a host name without corruption.
484 //
485 // As an example, "01.02.03.04.com" is a canonical hostname. If you called
486 // CanonicalizeHost on the substring "01.02.03.04" it will get "fixed" to
487 // "1.2.3.4" which will produce an invalid host name when reassembled. This
488 // can happen more than one might think because all numbers by themselves are
489 // considered IP addresses; so "5" canonicalizes to "0.0.0.5".
490 //
491 // Be careful: Because Punycode works on each dot-separated substring as a
492 // unit, you should only pass this function substrings that represent complete
493 // dot-separated subcomponents of the original host. Even if you have ASCII
494 // input, percent-escaped characters will have different meanings if split in
495 // the middle.
496 //
497 // Returns true if the host was valid. This function will treat a 0-length
498 // host as valid (because it's designed to be used for substrings) while the
499 // full version above will mark empty hosts as broken.
500 COMPONENT_EXPORT(URL)
501 bool CanonicalizeHostSubstring(const char* spec,
502 const Component& host,
503 CanonOutput* output);
504 COMPONENT_EXPORT(URL)
505 bool CanonicalizeHostSubstring(const char16_t* spec,
506 const Component& host,
507 CanonOutput* output);
508
509 // Host in non-special URLs.
510 COMPONENT_EXPORT(URL)
511 bool CanonicalizeNonSpecialHost(const char* spec,
512 const Component& host,
513 CanonOutput& output,
514 Component& out_host);
515 COMPONENT_EXPORT(URL)
516 bool CanonicalizeNonSpecialHost(const char16_t* spec,
517 const Component& host,
518 CanonOutput& output,
519 Component& out_host);
520
521 // Extended version of CanonicalizeNonSpecialHost, which returns additional
522 // information. See CanonicalizeSpecialHost for details.
523 COMPONENT_EXPORT(URL)
524 void CanonicalizeNonSpecialHostVerbose(const char* spec,
525 const Component& host,
526 CanonOutput& output,
527 CanonHostInfo& host_info);
528 COMPONENT_EXPORT(URL)
529 void CanonicalizeNonSpecialHostVerbose(const char16_t* spec,
530 const Component& host,
531 CanonOutput& output,
532 CanonHostInfo& host_info);
533
534 // IP addresses.
535 //
536 // Tries to interpret the given host name as an IPv4 or IPv6 address. If it is
537 // an IP address, it will canonicalize it as such, appending it to |output|.
538 // Additional status information is returned via the |*host_info| parameter.
539 // See the definition of CanonHostInfo above for details.
540 //
541 // This is called AUTOMATICALLY from the host canonicalizer, which ensures that
542 // the input is unescaped and name-prepped, etc. It should not normally be
543 // necessary or wise to call this directly.
544 COMPONENT_EXPORT(URL)
545 void CanonicalizeIPAddress(const char* spec,
546 const Component& host,
547 CanonOutput* output,
548 CanonHostInfo* host_info);
549 COMPONENT_EXPORT(URL)
550 void CanonicalizeIPAddress(const char16_t* spec,
551 const Component& host,
552 CanonOutput* output,
553 CanonHostInfo* host_info);
554
555 // Similar to CanonicalizeIPAddress, but supports only IPv6 address.
556 COMPONENT_EXPORT(URL)
557 void CanonicalizeIPv6Address(const char* spec,
558 const Component& host,
559 CanonOutput& output,
560 CanonHostInfo& host_info);
561
562 COMPONENT_EXPORT(URL)
563 void CanonicalizeIPv6Address(const char16_t* spec,
564 const Component& host,
565 CanonOutput& output,
566 CanonHostInfo& host_info);
567
568 // Port: this function will add the colon for the port if a port is present.
569 // The caller can pass PORT_UNSPECIFIED as the
570 // default_port_for_scheme argument if there is no default port.
571 //
572 // The 8-bit version requires UTF-8 encoding.
573 COMPONENT_EXPORT(URL)
574 bool CanonicalizePort(const char* spec,
575 const Component& port,
576 int default_port_for_scheme,
577 CanonOutput* output,
578 Component* out_port);
579 COMPONENT_EXPORT(URL)
580 bool CanonicalizePort(const char16_t* spec,
581 const Component& port,
582 int default_port_for_scheme,
583 CanonOutput* output,
584 Component* out_port);
585
586 // Returns the default port for the given canonical scheme, or PORT_UNSPECIFIED
587 // if the scheme is unknown. Based on https://url.spec.whatwg.org/#default-port
588 COMPONENT_EXPORT(URL)
589 int DefaultPortForScheme(const char* scheme, int scheme_len);
590
591 // Path. If the input does not begin in a slash (including if the input is
592 // empty), we'll prepend a slash to the path to make it canonical.
593 //
594 // The 8-bit version assumes UTF-8 encoding, but does not verify the validity
595 // of the UTF-8 (i.e., you can have invalid UTF-8 sequences, invalid
596 // characters, etc.). Normally, URLs will come in as UTF-16, so this isn't
597 // an issue. Somebody giving us an 8-bit path is responsible for generating
598 // the path that the server expects (we'll escape high-bit characters), so
599 // if something is invalid, it's their problem.
600 COMPONENT_EXPORT(URL)
601 bool CanonicalizePath(const char* spec,
602 const Component& path,
603 CanonMode canon_mode,
604 CanonOutput* output,
605 Component* out_path);
606 COMPONENT_EXPORT(URL)
607 bool CanonicalizePath(const char16_t* spec,
608 const Component& path,
609 CanonMode canon_mode,
610 CanonOutput* output,
611 Component* out_path);
612
613 // Deprecated. Please pass CanonMode explicitly.
614 //
615 // These functions are also used in net/third_party code. So removing these
616 // functions requires several steps.
617 COMPONENT_EXPORT(URL)
618 bool CanonicalizePath(const char* spec,
619 const Component& path,
620 CanonOutput* output,
621 Component* out_path);
622 COMPONENT_EXPORT(URL)
623 bool CanonicalizePath(const char16_t* spec,
624 const Component& path,
625 CanonOutput* output,
626 Component* out_path);
627
628 // Like CanonicalizePath(), but does not assume that its operating on the
629 // entire path. It therefore does not prepend a slash, etc.
630 COMPONENT_EXPORT(URL)
631 bool CanonicalizePartialPath(const char* spec,
632 const Component& path,
633 CanonOutput* output,
634 Component* out_path);
635 COMPONENT_EXPORT(URL)
636 bool CanonicalizePartialPath(const char16_t* spec,
637 const Component& path,
638 CanonOutput* output,
639 Component* out_path);
640
641 // Canonicalizes the input as a file path. This is like CanonicalizePath except
642 // that it also handles Windows drive specs. For example, the path can begin
643 // with "c|\" and it will get properly canonicalized to "C:/".
644 // The string will be appended to |*output| and |*out_path| will be updated.
645 //
646 // The 8-bit version requires UTF-8 encoding.
647 COMPONENT_EXPORT(URL)
648 bool FileCanonicalizePath(const char* spec,
649 const Component& path,
650 CanonOutput* output,
651 Component* out_path);
652 COMPONENT_EXPORT(URL)
653 bool FileCanonicalizePath(const char16_t* spec,
654 const Component& path,
655 CanonOutput* output,
656 Component* out_path);
657
658 // Query: Prepends the ? if needed.
659 //
660 // The 8-bit version requires the input to be UTF-8 encoding. Incorrectly
661 // encoded characters (in UTF-8 or UTF-16) will be replaced with the Unicode
662 // "invalid character." This function can not fail, we always just try to do
663 // our best for crazy input here since web pages can set it themselves.
664 //
665 // This will convert the given input into the output encoding that the given
666 // character set converter object provides. The converter will only be called
667 // if necessary, for ASCII input, no conversions are necessary.
668 //
669 // The converter can be NULL. In this case, the output encoding will be UTF-8.
670 COMPONENT_EXPORT(URL)
671 void CanonicalizeQuery(const char* spec,
672 const Component& query,
673 CharsetConverter* converter,
674 CanonOutput* output,
675 Component* out_query);
676 COMPONENT_EXPORT(URL)
677 void CanonicalizeQuery(const char16_t* spec,
678 const Component& query,
679 CharsetConverter* converter,
680 CanonOutput* output,
681 Component* out_query);
682
683 // Ref: Prepends the # if needed. The output will be UTF-8 (this is the only
684 // canonicalizer that does not produce ASCII output). The output is
685 // guaranteed to be valid UTF-8.
686 //
687 // This function will not fail. If the input is invalid UTF-8/UTF-16, we'll use
688 // the "Unicode replacement character" for the confusing bits and copy the rest.
689 COMPONENT_EXPORT(URL)
690 void CanonicalizeRef(const char* spec,
691 const Component& path,
692 CanonOutput* output,
693 Component* out_path);
694 COMPONENT_EXPORT(URL)
695 void CanonicalizeRef(const char16_t* spec,
696 const Component& path,
697 CanonOutput* output,
698 Component* out_path);
699
700 // Full canonicalizer ---------------------------------------------------------
701 //
702 // These functions replace any string contents, rather than append as above.
703 // See the above piece-by-piece functions for information specific to
704 // canonicalizing individual components.
705 //
706 // The output will be ASCII except the reference fragment, which may be UTF-8.
707 //
708 // The 8-bit versions require UTF-8 encoding.
709
710 // Use for standard URLs with authorities and paths.
711 COMPONENT_EXPORT(URL)
712 bool CanonicalizeStandardURL(const char* spec,
713 const Parsed& parsed,
714 SchemeType scheme_type,
715 CharsetConverter* query_converter,
716 CanonOutput* output,
717 Parsed* new_parsed);
718 COMPONENT_EXPORT(URL)
719 bool CanonicalizeStandardURL(const char16_t* spec,
720 const Parsed& parsed,
721 SchemeType scheme_type,
722 CharsetConverter* query_converter,
723 CanonOutput* output,
724 Parsed* new_parsed);
725
726 // Use for non-special URLs.
727 COMPONENT_EXPORT(URL)
728 bool CanonicalizeNonSpecialURL(const char* spec,
729 int spec_len,
730 const Parsed& parsed,
731 CharsetConverter* query_converter,
732 CanonOutput& output,
733 Parsed& new_parsed);
734 COMPONENT_EXPORT(URL)
735 bool CanonicalizeNonSpecialURL(const char16_t* spec,
736 int spec_len,
737 const Parsed& parsed,
738 CharsetConverter* query_converter,
739 CanonOutput& output,
740 Parsed& new_parsed);
741
742 // Use for file URLs.
743 COMPONENT_EXPORT(URL)
744 bool CanonicalizeFileURL(const char* spec,
745 int spec_len,
746 const Parsed& parsed,
747 CharsetConverter* query_converter,
748 CanonOutput* output,
749 Parsed* new_parsed);
750 COMPONENT_EXPORT(URL)
751 bool CanonicalizeFileURL(const char16_t* spec,
752 int spec_len,
753 const Parsed& parsed,
754 CharsetConverter* query_converter,
755 CanonOutput* output,
756 Parsed* new_parsed);
757
758 // Use for filesystem URLs.
759 COMPONENT_EXPORT(URL)
760 bool CanonicalizeFileSystemURL(const char* spec,
761 const Parsed& parsed,
762 CharsetConverter* query_converter,
763 CanonOutput* output,
764 Parsed* new_parsed);
765 COMPONENT_EXPORT(URL)
766 bool CanonicalizeFileSystemURL(const char16_t* spec,
767 const Parsed& parsed,
768 CharsetConverter* query_converter,
769 CanonOutput* output,
770 Parsed* new_parsed);
771
772 // Use for path URLs such as javascript. This does not modify the path in any
773 // way, for example, by escaping it.
774 COMPONENT_EXPORT(URL)
775 bool CanonicalizePathURL(const char* spec,
776 int spec_len,
777 const Parsed& parsed,
778 CanonOutput* output,
779 Parsed* new_parsed);
780 COMPONENT_EXPORT(URL)
781 bool CanonicalizePathURL(const char16_t* spec,
782 int spec_len,
783 const Parsed& parsed,
784 CanonOutput* output,
785 Parsed* new_parsed);
786
787 // Use to canonicalize just the path component of a "path" URL; e.g. the
788 // path of a javascript URL.
789 COMPONENT_EXPORT(URL)
790 void CanonicalizePathURLPath(const char* source,
791 const Component& component,
792 CanonOutput* output,
793 Component* new_component);
794 COMPONENT_EXPORT(URL)
795 void CanonicalizePathURLPath(const char16_t* source,
796 const Component& component,
797 CanonOutput* output,
798 Component* new_component);
799
800 // Use for mailto URLs. This "canonicalizes" the URL into a path and query
801 // component. It does not attempt to merge "to" fields. It uses UTF-8 for
802 // the query encoding if there is a query. This is because a mailto URL is
803 // really intended for an external mail program, and the encoding of a page,
804 // etc. which would influence a query encoding normally are irrelevant.
805 COMPONENT_EXPORT(URL)
806 bool CanonicalizeMailtoURL(const char* spec,
807 int spec_len,
808 const Parsed& parsed,
809 CanonOutput* output,
810 Parsed* new_parsed);
811 COMPONENT_EXPORT(URL)
812 bool CanonicalizeMailtoURL(const char16_t* spec,
813 int spec_len,
814 const Parsed& parsed,
815 CanonOutput* output,
816 Parsed* new_parsed);
817
818 // Part replacer --------------------------------------------------------------
819
820 // Internal structure used for storing separate strings for each component.
821 // The basic canonicalization functions use this structure internally so that
822 // component replacement (different strings for different components) can be
823 // treated on the same code path as regular canonicalization (the same string
824 // for each component).
825 //
826 // A Parsed structure usually goes along with this. Those components identify
827 // offsets within these strings, so that they can all be in the same string,
828 // or spread arbitrarily across different ones.
829 //
830 // This structures does not own any data. It is the caller's responsibility to
831 // ensure that the data the pointers point to stays in scope and is not
832 // modified.
833 template <typename CHAR>
834 struct URLComponentSource {
835 // Constructor normally used by callers wishing to replace components. This
836 // will make them all NULL, which is no replacement. The caller would then
837 // override the components they want to replace.
URLComponentSourceURLComponentSource838 URLComponentSource()
839 : scheme(nullptr),
840 username(nullptr),
841 password(nullptr),
842 host(nullptr),
843 port(nullptr),
844 path(nullptr),
845 query(nullptr),
846 ref(nullptr) {}
847
848 // Constructor normally used internally to initialize all the components to
849 // point to the same spec.
URLComponentSourceURLComponentSource850 explicit URLComponentSource(const CHAR* default_value)
851 : scheme(default_value),
852 username(default_value),
853 password(default_value),
854 host(default_value),
855 port(default_value),
856 path(default_value),
857 query(default_value),
858 ref(default_value) {}
859
860 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
861 // #addr-of
862 RAW_PTR_EXCLUSION const CHAR* scheme;
863 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
864 // #addr-of
865 RAW_PTR_EXCLUSION const CHAR* username;
866 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
867 // #addr-of
868 RAW_PTR_EXCLUSION const CHAR* password;
869 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
870 // #addr-of
871 RAW_PTR_EXCLUSION const CHAR* host;
872 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
873 // #addr-of
874 RAW_PTR_EXCLUSION const CHAR* port;
875 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
876 // #addr-of
877 RAW_PTR_EXCLUSION const CHAR* path;
878 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
879 // #addr-of
880 RAW_PTR_EXCLUSION const CHAR* query;
881 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
882 // #addr-of
883 RAW_PTR_EXCLUSION const CHAR* ref;
884 };
885
886 // This structure encapsulates information on modifying a URL. Each component
887 // may either be left unchanged, replaced, or deleted.
888 //
889 // By default, each component is unchanged. For those components that should be
890 // modified, call either Set* or Clear* to modify it.
891 //
892 // The string passed to Set* functions DOES NOT GET COPIED AND MUST BE KEPT
893 // IN SCOPE BY THE CALLER for as long as this object exists!
894 //
895 // Prefer the 8-bit replacement version if possible since it is more efficient.
896 template <typename CHAR>
897 class Replacements {
898 public:
Replacements()899 Replacements() {}
900
901 // Scheme
SetScheme(const CHAR * s,const Component & comp)902 void SetScheme(const CHAR* s, const Component& comp) {
903 sources_.scheme = s;
904 components_.scheme = comp;
905 }
906 // Note: we don't have a ClearScheme since this doesn't make any sense.
IsSchemeOverridden()907 bool IsSchemeOverridden() const { return sources_.scheme != NULL; }
908
909 // Username
SetUsername(const CHAR * s,const Component & comp)910 void SetUsername(const CHAR* s, const Component& comp) {
911 sources_.username = s;
912 components_.username = comp;
913 }
ClearUsername()914 void ClearUsername() {
915 sources_.username = Placeholder();
916 components_.username = Component();
917 }
IsUsernameOverridden()918 bool IsUsernameOverridden() const { return sources_.username != NULL; }
919
920 // Password
SetPassword(const CHAR * s,const Component & comp)921 void SetPassword(const CHAR* s, const Component& comp) {
922 sources_.password = s;
923 components_.password = comp;
924 }
ClearPassword()925 void ClearPassword() {
926 sources_.password = Placeholder();
927 components_.password = Component();
928 }
IsPasswordOverridden()929 bool IsPasswordOverridden() const { return sources_.password != NULL; }
930
931 // Host
SetHost(const CHAR * s,const Component & comp)932 void SetHost(const CHAR* s, const Component& comp) {
933 sources_.host = s;
934 components_.host = comp;
935 }
ClearHost()936 void ClearHost() {
937 sources_.host = Placeholder();
938 components_.host = Component();
939 }
IsHostOverridden()940 bool IsHostOverridden() const { return sources_.host != NULL; }
941
942 // Port
SetPort(const CHAR * s,const Component & comp)943 void SetPort(const CHAR* s, const Component& comp) {
944 sources_.port = s;
945 components_.port = comp;
946 }
ClearPort()947 void ClearPort() {
948 sources_.port = Placeholder();
949 components_.port = Component();
950 }
IsPortOverridden()951 bool IsPortOverridden() const { return sources_.port != NULL; }
952
953 // Path
SetPath(const CHAR * s,const Component & comp)954 void SetPath(const CHAR* s, const Component& comp) {
955 sources_.path = s;
956 components_.path = comp;
957 }
ClearPath()958 void ClearPath() {
959 sources_.path = Placeholder();
960 components_.path = Component();
961 }
IsPathOverridden()962 bool IsPathOverridden() const { return sources_.path != NULL; }
963
964 // Query
SetQuery(const CHAR * s,const Component & comp)965 void SetQuery(const CHAR* s, const Component& comp) {
966 sources_.query = s;
967 components_.query = comp;
968 }
ClearQuery()969 void ClearQuery() {
970 sources_.query = Placeholder();
971 components_.query = Component();
972 }
IsQueryOverridden()973 bool IsQueryOverridden() const { return sources_.query != NULL; }
974
975 // Ref
SetRef(const CHAR * s,const Component & comp)976 void SetRef(const CHAR* s, const Component& comp) {
977 sources_.ref = s;
978 components_.ref = comp;
979 }
ClearRef()980 void ClearRef() {
981 sources_.ref = Placeholder();
982 components_.ref = Component();
983 }
IsRefOverridden()984 bool IsRefOverridden() const { return sources_.ref != NULL; }
985
986 // Getters for the internal data. See the variables below for how the
987 // information is encoded.
sources()988 const URLComponentSource<CHAR>& sources() const { return sources_; }
components()989 const Parsed& components() const { return components_; }
990
991 private:
992 // Returns a pointer to a static empty string that is used as a placeholder
993 // to indicate a component should be deleted (see below).
Placeholder()994 const CHAR* Placeholder() {
995 static const CHAR empty_cstr = 0;
996 return &empty_cstr;
997 }
998
999 // We support three states:
1000 //
1001 // Action | Source Component
1002 // -----------------------+--------------------------------------------------
1003 // Don't change component | NULL (unused)
1004 // Replace component | (replacement string) (replacement component)
1005 // Delete component | (non-NULL) (invalid component: (0,-1))
1006 //
1007 // We use a pointer to the empty string for the source when the component
1008 // should be deleted.
1009 URLComponentSource<CHAR> sources_;
1010 Parsed components_;
1011 };
1012
1013 // The base must be an 8-bit canonical URL.
1014 COMPONENT_EXPORT(URL)
1015 bool ReplaceStandardURL(const char* base,
1016 const Parsed& base_parsed,
1017 const Replacements<char>& replacements,
1018 SchemeType scheme_type,
1019 CharsetConverter* query_converter,
1020 CanonOutput* output,
1021 Parsed* new_parsed);
1022 COMPONENT_EXPORT(URL)
1023 bool ReplaceStandardURL(const char* base,
1024 const Parsed& base_parsed,
1025 const Replacements<char16_t>& replacements,
1026 SchemeType scheme_type,
1027 CharsetConverter* query_converter,
1028 CanonOutput* output,
1029 Parsed* new_parsed);
1030
1031 // For non-special URLs.
1032 COMPONENT_EXPORT(URL)
1033 bool ReplaceNonSpecialURL(const char* base,
1034 const Parsed& base_parsed,
1035 const Replacements<char>& replacements,
1036 CharsetConverter* query_converter,
1037 CanonOutput& output,
1038 Parsed& new_parsed);
1039 COMPONENT_EXPORT(URL)
1040 bool ReplaceNonSpecialURL(const char* base,
1041 const Parsed& base_parsed,
1042 const Replacements<char16_t>& replacements,
1043 CharsetConverter* query_converter,
1044 CanonOutput& output,
1045 Parsed& new_parsed);
1046
1047 // Filesystem URLs can only have the path, query, or ref replaced.
1048 // All other components will be ignored.
1049 COMPONENT_EXPORT(URL)
1050 bool ReplaceFileSystemURL(const char* base,
1051 const Parsed& base_parsed,
1052 const Replacements<char>& replacements,
1053 CharsetConverter* query_converter,
1054 CanonOutput* output,
1055 Parsed* new_parsed);
1056 COMPONENT_EXPORT(URL)
1057 bool ReplaceFileSystemURL(const char* base,
1058 const Parsed& base_parsed,
1059 const Replacements<char16_t>& replacements,
1060 CharsetConverter* query_converter,
1061 CanonOutput* output,
1062 Parsed* new_parsed);
1063
1064 // Replacing some parts of a file URL is not permitted. Everything except
1065 // the host, path, query, and ref will be ignored.
1066 COMPONENT_EXPORT(URL)
1067 bool ReplaceFileURL(const char* base,
1068 const Parsed& base_parsed,
1069 const Replacements<char>& replacements,
1070 CharsetConverter* query_converter,
1071 CanonOutput* output,
1072 Parsed* new_parsed);
1073 COMPONENT_EXPORT(URL)
1074 bool ReplaceFileURL(const char* base,
1075 const Parsed& base_parsed,
1076 const Replacements<char16_t>& replacements,
1077 CharsetConverter* query_converter,
1078 CanonOutput* output,
1079 Parsed* new_parsed);
1080
1081 // Path URLs can only have the scheme and path replaced. All other components
1082 // will be ignored.
1083 COMPONENT_EXPORT(URL)
1084 bool ReplacePathURL(const char* base,
1085 const Parsed& base_parsed,
1086 const Replacements<char>& replacements,
1087 CanonOutput* output,
1088 Parsed* new_parsed);
1089 COMPONENT_EXPORT(URL)
1090 bool ReplacePathURL(const char* base,
1091 const Parsed& base_parsed,
1092 const Replacements<char16_t>& replacements,
1093 CanonOutput* output,
1094 Parsed* new_parsed);
1095
1096 // Mailto URLs can only have the scheme, path, and query replaced.
1097 // All other components will be ignored.
1098 COMPONENT_EXPORT(URL)
1099 bool ReplaceMailtoURL(const char* base,
1100 const Parsed& base_parsed,
1101 const Replacements<char>& replacements,
1102 CanonOutput* output,
1103 Parsed* new_parsed);
1104 COMPONENT_EXPORT(URL)
1105 bool ReplaceMailtoURL(const char* base,
1106 const Parsed& base_parsed,
1107 const Replacements<char16_t>& replacements,
1108 CanonOutput* output,
1109 Parsed* new_parsed);
1110
1111 // Relative URL ---------------------------------------------------------------
1112
1113 // Given an input URL or URL fragment |fragment|, determines if it is a
1114 // relative or absolute URL and places the result into |*is_relative|. If it is
1115 // relative, the relevant portion of the URL will be placed into
1116 // |*relative_component| (there may have been trimmed whitespace, for example).
1117 // This value is passed to ResolveRelativeURL. If the input is not relative,
1118 // this value is UNDEFINED (it may be changed by the function).
1119 //
1120 // Returns true on success (we successfully determined the URL is relative or
1121 // not). Failure means that the combination of URLs doesn't make any sense.
1122 //
1123 // The base URL should always be canonical, therefore is ASCII.
1124 COMPONENT_EXPORT(URL)
1125 bool IsRelativeURL(const char* base,
1126 const Parsed& base_parsed,
1127 const char* fragment,
1128 int fragment_len,
1129 bool is_base_hierarchical,
1130 bool* is_relative,
1131 Component* relative_component);
1132 COMPONENT_EXPORT(URL)
1133 bool IsRelativeURL(const char* base,
1134 const Parsed& base_parsed,
1135 const char16_t* fragment,
1136 int fragment_len,
1137 bool is_base_hierarchical,
1138 bool* is_relative,
1139 Component* relative_component);
1140
1141 // Given a canonical parsed source URL, a URL fragment known to be relative,
1142 // and the identified relevant portion of the relative URL (computed by
1143 // IsRelativeURL), this produces a new parsed canonical URL in |output| and
1144 // |out_parsed|.
1145 //
1146 // It also requires a flag indicating whether the base URL is a file: URL
1147 // which triggers additional logic.
1148 //
1149 // The base URL should be canonical and have a host (may be empty for file
1150 // URLs) and a path. If it doesn't have these, we can't resolve relative
1151 // URLs off of it and will return the base as the output with an error flag.
1152 // Because it is canonical is should also be ASCII.
1153 //
1154 // The query charset converter follows the same rules as CanonicalizeQuery.
1155 //
1156 // Returns true on success. On failure, the output will be "something
1157 // reasonable" that will be consistent and valid, just probably not what
1158 // was intended by the web page author or caller.
1159 COMPONENT_EXPORT(URL)
1160 bool ResolveRelativeURL(const char* base_url,
1161 const Parsed& base_parsed,
1162 bool base_is_file,
1163 const char* relative_url,
1164 const Component& relative_component,
1165 CharsetConverter* query_converter,
1166 CanonOutput* output,
1167 Parsed* out_parsed);
1168 COMPONENT_EXPORT(URL)
1169 bool ResolveRelativeURL(const char* base_url,
1170 const Parsed& base_parsed,
1171 bool base_is_file,
1172 const char16_t* relative_url,
1173 const Component& relative_component,
1174 CharsetConverter* query_converter,
1175 CanonOutput* output,
1176 Parsed* out_parsed);
1177
1178 } // namespace url
1179
1180 #endif // URL_URL_CANON_H_
1181