escaping.cc 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "y_absl/strings/escaping.h"
  15. #include <algorithm>
  16. #include <cassert>
  17. #include <cstddef>
  18. #include <cstdint>
  19. #include <cstring>
  20. #include <limits>
  21. #include <util/generic/string.h>
  22. #include <utility>
  23. #include "y_absl/base/config.h"
  24. #include "y_absl/base/internal/raw_logging.h"
  25. #include "y_absl/base/internal/unaligned_access.h"
  26. #include "y_absl/base/nullability.h"
  27. #include "y_absl/strings/ascii.h"
  28. #include "y_absl/strings/charset.h"
  29. #include "y_absl/strings/internal/escaping.h"
  30. #include "y_absl/strings/internal/resize_uninitialized.h"
  31. #include "y_absl/strings/internal/utf8.h"
  32. #include "y_absl/strings/numbers.h"
  33. #include "y_absl/strings/str_cat.h"
  34. #include "y_absl/strings/string_view.h"
  35. namespace y_absl {
  36. Y_ABSL_NAMESPACE_BEGIN
  37. namespace {
  38. // These are used for the leave_nulls_escaped argument to CUnescapeInternal().
  39. constexpr bool kUnescapeNulls = false;
  40. inline bool is_octal_digit(char c) { return ('0' <= c) && (c <= '7'); }
  41. inline unsigned int hex_digit_to_int(char c) {
  42. static_assert('0' == 0x30 && 'A' == 0x41 && 'a' == 0x61,
  43. "Character set must be ASCII.");
  44. assert(y_absl::ascii_isxdigit(static_cast<unsigned char>(c)));
  45. unsigned int x = static_cast<unsigned char>(c);
  46. if (x > '9') {
  47. x += 9;
  48. }
  49. return x & 0xf;
  50. }
  51. inline bool IsSurrogate(char32_t c, y_absl::string_view src,
  52. y_absl::Nullable<TString*> error) {
  53. if (c >= 0xD800 && c <= 0xDFFF) {
  54. if (error) {
  55. *error = y_absl::StrCat("invalid surrogate character (0xD800-DFFF): \\",
  56. src);
  57. }
  58. return true;
  59. }
  60. return false;
  61. }
  62. // ----------------------------------------------------------------------
  63. // CUnescapeInternal()
  64. // Implements both CUnescape() and CUnescapeForNullTerminatedString().
  65. //
  66. // Unescapes C escape sequences and is the reverse of CEscape().
  67. //
  68. // If 'source' is valid, stores the unescaped string and its size in
  69. // 'dest' and 'dest_len' respectively, and returns true. Otherwise
  70. // returns false and optionally stores the error description in
  71. // 'error'. Set 'error' to nullptr to disable error reporting.
  72. //
  73. // 'dest' should point to a buffer that is at least as big as 'source'.
  74. // 'source' and 'dest' may be the same.
  75. //
  76. // NOTE: any changes to this function must also be reflected in the older
  77. // UnescapeCEscapeSequences().
  78. // ----------------------------------------------------------------------
  79. bool CUnescapeInternal(y_absl::string_view source, bool leave_nulls_escaped,
  80. y_absl::Nonnull<char*> dest,
  81. y_absl::Nonnull<ptrdiff_t*> dest_len,
  82. y_absl::Nullable<TString*> error) {
  83. char* d = dest;
  84. const char* p = source.data();
  85. const char* end = p + source.size();
  86. const char* last_byte = end - 1;
  87. // Small optimization for case where source = dest and there's no escaping
  88. while (p == d && p < end && *p != '\\') p++, d++;
  89. while (p < end) {
  90. if (*p != '\\') {
  91. *d++ = *p++;
  92. } else {
  93. if (++p > last_byte) { // skip past the '\\'
  94. if (error) *error = "String cannot end with \\";
  95. return false;
  96. }
  97. switch (*p) {
  98. case 'a': *d++ = '\a'; break;
  99. case 'b': *d++ = '\b'; break;
  100. case 'f': *d++ = '\f'; break;
  101. case 'n': *d++ = '\n'; break;
  102. case 'r': *d++ = '\r'; break;
  103. case 't': *d++ = '\t'; break;
  104. case 'v': *d++ = '\v'; break;
  105. case '\\': *d++ = '\\'; break;
  106. case '?': *d++ = '\?'; break; // \? Who knew?
  107. case '\'': *d++ = '\''; break;
  108. case '"': *d++ = '\"'; break;
  109. case '0':
  110. case '1':
  111. case '2':
  112. case '3':
  113. case '4':
  114. case '5':
  115. case '6':
  116. case '7': {
  117. // octal digit: 1 to 3 digits
  118. const char* octal_start = p;
  119. unsigned int ch = static_cast<unsigned int>(*p - '0'); // digit 1
  120. if (p < last_byte && is_octal_digit(p[1]))
  121. ch = ch * 8 + static_cast<unsigned int>(*++p - '0'); // digit 2
  122. if (p < last_byte && is_octal_digit(p[1]))
  123. ch = ch * 8 + static_cast<unsigned int>(*++p - '0'); // digit 3
  124. if (ch > 0xff) {
  125. if (error) {
  126. *error = "Value of \\" +
  127. TString(octal_start,
  128. static_cast<size_t>(p + 1 - octal_start)) +
  129. " exceeds 0xff";
  130. }
  131. return false;
  132. }
  133. if ((ch == 0) && leave_nulls_escaped) {
  134. // Copy the escape sequence for the null character
  135. const size_t octal_size = static_cast<size_t>(p + 1 - octal_start);
  136. *d++ = '\\';
  137. memmove(d, octal_start, octal_size);
  138. d += octal_size;
  139. break;
  140. }
  141. *d++ = static_cast<char>(ch);
  142. break;
  143. }
  144. case 'x':
  145. case 'X': {
  146. if (p >= last_byte) {
  147. if (error) *error = "String cannot end with \\x";
  148. return false;
  149. } else if (!y_absl::ascii_isxdigit(static_cast<unsigned char>(p[1]))) {
  150. if (error) *error = "\\x cannot be followed by a non-hex digit";
  151. return false;
  152. }
  153. unsigned int ch = 0;
  154. const char* hex_start = p;
  155. while (p < last_byte &&
  156. y_absl::ascii_isxdigit(static_cast<unsigned char>(p[1])))
  157. // Arbitrarily many hex digits
  158. ch = (ch << 4) + hex_digit_to_int(*++p);
  159. if (ch > 0xFF) {
  160. if (error) {
  161. *error = "Value of \\" +
  162. TString(hex_start,
  163. static_cast<size_t>(p + 1 - hex_start)) +
  164. " exceeds 0xff";
  165. }
  166. return false;
  167. }
  168. if ((ch == 0) && leave_nulls_escaped) {
  169. // Copy the escape sequence for the null character
  170. const size_t hex_size = static_cast<size_t>(p + 1 - hex_start);
  171. *d++ = '\\';
  172. memmove(d, hex_start, hex_size);
  173. d += hex_size;
  174. break;
  175. }
  176. *d++ = static_cast<char>(ch);
  177. break;
  178. }
  179. case 'u': {
  180. // \uhhhh => convert 4 hex digits to UTF-8
  181. char32_t rune = 0;
  182. const char* hex_start = p;
  183. if (p + 4 >= end) {
  184. if (error) {
  185. *error = "\\u must be followed by 4 hex digits: \\" +
  186. TString(hex_start,
  187. static_cast<size_t>(p + 1 - hex_start));
  188. }
  189. return false;
  190. }
  191. for (int i = 0; i < 4; ++i) {
  192. // Look one char ahead.
  193. if (y_absl::ascii_isxdigit(static_cast<unsigned char>(p[1]))) {
  194. rune = (rune << 4) + hex_digit_to_int(*++p); // Advance p.
  195. } else {
  196. if (error) {
  197. *error = "\\u must be followed by 4 hex digits: \\" +
  198. TString(hex_start,
  199. static_cast<size_t>(p + 1 - hex_start));
  200. }
  201. return false;
  202. }
  203. }
  204. if ((rune == 0) && leave_nulls_escaped) {
  205. // Copy the escape sequence for the null character
  206. *d++ = '\\';
  207. memmove(d, hex_start, 5); // u0000
  208. d += 5;
  209. break;
  210. }
  211. if (IsSurrogate(rune, y_absl::string_view(hex_start, 5), error)) {
  212. return false;
  213. }
  214. d += strings_internal::EncodeUTF8Char(d, rune);
  215. break;
  216. }
  217. case 'U': {
  218. // \Uhhhhhhhh => convert 8 hex digits to UTF-8
  219. char32_t rune = 0;
  220. const char* hex_start = p;
  221. if (p + 8 >= end) {
  222. if (error) {
  223. *error = "\\U must be followed by 8 hex digits: \\" +
  224. TString(hex_start,
  225. static_cast<size_t>(p + 1 - hex_start));
  226. }
  227. return false;
  228. }
  229. for (int i = 0; i < 8; ++i) {
  230. // Look one char ahead.
  231. if (y_absl::ascii_isxdigit(static_cast<unsigned char>(p[1]))) {
  232. // Don't change rune until we're sure this
  233. // is within the Unicode limit, but do advance p.
  234. uint32_t newrune = (rune << 4) + hex_digit_to_int(*++p);
  235. if (newrune > 0x10FFFF) {
  236. if (error) {
  237. *error = "Value of \\" +
  238. TString(hex_start,
  239. static_cast<size_t>(p + 1 - hex_start)) +
  240. " exceeds Unicode limit (0x10FFFF)";
  241. }
  242. return false;
  243. } else {
  244. rune = newrune;
  245. }
  246. } else {
  247. if (error) {
  248. *error = "\\U must be followed by 8 hex digits: \\" +
  249. TString(hex_start,
  250. static_cast<size_t>(p + 1 - hex_start));
  251. }
  252. return false;
  253. }
  254. }
  255. if ((rune == 0) && leave_nulls_escaped) {
  256. // Copy the escape sequence for the null character
  257. *d++ = '\\';
  258. memmove(d, hex_start, 9); // U00000000
  259. d += 9;
  260. break;
  261. }
  262. if (IsSurrogate(rune, y_absl::string_view(hex_start, 9), error)) {
  263. return false;
  264. }
  265. d += strings_internal::EncodeUTF8Char(d, rune);
  266. break;
  267. }
  268. default: {
  269. if (error) *error = TString("Unknown escape sequence: \\") + *p;
  270. return false;
  271. }
  272. }
  273. p++; // read past letter we escaped
  274. }
  275. }
  276. *dest_len = d - dest;
  277. return true;
  278. }
  279. // ----------------------------------------------------------------------
  280. // CUnescapeInternal()
  281. //
  282. // Same as above but uses a TString for output. 'source' and 'dest'
  283. // may be the same.
  284. // ----------------------------------------------------------------------
  285. bool CUnescapeInternal(y_absl::string_view source, bool leave_nulls_escaped,
  286. y_absl::Nonnull<TString*> dest,
  287. y_absl::Nullable<TString*> error) {
  288. strings_internal::STLStringResizeUninitialized(dest, source.size());
  289. ptrdiff_t dest_size;
  290. if (!CUnescapeInternal(source,
  291. leave_nulls_escaped,
  292. &(*dest)[0],
  293. &dest_size,
  294. error)) {
  295. return false;
  296. }
  297. dest->erase(static_cast<size_t>(dest_size));
  298. return true;
  299. }
  300. // ----------------------------------------------------------------------
  301. // CEscape()
  302. // CHexEscape()
  303. // Utf8SafeCEscape()
  304. // Utf8SafeCHexEscape()
  305. // Escapes 'src' using C-style escape sequences. This is useful for
  306. // preparing query flags. The 'Hex' version uses hexadecimal rather than
  307. // octal sequences. The 'Utf8Safe' version does not touch UTF-8 bytes.
  308. //
  309. // Escaped chars: \n, \r, \t, ", ', \, and !y_absl::ascii_isprint().
  310. // ----------------------------------------------------------------------
  311. TString CEscapeInternal(y_absl::string_view src, bool use_hex,
  312. bool utf8_safe) {
  313. TString dest;
  314. bool last_hex_escape = false; // true if last output char was \xNN.
  315. for (char c : src) {
  316. bool is_hex_escape = false;
  317. switch (c) {
  318. case '\n': dest.append("\\" "n"); break;
  319. case '\r': dest.append("\\" "r"); break;
  320. case '\t': dest.append("\\" "t"); break;
  321. case '\"': dest.append("\\" "\""); break;
  322. case '\'': dest.append("\\" "'"); break;
  323. case '\\': dest.append("\\" "\\"); break;
  324. default: {
  325. // Note that if we emit \xNN and the src character after that is a hex
  326. // digit then that digit must be escaped too to prevent it being
  327. // interpreted as part of the character code by C.
  328. const unsigned char uc = static_cast<unsigned char>(c);
  329. if ((!utf8_safe || uc < 0x80) &&
  330. (!y_absl::ascii_isprint(uc) ||
  331. (last_hex_escape && y_absl::ascii_isxdigit(uc)))) {
  332. if (use_hex) {
  333. dest.append("\\" "x");
  334. dest.push_back(numbers_internal::kHexChar[uc / 16]);
  335. dest.push_back(numbers_internal::kHexChar[uc % 16]);
  336. is_hex_escape = true;
  337. } else {
  338. dest.append("\\");
  339. dest.push_back(numbers_internal::kHexChar[uc / 64]);
  340. dest.push_back(numbers_internal::kHexChar[(uc % 64) / 8]);
  341. dest.push_back(numbers_internal::kHexChar[uc % 8]);
  342. }
  343. } else {
  344. dest.push_back(c);
  345. break;
  346. }
  347. }
  348. }
  349. last_hex_escape = is_hex_escape;
  350. }
  351. return dest;
  352. }
  353. /* clang-format off */
  354. constexpr unsigned char kCEscapedLen[256] = {
  355. 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 4, 4, 2, 4, 4, // \t, \n, \r
  356. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  357. 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // ", '
  358. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // '0'..'9'
  359. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'A'..'O'
  360. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, // 'P'..'Z', '\'
  361. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'a'..'o'
  362. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, // 'p'..'z', DEL
  363. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  364. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  365. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  366. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  367. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  368. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  369. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  370. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  371. };
  372. /* clang-format on */
  373. // Calculates the length of the C-style escaped version of 'src'.
  374. // Assumes that non-printable characters are escaped using octal sequences, and
  375. // that UTF-8 bytes are not handled specially.
  376. inline size_t CEscapedLength(y_absl::string_view src) {
  377. size_t escaped_len = 0;
  378. // The maximum value of kCEscapedLen[x] is 4, so we can escape any string of
  379. // length size_t_max/4 without checking for overflow.
  380. size_t unchecked_limit =
  381. std::min<size_t>(src.size(), std::numeric_limits<size_t>::max() / 4);
  382. size_t i = 0;
  383. while (i < unchecked_limit) {
  384. // Common case: No need to check for overflow.
  385. escaped_len += kCEscapedLen[static_cast<unsigned char>(src[i++])];
  386. }
  387. while (i < src.size()) {
  388. // Beyond unchecked_limit we need to check for overflow before adding.
  389. size_t char_len = kCEscapedLen[static_cast<unsigned char>(src[i++])];
  390. Y_ABSL_INTERNAL_CHECK(
  391. escaped_len <= std::numeric_limits<size_t>::max() - char_len,
  392. "escaped_len overflow");
  393. escaped_len += char_len;
  394. }
  395. return escaped_len;
  396. }
  397. void CEscapeAndAppendInternal(y_absl::string_view src,
  398. y_absl::Nonnull<TString*> dest) {
  399. size_t escaped_len = CEscapedLength(src);
  400. if (escaped_len == src.size()) {
  401. dest->append(src.data(), src.size());
  402. return;
  403. }
  404. size_t cur_dest_len = dest->size();
  405. Y_ABSL_INTERNAL_CHECK(
  406. cur_dest_len <= std::numeric_limits<size_t>::max() - escaped_len,
  407. "TString size overflow");
  408. strings_internal::STLStringResizeUninitialized(dest,
  409. cur_dest_len + escaped_len);
  410. char* append_ptr = &(*dest)[cur_dest_len];
  411. for (char c : src) {
  412. size_t char_len = kCEscapedLen[static_cast<unsigned char>(c)];
  413. if (char_len == 1) {
  414. *append_ptr++ = c;
  415. } else if (char_len == 2) {
  416. switch (c) {
  417. case '\n':
  418. *append_ptr++ = '\\';
  419. *append_ptr++ = 'n';
  420. break;
  421. case '\r':
  422. *append_ptr++ = '\\';
  423. *append_ptr++ = 'r';
  424. break;
  425. case '\t':
  426. *append_ptr++ = '\\';
  427. *append_ptr++ = 't';
  428. break;
  429. case '\"':
  430. *append_ptr++ = '\\';
  431. *append_ptr++ = '\"';
  432. break;
  433. case '\'':
  434. *append_ptr++ = '\\';
  435. *append_ptr++ = '\'';
  436. break;
  437. case '\\':
  438. *append_ptr++ = '\\';
  439. *append_ptr++ = '\\';
  440. break;
  441. }
  442. } else {
  443. *append_ptr++ = '\\';
  444. *append_ptr++ = '0' + static_cast<unsigned char>(c) / 64;
  445. *append_ptr++ = '0' + (static_cast<unsigned char>(c) % 64) / 8;
  446. *append_ptr++ = '0' + static_cast<unsigned char>(c) % 8;
  447. }
  448. }
  449. }
  450. // Reverses the mapping in Base64EscapeInternal; see that method's
  451. // documentation for details of the mapping.
  452. bool Base64UnescapeInternal(y_absl::Nullable<const char*> src_param, size_t szsrc,
  453. y_absl::Nullable<char*> dest, size_t szdest,
  454. y_absl::Nonnull<const signed char*> unbase64,
  455. y_absl::Nonnull<size_t*> len) {
  456. static const char kPad64Equals = '=';
  457. static const char kPad64Dot = '.';
  458. size_t destidx = 0;
  459. int decode = 0;
  460. int state = 0;
  461. unsigned char ch = 0;
  462. unsigned int temp = 0;
  463. // If "char" is signed by default, using *src as an array index results in
  464. // accessing negative array elements. Treat the input as a pointer to
  465. // unsigned char to avoid this.
  466. const unsigned char* src = reinterpret_cast<const unsigned char*>(src_param);
  467. // The GET_INPUT macro gets the next input character, skipping
  468. // over any whitespace, and stopping when we reach the end of the
  469. // string or when we read any non-data character. The arguments are
  470. // an arbitrary identifier (used as a label for goto) and the number
  471. // of data bytes that must remain in the input to avoid aborting the
  472. // loop.
  473. #define GET_INPUT(label, remain) \
  474. label: \
  475. --szsrc; \
  476. ch = *src++; \
  477. decode = unbase64[ch]; \
  478. if (decode < 0) { \
  479. if (y_absl::ascii_isspace(ch) && szsrc >= remain) goto label; \
  480. state = 4 - remain; \
  481. break; \
  482. }
  483. // if dest is null, we're just checking to see if it's legal input
  484. // rather than producing output. (I suspect this could just be done
  485. // with a regexp...). We duplicate the loop so this test can be
  486. // outside it instead of in every iteration.
  487. if (dest) {
  488. // This loop consumes 4 input bytes and produces 3 output bytes
  489. // per iteration. We can't know at the start that there is enough
  490. // data left in the string for a full iteration, so the loop may
  491. // break out in the middle; if so 'state' will be set to the
  492. // number of input bytes read.
  493. while (szsrc >= 4) {
  494. // We'll start by optimistically assuming that the next four
  495. // bytes of the string (src[0..3]) are four good data bytes
  496. // (that is, no nulls, whitespace, padding chars, or illegal
  497. // chars). We need to test src[0..2] for nulls individually
  498. // before constructing temp to preserve the property that we
  499. // never read past a null in the string (no matter how long
  500. // szsrc claims the string is).
  501. if (!src[0] || !src[1] || !src[2] ||
  502. ((temp = ((unsigned(unbase64[src[0]]) << 18) |
  503. (unsigned(unbase64[src[1]]) << 12) |
  504. (unsigned(unbase64[src[2]]) << 6) |
  505. (unsigned(unbase64[src[3]])))) &
  506. 0x80000000)) {
  507. // Iff any of those four characters was bad (null, illegal,
  508. // whitespace, padding), then temp's high bit will be set
  509. // (because unbase64[] is -1 for all bad characters).
  510. //
  511. // We'll back up and resort to the slower decoder, which knows
  512. // how to handle those cases.
  513. GET_INPUT(first, 4);
  514. temp = static_cast<unsigned char>(decode);
  515. GET_INPUT(second, 3);
  516. temp = (temp << 6) | static_cast<unsigned char>(decode);
  517. GET_INPUT(third, 2);
  518. temp = (temp << 6) | static_cast<unsigned char>(decode);
  519. GET_INPUT(fourth, 1);
  520. temp = (temp << 6) | static_cast<unsigned char>(decode);
  521. } else {
  522. // We really did have four good data bytes, so advance four
  523. // characters in the string.
  524. szsrc -= 4;
  525. src += 4;
  526. }
  527. // temp has 24 bits of input, so write that out as three bytes.
  528. if (destidx + 3 > szdest) return false;
  529. dest[destidx + 2] = static_cast<char>(temp);
  530. temp >>= 8;
  531. dest[destidx + 1] = static_cast<char>(temp);
  532. temp >>= 8;
  533. dest[destidx] = static_cast<char>(temp);
  534. destidx += 3;
  535. }
  536. } else {
  537. while (szsrc >= 4) {
  538. if (!src[0] || !src[1] || !src[2] ||
  539. ((temp = ((unsigned(unbase64[src[0]]) << 18) |
  540. (unsigned(unbase64[src[1]]) << 12) |
  541. (unsigned(unbase64[src[2]]) << 6) |
  542. (unsigned(unbase64[src[3]])))) &
  543. 0x80000000)) {
  544. GET_INPUT(first_no_dest, 4);
  545. GET_INPUT(second_no_dest, 3);
  546. GET_INPUT(third_no_dest, 2);
  547. GET_INPUT(fourth_no_dest, 1);
  548. } else {
  549. szsrc -= 4;
  550. src += 4;
  551. }
  552. destidx += 3;
  553. }
  554. }
  555. #undef GET_INPUT
  556. // if the loop terminated because we read a bad character, return
  557. // now.
  558. if (decode < 0 && ch != kPad64Equals && ch != kPad64Dot &&
  559. !y_absl::ascii_isspace(ch))
  560. return false;
  561. if (ch == kPad64Equals || ch == kPad64Dot) {
  562. // if we stopped by hitting an '=' or '.', un-read that character -- we'll
  563. // look at it again when we count to check for the proper number of
  564. // equals signs at the end.
  565. ++szsrc;
  566. --src;
  567. } else {
  568. // This loop consumes 1 input byte per iteration. It's used to
  569. // clean up the 0-3 input bytes remaining when the first, faster
  570. // loop finishes. 'temp' contains the data from 'state' input
  571. // characters read by the first loop.
  572. while (szsrc > 0) {
  573. --szsrc;
  574. ch = *src++;
  575. decode = unbase64[ch];
  576. if (decode < 0) {
  577. if (y_absl::ascii_isspace(ch)) {
  578. continue;
  579. } else if (ch == kPad64Equals || ch == kPad64Dot) {
  580. // back up one character; we'll read it again when we check
  581. // for the correct number of pad characters at the end.
  582. ++szsrc;
  583. --src;
  584. break;
  585. } else {
  586. return false;
  587. }
  588. }
  589. // Each input character gives us six bits of output.
  590. temp = (temp << 6) | static_cast<unsigned char>(decode);
  591. ++state;
  592. if (state == 4) {
  593. // If we've accumulated 24 bits of output, write that out as
  594. // three bytes.
  595. if (dest) {
  596. if (destidx + 3 > szdest) return false;
  597. dest[destidx + 2] = static_cast<char>(temp);
  598. temp >>= 8;
  599. dest[destidx + 1] = static_cast<char>(temp);
  600. temp >>= 8;
  601. dest[destidx] = static_cast<char>(temp);
  602. }
  603. destidx += 3;
  604. state = 0;
  605. temp = 0;
  606. }
  607. }
  608. }
  609. // Process the leftover data contained in 'temp' at the end of the input.
  610. int expected_equals = 0;
  611. switch (state) {
  612. case 0:
  613. // Nothing left over; output is a multiple of 3 bytes.
  614. break;
  615. case 1:
  616. // Bad input; we have 6 bits left over.
  617. return false;
  618. case 2:
  619. // Produce one more output byte from the 12 input bits we have left.
  620. if (dest) {
  621. if (destidx + 1 > szdest) return false;
  622. temp >>= 4;
  623. dest[destidx] = static_cast<char>(temp);
  624. }
  625. ++destidx;
  626. expected_equals = 2;
  627. break;
  628. case 3:
  629. // Produce two more output bytes from the 18 input bits we have left.
  630. if (dest) {
  631. if (destidx + 2 > szdest) return false;
  632. temp >>= 2;
  633. dest[destidx + 1] = static_cast<char>(temp);
  634. temp >>= 8;
  635. dest[destidx] = static_cast<char>(temp);
  636. }
  637. destidx += 2;
  638. expected_equals = 1;
  639. break;
  640. default:
  641. // state should have no other values at this point.
  642. Y_ABSL_RAW_LOG(FATAL, "This can't happen; base64 decoder state = %d",
  643. state);
  644. }
  645. // The remainder of the string should be all whitespace, mixed with
  646. // exactly 0 equals signs, or exactly 'expected_equals' equals
  647. // signs. (Always accepting 0 equals signs is an Abseil extension
  648. // not covered in the RFC, as is accepting dot as the pad character.)
  649. int equals = 0;
  650. while (szsrc > 0) {
  651. if (*src == kPad64Equals || *src == kPad64Dot)
  652. ++equals;
  653. else if (!y_absl::ascii_isspace(*src))
  654. return false;
  655. --szsrc;
  656. ++src;
  657. }
  658. const bool ok = (equals == 0 || equals == expected_equals);
  659. if (ok) *len = destidx;
  660. return ok;
  661. }
  662. // The arrays below map base64-escaped characters back to their original values.
  663. // For the inverse case, see k(WebSafe)Base64Chars in the internal
  664. // escaping.cc.
  665. // These arrays were generated by the following inversion code:
  666. // #include <sys/time.h>
  667. // #include <stdlib.h>
  668. // #include <string.h>
  669. // main()
  670. // {
  671. // static const char Base64[] =
  672. // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  673. // char* pos;
  674. // int idx, i, j;
  675. // printf(" ");
  676. // for (i = 0; i < 255; i += 8) {
  677. // for (j = i; j < i + 8; j++) {
  678. // pos = strchr(Base64, j);
  679. // if ((pos == nullptr) || (j == 0))
  680. // idx = -1;
  681. // else
  682. // idx = pos - Base64;
  683. // if (idx == -1)
  684. // printf(" %2d, ", idx);
  685. // else
  686. // printf(" %2d/*%c*/,", idx, j);
  687. // }
  688. // printf("\n ");
  689. // }
  690. // }
  691. //
  692. // where the value of "Base64[]" was replaced by one of k(WebSafe)Base64Chars
  693. // in the internal escaping.cc.
  694. /* clang-format off */
  695. constexpr signed char kUnBase64[] = {
  696. -1, -1, -1, -1, -1, -1, -1, -1,
  697. -1, -1, -1, -1, -1, -1, -1, -1,
  698. -1, -1, -1, -1, -1, -1, -1, -1,
  699. -1, -1, -1, -1, -1, -1, -1, -1,
  700. -1, -1, -1, -1, -1, -1, -1, -1,
  701. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  702. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  703. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  704. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  705. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  706. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  707. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  708. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  709. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  710. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  711. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  712. -1, -1, -1, -1, -1, -1, -1, -1,
  713. -1, -1, -1, -1, -1, -1, -1, -1,
  714. -1, -1, -1, -1, -1, -1, -1, -1,
  715. -1, -1, -1, -1, -1, -1, -1, -1,
  716. -1, -1, -1, -1, -1, -1, -1, -1,
  717. -1, -1, -1, -1, -1, -1, -1, -1,
  718. -1, -1, -1, -1, -1, -1, -1, -1,
  719. -1, -1, -1, -1, -1, -1, -1, -1,
  720. -1, -1, -1, -1, -1, -1, -1, -1,
  721. -1, -1, -1, -1, -1, -1, -1, -1,
  722. -1, -1, -1, -1, -1, -1, -1, -1,
  723. -1, -1, -1, -1, -1, -1, -1, -1,
  724. -1, -1, -1, -1, -1, -1, -1, -1,
  725. -1, -1, -1, -1, -1, -1, -1, -1,
  726. -1, -1, -1, -1, -1, -1, -1, -1,
  727. -1, -1, -1, -1, -1, -1, -1, -1
  728. };
  729. constexpr signed char kUnWebSafeBase64[] = {
  730. -1, -1, -1, -1, -1, -1, -1, -1,
  731. -1, -1, -1, -1, -1, -1, -1, -1,
  732. -1, -1, -1, -1, -1, -1, -1, -1,
  733. -1, -1, -1, -1, -1, -1, -1, -1,
  734. -1, -1, -1, -1, -1, -1, -1, -1,
  735. -1, -1, -1, -1, -1, 62/*-*/, -1, -1,
  736. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  737. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  738. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  739. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  740. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  741. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, 63/*_*/,
  742. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  743. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  744. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  745. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  746. -1, -1, -1, -1, -1, -1, -1, -1,
  747. -1, -1, -1, -1, -1, -1, -1, -1,
  748. -1, -1, -1, -1, -1, -1, -1, -1,
  749. -1, -1, -1, -1, -1, -1, -1, -1,
  750. -1, -1, -1, -1, -1, -1, -1, -1,
  751. -1, -1, -1, -1, -1, -1, -1, -1,
  752. -1, -1, -1, -1, -1, -1, -1, -1,
  753. -1, -1, -1, -1, -1, -1, -1, -1,
  754. -1, -1, -1, -1, -1, -1, -1, -1,
  755. -1, -1, -1, -1, -1, -1, -1, -1,
  756. -1, -1, -1, -1, -1, -1, -1, -1,
  757. -1, -1, -1, -1, -1, -1, -1, -1,
  758. -1, -1, -1, -1, -1, -1, -1, -1,
  759. -1, -1, -1, -1, -1, -1, -1, -1,
  760. -1, -1, -1, -1, -1, -1, -1, -1,
  761. -1, -1, -1, -1, -1, -1, -1, -1
  762. };
  763. /* clang-format on */
  764. template <typename String>
  765. bool Base64UnescapeInternal(y_absl::Nullable<const char*> src, size_t slen,
  766. y_absl::Nonnull<String*> dest,
  767. y_absl::Nonnull<const signed char*> unbase64) {
  768. // Determine the size of the output string. Base64 encodes every 3 bytes into
  769. // 4 characters. Any leftover chars are added directly for good measure.
  770. const size_t dest_len = 3 * (slen / 4) + (slen % 4);
  771. strings_internal::STLStringResizeUninitialized(dest, dest_len);
  772. // We are getting the destination buffer by getting the beginning of the
  773. // string and converting it into a char *.
  774. size_t len;
  775. const bool ok =
  776. Base64UnescapeInternal(src, slen, &(*dest)[0], dest_len, unbase64, &len);
  777. if (!ok) {
  778. dest->clear();
  779. return false;
  780. }
  781. // could be shorter if there was padding
  782. assert(len <= dest_len);
  783. dest->erase(len);
  784. return true;
  785. }
  786. /* clang-format off */
  787. constexpr char kHexValueLenient[256] = {
  788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  791. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
  792. 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
  793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  794. 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
  795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  804. };
  805. constexpr signed char kHexValueStrict[256] = {
  806. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  807. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  808. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  809. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, // '0'..'9'
  810. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 'A'..'F'
  811. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  812. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 'a'..'f'
  813. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  814. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  815. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  816. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  817. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  818. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  819. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  820. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  821. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  822. };
  823. /* clang-format on */
  824. // This is a templated function so that T can be either a char*
  825. // or a string. This works because we use the [] operator to access
  826. // individual characters at a time.
  827. template <typename T>
  828. void HexStringToBytesInternal(y_absl::Nullable<const char*> from, T to,
  829. size_t num) {
  830. for (size_t i = 0; i < num; i++) {
  831. to[i] = static_cast<char>(kHexValueLenient[from[i * 2] & 0xFF] << 4) +
  832. (kHexValueLenient[from[i * 2 + 1] & 0xFF]);
  833. }
  834. }
  835. // This is a templated function so that T can be either a char* or a
  836. // TString.
  837. template <typename T>
  838. void BytesToHexStringInternal(y_absl::Nullable<const unsigned char*> src, T dest,
  839. size_t num) {
  840. auto dest_ptr = &dest[0];
  841. for (auto src_ptr = src; src_ptr != (src + num); ++src_ptr, dest_ptr += 2) {
  842. const char* hex_p = &numbers_internal::kHexTable[*src_ptr * 2];
  843. std::copy(hex_p, hex_p + 2, dest_ptr);
  844. }
  845. }
  846. } // namespace
  847. // ----------------------------------------------------------------------
  848. // CUnescape()
  849. //
  850. // See CUnescapeInternal() for implementation details.
  851. // ----------------------------------------------------------------------
  852. bool CUnescape(y_absl::string_view source, y_absl::Nonnull<TString*> dest,
  853. y_absl::Nullable<TString*> error) {
  854. return CUnescapeInternal(source, kUnescapeNulls, dest, error);
  855. }
  856. TString CEscape(y_absl::string_view src) {
  857. TString dest;
  858. CEscapeAndAppendInternal(src, &dest);
  859. return dest;
  860. }
  861. TString CHexEscape(y_absl::string_view src) {
  862. return CEscapeInternal(src, true, false);
  863. }
  864. TString Utf8SafeCEscape(y_absl::string_view src) {
  865. return CEscapeInternal(src, false, true);
  866. }
  867. TString Utf8SafeCHexEscape(y_absl::string_view src) {
  868. return CEscapeInternal(src, true, true);
  869. }
  870. bool Base64Unescape(y_absl::string_view src, y_absl::Nonnull<TString*> dest) {
  871. return Base64UnescapeInternal(src.data(), src.size(), dest, kUnBase64);
  872. }
  873. bool WebSafeBase64Unescape(y_absl::string_view src,
  874. y_absl::Nonnull<TString*> dest) {
  875. return Base64UnescapeInternal(src.data(), src.size(), dest, kUnWebSafeBase64);
  876. }
  877. void Base64Escape(y_absl::string_view src, y_absl::Nonnull<TString*> dest) {
  878. strings_internal::Base64EscapeInternal(
  879. reinterpret_cast<const unsigned char*>(src.data()), src.size(), dest,
  880. true, strings_internal::kBase64Chars);
  881. }
  882. void WebSafeBase64Escape(y_absl::string_view src,
  883. y_absl::Nonnull<TString*> dest) {
  884. strings_internal::Base64EscapeInternal(
  885. reinterpret_cast<const unsigned char*>(src.data()), src.size(), dest,
  886. false, strings_internal::kWebSafeBase64Chars);
  887. }
  888. TString Base64Escape(y_absl::string_view src) {
  889. TString dest;
  890. strings_internal::Base64EscapeInternal(
  891. reinterpret_cast<const unsigned char*>(src.data()), src.size(), &dest,
  892. true, strings_internal::kBase64Chars);
  893. return dest;
  894. }
  895. TString WebSafeBase64Escape(y_absl::string_view src) {
  896. TString dest;
  897. strings_internal::Base64EscapeInternal(
  898. reinterpret_cast<const unsigned char*>(src.data()), src.size(), &dest,
  899. false, strings_internal::kWebSafeBase64Chars);
  900. return dest;
  901. }
  902. bool HexStringToBytes(y_absl::string_view hex,
  903. y_absl::Nonnull<TString*> bytes) {
  904. TString output;
  905. size_t num_bytes = hex.size() / 2;
  906. if (hex.size() != num_bytes * 2) {
  907. return false;
  908. }
  909. y_absl::strings_internal::STLStringResizeUninitialized(&output, num_bytes);
  910. auto hex_p = hex.cbegin();
  911. for (TString::iterator bin_p = output.begin(); bin_p != output.end();
  912. ++bin_p) {
  913. int h1 = y_absl::kHexValueStrict[static_cast<size_t>(*hex_p++)];
  914. int h2 = y_absl::kHexValueStrict[static_cast<size_t>(*hex_p++)];
  915. if (h1 == -1 || h2 == -1) {
  916. output.resize(static_cast<size_t>(bin_p - output.begin()));
  917. return false;
  918. }
  919. *bin_p = static_cast<char>((h1 << 4) + h2);
  920. }
  921. *bytes = std::move(output);
  922. return true;
  923. }
  924. TString HexStringToBytes(y_absl::string_view from) {
  925. TString result;
  926. const auto num = from.size() / 2;
  927. strings_internal::STLStringResizeUninitialized(&result, num);
  928. y_absl::HexStringToBytesInternal<TString&>(from.data(), result, num);
  929. return result;
  930. }
  931. TString BytesToHexString(y_absl::string_view from) {
  932. TString result;
  933. strings_internal::STLStringResizeUninitialized(&result, 2 * from.size());
  934. y_absl::BytesToHexStringInternal<TString&>(
  935. reinterpret_cast<const unsigned char*>(from.data()), result, from.size());
  936. return result;
  937. }
  938. Y_ABSL_NAMESPACE_END
  939. } // namespace y_absl