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.
5 #ifndef URL_URL_CANON_H_
6 #define URL_URL_CANON_H_
11 #include <string_view>
13 #include "base/component_export.h"
14 #include "base/export_template.h"
15 #include "base/memory/raw_ptr_exclusion.h"
16 #include "base/numerics/clamped_math.h"
17 #include "url/third_party/mozilla/url_parse.h"
21 // Canonicalizer output -------------------------------------------------------
23 // Base class for the canonicalizer output, this maintains a buffer and
24 // supports simple resizing and append operations on it.
26 // It is VERY IMPORTANT that no virtual function calls be made on the common
27 // code path. We only have two virtual function calls, the destructor and a
28 // resize function that is called when the existing buffer is not big enough.
29 // The derived class is then in charge of setting up our buffer which we will
34 CanonOutputT() = default;
35 virtual ~CanonOutputT() = default;
37 // Implemented to resize the buffer. This function should update the buffer
38 // pointer to point to the new buffer, and any old data up to |cur_len_| in
39 // the buffer must be copied over.
41 // The new size |sz| must be larger than buffer_len_.
42 virtual void Resize(size_t sz) = 0;
44 // Accessor for returning a character at a given position. The input offset
45 // must be in the valid range.
46 inline T at(size_t offset) const { return buffer_[offset]; }
48 // Sets the character at the given position. The given position MUST be less
50 inline void set(size_t offset, T ch) { buffer_[offset] = ch; }
52 // Returns the number of characters currently in the buffer.
53 inline size_t length() const { return cur_len_; }
55 // Returns the current capacity of the buffer. The length() is the number of
56 // characters that have been declared to be written, but the capacity() is
57 // the number that can be written without reallocation. If the caller must
58 // write many characters at once, it can make sure there is enough capacity,
59 // write the data, then use set_size() to declare the new length().
60 size_t capacity() const { return buffer_len_; }
62 // Returns the contents of the buffer as a string_view.
63 std::basic_string_view<T> view() const {
64 return std::basic_string_view<T>(data(), length());
67 // Called by the user of this class to get the output. The output will NOT
68 // be NULL-terminated. Call length() to get the
70 const T* data() const { return buffer_; }
71 T* data() { return buffer_; }
73 // Shortens the URL to the new length. Used for "backing up" when processing
74 // relative paths. This can also be used if an external function writes a lot
75 // of data to the buffer (when using the "Raw" version below) beyond the end,
76 // to declare the new length.
78 // This MUST NOT be used to expand the size of the buffer beyond capacity().
79 void set_length(size_t new_len) { cur_len_ = new_len; }
81 // This is the most performance critical function, since it is called for
83 void push_back(T ch) {
84 // In VC2005, putting this common case first speeds up execution
85 // dramatically because this branch is predicted as taken.
86 if (cur_len_ < buffer_len_) {
87 buffer_[cur_len_] = ch;
92 // Grow the buffer to hold at least one more item. Hopefully we won't have
93 // to do this very often.
97 // Actually do the insertion.
98 buffer_[cur_len_] = ch;
102 // Appends the given string to the output.
103 void Append(const T* str, size_t str_len) {
104 if (str_len > buffer_len_ - cur_len_) {
105 if (!Grow(str_len - (buffer_len_ - cur_len_)))
108 memcpy(buffer_ + cur_len_, str, str_len * sizeof(T));
112 void Append(std::basic_string_view<T> str) { Append(str.data(), str.size()); }
114 void ReserveSizeIfNeeded(size_t estimated_size) {
115 // Reserve a bit extra to account for escaped chars.
116 if (estimated_size > buffer_len_)
117 Resize((base::ClampedNumeric<size_t>(estimated_size) + 8).RawValue());
121 // Grows the given buffer so that it can fit at least |min_additional|
122 // characters. Returns true if the buffer could be resized, false on OOM.
123 bool Grow(size_t min_additional) {
124 static const size_t kMinBufferLen = 16;
125 size_t new_len = (buffer_len_ == 0) ? kMinBufferLen : buffer_len_;
127 if (new_len >= (1 << 30)) // Prevent overflow below.
130 } while (new_len < buffer_len_ + min_additional);
135 // `buffer_` is not a raw_ptr<...> for performance reasons (based on analysis
136 // of sampling profiler data).
137 RAW_PTR_EXCLUSION T* buffer_ = nullptr;
138 size_t buffer_len_ = 0;
140 // Used characters in the buffer.
144 // Simple implementation of the CanonOutput using new[]. This class
145 // also supports a static buffer so if it is allocated on the stack, most
146 // URLs can be canonicalized with no heap allocations.
147 template <typename T, int fixed_capacity = 1024>
148 class RawCanonOutputT : public CanonOutputT<T> {
150 RawCanonOutputT() : CanonOutputT<T>() {
151 this->buffer_ = fixed_buffer_;
152 this->buffer_len_ = fixed_capacity;
154 ~RawCanonOutputT() override {
155 if (this->buffer_ != fixed_buffer_)
156 delete[] this->buffer_;
159 void Resize(size_t sz) override {
160 T* new_buf = new T[sz];
161 memcpy(new_buf, this->buffer_,
162 sizeof(T) * (this->cur_len_ < sz ? this->cur_len_ : sz));
163 if (this->buffer_ != fixed_buffer_)
164 delete[] this->buffer_;
165 this->buffer_ = new_buf;
166 this->buffer_len_ = sz;
170 T fixed_buffer_[fixed_capacity];
173 // Explicitely instantiate commonly used instatiations.
174 extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL))
176 extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL))
177 CanonOutputT<char16_t>;
179 // Normally, all canonicalization output is in narrow characters. We support
180 // the templates so it can also be used internally if a wide buffer is
182 typedef CanonOutputT<char> CanonOutput;
183 typedef CanonOutputT<char16_t> CanonOutputW;
185 template <int fixed_capacity>
186 class RawCanonOutput : public RawCanonOutputT<char, fixed_capacity> {};
187 template <int fixed_capacity>
188 class RawCanonOutputW : public RawCanonOutputT<char16_t, fixed_capacity> {};
190 // Character set converter ----------------------------------------------------
192 // Converts query strings into a custom encoding. The embedder can supply an
193 // implementation of this class to interface with their own character set
194 // conversion libraries.
196 // Embedders will want to see the unit test for the ICU version.
198 class COMPONENT_EXPORT(URL) CharsetConverter {
200 CharsetConverter() {}
201 virtual ~CharsetConverter() {}
203 // Converts the given input string from UTF-16 to whatever output format the
204 // converter supports. This is used only for the query encoding conversion,
205 // which does not fail. Instead, the converter should insert "invalid
206 // character" characters in the output for invalid sequences, and do the
209 // If the input contains a character not representable in the output
210 // character set, the converter should append the HTML entity sequence in
211 // decimal, (such as "你") with escaping of the ampersand, number
212 // sign, and semicolon (in the previous example it would be
213 // "%26%2320320%3B"). This rule is based on what IE does in this situation.
214 virtual void ConvertFromUTF16(const char16_t* input,
216 CanonOutput* output) = 0;
219 // Schemes --------------------------------------------------------------------
221 // Types of a scheme representing the requirements on the data represented by
222 // the authority component of a URL with the scheme.
224 // The authority component of a URL with the scheme has the form
225 // "username:password@host:port". The username and password entries are
226 // optional; the host may not be empty. The default value of the port can be
227 // omitted in serialization. This type occurs with network schemes like http,
229 SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION,
230 // The authority component of a URL with the scheme has the form "host:port",
231 // and does not include username or password. The default value of the port
232 // can be omitted in serialization. Used by inner URLs of filesystem URLs of
233 // origins with network hosts, from which the username and password are
235 SCHEME_WITH_HOST_AND_PORT,
236 // The authority component of an URL with the scheme has the form "host", and
237 // does not include port, username, or password. Used when the hosts are not
238 // network addresses; for example, schemes used internally by the browser.
240 // A URL with the scheme doesn't have the authority component.
241 SCHEME_WITHOUT_AUTHORITY,
244 // Whitespace -----------------------------------------------------------------
246 // Searches for whitespace that should be removed from the middle of URLs, and
247 // removes it. Removed whitespace are tabs and newlines, but NOT spaces. Spaces
248 // are preserved, which is what most browsers do. A pointer to the output will
249 // be returned, and the length of that output will be in |output_len|.
251 // This should be called before parsing if whitespace removal is desired (which
252 // it normally is when you are canonicalizing).
254 // If no whitespace is removed, this function will not use the buffer and will
255 // return a pointer to the input, to avoid the extra copy. If modification is
256 // required, the given |buffer| will be used and the returned pointer will
257 // point to the beginning of the buffer.
259 // Therefore, callers should not use the buffer, since it may actually be empty,
260 // use the computed pointer and |*output_len| instead.
262 // If |input| contained both removable whitespace and a raw `<` character,
263 // |potentially_dangling_markup| will be set to `true`. Otherwise, it will be
265 COMPONENT_EXPORT(URL)
266 const char* RemoveURLWhitespace(const char* input,
268 CanonOutputT<char>* buffer,
270 bool* potentially_dangling_markup);
271 COMPONENT_EXPORT(URL)
272 const char16_t* RemoveURLWhitespace(const char16_t* input,
274 CanonOutputT<char16_t>* buffer,
276 bool* potentially_dangling_markup);
278 // IDN ------------------------------------------------------------------------
280 // Converts the Unicode input representing a hostname to ASCII using IDN rules.
281 // The output must fall in the ASCII range, but will be encoded in UTF-16.
283 // On success, the output will be filled with the ASCII host name and it will
284 // return true. Unlike most other canonicalization functions, this assumes that
285 // the output is empty. The beginning of the host will be at offset 0, and
286 // the length of the output will be set to the length of the new host name.
288 // On error, returns false. The output in this case is undefined.
289 COMPONENT_EXPORT(URL)
290 bool IDNToASCII(std::u16string_view src, CanonOutputW* output);
292 // Piece-by-piece canonicalizers ----------------------------------------------
294 // These individual canonicalizers append the canonicalized versions of the
295 // corresponding URL component to the given CanonOutput. The spec and the
296 // previously-identified range of that component are the input. The range of
297 // the canonicalized component will be written to the output component.
299 // These functions all append to the output so they can be chained. Make sure
300 // the output is empty when you start.
302 // These functions returns boolean values indicating success. On failure, they
303 // will attempt to write something reasonable to the output so that, if
304 // displayed to the user, they will recognise it as something that's messed up.
305 // Nothing more should ever be done with these invalid URLs, however.
307 // Scheme: Appends the scheme and colon to the URL. The output component will
308 // indicate the range of characters up to but not including the colon.
310 // Canonical URLs always have a scheme. If the scheme is not present in the
311 // input, this will just write the colon to indicate an empty scheme. Does not
312 // append slashes which will be needed before any authority components for most
315 // The 8-bit version requires UTF-8 encoding.
316 COMPONENT_EXPORT(URL)
317 bool CanonicalizeScheme(const char* spec,
318 const Component& scheme,
320 Component* out_scheme);
321 COMPONENT_EXPORT(URL)
322 bool CanonicalizeScheme(const char16_t* spec,
323 const Component& scheme,
325 Component* out_scheme);
327 // User info: username/password. If present, this will add the delimiters so
328 // the output will be "<username>:<password>@" or "<username>@". Empty
329 // username/password pairs, or empty passwords, will get converted to
330 // nonexistent in the canonical version.
332 // The components for the username and password refer to ranges in the
333 // respective source strings. Usually, these will be the same string, which
334 // is legal as long as the two components don't overlap.
336 // The 8-bit version requires UTF-8 encoding.
337 COMPONENT_EXPORT(URL)
338 bool CanonicalizeUserInfo(const char* username_source,
339 const Component& username,
340 const char* password_source,
341 const Component& password,
343 Component* out_username,
344 Component* out_password);
345 COMPONENT_EXPORT(URL)
346 bool CanonicalizeUserInfo(const char16_t* username_source,
347 const Component& username,
348 const char16_t* password_source,
349 const Component& password,
351 Component* out_username,
352 Component* out_password);
354 // This structure holds detailed state exported from the IP/Host canonicalizers.
355 // Additional fields may be added as callers require them.
356 struct CanonHostInfo {
357 CanonHostInfo() : family(NEUTRAL), num_ipv4_components(0), out_host() {}
359 // Convenience function to test if family is an IP address.
360 bool IsIPAddress() const { return family == IPV4 || family == IPV6; }
362 // This field summarizes how the input was classified by the canonicalizer.
364 NEUTRAL, // - Doesn't resemble an IP address. As far as the IP
365 // canonicalizer is concerned, it should be treated as a
367 BROKEN, // - Almost an IP, but was not canonicalized. This could be an
368 // IPv4 address where truncation occurred, or something
369 // containing the special characters :[] which did not parse
370 // as an IPv6 address. Never attempt to connect to this
371 // address, because it might actually succeed!
372 IPV4, // - Successfully canonicalized as an IPv4 address.
373 IPV6, // - Successfully canonicalized as an IPv6 address.
377 // If |family| is IPV4, then this is the number of nonempty dot-separated
378 // components in the input text, from 1 to 4. If |family| is not IPV4,
379 // this value is undefined.
380 int num_ipv4_components;
382 // Location of host within the canonicalized output.
383 // CanonicalizeIPAddress() only sets this field if |family| is IPV4 or IPV6.
384 // CanonicalizeHostVerbose() always sets it.
387 // |address| contains the parsed IP Address (if any) in its first
388 // AddressLength() bytes, in network order. If IsIPAddress() is false
389 // AddressLength() will return zero and the content of |address| is undefined.
390 unsigned char address[16];
392 // Convenience function to calculate the length of an IP address corresponding
393 // to the current IP version in |family|, if any. For use with |address|.
394 int AddressLength() const {
395 return family == IPV4 ? 4 : (family == IPV6 ? 16 : 0);
401 // The 8-bit version requires UTF-8 encoding. Use this version when you only
402 // need to know whether canonicalization succeeded.
403 COMPONENT_EXPORT(URL)
404 bool CanonicalizeHost(const char* spec,
405 const Component& host,
407 Component* out_host);
408 COMPONENT_EXPORT(URL)
409 bool CanonicalizeHost(const char16_t* spec,
410 const Component& host,
412 Component* out_host);
414 // Extended version of CanonicalizeHost, which returns additional information.
415 // Use this when you need to know whether the hostname was an IP address.
416 // A successful return is indicated by host_info->family != BROKEN. See the
417 // definition of CanonHostInfo above for details.
418 COMPONENT_EXPORT(URL)
419 void CanonicalizeHostVerbose(const char* spec,
420 const Component& host,
422 CanonHostInfo* host_info);
423 COMPONENT_EXPORT(URL)
424 void CanonicalizeHostVerbose(const char16_t* spec,
425 const Component& host,
427 CanonHostInfo* host_info);
429 // Canonicalizes a string according to the host canonicalization rules. Unlike
430 // CanonicalizeHost, this will not check for IP addresses which can change the
431 // meaning (and canonicalization) of the components. This means it is possible
432 // to call this for sub-components of a host name without corruption.
434 // As an example, "01.02.03.04.com" is a canonical hostname. If you called
435 // CanonicalizeHost on the substring "01.02.03.04" it will get "fixed" to
436 // "1.2.3.4" which will produce an invalid host name when reassembled. This
437 // can happen more than one might think because all numbers by themselves are
438 // considered IP addresses; so "5" canonicalizes to "0.0.0.5".
440 // Be careful: Because Punycode works on each dot-separated substring as a
441 // unit, you should only pass this function substrings that represent complete
442 // dot-separated subcomponents of the original host. Even if you have ASCII
443 // input, percent-escaped characters will have different meanings if split in
446 // Returns true if the host was valid. This function will treat a 0-length
447 // host as valid (because it's designed to be used for substrings) while the
448 // full version above will mark empty hosts as broken.
449 COMPONENT_EXPORT(URL)
450 bool CanonicalizeHostSubstring(const char* spec,
451 const Component& host,
452 CanonOutput* output);
453 COMPONENT_EXPORT(URL)
454 bool CanonicalizeHostSubstring(const char16_t* spec,
455 const Component& host,
456 CanonOutput* output);
460 // Tries to interpret the given host name as an IPv4 or IPv6 address. If it is
461 // an IP address, it will canonicalize it as such, appending it to |output|.
462 // Additional status information is returned via the |*host_info| parameter.
463 // See the definition of CanonHostInfo above for details.
465 // This is called AUTOMATICALLY from the host canonicalizer, which ensures that
466 // the input is unescaped and name-prepped, etc. It should not normally be
467 // necessary or wise to call this directly.
468 COMPONENT_EXPORT(URL)
469 void CanonicalizeIPAddress(const char* spec,
470 const Component& host,
472 CanonHostInfo* host_info);
473 COMPONENT_EXPORT(URL)
474 void CanonicalizeIPAddress(const char16_t* spec,
475 const Component& host,
477 CanonHostInfo* host_info);
479 // Port: this function will add the colon for the port if a port is present.
480 // The caller can pass PORT_UNSPECIFIED as the
481 // default_port_for_scheme argument if there is no default port.
483 // The 8-bit version requires UTF-8 encoding.
484 COMPONENT_EXPORT(URL)
485 bool CanonicalizePort(const char* spec,
486 const Component& port,
487 int default_port_for_scheme,
489 Component* out_port);
490 COMPONENT_EXPORT(URL)
491 bool CanonicalizePort(const char16_t* spec,
492 const Component& port,
493 int default_port_for_scheme,
495 Component* out_port);
497 // Returns the default port for the given canonical scheme, or PORT_UNSPECIFIED
498 // if the scheme is unknown. Based on https://url.spec.whatwg.org/#default-port
499 COMPONENT_EXPORT(URL)
500 int DefaultPortForScheme(const char* scheme, int scheme_len);
502 // Path. If the input does not begin in a slash (including if the input is
503 // empty), we'll prepend a slash to the path to make it canonical.
505 // The 8-bit version assumes UTF-8 encoding, but does not verify the validity
506 // of the UTF-8 (i.e., you can have invalid UTF-8 sequences, invalid
507 // characters, etc.). Normally, URLs will come in as UTF-16, so this isn't
508 // an issue. Somebody giving us an 8-bit path is responsible for generating
509 // the path that the server expects (we'll escape high-bit characters), so
510 // if something is invalid, it's their problem.
511 COMPONENT_EXPORT(URL)
512 bool CanonicalizePath(const char* spec,
513 const Component& path,
515 Component* out_path);
516 COMPONENT_EXPORT(URL)
517 bool CanonicalizePath(const char16_t* spec,
518 const Component& path,
520 Component* out_path);
522 // Like CanonicalizePath(), but does not assume that its operating on the
523 // entire path. It therefore does not prepend a slash, etc.
524 COMPONENT_EXPORT(URL)
525 bool CanonicalizePartialPath(const char* spec,
526 const Component& path,
528 Component* out_path);
529 COMPONENT_EXPORT(URL)
530 bool CanonicalizePartialPath(const char16_t* spec,
531 const Component& path,
533 Component* out_path);
535 // Canonicalizes the input as a file path. This is like CanonicalizePath except
536 // that it also handles Windows drive specs. For example, the path can begin
537 // with "c|\" and it will get properly canonicalized to "C:/".
538 // The string will be appended to |*output| and |*out_path| will be updated.
540 // The 8-bit version requires UTF-8 encoding.
541 COMPONENT_EXPORT(URL)
542 bool FileCanonicalizePath(const char* spec,
543 const Component& path,
545 Component* out_path);
546 COMPONENT_EXPORT(URL)
547 bool FileCanonicalizePath(const char16_t* spec,
548 const Component& path,
550 Component* out_path);
552 // Query: Prepends the ? if needed.
554 // The 8-bit version requires the input to be UTF-8 encoding. Incorrectly
555 // encoded characters (in UTF-8 or UTF-16) will be replaced with the Unicode
556 // "invalid character." This function can not fail, we always just try to do
557 // our best for crazy input here since web pages can set it themselves.
559 // This will convert the given input into the output encoding that the given
560 // character set converter object provides. The converter will only be called
561 // if necessary, for ASCII input, no conversions are necessary.
563 // The converter can be NULL. In this case, the output encoding will be UTF-8.
564 COMPONENT_EXPORT(URL)
565 void CanonicalizeQuery(const char* spec,
566 const Component& query,
567 CharsetConverter* converter,
569 Component* out_query);
570 COMPONENT_EXPORT(URL)
571 void CanonicalizeQuery(const char16_t* spec,
572 const Component& query,
573 CharsetConverter* converter,
575 Component* out_query);
577 // Ref: Prepends the # if needed. The output will be UTF-8 (this is the only
578 // canonicalizer that does not produce ASCII output). The output is
579 // guaranteed to be valid UTF-8.
581 // This function will not fail. If the input is invalid UTF-8/UTF-16, we'll use
582 // the "Unicode replacement character" for the confusing bits and copy the rest.
583 COMPONENT_EXPORT(URL)
584 void CanonicalizeRef(const char* spec,
585 const Component& path,
587 Component* out_path);
588 COMPONENT_EXPORT(URL)
589 void CanonicalizeRef(const char16_t* spec,
590 const Component& path,
592 Component* out_path);
594 // Full canonicalizer ---------------------------------------------------------
596 // These functions replace any string contents, rather than append as above.
597 // See the above piece-by-piece functions for information specific to
598 // canonicalizing individual components.
600 // The output will be ASCII except the reference fragment, which may be UTF-8.
602 // The 8-bit versions require UTF-8 encoding.
604 // Use for standard URLs with authorities and paths.
605 COMPONENT_EXPORT(URL)
606 bool CanonicalizeStandardURL(const char* spec,
608 const Parsed& parsed,
609 SchemeType scheme_type,
610 CharsetConverter* query_converter,
613 COMPONENT_EXPORT(URL)
614 bool CanonicalizeStandardURL(const char16_t* spec,
616 const Parsed& parsed,
617 SchemeType scheme_type,
618 CharsetConverter* query_converter,
622 // Use for file URLs.
623 COMPONENT_EXPORT(URL)
624 bool CanonicalizeFileURL(const char* spec,
626 const Parsed& parsed,
627 CharsetConverter* query_converter,
630 COMPONENT_EXPORT(URL)
631 bool CanonicalizeFileURL(const char16_t* spec,
633 const Parsed& parsed,
634 CharsetConverter* query_converter,
638 // Use for filesystem URLs.
639 COMPONENT_EXPORT(URL)
640 bool CanonicalizeFileSystemURL(const char* spec,
642 const Parsed& parsed,
643 CharsetConverter* query_converter,
646 COMPONENT_EXPORT(URL)
647 bool CanonicalizeFileSystemURL(const char16_t* spec,
649 const Parsed& parsed,
650 CharsetConverter* query_converter,
654 // Use for path URLs such as javascript. This does not modify the path in any
655 // way, for example, by escaping it.
656 COMPONENT_EXPORT(URL)
657 bool CanonicalizePathURL(const char* spec,
659 const Parsed& parsed,
662 COMPONENT_EXPORT(URL)
663 bool CanonicalizePathURL(const char16_t* spec,
665 const Parsed& parsed,
669 // Use to canonicalize just the path component of a "path" URL; e.g. the
670 // path of a javascript URL.
671 COMPONENT_EXPORT(URL)
672 void CanonicalizePathURLPath(const char* source,
673 const Component& component,
675 Component* new_component);
676 COMPONENT_EXPORT(URL)
677 void CanonicalizePathURLPath(const char16_t* source,
678 const Component& component,
680 Component* new_component);
682 // Use for mailto URLs. This "canonicalizes" the URL into a path and query
683 // component. It does not attempt to merge "to" fields. It uses UTF-8 for
684 // the query encoding if there is a query. This is because a mailto URL is
685 // really intended for an external mail program, and the encoding of a page,
686 // etc. which would influence a query encoding normally are irrelevant.
687 COMPONENT_EXPORT(URL)
688 bool CanonicalizeMailtoURL(const char* spec,
690 const Parsed& parsed,
693 COMPONENT_EXPORT(URL)
694 bool CanonicalizeMailtoURL(const char16_t* spec,
696 const Parsed& parsed,
700 // Part replacer --------------------------------------------------------------
702 // Internal structure used for storing separate strings for each component.
703 // The basic canonicalization functions use this structure internally so that
704 // component replacement (different strings for different components) can be
705 // treated on the same code path as regular canonicalization (the same string
706 // for each component).
708 // A Parsed structure usually goes along with this. Those components identify
709 // offsets within these strings, so that they can all be in the same string,
710 // or spread arbitrarily across different ones.
712 // This structures does not own any data. It is the caller's responsibility to
713 // ensure that the data the pointers point to stays in scope and is not
715 template <typename CHAR>
716 struct URLComponentSource {
717 // Constructor normally used by callers wishing to replace components. This
718 // will make them all NULL, which is no replacement. The caller would then
719 // override the components they want to replace.
730 // Constructor normally used internally to initialize all the components to
731 // point to the same spec.
732 explicit URLComponentSource(const CHAR* default_value)
733 : scheme(default_value),
734 username(default_value),
735 password(default_value),
739 query(default_value),
740 ref(default_value) {}
742 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
744 RAW_PTR_EXCLUSION const CHAR* scheme;
745 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
747 RAW_PTR_EXCLUSION const CHAR* username;
748 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
750 RAW_PTR_EXCLUSION const CHAR* password;
751 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
753 RAW_PTR_EXCLUSION const CHAR* host;
754 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
756 RAW_PTR_EXCLUSION const CHAR* port;
757 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
759 RAW_PTR_EXCLUSION const CHAR* path;
760 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
762 RAW_PTR_EXCLUSION const CHAR* query;
763 // This field is not a raw_ptr<> because it was filtered by the rewriter for:
765 RAW_PTR_EXCLUSION const CHAR* ref;
768 // This structure encapsulates information on modifying a URL. Each component
769 // may either be left unchanged, replaced, or deleted.
771 // By default, each component is unchanged. For those components that should be
772 // modified, call either Set* or Clear* to modify it.
774 // The string passed to Set* functions DOES NOT GET COPIED AND MUST BE KEPT
775 // IN SCOPE BY THE CALLER for as long as this object exists!
777 // Prefer the 8-bit replacement version if possible since it is more efficient.
778 template <typename CHAR>
784 void SetScheme(const CHAR* s, const Component& comp) {
786 components_.scheme = comp;
788 // Note: we don't have a ClearScheme since this doesn't make any sense.
789 bool IsSchemeOverridden() const { return sources_.scheme != NULL; }
792 void SetUsername(const CHAR* s, const Component& comp) {
793 sources_.username = s;
794 components_.username = comp;
796 void ClearUsername() {
797 sources_.username = Placeholder();
798 components_.username = Component();
800 bool IsUsernameOverridden() const { return sources_.username != NULL; }
803 void SetPassword(const CHAR* s, const Component& comp) {
804 sources_.password = s;
805 components_.password = comp;
807 void ClearPassword() {
808 sources_.password = Placeholder();
809 components_.password = Component();
811 bool IsPasswordOverridden() const { return sources_.password != NULL; }
814 void SetHost(const CHAR* s, const Component& comp) {
816 components_.host = comp;
819 sources_.host = Placeholder();
820 components_.host = Component();
822 bool IsHostOverridden() const { return sources_.host != NULL; }
825 void SetPort(const CHAR* s, const Component& comp) {
827 components_.port = comp;
830 sources_.port = Placeholder();
831 components_.port = Component();
833 bool IsPortOverridden() const { return sources_.port != NULL; }
836 void SetPath(const CHAR* s, const Component& comp) {
838 components_.path = comp;
841 sources_.path = Placeholder();
842 components_.path = Component();
844 bool IsPathOverridden() const { return sources_.path != NULL; }
847 void SetQuery(const CHAR* s, const Component& comp) {
849 components_.query = comp;
852 sources_.query = Placeholder();
853 components_.query = Component();
855 bool IsQueryOverridden() const { return sources_.query != NULL; }
858 void SetRef(const CHAR* s, const Component& comp) {
860 components_.ref = comp;
863 sources_.ref = Placeholder();
864 components_.ref = Component();
866 bool IsRefOverridden() const { return sources_.ref != NULL; }
868 // Getters for the internal data. See the variables below for how the
869 // information is encoded.
870 const URLComponentSource<CHAR>& sources() const { return sources_; }
871 const Parsed& components() const { return components_; }
874 // Returns a pointer to a static empty string that is used as a placeholder
875 // to indicate a component should be deleted (see below).
876 const CHAR* Placeholder() {
877 static const CHAR empty_cstr = 0;
881 // We support three states:
883 // Action | Source Component
884 // -----------------------+--------------------------------------------------
885 // Don't change component | NULL (unused)
886 // Replace component | (replacement string) (replacement component)
887 // Delete component | (non-NULL) (invalid component: (0,-1))
889 // We use a pointer to the empty string for the source when the component
890 // should be deleted.
891 URLComponentSource<CHAR> sources_;
895 // The base must be an 8-bit canonical URL.
896 COMPONENT_EXPORT(URL)
897 bool ReplaceStandardURL(const char* base,
898 const Parsed& base_parsed,
899 const Replacements<char>& replacements,
900 SchemeType scheme_type,
901 CharsetConverter* query_converter,
904 COMPONENT_EXPORT(URL)
905 bool ReplaceStandardURL(const char* base,
906 const Parsed& base_parsed,
907 const Replacements<char16_t>& replacements,
908 SchemeType scheme_type,
909 CharsetConverter* query_converter,
913 // Filesystem URLs can only have the path, query, or ref replaced.
914 // All other components will be ignored.
915 COMPONENT_EXPORT(URL)
916 bool ReplaceFileSystemURL(const char* base,
917 const Parsed& base_parsed,
918 const Replacements<char>& replacements,
919 CharsetConverter* query_converter,
922 COMPONENT_EXPORT(URL)
923 bool ReplaceFileSystemURL(const char* base,
924 const Parsed& base_parsed,
925 const Replacements<char16_t>& replacements,
926 CharsetConverter* query_converter,
930 // Replacing some parts of a file URL is not permitted. Everything except
931 // the host, path, query, and ref will be ignored.
932 COMPONENT_EXPORT(URL)
933 bool ReplaceFileURL(const char* base,
934 const Parsed& base_parsed,
935 const Replacements<char>& replacements,
936 CharsetConverter* query_converter,
939 COMPONENT_EXPORT(URL)
940 bool ReplaceFileURL(const char* base,
941 const Parsed& base_parsed,
942 const Replacements<char16_t>& replacements,
943 CharsetConverter* query_converter,
947 // Path URLs can only have the scheme and path replaced. All other components
949 COMPONENT_EXPORT(URL)
950 bool ReplacePathURL(const char* base,
951 const Parsed& base_parsed,
952 const Replacements<char>& replacements,
955 COMPONENT_EXPORT(URL)
956 bool ReplacePathURL(const char* base,
957 const Parsed& base_parsed,
958 const Replacements<char16_t>& replacements,
962 // Mailto URLs can only have the scheme, path, and query replaced.
963 // All other components will be ignored.
964 COMPONENT_EXPORT(URL)
965 bool ReplaceMailtoURL(const char* base,
966 const Parsed& base_parsed,
967 const Replacements<char>& replacements,
970 COMPONENT_EXPORT(URL)
971 bool ReplaceMailtoURL(const char* base,
972 const Parsed& base_parsed,
973 const Replacements<char16_t>& replacements,
977 // Relative URL ---------------------------------------------------------------
979 // Given an input URL or URL fragment |fragment|, determines if it is a
980 // relative or absolute URL and places the result into |*is_relative|. If it is
981 // relative, the relevant portion of the URL will be placed into
982 // |*relative_component| (there may have been trimmed whitespace, for example).
983 // This value is passed to ResolveRelativeURL. If the input is not relative,
984 // this value is UNDEFINED (it may be changed by the function).
986 // Returns true on success (we successfully determined the URL is relative or
987 // not). Failure means that the combination of URLs doesn't make any sense.
989 // The base URL should always be canonical, therefore is ASCII.
990 COMPONENT_EXPORT(URL)
991 bool IsRelativeURL(const char* base,
992 const Parsed& base_parsed,
993 const char* fragment,
995 bool is_base_hierarchical,
997 Component* relative_component);
998 COMPONENT_EXPORT(URL)
999 bool IsRelativeURL(const char* base,
1000 const Parsed& base_parsed,
1001 const char16_t* fragment,
1003 bool is_base_hierarchical,
1005 Component* relative_component);
1007 // Given a canonical parsed source URL, a URL fragment known to be relative,
1008 // and the identified relevant portion of the relative URL (computed by
1009 // IsRelativeURL), this produces a new parsed canonical URL in |output| and
1012 // It also requires a flag indicating whether the base URL is a file: URL
1013 // which triggers additional logic.
1015 // The base URL should be canonical and have a host (may be empty for file
1016 // URLs) and a path. If it doesn't have these, we can't resolve relative
1017 // URLs off of it and will return the base as the output with an error flag.
1018 // Because it is canonical is should also be ASCII.
1020 // The query charset converter follows the same rules as CanonicalizeQuery.
1022 // Returns true on success. On failure, the output will be "something
1023 // reasonable" that will be consistent and valid, just probably not what
1024 // was intended by the web page author or caller.
1025 COMPONENT_EXPORT(URL)
1026 bool ResolveRelativeURL(const char* base_url,
1027 const Parsed& base_parsed,
1029 const char* relative_url,
1030 const Component& relative_component,
1031 CharsetConverter* query_converter,
1032 CanonOutput* output,
1033 Parsed* out_parsed);
1034 COMPONENT_EXPORT(URL)
1035 bool ResolveRelativeURL(const char* base_url,
1036 const Parsed& base_parsed,
1038 const char16_t* relative_url,
1039 const Component& relative_component,
1040 CharsetConverter* query_converter,
1041 CanonOutput* output,
1042 Parsed* out_parsed);
1046 #endif // URL_URL_CANON_H_