1 /*
  2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  3  *
  4  * This code is free software; you can redistribute it and/or modify it
  5  * under the terms of the GNU General Public License version 2 only, as
  6  * published by the Free Software Foundation.  Oracle designates this
  7  * particular file as subject to the "Classpath" exception as provided
  8  * by Oracle in the LICENSE file that accompanied this code.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  */
 24 
 25 /* infback.c -- inflate using a call-back interface
 26  * Copyright (C) 1995-2022 Mark Adler
 27  * For conditions of distribution and use, see copyright notice in zlib.h
 28  */
 29 
 30 /*
 31    This code is largely copied from inflate.c.  Normally either infback.o or
 32    inflate.o would be linked into an application--not both.  The interface
 33    with inffast.c is retained so that optimized assembler-coded versions of
 34    inflate_fast() can be used with either inflate.c or infback.c.
 35  */
 36 
 37 #include "zutil.h"
 38 #include "inftrees.h"
 39 #include "inflate.h"
 40 #include "inffast.h"
 41 
 42 /* function prototypes */
 43 local void fixedtables OF((struct inflate_state FAR *state));
 44 
 45 /*
 46    strm provides memory allocation functions in zalloc and zfree, or
 47    Z_NULL to use the library memory allocation functions.
 48 
 49    windowBits is in the range 8..15, and window is a user-supplied
 50    window and output buffer that is 2**windowBits bytes.
 51  */
 52 int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
 53 z_streamp strm;
 54 int windowBits;
 55 unsigned char FAR *window;
 56 const char *version;
 57 int stream_size;
 58 {
 59     struct inflate_state FAR *state;
 60 
 61     if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
 62         stream_size != (int)(sizeof(z_stream)))
 63         return Z_VERSION_ERROR;
 64     if (strm == Z_NULL || window == Z_NULL ||
 65         windowBits < 8 || windowBits > 15)
 66         return Z_STREAM_ERROR;
 67     strm->msg = Z_NULL;                 /* in case we return an error */
 68     if (strm->zalloc == (alloc_func)0) {
 69 #ifdef Z_SOLO
 70         return Z_STREAM_ERROR;
 71 #else
 72         strm->zalloc = zcalloc;
 73         strm->opaque = (voidpf)0;
 74 #endif
 75     }
 76     if (strm->zfree == (free_func)0)
 77 #ifdef Z_SOLO
 78         return Z_STREAM_ERROR;
 79 #else
 80     strm->zfree = zcfree;
 81 #endif
 82     state = (struct inflate_state FAR *)ZALLOC(strm, 1,
 83                                                sizeof(struct inflate_state));
 84     if (state == Z_NULL) return Z_MEM_ERROR;
 85     Tracev((stderr, "inflate: allocated\n"));
 86     strm->state = (struct internal_state FAR *)state;
 87     state->dmax = 32768U;
 88     state->wbits = (uInt)windowBits;
 89     state->wsize = 1U << windowBits;
 90     state->window = window;
 91     state->wnext = 0;
 92     state->whave = 0;
 93     state->sane = 1;
 94     return Z_OK;
 95 }
 96 
 97 /*
 98    Return state with length and distance decoding tables and index sizes set to
 99    fixed code decoding.  Normally this returns fixed tables from inffixed.h.
100    If BUILDFIXED is defined, then instead this routine builds the tables the
101    first time it's called, and returns those tables the first time and
102    thereafter.  This reduces the size of the code by about 2K bytes, in
103    exchange for a little execution time.  However, BUILDFIXED should not be
104    used for threaded applications, since the rewriting of the tables and virgin
105    may not be thread-safe.
106  */
107 local void fixedtables(state)
108 struct inflate_state FAR *state;
109 {
110 #ifdef BUILDFIXED
111     static int virgin = 1;
112     static code *lenfix, *distfix;
113     static code fixed[544];
114 
115     /* build fixed huffman tables if first call (may not be thread safe) */
116     if (virgin) {
117         unsigned sym, bits;
118         static code *next;
119 
120         /* literal/length table */
121         sym = 0;
122         while (sym < 144) state->lens[sym++] = 8;
123         while (sym < 256) state->lens[sym++] = 9;
124         while (sym < 280) state->lens[sym++] = 7;
125         while (sym < 288) state->lens[sym++] = 8;
126         next = fixed;
127         lenfix = next;
128         bits = 9;
129         inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
130 
131         /* distance table */
132         sym = 0;
133         while (sym < 32) state->lens[sym++] = 5;
134         distfix = next;
135         bits = 5;
136         inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
137 
138         /* do this just once */
139         virgin = 0;
140     }
141 #else /* !BUILDFIXED */
142 #   include "inffixed.h"
143 #endif /* BUILDFIXED */
144     state->lencode = lenfix;
145     state->lenbits = 9;
146     state->distcode = distfix;
147     state->distbits = 5;
148 }
149 
150 /* Macros for inflateBack(): */
151 
152 /* Load returned state from inflate_fast() */
153 #define LOAD() \
154     do { \
155         put = strm->next_out; \
156         left = strm->avail_out; \
157         next = strm->next_in; \
158         have = strm->avail_in; \
159         hold = state->hold; \
160         bits = state->bits; \
161     } while (0)
162 
163 /* Set state from registers for inflate_fast() */
164 #define RESTORE() \
165     do { \
166         strm->next_out = put; \
167         strm->avail_out = left; \
168         strm->next_in = next; \
169         strm->avail_in = have; \
170         state->hold = hold; \
171         state->bits = bits; \
172     } while (0)
173 
174 /* Clear the input bit accumulator */
175 #define INITBITS() \
176     do { \
177         hold = 0; \
178         bits = 0; \
179     } while (0)
180 
181 /* Assure that some input is available.  If input is requested, but denied,
182    then return a Z_BUF_ERROR from inflateBack(). */
183 #define PULL() \
184     do { \
185         if (have == 0) { \
186             have = in(in_desc, &next); \
187             if (have == 0) { \
188                 next = Z_NULL; \
189                 ret = Z_BUF_ERROR; \
190                 goto inf_leave; \
191             } \
192         } \
193     } while (0)
194 
195 /* Get a byte of input into the bit accumulator, or return from inflateBack()
196    with an error if there is no input available. */
197 #define PULLBYTE() \
198     do { \
199         PULL(); \
200         have--; \
201         hold += (unsigned long)(*next++) << bits; \
202         bits += 8; \
203     } while (0)
204 
205 /* Assure that there are at least n bits in the bit accumulator.  If there is
206    not enough available input to do that, then return from inflateBack() with
207    an error. */
208 #define NEEDBITS(n) \
209     do { \
210         while (bits < (unsigned)(n)) \
211             PULLBYTE(); \
212     } while (0)
213 
214 /* Return the low n bits of the bit accumulator (n < 16) */
215 #define BITS(n) \
216     ((unsigned)hold & ((1U << (n)) - 1))
217 
218 /* Remove n bits from the bit accumulator */
219 #define DROPBITS(n) \
220     do { \
221         hold >>= (n); \
222         bits -= (unsigned)(n); \
223     } while (0)
224 
225 /* Remove zero to seven bits as needed to go to a byte boundary */
226 #define BYTEBITS() \
227     do { \
228         hold >>= bits & 7; \
229         bits -= bits & 7; \
230     } while (0)
231 
232 /* Assure that some output space is available, by writing out the window
233    if it's full.  If the write fails, return from inflateBack() with a
234    Z_BUF_ERROR. */
235 #define ROOM() \
236     do { \
237         if (left == 0) { \
238             put = state->window; \
239             left = state->wsize; \
240             state->whave = left; \
241             if (out(out_desc, put, left)) { \
242                 ret = Z_BUF_ERROR; \
243                 goto inf_leave; \
244             } \
245         } \
246     } while (0)
247 
248 /*
249    strm provides the memory allocation functions and window buffer on input,
250    and provides information on the unused input on return.  For Z_DATA_ERROR
251    returns, strm will also provide an error message.
252 
253    in() and out() are the call-back input and output functions.  When
254    inflateBack() needs more input, it calls in().  When inflateBack() has
255    filled the window with output, or when it completes with data in the
256    window, it calls out() to write out the data.  The application must not
257    change the provided input until in() is called again or inflateBack()
258    returns.  The application must not change the window/output buffer until
259    inflateBack() returns.
260 
261    in() and out() are called with a descriptor parameter provided in the
262    inflateBack() call.  This parameter can be a structure that provides the
263    information required to do the read or write, as well as accumulated
264    information on the input and output such as totals and check values.
265 
266    in() should return zero on failure.  out() should return non-zero on
267    failure.  If either in() or out() fails, than inflateBack() returns a
268    Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it
269    was in() or out() that caused in the error.  Otherwise,  inflateBack()
270    returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
271    error, or Z_MEM_ERROR if it could not allocate memory for the state.
272    inflateBack() can also return Z_STREAM_ERROR if the input parameters
273    are not correct, i.e. strm is Z_NULL or the state was not initialized.
274  */
275 int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
276 z_streamp strm;
277 in_func in;
278 void FAR *in_desc;
279 out_func out;
280 void FAR *out_desc;
281 {
282     struct inflate_state FAR *state;
283     z_const unsigned char FAR *next;    /* next input */
284     unsigned char FAR *put;     /* next output */
285     unsigned have, left;        /* available input and output */
286     unsigned long hold;         /* bit buffer */
287     unsigned bits;              /* bits in bit buffer */
288     unsigned copy;              /* number of stored or match bytes to copy */
289     unsigned char FAR *from;    /* where to copy match bytes from */
290     code here;                  /* current decoding table entry */
291     code last;                  /* parent table entry */
292     unsigned len;               /* length to copy for repeats, bits to drop */
293     int ret;                    /* return code */
294     static const unsigned short order[19] = /* permutation of code lengths */
295         {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
296 
297     /* Check that the strm exists and that the state was initialized */
298     if (strm == Z_NULL || strm->state == Z_NULL)
299         return Z_STREAM_ERROR;
300     state = (struct inflate_state FAR *)strm->state;
301 
302     /* Reset the state */
303     strm->msg = Z_NULL;
304     state->mode = TYPE;
305     state->last = 0;
306     state->whave = 0;
307     next = strm->next_in;
308     have = next != Z_NULL ? strm->avail_in : 0;
309     hold = 0;
310     bits = 0;
311     put = state->window;
312     left = state->wsize;
313 
314     /* Inflate until end of block marked as last */
315     for (;;)
316         switch (state->mode) {
317         case TYPE:
318             /* determine and dispatch block type */
319             if (state->last) {
320                 BYTEBITS();
321                 state->mode = DONE;
322                 break;
323             }
324             NEEDBITS(3);
325             state->last = BITS(1);
326             DROPBITS(1);
327             switch (BITS(2)) {
328             case 0:                             /* stored block */
329                 Tracev((stderr, "inflate:     stored block%s\n",
330                         state->last ? " (last)" : ""));
331                 state->mode = STORED;
332                 break;
333             case 1:                             /* fixed block */
334                 fixedtables(state);
335                 Tracev((stderr, "inflate:     fixed codes block%s\n",
336                         state->last ? " (last)" : ""));
337                 state->mode = LEN;              /* decode codes */
338                 break;
339             case 2:                             /* dynamic block */
340                 Tracev((stderr, "inflate:     dynamic codes block%s\n",
341                         state->last ? " (last)" : ""));
342                 state->mode = TABLE;
343                 break;
344             case 3:
345                 strm->msg = (char *)"invalid block type";
346                 state->mode = BAD;
347             }
348             DROPBITS(2);
349             break;
350 
351         case STORED:
352             /* get and verify stored block length */
353             BYTEBITS();                         /* go to byte boundary */
354             NEEDBITS(32);
355             if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
356                 strm->msg = (char *)"invalid stored block lengths";
357                 state->mode = BAD;
358                 break;
359             }
360             state->length = (unsigned)hold & 0xffff;
361             Tracev((stderr, "inflate:       stored length %u\n",
362                     state->length));
363             INITBITS();
364 
365             /* copy stored block from input to output */
366             while (state->length != 0) {
367                 copy = state->length;
368                 PULL();
369                 ROOM();
370                 if (copy > have) copy = have;
371                 if (copy > left) copy = left;
372                 zmemcpy(put, next, copy);
373                 have -= copy;
374                 next += copy;
375                 left -= copy;
376                 put += copy;
377                 state->length -= copy;
378             }
379             Tracev((stderr, "inflate:       stored end\n"));
380             state->mode = TYPE;
381             break;
382 
383         case TABLE:
384             /* get dynamic table entries descriptor */
385             NEEDBITS(14);
386             state->nlen = BITS(5) + 257;
387             DROPBITS(5);
388             state->ndist = BITS(5) + 1;
389             DROPBITS(5);
390             state->ncode = BITS(4) + 4;
391             DROPBITS(4);
392 #ifndef PKZIP_BUG_WORKAROUND
393             if (state->nlen > 286 || state->ndist > 30) {
394                 strm->msg = (char *)"too many length or distance symbols";
395                 state->mode = BAD;
396                 break;
397             }
398 #endif
399             Tracev((stderr, "inflate:       table sizes ok\n"));
400 
401             /* get code length code lengths (not a typo) */
402             state->have = 0;
403             while (state->have < state->ncode) {
404                 NEEDBITS(3);
405                 state->lens[order[state->have++]] = (unsigned short)BITS(3);
406                 DROPBITS(3);
407             }
408             while (state->have < 19)
409                 state->lens[order[state->have++]] = 0;
410             state->next = state->codes;
411             state->lencode = (code const FAR *)(state->next);
412             state->lenbits = 7;
413             ret = inflate_table(CODES, state->lens, 19, &(state->next),
414                                 &(state->lenbits), state->work);
415             if (ret) {
416                 strm->msg = (char *)"invalid code lengths set";
417                 state->mode = BAD;
418                 break;
419             }
420             Tracev((stderr, "inflate:       code lengths ok\n"));
421 
422             /* get length and distance code code lengths */
423             state->have = 0;
424             while (state->have < state->nlen + state->ndist) {
425                 for (;;) {
426                     here = state->lencode[BITS(state->lenbits)];
427                     if ((unsigned)(here.bits) <= bits) break;
428                     PULLBYTE();
429                 }
430                 if (here.val < 16) {
431                     DROPBITS(here.bits);
432                     state->lens[state->have++] = here.val;
433                 }
434                 else {
435                     if (here.val == 16) {
436                         NEEDBITS(here.bits + 2);
437                         DROPBITS(here.bits);
438                         if (state->have == 0) {
439                             strm->msg = (char *)"invalid bit length repeat";
440                             state->mode = BAD;
441                             break;
442                         }
443                         len = (unsigned)(state->lens[state->have - 1]);
444                         copy = 3 + BITS(2);
445                         DROPBITS(2);
446                     }
447                     else if (here.val == 17) {
448                         NEEDBITS(here.bits + 3);
449                         DROPBITS(here.bits);
450                         len = 0;
451                         copy = 3 + BITS(3);
452                         DROPBITS(3);
453                     }
454                     else {
455                         NEEDBITS(here.bits + 7);
456                         DROPBITS(here.bits);
457                         len = 0;
458                         copy = 11 + BITS(7);
459                         DROPBITS(7);
460                     }
461                     if (state->have + copy > state->nlen + state->ndist) {
462                         strm->msg = (char *)"invalid bit length repeat";
463                         state->mode = BAD;
464                         break;
465                     }
466                     while (copy--)
467                         state->lens[state->have++] = (unsigned short)len;
468                 }
469             }
470 
471             /* handle error breaks in while */
472             if (state->mode == BAD) break;
473 
474             /* check for end-of-block code (better have one) */
475             if (state->lens[256] == 0) {
476                 strm->msg = (char *)"invalid code -- missing end-of-block";
477                 state->mode = BAD;
478                 break;
479             }
480 
481             /* build code tables -- note: do not change the lenbits or distbits
482                values here (9 and 6) without reading the comments in inftrees.h
483                concerning the ENOUGH constants, which depend on those values */
484             state->next = state->codes;
485             state->lencode = (code const FAR *)(state->next);
486             state->lenbits = 9;
487             ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
488                                 &(state->lenbits), state->work);
489             if (ret) {
490                 strm->msg = (char *)"invalid literal/lengths set";
491                 state->mode = BAD;
492                 break;
493             }
494             state->distcode = (code const FAR *)(state->next);
495             state->distbits = 6;
496             ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
497                             &(state->next), &(state->distbits), state->work);
498             if (ret) {
499                 strm->msg = (char *)"invalid distances set";
500                 state->mode = BAD;
501                 break;
502             }
503             Tracev((stderr, "inflate:       codes ok\n"));
504             state->mode = LEN;
505                 /* fallthrough */
506 
507         case LEN:
508             /* use inflate_fast() if we have enough input and output */
509             if (have >= 6 && left >= 258) {
510                 RESTORE();
511                 if (state->whave < state->wsize)
512                     state->whave = state->wsize - left;
513                 inflate_fast(strm, state->wsize);
514                 LOAD();
515                 break;
516             }
517 
518             /* get a literal, length, or end-of-block code */
519             for (;;) {
520                 here = state->lencode[BITS(state->lenbits)];
521                 if ((unsigned)(here.bits) <= bits) break;
522                 PULLBYTE();
523             }
524             if (here.op && (here.op & 0xf0) == 0) {
525                 last = here;
526                 for (;;) {
527                     here = state->lencode[last.val +
528                             (BITS(last.bits + last.op) >> last.bits)];
529                     if ((unsigned)(last.bits + here.bits) <= bits) break;
530                     PULLBYTE();
531                 }
532                 DROPBITS(last.bits);
533             }
534             DROPBITS(here.bits);
535             state->length = (unsigned)here.val;
536 
537             /* process literal */
538             if (here.op == 0) {
539                 Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
540                         "inflate:         literal '%c'\n" :
541                         "inflate:         literal 0x%02x\n", here.val));
542                 ROOM();
543                 *put++ = (unsigned char)(state->length);
544                 left--;
545                 state->mode = LEN;
546                 break;
547             }
548 
549             /* process end of block */
550             if (here.op & 32) {
551                 Tracevv((stderr, "inflate:         end of block\n"));
552                 state->mode = TYPE;
553                 break;
554             }
555 
556             /* invalid code */
557             if (here.op & 64) {
558                 strm->msg = (char *)"invalid literal/length code";
559                 state->mode = BAD;
560                 break;
561             }
562 
563             /* length code -- get extra bits, if any */
564             state->extra = (unsigned)(here.op) & 15;
565             if (state->extra != 0) {
566                 NEEDBITS(state->extra);
567                 state->length += BITS(state->extra);
568                 DROPBITS(state->extra);
569             }
570             Tracevv((stderr, "inflate:         length %u\n", state->length));
571 
572             /* get distance code */
573             for (;;) {
574                 here = state->distcode[BITS(state->distbits)];
575                 if ((unsigned)(here.bits) <= bits) break;
576                 PULLBYTE();
577             }
578             if ((here.op & 0xf0) == 0) {
579                 last = here;
580                 for (;;) {
581                     here = state->distcode[last.val +
582                             (BITS(last.bits + last.op) >> last.bits)];
583                     if ((unsigned)(last.bits + here.bits) <= bits) break;
584                     PULLBYTE();
585                 }
586                 DROPBITS(last.bits);
587             }
588             DROPBITS(here.bits);
589             if (here.op & 64) {
590                 strm->msg = (char *)"invalid distance code";
591                 state->mode = BAD;
592                 break;
593             }
594             state->offset = (unsigned)here.val;
595 
596             /* get distance extra bits, if any */
597             state->extra = (unsigned)(here.op) & 15;
598             if (state->extra != 0) {
599                 NEEDBITS(state->extra);
600                 state->offset += BITS(state->extra);
601                 DROPBITS(state->extra);
602             }
603             if (state->offset > state->wsize - (state->whave < state->wsize ?
604                                                 left : 0)) {
605                 strm->msg = (char *)"invalid distance too far back";
606                 state->mode = BAD;
607                 break;
608             }
609             Tracevv((stderr, "inflate:         distance %u\n", state->offset));
610 
611             /* copy match from window to output */
612             do {
613                 ROOM();
614                 copy = state->wsize - state->offset;
615                 if (copy < left) {
616                     from = put + copy;
617                     copy = left - copy;
618                 }
619                 else {
620                     from = put - state->offset;
621                     copy = left;
622                 }
623                 if (copy > state->length) copy = state->length;
624                 state->length -= copy;
625                 left -= copy;
626                 do {
627                     *put++ = *from++;
628                 } while (--copy);
629             } while (state->length != 0);
630             break;
631 
632         case DONE:
633             /* inflate stream terminated properly */
634             ret = Z_STREAM_END;
635             goto inf_leave;
636 
637         case BAD:
638             ret = Z_DATA_ERROR;
639             goto inf_leave;
640 
641         default:
642             /* can't happen, but makes compilers happy */
643             ret = Z_STREAM_ERROR;
644             goto inf_leave;
645         }
646 
647     /* Write leftover output and return unused input */
648   inf_leave:
649     if (left < state->wsize) {
650         if (out(out_desc, state->window, state->wsize - left) &&
651             ret == Z_STREAM_END)
652             ret = Z_BUF_ERROR;
653     }
654     strm->next_in = next;
655     strm->avail_in = have;
656     return ret;
657 }
658 
659 int ZEXPORT inflateBackEnd(strm)
660 z_streamp strm;
661 {
662     if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
663         return Z_STREAM_ERROR;
664     ZFREE(strm, strm->state);
665     strm->state = Z_NULL;
666     Tracev((stderr, "inflate: end\n"));
667     return Z_OK;
668 }