273f056841474ef1d6f420fc8b6bc5d65e42cb62
[platform/framework/web/chromium-efl.git] / url / url_canon.h
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.
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/strings/string16.h"
14 #include "url/third_party/mozilla/url_parse.h"
15
16 namespace url {
17
18 // Canonicalizer output -------------------------------------------------------
19
20 // Base class for the canonicalizer output, this maintains a buffer and
21 // supports simple resizing and append operations on it.
22 //
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
27 // manage.
28 template<typename T>
29 class CanonOutputT {
30  public:
31   CanonOutputT() : buffer_(NULL), buffer_len_(0), cur_len_(0) {
32   }
33   virtual ~CanonOutputT() {
34   }
35
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.
39   //
40   // The new size |sz| must be larger than buffer_len_.
41   virtual void Resize(int sz) = 0;
42
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];
47   }
48
49   // Sets the character at the given position. The given position MUST be less
50   // than the length().
51   inline void set(int offset, T ch) {
52     buffer_[offset] = ch;
53   }
54
55   // Returns the number of characters currently in the buffer.
56   inline int length() const {
57     return cur_len_;
58   }
59
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 {
66     return buffer_len_;
67   }
68
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
71   // length.
72   const T* data() const {
73     return buffer_;
74   }
75   T* data() {
76     return buffer_;
77   }
78
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.
83   //
84   // This MUST NOT be used to expand the size of the buffer beyond capacity().
85   void set_length(int new_len) {
86     cur_len_ = new_len;
87   }
88
89   // This is the most performance critical function, since it is called for
90   // every character.
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;
96       cur_len_++;
97       return;
98     }
99
100     // Grow the buffer to hold at least one more item. Hopefully we won't have
101     // to do this very often.
102     if (!Grow(1))
103       return;
104
105     // Actually do the insertion.
106     buffer_[cur_len_] = ch;
107     cur_len_++;
108   }
109
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_))
114         return;
115     }
116     for (int i = 0; i < str_len; i++)
117       buffer_[cur_len_ + i] = str[i];
118     cur_len_ += str_len;
119   }
120
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);
125   }
126
127  protected:
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_;
133     do {
134       if (new_len >= (1 << 30))  // Prevent overflow below.
135         return false;
136       new_len *= 2;
137     } while (new_len < buffer_len_ + min_additional);
138     Resize(new_len);
139     return true;
140   }
141
142   T* buffer_;
143   int buffer_len_;
144
145   // Used characters in the buffer.
146   int cur_len_;
147 };
148
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> {
154  public:
155   RawCanonOutputT() : CanonOutputT<T>() {
156     this->buffer_ = fixed_buffer_;
157     this->buffer_len_ = fixed_capacity;
158   }
159   ~RawCanonOutputT() override {
160     if (this->buffer_ != fixed_buffer_)
161       delete[] this->buffer_;
162   }
163
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;
172   }
173
174  protected:
175   T fixed_buffer_[fixed_capacity];
176 };
177
178 // Explicitely instantiate commonly used instatiations.
179 extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL))
180     CanonOutputT<char>;
181 extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL))
182     CanonOutputT<base::char16>;
183
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
186 // required.
187 typedef CanonOutputT<char> CanonOutput;
188 typedef CanonOutputT<base::char16> CanonOutputW;
189
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> {};
194
195 // Character set converter ----------------------------------------------------
196 //
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.
200 //
201 // Embedders will want to see the unit test for the ICU version.
202
203 class COMPONENT_EXPORT(URL) CharsetConverter {
204  public:
205   CharsetConverter() {}
206   virtual ~CharsetConverter() {}
207
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
212   // best it can.
213   //
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 "&#20320;") 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,
220                                 int input_len,
221                                 CanonOutput* output) = 0;
222 };
223
224 // Schemes --------------------------------------------------------------------
225
226 // Types of a scheme representing the requirements on the data represented by
227 // the authority component of a URL with the scheme.
228 enum SchemeType {
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,
233   // https, and ftp.
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
239   // stripped.
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.
244   SCHEME_WITH_HOST,
245   // A URL with the scheme doesn't have the authority component.
246   SCHEME_WITHOUT_AUTHORITY,
247 };
248
249 // Whitespace -----------------------------------------------------------------
250
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|.
255 //
256 // This should be called before parsing if whitespace removal is desired (which
257 // it normally is when you are canonicalizing).
258 //
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.
263 //
264 // Therefore, callers should not use the buffer, since it may actually be empty,
265 // use the computed pointer and |*output_len| instead.
266 //
267 // If |input| contained both removable whitespace and a raw `<` character,
268 // |potentially_dangling_markup| will be set to `true`. Otherwise, it will be
269 // left untouched.
270 COMPONENT_EXPORT(URL)
271 const char* RemoveURLWhitespace(const char* input,
272                                 int input_len,
273                                 CanonOutputT<char>* buffer,
274                                 int* output_len,
275                                 bool* potentially_dangling_markup);
276 COMPONENT_EXPORT(URL)
277 const base::char16* RemoveURLWhitespace(const base::char16* input,
278                                         int input_len,
279                                         CanonOutputT<base::char16>* buffer,
280                                         int* output_len,
281                                         bool* potentially_dangling_markup);
282
283 // IDN ------------------------------------------------------------------------
284
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.
287 //
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.
292 //
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);
296
297 // Piece-by-piece canonicalizers ----------------------------------------------
298 //
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.
303 //
304 // These functions all append to the output so they can be chained. Make sure
305 // the output is empty when you start.
306 //
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.
311
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.
314 //
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
318 // URLs.
319 //
320 // The 8-bit version requires UTF-8 encoding.
321 COMPONENT_EXPORT(URL)
322 bool CanonicalizeScheme(const char* spec,
323                         const Component& scheme,
324                         CanonOutput* output,
325                         Component* out_scheme);
326 COMPONENT_EXPORT(URL)
327 bool CanonicalizeScheme(const base::char16* spec,
328                         const Component& scheme,
329                         CanonOutput* output,
330                         Component* out_scheme);
331
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.
336 //
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.
340 //
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,
347                           CanonOutput* output,
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,
355                           CanonOutput* output,
356                           Component* out_username,
357                           Component* out_password);
358
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() {}
363
364   // Convenience function to test if family is an IP address.
365   bool IsIPAddress() const { return family == IPV4 || family == IPV6; }
366
367   // This field summarizes how the input was classified by the canonicalizer.
368   enum Family {
369     NEUTRAL,   // - Doesn't resemble an IP address. As far as the IP
370                //   canonicalizer is concerned, it should be treated as a
371                //   hostname.
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.
379   };
380   Family family;
381
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;
386
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.
390   Component out_host;
391
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];
396
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);
401   }
402 };
403
404
405 // Host.
406 //
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,
412                       CanonOutput* output,
413                       Component* out_host);
414 COMPONENT_EXPORT(URL)
415 bool CanonicalizeHost(const base::char16* spec,
416                       const Component& host,
417                       CanonOutput* output,
418                       Component* out_host);
419
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,
427                              CanonOutput* output,
428                              CanonHostInfo* host_info);
429 COMPONENT_EXPORT(URL)
430 void CanonicalizeHostVerbose(const base::char16* spec,
431                              const Component& host,
432                              CanonOutput* output,
433                              CanonHostInfo* host_info);
434
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.
439 //
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".
445 //
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
450 // the middle.
451 //
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);
463
464 // IP addresses.
465 //
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.
470 //
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,
477                            CanonOutput* output,
478                            CanonHostInfo* host_info);
479 COMPONENT_EXPORT(URL)
480 void CanonicalizeIPAddress(const base::char16* spec,
481                            const Component& host,
482                            CanonOutput* output,
483                            CanonHostInfo* host_info);
484
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.
488 //
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,
494                       CanonOutput* output,
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,
500                       CanonOutput* output,
501                       Component* out_port);
502
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);
507
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.
510 //
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,
520                       CanonOutput* output,
521                       Component* out_path);
522 COMPONENT_EXPORT(URL)
523 bool CanonicalizePath(const base::char16* spec,
524                       const Component& path,
525                       CanonOutput* output,
526                       Component* out_path);
527
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.
532 //
533 // The 8-bit version requires UTF-8 encoding.
534 COMPONENT_EXPORT(URL)
535 bool FileCanonicalizePath(const char* spec,
536                           const Component& path,
537                           CanonOutput* output,
538                           Component* out_path);
539 COMPONENT_EXPORT(URL)
540 bool FileCanonicalizePath(const base::char16* spec,
541                           const Component& path,
542                           CanonOutput* output,
543                           Component* out_path);
544
545 // Query: Prepends the ? if needed.
546 //
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.
551 //
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.
555 //
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,
561                        CanonOutput* output,
562                        Component* out_query);
563 COMPONENT_EXPORT(URL)
564 void CanonicalizeQuery(const base::char16* spec,
565                        const Component& query,
566                        CharsetConverter* converter,
567                        CanonOutput* output,
568                        Component* out_query);
569
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.
573 //
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,
579                      CanonOutput* output,
580                      Component* out_path);
581 COMPONENT_EXPORT(URL)
582 void CanonicalizeRef(const base::char16* spec,
583                      const Component& path,
584                      CanonOutput* output,
585                      Component* out_path);
586
587 // Full canonicalizer ---------------------------------------------------------
588 //
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.
592 //
593 // The output will be ASCII except the reference fragment, which may be UTF-8.
594 //
595 // The 8-bit versions require UTF-8 encoding.
596
597 // Use for standard URLs with authorities and paths.
598 COMPONENT_EXPORT(URL)
599 bool CanonicalizeStandardURL(const char* spec,
600                              int spec_len,
601                              const Parsed& parsed,
602                              SchemeType scheme_type,
603                              CharsetConverter* query_converter,
604                              CanonOutput* output,
605                              Parsed* new_parsed);
606 COMPONENT_EXPORT(URL)
607 bool CanonicalizeStandardURL(const base::char16* spec,
608                              int spec_len,
609                              const Parsed& parsed,
610                              SchemeType scheme_type,
611                              CharsetConverter* query_converter,
612                              CanonOutput* output,
613                              Parsed* new_parsed);
614
615 // Use for file URLs.
616 COMPONENT_EXPORT(URL)
617 bool CanonicalizeFileURL(const char* spec,
618                          int spec_len,
619                          const Parsed& parsed,
620                          CharsetConverter* query_converter,
621                          CanonOutput* output,
622                          Parsed* new_parsed);
623 COMPONENT_EXPORT(URL)
624 bool CanonicalizeFileURL(const base::char16* spec,
625                          int spec_len,
626                          const Parsed& parsed,
627                          CharsetConverter* query_converter,
628                          CanonOutput* output,
629                          Parsed* new_parsed);
630
631 // Use for filesystem URLs.
632 COMPONENT_EXPORT(URL)
633 bool CanonicalizeFileSystemURL(const char* spec,
634                                int spec_len,
635                                const Parsed& parsed,
636                                CharsetConverter* query_converter,
637                                CanonOutput* output,
638                                Parsed* new_parsed);
639 COMPONENT_EXPORT(URL)
640 bool CanonicalizeFileSystemURL(const base::char16* spec,
641                                int spec_len,
642                                const Parsed& parsed,
643                                CharsetConverter* query_converter,
644                                CanonOutput* output,
645                                Parsed* new_parsed);
646
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,
651                          int spec_len,
652                          const Parsed& parsed,
653                          CanonOutput* output,
654                          Parsed* new_parsed);
655 COMPONENT_EXPORT(URL)
656 bool CanonicalizePathURL(const base::char16* spec,
657                          int spec_len,
658                          const Parsed& parsed,
659                          CanonOutput* output,
660                          Parsed* new_parsed);
661
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,
669                            int spec_len,
670                            const Parsed& parsed,
671                            CanonOutput* output,
672                            Parsed* new_parsed);
673 COMPONENT_EXPORT(URL)
674 bool CanonicalizeMailtoURL(const base::char16* spec,
675                            int spec_len,
676                            const Parsed& parsed,
677                            CanonOutput* output,
678                            Parsed* new_parsed);
679
680 // Part replacer --------------------------------------------------------------
681
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).
687 //
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.
691 //
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
694 // modified.
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.
700   URLComponentSource()
701       : scheme(NULL),
702         username(NULL),
703         password(NULL),
704         host(NULL),
705         port(NULL),
706         path(NULL),
707         query(NULL),
708         ref(NULL) {
709   }
710
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),
717         host(default_value),
718         port(default_value),
719         path(default_value),
720         query(default_value),
721         ref(default_value) {
722   }
723
724   const CHAR* scheme;
725   const CHAR* username;
726   const CHAR* password;
727   const CHAR* host;
728   const CHAR* port;
729   const CHAR* path;
730   const CHAR* query;
731   const CHAR* ref;
732 };
733
734 // This structure encapsulates information on modifying a URL. Each component
735 // may either be left unchanged, replaced, or deleted.
736 //
737 // By default, each component is unchanged. For those components that should be
738 // modified, call either Set* or Clear* to modify it.
739 //
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!
742 //
743 // Prefer the 8-bit replacement version if possible since it is more efficient.
744 template<typename CHAR>
745 class Replacements {
746  public:
747   Replacements() {
748   }
749
750   // Scheme
751   void SetScheme(const CHAR* s, const Component& comp) {
752     sources_.scheme = s;
753     components_.scheme = comp;
754   }
755   // Note: we don't have a ClearScheme since this doesn't make any sense.
756   bool IsSchemeOverridden() const { return sources_.scheme != NULL; }
757
758   // Username
759   void SetUsername(const CHAR* s, const Component& comp) {
760     sources_.username = s;
761     components_.username = comp;
762   }
763   void ClearUsername() {
764     sources_.username = Placeholder();
765     components_.username = Component();
766   }
767   bool IsUsernameOverridden() const { return sources_.username != NULL; }
768
769   // Password
770   void SetPassword(const CHAR* s, const Component& comp) {
771     sources_.password = s;
772     components_.password = comp;
773   }
774   void ClearPassword() {
775     sources_.password = Placeholder();
776     components_.password = Component();
777   }
778   bool IsPasswordOverridden() const { return sources_.password != NULL; }
779
780   // Host
781   void SetHost(const CHAR* s, const Component& comp) {
782     sources_.host = s;
783     components_.host = comp;
784   }
785   void ClearHost() {
786     sources_.host = Placeholder();
787     components_.host = Component();
788   }
789   bool IsHostOverridden() const { return sources_.host != NULL; }
790
791   // Port
792   void SetPort(const CHAR* s, const Component& comp) {
793     sources_.port = s;
794     components_.port = comp;
795   }
796   void ClearPort() {
797     sources_.port = Placeholder();
798     components_.port = Component();
799   }
800   bool IsPortOverridden() const { return sources_.port != NULL; }
801
802   // Path
803   void SetPath(const CHAR* s, const Component& comp) {
804     sources_.path = s;
805     components_.path = comp;
806   }
807   void ClearPath() {
808     sources_.path = Placeholder();
809     components_.path = Component();
810   }
811   bool IsPathOverridden() const { return sources_.path != NULL; }
812
813   // Query
814   void SetQuery(const CHAR* s, const Component& comp) {
815     sources_.query = s;
816     components_.query = comp;
817   }
818   void ClearQuery() {
819     sources_.query = Placeholder();
820     components_.query = Component();
821   }
822   bool IsQueryOverridden() const { return sources_.query != NULL; }
823
824   // Ref
825   void SetRef(const CHAR* s, const Component& comp) {
826     sources_.ref = s;
827     components_.ref = comp;
828   }
829   void ClearRef() {
830     sources_.ref = Placeholder();
831     components_.ref = Component();
832   }
833   bool IsRefOverridden() const { return sources_.ref != NULL; }
834
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_; }
839
840  private:
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;
845     return &empty_cstr;
846   }
847
848   // We support three states:
849   //
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))
855   //
856   // We use a pointer to the empty string for the source when the component
857   // should be deleted.
858   URLComponentSource<CHAR> sources_;
859   Parsed components_;
860 };
861
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,
869                         CanonOutput* output,
870                         Parsed* new_parsed);
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,
877                         CanonOutput* output,
878                         Parsed* new_parsed);
879
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,
887                           CanonOutput* output,
888                           Parsed* new_parsed);
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,
894                           CanonOutput* output,
895                           Parsed* new_parsed);
896
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,
904                     CanonOutput* output,
905                     Parsed* new_parsed);
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,
911                     CanonOutput* output,
912                     Parsed* new_parsed);
913
914 // Path URLs can only have the scheme and path replaced. All other components
915 // will be ignored.
916 COMPONENT_EXPORT(URL)
917 bool ReplacePathURL(const char* base,
918                     const Parsed& base_parsed,
919                     const Replacements<char>& replacements,
920                     CanonOutput* output,
921                     Parsed* new_parsed);
922 COMPONENT_EXPORT(URL)
923 bool ReplacePathURL(const char* base,
924                     const Parsed& base_parsed,
925                     const Replacements<base::char16>& replacements,
926                     CanonOutput* output,
927                     Parsed* new_parsed);
928
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,
935                       CanonOutput* output,
936                       Parsed* new_parsed);
937 COMPONENT_EXPORT(URL)
938 bool ReplaceMailtoURL(const char* base,
939                       const Parsed& base_parsed,
940                       const Replacements<base::char16>& replacements,
941                       CanonOutput* output,
942                       Parsed* new_parsed);
943
944 // Relative URL ---------------------------------------------------------------
945
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).
952 //
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.
955 //
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,
961                    int fragment_len,
962                    bool is_base_hierarchical,
963                    bool* is_relative,
964                    Component* relative_component);
965 COMPONENT_EXPORT(URL)
966 bool IsRelativeURL(const char* base,
967                    const Parsed& base_parsed,
968                    const base::char16* fragment,
969                    int fragment_len,
970                    bool is_base_hierarchical,
971                    bool* is_relative,
972                    Component* relative_component);
973
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
977 // |out_parsed|.
978 //
979 // It also requires a flag indicating whether the base URL is a file: URL
980 // which triggers additional logic.
981 //
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.
986 //
987 // The query charset converter follows the same rules as CanonicalizeQuery.
988 //
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,
995                         bool base_is_file,
996                         const char* relative_url,
997                         const Component& relative_component,
998                         CharsetConverter* query_converter,
999                         CanonOutput* output,
1000                         Parsed* out_parsed);
1001 COMPONENT_EXPORT(URL)
1002 bool ResolveRelativeURL(const char* base_url,
1003                         const Parsed& base_parsed,
1004                         bool base_is_file,
1005                         const base::char16* relative_url,
1006                         const Component& relative_component,
1007                         CharsetConverter* query_converter,
1008                         CanonOutput* output,
1009                         Parsed* out_parsed);
1010
1011 }  // namespace url
1012
1013 #endif  // URL_URL_CANON_H_