fix compiler warning
[platform/upstream/curl.git] / lib / base64.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2007, 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 "urldata.h" /* for the SessionHandle definition */
44 #include "easyif.h"  /* for Curl_convert_... prototypes */
45 #include "base64.h"
46 #include "memory.h"
47
48 /* include memdebug.h last */
49 #include "memdebug.h"
50
51 /* ---- Base64 Encoding/Decoding Table --- */
52 static const char table64[]=
53   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
54
55 static void decodeQuantum(unsigned char *dest, const char *src)
56 {
57   unsigned int x = 0;
58   int i;
59   char *found;
60
61   for(i = 0; i < 4; i++) {
62     if((found = strchr(table64, src[i])) != 0)
63       x = (x << 6) + (unsigned int)(found - table64);
64     else if(src[i] == '=')
65       x = (x << 6);
66   }
67
68   dest[2] = (unsigned char)(x & 255);
69   x >>= 8;
70   dest[1] = (unsigned char)(x & 255);
71   x >>= 8;
72   dest[0] = (unsigned char)(x & 255);
73 }
74
75 /*
76  * Curl_base64_decode()
77  *
78  * Given a base64 string at src, decode it and return an allocated memory in
79  * the *outptr. Returns the length of the decoded data.
80  */
81 size_t Curl_base64_decode(const char *src, unsigned char **outptr)
82 {
83   int length = 0;
84   int equalsTerm = 0;
85   int i;
86   int numQuantums;
87   unsigned char lastQuantum[3];
88   size_t rawlen=0;
89   unsigned char *newstr;
90
91   *outptr = NULL;
92
93   while((src[length] != '=') && src[length])
94     length++;
95   /* A maximum of two = padding characters is allowed */
96   if(src[length] == '=') {
97     equalsTerm++;
98     if(src[length+equalsTerm] == '=')
99       equalsTerm++;
100   }
101   numQuantums = (length + equalsTerm) / 4;
102
103   /* Don't allocate a buffer if the decoded length is 0 */
104   if (numQuantums <= 0)
105     return 0;
106
107   rawlen = (numQuantums * 3) - equalsTerm;
108
109   /* The buffer must be large enough to make room for the last quantum
110   (which may be partially thrown out) and the zero terminator. */
111   newstr = malloc(rawlen+4);
112   if(!newstr)
113     return 0;
114
115   *outptr = newstr;
116
117   /* Decode all but the last quantum (which may not decode to a
118   multiple of 3 bytes) */
119   for(i = 0; i < numQuantums - 1; i++) {
120     decodeQuantum((unsigned char *)newstr, src);
121     newstr += 3; src += 4;
122   }
123
124   /* This final decode may actually read slightly past the end of the buffer
125   if the input string is missing pad bytes.  This will almost always be
126   harmless. */
127   decodeQuantum(lastQuantum, src);
128   for(i = 0; i < 3 - equalsTerm; i++)
129     newstr[i] = lastQuantum[i];
130
131   newstr[i] = 0; /* zero terminate */
132   return rawlen;
133 }
134
135 /*
136  * Curl_base64_encode()
137  *
138  * Returns the length of the newly created base64 string. The third argument
139  * is a pointer to an allocated area holding the base64 data. If something
140  * went wrong, -1 is returned.
141  *
142  */
143 size_t Curl_base64_encode(struct SessionHandle *data,
144                           const char *inp, size_t insize, char **outptr)
145 {
146   unsigned char ibuf[3];
147   unsigned char obuf[4];
148   int i;
149   int inputparts;
150   char *output;
151   char *base64data;
152 #ifdef CURL_DOES_CONVERSIONS
153   char *convbuf = NULL;
154 #endif
155
156   char *indata = (char *)inp;
157
158   *outptr = NULL; /* set to NULL in case of failure before we reach the end */
159
160   if(0 == insize)
161     insize = strlen(indata);
162
163   base64data = output = (char*)malloc(insize*4/3+4);
164   if(NULL == output)
165     return 0;
166
167 #ifdef CURL_DOES_CONVERSIONS
168   /*
169    * The base64 data needs to be created using the network encoding
170    * not the host encoding.  And we can't change the actual input
171    * so we copy it to a buffer, translate it, and use that instead.
172    */
173   if(data) {
174     convbuf = (char*)malloc(insize);
175     if(!convbuf) {
176       free(output);
177       return 0;
178     }
179     memcpy(convbuf, indata, insize);
180     if(CURLE_OK != Curl_convert_to_network(data, convbuf, insize)) {
181       free(convbuf);
182       free(output);
183       return 0;
184     }
185     indata = convbuf; /* switch to the converted buffer */
186   }
187 #else
188   (void)data;
189 #endif
190
191   while(insize > 0) {
192     for (i = inputparts = 0; i < 3; i++) {
193       if(insize > 0) {
194         inputparts++;
195         ibuf[i] = *indata;
196         indata++;
197         insize--;
198       }
199       else
200         ibuf[i] = 0;
201     }
202
203     obuf[0] = (unsigned char)  ((ibuf[0] & 0xFC) >> 2);
204     obuf[1] = (unsigned char) (((ibuf[0] & 0x03) << 4) | \
205                                ((ibuf[1] & 0xF0) >> 4));
206     obuf[2] = (unsigned char) (((ibuf[1] & 0x0F) << 2) | \
207                                ((ibuf[2] & 0xC0) >> 6));
208     obuf[3] = (unsigned char)   (ibuf[2] & 0x3F);
209
210     switch(inputparts) {
211     case 1: /* only one byte read */
212       snprintf(output, 5, "%c%c==",
213                table64[obuf[0]],
214                table64[obuf[1]]);
215       break;
216     case 2: /* two bytes read */
217       snprintf(output, 5, "%c%c%c=",
218                table64[obuf[0]],
219                table64[obuf[1]],
220                table64[obuf[2]]);
221       break;
222     default:
223       snprintf(output, 5, "%c%c%c%c",
224                table64[obuf[0]],
225                table64[obuf[1]],
226                table64[obuf[2]],
227                table64[obuf[3]] );
228       break;
229     }
230     output += 4;
231   }
232   *output=0;
233   *outptr = base64data; /* make it return the actual data memory */
234
235 #ifdef CURL_DOES_CONVERSIONS
236   if(data)
237     free(convbuf);
238 #endif
239   return strlen(base64data); /* return the length of the new data */
240 }
241 /* ---- End of Base64 Encoding ---- */
242
243 /************* TEST HARNESS STUFF ****************/
244
245
246 #ifdef TEST_ENCODE
247 /* encoding test harness. Read in standard input and write out the length
248  * returned by Curl_base64_encode, followed by the base64'd data itself
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   size_t base64Len;
259   unsigned char *data;
260   int dataLen;
261   struct SessionHandle *handle = NULL;
262
263 #ifdef CURL_DOES_CONVERSIONS
264   /* get a Curl handle so Curl_base64_encode can translate properly */
265   handle = curl_easy_init();
266   if(handle == NULL) {
267     fprintf(stderr, "Error: curl_easy_init failed\n");
268     return 0;
269   }
270 #endif
271   data = (unsigned char *)suck(&dataLen);
272   base64Len = Curl_base64_encode(handle, data, dataLen, &base64);
273
274   fprintf(stderr, "%d\n", base64Len);
275   fprintf(stdout, "%s\n", base64);
276
277   free(base64); free(data);
278 #ifdef CURL_DOES_CONVERSIONS
279   curl_easy_cleanup(handle);
280 #endif
281   return 0;
282 }
283 #endif
284
285 #ifdef TEST_DECODE
286 /* decoding test harness. Read in a base64 string from stdin and write out the
287  * length returned by Curl_base64_decode, followed by the decoded data itself
288  *
289  * gcc -DTEST_DECODE base64.c -o base64 mprintf.o memdebug.o
290  */
291 #include <stdio.h>
292
293 #define TEST_NEED_SUCK
294 void *suck(int *);
295
296 int main(int argc, char **argv, char **envp)
297 {
298   char *base64;
299   int base64Len;
300   unsigned char *data;
301   int dataLen;
302   int i, j;
303 #ifdef CURL_DOES_CONVERSIONS
304   /* get a Curl handle so main can translate properly */
305   struct SessionHandle *handle = curl_easy_init();
306   if(handle == NULL) {
307     fprintf(stderr, "Error: curl_easy_init failed\n");
308     return 0;
309   }
310 #endif
311
312   base64 = (char *)suck(&base64Len);
313   dataLen = Curl_base64_decode(base64, &data);
314
315   fprintf(stderr, "%d\n", dataLen);
316
317   for(i=0; i < dataLen; i+=0x10) {
318     printf("0x%02x: ", i);
319     for(j=0; j < 0x10; j++)
320       if((j+i) < dataLen)
321         printf("%02x ", data[i+j]);
322       else
323         printf("   ");
324
325     printf(" | ");
326
327     for(j=0; j < 0x10; j++)
328       if((j+i) < dataLen) {
329 #ifdef CURL_DOES_CONVERSIONS
330         if(CURLE_OK !=
331              Curl_convert_from_network(handle, &data[i+j], (size_t)1))
332           data[i+j] = '.';
333 #endif /* CURL_DOES_CONVERSIONS */
334         printf("%c", ISGRAPH(data[i+j])?data[i+j]:'.');
335       } else
336         break;
337     puts("");
338   }
339
340 #ifdef CURL_DOES_CONVERSIONS
341   curl_easy_cleanup(handle);
342 #endif
343   free(base64); free(data);
344   return 0;
345 }
346 #endif
347
348 #ifdef TEST_NEED_SUCK
349 /* this function 'sucks' in as much as possible from stdin */
350 void *suck(int *lenptr)
351 {
352   int cursize = 8192;
353   unsigned char *buf = NULL;
354   int lastread;
355   int len = 0;
356
357   do {
358     cursize *= 2;
359     buf = (unsigned char *)realloc(buf, cursize);
360     memset(buf + len, 0, cursize - len);
361     lastread = fread(buf + len, 1, cursize - len, stdin);
362     len += lastread;
363   } while(!feof(stdin));
364
365   lenptr[0] = len;
366   return (void *)buf;
367 }
368 #endif