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