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