• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 #include <errno.h>
31 #include <unicode/ucnv.h>
32 
33 #include "googleurl/src/url_canon.h"
34 #include "googleurl/src/url_canon_icu.h"
35 #include "googleurl/src/url_canon_internal.h"
36 #include "googleurl/src/url_canon_stdstring.h"
37 #include "googleurl/src/url_parse.h"
38 #include "googleurl/src/url_test_utils.h"
39 #include "testing/gtest/include/gtest/gtest.h"
40 
41 // Some implementations of base/basictypes.h may define ARRAYSIZE.
42 // If it's not defined, we define it to the ARRAYSIZE_UNSAFE macro
43 // which is in our version of basictypes.h.
44 #ifndef ARRAYSIZE
45 #define ARRAYSIZE ARRAYSIZE_UNSAFE
46 #endif
47 
48 using url_test_utils::WStringToUTF16;
49 using url_test_utils::ConvertUTF8ToUTF16;
50 using url_test_utils::ConvertUTF16ToUTF8;
51 using url_canon::CanonHostInfo;
52 
53 namespace {
54 
55 struct ComponentCase {
56   const char* input;
57   const char* expected;
58   url_parse::Component expected_component;
59   bool expected_success;
60 };
61 
62 // ComponentCase but with dual 8-bit/16-bit input. Generally, the unit tests
63 // treat each input as optional, and will only try processing if non-NULL.
64 // The output is always 8-bit.
65 struct DualComponentCase {
66   const char* input8;
67   const wchar_t* input16;
68   const char* expected;
69   url_parse::Component expected_component;
70   bool expected_success;
71 };
72 
73 // Test cases for CanonicalizeIPAddress().  The inputs are identical to
74 // DualComponentCase, but the output has extra CanonHostInfo fields.
75 struct IPAddressCase {
76   const char* input8;
77   const wchar_t* input16;
78   const char* expected;
79   url_parse::Component expected_component;
80 
81   // CanonHostInfo fields, for verbose output.
82   CanonHostInfo::Family expected_family;
83   int expected_num_ipv4_components;
84 };
85 
86 struct ReplaceCase {
87   const char* base;
88   const char* scheme;
89   const char* username;
90   const char* password;
91   const char* host;
92   const char* port;
93   const char* path;
94   const char* query;
95   const char* ref;
96   const char* expected;
97 };
98 
99 // Wrapper around a UConverter object that managers creation and destruction.
100 class UConvScoper {
101  public:
UConvScoper(const char * charset_name)102   explicit UConvScoper(const char* charset_name) {
103     UErrorCode err = U_ZERO_ERROR;
104     converter_ = ucnv_open(charset_name, &err);
105   }
106 
~UConvScoper()107   ~UConvScoper() {
108     if (converter_)
109       ucnv_close(converter_);
110   }
111 
112   // Returns the converter object, may be NULL.
converter() const113   UConverter* converter() const { return converter_; }
114 
115  private:
116   UConverter* converter_;
117 };
118 
119 // Magic string used in the replacements code that tells SetupReplComp to
120 // call the clear function.
121 const char kDeleteComp[] = "|";
122 
123 // Sets up a replacement for a single component. This is given pointers to
124 // the set and clear function for the component being replaced, and will
125 // either set the component (if it exists) or clear it (if the replacement
126 // string matches kDeleteComp).
127 //
128 // This template is currently used only for the 8-bit case, and the strlen
129 // causes it to fail in other cases. It is left a template in case we have
130 // tests for wide replacements.
131 template<typename CHAR>
SetupReplComp(void (url_canon::Replacements<CHAR>::* set)(const CHAR *,const url_parse::Component &),void (url_canon::Replacements<CHAR>::* clear)(),url_canon::Replacements<CHAR> * rep,const CHAR * str)132 void SetupReplComp(
133     void (url_canon::Replacements<CHAR>::*set)(const CHAR*,
134                                                const url_parse::Component&),
135     void (url_canon::Replacements<CHAR>::*clear)(),
136     url_canon::Replacements<CHAR>* rep,
137     const CHAR* str) {
138   if (str && str[0] == kDeleteComp[0]) {
139     (rep->*clear)();
140   } else if (str) {
141     (rep->*set)(str, url_parse::Component(0, static_cast<int>(strlen(str))));
142   }
143 }
144 
145 }  // namespace
146 
TEST(URLCanonTest,DoAppendUTF8)147 TEST(URLCanonTest, DoAppendUTF8) {
148   struct UTF8Case {
149     unsigned input;
150     const char* output;
151   } utf_cases[] = {
152     // Valid code points.
153     {0x24, "\x24"},
154     {0xA2, "\xC2\xA2"},
155     {0x20AC, "\xE2\x82\xAC"},
156     {0x24B62, "\xF0\xA4\xAD\xA2"},
157     {0x10FFFF, "\xF4\x8F\xBF\xBF"},
158   };
159   std::string out_str;
160   for (size_t i = 0; i < ARRAYSIZE(utf_cases); i++) {
161     out_str.clear();
162     url_canon::StdStringCanonOutput output(&out_str);
163     url_canon::AppendUTF8Value(utf_cases[i].input, &output);
164     output.Complete();
165     EXPECT_EQ(utf_cases[i].output, out_str);
166   }
167 }
168 
169 // TODO(mattm): Can't run this in debug mode for now, since the DCHECK will
170 // cause the Chromium stacktrace dialog to appear and hang the test.
171 // See http://crbug.com/49580.
172 #if defined(GTEST_HAS_DEATH_TEST) && defined(NDEBUG)
TEST(URLCanonTest,DoAppendUTF8Invalid)173 TEST(URLCanonTest, DoAppendUTF8Invalid) {
174   std::string out_str;
175   url_canon::StdStringCanonOutput output(&out_str);
176   // Invalid code point (too large).
177   ASSERT_DEBUG_DEATH({
178     url_canon::AppendUTF8Value(0x110000, &output);
179     output.Complete();
180     EXPECT_EQ("", out_str);
181   }, "");
182 }
183 #endif
184 
TEST(URLCanonTest,UTF)185 TEST(URLCanonTest, UTF) {
186   // Low-level test that we handle reading, canonicalization, and writing
187   // UTF-8/UTF-16 strings properly.
188   struct UTFCase {
189     const char* input8;
190     const wchar_t* input16;
191     bool expected_success;
192     const char* output;
193   } utf_cases[] = {
194       // Valid canonical input should get passed through & escaped.
195     {"\xe4\xbd\xa0\xe5\xa5\xbd", L"\x4f60\x597d", true, "%E4%BD%A0%E5%A5%BD"},
196       // Test a characer that takes > 16 bits (U+10300 = old italic letter A)
197     {"\xF0\x90\x8C\x80", L"\xd800\xdf00", true, "%F0%90%8C%80"},
198       // Non-shortest-form UTF-8 are invalid. The bad char should be replaced
199       // with the invalid character (EF BF DB in UTF-8).
200     {"\xf0\x84\xbd\xa0\xe5\xa5\xbd", NULL, false, "%EF%BF%BD%E5%A5%BD"},
201       // Invalid UTF-8 sequences should be marked as invalid (the first
202       // sequence is truncated).
203     {"\xe4\xa0\xe5\xa5\xbd", L"\xd800\x597d", false, "%EF%BF%BD%E5%A5%BD"},
204       // Character going off the end.
205     {"\xe4\xbd\xa0\xe5\xa5", L"\x4f60\xd800", false, "%E4%BD%A0%EF%BF%BD"},
206       // ...same with low surrogates with no high surrogate.
207     {"\xed\xb0\x80", L"\xdc00", false, "%EF%BF%BD"},
208       // Test a UTF-8 encoded surrogate value is marked as invalid.
209       // ED A0 80 = U+D800
210     {"\xed\xa0\x80", NULL, false, "%EF%BF%BD"},
211   };
212 
213   std::string out_str;
214   for (size_t i = 0; i < ARRAYSIZE(utf_cases); i++) {
215     if (utf_cases[i].input8) {
216       out_str.clear();
217       url_canon::StdStringCanonOutput output(&out_str);
218 
219       int input_len = static_cast<int>(strlen(utf_cases[i].input8));
220       bool success = true;
221       for (int ch = 0; ch < input_len; ch++) {
222         success &= AppendUTF8EscapedChar(utf_cases[i].input8, &ch, input_len,
223                                          &output);
224       }
225       output.Complete();
226       EXPECT_EQ(utf_cases[i].expected_success, success);
227       EXPECT_EQ(std::string(utf_cases[i].output), out_str);
228     }
229     if (utf_cases[i].input16) {
230       out_str.clear();
231       url_canon::StdStringCanonOutput output(&out_str);
232 
233       string16 input_str(WStringToUTF16(utf_cases[i].input16));
234       int input_len = static_cast<int>(input_str.length());
235       bool success = true;
236       for (int ch = 0; ch < input_len; ch++) {
237         success &= AppendUTF8EscapedChar(input_str.c_str(), &ch, input_len,
238                                          &output);
239       }
240       output.Complete();
241       EXPECT_EQ(utf_cases[i].expected_success, success);
242       EXPECT_EQ(std::string(utf_cases[i].output), out_str);
243     }
244 
245     if (utf_cases[i].input8 && utf_cases[i].input16 &&
246         utf_cases[i].expected_success) {
247       // Check that the UTF-8 and UTF-16 inputs are equivalent.
248 
249       // UTF-16 -> UTF-8
250       std::string input8_str(utf_cases[i].input8);
251       string16 input16_str(WStringToUTF16(utf_cases[i].input16));
252       EXPECT_EQ(input8_str, ConvertUTF16ToUTF8(input16_str));
253 
254       // UTF-8 -> UTF-16
255       EXPECT_EQ(input16_str, ConvertUTF8ToUTF16(input8_str));
256     }
257   }
258 }
259 
TEST(URLCanonTest,ICUCharsetConverter)260 TEST(URLCanonTest, ICUCharsetConverter) {
261   struct ICUCase {
262     const wchar_t* input;
263     const char* encoding;
264     const char* expected;
265   } icu_cases[] = {
266       // UTF-8.
267     {L"Hello, world", "utf-8", "Hello, world"},
268     {L"\x4f60\x597d", "utf-8", "\xe4\xbd\xa0\xe5\xa5\xbd"},
269       // Non-BMP UTF-8.
270     {L"!\xd800\xdf00!", "utf-8", "!\xf0\x90\x8c\x80!"},
271       // Big5
272     {L"\x4f60\x597d", "big5", "\xa7\x41\xa6\x6e"},
273       // Unrepresentable character in the destination set.
274     {L"hello\x4f60\x06de\x597dworld", "big5", "hello\xa7\x41%26%231758%3B\xa6\x6eworld"},
275   };
276 
277   for (size_t i = 0; i < ARRAYSIZE(icu_cases); i++) {
278     UConvScoper conv(icu_cases[i].encoding);
279     ASSERT_TRUE(conv.converter() != NULL);
280     url_canon::ICUCharsetConverter converter(conv.converter());
281 
282     std::string str;
283     url_canon::StdStringCanonOutput output(&str);
284 
285     string16 input_str(WStringToUTF16(icu_cases[i].input));
286     int input_len = static_cast<int>(input_str.length());
287     converter.ConvertFromUTF16(input_str.c_str(), input_len, &output);
288     output.Complete();
289 
290     EXPECT_STREQ(icu_cases[i].expected, str.c_str());
291   }
292 
293   // Test string sizes around the resize boundary for the output to make sure
294   // the converter resizes as needed.
295   const int static_size = 16;
296   UConvScoper conv("utf-8");
297   ASSERT_TRUE(conv.converter());
298   url_canon::ICUCharsetConverter converter(conv.converter());
299   for (int i = static_size - 2; i <= static_size + 2; i++) {
300     // Make a string with the appropriate length.
301     string16 input;
302     for (int ch = 0; ch < i; ch++)
303       input.push_back('a');
304 
305     url_canon::RawCanonOutput<static_size> output;
306     converter.ConvertFromUTF16(input.c_str(), static_cast<int>(input.length()),
307                                &output);
308     EXPECT_EQ(input.length(), static_cast<size_t>(output.length()));
309   }
310 }
311 
TEST(URLCanonTest,Scheme)312 TEST(URLCanonTest, Scheme) {
313   // Here, we're mostly testing that unusual characters are handled properly.
314   // The canonicalizer doesn't do any parsing or whitespace detection. It will
315   // also do its best on error, and will escape funny sequences (these won't be
316   // valid schemes and it will return error).
317   //
318   // Note that the canonicalizer will append a colon to the output to separate
319   // out the rest of the URL, which is not present in the input. We check,
320   // however, that the output range includes everything but the colon.
321   ComponentCase scheme_cases[] = {
322     {"http", "http:", url_parse::Component(0, 4), true},
323     {"HTTP", "http:", url_parse::Component(0, 4), true},
324     {" HTTP ", "%20http%20:", url_parse::Component(0, 10), false},
325     {"htt: ", "htt%3A%20:", url_parse::Component(0, 9), false},
326     {"\xe4\xbd\xa0\xe5\xa5\xbdhttp", "%E4%BD%A0%E5%A5%BDhttp:", url_parse::Component(0, 22), false},
327       // Don't re-escape something already escaped. Note that it will
328       // "canonicalize" the 'A' to 'a', but that's OK.
329     {"ht%3Atp", "ht%3atp:", url_parse::Component(0, 7), false},
330   };
331 
332   std::string out_str;
333 
334   for (size_t i = 0; i < arraysize(scheme_cases); i++) {
335     int url_len = static_cast<int>(strlen(scheme_cases[i].input));
336     url_parse::Component in_comp(0, url_len);
337     url_parse::Component out_comp;
338 
339     out_str.clear();
340     url_canon::StdStringCanonOutput output1(&out_str);
341     bool success = url_canon::CanonicalizeScheme(scheme_cases[i].input,
342                                                  in_comp, &output1, &out_comp);
343     output1.Complete();
344 
345     EXPECT_EQ(scheme_cases[i].expected_success, success);
346     EXPECT_EQ(std::string(scheme_cases[i].expected), out_str);
347     EXPECT_EQ(scheme_cases[i].expected_component.begin, out_comp.begin);
348     EXPECT_EQ(scheme_cases[i].expected_component.len, out_comp.len);
349 
350     // Now try the wide version
351     out_str.clear();
352     url_canon::StdStringCanonOutput output2(&out_str);
353 
354     string16 wide_input(ConvertUTF8ToUTF16(scheme_cases[i].input));
355     in_comp.len = static_cast<int>(wide_input.length());
356     success = url_canon::CanonicalizeScheme(wide_input.c_str(), in_comp,
357                                             &output2, &out_comp);
358     output2.Complete();
359 
360     EXPECT_EQ(scheme_cases[i].expected_success, success);
361     EXPECT_EQ(std::string(scheme_cases[i].expected), out_str);
362     EXPECT_EQ(scheme_cases[i].expected_component.begin, out_comp.begin);
363     EXPECT_EQ(scheme_cases[i].expected_component.len, out_comp.len);
364   }
365 
366   // Test the case where the scheme is declared nonexistant, it should be
367   // converted into an empty scheme.
368   url_parse::Component out_comp;
369   out_str.clear();
370   url_canon::StdStringCanonOutput output(&out_str);
371 
372   EXPECT_TRUE(url_canon::CanonicalizeScheme("", url_parse::Component(0, -1),
373                                             &output, &out_comp));
374   output.Complete();
375 
376   EXPECT_EQ(std::string(":"), out_str);
377   EXPECT_EQ(0, out_comp.begin);
378   EXPECT_EQ(0, out_comp.len);
379 }
380 
TEST(URLCanonTest,Host)381 TEST(URLCanonTest, Host) {
382   IPAddressCase host_cases[] = {
383        // Basic canonicalization, uppercase should be converted to lowercase.
384     {"GoOgLe.CoM", L"GoOgLe.CoM", "google.com", url_parse::Component(0, 10), CanonHostInfo::NEUTRAL, -1},
385       // Spaces and some other characters should be escaped.
386     {"Goo%20 goo%7C|.com", L"Goo%20 goo%7C|.com", "goo%20%20goo%7C%7C.com", url_parse::Component(0, 22), CanonHostInfo::NEUTRAL, -1},
387       // Exciting different types of spaces!
388     {NULL, L"GOO\x00a0\x3000goo.com", "goo%20%20goo.com", url_parse::Component(0, 16), CanonHostInfo::NEUTRAL, -1},
389       // Other types of space (no-break, zero-width, zero-width-no-break) are
390       // name-prepped away to nothing.
391     {NULL, L"GOO\x200b\x2060\xfeffgoo.com", "googoo.com", url_parse::Component(0, 10), CanonHostInfo::NEUTRAL, -1},
392       // Ideographic full stop (full-width period for Chinese, etc.) should be
393       // treated as a dot.
394     {NULL, L"www.foo\x3002"L"bar.com", "www.foo.bar.com", url_parse::Component(0, 15), CanonHostInfo::NEUTRAL, -1},
395       // Invalid unicode characters should fail...
396       // ...In wide input, ICU will barf and we'll end up with the input as
397       //    escaped UTF-8 (the invalid character should be replaced with the
398       //    replacement character).
399     {"\xef\xb7\x90zyx.com", L"\xfdd0zyx.com", "%EF%BF%BDzyx.com", url_parse::Component(0, 16), CanonHostInfo::BROKEN, -1},
400       // ...This is the same as previous but with with escaped.
401     {"%ef%b7%90zyx.com", L"%ef%b7%90zyx.com", "%EF%BF%BDzyx.com", url_parse::Component(0, 16), CanonHostInfo::BROKEN, -1},
402       // Test name prepping, fullwidth input should be converted to ASCII and NOT
403       // IDN-ized. This is "Go" in fullwidth UTF-8/UTF-16.
404     {"\xef\xbc\xa7\xef\xbd\x8f.com", L"\xff27\xff4f.com", "go.com", url_parse::Component(0, 6), CanonHostInfo::NEUTRAL, -1},
405       // Test that fullwidth escaped values are properly name-prepped,
406       // then converted or rejected.
407       // ...%41 in fullwidth = 'A' (also as escaped UTF-8 input)
408     {"\xef\xbc\x85\xef\xbc\x94\xef\xbc\x91.com", L"\xff05\xff14\xff11.com", "a.com", url_parse::Component(0, 5), CanonHostInfo::NEUTRAL, -1},
409     {"%ef%bc%85%ef%bc%94%ef%bc%91.com", L"%ef%bc%85%ef%bc%94%ef%bc%91.com", "a.com", url_parse::Component(0, 5), CanonHostInfo::NEUTRAL, -1},
410       // ...%00 in fullwidth should fail (also as escaped UTF-8 input)
411     {"\xef\xbc\x85\xef\xbc\x90\xef\xbc\x90.com", L"\xff05\xff10\xff10.com", "%00.com", url_parse::Component(0, 7), CanonHostInfo::BROKEN, -1},
412     {"%ef%bc%85%ef%bc%90%ef%bc%90.com", L"%ef%bc%85%ef%bc%90%ef%bc%90.com", "%00.com", url_parse::Component(0, 7), CanonHostInfo::BROKEN, -1},
413       // Basic IDN support, UTF-8 and UTF-16 input should be converted to IDN
414     {"\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xbd\xa0\xe5\xa5\xbd", L"\x4f60\x597d\x4f60\x597d", "xn--6qqa088eba", url_parse::Component(0, 14), CanonHostInfo::NEUTRAL, -1},
415       // Mixed UTF-8 and escaped UTF-8 (narrow case) and UTF-16 and escaped
416       // UTF-8 (wide case). The output should be equivalent to the true wide
417       // character input above).
418     {"%E4%BD%A0%E5%A5%BD\xe4\xbd\xa0\xe5\xa5\xbd", L"%E4%BD%A0%E5%A5%BD\x4f60\x597d", "xn--6qqa088eba", url_parse::Component(0, 14), CanonHostInfo::NEUTRAL, -1},
419       // Invalid escaped characters should fail and the percents should be
420       // escaped.
421     {"%zz%66%a", L"%zz%66%a", "%25zzf%25a", url_parse::Component(0, 10), CanonHostInfo::BROKEN, -1},
422       // If we get an invalid character that has been escaped.
423     {"%25", L"%25", "%25", url_parse::Component(0, 3), CanonHostInfo::BROKEN, -1},
424     {"hello%00", L"hello%00", "hello%00", url_parse::Component(0, 8), CanonHostInfo::BROKEN, -1},
425       // Escaped numbers should be treated like IP addresses if they are.
426     {"%30%78%63%30%2e%30%32%35%30.01", L"%30%78%63%30%2e%30%32%35%30.01", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 3},
427     {"%30%78%63%30%2e%30%32%35%30.01%2e", L"%30%78%63%30%2e%30%32%35%30.01%2e", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 3},
428       // Invalid escaping should trigger the regular host error handling.
429     {"%3g%78%63%30%2e%30%32%35%30%2E.01", L"%3g%78%63%30%2e%30%32%35%30%2E.01", "%253gxc0.0250..01", url_parse::Component(0, 17), CanonHostInfo::BROKEN, -1},
430       // Something that isn't exactly an IP should get treated as a host and
431       // spaces escaped.
432     {"192.168.0.1 hello", L"192.168.0.1 hello", "192.168.0.1%20hello", url_parse::Component(0, 19), CanonHostInfo::NEUTRAL, -1},
433       // Fullwidth and escaped UTF-8 fullwidth should still be treated as IP.
434       // These are "0Xc0.0250.01" in fullwidth.
435     {"\xef\xbc\x90%Ef%bc\xb8%ef%Bd%83\xef\xbc\x90%EF%BC%8E\xef\xbc\x90\xef\xbc\x92\xef\xbc\x95\xef\xbc\x90\xef\xbc%8E\xef\xbc\x90\xef\xbc\x91", L"\xff10\xff38\xff43\xff10\xff0e\xff10\xff12\xff15\xff10\xff0e\xff10\xff11", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 3},
436       // Broken IP addresses get marked as such.
437     {"192.168.0.257", L"192.168.0.257", "192.168.0.257", url_parse::Component(0, 13), CanonHostInfo::BROKEN, -1},
438     {"[google.com]", L"[google.com]", "[google.com]", url_parse::Component(0, 12), CanonHostInfo::BROKEN, -1},
439       // Cyrillic letter followed buy ( should return punicode for ( escaped before punicode string was created. I.e.
440       // if ( is escaped after punicode is created we would get xn--%28-8tb (incorrect).
441     {"\xd1\x82(", L"\x0442(", "xn--%28-7ed", url_parse::Component(0, 11), CanonHostInfo::NEUTRAL, -1},
442   };
443 
444   // CanonicalizeHost() non-verbose.
445   std::string out_str;
446   for (size_t i = 0; i < arraysize(host_cases); i++) {
447     // Narrow version.
448     if (host_cases[i].input8) {
449       int host_len = static_cast<int>(strlen(host_cases[i].input8));
450       url_parse::Component in_comp(0, host_len);
451       url_parse::Component out_comp;
452 
453       out_str.clear();
454       url_canon::StdStringCanonOutput output(&out_str);
455 
456       bool success = url_canon::CanonicalizeHost(host_cases[i].input8, in_comp,
457                                                  &output, &out_comp);
458       output.Complete();
459 
460       EXPECT_EQ(host_cases[i].expected_family != CanonHostInfo::BROKEN,
461                 success);
462       EXPECT_EQ(std::string(host_cases[i].expected), out_str);
463       EXPECT_EQ(host_cases[i].expected_component.begin, out_comp.begin);
464       EXPECT_EQ(host_cases[i].expected_component.len, out_comp.len);
465     }
466 
467     // Wide version.
468     if (host_cases[i].input16) {
469       string16 input16(WStringToUTF16(host_cases[i].input16));
470       int host_len = static_cast<int>(input16.length());
471       url_parse::Component in_comp(0, host_len);
472       url_parse::Component out_comp;
473 
474       out_str.clear();
475       url_canon::StdStringCanonOutput output(&out_str);
476 
477       bool success = url_canon::CanonicalizeHost(input16.c_str(), in_comp,
478                                                  &output, &out_comp);
479       output.Complete();
480 
481       EXPECT_EQ(host_cases[i].expected_family != CanonHostInfo::BROKEN,
482                 success);
483       EXPECT_EQ(std::string(host_cases[i].expected), out_str);
484       EXPECT_EQ(host_cases[i].expected_component.begin, out_comp.begin);
485       EXPECT_EQ(host_cases[i].expected_component.len, out_comp.len);
486     }
487   }
488 
489   // CanonicalizeHostVerbose()
490   for (size_t i = 0; i < arraysize(host_cases); i++) {
491     // Narrow version.
492     if (host_cases[i].input8) {
493       int host_len = static_cast<int>(strlen(host_cases[i].input8));
494       url_parse::Component in_comp(0, host_len);
495 
496       out_str.clear();
497       url_canon::StdStringCanonOutput output(&out_str);
498       CanonHostInfo host_info;
499 
500       url_canon::CanonicalizeHostVerbose(host_cases[i].input8, in_comp,
501                                          &output, &host_info);
502       output.Complete();
503 
504       EXPECT_EQ(host_cases[i].expected_family, host_info.family);
505       EXPECT_EQ(std::string(host_cases[i].expected), out_str);
506       EXPECT_EQ(host_cases[i].expected_component.begin,
507                 host_info.out_host.begin);
508       EXPECT_EQ(host_cases[i].expected_component.len, host_info.out_host.len);
509       if (host_cases[i].expected_family == CanonHostInfo::IPV4) {
510         EXPECT_EQ(host_cases[i].expected_num_ipv4_components,
511                   host_info.num_ipv4_components);
512       }
513     }
514 
515     // Wide version.
516     if (host_cases[i].input16) {
517       string16 input16(WStringToUTF16(host_cases[i].input16));
518       int host_len = static_cast<int>(input16.length());
519       url_parse::Component in_comp(0, host_len);
520 
521       out_str.clear();
522       url_canon::StdStringCanonOutput output(&out_str);
523       CanonHostInfo host_info;
524 
525       url_canon::CanonicalizeHostVerbose(input16.c_str(), in_comp,
526                                          &output, &host_info);
527       output.Complete();
528 
529       EXPECT_EQ(host_cases[i].expected_family, host_info.family);
530       EXPECT_EQ(std::string(host_cases[i].expected), out_str);
531       EXPECT_EQ(host_cases[i].expected_component.begin,
532                 host_info.out_host.begin);
533       EXPECT_EQ(host_cases[i].expected_component.len, host_info.out_host.len);
534       if (host_cases[i].expected_family == CanonHostInfo::IPV4) {
535         EXPECT_EQ(host_cases[i].expected_num_ipv4_components,
536                   host_info.num_ipv4_components);
537       }
538     }
539   }
540 }
541 
TEST(URLCanonTest,IPv4)542 TEST(URLCanonTest, IPv4) {
543   IPAddressCase cases[] = {
544       // Empty is not an IP address.
545     {"", L"", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
546     {".", L".", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
547       // Regular IP addresses in different bases.
548     {"192.168.0.1", L"192.168.0.1", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 4},
549     {"0300.0250.00.01", L"0300.0250.00.01", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 4},
550     {"0xC0.0Xa8.0x0.0x1", L"0xC0.0Xa8.0x0.0x1", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 4},
551       // Non-IP addresses due to invalid characters.
552     {"192.168.9.com", L"192.168.9.com", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
553       // Invalid characters for the base should be rejected.
554     {"19a.168.0.1", L"19a.168.0.1", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
555     {"0308.0250.00.01", L"0308.0250.00.01", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
556     {"0xCG.0xA8.0x0.0x1", L"0xCG.0xA8.0x0.0x1", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
557       // If there are not enough components, the last one should fill them out.
558     {"192", L"192", "0.0.0.192", url_parse::Component(0, 9), CanonHostInfo::IPV4, 1},
559     {"0xC0a80001", L"0xC0a80001", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 1},
560     {"030052000001", L"030052000001", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 1},
561     {"000030052000001", L"000030052000001", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 1},
562     {"192.168", L"192.168", "192.0.0.168", url_parse::Component(0, 11), CanonHostInfo::IPV4, 2},
563     {"192.0x00A80001", L"192.0x000A80001", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 2},
564     {"0xc0.052000001", L"0xc0.052000001", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 2},
565     {"192.168.1", L"192.168.1", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 3},
566       // Too many components means not an IP address.
567     {"192.168.0.0.1", L"192.168.0.0.1", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
568       // We allow a single trailing dot.
569     {"192.168.0.1.", L"192.168.0.1.", "192.168.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 4},
570     {"192.168.0.1. hello", L"192.168.0.1. hello", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
571     {"192.168.0.1..", L"192.168.0.1..", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
572       // Two dots in a row means not an IP address.
573     {"192.168..1", L"192.168..1", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
574       // Any numerical overflow should be marked as BROKEN.
575     {"0x100.0", L"0x100.0", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
576     {"0x100.0.0", L"0x100.0.0", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
577     {"0x100.0.0.0", L"0x100.0.0.0", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
578     {"0.0x100.0.0", L"0.0x100.0.0", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
579     {"0.0.0x100.0", L"0.0.0x100.0", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
580     {"0.0.0.0x100", L"0.0.0.0x100", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
581     {"0.0.0x10000", L"0.0.0x10000", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
582     {"0.0x1000000", L"0.0x1000000", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
583     {"0x100000000", L"0x100000000", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
584       // Repeat the previous tests, minus 1, to verify boundaries.
585     {"0xFF.0", L"0xFF.0", "255.0.0.0", url_parse::Component(0, 9), CanonHostInfo::IPV4, 2},
586     {"0xFF.0.0", L"0xFF.0.0", "255.0.0.0", url_parse::Component(0, 9), CanonHostInfo::IPV4, 3},
587     {"0xFF.0.0.0", L"0xFF.0.0.0", "255.0.0.0", url_parse::Component(0, 9), CanonHostInfo::IPV4, 4},
588     {"0.0xFF.0.0", L"0.0xFF.0.0", "0.255.0.0", url_parse::Component(0, 9), CanonHostInfo::IPV4, 4},
589     {"0.0.0xFF.0", L"0.0.0xFF.0", "0.0.255.0", url_parse::Component(0, 9), CanonHostInfo::IPV4, 4},
590     {"0.0.0.0xFF", L"0.0.0.0xFF", "0.0.0.255", url_parse::Component(0, 9), CanonHostInfo::IPV4, 4},
591     {"0.0.0xFFFF", L"0.0.0xFFFF", "0.0.255.255", url_parse::Component(0, 11), CanonHostInfo::IPV4, 3},
592     {"0.0xFFFFFF", L"0.0xFFFFFF", "0.255.255.255", url_parse::Component(0, 13), CanonHostInfo::IPV4, 2},
593     {"0xFFFFFFFF", L"0xFFFFFFFF", "255.255.255.255", url_parse::Component(0, 15), CanonHostInfo::IPV4, 1},
594       // Old trunctations tests.  They're all "BROKEN" now.
595     {"276.256.0xf1a2.077777", L"276.256.0xf1a2.077777", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
596     {"192.168.0.257", L"192.168.0.257", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
597     {"192.168.0xa20001", L"192.168.0xa20001", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
598     {"192.015052000001", L"192.015052000001", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
599     {"0X12C0a80001", L"0X12C0a80001", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
600     {"276.1.2", L"276.1.2", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
601       // Spaces should be rejected.
602     {"192.168.0.1 hello", L"192.168.0.1 hello", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
603       // Very large numbers.
604     {"0000000000000300.0x00000000000000fF.00000000000000001", L"0000000000000300.0x00000000000000fF.00000000000000001", "192.255.0.1", url_parse::Component(0, 11), CanonHostInfo::IPV4, 3},
605     {"0000000000000300.0xffffffffFFFFFFFF.3022415481470977", L"0000000000000300.0xffffffffFFFFFFFF.3022415481470977", "", url_parse::Component(0, 11), CanonHostInfo::BROKEN, -1},
606       // A number has no length limit, but long numbers can still overflow.
607     {"00000000000000000001", L"00000000000000000001", "0.0.0.1", url_parse::Component(0, 7), CanonHostInfo::IPV4, 1},
608     {"0000000000000000100000000000000001", L"0000000000000000100000000000000001", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
609       // If a long component is non-numeric, it's a hostname, *not* a broken IP.
610     {"0.0.0.000000000000000000z", L"0.0.0.000000000000000000z", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
611     {"0.0.0.100000000000000000z", L"0.0.0.100000000000000000z", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
612       // Truncation of all zeros should still result in 0.
613     {"0.00.0x.0x0", L"0.00.0x.0x0", "0.0.0.0", url_parse::Component(0, 7), CanonHostInfo::IPV4, 4},
614   };
615 
616   for (size_t i = 0; i < arraysize(cases); i++) {
617     // 8-bit version.
618     url_parse::Component component(0,
619                                    static_cast<int>(strlen(cases[i].input8)));
620 
621     std::string out_str1;
622     url_canon::StdStringCanonOutput output1(&out_str1);
623     url_canon::CanonHostInfo host_info;
624     url_canon::CanonicalizeIPAddress(cases[i].input8, component, &output1,
625                                      &host_info);
626     output1.Complete();
627 
628     EXPECT_EQ(cases[i].expected_family, host_info.family);
629     if (host_info.family == CanonHostInfo::IPV4) {
630       EXPECT_STREQ(cases[i].expected, out_str1.c_str());
631       EXPECT_EQ(cases[i].expected_component.begin, host_info.out_host.begin);
632       EXPECT_EQ(cases[i].expected_component.len, host_info.out_host.len);
633       EXPECT_EQ(cases[i].expected_num_ipv4_components,
634                 host_info.num_ipv4_components);
635     }
636 
637     // 16-bit version.
638     string16 input16(WStringToUTF16(cases[i].input16));
639     component = url_parse::Component(0, static_cast<int>(input16.length()));
640 
641     std::string out_str2;
642     url_canon::StdStringCanonOutput output2(&out_str2);
643     url_canon::CanonicalizeIPAddress(input16.c_str(), component, &output2,
644                                      &host_info);
645     output2.Complete();
646 
647     EXPECT_EQ(cases[i].expected_family, host_info.family);
648     if (host_info.family == CanonHostInfo::IPV4) {
649       EXPECT_STREQ(cases[i].expected, out_str2.c_str());
650       EXPECT_EQ(cases[i].expected_component.begin, host_info.out_host.begin);
651       EXPECT_EQ(cases[i].expected_component.len, host_info.out_host.len);
652       EXPECT_EQ(cases[i].expected_num_ipv4_components,
653                 host_info.num_ipv4_components);
654     }
655   }
656 }
657 
TEST(URLCanonTest,IPv6)658 TEST(URLCanonTest, IPv6) {
659   IPAddressCase cases[] = {
660       // Empty is not an IP address.
661     {"", L"", "", url_parse::Component(), CanonHostInfo::NEUTRAL, -1},
662       // Non-IPs with [:] characters are marked BROKEN.
663     {":", L":", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
664     {"[", L"[", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
665     {"[:", L"[:", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
666     {"]", L"]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
667     {":]", L":]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
668     {"[]", L"[]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
669     {"[:]", L"[:]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
670       // Regular IP address is invalid without bounding '[' and ']'.
671     {"2001:db8::1", L"2001:db8::1", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
672     {"[2001:db8::1", L"[2001:db8::1", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
673     {"2001:db8::1]", L"2001:db8::1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
674       // Regular IP addresses.
675     {"[::]", L"[::]", "[::]", url_parse::Component(0,4), CanonHostInfo::IPV6, -1},
676     {"[::1]", L"[::1]", "[::1]", url_parse::Component(0,5), CanonHostInfo::IPV6, -1},
677     {"[1::]", L"[1::]", "[1::]", url_parse::Component(0,5), CanonHostInfo::IPV6, -1},
678     {"[::192.168.0.1]", L"[::192.168.0.1]", "[::c0a8:1]", url_parse::Component(0,10), CanonHostInfo::IPV6, -1},
679     {"[::ffff:192.168.0.1]", L"[::ffff:192.168.0.1]", "[::ffff:c0a8:1]", url_parse::Component(0,15), CanonHostInfo::IPV6, -1},
680 
681     // Leading zeros should be stripped.
682     {"[000:01:02:003:004:5:6:007]", L"[000:01:02:003:004:5:6:007]", "[0:1:2:3:4:5:6:7]", url_parse::Component(0,17), CanonHostInfo::IPV6, -1},
683 
684     // Upper case letters should be lowercased.
685     {"[A:b:c:DE:fF:0:1:aC]", L"[A:b:c:DE:fF:0:1:aC]", "[a:b:c:de:ff:0:1:ac]", url_parse::Component(0,20), CanonHostInfo::IPV6, -1},
686 
687     // The same address can be written with different contractions, but should
688     // get canonicalized to the same thing.
689     {"[1:0:0:2::3:0]", L"[1:0:0:2::3:0]", "[1::2:0:0:3:0]", url_parse::Component(0,14), CanonHostInfo::IPV6, -1},
690     {"[1::2:0:0:3:0]", L"[1::2:0:0:3:0]", "[1::2:0:0:3:0]", url_parse::Component(0,14), CanonHostInfo::IPV6, -1},
691 
692     // IPv4 addresses
693     // Only mapped and compat addresses can have IPv4 syntax embedded.
694     {"[::eeee:192.168.0.1]", L"[::eeee:192.168.0.1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
695     {"[2001::192.168.0.1]", L"[2001::192.168.0.1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
696     {"[1:2:192.168.0.1:5:6]", L"[1:2:192.168.0.1:5:6]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
697 
698     // IPv4 with last component missing.
699     {"[::ffff:192.1.2]", L"[::ffff:192.1.2]", "[::ffff:c001:2]", url_parse::Component(0,15), CanonHostInfo::IPV6, -1},
700 
701     // IPv4 using hex.
702     // TODO(eroman): Should this format be disallowed?
703     {"[::ffff:0xC0.0Xa8.0x0.0x1]", L"[::ffff:0xC0.0Xa8.0x0.0x1]", "[::ffff:c0a8:1]", url_parse::Component(0,15), CanonHostInfo::IPV6, -1},
704 
705     // There may be zeros surrounding the "::" contraction.
706     {"[0:0::0:0:8]", L"[0:0::0:0:8]", "[::8]", url_parse::Component(0,5), CanonHostInfo::IPV6, -1},
707 
708     {"[2001:db8::1]", L"[2001:db8::1]", "[2001:db8::1]", url_parse::Component(0,13), CanonHostInfo::IPV6, -1},
709 
710       // Can only have one "::" contraction in an IPv6 string literal.
711     {"[2001::db8::1]", L"[2001::db8::1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
712       // No more than 2 consecutive ':'s.
713     {"[2001:db8:::1]", L"[2001:db8:::1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
714     {"[:::]", L"[:::]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
715       // Non-IP addresses due to invalid characters.
716     {"[2001::.com]", L"[2001::.com]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
717       // If there are not enough components, the last one should fill them out.
718     // ... omitted at this time ...
719       // Too many components means not an IP address.  Similarly with too few if using IPv4 compat or mapped addresses.
720     {"[::192.168.0.0.1]", L"[::192.168.0.0.1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
721     {"[::ffff:192.168.0.0.1]", L"[::ffff:192.168.0.0.1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
722     {"[1:2:3:4:5:6:7:8:9]", L"[1:2:3:4:5:6:7:8:9]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
723     // Too many bits (even though 8 comonents, the last one holds 32 bits).
724     {"[0:0:0:0:0:0:0:192.168.0.1]", L"[0:0:0:0:0:0:0:192.168.0.1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
725 
726     // Too many bits specified -- the contraction would have to be zero-length
727     // to not exceed 128 bits.
728     {"[1:2:3:4:5:6::192.168.0.1]", L"[1:2:3:4:5:6::192.168.0.1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
729 
730     // The contraction is for 16 bits of zero.
731     {"[1:2:3:4:5:6::8]", L"[1:2:3:4:5:6::8]", "[1:2:3:4:5:6:0:8]", url_parse::Component(0,17), CanonHostInfo::IPV6, -1},
732 
733     // Cannot have a trailing colon.
734     {"[1:2:3:4:5:6:7:8:]", L"[1:2:3:4:5:6:7:8:]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
735     {"[1:2:3:4:5:6:192.168.0.1:]", L"[1:2:3:4:5:6:192.168.0.1:]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
736 
737     // Cannot have negative numbers.
738     {"[-1:2:3:4:5:6:7:8]", L"[-1:2:3:4:5:6:7:8]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
739 
740     // Scope ID -- the URL may contain an optional ["%" <scope_id>] section.
741     // The scope_id should be included in the canonicalized URL, and is an
742     // unsigned decimal number.
743 
744     // Invalid because no ID was given after the percent.
745 
746     // Don't allow scope-id
747     {"[1::%1]", L"[1::%1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
748     {"[1::%eth0]", L"[1::%eth0]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
749     {"[1::%]", L"[1::%]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
750     {"[%]", L"[%]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
751     {"[::%:]", L"[::%:]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
752 
753     // Don't allow leading or trailing colons.
754     {"[:0:0::0:0:8]", L"[:0:0::0:0:8]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
755     {"[0:0::0:0:8:]", L"[0:0::0:0:8:]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
756     {"[:0:0::0:0:8:]", L"[:0:0::0:0:8:]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
757 
758       // We allow a single trailing dot.
759     // ... omitted at this time ...
760       // Two dots in a row means not an IP address.
761     {"[::192.168..1]", L"[::192.168..1]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
762       // Any non-first components get truncated to one byte.
763     // ... omitted at this time ...
764       // Spaces should be rejected.
765     {"[::1 hello]", L"[::1 hello]", "", url_parse::Component(), CanonHostInfo::BROKEN, -1},
766   };
767 
768   for (size_t i = 0; i < arraysize(cases); i++) {
769     // 8-bit version.
770     url_parse::Component component(0,
771                                    static_cast<int>(strlen(cases[i].input8)));
772 
773     std::string out_str1;
774     url_canon::StdStringCanonOutput output1(&out_str1);
775     url_canon::CanonHostInfo host_info;
776     url_canon::CanonicalizeIPAddress(cases[i].input8, component, &output1,
777                                      &host_info);
778     output1.Complete();
779 
780     EXPECT_EQ(cases[i].expected_family, host_info.family);
781     if (host_info.family == CanonHostInfo::IPV6) {
782       EXPECT_STREQ(cases[i].expected, out_str1.c_str());
783       EXPECT_EQ(cases[i].expected_component.begin,
784                 host_info.out_host.begin);
785       EXPECT_EQ(cases[i].expected_component.len, host_info.out_host.len);
786     }
787 
788     // 16-bit version.
789     string16 input16(WStringToUTF16(cases[i].input16));
790     component = url_parse::Component(0, static_cast<int>(input16.length()));
791 
792     std::string out_str2;
793     url_canon::StdStringCanonOutput output2(&out_str2);
794     url_canon::CanonicalizeIPAddress(input16.c_str(), component, &output2,
795                                      &host_info);
796     output2.Complete();
797 
798     EXPECT_EQ(cases[i].expected_family, host_info.family);
799     if (host_info.family == CanonHostInfo::IPV6) {
800       EXPECT_STREQ(cases[i].expected, out_str2.c_str());
801       EXPECT_EQ(cases[i].expected_component.begin, host_info.out_host.begin);
802       EXPECT_EQ(cases[i].expected_component.len, host_info.out_host.len);
803     }
804   }
805 }
806 
TEST(URLCanonTest,IPEmpty)807 TEST(URLCanonTest, IPEmpty) {
808   std::string out_str1;
809   url_canon::StdStringCanonOutput output1(&out_str1);
810   url_canon::CanonHostInfo host_info;
811 
812   // This tests tests.
813   const char spec[] = "192.168.0.1";
814   url_canon::CanonicalizeIPAddress(spec, url_parse::Component(),
815                                    &output1, &host_info);
816   EXPECT_FALSE(host_info.IsIPAddress());
817 
818   url_canon::CanonicalizeIPAddress(spec, url_parse::Component(0, 0),
819                                    &output1, &host_info);
820   EXPECT_FALSE(host_info.IsIPAddress());
821 }
822 
TEST(URLCanonTest,UserInfo)823 TEST(URLCanonTest, UserInfo) {
824   // Note that the canonicalizer should escape and treat empty components as
825   // not being there.
826 
827   // We actually parse a full input URL so we can get the initial components.
828   struct UserComponentCase {
829     const char* input;
830     const char* expected;
831     url_parse::Component expected_username;
832     url_parse::Component expected_password;
833     bool expected_success;
834   } user_info_cases[] = {
835     {"http://user:pass@host.com/", "user:pass@", url_parse::Component(0, 4), url_parse::Component(5, 4), true},
836     {"http://@host.com/", "", url_parse::Component(0, -1), url_parse::Component(0, -1), true},
837     {"http://:@host.com/", "", url_parse::Component(0, -1), url_parse::Component(0, -1), true},
838     {"http://foo:@host.com/", "foo@", url_parse::Component(0, 3), url_parse::Component(0, -1), true},
839     {"http://:foo@host.com/", ":foo@", url_parse::Component(0, 0), url_parse::Component(1, 3), true},
840     {"http://^ :$\t@host.com/", "%5E%20:$%09@", url_parse::Component(0, 6), url_parse::Component(7, 4), true},
841     {"http://user:pass@/", "user:pass@", url_parse::Component(0, 4), url_parse::Component(5, 4), true},
842     {"http://%2540:bar@domain.com/", "%2540:bar@", url_parse::Component(0, 5), url_parse::Component(6, 3), true },
843 
844       // IE7 compatability: old versions allowed backslashes in usernames, but
845       // IE7 does not. We disallow it as well.
846     {"ftp://me\\mydomain:pass@foo.com/", "", url_parse::Component(0, -1), url_parse::Component(0, -1), true},
847   };
848 
849   for (size_t i = 0; i < ARRAYSIZE(user_info_cases); i++) {
850     int url_len = static_cast<int>(strlen(user_info_cases[i].input));
851     url_parse::Parsed parsed;
852     url_parse::ParseStandardURL(user_info_cases[i].input, url_len, &parsed);
853     url_parse::Component out_user, out_pass;
854     std::string out_str;
855     url_canon::StdStringCanonOutput output1(&out_str);
856 
857     bool success = url_canon::CanonicalizeUserInfo(user_info_cases[i].input,
858                                                    parsed.username,
859                                                    user_info_cases[i].input,
860                                                    parsed.password,
861                                                    &output1, &out_user,
862                                                    &out_pass);
863     output1.Complete();
864 
865     EXPECT_EQ(user_info_cases[i].expected_success, success);
866     EXPECT_EQ(std::string(user_info_cases[i].expected), out_str);
867     EXPECT_EQ(user_info_cases[i].expected_username.begin, out_user.begin);
868     EXPECT_EQ(user_info_cases[i].expected_username.len, out_user.len);
869     EXPECT_EQ(user_info_cases[i].expected_password.begin, out_pass.begin);
870     EXPECT_EQ(user_info_cases[i].expected_password.len, out_pass.len);
871 
872     // Now try the wide version
873     out_str.clear();
874     url_canon::StdStringCanonOutput output2(&out_str);
875     string16 wide_input(ConvertUTF8ToUTF16(user_info_cases[i].input));
876     success = url_canon::CanonicalizeUserInfo(wide_input.c_str(),
877                                               parsed.username,
878                                               wide_input.c_str(),
879                                               parsed.password,
880                                               &output2, &out_user, &out_pass);
881     output2.Complete();
882 
883     EXPECT_EQ(user_info_cases[i].expected_success, success);
884     EXPECT_EQ(std::string(user_info_cases[i].expected), out_str);
885     EXPECT_EQ(user_info_cases[i].expected_username.begin, out_user.begin);
886     EXPECT_EQ(user_info_cases[i].expected_username.len, out_user.len);
887     EXPECT_EQ(user_info_cases[i].expected_password.begin, out_pass.begin);
888     EXPECT_EQ(user_info_cases[i].expected_password.len, out_pass.len);
889   }
890 }
891 
TEST(URLCanonTest,Port)892 TEST(URLCanonTest, Port) {
893   // We only need to test that the number gets properly put into the output
894   // buffer. The parser unit tests will test scanning the number correctly.
895   //
896   // Note that the CanonicalizePort will always prepend a colon to the output
897   // to separate it from the colon that it assumes preceeds it.
898   struct PortCase {
899     const char* input;
900     int default_port;
901     const char* expected;
902     url_parse::Component expected_component;
903     bool expected_success;
904   } port_cases[] = {
905       // Invalid input should be copied w/ failure.
906     {"as df", 80, ":as%20df", url_parse::Component(1, 7), false},
907     {"-2", 80, ":-2", url_parse::Component(1, 2), false},
908       // Default port should be omitted.
909     {"80", 80, "", url_parse::Component(0, -1), true},
910     {"8080", 80, ":8080", url_parse::Component(1, 4), true},
911       // PORT_UNSPECIFIED should mean always keep the port.
912     {"80", url_parse::PORT_UNSPECIFIED, ":80", url_parse::Component(1, 2), true},
913   };
914 
915   for (size_t i = 0; i < ARRAYSIZE(port_cases); i++) {
916     int url_len = static_cast<int>(strlen(port_cases[i].input));
917     url_parse::Component in_comp(0, url_len);
918     url_parse::Component out_comp;
919     std::string out_str;
920     url_canon::StdStringCanonOutput output1(&out_str);
921     bool success = url_canon::CanonicalizePort(port_cases[i].input, in_comp,
922                                                port_cases[i].default_port,
923                                                &output1, &out_comp);
924     output1.Complete();
925 
926     EXPECT_EQ(port_cases[i].expected_success, success);
927     EXPECT_EQ(std::string(port_cases[i].expected), out_str);
928     EXPECT_EQ(port_cases[i].expected_component.begin, out_comp.begin);
929     EXPECT_EQ(port_cases[i].expected_component.len, out_comp.len);
930 
931     // Now try the wide version
932     out_str.clear();
933     url_canon::StdStringCanonOutput output2(&out_str);
934     string16 wide_input(ConvertUTF8ToUTF16(port_cases[i].input));
935     success = url_canon::CanonicalizePort(wide_input.c_str(), in_comp,
936                                           port_cases[i].default_port,
937                                           &output2, &out_comp);
938     output2.Complete();
939 
940     EXPECT_EQ(port_cases[i].expected_success, success);
941     EXPECT_EQ(std::string(port_cases[i].expected), out_str);
942     EXPECT_EQ(port_cases[i].expected_component.begin, out_comp.begin);
943     EXPECT_EQ(port_cases[i].expected_component.len, out_comp.len);
944   }
945 }
946 
TEST(URLCanonTest,Path)947 TEST(URLCanonTest, Path) {
948   DualComponentCase path_cases[] = {
949     // ----- path collapsing tests -----
950     {"/././foo", L"/././foo", "/foo", url_parse::Component(0, 4), true},
951     {"/./.foo", L"/./.foo", "/.foo", url_parse::Component(0, 5), true},
952     {"/foo/.", L"/foo/.", "/foo/", url_parse::Component(0, 5), true},
953     {"/foo/./", L"/foo/./", "/foo/", url_parse::Component(0, 5), true},
954       // double dots followed by a slash or the end of the string count
955     {"/foo/bar/..", L"/foo/bar/..", "/foo/", url_parse::Component(0, 5), true},
956     {"/foo/bar/../", L"/foo/bar/../", "/foo/", url_parse::Component(0, 5), true},
957       // don't count double dots when they aren't followed by a slash
958     {"/foo/..bar", L"/foo/..bar", "/foo/..bar", url_parse::Component(0, 10), true},
959       // some in the middle
960     {"/foo/bar/../ton", L"/foo/bar/../ton", "/foo/ton", url_parse::Component(0, 8), true},
961     {"/foo/bar/../ton/../../a", L"/foo/bar/../ton/../../a", "/a", url_parse::Component(0, 2), true},
962       // we should not be able to go above the root
963     {"/foo/../../..", L"/foo/../../..", "/", url_parse::Component(0, 1), true},
964     {"/foo/../../../ton", L"/foo/../../../ton", "/ton", url_parse::Component(0, 4), true},
965       // escaped dots should be unescaped and treated the same as dots
966     {"/foo/%2e", L"/foo/%2e", "/foo/", url_parse::Component(0, 5), true},
967     {"/foo/%2e%2", L"/foo/%2e%2", "/foo/.%2", url_parse::Component(0, 8), true},
968     {"/foo/%2e./%2e%2e/.%2e/%2e.bar", L"/foo/%2e./%2e%2e/.%2e/%2e.bar", "/..bar", url_parse::Component(0, 6), true},
969       // Multiple slashes in a row should be preserved and treated like empty
970       // directory names.
971     {"////../..", L"////../..", "//", url_parse::Component(0, 2), true},
972 
973     // ----- escaping tests -----
974     {"/foo", L"/foo", "/foo", url_parse::Component(0, 4), true},
975       // Valid escape sequence
976     {"/%20foo", L"/%20foo", "/%20foo", url_parse::Component(0, 7), true},
977       // Invalid escape sequence we should pass through unchanged.
978     {"/foo%", L"/foo%", "/foo%", url_parse::Component(0, 5), true},
979     {"/foo%2", L"/foo%2", "/foo%2", url_parse::Component(0, 6), true},
980       // Invalid escape sequence: bad characters should be treated the same as
981       // the sourrounding text, not as escaped (in this case, UTF-8).
982     {"/foo%2zbar", L"/foo%2zbar", "/foo%2zbar", url_parse::Component(0, 10), true},
983     {"/foo%2\xc2\xa9zbar", NULL, "/foo%2%C2%A9zbar", url_parse::Component(0, 16), true},
984     {NULL, L"/foo%2\xc2\xa9zbar", "/foo%2%C3%82%C2%A9zbar", url_parse::Component(0, 22), true},
985       // Regular characters that are escaped should be unescaped
986     {"/foo%41%7a", L"/foo%41%7a", "/fooAz", url_parse::Component(0, 6), true},
987       // Funny characters that are unescaped should be escaped
988     {"/foo\x09\x91%91", NULL, "/foo%09%91%91", url_parse::Component(0, 13), true},
989     {NULL, L"/foo\x09\x91%91", "/foo%09%C2%91%91", url_parse::Component(0, 16), true},
990       // Invalid characters that are escaped should cause a failure.
991     {"/foo%00%51", L"/foo%00%51", "/foo%00Q", url_parse::Component(0, 8), false},
992       // Some characters should be passed through unchanged regardless of esc.
993     {"/(%28:%3A%29)", L"/(%28:%3A%29)", "/(%28:%3A%29)", url_parse::Component(0, 13), true},
994       // Characters that are properly escaped should not have the case changed
995       // of hex letters.
996     {"/%3A%3a%3C%3c", L"/%3A%3a%3C%3c", "/%3A%3a%3C%3c", url_parse::Component(0, 13), true},
997       // Funny characters that are unescaped should be escaped
998     {"/foo\tbar", L"/foo\tbar", "/foo%09bar", url_parse::Component(0, 10), true},
999       // Backslashes should get converted to forward slashes
1000     {"\\foo\\bar", L"\\foo\\bar", "/foo/bar", url_parse::Component(0, 8), true},
1001       // Hashes found in paths (possibly only when the caller explicitly sets
1002       // the path on an already-parsed URL) should be escaped.
1003     {"/foo#bar", L"/foo#bar", "/foo%23bar", url_parse::Component(0, 10), true},
1004       // %7f should be allowed and %3D should not be unescaped (these were wrong
1005       // in a previous version).
1006     {"/%7Ffp3%3Eju%3Dduvgw%3Dd", L"/%7Ffp3%3Eju%3Dduvgw%3Dd", "/%7Ffp3%3Eju%3Dduvgw%3Dd", url_parse::Component(0, 24), true},
1007       // @ should be passed through unchanged (escaped or unescaped).
1008     {"/@asdf%40", L"/@asdf%40", "/@asdf%40", url_parse::Component(0, 9), true},
1009 
1010     // ----- encoding tests -----
1011       // Basic conversions
1012     {"/\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xbd\xa0\xe5\xa5\xbd", L"/\x4f60\x597d\x4f60\x597d", "/%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD", url_parse::Component(0, 37), true},
1013       // Invalid unicode characters should fail. We only do validation on
1014       // UTF-16 input, so this doesn't happen on 8-bit.
1015     {"/\xef\xb7\x90zyx", NULL, "/%EF%B7%90zyx", url_parse::Component(0, 13), true},
1016     {NULL, L"/\xfdd0zyx", "/%EF%BF%BDzyx", url_parse::Component(0, 13), false},
1017   };
1018 
1019   for (size_t i = 0; i < arraysize(path_cases); i++) {
1020     if (path_cases[i].input8) {
1021       int len = static_cast<int>(strlen(path_cases[i].input8));
1022       url_parse::Component in_comp(0, len);
1023       url_parse::Component out_comp;
1024       std::string out_str;
1025       url_canon::StdStringCanonOutput output(&out_str);
1026       bool success = url_canon::CanonicalizePath(path_cases[i].input8, in_comp,
1027                                                  &output, &out_comp);
1028       output.Complete();
1029 
1030       EXPECT_EQ(path_cases[i].expected_success, success);
1031       EXPECT_EQ(path_cases[i].expected_component.begin, out_comp.begin);
1032       EXPECT_EQ(path_cases[i].expected_component.len, out_comp.len);
1033       EXPECT_EQ(path_cases[i].expected, out_str);
1034     }
1035 
1036     if (path_cases[i].input16) {
1037       string16 input16(WStringToUTF16(path_cases[i].input16));
1038       int len = static_cast<int>(input16.length());
1039       url_parse::Component in_comp(0, len);
1040       url_parse::Component out_comp;
1041       std::string out_str;
1042       url_canon::StdStringCanonOutput output(&out_str);
1043 
1044       bool success = url_canon::CanonicalizePath(input16.c_str(), in_comp,
1045                                                  &output, &out_comp);
1046       output.Complete();
1047 
1048       EXPECT_EQ(path_cases[i].expected_success, success);
1049       EXPECT_EQ(path_cases[i].expected_component.begin, out_comp.begin);
1050       EXPECT_EQ(path_cases[i].expected_component.len, out_comp.len);
1051       EXPECT_EQ(path_cases[i].expected, out_str);
1052     }
1053   }
1054 
1055   // Manual test: embedded NULLs should be escaped and the URL should be marked
1056   // as invalid.
1057   const char path_with_null[] = "/ab\0c";
1058   url_parse::Component in_comp(0, 5);
1059   url_parse::Component out_comp;
1060 
1061   std::string out_str;
1062   url_canon::StdStringCanonOutput output(&out_str);
1063   bool success = url_canon::CanonicalizePath(path_with_null, in_comp,
1064                                              &output, &out_comp);
1065   output.Complete();
1066   EXPECT_FALSE(success);
1067   EXPECT_EQ("/ab%00c", out_str);
1068 }
1069 
TEST(URLCanonTest,Query)1070 TEST(URLCanonTest, Query) {
1071   struct QueryCase {
1072     const char* input8;
1073     const wchar_t* input16;
1074     const char* encoding;
1075     const char* expected;
1076   } query_cases[] = {
1077       // Regular ASCII case in some different encodings.
1078     {"foo=bar", L"foo=bar", NULL, "?foo=bar"},
1079     {"foo=bar", L"foo=bar", "utf-8", "?foo=bar"},
1080     {"foo=bar", L"foo=bar", "shift_jis", "?foo=bar"},
1081     {"foo=bar", L"foo=bar", "gb2312", "?foo=bar"},
1082       // Allow question marks in the query without escaping
1083     {"as?df", L"as?df", NULL, "?as?df"},
1084       // Always escape '#' since it would mark the ref.
1085     {"as#df", L"as#df", NULL, "?as%23df"},
1086       // Escape some questionable 8-bit characters, but never unescape.
1087     {"\x02hello\x7f bye", L"\x02hello\x7f bye", NULL, "?%02hello%7F%20bye"},
1088     {"%40%41123", L"%40%41123", NULL, "?%40%41123"},
1089       // Chinese input/output
1090     {"q=\xe4\xbd\xa0\xe5\xa5\xbd", L"q=\x4f60\x597d", NULL, "?q=%E4%BD%A0%E5%A5%BD"},
1091     {"q=\xe4\xbd\xa0\xe5\xa5\xbd", L"q=\x4f60\x597d", "gb2312", "?q=%C4%E3%BA%C3"},
1092     {"q=\xe4\xbd\xa0\xe5\xa5\xbd", L"q=\x4f60\x597d", "big5", "?q=%A7A%A6n"},
1093       // Unencodable character in the destination character set should be
1094       // escaped. The escape sequence unescapes to be the entity name:
1095       // "?q=&#20320;"
1096     {"q=Chinese\xef\xbc\xa7", L"q=Chinese\xff27", "iso-8859-1", "?q=Chinese%26%2365319%3B"},
1097       // Invalid UTF-8/16 input should be replaced with invalid characters.
1098     {"q=\xed\xed", L"q=\xd800\xd800", NULL, "?q=%EF%BF%BD%EF%BF%BD"},
1099       // Don't allow < or > because sometimes they are used for XSS if the
1100       // URL is echoed in content. Firefox does this, IE doesn't.
1101     {"q=<asdf>", L"q=<asdf>", NULL, "?q=%3Casdf%3E"},
1102       // Escape double quotemarks in the query.
1103     {"q=\"asdf\"", L"q=\"asdf\"", NULL, "?q=%22asdf%22"},
1104   };
1105 
1106   for (size_t i = 0; i < ARRAYSIZE(query_cases); i++) {
1107     url_parse::Component out_comp;
1108 
1109     UConvScoper conv(query_cases[i].encoding);
1110     ASSERT_TRUE(!query_cases[i].encoding || conv.converter());
1111     url_canon::ICUCharsetConverter converter(conv.converter());
1112 
1113     // Map NULL to a NULL converter pointer.
1114     url_canon::ICUCharsetConverter* conv_pointer = &converter;
1115     if (!query_cases[i].encoding)
1116       conv_pointer = NULL;
1117 
1118     if (query_cases[i].input8) {
1119       int len = static_cast<int>(strlen(query_cases[i].input8));
1120       url_parse::Component in_comp(0, len);
1121       std::string out_str;
1122 
1123       url_canon::StdStringCanonOutput output(&out_str);
1124       url_canon::CanonicalizeQuery(query_cases[i].input8, in_comp,
1125                                    conv_pointer, &output, &out_comp);
1126       output.Complete();
1127 
1128       EXPECT_EQ(query_cases[i].expected, out_str);
1129     }
1130 
1131     if (query_cases[i].input16) {
1132       string16 input16(WStringToUTF16(query_cases[i].input16));
1133       int len = static_cast<int>(input16.length());
1134       url_parse::Component in_comp(0, len);
1135       std::string out_str;
1136 
1137       url_canon::StdStringCanonOutput output(&out_str);
1138       url_canon::CanonicalizeQuery(input16.c_str(), in_comp,
1139                                    conv_pointer, &output, &out_comp);
1140       output.Complete();
1141 
1142       EXPECT_EQ(query_cases[i].expected, out_str);
1143     }
1144   }
1145 
1146   // Extra test for input with embedded NULL;
1147   std::string out_str;
1148   url_canon::StdStringCanonOutput output(&out_str);
1149   url_parse::Component out_comp;
1150   url_canon::CanonicalizeQuery("a \x00z\x01", url_parse::Component(0, 5), NULL,
1151                                &output, &out_comp);
1152   output.Complete();
1153   EXPECT_EQ("?a%20%00z%01", out_str);
1154 }
1155 
TEST(URLCanonTest,Ref)1156 TEST(URLCanonTest, Ref) {
1157   // Refs are trivial, it just checks the encoding.
1158   DualComponentCase ref_cases[] = {
1159       // Regular one, we shouldn't escape spaces, et al.
1160     {"hello, world", L"hello, world", "#hello, world", url_parse::Component(1, 12), true},
1161       // UTF-8/wide input should be preserved
1162     {"\xc2\xa9", L"\xa9", "#\xc2\xa9", url_parse::Component(1, 2), true},
1163       // Test a characer that takes > 16 bits (U+10300 = old italic letter A)
1164     {"\xF0\x90\x8C\x80ss", L"\xd800\xdf00ss", "#\xF0\x90\x8C\x80ss", url_parse::Component(1, 6), true},
1165       // Escaping should be preserved unchanged, even invalid ones
1166     {"%41%a", L"%41%a", "#%41%a", url_parse::Component(1, 5), true},
1167       // Invalid UTF-8/16 input should be flagged and the input made valid
1168     {"\xc2", NULL, "#\xef\xbf\xbd", url_parse::Component(1, 3), true},
1169     {NULL, L"\xd800\x597d", "#\xef\xbf\xbd\xe5\xa5\xbd", url_parse::Component(1, 6), true},
1170       // Test a Unicode invalid character.
1171     {"a\xef\xb7\x90", L"a\xfdd0", "#a\xef\xbf\xbd", url_parse::Component(1, 4), true},
1172       // Refs can have # signs and we should preserve them.
1173     {"asdf#qwer", L"asdf#qwer", "#asdf#qwer", url_parse::Component(1, 9), true},
1174     {"#asdf", L"#asdf", "##asdf", url_parse::Component(1, 5), true},
1175   };
1176 
1177   for (size_t i = 0; i < arraysize(ref_cases); i++) {
1178     // 8-bit input
1179     if (ref_cases[i].input8) {
1180       int len = static_cast<int>(strlen(ref_cases[i].input8));
1181       url_parse::Component in_comp(0, len);
1182       url_parse::Component out_comp;
1183 
1184       std::string out_str;
1185       url_canon::StdStringCanonOutput output(&out_str);
1186       url_canon::CanonicalizeRef(ref_cases[i].input8, in_comp,
1187                                  &output, &out_comp);
1188       output.Complete();
1189 
1190       EXPECT_EQ(ref_cases[i].expected_component.begin, out_comp.begin);
1191       EXPECT_EQ(ref_cases[i].expected_component.len, out_comp.len);
1192       EXPECT_EQ(ref_cases[i].expected, out_str);
1193     }
1194 
1195     // 16-bit input
1196     if (ref_cases[i].input16) {
1197       string16 input16(WStringToUTF16(ref_cases[i].input16));
1198       int len = static_cast<int>(input16.length());
1199       url_parse::Component in_comp(0, len);
1200       url_parse::Component out_comp;
1201 
1202       std::string out_str;
1203       url_canon::StdStringCanonOutput output(&out_str);
1204       url_canon::CanonicalizeRef(input16.c_str(), in_comp, &output, &out_comp);
1205       output.Complete();
1206 
1207       EXPECT_EQ(ref_cases[i].expected_component.begin, out_comp.begin);
1208       EXPECT_EQ(ref_cases[i].expected_component.len, out_comp.len);
1209       EXPECT_EQ(ref_cases[i].expected, out_str);
1210     }
1211   }
1212 
1213   // Try one with an embedded NULL. It should be stripped.
1214   const char null_input[5] = "ab\x00z";
1215   url_parse::Component null_input_component(0, 4);
1216   url_parse::Component out_comp;
1217 
1218   std::string out_str;
1219   url_canon::StdStringCanonOutput output(&out_str);
1220   url_canon::CanonicalizeRef(null_input, null_input_component,
1221                              &output, &out_comp);
1222   output.Complete();
1223 
1224   EXPECT_EQ(1, out_comp.begin);
1225   EXPECT_EQ(3, out_comp.len);
1226   EXPECT_EQ("#abz", out_str);
1227 }
1228 
TEST(URLCanonTest,CanonicalizeStandardURL)1229 TEST(URLCanonTest, CanonicalizeStandardURL) {
1230   // The individual component canonicalize tests should have caught the cases
1231   // for each of those components. Here, we just need to test that the various
1232   // parts are included or excluded properly, and have the correct separators.
1233   struct URLCase {
1234     const char* input;
1235     const char* expected;
1236     bool expected_success;
1237   } cases[] = {
1238     {"http://www.google.com/foo?bar=baz#", "http://www.google.com/foo?bar=baz#", true},
1239     {"http://[www.google.com]/", "http://[www.google.com]/", false},
1240     {"ht\ttp:@www.google.com:80/;p?#", "ht%09tp://www.google.com:80/;p?#", false},
1241     {"http:////////user:@google.com:99?foo", "http://user@google.com:99/?foo", true},
1242     {"www.google.com", ":www.google.com/", true},
1243     {"http://192.0x00A80001", "http://192.168.0.1/", true},
1244     {"http://www/foo%2Ehtml", "http://www/foo.html", true},
1245     {"http://user:pass@/", "http://user:pass@/", false},
1246     {"http://%25DOMAIN:foobar@foodomain.com/", "http://%25DOMAIN:foobar@foodomain.com/", true},
1247 
1248       // Backslashes should get converted to forward slashes.
1249     {"http:\\\\www.google.com\\foo", "http://www.google.com/foo", true},
1250 
1251       // Busted refs shouldn't make the whole thing fail.
1252     {"http://www.google.com/asdf#\xc2", "http://www.google.com/asdf#\xef\xbf\xbd", true},
1253 
1254       // Basic port tests.
1255     {"http://foo:80/", "http://foo/", true},
1256     {"http://foo:81/", "http://foo:81/", true},
1257     {"httpa://foo:80/", "httpa://foo:80/", true},
1258     {"http://foo:-80/", "http://foo:-80/", false},
1259 
1260     {"https://foo:443/", "https://foo/", true},
1261     {"https://foo:80/", "https://foo:80/", true},
1262     {"ftp://foo:21/", "ftp://foo/", true},
1263     {"ftp://foo:80/", "ftp://foo:80/", true},
1264     {"gopher://foo:70/", "gopher://foo/", true},
1265     {"gopher://foo:443/", "gopher://foo:443/", true},
1266     {"ws://foo:80/", "ws://foo/", true},
1267     {"ws://foo:81/", "ws://foo:81/", true},
1268     {"ws://foo:443/", "ws://foo:443/", true},
1269     {"ws://foo:815/", "ws://foo:815/", true},
1270     {"wss://foo:80/", "wss://foo:80/", true},
1271     {"wss://foo:81/", "wss://foo:81/", true},
1272     {"wss://foo:443/", "wss://foo/", true},
1273     {"wss://foo:815/", "wss://foo:815/", true},
1274   };
1275 
1276   for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
1277     int url_len = static_cast<int>(strlen(cases[i].input));
1278     url_parse::Parsed parsed;
1279     url_parse::ParseStandardURL(cases[i].input, url_len, &parsed);
1280 
1281     url_parse::Parsed out_parsed;
1282     std::string out_str;
1283     url_canon::StdStringCanonOutput output(&out_str);
1284     bool success = url_canon::CanonicalizeStandardURL(
1285         cases[i].input, url_len, parsed, NULL, &output, &out_parsed);
1286     output.Complete();
1287 
1288     EXPECT_EQ(cases[i].expected_success, success);
1289     EXPECT_EQ(cases[i].expected, out_str);
1290   }
1291 }
1292 
1293 // The codepath here is the same as for regular canonicalization, so we just
1294 // need to test that things are replaced or not correctly.
TEST(URLCanonTest,ReplaceStandardURL)1295 TEST(URLCanonTest, ReplaceStandardURL) {
1296   ReplaceCase replace_cases[] = {
1297       // Common case of truncating the path.
1298     {"http://www.google.com/foo?bar=baz#ref", NULL, NULL, NULL, NULL, NULL, "/", kDeleteComp, kDeleteComp, "http://www.google.com/"},
1299       // Replace everything
1300     {"http://a:b@google.com:22/foo;bar?baz@cat", "https", "me", "pw", "host.com", "99", "/path", "query", "ref", "https://me:pw@host.com:99/path?query#ref"},
1301       // Replace nothing
1302     {"http://a:b@google.com:22/foo?baz@cat", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "http://a:b@google.com:22/foo?baz@cat"},
1303   };
1304 
1305   for (size_t i = 0; i < arraysize(replace_cases); i++) {
1306     const ReplaceCase& cur = replace_cases[i];
1307     int base_len = static_cast<int>(strlen(cur.base));
1308     url_parse::Parsed parsed;
1309     url_parse::ParseStandardURL(cur.base, base_len, &parsed);
1310 
1311     url_canon::Replacements<char> r;
1312     typedef url_canon::Replacements<char> R;  // Clean up syntax.
1313 
1314     // Note that for the scheme we pass in a different clear function since
1315     // there is no function to clear the scheme.
1316     SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
1317     SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
1318     SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
1319     SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
1320     SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
1321     SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
1322     SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
1323     SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
1324 
1325     std::string out_str;
1326     url_canon::StdStringCanonOutput output(&out_str);
1327     url_parse::Parsed out_parsed;
1328     url_canon::ReplaceStandardURL(replace_cases[i].base, parsed,
1329                                   r, NULL, &output, &out_parsed);
1330     output.Complete();
1331 
1332     EXPECT_EQ(replace_cases[i].expected, out_str);
1333   }
1334 
1335   // The path pointer should be ignored if the address is invalid.
1336   {
1337     const char src[] = "http://www.google.com/here_is_the_path";
1338     int src_len = static_cast<int>(strlen(src));
1339 
1340     url_parse::Parsed parsed;
1341     url_parse::ParseStandardURL(src, src_len, &parsed);
1342 
1343     // Replace the path to 0 length string. By using 1 as the string address,
1344     // the test should get an access violation if it tries to dereference it.
1345     url_canon::Replacements<char> r;
1346     r.SetPath(reinterpret_cast<char*>(0x00000001), url_parse::Component(0, 0));
1347     std::string out_str1;
1348     url_canon::StdStringCanonOutput output1(&out_str1);
1349     url_parse::Parsed new_parsed;
1350     url_canon::ReplaceStandardURL(src, parsed, r, NULL, &output1, &new_parsed);
1351     output1.Complete();
1352     EXPECT_STREQ("http://www.google.com/", out_str1.c_str());
1353 
1354     // Same with an "invalid" path.
1355     r.SetPath(reinterpret_cast<char*>(0x00000001), url_parse::Component());
1356     std::string out_str2;
1357     url_canon::StdStringCanonOutput output2(&out_str2);
1358     url_canon::ReplaceStandardURL(src, parsed, r, NULL, &output2, &new_parsed);
1359     output2.Complete();
1360     EXPECT_STREQ("http://www.google.com/", out_str2.c_str());
1361   }
1362 }
1363 
TEST(URLCanonTest,ReplaceFileURL)1364 TEST(URLCanonTest, ReplaceFileURL) {
1365   ReplaceCase replace_cases[] = {
1366       // Replace everything
1367     {"file:///C:/gaba?query#ref", NULL, NULL, NULL, "filer", NULL, "/foo", "b", "c", "file://filer/foo?b#c"},
1368       // Replace nothing
1369     {"file:///C:/gaba?query#ref", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "file:///C:/gaba?query#ref"},
1370       // Clear non-path components (common)
1371     {"file:///C:/gaba?query#ref", NULL, NULL, NULL, NULL, NULL, NULL, kDeleteComp, kDeleteComp, "file:///C:/gaba"},
1372       // Replace path with something that doesn't begin with a slash and make
1373       // sure it get added properly.
1374     {"file:///C:/gaba", NULL, NULL, NULL, NULL, NULL, "interesting/", NULL, NULL, "file:///interesting/"},
1375     {"file:///home/gaba?query#ref", NULL, NULL, NULL, "filer", NULL, "/foo", "b", "c", "file://filer/foo?b#c"},
1376     {"file:///home/gaba?query#ref", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "file:///home/gaba?query#ref"},
1377     {"file:///home/gaba?query#ref", NULL, NULL, NULL, NULL, NULL, NULL, kDeleteComp, kDeleteComp, "file:///home/gaba"},
1378     {"file:///home/gaba", NULL, NULL, NULL, NULL, NULL, "interesting/", NULL, NULL, "file:///interesting/"},
1379   };
1380 
1381   for (size_t i = 0; i < arraysize(replace_cases); i++) {
1382     const ReplaceCase& cur = replace_cases[i];
1383     int base_len = static_cast<int>(strlen(cur.base));
1384     url_parse::Parsed parsed;
1385     url_parse::ParseFileURL(cur.base, base_len, &parsed);
1386 
1387     url_canon::Replacements<char> r;
1388     typedef url_canon::Replacements<char> R;  // Clean up syntax.
1389     SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
1390     SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
1391     SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
1392     SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
1393     SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
1394     SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
1395     SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
1396     SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
1397 
1398     std::string out_str;
1399     url_canon::StdStringCanonOutput output(&out_str);
1400     url_parse::Parsed out_parsed;
1401     url_canon::ReplaceFileURL(cur.base, parsed,
1402                               r, NULL, &output, &out_parsed);
1403     output.Complete();
1404 
1405     EXPECT_EQ(replace_cases[i].expected, out_str);
1406   }
1407 }
1408 
TEST(URLCanonTest,ReplacePathURL)1409 TEST(URLCanonTest, ReplacePathURL) {
1410   ReplaceCase replace_cases[] = {
1411       // Replace everything
1412     {"data:foo", "javascript", NULL, NULL, NULL, NULL, "alert('foo?');", NULL, NULL, "javascript:alert('foo?');"},
1413       // Replace nothing
1414     {"data:foo", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "data:foo"},
1415       // Replace one or the other
1416     {"data:foo", "javascript", NULL, NULL, NULL, NULL, NULL, NULL, NULL, "javascript:foo"},
1417     {"data:foo", NULL, NULL, NULL, NULL, NULL, "bar", NULL, NULL, "data:bar"},
1418     {"data:foo", NULL, NULL, NULL, NULL, NULL, kDeleteComp, NULL, NULL, "data:"},
1419   };
1420 
1421   for (size_t i = 0; i < arraysize(replace_cases); i++) {
1422     const ReplaceCase& cur = replace_cases[i];
1423     int base_len = static_cast<int>(strlen(cur.base));
1424     url_parse::Parsed parsed;
1425     url_parse::ParsePathURL(cur.base, base_len, &parsed);
1426 
1427     url_canon::Replacements<char> r;
1428     typedef url_canon::Replacements<char> R;  // Clean up syntax.
1429     SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
1430     SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
1431     SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
1432     SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
1433     SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
1434     SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
1435     SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
1436     SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
1437 
1438     std::string out_str;
1439     url_canon::StdStringCanonOutput output(&out_str);
1440     url_parse::Parsed out_parsed;
1441     url_canon::ReplacePathURL(cur.base, parsed,
1442                               r, &output, &out_parsed);
1443     output.Complete();
1444 
1445     EXPECT_EQ(replace_cases[i].expected, out_str);
1446   }
1447 }
1448 
TEST(URLCanonTest,ReplaceMailtoURL)1449 TEST(URLCanonTest, ReplaceMailtoURL) {
1450   ReplaceCase replace_cases[] = {
1451       // Replace everything
1452     {"mailto:jon@foo.com?body=sup", "mailto", NULL, NULL, NULL, NULL, "addr1", "to=tony", NULL, "mailto:addr1?to=tony"},
1453       // Replace nothing
1454     {"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "mailto:jon@foo.com?body=sup"},
1455       // Replace the path
1456     {"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, "jason", NULL, NULL, "mailto:jason?body=sup"},
1457       // Replace the query
1458     {"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, NULL, "custom=1", NULL, "mailto:jon@foo.com?custom=1"},
1459       // Replace the path and query
1460     {"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, "jason", "custom=1", NULL, "mailto:jason?custom=1"},
1461       // Set the query to empty (should leave trailing question mark)
1462     {"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, NULL, "", NULL, "mailto:jon@foo.com?"},
1463       // Clear the query
1464     {"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, NULL, "|", NULL, "mailto:jon@foo.com"},
1465       // Clear the path
1466     {"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, "|", NULL, NULL, "mailto:?body=sup"},
1467       // Clear the path + query
1468     {"mailto:", NULL, NULL, NULL, NULL, NULL, "|", "|", NULL, "mailto:"},
1469       // Setting the ref should have no effect
1470     {"mailto:addr1", NULL, NULL, NULL, NULL, NULL, NULL, NULL, "BLAH", "mailto:addr1"},
1471   };
1472 
1473   for (size_t i = 0; i < arraysize(replace_cases); i++) {
1474     const ReplaceCase& cur = replace_cases[i];
1475     int base_len = static_cast<int>(strlen(cur.base));
1476     url_parse::Parsed parsed;
1477     url_parse::ParseMailtoURL(cur.base, base_len, &parsed);
1478 
1479     url_canon::Replacements<char> r;
1480     typedef url_canon::Replacements<char> R;
1481     SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
1482     SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
1483     SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
1484     SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
1485     SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
1486     SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
1487     SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
1488     SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
1489 
1490     std::string out_str;
1491     url_canon::StdStringCanonOutput output(&out_str);
1492     url_parse::Parsed out_parsed;
1493     url_canon::ReplaceMailtoURL(cur.base, parsed,
1494                                 r, &output, &out_parsed);
1495     output.Complete();
1496 
1497     EXPECT_EQ(replace_cases[i].expected, out_str);
1498   }
1499 }
1500 
TEST(URLCanonTest,CanonicalizeFileURL)1501 TEST(URLCanonTest, CanonicalizeFileURL) {
1502   struct URLCase {
1503     const char* input;
1504     const char* expected;
1505     bool expected_success;
1506     url_parse::Component expected_host;
1507     url_parse::Component expected_path;
1508   } cases[] = {
1509 #ifdef _WIN32
1510       // Windows-style paths
1511     {"file:c:\\foo\\bar.html", "file:///C:/foo/bar.html", true, url_parse::Component(), url_parse::Component(7, 16)},
1512     {"  File:c|////foo\\bar.html", "file:///C:////foo/bar.html", true, url_parse::Component(), url_parse::Component(7, 19)},
1513     {"file:", "file:///", true, url_parse::Component(), url_parse::Component(7, 1)},
1514     {"file:UNChost/path", "file://unchost/path", true, url_parse::Component(7, 7), url_parse::Component(14, 5)},
1515       // CanonicalizeFileURL supports absolute Windows style paths for IE
1516       // compatability. Note that the caller must decide that this is a file
1517       // URL itself so it can call the file canonicalizer. This is usually
1518       // done automatically as part of relative URL resolving.
1519     {"c:\\foo\\bar", "file:///C:/foo/bar", true, url_parse::Component(), url_parse::Component(7, 11)},
1520     {"C|/foo/bar", "file:///C:/foo/bar", true, url_parse::Component(), url_parse::Component(7, 11)},
1521     {"/C|\\foo\\bar", "file:///C:/foo/bar", true, url_parse::Component(), url_parse::Component(7, 11)},
1522     {"//C|/foo/bar", "file:///C:/foo/bar", true, url_parse::Component(), url_parse::Component(7, 11)},
1523     {"//server/file", "file://server/file", true, url_parse::Component(7, 6), url_parse::Component(13, 5)},
1524     {"\\\\server\\file", "file://server/file", true, url_parse::Component(7, 6), url_parse::Component(13, 5)},
1525     {"/\\server/file", "file://server/file", true, url_parse::Component(7, 6), url_parse::Component(13, 5)},
1526       // We should preserve the number of slashes after the colon for IE
1527       // compatability, except when there is none, in which case we should
1528       // add one.
1529     {"file:c:foo/bar.html", "file:///C:/foo/bar.html", true, url_parse::Component(), url_parse::Component(7, 16)},
1530     {"file:/\\/\\C:\\\\//foo\\bar.html", "file:///C:////foo/bar.html", true, url_parse::Component(), url_parse::Component(7, 19)},
1531       // Three slashes should be non-UNC, even if there is no drive spec (IE
1532       // does this, which makes the resulting request invalid).
1533     {"file:///foo/bar.txt", "file:///foo/bar.txt", true, url_parse::Component(), url_parse::Component(7, 12)},
1534       // TODO(brettw) we should probably fail for invalid host names, which
1535       // would change the expected result on this test. We also currently allow
1536       // colon even though it's probably invalid, because its currently the
1537       // "natural" result of the way the canonicalizer is written. There doesn't
1538       // seem to be a strong argument for why allowing it here would be bad, so
1539       // we just tolerate it and the load will fail later.
1540     {"FILE:/\\/\\7:\\\\//foo\\bar.html", "file://7:////foo/bar.html", false, url_parse::Component(7, 2), url_parse::Component(9, 16)},
1541     {"file:filer/home\\me", "file://filer/home/me", true, url_parse::Component(7, 5), url_parse::Component(12, 8)},
1542       // Make sure relative paths can't go above the "C:"
1543     {"file:///C:/foo/../../../bar.html", "file:///C:/bar.html", true, url_parse::Component(), url_parse::Component(7, 12)},
1544       // Busted refs shouldn't make the whole thing fail.
1545     {"file:///C:/asdf#\xc2", "file:///C:/asdf#\xef\xbf\xbd", true, url_parse::Component(), url_parse::Component(7, 8)},
1546 #else
1547       // Unix-style paths
1548     {"file:///home/me", "file:///home/me", true, url_parse::Component(), url_parse::Component(7, 8)},
1549       // Windowsy ones should get still treated as Unix-style.
1550     {"file:c:\\foo\\bar.html", "file:///c:/foo/bar.html", true, url_parse::Component(), url_parse::Component(7, 16)},
1551     {"file:c|//foo\\bar.html", "file:///c%7C//foo/bar.html", true, url_parse::Component(), url_parse::Component(7, 19)},
1552       // file: tests from WebKit (LayoutTests/fast/loader/url-parse-1.html)
1553     {"//", "file:///", true, url_parse::Component(), url_parse::Component(7, 1)},
1554     {"///", "file:///", true, url_parse::Component(), url_parse::Component(7, 1)},
1555     {"///test", "file:///test", true, url_parse::Component(), url_parse::Component(7, 5)},
1556     {"file://test", "file://test/", true, url_parse::Component(7, 4), url_parse::Component(11, 1)},
1557     {"file://localhost",  "file://localhost/", true, url_parse::Component(7, 9), url_parse::Component(16, 1)},
1558     {"file://localhost/", "file://localhost/", true, url_parse::Component(7, 9), url_parse::Component(16, 1)},
1559     {"file://localhost/test", "file://localhost/test", true, url_parse::Component(7, 9), url_parse::Component(16, 5)},
1560 #endif  // _WIN32
1561   };
1562 
1563   for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
1564     int url_len = static_cast<int>(strlen(cases[i].input));
1565     url_parse::Parsed parsed;
1566     url_parse::ParseFileURL(cases[i].input, url_len, &parsed);
1567 
1568     url_parse::Parsed out_parsed;
1569     std::string out_str;
1570     url_canon::StdStringCanonOutput output(&out_str);
1571     bool success = url_canon::CanonicalizeFileURL(cases[i].input, url_len,
1572                                                   parsed, NULL, &output,
1573                                                   &out_parsed);
1574     output.Complete();
1575 
1576     EXPECT_EQ(cases[i].expected_success, success);
1577     EXPECT_EQ(cases[i].expected, out_str);
1578 
1579     // Make sure the spec was properly identified, the file canonicalizer has
1580     // different code for writing the spec.
1581     EXPECT_EQ(0, out_parsed.scheme.begin);
1582     EXPECT_EQ(4, out_parsed.scheme.len);
1583 
1584     EXPECT_EQ(cases[i].expected_host.begin, out_parsed.host.begin);
1585     EXPECT_EQ(cases[i].expected_host.len, out_parsed.host.len);
1586 
1587     EXPECT_EQ(cases[i].expected_path.begin, out_parsed.path.begin);
1588     EXPECT_EQ(cases[i].expected_path.len, out_parsed.path.len);
1589   }
1590 }
1591 
TEST(URLCanonTest,CanonicalizePathURL)1592 TEST(URLCanonTest, CanonicalizePathURL) {
1593   // Path URLs should get canonicalized schemes but nothing else.
1594   struct PathCase {
1595     const char* input;
1596     const char* expected;
1597   } path_cases[] = {
1598     {"javascript:", "javascript:"},
1599     {"JavaScript:Foo", "javascript:Foo"},
1600     {":\":This /is interesting;?#", ":\":This /is interesting;?#"},
1601   };
1602 
1603   for (size_t i = 0; i < ARRAYSIZE(path_cases); i++) {
1604     int url_len = static_cast<int>(strlen(path_cases[i].input));
1605     url_parse::Parsed parsed;
1606     url_parse::ParsePathURL(path_cases[i].input, url_len, &parsed);
1607 
1608     url_parse::Parsed out_parsed;
1609     std::string out_str;
1610     url_canon::StdStringCanonOutput output(&out_str);
1611     bool success = url_canon::CanonicalizePathURL(path_cases[i].input, url_len,
1612                                                   parsed, &output,
1613                                                   &out_parsed);
1614     output.Complete();
1615 
1616     EXPECT_TRUE(success);
1617     EXPECT_EQ(path_cases[i].expected, out_str);
1618 
1619     EXPECT_EQ(0, out_parsed.host.begin);
1620     EXPECT_EQ(-1, out_parsed.host.len);
1621 
1622     // When we end with a colon at the end, there should be no path.
1623     if (path_cases[i].input[url_len - 1] == ':') {
1624       EXPECT_EQ(0, out_parsed.path.begin);
1625       EXPECT_EQ(-1, out_parsed.path.len);
1626     }
1627   }
1628 }
1629 
TEST(URLCanonTest,CanonicalizeMailtoURL)1630 TEST(URLCanonTest, CanonicalizeMailtoURL) {
1631   struct URLCase {
1632     const char* input;
1633     const char* expected;
1634     bool expected_success;
1635     url_parse::Component expected_path;
1636     url_parse::Component expected_query;
1637   } cases[] = {
1638     {"mailto:addr1", "mailto:addr1", true, url_parse::Component(7, 5), url_parse::Component()},
1639     {"mailto:addr1@foo.com", "mailto:addr1@foo.com", true, url_parse::Component(7, 13), url_parse::Component()},
1640     // Trailing whitespace is stripped.
1641     {"MaIlTo:addr1 \t ", "mailto:addr1", true, url_parse::Component(7, 5), url_parse::Component()},
1642     {"MaIlTo:addr1?to=jon", "mailto:addr1?to=jon", true, url_parse::Component(7, 5), url_parse::Component(13,6)},
1643     {"mailto:addr1,addr2", "mailto:addr1,addr2", true, url_parse::Component(7, 11), url_parse::Component()},
1644     {"mailto:addr1, addr2", "mailto:addr1, addr2", true, url_parse::Component(7, 12), url_parse::Component()},
1645     {"mailto:addr1%2caddr2", "mailto:addr1%2caddr2", true, url_parse::Component(7, 13), url_parse::Component()},
1646     {"mailto:\xF0\x90\x8C\x80", "mailto:%F0%90%8C%80", true, url_parse::Component(7, 12), url_parse::Component()},
1647     // Null character should be escaped to %00
1648     {"mailto:addr1\0addr2?foo", "mailto:addr1%00addr2?foo", true, url_parse::Component(7, 13), url_parse::Component(21, 3)},
1649     // Invalid -- UTF-8 encoded surrogate value.
1650     {"mailto:\xed\xa0\x80", "mailto:%EF%BF%BD", false, url_parse::Component(7, 9), url_parse::Component()},
1651     {"mailto:addr1?", "mailto:addr1?", true, url_parse::Component(7, 5), url_parse::Component(13, 0)},
1652   };
1653 
1654   // Define outside of loop to catch bugs where components aren't reset
1655   url_parse::Parsed parsed;
1656   url_parse::Parsed out_parsed;
1657 
1658   for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
1659     int url_len = static_cast<int>(strlen(cases[i].input));
1660     if (i == 8) {
1661       // The 9th test case purposely has a '\0' in it -- don't count it
1662       // as the string terminator.
1663       url_len = 22;
1664     }
1665     url_parse::ParseMailtoURL(cases[i].input, url_len, &parsed);
1666 
1667     std::string out_str;
1668     url_canon::StdStringCanonOutput output(&out_str);
1669     bool success = url_canon::CanonicalizeMailtoURL(cases[i].input, url_len,
1670                                                     parsed, &output,
1671                                                     &out_parsed);
1672     output.Complete();
1673 
1674     EXPECT_EQ(cases[i].expected_success, success);
1675     EXPECT_EQ(cases[i].expected, out_str);
1676 
1677     // Make sure the spec was properly identified
1678     EXPECT_EQ(0, out_parsed.scheme.begin);
1679     EXPECT_EQ(6, out_parsed.scheme.len);
1680 
1681     EXPECT_EQ(cases[i].expected_path.begin, out_parsed.path.begin);
1682     EXPECT_EQ(cases[i].expected_path.len, out_parsed.path.len);
1683 
1684     EXPECT_EQ(cases[i].expected_query.begin, out_parsed.query.begin);
1685     EXPECT_EQ(cases[i].expected_query.len, out_parsed.query.len);
1686   }
1687 }
1688 
1689 #ifndef WIN32
1690 
TEST(URLCanonTest,_itoa_s)1691 TEST(URLCanonTest, _itoa_s) {
1692   // We fill the buffer with 0xff to ensure that it's getting properly
1693   // null-terminated.  We also allocate one byte more than what we tell
1694   // _itoa_s about, and ensure that the extra byte is untouched.
1695   char buf[6];
1696   memset(buf, 0xff, sizeof(buf));
1697   EXPECT_EQ(0, url_canon::_itoa_s(12, buf, sizeof(buf) - 1, 10));
1698   EXPECT_STREQ("12", buf);
1699   EXPECT_EQ('\xFF', buf[3]);
1700 
1701   // Test the edge cases - exactly the buffer size and one over
1702   memset(buf, 0xff, sizeof(buf));
1703   EXPECT_EQ(0, url_canon::_itoa_s(1234, buf, sizeof(buf) - 1, 10));
1704   EXPECT_STREQ("1234", buf);
1705   EXPECT_EQ('\xFF', buf[5]);
1706 
1707   memset(buf, 0xff, sizeof(buf));
1708   EXPECT_EQ(EINVAL, url_canon::_itoa_s(12345, buf, sizeof(buf) - 1, 10));
1709   EXPECT_EQ('\xFF', buf[5]);  // should never write to this location
1710 
1711   // Test the template overload (note that this will see the full buffer)
1712   memset(buf, 0xff, sizeof(buf));
1713   EXPECT_EQ(0, url_canon::_itoa_s(12, buf, 10));
1714   EXPECT_STREQ("12", buf);
1715   EXPECT_EQ('\xFF', buf[3]);
1716 
1717   memset(buf, 0xff, sizeof(buf));
1718   EXPECT_EQ(0, url_canon::_itoa_s(12345, buf, 10));
1719   EXPECT_STREQ("12345", buf);
1720 
1721   EXPECT_EQ(EINVAL, url_canon::_itoa_s(123456, buf, 10));
1722 
1723   // Test that radix 16 is supported.
1724   memset(buf, 0xff, sizeof(buf));
1725   EXPECT_EQ(0, url_canon::_itoa_s(1234, buf, sizeof(buf) - 1, 16));
1726   EXPECT_STREQ("4d2", buf);
1727   EXPECT_EQ('\xFF', buf[5]);
1728 }
1729 
TEST(URLCanonTest,_itow_s)1730 TEST(URLCanonTest, _itow_s) {
1731   // We fill the buffer with 0xff to ensure that it's getting properly
1732   // null-terminated.  We also allocate one byte more than what we tell
1733   // _itoa_s about, and ensure that the extra byte is untouched.
1734   char16 buf[6];
1735   const char fill_mem = 0xff;
1736   const char16 fill_char = 0xffff;
1737   memset(buf, fill_mem, sizeof(buf));
1738   EXPECT_EQ(0, url_canon::_itow_s(12, buf, sizeof(buf) / 2 - 1, 10));
1739   EXPECT_EQ(WStringToUTF16(L"12"), string16(buf));
1740   EXPECT_EQ(fill_char, buf[3]);
1741 
1742   // Test the edge cases - exactly the buffer size and one over
1743   EXPECT_EQ(0, url_canon::_itow_s(1234, buf, sizeof(buf) / 2 - 1, 10));
1744   EXPECT_EQ(WStringToUTF16(L"1234"), string16(buf));
1745   EXPECT_EQ(fill_char, buf[5]);
1746 
1747   memset(buf, fill_mem, sizeof(buf));
1748   EXPECT_EQ(EINVAL, url_canon::_itow_s(12345, buf, sizeof(buf) / 2 - 1, 10));
1749   EXPECT_EQ(fill_char, buf[5]);  // should never write to this location
1750 
1751   // Test the template overload (note that this will see the full buffer)
1752   memset(buf, fill_mem, sizeof(buf));
1753   EXPECT_EQ(0, url_canon::_itow_s(12, buf, 10));
1754   EXPECT_EQ(WStringToUTF16(L"12"), string16(buf));
1755   EXPECT_EQ(fill_char, buf[3]);
1756 
1757   memset(buf, fill_mem, sizeof(buf));
1758   EXPECT_EQ(0, url_canon::_itow_s(12345, buf, 10));
1759   EXPECT_EQ(WStringToUTF16(L"12345"), string16(buf));
1760 
1761   EXPECT_EQ(EINVAL, url_canon::_itow_s(123456, buf, 10));
1762 }
1763 
1764 #endif  // !WIN32
1765 
1766 // Returns true if the given two structures are the same.
ParsedIsEqual(const url_parse::Parsed & a,const url_parse::Parsed & b)1767 static bool ParsedIsEqual(const url_parse::Parsed& a,
1768                           const url_parse::Parsed& b) {
1769   return a.scheme.begin == b.scheme.begin && a.scheme.len == b.scheme.len &&
1770          a.username.begin == b.username.begin && a.username.len == b.username.len &&
1771          a.password.begin == b.password.begin && a.password.len == b.password.len &&
1772          a.host.begin == b.host.begin && a.host.len == b.host.len &&
1773          a.port.begin == b.port.begin && a.port.len == b.port.len &&
1774          a.path.begin == b.path.begin && a.path.len == b.path.len &&
1775          a.query.begin == b.query.begin && a.query.len == b.query.len &&
1776          a.ref.begin == b.ref.begin && a.ref.len == b.ref.len;
1777 }
1778 
TEST(URLCanonTest,ResolveRelativeURL)1779 TEST(URLCanonTest, ResolveRelativeURL) {
1780   struct RelativeCase {
1781     const char* base;      // Input base URL: MUST BE CANONICAL
1782     bool is_base_hier;     // Is the base URL hierarchical
1783     bool is_base_file;     // Tells us if the base is a file URL.
1784     const char* test;      // Input URL to test against.
1785     bool succeed_relative; // Whether we expect IsRelativeURL to succeed
1786     bool is_rel;           // Whether we expect |test| to be relative or not.
1787     bool succeed_resolve;  // Whether we expect ResolveRelativeURL to succeed.
1788     const char* resolved;  // What we expect in the result when resolving.
1789   } rel_cases[] = {
1790       // Basic absolute input.
1791     {"http://host/a", true, false, "http://another/", true, false, false, NULL},
1792     {"http://host/a", true, false, "http:////another/", true, false, false, NULL},
1793       // Empty relative URLs should only remove the ref part of the URL,
1794       // leaving the rest unchanged.
1795     {"http://foo/bar", true, false, "", true, true, true, "http://foo/bar"},
1796     {"http://foo/bar#ref", true, false, "", true, true, true, "http://foo/bar"},
1797     {"http://foo/bar#", true, false, "", true, true, true, "http://foo/bar"},
1798       // Spaces at the ends of the relative path should be ignored.
1799     {"http://foo/bar", true, false, "  another  ", true, true, true, "http://foo/another"},
1800     {"http://foo/bar", true, false, "  .  ", true, true, true, "http://foo/"},
1801     {"http://foo/bar", true, false, " \t ", true, true, true, "http://foo/bar"},
1802       // Matching schemes without two slashes are treated as relative.
1803     {"http://host/a", true, false, "http:path", true, true, true, "http://host/path"},
1804     {"http://host/a/", true, false, "http:path", true, true, true, "http://host/a/path"},
1805     {"http://host/a", true, false, "http:/path", true, true, true, "http://host/path"},
1806     {"http://host/a", true, false, "HTTP:/path", true, true, true, "http://host/path"},
1807       // Nonmatching schemes are absolute.
1808     {"http://host/a", true, false, "https:host2", true, false, false, NULL},
1809     {"http://host/a", true, false, "htto:/host2", true, false, false, NULL},
1810       // Absolute path input
1811     {"http://host/a", true, false, "/b/c/d", true, true, true, "http://host/b/c/d"},
1812     {"http://host/a", true, false, "\\b\\c\\d", true, true, true, "http://host/b/c/d"},
1813     {"http://host/a", true, false, "/b/../c", true, true, true, "http://host/c"},
1814     {"http://host/a?b#c", true, false, "/b/../c", true, true, true, "http://host/c"},
1815     {"http://host/a", true, false, "\\b/../c?x#y", true, true, true, "http://host/c?x#y"},
1816     {"http://host/a?b#c", true, false, "/b/../c?x#y", true, true, true, "http://host/c?x#y"},
1817       // Relative path input
1818     {"http://host/a", true, false, "b", true, true, true, "http://host/b"},
1819     {"http://host/a", true, false, "bc/de", true, true, true, "http://host/bc/de"},
1820     {"http://host/a/", true, false, "bc/de?query#ref", true, true, true, "http://host/a/bc/de?query#ref"},
1821     {"http://host/a/", true, false, ".", true, true, true, "http://host/a/"},
1822     {"http://host/a/", true, false, "..", true, true, true, "http://host/"},
1823     {"http://host/a/", true, false, "./..", true, true, true, "http://host/"},
1824     {"http://host/a/", true, false, "../.", true, true, true, "http://host/"},
1825     {"http://host/a/", true, false, "././.", true, true, true, "http://host/a/"},
1826     {"http://host/a?query#ref", true, false, "../../../foo", true, true, true, "http://host/foo"},
1827       // Query input
1828     {"http://host/a", true, false, "?foo=bar", true, true, true, "http://host/a?foo=bar"},
1829     {"http://host/a?x=y#z", true, false, "?", true, true, true, "http://host/a?"},
1830     {"http://host/a?x=y#z", true, false, "?foo=bar#com", true, true, true, "http://host/a?foo=bar#com"},
1831       // Ref input
1832     {"http://host/a", true, false, "#ref", true, true, true, "http://host/a#ref"},
1833     {"http://host/a#b", true, false, "#", true, true, true, "http://host/a#"},
1834     {"http://host/a?foo=bar#hello", true, false, "#bye", true, true, true, "http://host/a?foo=bar#bye"},
1835       // Non-hierarchical base: no relative handling. Relative input should
1836       // error, and if a scheme is present, it should be treated as absolute.
1837     {"data:foobar", false, false, "baz.html", false, false, false, NULL},
1838     {"data:foobar", false, false, "data:baz", true, false, false, NULL},
1839     {"data:foobar", false, false, "data:/base", true, false, false, NULL},
1840       // Non-hierarchical base: absolute input should succeed.
1841     {"data:foobar", false, false, "http://host/", true, false, false, NULL},
1842     {"data:foobar", false, false, "http:host", true, false, false, NULL},
1843       // Invalid schemes should be treated as relative.
1844     {"http://foo/bar", true, false, "./asd:fgh", true, true, true, "http://foo/asd:fgh"},
1845     {"http://foo/bar", true, false, ":foo", true, true, true, "http://foo/:foo"},
1846     {"http://foo/bar", true, false, " hello world", true, true, true, "http://foo/hello%20world"},
1847     {"data:asdf", false, false, ":foo", false, false, false, NULL},
1848       // We should treat semicolons like any other character in URL resolving
1849     {"http://host/a", true, false, ";foo", true, true, true, "http://host/;foo"},
1850     {"http://host/a;", true, false, ";foo", true, true, true, "http://host/;foo"},
1851     {"http://host/a", true, false, ";/../bar", true, true, true, "http://host/bar"},
1852       // Relative URLs can also be written as "//foo/bar" which is relative to
1853       // the scheme. In this case, it would take the old scheme, so for http
1854       // the example would resolve to "http://foo/bar".
1855     {"http://host/a", true, false, "//another", true, true, true, "http://another/"},
1856     {"http://host/a", true, false, "//another/path?query#ref", true, true, true, "http://another/path?query#ref"},
1857     {"http://host/a", true, false, "///another/path", true, true, true, "http://another/path"},
1858     {"http://host/a", true, false, "//Another\\path", true, true, true, "http://another/path"},
1859     {"http://host/a", true, false, "//", true, true, false, "http:"},
1860       // IE will also allow one or the other to be a backslash to get the same
1861       // behavior.
1862     {"http://host/a", true, false, "\\/another/path", true, true, true, "http://another/path"},
1863     {"http://host/a", true, false, "/\\Another\\path", true, true, true, "http://another/path"},
1864 #ifdef WIN32
1865       // Resolving against Windows file base URLs.
1866     {"file:///C:/foo", true, true, "http://host/", true, false, false, NULL},
1867     {"file:///C:/foo", true, true, "bar", true, true, true, "file:///C:/bar"},
1868     {"file:///C:/foo", true, true, "../../../bar.html", true, true, true, "file:///C:/bar.html"},
1869     {"file:///C:/foo", true, true, "/../bar.html", true, true, true, "file:///C:/bar.html"},
1870       // But two backslashes on Windows should be UNC so should be treated
1871       // as absolute.
1872     {"http://host/a", true, false, "\\\\another\\path", true, false, false, NULL},
1873       // IE doesn't support drive specs starting with two slashes. It fails
1874       // immediately and doesn't even try to load. We fix it up to either
1875       // an absolute path or UNC depending on what it looks like.
1876     {"file:///C:/something", true, true, "//c:/foo", true, true, true, "file:///C:/foo"},
1877     {"file:///C:/something", true, true, "//localhost/c:/foo", true, true, true, "file:///C:/foo"},
1878       // Windows drive specs should be allowed and treated as absolute.
1879     {"file:///C:/foo", true, true, "c:", true, false, false, NULL},
1880     {"file:///C:/foo", true, true, "c:/foo", true, false, false, NULL},
1881     {"http://host/a", true, false, "c:\\foo", true, false, false, NULL},
1882       // Relative paths with drive letters should be allowed when the base is
1883       // also a file.
1884     {"file:///C:/foo", true, true, "/z:/bar", true, true, true, "file:///Z:/bar"},
1885       // Treat absolute paths as being off of the drive.
1886     {"file:///C:/foo", true, true, "/bar", true, true, true, "file:///C:/bar"},
1887     {"file://localhost/C:/foo", true, true, "/bar", true, true, true, "file://localhost/C:/bar"},
1888     {"file:///C:/foo/com/", true, true, "/bar", true, true, true, "file:///C:/bar"},
1889       // On Windows, two slashes without a drive letter when the base is a file
1890       // means that the path is UNC.
1891     {"file:///C:/something", true, true, "//somehost/path", true, true, true, "file://somehost/path"},
1892     {"file:///C:/something", true, true, "/\\//somehost/path", true, true, true, "file://somehost/path"},
1893 #else
1894       // On Unix we fall back to relative behavior since there's nothing else
1895       // reasonable to do.
1896     {"http://host/a", true, false, "\\\\Another\\path", true, true, true, "http://another/path"},
1897 #endif
1898       // Even on Windows, we don't allow relative drive specs when the base
1899       // is not file.
1900     {"http://host/a", true, false, "/c:\\foo", true, true, true, "http://host/c:/foo"},
1901     {"http://host/a", true, false, "//c:\\foo", true, true, true, "http://c/foo"},
1902   };
1903 
1904   for (size_t i = 0; i < ARRAYSIZE(rel_cases); i++) {
1905     const RelativeCase& cur_case = rel_cases[i];
1906 
1907     url_parse::Parsed parsed;
1908     int base_len = static_cast<int>(strlen(cur_case.base));
1909     if (cur_case.is_base_file)
1910       url_parse::ParseFileURL(cur_case.base, base_len, &parsed);
1911     else if (cur_case.is_base_hier)
1912       url_parse::ParseStandardURL(cur_case.base, base_len, &parsed);
1913     else
1914       url_parse::ParsePathURL(cur_case.base, base_len, &parsed);
1915 
1916     // First see if it is relative.
1917     int test_len = static_cast<int>(strlen(cur_case.test));
1918     bool is_relative;
1919     url_parse::Component relative_component;
1920     bool succeed_is_rel = url_canon::IsRelativeURL(
1921         cur_case.base, parsed, cur_case.test, test_len, cur_case.is_base_hier,
1922         &is_relative, &relative_component);
1923 
1924     EXPECT_EQ(cur_case.succeed_relative, succeed_is_rel) <<
1925         "succeed is rel failure on " << cur_case.test;
1926     EXPECT_EQ(cur_case.is_rel, is_relative) <<
1927         "is rel failure on " << cur_case.test;
1928     // Now resolve it.
1929     if (succeed_is_rel && is_relative && cur_case.is_rel) {
1930       std::string resolved;
1931       url_canon::StdStringCanonOutput output(&resolved);
1932       url_parse::Parsed resolved_parsed;
1933 
1934       bool succeed_resolve = url_canon::ResolveRelativeURL(
1935           cur_case.base, parsed, cur_case.is_base_file,
1936           cur_case.test, relative_component, NULL, &output, &resolved_parsed);
1937       output.Complete();
1938 
1939       EXPECT_EQ(cur_case.succeed_resolve, succeed_resolve);
1940       EXPECT_EQ(cur_case.resolved, resolved) << " on " << cur_case.test;
1941 
1942       // Verify that the output parsed structure is the same as parsing a
1943       // the URL freshly.
1944       url_parse::Parsed ref_parsed;
1945       int resolved_len = static_cast<int>(resolved.size());
1946       if (cur_case.is_base_file)
1947         url_parse::ParseFileURL(resolved.c_str(), resolved_len, &ref_parsed);
1948       else if (cur_case.is_base_hier)
1949         url_parse::ParseStandardURL(resolved.c_str(), resolved_len, &ref_parsed);
1950       else
1951         url_parse::ParsePathURL(resolved.c_str(), resolved_len, &ref_parsed);
1952       EXPECT_TRUE(ParsedIsEqual(ref_parsed, resolved_parsed));
1953     }
1954   }
1955 }
1956 
1957 // It used to be when we did a replacement with a long buffer of UTF-16
1958 // characters, we would get invalid data in the URL. This is because the buffer
1959 // it used to hold the UTF-8 data was resized, while some pointers were still
1960 // kept to the old buffer that was removed.
TEST(URLCanonTest,ReplacementOverflow)1961 TEST(URLCanonTest, ReplacementOverflow) {
1962   const char src[] = "file:///C:/foo/bar";
1963   int src_len = static_cast<int>(strlen(src));
1964   url_parse::Parsed parsed;
1965   url_parse::ParseFileURL(src, src_len, &parsed);
1966 
1967   // Override two components, the path with something short, and the query with
1968   // sonething long enough to trigger the bug.
1969   url_canon::Replacements<char16> repl;
1970   string16 new_query;
1971   for (int i = 0; i < 4800; i++)
1972     new_query.push_back('a');
1973 
1974   string16 new_path(WStringToUTF16(L"/foo"));
1975   repl.SetPath(new_path.c_str(), url_parse::Component(0, 4));
1976   repl.SetQuery(new_query.c_str(),
1977                 url_parse::Component(0, static_cast<int>(new_query.length())));
1978 
1979   // Call ReplaceComponents on the string. It doesn't matter if we call it for
1980   // standard URLs, file URLs, etc, since they will go to the same replacement
1981   // function that was buggy.
1982   url_parse::Parsed repl_parsed;
1983   std::string repl_str;
1984   url_canon::StdStringCanonOutput repl_output(&repl_str);
1985   url_canon::ReplaceFileURL(src, parsed, repl, NULL, &repl_output, &repl_parsed);
1986   repl_output.Complete();
1987 
1988   // Generate the expected string and check.
1989   std::string expected("file:///foo?");
1990   for (size_t i = 0; i < new_query.length(); i++)
1991     expected.push_back('a');
1992   EXPECT_TRUE(expected == repl_str);
1993 }
1994