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