98b2813090662e88d668aefc4cefcef6e38796b7
[platform/upstream/curl.git] / lib / base64.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2004, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id$
22  ***************************************************************************/
23
24 /* Base64 encoding/decoding
25  *
26  * Test harnesses down the bottom - compile with -DTEST_ENCODE for
27  * a program that will read in raw data from stdin and write out
28  * a base64-encoded version to stdout, and the length returned by the
29  * encoding function to stderr. Compile with -DTEST_DECODE for a program that
30  * will go the other way.
31  *
32  * This code will break if int is smaller than 32 bits
33  */
34
35 #include "setup.h"
36
37 #include <stdlib.h>
38 #include <string.h>
39
40 #define _MPRINTF_REPLACE /* use our functions only */
41 #include <curl/mprintf.h>
42
43 #include "base64.h"
44 #include "memory.h"
45
46 /* include memdebug.h last */
47 #include "memdebug.h"
48
49
50 static void decodeQuantum(unsigned char *dest, const char *src)
51 {
52   unsigned int x = 0;
53   int i;
54   for(i = 0; i < 4; i++) {
55     if(src[i] >= 'A' && src[i] <= 'Z')
56       x = (x << 6) + (unsigned int)(src[i] - 'A' + 0);
57     else if(src[i] >= 'a' && src[i] <= 'z')
58       x = (x << 6) + (unsigned int)(src[i] - 'a' + 26);
59     else if(src[i] >= '0' && src[i] <= '9')
60       x = (x << 6) + (unsigned int)(src[i] - '0' + 52);
61     else if(src[i] == '+')
62       x = (x << 6) + 62;
63     else if(src[i] == '/')
64       x = (x << 6) + 63;
65     else if(src[i] == '=')
66       x = (x << 6);
67   }
68
69   dest[2] = (unsigned char)(x & 255);
70   x >>= 8;
71   dest[1] = (unsigned char)(x & 255);
72   x >>= 8;
73   dest[0] = (unsigned char)(x & 255);
74 }
75
76 /*
77  * Curl_base64_decode()
78  *
79  * Given a base64 string at src, decode it and return an allocated memory in
80  * the *outptr. Returns the length of the decoded data.
81  */
82 size_t Curl_base64_decode(const char *src, unsigned char **outptr)
83 {
84   int length = 0;
85   int equalsTerm = 0;
86   int i;
87   int numQuantums;
88   unsigned char lastQuantum[3];
89   size_t rawlen=0;
90   unsigned char *newstr;
91
92   *outptr = NULL;
93
94   while((src[length] != '=') && src[length])
95     length++;
96   /* A maximum of two = padding characters is allowed */
97   if(src[length] == '=') {
98     equalsTerm++;
99     if(src[length+equalsTerm] == '=')
100       equalsTerm++;
101   }
102   numQuantums = (length + equalsTerm) / 4;
103
104   /* Don't allocate a buffer if the decoded length is 0 */
105   if (numQuantums <= 0)
106     return 0;
107
108   rawlen = (numQuantums * 3) - equalsTerm;
109
110   /* The buffer must be large enough to make room for the last quantum
111   (which may be partially thrown out) and the zero terminator. */
112   newstr = malloc(rawlen+4);
113   if(!newstr)
114     return 0;
115
116   *outptr = newstr;
117
118   /* Decode all but the last quantum (which may not decode to a
119   multiple of 3 bytes) */
120   for(i = 0; i < numQuantums - 1; i++) {
121     decodeQuantum((unsigned char *)newstr, src);
122     newstr += 3; src += 4;
123   }
124
125   /* This final decode may actually read slightly past the end of the buffer
126   if the input string is missing pad bytes.  This will almost always be
127   harmless. */
128   decodeQuantum(lastQuantum, src);
129   for(i = 0; i < 3 - equalsTerm; i++)
130     newstr[i] = lastQuantum[i];
131
132   newstr[i] = 0; /* zero terminate */
133   return rawlen;
134 }
135
136 /* ---- Base64 Encoding --- */
137 static const char table64[]=
138   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
139
140 /*
141  * Curl_base64_encode()
142  *
143  * Returns the length of the newly created base64 string. The third argument
144  * is a pointer to an allocated area holding the base64 data. If something
145  * went wrong, -1 is returned.
146  *
147  */
148 size_t Curl_base64_encode(const char *inp, size_t insize, char **outptr)
149 {
150   unsigned char ibuf[3];
151   unsigned char obuf[4];
152   int i;
153   int inputparts;
154   char *output;
155   char *base64data;
156
157   char *indata = (char *)inp;
158
159   *outptr = NULL; /* set to NULL in case of failure before we reach the end */
160
161   if(0 == insize)
162     insize = strlen(indata);
163
164   base64data = output = (char*)malloc(insize*4/3+4);
165   if(NULL == output)
166     return 0;
167
168   while(insize > 0) {
169     for (i = inputparts = 0; i < 3; i++) {
170       if(insize > 0) {
171         inputparts++;
172         ibuf[i] = *indata;
173         indata++;
174         insize--;
175       }
176       else
177         ibuf[i] = 0;
178     }
179
180     obuf [0] = (ibuf [0] & 0xFC) >> 2;
181     obuf [1] = ((ibuf [0] & 0x03) << 4) | ((ibuf [1] & 0xF0) >> 4);
182     obuf [2] = ((ibuf [1] & 0x0F) << 2) | ((ibuf [2] & 0xC0) >> 6);
183     obuf [3] = ibuf [2] & 0x3F;
184
185     switch(inputparts) {
186     case 1: /* only one byte read */
187       snprintf(output, 5, "%c%c==",
188                table64[obuf[0]],
189                table64[obuf[1]]);
190       break;
191     case 2: /* two bytes read */
192       snprintf(output, 5, "%c%c%c=",
193                table64[obuf[0]],
194                table64[obuf[1]],
195                table64[obuf[2]]);
196       break;
197     default:
198       snprintf(output, 5, "%c%c%c%c",
199                table64[obuf[0]],
200                table64[obuf[1]],
201                table64[obuf[2]],
202                table64[obuf[3]] );
203       break;
204     }
205     output += 4;
206   }
207   *output=0;
208   *outptr = base64data; /* make it return the actual data memory */
209
210   return strlen(base64data); /* return the length of the new data */
211 }
212 /* ---- End of Base64 Encoding ---- */
213
214 /************* TEST HARNESS STUFF ****************/
215
216
217 #ifdef TEST_ENCODE
218 /* encoding test harness. Read in standard input and write out the length
219  * returned by Curl_base64_encode, followed by the base64'd data itself
220  */
221 #include <stdio.h>
222
223 #define TEST_NEED_SUCK
224 void *suck(int *);
225
226 int main(int argc, char **argv, char **envp)
227 {
228   char *base64;
229   size_t base64Len;
230   unsigned char *data;
231   int dataLen;
232
233   data = (unsigned char *)suck(&dataLen);
234   base64Len = Curl_base64_encode(data, dataLen, &base64);
235
236   fprintf(stderr, "%d\n", base64Len);
237   fprintf(stdout, "%s",   base64);
238
239   free(base64); free(data);
240   return 0;
241 }
242 #endif
243
244 #ifdef TEST_DECODE
245 /* decoding test harness. Read in a base64 string from stdin and write out the
246  * length returned by Curl_base64_decode, followed by the decoded data itself
247  *
248  * gcc -DTEST_DECODE base64.c -o base64 mprintf.o memdebug.o
249  */
250 #include <stdio.h>
251
252 #define TEST_NEED_SUCK
253 void *suck(int *);
254
255 int main(int argc, char **argv, char **envp)
256 {
257   char *base64;
258   int base64Len;
259   unsigned char *data;
260   int dataLen;
261   int i, j;
262
263   base64 = (char *)suck(&base64Len);
264   data = (unsigned char *)malloc(base64Len * 3/4 + 8);
265   dataLen = Curl_base64_decode(base64, data);
266
267   fprintf(stderr, "%d\n", dataLen);
268
269   for(i=0; i < dataLen; i+=0x10) {
270     printf("0x%02x: ", i);
271     for(j=0; j < 0x10; j++)
272       if((j+i) < dataLen)
273         printf("%02x ", data[i+j]);
274       else
275         printf("   ");
276
277     printf(" | ");
278
279     for(j=0; j < 0x10; j++)
280       if((j+i) < dataLen)
281         printf("%c", isgraph(data[i+j])?data[i+j]:'.');
282       else
283         break;
284     puts("");
285   }
286
287   free(base64); free(data);
288   return 0;
289 }
290 #endif
291
292 #ifdef TEST_NEED_SUCK
293 /* this function 'sucks' in as much as possible from stdin */
294 void *suck(int *lenptr)
295 {
296   int cursize = 8192;
297   unsigned char *buf = NULL;
298   int lastread;
299   int len = 0;
300
301   do {
302     cursize *= 2;
303     buf = (unsigned char *)realloc(buf, cursize);
304     memset(buf + len, 0, cursize - len);
305     lastread = fread(buf + len, 1, cursize - len, stdin);
306     len += lastread;
307   } while(!feof(stdin));
308
309   lenptr[0] = len;
310   return (void *)buf;
311 }
312 #endif