Use "" not <> for internal/ includes
[openssl.git] / crypto / evp / bio_b64.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <errno.h>
12 #include "internal/cryptlib.h"
13 #include <openssl/buffer.h>
14 #include <openssl/evp.h>
15 #include "internal/bio.h"
16
17 static int b64_write(BIO *h, const char *buf, int num);
18 static int b64_read(BIO *h, char *buf, int size);
19 static int b64_puts(BIO *h, const char *str);
20 static long b64_ctrl(BIO *h, int cmd, long arg1, void *arg2);
21 static int b64_new(BIO *h);
22 static int b64_free(BIO *data);
23 static long b64_callback_ctrl(BIO *h, int cmd, bio_info_cb *fp);
24 #define B64_BLOCK_SIZE  1024
25 #define B64_BLOCK_SIZE2 768
26 #define B64_NONE        0
27 #define B64_ENCODE      1
28 #define B64_DECODE      2
29
30 typedef struct b64_struct {
31     /*
32      * BIO *bio; moved to the BIO structure
33      */
34     int buf_len;
35     int buf_off;
36     int tmp_len;                /* used to find the start when decoding */
37     int tmp_nl;                 /* If true, scan until '\n' */
38     int encode;
39     int start;                  /* have we started decoding yet? */
40     int cont;                   /* <= 0 when finished */
41     EVP_ENCODE_CTX *base64;
42     char buf[EVP_ENCODE_LENGTH(B64_BLOCK_SIZE) + 10];
43     char tmp[B64_BLOCK_SIZE];
44 } BIO_B64_CTX;
45
46 static const BIO_METHOD methods_b64 = {
47     BIO_TYPE_BASE64, "base64 encoding",
48     /* TODO: Convert to new style write function */
49     bwrite_conv,
50     b64_write,
51     /* TODO: Convert to new style read function */
52     bread_conv,
53     b64_read,
54     b64_puts,
55     NULL,                       /* b64_gets, */
56     b64_ctrl,
57     b64_new,
58     b64_free,
59     b64_callback_ctrl,
60 };
61
62
63 const BIO_METHOD *BIO_f_base64(void)
64 {
65     return &methods_b64;
66 }
67
68 static int b64_new(BIO *bi)
69 {
70     BIO_B64_CTX *ctx;
71
72     ctx = OPENSSL_zalloc(sizeof(*ctx));
73     if (ctx == NULL)
74         return 0;
75
76     ctx->cont = 1;
77     ctx->start = 1;
78     ctx->base64 = EVP_ENCODE_CTX_new();
79     if (ctx->base64 == NULL) {
80         OPENSSL_free(ctx);
81         return 0;
82     }
83
84     BIO_set_data(bi, ctx);
85     BIO_set_init(bi, 1);
86
87     return 1;
88 }
89
90 static int b64_free(BIO *a)
91 {
92     BIO_B64_CTX *ctx;
93     if (a == NULL)
94         return 0;
95
96     ctx = BIO_get_data(a);
97     if (ctx == NULL)
98         return 0;
99
100     EVP_ENCODE_CTX_free(ctx->base64);
101     OPENSSL_free(ctx);
102     BIO_set_data(a, NULL);
103     BIO_set_init(a, 0);
104
105     return 1;
106 }
107
108 static int b64_read(BIO *b, char *out, int outl)
109 {
110     int ret = 0, i, ii, j, k, x, n, num, ret_code = 0;
111     BIO_B64_CTX *ctx;
112     unsigned char *p, *q;
113     BIO *next;
114
115     if (out == NULL)
116         return (0);
117     ctx = (BIO_B64_CTX *)BIO_get_data(b);
118
119     next = BIO_next(b);
120     if ((ctx == NULL) || (next == NULL))
121         return 0;
122
123     BIO_clear_retry_flags(b);
124
125     if (ctx->encode != B64_DECODE) {
126         ctx->encode = B64_DECODE;
127         ctx->buf_len = 0;
128         ctx->buf_off = 0;
129         ctx->tmp_len = 0;
130         EVP_DecodeInit(ctx->base64);
131     }
132
133     /* First check if there are bytes decoded/encoded */
134     if (ctx->buf_len > 0) {
135         OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
136         i = ctx->buf_len - ctx->buf_off;
137         if (i > outl)
138             i = outl;
139         OPENSSL_assert(ctx->buf_off + i < (int)sizeof(ctx->buf));
140         memcpy(out, &(ctx->buf[ctx->buf_off]), i);
141         ret = i;
142         out += i;
143         outl -= i;
144         ctx->buf_off += i;
145         if (ctx->buf_len == ctx->buf_off) {
146             ctx->buf_len = 0;
147             ctx->buf_off = 0;
148         }
149     }
150
151     /*
152      * At this point, we have room of outl bytes and an empty buffer, so we
153      * should read in some more.
154      */
155
156     ret_code = 0;
157     while (outl > 0) {
158         if (ctx->cont <= 0)
159             break;
160
161         i = BIO_read(next, &(ctx->tmp[ctx->tmp_len]),
162                      B64_BLOCK_SIZE - ctx->tmp_len);
163
164         if (i <= 0) {
165             ret_code = i;
166
167             /* Should we continue next time we are called? */
168             if (!BIO_should_retry(next)) {
169                 ctx->cont = i;
170                 /* If buffer empty break */
171                 if (ctx->tmp_len == 0)
172                     break;
173                 /* Fall through and process what we have */
174                 else
175                     i = 0;
176             }
177             /* else we retry and add more data to buffer */
178             else
179                 break;
180         }
181         i += ctx->tmp_len;
182         ctx->tmp_len = i;
183
184         /*
185          * We need to scan, a line at a time until we have a valid line if we
186          * are starting.
187          */
188         if (ctx->start && (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL)) {
189             /* ctx->start=1; */
190             ctx->tmp_len = 0;
191         } else if (ctx->start) {
192             q = p = (unsigned char *)ctx->tmp;
193             num = 0;
194             for (j = 0; j < i; j++) {
195                 if (*(q++) != '\n')
196                     continue;
197
198                 /*
199                  * due to a previous very long line, we need to keep on
200                  * scanning for a '\n' before we even start looking for
201                  * base64 encoded stuff.
202                  */
203                 if (ctx->tmp_nl) {
204                     p = q;
205                     ctx->tmp_nl = 0;
206                     continue;
207                 }
208
209                 k = EVP_DecodeUpdate(ctx->base64,
210                                      (unsigned char *)ctx->buf,
211                                      &num, p, q - p);
212                 if ((k <= 0) && (num == 0) && (ctx->start))
213                     EVP_DecodeInit(ctx->base64);
214                 else {
215                     if (p != (unsigned char *)
216                         &(ctx->tmp[0])) {
217                         i -= (p - (unsigned char *)
218                               &(ctx->tmp[0]));
219                         for (x = 0; x < i; x++)
220                             ctx->tmp[x] = p[x];
221                     }
222                     EVP_DecodeInit(ctx->base64);
223                     ctx->start = 0;
224                     break;
225                 }
226                 p = q;
227             }
228
229             /* we fell off the end without starting */
230             if ((j == i) && (num == 0)) {
231                 /*
232                  * Is this is one long chunk?, if so, keep on reading until a
233                  * new line.
234                  */
235                 if (p == (unsigned char *)&(ctx->tmp[0])) {
236                     /* Check buffer full */
237                     if (i == B64_BLOCK_SIZE) {
238                         ctx->tmp_nl = 1;
239                         ctx->tmp_len = 0;
240                     }
241                 } else if (p != q) { /* finished on a '\n' */
242                     n = q - p;
243                     for (ii = 0; ii < n; ii++)
244                         ctx->tmp[ii] = p[ii];
245                     ctx->tmp_len = n;
246                 }
247                 /* else finished on a '\n' */
248                 continue;
249             } else {
250                 ctx->tmp_len = 0;
251             }
252         } else if ((i < B64_BLOCK_SIZE) && (ctx->cont > 0)) {
253             /*
254              * If buffer isn't full and we can retry then restart to read in
255              * more data.
256              */
257             continue;
258         }
259
260         if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) {
261             int z, jj;
262
263             jj = i & ~3;        /* process per 4 */
264             z = EVP_DecodeBlock((unsigned char *)ctx->buf,
265                                 (unsigned char *)ctx->tmp, jj);
266             if (jj > 2) {
267                 if (ctx->tmp[jj - 1] == '=') {
268                     z--;
269                     if (ctx->tmp[jj - 2] == '=')
270                         z--;
271                 }
272             }
273             /*
274              * z is now number of output bytes and jj is the number consumed
275              */
276             if (jj != i) {
277                 memmove(ctx->tmp, &ctx->tmp[jj], i - jj);
278                 ctx->tmp_len = i - jj;
279             }
280             ctx->buf_len = 0;
281             if (z > 0) {
282                 ctx->buf_len = z;
283             }
284             i = z;
285         } else {
286             i = EVP_DecodeUpdate(ctx->base64,
287                                  (unsigned char *)ctx->buf, &ctx->buf_len,
288                                  (unsigned char *)ctx->tmp, i);
289             ctx->tmp_len = 0;
290         }
291         ctx->buf_off = 0;
292         if (i < 0) {
293             ret_code = 0;
294             ctx->buf_len = 0;
295             break;
296         }
297
298         if (ctx->buf_len <= outl)
299             i = ctx->buf_len;
300         else
301             i = outl;
302
303         memcpy(out, ctx->buf, i);
304         ret += i;
305         ctx->buf_off = i;
306         if (ctx->buf_off == ctx->buf_len) {
307             ctx->buf_len = 0;
308             ctx->buf_off = 0;
309         }
310         outl -= i;
311         out += i;
312     }
313     /* BIO_clear_retry_flags(b); */
314     BIO_copy_next_retry(b);
315     return ((ret == 0) ? ret_code : ret);
316 }
317
318 static int b64_write(BIO *b, const char *in, int inl)
319 {
320     int ret = 0;
321     int n;
322     int i;
323     BIO_B64_CTX *ctx;
324     BIO *next;
325
326     ctx = (BIO_B64_CTX *)BIO_get_data(b);
327     next = BIO_next(b);
328     if ((ctx == NULL) || (next == NULL))
329         return 0;
330
331     BIO_clear_retry_flags(b);
332
333     if (ctx->encode != B64_ENCODE) {
334         ctx->encode = B64_ENCODE;
335         ctx->buf_len = 0;
336         ctx->buf_off = 0;
337         ctx->tmp_len = 0;
338         EVP_EncodeInit(ctx->base64);
339     }
340
341     OPENSSL_assert(ctx->buf_off < (int)sizeof(ctx->buf));
342     OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
343     OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
344     n = ctx->buf_len - ctx->buf_off;
345     while (n > 0) {
346         i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n);
347         if (i <= 0) {
348             BIO_copy_next_retry(b);
349             return (i);
350         }
351         OPENSSL_assert(i <= n);
352         ctx->buf_off += i;
353         OPENSSL_assert(ctx->buf_off <= (int)sizeof(ctx->buf));
354         OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
355         n -= i;
356     }
357     /* at this point all pending data has been written */
358     ctx->buf_off = 0;
359     ctx->buf_len = 0;
360
361     if ((in == NULL) || (inl <= 0))
362         return (0);
363
364     while (inl > 0) {
365         n = (inl > B64_BLOCK_SIZE) ? B64_BLOCK_SIZE : inl;
366
367         if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) {
368             if (ctx->tmp_len > 0) {
369                 OPENSSL_assert(ctx->tmp_len <= 3);
370                 n = 3 - ctx->tmp_len;
371                 /*
372                  * There's a theoretical possibility for this
373                  */
374                 if (n > inl)
375                     n = inl;
376                 memcpy(&(ctx->tmp[ctx->tmp_len]), in, n);
377                 ctx->tmp_len += n;
378                 ret += n;
379                 if (ctx->tmp_len < 3)
380                     break;
381                 ctx->buf_len =
382                     EVP_EncodeBlock((unsigned char *)ctx->buf,
383                                     (unsigned char *)ctx->tmp, ctx->tmp_len);
384                 OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
385                 OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
386                 /*
387                  * Since we're now done using the temporary buffer, the
388                  * length should be 0'd
389                  */
390                 ctx->tmp_len = 0;
391             } else {
392                 if (n < 3) {
393                     memcpy(ctx->tmp, in, n);
394                     ctx->tmp_len = n;
395                     ret += n;
396                     break;
397                 }
398                 n -= n % 3;
399                 ctx->buf_len =
400                     EVP_EncodeBlock((unsigned char *)ctx->buf,
401                                     (const unsigned char *)in, n);
402                 OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
403                 OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
404                 ret += n;
405             }
406         } else {
407             if (!EVP_EncodeUpdate(ctx->base64,
408                                  (unsigned char *)ctx->buf, &ctx->buf_len,
409                                  (unsigned char *)in, n))
410                 return ((ret == 0) ? -1 : ret);
411             OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf));
412             OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
413             ret += n;
414         }
415         inl -= n;
416         in += n;
417
418         ctx->buf_off = 0;
419         n = ctx->buf_len;
420         while (n > 0) {
421             i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n);
422             if (i <= 0) {
423                 BIO_copy_next_retry(b);
424                 return ((ret == 0) ? i : ret);
425             }
426             OPENSSL_assert(i <= n);
427             n -= i;
428             ctx->buf_off += i;
429             OPENSSL_assert(ctx->buf_off <= (int)sizeof(ctx->buf));
430             OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
431         }
432         ctx->buf_len = 0;
433         ctx->buf_off = 0;
434     }
435     return (ret);
436 }
437
438 static long b64_ctrl(BIO *b, int cmd, long num, void *ptr)
439 {
440     BIO_B64_CTX *ctx;
441     long ret = 1;
442     int i;
443     BIO *next;
444
445     ctx = (BIO_B64_CTX *)BIO_get_data(b);
446     next = BIO_next(b);
447     if ((ctx == NULL) || (next == NULL))
448         return 0;
449
450     switch (cmd) {
451     case BIO_CTRL_RESET:
452         ctx->cont = 1;
453         ctx->start = 1;
454         ctx->encode = B64_NONE;
455         ret = BIO_ctrl(next, cmd, num, ptr);
456         break;
457     case BIO_CTRL_EOF:         /* More to read */
458         if (ctx->cont <= 0)
459             ret = 1;
460         else
461             ret = BIO_ctrl(next, cmd, num, ptr);
462         break;
463     case BIO_CTRL_WPENDING:    /* More to write in buffer */
464         OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
465         ret = ctx->buf_len - ctx->buf_off;
466         if ((ret == 0) && (ctx->encode != B64_NONE)
467             && (EVP_ENCODE_CTX_num(ctx->base64) != 0))
468             ret = 1;
469         else if (ret <= 0)
470             ret = BIO_ctrl(next, cmd, num, ptr);
471         break;
472     case BIO_CTRL_PENDING:     /* More to read in buffer */
473         OPENSSL_assert(ctx->buf_len >= ctx->buf_off);
474         ret = ctx->buf_len - ctx->buf_off;
475         if (ret <= 0)
476             ret = BIO_ctrl(next, cmd, num, ptr);
477         break;
478     case BIO_CTRL_FLUSH:
479         /* do a final write */
480  again:
481         while (ctx->buf_len != ctx->buf_off) {
482             i = b64_write(b, NULL, 0);
483             if (i < 0)
484                 return i;
485         }
486         if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) {
487             if (ctx->tmp_len != 0) {
488                 ctx->buf_len = EVP_EncodeBlock((unsigned char *)ctx->buf,
489                                                (unsigned char *)ctx->tmp,
490                                                ctx->tmp_len);
491                 ctx->buf_off = 0;
492                 ctx->tmp_len = 0;
493                 goto again;
494             }
495         } else if (ctx->encode != B64_NONE
496                    && EVP_ENCODE_CTX_num(ctx->base64) != 0) {
497             ctx->buf_off = 0;
498             EVP_EncodeFinal(ctx->base64,
499                             (unsigned char *)ctx->buf, &(ctx->buf_len));
500             /* push out the bytes */
501             goto again;
502         }
503         /* Finally flush the underlying BIO */
504         ret = BIO_ctrl(next, cmd, num, ptr);
505         break;
506
507     case BIO_C_DO_STATE_MACHINE:
508         BIO_clear_retry_flags(b);
509         ret = BIO_ctrl(next, cmd, num, ptr);
510         BIO_copy_next_retry(b);
511         break;
512
513     case BIO_CTRL_DUP:
514         break;
515     case BIO_CTRL_INFO:
516     case BIO_CTRL_GET:
517     case BIO_CTRL_SET:
518     default:
519         ret = BIO_ctrl(next, cmd, num, ptr);
520         break;
521     }
522     return ret;
523 }
524
525 static long b64_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
526 {
527     long ret = 1;
528     BIO *next = BIO_next(b);
529
530     if (next == NULL)
531         return 0;
532     switch (cmd) {
533     default:
534         ret = BIO_callback_ctrl(next, cmd, fp);
535         break;
536     }
537     return (ret);
538 }
539
540 static int b64_puts(BIO *b, const char *str)
541 {
542     return b64_write(b, str, strlen(str));
543 }