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