Upload upstream chromium 67.0.3396
[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/export_template.h"
12 #include "base/strings/string16.h"
13 #include "url/third_party/mozilla/url_parse.h"
14 #include "url/url_export.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   virtual ~RawCanonOutputT() {
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(URL_EXPORT) CanonOutputT<char>;
180 extern template class EXPORT_TEMPLATE_DECLARE(URL_EXPORT)
181     CanonOutputT<base::char16>;
182
183 // Normally, all canonicalization output is in narrow characters. We support
184 // the templates so it can also be used internally if a wide buffer is
185 // required.
186 typedef CanonOutputT<char> CanonOutput;
187 typedef CanonOutputT<base::char16> CanonOutputW;
188
189 template<int fixed_capacity>
190 class RawCanonOutput : public RawCanonOutputT<char, fixed_capacity> {};
191 template<int fixed_capacity>
192 class RawCanonOutputW : public RawCanonOutputT<base::char16, fixed_capacity> {};
193
194 // Character set converter ----------------------------------------------------
195 //
196 // Converts query strings into a custom encoding. The embedder can supply an
197 // implementation of this class to interface with their own character set
198 // conversion libraries.
199 //
200 // Embedders will want to see the unit test for the ICU version.
201
202 class URL_EXPORT CharsetConverter {
203  public:
204   CharsetConverter() {}
205   virtual ~CharsetConverter() {}
206
207   // Converts the given input string from UTF-16 to whatever output format the
208   // converter supports. This is used only for the query encoding conversion,
209   // which does not fail. Instead, the converter should insert "invalid
210   // character" characters in the output for invalid sequences, and do the
211   // best it can.
212   //
213   // If the input contains a character not representable in the output
214   // character set, the converter should append the HTML entity sequence in
215   // decimal, (such as "&#20320;") with escaping of the ampersand, number
216   // sign, and semicolon (in the previous example it would be
217   // "%26%2320320%3B"). This rule is based on what IE does in this situation.
218   virtual void ConvertFromUTF16(const base::char16* input,
219                                 int input_len,
220                                 CanonOutput* output) = 0;
221 };
222
223 // Schemes --------------------------------------------------------------------
224
225 // Types of a scheme representing the requirements on the data represented by
226 // the authority component of a URL with the scheme.
227 enum SchemeType {
228   // The authority component of a URL with the scheme has the form
229   // "username:password@host:port". The username and password entries are
230   // optional; the host may not be empty. The default value of the port can be
231   // omitted in serialization. This type occurs with network schemes like http,
232   // https, and ftp.
233   SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION,
234   // The authority component of a URL with the scheme has the form "host:port",
235   // and does not include username or password. The default value of the port
236   // can be omitted in serialization. Used by inner URLs of filesystem URLs of
237   // origins with network hosts, from which the username and password are
238   // stripped.
239   SCHEME_WITH_HOST_AND_PORT,
240   // The authority component of an URL with the scheme has the form "host", and
241   // does not include port, username, or password. Used when the hosts are not
242   // network addresses; for example, schemes used internally by the browser.
243   SCHEME_WITH_HOST,
244   // A URL with the scheme doesn't have the authority component.
245   SCHEME_WITHOUT_AUTHORITY,
246 };
247
248 // Whitespace -----------------------------------------------------------------
249
250 // Searches for whitespace that should be removed from the middle of URLs, and
251 // removes it. Removed whitespace are tabs and newlines, but NOT spaces. Spaces
252 // are preserved, which is what most browsers do. A pointer to the output will
253 // be returned, and the length of that output will be in |output_len|.
254 //
255 // This should be called before parsing if whitespace removal is desired (which
256 // it normally is when you are canonicalizing).
257 //
258 // If no whitespace is removed, this function will not use the buffer and will
259 // return a pointer to the input, to avoid the extra copy. If modification is
260 // required, the given |buffer| will be used and the returned pointer will
261 // point to the beginning of the buffer.
262 //
263 // Therefore, callers should not use the buffer, since it may actually be empty,
264 // use the computed pointer and |*output_len| instead.
265 //
266 // If |input| contained both removable whitespace and a raw `<` character,
267 // |potentially_dangling_markup| will be set to `true`. Otherwise, it will be
268 // left untouched.
269 URL_EXPORT const char* RemoveURLWhitespace(const char* input,
270                                            int input_len,
271                                            CanonOutputT<char>* buffer,
272                                            int* output_len,
273                                            bool* potentially_dangling_markup);
274 URL_EXPORT const base::char16* RemoveURLWhitespace(
275     const base::char16* input,
276     int input_len,
277     CanonOutputT<base::char16>* buffer,
278     int* output_len,
279     bool* potentially_dangling_markup);
280
281 // IDN ------------------------------------------------------------------------
282
283 // Converts the Unicode input representing a hostname to ASCII using IDN rules.
284 // The output must fall in the ASCII range, but will be encoded in UTF-16.
285 //
286 // On success, the output will be filled with the ASCII host name and it will
287 // return true. Unlike most other canonicalization functions, this assumes that
288 // the output is empty. The beginning of the host will be at offset 0, and
289 // the length of the output will be set to the length of the new host name.
290 //
291 // On error, returns false. The output in this case is undefined.
292 URL_EXPORT bool IDNToASCII(const base::char16* src,
293                            int src_len,
294                            CanonOutputW* output);
295
296 // Piece-by-piece canonicalizers ----------------------------------------------
297 //
298 // These individual canonicalizers append the canonicalized versions of the
299 // corresponding URL component to the given std::string. The spec and the
300 // previously-identified range of that component are the input. The range of
301 // the canonicalized component will be written to the output component.
302 //
303 // These functions all append to the output so they can be chained. Make sure
304 // the output is empty when you start.
305 //
306 // These functions returns boolean values indicating success. On failure, they
307 // will attempt to write something reasonable to the output so that, if
308 // displayed to the user, they will recognise it as something that's messed up.
309 // Nothing more should ever be done with these invalid URLs, however.
310
311 // Scheme: Appends the scheme and colon to the URL. The output component will
312 // indicate the range of characters up to but not including the colon.
313 //
314 // Canonical URLs always have a scheme. If the scheme is not present in the
315 // input, this will just write the colon to indicate an empty scheme. Does not
316 // append slashes which will be needed before any authority components for most
317 // URLs.
318 //
319 // The 8-bit version requires UTF-8 encoding.
320 URL_EXPORT bool CanonicalizeScheme(const char* spec,
321                                    const Component& scheme,
322                                    CanonOutput* output,
323                                    Component* out_scheme);
324 URL_EXPORT bool CanonicalizeScheme(const base::char16* spec,
325                                    const Component& scheme,
326                                    CanonOutput* output,
327                                    Component* out_scheme);
328
329 // User info: username/password. If present, this will add the delimiters so
330 // the output will be "<username>:<password>@" or "<username>@". Empty
331 // username/password pairs, or empty passwords, will get converted to
332 // nonexistent in the canonical version.
333 //
334 // The components for the username and password refer to ranges in the
335 // respective source strings. Usually, these will be the same string, which
336 // is legal as long as the two components don't overlap.
337 //
338 // The 8-bit version requires UTF-8 encoding.
339 URL_EXPORT bool CanonicalizeUserInfo(const char* username_source,
340                                      const Component& username,
341                                      const char* password_source,
342                                      const Component& password,
343                                      CanonOutput* output,
344                                      Component* out_username,
345                                      Component* out_password);
346 URL_EXPORT bool CanonicalizeUserInfo(const base::char16* username_source,
347                                      const Component& username,
348                                      const base::char16* password_source,
349                                      const Component& password,
350                                      CanonOutput* output,
351                                      Component* out_username,
352                                      Component* out_password);
353
354 // This structure holds detailed state exported from the IP/Host canonicalizers.
355 // Additional fields may be added as callers require them.
356 struct CanonHostInfo {
357   CanonHostInfo() : family(NEUTRAL), num_ipv4_components(0), out_host() {}
358
359   // Convenience function to test if family is an IP address.
360   bool IsIPAddress() const { return family == IPV4 || family == IPV6; }
361
362   // This field summarizes how the input was classified by the canonicalizer.
363   enum Family {
364     NEUTRAL,   // - Doesn't resemble an IP address. As far as the IP
365                //   canonicalizer is concerned, it should be treated as a
366                //   hostname.
367     BROKEN,    // - Almost an IP, but was not canonicalized. This could be an
368                //   IPv4 address where truncation occurred, or something
369                //   containing the special characters :[] which did not parse
370                //   as an IPv6 address. Never attempt to connect to this
371                //   address, because it might actually succeed!
372     IPV4,      // - Successfully canonicalized as an IPv4 address.
373     IPV6,      // - Successfully canonicalized as an IPv6 address.
374   };
375   Family family;
376
377   // If |family| is IPV4, then this is the number of nonempty dot-separated
378   // components in the input text, from 1 to 4. If |family| is not IPV4,
379   // this value is undefined.
380   int num_ipv4_components;
381
382   // Location of host within the canonicalized output.
383   // CanonicalizeIPAddress() only sets this field if |family| is IPV4 or IPV6.
384   // CanonicalizeHostVerbose() always sets it.
385   Component out_host;
386
387   // |address| contains the parsed IP Address (if any) in its first
388   // AddressLength() bytes, in network order. If IsIPAddress() is false
389   // AddressLength() will return zero and the content of |address| is undefined.
390   unsigned char address[16];
391
392   // Convenience function to calculate the length of an IP address corresponding
393   // to the current IP version in |family|, if any. For use with |address|.
394   int AddressLength() const {
395     return family == IPV4 ? 4 : (family == IPV6 ? 16 : 0);
396   }
397 };
398
399
400 // Host.
401 //
402 // The 8-bit version requires UTF-8 encoding. Use this version when you only
403 // need to know whether canonicalization succeeded.
404 URL_EXPORT bool CanonicalizeHost(const char* spec,
405                                  const Component& host,
406                                  CanonOutput* output,
407                                  Component* out_host);
408 URL_EXPORT bool CanonicalizeHost(const base::char16* spec,
409                                  const Component& host,
410                                  CanonOutput* output,
411                                  Component* out_host);
412
413 // Extended version of CanonicalizeHost, which returns additional information.
414 // Use this when you need to know whether the hostname was an IP address.
415 // A successful return is indicated by host_info->family != BROKEN. See the
416 // definition of CanonHostInfo above for details.
417 URL_EXPORT void CanonicalizeHostVerbose(const char* spec,
418                                         const Component& host,
419                                         CanonOutput* output,
420                                         CanonHostInfo* host_info);
421 URL_EXPORT void CanonicalizeHostVerbose(const base::char16* spec,
422                                         const Component& host,
423                                         CanonOutput* output,
424                                         CanonHostInfo* host_info);
425
426 // Canonicalizes a string according to the host canonicalization rules. Unlike
427 // CanonicalizeHost, this will not check for IP addresses which can change the
428 // meaning (and canonicalization) of the components. This means it is possible
429 // to call this for sub-components of a host name without corruption.
430 //
431 // As an example, "01.02.03.04.com" is a canonical hostname. If you called
432 // CanonicalizeHost on the substring "01.02.03.04" it will get "fixed" to
433 // "1.2.3.4" which will produce an invalid host name when reassembled. This
434 // can happen more than one might think because all numbers by themselves are
435 // considered IP addresses; so "5" canonicalizes to "0.0.0.5".
436 //
437 // Be careful: Because Punycode works on each dot-separated substring as a
438 // unit, you should only pass this function substrings that represent complete
439 // dot-separated subcomponents of the original host. Even if you have ASCII
440 // input, percent-escaped characters will have different meanings if split in
441 // the middle.
442 //
443 // Returns true if the host was valid. This function will treat a 0-length
444 // host as valid (because it's designed to be used for substrings) while the
445 // full version above will mark empty hosts as broken.
446 URL_EXPORT bool CanonicalizeHostSubstring(const char* spec,
447                                           const Component& host,
448                                           CanonOutput* output);
449 URL_EXPORT bool CanonicalizeHostSubstring(const base::char16* spec,
450                                           const Component& host,
451                                           CanonOutput* output);
452
453 // IP addresses.
454 //
455 // Tries to interpret the given host name as an IPv4 or IPv6 address. If it is
456 // an IP address, it will canonicalize it as such, appending it to |output|.
457 // Additional status information is returned via the |*host_info| parameter.
458 // See the definition of CanonHostInfo above for details.
459 //
460 // This is called AUTOMATICALLY from the host canonicalizer, which ensures that
461 // the input is unescaped and name-prepped, etc. It should not normally be
462 // necessary or wise to call this directly.
463 URL_EXPORT void CanonicalizeIPAddress(const char* spec,
464                                       const Component& host,
465                                       CanonOutput* output,
466                                       CanonHostInfo* host_info);
467 URL_EXPORT void CanonicalizeIPAddress(const base::char16* spec,
468                                       const Component& host,
469                                       CanonOutput* output,
470                                       CanonHostInfo* host_info);
471
472 // Port: this function will add the colon for the port if a port is present.
473 // The caller can pass PORT_UNSPECIFIED as the
474 // default_port_for_scheme argument if there is no default port.
475 //
476 // The 8-bit version requires UTF-8 encoding.
477 URL_EXPORT bool CanonicalizePort(const char* spec,
478                                  const Component& port,
479                                  int default_port_for_scheme,
480                                  CanonOutput* output,
481                                  Component* out_port);
482 URL_EXPORT bool CanonicalizePort(const base::char16* 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.
490 URL_EXPORT int DefaultPortForScheme(const char* scheme, int scheme_len);
491
492 // Path. If the input does not begin in a slash (including if the input is
493 // empty), we'll prepend a slash to the path to make it canonical.
494 //
495 // The 8-bit version assumes UTF-8 encoding, but does not verify the validity
496 // of the UTF-8 (i.e., you can have invalid UTF-8 sequences, invalid
497 // characters, etc.). Normally, URLs will come in as UTF-16, so this isn't
498 // an issue. Somebody giving us an 8-bit path is responsible for generating
499 // the path that the server expects (we'll escape high-bit characters), so
500 // if something is invalid, it's their problem.
501 URL_EXPORT bool CanonicalizePath(const char* spec,
502                                  const Component& path,
503                                  CanonOutput* output,
504                                  Component* out_path);
505 URL_EXPORT bool CanonicalizePath(const base::char16* spec,
506                                  const Component& path,
507                                  CanonOutput* output,
508                                  Component* out_path);
509
510 // Canonicalizes the input as a file path. This is like CanonicalizePath except
511 // that it also handles Windows drive specs. For example, the path can begin
512 // with "c|\" and it will get properly canonicalized to "C:/".
513 // The string will be appended to |*output| and |*out_path| will be updated.
514 //
515 // The 8-bit version requires UTF-8 encoding.
516 URL_EXPORT bool FileCanonicalizePath(const char* spec,
517                                      const Component& path,
518                                      CanonOutput* output,
519                                      Component* out_path);
520 URL_EXPORT bool FileCanonicalizePath(const base::char16* spec,
521                                      const Component& path,
522                                      CanonOutput* output,
523                                      Component* out_path);
524
525 // Query: Prepends the ? if needed.
526 //
527 // The 8-bit version requires the input to be UTF-8 encoding. Incorrectly
528 // encoded characters (in UTF-8 or UTF-16) will be replaced with the Unicode
529 // "invalid character." This function can not fail, we always just try to do
530 // our best for crazy input here since web pages can set it themselves.
531 //
532 // This will convert the given input into the output encoding that the given
533 // character set converter object provides. The converter will only be called
534 // if necessary, for ASCII input, no conversions are necessary.
535 //
536 // The converter can be NULL. In this case, the output encoding will be UTF-8.
537 URL_EXPORT void CanonicalizeQuery(const char* spec,
538                                   const Component& query,
539                                   CharsetConverter* converter,
540                                   CanonOutput* output,
541                                   Component* out_query);
542 URL_EXPORT void CanonicalizeQuery(const base::char16* spec,
543                                   const Component& query,
544                                   CharsetConverter* converter,
545                                   CanonOutput* output,
546                                   Component* out_query);
547
548 // Ref: Prepends the # if needed. The output will be UTF-8 (this is the only
549 // canonicalizer that does not produce ASCII output). The output is
550 // guaranteed to be valid UTF-8.
551 //
552 // This function will not fail. If the input is invalid UTF-8/UTF-16, we'll use
553 // the "Unicode replacement character" for the confusing bits and copy the rest.
554 URL_EXPORT void CanonicalizeRef(const char* spec,
555                                 const Component& path,
556                                 CanonOutput* output,
557                                 Component* out_path);
558 URL_EXPORT void CanonicalizeRef(const base::char16* spec,
559                                 const Component& path,
560                                 CanonOutput* output,
561                                 Component* out_path);
562
563 // Full canonicalizer ---------------------------------------------------------
564 //
565 // These functions replace any string contents, rather than append as above.
566 // See the above piece-by-piece functions for information specific to
567 // canonicalizing individual components.
568 //
569 // The output will be ASCII except the reference fragment, which may be UTF-8.
570 //
571 // The 8-bit versions require UTF-8 encoding.
572
573 // Use for standard URLs with authorities and paths.
574 URL_EXPORT bool CanonicalizeStandardURL(const char* spec,
575                                         int spec_len,
576                                         const Parsed& parsed,
577                                         SchemeType scheme_type,
578                                         CharsetConverter* query_converter,
579                                         CanonOutput* output,
580                                         Parsed* new_parsed);
581 URL_EXPORT bool CanonicalizeStandardURL(const base::char16* spec,
582                                         int spec_len,
583                                         const Parsed& parsed,
584                                         SchemeType scheme_type,
585                                         CharsetConverter* query_converter,
586                                         CanonOutput* output,
587                                         Parsed* new_parsed);
588
589 // Use for file URLs.
590 URL_EXPORT bool CanonicalizeFileURL(const char* spec,
591                                     int spec_len,
592                                     const Parsed& parsed,
593                                     CharsetConverter* query_converter,
594                                     CanonOutput* output,
595                                     Parsed* new_parsed);
596 URL_EXPORT bool CanonicalizeFileURL(const base::char16* spec,
597                                     int spec_len,
598                                     const Parsed& parsed,
599                                     CharsetConverter* query_converter,
600                                     CanonOutput* output,
601                                     Parsed* new_parsed);
602
603 // Use for filesystem URLs.
604 URL_EXPORT bool CanonicalizeFileSystemURL(const char* spec,
605                                           int spec_len,
606                                           const Parsed& parsed,
607                                           CharsetConverter* query_converter,
608                                           CanonOutput* output,
609                                           Parsed* new_parsed);
610 URL_EXPORT bool CanonicalizeFileSystemURL(const base::char16* spec,
611                                           int spec_len,
612                                           const Parsed& parsed,
613                                           CharsetConverter* query_converter,
614                                           CanonOutput* output,
615                                           Parsed* new_parsed);
616
617 // Use for path URLs such as javascript. This does not modify the path in any
618 // way, for example, by escaping it.
619 URL_EXPORT bool CanonicalizePathURL(const char* spec,
620                                     int spec_len,
621                                     const Parsed& parsed,
622                                     CanonOutput* output,
623                                     Parsed* new_parsed);
624 URL_EXPORT bool CanonicalizePathURL(const base::char16* spec,
625                                     int spec_len,
626                                     const Parsed& parsed,
627                                     CanonOutput* output,
628                                     Parsed* new_parsed);
629
630 // Use for mailto URLs. This "canonicalizes" the URL into a path and query
631 // component. It does not attempt to merge "to" fields. It uses UTF-8 for
632 // the query encoding if there is a query. This is because a mailto URL is
633 // really intended for an external mail program, and the encoding of a page,
634 // etc. which would influence a query encoding normally are irrelevant.
635 URL_EXPORT bool CanonicalizeMailtoURL(const char* spec,
636                                       int spec_len,
637                                       const Parsed& parsed,
638                                       CanonOutput* output,
639                                       Parsed* new_parsed);
640 URL_EXPORT bool CanonicalizeMailtoURL(const base::char16* spec,
641                                       int spec_len,
642                                       const Parsed& parsed,
643                                       CanonOutput* output,
644                                       Parsed* new_parsed);
645
646 // Part replacer --------------------------------------------------------------
647
648 // Internal structure used for storing separate strings for each component.
649 // The basic canonicalization functions use this structure internally so that
650 // component replacement (different strings for different components) can be
651 // treated on the same code path as regular canonicalization (the same string
652 // for each component).
653 //
654 // A Parsed structure usually goes along with this. Those components identify
655 // offsets within these strings, so that they can all be in the same string,
656 // or spread arbitrarily across different ones.
657 //
658 // This structures does not own any data. It is the caller's responsibility to
659 // ensure that the data the pointers point to stays in scope and is not
660 // modified.
661 template<typename CHAR>
662 struct URLComponentSource {
663   // Constructor normally used by callers wishing to replace components. This
664   // will make them all NULL, which is no replacement. The caller would then
665   // override the components they want to replace.
666   URLComponentSource()
667       : scheme(NULL),
668         username(NULL),
669         password(NULL),
670         host(NULL),
671         port(NULL),
672         path(NULL),
673         query(NULL),
674         ref(NULL) {
675   }
676
677   // Constructor normally used internally to initialize all the components to
678   // point to the same spec.
679   explicit URLComponentSource(const CHAR* default_value)
680       : scheme(default_value),
681         username(default_value),
682         password(default_value),
683         host(default_value),
684         port(default_value),
685         path(default_value),
686         query(default_value),
687         ref(default_value) {
688   }
689
690   const CHAR* scheme;
691   const CHAR* username;
692   const CHAR* password;
693   const CHAR* host;
694   const CHAR* port;
695   const CHAR* path;
696   const CHAR* query;
697   const CHAR* ref;
698 };
699
700 // This structure encapsulates information on modifying a URL. Each component
701 // may either be left unchanged, replaced, or deleted.
702 //
703 // By default, each component is unchanged. For those components that should be
704 // modified, call either Set* or Clear* to modify it.
705 //
706 // The string passed to Set* functions DOES NOT GET COPIED AND MUST BE KEPT
707 // IN SCOPE BY THE CALLER for as long as this object exists!
708 //
709 // Prefer the 8-bit replacement version if possible since it is more efficient.
710 template<typename CHAR>
711 class Replacements {
712  public:
713   Replacements() {
714   }
715
716   // Scheme
717   void SetScheme(const CHAR* s, const Component& comp) {
718     sources_.scheme = s;
719     components_.scheme = comp;
720   }
721   // Note: we don't have a ClearScheme since this doesn't make any sense.
722   bool IsSchemeOverridden() const { return sources_.scheme != NULL; }
723
724   // Username
725   void SetUsername(const CHAR* s, const Component& comp) {
726     sources_.username = s;
727     components_.username = comp;
728   }
729   void ClearUsername() {
730     sources_.username = Placeholder();
731     components_.username = Component();
732   }
733   bool IsUsernameOverridden() const { return sources_.username != NULL; }
734
735   // Password
736   void SetPassword(const CHAR* s, const Component& comp) {
737     sources_.password = s;
738     components_.password = comp;
739   }
740   void ClearPassword() {
741     sources_.password = Placeholder();
742     components_.password = Component();
743   }
744   bool IsPasswordOverridden() const { return sources_.password != NULL; }
745
746   // Host
747   void SetHost(const CHAR* s, const Component& comp) {
748     sources_.host = s;
749     components_.host = comp;
750   }
751   void ClearHost() {
752     sources_.host = Placeholder();
753     components_.host = Component();
754   }
755   bool IsHostOverridden() const { return sources_.host != NULL; }
756
757   // Port
758   void SetPort(const CHAR* s, const Component& comp) {
759     sources_.port = s;
760     components_.port = comp;
761   }
762   void ClearPort() {
763     sources_.port = Placeholder();
764     components_.port = Component();
765   }
766   bool IsPortOverridden() const { return sources_.port != NULL; }
767
768   // Path
769   void SetPath(const CHAR* s, const Component& comp) {
770     sources_.path = s;
771     components_.path = comp;
772   }
773   void ClearPath() {
774     sources_.path = Placeholder();
775     components_.path = Component();
776   }
777   bool IsPathOverridden() const { return sources_.path != NULL; }
778
779   // Query
780   void SetQuery(const CHAR* s, const Component& comp) {
781     sources_.query = s;
782     components_.query = comp;
783   }
784   void ClearQuery() {
785     sources_.query = Placeholder();
786     components_.query = Component();
787   }
788   bool IsQueryOverridden() const { return sources_.query != NULL; }
789
790   // Ref
791   void SetRef(const CHAR* s, const Component& comp) {
792     sources_.ref = s;
793     components_.ref = comp;
794   }
795   void ClearRef() {
796     sources_.ref = Placeholder();
797     components_.ref = Component();
798   }
799   bool IsRefOverridden() const { return sources_.ref != NULL; }
800
801   // Getters for the internal data. See the variables below for how the
802   // information is encoded.
803   const URLComponentSource<CHAR>& sources() const { return sources_; }
804   const Parsed& components() const { return components_; }
805
806  private:
807   // Returns a pointer to a static empty string that is used as a placeholder
808   // to indicate a component should be deleted (see below).
809   const CHAR* Placeholder() {
810     static const CHAR empty_cstr = 0;
811     return &empty_cstr;
812   }
813
814   // We support three states:
815   //
816   // Action                 | Source                Component
817   // -----------------------+--------------------------------------------------
818   // Don't change component | NULL                  (unused)
819   // Replace component      | (replacement string)  (replacement component)
820   // Delete component       | (non-NULL)            (invalid component: (0,-1))
821   //
822   // We use a pointer to the empty string for the source when the component
823   // should be deleted.
824   URLComponentSource<CHAR> sources_;
825   Parsed components_;
826 };
827
828 // The base must be an 8-bit canonical URL.
829 URL_EXPORT bool ReplaceStandardURL(const char* base,
830                                    const Parsed& base_parsed,
831                                    const Replacements<char>& replacements,
832                                    SchemeType scheme_type,
833                                    CharsetConverter* query_converter,
834                                    CanonOutput* output,
835                                    Parsed* new_parsed);
836 URL_EXPORT bool ReplaceStandardURL(
837     const char* base,
838     const Parsed& base_parsed,
839     const Replacements<base::char16>& replacements,
840     SchemeType scheme_type,
841     CharsetConverter* query_converter,
842     CanonOutput* output,
843     Parsed* new_parsed);
844
845 // Filesystem URLs can only have the path, query, or ref replaced.
846 // All other components will be ignored.
847 URL_EXPORT bool ReplaceFileSystemURL(const char* base,
848                                      const Parsed& base_parsed,
849                                      const Replacements<char>& replacements,
850                                      CharsetConverter* query_converter,
851                                      CanonOutput* output,
852                                      Parsed* new_parsed);
853 URL_EXPORT bool ReplaceFileSystemURL(
854     const char* base,
855     const Parsed& base_parsed,
856     const Replacements<base::char16>& replacements,
857     CharsetConverter* query_converter,
858     CanonOutput* output,
859     Parsed* new_parsed);
860
861 // Replacing some parts of a file URL is not permitted. Everything except
862 // the host, path, query, and ref will be ignored.
863 URL_EXPORT bool ReplaceFileURL(const char* base,
864                                const Parsed& base_parsed,
865                                const Replacements<char>& replacements,
866                                CharsetConverter* query_converter,
867                                CanonOutput* output,
868                                Parsed* new_parsed);
869 URL_EXPORT bool ReplaceFileURL(const char* base,
870                                const Parsed& base_parsed,
871                                const Replacements<base::char16>& replacements,
872                                CharsetConverter* query_converter,
873                                CanonOutput* output,
874                                Parsed* new_parsed);
875
876 // Path URLs can only have the scheme and path replaced. All other components
877 // will be ignored.
878 URL_EXPORT bool ReplacePathURL(const char* base,
879                                const Parsed& base_parsed,
880                                const Replacements<char>& replacements,
881                                CanonOutput* output,
882                                Parsed* new_parsed);
883 URL_EXPORT bool ReplacePathURL(const char* base,
884                                const Parsed& base_parsed,
885                                const Replacements<base::char16>& replacements,
886                                CanonOutput* output,
887                                Parsed* new_parsed);
888
889 // Mailto URLs can only have the scheme, path, and query replaced.
890 // All other components will be ignored.
891 URL_EXPORT bool ReplaceMailtoURL(const char* base,
892                                  const Parsed& base_parsed,
893                                  const Replacements<char>& replacements,
894                                  CanonOutput* output,
895                                  Parsed* new_parsed);
896 URL_EXPORT bool ReplaceMailtoURL(const char* base,
897                                  const Parsed& base_parsed,
898                                  const Replacements<base::char16>& replacements,
899                                  CanonOutput* output,
900                                  Parsed* new_parsed);
901
902 // Relative URL ---------------------------------------------------------------
903
904 // Given an input URL or URL fragment |fragment|, determines if it is a
905 // relative or absolute URL and places the result into |*is_relative|. If it is
906 // relative, the relevant portion of the URL will be placed into
907 // |*relative_component| (there may have been trimmed whitespace, for example).
908 // This value is passed to ResolveRelativeURL. If the input is not relative,
909 // this value is UNDEFINED (it may be changed by the function).
910 //
911 // Returns true on success (we successfully determined the URL is relative or
912 // not). Failure means that the combination of URLs doesn't make any sense.
913 //
914 // The base URL should always be canonical, therefore is ASCII.
915 URL_EXPORT bool IsRelativeURL(const char* base,
916                               const Parsed& base_parsed,
917                               const char* fragment,
918                               int fragment_len,
919                               bool is_base_hierarchical,
920                               bool* is_relative,
921                               Component* relative_component);
922 URL_EXPORT bool IsRelativeURL(const char* base,
923                               const Parsed& base_parsed,
924                               const base::char16* fragment,
925                               int fragment_len,
926                               bool is_base_hierarchical,
927                               bool* is_relative,
928                               Component* relative_component);
929
930 // Given a canonical parsed source URL, a URL fragment known to be relative,
931 // and the identified relevant portion of the relative URL (computed by
932 // IsRelativeURL), this produces a new parsed canonical URL in |output| and
933 // |out_parsed|.
934 //
935 // It also requires a flag indicating whether the base URL is a file: URL
936 // which triggers additional logic.
937 //
938 // The base URL should be canonical and have a host (may be empty for file
939 // URLs) and a path. If it doesn't have these, we can't resolve relative
940 // URLs off of it and will return the base as the output with an error flag.
941 // Because it is canonical is should also be ASCII.
942 //
943 // The query charset converter follows the same rules as CanonicalizeQuery.
944 //
945 // Returns true on success. On failure, the output will be "something
946 // reasonable" that will be consistent and valid, just probably not what
947 // was intended by the web page author or caller.
948 URL_EXPORT bool ResolveRelativeURL(const char* base_url,
949                                    const Parsed& base_parsed,
950                                    bool base_is_file,
951                                    const char* relative_url,
952                                    const Component& relative_component,
953                                    CharsetConverter* query_converter,
954                                    CanonOutput* output,
955                                    Parsed* out_parsed);
956 URL_EXPORT bool ResolveRelativeURL(const char* base_url,
957                                    const Parsed& base_parsed,
958                                    bool base_is_file,
959                                    const base::char16* relative_url,
960                                    const Component& relative_component,
961                                    CharsetConverter* query_converter,
962                                    CanonOutput* output,
963                                    Parsed* out_parsed);
964
965 }  // namespace url
966
967 #endif  // URL_URL_CANON_H_