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