93e4166b48e9a2dcd798de94fba92f3bdf5c9c6f
[openssl.git] / crypto / evp / bio_b64.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57
58 #include <stdio.h>
59 #include <errno.h>
60 #include "internal/cryptlib.h"
61 #include <openssl/buffer.h>
62 #include <openssl/evp.h>
63
64 static int b64_write(BIO *h, const char *buf, int num);
65 static int b64_read(BIO *h, char *buf, int size);
66 static int b64_puts(BIO *h, const char *str);
67 /*
68  * static int b64_gets(BIO *h, char *str, int size);
69  */
70 static long b64_ctrl(BIO *h, int cmd, long arg1, void *arg2);
71 static int b64_new(BIO *h);
72 static int b64_free(BIO *data);
73 static long b64_callback_ctrl(BIO *h, int cmd, bio_info_cb *fp);
74 #define B64_BLOCK_SIZE  1024
75 #define B64_BLOCK_SIZE2 768
76 #define B64_NONE        0
77 #define B64_ENCODE      1
78 #define B64_DECODE      2
79
80 typedef struct b64_struct {
81     /*
82      * BIO *bio; moved to the BIO structure
83      */
84     int buf_len;
85     int buf_off;
86     int tmp_len;                /* used to find the start when decoding */
87     int tmp_nl;                 /* If true, scan until '\n' */
88     int encode;
89     int start;                  /* have we started decoding yet? */
90     int cont;                   /* <= 0 when finished */
91     EVP_ENCODE_CTX *base64;
92     char buf[EVP_ENCODE_LENGTH(B64_BLOCK_SIZE) + 10];
93     char tmp[B64_BLOCK_SIZE];
94 } BIO_B64_CTX;
95
96 static const BIO_METHOD methods_b64 = {
97     BIO_TYPE_BASE64, "base64 encoding",
98     b64_write,
99     b64_read,
100     b64_puts,
101     NULL,                       /* b64_gets, */
102     b64_ctrl,
103     b64_new,
104     b64_free,
105     b64_callback_ctrl,
106 };
107
108 const BIO_METHOD *BIO_f_base64(void)
109 {
110     return (&methods_b64);
111 }
112
113 static int b64_new(BIO *bi)
114 {
115     BIO_B64_CTX *ctx;
116
117     ctx = OPENSSL_zalloc(sizeof(*ctx));
118     if (ctx == NULL)
119         return (0);
120
121     ctx->cont = 1;
122     ctx->start = 1;
123     ctx->base64 = EVP_ENCODE_CTX_new();
124     bi->init = 1;
125     bi->ptr = (char *)ctx;
126     bi->flags = 0;
127     bi->num = 0;
128     return (1);
129 }
130
131 static int b64_free(BIO *a)
132 {
133     if (a == NULL)
134         return (0);
135     EVP_ENCODE_CTX_free(((BIO_B64_CTX *)a->ptr)->base64);
136     OPENSSL_free(a->ptr);
137     a->ptr = NULL;
138     a->init = 0;
139     a->flags = 0;
140     return (1);
141 }
142
143 static int b64_read(BIO *b, char *out, int outl)
144 {
145     int ret = 0, i, ii, j, k, x, n, num, ret_code = 0;
146     BIO_B64_CTX *ctx;
147     unsigned char *p, *q;
148
149     if (out == NULL)
150         return (0);
151     ctx = (BIO_B64_CTX *)b->ptr;
152
153     if ((ctx == NULL) || (b->next_bio == NULL))
154         return (0);
155
156     BIO_clear_retry_flags(b);
157
158     if (ctx->encode != B64_DECODE) {
159         ctx->encode = B64_DECODE;
160         ctx->buf_len = 0;
161         ctx->buf_off = 0;
162         ctx->tmp_len = 0;
163         EVP_DecodeInit(ctx->base64);
164     }
165
166     /* First check if there are bytes decoded/encoded */
167     if (ctx->buf_len > 0) {
168         OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
169         i = ctx->buf_len - ctx->buf_off;
170         if (i > outl)
171             i = outl;
172         OPENSSL_assert(ctx->buf_off + i < (int)sizeof(ctx->buf));
173         memcpy(out, &(ctx->buf[ctx->buf_off]), i);
174         ret = i;
175         out += i;
176         outl -= i;
177         ctx->buf_off += i;
178         if (ctx->buf_len == ctx->buf_off) {
179             ctx->buf_len = 0;
180             ctx->buf_off = 0;
181         }
182     }
183
184     /*
185      * At this point, we have room of outl bytes and an empty buffer, so we
186      * should read in some more.
187      */
188
189     ret_code = 0;
190     while (outl > 0) {
191         if (ctx->cont <= 0)
192             break;
193
194         i = BIO_read(b->next_bio, &(ctx->tmp[ctx->tmp_len]),
195                      B64_BLOCK_SIZE - ctx->tmp_len);
196
197         if (i <= 0) {
198             ret_code = i;
199
200             /* Should we continue next time we are called? */
201             if (!BIO_should_retry(b->next_bio)) {
202                 ctx->cont = i;
203                 /* If buffer empty break */
204                 if (ctx->tmp_len == 0)
205                     break;
206                 /* Fall through and process what we have */
207                 else
208                     i = 0;
209             }
210             /* else we retry and add more data to buffer */
211             else
212                 break;
213         }
214         i += ctx->tmp_len;
215         ctx->tmp_len = i;
216
217         /*
218          * We need to scan, a line at a time until we have a valid line if we
219          * are starting.
220          */
221         if (ctx->start && (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL)) {
222             /* ctx->start=1; */
223             ctx->tmp_len = 0;
224         } else if (ctx->start) {
225             q = p = (unsigned char *)ctx->tmp;
226             num = 0;
227             for (j = 0; j < i; j++) {
228                 if (*(q++) != '\n')
229                     continue;
230
231                 /*
232                  * due to a previous very long line, we need to keep on
233                  * scanning for a '\n' before we even start looking for
234                  * base64 encoded stuff.
235                  */
236                 if (ctx->tmp_nl) {
237                     p = q;
238                     ctx->tmp_nl = 0;
239                     continue;
240                 }
241
242                 k = EVP_DecodeUpdate(ctx->base64,
243                                      (unsigned char *)ctx->buf,
244                                      &num, p, q - p);
245                 if ((k <= 0) && (num == 0) && (ctx->start))
246                     EVP_DecodeInit(ctx->base64);
247                 else {
248                     if (p != (unsigned char *)
249                         &(ctx->tmp[0])) {
250                         i -= (p - (unsigned char *)
251                               &(ctx->tmp[0]));
252                         for (x = 0; x < i; x++)
253                             ctx->tmp[x] = p[x];
254                     }
255                     EVP_DecodeInit(ctx->base64);
256                     ctx->start = 0;
257                     break;
258                 }
259                 p = q;
260             }
261
262             /* we fell off the end without starting */
263             if ((j == i) && (num == 0)) {
264                 /*
265                  * Is this is one long chunk?, if so, keep on reading until a
266                  * new line.
267                  */
268                 if (p == (unsigned char *)&(ctx->tmp[0])) {
269                     /* Check buffer full */
270                     if (i == B64_BLOCK_SIZE) {
271                         ctx->tmp_nl = 1;
272                         ctx->tmp_len = 0;
273                     }
274                 } else if (p != q) { /* finished on a '\n' */
275                     n = q - p;
276                     for (ii = 0; ii < n; ii++)
277                         ctx->tmp[ii] = p[ii];
278                     ctx->tmp_len = n;
279                 }
280                 /* else finished on a '\n' */
281                 continue;
282             } else {
283                 ctx->tmp_len = 0;
284             }
285         } else if ((i < B64_BLOCK_SIZE) && (ctx->cont > 0)) {
286             /*
287              * If buffer isn't full and we can retry then restart to read in
288              * more data.
289              */
290             continue;
291         }
292
293         if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) {
294             int z, jj;
295
296             jj = i & ~3;        /* process per 4 */
297             z = EVP_DecodeBlock((unsigned char *)ctx->buf,
298                                 (unsigned char *)ctx->tmp, jj);
299             if (jj > 2) {
300                 if (ctx->tmp[jj - 1] == '=') {
301                     z--;
302                     if (ctx->tmp[jj - 2] == '=')
303                         z--;
304                 }
305             }
306             /*
307              * z is now number of output bytes and jj is the number consumed
308              */
309             if (jj != i) {
310                 memmove(ctx->tmp, &ctx->tmp[jj], i - jj);
311                 ctx->tmp_len = i - jj;
312             }
313             ctx->buf_len = 0;
314             if (z > 0) {
315                 ctx->buf_len = z;
316             }
317             i = z;
318         } else {
319             i = EVP_DecodeUpdate(ctx->base64,
320                                  (unsigned char *)ctx->buf, &ctx->buf_len,
321                                  (unsigned char *)ctx->tmp, i);
322             ctx->tmp_len = 0;
323         }
324         ctx->buf_off = 0;
325         if (i < 0) {
326             ret_code = 0;
327             ctx->buf_len = 0;
328             break;
329         }
330
331         if (ctx->buf_len <= outl)
332             i = ctx->buf_len;
333         else
334             i = outl;
335
336         memcpy(out, ctx->buf, i);
337         ret += i;
338         ctx->buf_off = i;
339         if (ctx->buf_off == ctx->buf_len) {
340             ctx->buf_len = 0;
341             ctx->buf_off = 0;
342         }
343         outl -= i;
344         out += i;
345     }
346     /* BIO_clear_retry_flags(b); */
347     BIO_copy_next_retry(b);
348     return ((ret == 0) ? ret_code : ret);
349 }
350
351 static int b64_write(BIO *b, const char *in, int inl)
352 {
353     int ret = 0;
354     int n;
355     int i;
356     BIO_B64_CTX *ctx;
357
358     ctx = (BIO_B64_CTX *)b->ptr;
359     BIO_clear_retry_flags(b);
360
361     if (ctx->encode != B64_ENCODE) {
362         ctx->encode = B64_ENCODE;
363         ctx->buf_len = 0;
364         ctx->buf_off = 0;
365         ctx->tmp_len = 0;
366         EVP_EncodeInit(ctx->base64);
367     }
368
369     OPENSSL_assert(ctx->buf_off < (int)sizeof(ctx->buf));
370     OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
371     OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
372     n = ctx->buf_len - ctx->buf_off;
373     while (n > 0) {
374         i = BIO_write(b->next_bio, &(ctx->buf[ctx->buf_off]), n);
375         if (i <= 0) {
376             BIO_copy_next_retry(b);
377             return (i);
378         }
379         OPENSSL_assert(i <= n);
380         ctx->buf_off += i;
381         OPENSSL_assert(ctx->buf_off <= (int)sizeof(ctx->buf));
382         OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
383         n -= i;
384     }
385     /* at this point all pending data has been written */
386     ctx->buf_off = 0;
387     ctx->buf_len = 0;
388
389     if ((in == NULL) || (inl <= 0))
390         return (0);
391
392     while (inl > 0) {
393         n = (inl > B64_BLOCK_SIZE) ? B64_BLOCK_SIZE : inl;
394
395         if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) {
396             if (ctx->tmp_len > 0) {
397                 OPENSSL_assert(ctx->tmp_len <= 3);
398                 n = 3 - ctx->tmp_len;
399                 /*
400                  * There's a theoretical possibility for this
401                  */
402                 if (n > inl)
403                     n = inl;
404                 memcpy(&(ctx->tmp[ctx->tmp_len]), in, n);
405                 ctx->tmp_len += n;
406                 ret += n;
407                 if (ctx->tmp_len < 3)
408                     break;
409                 ctx->buf_len =
410                     EVP_EncodeBlock((unsigned char *)ctx->buf,
411                                     (unsigned char *)ctx->tmp, ctx->tmp_len);
412                 OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
413                 OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
414                 /*
415                  * Since we're now done using the temporary buffer, the
416                  * length should be 0'd
417                  */
418                 ctx->tmp_len = 0;
419             } else {
420                 if (n < 3) {
421                     memcpy(ctx->tmp, in, n);
422                     ctx->tmp_len = n;
423                     ret += n;
424                     break;
425                 }
426                 n -= n % 3;
427                 ctx->buf_len =
428                     EVP_EncodeBlock((unsigned char *)ctx->buf,
429                                     (const unsigned char *)in, n);
430                 OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
431                 OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
432                 ret += n;
433             }
434         } else {
435             EVP_EncodeUpdate(ctx->base64,
436                              (unsigned char *)ctx->buf, &ctx->buf_len,
437                              (unsigned char *)in, n);
438             OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
439             OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
440             ret += n;
441         }
442         inl -= n;
443         in += n;
444
445         ctx->buf_off = 0;
446         n = ctx->buf_len;
447         while (n > 0) {
448             i = BIO_write(b->next_bio, &(ctx->buf[ctx->buf_off]), n);
449             if (i <= 0) {
450                 BIO_copy_next_retry(b);
451                 return ((ret == 0) ? i : ret);
452             }
453             OPENSSL_assert(i <= n);
454             n -= i;
455             ctx->buf_off += i;
456             OPENSSL_assert(ctx->buf_off <= (int)sizeof(ctx->buf));
457             OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
458         }
459         ctx->buf_len = 0;
460         ctx->buf_off = 0;
461     }
462     return (ret);
463 }
464
465 static long b64_ctrl(BIO *b, int cmd, long num, void *ptr)
466 {
467     BIO_B64_CTX *ctx;
468     long ret = 1;
469     int i;
470
471     ctx = (BIO_B64_CTX *)b->ptr;
472
473     switch (cmd) {
474     case BIO_CTRL_RESET:
475         ctx->cont = 1;
476         ctx->start = 1;
477         ctx->encode = B64_NONE;
478         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
479         break;
480     case BIO_CTRL_EOF:         /* More to read */
481         if (ctx->cont <= 0)
482             ret = 1;
483         else
484             ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
485         break;
486     case BIO_CTRL_WPENDING:    /* More to write in buffer */
487         OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
488         ret = ctx->buf_len - ctx->buf_off;
489         if ((ret == 0) && (ctx->encode != B64_NONE)
490             && (EVP_ENCODE_CTX_num(ctx->base64) != 0))
491             ret = 1;
492         else if (ret <= 0)
493             ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
494         break;
495     case BIO_CTRL_PENDING:     /* More to read in buffer */
496         OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
497         ret = ctx->buf_len - ctx->buf_off;
498         if (ret <= 0)
499             ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
500         break;
501     case BIO_CTRL_FLUSH:
502         /* do a final write */
503  again:
504         while (ctx->buf_len != ctx->buf_off) {
505             i = b64_write(b, NULL, 0);
506             if (i < 0)
507                 return i;
508         }
509         if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) {
510             if (ctx->tmp_len != 0) {
511                 ctx->buf_len = EVP_EncodeBlock((unsigned char *)ctx->buf,
512                                                (unsigned char *)ctx->tmp,
513                                                ctx->tmp_len);
514                 ctx->buf_off = 0;
515                 ctx->tmp_len = 0;
516                 goto again;
517             }
518         } else if (ctx->encode != B64_NONE
519                    && EVP_ENCODE_CTX_num(ctx->base64) != 0) {
520             ctx->buf_off = 0;
521             EVP_EncodeFinal(ctx->base64,
522                             (unsigned char *)ctx->buf, &(ctx->buf_len));
523             /* push out the bytes */
524             goto again;
525         }
526         /* Finally flush the underlying BIO */
527         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
528         break;
529
530     case BIO_C_DO_STATE_MACHINE:
531         BIO_clear_retry_flags(b);
532         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
533         BIO_copy_next_retry(b);
534         break;
535
536     case BIO_CTRL_DUP:
537         break;
538     case BIO_CTRL_INFO:
539     case BIO_CTRL_GET:
540     case BIO_CTRL_SET:
541     default:
542         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
543         break;
544     }
545     return (ret);
546 }
547
548 static long b64_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
549 {
550     long ret = 1;
551
552     if (b->next_bio == NULL)
553         return (0);
554     switch (cmd) {
555     default:
556         ret = BIO_callback_ctrl(b->next_bio, cmd, fp);
557         break;
558     }
559     return (ret);
560 }
561
562 static int b64_puts(BIO *b, const char *str)
563 {
564     return b64_write(b, str, strlen(str));
565 }