escaping.cc 34 KB

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