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