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