escaping.cc 35 KB

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