1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef URL_URL_CANON_H_
6 #define URL_URL_CANON_H_
11 #include "base/component_export.h"
12 #include "base/export_template.h"
13 #include "base/strings/string16.h"
14 #include "url/third_party/mozilla/url_parse.h"
18 // Canonicalizer output -------------------------------------------------------
20 // Base class for the canonicalizer output, this maintains a buffer and
21 // supports simple resizing and append operations on it.
23 // It is VERY IMPORTANT that no virtual function calls be made on the common
24 // code path. We only have two virtual function calls, the destructor and a
25 // resize function that is called when the existing buffer is not big enough.
26 // The derived class is then in charge of setting up our buffer which we will
31 CanonOutputT() : buffer_(NULL), buffer_len_(0), cur_len_(0) {
33 virtual ~CanonOutputT() {
36 // Implemented to resize the buffer. This function should update the buffer
37 // pointer to point to the new buffer, and any old data up to |cur_len_| in
38 // the buffer must be copied over.
40 // The new size |sz| must be larger than buffer_len_.
41 virtual void Resize(int sz) = 0;
43 // Accessor for returning a character at a given position. The input offset
44 // must be in the valid range.
45 inline T at(int offset) const {
46 return buffer_[offset];
49 // Sets the character at the given position. The given position MUST be less
51 inline void set(int offset, T ch) {
55 // Returns the number of characters currently in the buffer.
56 inline int length() const {
60 // Returns the current capacity of the buffer. The length() is the number of
61 // characters that have been declared to be written, but the capacity() is
62 // the number that can be written without reallocation. If the caller must
63 // write many characters at once, it can make sure there is enough capacity,
64 // write the data, then use set_size() to declare the new length().
65 int capacity() const {
69 // Called by the user of this class to get the output. The output will NOT
70 // be NULL-terminated. Call length() to get the
72 const T* data() const {
79 // Shortens the URL to the new length. Used for "backing up" when processing
80 // relative paths. This can also be used if an external function writes a lot
81 // of data to the buffer (when using the "Raw" version below) beyond the end,
82 // to declare the new length.
84 // This MUST NOT be used to expand the size of the buffer beyond capacity().
85 void set_length(int new_len) {
89 // This is the most performance critical function, since it is called for
91 void push_back(T ch) {
92 // In VC2005, putting this common case first speeds up execution
93 // dramatically because this branch is predicted as taken.
94 if (cur_len_ < buffer_len_) {
95 buffer_[cur_len_] = ch;
100 // Grow the buffer to hold at least one more item. Hopefully we won't have
101 // to do this very often.
105 // Actually do the insertion.
106 buffer_[cur_len_] = ch;
110 // Appends the given string to the output.
111 void Append(const T* str, int str_len) {
112 if (cur_len_ + str_len > buffer_len_) {
113 if (!Grow(cur_len_ + str_len - buffer_len_))
116 for (int i = 0; i < str_len; i++)
117 buffer_[cur_len_ + i] = str[i];
121 void ReserveSizeIfNeeded(int estimated_size) {
122 // Reserve a bit extra to account for escaped chars.
123 if (estimated_size > buffer_len_)
124 Resize(estimated_size + 8);
128 // Grows the given buffer so that it can fit at least |min_additional|
129 // characters. Returns true if the buffer could be resized, false on OOM.
130 bool Grow(int min_additional) {
131 static const int kMinBufferLen = 16;
132 int new_len = (buffer_len_ == 0) ? kMinBufferLen : buffer_len_;
134 if (new_len >= (1 << 30)) // Prevent overflow below.
137 } while (new_len < buffer_len_ + min_additional);
145 // Used characters in the buffer.
149 // Simple implementation of the CanonOutput using new[]. This class
150 // also supports a static buffer so if it is allocated on the stack, most
151 // URLs can be canonicalized with no heap allocations.
152 template<typename T, int fixed_capacity = 1024>
153 class RawCanonOutputT : public CanonOutputT<T> {
155 RawCanonOutputT() : CanonOutputT<T>() {
156 this->buffer_ = fixed_buffer_;
157 this->buffer_len_ = fixed_capacity;
159 ~RawCanonOutputT() override {
160 if (this->buffer_ != fixed_buffer_)
161 delete[] this->buffer_;
164 void Resize(int sz) override {
165 T* new_buf = new T[sz];
166 memcpy(new_buf, this->buffer_,
167 sizeof(T) * (this->cur_len_ < sz ? this->cur_len_ : sz));
168 if (this->buffer_ != fixed_buffer_)
169 delete[] this->buffer_;
170 this->buffer_ = new_buf;
171 this->buffer_len_ = sz;
175 T fixed_buffer_[fixed_capacity];
178 // Explicitely instantiate commonly used instatiations.
179 extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL))
181 extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL))
182 CanonOutputT<base::char16>;
184 // Normally, all canonicalization output is in narrow characters. We support
185 // the templates so it can also be used internally if a wide buffer is
187 typedef CanonOutputT<char> CanonOutput;
188 typedef CanonOutputT<base::char16> CanonOutputW;
190 template<int fixed_capacity>
191 class RawCanonOutput : public RawCanonOutputT<char, fixed_capacity> {};
192 template<int fixed_capacity>
193 class RawCanonOutputW : public RawCanonOutputT<base::char16, fixed_capacity> {};
195 // Character set converter ----------------------------------------------------
197 // Converts query strings into a custom encoding. The embedder can supply an
198 // implementation of this class to interface with their own character set
199 // conversion libraries.
201 // Embedders will want to see the unit test for the ICU version.
203 class COMPONENT_EXPORT(URL) CharsetConverter {
205 CharsetConverter() {}
206 virtual ~CharsetConverter() {}
208 // Converts the given input string from UTF-16 to whatever output format the
209 // converter supports. This is used only for the query encoding conversion,
210 // which does not fail. Instead, the converter should insert "invalid
211 // character" characters in the output for invalid sequences, and do the
214 // If the input contains a character not representable in the output
215 // character set, the converter should append the HTML entity sequence in
216 // decimal, (such as "你") with escaping of the ampersand, number
217 // sign, and semicolon (in the previous example it would be
218 // "%26%2320320%3B"). This rule is based on what IE does in this situation.
219 virtual void ConvertFromUTF16(const base::char16* input,
221 CanonOutput* output) = 0;
224 // Schemes --------------------------------------------------------------------
226 // Types of a scheme representing the requirements on the data represented by
227 // the authority component of a URL with the scheme.
229 // The authority component of a URL with the scheme has the form
230 // "username:password@host:port". The username and password entries are
231 // optional; the host may not be empty. The default value of the port can be
232 // omitted in serialization. This type occurs with network schemes like http,
234 SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION,
235 // The authority component of a URL with the scheme has the form "host:port",
236 // and does not include username or password. The default value of the port
237 // can be omitted in serialization. Used by inner URLs of filesystem URLs of
238 // origins with network hosts, from which the username and password are
240 SCHEME_WITH_HOST_AND_PORT,
241 // The authority component of an URL with the scheme has the form "host", and
242 // does not include port, username, or password. Used when the hosts are not
243 // network addresses; for example, schemes used internally by the browser.
245 // A URL with the scheme doesn't have the authority component.
246 SCHEME_WITHOUT_AUTHORITY,
249 // Whitespace -----------------------------------------------------------------
251 // Searches for whitespace that should be removed from the middle of URLs, and
252 // removes it. Removed whitespace are tabs and newlines, but NOT spaces. Spaces
253 // are preserved, which is what most browsers do. A pointer to the output will
254 // be returned, and the length of that output will be in |output_len|.
256 // This should be called before parsing if whitespace removal is desired (which
257 // it normally is when you are canonicalizing).
259 // If no whitespace is removed, this function will not use the buffer and will
260 // return a pointer to the input, to avoid the extra copy. If modification is
261 // required, the given |buffer| will be used and the returned pointer will
262 // point to the beginning of the buffer.
264 // Therefore, callers should not use the buffer, since it may actually be empty,
265 // use the computed pointer and |*output_len| instead.
267 // If |input| contained both removable whitespace and a raw `<` character,
268 // |potentially_dangling_markup| will be set to `true`. Otherwise, it will be
270 COMPONENT_EXPORT(URL)
271 const char* RemoveURLWhitespace(const char* input,
273 CanonOutputT<char>* buffer,
275 bool* potentially_dangling_markup);
276 COMPONENT_EXPORT(URL)
277 const base::char16* RemoveURLWhitespace(const base::char16* input,
279 CanonOutputT<base::char16>* buffer,
281 bool* potentially_dangling_markup);
283 // IDN ------------------------------------------------------------------------
285 // Converts the Unicode input representing a hostname to ASCII using IDN rules.
286 // The output must fall in the ASCII range, but will be encoded in UTF-16.
288 // On success, the output will be filled with the ASCII host name and it will
289 // return true. Unlike most other canonicalization functions, this assumes that
290 // the output is empty. The beginning of the host will be at offset 0, and
291 // the length of the output will be set to the length of the new host name.
293 // On error, returns false. The output in this case is undefined.
294 COMPONENT_EXPORT(URL)
295 bool IDNToASCII(const base::char16* src, int src_len, CanonOutputW* output);
297 // Piece-by-piece canonicalizers ----------------------------------------------
299 // These individual canonicalizers append the canonicalized versions of the
300 // corresponding URL component to the given std::string. The spec and the
301 // previously-identified range of that component are the input. The range of
302 // the canonicalized component will be written to the output component.
304 // These functions all append to the output so they can be chained. Make sure
305 // the output is empty when you start.
307 // These functions returns boolean values indicating success. On failure, they
308 // will attempt to write something reasonable to the output so that, if
309 // displayed to the user, they will recognise it as something that's messed up.
310 // Nothing more should ever be done with these invalid URLs, however.
312 // Scheme: Appends the scheme and colon to the URL. The output component will
313 // indicate the range of characters up to but not including the colon.
315 // Canonical URLs always have a scheme. If the scheme is not present in the
316 // input, this will just write the colon to indicate an empty scheme. Does not
317 // append slashes which will be needed before any authority components for most
320 // The 8-bit version requires UTF-8 encoding.
321 COMPONENT_EXPORT(URL)
322 bool CanonicalizeScheme(const char* spec,
323 const Component& scheme,
325 Component* out_scheme);
326 COMPONENT_EXPORT(URL)
327 bool CanonicalizeScheme(const base::char16* spec,
328 const Component& scheme,
330 Component* out_scheme);
332 // User info: username/password. If present, this will add the delimiters so
333 // the output will be "<username>:<password>@" or "<username>@". Empty
334 // username/password pairs, or empty passwords, will get converted to
335 // nonexistent in the canonical version.
337 // The components for the username and password refer to ranges in the
338 // respective source strings. Usually, these will be the same string, which
339 // is legal as long as the two components don't overlap.
341 // The 8-bit version requires UTF-8 encoding.
342 COMPONENT_EXPORT(URL)
343 bool CanonicalizeUserInfo(const char* username_source,
344 const Component& username,
345 const char* password_source,
346 const Component& password,
348 Component* out_username,
349 Component* out_password);
350 COMPONENT_EXPORT(URL)
351 bool CanonicalizeUserInfo(const base::char16* username_source,
352 const Component& username,
353 const base::char16* password_source,
354 const Component& password,
356 Component* out_username,
357 Component* out_password);
359 // This structure holds detailed state exported from the IP/Host canonicalizers.
360 // Additional fields may be added as callers require them.
361 struct CanonHostInfo {
362 CanonHostInfo() : family(NEUTRAL), num_ipv4_components(0), out_host() {}
364 // Convenience function to test if family is an IP address.
365 bool IsIPAddress() const { return family == IPV4 || family == IPV6; }
367 // This field summarizes how the input was classified by the canonicalizer.
369 NEUTRAL, // - Doesn't resemble an IP address. As far as the IP
370 // canonicalizer is concerned, it should be treated as a
372 BROKEN, // - Almost an IP, but was not canonicalized. This could be an
373 // IPv4 address where truncation occurred, or something
374 // containing the special characters :[] which did not parse
375 // as an IPv6 address. Never attempt to connect to this
376 // address, because it might actually succeed!
377 IPV4, // - Successfully canonicalized as an IPv4 address.
378 IPV6, // - Successfully canonicalized as an IPv6 address.
382 // If |family| is IPV4, then this is the number of nonempty dot-separated
383 // components in the input text, from 1 to 4. If |family| is not IPV4,
384 // this value is undefined.
385 int num_ipv4_components;
387 // Location of host within the canonicalized output.
388 // CanonicalizeIPAddress() only sets this field if |family| is IPV4 or IPV6.
389 // CanonicalizeHostVerbose() always sets it.
392 // |address| contains the parsed IP Address (if any) in its first
393 // AddressLength() bytes, in network order. If IsIPAddress() is false
394 // AddressLength() will return zero and the content of |address| is undefined.
395 unsigned char address[16];
397 // Convenience function to calculate the length of an IP address corresponding
398 // to the current IP version in |family|, if any. For use with |address|.
399 int AddressLength() const {
400 return family == IPV4 ? 4 : (family == IPV6 ? 16 : 0);
407 // The 8-bit version requires UTF-8 encoding. Use this version when you only
408 // need to know whether canonicalization succeeded.
409 COMPONENT_EXPORT(URL)
410 bool CanonicalizeHost(const char* spec,
411 const Component& host,
413 Component* out_host);
414 COMPONENT_EXPORT(URL)
415 bool CanonicalizeHost(const base::char16* spec,
416 const Component& host,
418 Component* out_host);
420 // Extended version of CanonicalizeHost, which returns additional information.
421 // Use this when you need to know whether the hostname was an IP address.
422 // A successful return is indicated by host_info->family != BROKEN. See the
423 // definition of CanonHostInfo above for details.
424 COMPONENT_EXPORT(URL)
425 void CanonicalizeHostVerbose(const char* spec,
426 const Component& host,
428 CanonHostInfo* host_info);
429 COMPONENT_EXPORT(URL)
430 void CanonicalizeHostVerbose(const base::char16* spec,
431 const Component& host,
433 CanonHostInfo* host_info);
435 // Canonicalizes a string according to the host canonicalization rules. Unlike
436 // CanonicalizeHost, this will not check for IP addresses which can change the
437 // meaning (and canonicalization) of the components. This means it is possible
438 // to call this for sub-components of a host name without corruption.
440 // As an example, "01.02.03.04.com" is a canonical hostname. If you called
441 // CanonicalizeHost on the substring "01.02.03.04" it will get "fixed" to
442 // "1.2.3.4" which will produce an invalid host name when reassembled. This
443 // can happen more than one might think because all numbers by themselves are
444 // considered IP addresses; so "5" canonicalizes to "0.0.0.5".
446 // Be careful: Because Punycode works on each dot-separated substring as a
447 // unit, you should only pass this function substrings that represent complete
448 // dot-separated subcomponents of the original host. Even if you have ASCII
449 // input, percent-escaped characters will have different meanings if split in
452 // Returns true if the host was valid. This function will treat a 0-length
453 // host as valid (because it's designed to be used for substrings) while the
454 // full version above will mark empty hosts as broken.
455 COMPONENT_EXPORT(URL)
456 bool CanonicalizeHostSubstring(const char* spec,
457 const Component& host,
458 CanonOutput* output);
459 COMPONENT_EXPORT(URL)
460 bool CanonicalizeHostSubstring(const base::char16* spec,
461 const Component& host,
462 CanonOutput* output);
466 // Tries to interpret the given host name as an IPv4 or IPv6 address. If it is
467 // an IP address, it will canonicalize it as such, appending it to |output|.
468 // Additional status information is returned via the |*host_info| parameter.
469 // See the definition of CanonHostInfo above for details.
471 // This is called AUTOMATICALLY from the host canonicalizer, which ensures that
472 // the input is unescaped and name-prepped, etc. It should not normally be
473 // necessary or wise to call this directly.
474 COMPONENT_EXPORT(URL)
475 void CanonicalizeIPAddress(const char* spec,
476 const Component& host,
478 CanonHostInfo* host_info);
479 COMPONENT_EXPORT(URL)
480 void CanonicalizeIPAddress(const base::char16* spec,
481 const Component& host,
483 CanonHostInfo* host_info);
485 // Port: this function will add the colon for the port if a port is present.
486 // The caller can pass PORT_UNSPECIFIED as the
487 // default_port_for_scheme argument if there is no default port.
489 // The 8-bit version requires UTF-8 encoding.
490 COMPONENT_EXPORT(URL)
491 bool CanonicalizePort(const char* spec,
492 const Component& port,
493 int default_port_for_scheme,
495 Component* out_port);
496 COMPONENT_EXPORT(URL)
497 bool CanonicalizePort(const base::char16* spec,
498 const Component& port,
499 int default_port_for_scheme,
501 Component* out_port);
503 // Returns the default port for the given canonical scheme, or PORT_UNSPECIFIED
504 // if the scheme is unknown.
505 COMPONENT_EXPORT(URL)
506 int DefaultPortForScheme(const char* scheme, int scheme_len);
508 // Path. If the input does not begin in a slash (including if the input is
509 // empty), we'll prepend a slash to the path to make it canonical.
511 // The 8-bit version assumes UTF-8 encoding, but does not verify the validity
512 // of the UTF-8 (i.e., you can have invalid UTF-8 sequences, invalid
513 // characters, etc.). Normally, URLs will come in as UTF-16, so this isn't
514 // an issue. Somebody giving us an 8-bit path is responsible for generating
515 // the path that the server expects (we'll escape high-bit characters), so
516 // if something is invalid, it's their problem.
517 COMPONENT_EXPORT(URL)
518 bool CanonicalizePath(const char* spec,
519 const Component& path,
521 Component* out_path);
522 COMPONENT_EXPORT(URL)
523 bool CanonicalizePath(const base::char16* spec,
524 const Component& path,
526 Component* out_path);
528 // Canonicalizes the input as a file path. This is like CanonicalizePath except
529 // that it also handles Windows drive specs. For example, the path can begin
530 // with "c|\" and it will get properly canonicalized to "C:/".
531 // The string will be appended to |*output| and |*out_path| will be updated.
533 // The 8-bit version requires UTF-8 encoding.
534 COMPONENT_EXPORT(URL)
535 bool FileCanonicalizePath(const char* spec,
536 const Component& path,
538 Component* out_path);
539 COMPONENT_EXPORT(URL)
540 bool FileCanonicalizePath(const base::char16* spec,
541 const Component& path,
543 Component* out_path);
545 // Query: Prepends the ? if needed.
547 // The 8-bit version requires the input to be UTF-8 encoding. Incorrectly
548 // encoded characters (in UTF-8 or UTF-16) will be replaced with the Unicode
549 // "invalid character." This function can not fail, we always just try to do
550 // our best for crazy input here since web pages can set it themselves.
552 // This will convert the given input into the output encoding that the given
553 // character set converter object provides. The converter will only be called
554 // if necessary, for ASCII input, no conversions are necessary.
556 // The converter can be NULL. In this case, the output encoding will be UTF-8.
557 COMPONENT_EXPORT(URL)
558 void CanonicalizeQuery(const char* spec,
559 const Component& query,
560 CharsetConverter* converter,
562 Component* out_query);
563 COMPONENT_EXPORT(URL)
564 void CanonicalizeQuery(const base::char16* spec,
565 const Component& query,
566 CharsetConverter* converter,
568 Component* out_query);
570 // Ref: Prepends the # if needed. The output will be UTF-8 (this is the only
571 // canonicalizer that does not produce ASCII output). The output is
572 // guaranteed to be valid UTF-8.
574 // This function will not fail. If the input is invalid UTF-8/UTF-16, we'll use
575 // the "Unicode replacement character" for the confusing bits and copy the rest.
576 COMPONENT_EXPORT(URL)
577 void CanonicalizeRef(const char* spec,
578 const Component& path,
580 Component* out_path);
581 COMPONENT_EXPORT(URL)
582 void CanonicalizeRef(const base::char16* spec,
583 const Component& path,
585 Component* out_path);
587 // Full canonicalizer ---------------------------------------------------------
589 // These functions replace any string contents, rather than append as above.
590 // See the above piece-by-piece functions for information specific to
591 // canonicalizing individual components.
593 // The output will be ASCII except the reference fragment, which may be UTF-8.
595 // The 8-bit versions require UTF-8 encoding.
597 // Use for standard URLs with authorities and paths.
598 COMPONENT_EXPORT(URL)
599 bool CanonicalizeStandardURL(const char* spec,
601 const Parsed& parsed,
602 SchemeType scheme_type,
603 CharsetConverter* query_converter,
606 COMPONENT_EXPORT(URL)
607 bool CanonicalizeStandardURL(const base::char16* spec,
609 const Parsed& parsed,
610 SchemeType scheme_type,
611 CharsetConverter* query_converter,
615 // Use for file URLs.
616 COMPONENT_EXPORT(URL)
617 bool CanonicalizeFileURL(const char* spec,
619 const Parsed& parsed,
620 CharsetConverter* query_converter,
623 COMPONENT_EXPORT(URL)
624 bool CanonicalizeFileURL(const base::char16* spec,
626 const Parsed& parsed,
627 CharsetConverter* query_converter,
631 // Use for filesystem URLs.
632 COMPONENT_EXPORT(URL)
633 bool CanonicalizeFileSystemURL(const char* spec,
635 const Parsed& parsed,
636 CharsetConverter* query_converter,
639 COMPONENT_EXPORT(URL)
640 bool CanonicalizeFileSystemURL(const base::char16* spec,
642 const Parsed& parsed,
643 CharsetConverter* query_converter,
647 // Use for path URLs such as javascript. This does not modify the path in any
648 // way, for example, by escaping it.
649 COMPONENT_EXPORT(URL)
650 bool CanonicalizePathURL(const char* spec,
652 const Parsed& parsed,
655 COMPONENT_EXPORT(URL)
656 bool CanonicalizePathURL(const base::char16* spec,
658 const Parsed& parsed,
662 // Use for mailto URLs. This "canonicalizes" the URL into a path and query
663 // component. It does not attempt to merge "to" fields. It uses UTF-8 for
664 // the query encoding if there is a query. This is because a mailto URL is
665 // really intended for an external mail program, and the encoding of a page,
666 // etc. which would influence a query encoding normally are irrelevant.
667 COMPONENT_EXPORT(URL)
668 bool CanonicalizeMailtoURL(const char* spec,
670 const Parsed& parsed,
673 COMPONENT_EXPORT(URL)
674 bool CanonicalizeMailtoURL(const base::char16* spec,
676 const Parsed& parsed,
680 // Part replacer --------------------------------------------------------------
682 // Internal structure used for storing separate strings for each component.
683 // The basic canonicalization functions use this structure internally so that
684 // component replacement (different strings for different components) can be
685 // treated on the same code path as regular canonicalization (the same string
686 // for each component).
688 // A Parsed structure usually goes along with this. Those components identify
689 // offsets within these strings, so that they can all be in the same string,
690 // or spread arbitrarily across different ones.
692 // This structures does not own any data. It is the caller's responsibility to
693 // ensure that the data the pointers point to stays in scope and is not
695 template<typename CHAR>
696 struct URLComponentSource {
697 // Constructor normally used by callers wishing to replace components. This
698 // will make them all NULL, which is no replacement. The caller would then
699 // override the components they want to replace.
711 // Constructor normally used internally to initialize all the components to
712 // point to the same spec.
713 explicit URLComponentSource(const CHAR* default_value)
714 : scheme(default_value),
715 username(default_value),
716 password(default_value),
720 query(default_value),
725 const CHAR* username;
726 const CHAR* password;
734 // This structure encapsulates information on modifying a URL. Each component
735 // may either be left unchanged, replaced, or deleted.
737 // By default, each component is unchanged. For those components that should be
738 // modified, call either Set* or Clear* to modify it.
740 // The string passed to Set* functions DOES NOT GET COPIED AND MUST BE KEPT
741 // IN SCOPE BY THE CALLER for as long as this object exists!
743 // Prefer the 8-bit replacement version if possible since it is more efficient.
744 template<typename CHAR>
751 void SetScheme(const CHAR* s, const Component& comp) {
753 components_.scheme = comp;
755 // Note: we don't have a ClearScheme since this doesn't make any sense.
756 bool IsSchemeOverridden() const { return sources_.scheme != NULL; }
759 void SetUsername(const CHAR* s, const Component& comp) {
760 sources_.username = s;
761 components_.username = comp;
763 void ClearUsername() {
764 sources_.username = Placeholder();
765 components_.username = Component();
767 bool IsUsernameOverridden() const { return sources_.username != NULL; }
770 void SetPassword(const CHAR* s, const Component& comp) {
771 sources_.password = s;
772 components_.password = comp;
774 void ClearPassword() {
775 sources_.password = Placeholder();
776 components_.password = Component();
778 bool IsPasswordOverridden() const { return sources_.password != NULL; }
781 void SetHost(const CHAR* s, const Component& comp) {
783 components_.host = comp;
786 sources_.host = Placeholder();
787 components_.host = Component();
789 bool IsHostOverridden() const { return sources_.host != NULL; }
792 void SetPort(const CHAR* s, const Component& comp) {
794 components_.port = comp;
797 sources_.port = Placeholder();
798 components_.port = Component();
800 bool IsPortOverridden() const { return sources_.port != NULL; }
803 void SetPath(const CHAR* s, const Component& comp) {
805 components_.path = comp;
808 sources_.path = Placeholder();
809 components_.path = Component();
811 bool IsPathOverridden() const { return sources_.path != NULL; }
814 void SetQuery(const CHAR* s, const Component& comp) {
816 components_.query = comp;
819 sources_.query = Placeholder();
820 components_.query = Component();
822 bool IsQueryOverridden() const { return sources_.query != NULL; }
825 void SetRef(const CHAR* s, const Component& comp) {
827 components_.ref = comp;
830 sources_.ref = Placeholder();
831 components_.ref = Component();
833 bool IsRefOverridden() const { return sources_.ref != NULL; }
835 // Getters for the internal data. See the variables below for how the
836 // information is encoded.
837 const URLComponentSource<CHAR>& sources() const { return sources_; }
838 const Parsed& components() const { return components_; }
841 // Returns a pointer to a static empty string that is used as a placeholder
842 // to indicate a component should be deleted (see below).
843 const CHAR* Placeholder() {
844 static const CHAR empty_cstr = 0;
848 // We support three states:
850 // Action | Source Component
851 // -----------------------+--------------------------------------------------
852 // Don't change component | NULL (unused)
853 // Replace component | (replacement string) (replacement component)
854 // Delete component | (non-NULL) (invalid component: (0,-1))
856 // We use a pointer to the empty string for the source when the component
857 // should be deleted.
858 URLComponentSource<CHAR> sources_;
862 // The base must be an 8-bit canonical URL.
863 COMPONENT_EXPORT(URL)
864 bool ReplaceStandardURL(const char* base,
865 const Parsed& base_parsed,
866 const Replacements<char>& replacements,
867 SchemeType scheme_type,
868 CharsetConverter* query_converter,
871 COMPONENT_EXPORT(URL)
872 bool ReplaceStandardURL(const char* base,
873 const Parsed& base_parsed,
874 const Replacements<base::char16>& replacements,
875 SchemeType scheme_type,
876 CharsetConverter* query_converter,
880 // Filesystem URLs can only have the path, query, or ref replaced.
881 // All other components will be ignored.
882 COMPONENT_EXPORT(URL)
883 bool ReplaceFileSystemURL(const char* base,
884 const Parsed& base_parsed,
885 const Replacements<char>& replacements,
886 CharsetConverter* query_converter,
889 COMPONENT_EXPORT(URL)
890 bool ReplaceFileSystemURL(const char* base,
891 const Parsed& base_parsed,
892 const Replacements<base::char16>& replacements,
893 CharsetConverter* query_converter,
897 // Replacing some parts of a file URL is not permitted. Everything except
898 // the host, path, query, and ref will be ignored.
899 COMPONENT_EXPORT(URL)
900 bool ReplaceFileURL(const char* base,
901 const Parsed& base_parsed,
902 const Replacements<char>& replacements,
903 CharsetConverter* query_converter,
906 COMPONENT_EXPORT(URL)
907 bool ReplaceFileURL(const char* base,
908 const Parsed& base_parsed,
909 const Replacements<base::char16>& replacements,
910 CharsetConverter* query_converter,
914 // Path URLs can only have the scheme and path replaced. All other components
916 COMPONENT_EXPORT(URL)
917 bool ReplacePathURL(const char* base,
918 const Parsed& base_parsed,
919 const Replacements<char>& replacements,
922 COMPONENT_EXPORT(URL)
923 bool ReplacePathURL(const char* base,
924 const Parsed& base_parsed,
925 const Replacements<base::char16>& replacements,
929 // Mailto URLs can only have the scheme, path, and query replaced.
930 // All other components will be ignored.
931 COMPONENT_EXPORT(URL)
932 bool ReplaceMailtoURL(const char* base,
933 const Parsed& base_parsed,
934 const Replacements<char>& replacements,
937 COMPONENT_EXPORT(URL)
938 bool ReplaceMailtoURL(const char* base,
939 const Parsed& base_parsed,
940 const Replacements<base::char16>& replacements,
944 // Relative URL ---------------------------------------------------------------
946 // Given an input URL or URL fragment |fragment|, determines if it is a
947 // relative or absolute URL and places the result into |*is_relative|. If it is
948 // relative, the relevant portion of the URL will be placed into
949 // |*relative_component| (there may have been trimmed whitespace, for example).
950 // This value is passed to ResolveRelativeURL. If the input is not relative,
951 // this value is UNDEFINED (it may be changed by the function).
953 // Returns true on success (we successfully determined the URL is relative or
954 // not). Failure means that the combination of URLs doesn't make any sense.
956 // The base URL should always be canonical, therefore is ASCII.
957 COMPONENT_EXPORT(URL)
958 bool IsRelativeURL(const char* base,
959 const Parsed& base_parsed,
960 const char* fragment,
962 bool is_base_hierarchical,
964 Component* relative_component);
965 COMPONENT_EXPORT(URL)
966 bool IsRelativeURL(const char* base,
967 const Parsed& base_parsed,
968 const base::char16* fragment,
970 bool is_base_hierarchical,
972 Component* relative_component);
974 // Given a canonical parsed source URL, a URL fragment known to be relative,
975 // and the identified relevant portion of the relative URL (computed by
976 // IsRelativeURL), this produces a new parsed canonical URL in |output| and
979 // It also requires a flag indicating whether the base URL is a file: URL
980 // which triggers additional logic.
982 // The base URL should be canonical and have a host (may be empty for file
983 // URLs) and a path. If it doesn't have these, we can't resolve relative
984 // URLs off of it and will return the base as the output with an error flag.
985 // Because it is canonical is should also be ASCII.
987 // The query charset converter follows the same rules as CanonicalizeQuery.
989 // Returns true on success. On failure, the output will be "something
990 // reasonable" that will be consistent and valid, just probably not what
991 // was intended by the web page author or caller.
992 COMPONENT_EXPORT(URL)
993 bool ResolveRelativeURL(const char* base_url,
994 const Parsed& base_parsed,
996 const char* relative_url,
997 const Component& relative_component,
998 CharsetConverter* query_converter,
1000 Parsed* out_parsed);
1001 COMPONENT_EXPORT(URL)
1002 bool ResolveRelativeURL(const char* base_url,
1003 const Parsed& base_parsed,
1005 const base::char16* relative_url,
1006 const Component& relative_component,
1007 CharsetConverter* query_converter,
1008 CanonOutput* output,
1009 Parsed* out_parsed);
1013 #endif // URL_URL_CANON_H_