Upload upstream chromium 120.0.6099.5
[platform/framework/web/chromium-efl.git] / url / url_canon.h
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/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"
18
19 namespace url {
20
21 // Canonicalizer output -------------------------------------------------------
22
23 // Base class for the canonicalizer output, this maintains a buffer and
24 // supports simple resizing and append operations on it.
25 //
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
30 // manage.
31 template <typename T>
32 class CanonOutputT {
33  public:
34   CanonOutputT() = default;
35   virtual ~CanonOutputT() = default;
36
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.
40   //
41   // The new size |sz| must be larger than buffer_len_.
42   virtual void Resize(size_t sz) = 0;
43
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]; }
47
48   // Sets the character at the given position. The given position MUST be less
49   // than the length().
50   inline void set(size_t offset, T ch) { buffer_[offset] = ch; }
51
52   // Returns the number of characters currently in the buffer.
53   inline size_t length() const { return cur_len_; }
54
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_; }
61
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());
65   }
66
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
69   // length.
70   const T* data() const { return buffer_; }
71   T* data() { return buffer_; }
72
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.
77   //
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; }
80
81   // This is the most performance critical function, since it is called for
82   // every character.
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;
88       cur_len_++;
89       return;
90     }
91
92     // Grow the buffer to hold at least one more item. Hopefully we won't have
93     // to do this very often.
94     if (!Grow(1))
95       return;
96
97     // Actually do the insertion.
98     buffer_[cur_len_] = ch;
99     cur_len_++;
100   }
101
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_)))
106         return;
107     }
108     memcpy(buffer_ + cur_len_, str, str_len * sizeof(T));
109     cur_len_ += str_len;
110   }
111
112   void Append(std::basic_string_view<T> str) { Append(str.data(), str.size()); }
113
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());
118   }
119
120  protected:
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_;
126     do {
127       if (new_len >= (1 << 30))  // Prevent overflow below.
128         return false;
129       new_len *= 2;
130     } while (new_len < buffer_len_ + min_additional);
131     Resize(new_len);
132     return true;
133   }
134
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;
139
140   // Used characters in the buffer.
141   size_t cur_len_ = 0;
142 };
143
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> {
149  public:
150   RawCanonOutputT() : CanonOutputT<T>() {
151     this->buffer_ = fixed_buffer_;
152     this->buffer_len_ = fixed_capacity;
153   }
154   ~RawCanonOutputT() override {
155     if (this->buffer_ != fixed_buffer_)
156       delete[] this->buffer_;
157   }
158
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;
167   }
168
169  protected:
170   T fixed_buffer_[fixed_capacity];
171 };
172
173 // Explicitely instantiate commonly used instatiations.
174 extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL))
175     CanonOutputT<char>;
176 extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL))
177     CanonOutputT<char16_t>;
178
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
181 // required.
182 typedef CanonOutputT<char> CanonOutput;
183 typedef CanonOutputT<char16_t> CanonOutputW;
184
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> {};
189
190 // Character set converter ----------------------------------------------------
191 //
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.
195 //
196 // Embedders will want to see the unit test for the ICU version.
197
198 class COMPONENT_EXPORT(URL) CharsetConverter {
199  public:
200   CharsetConverter() {}
201   virtual ~CharsetConverter() {}
202
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
207   // best it can.
208   //
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 "&#20320;") 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,
215                                 int input_len,
216                                 CanonOutput* output) = 0;
217 };
218
219 // Schemes --------------------------------------------------------------------
220
221 // Types of a scheme representing the requirements on the data represented by
222 // the authority component of a URL with the scheme.
223 enum SchemeType {
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,
228   // https, and ftp.
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
234   // stripped.
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.
239   SCHEME_WITH_HOST,
240   // A URL with the scheme doesn't have the authority component.
241   SCHEME_WITHOUT_AUTHORITY,
242 };
243
244 // Whitespace -----------------------------------------------------------------
245
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|.
250 //
251 // This should be called before parsing if whitespace removal is desired (which
252 // it normally is when you are canonicalizing).
253 //
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.
258 //
259 // Therefore, callers should not use the buffer, since it may actually be empty,
260 // use the computed pointer and |*output_len| instead.
261 //
262 // If |input| contained both removable whitespace and a raw `<` character,
263 // |potentially_dangling_markup| will be set to `true`. Otherwise, it will be
264 // left untouched.
265 COMPONENT_EXPORT(URL)
266 const char* RemoveURLWhitespace(const char* input,
267                                 int input_len,
268                                 CanonOutputT<char>* buffer,
269                                 int* output_len,
270                                 bool* potentially_dangling_markup);
271 COMPONENT_EXPORT(URL)
272 const char16_t* RemoveURLWhitespace(const char16_t* input,
273                                     int input_len,
274                                     CanonOutputT<char16_t>* buffer,
275                                     int* output_len,
276                                     bool* potentially_dangling_markup);
277
278 // IDN ------------------------------------------------------------------------
279
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.
282 //
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.
287 //
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);
291
292 // Piece-by-piece canonicalizers ----------------------------------------------
293 //
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.
298 //
299 // These functions all append to the output so they can be chained. Make sure
300 // the output is empty when you start.
301 //
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.
306
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.
309 //
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
313 // URLs.
314 //
315 // The 8-bit version requires UTF-8 encoding.
316 COMPONENT_EXPORT(URL)
317 bool CanonicalizeScheme(const char* spec,
318                         const Component& scheme,
319                         CanonOutput* output,
320                         Component* out_scheme);
321 COMPONENT_EXPORT(URL)
322 bool CanonicalizeScheme(const char16_t* spec,
323                         const Component& scheme,
324                         CanonOutput* output,
325                         Component* out_scheme);
326
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.
331 //
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.
335 //
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,
342                           CanonOutput* output,
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,
350                           CanonOutput* output,
351                           Component* out_username,
352                           Component* out_password);
353
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() {}
358
359   // Convenience function to test if family is an IP address.
360   bool IsIPAddress() const { return family == IPV4 || family == IPV6; }
361
362   // This field summarizes how the input was classified by the canonicalizer.
363   enum Family {
364     NEUTRAL,  // - Doesn't resemble an IP address. As far as the IP
365               //   canonicalizer is concerned, it should be treated as a
366               //   hostname.
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.
374   };
375   Family family;
376
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;
381
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.
385   Component out_host;
386
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];
391
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);
396   }
397 };
398
399 // Host.
400 //
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,
406                       CanonOutput* output,
407                       Component* out_host);
408 COMPONENT_EXPORT(URL)
409 bool CanonicalizeHost(const char16_t* spec,
410                       const Component& host,
411                       CanonOutput* output,
412                       Component* out_host);
413
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,
421                              CanonOutput* output,
422                              CanonHostInfo* host_info);
423 COMPONENT_EXPORT(URL)
424 void CanonicalizeHostVerbose(const char16_t* spec,
425                              const Component& host,
426                              CanonOutput* output,
427                              CanonHostInfo* host_info);
428
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.
433 //
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".
439 //
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
444 // the middle.
445 //
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);
457
458 // IP addresses.
459 //
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.
464 //
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,
471                            CanonOutput* output,
472                            CanonHostInfo* host_info);
473 COMPONENT_EXPORT(URL)
474 void CanonicalizeIPAddress(const char16_t* spec,
475                            const Component& host,
476                            CanonOutput* output,
477                            CanonHostInfo* host_info);
478
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.
482 //
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,
488                       CanonOutput* output,
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,
494                       CanonOutput* output,
495                       Component* out_port);
496
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);
501
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.
504 //
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,
514                       CanonOutput* output,
515                       Component* out_path);
516 COMPONENT_EXPORT(URL)
517 bool CanonicalizePath(const char16_t* spec,
518                       const Component& path,
519                       CanonOutput* output,
520                       Component* out_path);
521
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,
527                              CanonOutput* output,
528                              Component* out_path);
529 COMPONENT_EXPORT(URL)
530 bool CanonicalizePartialPath(const char16_t* spec,
531                              const Component& path,
532                              CanonOutput* output,
533                              Component* out_path);
534
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.
539 //
540 // The 8-bit version requires UTF-8 encoding.
541 COMPONENT_EXPORT(URL)
542 bool FileCanonicalizePath(const char* spec,
543                           const Component& path,
544                           CanonOutput* output,
545                           Component* out_path);
546 COMPONENT_EXPORT(URL)
547 bool FileCanonicalizePath(const char16_t* spec,
548                           const Component& path,
549                           CanonOutput* output,
550                           Component* out_path);
551
552 // Query: Prepends the ? if needed.
553 //
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.
558 //
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.
562 //
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,
568                        CanonOutput* output,
569                        Component* out_query);
570 COMPONENT_EXPORT(URL)
571 void CanonicalizeQuery(const char16_t* spec,
572                        const Component& query,
573                        CharsetConverter* converter,
574                        CanonOutput* output,
575                        Component* out_query);
576
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.
580 //
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,
586                      CanonOutput* output,
587                      Component* out_path);
588 COMPONENT_EXPORT(URL)
589 void CanonicalizeRef(const char16_t* spec,
590                      const Component& path,
591                      CanonOutput* output,
592                      Component* out_path);
593
594 // Full canonicalizer ---------------------------------------------------------
595 //
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.
599 //
600 // The output will be ASCII except the reference fragment, which may be UTF-8.
601 //
602 // The 8-bit versions require UTF-8 encoding.
603
604 // Use for standard URLs with authorities and paths.
605 COMPONENT_EXPORT(URL)
606 bool CanonicalizeStandardURL(const char* spec,
607                              int spec_len,
608                              const Parsed& parsed,
609                              SchemeType scheme_type,
610                              CharsetConverter* query_converter,
611                              CanonOutput* output,
612                              Parsed* new_parsed);
613 COMPONENT_EXPORT(URL)
614 bool CanonicalizeStandardURL(const char16_t* spec,
615                              int spec_len,
616                              const Parsed& parsed,
617                              SchemeType scheme_type,
618                              CharsetConverter* query_converter,
619                              CanonOutput* output,
620                              Parsed* new_parsed);
621
622 // Use for file URLs.
623 COMPONENT_EXPORT(URL)
624 bool CanonicalizeFileURL(const char* spec,
625                          int spec_len,
626                          const Parsed& parsed,
627                          CharsetConverter* query_converter,
628                          CanonOutput* output,
629                          Parsed* new_parsed);
630 COMPONENT_EXPORT(URL)
631 bool CanonicalizeFileURL(const char16_t* spec,
632                          int spec_len,
633                          const Parsed& parsed,
634                          CharsetConverter* query_converter,
635                          CanonOutput* output,
636                          Parsed* new_parsed);
637
638 // Use for filesystem URLs.
639 COMPONENT_EXPORT(URL)
640 bool CanonicalizeFileSystemURL(const char* spec,
641                                int spec_len,
642                                const Parsed& parsed,
643                                CharsetConverter* query_converter,
644                                CanonOutput* output,
645                                Parsed* new_parsed);
646 COMPONENT_EXPORT(URL)
647 bool CanonicalizeFileSystemURL(const char16_t* spec,
648                                int spec_len,
649                                const Parsed& parsed,
650                                CharsetConverter* query_converter,
651                                CanonOutput* output,
652                                Parsed* new_parsed);
653
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,
658                          int spec_len,
659                          const Parsed& parsed,
660                          CanonOutput* output,
661                          Parsed* new_parsed);
662 COMPONENT_EXPORT(URL)
663 bool CanonicalizePathURL(const char16_t* spec,
664                          int spec_len,
665                          const Parsed& parsed,
666                          CanonOutput* output,
667                          Parsed* new_parsed);
668
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,
674                              CanonOutput* output,
675                              Component* new_component);
676 COMPONENT_EXPORT(URL)
677 void CanonicalizePathURLPath(const char16_t* source,
678                              const Component& component,
679                              CanonOutput* output,
680                              Component* new_component);
681
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,
689                            int spec_len,
690                            const Parsed& parsed,
691                            CanonOutput* output,
692                            Parsed* new_parsed);
693 COMPONENT_EXPORT(URL)
694 bool CanonicalizeMailtoURL(const char16_t* spec,
695                            int spec_len,
696                            const Parsed& parsed,
697                            CanonOutput* output,
698                            Parsed* new_parsed);
699
700 // Part replacer --------------------------------------------------------------
701
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).
707 //
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.
711 //
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
714 // modified.
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.
720   URLComponentSource()
721       : scheme(nullptr),
722         username(nullptr),
723         password(nullptr),
724         host(nullptr),
725         port(nullptr),
726         path(nullptr),
727         query(nullptr),
728         ref(nullptr) {}
729
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),
736         host(default_value),
737         port(default_value),
738         path(default_value),
739         query(default_value),
740         ref(default_value) {}
741
742   // This field is not a raw_ptr<> because it was filtered by the rewriter for:
743   // #addr-of
744   RAW_PTR_EXCLUSION const CHAR* scheme;
745   // This field is not a raw_ptr<> because it was filtered by the rewriter for:
746   // #addr-of
747   RAW_PTR_EXCLUSION const CHAR* username;
748   // This field is not a raw_ptr<> because it was filtered by the rewriter for:
749   // #addr-of
750   RAW_PTR_EXCLUSION const CHAR* password;
751   // This field is not a raw_ptr<> because it was filtered by the rewriter for:
752   // #addr-of
753   RAW_PTR_EXCLUSION const CHAR* host;
754   // This field is not a raw_ptr<> because it was filtered by the rewriter for:
755   // #addr-of
756   RAW_PTR_EXCLUSION const CHAR* port;
757   // This field is not a raw_ptr<> because it was filtered by the rewriter for:
758   // #addr-of
759   RAW_PTR_EXCLUSION const CHAR* path;
760   // This field is not a raw_ptr<> because it was filtered by the rewriter for:
761   // #addr-of
762   RAW_PTR_EXCLUSION const CHAR* query;
763   // This field is not a raw_ptr<> because it was filtered by the rewriter for:
764   // #addr-of
765   RAW_PTR_EXCLUSION const CHAR* ref;
766 };
767
768 // This structure encapsulates information on modifying a URL. Each component
769 // may either be left unchanged, replaced, or deleted.
770 //
771 // By default, each component is unchanged. For those components that should be
772 // modified, call either Set* or Clear* to modify it.
773 //
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!
776 //
777 // Prefer the 8-bit replacement version if possible since it is more efficient.
778 template <typename CHAR>
779 class Replacements {
780  public:
781   Replacements() {}
782
783   // Scheme
784   void SetScheme(const CHAR* s, const Component& comp) {
785     sources_.scheme = s;
786     components_.scheme = comp;
787   }
788   // Note: we don't have a ClearScheme since this doesn't make any sense.
789   bool IsSchemeOverridden() const { return sources_.scheme != NULL; }
790
791   // Username
792   void SetUsername(const CHAR* s, const Component& comp) {
793     sources_.username = s;
794     components_.username = comp;
795   }
796   void ClearUsername() {
797     sources_.username = Placeholder();
798     components_.username = Component();
799   }
800   bool IsUsernameOverridden() const { return sources_.username != NULL; }
801
802   // Password
803   void SetPassword(const CHAR* s, const Component& comp) {
804     sources_.password = s;
805     components_.password = comp;
806   }
807   void ClearPassword() {
808     sources_.password = Placeholder();
809     components_.password = Component();
810   }
811   bool IsPasswordOverridden() const { return sources_.password != NULL; }
812
813   // Host
814   void SetHost(const CHAR* s, const Component& comp) {
815     sources_.host = s;
816     components_.host = comp;
817   }
818   void ClearHost() {
819     sources_.host = Placeholder();
820     components_.host = Component();
821   }
822   bool IsHostOverridden() const { return sources_.host != NULL; }
823
824   // Port
825   void SetPort(const CHAR* s, const Component& comp) {
826     sources_.port = s;
827     components_.port = comp;
828   }
829   void ClearPort() {
830     sources_.port = Placeholder();
831     components_.port = Component();
832   }
833   bool IsPortOverridden() const { return sources_.port != NULL; }
834
835   // Path
836   void SetPath(const CHAR* s, const Component& comp) {
837     sources_.path = s;
838     components_.path = comp;
839   }
840   void ClearPath() {
841     sources_.path = Placeholder();
842     components_.path = Component();
843   }
844   bool IsPathOverridden() const { return sources_.path != NULL; }
845
846   // Query
847   void SetQuery(const CHAR* s, const Component& comp) {
848     sources_.query = s;
849     components_.query = comp;
850   }
851   void ClearQuery() {
852     sources_.query = Placeholder();
853     components_.query = Component();
854   }
855   bool IsQueryOverridden() const { return sources_.query != NULL; }
856
857   // Ref
858   void SetRef(const CHAR* s, const Component& comp) {
859     sources_.ref = s;
860     components_.ref = comp;
861   }
862   void ClearRef() {
863     sources_.ref = Placeholder();
864     components_.ref = Component();
865   }
866   bool IsRefOverridden() const { return sources_.ref != NULL; }
867
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_; }
872
873  private:
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;
878     return &empty_cstr;
879   }
880
881   // We support three states:
882   //
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))
888   //
889   // We use a pointer to the empty string for the source when the component
890   // should be deleted.
891   URLComponentSource<CHAR> sources_;
892   Parsed components_;
893 };
894
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,
902                         CanonOutput* output,
903                         Parsed* new_parsed);
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,
910                         CanonOutput* output,
911                         Parsed* new_parsed);
912
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,
920                           CanonOutput* output,
921                           Parsed* new_parsed);
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,
927                           CanonOutput* output,
928                           Parsed* new_parsed);
929
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,
937                     CanonOutput* output,
938                     Parsed* new_parsed);
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,
944                     CanonOutput* output,
945                     Parsed* new_parsed);
946
947 // Path URLs can only have the scheme and path replaced. All other components
948 // will be ignored.
949 COMPONENT_EXPORT(URL)
950 bool ReplacePathURL(const char* base,
951                     const Parsed& base_parsed,
952                     const Replacements<char>& replacements,
953                     CanonOutput* output,
954                     Parsed* new_parsed);
955 COMPONENT_EXPORT(URL)
956 bool ReplacePathURL(const char* base,
957                     const Parsed& base_parsed,
958                     const Replacements<char16_t>& replacements,
959                     CanonOutput* output,
960                     Parsed* new_parsed);
961
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,
968                       CanonOutput* output,
969                       Parsed* new_parsed);
970 COMPONENT_EXPORT(URL)
971 bool ReplaceMailtoURL(const char* base,
972                       const Parsed& base_parsed,
973                       const Replacements<char16_t>& replacements,
974                       CanonOutput* output,
975                       Parsed* new_parsed);
976
977 // Relative URL ---------------------------------------------------------------
978
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).
985 //
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.
988 //
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,
994                    int fragment_len,
995                    bool is_base_hierarchical,
996                    bool* is_relative,
997                    Component* relative_component);
998 COMPONENT_EXPORT(URL)
999 bool IsRelativeURL(const char* base,
1000                    const Parsed& base_parsed,
1001                    const char16_t* fragment,
1002                    int fragment_len,
1003                    bool is_base_hierarchical,
1004                    bool* is_relative,
1005                    Component* relative_component);
1006
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
1010 // |out_parsed|.
1011 //
1012 // It also requires a flag indicating whether the base URL is a file: URL
1013 // which triggers additional logic.
1014 //
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.
1019 //
1020 // The query charset converter follows the same rules as CanonicalizeQuery.
1021 //
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,
1028                         bool base_is_file,
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,
1037                         bool base_is_file,
1038                         const char16_t* relative_url,
1039                         const Component& relative_component,
1040                         CharsetConverter* query_converter,
1041                         CanonOutput* output,
1042                         Parsed* out_parsed);
1043
1044 }  // namespace url
1045
1046 #endif  // URL_URL_CANON_H_