Stop raising ERR_R_MALLOC_FAILURE in most places
[openssl.git] / crypto / comp / c_zlib.c
1 /*
2  * Copyright 1998-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 <stdlib.h>
12 #include <string.h>
13 #include <openssl/objects.h>
14 #include "internal/comp.h"
15 #include <openssl/err.h>
16 #include "crypto/cryptlib.h"
17 #include "internal/bio.h"
18 #include "internal/thread_once.h"
19 #include "comp_local.h"
20
21 COMP_METHOD *COMP_zlib(void);
22
23 static COMP_METHOD zlib_method_nozlib = {
24     NID_undef,
25     "(undef)",
26     NULL,
27     NULL,
28     NULL,
29     NULL,
30 };
31
32 #ifndef ZLIB
33 # undef ZLIB_SHARED
34 #else
35
36 # include <zlib.h>
37
38 static int zlib_stateful_init(COMP_CTX *ctx);
39 static void zlib_stateful_finish(COMP_CTX *ctx);
40 static int zlib_stateful_compress_block(COMP_CTX *ctx, unsigned char *out,
41                                         unsigned int olen, unsigned char *in,
42                                         unsigned int ilen);
43 static int zlib_stateful_expand_block(COMP_CTX *ctx, unsigned char *out,
44                                       unsigned int olen, unsigned char *in,
45                                       unsigned int ilen);
46
47 /* memory allocations functions for zlib initialisation */
48 static void *zlib_zalloc(void *opaque, unsigned int no, unsigned int size)
49 {
50     void *p;
51
52     p = OPENSSL_zalloc(no * size);
53     return p;
54 }
55
56 static void zlib_zfree(void *opaque, void *address)
57 {
58     OPENSSL_free(address);
59 }
60
61
62 static COMP_METHOD zlib_stateful_method = {
63     NID_zlib_compression,
64     LN_zlib_compression,
65     zlib_stateful_init,
66     zlib_stateful_finish,
67     zlib_stateful_compress_block,
68     zlib_stateful_expand_block
69 };
70
71 /*
72  * When OpenSSL is built on Windows, we do not want to require that
73  * the ZLIB.DLL be available in order for the OpenSSL DLLs to
74  * work.  Therefore, all ZLIB routines are loaded at run time
75  * and we do not link to a .LIB file when ZLIB_SHARED is set.
76  */
77 # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
78 #  include <windows.h>
79 # endif                         /* !(OPENSSL_SYS_WINDOWS ||
80                                  * OPENSSL_SYS_WIN32) */
81
82 # ifdef ZLIB_SHARED
83 #  include "internal/dso.h"
84
85 /* Function pointers */
86 typedef int (*compress_ft) (Bytef *dest, uLongf * destLen,
87                             const Bytef *source, uLong sourceLen);
88 typedef int (*inflateEnd_ft) (z_streamp strm);
89 typedef int (*inflate_ft) (z_streamp strm, int flush);
90 typedef int (*inflateInit__ft) (z_streamp strm,
91                                 const char *version, int stream_size);
92 typedef int (*deflateEnd_ft) (z_streamp strm);
93 typedef int (*deflate_ft) (z_streamp strm, int flush);
94 typedef int (*deflateInit__ft) (z_streamp strm, int level,
95                                 const char *version, int stream_size);
96 typedef const char *(*zError__ft) (int err);
97 static compress_ft p_compress = NULL;
98 static inflateEnd_ft p_inflateEnd = NULL;
99 static inflate_ft p_inflate = NULL;
100 static inflateInit__ft p_inflateInit_ = NULL;
101 static deflateEnd_ft p_deflateEnd = NULL;
102 static deflate_ft p_deflate = NULL;
103 static deflateInit__ft p_deflateInit_ = NULL;
104 static zError__ft p_zError = NULL;
105
106 static DSO *zlib_dso = NULL;
107
108 #  define compress                p_compress
109 #  define inflateEnd              p_inflateEnd
110 #  define inflate                 p_inflate
111 #  define inflateInit_            p_inflateInit_
112 #  define deflateEnd              p_deflateEnd
113 #  define deflate                 p_deflate
114 #  define deflateInit_            p_deflateInit_
115 #  define zError                  p_zError
116 # endif                         /* ZLIB_SHARED */
117
118 struct zlib_state {
119     z_stream istream;
120     z_stream ostream;
121 };
122
123 static int zlib_stateful_init(COMP_CTX *ctx)
124 {
125     int err;
126     struct zlib_state *state = OPENSSL_zalloc(sizeof(*state));
127
128     if (state == NULL)
129         goto err;
130
131     state->istream.zalloc = zlib_zalloc;
132     state->istream.zfree = zlib_zfree;
133     state->istream.opaque = Z_NULL;
134     state->istream.next_in = Z_NULL;
135     state->istream.next_out = Z_NULL;
136     err = inflateInit_(&state->istream, ZLIB_VERSION, sizeof(z_stream));
137     if (err != Z_OK)
138         goto err;
139
140     state->ostream.zalloc = zlib_zalloc;
141     state->ostream.zfree = zlib_zfree;
142     state->ostream.opaque = Z_NULL;
143     state->ostream.next_in = Z_NULL;
144     state->ostream.next_out = Z_NULL;
145     err = deflateInit_(&state->ostream, Z_DEFAULT_COMPRESSION,
146                        ZLIB_VERSION, sizeof(z_stream));
147     if (err != Z_OK)
148         goto err;
149
150     ctx->data = state;
151     return 1;
152  err:
153     OPENSSL_free(state);
154     return 0;
155 }
156
157 static void zlib_stateful_finish(COMP_CTX *ctx)
158 {
159     struct zlib_state *state = ctx->data;
160     inflateEnd(&state->istream);
161     deflateEnd(&state->ostream);
162     OPENSSL_free(state);
163 }
164
165 static int zlib_stateful_compress_block(COMP_CTX *ctx, unsigned char *out,
166                                         unsigned int olen, unsigned char *in,
167                                         unsigned int ilen)
168 {
169     int err = Z_OK;
170     struct zlib_state *state = ctx->data;
171
172     if (state == NULL)
173         return -1;
174
175     state->ostream.next_in = in;
176     state->ostream.avail_in = ilen;
177     state->ostream.next_out = out;
178     state->ostream.avail_out = olen;
179     if (ilen > 0)
180         err = deflate(&state->ostream, Z_SYNC_FLUSH);
181     if (err != Z_OK)
182         return -1;
183     return olen - state->ostream.avail_out;
184 }
185
186 static int zlib_stateful_expand_block(COMP_CTX *ctx, unsigned char *out,
187                                       unsigned int olen, unsigned char *in,
188                                       unsigned int ilen)
189 {
190     int err = Z_OK;
191     struct zlib_state *state = ctx->data;
192
193     if (state == NULL)
194         return 0;
195
196     state->istream.next_in = in;
197     state->istream.avail_in = ilen;
198     state->istream.next_out = out;
199     state->istream.avail_out = olen;
200     if (ilen > 0)
201         err = inflate(&state->istream, Z_SYNC_FLUSH);
202     if (err != Z_OK)
203         return -1;
204     return olen - state->istream.avail_out;
205 }
206
207 static CRYPTO_ONCE zlib_once = CRYPTO_ONCE_STATIC_INIT;
208 DEFINE_RUN_ONCE_STATIC(ossl_comp_zlib_init)
209 {
210 # ifdef ZLIB_SHARED
211     /* LIBZ may be externally defined, and we should respect that value */
212 #  ifndef LIBZ
213 #   if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
214 #    define LIBZ "ZLIB1"
215 #   elif defined(OPENSSL_SYS_VMS)
216 #    define LIBZ "LIBZ"
217 #   else
218 #    define LIBZ "z"
219 #   endif
220 #  endif
221
222     zlib_dso = DSO_load(NULL, LIBZ, NULL, 0);
223     if (zlib_dso != NULL) {
224         p_compress = (compress_ft) DSO_bind_func(zlib_dso, "compress");
225         p_inflateEnd = (inflateEnd_ft) DSO_bind_func(zlib_dso, "inflateEnd");
226         p_inflate = (inflate_ft) DSO_bind_func(zlib_dso, "inflate");
227         p_inflateInit_ = (inflateInit__ft) DSO_bind_func(zlib_dso, "inflateInit_");
228         p_deflateEnd = (deflateEnd_ft) DSO_bind_func(zlib_dso, "deflateEnd");
229         p_deflate = (deflate_ft) DSO_bind_func(zlib_dso, "deflate");
230         p_deflateInit_ = (deflateInit__ft) DSO_bind_func(zlib_dso, "deflateInit_");
231         p_zError = (zError__ft) DSO_bind_func(zlib_dso, "zError");
232
233         if (p_compress == NULL || p_inflateEnd == NULL
234                 || p_inflate == NULL || p_inflateInit_ == NULL
235                 || p_deflateEnd == NULL || p_deflate == NULL
236                 || p_deflateInit_ == NULL || p_zError == NULL) {
237             ossl_comp_zlib_cleanup();
238             return 0;
239         }
240     }
241 # endif
242     return 1;
243 }
244 #endif
245
246 COMP_METHOD *COMP_zlib(void)
247 {
248     COMP_METHOD *meth = &zlib_method_nozlib;
249
250 #ifdef ZLIB
251     if (RUN_ONCE(&zlib_once, ossl_comp_zlib_init))
252         meth = &zlib_stateful_method;
253 #endif
254
255     return meth;
256 }
257
258 /* Also called from OPENSSL_cleanup() */
259 void ossl_comp_zlib_cleanup(void)
260 {
261 #ifdef ZLIB_SHARED
262     DSO_free(zlib_dso);
263     zlib_dso = NULL;
264 #endif
265 }
266
267 #ifdef ZLIB
268
269 /* Zlib based compression/decompression filter BIO */
270
271 typedef struct {
272     unsigned char *ibuf;        /* Input buffer */
273     int ibufsize;               /* Buffer size */
274     z_stream zin;               /* Input decompress context */
275     unsigned char *obuf;        /* Output buffer */
276     int obufsize;               /* Output buffer size */
277     unsigned char *optr;        /* Position in output buffer */
278     int ocount;                 /* Amount of data in output buffer */
279     int odone;                  /* deflate EOF */
280     int comp_level;             /* Compression level to use */
281     z_stream zout;              /* Output compression context */
282 } BIO_ZLIB_CTX;
283
284 # define ZLIB_DEFAULT_BUFSIZE 1024
285
286 static int bio_zlib_new(BIO *bi);
287 static int bio_zlib_free(BIO *bi);
288 static int bio_zlib_read(BIO *b, char *out, int outl);
289 static int bio_zlib_write(BIO *b, const char *in, int inl);
290 static long bio_zlib_ctrl(BIO *b, int cmd, long num, void *ptr);
291 static long bio_zlib_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp);
292
293 static const BIO_METHOD bio_meth_zlib = {
294     BIO_TYPE_COMP,
295     "zlib",
296     bwrite_conv,
297     bio_zlib_write,
298     bread_conv,
299     bio_zlib_read,
300     NULL,                      /* bio_zlib_puts, */
301     NULL,                      /* bio_zlib_gets, */
302     bio_zlib_ctrl,
303     bio_zlib_new,
304     bio_zlib_free,
305     bio_zlib_callback_ctrl
306 };
307
308 const BIO_METHOD *BIO_f_zlib(void)
309 {
310     return &bio_meth_zlib;
311 }
312
313 static int bio_zlib_new(BIO *bi)
314 {
315     BIO_ZLIB_CTX *ctx;
316
317 # ifdef ZLIB_SHARED
318     if (!RUN_ONCE(&zlib_once, ossl_comp_zlib_init)) {
319         ERR_raise(ERR_LIB_COMP, COMP_R_ZLIB_NOT_SUPPORTED);
320         return 0;
321     }
322 # endif
323     ctx = OPENSSL_zalloc(sizeof(*ctx));
324     if (ctx == NULL)
325         return 0;
326     ctx->ibufsize = ZLIB_DEFAULT_BUFSIZE;
327     ctx->obufsize = ZLIB_DEFAULT_BUFSIZE;
328     ctx->zin.zalloc = Z_NULL;
329     ctx->zin.zfree = Z_NULL;
330     ctx->zout.zalloc = Z_NULL;
331     ctx->zout.zfree = Z_NULL;
332     ctx->comp_level = Z_DEFAULT_COMPRESSION;
333     BIO_set_init(bi, 1);
334     BIO_set_data(bi, ctx);
335
336     return 1;
337 }
338
339 static int bio_zlib_free(BIO *bi)
340 {
341     BIO_ZLIB_CTX *ctx;
342
343     if (!bi)
344         return 0;
345     ctx = BIO_get_data(bi);
346     if (ctx->ibuf) {
347         /* Destroy decompress context */
348         inflateEnd(&ctx->zin);
349         OPENSSL_free(ctx->ibuf);
350     }
351     if (ctx->obuf) {
352         /* Destroy compress context */
353         deflateEnd(&ctx->zout);
354         OPENSSL_free(ctx->obuf);
355     }
356     OPENSSL_free(ctx);
357     BIO_set_data(bi, NULL);
358     BIO_set_init(bi, 0);
359
360     return 1;
361 }
362
363 static int bio_zlib_read(BIO *b, char *out, int outl)
364 {
365     BIO_ZLIB_CTX *ctx;
366     int ret;
367     z_stream *zin;
368     BIO *next = BIO_next(b);
369
370     if (!out || !outl)
371         return 0;
372     ctx = BIO_get_data(b);
373     zin = &ctx->zin;
374     BIO_clear_retry_flags(b);
375     if (!ctx->ibuf) {
376         ctx->ibuf = OPENSSL_malloc(ctx->ibufsize);
377         if (ctx->ibuf == NULL)
378             return 0;
379         if ((ret = inflateInit(zin)) != Z_OK) {
380             ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_INFLATE_ERROR,
381                            "zlib error: %s", zError(ret));
382             return 0;
383         }
384         zin->next_in = ctx->ibuf;
385         zin->avail_in = 0;
386     }
387
388     /* Copy output data directly to supplied buffer */
389     zin->next_out = (unsigned char *)out;
390     zin->avail_out = (unsigned int)outl;
391     for (;;) {
392         /* Decompress while data available */
393         while (zin->avail_in) {
394             ret = inflate(zin, 0);
395             if ((ret != Z_OK) && (ret != Z_STREAM_END)) {
396                 ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_INFLATE_ERROR,
397                                "zlib error: %s", zError(ret));
398                 return 0;
399             }
400             /* If EOF or we've read everything then return */
401             if ((ret == Z_STREAM_END) || !zin->avail_out)
402                 return outl - zin->avail_out;
403         }
404
405         /*
406          * No data in input buffer try to read some in, if an error then
407          * return the total data read.
408          */
409         ret = BIO_read(next, ctx->ibuf, ctx->ibufsize);
410         if (ret <= 0) {
411             /* Total data read */
412             int tot = outl - zin->avail_out;
413             BIO_copy_next_retry(b);
414             if (ret < 0)
415                 return (tot > 0) ? tot : ret;
416             return tot;
417         }
418         zin->avail_in = ret;
419         zin->next_in = ctx->ibuf;
420     }
421 }
422
423 static int bio_zlib_write(BIO *b, const char *in, int inl)
424 {
425     BIO_ZLIB_CTX *ctx;
426     int ret;
427     z_stream *zout;
428     BIO *next = BIO_next(b);
429
430     if (!in || !inl)
431         return 0;
432     ctx = BIO_get_data(b);
433     if (ctx->odone)
434         return 0;
435     zout = &ctx->zout;
436     BIO_clear_retry_flags(b);
437     if (!ctx->obuf) {
438         ctx->obuf = OPENSSL_malloc(ctx->obufsize);
439         /* Need error here */
440         if (ctx->obuf == NULL)
441             return 0;
442         ctx->optr = ctx->obuf;
443         ctx->ocount = 0;
444         if ((ret = deflateInit(zout, ctx->comp_level)) != Z_OK) {
445             ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_DEFLATE_ERROR,
446                            "zlib error: %s", zError(ret));
447             return 0;
448         }
449         zout->next_out = ctx->obuf;
450         zout->avail_out = ctx->obufsize;
451     }
452     /* Obtain input data directly from supplied buffer */
453     zout->next_in = (void *)in;
454     zout->avail_in = inl;
455     for (;;) {
456         /* If data in output buffer write it first */
457         while (ctx->ocount) {
458             ret = BIO_write(next, ctx->optr, ctx->ocount);
459             if (ret <= 0) {
460                 /* Total data written */
461                 int tot = inl - zout->avail_in;
462                 BIO_copy_next_retry(b);
463                 if (ret < 0)
464                     return (tot > 0) ? tot : ret;
465                 return tot;
466             }
467             ctx->optr += ret;
468             ctx->ocount -= ret;
469         }
470
471         /* Have we consumed all supplied data? */
472         if (!zout->avail_in)
473             return inl;
474
475         /* Compress some more */
476
477         /* Reset buffer */
478         ctx->optr = ctx->obuf;
479         zout->next_out = ctx->obuf;
480         zout->avail_out = ctx->obufsize;
481         /* Compress some more */
482         ret = deflate(zout, 0);
483         if (ret != Z_OK) {
484             ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_DEFLATE_ERROR,
485                            "zlib error: %s", zError(ret));
486             return 0;
487         }
488         ctx->ocount = ctx->obufsize - zout->avail_out;
489     }
490 }
491
492 static int bio_zlib_flush(BIO *b)
493 {
494     BIO_ZLIB_CTX *ctx;
495     int ret;
496     z_stream *zout;
497     BIO *next = BIO_next(b);
498
499     ctx = BIO_get_data(b);
500     /* If no data written or already flush show success */
501     if (!ctx->obuf || (ctx->odone && !ctx->ocount))
502         return 1;
503     zout = &ctx->zout;
504     BIO_clear_retry_flags(b);
505     /* No more input data */
506     zout->next_in = NULL;
507     zout->avail_in = 0;
508     for (;;) {
509         /* If data in output buffer write it first */
510         while (ctx->ocount) {
511             ret = BIO_write(next, ctx->optr, ctx->ocount);
512             if (ret <= 0) {
513                 BIO_copy_next_retry(b);
514                 return ret;
515             }
516             ctx->optr += ret;
517             ctx->ocount -= ret;
518         }
519         if (ctx->odone)
520             return 1;
521
522         /* Compress some more */
523
524         /* Reset buffer */
525         ctx->optr = ctx->obuf;
526         zout->next_out = ctx->obuf;
527         zout->avail_out = ctx->obufsize;
528         /* Compress some more */
529         ret = deflate(zout, Z_FINISH);
530         if (ret == Z_STREAM_END)
531             ctx->odone = 1;
532         else if (ret != Z_OK) {
533             ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_DEFLATE_ERROR,
534                            "zlib error: %s", zError(ret));
535             return 0;
536         }
537         ctx->ocount = ctx->obufsize - zout->avail_out;
538     }
539 }
540
541 static long bio_zlib_ctrl(BIO *b, int cmd, long num, void *ptr)
542 {
543     BIO_ZLIB_CTX *ctx;
544     int ret, *ip;
545     int ibs, obs;
546     BIO *next = BIO_next(b);
547
548     if (next == NULL)
549         return 0;
550     ctx = BIO_get_data(b);
551     switch (cmd) {
552
553     case BIO_CTRL_RESET:
554         ctx->ocount = 0;
555         ctx->odone = 0;
556         ret = 1;
557         break;
558
559     case BIO_CTRL_FLUSH:
560         ret = bio_zlib_flush(b);
561         if (ret > 0)
562             ret = BIO_flush(next);
563         break;
564
565     case BIO_C_SET_BUFF_SIZE:
566         ibs = -1;
567         obs = -1;
568         if (ptr != NULL) {
569             ip = ptr;
570             if (*ip == 0)
571                 ibs = (int)num;
572             else
573                 obs = (int)num;
574         } else {
575             ibs = (int)num;
576             obs = ibs;
577         }
578
579         if (ibs != -1) {
580             OPENSSL_free(ctx->ibuf);
581             ctx->ibuf = NULL;
582             ctx->ibufsize = ibs;
583         }
584
585         if (obs != -1) {
586             OPENSSL_free(ctx->obuf);
587             ctx->obuf = NULL;
588             ctx->obufsize = obs;
589         }
590         ret = 1;
591         break;
592
593     case BIO_C_DO_STATE_MACHINE:
594         BIO_clear_retry_flags(b);
595         ret = BIO_ctrl(next, cmd, num, ptr);
596         BIO_copy_next_retry(b);
597         break;
598
599     case BIO_CTRL_WPENDING:
600         if (ctx->obuf == NULL)
601             return 0;
602
603         if (ctx->odone) {
604             ret = ctx->ocount;
605         } else {
606             ret = ctx->ocount;
607             if (ret == 0)
608                 /* Unknown amount pending but we are not finished */
609                 ret = 1;
610         }
611         if (ret == 0)
612             ret = BIO_ctrl(next, cmd, num, ptr);
613         break;
614
615     case BIO_CTRL_PENDING:
616         ret = ctx->zin.avail_in;
617         if (ret == 0)
618             ret = BIO_ctrl(next, cmd, num, ptr);
619         break;
620
621     default:
622         ret = BIO_ctrl(next, cmd, num, ptr);
623         break;
624
625     }
626
627     return ret;
628 }
629
630 static long bio_zlib_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp)
631 {
632     BIO *next = BIO_next(b);
633
634     if (next == NULL)
635         return 0;
636     return BIO_callback_ctrl(next, cmd, fp);
637 }
638
639 #endif