url_canon_host.cc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/check.h"
  5. #include "base/cpu_reduction_experiment.h"
  6. #include "url/url_canon.h"
  7. #include "url/url_canon_internal.h"
  8. namespace url {
  9. namespace {
  10. // For reference, here's what IE supports:
  11. // Key: 0 (disallowed: failure if present in the input)
  12. // + (allowed either escaped or unescaped, and unmodified)
  13. // U (allowed escaped or unescaped but always unescaped if present in
  14. // escaped form)
  15. // E (allowed escaped or unescaped but always escaped if present in
  16. // unescaped form)
  17. // % (only allowed escaped in the input, will be unmodified).
  18. // I left blank alpha numeric characters.
  19. //
  20. // 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
  21. // -----------------------------------------------
  22. // 0 0 E E E E E E E E E E E E E E E
  23. // 1 E E E E E E E E E E E E E E E E
  24. // 2 E + E E + E + + + + + + + U U 0
  25. // 3 % % E + E 0 <-- Those are : ; < = > ?
  26. // 4 %
  27. // 5 U 0 U U U <-- Those are [ \ ] ^ _
  28. // 6 E <-- That's `
  29. // 7 E E E U E <-- Those are { | } ~ (UNPRINTABLE)
  30. //
  31. // NOTE: I didn't actually test all the control characters. Some may be
  32. // disallowed in the input, but they are all accepted escaped except for 0.
  33. // I also didn't test if characters affecting HTML parsing are allowed
  34. // unescaped, e.g. (") or (#), which would indicate the beginning of the path.
  35. // Surprisingly, space is accepted in the input and always escaped.
  36. // This table lists the canonical version of all characters we allow in the
  37. // input, with 0 indicating it is disallowed. We use the magic kEscapedHostChar
  38. // value to indicate that this character should be escaped. We are a little more
  39. // restrictive than IE, but less restrictive than Firefox.
  40. //
  41. // Note that we disallow the % character. We will allow it when part of an
  42. // escape sequence, of course, but this disallows "%25". Even though IE allows
  43. // it, allowing it would put us in a funny state. If there was an invalid
  44. // escape sequence like "%zz", we'll add "%25zz" to the output and fail.
  45. // Allowing percents means we'll succeed a second time, so validity would change
  46. // based on how many times you run the canonicalizer. We prefer to always report
  47. // the same vailidity, so reject this.
  48. const unsigned char kEsc = 0xff;
  49. const unsigned char kHostCharLookup[0x80] = {
  50. // 00-1f: all are invalid
  51. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  52. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  53. // ' ' ! " # $ % & ' ( ) * + , - . /
  54. kEsc,kEsc,kEsc,kEsc,kEsc, 0, kEsc,kEsc,kEsc,kEsc,kEsc, '+',kEsc, '-', '.', 0,
  55. // 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
  56. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', 0 ,kEsc,kEsc,kEsc, 0 ,
  57. // @ A B C D E F G H I J K L M N O
  58. kEsc, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  59. // P Q R S T U V W X Y Z [ \ ] ^ _
  60. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '[', 0 , ']', 0 , '_',
  61. // ` a b c d e f g h i j k l m n o
  62. kEsc, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  63. // p q r s t u v w x y z { | } ~
  64. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',kEsc,kEsc,kEsc, 0 , 0 };
  65. // RFC1034 maximum FQDN length.
  66. constexpr size_t kMaxHostLength = 253;
  67. // Generous padding to account for the fact that UTS#46 normalization can cause
  68. // a long string to actually shrink and fit within the 253 character RFC1034
  69. // FQDN length limit. Note that this can still be too short for pathological
  70. // cases: An arbitrary number of characters (e.g. U+00AD SOFT HYPHEN) can be
  71. // removed from the input by UTS#46 processing. However, this should be
  72. // sufficient for all normally-encountered, non-abusive hostname strings.
  73. constexpr size_t kMaxHostBufferLength = kMaxHostLength * 5;
  74. constexpr size_t kTempHostBufferLen = 1024;
  75. using StackBuffer = RawCanonOutputT<char, kTempHostBufferLen>;
  76. using StackBufferW = RawCanonOutputT<char16_t, kTempHostBufferLen>;
  77. // Scans a host name and fills in the output flags according to what we find.
  78. // |has_non_ascii| will be true if there are any non-7-bit characters, and
  79. // |has_escaped| will be true if there is a percent sign.
  80. template<typename CHAR, typename UCHAR>
  81. void ScanHostname(const CHAR* spec,
  82. const Component& host,
  83. bool* has_non_ascii,
  84. bool* has_escaped) {
  85. int end = host.end();
  86. *has_non_ascii = false;
  87. *has_escaped = false;
  88. for (int i = host.begin; i < end; i++) {
  89. if (static_cast<UCHAR>(spec[i]) >= 0x80)
  90. *has_non_ascii = true;
  91. else if (spec[i] == '%')
  92. *has_escaped = true;
  93. }
  94. }
  95. // Canonicalizes a host name that is entirely 8-bit characters (even though
  96. // the type holding them may be 16 bits. Escaped characters will be unescaped.
  97. // Non-7-bit characters (for example, UTF-8) will be passed unchanged.
  98. //
  99. // The |*has_non_ascii| flag will be true if there are non-7-bit characters in
  100. // the output.
  101. //
  102. // This function is used in two situations:
  103. //
  104. // * When the caller knows there is no non-ASCII or percent escaped
  105. // characters. This is what DoHost does. The result will be a completely
  106. // canonicalized host since we know nothing weird can happen (escaped
  107. // characters could be unescaped to non-7-bit, so they have to be treated
  108. // with suspicion at this point). It does not use the |has_non_ascii| flag.
  109. //
  110. // * When the caller has an 8-bit string that may need unescaping.
  111. // DoComplexHost calls us this situation to do unescaping and validation.
  112. // After this, it may do other IDN operations depending on the value of the
  113. // |*has_non_ascii| flag.
  114. //
  115. // The return value indicates if the output is a potentially valid host name.
  116. template <typename INCHAR, typename OUTCHAR>
  117. bool DoSimpleHost(const INCHAR* host,
  118. size_t host_len,
  119. CanonOutputT<OUTCHAR>* output,
  120. bool* has_non_ascii) {
  121. *has_non_ascii = false;
  122. bool success = true;
  123. for (size_t i = 0; i < host_len; ++i) {
  124. unsigned int source = host[i];
  125. if (source == '%') {
  126. // Unescape first, if possible.
  127. // Source will be used only if decode operation was successful.
  128. if (!DecodeEscaped(host, &i, host_len,
  129. reinterpret_cast<unsigned char*>(&source))) {
  130. // Invalid escaped character. There is nothing that can make this
  131. // host valid. We append an escaped percent so the URL looks reasonable
  132. // and mark as failed.
  133. AppendEscapedChar('%', output);
  134. success = false;
  135. continue;
  136. }
  137. }
  138. if (source < 0x80) {
  139. // We have ASCII input, we can use our lookup table.
  140. unsigned char replacement = kHostCharLookup[source];
  141. if (!replacement) {
  142. // Invalid character, add it as percent-escaped and mark as failed.
  143. AppendEscapedChar(source, output);
  144. success = false;
  145. } else if (replacement == kEsc) {
  146. // This character is valid but should be escaped.
  147. AppendEscapedChar(source, output);
  148. } else {
  149. // Common case, the given character is valid in a hostname, the lookup
  150. // table tells us the canonical representation of that character (lower
  151. // cased).
  152. output->push_back(replacement);
  153. }
  154. } else {
  155. // It's a non-ascii char. Just push it to the output.
  156. // In case where we have char16 input, and char output it's safe to
  157. // cast char16->char only if input string was converted to ASCII.
  158. output->push_back(static_cast<OUTCHAR>(source));
  159. *has_non_ascii = true;
  160. }
  161. }
  162. return success;
  163. }
  164. // Canonicalizes a host that requires IDN conversion. Returns true on success
  165. bool DoIDNHost(const char16_t* src, size_t src_len, CanonOutput* output) {
  166. int original_output_len = output->length(); // So we can rewind below.
  167. // We need to escape URL before doing IDN conversion, since punicode strings
  168. // cannot be escaped after they are created.
  169. RawCanonOutputW<kTempHostBufferLen> url_escaped_host;
  170. bool has_non_ascii;
  171. DoSimpleHost(src, src_len, &url_escaped_host, &has_non_ascii);
  172. if (url_escaped_host.length() > kMaxHostBufferLength) {
  173. AppendInvalidNarrowString(src, 0, src_len, output);
  174. return false;
  175. }
  176. StackBufferW wide_output;
  177. if (!IDNToASCII(url_escaped_host.data(),
  178. url_escaped_host.length(),
  179. &wide_output)) {
  180. // Some error, give up. This will write some reasonable looking
  181. // representation of the string to the output.
  182. AppendInvalidNarrowString(src, 0, src_len, output);
  183. return false;
  184. }
  185. // Now we check the ASCII output like a normal host. It will also handle
  186. // unescaping. Although we unescaped everything before this function call, if
  187. // somebody does %00 as fullwidth, ICU will convert this to ASCII.
  188. bool success = DoSimpleHost(wide_output.data(), wide_output.length(), output,
  189. &has_non_ascii);
  190. if (has_non_ascii) {
  191. // ICU generated something that DoSimpleHost didn't think looked like
  192. // ASCII. This is quite rare, but ICU might convert some characters to
  193. // percent signs which might generate new escape sequences which might in
  194. // turn be invalid. An example is U+FE6A "small percent" which ICU will
  195. // name prep into an ASCII percent and then we can interpret the following
  196. // characters as escaped characters.
  197. //
  198. // If DoSimpleHost didn't think the output was ASCII, just escape the
  199. // thing we gave ICU and give up. DoSimpleHost will have handled a further
  200. // level of escaping from ICU for simple ASCII cases (i.e. if ICU generates
  201. // a new escaped ASCII sequence like "%41" we'll unescape it) but it won't
  202. // do more (like handle escaped non-ASCII sequences). Handling the escaped
  203. // ASCII isn't strictly necessary, but DoSimpleHost handles this case
  204. // anyway so we handle it/
  205. output->set_length(original_output_len);
  206. AppendInvalidNarrowString(wide_output.data(), 0, wide_output.length(),
  207. output);
  208. return false;
  209. }
  210. return success;
  211. }
  212. // 8-bit convert host to its ASCII version: this converts the UTF-8 input to
  213. // UTF-16. The has_escaped flag should be set if the input string requires
  214. // unescaping.
  215. bool DoComplexHost(const char* host,
  216. size_t host_len,
  217. bool has_non_ascii,
  218. bool has_escaped,
  219. CanonOutput* output) {
  220. // Save the current position in the output. We may write stuff and rewind it
  221. // below, so we need to know where to rewind to.
  222. size_t begin_length = output->length();
  223. // Points to the UTF-8 data we want to convert. This will either be the
  224. // input or the unescaped version written to |*output| if necessary.
  225. const char* utf8_source;
  226. size_t utf8_source_len;
  227. bool are_all_escaped_valid = true;
  228. if (has_escaped) {
  229. // Unescape before converting to UTF-16 for IDN. We write this into the
  230. // output because it most likely does not require IDNization, and we can
  231. // save another huge stack buffer. It will be replaced below if it requires
  232. // IDN. This will also update our non-ASCII flag so we know whether the
  233. // unescaped input requires IDN.
  234. if (!DoSimpleHost(host, host_len, output, &has_non_ascii)) {
  235. // Error with some escape sequence. We'll call the current output
  236. // complete. DoSimpleHost will have written some "reasonable" output
  237. // for the invalid escapes, but the output could be non-ASCII and
  238. // needs to go through re-encoding below.
  239. are_all_escaped_valid = false;
  240. }
  241. // Unescaping may have left us with ASCII input, in which case the
  242. // unescaped version we wrote to output is complete.
  243. if (!has_non_ascii) {
  244. return are_all_escaped_valid;
  245. }
  246. // Save the pointer into the data was just converted (it may be appended to
  247. // other data in the output buffer).
  248. utf8_source = &output->data()[begin_length];
  249. utf8_source_len = output->length() - begin_length;
  250. } else {
  251. // We don't need to unescape, use input for IDNization later. (We know the
  252. // input has non-ASCII, or the simple version would have been called
  253. // instead of us.)
  254. utf8_source = host;
  255. utf8_source_len = host_len;
  256. }
  257. // Non-ASCII input requires IDN, convert to UTF-16 and do the IDN conversion.
  258. // Above, we may have used the output to write the unescaped values to, so
  259. // we have to rewind it to where we started after we convert it to UTF-16.
  260. StackBufferW utf16;
  261. if (!ConvertUTF8ToUTF16(utf8_source, utf8_source_len, &utf16)) {
  262. // In this error case, the input may or may not be the output.
  263. StackBuffer utf8;
  264. for (size_t i = 0; i < utf8_source_len; i++)
  265. utf8.push_back(utf8_source[i]);
  266. output->set_length(begin_length);
  267. AppendInvalidNarrowString(utf8.data(), 0, utf8.length(), output);
  268. return false;
  269. }
  270. output->set_length(begin_length);
  271. // This will call DoSimpleHost which will do normal ASCII canonicalization
  272. // and also check for IP addresses in the outpt.
  273. return DoIDNHost(utf16.data(), utf16.length(), output) &&
  274. are_all_escaped_valid;
  275. }
  276. // UTF-16 convert host to its ASCII version. The set up is already ready for
  277. // the backend, so we just pass through. The has_escaped flag should be set if
  278. // the input string requires unescaping.
  279. bool DoComplexHost(const char16_t* host,
  280. size_t host_len,
  281. bool has_non_ascii,
  282. bool has_escaped,
  283. CanonOutput* output) {
  284. if (has_escaped) {
  285. // Yikes, we have escaped characters with wide input. The escaped
  286. // characters should be interpreted as UTF-8. To solve this problem,
  287. // we convert to UTF-8, unescape, then convert back to UTF-16 for IDN.
  288. //
  289. // We don't bother to optimize the conversion in the ASCII case (which
  290. // *could* just be a copy) and use the UTF-8 path, because it should be
  291. // very rare that host names have escaped characters, and it is relatively
  292. // fast to do the conversion anyway.
  293. StackBuffer utf8;
  294. if (!ConvertUTF16ToUTF8(host, host_len, &utf8)) {
  295. AppendInvalidNarrowString(host, 0, host_len, output);
  296. return false;
  297. }
  298. // Once we convert to UTF-8, we can use the 8-bit version of the complex
  299. // host handling code above.
  300. return DoComplexHost(utf8.data(), utf8.length(), has_non_ascii, has_escaped,
  301. output);
  302. }
  303. // No unescaping necessary, we can safely pass the input to ICU. This
  304. // function will only get called if we either have escaped or non-ascii
  305. // input, so it's safe to just use ICU now. Even if the input is ASCII,
  306. // this function will do the right thing (just slower than we could).
  307. return DoIDNHost(host, host_len, output);
  308. }
  309. template <typename CHAR, typename UCHAR>
  310. bool DoHostSubstring(const CHAR* spec,
  311. const Component& host,
  312. CanonOutput* output) {
  313. DCHECK(host.is_valid());
  314. bool has_non_ascii, has_escaped;
  315. ScanHostname<CHAR, UCHAR>(spec, host, &has_non_ascii, &has_escaped);
  316. if (has_non_ascii || has_escaped) {
  317. return DoComplexHost(&spec[host.begin], static_cast<size_t>(host.len),
  318. has_non_ascii, has_escaped, output);
  319. }
  320. const bool success = DoSimpleHost(
  321. &spec[host.begin], static_cast<size_t>(host.len), output, &has_non_ascii);
  322. DCHECK(!has_non_ascii);
  323. return success;
  324. }
  325. template <typename CHAR, typename UCHAR>
  326. void DoHost(const CHAR* spec,
  327. const Component& host,
  328. CanonOutput* output,
  329. CanonHostInfo* host_info) {
  330. if (!host.is_nonempty()) {
  331. // Empty hosts don't need anything.
  332. host_info->family = CanonHostInfo::NEUTRAL;
  333. host_info->out_host = Component();
  334. return;
  335. }
  336. // Keep track of output's initial length, so we can rewind later.
  337. const int output_begin = output->length();
  338. if (DoHostSubstring<CHAR, UCHAR>(spec, host, output)) {
  339. // After all the other canonicalization, check if we ended up with an IP
  340. // address. IP addresses are small, so writing into this temporary buffer
  341. // should not cause an allocation.
  342. RawCanonOutput<64> canon_ip;
  343. CanonicalizeIPAddress(output->data(),
  344. MakeRange(output_begin, output->length()),
  345. &canon_ip, host_info);
  346. // If we got an IPv4/IPv6 address, copy the canonical form back to the
  347. // real buffer. Otherwise, it's a hostname or broken IP, in which case
  348. // we just leave it in place.
  349. if (host_info->IsIPAddress()) {
  350. output->set_length(output_begin);
  351. output->Append(canon_ip.data(), canon_ip.length());
  352. }
  353. } else {
  354. // Canonicalization failed. Set BROKEN to notify the caller.
  355. host_info->family = CanonHostInfo::BROKEN;
  356. }
  357. host_info->out_host = MakeRange(output_begin, output->length());
  358. }
  359. } // namespace
  360. bool CanonicalizeHost(const char* spec,
  361. const Component& host,
  362. CanonOutput* output,
  363. Component* out_host) {
  364. CanonHostInfo host_info;
  365. DoHost<char, unsigned char>(spec, host, output, &host_info);
  366. *out_host = host_info.out_host;
  367. return (host_info.family != CanonHostInfo::BROKEN);
  368. }
  369. bool CanonicalizeHost(const char16_t* spec,
  370. const Component& host,
  371. CanonOutput* output,
  372. Component* out_host) {
  373. CanonHostInfo host_info;
  374. DoHost<char16_t, char16_t>(spec, host, output, &host_info);
  375. *out_host = host_info.out_host;
  376. return (host_info.family != CanonHostInfo::BROKEN);
  377. }
  378. void CanonicalizeHostVerbose(const char* spec,
  379. const Component& host,
  380. CanonOutput* output,
  381. CanonHostInfo* host_info) {
  382. DoHost<char, unsigned char>(spec, host, output, host_info);
  383. }
  384. void CanonicalizeHostVerbose(const char16_t* spec,
  385. const Component& host,
  386. CanonOutput* output,
  387. CanonHostInfo* host_info) {
  388. DoHost<char16_t, char16_t>(spec, host, output, host_info);
  389. }
  390. bool CanonicalizeHostSubstring(const char* spec,
  391. const Component& host,
  392. CanonOutput* output) {
  393. return DoHostSubstring<char, unsigned char>(spec, host, output);
  394. }
  395. bool CanonicalizeHostSubstring(const char16_t* spec,
  396. const Component& host,
  397. CanonOutput* output) {
  398. return DoHostSubstring<char16_t, char16_t>(spec, host, output);
  399. }
  400. } // namespace url