Fix for Geolocation webTCT failures
[platform/framework/web/chromium-efl.git] / url / url_canon_unittest.cc
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "url/url_canon.h"
6
7 #include <errno.h>
8 #include <stddef.h>
9 #include <string_view>
10
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/test/gtest_util.h"
14 #include "base/test/scoped_feature_list.h"
15 #include "testing/gtest/include/gtest/gtest.h"
16 #include "url/third_party/mozilla/url_parse.h"
17 #include "url/url_canon_internal.h"
18 #include "url/url_canon_stdstring.h"
19 #include "url/url_features.h"
20 #include "url/url_test_utils.h"
21
22 namespace url {
23
24 namespace {
25
26 struct ComponentCase {
27   const char* input;
28   const char* expected;
29   Component expected_component;
30   bool expected_success;
31 };
32
33 // ComponentCase but with dual 8-bit/16-bit input. Generally, the unit tests
34 // treat each input as optional, and will only try processing if non-NULL.
35 // The output is always 8-bit.
36 struct DualComponentCase {
37   const char* input8;
38   const wchar_t* input16;
39   const char* expected;
40   Component expected_component;
41   bool expected_success;
42 };
43
44 // Test cases for CanonicalizeIPAddress(). The inputs are identical to
45 // DualComponentCase, but the output has extra CanonHostInfo fields.
46 struct IPAddressCase {
47   const char* input8;
48   const wchar_t* input16;
49   const char* expected;
50   Component expected_component;
51
52   // CanonHostInfo fields, for verbose output.
53   CanonHostInfo::Family expected_family;
54   int expected_num_ipv4_components;
55   const char* expected_address_hex;  // Two hex chars per IP address byte.
56 };
57
58 struct ReplaceCase {
59   const char* base;
60   const char* scheme;
61   const char* username;
62   const char* password;
63   const char* host;
64   const char* port;
65   const char* path;
66   const char* query;
67   const char* ref;
68   const char* expected;
69 };
70
71 // Magic string used in the replacements code that tells SetupReplComp to
72 // call the clear function.
73 const char kDeleteComp[] = "|";
74
75 // Sets up a replacement for a single component. This is given pointers to
76 // the set and clear function for the component being replaced, and will
77 // either set the component (if it exists) or clear it (if the replacement
78 // string matches kDeleteComp).
79 //
80 // This template is currently used only for the 8-bit case, and the strlen
81 // causes it to fail in other cases. It is left a template in case we have
82 // tests for wide replacements.
83 template<typename CHAR>
84 void SetupReplComp(
85     void (Replacements<CHAR>::*set)(const CHAR*, const Component&),
86     void (Replacements<CHAR>::*clear)(),
87     Replacements<CHAR>* rep,
88     const CHAR* str) {
89   if (str && str[0] == kDeleteComp[0]) {
90     (rep->*clear)();
91   } else if (str) {
92     (rep->*set)(str, Component(0, static_cast<int>(strlen(str))));
93   }
94 }
95
96 }  // namespace
97
98 TEST(URLCanonTest, DoAppendUTF8) {
99   struct UTF8Case {
100     unsigned input;
101     const char* output;
102   } utf_cases[] = {
103     // Valid code points.
104     {0x24, "\x24"},
105     {0xA2, "\xC2\xA2"},
106     {0x20AC, "\xE2\x82\xAC"},
107     {0x24B62, "\xF0\xA4\xAD\xA2"},
108     {0x10FFFF, "\xF4\x8F\xBF\xBF"},
109   };
110   std::string out_str;
111   for (const auto& utf_case : utf_cases) {
112     out_str.clear();
113     StdStringCanonOutput output(&out_str);
114     AppendUTF8Value(utf_case.input, &output);
115     output.Complete();
116     EXPECT_EQ(utf_case.output, out_str);
117   }
118 }
119
120 TEST(URLCanonTest, DoAppendUTF8Invalid) {
121   std::string out_str;
122   StdStringCanonOutput output(&out_str);
123   // Invalid code point (too large).
124   EXPECT_DCHECK_DEATH({
125     AppendUTF8Value(0x110000, &output);
126     output.Complete();
127   });
128 }
129
130 TEST(URLCanonTest, UTF) {
131   // Low-level test that we handle reading, canonicalization, and writing
132   // UTF-8/UTF-16 strings properly.
133   struct UTFCase {
134     const char* input8;
135     const wchar_t* input16;
136     bool expected_success;
137     const char* output;
138   } utf_cases[] = {
139       // Valid canonical input should get passed through & escaped.
140       {"\xe4\xbd\xa0\xe5\xa5\xbd", L"\x4f60\x597d", true, "%E4%BD%A0%E5%A5%BD"},
141       // Test a character that takes > 16 bits (U+10300 = old italic letter A)
142       {"\xF0\x90\x8C\x80", L"\xd800\xdf00", true, "%F0%90%8C%80"},
143       // Non-shortest-form UTF-8 characters are invalid. The bad bytes should
144       // each be replaced with the invalid character (EF BF DB in UTF-8).
145       {"\xf0\x84\xbd\xa0\xe5\xa5\xbd", nullptr, false,
146        "%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%E5%A5%BD"},
147       // Invalid UTF-8 sequences should be marked as invalid (the first
148       // sequence is truncated).
149       {"\xe4\xa0\xe5\xa5\xbd", L"\xd800\x597d", false, "%EF%BF%BD%E5%A5%BD"},
150       // Character going off the end.
151       {"\xe4\xbd\xa0\xe5\xa5", L"\x4f60\xd800", false, "%E4%BD%A0%EF%BF%BD"},
152       // ...same with low surrogates with no high surrogate.
153       {nullptr, L"\xdc00", false, "%EF%BF%BD"},
154       // Test a UTF-8 encoded surrogate value is marked as invalid.
155       // ED A0 80 = U+D800
156       {"\xed\xa0\x80", nullptr, false, "%EF%BF%BD%EF%BF%BD%EF%BF%BD"},
157       // ...even when paired.
158       {"\xed\xa0\x80\xed\xb0\x80", nullptr, false,
159        "%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD"},
160   };
161
162   std::string out_str;
163   for (const auto& utf_case : utf_cases) {
164     if (utf_case.input8) {
165       out_str.clear();
166       StdStringCanonOutput output(&out_str);
167
168       size_t input_len = strlen(utf_case.input8);
169       bool success = true;
170       for (size_t ch = 0; ch < input_len; ch++) {
171         success &=
172             AppendUTF8EscapedChar(utf_case.input8, &ch, input_len, &output);
173       }
174       output.Complete();
175       EXPECT_EQ(utf_case.expected_success, success);
176       EXPECT_EQ(utf_case.output, out_str);
177     }
178     if (utf_case.input16) {
179       out_str.clear();
180       StdStringCanonOutput output(&out_str);
181
182       std::u16string input_str(
183           test_utils::TruncateWStringToUTF16(utf_case.input16));
184       size_t input_len = input_str.length();
185       bool success = true;
186       for (size_t ch = 0; ch < input_len; ch++) {
187         success &= AppendUTF8EscapedChar(input_str.c_str(), &ch, input_len,
188                                          &output);
189       }
190       output.Complete();
191       EXPECT_EQ(utf_case.expected_success, success);
192       EXPECT_EQ(utf_case.output, out_str);
193     }
194
195     if (utf_case.input8 && utf_case.input16 && utf_case.expected_success) {
196       // Check that the UTF-8 and UTF-16 inputs are equivalent.
197
198       // UTF-16 -> UTF-8
199       std::string input8_str(utf_case.input8);
200       std::u16string input16_str(
201           test_utils::TruncateWStringToUTF16(utf_case.input16));
202       EXPECT_EQ(input8_str, base::UTF16ToUTF8(input16_str));
203
204       // UTF-8 -> UTF-16
205       EXPECT_EQ(input16_str, base::UTF8ToUTF16(input8_str));
206     }
207   }
208 }
209
210 TEST(URLCanonTest, Scheme) {
211   // Here, we're mostly testing that unusual characters are handled properly.
212   // The canonicalizer doesn't do any parsing or whitespace detection. It will
213   // also do its best on error, and will escape funny sequences (these won't be
214   // valid schemes and it will return error).
215   //
216   // Note that the canonicalizer will append a colon to the output to separate
217   // out the rest of the URL, which is not present in the input. We check,
218   // however, that the output range includes everything but the colon.
219   ComponentCase scheme_cases[] = {
220     {"http", "http:", Component(0, 4), true},
221     {"HTTP", "http:", Component(0, 4), true},
222     {" HTTP ", "%20http%20:", Component(0, 10), false},
223     {"htt: ", "htt%3A%20:", Component(0, 9), false},
224     {"\xe4\xbd\xa0\xe5\xa5\xbdhttp", "%E4%BD%A0%E5%A5%BDhttp:", Component(0, 22), false},
225       // Don't re-escape something already escaped. Note that it will
226       // "canonicalize" the 'A' to 'a', but that's OK.
227     {"ht%3Atp", "ht%3atp:", Component(0, 7), false},
228     {"", ":", Component(0, 0), false},
229   };
230
231   std::string out_str;
232
233   for (const auto& scheme_case : scheme_cases) {
234     int url_len = static_cast<int>(strlen(scheme_case.input));
235     Component in_comp(0, url_len);
236     Component out_comp;
237
238     out_str.clear();
239     StdStringCanonOutput output1(&out_str);
240     bool success =
241         CanonicalizeScheme(scheme_case.input, in_comp, &output1, &out_comp);
242     output1.Complete();
243
244     EXPECT_EQ(scheme_case.expected_success, success);
245     EXPECT_EQ(scheme_case.expected, out_str);
246     EXPECT_EQ(scheme_case.expected_component.begin, out_comp.begin);
247     EXPECT_EQ(scheme_case.expected_component.len, out_comp.len);
248
249     // Now try the wide version.
250     out_str.clear();
251     StdStringCanonOutput output2(&out_str);
252
253     std::u16string wide_input(base::UTF8ToUTF16(scheme_case.input));
254     in_comp.len = static_cast<int>(wide_input.length());
255     success = CanonicalizeScheme(wide_input.c_str(), in_comp, &output2,
256                                  &out_comp);
257     output2.Complete();
258
259     EXPECT_EQ(scheme_case.expected_success, success);
260     EXPECT_EQ(scheme_case.expected, out_str);
261     EXPECT_EQ(scheme_case.expected_component.begin, out_comp.begin);
262     EXPECT_EQ(scheme_case.expected_component.len, out_comp.len);
263   }
264
265   // Test the case where the scheme is declared nonexistent, it should be
266   // converted into an empty scheme.
267   Component out_comp;
268   out_str.clear();
269   StdStringCanonOutput output(&out_str);
270
271   EXPECT_FALSE(CanonicalizeScheme("", Component(0, -1), &output, &out_comp));
272   output.Complete();
273
274   EXPECT_EQ(":", out_str);
275   EXPECT_EQ(0, out_comp.begin);
276   EXPECT_EQ(0, out_comp.len);
277 }
278
279 // IDNA mode to use in CanonHost tests.
280 enum class IDNAMode { kTransitional, kNonTransitional };
281
282 class URLCanonHostTest
283     : public ::testing::Test,
284       public ::testing::WithParamInterface<IDNAMode> {
285  public:
286   URLCanonHostTest() {
287     if (GetParam() == IDNAMode::kNonTransitional) {
288       scoped_feature_list_.InitAndEnableFeature(kUseIDNA2008NonTransitional);
289     } else {
290       scoped_feature_list_.InitAndDisableFeature(kUseIDNA2008NonTransitional);
291     }
292   }
293
294  private:
295   base::test::ScopedFeatureList scoped_feature_list_;
296 };
297
298 INSTANTIATE_TEST_SUITE_P(All,
299                          URLCanonHostTest,
300                          ::testing::Values(IDNAMode::kTransitional,
301                                            IDNAMode::kNonTransitional));
302
303 TEST_P(URLCanonHostTest, Host) {
304   bool use_idna_non_transitional = IsUsingIDNA2008NonTransitional();
305
306   // clang-format off
307   IPAddressCase host_cases[] = {
308       // Basic canonicalization, uppercase should be converted to lowercase.
309       {"GoOgLe.CoM", L"GoOgLe.CoM", "google.com", Component(0, 10),
310        CanonHostInfo::NEUTRAL, -1, ""},
311       // TODO(https://crbug.com/1416013): Update the test after SPACE is
312       // correctly handled.
313       {"Goo%20 goo.com", L"Goo%20 goo.com", "goo%20%20goo.com",
314        Component(0, 16), CanonHostInfo::NEUTRAL, -1, ""},
315       // TODO(https://crbug.com/1416013): Update the test after ASTERISK is
316       // correctly handled.
317       {"Goo%2a*goo.com", L"Goo%2a*goo.com", "goo%2A%2Agoo.com",
318        Component(0, 16), CanonHostInfo::NEUTRAL, -1, ""},
319       // Exciting different types of spaces!
320       {nullptr, L"GOO\x00a0\x3000goo.com", "goo%20%20goo.com", Component(0, 16),
321        CanonHostInfo::NEUTRAL, -1, ""},
322       // Other types of space (no-break, zero-width, zero-width-no-break) are
323       // name-prepped away to nothing.
324       {nullptr, L"GOO\x200b\x2060\xfeffgoo.com", "googoo.com", Component(0, 10),
325        CanonHostInfo::NEUTRAL, -1, ""},
326       // Ideographic full stop (full-width period for Chinese, etc.) should be
327       // treated as a dot.
328       {nullptr,
329        L"www.foo\x3002"
330        L"bar.com",
331        "www.foo.bar.com", Component(0, 15), CanonHostInfo::NEUTRAL, -1, ""},
332       // Invalid unicode characters should fail...
333       {"\xef\xb7\x90zyx.com", L"\xfdd0zyx.com", "%EF%B7%90zyx.com",
334        Component(0, 16), CanonHostInfo::BROKEN, -1, ""},
335       // ...This is the same as previous but with with escaped.
336       {"%ef%b7%90zyx.com", L"%ef%b7%90zyx.com", "%EF%B7%90zyx.com",
337        Component(0, 16), CanonHostInfo::BROKEN, -1, ""},
338       // Test name prepping, fullwidth input should be converted to ASCII and
339       // NOT
340       // IDN-ized. This is "Go" in fullwidth UTF-8/UTF-16.
341       {"\xef\xbc\xa7\xef\xbd\x8f.com", L"\xff27\xff4f.com", "go.com",
342        Component(0, 6), CanonHostInfo::NEUTRAL, -1, ""},
343       // Test that fullwidth escaped values are properly name-prepped,
344       // then converted or rejected.
345       // ...%41 in fullwidth = 'A' (also as escaped UTF-8 input)
346       {"\xef\xbc\x85\xef\xbc\x94\xef\xbc\x91.com", L"\xff05\xff14\xff11.com",
347        "a.com", Component(0, 5), CanonHostInfo::NEUTRAL, -1, ""},
348       {"%ef%bc%85%ef%bc%94%ef%bc%91.com", L"%ef%bc%85%ef%bc%94%ef%bc%91.com",
349        "a.com", Component(0, 5), CanonHostInfo::NEUTRAL, -1, ""},
350       // ...%00 in fullwidth should fail (also as escaped UTF-8 input)
351       {"\xef\xbc\x85\xef\xbc\x90\xef\xbc\x90.com", L"\xff05\xff10\xff10.com",
352        "%00.com", Component(0, 7), CanonHostInfo::BROKEN, -1, ""},
353       {"%ef%bc%85%ef%bc%90%ef%bc%90.com", L"%ef%bc%85%ef%bc%90%ef%bc%90.com",
354        "%00.com", Component(0, 7), CanonHostInfo::BROKEN, -1, ""},
355       // ICU will convert weird percents into ASCII percents, but not unescape
356       // further. A weird percent is U+FE6A (EF B9 AA in UTF-8) which is a
357       // "small percent". At this point we should be within our rights to mark
358       // anything as invalid since the URL is corrupt or malicious. The code
359       // happens to allow ASCII characters (%41 = "A" -> 'a') to be unescaped
360       // and kept as valid, so we validate that behavior here, but this level
361       // of fixing the input shouldn't be seen as required. "%81" is invalid.
362       {"\xef\xb9\xaa"
363        "41.com",
364        L"\xfe6a"
365        L"41.com",
366        "a.com", Component(0, 5), CanonHostInfo::NEUTRAL, -1, ""},
367       {"%ef%b9%aa"
368        "41.com",
369        L"\xfe6a"
370        L"41.com",
371        "a.com", Component(0, 5), CanonHostInfo::NEUTRAL, -1, ""},
372       {"\xef\xb9\xaa"
373        "81.com",
374        L"\xfe6a"
375        L"81.com",
376        "%81.com", Component(0, 7), CanonHostInfo::BROKEN, -1, ""},
377       {"%ef%b9%aa"
378        "81.com",
379        L"\xfe6a"
380        L"81.com",
381        "%81.com", Component(0, 7), CanonHostInfo::BROKEN, -1, ""},
382       // Basic IDN support, UTF-8 and UTF-16 input should be converted to IDN
383       {"\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xbd\xa0\xe5\xa5\xbd",
384        L"\x4f60\x597d\x4f60\x597d", "xn--6qqa088eba", Component(0, 14),
385        CanonHostInfo::NEUTRAL, -1, ""},
386       // See http://unicode.org/cldr/utility/idna.jsp for other
387       // examples/experiments and http://goo.gl/7yG11o
388       // for the full list of characters handled differently by
389       // IDNA 2003, UTS 46 (http://unicode.org/reports/tr46/ ) and IDNA 2008.
390
391       // 4 Deviation characters are mapped/ignored in UTS 46 transitional
392       // mechansm. UTS 46, table 4 row (g).
393       // Sharp-s is mapped to 'ss' in IDNA 2003, not in IDNA 2008 or UTF 46
394       // after transitional period.
395       // Previously, it'd be "fussball.de".
396       {"fu\xc3\x9f"
397        "ball.de",
398        L"fu\x00df"
399        L"ball.de",
400        use_idna_non_transitional ? "xn--fuball-cta.de" : "fussball.de",
401        use_idna_non_transitional ? Component(0, 17) : Component(0, 11),
402        CanonHostInfo::NEUTRAL, -1, ""},
403
404       // Final-sigma (U+03C3) was mapped to regular sigma (U+03C2).
405       // Previously, it'd be "xn--wxaikc9b".
406       {"\xcf\x83\xcf\x8c\xce\xbb\xce\xbf\xcf\x82", L"\x3c3\x3cc\x3bb\x3bf\x3c2",
407        use_idna_non_transitional ? "xn--wxaijb9b" : "xn--wxaikc6b",
408        Component(0, 12), CanonHostInfo::NEUTRAL, -1, ""},
409
410       // ZWNJ (U+200C) and ZWJ (U+200D) are mapped away in UTS 46 transitional
411       // handling as well as in IDNA 2003, but not thereafter.
412       {"a\xe2\x80\x8c"
413        "b\xe2\x80\x8d"
414        "c",
415        L"a\x200c"
416        L"b\x200d"
417        L"c",
418        use_idna_non_transitional ? "xn--abc-9m0ag" : "abc",
419        use_idna_non_transitional ? Component(0, 13) : Component(0, 3),
420        CanonHostInfo::NEUTRAL, -1, ""},
421
422       // ZWJ between Devanagari characters was still mapped away in UTS 46
423       // transitional handling. IDNA 2008 gives xn--11bo0mv54g.
424       // Previously "xn--11bo0m".
425       {"\xe0\xa4\x95\xe0\xa5\x8d\xe2\x80\x8d\xe0\xa4\x9c",
426        L"\x915\x94d\x200d\x91c",
427        use_idna_non_transitional ? "xn--11bo0mv54g" : "xn--11bo0m",
428        use_idna_non_transitional ? Component(0, 14) : Component(0, 10),
429        CanonHostInfo::NEUTRAL, -1, ""},
430
431       // Fullwidth exclamation mark is disallowed. UTS 46, table 4, row (b)
432       // However, we do allow this at the moment because we don't use
433       // STD3 rules and canonicalize full-width ASCII to ASCII.
434       {"wow\xef\xbc\x81", L"wow\xff01", "wow!", Component(0, 4),
435        CanonHostInfo::NEUTRAL, -1, ""},
436       // U+2132 (turned capital F) is disallowed. UTS 46, table 4, row (c)
437       // Allowed in IDNA 2003, but the mapping changed after Unicode 3.2
438       {"\xe2\x84\xb2oo", L"\x2132oo", "%E2%84%B2oo", Component(0, 11),
439        CanonHostInfo::BROKEN, -1, ""},
440       // U+2F868 (CJK Comp) is disallowed. UTS 46, table 4, row (d)
441       // Allowed in IDNA 2003, but the mapping changed after Unicode 3.2
442       {"\xf0\xaf\xa1\xa8\xe5\xa7\xbb.cn", L"\xd87e\xdc68\x59fb.cn",
443        "%F0%AF%A1%A8%E5%A7%BB.cn", Component(0, 24), CanonHostInfo::BROKEN, -1,
444        ""},
445       // Maps uppercase letters to lower case letters. UTS 46 table 4 row (e)
446       {"M\xc3\x9cNCHEN", L"M\xdcNCHEN", "xn--mnchen-3ya", Component(0, 14),
447        CanonHostInfo::NEUTRAL, -1, ""},
448       // An already-IDNA host is not modified.
449       {"xn--mnchen-3ya", L"xn--mnchen-3ya", "xn--mnchen-3ya", Component(0, 14),
450        CanonHostInfo::NEUTRAL, -1, ""},
451       // Symbol/punctuations are allowed in IDNA 2003/UTS46.
452       // Not allowed in IDNA 2008. UTS 46 table 4 row (f).
453       {"\xe2\x99\xa5ny.us", L"\x2665ny.us", "xn--ny-s0x.us", Component(0, 13),
454        CanonHostInfo::NEUTRAL, -1, ""},
455       // U+11013 is new in Unicode 6.0 and is allowed. UTS 46 table 4, row (h)
456       // We used to allow it because we passed through unassigned code points.
457       {"\xf0\x91\x80\x93.com", L"\xd804\xdc13.com", "xn--n00d.com",
458        Component(0, 12), CanonHostInfo::NEUTRAL, -1, ""},
459       // U+0602 is disallowed in UTS46/IDNA 2008. UTS 46 table 4, row(i)
460       // Used to be allowed in INDA 2003.
461       {"\xd8\x82.eg", L"\x602.eg", "%D8%82.eg", Component(0, 9),
462        CanonHostInfo::BROKEN, -1, ""},
463       // U+20B7 is new in Unicode 5.2 (not a part of IDNA 2003 based
464       // on Unicode 3.2). We did allow it in the past because we let unassigned
465       // code point pass. We continue to allow it even though it's a
466       // "punctuation and symbol" blocked in IDNA 2008.
467       // UTS 46 table 4, row (j)
468       {"\xe2\x82\xb7.com", L"\x20b7.com", "xn--wzg.com", Component(0, 11),
469        CanonHostInfo::NEUTRAL, -1, ""},
470       // Maps uppercase letters to lower case letters.
471       // In IDNA 2003, it's allowed without case-folding
472       // ( xn--bc-7cb.com ) because it's not defined in Unicode 3.2
473       // (added in Unicode 4.1). UTS 46 table 4 row (k)
474       {"bc\xc8\xba.com", L"bc\x23a.com", "xn--bc-is1a.com", Component(0, 15),
475        CanonHostInfo::NEUTRAL, -1, ""},
476       // Maps U+FF43 (Full Width Small Letter C) to 'c'.
477       {"ab\xef\xbd\x83.xyz", L"ab\xff43.xyz", "abc.xyz", Component(0, 7),
478        CanonHostInfo::NEUTRAL, -1, ""},
479       // Maps U+1D68C (Math Monospace Small C) to 'c'.
480       // U+1D68C = \xD835\xDE8C in UTF-16
481       {"ab\xf0\x9d\x9a\x8c.xyz", L"ab\xd835\xde8c.xyz", "abc.xyz",
482        Component(0, 7), CanonHostInfo::NEUTRAL, -1, ""},
483       // BiDi check test
484       // "Divehi" in Divehi (Thaana script) ends with BidiClass=NSM.
485       // Disallowed in IDNA 2003 but now allowed in UTS 46/IDNA 2008.
486       {"\xde\x8b\xde\xa8\xde\x88\xde\xac\xde\x80\xde\xa8",
487        L"\x78b\x7a8\x788\x7ac\x780\x7a8", "xn--hqbpi0jcw", Component(0, 13),
488        CanonHostInfo::NEUTRAL, -1, ""},
489       // Disallowed in both IDNA 2003 and 2008 with BiDi check.
490       // Labels starting with a RTL character cannot end with a LTR character.
491       {"\xd8\xac\xd8\xa7\xd8\xb1xyz", L"\x62c\x627\x631xyz",
492        "%D8%AC%D8%A7%D8%B1xyz", Component(0, 21), CanonHostInfo::BROKEN, -1,
493        ""},
494       // Labels starting with a RTL character can end with BC=EN (European
495       // number). Disallowed in IDNA 2003 but now allowed.
496       {"\xd8\xac\xd8\xa7\xd8\xb1"
497        "2",
498        L"\x62c\x627\x631"
499        L"2",
500        "xn--2-ymcov", Component(0, 11), CanonHostInfo::NEUTRAL, -1, ""},
501       // Labels starting with a RTL character cannot have "L" characters
502       // even if it ends with an BC=EN. Disallowed in both IDNA 2003/2008.
503       {"\xd8\xac\xd8\xa7\xd8\xb1xy2", L"\x62c\x627\x631xy2",
504        "%D8%AC%D8%A7%D8%B1xy2", Component(0, 21), CanonHostInfo::BROKEN, -1,
505        ""},
506       // Labels starting with a RTL character can end with BC=AN (Arabic number)
507       // Disallowed in IDNA 2003, but now allowed.
508       {"\xd8\xac\xd8\xa7\xd8\xb1\xd9\xa2", L"\x62c\x627\x631\x662",
509        "xn--mgbjq0r", Component(0, 11), CanonHostInfo::NEUTRAL, -1, ""},
510       // Labels starting with a RTL character cannot have "L" characters
511       // even if it ends with an BC=AN (Arabic number).
512       // Disallowed in both IDNA 2003/2008.
513       {"\xd8\xac\xd8\xa7\xd8\xb1xy\xd9\xa2", L"\x62c\x627\x631xy\x662",
514        "%D8%AC%D8%A7%D8%B1xy%D9%A2", Component(0, 26), CanonHostInfo::BROKEN,
515        -1, ""},
516       // Labels starting with a RTL character cannot mix BC=EN and BC=AN
517       {"\xd8\xac\xd8\xa7\xd8\xb1xy2\xd9\xa2", L"\x62c\x627\x631xy2\x662",
518        "%D8%AC%D8%A7%D8%B1xy2%D9%A2", Component(0, 27), CanonHostInfo::BROKEN,
519        -1, ""},
520       // As of Unicode 6.2, U+20CF is not assigned. We do not allow it.
521       {"\xe2\x83\x8f.com", L"\x20cf.com", "%E2%83%8F.com", Component(0, 13),
522        CanonHostInfo::BROKEN, -1, ""},
523       // U+0080 is not allowed.
524       {"\xc2\x80.com", L"\x80.com", "%C2%80.com", Component(0, 10),
525        CanonHostInfo::BROKEN, -1, ""},
526       // Mixed UTF-8 and escaped UTF-8 (narrow case) and UTF-16 and escaped
527       // Mixed UTF-8 and escaped UTF-8 (narrow case) and UTF-16 and escaped
528       // UTF-8 (wide case). The output should be equivalent to the true wide
529       // character input above).
530       {"%E4%BD%A0%E5%A5%BD\xe4\xbd\xa0\xe5\xa5\xbd",
531        L"%E4%BD%A0%E5%A5%BD\x4f60\x597d", "xn--6qqa088eba", Component(0, 14),
532        CanonHostInfo::NEUTRAL, -1, ""},
533       // Invalid escaped characters should fail and the percents should be
534       // escaped.
535       {"%zz%66%a", L"%zz%66%a", "%25zzf%25a", Component(0, 10),
536        CanonHostInfo::BROKEN, -1, ""},
537       // If we get an invalid character that has been escaped.
538       {"%25", L"%25", "%25", Component(0, 3), CanonHostInfo::BROKEN, -1, ""},
539       {"hello%00", L"hello%00", "hello%00", Component(0, 8),
540        CanonHostInfo::BROKEN, -1, ""},
541       // Escaped numbers should be treated like IP addresses if they are.
542       {"%30%78%63%30%2e%30%32%35%30.01", L"%30%78%63%30%2e%30%32%35%30.01",
543        "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 3, "C0A80001"},
544       {"%30%78%63%30%2e%30%32%35%30.01%2e",
545        L"%30%78%63%30%2e%30%32%35%30.01%2e", "192.168.0.1", Component(0, 11),
546        CanonHostInfo::IPV4, 3, "C0A80001"},
547       // Invalid escaping should trigger the regular host error handling.
548       {"%3g%78%63%30%2e%30%32%35%30%2E.01",
549        L"%3g%78%63%30%2e%30%32%35%30%2E.01", "%253gxc0.0250..01",
550        Component(0, 17), CanonHostInfo::BROKEN, -1, ""},
551       // Something that isn't exactly an IP should get treated as a host and
552       // spaces escaped.
553       {"192.168.0.1 hello", L"192.168.0.1 hello", "192.168.0.1%20hello",
554        Component(0, 19), CanonHostInfo::NEUTRAL, -1, ""},
555       // Fullwidth and escaped UTF-8 fullwidth should still be treated as IP.
556       // These are "0Xc0.0250.01" in fullwidth.
557       {"\xef\xbc\x90%Ef%bc\xb8%ef%Bd%83\xef\xbc\x90%EF%BC%"
558        "8E\xef\xbc\x90\xef\xbc\x92\xef\xbc\x95\xef\xbc\x90\xef\xbc%"
559        "8E\xef\xbc\x90\xef\xbc\x91",
560        L"\xff10\xff38\xff43\xff10\xff0e\xff10\xff12\xff15\xff10\xff0e\xff10"
561        L"\xff11",
562        "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 3, "C0A80001"},
563       // Broken IP addresses get marked as such.
564       {"192.168.0.257", L"192.168.0.257", "192.168.0.257", Component(0, 13),
565        CanonHostInfo::BROKEN, -1, ""},
566       {"[google.com]", L"[google.com]", "[google.com]", Component(0, 12),
567        CanonHostInfo::BROKEN, -1, ""},
568       // Cyrillic letter followed by '(' should return punycode for '(' escaped
569       // before punycode string was created. I.e.
570       // if '(' is escaped after punycode is created we would get xn--%28-8tb
571       // (incorrect).
572       {"\xd1\x82(", L"\x0442(", "xn--(-8tb", Component(0, 9),
573        CanonHostInfo::NEUTRAL, -1, ""},
574       // Address with all hexadecimal characters with leading number of 1<<32
575       // or greater and should return NEUTRAL rather than BROKEN if not all
576       // components are numbers.
577       {"12345678912345.de", L"12345678912345.de", "12345678912345.de",
578        Component(0, 17), CanonHostInfo::NEUTRAL, -1, ""},
579       {"1.12345678912345.de", L"1.12345678912345.de", "1.12345678912345.de",
580        Component(0, 19), CanonHostInfo::NEUTRAL, -1, ""},
581       {"12345678912345.12345678912345.de", L"12345678912345.12345678912345.de",
582        "12345678912345.12345678912345.de", Component(0, 32),
583        CanonHostInfo::NEUTRAL, -1, ""},
584       {"1.2.0xB3A73CE5B59.de", L"1.2.0xB3A73CE5B59.de", "1.2.0xb3a73ce5b59.de",
585        Component(0, 20), CanonHostInfo::NEUTRAL, -1, ""},
586       {"12345678912345.0xde", L"12345678912345.0xde", "12345678912345.0xde",
587        Component(0, 19), CanonHostInfo::BROKEN, -1, ""},
588       // A label that starts with "xn--" but contains non-ASCII characters
589       // should
590       // be an error. Escape the invalid characters.
591       {"xn--m\xc3\xbcnchen", L"xn--m\xfcnchen", "xn--m%C3%BCnchen",
592        Component(0, 16), CanonHostInfo::BROKEN, -1, ""},
593   };
594   // clang-format on
595
596   // CanonicalizeHost() non-verbose.
597   std::string out_str;
598   for (const auto& host_case : host_cases) {
599     // Narrow version.
600     if (host_case.input8) {
601       int host_len = static_cast<int>(strlen(host_case.input8));
602       Component in_comp(0, host_len);
603       Component out_comp;
604
605       out_str.clear();
606       StdStringCanonOutput output(&out_str);
607
608       bool success =
609           CanonicalizeHost(host_case.input8, in_comp, &output, &out_comp);
610       output.Complete();
611
612       EXPECT_EQ(host_case.expected_family != CanonHostInfo::BROKEN, success)
613           << "for input: " << host_case.input8;
614       EXPECT_EQ(host_case.expected, out_str)
615           << "for input: " << host_case.input8;
616       EXPECT_EQ(host_case.expected_component.begin, out_comp.begin)
617           << "for input: " << host_case.input8;
618       EXPECT_EQ(host_case.expected_component.len, out_comp.len)
619           << "for input: " << host_case.input8;
620     }
621
622     // Wide version.
623     if (host_case.input16) {
624       std::u16string input16(
625           test_utils::TruncateWStringToUTF16(host_case.input16));
626       int host_len = static_cast<int>(input16.length());
627       Component in_comp(0, host_len);
628       Component out_comp;
629
630       out_str.clear();
631       StdStringCanonOutput output(&out_str);
632
633       bool success = CanonicalizeHost(input16.c_str(), in_comp, &output,
634                                       &out_comp);
635       output.Complete();
636
637       EXPECT_EQ(host_case.expected_family != CanonHostInfo::BROKEN, success);
638       EXPECT_EQ(host_case.expected, out_str);
639       EXPECT_EQ(host_case.expected_component.begin, out_comp.begin);
640       EXPECT_EQ(host_case.expected_component.len, out_comp.len);
641     }
642   }
643
644   // CanonicalizeHostVerbose()
645   for (const auto& host_case : host_cases) {
646     // Narrow version.
647     if (host_case.input8) {
648       int host_len = static_cast<int>(strlen(host_case.input8));
649       Component in_comp(0, host_len);
650
651       out_str.clear();
652       StdStringCanonOutput output(&out_str);
653       CanonHostInfo host_info;
654
655       CanonicalizeHostVerbose(host_case.input8, in_comp, &output, &host_info);
656       output.Complete();
657
658       EXPECT_EQ(host_case.expected_family, host_info.family);
659       EXPECT_EQ(host_case.expected, out_str);
660       EXPECT_EQ(host_case.expected_component.begin, host_info.out_host.begin);
661       EXPECT_EQ(host_case.expected_component.len, host_info.out_host.len);
662       EXPECT_EQ(
663           host_case.expected_address_hex,
664           base::HexEncode(host_info.address,
665                           static_cast<size_t>(host_info.AddressLength())));
666       if (host_case.expected_family == CanonHostInfo::IPV4) {
667         EXPECT_EQ(host_case.expected_num_ipv4_components,
668                   host_info.num_ipv4_components);
669       }
670     }
671
672     // Wide version.
673     if (host_case.input16) {
674       std::u16string input16(
675           test_utils::TruncateWStringToUTF16(host_case.input16));
676       int host_len = static_cast<int>(input16.length());
677       Component in_comp(0, host_len);
678
679       out_str.clear();
680       StdStringCanonOutput output(&out_str);
681       CanonHostInfo host_info;
682
683       CanonicalizeHostVerbose(input16.c_str(), in_comp, &output, &host_info);
684       output.Complete();
685
686       EXPECT_EQ(host_case.expected_family, host_info.family);
687       EXPECT_EQ(host_case.expected, out_str);
688       EXPECT_EQ(host_case.expected_component.begin, host_info.out_host.begin);
689       EXPECT_EQ(host_case.expected_component.len, host_info.out_host.len);
690       EXPECT_EQ(
691           host_case.expected_address_hex,
692           base::HexEncode(host_info.address,
693                           static_cast<size_t>(host_info.AddressLength())));
694       if (host_case.expected_family == CanonHostInfo::IPV4) {
695         EXPECT_EQ(host_case.expected_num_ipv4_components,
696                   host_info.num_ipv4_components);
697       }
698     }
699   }
700 }
701
702 TEST(URLCanonTest, HostPuncutationChar) {
703   // '%' is not tested here. '%' is used for percent-escaping.
704   const std::string_view allowed_host_chars[] = {
705       "!", "\"", "$", "&", "'", "(", ")", "+", ",",
706       "-", ".",  ";", "=", "_", "`", "{", "}", "~",
707   };
708
709   const std::string_view forbidden_host_chars[] = {
710       "#", "/", ":", "<", ">", "?", "@", "[", "\\", "]", "^", "|",
711   };
712
713   // Standard non-compliant characters which are escaped. See
714   // https://crbug.com/1416013.
715   struct EscapedCharTestCase {
716     std::string_view input;
717     std::string_view expected;
718   } escaped_host_chars[] = {{" ", "%20"}, {"*", "%2A"}};
719
720   for (const std::string_view input : allowed_host_chars) {
721     std::string out_str;
722     Component in_comp(0, input.size());
723     Component out_comp;
724     StdStringCanonOutput output(&out_str);
725     bool success = CanonicalizeHost(input.data(), in_comp, &output, &out_comp);
726     EXPECT_TRUE(success) << "Input: " << input;
727     output.Complete();
728     EXPECT_EQ(out_str, input) << "Input: " << input;
729   }
730
731   for (const std::string_view input : forbidden_host_chars) {
732     std::string out_str;
733     Component in_comp(0, input.size());
734     Component out_comp;
735     StdStringCanonOutput output(&out_str);
736     EXPECT_FALSE(CanonicalizeHost(input.data(), in_comp, &output, &out_comp))
737         << "Input: " << input;
738   }
739
740   for (const auto& c : escaped_host_chars) {
741     std::string out_str;
742     Component in_comp(0, c.input.size());
743     Component out_comp;
744     StdStringCanonOutput output(&out_str);
745     bool success =
746         CanonicalizeHost(c.input.data(), in_comp, &output, &out_comp);
747     EXPECT_TRUE(success) << "Input: " << c.input;
748     output.Complete();
749     EXPECT_EQ(out_str, c.expected) << "Input: " << c.input;
750   }
751 }
752
753 TEST(URLCanonTest, IPv4) {
754   // clang-format off
755   IPAddressCase cases[] = {
756     // Empty is not an IP address.
757     {"", L"", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
758     {".", L".", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
759     // Regular IP addresses in different bases.
760     {"192.168.0.1", L"192.168.0.1", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 4, "C0A80001"},
761     {"0300.0250.00.01", L"0300.0250.00.01", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 4, "C0A80001"},
762     {"0xC0.0Xa8.0x0.0x1", L"0xC0.0Xa8.0x0.0x1", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 4, "C0A80001"},
763     // Non-IP addresses due to invalid characters.
764     {"192.168.9.com", L"192.168.9.com", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
765     // Hostnames with a numeric final component but other components that don't
766     // parse as numbers should be considered broken.
767     {"19a.168.0.1", L"19a.168.0.1", "", Component(), CanonHostInfo::BROKEN, -1, ""},
768     {"19a.168.0.1.", L"19a.168.0.1.", "", Component(), CanonHostInfo::BROKEN, -1, ""},
769     {"0308.0250.00.01", L"0308.0250.00.01", "", Component(), CanonHostInfo::BROKEN, -1, ""},
770     {"0308.0250.00.01.", L"0308.0250.00.01.", "", Component(), CanonHostInfo::BROKEN, -1, ""},
771     {"0xCG.0xA8.0x0.0x1", L"0xCG.0xA8.0x0.0x1", "", Component(), CanonHostInfo::BROKEN, -1, ""},
772     {"0xCG.0xA8.0x0.0x1.", L"0xCG.0xA8.0x0.0x1.", "", Component(), CanonHostInfo::BROKEN, -1, ""},
773     // Non-numeric terminal compeonent should be considered not IPv4 hostnames, but valid.
774     {"19.168.0.1a", L"19.168.0.1a", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
775     {"0xC.0xA8.0x0.0x1G", L"0xC.0xA8.0x0.0x1G", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
776     // Hostnames that would be considered broken IPv4 hostnames should be considered valid non-IPv4 hostnames if they end with two dots instead of 0 or 1.
777     {"19a.168.0.1..", L"19a.168.0.1..", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
778     {"0308.0250.00.01..", L"0308.0250.00.01..", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
779     {"0xCG.0xA8.0x0.0x1..", L"0xCG.0xA8.0x0.0x1..", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
780     // Hosts with components that aren't considered valid IPv4 numbers but are entirely numeric should be considered invalid.
781     {"1.2.3.08", L"1.2.3.08", "", Component(), CanonHostInfo::BROKEN, -1, ""},
782     {"1.2.3.08.", L"1.2.3.08.", "", Component(), CanonHostInfo::BROKEN, -1, ""},
783     // If there are not enough components, the last one should fill them out.
784     {"192", L"192", "0.0.0.192", Component(0, 9), CanonHostInfo::IPV4, 1, "000000C0"},
785     {"0xC0a80001", L"0xC0a80001", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 1, "C0A80001"},
786     {"030052000001", L"030052000001", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 1, "C0A80001"},
787     {"000030052000001", L"000030052000001", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 1, "C0A80001"},
788     {"192.168", L"192.168", "192.0.0.168", Component(0, 11), CanonHostInfo::IPV4, 2, "C00000A8"},
789     {"192.0x00A80001", L"192.0x000A80001", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 2, "C0A80001"},
790     {"0xc0.052000001", L"0xc0.052000001", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 2, "C0A80001"},
791     {"192.168.1", L"192.168.1", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 3, "C0A80001"},
792     // Hostnames with too many components, but a numeric final numeric component are invalid.
793     {"192.168.0.0.1", L"192.168.0.0.1", "", Component(), CanonHostInfo::BROKEN, -1, ""},
794     // We allow a single trailing dot.
795     {"192.168.0.1.", L"192.168.0.1.", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 4, "C0A80001"},
796     {"192.168.0.1. hello", L"192.168.0.1. hello", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
797     {"192.168.0.1..", L"192.168.0.1..", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
798     // Hosts with two dots in a row with a final numeric component are considered invalid.
799     {"192.168..1", L"192.168..1", "", Component(), CanonHostInfo::BROKEN, -1, ""},
800     {"192.168..1.", L"192.168..1.", "", Component(), CanonHostInfo::BROKEN, -1, ""},
801     // Any numerical overflow should be marked as BROKEN.
802     {"0x100.0", L"0x100.0", "", Component(), CanonHostInfo::BROKEN, -1, ""},
803     {"0x100.0.0", L"0x100.0.0", "", Component(), CanonHostInfo::BROKEN, -1, ""},
804     {"0x100.0.0.0", L"0x100.0.0.0", "", Component(), CanonHostInfo::BROKEN, -1, ""},
805     {"0.0x100.0.0", L"0.0x100.0.0", "", Component(), CanonHostInfo::BROKEN, -1, ""},
806     {"0.0.0x100.0", L"0.0.0x100.0", "", Component(), CanonHostInfo::BROKEN, -1, ""},
807     {"0.0.0.0x100", L"0.0.0.0x100", "", Component(), CanonHostInfo::BROKEN, -1, ""},
808     {"0.0.0x10000", L"0.0.0x10000", "", Component(), CanonHostInfo::BROKEN, -1, ""},
809     {"0.0x1000000", L"0.0x1000000", "", Component(), CanonHostInfo::BROKEN, -1, ""},
810     {"0x100000000", L"0x100000000", "", Component(), CanonHostInfo::BROKEN, -1, ""},
811     // Repeat the previous tests, minus 1, to verify boundaries.
812     {"0xFF.0", L"0xFF.0", "255.0.0.0", Component(0, 9), CanonHostInfo::IPV4, 2, "FF000000"},
813     {"0xFF.0.0", L"0xFF.0.0", "255.0.0.0", Component(0, 9), CanonHostInfo::IPV4, 3, "FF000000"},
814     {"0xFF.0.0.0", L"0xFF.0.0.0", "255.0.0.0", Component(0, 9), CanonHostInfo::IPV4, 4, "FF000000"},
815     {"0.0xFF.0.0", L"0.0xFF.0.0", "0.255.0.0", Component(0, 9), CanonHostInfo::IPV4, 4, "00FF0000"},
816     {"0.0.0xFF.0", L"0.0.0xFF.0", "0.0.255.0", Component(0, 9), CanonHostInfo::IPV4, 4, "0000FF00"},
817     {"0.0.0.0xFF", L"0.0.0.0xFF", "0.0.0.255", Component(0, 9), CanonHostInfo::IPV4, 4, "000000FF"},
818     {"0.0.0xFFFF", L"0.0.0xFFFF", "0.0.255.255", Component(0, 11), CanonHostInfo::IPV4, 3, "0000FFFF"},
819     {"0.0xFFFFFF", L"0.0xFFFFFF", "0.255.255.255", Component(0, 13), CanonHostInfo::IPV4, 2, "00FFFFFF"},
820     {"0xFFFFFFFF", L"0xFFFFFFFF", "255.255.255.255", Component(0, 15), CanonHostInfo::IPV4, 1, "FFFFFFFF"},
821     // Old trunctations tests. They're all "BROKEN" now.
822     {"276.256.0xf1a2.077777", L"276.256.0xf1a2.077777", "", Component(), CanonHostInfo::BROKEN, -1, ""},
823     {"192.168.0.257", L"192.168.0.257", "", Component(), CanonHostInfo::BROKEN, -1, ""},
824     {"192.168.0xa20001", L"192.168.0xa20001", "", Component(), CanonHostInfo::BROKEN, -1, ""},
825     {"192.015052000001", L"192.015052000001", "", Component(), CanonHostInfo::BROKEN, -1, ""},
826     {"0X12C0a80001", L"0X12C0a80001", "", Component(), CanonHostInfo::BROKEN, -1, ""},
827     {"276.1.2", L"276.1.2", "", Component(), CanonHostInfo::BROKEN, -1, ""},
828     // Too many components should be rejected, in valid ranges or not.
829     {"255.255.255.255.255", L"255.255.255.255.255", "", Component(), CanonHostInfo::BROKEN, -1, ""},
830     {"256.256.256.256.256", L"256.256.256.256.256", "", Component(), CanonHostInfo::BROKEN, -1, ""},
831     // Spaces should be rejected.
832     {"192.168.0.1 hello", L"192.168.0.1 hello", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
833     // Very large numbers.
834     {"0000000000000300.0x00000000000000fF.00000000000000001", L"0000000000000300.0x00000000000000fF.00000000000000001", "192.255.0.1", Component(0, 11), CanonHostInfo::IPV4, 3, "C0FF0001"},
835     {"0000000000000300.0xffffffffFFFFFFFF.3022415481470977", L"0000000000000300.0xffffffffFFFFFFFF.3022415481470977", "", Component(0, 11), CanonHostInfo::BROKEN, -1, ""},
836     // A number has no length limit, but long numbers can still overflow.
837     {"00000000000000000001", L"00000000000000000001", "0.0.0.1", Component(0, 7), CanonHostInfo::IPV4, 1, "00000001"},
838     {"0000000000000000100000000000000001", L"0000000000000000100000000000000001", "", Component(), CanonHostInfo::BROKEN, -1, ""},
839     // If a long component is non-numeric, it's a hostname, *not* a broken IP.
840     {"0.0.0.000000000000000000z", L"0.0.0.000000000000000000z", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
841     {"0.0.0.100000000000000000z", L"0.0.0.100000000000000000z", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
842     // Truncation of all zeros should still result in 0.
843     {"0.00.0x.0x0", L"0.00.0x.0x0", "0.0.0.0", Component(0, 7), CanonHostInfo::IPV4, 4, "00000000"},
844     // Non-ASCII characters in final component should return NEUTRAL.
845     {"1.2.3.\xF0\x9F\x92\xA9", L"1.2.3.\xD83D\xDCA9", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
846     {"1.2.3.4\xF0\x9F\x92\xA9", L"1.2.3.4\xD83D\xDCA9", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
847     {"1.2.3.0x\xF0\x9F\x92\xA9", L"1.2.3.0x\xD83D\xDCA9", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
848     {"1.2.3.0\xF0\x9F\x92\xA9", L"1.2.3.0\xD83D\xDCA9", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
849     // Non-ASCII characters in other components should result in broken IPs when final component is numeric.
850     {"1.2.\xF0\x9F\x92\xA9.4", L"1.2.\xD83D\xDCA9.4", "", Component(), CanonHostInfo::BROKEN, -1, ""},
851     {"1.2.3\xF0\x9F\x92\xA9.4", L"1.2.3\xD83D\xDCA9.4", "", Component(), CanonHostInfo::BROKEN, -1, ""},
852     {"1.2.0x\xF0\x9F\x92\xA9.4", L"1.2.0x\xD83D\xDCA9.4", "", Component(), CanonHostInfo::BROKEN, -1, ""},
853     {"1.2.0\xF0\x9F\x92\xA9.4", L"1.2.0\xD83D\xDCA9.4", "", Component(), CanonHostInfo::BROKEN, -1, ""},
854     {"\xF0\x9F\x92\xA9.2.3.4", L"\xD83D\xDCA9.2.3.4", "", Component(), CanonHostInfo::BROKEN, -1, ""},
855   };
856   // clang-format on
857
858   for (const auto& test_case : cases) {
859     SCOPED_TRACE(test_case.input8);
860
861     // 8-bit version.
862     Component component(0, static_cast<int>(strlen(test_case.input8)));
863
864     std::string out_str1;
865     StdStringCanonOutput output1(&out_str1);
866     CanonHostInfo host_info;
867     CanonicalizeIPAddress(test_case.input8, component, &output1, &host_info);
868     output1.Complete();
869
870     EXPECT_EQ(test_case.expected_family, host_info.family);
871     EXPECT_EQ(test_case.expected_address_hex,
872               base::HexEncode(host_info.address,
873                               static_cast<size_t>(host_info.AddressLength())));
874     if (host_info.family == CanonHostInfo::IPV4) {
875       EXPECT_STREQ(test_case.expected, out_str1.c_str());
876       EXPECT_EQ(test_case.expected_component.begin, host_info.out_host.begin);
877       EXPECT_EQ(test_case.expected_component.len, host_info.out_host.len);
878       EXPECT_EQ(test_case.expected_num_ipv4_components,
879                 host_info.num_ipv4_components);
880     }
881
882     // 16-bit version.
883     std::u16string input16(
884         test_utils::TruncateWStringToUTF16(test_case.input16));
885     component = Component(0, static_cast<int>(input16.length()));
886
887     std::string out_str2;
888     StdStringCanonOutput output2(&out_str2);
889     CanonicalizeIPAddress(input16.c_str(), component, &output2, &host_info);
890     output2.Complete();
891
892     EXPECT_EQ(test_case.expected_family, host_info.family);
893     EXPECT_EQ(test_case.expected_address_hex,
894               base::HexEncode(host_info.address,
895                               static_cast<size_t>(host_info.AddressLength())));
896     if (host_info.family == CanonHostInfo::IPV4) {
897       EXPECT_STREQ(test_case.expected, out_str2.c_str());
898       EXPECT_EQ(test_case.expected_component.begin, host_info.out_host.begin);
899       EXPECT_EQ(test_case.expected_component.len, host_info.out_host.len);
900       EXPECT_EQ(test_case.expected_num_ipv4_components,
901                 host_info.num_ipv4_components);
902     }
903   }
904 }
905
906 TEST(URLCanonTest, IPv6) {
907   IPAddressCase cases[] = {
908       // Empty is not an IP address.
909       {"", L"", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
910       // Non-IPs with [:] characters are marked BROKEN.
911       {":", L":", "", Component(), CanonHostInfo::BROKEN, -1, ""},
912       {"[", L"[", "", Component(), CanonHostInfo::BROKEN, -1, ""},
913       {"[:", L"[:", "", Component(), CanonHostInfo::BROKEN, -1, ""},
914       {"]", L"]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
915       {":]", L":]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
916       {"[]", L"[]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
917       {"[:]", L"[:]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
918       // Regular IP address is invalid without bounding '[' and ']'.
919       {"2001:db8::1", L"2001:db8::1", "", Component(), CanonHostInfo::BROKEN,
920        -1, ""},
921       {"[2001:db8::1", L"[2001:db8::1", "", Component(), CanonHostInfo::BROKEN,
922        -1, ""},
923       {"2001:db8::1]", L"2001:db8::1]", "", Component(), CanonHostInfo::BROKEN,
924        -1, ""},
925       // Regular IP addresses.
926       {"[::]", L"[::]", "[::]", Component(0, 4), CanonHostInfo::IPV6, -1,
927        "00000000000000000000000000000000"},
928       {"[::1]", L"[::1]", "[::1]", Component(0, 5), CanonHostInfo::IPV6, -1,
929        "00000000000000000000000000000001"},
930       {"[1::]", L"[1::]", "[1::]", Component(0, 5), CanonHostInfo::IPV6, -1,
931        "00010000000000000000000000000000"},
932
933       // Leading zeros should be stripped.
934       {"[000:01:02:003:004:5:6:007]", L"[000:01:02:003:004:5:6:007]",
935        "[0:1:2:3:4:5:6:7]", Component(0, 17), CanonHostInfo::IPV6, -1,
936        "00000001000200030004000500060007"},
937
938       // Upper case letters should be lowercased.
939       {"[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]",
940        Component(0, 20), CanonHostInfo::IPV6, -1,
941        "000A000B000C00DE00FF0000000100AC"},
942
943       // The same address can be written with different contractions, but should
944       // get canonicalized to the same thing.
945       {"[1:0:0:2::3:0]", L"[1:0:0:2::3:0]", "[1::2:0:0:3:0]", Component(0, 14),
946        CanonHostInfo::IPV6, -1, "00010000000000020000000000030000"},
947       {"[1::2:0:0:3:0]", L"[1::2:0:0:3:0]", "[1::2:0:0:3:0]", Component(0, 14),
948        CanonHostInfo::IPV6, -1, "00010000000000020000000000030000"},
949
950       // Addresses with embedded IPv4.
951       {"[::192.168.0.1]", L"[::192.168.0.1]", "[::c0a8:1]", Component(0, 10),
952        CanonHostInfo::IPV6, -1, "000000000000000000000000C0A80001"},
953       {"[::ffff:192.168.0.1]", L"[::ffff:192.168.0.1]", "[::ffff:c0a8:1]",
954        Component(0, 15), CanonHostInfo::IPV6, -1,
955        "00000000000000000000FFFFC0A80001"},
956       {"[::eeee:192.168.0.1]", L"[::eeee:192.168.0.1]", "[::eeee:c0a8:1]",
957        Component(0, 15), CanonHostInfo::IPV6, -1,
958        "00000000000000000000EEEEC0A80001"},
959       {"[2001::192.168.0.1]", L"[2001::192.168.0.1]", "[2001::c0a8:1]",
960        Component(0, 14), CanonHostInfo::IPV6, -1,
961        "200100000000000000000000C0A80001"},
962       {"[1:2:192.168.0.1:5:6]", L"[1:2:192.168.0.1:5:6]", "", Component(),
963        CanonHostInfo::BROKEN, -1, ""},
964
965       // IPv4 embedded IPv6 addresses
966       {"[::ffff:192.1.2]", L"[::ffff:192.1.2]", "[::ffff:c001:2]", Component(),
967        CanonHostInfo::BROKEN, -1, ""},
968       {"[::ffff:192.1]", L"[::ffff:192.1]", "[::ffff:c000:1]", Component(),
969        CanonHostInfo::BROKEN, -1, ""},
970       {"[::ffff:192.1.2.3.4]", L"[::ffff:192.1.2.3.4]", "", Component(),
971        CanonHostInfo::BROKEN, -1, ""},
972
973       // IPv4 using hex.
974       // TODO(eroman): Should this format be disallowed?
975       {"[::ffff:0xC0.0Xa8.0x0.0x1]", L"[::ffff:0xC0.0Xa8.0x0.0x1]",
976        "[::ffff:c0a8:1]", Component(0, 15), CanonHostInfo::IPV6, -1,
977        "00000000000000000000FFFFC0A80001"},
978
979       // There may be zeros surrounding the "::" contraction.
980       {"[0:0::0:0:8]", L"[0:0::0:0:8]", "[::8]", Component(0, 5),
981        CanonHostInfo::IPV6, -1, "00000000000000000000000000000008"},
982
983       {"[2001:db8::1]", L"[2001:db8::1]", "[2001:db8::1]", Component(0, 13),
984        CanonHostInfo::IPV6, -1, "20010DB8000000000000000000000001"},
985
986       // Can only have one "::" contraction in an IPv6 string literal.
987       {"[2001::db8::1]", L"[2001::db8::1]", "", Component(),
988        CanonHostInfo::BROKEN, -1, ""},
989       // No more than 2 consecutive ':'s.
990       {"[2001:db8:::1]", L"[2001:db8:::1]", "", Component(),
991        CanonHostInfo::BROKEN, -1, ""},
992       {"[:::]", L"[:::]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
993       // Non-IP addresses due to invalid characters.
994       {"[2001::.com]", L"[2001::.com]", "", Component(), CanonHostInfo::BROKEN,
995        -1, ""},
996       // If there are not enough components, the last one should fill them out.
997       // ... omitted at this time ...
998       // Too many components means not an IP address. Similarly, with too few
999       // if using IPv4 compat or mapped addresses.
1000       {"[::192.168.0.0.1]", L"[::192.168.0.0.1]", "", Component(),
1001        CanonHostInfo::BROKEN, -1, ""},
1002       {"[::ffff:192.168.0.0.1]", L"[::ffff:192.168.0.0.1]", "", Component(),
1003        CanonHostInfo::BROKEN, -1, ""},
1004       {"[1:2:3:4:5:6:7:8:9]", L"[1:2:3:4:5:6:7:8:9]", "", Component(),
1005        CanonHostInfo::BROKEN, -1, ""},
1006       // Too many bits (even though 8 components, the last one holds 32 bits).
1007       {"[0:0:0:0:0:0:0:192.168.0.1]", L"[0:0:0:0:0:0:0:192.168.0.1]", "",
1008        Component(), CanonHostInfo::BROKEN, -1, ""},
1009
1010       // Too many bits specified -- the contraction would have to be zero-length
1011       // to not exceed 128 bits.
1012       {"[1:2:3:4:5:6::192.168.0.1]", L"[1:2:3:4:5:6::192.168.0.1]", "",
1013        Component(), CanonHostInfo::BROKEN, -1, ""},
1014
1015       // The contraction is for 16 bits of zero.
1016       {"[1:2:3:4:5:6::8]", L"[1:2:3:4:5:6::8]", "[1:2:3:4:5:6:0:8]",
1017        Component(0, 17), CanonHostInfo::IPV6, -1,
1018        "00010002000300040005000600000008"},
1019
1020       // Cannot have a trailing colon.
1021       {"[1:2:3:4:5:6:7:8:]", L"[1:2:3:4:5:6:7:8:]", "", Component(),
1022        CanonHostInfo::BROKEN, -1, ""},
1023       {"[1:2:3:4:5:6:192.168.0.1:]", L"[1:2:3:4:5:6:192.168.0.1:]", "",
1024        Component(), CanonHostInfo::BROKEN, -1, ""},
1025
1026       // Cannot have negative numbers.
1027       {"[-1:2:3:4:5:6:7:8]", L"[-1:2:3:4:5:6:7:8]", "", Component(),
1028        CanonHostInfo::BROKEN, -1, ""},
1029
1030       // Scope ID -- the URL may contain an optional ["%" <scope_id>] section.
1031       // The scope_id should be included in the canonicalized URL, and is an
1032       // unsigned decimal number.
1033
1034       // Invalid because no ID was given after the percent.
1035
1036       // Don't allow scope-id
1037       {"[1::%1]", L"[1::%1]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
1038       {"[1::%eth0]", L"[1::%eth0]", "", Component(), CanonHostInfo::BROKEN, -1,
1039        ""},
1040       {"[1::%]", L"[1::%]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
1041       {"[%]", L"[%]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
1042       {"[::%:]", L"[::%:]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
1043
1044       // Don't allow leading or trailing colons.
1045       {"[:0:0::0:0:8]", L"[:0:0::0:0:8]", "", Component(),
1046        CanonHostInfo::BROKEN, -1, ""},
1047       {"[0:0::0:0:8:]", L"[0:0::0:0:8:]", "", Component(),
1048        CanonHostInfo::BROKEN, -1, ""},
1049       {"[:0:0::0:0:8:]", L"[:0:0::0:0:8:]", "", Component(),
1050        CanonHostInfo::BROKEN, -1, ""},
1051
1052       // We allow a single trailing dot.
1053       // ... omitted at this time ...
1054       // Two dots in a row means not an IP address.
1055       {"[::192.168..1]", L"[::192.168..1]", "", Component(),
1056        CanonHostInfo::BROKEN, -1, ""},
1057       // Any non-first components get truncated to one byte.
1058       // ... omitted at this time ...
1059       // Spaces should be rejected.
1060       {"[::1 hello]", L"[::1 hello]", "", Component(), CanonHostInfo::BROKEN,
1061        -1, ""},
1062   };
1063
1064   for (size_t i = 0; i < std::size(cases); i++) {
1065     // 8-bit version.
1066     Component component(0, static_cast<int>(strlen(cases[i].input8)));
1067
1068     std::string out_str1;
1069     StdStringCanonOutput output1(&out_str1);
1070     CanonHostInfo host_info;
1071     CanonicalizeIPAddress(cases[i].input8, component, &output1, &host_info);
1072     output1.Complete();
1073
1074     EXPECT_EQ(cases[i].expected_family, host_info.family);
1075     EXPECT_EQ(cases[i].expected_address_hex,
1076               base::HexEncode(host_info.address,
1077                               static_cast<size_t>(host_info.AddressLength())))
1078         << "iter " << i << " host " << cases[i].input8;
1079     if (host_info.family == CanonHostInfo::IPV6) {
1080       EXPECT_STREQ(cases[i].expected, out_str1.c_str());
1081       EXPECT_EQ(cases[i].expected_component.begin,
1082                 host_info.out_host.begin);
1083       EXPECT_EQ(cases[i].expected_component.len, host_info.out_host.len);
1084     }
1085
1086     // 16-bit version.
1087     std::u16string input16(
1088         test_utils::TruncateWStringToUTF16(cases[i].input16));
1089     component = Component(0, static_cast<int>(input16.length()));
1090
1091     std::string out_str2;
1092     StdStringCanonOutput output2(&out_str2);
1093     CanonicalizeIPAddress(input16.c_str(), component, &output2, &host_info);
1094     output2.Complete();
1095
1096     EXPECT_EQ(cases[i].expected_family, host_info.family);
1097     EXPECT_EQ(cases[i].expected_address_hex,
1098               base::HexEncode(host_info.address,
1099                               static_cast<size_t>(host_info.AddressLength())));
1100     if (host_info.family == CanonHostInfo::IPV6) {
1101       EXPECT_STREQ(cases[i].expected, out_str2.c_str());
1102       EXPECT_EQ(cases[i].expected_component.begin, host_info.out_host.begin);
1103       EXPECT_EQ(cases[i].expected_component.len, host_info.out_host.len);
1104     }
1105   }
1106 }
1107
1108 TEST(URLCanonTest, IPEmpty) {
1109   std::string out_str1;
1110   StdStringCanonOutput output1(&out_str1);
1111   CanonHostInfo host_info;
1112
1113   // This tests tests.
1114   const char spec[] = "192.168.0.1";
1115   CanonicalizeIPAddress(spec, Component(), &output1, &host_info);
1116   EXPECT_FALSE(host_info.IsIPAddress());
1117
1118   CanonicalizeIPAddress(spec, Component(0, 0), &output1, &host_info);
1119   EXPECT_FALSE(host_info.IsIPAddress());
1120 }
1121
1122 // Verifies that CanonicalizeHostSubstring produces the expected output and
1123 // does not "fix" IP addresses. Because this code is a subset of
1124 // CanonicalizeHost, the shared functionality is not tested.
1125 TEST(URLCanonTest, CanonicalizeHostSubstring) {
1126   // Basic sanity check.
1127   {
1128     std::string out_str;
1129     StdStringCanonOutput output(&out_str);
1130     EXPECT_TRUE(CanonicalizeHostSubstring("M\xc3\x9cNCHEN.com",
1131                                           Component(0, 12), &output));
1132     output.Complete();
1133     EXPECT_EQ("xn--mnchen-3ya.com", out_str);
1134   }
1135
1136   // Failure case.
1137   {
1138     std::string out_str;
1139     StdStringCanonOutput output(&out_str);
1140     EXPECT_FALSE(CanonicalizeHostSubstring(
1141         test_utils::TruncateWStringToUTF16(L"\xfdd0zyx.com").c_str(),
1142         Component(0, 8), &output));
1143     output.Complete();
1144     EXPECT_EQ("%EF%B7%90zyx.com", out_str);
1145   }
1146
1147   // Should return true for empty input strings.
1148   {
1149     std::string out_str;
1150     StdStringCanonOutput output(&out_str);
1151     EXPECT_TRUE(CanonicalizeHostSubstring("", Component(0, 0), &output));
1152     output.Complete();
1153     EXPECT_EQ(std::string(), out_str);
1154   }
1155
1156   // Numbers that look like IP addresses should not be changed.
1157   {
1158     std::string out_str;
1159     StdStringCanonOutput output(&out_str);
1160     EXPECT_TRUE(
1161         CanonicalizeHostSubstring("01.02.03.04", Component(0, 11), &output));
1162     output.Complete();
1163     EXPECT_EQ("01.02.03.04", out_str);
1164   }
1165 }
1166
1167 TEST(URLCanonTest, UserInfo) {
1168   // Note that the canonicalizer should escape and treat empty components as
1169   // not being there.
1170
1171   // We actually parse a full input URL so we can get the initial components.
1172   struct UserComponentCase {
1173     const char* input;
1174     const char* expected;
1175     Component expected_username;
1176     Component expected_password;
1177     bool expected_success;
1178   } user_info_cases[] = {
1179     {"http://user:pass@host.com/", "user:pass@", Component(0, 4), Component(5, 4), true},
1180     {"http://@host.com/", "", Component(0, -1), Component(0, -1), true},
1181     {"http://:@host.com/", "", Component(0, -1), Component(0, -1), true},
1182     {"http://foo:@host.com/", "foo@", Component(0, 3), Component(0, -1), true},
1183     {"http://:foo@host.com/", ":foo@", Component(0, 0), Component(1, 3), true},
1184     {"http://^ :$\t@host.com/", "%5E%20:$%09@", Component(0, 6), Component(7, 4), true},
1185     {"http://user:pass@/", "user:pass@", Component(0, 4), Component(5, 4), true},
1186     {"http://%2540:bar@domain.com/", "%2540:bar@", Component(0, 5), Component(6, 3), true },
1187
1188       // IE7 compatibility: old versions allowed backslashes in usernames, but
1189       // IE7 does not. We disallow it as well.
1190     {"ftp://me\\mydomain:pass@foo.com/", "", Component(0, -1), Component(0, -1), true},
1191   };
1192
1193   for (const auto& user_info_case : user_info_cases) {
1194     int url_len = static_cast<int>(strlen(user_info_case.input));
1195     Parsed parsed;
1196     ParseStandardURL(user_info_case.input, url_len, &parsed);
1197     Component out_user, out_pass;
1198     std::string out_str;
1199     StdStringCanonOutput output1(&out_str);
1200
1201     bool success = CanonicalizeUserInfo(user_info_case.input, parsed.username,
1202                                         user_info_case.input, parsed.password,
1203                                         &output1, &out_user, &out_pass);
1204     output1.Complete();
1205
1206     EXPECT_EQ(user_info_case.expected_success, success);
1207     EXPECT_EQ(user_info_case.expected, out_str);
1208     EXPECT_EQ(user_info_case.expected_username.begin, out_user.begin);
1209     EXPECT_EQ(user_info_case.expected_username.len, out_user.len);
1210     EXPECT_EQ(user_info_case.expected_password.begin, out_pass.begin);
1211     EXPECT_EQ(user_info_case.expected_password.len, out_pass.len);
1212
1213     // Now try the wide version
1214     out_str.clear();
1215     StdStringCanonOutput output2(&out_str);
1216     std::u16string wide_input(base::UTF8ToUTF16(user_info_case.input));
1217     success = CanonicalizeUserInfo(wide_input.c_str(),
1218                                    parsed.username,
1219                                    wide_input.c_str(),
1220                                    parsed.password,
1221                                    &output2,
1222                                    &out_user,
1223                                    &out_pass);
1224     output2.Complete();
1225
1226     EXPECT_EQ(user_info_case.expected_success, success);
1227     EXPECT_EQ(user_info_case.expected, out_str);
1228     EXPECT_EQ(user_info_case.expected_username.begin, out_user.begin);
1229     EXPECT_EQ(user_info_case.expected_username.len, out_user.len);
1230     EXPECT_EQ(user_info_case.expected_password.begin, out_pass.begin);
1231     EXPECT_EQ(user_info_case.expected_password.len, out_pass.len);
1232   }
1233 }
1234
1235 TEST(URLCanonTest, Port) {
1236   // We only need to test that the number gets properly put into the output
1237   // buffer. The parser unit tests will test scanning the number correctly.
1238   //
1239   // Note that the CanonicalizePort will always prepend a colon to the output
1240   // to separate it from the colon that it assumes precedes it.
1241   struct PortCase {
1242     const char* input;
1243     int default_port;
1244     const char* expected;
1245     Component expected_component;
1246     bool expected_success;
1247   } port_cases[] = {
1248       // Invalid input should be copied w/ failure.
1249     {"as df", 80, ":as%20df", Component(1, 7), false},
1250     {"-2", 80, ":-2", Component(1, 2), false},
1251       // Default port should be omitted.
1252     {"80", 80, "", Component(0, -1), true},
1253     {"8080", 80, ":8080", Component(1, 4), true},
1254       // PORT_UNSPECIFIED should mean always keep the port.
1255     {"80", PORT_UNSPECIFIED, ":80", Component(1, 2), true},
1256   };
1257
1258   for (const auto& port_case : port_cases) {
1259     int url_len = static_cast<int>(strlen(port_case.input));
1260     Component in_comp(0, url_len);
1261     Component out_comp;
1262     std::string out_str;
1263     StdStringCanonOutput output1(&out_str);
1264     bool success = CanonicalizePort(
1265         port_case.input, in_comp, port_case.default_port, &output1, &out_comp);
1266     output1.Complete();
1267
1268     EXPECT_EQ(port_case.expected_success, success);
1269     EXPECT_EQ(port_case.expected, out_str);
1270     EXPECT_EQ(port_case.expected_component.begin, out_comp.begin);
1271     EXPECT_EQ(port_case.expected_component.len, out_comp.len);
1272
1273     // Now try the wide version
1274     out_str.clear();
1275     StdStringCanonOutput output2(&out_str);
1276     std::u16string wide_input(base::UTF8ToUTF16(port_case.input));
1277     success = CanonicalizePort(wide_input.c_str(), in_comp,
1278                                port_case.default_port, &output2, &out_comp);
1279     output2.Complete();
1280
1281     EXPECT_EQ(port_case.expected_success, success);
1282     EXPECT_EQ(port_case.expected, out_str);
1283     EXPECT_EQ(port_case.expected_component.begin, out_comp.begin);
1284     EXPECT_EQ(port_case.expected_component.len, out_comp.len);
1285   }
1286 }
1287
1288 DualComponentCase kCommonPathCases[] = {
1289     // ----- path collapsing tests -----
1290     {"/././foo", L"/././foo", "/foo", Component(0, 4), true},
1291     {"/./.foo", L"/./.foo", "/.foo", Component(0, 5), true},
1292     {"/foo/.", L"/foo/.", "/foo/", Component(0, 5), true},
1293     {"/foo/./", L"/foo/./", "/foo/", Component(0, 5), true},
1294     // double dots followed by a slash or the end of the string count
1295     {"/foo/bar/..", L"/foo/bar/..", "/foo/", Component(0, 5), true},
1296     {"/foo/bar/../", L"/foo/bar/../", "/foo/", Component(0, 5), true},
1297     // don't count double dots when they aren't followed by a slash
1298     {"/foo/..bar", L"/foo/..bar", "/foo/..bar", Component(0, 10), true},
1299     // some in the middle
1300     {"/foo/bar/../ton", L"/foo/bar/../ton", "/foo/ton", Component(0, 8), true},
1301     {"/foo/bar/../ton/../../a", L"/foo/bar/../ton/../../a", "/a",
1302      Component(0, 2), true},
1303     // we should not be able to go above the root
1304     {"/foo/../../..", L"/foo/../../..", "/", Component(0, 1), true},
1305     {"/foo/../../../ton", L"/foo/../../../ton", "/ton", Component(0, 4), true},
1306     // escaped dots should be unescaped and treated the same as dots
1307     {"/foo/%2e", L"/foo/%2e", "/foo/", Component(0, 5), true},
1308     {"/foo/%2e%2", L"/foo/%2e%2", "/foo/.%2", Component(0, 8), true},
1309     {"/foo/%2e./%2e%2e/.%2e/%2e.bar", L"/foo/%2e./%2e%2e/.%2e/%2e.bar",
1310      "/..bar", Component(0, 6), true},
1311     // Multiple slashes in a row should be preserved and treated like empty
1312     // directory names.
1313     {"////../..", L"////../..", "//", Component(0, 2), true},
1314
1315     // ----- escaping tests -----
1316     {"/foo", L"/foo", "/foo", Component(0, 4), true},
1317     // Valid escape sequence
1318     {"/%20foo", L"/%20foo", "/%20foo", Component(0, 7), true},
1319     // Invalid escape sequence we should pass through unchanged.
1320     {"/foo%", L"/foo%", "/foo%", Component(0, 5), true},
1321     {"/foo%2", L"/foo%2", "/foo%2", Component(0, 6), true},
1322     // Invalid escape sequence: bad characters should be treated the same as
1323     // the surrounding text, not as escaped (in this case, UTF-8).
1324     {"/foo%2zbar", L"/foo%2zbar", "/foo%2zbar", Component(0, 10), true},
1325     {"/foo%2\xc2\xa9zbar", nullptr, "/foo%2%C2%A9zbar", Component(0, 16), true},
1326     {nullptr, L"/foo%2\xc2\xa9zbar", "/foo%2%C3%82%C2%A9zbar", Component(0, 22),
1327      true},
1328     // Regular characters that are escaped should remain escaped
1329     {"/foo%41%7a", L"/foo%41%7a", "/foo%41%7a", Component(0, 10), true},
1330     // Funny characters that are unescaped should be escaped
1331     {"/foo\x09\x91%91", nullptr, "/foo%09%91%91", Component(0, 13), true},
1332     {nullptr, L"/foo\x09\x91%91", "/foo%09%C2%91%91", Component(0, 16), true},
1333     // %00 should not cause failures.
1334     {"/foo%00%51", L"/foo%00%51", "/foo%00%51", Component(0, 10), true},
1335     // Some characters should be passed through unchanged regardless of esc.
1336     {"/(%28:%3A%29)", L"/(%28:%3A%29)", "/(%28:%3A%29)", Component(0, 13),
1337      true},
1338     // Characters that are properly escaped should not have the case changed
1339     // of hex letters.
1340     {"/%3A%3a%3C%3c", L"/%3A%3a%3C%3c", "/%3A%3a%3C%3c", Component(0, 13),
1341      true},
1342     // Funny characters that are unescaped should be escaped
1343     {"/foo\tbar", L"/foo\tbar", "/foo%09bar", Component(0, 10), true},
1344     // Backslashes should get converted to forward slashes
1345     {"\\foo\\bar", L"\\foo\\bar", "/foo/bar", Component(0, 8), true},
1346     // Hashes found in paths (possibly only when the caller explicitly sets
1347     // the path on an already-parsed URL) should be escaped.
1348     {"/foo#bar", L"/foo#bar", "/foo%23bar", Component(0, 10), true},
1349     // %7f should be allowed and %3D should not be unescaped (these were wrong
1350     // in a previous version).
1351     {"/%7Ffp3%3Eju%3Dduvgw%3Dd", L"/%7Ffp3%3Eju%3Dduvgw%3Dd",
1352      "/%7Ffp3%3Eju%3Dduvgw%3Dd", Component(0, 24), true},
1353     // @ should be passed through unchanged (escaped or unescaped).
1354     {"/@asdf%40", L"/@asdf%40", "/@asdf%40", Component(0, 9), true},
1355     // Nested escape sequences no longer happen. See https://crbug.com/1252531.
1356     {"/%A%42", L"/%A%42", "/%A%42", Component(0, 6), true},
1357     {"/%%41B", L"/%%41B", "/%%41B", Component(0, 6), true},
1358     {"/%%41%42", L"/%%41%42", "/%%41%42", Component(0, 8), true},
1359     // Make sure truncated "nested" escapes don't result in reading off the
1360     // string end.
1361     {"/%%41", L"/%%41", "/%%41", Component(0, 5), true},
1362     // Don't unescape the leading '%' if unescaping doesn't result in a valid
1363     // new escape sequence.
1364     {"/%%470", L"/%%470", "/%%470", Component(0, 6), true},
1365     {"/%%2D%41", L"/%%2D%41", "/%%2D%41", Component(0, 8), true},
1366     // Don't erroneously downcast a UTF-16 character in a way that makes it
1367     // look like part of an escape sequence.
1368     {nullptr, L"/%%41\x0130", "/%%41%C4%B0", Component(0, 11), true},
1369
1370     // ----- encoding tests -----
1371     // Basic conversions
1372     {"/\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xbd\xa0\xe5\xa5\xbd",
1373      L"/\x4f60\x597d\x4f60\x597d", "/%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD",
1374      Component(0, 37), true},
1375     // Unicode Noncharacter (U+FDD0) should not fail.
1376     {"/\xef\xb7\x90zyx", nullptr, "/%EF%B7%90zyx", Component(0, 13), true},
1377     {nullptr, L"/\xfdd0zyx", "/%EF%B7%90zyx", Component(0, 13), true},
1378 };
1379
1380 typedef bool (*CanonFunc8Bit)(const char*,
1381                               const Component&,
1382                               CanonOutput*,
1383                               Component*);
1384 typedef bool (*CanonFunc16Bit)(const char16_t*,
1385                                const Component&,
1386                                CanonOutput*,
1387                                Component*);
1388
1389 void DoPathTest(const DualComponentCase* path_cases,
1390                 size_t num_cases,
1391                 CanonFunc8Bit canon_func_8,
1392                 CanonFunc16Bit canon_func_16) {
1393   for (size_t i = 0; i < num_cases; i++) {
1394     testing::Message scope_message;
1395     scope_message << path_cases[i].input8 << "," << path_cases[i].input16;
1396     SCOPED_TRACE(scope_message);
1397     if (path_cases[i].input8) {
1398       int len = static_cast<int>(strlen(path_cases[i].input8));
1399       Component in_comp(0, len);
1400       Component out_comp;
1401       std::string out_str;
1402       StdStringCanonOutput output(&out_str);
1403       bool success =
1404           canon_func_8(path_cases[i].input8, in_comp, &output, &out_comp);
1405       output.Complete();
1406
1407       EXPECT_EQ(path_cases[i].expected_success, success);
1408       EXPECT_EQ(path_cases[i].expected_component.begin, out_comp.begin);
1409       EXPECT_EQ(path_cases[i].expected_component.len, out_comp.len);
1410       EXPECT_EQ(path_cases[i].expected, out_str);
1411     }
1412
1413     if (path_cases[i].input16) {
1414       std::u16string input16(
1415           test_utils::TruncateWStringToUTF16(path_cases[i].input16));
1416       int len = static_cast<int>(input16.length());
1417       Component in_comp(0, len);
1418       Component out_comp;
1419       std::string out_str;
1420       StdStringCanonOutput output(&out_str);
1421
1422       bool success =
1423           canon_func_16(input16.c_str(), in_comp, &output, &out_comp);
1424       output.Complete();
1425
1426       EXPECT_EQ(path_cases[i].expected_success, success);
1427       EXPECT_EQ(path_cases[i].expected_component.begin, out_comp.begin);
1428       EXPECT_EQ(path_cases[i].expected_component.len, out_comp.len);
1429       EXPECT_EQ(path_cases[i].expected, out_str);
1430     }
1431   }
1432 }
1433
1434 TEST(URLCanonTest, Path) {
1435   DoPathTest(kCommonPathCases, std::size(kCommonPathCases), CanonicalizePath,
1436              CanonicalizePath);
1437
1438   // Manual test: embedded NULLs should be escaped and the URL should be marked
1439   // as valid.
1440   const char path_with_null[] = "/ab\0c";
1441   Component in_comp(0, 5);
1442   Component out_comp;
1443
1444   std::string out_str;
1445   StdStringCanonOutput output(&out_str);
1446   bool success = CanonicalizePath(path_with_null, in_comp, &output, &out_comp);
1447   output.Complete();
1448   EXPECT_TRUE(success);
1449   EXPECT_EQ("/ab%00c", out_str);
1450 }
1451
1452 TEST(URLCanonTest, PartialPath) {
1453   DualComponentCase partial_path_cases[] = {
1454       {".html", L".html", ".html", Component(0, 5), true},
1455       {"", L"", "", Component(0, 0), true},
1456   };
1457
1458   DoPathTest(kCommonPathCases, std::size(kCommonPathCases),
1459              CanonicalizePartialPath, CanonicalizePartialPath);
1460   DoPathTest(partial_path_cases, std::size(partial_path_cases),
1461              CanonicalizePartialPath, CanonicalizePartialPath);
1462 }
1463
1464 TEST(URLCanonTest, Query) {
1465   struct QueryCase {
1466     const char* input8;
1467     const wchar_t* input16;
1468     const char* expected;
1469   } query_cases[] = {
1470       // Regular ASCII case.
1471     {"foo=bar", L"foo=bar", "?foo=bar"},
1472       // Allow question marks in the query without escaping
1473     {"as?df", L"as?df", "?as?df"},
1474       // Always escape '#' since it would mark the ref.
1475     {"as#df", L"as#df", "?as%23df"},
1476       // Escape some questionable 8-bit characters, but never unescape.
1477     {"\x02hello\x7f bye", L"\x02hello\x7f bye", "?%02hello%7F%20bye"},
1478     {"%40%41123", L"%40%41123", "?%40%41123"},
1479       // Chinese input/output
1480     {"q=\xe4\xbd\xa0\xe5\xa5\xbd", L"q=\x4f60\x597d", "?q=%E4%BD%A0%E5%A5%BD"},
1481       // Invalid UTF-8/16 input should be replaced with invalid characters.
1482     {"q=\xed\xed", L"q=\xd800\xd800", "?q=%EF%BF%BD%EF%BF%BD"},
1483       // Don't allow < or > because sometimes they are used for XSS if the
1484       // URL is echoed in content. Firefox does this, IE doesn't.
1485     {"q=<asdf>", L"q=<asdf>", "?q=%3Casdf%3E"},
1486       // Escape double quotemarks in the query.
1487     {"q=\"asdf\"", L"q=\"asdf\"", "?q=%22asdf%22"},
1488   };
1489
1490   for (const auto& query_case : query_cases) {
1491     Component out_comp;
1492
1493     if (query_case.input8) {
1494       int len = static_cast<int>(strlen(query_case.input8));
1495       Component in_comp(0, len);
1496       std::string out_str;
1497
1498       StdStringCanonOutput output(&out_str);
1499       CanonicalizeQuery(query_case.input8, in_comp, nullptr, &output,
1500                         &out_comp);
1501       output.Complete();
1502
1503       EXPECT_EQ(query_case.expected, out_str);
1504     }
1505
1506     if (query_case.input16) {
1507       std::u16string input16(
1508           test_utils::TruncateWStringToUTF16(query_case.input16));
1509       int len = static_cast<int>(input16.length());
1510       Component in_comp(0, len);
1511       std::string out_str;
1512
1513       StdStringCanonOutput output(&out_str);
1514       CanonicalizeQuery(input16.c_str(), in_comp, nullptr, &output, &out_comp);
1515       output.Complete();
1516
1517       EXPECT_EQ(query_case.expected, out_str);
1518     }
1519   }
1520
1521   // Extra test for input with embedded NULL;
1522   std::string out_str;
1523   StdStringCanonOutput output(&out_str);
1524   Component out_comp;
1525   CanonicalizeQuery("a \x00z\x01", Component(0, 5), nullptr, &output,
1526                     &out_comp);
1527   output.Complete();
1528   EXPECT_EQ("?a%20%00z%01", out_str);
1529 }
1530
1531 TEST(URLCanonTest, Ref) {
1532   // Refs are trivial, it just checks the encoding.
1533   DualComponentCase ref_cases[] = {
1534       {"hello!", L"hello!", "#hello!", Component(1, 6), true},
1535       // We should escape spaces, double-quotes, angled braces, and backtics.
1536       {"hello, world", L"hello, world", "#hello,%20world", Component(1, 14),
1537        true},
1538       {"hello,\"world", L"hello,\"world", "#hello,%22world", Component(1, 14),
1539        true},
1540       {"hello,<world", L"hello,<world", "#hello,%3Cworld", Component(1, 14),
1541        true},
1542       {"hello,>world", L"hello,>world", "#hello,%3Eworld", Component(1, 14),
1543        true},
1544       {"hello,`world", L"hello,`world", "#hello,%60world", Component(1, 14),
1545        true},
1546       // UTF-8/wide input should be preserved
1547       {"\xc2\xa9", L"\xa9", "#%C2%A9", Component(1, 6), true},
1548       // Test a characer that takes > 16 bits (U+10300 = old italic letter A)
1549       {"\xF0\x90\x8C\x80ss", L"\xd800\xdf00ss", "#%F0%90%8C%80ss",
1550        Component(1, 14), true},
1551       // Escaping should be preserved unchanged, even invalid ones
1552       {"%41%a", L"%41%a", "#%41%a", Component(1, 5), true},
1553       // Invalid UTF-8/16 input should be flagged and the input made valid
1554       {"\xc2", nullptr, "#%EF%BF%BD", Component(1, 9), true},
1555       {nullptr, L"\xd800\x597d", "#%EF%BF%BD%E5%A5%BD", Component(1, 18), true},
1556       // Test a Unicode invalid character.
1557       {"a\xef\xb7\x90", L"a\xfdd0", "#a%EF%B7%90", Component(1, 10), true},
1558       // Refs can have # signs and we should preserve them.
1559       {"asdf#qwer", L"asdf#qwer", "#asdf#qwer", Component(1, 9), true},
1560       {"#asdf", L"#asdf", "##asdf", Component(1, 5), true},
1561   };
1562
1563   for (const auto& ref_case : ref_cases) {
1564     // 8-bit input
1565     if (ref_case.input8) {
1566       int len = static_cast<int>(strlen(ref_case.input8));
1567       Component in_comp(0, len);
1568       Component out_comp;
1569
1570       std::string out_str;
1571       StdStringCanonOutput output(&out_str);
1572       CanonicalizeRef(ref_case.input8, in_comp, &output, &out_comp);
1573       output.Complete();
1574
1575       EXPECT_EQ(ref_case.expected_component.begin, out_comp.begin);
1576       EXPECT_EQ(ref_case.expected_component.len, out_comp.len);
1577       EXPECT_EQ(ref_case.expected, out_str);
1578     }
1579
1580     // 16-bit input
1581     if (ref_case.input16) {
1582       std::u16string input16(
1583           test_utils::TruncateWStringToUTF16(ref_case.input16));
1584       int len = static_cast<int>(input16.length());
1585       Component in_comp(0, len);
1586       Component out_comp;
1587
1588       std::string out_str;
1589       StdStringCanonOutput output(&out_str);
1590       CanonicalizeRef(input16.c_str(), in_comp, &output, &out_comp);
1591       output.Complete();
1592
1593       EXPECT_EQ(ref_case.expected_component.begin, out_comp.begin);
1594       EXPECT_EQ(ref_case.expected_component.len, out_comp.len);
1595       EXPECT_EQ(ref_case.expected, out_str);
1596     }
1597   }
1598
1599   // Try one with an embedded NULL. It should be stripped.
1600   const char null_input[5] = "ab\x00z";
1601   Component null_input_component(0, 4);
1602   Component out_comp;
1603
1604   std::string out_str;
1605   StdStringCanonOutput output(&out_str);
1606   CanonicalizeRef(null_input, null_input_component, &output, &out_comp);
1607   output.Complete();
1608
1609   EXPECT_EQ(1, out_comp.begin);
1610   EXPECT_EQ(6, out_comp.len);
1611   EXPECT_EQ("#ab%00z", out_str);
1612 }
1613
1614 TEST(URLCanonTest, CanonicalizeStandardURL) {
1615   // The individual component canonicalize tests should have caught the cases
1616   // for each of those components. Here, we just need to test that the various
1617   // parts are included or excluded properly, and have the correct separators.
1618   // clang-format off
1619   struct URLCase {
1620     const char* input;
1621     const char* expected;
1622     bool expected_success;
1623   } cases[] = {
1624     {"http://www.google.com/foo?bar=baz#", "http://www.google.com/foo?bar=baz#",
1625      true},
1626
1627       // Backslashes should get converted to forward slashes.
1628       {"http:\\\\www.google.com\\foo", "http://www.google.com/foo", true},
1629
1630       // Busted refs shouldn't make the whole thing fail.
1631       {"http://www.google.com/asdf#\xc2",
1632        "http://www.google.com/asdf#%EF%BF%BD", true},
1633
1634       // Basic port tests.
1635       {"http://foo:80/", "http://foo/", true},
1636       {"http://foo:81/", "http://foo:81/", true},
1637       {"httpa://foo:80/", "httpa://foo:80/", true},
1638       {"http://foo:-80/", "http://foo:-80/", false},
1639
1640       {"https://foo:443/", "https://foo/", true},
1641       {"https://foo:80/", "https://foo:80/", true},
1642       {"ftp://foo:21/", "ftp://foo/", true},
1643       {"ftp://foo:80/", "ftp://foo:80/", true},
1644       {"gopher://foo:70/", "gopher://foo:70/", true},
1645       {"gopher://foo:443/", "gopher://foo:443/", true},
1646       {"ws://foo:80/", "ws://foo/", true},
1647       {"ws://foo:81/", "ws://foo:81/", true},
1648       {"ws://foo:443/", "ws://foo:443/", true},
1649       {"ws://foo:815/", "ws://foo:815/", true},
1650       {"wss://foo:80/", "wss://foo:80/", true},
1651       {"wss://foo:81/", "wss://foo:81/", true},
1652       {"wss://foo:443/", "wss://foo/", true},
1653       {"wss://foo:815/", "wss://foo:815/", true},
1654
1655       // This particular code path ends up "backing up" to replace an invalid
1656       // host ICU generated with an escaped version. Test that in the context
1657       // of a full URL to make sure the backing up doesn't mess up the non-host
1658       // parts of the URL. "EF B9 AA" is U+FE6A which is a type of percent that
1659       // ICU will convert to an ASCII one, generating "%81".
1660       {"ws:)W\x1eW\xef\xb9\xaa"
1661        "81:80/",
1662        "ws://)w%1ew%81/", false},
1663       // Regression test for the last_invalid_percent_index bug described in
1664       // https://crbug.com/1080890#c10.
1665       {R"(HTTP:S/5%\../>%41)", "http://s/%3E%41", true},
1666   };
1667   // clang-format on
1668
1669   for (const auto& i : cases) {
1670     int url_len = static_cast<int>(strlen(i.input));
1671     Parsed parsed;
1672     ParseStandardURL(i.input, url_len, &parsed);
1673
1674     Parsed out_parsed;
1675     std::string out_str;
1676     StdStringCanonOutput output(&out_str);
1677     bool success = CanonicalizeStandardURL(
1678         i.input, url_len, parsed, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION,
1679         nullptr, &output, &out_parsed);
1680     output.Complete();
1681
1682     EXPECT_EQ(i.expected_success, success);
1683     EXPECT_EQ(i.expected, out_str);
1684   }
1685 }
1686
1687 // The codepath here is the same as for regular canonicalization, so we just
1688 // need to test that things are replaced or not correctly.
1689 TEST(URLCanonTest, ReplaceStandardURL) {
1690   ReplaceCase replace_cases[] = {
1691       // Common case of truncating the path.
1692       {"http://www.google.com/foo?bar=baz#ref", nullptr, nullptr, nullptr,
1693        nullptr, nullptr, "/", kDeleteComp, kDeleteComp,
1694        "http://www.google.com/"},
1695       // Replace everything
1696       {"http://a:b@google.com:22/foo;bar?baz@cat", "https", "me", "pw",
1697        "host.com", "99", "/path", "query", "ref",
1698        "https://me:pw@host.com:99/path?query#ref"},
1699       // Replace nothing
1700       {"http://a:b@google.com:22/foo?baz@cat", nullptr, nullptr, nullptr,
1701        nullptr, nullptr, nullptr, nullptr, nullptr,
1702        "http://a:b@google.com:22/foo?baz@cat"},
1703       // Replace scheme with filesystem. The result is garbage, but you asked
1704       // for it.
1705       {"http://a:b@google.com:22/foo?baz@cat", "filesystem", nullptr, nullptr,
1706        nullptr, nullptr, nullptr, nullptr, nullptr,
1707        "filesystem://a:b@google.com:22/foo?baz@cat"},
1708   };
1709
1710   for (const auto& replace_case : replace_cases) {
1711     const ReplaceCase& cur = replace_case;
1712     int base_len = static_cast<int>(strlen(cur.base));
1713     Parsed parsed;
1714     ParseStandardURL(cur.base, base_len, &parsed);
1715
1716     Replacements<char> r;
1717     typedef Replacements<char> R;  // Clean up syntax.
1718
1719     // Note that for the scheme we pass in a different clear function since
1720     // there is no function to clear the scheme.
1721     SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
1722     SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
1723     SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
1724     SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
1725     SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
1726     SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
1727     SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
1728     SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
1729
1730     std::string out_str;
1731     StdStringCanonOutput output(&out_str);
1732     Parsed out_parsed;
1733     ReplaceStandardURL(replace_case.base, parsed, r,
1734                        SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, nullptr,
1735                        &output, &out_parsed);
1736     output.Complete();
1737
1738     EXPECT_EQ(replace_case.expected, out_str);
1739   }
1740
1741   // The path pointer should be ignored if the address is invalid.
1742   {
1743     const char src[] = "http://www.google.com/here_is_the_path";
1744     int src_len = static_cast<int>(strlen(src));
1745
1746     Parsed parsed;
1747     ParseStandardURL(src, src_len, &parsed);
1748
1749     // Replace the path to 0 length string. By using 1 as the string address,
1750     // the test should get an access violation if it tries to dereference it.
1751     Replacements<char> r;
1752     r.SetPath(reinterpret_cast<char*>(0x00000001), Component(0, 0));
1753     std::string out_str1;
1754     StdStringCanonOutput output1(&out_str1);
1755     Parsed new_parsed;
1756     ReplaceStandardURL(src, parsed, r,
1757                        SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, nullptr,
1758                        &output1, &new_parsed);
1759     output1.Complete();
1760     EXPECT_STREQ("http://www.google.com/", out_str1.c_str());
1761
1762     // Same with an "invalid" path.
1763     r.SetPath(reinterpret_cast<char*>(0x00000001), Component());
1764     std::string out_str2;
1765     StdStringCanonOutput output2(&out_str2);
1766     ReplaceStandardURL(src, parsed, r,
1767                        SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, nullptr,
1768                        &output2, &new_parsed);
1769     output2.Complete();
1770     EXPECT_STREQ("http://www.google.com/", out_str2.c_str());
1771   }
1772 }
1773
1774 TEST(URLCanonTest, ReplaceFileURL) {
1775   ReplaceCase replace_cases[] = {
1776       // Replace everything
1777       {"file:///C:/gaba?query#ref", nullptr, nullptr, nullptr, "filer", nullptr,
1778        "/foo", "b", "c", "file://filer/foo?b#c"},
1779       // Replace nothing
1780       {"file:///C:/gaba?query#ref", nullptr, nullptr, nullptr, nullptr, nullptr,
1781        nullptr, nullptr, nullptr, "file:///C:/gaba?query#ref"},
1782       {"file:///Y:", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
1783        nullptr, nullptr, "file:///Y:"},
1784       {"file:///Y:/", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
1785        nullptr, nullptr, "file:///Y:/"},
1786       {"file:///./Y", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
1787        nullptr, nullptr, "file:///Y"},
1788       {"file:///./Y:", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
1789        nullptr, nullptr, "file:///Y:"},
1790       // Clear non-path components (common)
1791       {"file:///C:/gaba?query#ref", nullptr, nullptr, nullptr, nullptr, nullptr,
1792        nullptr, kDeleteComp, kDeleteComp, "file:///C:/gaba"},
1793       // Replace path with something that doesn't begin with a slash and make
1794       // sure it gets added properly.
1795       {"file:///C:/gaba", nullptr, nullptr, nullptr, nullptr, nullptr,
1796        "interesting/", nullptr, nullptr, "file:///interesting/"},
1797       {"file:///home/gaba?query#ref", nullptr, nullptr, nullptr, "filer",
1798        nullptr, "/foo", "b", "c", "file://filer/foo?b#c"},
1799       {"file:///home/gaba?query#ref", nullptr, nullptr, nullptr, nullptr,
1800        nullptr, nullptr, nullptr, nullptr, "file:///home/gaba?query#ref"},
1801       {"file:///home/gaba?query#ref", nullptr, nullptr, nullptr, nullptr,
1802        nullptr, nullptr, kDeleteComp, kDeleteComp, "file:///home/gaba"},
1803       {"file:///home/gaba", nullptr, nullptr, nullptr, nullptr, nullptr,
1804        "interesting/", nullptr, nullptr, "file:///interesting/"},
1805       // Replace scheme -- shouldn't do anything.
1806       {"file:///C:/gaba?query#ref", "http", nullptr, nullptr, nullptr, nullptr,
1807        nullptr, nullptr, nullptr, "file:///C:/gaba?query#ref"},
1808   };
1809
1810   for (const auto& replace_case : replace_cases) {
1811     const ReplaceCase& cur = replace_case;
1812     SCOPED_TRACE(cur.base);
1813     int base_len = static_cast<int>(strlen(cur.base));
1814     Parsed parsed;
1815     ParseFileURL(cur.base, base_len, &parsed);
1816
1817     Replacements<char> r;
1818     typedef Replacements<char> R;  // Clean up syntax.
1819     SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
1820     SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
1821     SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
1822     SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
1823     SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
1824     SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
1825     SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
1826     SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
1827
1828     std::string out_str;
1829     StdStringCanonOutput output(&out_str);
1830     Parsed out_parsed;
1831     ReplaceFileURL(cur.base, parsed, r, nullptr, &output, &out_parsed);
1832     output.Complete();
1833
1834     EXPECT_EQ(replace_case.expected, out_str);
1835   }
1836 }
1837
1838 TEST(URLCanonTest, ReplaceFileSystemURL) {
1839   ReplaceCase replace_cases[] = {
1840       // Replace everything in the outer URL.
1841       {"filesystem:file:///temporary/gaba?query#ref", nullptr, nullptr, nullptr,
1842        nullptr, nullptr, "/foo", "b", "c",
1843        "filesystem:file:///temporary/foo?b#c"},
1844       // Replace nothing
1845       {"filesystem:file:///temporary/gaba?query#ref", nullptr, nullptr, nullptr,
1846        nullptr, nullptr, nullptr, nullptr, nullptr,
1847        "filesystem:file:///temporary/gaba?query#ref"},
1848       // Clear non-path components (common)
1849       {"filesystem:file:///temporary/gaba?query#ref", nullptr, nullptr, nullptr,
1850        nullptr, nullptr, nullptr, kDeleteComp, kDeleteComp,
1851        "filesystem:file:///temporary/gaba"},
1852       // Replace path with something that doesn't begin with a slash and make
1853       // sure it gets added properly.
1854       {"filesystem:file:///temporary/gaba?query#ref", nullptr, nullptr, nullptr,
1855        nullptr, nullptr, "interesting/", nullptr, nullptr,
1856        "filesystem:file:///temporary/interesting/?query#ref"},
1857       // Replace scheme -- shouldn't do anything except canonicalize.
1858       {"filesystem:http://u:p@bar.com/t/gaba?query#ref", "http", nullptr,
1859        nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
1860        "filesystem:http://bar.com/t/gaba?query#ref"},
1861       // Replace username -- shouldn't do anything except canonicalize.
1862       {"filesystem:http://u:p@bar.com/t/gaba?query#ref", nullptr, "u2", nullptr,
1863        nullptr, nullptr, nullptr, nullptr, nullptr,
1864        "filesystem:http://bar.com/t/gaba?query#ref"},
1865       // Replace password -- shouldn't do anything except canonicalize.
1866       {"filesystem:http://u:p@bar.com/t/gaba?query#ref", nullptr, nullptr,
1867        "pw2", nullptr, nullptr, nullptr, nullptr, nullptr,
1868        "filesystem:http://bar.com/t/gaba?query#ref"},
1869       // Replace host -- shouldn't do anything except canonicalize.
1870       {"filesystem:http://u:p@bar.com:80/t/gaba?query#ref", nullptr, nullptr,
1871        nullptr, "foo.com", nullptr, nullptr, nullptr, nullptr,
1872        "filesystem:http://bar.com/t/gaba?query#ref"},
1873       // Replace port -- shouldn't do anything except canonicalize.
1874       {"filesystem:http://u:p@bar.com:40/t/gaba?query#ref", nullptr, nullptr,
1875        nullptr, nullptr, "41", nullptr, nullptr, nullptr,
1876        "filesystem:http://bar.com:40/t/gaba?query#ref"},
1877   };
1878
1879   for (const auto& replace_case : replace_cases) {
1880     const ReplaceCase& cur = replace_case;
1881     int base_len = static_cast<int>(strlen(cur.base));
1882     Parsed parsed;
1883     ParseFileSystemURL(cur.base, base_len, &parsed);
1884
1885     Replacements<char> r;
1886     typedef Replacements<char> R;  // Clean up syntax.
1887     SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
1888     SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
1889     SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
1890     SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
1891     SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
1892     SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
1893     SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
1894     SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
1895
1896     std::string out_str;
1897     StdStringCanonOutput output(&out_str);
1898     Parsed out_parsed;
1899     ReplaceFileSystemURL(cur.base, parsed, r, nullptr, &output, &out_parsed);
1900     output.Complete();
1901
1902     EXPECT_EQ(replace_case.expected, out_str);
1903   }
1904 }
1905
1906 TEST(URLCanonTest, ReplacePathURL) {
1907   ReplaceCase replace_cases[] = {
1908       // Replace everything
1909       {"data:foo", "javascript", nullptr, nullptr, nullptr, nullptr,
1910        "alert('foo?');", nullptr, nullptr, "javascript:alert('foo?');"},
1911       // Replace nothing
1912       {"data:foo", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
1913        nullptr, nullptr, "data:foo"},
1914       // Replace one or the other
1915       {"data:foo", "javascript", nullptr, nullptr, nullptr, nullptr, nullptr,
1916        nullptr, nullptr, "javascript:foo"},
1917       {"data:foo", nullptr, nullptr, nullptr, nullptr, nullptr, "bar", nullptr,
1918        nullptr, "data:bar"},
1919       {"data:foo", nullptr, nullptr, nullptr, nullptr, nullptr, kDeleteComp,
1920        nullptr, nullptr, "data:"},
1921   };
1922
1923   for (const auto& replace_case : replace_cases) {
1924     const ReplaceCase& cur = replace_case;
1925     int base_len = static_cast<int>(strlen(cur.base));
1926     Parsed parsed;
1927     ParsePathURL(cur.base, base_len, false, &parsed);
1928
1929     Replacements<char> r;
1930     typedef Replacements<char> R;  // Clean up syntax.
1931     SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
1932     SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
1933     SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
1934     SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
1935     SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
1936     SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
1937     SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
1938     SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
1939
1940     std::string out_str;
1941     StdStringCanonOutput output(&out_str);
1942     Parsed out_parsed;
1943     ReplacePathURL(cur.base, parsed, r, &output, &out_parsed);
1944     output.Complete();
1945
1946     EXPECT_EQ(replace_case.expected, out_str);
1947   }
1948 }
1949
1950 TEST(URLCanonTest, ReplaceMailtoURL) {
1951   ReplaceCase replace_cases[] = {
1952       // Replace everything
1953       {"mailto:jon@foo.com?body=sup", "mailto", nullptr, nullptr, nullptr,
1954        nullptr, "addr1", "to=tony", nullptr, "mailto:addr1?to=tony"},
1955       // Replace nothing
1956       {"mailto:jon@foo.com?body=sup", nullptr, nullptr, nullptr, nullptr,
1957        nullptr, nullptr, nullptr, nullptr, "mailto:jon@foo.com?body=sup"},
1958       // Replace the path
1959       {"mailto:jon@foo.com?body=sup", nullptr, nullptr, nullptr, nullptr,
1960        nullptr, "jason", nullptr, nullptr, "mailto:jason?body=sup"},
1961       // Replace the query
1962       {"mailto:jon@foo.com?body=sup", nullptr, nullptr, nullptr, nullptr,
1963        nullptr, nullptr, "custom=1", nullptr, "mailto:jon@foo.com?custom=1"},
1964       // Replace the path and query
1965       {"mailto:jon@foo.com?body=sup", nullptr, nullptr, nullptr, nullptr,
1966        nullptr, "jason", "custom=1", nullptr, "mailto:jason?custom=1"},
1967       // Set the query to empty (should leave trailing question mark)
1968       {"mailto:jon@foo.com?body=sup", nullptr, nullptr, nullptr, nullptr,
1969        nullptr, nullptr, "", nullptr, "mailto:jon@foo.com?"},
1970       // Clear the query
1971       {"mailto:jon@foo.com?body=sup", nullptr, nullptr, nullptr, nullptr,
1972        nullptr, nullptr, "|", nullptr, "mailto:jon@foo.com"},
1973       // Clear the path
1974       {"mailto:jon@foo.com?body=sup", nullptr, nullptr, nullptr, nullptr,
1975        nullptr, "|", nullptr, nullptr, "mailto:?body=sup"},
1976       // Clear the path + query
1977       {"mailto:", nullptr, nullptr, nullptr, nullptr, nullptr, "|", "|",
1978        nullptr, "mailto:"},
1979       // Setting the ref should have no effect
1980       {"mailto:addr1", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
1981        nullptr, "BLAH", "mailto:addr1"},
1982   };
1983
1984   for (const auto& replace_case : replace_cases) {
1985     const ReplaceCase& cur = replace_case;
1986     int base_len = static_cast<int>(strlen(cur.base));
1987     Parsed parsed;
1988     ParseMailtoURL(cur.base, base_len, &parsed);
1989
1990     Replacements<char> r;
1991     typedef Replacements<char> R;
1992     SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
1993     SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
1994     SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
1995     SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
1996     SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
1997     SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
1998     SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
1999     SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
2000
2001     std::string out_str;
2002     StdStringCanonOutput output(&out_str);
2003     Parsed out_parsed;
2004     ReplaceMailtoURL(cur.base, parsed, r, &output, &out_parsed);
2005     output.Complete();
2006
2007     EXPECT_EQ(replace_case.expected, out_str);
2008   }
2009 }
2010
2011 TEST(URLCanonTest, CanonicalizeFileURL) {
2012   struct URLCase {
2013     const char* input;
2014     const char* expected;
2015     bool expected_success;
2016     Component expected_host;
2017     Component expected_path;
2018   } cases[] = {
2019 #ifdef _WIN32
2020       // Windows-style paths
2021       {"file:c:\\foo\\bar.html", "file:///C:/foo/bar.html", true, Component(),
2022        Component(7, 16)},
2023       {"  File:c|////foo\\bar.html", "file:///C:////foo/bar.html", true,
2024        Component(), Component(7, 19)},
2025       {"file:", "file:///", true, Component(), Component(7, 1)},
2026       {"file:UNChost/path", "file://unchost/path", true, Component(7, 7),
2027        Component(14, 5)},
2028       // CanonicalizeFileURL supports absolute Windows style paths for IE
2029       // compatibility. Note that the caller must decide that this is a file
2030       // URL itself so it can call the file canonicalizer. This is usually
2031       // done automatically as part of relative URL resolving.
2032       {"c:\\foo\\bar", "file:///C:/foo/bar", true, Component(),
2033        Component(7, 11)},
2034       {"C|/foo/bar", "file:///C:/foo/bar", true, Component(), Component(7, 11)},
2035       {"/C|\\foo\\bar", "file:///C:/foo/bar", true, Component(),
2036        Component(7, 11)},
2037       {"//C|/foo/bar", "file:///C:/foo/bar", true, Component(),
2038        Component(7, 11)},
2039       {"//server/file", "file://server/file", true, Component(7, 6),
2040        Component(13, 5)},
2041       {"\\\\server\\file", "file://server/file", true, Component(7, 6),
2042        Component(13, 5)},
2043       {"/\\server/file", "file://server/file", true, Component(7, 6),
2044        Component(13, 5)},
2045       // We should preserve the number of slashes after the colon for IE
2046       // compatibility, except when there is none, in which case we should
2047       // add one.
2048       {"file:c:foo/bar.html", "file:///C:/foo/bar.html", true, Component(),
2049        Component(7, 16)},
2050       {"file:/\\/\\C:\\\\//foo\\bar.html", "file:///C:////foo/bar.html", true,
2051        Component(), Component(7, 19)},
2052       // Three slashes should be non-UNC, even if there is no drive spec (IE
2053       // does this, which makes the resulting request invalid).
2054       {"file:///foo/bar.txt", "file:///foo/bar.txt", true, Component(),
2055        Component(7, 12)},
2056       // TODO(brettw) we should probably fail for invalid host names, which
2057       // would change the expected result on this test. We also currently allow
2058       // colon even though it's probably invalid, because its currently the
2059       // "natural" result of the way the canonicalizer is written. There doesn't
2060       // seem to be a strong argument for why allowing it here would be bad, so
2061       // we just tolerate it and the load will fail later.
2062       {"FILE:/\\/\\7:\\\\//foo\\bar.html", "file://7:////foo/bar.html", false,
2063        Component(7, 2), Component(9, 16)},
2064       {"file:filer/home\\me", "file://filer/home/me", true, Component(7, 5),
2065        Component(12, 8)},
2066       // Make sure relative paths can't go above the "C:"
2067       {"file:///C:/foo/../../../bar.html", "file:///C:/bar.html", true,
2068        Component(), Component(7, 12)},
2069       // Busted refs shouldn't make the whole thing fail.
2070       {"file:///C:/asdf#\xc2", "file:///C:/asdf#%EF%BF%BD", true, Component(),
2071        Component(7, 8)},
2072       {"file:///./s:", "file:///S:", true, Component(), Component(7, 3)},
2073 #else
2074       // Unix-style paths
2075       {"file:///home/me", "file:///home/me", true, Component(),
2076        Component(7, 8)},
2077       // Windowsy ones should get still treated as Unix-style.
2078       {"file:c:\\foo\\bar.html", "file:///c:/foo/bar.html", true, Component(),
2079        Component(7, 16)},
2080       {"file:c|//foo\\bar.html", "file:///c%7C//foo/bar.html", true,
2081        Component(), Component(7, 19)},
2082       {"file:///./s:", "file:///s:", true, Component(), Component(7, 3)},
2083       // file: tests from WebKit (LayoutTests/fast/loader/url-parse-1.html)
2084       {"//", "file:///", true, Component(), Component(7, 1)},
2085       {"///", "file:///", true, Component(), Component(7, 1)},
2086       {"///test", "file:///test", true, Component(), Component(7, 5)},
2087       {"file://test", "file://test/", true, Component(7, 4), Component(11, 1)},
2088       {"file://localhost", "file://localhost/", true, Component(7, 9),
2089        Component(16, 1)},
2090       {"file://localhost/", "file://localhost/", true, Component(7, 9),
2091        Component(16, 1)},
2092       {"file://localhost/test", "file://localhost/test", true, Component(7, 9),
2093        Component(16, 5)},
2094 #endif  // _WIN32
2095   };
2096
2097   for (const auto& i : cases) {
2098     int url_len = static_cast<int>(strlen(i.input));
2099     Parsed parsed;
2100     ParseFileURL(i.input, url_len, &parsed);
2101
2102     Parsed out_parsed;
2103     std::string out_str;
2104     StdStringCanonOutput output(&out_str);
2105     bool success = CanonicalizeFileURL(i.input, url_len, parsed, nullptr,
2106                                        &output, &out_parsed);
2107     output.Complete();
2108
2109     EXPECT_EQ(i.expected_success, success);
2110     EXPECT_EQ(i.expected, out_str);
2111
2112     // Make sure the spec was properly identified, the file canonicalizer has
2113     // different code for writing the spec.
2114     EXPECT_EQ(0, out_parsed.scheme.begin);
2115     EXPECT_EQ(4, out_parsed.scheme.len);
2116
2117     EXPECT_EQ(i.expected_host.begin, out_parsed.host.begin);
2118     EXPECT_EQ(i.expected_host.len, out_parsed.host.len);
2119
2120     EXPECT_EQ(i.expected_path.begin, out_parsed.path.begin);
2121     EXPECT_EQ(i.expected_path.len, out_parsed.path.len);
2122   }
2123 }
2124
2125 TEST(URLCanonTest, CanonicalizeFileSystemURL) {
2126   struct URLCase {
2127     const char* input;
2128     const char* expected;
2129     bool expected_success;
2130   } cases[] = {
2131       {"Filesystem:htTp://www.Foo.com:80/tempoRary",
2132        "filesystem:http://www.foo.com/tempoRary/", true},
2133       {"filesystem:httpS://www.foo.com/temporary/",
2134        "filesystem:https://www.foo.com/temporary/", true},
2135       {"filesystem:http://www.foo.com//", "filesystem:http://www.foo.com//",
2136        false},
2137       {"filesystem:http://www.foo.com/persistent/bob?query#ref",
2138        "filesystem:http://www.foo.com/persistent/bob?query#ref", true},
2139       {"filesystem:fIle://\\temporary/", "filesystem:file:///temporary/", true},
2140       {"filesystem:fiLe:///temporary", "filesystem:file:///temporary/", true},
2141       {"filesystem:File:///temporary/Bob?qUery#reF",
2142        "filesystem:file:///temporary/Bob?qUery#reF", true},
2143       {"FilEsysteM:htTp:E=/.", "filesystem:http://e=//", false},
2144   };
2145
2146   for (const auto& i : cases) {
2147     int url_len = static_cast<int>(strlen(i.input));
2148     Parsed parsed;
2149     ParseFileSystemURL(i.input, url_len, &parsed);
2150
2151     Parsed out_parsed;
2152     std::string out_str;
2153     StdStringCanonOutput output(&out_str);
2154     bool success = CanonicalizeFileSystemURL(i.input, url_len, parsed, nullptr,
2155                                              &output, &out_parsed);
2156     output.Complete();
2157
2158     EXPECT_EQ(i.expected_success, success);
2159     EXPECT_EQ(i.expected, out_str);
2160
2161     // Make sure the spec was properly identified, the filesystem canonicalizer
2162     // has different code for writing the spec.
2163     EXPECT_EQ(0, out_parsed.scheme.begin);
2164     EXPECT_EQ(10, out_parsed.scheme.len);
2165     if (success)
2166       EXPECT_GT(out_parsed.path.len, 0);
2167   }
2168 }
2169
2170 TEST(URLCanonTest, CanonicalizePathURL) {
2171   // Path URLs should get canonicalized schemes but nothing else.
2172   struct PathCase {
2173     const char* input;
2174     const char* expected;
2175   } path_cases[] = {
2176       {"javascript:", "javascript:"},
2177       {"JavaScript:Foo", "javascript:Foo"},
2178       {"Foo:\":This /is interesting;?#", "foo:\":This /is interesting;?#"},
2179
2180       // Unicode invalid characters should not cause failure. See
2181       // https://crbug.com/925614.
2182       {"javascript:\uFFFF", "javascript:%EF%BF%BF"},
2183   };
2184
2185   for (const auto& path_case : path_cases) {
2186     int url_len = static_cast<int>(strlen(path_case.input));
2187     Parsed parsed;
2188     ParsePathURL(path_case.input, url_len, true, &parsed);
2189
2190     Parsed out_parsed;
2191     std::string out_str;
2192     StdStringCanonOutput output(&out_str);
2193     bool success = CanonicalizePathURL(path_case.input, url_len, parsed,
2194                                        &output, &out_parsed);
2195     output.Complete();
2196
2197     EXPECT_TRUE(success);
2198     EXPECT_EQ(path_case.expected, out_str);
2199
2200     EXPECT_EQ(0, out_parsed.host.begin);
2201     EXPECT_EQ(-1, out_parsed.host.len);
2202
2203     // When we end with a colon at the end, there should be no path.
2204     if (path_case.input[url_len - 1] == ':') {
2205       EXPECT_EQ(0, out_parsed.GetContent().begin);
2206       EXPECT_EQ(-1, out_parsed.GetContent().len);
2207     }
2208   }
2209 }
2210
2211 TEST(URLCanonTest, CanonicalizePathURLPath) {
2212   struct PathCase {
2213     std::string input;
2214     std::wstring input16;
2215     std::string expected;
2216   } path_cases[] = {
2217       {"Foo", L"Foo", "Foo"},
2218       {"\":This /is interesting;?#", L"\":This /is interesting;?#",
2219        "\":This /is interesting;?#"},
2220       {"\uFFFF", L"\uFFFF", "%EF%BF%BF"},
2221   };
2222
2223   for (const auto& path_case : path_cases) {
2224     // 8-bit string input
2225     std::string out_str;
2226     StdStringCanonOutput output(&out_str);
2227     url::Component out_component;
2228     CanonicalizePathURLPath(path_case.input.data(),
2229                             Component(0, path_case.input.size()), &output,
2230                             &out_component);
2231     output.Complete();
2232
2233     EXPECT_EQ(path_case.expected, out_str);
2234
2235     EXPECT_EQ(0, out_component.begin);
2236     EXPECT_EQ(path_case.expected.size(),
2237               static_cast<size_t>(out_component.len));
2238
2239     // 16-bit string input
2240     std::string out_str16;
2241     StdStringCanonOutput output16(&out_str16);
2242     url::Component out_component16;
2243     std::u16string input16(
2244         test_utils::TruncateWStringToUTF16(path_case.input16.data()));
2245     CanonicalizePathURLPath(input16.c_str(),
2246                             Component(0, path_case.input16.size()), &output16,
2247                             &out_component16);
2248     output16.Complete();
2249
2250     EXPECT_EQ(path_case.expected, out_str16);
2251
2252     EXPECT_EQ(0, out_component16.begin);
2253     EXPECT_EQ(path_case.expected.size(),
2254               static_cast<size_t>(out_component16.len));
2255   }
2256 }
2257
2258 TEST(URLCanonTest, CanonicalizeMailtoURL) {
2259   struct URLCase {
2260     const char* input;
2261     const char* expected;
2262     bool expected_success;
2263     Component expected_path;
2264     Component expected_query;
2265   } cases[] = {
2266     // Null character should be escaped to %00.
2267     // Keep this test first in the list as it is handled specially below.
2268     {"mailto:addr1\0addr2?foo",
2269      "mailto:addr1%00addr2?foo",
2270      true, Component(7, 13), Component(21, 3)},
2271     {"mailto:addr1",
2272      "mailto:addr1",
2273      true, Component(7, 5), Component()},
2274     {"mailto:addr1@foo.com",
2275      "mailto:addr1@foo.com",
2276      true, Component(7, 13), Component()},
2277     // Trailing whitespace is stripped.
2278     {"MaIlTo:addr1 \t ",
2279      "mailto:addr1",
2280      true, Component(7, 5), Component()},
2281     {"MaIlTo:addr1?to=jon",
2282      "mailto:addr1?to=jon",
2283      true, Component(7, 5), Component(13,6)},
2284     {"mailto:addr1,addr2",
2285      "mailto:addr1,addr2",
2286      true, Component(7, 11), Component()},
2287     // Embedded spaces must be encoded.
2288     {"mailto:addr1, addr2",
2289      "mailto:addr1,%20addr2",
2290      true, Component(7, 14), Component()},
2291     {"mailto:addr1, addr2?subject=one two ",
2292      "mailto:addr1,%20addr2?subject=one%20two",
2293      true, Component(7, 14), Component(22, 17)},
2294     {"mailto:addr1%2caddr2",
2295      "mailto:addr1%2caddr2",
2296      true, Component(7, 13), Component()},
2297     {"mailto:\xF0\x90\x8C\x80",
2298      "mailto:%F0%90%8C%80",
2299      true, Component(7, 12), Component()},
2300     // Invalid -- UTF-8 encoded surrogate value.
2301     {"mailto:\xed\xa0\x80",
2302      "mailto:%EF%BF%BD%EF%BF%BD%EF%BF%BD",
2303      false, Component(7, 27), Component()},
2304     {"mailto:addr1?",
2305      "mailto:addr1?",
2306      true, Component(7, 5), Component(13, 0)},
2307     // Certain characters have special meanings and must be encoded.
2308     {"mailto:! \x22$&()+,-./09:;<=>@AZ[\\]&_`az{|}~\x7f?Query! \x22$&()+,-./09:;<=>@AZ[\\]&_`az{|}~",
2309      "mailto:!%20%22$&()+,-./09:;%3C=%3E@AZ[\\]&_%60az%7B%7C%7D~%7F?Query!%20%22$&()+,-./09:;%3C=%3E@AZ[\\]&_`az{|}~",
2310      true, Component(7, 53), Component(61, 47)},
2311   };
2312
2313   // Define outside of loop to catch bugs where components aren't reset
2314   Parsed parsed;
2315   Parsed out_parsed;
2316
2317   for (size_t i = 0; i < std::size(cases); i++) {
2318     int url_len = static_cast<int>(strlen(cases[i].input));
2319     if (i == 0) {
2320       // The first test case purposely has a '\0' in it -- don't count it
2321       // as the string terminator.
2322       url_len = 22;
2323     }
2324     ParseMailtoURL(cases[i].input, url_len, &parsed);
2325
2326     std::string out_str;
2327     StdStringCanonOutput output(&out_str);
2328     bool success = CanonicalizeMailtoURL(cases[i].input, url_len, parsed,
2329                                          &output, &out_parsed);
2330     output.Complete();
2331
2332     EXPECT_EQ(cases[i].expected_success, success);
2333     EXPECT_EQ(cases[i].expected, out_str);
2334
2335     // Make sure the spec was properly identified
2336     EXPECT_EQ(0, out_parsed.scheme.begin);
2337     EXPECT_EQ(6, out_parsed.scheme.len);
2338
2339     EXPECT_EQ(cases[i].expected_path.begin, out_parsed.path.begin);
2340     EXPECT_EQ(cases[i].expected_path.len, out_parsed.path.len);
2341
2342     EXPECT_EQ(cases[i].expected_query.begin, out_parsed.query.begin);
2343     EXPECT_EQ(cases[i].expected_query.len, out_parsed.query.len);
2344   }
2345 }
2346
2347 #ifndef WIN32
2348
2349 TEST(URLCanonTest, _itoa_s) {
2350   // We fill the buffer with 0xff to ensure that it's getting properly
2351   // null-terminated. We also allocate one byte more than what we tell
2352   // _itoa_s about, and ensure that the extra byte is untouched.
2353   char buf[6];
2354   memset(buf, 0xff, sizeof(buf));
2355   EXPECT_EQ(0, _itoa_s(12, buf, sizeof(buf) - 1, 10));
2356   EXPECT_STREQ("12", buf);
2357   EXPECT_EQ('\xFF', buf[3]);
2358
2359   // Test the edge cases - exactly the buffer size and one over
2360   memset(buf, 0xff, sizeof(buf));
2361   EXPECT_EQ(0, _itoa_s(1234, buf, sizeof(buf) - 1, 10));
2362   EXPECT_STREQ("1234", buf);
2363   EXPECT_EQ('\xFF', buf[5]);
2364
2365   memset(buf, 0xff, sizeof(buf));
2366   EXPECT_EQ(EINVAL, _itoa_s(12345, buf, sizeof(buf) - 1, 10));
2367   EXPECT_EQ('\xFF', buf[5]);  // should never write to this location
2368
2369   // Test the template overload (note that this will see the full buffer)
2370   memset(buf, 0xff, sizeof(buf));
2371   EXPECT_EQ(0, _itoa_s(12, buf, 10));
2372   EXPECT_STREQ("12", buf);
2373   EXPECT_EQ('\xFF', buf[3]);
2374
2375   memset(buf, 0xff, sizeof(buf));
2376   EXPECT_EQ(0, _itoa_s(12345, buf, 10));
2377   EXPECT_STREQ("12345", buf);
2378
2379   EXPECT_EQ(EINVAL, _itoa_s(123456, buf, 10));
2380
2381   // Test that radix 16 is supported.
2382   memset(buf, 0xff, sizeof(buf));
2383   EXPECT_EQ(0, _itoa_s(1234, buf, sizeof(buf) - 1, 16));
2384   EXPECT_STREQ("4d2", buf);
2385   EXPECT_EQ('\xFF', buf[5]);
2386 }
2387
2388 TEST(URLCanonTest, _itow_s) {
2389   // We fill the buffer with 0xff to ensure that it's getting properly
2390   // null-terminated. We also allocate one byte more than what we tell
2391   // _itoa_s about, and ensure that the extra byte is untouched.
2392   char16_t buf[6];
2393   const char fill_mem = 0xff;
2394   const char16_t fill_char = 0xffff;
2395   memset(buf, fill_mem, sizeof(buf));
2396   EXPECT_EQ(0, _itow_s(12, buf, sizeof(buf) / 2 - 1, 10));
2397   EXPECT_EQ(u"12", std::u16string(buf));
2398   EXPECT_EQ(fill_char, buf[3]);
2399
2400   // Test the edge cases - exactly the buffer size and one over
2401   EXPECT_EQ(0, _itow_s(1234, buf, sizeof(buf) / 2 - 1, 10));
2402   EXPECT_EQ(u"1234", std::u16string(buf));
2403   EXPECT_EQ(fill_char, buf[5]);
2404
2405   memset(buf, fill_mem, sizeof(buf));
2406   EXPECT_EQ(EINVAL, _itow_s(12345, buf, sizeof(buf) / 2 - 1, 10));
2407   EXPECT_EQ(fill_char, buf[5]);  // should never write to this location
2408
2409   // Test the template overload (note that this will see the full buffer)
2410   memset(buf, fill_mem, sizeof(buf));
2411   EXPECT_EQ(0, _itow_s(12, buf, 10));
2412   EXPECT_EQ(u"12", std::u16string(buf));
2413   EXPECT_EQ(fill_char, buf[3]);
2414
2415   memset(buf, fill_mem, sizeof(buf));
2416   EXPECT_EQ(0, _itow_s(12345, buf, 10));
2417   EXPECT_EQ(u"12345", std::u16string(buf));
2418
2419   EXPECT_EQ(EINVAL, _itow_s(123456, buf, 10));
2420 }
2421
2422 #endif  // !WIN32
2423
2424 // Returns true if the given two structures are the same.
2425 static bool ParsedIsEqual(const Parsed& a, const Parsed& b) {
2426   return a.scheme.begin == b.scheme.begin && a.scheme.len == b.scheme.len &&
2427          a.username.begin == b.username.begin && a.username.len == b.username.len &&
2428          a.password.begin == b.password.begin && a.password.len == b.password.len &&
2429          a.host.begin == b.host.begin && a.host.len == b.host.len &&
2430          a.port.begin == b.port.begin && a.port.len == b.port.len &&
2431          a.path.begin == b.path.begin && a.path.len == b.path.len &&
2432          a.query.begin == b.query.begin && a.query.len == b.query.len &&
2433          a.ref.begin == b.ref.begin && a.ref.len == b.ref.len;
2434 }
2435
2436 TEST(URLCanonTest, ResolveRelativeURL) {
2437   struct RelativeCase {
2438     const char* base;      // Input base URL: MUST BE CANONICAL
2439     bool is_base_hier;     // Is the base URL hierarchical
2440     bool is_base_file;     // Tells us if the base is a file URL.
2441     const char* test;      // Input URL to test against.
2442     bool succeed_relative; // Whether we expect IsRelativeURL to succeed
2443     bool is_rel;           // Whether we expect |test| to be relative or not.
2444     bool succeed_resolve;  // Whether we expect ResolveRelativeURL to succeed.
2445     const char* resolved;  // What we expect in the result when resolving.
2446   } rel_cases[] = {
2447       // Basic absolute input.
2448       {"http://host/a", true, false, "http://another/", true, false, false,
2449        nullptr},
2450       {"http://host/a", true, false, "http:////another/", true, false, false,
2451        nullptr},
2452       // Empty relative URLs should only remove the ref part of the URL,
2453       // leaving the rest unchanged.
2454       {"http://foo/bar", true, false, "", true, true, true, "http://foo/bar"},
2455       {"http://foo/bar#ref", true, false, "", true, true, true,
2456        "http://foo/bar"},
2457       {"http://foo/bar#", true, false, "", true, true, true, "http://foo/bar"},
2458       // Spaces at the ends of the relative path should be ignored.
2459       {"http://foo/bar", true, false, "  another  ", true, true, true,
2460        "http://foo/another"},
2461       {"http://foo/bar", true, false, "  .  ", true, true, true, "http://foo/"},
2462       {"http://foo/bar", true, false, " \t ", true, true, true,
2463        "http://foo/bar"},
2464       // Matching schemes without two slashes are treated as relative.
2465       {"http://host/a", true, false, "http:path", true, true, true,
2466        "http://host/path"},
2467       {"http://host/a/", true, false, "http:path", true, true, true,
2468        "http://host/a/path"},
2469       {"http://host/a", true, false, "http:/path", true, true, true,
2470        "http://host/path"},
2471       {"http://host/a", true, false, "HTTP:/path", true, true, true,
2472        "http://host/path"},
2473       // Nonmatching schemes are absolute.
2474       {"http://host/a", true, false, "https:host2", true, false, false,
2475        nullptr},
2476       {"http://host/a", true, false, "htto:/host2", true, false, false,
2477        nullptr},
2478       // Absolute path input
2479       {"http://host/a", true, false, "/b/c/d", true, true, true,
2480        "http://host/b/c/d"},
2481       {"http://host/a", true, false, "\\b\\c\\d", true, true, true,
2482        "http://host/b/c/d"},
2483       {"http://host/a", true, false, "/b/../c", true, true, true,
2484        "http://host/c"},
2485       {"http://host/a?b#c", true, false, "/b/../c", true, true, true,
2486        "http://host/c"},
2487       {"http://host/a", true, false, "\\b/../c?x#y", true, true, true,
2488        "http://host/c?x#y"},
2489       {"http://host/a?b#c", true, false, "/b/../c?x#y", true, true, true,
2490        "http://host/c?x#y"},
2491       // Relative path input
2492       {"http://host/a", true, false, "b", true, true, true, "http://host/b"},
2493       {"http://host/a", true, false, "bc/de", true, true, true,
2494        "http://host/bc/de"},
2495       {"http://host/a/", true, false, "bc/de?query#ref", true, true, true,
2496        "http://host/a/bc/de?query#ref"},
2497       {"http://host/a/", true, false, ".", true, true, true, "http://host/a/"},
2498       {"http://host/a/", true, false, "..", true, true, true, "http://host/"},
2499       {"http://host/a/", true, false, "./..", true, true, true, "http://host/"},
2500       {"http://host/a/", true, false, "../.", true, true, true, "http://host/"},
2501       {"http://host/a/", true, false, "././.", true, true, true,
2502        "http://host/a/"},
2503       {"http://host/a?query#ref", true, false, "../../../foo", true, true, true,
2504        "http://host/foo"},
2505       // Query input
2506       {"http://host/a", true, false, "?foo=bar", true, true, true,
2507        "http://host/a?foo=bar"},
2508       {"http://host/a?x=y#z", true, false, "?", true, true, true,
2509        "http://host/a?"},
2510       {"http://host/a?x=y#z", true, false, "?foo=bar#com", true, true, true,
2511        "http://host/a?foo=bar#com"},
2512       // Ref input
2513       {"http://host/a", true, false, "#ref", true, true, true,
2514        "http://host/a#ref"},
2515       {"http://host/a#b", true, false, "#", true, true, true, "http://host/a#"},
2516       {"http://host/a?foo=bar#hello", true, false, "#bye", true, true, true,
2517        "http://host/a?foo=bar#bye"},
2518       // Non-hierarchical base: no relative handling. Relative input should
2519       // error, and if a scheme is present, it should be treated as absolute.
2520       {"data:foobar", false, false, "baz.html", false, false, false, nullptr},
2521       {"data:foobar", false, false, "data:baz", true, false, false, nullptr},
2522       {"data:foobar", false, false, "data:/base", true, false, false, nullptr},
2523       // Non-hierarchical base: absolute input should succeed.
2524       {"data:foobar", false, false, "http://host/", true, false, false,
2525        nullptr},
2526       {"data:foobar", false, false, "http:host", true, false, false, nullptr},
2527       // Non-hierarchical base: empty URL should give error.
2528       {"data:foobar", false, false, "", false, false, false, nullptr},
2529       // Invalid schemes should be treated as relative.
2530       {"http://foo/bar", true, false, "./asd:fgh", true, true, true,
2531        "http://foo/asd:fgh"},
2532       {"http://foo/bar", true, false, ":foo", true, true, true,
2533        "http://foo/:foo"},
2534       {"http://foo/bar", true, false, " hello world", true, true, true,
2535        "http://foo/hello%20world"},
2536       {"data:asdf", false, false, ":foo", false, false, false, nullptr},
2537       {"data:asdf", false, false, "bad(':foo')", false, false, false, nullptr},
2538       // We should treat semicolons like any other character in URL resolving
2539       {"http://host/a", true, false, ";foo", true, true, true,
2540        "http://host/;foo"},
2541       {"http://host/a;", true, false, ";foo", true, true, true,
2542        "http://host/;foo"},
2543       {"http://host/a", true, false, ";/../bar", true, true, true,
2544        "http://host/bar"},
2545       // Relative URLs can also be written as "//foo/bar" which is relative to
2546       // the scheme. In this case, it would take the old scheme, so for http
2547       // the example would resolve to "http://foo/bar".
2548       {"http://host/a", true, false, "//another", true, true, true,
2549        "http://another/"},
2550       {"http://host/a", true, false, "//another/path?query#ref", true, true,
2551        true, "http://another/path?query#ref"},
2552       {"http://host/a", true, false, "///another/path", true, true, true,
2553        "http://another/path"},
2554       {"http://host/a", true, false, "//Another\\path", true, true, true,
2555        "http://another/path"},
2556       {"http://host/a", true, false, "//", true, true, false, "http:"},
2557       // IE will also allow one or the other to be a backslash to get the same
2558       // behavior.
2559       {"http://host/a", true, false, "\\/another/path", true, true, true,
2560        "http://another/path"},
2561       {"http://host/a", true, false, "/\\Another\\path", true, true, true,
2562        "http://another/path"},
2563 #ifdef WIN32
2564       // Resolving against Windows file base URLs.
2565       {"file:///C:/foo", true, true, "http://host/", true, false, false,
2566        nullptr},
2567       {"file:///C:/foo", true, true, "bar", true, true, true, "file:///C:/bar"},
2568       {"file:///C:/foo", true, true, "../../../bar.html", true, true, true,
2569        "file:///C:/bar.html"},
2570       {"file:///C:/foo", true, true, "/../bar.html", true, true, true,
2571        "file:///C:/bar.html"},
2572       // But two backslashes on Windows should be UNC so should be treated
2573       // as absolute.
2574       {"http://host/a", true, false, "\\\\another\\path", true, false, false,
2575        nullptr},
2576       // IE doesn't support drive specs starting with two slashes. It fails
2577       // immediately and doesn't even try to load. We fix it up to either
2578       // an absolute path or UNC depending on what it looks like.
2579       {"file:///C:/something", true, true, "//c:/foo", true, true, true,
2580        "file:///C:/foo"},
2581       {"file:///C:/something", true, true, "//localhost/c:/foo", true, true,
2582        true, "file:///C:/foo"},
2583       // Windows drive specs should be allowed and treated as absolute.
2584       {"file:///C:/foo", true, true, "c:", true, false, false, nullptr},
2585       {"file:///C:/foo", true, true, "c:/foo", true, false, false, nullptr},
2586       {"http://host/a", true, false, "c:\\foo", true, false, false, nullptr},
2587       // Relative paths with drive letters should be allowed when the base is
2588       // also a file.
2589       {"file:///C:/foo", true, true, "/z:/bar", true, true, true,
2590        "file:///Z:/bar"},
2591       // Treat absolute paths as being off of the drive.
2592       {"file:///C:/foo", true, true, "/bar", true, true, true,
2593        "file:///C:/bar"},
2594       {"file://localhost/C:/foo", true, true, "/bar", true, true, true,
2595        "file://localhost/C:/bar"},
2596       {"file:///C:/foo/com/", true, true, "/bar", true, true, true,
2597        "file:///C:/bar"},
2598       // On Windows, two slashes without a drive letter when the base is a file
2599       // means that the path is UNC.
2600       {"file:///C:/something", true, true, "//somehost/path", true, true, true,
2601        "file://somehost/path"},
2602       {"file:///C:/something", true, true, "/\\//somehost/path", true, true,
2603        true, "file://somehost/path"},
2604 #else
2605       // On Unix we fall back to relative behavior since there's nothing else
2606       // reasonable to do.
2607       {"http://host/a", true, false, "\\\\Another\\path", true, true, true,
2608        "http://another/path"},
2609 #endif
2610       // Even on Windows, we don't allow relative drive specs when the base
2611       // is not file.
2612       {"http://host/a", true, false, "/c:\\foo", true, true, true,
2613        "http://host/c:/foo"},
2614       {"http://host/a", true, false, "//c:\\foo", true, true, true,
2615        "http://c/foo"},
2616       // Cross-platform relative file: resolution behavior.
2617       {"file://host/a", true, true, "/", true, true, true, "file://host/"},
2618       {"file://host/a", true, true, "//", true, true, true, "file:///"},
2619       {"file://host/a", true, true, "/b", true, true, true, "file://host/b"},
2620       {"file://host/a", true, true, "//b", true, true, true, "file://b/"},
2621       // Ensure that ports aren't allowed for hosts relative to a file url.
2622       // Although the result string shows a host:port portion, the call to
2623       // resolve the relative URL returns false, indicating parse failure,
2624       // which is what is required.
2625       {"file:///foo.txt", true, true, "//host:80/bar.txt", true, true, false,
2626        "file://host:80/bar.txt"},
2627       // Filesystem URL tests; filesystem URLs are only valid and relative if
2628       // they have no scheme, e.g. "./index.html". There's no valid equivalent
2629       // to http:index.html.
2630       {"filesystem:http://host/t/path", true, false,
2631        "filesystem:http://host/t/path2", true, false, false, nullptr},
2632       {"filesystem:http://host/t/path", true, false,
2633        "filesystem:https://host/t/path2", true, false, false, nullptr},
2634       {"filesystem:http://host/t/path", true, false, "http://host/t/path2",
2635        true, false, false, nullptr},
2636       {"http://host/t/path", true, false, "filesystem:http://host/t/path2",
2637        true, false, false, nullptr},
2638       {"filesystem:http://host/t/path", true, false, "./path2", true, true,
2639        true, "filesystem:http://host/t/path2"},
2640       {"filesystem:http://host/t/path/", true, false, "path2", true, true, true,
2641        "filesystem:http://host/t/path/path2"},
2642       {"filesystem:http://host/t/path", true, false, "filesystem:http:path2",
2643        true, false, false, nullptr},
2644       // Absolute URLs are still not relative to a non-standard base URL.
2645       {"about:blank", false, false, "http://X/A", true, false, true, ""},
2646       {"about:blank", false, false, "content://content.Provider/", true, false,
2647        true, ""},
2648   };
2649
2650   for (const auto& cur_case : rel_cases) {
2651     Parsed parsed;
2652     int base_len = static_cast<int>(strlen(cur_case.base));
2653     if (cur_case.is_base_file)
2654       ParseFileURL(cur_case.base, base_len, &parsed);
2655     else if (cur_case.is_base_hier)
2656       ParseStandardURL(cur_case.base, base_len, &parsed);
2657     else
2658       ParsePathURL(cur_case.base, base_len, false, &parsed);
2659
2660     // First see if it is relative.
2661     int test_len = static_cast<int>(strlen(cur_case.test));
2662     bool is_relative;
2663     Component relative_component;
2664     bool succeed_is_rel = IsRelativeURL(
2665         cur_case.base, parsed, cur_case.test, test_len, cur_case.is_base_hier,
2666         &is_relative, &relative_component);
2667
2668     EXPECT_EQ(cur_case.succeed_relative, succeed_is_rel) <<
2669         "succeed is rel failure on " << cur_case.test;
2670     EXPECT_EQ(cur_case.is_rel, is_relative) <<
2671         "is rel failure on " << cur_case.test;
2672     // Now resolve it.
2673     if (succeed_is_rel && is_relative && cur_case.is_rel) {
2674       std::string resolved;
2675       StdStringCanonOutput output(&resolved);
2676       Parsed resolved_parsed;
2677
2678       bool succeed_resolve = ResolveRelativeURL(
2679           cur_case.base, parsed, cur_case.is_base_file, cur_case.test,
2680           relative_component, nullptr, &output, &resolved_parsed);
2681       output.Complete();
2682
2683       EXPECT_EQ(cur_case.succeed_resolve, succeed_resolve);
2684       EXPECT_EQ(cur_case.resolved, resolved) << " on " << cur_case.test;
2685
2686       // Verify that the output parsed structure is the same as parsing a
2687       // the URL freshly.
2688       Parsed ref_parsed;
2689       int resolved_len = static_cast<int>(resolved.size());
2690       if (cur_case.is_base_file) {
2691         ParseFileURL(resolved.c_str(), resolved_len, &ref_parsed);
2692       } else if (cur_case.is_base_hier) {
2693         ParseStandardURL(resolved.c_str(), resolved_len, &ref_parsed);
2694       } else {
2695         ParsePathURL(resolved.c_str(), resolved_len, false, &ref_parsed);
2696       }
2697       EXPECT_TRUE(ParsedIsEqual(ref_parsed, resolved_parsed));
2698     }
2699   }
2700 }
2701
2702 // It used to be the case that when we did a replacement with a long buffer of
2703 // UTF-16 characters, we would get invalid data in the URL. This is because the
2704 // buffer that it used to hold the UTF-8 data was resized, while some pointers
2705 // were still kept to the old buffer that was removed.
2706 TEST(URLCanonTest, ReplacementOverflow) {
2707   const char src[] = "file:///C:/foo/bar";
2708   int src_len = static_cast<int>(strlen(src));
2709   Parsed parsed;
2710   ParseFileURL(src, src_len, &parsed);
2711
2712   // Override two components, the path with something short, and the query with
2713   // something long enough to trigger the bug.
2714   Replacements<char16_t> repl;
2715   std::u16string new_query;
2716   for (int i = 0; i < 4800; i++)
2717     new_query.push_back('a');
2718
2719   std::u16string new_path(test_utils::TruncateWStringToUTF16(L"/foo"));
2720   repl.SetPath(new_path.c_str(), Component(0, 4));
2721   repl.SetQuery(new_query.c_str(),
2722                 Component(0, static_cast<int>(new_query.length())));
2723
2724   // Call ReplaceComponents on the string. It doesn't matter if we call it for
2725   // standard URLs, file URLs, etc, since they will go to the same replacement
2726   // function that was buggy.
2727   Parsed repl_parsed;
2728   std::string repl_str;
2729   StdStringCanonOutput repl_output(&repl_str);
2730   ReplaceFileURL(src, parsed, repl, nullptr, &repl_output, &repl_parsed);
2731   repl_output.Complete();
2732
2733   // Generate the expected string and check.
2734   std::string expected("file:///foo?");
2735   for (size_t i = 0; i < new_query.length(); i++)
2736     expected.push_back('a');
2737   EXPECT_TRUE(expected == repl_str);
2738 }
2739
2740 TEST(URLCanonTest, DefaultPortForScheme) {
2741   struct TestCases {
2742     const char* scheme;
2743     const int expected_port;
2744   } cases[]{
2745       {"http", 80},
2746       {"https", 443},
2747       {"ftp", 21},
2748       {"ws", 80},
2749       {"wss", 443},
2750       {"fake-scheme", PORT_UNSPECIFIED},
2751       {"HTTP", PORT_UNSPECIFIED},
2752       {"HTTPS", PORT_UNSPECIFIED},
2753       {"FTP", PORT_UNSPECIFIED},
2754       {"WS", PORT_UNSPECIFIED},
2755       {"WSS", PORT_UNSPECIFIED},
2756   };
2757
2758   for (const auto& test_case : cases) {
2759     SCOPED_TRACE(test_case.scheme);
2760     EXPECT_EQ(test_case.expected_port,
2761               DefaultPortForScheme(test_case.scheme, strlen(test_case.scheme)));
2762   }
2763 }
2764
2765 TEST(URLCanonTest, FindWindowsDriveLetter) {
2766   struct TestCase {
2767     std::string_view spec;
2768     int begin;
2769     int end;  // -1 for end of spec
2770     int expected_drive_letter_pos;
2771   } cases[] = {
2772       {"/", 0, -1, -1},
2773
2774       {"c:/foo", 0, -1, 0},
2775       {"/c:/foo", 0, -1, 1},
2776       {"//c:/foo", 0, -1, -1},  // "//" does not canonicalize to "/"
2777       {"\\C|\\foo", 0, -1, 1},
2778       {"/cd:/foo", 0, -1, -1},  // "/c" does not canonicalize to "/"
2779       {"/./c:/foo", 0, -1, 3},
2780       {"/.//c:/foo", 0, -1, -1},  // "/.//" does not canonicalize to "/"
2781       {"/././c:/foo", 0, -1, 5},
2782       {"/abc/c:/foo", 0, -1, -1},  // "/abc/" does not canonicalize to "/"
2783       {"/abc/./../c:/foo", 0, -1, 10},
2784
2785       {"/c:/c:/foo", 3, -1, 4},  // actual input is "/c:/foo"
2786       {"/c:/foo", 3, -1, -1},    // actual input is "/foo"
2787       {"/c:/foo", 0, 1, -1},     // actual input is "/"
2788   };
2789
2790   for (const auto& c : cases) {
2791     int end = c.end;
2792     if (end == -1)
2793       end = c.spec.size();
2794
2795     EXPECT_EQ(c.expected_drive_letter_pos,
2796               FindWindowsDriveLetter(c.spec.data(), c.begin, end))
2797         << "for " << c.spec << "[" << c.begin << ":" << end << "] (UTF-8)";
2798
2799     std::u16string spec16 = base::ASCIIToUTF16(c.spec);
2800     EXPECT_EQ(c.expected_drive_letter_pos,
2801               FindWindowsDriveLetter(spec16.data(), c.begin, end))
2802         << "for " << c.spec << "[" << c.begin << ":" << end << "] (UTF-16)";
2803   }
2804 }
2805
2806 TEST(URLCanonTest, IDNToASCII) {
2807   RawCanonOutputW<1024> output;
2808
2809   // Basic ASCII test.
2810   std::u16string str = u"hello";
2811   EXPECT_TRUE(IDNToASCII(str, &output));
2812   EXPECT_EQ(u"hello", std::u16string(output.data()));
2813   output.set_length(0);
2814
2815   // Mixed ASCII/non-ASCII.
2816   str = u"hellö";
2817   EXPECT_TRUE(IDNToASCII(str, &output));
2818   EXPECT_EQ(u"xn--hell-8qa", std::u16string(output.data()));
2819   output.set_length(0);
2820
2821   // All non-ASCII.
2822   str = u"你好";
2823   EXPECT_TRUE(IDNToASCII(str, &output));
2824   EXPECT_EQ(u"xn--6qq79v", std::u16string(output.data()));
2825   output.set_length(0);
2826
2827   // Characters that need mapping (the resulting Punycode is the encoding for
2828   // "1⁄4").
2829   str = u"¼";
2830   EXPECT_TRUE(IDNToASCII(str, &output));
2831   EXPECT_EQ(u"xn--14-c6t", std::u16string(output.data()));
2832   output.set_length(0);
2833
2834   // String to encode already starts with "xn--", and all ASCII. Should not
2835   // modify the string.
2836   str = u"xn--hell-8qa";
2837   EXPECT_TRUE(IDNToASCII(str, &output));
2838   EXPECT_EQ(u"xn--hell-8qa", std::u16string(output.data()));
2839   output.set_length(0);
2840
2841   // String to encode already starts with "xn--", and mixed ASCII/non-ASCII.
2842   // Should fail, due to a special case: if the label starts with "xn--", it
2843   // should be parsed as Punycode, which must be all ASCII.
2844   str = u"xn--hellö";
2845   EXPECT_FALSE(IDNToASCII(str, &output));
2846   output.set_length(0);
2847
2848   // String to encode already starts with "xn--", and mixed ASCII/non-ASCII.
2849   // This tests that there is still an error for the character '⁄' (U+2044),
2850   // which would be a valid ASCII character, U+0044, if the high byte were
2851   // ignored.
2852   str = u"xn--1⁄4";
2853   EXPECT_FALSE(IDNToASCII(str, &output));
2854   output.set_length(0);
2855 }
2856
2857 }  // namespace url