io: add a GRUB_GZ prefix to gzio specific defines
[grub.git] / grub-core / io / gzio.c
1 /* gzio.c - decompression support for gzip */
2 /*
3  *  GRUB  --  GRand Unified Bootloader
4  *  Copyright (C) 1999,2005,2006,2007,2009  Free Software Foundation, Inc.
5  *
6  *  GRUB is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  GRUB is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /*
21  * Most of this file was originally the source file "inflate.c", written
22  * by Mark Adler.  It has been very heavily modified.  In particular, the
23  * original would run through the whole file at once, and this version can
24  * be stopped and restarted on any boundary during the decompression process.
25  *
26  * The license and header comments that file are included here.
27  */
28
29 /* inflate.c -- Not copyrighted 1992 by Mark Adler
30    version c10p1, 10 January 1993 */
31
32 /* You can do whatever you like with this source file, though I would
33    prefer that if you modify it and redistribute it that you include
34    comments to that effect with your name and the date.  Thank you.
35  */
36
37 #include <grub/err.h>
38 #include <grub/types.h>
39 #include <grub/mm.h>
40 #include <grub/misc.h>
41 #include <grub/fs.h>
42 #include <grub/file.h>
43 #include <grub/dl.h>
44 #include <grub/deflate.h>
45 #include <grub/i18n.h>
46
47 GRUB_MOD_LICENSE ("GPLv3+");
48
49 /*
50  *  Window Size
51  *
52  *  This must be a power of two, and at least 32K for zip's deflate method
53  */
54
55 #define WSIZE   0x8000
56
57
58 #define INBUFSIZ  0x2000
59
60 /* The state stored in filesystem-specific data.  */
61 struct grub_gzio
62 {
63   /* The underlying file object.  */
64   grub_file_t file;
65   /* If input is in memory following fields are used instead of file.  */
66   grub_size_t mem_input_size, mem_input_off;
67   grub_uint8_t *mem_input;
68   /* The offset at which the data starts in the underlying file.  */
69   grub_off_t data_offset;
70   /* The type of current block.  */
71   int block_type;
72   /* The length of current block.  */
73   int block_len;
74   /* The flag of the last block.  */
75   int last_block;
76   /* The flag of codes.  */
77   int code_state;
78   /* The length of a copy.  */
79   unsigned inflate_n;
80   /* The index of a copy.  */
81   unsigned inflate_d;
82   /* The input buffer.  */
83   grub_uint8_t inbuf[INBUFSIZ];
84   int inbuf_d;
85   /* The bit buffer.  */
86   unsigned long bb;
87   /* The bits in the bit buffer.  */
88   unsigned bk;
89   /* The sliding window in uncompressed data.  */
90   grub_uint8_t slide[WSIZE];
91   /* Current position in the slide.  */
92   unsigned wp;
93   /* The literal/length code table.  */
94   struct huft *tl;
95   /* The distance code table.  */
96   struct huft *td;
97   /* The lookup bits for the literal/length code table. */
98   int bl;
99   /* The lookup bits for the distance code table.  */
100   int bd;
101   /* The original offset value.  */
102   grub_off_t saved_offset;
103 };
104 typedef struct grub_gzio *grub_gzio_t;
105
106 /* Declare the filesystem structure for grub_gzio_open.  */
107 static struct grub_fs grub_gzio_fs;
108
109 /* Function prototypes */
110 static void initialize_tables (grub_gzio_t);
111
112 /* Eat variable-length header fields.  */
113 static int
114 eat_field (grub_file_t file, int len)
115 {
116   char ch = 1;
117   int not_retval = 1;
118
119   do
120     {
121       if (len >= 0)
122         {
123           if (! (len--))
124             break;
125         }
126       else
127         {
128           if (! ch)
129             break;
130         }
131     }
132   while ((not_retval = grub_file_read (file, &ch, 1)) == 1);
133
134   return ! not_retval;
135 }
136
137
138 /* Little-Endian defines for the 2-byte magic numbers for gzip files.  */
139 #define GZIP_MAGIC      grub_le_to_cpu16 (0x8B1F)
140 #define OLD_GZIP_MAGIC  grub_le_to_cpu16 (0x9E1F)
141
142 /* Compression methods (see algorithm.doc) */
143 #define GRUB_GZ_STORED      0
144 #define GRUB_GZ_COMPRESSED  1
145 #define GRUB_GZ_PACKED      2
146 #define GRUB_GZ_LZHED       3
147 /* methods 4 to 7 reserved */
148 #define GRUB_GZ_DEFLATED    8
149 #define GRUB_GZ_MAX_METHODS 9
150
151 /* gzip flag byte */
152 #define GRUB_GZ_ASCII_FLAG   0x01       /* bit 0 set: file probably ascii text */
153 #define GRUB_GZ_CONTINUATION 0x02       /* bit 1 set: continuation of multi-part gzip file */
154 #define GRUB_GZ_EXTRA_FIELD  0x04       /* bit 2 set: extra field present */
155 #define GRUB_GZ_ORIG_NAME    0x08       /* bit 3 set: original file name present */
156 #define GRUB_GZ_COMMENT      0x10       /* bit 4 set: file comment present */
157 #define GRUB_GZ_ENCRYPTED    0x20       /* bit 5 set: file is encrypted */
158 #define GRUB_GZ_RESERVED     0xC0       /* bit 6,7:   reserved */
159
160 #define GRUB_GZ_UNSUPPORTED_FLAGS       (GRUB_GZ_CONTINUATION | GRUB_GZ_ENCRYPTED | GRUB_GZ_RESERVED)
161
162 /* inflate block codes */
163 #define INFLATE_STORED  0
164 #define INFLATE_FIXED   1
165 #define INFLATE_DYNAMIC 2
166
167 typedef unsigned char uch;
168 typedef unsigned short ush;
169 typedef unsigned long ulg;
170
171 static int
172 test_gzip_header (grub_file_t file)
173 {
174   struct {
175     grub_uint16_t magic;
176     grub_uint8_t method;
177     grub_uint8_t flags;
178     grub_uint32_t timestamp;
179     grub_uint8_t extra_flags;
180     grub_uint8_t os_type;
181   } hdr;
182   grub_uint16_t extra_len;
183   grub_uint32_t orig_len;
184   grub_gzio_t gzio = file->data;
185
186   if (grub_file_tell (gzio->file) != 0)
187     grub_file_seek (gzio->file, 0);
188
189   /*
190    *  This checks if the file is gzipped.  If a problem occurs here
191    *  (other than a real error with the disk) then we don't think it
192    *  is a compressed file, and simply mark it as such.
193    */
194   if (grub_file_read (gzio->file, &hdr, 10) != 10
195       || ((hdr.magic != GZIP_MAGIC)
196           && (hdr.magic != OLD_GZIP_MAGIC)))
197     return 0;
198
199   /*
200    *  This does consistency checking on the header data.  If a
201    *  problem occurs from here on, then we have corrupt or otherwise
202    *  bad data, and the error should be reported to the user.
203    */
204   if (hdr.method != GRUB_GZ_DEFLATED
205       || (hdr.flags & GRUB_GZ_UNSUPPORTED_FLAGS)
206       || ((hdr.flags & GRUB_GZ_EXTRA_FIELD)
207           && (grub_file_read (gzio->file, &extra_len, 2) != 2
208               || eat_field (gzio->file,
209                             grub_le_to_cpu16 (extra_len))))
210       || ((hdr.flags & GRUB_GZ_ORIG_NAME) && eat_field (gzio->file, -1))
211       || ((hdr.flags & GRUB_GZ_COMMENT) && eat_field (gzio->file, -1)))
212     return 0;
213
214   gzio->data_offset = grub_file_tell (gzio->file);
215
216   /* FIXME: don't do this on not easily seekable files.  */
217   {
218     grub_file_seek (gzio->file, grub_file_size (gzio->file) - 4);
219     if (grub_file_read (gzio->file, &orig_len, 4) != 4)
220       return 0;
221     /* FIXME: this does not handle files whose original size is over 4GB.
222        But how can we know the real original size?  */
223     file->size = grub_le_to_cpu32 (orig_len);
224   }
225
226   initialize_tables (gzio);
227
228   return 1;
229 }
230
231
232 /* Huffman code lookup table entry--this entry is four bytes for machines
233    that have 16-bit pointers (e.g. PC's in the small or medium model).
234    Valid extra bits are 0..13.  e == 15 is EOB (end of block), e == 16
235    means that v is a literal, 16 < e < 32 means that v is a pointer to
236    the next table, which codes e - 16 bits, and lastly e == 99 indicates
237    an unused code.  If a code with e == 99 is looked up, this implies an
238    error in the data. */
239 struct huft
240 {
241   uch e;                        /* number of extra bits or operation */
242   uch b;                        /* number of bits in this code or subcode */
243   union
244     {
245       ush n;                    /* literal, length base, or distance base */
246       struct huft *t;           /* pointer to next level of table */
247     }
248   v;
249 };
250
251
252 /* The inflate algorithm uses a sliding 32K byte window on the uncompressed
253    stream to find repeated byte strings.  This is implemented here as a
254    circular buffer.  The index is updated simply by incrementing and then
255    and'ing with 0x7fff (32K-1). */
256 /* It is left to other modules to supply the 32K area.  It is assumed
257    to be usable as if it were declared "uch slide[32768];" or as just
258    "uch *slide;" and then malloc'ed in the latter case.  The definition
259    must be in unzip.h, included above. */
260
261
262 /* Tables for deflate from PKZIP's appnote.txt. */
263 static unsigned bitorder[] =
264 {                               /* Order of the bit length code lengths */
265   16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
266 static ush cplens[] =
267 {                               /* Copy lengths for literal codes 257..285 */
268   3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
269   35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
270         /* note: see note #13 above about the 258 in this list. */
271 static ush cplext[] =
272 {                               /* Extra bits for literal codes 257..285 */
273   0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
274   3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99};       /* 99==invalid */
275 static ush cpdist[] =
276 {                               /* Copy offsets for distance codes 0..29 */
277   1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
278   257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
279   8193, 12289, 16385, 24577};
280 static ush cpdext[] =
281 {                               /* Extra bits for distance codes */
282   0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
283   7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
284   12, 12, 13, 13};
285
286
287 /*
288    Huffman code decoding is performed using a multi-level table lookup.
289    The fastest way to decode is to simply build a lookup table whose
290    size is determined by the longest code.  However, the time it takes
291    to build this table can also be a factor if the data being decoded
292    is not very long.  The most common codes are necessarily the
293    shortest codes, so those codes dominate the decoding time, and hence
294    the speed.  The idea is you can have a shorter table that decodes the
295    shorter, more probable codes, and then point to subsidiary tables for
296    the longer codes.  The time it costs to decode the longer codes is
297    then traded against the time it takes to make longer tables.
298
299    This results of this trade are in the variables lbits and dbits
300    below.  lbits is the number of bits the first level table for literal/
301    length codes can decode in one step, and dbits is the same thing for
302    the distance codes.  Subsequent tables are also less than or equal to
303    those sizes.  These values may be adjusted either when all of the
304    codes are shorter than that, in which case the longest code length in
305    bits is used, or when the shortest code is *longer* than the requested
306    table size, in which case the length of the shortest code in bits is
307    used.
308
309    There are two different values for the two tables, since they code a
310    different number of possibilities each.  The literal/length table
311    codes 286 possible values, or in a flat code, a little over eight
312    bits.  The distance table codes 30 possible values, or a little less
313    than five bits, flat.  The optimum values for speed end up being
314    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
315    The optimum values may differ though from machine to machine, and
316    possibly even between compilers.  Your mileage may vary.
317  */
318
319
320 static int lbits = 9;           /* bits in base literal/length lookup table */
321 static int dbits = 6;           /* bits in base distance lookup table */
322
323
324 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
325 #define BMAX 16                 /* maximum bit length of any code (16 for explode) */
326 #define N_MAX 288               /* maximum number of codes in any set */
327
328
329 /* Macros for inflate() bit peeking and grabbing.
330    The usage is:
331
332         NEEDBITS(j)
333         x = b & mask_bits[j];
334         DUMPBITS(j)
335
336    where NEEDBITS makes sure that b has at least j bits in it, and
337    DUMPBITS removes the bits from b.  The macros use the variable k
338    for the number of bits in b.  Normally, b and k are register
339    variables for speed, and are initialized at the beginning of a
340    routine that uses these macros from a global bit buffer and count.
341
342    If we assume that EOB will be the longest code, then we will never
343    ask for bits with NEEDBITS that are beyond the end of the stream.
344    So, NEEDBITS should not read any more bytes than are needed to
345    meet the request.  Then no bytes need to be "returned" to the buffer
346    at the end of the last block.
347
348    However, this assumption is not true for fixed blocks--the EOB code
349    is 7 bits, but the other literal/length codes can be 8 or 9 bits.
350    (The EOB code is shorter than other codes because fixed blocks are
351    generally short.  So, while a block always has an EOB, many other
352    literal/length codes have a significantly lower probability of
353    showing up at all.)  However, by making the first table have a
354    lookup of seven bits, the EOB code will be found in that first
355    lookup, and so will not require that too many bits be pulled from
356    the stream.
357  */
358
359 static ush mask_bits[] =
360 {
361   0x0000,
362   0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
363   0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
364 };
365
366 #define NEEDBITS(n) do {while(k<(n)){b|=((ulg)get_byte(gzio))<<k;k+=8;}} while (0)
367 #define DUMPBITS(n) do {b>>=(n);k-=(n);} while (0)
368
369 static int
370 get_byte (grub_gzio_t gzio)
371 {
372   if (gzio->mem_input)
373     {
374       if (gzio->mem_input_off < gzio->mem_input_size)
375         return gzio->mem_input[gzio->mem_input_off++];
376       return 0;
377     }
378
379   if (gzio->file && (grub_file_tell (gzio->file)
380                      == (grub_off_t) gzio->data_offset
381                      || gzio->inbuf_d == INBUFSIZ))
382     {
383       gzio->inbuf_d = 0;
384       grub_file_read (gzio->file, gzio->inbuf, INBUFSIZ);
385     }
386
387   return gzio->inbuf[gzio->inbuf_d++];
388 }
389
390 static void
391 gzio_seek (grub_gzio_t gzio, grub_off_t off)
392 {
393   if (gzio->mem_input)
394     {
395       if (off > gzio->mem_input_size)
396         grub_error (GRUB_ERR_OUT_OF_RANGE,
397                     N_("attempt to seek outside of the file"));
398       else
399         gzio->mem_input_off = off;
400     }
401   else
402     grub_file_seek (gzio->file, off);
403 }
404
405 /* more function prototypes */
406 static int huft_build (unsigned *, unsigned, unsigned, ush *, ush *,
407                        struct huft **, int *);
408 static int huft_free (struct huft *);
409 static int inflate_codes_in_window (grub_gzio_t);
410
411
412 /* Given a list of code lengths and a maximum table size, make a set of
413    tables to decode that set of codes.  Return zero on success, one if
414    the given code set is incomplete (the tables are still built in this
415    case), two if the input is invalid (all zero length codes or an
416    oversubscribed set of lengths), and three if not enough memory. */
417
418 static int
419 huft_build (unsigned *b,        /* code lengths in bits (all assumed <= BMAX) */
420             unsigned n,         /* number of codes (assumed <= N_MAX) */
421             unsigned s,         /* number of simple-valued codes (0..s-1) */
422             ush * d,            /* list of base values for non-simple codes */
423             ush * e,            /* list of extra bits for non-simple codes */
424             struct huft **t,    /* result: starting table */
425             int *m)             /* maximum lookup bits, returns actual */
426 {
427   unsigned a;                   /* counter for codes of length k */
428   unsigned c[BMAX + 1];         /* bit length count table */
429   unsigned f;                   /* i repeats in table every f entries */
430   int g;                        /* maximum code length */
431   int h;                        /* table level */
432   register unsigned i;          /* counter, current code */
433   register unsigned j;          /* counter */
434   register int k;               /* number of bits in current code */
435   int l;                        /* bits per table (returned in m) */
436   register unsigned *p;         /* pointer into c[], b[], or v[] */
437   register struct huft *q;      /* points to current table */
438   struct huft r;                /* table entry for structure assignment */
439   struct huft *u[BMAX];         /* table stack */
440   unsigned v[N_MAX];            /* values in order of bit length */
441   register int w;               /* bits before this table == (l * h) */
442   unsigned x[BMAX + 1];         /* bit offsets, then code stack */
443   unsigned *xp;                 /* pointer into x */
444   int y;                        /* number of dummy codes added */
445   unsigned z;                   /* number of entries in current table */
446
447   /* Generate counts for each bit length */
448   grub_memset ((char *) c, 0, sizeof (c));
449   p = b;
450   i = n;
451   do
452     {
453       c[*p]++;                  /* assume all entries <= BMAX */
454       p++;                      /* Can't combine with above line (Solaris bug) */
455     }
456   while (--i);
457   if (c[0] == n)                /* null input--all zero length codes */
458     {
459       *t = (struct huft *) NULL;
460       *m = 0;
461       return 0;
462     }
463
464   /* Find minimum and maximum length, bound *m by those */
465   l = *m;
466   for (j = 1; j <= BMAX; j++)
467     if (c[j])
468       break;
469   k = j;                        /* minimum code length */
470   if ((unsigned) l < j)
471     l = j;
472   for (i = BMAX; i; i--)
473     if (c[i])
474       break;
475   g = i;                        /* maximum code length */
476   if ((unsigned) l > i)
477     l = i;
478   *m = l;
479
480   /* Adjust last length count to fill out codes, if needed */
481   for (y = 1 << j; j < i; j++, y <<= 1)
482     if ((y -= c[j]) < 0)
483       return 2;                 /* bad input: more codes than bits */
484   if ((y -= c[i]) < 0)
485     return 2;
486   c[i] += y;
487
488   /* Generate starting offsets into the value table for each length */
489   x[1] = j = 0;
490   p = c + 1;
491   xp = x + 2;
492   while (--i)
493     {                           /* note that i == g from above */
494       *xp++ = (j += *p++);
495     }
496
497   /* Make a table of values in order of bit lengths */
498   p = b;
499   i = 0;
500   do
501     {
502       if ((j = *p++) != 0)
503         v[x[j]++] = i;
504     }
505   while (++i < n);
506
507   /* Generate the Huffman codes and for each, make the table entries */
508   x[0] = i = 0;                 /* first Huffman code is zero */
509   p = v;                        /* grab values in bit order */
510   h = -1;                       /* no tables yet--level -1 */
511   w = -l;                       /* bits decoded == (l * h) */
512   u[0] = (struct huft *) NULL;  /* just to keep compilers happy */
513   q = (struct huft *) NULL;     /* ditto */
514   z = 0;                        /* ditto */
515
516   /* go through the bit lengths (k already is bits in shortest code) */
517   for (; k <= g; k++)
518     {
519       a = c[k];
520       while (a--)
521         {
522           /* here i is the Huffman code of length k bits for value *p */
523           /* make tables up to required level */
524           while (k > w + l)
525             {
526               h++;
527               w += l;           /* previous table always l bits */
528
529               /* compute minimum size table less than or equal to l bits */
530               z = (z = (unsigned) (g - w)) > (unsigned) l ? (unsigned) l : z;   /* upper limit on table size */
531               if ((f = 1 << (j = k - w)) > a + 1)       /* try a k-w bit table */
532                 {               /* too few codes for k-w bit table */
533                   f -= a + 1;   /* deduct codes from patterns left */
534                   xp = c + k;
535                   while (++j < z)       /* try smaller tables up to z bits */
536                     {
537                       if ((f <<= 1) <= *++xp)
538                         break;  /* enough codes to use up j bits */
539                       f -= *xp; /* else deduct codes from patterns */
540                     }
541                 }
542               z = 1 << j;       /* table entries for j-bit table */
543
544               /* allocate and link in new table */
545               q = (struct huft *) grub_zalloc ((z + 1) * sizeof (struct huft));
546               if (! q)
547                 {
548                   if (h)
549                     huft_free (u[0]);
550                   return 3;
551                 }
552
553               *t = q + 1;       /* link to list for huft_free() */
554               *(t = &(q->v.t)) = (struct huft *) NULL;
555               u[h] = ++q;       /* table starts after link */
556
557               /* connect to last table, if there is one */
558               if (h)
559                 {
560                   x[h] = i;     /* save pattern for backing up */
561                   r.b = (uch) l;        /* bits to dump before this table */
562                   r.e = (uch) (16 + j);         /* bits in this table */
563                   r.v.t = q;    /* pointer to this table */
564                   j = i >> (w - l);     /* (get around Turbo C bug) */
565                   u[h - 1][j] = r;      /* connect to last table */
566                 }
567             }
568
569           /* set up table entry in r */
570           r.b = (uch) (k - w);
571           if (p >= v + n)
572             r.e = 99;           /* out of values--invalid code */
573           else if (*p < s)
574             {
575               r.e = (uch) (*p < 256 ? 16 : 15);         /* 256 is end-of-block code */
576               r.v.n = (ush) (*p);       /* simple code is just the value */
577               p++;              /* one compiler does not like *p++ */
578             }
579           else
580             {
581               r.e = (uch) e[*p - s];    /* non-simple--look up in lists */
582               r.v.n = d[*p++ - s];
583             }
584
585           /* fill code-like entries with r */
586           f = 1 << (k - w);
587           for (j = i >> w; j < z; j += f)
588             q[j] = r;
589
590           /* backwards increment the k-bit code i */
591           for (j = 1 << (k - 1); i & j; j >>= 1)
592             i ^= j;
593           i ^= j;
594
595           /* backup over finished tables */
596           while ((i & ((1 << w) - 1)) != x[h])
597             {
598               h--;              /* don't need to update q */
599               w -= l;
600             }
601         }
602     }
603
604   /* Return true (1) if we were given an incomplete table */
605   return y != 0 && g != 1;
606 }
607
608
609 /* Free the malloc'ed tables built by huft_build(), which makes a linked
610    list of the tables it made, with the links in a dummy first entry of
611    each table.  */
612 static int
613 huft_free (struct huft *t)
614 {
615   register struct huft *p, *q;
616
617
618   /* Go through linked list, freeing from the malloced (t[-1]) address. */
619   p = t;
620   while (p != (struct huft *) NULL)
621     {
622       q = (--p)->v.t;
623       grub_free ((char *) p);
624       p = q;
625     }
626   return 0;
627 }
628
629
630 /*
631  *  inflate (decompress) the codes in a deflated (compressed) block.
632  *  Return an error code or zero if it all goes ok.
633  */
634
635 static int
636 inflate_codes_in_window (grub_gzio_t gzio)
637 {
638   register unsigned e;          /* table entry flag/number of extra bits */
639   unsigned n, d;                /* length and index for copy */
640   unsigned w;                   /* current window position */
641   struct huft *t;               /* pointer to table entry */
642   unsigned ml, md;              /* masks for bl and bd bits */
643   register ulg b;               /* bit buffer */
644   register unsigned k;          /* number of bits in bit buffer */
645
646   /* make local copies of globals */
647   d = gzio->inflate_d;
648   n = gzio->inflate_n;
649   b = gzio->bb;                 /* initialize bit buffer */
650   k = gzio->bk;
651   w = gzio->wp;                 /* initialize window position */
652
653   /* inflate the coded data */
654   ml = mask_bits[gzio->bl];             /* precompute masks for speed */
655   md = mask_bits[gzio->bd];
656   for (;;)                      /* do until end of block */
657     {
658       if (! gzio->code_state)
659         {
660           NEEDBITS ((unsigned) gzio->bl);
661           if ((e = (t = gzio->tl + ((unsigned) b & ml))->e) > 16)
662             do
663               {
664                 if (e == 99)
665                   {
666                     grub_error (GRUB_ERR_BAD_COMPRESSED_DATA,
667                                 "an unused code found");
668                     return 1;
669                   }
670                 DUMPBITS (t->b);
671                 e -= 16;
672                 NEEDBITS (e);
673               }
674             while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e) > 16);
675           DUMPBITS (t->b);
676
677           if (e == 16)          /* then it's a literal */
678             {
679               gzio->slide[w++] = (uch) t->v.n;
680               if (w == WSIZE)
681                 break;
682             }
683           else
684             /* it's an EOB or a length */
685             {
686               /* exit if end of block */
687               if (e == 15)
688                 {
689                   gzio->block_len = 0;
690                   break;
691                 }
692
693               /* get length of block to copy */
694               NEEDBITS (e);
695               n = t->v.n + ((unsigned) b & mask_bits[e]);
696               DUMPBITS (e);
697
698               /* decode distance of block to copy */
699               NEEDBITS ((unsigned) gzio->bd);
700               if ((e = (t = gzio->td + ((unsigned) b & md))->e) > 16)
701                 do
702                   {
703                     if (e == 99)
704                       {
705                         grub_error (GRUB_ERR_BAD_COMPRESSED_DATA,
706                                     "an unused code found");
707                         return 1;
708                       }
709                     DUMPBITS (t->b);
710                     e -= 16;
711                     NEEDBITS (e);
712                   }
713                 while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e)
714                        > 16);
715               DUMPBITS (t->b);
716               NEEDBITS (e);
717               d = w - t->v.n - ((unsigned) b & mask_bits[e]);
718               DUMPBITS (e);
719               gzio->code_state++;
720             }
721         }
722
723       if (gzio->code_state)
724         {
725           /* do the copy */
726           do
727             {
728               n -= (e = (e = WSIZE - ((d &= WSIZE - 1) > w ? d : w)) > n ? n
729                     : e);
730
731               if (w - d >= e)
732                 {
733                   grub_memmove (gzio->slide + w, gzio->slide + d, e);
734                   w += e;
735                   d += e;
736                 }
737               else
738                 /* purposefully use the overlap for extra copies here!! */
739                 {
740                   while (e--)
741                     gzio->slide[w++] = gzio->slide[d++];
742                 }
743
744               if (w == WSIZE)
745                 break;
746             }
747           while (n);
748
749           if (! n)
750             gzio->code_state--;
751
752           /* did we break from the loop too soon? */
753           if (w == WSIZE)
754             break;
755         }
756     }
757
758   /* restore the globals from the locals */
759   gzio->inflate_d = d;
760   gzio->inflate_n = n;
761   gzio->wp = w;                 /* restore global window pointer */
762   gzio->bb = b;                 /* restore global bit buffer */
763   gzio->bk = k;
764
765   return ! gzio->block_len;
766 }
767
768
769 /* get header for an inflated type 0 (stored) block. */
770
771 static void
772 init_stored_block (grub_gzio_t gzio)
773 {
774   register ulg b;               /* bit buffer */
775   register unsigned k;          /* number of bits in bit buffer */
776
777   /* make local copies of globals */
778   b = gzio->bb;                 /* initialize bit buffer */
779   k = gzio->bk;
780
781   /* go to byte boundary */
782   DUMPBITS (k & 7);
783
784   /* get the length and its complement */
785   NEEDBITS (16);
786   gzio->block_len = ((unsigned) b & 0xffff);
787   DUMPBITS (16);
788   NEEDBITS (16);
789   if (gzio->block_len != (int) ((~b) & 0xffff))
790     grub_error (GRUB_ERR_BAD_COMPRESSED_DATA,
791                 "the length of a stored block does not match");
792   DUMPBITS (16);
793
794   /* restore global variables */
795   gzio->bb = b;
796   gzio->bk = k;
797 }
798
799
800 /* get header for an inflated type 1 (fixed Huffman codes) block.  We should
801    either replace this with a custom decoder, or at least precompute the
802    Huffman tables. */
803
804 static void
805 init_fixed_block (grub_gzio_t gzio)
806 {
807   int i;                        /* temporary variable */
808   unsigned l[288];              /* length list for huft_build */
809
810   /* set up literal table */
811   for (i = 0; i < 144; i++)
812     l[i] = 8;
813   for (; i < 256; i++)
814     l[i] = 9;
815   for (; i < 280; i++)
816     l[i] = 7;
817   for (; i < 288; i++)          /* make a complete, but wrong code set */
818     l[i] = 8;
819   gzio->bl = 7;
820   if (huft_build (l, 288, 257, cplens, cplext, &gzio->tl, &gzio->bl) != 0)
821     {
822       if (grub_errno == GRUB_ERR_NONE)
823         grub_error (GRUB_ERR_BAD_COMPRESSED_DATA,
824                     "failed in building a Huffman code table");
825       return;
826     }
827
828   /* set up distance table */
829   for (i = 0; i < 30; i++)      /* make an incomplete code set */
830     l[i] = 5;
831   gzio->bd = 5;
832   if (huft_build (l, 30, 0, cpdist, cpdext, &gzio->td, &gzio->bd) > 1)
833     {
834       if (grub_errno == GRUB_ERR_NONE)
835         grub_error (GRUB_ERR_BAD_COMPRESSED_DATA,
836                     "failed in building a Huffman code table");
837       huft_free (gzio->tl);
838       gzio->tl = 0;
839       return;
840     }
841
842   /* indicate we're now working on a block */
843   gzio->code_state = 0;
844   gzio->block_len++;
845 }
846
847
848 /* get header for an inflated type 2 (dynamic Huffman codes) block. */
849
850 static void
851 init_dynamic_block (grub_gzio_t gzio)
852 {
853   int i;                        /* temporary variables */
854   unsigned j;
855   unsigned l;                   /* last length */
856   unsigned m;                   /* mask for bit lengths table */
857   unsigned n;                   /* number of lengths to get */
858   unsigned nb;                  /* number of bit length codes */
859   unsigned nl;                  /* number of literal/length codes */
860   unsigned nd;                  /* number of distance codes */
861   unsigned ll[286 + 30];        /* literal/length and distance code lengths */
862   register ulg b;               /* bit buffer */
863   register unsigned k;          /* number of bits in bit buffer */
864
865   /* make local bit buffer */
866   b = gzio->bb;
867   k = gzio->bk;
868
869   /* read in table lengths */
870   NEEDBITS (5);
871   nl = 257 + ((unsigned) b & 0x1f);     /* number of literal/length codes */
872   DUMPBITS (5);
873   NEEDBITS (5);
874   nd = 1 + ((unsigned) b & 0x1f);       /* number of distance codes */
875   DUMPBITS (5);
876   NEEDBITS (4);
877   nb = 4 + ((unsigned) b & 0xf);        /* number of bit length codes */
878   DUMPBITS (4);
879   if (nl > 286 || nd > 30)
880     {
881       grub_error (GRUB_ERR_BAD_COMPRESSED_DATA, "too much data");
882       return;
883     }
884
885   /* read in bit-length-code lengths */
886   for (j = 0; j < nb; j++)
887     {
888       NEEDBITS (3);
889       ll[bitorder[j]] = (unsigned) b & 7;
890       DUMPBITS (3);
891     }
892   for (; j < 19; j++)
893     ll[bitorder[j]] = 0;
894
895   /* build decoding table for trees--single level, 7 bit lookup */
896   gzio->bl = 7;
897   if (huft_build (ll, 19, 19, NULL, NULL, &gzio->tl, &gzio->bl) != 0)
898     {
899       grub_error (GRUB_ERR_BAD_COMPRESSED_DATA,
900                   "failed in building a Huffman code table");
901       return;
902     }
903
904   /* read in literal and distance code lengths */
905   n = nl + nd;
906   m = mask_bits[gzio->bl];
907   i = l = 0;
908   while ((unsigned) i < n)
909     {
910       NEEDBITS ((unsigned) gzio->bl);
911       j = (gzio->td = gzio->tl + ((unsigned) b & m))->b;
912       DUMPBITS (j);
913       j = gzio->td->v.n;
914       if (j < 16)               /* length of code in bits (0..15) */
915         ll[i++] = l = j;        /* save last length in l */
916       else if (j == 16)         /* repeat last length 3 to 6 times */
917         {
918           NEEDBITS (2);
919           j = 3 + ((unsigned) b & 3);
920           DUMPBITS (2);
921           if ((unsigned) i + j > n)
922             {
923               grub_error (GRUB_ERR_BAD_COMPRESSED_DATA, "too many codes found");
924               return;
925             }
926           while (j--)
927             ll[i++] = l;
928         }
929       else if (j == 17)         /* 3 to 10 zero length codes */
930         {
931           NEEDBITS (3);
932           j = 3 + ((unsigned) b & 7);
933           DUMPBITS (3);
934           if ((unsigned) i + j > n)
935             {
936               grub_error (GRUB_ERR_BAD_COMPRESSED_DATA, "too many codes found");
937               return;
938             }
939           while (j--)
940             ll[i++] = 0;
941           l = 0;
942         }
943       else
944         /* j == 18: 11 to 138 zero length codes */
945         {
946           NEEDBITS (7);
947           j = 11 + ((unsigned) b & 0x7f);
948           DUMPBITS (7);
949           if ((unsigned) i + j > n)
950             {
951               grub_error (GRUB_ERR_BAD_COMPRESSED_DATA, "too many codes found");
952               return;
953             }
954           while (j--)
955             ll[i++] = 0;
956           l = 0;
957         }
958     }
959
960   /* free decoding table for trees */
961   huft_free (gzio->tl);
962   gzio->td = 0;
963   gzio->tl = 0;
964
965   /* restore the global bit buffer */
966   gzio->bb = b;
967   gzio->bk = k;
968
969   /* build the decoding tables for literal/length and distance codes */
970   gzio->bl = lbits;
971   if (huft_build (ll, nl, 257, cplens, cplext, &gzio->tl, &gzio->bl) != 0)
972     {
973       grub_error (GRUB_ERR_BAD_COMPRESSED_DATA,
974                   "failed in building a Huffman code table");
975       return;
976     }
977   gzio->bd = dbits;
978   if (huft_build (ll + nl, nd, 0, cpdist, cpdext, &gzio->td, &gzio->bd) != 0)
979     {
980       huft_free (gzio->tl);
981       gzio->tl = 0;
982       grub_error (GRUB_ERR_BAD_COMPRESSED_DATA,
983                   "failed in building a Huffman code table");
984       return;
985     }
986
987   /* indicate we're now working on a block */
988   gzio->code_state = 0;
989   gzio->block_len++;
990 }
991
992
993 static void
994 get_new_block (grub_gzio_t gzio)
995 {
996   register ulg b;               /* bit buffer */
997   register unsigned k;          /* number of bits in bit buffer */
998
999   /* make local bit buffer */
1000   b = gzio->bb;
1001   k = gzio->bk;
1002
1003   /* read in last block bit */
1004   NEEDBITS (1);
1005   gzio->last_block = (int) b & 1;
1006   DUMPBITS (1);
1007
1008   /* read in block type */
1009   NEEDBITS (2);
1010   gzio->block_type = (unsigned) b & 3;
1011   DUMPBITS (2);
1012
1013   /* restore the global bit buffer */
1014   gzio->bb = b;
1015   gzio->bk = k;
1016
1017   switch (gzio->block_type)
1018     {
1019     case INFLATE_STORED:
1020       init_stored_block (gzio);
1021       break;
1022     case INFLATE_FIXED:
1023       init_fixed_block (gzio);
1024       break;
1025     case INFLATE_DYNAMIC:
1026       init_dynamic_block (gzio);
1027       break;
1028     default:
1029       break;
1030     }
1031 }
1032
1033
1034 static void
1035 inflate_window (grub_gzio_t gzio)
1036 {
1037   /* initialize window */
1038   gzio->wp = 0;
1039
1040   /*
1041    *  Main decompression loop.
1042    */
1043
1044   while (gzio->wp < WSIZE && grub_errno == GRUB_ERR_NONE)
1045     {
1046       if (! gzio->block_len)
1047         {
1048           if (gzio->last_block)
1049             break;
1050
1051           get_new_block (gzio);
1052         }
1053
1054       if (gzio->block_type > INFLATE_DYNAMIC)
1055         grub_error (GRUB_ERR_BAD_COMPRESSED_DATA,
1056                     "unknown block type %d", gzio->block_type);
1057
1058       if (grub_errno != GRUB_ERR_NONE)
1059         return;
1060
1061       /*
1062        *  Expand stored block here.
1063        */
1064       if (gzio->block_type == INFLATE_STORED)
1065         {
1066           int w = gzio->wp;
1067
1068           /*
1069            *  This is basically a glorified pass-through
1070            */
1071
1072           while (gzio->block_len && w < WSIZE && grub_errno == GRUB_ERR_NONE)
1073             {
1074               gzio->slide[w++] = get_byte (gzio);
1075               gzio->block_len--;
1076             }
1077
1078           gzio->wp = w;
1079
1080           continue;
1081         }
1082
1083       /*
1084        *  Expand other kind of block.
1085        */
1086
1087       if (inflate_codes_in_window (gzio))
1088         {
1089           huft_free (gzio->tl);
1090           huft_free (gzio->td);
1091           gzio->tl = 0;
1092           gzio->td = 0;
1093         }
1094     }
1095
1096   gzio->saved_offset += gzio->wp;
1097
1098   /* XXX do CRC calculation here! */
1099 }
1100
1101
1102 static void
1103 initialize_tables (grub_gzio_t gzio)
1104 {
1105   gzio->saved_offset = 0;
1106   gzio_seek (gzio, gzio->data_offset);
1107
1108   /* Initialize the bit buffer.  */
1109   gzio->bk = 0;
1110   gzio->bb = 0;
1111
1112   /* Reset partial decompression code.  */
1113   gzio->last_block = 0;
1114   gzio->block_len = 0;
1115
1116   /* Reset memory allocation stuff.  */
1117   huft_free (gzio->tl);
1118   huft_free (gzio->td);
1119   gzio->tl = NULL;
1120   gzio->td = NULL;
1121 }
1122
1123
1124 /* Open a new decompressing object on the top of IO. If TRANSPARENT is true,
1125    even if IO does not contain data compressed by gzip, return a valid file
1126    object. Note that this function won't close IO, even if an error occurs.  */
1127 static grub_file_t
1128 grub_gzio_open (grub_file_t io, const char *name __attribute__ ((unused)))
1129 {
1130   grub_file_t file;
1131   grub_gzio_t gzio = 0;
1132
1133   file = (grub_file_t) grub_zalloc (sizeof (*file));
1134   if (! file)
1135     return 0;
1136
1137   gzio = grub_zalloc (sizeof (*gzio));
1138   if (! gzio)
1139     {
1140       grub_free (file);
1141       return 0;
1142     }
1143
1144   gzio->file = io;
1145
1146   file->device = io->device;
1147   file->data = gzio;
1148   file->fs = &grub_gzio_fs;
1149   file->not_easily_seekable = 1;
1150
1151   if (! test_gzip_header (file))
1152     {
1153       grub_errno = GRUB_ERR_NONE;
1154       grub_free (gzio);
1155       grub_free (file);
1156       grub_file_seek (io, 0);
1157
1158       return io;
1159     }
1160
1161   return file;
1162 }
1163
1164 static grub_uint8_t
1165 mod_31 (grub_uint16_t v)
1166 {
1167   /* At most 2 iterations for any number that
1168      we can get here.
1169      In any case faster than real division.  */
1170   while (v > 0x1f)
1171     v = (v & 0x1f) + (v >> 5);
1172   if (v == 0x1f)
1173     return 0;
1174   return v;
1175 }
1176
1177 static int
1178 test_zlib_header (grub_gzio_t gzio)
1179 {
1180   grub_uint8_t cmf, flg;
1181   
1182   cmf = get_byte (gzio);
1183   flg = get_byte (gzio);
1184
1185   /* Check that compression method is DEFLATE.  */
1186   if ((cmf & 0xf) != GRUB_GZ_DEFLATED)
1187     {
1188       /* TRANSLATORS: It's about given file having some strange format, not
1189          complete lack of gzip support.  */
1190       grub_error (GRUB_ERR_BAD_COMPRESSED_DATA, N_("unsupported gzip format"));
1191       return 0;
1192     }
1193
1194   /* Usually it would be: (cmf * 256 + flg) % 31 != 0.  */
1195   /* But 256 == 8 (31).  */
1196   /* By multiplying by 4 and using 32 == 1 (31). We get our formula.  */
1197   if (mod_31 (cmf + flg * 4) != 0)
1198     {
1199       grub_error (GRUB_ERR_BAD_COMPRESSED_DATA, N_("unsupported gzip format"));
1200       return 0;
1201     }
1202
1203   /* Dictionary isn't supported.  */
1204   if (flg & 0x20)
1205     {
1206       grub_error (GRUB_ERR_BAD_COMPRESSED_DATA, N_("unsupported gzip format"));
1207       return 0;
1208     }
1209
1210   gzio->data_offset = 2;
1211   initialize_tables (gzio);
1212
1213   return 1;
1214 }
1215
1216 static grub_ssize_t
1217 grub_gzio_read_real (grub_gzio_t gzio, grub_off_t offset,
1218                      char *buf, grub_size_t len)
1219 {
1220   grub_ssize_t ret = 0;
1221
1222   /* Do we reset decompression to the beginning of the file?  */
1223   if (gzio->saved_offset > offset + WSIZE)
1224     initialize_tables (gzio);
1225
1226   /*
1227    *  This loop operates upon uncompressed data only.  The only
1228    *  special thing it does is to make sure the decompression
1229    *  window is within the range of data it needs.
1230    */
1231
1232   while (len > 0 && grub_errno == GRUB_ERR_NONE)
1233     {
1234       register grub_size_t size;
1235       register char *srcaddr;
1236
1237       while (offset >= gzio->saved_offset)
1238         {
1239           inflate_window (gzio);
1240           if (gzio->wp == 0)
1241             goto out;
1242         }
1243
1244       if (gzio->wp == 0)
1245         goto out;
1246
1247       srcaddr = (char *) ((offset & (WSIZE - 1)) + gzio->slide);
1248       size = gzio->saved_offset - offset;
1249       if (size > len)
1250         size = len;
1251
1252       grub_memmove (buf, srcaddr, size);
1253
1254       buf += size;
1255       len -= size;
1256       ret += size;
1257       offset += size;
1258     }
1259
1260  out:
1261   if (grub_errno != GRUB_ERR_NONE)
1262     ret = -1;
1263
1264   return ret;
1265 }
1266
1267 static grub_ssize_t
1268 grub_gzio_read (grub_file_t file, char *buf, grub_size_t len)
1269 {
1270   grub_ssize_t ret;
1271   ret = grub_gzio_read_real (file->data, file->offset, buf, len);
1272
1273   if (!grub_errno && ret != (grub_ssize_t) len)
1274     {
1275       grub_error (GRUB_ERR_BAD_COMPRESSED_DATA, "premature end of compressed");
1276       ret = -1;
1277     }
1278   return ret;
1279 }
1280
1281 /* Release everything, including the underlying file object.  */
1282 static grub_err_t
1283 grub_gzio_close (grub_file_t file)
1284 {
1285   grub_gzio_t gzio = file->data;
1286
1287   grub_file_close (gzio->file);
1288   huft_free (gzio->tl);
1289   huft_free (gzio->td);
1290   grub_free (gzio);
1291
1292   /* No need to close the same device twice.  */
1293   file->device = 0;
1294   file->name = 0;
1295
1296   return grub_errno;
1297 }
1298
1299 grub_ssize_t
1300 grub_zlib_decompress (char *inbuf, grub_size_t insize, grub_off_t off,
1301                       char *outbuf, grub_size_t outsize)
1302 {
1303   grub_gzio_t gzio = 0;
1304   grub_ssize_t ret;
1305
1306   gzio = grub_zalloc (sizeof (*gzio));
1307   if (! gzio)
1308     return -1;
1309   gzio->mem_input = (grub_uint8_t *) inbuf;
1310   gzio->mem_input_size = insize;
1311   gzio->mem_input_off = 0;
1312
1313   if (!test_zlib_header (gzio))
1314     {
1315       grub_free (gzio);
1316       return -1;
1317     }
1318
1319   ret = grub_gzio_read_real (gzio, off, outbuf, outsize);
1320   grub_free (gzio);
1321
1322   /* FIXME: Check Adler.  */
1323   return ret;
1324 }
1325
1326 grub_ssize_t
1327 grub_deflate_decompress (char *inbuf, grub_size_t insize, grub_off_t off,
1328                          char *outbuf, grub_size_t outsize)
1329 {
1330   grub_gzio_t gzio = 0;
1331   grub_ssize_t ret;
1332
1333   gzio = grub_zalloc (sizeof (*gzio));
1334   if (! gzio)
1335     return -1;
1336   gzio->mem_input = (grub_uint8_t *) inbuf;
1337   gzio->mem_input_size = insize;
1338   gzio->mem_input_off = 0;
1339
1340   initialize_tables (gzio);
1341
1342   ret = grub_gzio_read_real (gzio, off, outbuf, outsize);
1343   grub_free (gzio);
1344
1345   return ret;
1346 }
1347
1348 \f
1349
1350 static struct grub_fs grub_gzio_fs =
1351   {
1352     .name = "gzio",
1353     .dir = 0,
1354     .open = 0,
1355     .read = grub_gzio_read,
1356     .close = grub_gzio_close,
1357     .label = 0,
1358     .next = 0
1359   };
1360
1361 GRUB_MOD_INIT(gzio)
1362 {
1363   grub_file_filter_register (GRUB_FILE_FILTER_GZIO, grub_gzio_open);
1364 }
1365
1366 GRUB_MOD_FINI(gzio)
1367 {
1368   grub_file_filter_unregister (GRUB_FILE_FILTER_GZIO);
1369 }