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