escape.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. // Copyright (c) 2020 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/strings/escape.h"
  5. #include <ostream>
  6. #include "base/check_op.h"
  7. #include "base/feature_list.h"
  8. #include "base/features.h"
  9. #include "base/strings/string_piece.h"
  10. #include "base/strings/string_util.h"
  11. #include "base/strings/utf_string_conversion_utils.h"
  12. #include "base/strings/utf_string_conversions.h"
  13. #include "base/third_party/icu/icu_utf.h"
  14. namespace base {
  15. namespace {
  16. const char kHexString[] = "0123456789ABCDEF";
  17. inline char IntToHex(int i) {
  18. DCHECK_GE(i, 0) << i << " not a hex value";
  19. DCHECK_LE(i, 15) << i << " not a hex value";
  20. return kHexString[i];
  21. }
  22. // A fast bit-vector map for ascii characters.
  23. //
  24. // Internally stores 256 bits in an array of 8 ints.
  25. // Does quick bit-flicking to lookup needed characters.
  26. struct Charmap {
  27. bool Contains(unsigned char c) const {
  28. return ((map[c >> 5] & (1 << (c & 31))) != 0);
  29. }
  30. uint32_t map[8];
  31. };
  32. // Given text to escape and a Charmap defining which values to escape,
  33. // return an escaped string. If use_plus is true, spaces are converted
  34. // to +, otherwise, if spaces are in the charmap, they are converted to
  35. // %20. And if keep_escaped is true, %XX will be kept as it is, otherwise, if
  36. // '%' is in the charmap, it is converted to %25.
  37. std::string Escape(StringPiece text,
  38. const Charmap& charmap,
  39. bool use_plus,
  40. bool keep_escaped = false) {
  41. std::string escaped;
  42. escaped.reserve(text.length() * 3);
  43. for (unsigned int i = 0; i < text.length(); ++i) {
  44. unsigned char c = static_cast<unsigned char>(text[i]);
  45. if (use_plus && ' ' == c) {
  46. escaped.push_back('+');
  47. } else if (keep_escaped && '%' == c && i + 2 < text.length() &&
  48. IsHexDigit(text[i + 1]) && IsHexDigit(text[i + 2])) {
  49. escaped.push_back('%');
  50. } else if (charmap.Contains(c)) {
  51. escaped.push_back('%');
  52. escaped.push_back(IntToHex(c >> 4));
  53. escaped.push_back(IntToHex(c & 0xf));
  54. } else {
  55. escaped.push_back(static_cast<char>(c));
  56. }
  57. }
  58. return escaped;
  59. }
  60. // Convert a character |c| to a form that will not be mistaken as HTML.
  61. template <class str>
  62. void AppendEscapedCharForHTMLImpl(typename str::value_type c, str* output) {
  63. static constexpr struct {
  64. char key;
  65. StringPiece replacement;
  66. } kCharsToEscape[] = {
  67. {'<', "&lt;"}, {'>', "&gt;"}, {'&', "&amp;"},
  68. {'"', "&quot;"}, {'\'', "&#39;"},
  69. };
  70. for (const auto& char_to_escape : kCharsToEscape) {
  71. if (c == char_to_escape.key) {
  72. output->append(std::begin(char_to_escape.replacement),
  73. std::end(char_to_escape.replacement));
  74. return;
  75. }
  76. }
  77. output->push_back(c);
  78. }
  79. // Convert |input| string to a form that will not be interpreted as HTML.
  80. template <typename T, typename CharT = typename T::value_type>
  81. std::basic_string<CharT> EscapeForHTMLImpl(T input) {
  82. std::basic_string<CharT> result;
  83. result.reserve(input.size()); // Optimize for no escaping.
  84. for (auto c : input) {
  85. AppendEscapedCharForHTMLImpl(c, &result);
  86. }
  87. return result;
  88. }
  89. // Everything except alphanumerics and -._~
  90. // See RFC 3986 for the list of unreserved characters.
  91. static const Charmap kUnreservedCharmap = {
  92. {0xffffffffL, 0xfc009fffL, 0x78000001L, 0xb8000001L, 0xffffffffL,
  93. 0xffffffffL, 0xffffffffL, 0xffffffffL}};
  94. // Everything except alphanumerics and !'()*-._~
  95. // See RFC 2396 for the list of reserved characters.
  96. static const Charmap kQueryCharmap = {{0xffffffffL, 0xfc00987dL, 0x78000001L,
  97. 0xb8000001L, 0xffffffffL, 0xffffffffL,
  98. 0xffffffffL, 0xffffffffL}};
  99. // non-printable, non-7bit, and (including space) "#%:<>?[\]^`{|}
  100. static const Charmap kPathCharmap = {{0xffffffffL, 0xd400002dL, 0x78000000L,
  101. 0xb8000001L, 0xffffffffL, 0xffffffffL,
  102. 0xffffffffL, 0xffffffffL}};
  103. #if BUILDFLAG(IS_APPLE)
  104. // non-printable, non-7bit, and (including space) "#%<>[\]^`{|}
  105. static const Charmap kNSURLCharmap = {{0xffffffffL, 0x5000002dL, 0x78000000L,
  106. 0xb8000001L, 0xffffffffL, 0xffffffffL,
  107. 0xffffffffL, 0xffffffffL}};
  108. #endif // BUILDFLAG(IS_APPLE)
  109. // non-printable, non-7bit, and (including space) ?>=<;+'&%$#"![\]^`{|}
  110. static const Charmap kUrlEscape = {{0xffffffffL, 0xf80008fdL, 0x78000001L,
  111. 0xb8000001L, 0xffffffffL, 0xffffffffL,
  112. 0xffffffffL, 0xffffffffL}};
  113. // non-7bit, as well as %.
  114. static const Charmap kNonASCIICharmapAndPercent = {
  115. {0x00000000L, 0x00000020L, 0x00000000L, 0x00000000L, 0xffffffffL,
  116. 0xffffffffL, 0xffffffffL, 0xffffffffL}};
  117. // non-7bit
  118. static const Charmap kNonASCIICharmap = {{0x00000000L, 0x00000000L, 0x00000000L,
  119. 0x00000000L, 0xffffffffL, 0xffffffffL,
  120. 0xffffffffL, 0xffffffffL}};
  121. // Everything except alphanumerics, the reserved characters(;/?:@&=+$,) and
  122. // !'()*-._~#[]
  123. static const Charmap kExternalHandlerCharmap = {
  124. {0xffffffffL, 0x50000025L, 0x50000000L, 0xb8000001L, 0xffffffffL,
  125. 0xffffffffL, 0xffffffffL, 0xffffffffL}};
  126. // Contains nonzero when the corresponding character is unescapable for normal
  127. // URLs. These characters are the ones that may change the parsing of a URL, so
  128. // we don't want to unescape them sometimes. In many case we won't want to
  129. // unescape spaces, but that is controlled by parameters to Unescape*.
  130. //
  131. // The basic rule is that we can't unescape anything that would changing parsing
  132. // like # or ?. We also can't unescape &, =, or + since that could be part of a
  133. // query and that could change the server's parsing of the query. Nor can we
  134. // unescape \ since src/url/ will convert it to a /.
  135. //
  136. // Lastly, we can't unescape anything that doesn't have a canonical
  137. // representation in a URL. This means that unescaping will change the URL, and
  138. // you could get different behavior if you copy and paste the URL, or press
  139. // enter in the URL bar. The list of characters that fall into this category
  140. // are the ones labeled PASS (allow either escaped or unescaped) in the big
  141. // lookup table at the top of url/url_canon_path.cc. Also, characters
  142. // that have CHAR_QUERY set in url/url_canon_internal.cc but are not
  143. // allowed in query strings according to http://www.ietf.org/rfc/rfc3261.txt are
  144. // not unescaped, to avoid turning a valid url according to spec into an
  145. // invalid one.
  146. // clang-format off
  147. const char kUrlUnescape[128] = {
  148. // Null, control chars...
  149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  151. // ' ' ! " # $ % & ' ( ) * + , - . /
  152. 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
  153. // 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
  154. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,
  155. // @ A B C D E F G H I J K L M N O
  156. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  157. // P Q R S T U V W X Y Z [ \ ] ^ _
  158. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
  159. // ` a b c d e f g h i j k l m n o
  160. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  161. // p q r s t u v w x y z { | } ~ <NBSP>
  162. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0,
  163. };
  164. // clang-format on
  165. // Attempts to unescape the sequence at |index| within |escaped_text|. If
  166. // successful, sets |value| to the unescaped value. Returns whether
  167. // unescaping succeeded.
  168. bool UnescapeUnsignedByteAtIndex(StringPiece escaped_text,
  169. size_t index,
  170. unsigned char* value) {
  171. if ((index + 2) >= escaped_text.size())
  172. return false;
  173. if (escaped_text[index] != '%')
  174. return false;
  175. char most_sig_digit(escaped_text[index + 1]);
  176. char least_sig_digit(escaped_text[index + 2]);
  177. if (IsHexDigit(most_sig_digit) && IsHexDigit(least_sig_digit)) {
  178. *value = static_cast<unsigned char>(HexDigitToInt(most_sig_digit) * 16 +
  179. HexDigitToInt(least_sig_digit));
  180. return true;
  181. }
  182. return false;
  183. }
  184. // Attempts to unescape and decode a UTF-8-encoded percent-escaped character at
  185. // the specified index. On success, returns true, sets |code_point_out| to be
  186. // the character's code point and |unescaped_out| to be the unescaped UTF-8
  187. // string. |unescaped_out| will always be 1/3rd the length of the substring of
  188. // |escaped_text| that corresponds to the unescaped character.
  189. bool UnescapeUTF8CharacterAtIndex(StringPiece escaped_text,
  190. size_t index,
  191. base_icu::UChar32* code_point_out,
  192. std::string* unescaped_out) {
  193. DCHECK(unescaped_out->empty());
  194. unsigned char bytes[CBU8_MAX_LENGTH];
  195. if (!UnescapeUnsignedByteAtIndex(escaped_text, index, &bytes[0]))
  196. return false;
  197. size_t num_bytes = 1;
  198. // If this is a lead byte, need to collect trail bytes as well.
  199. if (CBU8_IS_LEAD(bytes[0])) {
  200. // Look for the last trail byte of the UTF-8 character. Give up once
  201. // reach max character length number of bytes, or hit an unescaped
  202. // character. No need to check length of escaped_text, as
  203. // UnescapeUnsignedByteAtIndex checks lengths.
  204. while (num_bytes < std::size(bytes) &&
  205. UnescapeUnsignedByteAtIndex(escaped_text, index + num_bytes * 3,
  206. &bytes[num_bytes]) &&
  207. CBU8_IS_TRAIL(bytes[num_bytes])) {
  208. ++num_bytes;
  209. }
  210. }
  211. size_t char_index = 0;
  212. // Check if the unicode "character" that was just unescaped is valid.
  213. if (!ReadUnicodeCharacter(reinterpret_cast<char*>(bytes), num_bytes,
  214. &char_index, code_point_out)) {
  215. return false;
  216. }
  217. // It's possible that a prefix of |bytes| forms a valid UTF-8 character,
  218. // and the rest are not valid UTF-8, so need to update |num_bytes| based
  219. // on the result of ReadUnicodeCharacter().
  220. num_bytes = char_index + 1;
  221. *unescaped_out = std::string(reinterpret_cast<char*>(bytes), num_bytes);
  222. return true;
  223. }
  224. // This method takes a Unicode code point and returns true if it should be
  225. // unescaped, based on |rules|.
  226. bool ShouldUnescapeCodePoint(UnescapeRule::Type rules,
  227. base_icu::UChar32 code_point) {
  228. // If this is an ASCII character, use the lookup table.
  229. if (code_point >= 0 && code_point < 0x80) {
  230. return kUrlUnescape[static_cast<size_t>(code_point)] ||
  231. // Allow some additional unescaping when flags are set.
  232. (code_point == ' ' && (rules & UnescapeRule::SPACES)) ||
  233. // Allow any of the prohibited but non-control characters when doing
  234. // "special" chars.
  235. ((code_point == '/' || code_point == '\\') &&
  236. (rules & UnescapeRule::PATH_SEPARATORS)) ||
  237. (code_point > ' ' && code_point != '/' && code_point != '\\' &&
  238. (rules & UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS));
  239. }
  240. // Compare the code point against a list of characters that can be used
  241. // to spoof other URLs.
  242. //
  243. // Can't use icu to make this cleaner, because Cronet cannot depend on
  244. // icu, and currently uses this file.
  245. // TODO(https://crbug.com/829873): Try to make this use icu, both to
  246. // protect against regressions as the Unicode standard is updated and to
  247. // reduce the number of long lists of characters.
  248. return !(
  249. // Per http://tools.ietf.org/html/rfc3987#section-4.1, certain BiDi
  250. // control characters are not allowed to appear unescaped in URLs.
  251. code_point == 0x200E || // LEFT-TO-RIGHT MARK (%E2%80%8E)
  252. code_point == 0x200F || // RIGHT-TO-LEFT MARK (%E2%80%8F)
  253. code_point == 0x202A || // LEFT-TO-RIGHT EMBEDDING (%E2%80%AA)
  254. code_point == 0x202B || // RIGHT-TO-LEFT EMBEDDING (%E2%80%AB)
  255. code_point == 0x202C || // POP DIRECTIONAL FORMATTING (%E2%80%AC)
  256. code_point == 0x202D || // LEFT-TO-RIGHT OVERRIDE (%E2%80%AD)
  257. code_point == 0x202E || // RIGHT-TO-LEFT OVERRIDE (%E2%80%AE)
  258. // The Unicode Technical Report (TR9) as referenced by RFC 3987 above has
  259. // since added some new BiDi control characters that are not safe to
  260. // unescape. http://www.unicode.org/reports/tr9
  261. code_point == 0x061C || // ARABIC LETTER MARK (%D8%9C)
  262. code_point == 0x2066 || // LEFT-TO-RIGHT ISOLATE (%E2%81%A6)
  263. code_point == 0x2067 || // RIGHT-TO-LEFT ISOLATE (%E2%81%A7)
  264. code_point == 0x2068 || // FIRST STRONG ISOLATE (%E2%81%A8)
  265. code_point == 0x2069 || // POP DIRECTIONAL ISOLATE (%E2%81%A9)
  266. // The following spoofable characters are also banned in unescaped URLs,
  267. // because they could be used to imitate parts of a web browser's UI.
  268. code_point == 0x1F50F || // LOCK WITH INK PEN (%F0%9F%94%8F)
  269. code_point == 0x1F510 || // CLOSED LOCK WITH KEY (%F0%9F%94%90)
  270. code_point == 0x1F512 || // LOCK (%F0%9F%94%92)
  271. code_point == 0x1F513 || // OPEN LOCK (%F0%9F%94%93)
  272. // Spaces are also banned, as they can be used to scroll text out of view.
  273. code_point == 0x0085 || // NEXT LINE (%C2%85)
  274. code_point == 0x00A0 || // NO-BREAK SPACE (%C2%A0)
  275. code_point == 0x1680 || // OGHAM SPACE MARK (%E1%9A%80)
  276. code_point == 0x2000 || // EN QUAD (%E2%80%80)
  277. code_point == 0x2001 || // EM QUAD (%E2%80%81)
  278. code_point == 0x2002 || // EN SPACE (%E2%80%82)
  279. code_point == 0x2003 || // EM SPACE (%E2%80%83)
  280. code_point == 0x2004 || // THREE-PER-EM SPACE (%E2%80%84)
  281. code_point == 0x2005 || // FOUR-PER-EM SPACE (%E2%80%85)
  282. code_point == 0x2006 || // SIX-PER-EM SPACE (%E2%80%86)
  283. code_point == 0x2007 || // FIGURE SPACE (%E2%80%87)
  284. code_point == 0x2008 || // PUNCTUATION SPACE (%E2%80%88)
  285. code_point == 0x2009 || // THIN SPACE (%E2%80%89)
  286. code_point == 0x200A || // HAIR SPACE (%E2%80%8A)
  287. code_point == 0x2028 || // LINE SEPARATOR (%E2%80%A8)
  288. code_point == 0x2029 || // PARAGRAPH SEPARATOR (%E2%80%A9)
  289. code_point == 0x202F || // NARROW NO-BREAK SPACE (%E2%80%AF)
  290. code_point == 0x205F || // MEDIUM MATHEMATICAL SPACE (%E2%81%9F)
  291. code_point == 0x3000 || // IDEOGRAPHIC SPACE (%E3%80%80)
  292. // U+2800 is rendered as a space, but is not considered whitespace (see
  293. // crbug.com/1068531).
  294. code_point == 0x2800 || // BRAILLE PATTERN BLANK (%E2%A0%80)
  295. // Default Ignorable ([:Default_Ignorable_Code_Point=Yes:]) and Format
  296. // characters ([:Cf:]) are also banned (see crbug.com/824715).
  297. code_point == 0x00AD || // SOFT HYPHEN (%C2%AD)
  298. code_point == 0x034F || // COMBINING GRAPHEME JOINER (%CD%8F)
  299. // Arabic number formatting
  300. (code_point >= 0x0600 && code_point <= 0x0605) ||
  301. // U+061C is already banned as a BiDi control character.
  302. code_point == 0x06DD || // ARABIC END OF AYAH (%DB%9D)
  303. code_point == 0x070F || // SYRIAC ABBREVIATION MARK (%DC%8F)
  304. code_point == 0x08E2 || // ARABIC DISPUTED END OF AYAH (%E0%A3%A2)
  305. code_point == 0x115F || // HANGUL CHOSEONG FILLER (%E1%85%9F)
  306. code_point == 0x1160 || // HANGUL JUNGSEONG FILLER (%E1%85%A0)
  307. code_point == 0x17B4 || // KHMER VOWEL INHERENT AQ (%E1%9E%B4)
  308. code_point == 0x17B5 || // KHMER VOWEL INHERENT AA (%E1%9E%B5)
  309. code_point == 0x180B || // MONGOLIAN FREE VARIATION SELECTOR ONE
  310. // (%E1%A0%8B)
  311. code_point == 0x180C || // MONGOLIAN FREE VARIATION SELECTOR TWO
  312. // (%E1%A0%8C)
  313. code_point == 0x180D || // MONGOLIAN FREE VARIATION SELECTOR THREE
  314. // (%E1%A0%8D)
  315. code_point == 0x180E || // MONGOLIAN VOWEL SEPARATOR (%E1%A0%8E)
  316. code_point == 0x200B || // ZERO WIDTH SPACE (%E2%80%8B)
  317. code_point == 0x200C || // ZERO WIDTH SPACE NON-JOINER (%E2%80%8C)
  318. code_point == 0x200D || // ZERO WIDTH JOINER (%E2%80%8D)
  319. // U+200E, U+200F, U+202A--202E, and U+2066--2069 are already banned as
  320. // BiDi control characters.
  321. code_point == 0x2060 || // WORD JOINER (%E2%81%A0)
  322. code_point == 0x2061 || // FUNCTION APPLICATION (%E2%81%A1)
  323. code_point == 0x2062 || // INVISIBLE TIMES (%E2%81%A2)
  324. code_point == 0x2063 || // INVISIBLE SEPARATOR (%E2%81%A3)
  325. code_point == 0x2064 || // INVISIBLE PLUS (%E2%81%A4)
  326. code_point == 0x2065 || // null (%E2%81%A5)
  327. // 0x2066--0x2069 are already banned as a BiDi control characters.
  328. // General Punctuation - Deprecated (U+206A--206F)
  329. (code_point >= 0x206A && code_point <= 0x206F) ||
  330. code_point == 0x3164 || // HANGUL FILLER (%E3%85%A4)
  331. (code_point >= 0xFFF0 && code_point <= 0xFFF8) || // null
  332. // Variation selectors (%EF%B8%80 -- %EF%B8%8F)
  333. (code_point >= 0xFE00 && code_point <= 0xFE0F) ||
  334. code_point == 0xFEFF || // ZERO WIDTH NO-BREAK SPACE (%EF%BB%BF)
  335. code_point == 0xFFA0 || // HALFWIDTH HANGUL FILLER (%EF%BE%A0)
  336. code_point == 0xFFF9 || // INTERLINEAR ANNOTATION ANCHOR (%EF%BF%B9)
  337. code_point == 0xFFFA || // INTERLINEAR ANNOTATION SEPARATOR (%EF%BF%BA)
  338. code_point == 0xFFFB || // INTERLINEAR ANNOTATION TERMINATOR (%EF%BF%BB)
  339. code_point == 0x110BD || // KAITHI NUMBER SIGN (%F0%91%82%BD)
  340. code_point == 0x110CD || // KAITHI NUMBER SIGN ABOVE (%F0%91%83%8D)
  341. // Egyptian hieroglyph formatting (%F0%93%90%B0 -- %F0%93%90%B8)
  342. (code_point >= 0x13430 && code_point <= 0x13438) ||
  343. // Shorthand format controls (%F0%9B%B2%A0 -- %F0%9B%B2%A3)
  344. (code_point >= 0x1BCA0 && code_point <= 0x1BCA3) ||
  345. // Beams and slurs (%F0%9D%85%B3 -- %F0%9D%85%BA)
  346. (code_point >= 0x1D173 && code_point <= 0x1D17A) ||
  347. // Tags, Variation Selectors, nulls
  348. (code_point >= 0xE0000 && code_point <= 0xE0FFF));
  349. }
  350. // Unescapes |escaped_text| according to |rules|, returning the resulting
  351. // string. Fills in an |adjustments| parameter, if non-nullptr, so it reflects
  352. // the alterations done to the string that are not one-character-to-one-
  353. // character. The resulting |adjustments| will always be sorted by increasing
  354. // offset.
  355. std::string UnescapeURLWithAdjustmentsImpl(
  356. StringPiece escaped_text,
  357. UnescapeRule::Type rules,
  358. OffsetAdjuster::Adjustments* adjustments) {
  359. if (adjustments)
  360. adjustments->clear();
  361. // Do not unescape anything, return the |escaped_text| text.
  362. if (rules == UnescapeRule::NONE)
  363. return std::string(escaped_text);
  364. // The output of the unescaping is always smaller than the input, so we can
  365. // reserve the input size to make sure we have enough buffer and don't have
  366. // to allocate in the loop below.
  367. std::string result;
  368. result.reserve(escaped_text.length());
  369. // Locations of adjusted text.
  370. for (size_t i = 0, max = escaped_text.size(); i < max;) {
  371. // Try to unescape the character.
  372. base_icu::UChar32 code_point;
  373. std::string unescaped;
  374. if (!UnescapeUTF8CharacterAtIndex(escaped_text, i, &code_point,
  375. &unescaped)) {
  376. // Check if the next character can be unescaped, but not as a valid UTF-8
  377. // character. In that case, just unescaped and write the non-sense
  378. // character.
  379. //
  380. // TODO(https://crbug.com/829868): Do not unescape illegal UTF-8
  381. // sequences.
  382. unsigned char non_utf8_byte;
  383. if (UnescapeUnsignedByteAtIndex(escaped_text, i, &non_utf8_byte)) {
  384. result.push_back(static_cast<char>(non_utf8_byte));
  385. if (adjustments)
  386. adjustments->push_back(OffsetAdjuster::Adjustment(i, 3, 1));
  387. i += 3;
  388. continue;
  389. }
  390. // Character is not escaped, so append as is, unless it's a '+' and
  391. // REPLACE_PLUS_WITH_SPACE is being applied.
  392. if (escaped_text[i] == '+' &&
  393. (rules & UnescapeRule::REPLACE_PLUS_WITH_SPACE)) {
  394. result.push_back(' ');
  395. } else {
  396. result.push_back(escaped_text[i]);
  397. }
  398. ++i;
  399. continue;
  400. }
  401. DCHECK(!unescaped.empty());
  402. if (!ShouldUnescapeCodePoint(rules, code_point)) {
  403. // If it's a valid UTF-8 character, but not safe to unescape, copy all
  404. // bytes directly.
  405. result.append(escaped_text.begin() + i,
  406. escaped_text.begin() + i + 3 * unescaped.length());
  407. i += unescaped.length() * 3;
  408. continue;
  409. }
  410. // If the code point is allowed, and append the entire unescaped character.
  411. result.append(unescaped);
  412. if (adjustments) {
  413. for (size_t j = 0; j < unescaped.length(); ++j) {
  414. adjustments->push_back(OffsetAdjuster::Adjustment(i + j * 3, 3, 1));
  415. }
  416. }
  417. i += 3 * unescaped.length();
  418. }
  419. return result;
  420. }
  421. } // namespace
  422. std::string EscapeAllExceptUnreserved(StringPiece text) {
  423. return Escape(text, kUnreservedCharmap, false);
  424. }
  425. std::string EscapeQueryParamValue(StringPiece text, bool use_plus) {
  426. return Escape(text, kQueryCharmap, use_plus);
  427. }
  428. std::string EscapePath(StringPiece path) {
  429. return Escape(path, kPathCharmap, false);
  430. }
  431. #if BUILDFLAG(IS_APPLE)
  432. std::string EscapeNSURLPrecursor(StringPiece precursor) {
  433. return Escape(precursor, kNSURLCharmap, false, true);
  434. }
  435. #endif // BUILDFLAG(IS_APPLE)
  436. std::string EscapeUrlEncodedData(StringPiece path, bool use_plus) {
  437. return Escape(path, kUrlEscape, use_plus);
  438. }
  439. std::string EscapeNonASCIIAndPercent(StringPiece input) {
  440. return Escape(input, kNonASCIICharmapAndPercent, false);
  441. }
  442. std::string EscapeNonASCII(StringPiece input) {
  443. return Escape(input, kNonASCIICharmap, false);
  444. }
  445. std::string EscapeExternalHandlerValue(StringPiece text) {
  446. return Escape(text, kExternalHandlerCharmap, false, true);
  447. }
  448. void AppendEscapedCharForHTML(char c, std::string* output) {
  449. AppendEscapedCharForHTMLImpl(c, output);
  450. }
  451. std::string EscapeForHTML(StringPiece input) {
  452. return EscapeForHTMLImpl(input);
  453. }
  454. std::u16string EscapeForHTML(StringPiece16 input) {
  455. return EscapeForHTMLImpl(input);
  456. }
  457. std::string UnescapeURLComponent(StringPiece escaped_text,
  458. UnescapeRule::Type rules) {
  459. return UnescapeURLWithAdjustmentsImpl(escaped_text, rules, nullptr);
  460. }
  461. std::u16string UnescapeAndDecodeUTF8URLComponentWithAdjustments(
  462. StringPiece text,
  463. UnescapeRule::Type rules,
  464. OffsetAdjuster::Adjustments* adjustments) {
  465. std::u16string result;
  466. OffsetAdjuster::Adjustments unescape_adjustments;
  467. std::string unescaped_url(
  468. UnescapeURLWithAdjustmentsImpl(text, rules, &unescape_adjustments));
  469. if (UTF8ToUTF16WithAdjustments(unescaped_url.data(), unescaped_url.length(),
  470. &result, adjustments)) {
  471. // Character set looks like it's valid.
  472. if (adjustments) {
  473. OffsetAdjuster::MergeSequentialAdjustments(unescape_adjustments,
  474. adjustments);
  475. }
  476. return result;
  477. }
  478. // Character set is not valid. Return the escaped version.
  479. return UTF8ToUTF16WithAdjustments(text, adjustments);
  480. }
  481. std::string UnescapeBinaryURLComponent(StringPiece escaped_text,
  482. UnescapeRule::Type rules) {
  483. // Only NORMAL and REPLACE_PLUS_WITH_SPACE are supported.
  484. DCHECK(rules != UnescapeRule::NONE);
  485. DCHECK(!(rules &
  486. ~(UnescapeRule::NORMAL | UnescapeRule::REPLACE_PLUS_WITH_SPACE)));
  487. // If there are no '%' characters in the string, there will be nothing to
  488. // unescape, so we can take the fast path.
  489. if (base::FeatureList::IsEnabled(features::kOptimizeDataUrls) &&
  490. escaped_text.find('%') == StringPiece::npos) {
  491. std::string unescaped_text(escaped_text);
  492. if (rules & UnescapeRule::REPLACE_PLUS_WITH_SPACE)
  493. std::replace(unescaped_text.begin(), unescaped_text.end(), '+', ' ');
  494. return unescaped_text;
  495. }
  496. std::string unescaped_text;
  497. // The output of the unescaping is always smaller than the input, so we can
  498. // reserve the input size to make sure we have enough buffer and don't have
  499. // to allocate in the loop below.
  500. // Increase capacity before size, as just resizing can grow capacity
  501. // needlessly beyond our requested size.
  502. unescaped_text.reserve(escaped_text.size());
  503. unescaped_text.resize(escaped_text.size());
  504. size_t output_index = 0;
  505. for (size_t i = 0, max = escaped_text.size(); i < max;) {
  506. unsigned char byte;
  507. // UnescapeUnsignedByteAtIndex does bounds checking, so this is always safe
  508. // to call.
  509. if (UnescapeUnsignedByteAtIndex(escaped_text, i, &byte)) {
  510. unescaped_text[output_index++] = static_cast<char>(byte);
  511. i += 3;
  512. continue;
  513. }
  514. if ((rules & UnescapeRule::REPLACE_PLUS_WITH_SPACE) &&
  515. escaped_text[i] == '+') {
  516. unescaped_text[output_index++] = ' ';
  517. ++i;
  518. continue;
  519. }
  520. unescaped_text[output_index++] = escaped_text[i++];
  521. }
  522. DCHECK_LE(output_index, unescaped_text.size());
  523. unescaped_text.resize(output_index);
  524. return unescaped_text;
  525. }
  526. bool UnescapeBinaryURLComponentSafe(StringPiece escaped_text,
  527. bool fail_on_path_separators,
  528. std::string* unescaped_text) {
  529. unescaped_text->clear();
  530. std::set<unsigned char> illegal_encoded_bytes;
  531. for (unsigned char c = '\x00'; c < '\x20'; ++c) {
  532. illegal_encoded_bytes.insert(c);
  533. }
  534. if (fail_on_path_separators) {
  535. illegal_encoded_bytes.insert('/');
  536. illegal_encoded_bytes.insert('\\');
  537. }
  538. if (ContainsEncodedBytes(escaped_text, illegal_encoded_bytes))
  539. return false;
  540. *unescaped_text = UnescapeBinaryURLComponent(escaped_text);
  541. return true;
  542. }
  543. bool ContainsEncodedBytes(StringPiece escaped_text,
  544. const std::set<unsigned char>& bytes) {
  545. for (size_t i = 0, max = escaped_text.size(); i < max;) {
  546. unsigned char byte;
  547. // UnescapeUnsignedByteAtIndex does bounds checking, so this is always safe
  548. // to call.
  549. if (UnescapeUnsignedByteAtIndex(escaped_text, i, &byte)) {
  550. if (bytes.find(byte) != bytes.end())
  551. return true;
  552. i += 3;
  553. continue;
  554. }
  555. ++i;
  556. }
  557. return false;
  558. }
  559. std::u16string UnescapeForHTML(StringPiece16 input) {
  560. static const struct {
  561. const char* ampersand_code;
  562. const char16_t replacement;
  563. } kEscapeToChars[] = {
  564. {"&lt;", '<'}, {"&gt;", '>'}, {"&amp;", '&'},
  565. {"&quot;", '"'}, {"&#39;", '\''},
  566. };
  567. constexpr size_t kEscapeToCharsCount = std::size(kEscapeToChars);
  568. if (input.find(u"&") == std::string::npos)
  569. return std::u16string(input);
  570. std::u16string ampersand_chars[kEscapeToCharsCount];
  571. std::u16string text(input);
  572. for (std::u16string::iterator iter = text.begin(); iter != text.end();
  573. ++iter) {
  574. if (*iter == '&') {
  575. // Potential ampersand encode char.
  576. size_t index = static_cast<size_t>(iter - text.begin());
  577. for (size_t i = 0; i < std::size(kEscapeToChars); i++) {
  578. if (ampersand_chars[i].empty()) {
  579. ampersand_chars[i] = ASCIIToUTF16(kEscapeToChars[i].ampersand_code);
  580. }
  581. if (text.find(ampersand_chars[i], index) == index) {
  582. text.replace(
  583. iter, iter + static_cast<ptrdiff_t>(ampersand_chars[i].length()),
  584. 1, kEscapeToChars[i].replacement);
  585. break;
  586. }
  587. }
  588. }
  589. }
  590. return text;
  591. }
  592. } // namespace base