1 // Copyright 2019 Google Inc. All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 #include "tools/windows/converter_exe/escaping.h"
30
31 #include <assert.h>
32
33 #define kApb kAsciiPropertyBits
34
35 const unsigned char kAsciiPropertyBits[256] = {
36 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, // 0x00
37 0x40, 0x68, 0x48, 0x48, 0x48, 0x48, 0x40, 0x40,
38 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, // 0x10
39 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
40 0x28, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, // 0x20
41 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
42 0x84, 0x84, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
43 0x10, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x05, // 0x40
44 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
45 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, // 0x50
46 0x05, 0x05, 0x05, 0x10, 0x10, 0x10, 0x10, 0x10,
47 0x10, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x05, // 0x60
48 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
49 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, // 0x70
50 0x05, 0x05, 0x05, 0x10, 0x10, 0x10, 0x10, 0x40,
51 };
52
53 // Use !! to suppress the warning C4800 of forcing 'int' to 'bool'.
ascii_isspace(unsigned char c)54 static inline bool ascii_isspace(unsigned char c) { return !!(kApb[c] & 0x08); }
55
56 ///////////////////////////////////
57 // scoped_array
58 ///////////////////////////////////
59 // scoped_array<C> is like scoped_ptr<C>, except that the caller must allocate
60 // with new [] and the destructor deletes objects with delete [].
61 //
62 // As with scoped_ptr<C>, a scoped_array<C> either points to an object
63 // or is NULL. A scoped_array<C> owns the object that it points to.
64 // scoped_array<T> is thread-compatible, and once you index into it,
65 // the returned objects have only the threadsafety guarantees of T.
66 //
67 // Size: sizeof(scoped_array<C>) == sizeof(C*)
68 template <class C>
69 class scoped_array {
70 public:
71
72 // The element type
73 typedef C element_type;
74
75 // Constructor. Defaults to intializing with NULL.
76 // There is no way to create an uninitialized scoped_array.
77 // The input parameter must be allocated with new [].
scoped_array(C * p=NULL)78 explicit scoped_array(C* p = NULL) : array_(p) { }
79
80 // Destructor. If there is a C object, delete it.
81 // We don't need to test ptr_ == NULL because C++ does that for us.
~scoped_array()82 ~scoped_array() {
83 enum { type_must_be_complete = sizeof(C) };
84 delete[] array_;
85 }
86
87 // Reset. Deletes the current owned object, if any.
88 // Then takes ownership of a new object, if given.
89 // this->reset(this->get()) works.
reset(C * p=NULL)90 void reset(C* p = NULL) {
91 if (p != array_) {
92 enum { type_must_be_complete = sizeof(C) };
93 delete[] array_;
94 array_ = p;
95 }
96 }
97
98 // Get one element of the current object.
99 // Will assert() if there is no current object, or index i is negative.
operator [](std::ptrdiff_t i) const100 C& operator[](std::ptrdiff_t i) const {
101 assert(i >= 0);
102 assert(array_ != NULL);
103 return array_[i];
104 }
105
106 // Get a pointer to the zeroth element of the current object.
107 // If there is no current object, return NULL.
get() const108 C* get() const {
109 return array_;
110 }
111
112 // Comparison operators.
113 // These return whether a scoped_array and a raw pointer refer to
114 // the same array, not just to two different but equal arrays.
operator ==(const C * p) const115 bool operator==(const C* p) const { return array_ == p; }
operator !=(const C * p) const116 bool operator!=(const C* p) const { return array_ != p; }
117
118 // Swap two scoped arrays.
swap(scoped_array & p2)119 void swap(scoped_array& p2) {
120 C* tmp = array_;
121 array_ = p2.array_;
122 p2.array_ = tmp;
123 }
124
125 // Release an array.
126 // The return value is the current pointer held by this object.
127 // If this object holds a NULL pointer, the return value is NULL.
128 // After this operation, this object will hold a NULL pointer,
129 // and will not own the object any more.
release()130 C* release() {
131 C* retVal = array_;
132 array_ = NULL;
133 return retVal;
134 }
135
136 private:
137 C* array_;
138
139 // Forbid comparison of different scoped_array types.
140 template <class C2> bool operator==(scoped_array<C2> const& p2) const;
141 template <class C2> bool operator!=(scoped_array<C2> const& p2) const;
142
143 // Disallow evil constructors
144 scoped_array(const scoped_array&);
145 void operator=(const scoped_array&);
146 };
147
148
149 ///////////////////////////////////
150 // Escape methods
151 ///////////////////////////////////
152
153 namespace strings {
154
155 // Return a mutable char* pointing to a string's internal buffer,
156 // which may not be null-terminated. Writing through this pointer will
157 // modify the string.
158 //
159 // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
160 // next call to a string method that invalidates iterators.
161 //
162 // As of 2006-04, there is no standard-blessed way of getting a
163 // mutable reference to a string's internal buffer. However, issue 530
164 // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530)
165 // proposes this as the method. According to Matt Austern, this should
166 // already work on all current implementations.
string_as_array(string * str)167 inline char* string_as_array(string* str) {
168 // DO NOT USE const_cast<char*>(str->data())! See the unittest for why.
169 return str->empty() ? NULL : &*str->begin();
170 }
171
CalculateBase64EscapedLen(int input_len,bool do_padding)172 int CalculateBase64EscapedLen(int input_len, bool do_padding) {
173 // these formulae were copied from comments that used to go with the base64
174 // encoding functions
175 int intermediate_result = 8 * input_len + 5;
176 assert(intermediate_result > 0); // make sure we didn't overflow
177 int len = intermediate_result / 6;
178 if (do_padding) len = ((len + 3) / 4) * 4;
179 return len;
180 }
181
182 // Base64Escape does padding, so this calculation includes padding.
CalculateBase64EscapedLen(int input_len)183 int CalculateBase64EscapedLen(int input_len) {
184 return CalculateBase64EscapedLen(input_len, true);
185 }
186
187 // ----------------------------------------------------------------------
188 // int Base64Unescape() - base64 decoder
189 // int Base64Escape() - base64 encoder
190 // int WebSafeBase64Unescape() - Google's variation of base64 decoder
191 // int WebSafeBase64Escape() - Google's variation of base64 encoder
192 //
193 // Check out
194 // http://www.cis.ohio-state.edu/htbin/rfc/rfc2045.html for formal
195 // description, but what we care about is that...
196 // Take the encoded stuff in groups of 4 characters and turn each
197 // character into a code 0 to 63 thus:
198 // A-Z map to 0 to 25
199 // a-z map to 26 to 51
200 // 0-9 map to 52 to 61
201 // +(- for WebSafe) maps to 62
202 // /(_ for WebSafe) maps to 63
203 // There will be four numbers, all less than 64 which can be represented
204 // by a 6 digit binary number (aaaaaa, bbbbbb, cccccc, dddddd respectively).
205 // Arrange the 6 digit binary numbers into three bytes as such:
206 // aaaaaabb bbbbcccc ccdddddd
207 // Equals signs (one or two) are used at the end of the encoded block to
208 // indicate that the text was not an integer multiple of three bytes long.
209 // ----------------------------------------------------------------------
210
Base64UnescapeInternal(const char * src,int szsrc,char * dest,int szdest,const signed char * unbase64)211 int Base64UnescapeInternal(const char *src, int szsrc,
212 char *dest, int szdest,
213 const signed char* unbase64) {
214 static const char kPad64 = '=';
215
216 int decode = 0;
217 int destidx = 0;
218 int state = 0;
219 unsigned int ch = 0;
220 unsigned int temp = 0;
221
222 // The GET_INPUT macro gets the next input character, skipping
223 // over any whitespace, and stopping when we reach the end of the
224 // string or when we read any non-data character. The arguments are
225 // an arbitrary identifier (used as a label for goto) and the number
226 // of data bytes that must remain in the input to avoid aborting the
227 // loop.
228 #define GET_INPUT(label, remain) \
229 label: \
230 --szsrc; \
231 ch = *src++; \
232 decode = unbase64[ch]; \
233 if (decode < 0) { \
234 if (ascii_isspace((char)ch) && szsrc >= remain) \
235 goto label; \
236 state = 4 - remain; \
237 break; \
238 }
239
240 // if dest is null, we're just checking to see if it's legal input
241 // rather than producing output. (I suspect this could just be done
242 // with a regexp...). We duplicate the loop so this test can be
243 // outside it instead of in every iteration.
244
245 if (dest) {
246 // This loop consumes 4 input bytes and produces 3 output bytes
247 // per iteration. We can't know at the start that there is enough
248 // data left in the string for a full iteration, so the loop may
249 // break out in the middle; if so 'state' will be set to the
250 // number of input bytes read.
251
252 while (szsrc >= 4) {
253 // We'll start by optimistically assuming that the next four
254 // bytes of the string (src[0..3]) are four good data bytes
255 // (that is, no nulls, whitespace, padding chars, or illegal
256 // chars). We need to test src[0..2] for nulls individually
257 // before constructing temp to preserve the property that we
258 // never read past a null in the string (no matter how long
259 // szsrc claims the string is).
260
261 if (!src[0] || !src[1] || !src[2] ||
262 (temp = ((unbase64[static_cast<int>(src[0])] << 18) |
263 (unbase64[static_cast<int>(src[1])] << 12) |
264 (unbase64[static_cast<int>(src[2])] << 6) |
265 (unbase64[static_cast<int>(src[3])]))) & 0x80000000) {
266 // Iff any of those four characters was bad (null, illegal,
267 // whitespace, padding), then temp's high bit will be set
268 // (because unbase64[] is -1 for all bad characters).
269 //
270 // We'll back up and resort to the slower decoder, which knows
271 // how to handle those cases.
272
273 GET_INPUT(first, 4);
274 temp = decode;
275 GET_INPUT(second, 3);
276 temp = (temp << 6) | decode;
277 GET_INPUT(third, 2);
278 temp = (temp << 6) | decode;
279 GET_INPUT(fourth, 1);
280 temp = (temp << 6) | decode;
281 } else {
282 // We really did have four good data bytes, so advance four
283 // characters in the string.
284
285 szsrc -= 4;
286 src += 4;
287 decode = -1;
288 ch = '\0';
289 }
290
291 // temp has 24 bits of input, so write that out as three bytes.
292
293 if (destidx+3 > szdest) return -1;
294 dest[destidx+2] = (char)temp;
295 temp >>= 8;
296 dest[destidx+1] = (char)temp;
297 temp >>= 8;
298 dest[destidx] = (char)temp;
299 destidx += 3;
300 }
301 } else {
302 while (szsrc >= 4) {
303 if (!src[0] || !src[1] || !src[2] ||
304 (temp = ((unbase64[static_cast<int>(src[0])] << 18) |
305 (unbase64[static_cast<int>(src[1])] << 12) |
306 (unbase64[static_cast<int>(src[2])] << 6) |
307 (unbase64[static_cast<int>(src[3])]))) & 0x80000000) {
308 GET_INPUT(first_no_dest, 4);
309 GET_INPUT(second_no_dest, 3);
310 GET_INPUT(third_no_dest, 2);
311 GET_INPUT(fourth_no_dest, 1);
312 } else {
313 szsrc -= 4;
314 src += 4;
315 decode = -1;
316 ch = '\0';
317 }
318 destidx += 3;
319 }
320 }
321
322 #undef GET_INPUT
323
324 // if the loop terminated because we read a bad character, return
325 // now.
326 if (decode < 0 && ch != '\0' && ch != kPad64 && !ascii_isspace((char)ch))
327 return -1;
328
329 if (ch == kPad64) {
330 // if we stopped by hitting an '=', un-read that character -- we'll
331 // look at it again when we count to check for the proper number of
332 // equals signs at the end.
333 ++szsrc;
334 --src;
335 } else {
336 // This loop consumes 1 input byte per iteration. It's used to
337 // clean up the 0-3 input bytes remaining when the first, faster
338 // loop finishes. 'temp' contains the data from 'state' input
339 // characters read by the first loop.
340 while (szsrc > 0) {
341 --szsrc;
342 ch = *src++;
343 decode = unbase64[ch];
344 if (decode < 0) {
345 if (ascii_isspace((char)ch)) {
346 continue;
347 } else if (ch == '\0') {
348 break;
349 } else if (ch == kPad64) {
350 // back up one character; we'll read it again when we check
351 // for the correct number of equals signs at the end.
352 ++szsrc;
353 --src;
354 break;
355 } else {
356 return -1;
357 }
358 }
359
360 // Each input character gives us six bits of output.
361 temp = (temp << 6) | decode;
362 ++state;
363 if (state == 4) {
364 // If we've accumulated 24 bits of output, write that out as
365 // three bytes.
366 if (dest) {
367 if (destidx+3 > szdest) return -1;
368 dest[destidx+2] = (char)temp;
369 temp >>= 8;
370 dest[destidx+1] = (char)temp;
371 temp >>= 8;
372 dest[destidx] = (char)temp;
373 }
374 destidx += 3;
375 state = 0;
376 temp = 0;
377 }
378 }
379 }
380
381 // Process the leftover data contained in 'temp' at the end of the input.
382 int expected_equals = 0;
383 switch (state) {
384 case 0:
385 // Nothing left over; output is a multiple of 3 bytes.
386 break;
387
388 case 1:
389 // Bad input; we have 6 bits left over.
390 return -1;
391
392 case 2:
393 // Produce one more output byte from the 12 input bits we have left.
394 if (dest) {
395 if (destidx+1 > szdest) return -1;
396 temp >>= 4;
397 dest[destidx] = (char)temp;
398 }
399 ++destidx;
400 expected_equals = 2;
401 break;
402
403 case 3:
404 // Produce two more output bytes from the 18 input bits we have left.
405 if (dest) {
406 if (destidx+2 > szdest) return -1;
407 temp >>= 2;
408 dest[destidx+1] = (char)temp;
409 temp >>= 8;
410 dest[destidx] = (char)temp;
411 }
412 destidx += 2;
413 expected_equals = 1;
414 break;
415
416 default:
417 // state should have no other values at this point.
418 fprintf(stdout, "This can't happen; base64 decoder state = %d", state);
419 }
420
421 // The remainder of the string should be all whitespace, mixed with
422 // exactly 0 equals signs, or exactly 'expected_equals' equals
423 // signs. (Always accepting 0 equals signs is a google extension
424 // not covered in the RFC.)
425
426 int equals = 0;
427 while (szsrc > 0 && *src) {
428 if (*src == kPad64)
429 ++equals;
430 else if (!ascii_isspace(*src))
431 return -1;
432 --szsrc;
433 ++src;
434 }
435
436 return (equals == 0 || equals == expected_equals) ? destidx : -1;
437 }
438
Base64Unescape(const char * src,int szsrc,char * dest,int szdest)439 int Base64Unescape(const char *src, int szsrc, char *dest, int szdest) {
440 static const signed char UnBase64[] = {
441 -1, -1, -1, -1, -1, -1, -1, -1,
442 -1, -1, -1, -1, -1, -1, -1, -1,
443 -1, -1, -1, -1, -1, -1, -1, -1,
444 -1, -1, -1, -1, -1, -1, -1, -1,
445 -1, -1, -1, -1, -1, -1, -1, -1,
446 -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
447 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
448 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
449 -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
450 7/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
451 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
452 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
453 -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
454 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
455 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
456 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
457 -1, -1, -1, -1, -1, -1, -1, -1,
458 -1, -1, -1, -1, -1, -1, -1, -1,
459 -1, -1, -1, -1, -1, -1, -1, -1,
460 -1, -1, -1, -1, -1, -1, -1, -1,
461 -1, -1, -1, -1, -1, -1, -1, -1,
462 -1, -1, -1, -1, -1, -1, -1, -1,
463 -1, -1, -1, -1, -1, -1, -1, -1,
464 -1, -1, -1, -1, -1, -1, -1, -1,
465 -1, -1, -1, -1, -1, -1, -1, -1,
466 -1, -1, -1, -1, -1, -1, -1, -1,
467 -1, -1, -1, -1, -1, -1, -1, -1,
468 -1, -1, -1, -1, -1, -1, -1, -1,
469 -1, -1, -1, -1, -1, -1, -1, -1,
470 -1, -1, -1, -1, -1, -1, -1, -1,
471 -1, -1, -1, -1, -1, -1, -1, -1,
472 -1, -1, -1, -1, -1, -1, -1, -1
473 };
474 // The above array was generated by the following code
475 // #include <sys/time.h>
476 // #include <stdlib.h>
477 // #include <string.h>
478 // main()
479 // {
480 // static const char Base64[] =
481 // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
482 // char *pos;
483 // int idx, i, j;
484 // printf(" ");
485 // for (i = 0; i < 255; i += 8) {
486 // for (j = i; j < i + 8; j++) {
487 // pos = strchr(Base64, j);
488 // if ((pos == NULL) || (j == 0))
489 // idx = -1;
490 // else
491 // idx = pos - Base64;
492 // if (idx == -1)
493 // printf(" %2d, ", idx);
494 // else
495 // printf(" %2d/*%c*/,", idx, j);
496 // }
497 // printf("\n ");
498 // }
499 // }
500
501 return Base64UnescapeInternal(src, szsrc, dest, szdest, UnBase64);
502 }
503
Base64Unescape(const char * src,int slen,string * dest)504 bool Base64Unescape(const char *src, int slen, string* dest) {
505 // Determine the size of the output string. Base64 encodes every 3 bytes into
506 // 4 characters. any leftover chars are added directly for good measure.
507 // This is documented in the base64 RFC: http://www.ietf.org/rfc/rfc3548.txt
508 const int dest_len = 3 * (slen / 4) + (slen % 4);
509
510 dest->resize(dest_len);
511
512 // We are getting the destination buffer by getting the beginning of the
513 // string and converting it into a char *.
514 const int len = Base64Unescape(src, slen,
515 string_as_array(dest), dest->size());
516 if (len < 0) {
517 return false;
518 }
519
520 // could be shorter if there was padding
521 assert(len <= dest_len);
522 dest->resize(len);
523
524 return true;
525 }
526
527 // Base64Escape
528 //
529 // NOTE: We have to use an unsigned type for src because code built
530 // in the the /google tree treats characters as signed unless
531 // otherwised specified.
532 //
533 // TODO(who?): Move this function to use the char* type for "src"
Base64EscapeInternal(const unsigned char * src,int szsrc,char * dest,int szdest,const char * base64,bool do_padding)534 int Base64EscapeInternal(const unsigned char *src, int szsrc,
535 char *dest, int szdest, const char *base64,
536 bool do_padding) {
537 static const char kPad64 = '=';
538
539 if (szsrc <= 0) return 0;
540
541 char *cur_dest = dest;
542 const unsigned char *cur_src = src;
543
544 // Three bytes of data encodes to four characters of cyphertext.
545 // So we can pump through three-byte chunks atomically.
546 while (szsrc > 2) { /* keep going until we have less than 24 bits */
547 if ((szdest -= 4) < 0) return 0;
548 cur_dest[0] = base64[cur_src[0] >> 2];
549 cur_dest[1] = base64[((cur_src[0] & 0x03) << 4) + (cur_src[1] >> 4)];
550 cur_dest[2] = base64[((cur_src[1] & 0x0f) << 2) + (cur_src[2] >> 6)];
551 cur_dest[3] = base64[cur_src[2] & 0x3f];
552
553 cur_dest += 4;
554 cur_src += 3;
555 szsrc -= 3;
556 }
557
558 /* now deal with the tail (<=2 bytes) */
559 switch (szsrc) {
560 case 0:
561 // Nothing left; nothing more to do.
562 break;
563 case 1:
564 // One byte left: this encodes to two characters, and (optionally)
565 // two pad characters to round out the four-character cypherblock.
566 if ((szdest -= 2) < 0) return 0;
567 cur_dest[0] = base64[cur_src[0] >> 2];
568 cur_dest[1] = base64[(cur_src[0] & 0x03) << 4];
569 cur_dest += 2;
570 if (do_padding) {
571 if ((szdest -= 2) < 0) return 0;
572 cur_dest[0] = kPad64;
573 cur_dest[1] = kPad64;
574 cur_dest += 2;
575 }
576 break;
577 case 2:
578 // Two bytes left: this encodes to three characters, and (optionally)
579 // one pad character to round out the four-character cypherblock.
580 if ((szdest -= 3) < 0) return 0;
581 cur_dest[0] = base64[cur_src[0] >> 2];
582 cur_dest[1] = base64[((cur_src[0] & 0x03) << 4) + (cur_src[1] >> 4)];
583 cur_dest[2] = base64[(cur_src[1] & 0x0f) << 2];
584 cur_dest += 3;
585 if (do_padding) {
586 if ((szdest -= 1) < 0) return 0;
587 cur_dest[0] = kPad64;
588 cur_dest += 1;
589 }
590 break;
591 default:
592 // Should not be reached: blocks of 3 bytes are handled
593 // in the while loop before this switch statement.
594 fprintf(stderr, "Logic problem? szsrc = %d", szsrc);
595 assert(false);
596 break;
597 }
598 return (cur_dest - dest);
599 }
600
601 static const char kBase64Chars[] =
602 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
603
604 static const char kWebSafeBase64Chars[] =
605 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
606
Base64Escape(const unsigned char * src,int szsrc,char * dest,int szdest)607 int Base64Escape(const unsigned char *src, int szsrc, char *dest, int szdest) {
608 return Base64EscapeInternal(src, szsrc, dest, szdest, kBase64Chars, true);
609 }
610
Base64Escape(const unsigned char * src,int szsrc,string * dest,bool do_padding)611 void Base64Escape(const unsigned char *src, int szsrc,
612 string* dest, bool do_padding) {
613 const int max_escaped_size =
614 CalculateBase64EscapedLen(szsrc, do_padding);
615 dest->clear();
616 dest->resize(max_escaped_size + 1, '\0');
617 const int escaped_len = Base64EscapeInternal(src, szsrc,
618 &*dest->begin(), dest->size(),
619 kBase64Chars,
620 do_padding);
621 assert(max_escaped_size <= escaped_len);
622 dest->resize(escaped_len);
623 }
624
Base64Escape(const string & src,string * dest)625 void Base64Escape(const string& src, string* dest) {
626 Base64Escape(reinterpret_cast<const unsigned char*>(src.c_str()),
627 src.size(), dest, true);
628 }
629
630 ////////////////////////////////////////////////////
631 // WebSafe methods
632 ////////////////////////////////////////////////////
633
WebSafeBase64Unescape(const char * src,int szsrc,char * dest,int szdest)634 int WebSafeBase64Unescape(const char *src, int szsrc, char *dest, int szdest) {
635 static const signed char UnBase64[] = {
636 -1, -1, -1, -1, -1, -1, -1, -1,
637 -1, -1, -1, -1, -1, -1, -1, -1,
638 -1, -1, -1, -1, -1, -1, -1, -1,
639 -1, -1, -1, -1, -1, -1, -1, -1,
640 -1, -1, -1, -1, -1, -1, -1, -1,
641 -1, -1, -1, -1, -1, 62/*-*/, -1, -1,
642 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
643 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
644 -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
645 7/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
646 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
647 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, 63/*_*/,
648 -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
649 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
650 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
651 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
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, -1, -1, -1, -1, -1,
658 -1, -1, -1, -1, -1, -1, -1, -1,
659 -1, -1, -1, -1, -1, -1, -1, -1,
660 -1, -1, -1, -1, -1, -1, -1, -1,
661 -1, -1, -1, -1, -1, -1, -1, -1,
662 -1, -1, -1, -1, -1, -1, -1, -1,
663 -1, -1, -1, -1, -1, -1, -1, -1,
664 -1, -1, -1, -1, -1, -1, -1, -1,
665 -1, -1, -1, -1, -1, -1, -1, -1,
666 -1, -1, -1, -1, -1, -1, -1, -1,
667 -1, -1, -1, -1, -1, -1, -1, -1
668 };
669 // The above array was generated by the following code
670 // #include <sys/time.h>
671 // #include <stdlib.h>
672 // #include <string.h>
673 // main()
674 // {
675 // static const char Base64[] =
676 // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
677 // char *pos;
678 // int idx, i, j;
679 // printf(" ");
680 // for (i = 0; i < 255; i += 8) {
681 // for (j = i; j < i + 8; j++) {
682 // pos = strchr(Base64, j);
683 // if ((pos == NULL) || (j == 0))
684 // idx = -1;
685 // else
686 // idx = pos - Base64;
687 // if (idx == -1)
688 // printf(" %2d, ", idx);
689 // else
690 // printf(" %2d/*%c*/,", idx, j);
691 // }
692 // printf("\n ");
693 // }
694 // }
695
696 return Base64UnescapeInternal(src, szsrc, dest, szdest, UnBase64);
697 }
698
WebSafeBase64Unescape(const char * src,int slen,string * dest)699 bool WebSafeBase64Unescape(const char *src, int slen, string* dest) {
700 int dest_len = 3 * (slen / 4) + (slen % 4);
701 dest->clear();
702 dest->resize(dest_len);
703 int len = WebSafeBase64Unescape(src, slen, &*dest->begin(), dest->size());
704 if (len < 0) {
705 dest->clear();
706 return false;
707 }
708 // could be shorter if there was padding
709 assert(len <= dest_len);
710 dest->resize(len);
711 return true;
712 }
713
WebSafeBase64Unescape(const string & src,string * dest)714 bool WebSafeBase64Unescape(const string& src, string* dest) {
715 return WebSafeBase64Unescape(src.data(), src.size(), dest);
716 }
717
WebSafeBase64Escape(const unsigned char * src,int szsrc,char * dest,int szdest,bool do_padding)718 int WebSafeBase64Escape(const unsigned char *src, int szsrc, char *dest,
719 int szdest, bool do_padding) {
720 return Base64EscapeInternal(src, szsrc, dest, szdest,
721 kWebSafeBase64Chars, do_padding);
722 }
723
WebSafeBase64Escape(const unsigned char * src,int szsrc,string * dest,bool do_padding)724 void WebSafeBase64Escape(const unsigned char *src, int szsrc,
725 string *dest, bool do_padding) {
726 const int max_escaped_size =
727 CalculateBase64EscapedLen(szsrc, do_padding);
728 dest->clear();
729 dest->resize(max_escaped_size + 1, '\0');
730 const int escaped_len = Base64EscapeInternal(src, szsrc,
731 &*dest->begin(), dest->size(),
732 kWebSafeBase64Chars,
733 do_padding);
734 assert(max_escaped_size <= escaped_len);
735 dest->resize(escaped_len);
736 }
737
WebSafeBase64EscapeInternal(const string & src,string * dest,bool do_padding)738 void WebSafeBase64EscapeInternal(const string& src,
739 string* dest,
740 bool do_padding) {
741 int encoded_len = CalculateBase64EscapedLen(src.size());
742 scoped_array<char> buf(new char[encoded_len]);
743 int len = WebSafeBase64Escape(reinterpret_cast<const unsigned char*>(src.c_str()),
744 src.size(), buf.get(),
745 encoded_len, do_padding);
746 dest->assign(buf.get(), len);
747 }
748
WebSafeBase64Escape(const string & src,string * dest)749 void WebSafeBase64Escape(const string& src, string* dest) {
750 WebSafeBase64EscapeInternal(src, dest, false);
751 }
752
WebSafeBase64EscapeWithPadding(const string & src,string * dest)753 void WebSafeBase64EscapeWithPadding(const string& src, string* dest) {
754 WebSafeBase64EscapeInternal(src, dest, true);
755 }
756
757 } // namespace strings
758