619765ceff7355a33a5b6b5a330e0cc87dd7e18f
[openssl.git] / crypto / comp / c_zlib.c
1 /* ====================================================================
2  * Copyright (c) 1999-2015 The OpenSSL Project.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * 3. All advertising materials mentioning features or use of this
17  *    software must display the following acknowledgment:
18  *    "This product includes software developed by the OpenSSL Project
19  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
20  *
21  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For written permission, please contact
24  *    openssl-core@OpenSSL.org.
25  *
26  * 5. Products derived from this software may not be called "OpenSSL"
27  *    nor may "OpenSSL" appear in their names without prior written
28  *    permission of the OpenSSL Project.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the OpenSSL Project
33  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46  * OF THE POSSIBILITY OF SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This product includes cryptographic software written by Eric Young
50  * (eay@cryptsoft.com).  This product includes software written by Tim
51  * Hudson (tjh@cryptsoft.com).
52  *
53  */
54
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <openssl/objects.h>
59 #include <openssl/comp.h>
60 #include <openssl/err.h>
61 #include <internal/cryptlib_int.h>
62 #include "comp_lcl.h"
63
64 COMP_METHOD *COMP_zlib(void);
65
66 static COMP_METHOD zlib_method_nozlib = {
67     NID_undef,
68     "(undef)",
69     NULL,
70     NULL,
71     NULL,
72     NULL,
73 };
74
75 #ifndef ZLIB
76 # undef ZLIB_SHARED
77 #else
78
79 # include <zlib.h>
80
81 static int zlib_stateful_init(COMP_CTX *ctx);
82 static void zlib_stateful_finish(COMP_CTX *ctx);
83 static int zlib_stateful_compress_block(COMP_CTX *ctx, unsigned char *out,
84                                         unsigned int olen, unsigned char *in,
85                                         unsigned int ilen);
86 static int zlib_stateful_expand_block(COMP_CTX *ctx, unsigned char *out,
87                                       unsigned int olen, unsigned char *in,
88                                       unsigned int ilen);
89
90 /* memory allocations functions for zlib initialisation */
91 static void *zlib_zalloc(void *opaque, unsigned int no, unsigned int size)
92 {
93     void *p;
94
95     p = OPENSSL_zalloc(no * size);
96     return p;
97 }
98
99 static void zlib_zfree(void *opaque, void *address)
100 {
101     OPENSSL_free(address);
102 }
103
104
105 static COMP_METHOD zlib_stateful_method = {
106     NID_zlib_compression,
107     LN_zlib_compression,
108     zlib_stateful_init,
109     zlib_stateful_finish,
110     zlib_stateful_compress_block,
111     zlib_stateful_expand_block
112 };
113
114 /*
115  * When OpenSSL is built on Windows, we do not want to require that
116  * the ZLIB.DLL be available in order for the OpenSSL DLLs to
117  * work.  Therefore, all ZLIB routines are loaded at run time
118  * and we do not link to a .LIB file when ZLIB_SHARED is set.
119  */
120 # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
121 #  include <windows.h>
122 # endif                         /* !(OPENSSL_SYS_WINDOWS ||
123                                  * OPENSSL_SYS_WIN32) */
124
125 # ifdef ZLIB_SHARED
126 #  include <openssl/dso.h>
127
128 /* Function pointers */
129 typedef int (*compress_ft) (Bytef *dest, uLongf * destLen,
130                             const Bytef *source, uLong sourceLen);
131 typedef int (*inflateEnd_ft) (z_streamp strm);
132 typedef int (*inflate_ft) (z_streamp strm, int flush);
133 typedef int (*inflateInit__ft) (z_streamp strm,
134                                 const char *version, int stream_size);
135 typedef int (*deflateEnd_ft) (z_streamp strm);
136 typedef int (*deflate_ft) (z_streamp strm, int flush);
137 typedef int (*deflateInit__ft) (z_streamp strm, int level,
138                                 const char *version, int stream_size);
139 typedef const char *(*zError__ft) (int err);
140 static compress_ft p_compress = NULL;
141 static inflateEnd_ft p_inflateEnd = NULL;
142 static inflate_ft p_inflate = NULL;
143 static inflateInit__ft p_inflateInit_ = NULL;
144 static deflateEnd_ft p_deflateEnd = NULL;
145 static deflate_ft p_deflate = NULL;
146 static deflateInit__ft p_deflateInit_ = NULL;
147 static zError__ft p_zError = NULL;
148
149 static int zlib_loaded = 0;     /* only attempt to init func pts once */
150 static DSO *zlib_dso = NULL;
151
152 #  define compress                p_compress
153 #  define inflateEnd              p_inflateEnd
154 #  define inflate                 p_inflate
155 #  define inflateInit_            p_inflateInit_
156 #  define deflateEnd              p_deflateEnd
157 #  define deflate                 p_deflate
158 #  define deflateInit_            p_deflateInit_
159 #  define zError                  p_zError
160 # endif                         /* ZLIB_SHARED */
161
162 struct zlib_state {
163     z_stream istream;
164     z_stream ostream;
165 };
166
167 static int zlib_stateful_init(COMP_CTX *ctx)
168 {
169     int err;
170     struct zlib_state *state = OPENSSL_zalloc(sizeof(*state));
171
172     if (state == NULL)
173         goto err;
174
175     state->istream.zalloc = zlib_zalloc;
176     state->istream.zfree = zlib_zfree;
177     state->istream.opaque = Z_NULL;
178     state->istream.next_in = Z_NULL;
179     state->istream.next_out = Z_NULL;
180     err = inflateInit_(&state->istream, ZLIB_VERSION, sizeof(z_stream));
181     if (err != Z_OK)
182         goto err;
183
184     state->ostream.zalloc = zlib_zalloc;
185     state->ostream.zfree = zlib_zfree;
186     state->ostream.opaque = Z_NULL;
187     state->ostream.next_in = Z_NULL;
188     state->ostream.next_out = Z_NULL;
189     err = deflateInit_(&state->ostream, Z_DEFAULT_COMPRESSION,
190                        ZLIB_VERSION, sizeof(z_stream));
191     if (err != Z_OK)
192         goto err;
193
194     ctx->data = state;
195     return 1;
196  err:
197     OPENSSL_free(state);
198     return 0;
199 }
200
201 static void zlib_stateful_finish(COMP_CTX *ctx)
202 {
203     struct zlib_state *state = ctx->data;
204     inflateEnd(&state->istream);
205     deflateEnd(&state->ostream);
206     OPENSSL_free(state);
207 }
208
209 static int zlib_stateful_compress_block(COMP_CTX *ctx, unsigned char *out,
210                                         unsigned int olen, unsigned char *in,
211                                         unsigned int ilen)
212 {
213     int err = Z_OK;
214     struct zlib_state *state = ctx->data;
215
216     if (state == NULL)
217         return -1;
218
219     state->ostream.next_in = in;
220     state->ostream.avail_in = ilen;
221     state->ostream.next_out = out;
222     state->ostream.avail_out = olen;
223     if (ilen > 0)
224         err = deflate(&state->ostream, Z_SYNC_FLUSH);
225     if (err != Z_OK)
226         return -1;
227 # ifdef DEBUG_ZLIB
228     fprintf(stderr, "compress(%4d)->%4d %s\n",
229             ilen, olen - state->ostream.avail_out,
230             (ilen != olen - state->ostream.avail_out) ? "zlib" : "clear");
231 # endif
232     return olen - state->ostream.avail_out;
233 }
234
235 static int zlib_stateful_expand_block(COMP_CTX *ctx, unsigned char *out,
236                                       unsigned int olen, unsigned char *in,
237                                       unsigned int ilen)
238 {
239     int err = Z_OK;
240     struct zlib_state *state = ctx->data;
241
242     if (state == NULL)
243         return 0;
244
245     state->istream.next_in = in;
246     state->istream.avail_in = ilen;
247     state->istream.next_out = out;
248     state->istream.avail_out = olen;
249     if (ilen > 0)
250         err = inflate(&state->istream, Z_SYNC_FLUSH);
251     if (err != Z_OK)
252         return -1;
253 # ifdef DEBUG_ZLIB
254     fprintf(stderr, "expand(%4d)->%4d %s\n",
255             ilen, olen - state->istream.avail_out,
256             (ilen != olen - state->istream.avail_out) ? "zlib" : "clear");
257 # endif
258     return olen - state->istream.avail_out;
259 }
260
261 #endif
262
263 COMP_METHOD *COMP_zlib(void)
264 {
265     COMP_METHOD *meth = &zlib_method_nozlib;
266
267 #ifdef ZLIB_SHARED
268     if (!zlib_loaded) {
269 # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
270         zlib_dso = DSO_load(NULL, "ZLIB1", NULL, 0);
271 # else
272         zlib_dso = DSO_load(NULL, "z", NULL, 0);
273 # endif
274         if (zlib_dso != NULL) {
275             p_compress = (compress_ft) DSO_bind_func(zlib_dso, "compress");
276             p_inflateEnd
277                 = (inflateEnd_ft) DSO_bind_func(zlib_dso, "inflateEnd");
278             p_inflate = (inflate_ft) DSO_bind_func(zlib_dso, "inflate");
279             p_inflateInit_
280                 = (inflateInit__ft) DSO_bind_func(zlib_dso, "inflateInit_");
281             p_deflateEnd
282                 = (deflateEnd_ft) DSO_bind_func(zlib_dso, "deflateEnd");
283             p_deflate = (deflate_ft) DSO_bind_func(zlib_dso, "deflate");
284             p_deflateInit_
285                 = (deflateInit__ft) DSO_bind_func(zlib_dso, "deflateInit_");
286             p_zError = (zError__ft) DSO_bind_func(zlib_dso, "zError");
287
288             if (p_compress && p_inflateEnd && p_inflate
289                 && p_inflateInit_ && p_deflateEnd
290                 && p_deflate && p_deflateInit_ && p_zError)
291                 zlib_loaded++;
292             if (zlib_loaded)
293                 meth = &zlib_stateful_method;
294             OPENSSL_init_crypto(OPENSSL_INIT_ZLIB, NULL);
295         }
296     }
297 #endif
298 #if defined(ZLIB)
299     meth = &zlib_stateful_method;
300 #endif
301
302     return (meth);
303 }
304
305 void COMP_zlib_cleanup(void)
306 {
307 #ifdef ZLIB_SHARED
308     if (zlib_dso != NULL)
309         DSO_free(zlib_dso);
310     zlib_dso = NULL;
311 #endif
312 }
313
314 #ifdef ZLIB
315
316 /* Zlib based compression/decompression filter BIO */
317
318 typedef struct {
319     unsigned char *ibuf;        /* Input buffer */
320     int ibufsize;               /* Buffer size */
321     z_stream zin;               /* Input decompress context */
322     unsigned char *obuf;        /* Output buffer */
323     int obufsize;               /* Output buffer size */
324     unsigned char *optr;        /* Position in output buffer */
325     int ocount;                 /* Amount of data in output buffer */
326     int odone;                  /* deflate EOF */
327     int comp_level;             /* Compression level to use */
328     z_stream zout;              /* Output compression context */
329 } BIO_ZLIB_CTX;
330
331 # define ZLIB_DEFAULT_BUFSIZE 1024
332
333 static int bio_zlib_new(BIO *bi);
334 static int bio_zlib_free(BIO *bi);
335 static int bio_zlib_read(BIO *b, char *out, int outl);
336 static int bio_zlib_write(BIO *b, const char *in, int inl);
337 static long bio_zlib_ctrl(BIO *b, int cmd, long num, void *ptr);
338 static long bio_zlib_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp);
339
340 static BIO_METHOD bio_meth_zlib = {
341     BIO_TYPE_COMP,
342     "zlib",
343     bio_zlib_write,
344     bio_zlib_read,
345     NULL,
346     NULL,
347     bio_zlib_ctrl,
348     bio_zlib_new,
349     bio_zlib_free,
350     bio_zlib_callback_ctrl
351 };
352
353 BIO_METHOD *BIO_f_zlib(void)
354 {
355     return &bio_meth_zlib;
356 }
357
358 static int bio_zlib_new(BIO *bi)
359 {
360     BIO_ZLIB_CTX *ctx;
361 # ifdef ZLIB_SHARED
362     (void)COMP_zlib();
363     if (!zlib_loaded) {
364         COMPerr(COMP_F_BIO_ZLIB_NEW, COMP_R_ZLIB_NOT_SUPPORTED);
365         return 0;
366     }
367 # endif
368     ctx = OPENSSL_zalloc(sizeof(*ctx));
369     if (ctx == NULL) {
370         COMPerr(COMP_F_BIO_ZLIB_NEW, ERR_R_MALLOC_FAILURE);
371         return 0;
372     }
373     ctx->ibufsize = ZLIB_DEFAULT_BUFSIZE;
374     ctx->obufsize = ZLIB_DEFAULT_BUFSIZE;
375     ctx->zin.zalloc = Z_NULL;
376     ctx->zin.zfree = Z_NULL;
377     ctx->zout.zalloc = Z_NULL;
378     ctx->zout.zfree = Z_NULL;
379     ctx->comp_level = Z_DEFAULT_COMPRESSION;
380     bi->init = 1;
381     bi->ptr = (char *)ctx;
382     bi->flags = 0;
383     return 1;
384 }
385
386 static int bio_zlib_free(BIO *bi)
387 {
388     BIO_ZLIB_CTX *ctx;
389     if (!bi)
390         return 0;
391     ctx = (BIO_ZLIB_CTX *) bi->ptr;
392     if (ctx->ibuf) {
393         /* Destroy decompress context */
394         inflateEnd(&ctx->zin);
395         OPENSSL_free(ctx->ibuf);
396     }
397     if (ctx->obuf) {
398         /* Destroy compress context */
399         deflateEnd(&ctx->zout);
400         OPENSSL_free(ctx->obuf);
401     }
402     OPENSSL_free(ctx);
403     bi->ptr = NULL;
404     bi->init = 0;
405     bi->flags = 0;
406     return 1;
407 }
408
409 static int bio_zlib_read(BIO *b, char *out, int outl)
410 {
411     BIO_ZLIB_CTX *ctx;
412     int ret;
413     z_stream *zin;
414     if (!out || !outl)
415         return 0;
416     ctx = (BIO_ZLIB_CTX *) b->ptr;
417     zin = &ctx->zin;
418     BIO_clear_retry_flags(b);
419     if (!ctx->ibuf) {
420         ctx->ibuf = OPENSSL_malloc(ctx->ibufsize);
421         if (ctx->ibuf == NULL) {
422             COMPerr(COMP_F_BIO_ZLIB_READ, ERR_R_MALLOC_FAILURE);
423             return 0;
424         }
425         inflateInit(zin);
426         zin->next_in = ctx->ibuf;
427         zin->avail_in = 0;
428     }
429
430     /* Copy output data directly to supplied buffer */
431     zin->next_out = (unsigned char *)out;
432     zin->avail_out = (unsigned int)outl;
433     for (;;) {
434         /* Decompress while data available */
435         while (zin->avail_in) {
436             ret = inflate(zin, 0);
437             if ((ret != Z_OK) && (ret != Z_STREAM_END)) {
438                 COMPerr(COMP_F_BIO_ZLIB_READ, COMP_R_ZLIB_INFLATE_ERROR);
439                 ERR_add_error_data(2, "zlib error:", zError(ret));
440                 return 0;
441             }
442             /* If EOF or we've read everything then return */
443             if ((ret == Z_STREAM_END) || !zin->avail_out)
444                 return outl - zin->avail_out;
445         }
446
447         /*
448          * No data in input buffer try to read some in, if an error then
449          * return the total data read.
450          */
451         ret = BIO_read(b->next_bio, ctx->ibuf, ctx->ibufsize);
452         if (ret <= 0) {
453             /* Total data read */
454             int tot = outl - zin->avail_out;
455             BIO_copy_next_retry(b);
456             if (ret < 0)
457                 return (tot > 0) ? tot : ret;
458             return tot;
459         }
460         zin->avail_in = ret;
461         zin->next_in = ctx->ibuf;
462     }
463 }
464
465 static int bio_zlib_write(BIO *b, const char *in, int inl)
466 {
467     BIO_ZLIB_CTX *ctx;
468     int ret;
469     z_stream *zout;
470     if (!in || !inl)
471         return 0;
472     ctx = (BIO_ZLIB_CTX *) b->ptr;
473     if (ctx->odone)
474         return 0;
475     zout = &ctx->zout;
476     BIO_clear_retry_flags(b);
477     if (!ctx->obuf) {
478         ctx->obuf = OPENSSL_malloc(ctx->obufsize);
479         /* Need error here */
480         if (ctx->obuf == NULL) {
481             COMPerr(COMP_F_BIO_ZLIB_WRITE, ERR_R_MALLOC_FAILURE);
482             return 0;
483         }
484         ctx->optr = ctx->obuf;
485         ctx->ocount = 0;
486         deflateInit(zout, ctx->comp_level);
487         zout->next_out = ctx->obuf;
488         zout->avail_out = ctx->obufsize;
489     }
490     /* Obtain input data directly from supplied buffer */
491     zout->next_in = (void *)in;
492     zout->avail_in = inl;
493     for (;;) {
494         /* If data in output buffer write it first */
495         while (ctx->ocount) {
496             ret = BIO_write(b->next_bio, ctx->optr, ctx->ocount);
497             if (ret <= 0) {
498                 /* Total data written */
499                 int tot = inl - zout->avail_in;
500                 BIO_copy_next_retry(b);
501                 if (ret < 0)
502                     return (tot > 0) ? tot : ret;
503                 return tot;
504             }
505             ctx->optr += ret;
506             ctx->ocount -= ret;
507         }
508
509         /* Have we consumed all supplied data? */
510         if (!zout->avail_in)
511             return inl;
512
513         /* Compress some more */
514
515         /* Reset buffer */
516         ctx->optr = ctx->obuf;
517         zout->next_out = ctx->obuf;
518         zout->avail_out = ctx->obufsize;
519         /* Compress some more */
520         ret = deflate(zout, 0);
521         if (ret != Z_OK) {
522             COMPerr(COMP_F_BIO_ZLIB_WRITE, COMP_R_ZLIB_DEFLATE_ERROR);
523             ERR_add_error_data(2, "zlib error:", zError(ret));
524             return 0;
525         }
526         ctx->ocount = ctx->obufsize - zout->avail_out;
527     }
528 }
529
530 static int bio_zlib_flush(BIO *b)
531 {
532     BIO_ZLIB_CTX *ctx;
533     int ret;
534     z_stream *zout;
535     ctx = (BIO_ZLIB_CTX *) b->ptr;
536     /* If no data written or already flush show success */
537     if (!ctx->obuf || (ctx->odone && !ctx->ocount))
538         return 1;
539     zout = &ctx->zout;
540     BIO_clear_retry_flags(b);
541     /* No more input data */
542     zout->next_in = NULL;
543     zout->avail_in = 0;
544     for (;;) {
545         /* If data in output buffer write it first */
546         while (ctx->ocount) {
547             ret = BIO_write(b->next_bio, ctx->optr, ctx->ocount);
548             if (ret <= 0) {
549                 BIO_copy_next_retry(b);
550                 return ret;
551             }
552             ctx->optr += ret;
553             ctx->ocount -= ret;
554         }
555         if (ctx->odone)
556             return 1;
557
558         /* Compress some more */
559
560         /* Reset buffer */
561         ctx->optr = ctx->obuf;
562         zout->next_out = ctx->obuf;
563         zout->avail_out = ctx->obufsize;
564         /* Compress some more */
565         ret = deflate(zout, Z_FINISH);
566         if (ret == Z_STREAM_END)
567             ctx->odone = 1;
568         else if (ret != Z_OK) {
569             COMPerr(COMP_F_BIO_ZLIB_FLUSH, COMP_R_ZLIB_DEFLATE_ERROR);
570             ERR_add_error_data(2, "zlib error:", zError(ret));
571             return 0;
572         }
573         ctx->ocount = ctx->obufsize - zout->avail_out;
574     }
575 }
576
577 static long bio_zlib_ctrl(BIO *b, int cmd, long num, void *ptr)
578 {
579     BIO_ZLIB_CTX *ctx;
580     int ret, *ip;
581     int ibs, obs;
582     if (!b->next_bio)
583         return 0;
584     ctx = (BIO_ZLIB_CTX *) b->ptr;
585     switch (cmd) {
586
587     case BIO_CTRL_RESET:
588         ctx->ocount = 0;
589         ctx->odone = 0;
590         ret = 1;
591         break;
592
593     case BIO_CTRL_FLUSH:
594         ret = bio_zlib_flush(b);
595         if (ret > 0)
596             ret = BIO_flush(b->next_bio);
597         break;
598
599     case BIO_C_SET_BUFF_SIZE:
600         ibs = -1;
601         obs = -1;
602         if (ptr != NULL) {
603             ip = ptr;
604             if (*ip == 0)
605                 ibs = (int)num;
606             else
607                 obs = (int)num;
608         } else {
609             ibs = (int)num;
610             obs = ibs;
611         }
612
613         if (ibs != -1) {
614             OPENSSL_free(ctx->ibuf);
615             ctx->ibuf = NULL;
616             ctx->ibufsize = ibs;
617         }
618
619         if (obs != -1) {
620             OPENSSL_free(ctx->obuf);
621             ctx->obuf = NULL;
622             ctx->obufsize = obs;
623         }
624         ret = 1;
625         break;
626
627     case BIO_C_DO_STATE_MACHINE:
628         BIO_clear_retry_flags(b);
629         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
630         BIO_copy_next_retry(b);
631         break;
632
633     default:
634         ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
635         break;
636
637     }
638
639     return ret;
640 }
641
642 static long bio_zlib_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
643 {
644     if (!b->next_bio)
645         return 0;
646     return BIO_callback_ctrl(b->next_bio, cmd, fp);
647 }
648
649 #endif