Release: 1.1.6
[captive.git] / src / install / acquire / cabextract / cabextract.c
1 /* cabextract 0.6 - a program to extract Microsoft Cabinet files
2  * (C) 2000-2002 Stuart Caie <kyzer@4u.net>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 /* This is NOT a general purpose cabinet library with a front end tacked
20  * on. If you want a comprehensive library to read and write cabinet
21  * files, please get "libcabinet". If you want to create CAB files on UNIX
22  * systems, get "Cablinux".
23  *
24  * Get the official Microsoft CAB SDK from here:
25  *    http://msdn.microsoft.com/workshop/management/cab/cab-sdk.exe
26  * You can use cabextract on this file to extract the contents.
27  *
28  * Many thanks to Dirk Stoecker, Matthew Russoto and Dave Tritscher and,
29  * of course, Microsoft for the documentation they _did_ provide wholly
30  * and accurately. MSZIP is a one-byte adaption of the deflate and inflate
31  * methods created by Phil Katz. Quantum is based on the Quantum archiver,
32  * created by David Stafford. LZX is an adaption of the LZX method created
33  * by Jonathan Forbes and Tomi Poutanen.
34  *
35  * Furthermore, thanks to Jae Jung, for single-handedly fixing all the
36  * bugs with LZX decompression in cabextract 0.1, and Eric Sharkey for the
37  * original manual page.
38  */
39
40 /* CAB files are 'cabinets'. 'Folders' store compressed data, and may span
41  * several cabinets. 'Files' live as data inside a folder when
42  * uncompressed. EOR checksums are used instead of CRCs. Four compression
43  * formats are known - NONE, MSZIP, QUANTUM and LZX. NONE is obviously
44  * uncompressed data. MSZIP is simply PKZIP's deflate/inflate algorithims
45  * with 'CK' as a signature instead of 'PK'. QUANTUM is an LZ77 +
46  * arithmetic coding method. LZX is a much loved LZH based archiver in the
47  * Amiga world, the algorithm taken (bought?) by Microsoft and tweaked for
48  * Intel code.
49  */
50
51 #ifdef HAVE_CONFIG_H
52 #include <config.h>
53
54 #include <stdio.h> /* everyone has this! */
55
56 #ifdef HAVE_SYS_TYPES_H
57 # include <sys/types.h>
58 #endif
59
60 #ifdef HAVE_CTYPE_H
61 # include <ctype.h>
62 #endif
63
64 #ifdef HAVE_LIMITS_H
65 # include <limits.h>
66 #endif
67
68 #ifdef HAVE_STDLIB_H
69 # include <stdlib.h>
70 #endif
71
72 #ifdef HAVE_STRING_H
73 # include <string.h>
74 #endif
75
76 #ifdef HAVE_STRINGS_H
77 # include <strings.h>
78 #endif
79
80 #ifdef HAVE_SYS_STAT_H
81 # include <sys/stat.h>
82 #endif
83
84 #if TIME_WITH_SYS_TIME
85 # include <sys/time.h>
86 # include <time.h>
87 #else
88 # if HAVE_SYS_TIME_H
89 #  include <sys/time.h>
90 # else
91 #  include <time.h>
92 # endif
93 #endif
94
95 #ifdef HAVE_UTIME_H
96 # include <utime.h>
97 #endif
98
99 #if HAVE_DIRENT_H
100 # include <dirent.h>
101 #else
102 # define dirent direct
103 # if HAVE_SYS_NDIR_H
104 #  include <sys/ndir.h>
105 # endif
106 # if HAVE_SYS_DIR_H
107 #  include <sys/dir.h>
108 # endif
109 # if HAVE_NDIR_H
110 #  include <ndir.h>
111 # endif
112 #endif
113
114 #if !STDC_HEADERS
115 # if !HAVE_STRCHR
116 #  define strchr index
117 #  define strrchr rindex
118 # endif
119 # if !HAVE_STRCASECMP
120 #  define strcasecmp strcmpi
121 # endif
122 # if !HAVE_MEMCPY
123 #  define memcpy(d,,n) bcopy((s),(d),(n)
124 # endif
125 #endif
126
127 #ifndef HAVE_MKTIME
128 extern time_t mktime(struct tm *tp);
129 #endif
130
131 #include "getopt.h"
132
133 #else /* !HAVE_CONFIG_H */
134
135 #include <ctype.h>
136 #include <limits.h>
137 #include <stdio.h>
138 #include <stdlib.h>
139 #include <sys/stat.h>
140 #include <sys/types.h>
141 #include <string.h>
142 #include <time.h>
143 #include <utime.h>
144 #include <dirent.h>
145 #include "getopt.h"
146 #define VERSION "x.x"
147
148 #endif
149
150 #ifdef DEBUG
151 # define D(x) printf x ;
152 #else
153 # define D(x)
154 #endif
155
156
157 typedef unsigned char  UBYTE; /* 8 bits exactly    */
158 typedef unsigned short UWORD; /* 16 bits (or more) */
159 typedef unsigned int   ULONG; /* 32 bits (or more) */
160 typedef   signed int    LONG; /* 32 bits (or more) */
161
162 /* number of bits in a ULONG */
163 #ifndef CHAR_BIT
164 # define CHAR_BIT (8)
165 #endif
166 #define ULONG_BITS (sizeof(ULONG) * CHAR_BIT)
167
168 /* endian-neutral reading of little-endian data */
169 #define EndGetI32(a)  ((((a)[3])<<24)|(((a)[2])<<16)|(((a)[1])<<8)|((a)[0]))
170 #define EndGetI16(a)  ((((a)[1])<<8)|((a)[0]))
171
172 /* maximum number of cabinets any one folder can be split across */
173 #define CAB_SPLITMAX (10)
174
175 struct cabinet {
176   struct cabinet *next;                /* for making a list of cabinets  */
177   char  *filename;                     /* input name of cabinet          */
178   FILE  *fh;                           /* open file handle or NULL       */
179   off_t filelen;                       /* length of cabinet file         */
180   off_t blocks_off;                    /* offset to data blocks in file  */
181   struct cabinet *prevcab, *nextcab;   /* multipart cabinet chains       */
182   char *prevname, *nextname;           /* and their filenames            */
183   char *previnfo, *nextinfo;           /* and their visible names        */
184   struct folder *folders;              /* first folder in this cabinet   */
185   struct file *files;                  /* first file in this cabinet     */
186   UBYTE block_resv;                    /* reserved space in datablocks   */
187   UBYTE flags;                         /* header flags                   */
188 };
189
190 struct folder {
191   struct folder *next;
192   struct cabinet *cab[CAB_SPLITMAX];   /* cabinet(s) this folder spans   */
193   off_t offset[CAB_SPLITMAX];          /* offset to data blocks          */
194   UWORD comp_type;                     /* compression format/window size */
195   ULONG comp_size;                     /* compressed size of folder      */
196   UBYTE num_splits;                    /* number of split blocks + 1     */
197   UWORD num_blocks;                    /* total number of blocks         */
198   struct file *contfile;               /* the first split file           */
199 };
200
201 struct file {
202   struct file *next;                   /* next file in sequence          */
203   struct folder *folder;               /* folder that contains this file */
204   char *filename;                      /* output name of file            */
205   FILE *fh;                            /* open file handle or NULL       */
206   ULONG length;                        /* uncompressed length of file    */
207   ULONG offset;                        /* uncompressed offset in folder  */
208   UWORD index;                         /* magic index number of folder   */
209   UWORD time, date, attribs;           /* MS-DOS time/date/attributes    */
210 };
211
212
213 /* structure offsets */
214 #define cfhead_Signature         (0x00)
215 #define cfhead_CabinetSize       (0x08)
216 #define cfhead_FileOffset        (0x10)
217 #define cfhead_MinorVersion      (0x18)
218 #define cfhead_MajorVersion      (0x19)
219 #define cfhead_NumFolders        (0x1A)
220 #define cfhead_NumFiles          (0x1C)
221 #define cfhead_Flags             (0x1E)
222 #define cfhead_SetID             (0x20)
223 #define cfhead_CabinetIndex      (0x22)
224 #define cfhead_SIZEOF            (0x24)
225 #define cfheadext_HeaderReserved (0x00)
226 #define cfheadext_FolderReserved (0x02)
227 #define cfheadext_DataReserved   (0x03)
228 #define cfheadext_SIZEOF         (0x04)
229 #define cffold_DataOffset        (0x00)
230 #define cffold_NumBlocks         (0x04)
231 #define cffold_CompType          (0x06)
232 #define cffold_SIZEOF            (0x08)
233 #define cffile_UncompressedSize  (0x00)
234 #define cffile_FolderOffset      (0x04)
235 #define cffile_FolderIndex       (0x08)
236 #define cffile_Date              (0x0A)
237 #define cffile_Time              (0x0C)
238 #define cffile_Attribs           (0x0E)
239 #define cffile_SIZEOF            (0x10)
240 #define cfdata_CheckSum          (0x00)
241 #define cfdata_CompressedSize    (0x04)
242 #define cfdata_UncompressedSize  (0x06)
243 #define cfdata_SIZEOF            (0x08)
244
245 /* flags */
246 #define cffoldCOMPTYPE_MASK            (0x000f)
247 #define cffoldCOMPTYPE_NONE            (0x0000)
248 #define cffoldCOMPTYPE_MSZIP           (0x0001)
249 #define cffoldCOMPTYPE_QUANTUM         (0x0002)
250 #define cffoldCOMPTYPE_LZX             (0x0003)
251 #define cfheadPREV_CABINET             (0x0001)
252 #define cfheadNEXT_CABINET             (0x0002)
253 #define cfheadRESERVE_PRESENT          (0x0004)
254 #define cffileCONTINUED_FROM_PREV      (0xFFFD)
255 #define cffileCONTINUED_TO_NEXT        (0xFFFE)
256 #define cffileCONTINUED_PREV_AND_NEXT  (0xFFFF)
257 #define cffile_A_RDONLY                (0x01)
258 #define cffile_A_HIDDEN                (0x02)
259 #define cffile_A_SYSTEM                (0x04)
260 #define cffile_A_ARCH                  (0x20)
261 #define cffile_A_EXEC                  (0x40)
262 #define cffile_A_NAME_IS_UTF           (0x80)
263
264
265 /*--------------------------------------------------------------------------*/
266 /* our archiver information / state */
267
268 /* MSZIP stuff */
269 #define ZIPWSIZE        0x8000  /* window size */
270 #define ZIPLBITS        9       /* bits in base literal/length lookup table */
271 #define ZIPDBITS        6       /* bits in base distance lookup table */
272 #define ZIPBMAX         16      /* maximum bit length of any code */
273 #define ZIPN_MAX        288     /* maximum number of codes in any set */
274
275 struct Ziphuft {
276   UBYTE e;                /* number of extra bits or operation */
277   UBYTE b;                /* number of bits in this code or subcode */
278   union {
279     UWORD n;              /* literal, length base, or distance base */
280     struct Ziphuft *t;    /* pointer to next level of table */
281   } v;
282 };
283
284 struct ZIPstate {
285     ULONG window_posn;     /* current offset within the window        */
286     ULONG bb;              /* bit buffer */
287     ULONG bk;              /* bits in bit buffer */
288     ULONG ll[288+32];      /* literal/length and distance code lengths */
289     ULONG c[ZIPBMAX+1];    /* bit length count table */
290     LONG  lx[ZIPBMAX+1];   /* memory for l[-1..ZIPBMAX-1] */
291     struct Ziphuft *u[ZIPBMAX];                 /* table stack */
292     ULONG v[ZIPN_MAX];     /* values in order of bit length */
293     ULONG x[ZIPBMAX+1];    /* bit offsets, then code stack */
294     UBYTE *inpos;
295 };
296   
297 /* Quantum stuff */
298
299 struct QTMmodelsym {
300   UWORD sym, cumfreq;
301 };
302
303 struct QTMmodel {
304   int shiftsleft, entries; 
305   struct QTMmodelsym *syms;
306   UWORD tabloc[256];
307 };
308
309 struct QTMstate {
310     UBYTE *window;         /* the actual decoding window              */
311     ULONG window_size;     /* window size (1Kb through 2Mb)           */
312     ULONG actual_size;     /* window size when it was first allocated */
313     ULONG window_posn;     /* current offset within the window        */
314
315     struct QTMmodel model7;
316     struct QTMmodelsym m7sym[7+1];
317
318     struct QTMmodel model4, model5, model6pos, model6len;
319     struct QTMmodelsym m4sym[0x18 + 1];
320     struct QTMmodelsym m5sym[0x24 + 1];
321     struct QTMmodelsym m6psym[0x2a + 1], m6lsym[0x1b + 1];
322
323     struct QTMmodel model00, model40, model80, modelC0;
324     struct QTMmodelsym m00sym[0x40 + 1], m40sym[0x40 + 1];
325     struct QTMmodelsym m80sym[0x40 + 1], mC0sym[0x40 + 1];
326 };
327
328 /* LZX stuff */
329
330 /* some constants defined by the LZX specification */
331 #define LZX_MIN_MATCH                (2)
332 #define LZX_MAX_MATCH                (257)
333 #define LZX_NUM_CHARS                (256)
334 #define LZX_BLOCKTYPE_INVALID        (0)   /* also blocktypes 4-7 invalid */
335 #define LZX_BLOCKTYPE_VERBATIM       (1)
336 #define LZX_BLOCKTYPE_ALIGNED        (2)
337 #define LZX_BLOCKTYPE_UNCOMPRESSED   (3)
338 #define LZX_PRETREE_NUM_ELEMENTS     (20)
339 #define LZX_ALIGNED_NUM_ELEMENTS     (8)   /* aligned offset tree #elements */
340 #define LZX_NUM_PRIMARY_LENGTHS      (7)   /* this one missing from spec! */
341 #define LZX_NUM_SECONDARY_LENGTHS    (249) /* length tree #elements */
342
343 /* LZX huffman defines: tweak tablebits as desired */
344 #define LZX_PRETREE_MAXSYMBOLS  (LZX_PRETREE_NUM_ELEMENTS)
345 #define LZX_PRETREE_TABLEBITS   (6)
346 #define LZX_MAINTREE_MAXSYMBOLS (LZX_NUM_CHARS + 50*8)
347 #define LZX_MAINTREE_TABLEBITS  (12)
348 #define LZX_LENGTH_MAXSYMBOLS   (LZX_NUM_SECONDARY_LENGTHS+1)
349 #define LZX_LENGTH_TABLEBITS    (12)
350 #define LZX_ALIGNED_MAXSYMBOLS  (LZX_ALIGNED_NUM_ELEMENTS)
351 #define LZX_ALIGNED_TABLEBITS   (7)
352
353 #define LZX_LENTABLE_SAFETY (64) /* we allow length table decoding overruns */
354
355 #define LZX_DECLARE_TABLE(tbl) \
356   UWORD tbl##_table[(1<<LZX_##tbl##_TABLEBITS) + (LZX_##tbl##_MAXSYMBOLS<<1)];\
357   UBYTE tbl##_len  [LZX_##tbl##_MAXSYMBOLS + LZX_LENTABLE_SAFETY]
358
359 struct LZXstate {
360     UBYTE *window;         /* the actual decoding window              */
361     ULONG window_size;     /* window size (32Kb through 2Mb)          */
362     ULONG actual_size;     /* window size when it was first allocated */
363     ULONG window_posn;     /* current offset within the window        */
364     ULONG R0, R1, R2;      /* for the LRU offset system               */
365     UWORD main_elements;   /* number of main tree elements            */
366     int   header_read;     /* have we started decoding at all yet?    */
367     UWORD block_type;      /* type of this block                      */
368     ULONG block_length;    /* uncompressed length of this block       */
369     ULONG block_remaining; /* uncompressed bytes still left to decode */
370     ULONG frames_read;     /* the number of CFDATA blocks processed   */
371     LONG  intel_filesize;  /* magic header value used for transform   */
372     LONG  intel_curpos;    /* current offset in transform space       */
373     int   intel_started;   /* have we seen any translatable data yet? */
374
375     LZX_DECLARE_TABLE(PRETREE);
376     LZX_DECLARE_TABLE(MAINTREE);
377     LZX_DECLARE_TABLE(LENGTH);
378     LZX_DECLARE_TABLE(ALIGNED);
379 };
380
381
382 /* generic stuff */
383 #define CAB(x) (decomp_state.x)
384 #define ZIP(x) (decomp_state.methods.zip.x)
385 #define QTM(x) (decomp_state.methods.qtm.x)
386 #define LZX(x) (decomp_state.methods.lzx.x)
387 #define DECR_OK           (0)
388 #define DECR_DATAFORMAT   (1)
389 #define DECR_ILLEGALDATA  (2)
390 #define DECR_NOMEMORY     (3)
391 #define DECR_CHECKSUM     (4)
392 #define DECR_INPUT        (5)
393 #define DECR_OUTPUT       (6)
394
395 /* CAB data blocks are <= 32768 bytes in uncompressed form. Uncompressed
396  * blocks have zero growth. MSZIP guarantees that it won't grow above
397  * uncompressed size by more than 12 bytes. LZX guarantees it won't grow
398  * more than 6144 bytes.
399  */
400 #define CAB_BLOCKMAX (32768)
401 #define CAB_INPUTMAX (CAB_BLOCKMAX+6144)
402
403 struct {
404   struct folder *current; /* current folder we're extracting from  */
405   ULONG offset;           /* uncompressed offset within folder     */
406   UBYTE *outpos;          /* (high level) start of data to use up  */
407   UWORD outlen;           /* (high level) amount of data to use up */
408   UWORD split;            /* at which split in current folder?     */
409   int (*decompress)(int, int); /* the chosen compression func      */
410   UBYTE inbuf[CAB_INPUTMAX+2]; /* +2 for lzx bitbuffer overflows!  */
411   UBYTE outbuf[CAB_BLOCKMAX];
412   union {
413     struct ZIPstate zip;
414     struct QTMstate qtm;
415     struct LZXstate lzx;
416   } methods;
417 } decomp_state;
418
419
420 /* MSZIP decruncher */
421
422 /* Dirk Stoecker wrote the ZIP decoder, based on the InfoZip deflate code */
423
424 /* Tables for deflate from PKZIP's appnote.txt. */
425 static const UBYTE Zipborder[] = /* Order of the bit length code lengths */
426 { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
427 static const UWORD Zipcplens[] = /* Copy lengths for literal codes 257..285 */
428 { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51,
429  59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
430 static const UWORD Zipcplext[] = /* Extra bits for literal codes 257..285 */
431 { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,
432   4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
433 static const UWORD Zipcpdist[] = /* Copy offsets for distance codes 0..29 */
434 { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385,
435 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
436 static const UWORD Zipcpdext[] = /* Extra bits for distance codes */
437 { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10,
438 10, 11, 11, 12, 12, 13, 13};
439
440 /* And'ing with Zipmask[n] masks the lower n bits */
441 static const UWORD Zipmask[17] = {
442  0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
443  0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
444 };
445
446 #define ZIPNEEDBITS(n) {while(k<(n)){LONG c=*(ZIP(inpos)++);\
447     b|=((ULONG)c)<<k;k+=8;}}
448 #define ZIPDUMPBITS(n) {b>>=(n);k-=(n);}
449
450 void Ziphuft_free(struct Ziphuft *t)
451 {
452   register struct Ziphuft *p, *q;
453
454   /* Go through linked list, freeing from the allocated (t[-1]) address. */
455   p = t;
456   while (p != (struct Ziphuft *)NULL)
457   {
458     q = (--p)->v.t;
459     free(p);
460     p = q;
461   } 
462 }
463
464 LONG Ziphuft_build(ULONG *b, ULONG n, ULONG s, UWORD *d, UWORD *e,
465 struct Ziphuft **t, LONG *m)
466 {
467   ULONG a;                      /* counter for codes of length k */
468   ULONG el;                     /* length of EOB code (value 256) */
469   ULONG f;                      /* i repeats in table every f entries */
470   LONG g;                       /* maximum code length */
471   LONG h;                       /* table level */
472   register ULONG i;             /* counter, current code */
473   register ULONG j;             /* counter */
474   register LONG k;              /* number of bits in current code */
475   LONG *l;                      /* stack of bits per table */
476   register ULONG *p;            /* pointer into ZIP(c)[],ZIP(b)[],ZIP(v)[] */
477   register struct Ziphuft *q;   /* points to current table */
478   struct Ziphuft r;             /* table entry for structure assignment */
479   register LONG w;              /* bits before this table == (l * h) */
480   ULONG *xp;                    /* pointer into x */
481   LONG y;                       /* number of dummy codes added */
482   ULONG z;                      /* number of entries in current table */
483
484   l = ZIP(lx)+1;
485
486   /* Generate counts for each bit length */
487   el = n > 256 ? b[256] : ZIPBMAX; /* set length of EOB code, if any */
488
489   for(i = 0; i < ZIPBMAX+1; ++i)
490     ZIP(c)[i] = 0;
491   p = b;  i = n;
492   do
493   {
494     ZIP(c)[*p]++; p++;               /* assume all entries <= ZIPBMAX */
495   } while (--i);
496   if (ZIP(c)[0] == n)                /* null input--all zero length codes */
497   {
498     *t = (struct Ziphuft *)NULL;
499     *m = 0;
500     return 0;
501   }
502
503   /* Find minimum and maximum length, bound *m by those */
504   for (j = 1; j <= ZIPBMAX; j++)
505     if (ZIP(c)[j])
506       break;
507   k = j;                        /* minimum code length */
508   if ((ULONG)*m < j)
509     *m = j;
510   for (i = ZIPBMAX; i; i--)
511     if (ZIP(c)[i])
512       break;
513   g = i;                        /* maximum code length */
514   if ((ULONG)*m > i)
515     *m = i;
516
517   /* Adjust last length count to fill out codes, if needed */
518   for (y = 1 << j; j < i; j++, y <<= 1)
519     if ((y -= ZIP(c)[j]) < 0)
520       return 2;                 /* bad input: more codes than bits */
521   if ((y -= ZIP(c)[i]) < 0)
522     return 2;
523   ZIP(c)[i] += y;
524
525   /* Generate starting offsets LONGo the value table for each length */
526   ZIP(x)[1] = j = 0;
527   p = ZIP(c) + 1;  xp = ZIP(x) + 2;
528   while (--i)
529   {                 /* note that i == g from above */
530     *xp++ = (j += *p++);
531   }
532
533   /* Make a table of values in order of bit lengths */
534   p = b;  i = 0;
535   do{
536     if ((j = *p++) != 0)
537       ZIP(v)[ZIP(x)[j]++] = i;
538   } while (++i < n);
539
540
541   /* Generate the Huffman codes and for each, make the table entries */
542   ZIP(x)[0] = i = 0;                 /* first Huffman code is zero */
543   p = ZIP(v);                        /* grab values in bit order */
544   h = -1;                       /* no tables yet--level -1 */
545   w = l[-1] = 0;                /* no bits decoded yet */
546   ZIP(u)[0] = (struct Ziphuft *)NULL;   /* just to keep compilers happy */
547   q = (struct Ziphuft *)NULL;      /* ditto */
548   z = 0;                        /* ditto */
549
550   /* go through the bit lengths (k already is bits in shortest code) */
551   for (; k <= g; k++)
552   {
553     a = ZIP(c)[k];
554     while (a--)
555     {
556       /* here i is the Huffman code of length k bits for value *p */
557       /* make tables up to required level */
558       while (k > w + l[h])
559       {
560         w += l[h++];            /* add bits already decoded */
561
562         /* compute minimum size table less than or equal to *m bits */
563         z = (z = g - w) > (ULONG)*m ? *m : z;        /* upper limit */
564         if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
565         {                       /* too few codes for k-w bit table */
566           f -= a + 1;           /* deduct codes from patterns left */
567           xp = ZIP(c) + k;
568           while (++j < z)       /* try smaller tables up to z bits */
569           {
570             if ((f <<= 1) <= *++xp)
571               break;            /* enough codes to use up j bits */
572             f -= *xp;           /* else deduct codes from patterns */
573           }
574         }
575         if ((ULONG)w + j > el && (ULONG)w < el)
576           j = el - w;           /* make EOB code end at table */
577         z = 1 << j;             /* table entries for j-bit table */
578         l[h] = j;               /* set table size in stack */
579
580         /* allocate and link in new table */
581         if (!(q = (struct Ziphuft *) malloc((z + 1)*sizeof(struct Ziphuft))))
582         {
583           if(h)
584             Ziphuft_free(ZIP(u)[0]);
585           return 3;             /* not enough memory */
586         }
587         *t = q + 1;             /* link to list for Ziphuft_free() */
588         *(t = &(q->v.t)) = (struct Ziphuft *)NULL;
589         ZIP(u)[h] = ++q;             /* table starts after link */
590
591         /* connect to last table, if there is one */
592         if (h)
593         {
594           ZIP(x)[h] = i;             /* save pattern for backing up */
595           r.b = (UBYTE)l[h-1];    /* bits to dump before this table */
596           r.e = (UBYTE)(16 + j);  /* bits in this table */
597           r.v.t = q;            /* pointer to this table */
598           j = (i & ((1 << w) - 1)) >> (w - l[h-1]);
599           ZIP(u)[h-1][j] = r;        /* connect to last table */
600         }
601       }
602
603       /* set up table entry in r */
604       r.b = (UBYTE)(k - w);
605       if (p >= ZIP(v) + n)
606         r.e = 99;               /* out of values--invalid code */
607       else if (*p < s)
608       {
609         r.e = (UBYTE)(*p < 256 ? 16 : 15);    /* 256 is end-of-block code */
610         r.v.n = *p++;           /* simple code is just the value */
611       }
612       else
613       {
614         r.e = (UBYTE)e[*p - s];   /* non-simple--look up in lists */
615         r.v.n = d[*p++ - s];
616       }
617
618       /* fill code-like entries with r */
619       f = 1 << (k - w);
620       for (j = i >> w; j < z; j += f)
621         q[j] = r;
622
623       /* backwards increment the k-bit code i */
624       for (j = 1 << (k - 1); i & j; j >>= 1)
625         i ^= j;
626       i ^= j;
627
628       /* backup over finished tables */
629       while ((i & ((1 << w) - 1)) != ZIP(x)[h])
630         w -= l[--h];            /* don't need to update q */
631     }
632   }
633
634   /* return actual size of base table */
635   *m = l[0];
636
637   /* Return true (1) if we were given an incomplete table */
638   return y != 0 && g != 1;
639 }
640
641 LONG Zipinflate_codes(struct Ziphuft *tl, struct Ziphuft *td,
642 LONG bl, LONG bd)
643 {
644   register ULONG e;  /* table entry flag/number of extra bits */
645   ULONG n, d;        /* length and index for copy */
646   ULONG w;           /* current window position */
647   struct Ziphuft *t; /* pointer to table entry */
648   ULONG ml, md;      /* masks for bl and bd bits */
649   register ULONG b;  /* bit buffer */
650   register ULONG k;  /* number of bits in bit buffer */
651
652   /* make local copies of globals */
653   b = ZIP(bb);                       /* initialize bit buffer */
654   k = ZIP(bk);
655   w = ZIP(window_posn);                       /* initialize window position */
656
657   /* inflate the coded data */
658   ml = Zipmask[bl];             /* precompute masks for speed */
659   md = Zipmask[bd];
660
661   for(;;)
662   {
663     ZIPNEEDBITS((ULONG)bl)
664     if((e = (t = tl + ((ULONG)b & ml))->e) > 16)
665       do
666       {
667         if (e == 99)
668           return 1;
669         ZIPDUMPBITS(t->b)
670         e -= 16;
671         ZIPNEEDBITS(e)
672       } while ((e = (t = t->v.t + ((ULONG)b & Zipmask[e]))->e) > 16);
673     ZIPDUMPBITS(t->b)
674     if (e == 16)                /* then it's a literal */
675       CAB(outbuf)[w++] = (UBYTE)t->v.n;
676     else                        /* it's an EOB or a length */
677     {
678       /* exit if end of block */
679       if(e == 15)
680         break;
681
682       /* get length of block to copy */
683       ZIPNEEDBITS(e)
684       n = t->v.n + ((ULONG)b & Zipmask[e]);
685       ZIPDUMPBITS(e);
686
687       /* decode distance of block to copy */
688       ZIPNEEDBITS((ULONG)bd)
689       if ((e = (t = td + ((ULONG)b & md))->e) > 16)
690         do {
691           if (e == 99)
692             return 1;
693           ZIPDUMPBITS(t->b)
694           e -= 16;
695           ZIPNEEDBITS(e)
696         } while ((e = (t = t->v.t + ((ULONG)b & Zipmask[e]))->e) > 16);
697       ZIPDUMPBITS(t->b)
698       ZIPNEEDBITS(e)
699       d = w - t->v.n - ((ULONG)b & Zipmask[e]);
700       ZIPDUMPBITS(e)
701       do
702       {
703         n -= (e = (e = ZIPWSIZE - ((d &= ZIPWSIZE-1) > w ? d : w)) > n ?n:e);
704         do
705         {
706           CAB(outbuf)[w++] = CAB(outbuf)[d++];
707         } while (--e);
708       } while (n);
709     }
710   }
711
712   /* restore the globals from the locals */
713   ZIP(window_posn) = w;              /* restore global window pointer */
714   ZIP(bb) = b;                       /* restore global bit buffer */
715   ZIP(bk) = k;
716
717   /* done */
718   return 0;
719 }
720
721 LONG Zipinflate_stored(void)
722 /* "decompress" an inflated type 0 (stored) block. */
723 {
724   ULONG n;           /* number of bytes in block */
725   ULONG w;           /* current window position */
726   register ULONG b;  /* bit buffer */
727   register ULONG k;  /* number of bits in bit buffer */
728
729   /* make local copies of globals */
730   b = ZIP(bb);                       /* initialize bit buffer */
731   k = ZIP(bk);
732   w = ZIP(window_posn);              /* initialize window position */
733
734   /* go to byte boundary */
735   n = k & 7;
736   ZIPDUMPBITS(n);
737
738   /* get the length and its complement */
739   ZIPNEEDBITS(16)
740   n = ((ULONG)b & 0xffff);
741   ZIPDUMPBITS(16)
742   ZIPNEEDBITS(16)
743   if (n != (ULONG)((~b) & 0xffff))
744     return 1;                   /* error in compressed data */
745   ZIPDUMPBITS(16)
746
747   /* read and output the compressed data */
748   while(n--)
749   {
750     ZIPNEEDBITS(8)
751     CAB(outbuf)[w++] = (UBYTE)b;
752     ZIPDUMPBITS(8)
753   }
754
755   /* restore the globals from the locals */
756   ZIP(window_posn) = w;              /* restore global window pointer */
757   ZIP(bb) = b;                       /* restore global bit buffer */
758   ZIP(bk) = k;
759   return 0;
760 }
761
762 LONG Zipinflate_fixed(void)
763 {
764   struct Ziphuft *fixed_tl;
765   struct Ziphuft *fixed_td;
766   LONG fixed_bl, fixed_bd;
767   LONG i;                /* temporary variable */
768   ULONG *l;
769
770   l = ZIP(ll);
771
772   /* literal table */
773   for(i = 0; i < 144; i++)
774     l[i] = 8;
775   for(; i < 256; i++)
776     l[i] = 9;
777   for(; i < 280; i++)
778     l[i] = 7;
779   for(; i < 288; i++)          /* make a complete, but wrong code set */
780     l[i] = 8;
781   fixed_bl = 7;
782   if((i = Ziphuft_build(l, 288, 257, (UWORD *) Zipcplens,
783   (UWORD *) Zipcplext, &fixed_tl, &fixed_bl)))
784     return i;
785
786   /* distance table */
787   for(i = 0; i < 30; i++)      /* make an incomplete code set */
788     l[i] = 5;
789   fixed_bd = 5;
790   if((i = Ziphuft_build(l, 30, 0, (UWORD *) Zipcpdist, (UWORD *) Zipcpdext,
791   &fixed_td, &fixed_bd)) > 1)
792   {
793     Ziphuft_free(fixed_tl);
794     return i;
795   }
796
797   /* decompress until an end-of-block code */
798   i = Zipinflate_codes(fixed_tl, fixed_td, fixed_bl, fixed_bd);
799
800   Ziphuft_free(fixed_td);
801   Ziphuft_free(fixed_tl);
802   return i;
803 }
804
805 LONG Zipinflate_dynamic(void)
806  /* decompress an inflated type 2 (dynamic Huffman codes) block. */
807 {
808   LONG i;               /* temporary variables */
809   ULONG j;
810   ULONG *ll;
811   ULONG l;              /* last length */
812   ULONG m;              /* mask for bit lengths table */
813   ULONG n;              /* number of lengths to get */
814   struct Ziphuft *tl;      /* literal/length code table */
815   struct Ziphuft *td;      /* distance code table */
816   LONG bl;              /* lookup bits for tl */
817   LONG bd;              /* lookup bits for td */
818   ULONG nb;             /* number of bit length codes */
819   ULONG nl;             /* number of literal/length codes */
820   ULONG nd;             /* number of distance codes */
821   register ULONG b;     /* bit buffer */
822   register ULONG k;     /* number of bits in bit buffer */
823
824   /* make local bit buffer */
825   b = ZIP(bb);
826   k = ZIP(bk);
827   ll = ZIP(ll);
828
829   /* read in table lengths */
830   ZIPNEEDBITS(5)
831   nl = 257 + ((ULONG)b & 0x1f);      /* number of literal/length codes */
832   ZIPDUMPBITS(5)
833   ZIPNEEDBITS(5)
834   nd = 1 + ((ULONG)b & 0x1f);        /* number of distance codes */
835   ZIPDUMPBITS(5)
836   ZIPNEEDBITS(4)
837   nb = 4 + ((ULONG)b & 0xf);         /* number of bit length codes */
838   ZIPDUMPBITS(4)
839   if(nl > 288 || nd > 32)
840     return 1;                   /* bad lengths */
841
842   /* read in bit-length-code lengths */
843   for(j = 0; j < nb; j++)
844   {
845     ZIPNEEDBITS(3)
846     ll[Zipborder[j]] = (ULONG)b & 7;
847     ZIPDUMPBITS(3)
848   }
849   for(; j < 19; j++)
850     ll[Zipborder[j]] = 0;
851
852   /* build decoding table for trees--single level, 7 bit lookup */
853   bl = 7;
854   if((i = Ziphuft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0)
855   {
856     if(i == 1)
857       Ziphuft_free(tl);
858     return i;                   /* incomplete code set */
859   }
860
861   /* read in literal and distance code lengths */
862   n = nl + nd;
863   m = Zipmask[bl];
864   i = l = 0;
865   while((ULONG)i < n)
866   {
867     ZIPNEEDBITS((ULONG)bl)
868     j = (td = tl + ((ULONG)b & m))->b;
869     ZIPDUMPBITS(j)
870     j = td->v.n;
871     if (j < 16)                 /* length of code in bits (0..15) */
872       ll[i++] = l = j;          /* save last length in l */
873     else if (j == 16)           /* repeat last length 3 to 6 times */
874     {
875       ZIPNEEDBITS(2)
876       j = 3 + ((ULONG)b & 3);
877       ZIPDUMPBITS(2)
878       if((ULONG)i + j > n)
879         return 1;
880       while (j--)
881         ll[i++] = l;
882     }
883     else if (j == 17)           /* 3 to 10 zero length codes */
884     {
885       ZIPNEEDBITS(3)
886       j = 3 + ((ULONG)b & 7);
887       ZIPDUMPBITS(3)
888       if ((ULONG)i + j > n)
889         return 1;
890       while (j--)
891         ll[i++] = 0;
892       l = 0;
893     }
894     else                        /* j == 18: 11 to 138 zero length codes */
895     {
896       ZIPNEEDBITS(7)
897       j = 11 + ((ULONG)b & 0x7f);
898       ZIPDUMPBITS(7)
899       if ((ULONG)i + j > n)
900         return 1;
901       while (j--)
902         ll[i++] = 0;
903       l = 0;
904     }
905   }
906
907   /* free decoding table for trees */
908   Ziphuft_free(tl);
909
910   /* restore the global bit buffer */
911   ZIP(bb) = b;
912   ZIP(bk) = k;
913
914   /* build the decoding tables for literal/length and distance codes */
915   bl = ZIPLBITS;
916   if((i = Ziphuft_build(ll, nl, 257, (UWORD *) Zipcplens, (UWORD *) Zipcplext, &tl, &bl)) != 0)
917   {
918     if(i == 1)
919       Ziphuft_free(tl);
920     return i;                   /* incomplete code set */
921   }
922   bd = ZIPDBITS;
923   Ziphuft_build(ll + nl, nd, 0, (UWORD *) Zipcpdist, (UWORD *) Zipcpdext, &td, &bd);
924
925   /* decompress until an end-of-block code */
926   if(Zipinflate_codes(tl, td, bl, bd))
927     return 1;
928
929   /* free the decoding tables, return */
930   Ziphuft_free(tl);
931   Ziphuft_free(td);
932   return 0;
933 }
934
935 LONG Zipinflate_block(LONG *e) /* e == last block flag */
936 { /* decompress an inflated block */
937   ULONG t;              /* block type */
938   register ULONG b;     /* bit buffer */
939   register ULONG k;     /* number of bits in bit buffer */
940
941   /* make local bit buffer */
942   b = ZIP(bb);
943   k = ZIP(bk);
944
945   /* read in last block bit */
946   ZIPNEEDBITS(1)
947   *e = (LONG)b & 1;
948   ZIPDUMPBITS(1)
949
950   /* read in block type */
951   ZIPNEEDBITS(2)
952   t = (ULONG)b & 3;
953   ZIPDUMPBITS(2)
954
955   /* restore the global bit buffer */
956   ZIP(bb) = b;
957   ZIP(bk) = k;
958
959   /* inflate that block type */
960   if(t == 2)
961     return Zipinflate_dynamic();
962   if(t == 0)
963     return Zipinflate_stored();
964   if(t == 1)
965     return Zipinflate_fixed();
966   /* bad block type */
967   return 2;
968 }
969
970 int ZIPdecompress(int inlen, int outlen)
971 {
972   LONG e;               /* last block flag */
973
974   ZIP(inpos) = CAB(inbuf);
975   ZIP(bb) = ZIP(bk) = ZIP(window_posn) = 0;
976   if(outlen > ZIPWSIZE)
977     return DECR_DATAFORMAT;
978
979   /* CK = Chris Kirmse, official Microsoft purloiner */
980   if(ZIP(inpos)[0] != 0x43 || ZIP(inpos)[1] != 0x4B)
981     return DECR_ILLEGALDATA;
982   ZIP(inpos) += 2;
983
984   do
985   {
986     if(Zipinflate_block(&e))
987       return DECR_ILLEGALDATA;
988   } while(!e);
989
990   /* return success */
991   return DECR_OK;
992 }
993
994 /* Quantum decruncher */
995
996 /* This decruncher was researched and implemented by Matthew Russoto. */
997 /* It has since been tidied up by Stuart Caie */
998
999 static UBYTE q_length_base[27], q_length_extra[27], q_extra_bits[42];
1000 static ULONG q_position_base[42];
1001
1002 /* Initialise a model which decodes symbols from [s] to [s]+[n]-1 */
1003 void QTMinitmodel(struct QTMmodel *m, struct QTMmodelsym *sym, int n, int s) {
1004   int i;
1005   m->shiftsleft = 4;
1006   m->entries    = n;
1007   m->syms       = sym;
1008   memset(m->tabloc, 0xFF, sizeof(m->tabloc)); /* clear out look-up table */
1009   for (i = 0; i < n; i++) {
1010     m->tabloc[i+s]     = i;   /* set up a look-up entry for symbol */
1011     m->syms[i].sym     = i+s; /* actual symbol */
1012     m->syms[i].cumfreq = n-i; /* current frequency of that symbol */
1013   }
1014   m->syms[n].cumfreq = 0;
1015 }
1016
1017 int QTMinit(int window, int level) {
1018   int wndsize = 1 << window, msz = window * 2, i;
1019   ULONG j;
1020
1021   /* QTM supports window sizes of 2^10 (1Kb) through 2^21 (2Mb) */
1022   /* if a previously allocated window is big enough, keep it    */
1023   if (window < 10 || window > 21) return DECR_DATAFORMAT;
1024   if (QTM(actual_size) < wndsize) {
1025     if (QTM(window)) free(QTM(window));
1026     QTM(window) = NULL;
1027   }
1028   if (!QTM(window)) {
1029     if (!(QTM(window) = malloc(wndsize))) return DECR_NOMEMORY;
1030     QTM(actual_size) = wndsize;
1031   }
1032   QTM(window_size) = wndsize;
1033   QTM(window_posn) = 0;
1034
1035   /* initialise static slot/extrabits tables */
1036   for (i = 0, j = 0; i < 27; i++) {
1037     q_length_extra[i] = (i == 26) ? 0 : (i < 2 ? 0 : i - 2) >> 2;
1038     q_length_base[i] = j; j += 1 << ((i == 26) ? 5 : q_length_extra[i]);
1039   }
1040   for (i = 0, j = 0; i < 42; i++) {
1041     q_extra_bits[i] = (i < 2 ? 0 : i-2) >> 1;
1042     q_position_base[i] = j; j += 1 << q_extra_bits[i];
1043   }
1044
1045   /* initialise arithmetic coding models */
1046
1047   QTMinitmodel(&QTM(model7), &QTM(m7sym)[0], 7, 0);
1048
1049   QTMinitmodel(&QTM(model00), &QTM(m00sym)[0], 0x40, 0x00);
1050   QTMinitmodel(&QTM(model40), &QTM(m40sym)[0], 0x40, 0x40);
1051   QTMinitmodel(&QTM(model80), &QTM(m80sym)[0], 0x40, 0x80);
1052   QTMinitmodel(&QTM(modelC0), &QTM(mC0sym)[0], 0x40, 0xC0);
1053
1054   /* model 4 depends on table size, ranges from 20 to 24  */
1055   QTMinitmodel(&QTM(model4), &QTM(m4sym)[0], (msz < 24) ? msz : 24, 0);
1056   /* model 5 depends on table size, ranges from 20 to 36  */
1057   QTMinitmodel(&QTM(model5), &QTM(m5sym)[0], (msz < 36) ? msz : 36, 0);
1058   /* model 6pos depends on table size, ranges from 20 to 42 */
1059   QTMinitmodel(&QTM(model6pos), &QTM(m6psym)[0], msz, 0);
1060   QTMinitmodel(&QTM(model6len), &QTM(m6lsym)[0], 27, 0);
1061
1062   return DECR_OK;
1063 }
1064
1065
1066 void QTMupdatemodel(struct QTMmodel *model, int sym) {
1067   struct QTMmodelsym temp;
1068   int i, j;
1069
1070   for (i = 0; i < sym; i++) model->syms[i].cumfreq += 8;
1071
1072   if (model->syms[0].cumfreq > 3800) {
1073     if (--model->shiftsleft) {
1074       for (i = model->entries - 1; i >= 0; i--) {
1075         /* -1, not -2; the 0 entry saves this */
1076         model->syms[i].cumfreq >>= 1;
1077         if (model->syms[i].cumfreq <= model->syms[i+1].cumfreq) {
1078           model->syms[i].cumfreq = model->syms[i+1].cumfreq + 1;
1079         }
1080       }
1081     }
1082     else {
1083       model->shiftsleft = 50;
1084       for (i = 0; i < model->entries ; i++) {
1085         /* no -1, want to include the 0 entry */
1086         /* this converts cumfreqs into frequencies, then shifts right */
1087         model->syms[i].cumfreq -= model->syms[i+1].cumfreq;
1088         model->syms[i].cumfreq++; /* avoid losing things entirely */
1089         model->syms[i].cumfreq >>= 1;
1090       }
1091
1092       /* now sort by frequencies, decreasing order -- this must be an
1093        * inplace selection sort, or a sort with the same (in)stability
1094        * characteristics
1095        */
1096       for (i = 0; i < model->entries - 1; i++) {
1097         for (j = i + 1; j < model->entries; j++) {
1098           if (model->syms[i].cumfreq < model->syms[j].cumfreq) {
1099             temp = model->syms[i];
1100             model->syms[i] = model->syms[j];
1101             model->syms[j] = temp;
1102           }
1103         }
1104       }
1105     
1106       /* then convert frequencies back to cumfreq */
1107       for (i = model->entries - 1; i >= 0; i--) {
1108         model->syms[i].cumfreq += model->syms[i+1].cumfreq;
1109       }
1110       /* then update the other part of the table */
1111       for (i = 0; i < model->entries; i++) {
1112         model->tabloc[model->syms[i].sym] = i;
1113       }
1114     }
1115   }
1116 }
1117
1118 /* Bitstream reading macros (Quantum / normal byte order)
1119  *
1120  * Q_INIT_BITSTREAM    should be used first to set up the system
1121  * Q_READ_BITS(var,n)  takes N bits from the buffer and puts them in var.
1122  *                     unlike LZX, this can loop several times to get the
1123  *                     requisite number of bits.
1124  * Q_FILL_BUFFER       adds more data to the bit buffer, if there is room
1125  *                     for another 16 bits.
1126  * Q_PEEK_BITS(n)      extracts (without removing) N bits from the bit
1127  *                     buffer
1128  * Q_REMOVE_BITS(n)    removes N bits from the bit buffer
1129  *
1130  * These bit access routines work by using the area beyond the MSB and the
1131  * LSB as a free source of zeroes. This avoids having to mask any bits.
1132  * So we have to know the bit width of the bitbuffer variable. This is
1133  * defined as ULONG_BITS.
1134  *
1135  * ULONG_BITS should be at least 16 bits. Unlike LZX's Huffman decoding,
1136  * Quantum's arithmetic decoding only needs 1 bit at a time, it doesn't
1137  * need an assured number. Retrieving larger bitstrings can be done with
1138  * multiple reads and fills of the bitbuffer. The code should work fine
1139  * for machines where ULONG >= 32 bits.
1140  *
1141  * Also note that Quantum reads bytes in normal order; LZX is in
1142  * little-endian order.
1143  */
1144
1145 #define Q_INIT_BITSTREAM do { bitsleft = 0; bitbuf = 0; } while (0)
1146
1147 #define Q_FILL_BUFFER do {                                              \
1148   if (bitsleft <= (ULONG_BITS - 16)) {                                  \
1149     bitbuf |= ((inpos[0]<<8)|inpos[1]) << (ULONG_BITS-16 - bitsleft);   \
1150     bitsleft += 16; inpos += 2;                                         \
1151   }                                                                     \
1152 } while (0)
1153
1154 #define Q_PEEK_BITS(n)   (bitbuf >> (ULONG_BITS - (n)))
1155 #define Q_REMOVE_BITS(n) ((bitbuf <<= (n)), (bitsleft -= (n)))
1156
1157 #define Q_READ_BITS(v,n) do {                                           \
1158   (v) = 0;                                                              \
1159   for (bitsneed = (n); bitsneed; bitsneed -= bitrun) {                  \
1160     Q_FILL_BUFFER;                                                      \
1161     bitrun = (bitsneed > bitsleft) ? bitsleft : bitsneed;               \
1162     (v) = ((v) << bitrun) | Q_PEEK_BITS(bitrun);                        \
1163     Q_REMOVE_BITS(bitrun);                                              \
1164   }                                                                     \
1165 } while (0)
1166
1167 #define Q_MENTRIES(model) (QTM(model).entries)
1168 #define Q_MSYM(model,symidx) (QTM(model).syms[(symidx)].sym)
1169 #define Q_MSYMFREQ(model,symidx) (QTM(model).syms[(symidx)].cumfreq)
1170
1171 /* GET_SYMBOL(model, var) fetches the next symbol from the stated model
1172  * and puts it in var. it may need to read the bitstream to do this.
1173  */
1174 #define GET_SYMBOL(m, var) do {                                         \
1175   range =  ((H - L) & 0xFFFF) + 1;                                      \
1176   symf = ((((C - L + 1) * Q_MSYMFREQ(m,0)) - 1) / range) & 0xFFFF;      \
1177                                                                         \
1178   for (i=1; i < Q_MENTRIES(m); i++) {                                   \
1179     if (Q_MSYMFREQ(m,i) <= symf) break;                                 \
1180   }                                                                     \
1181   (var) = Q_MSYM(m,i-1);                                                \
1182                                                                         \
1183   range = (H - L) + 1;                                                  \
1184   H = L + ((Q_MSYMFREQ(m,i-1) * range) / Q_MSYMFREQ(m,0)) - 1;          \
1185   L = L + ((Q_MSYMFREQ(m,i)   * range) / Q_MSYMFREQ(m,0));              \
1186   while (1) {                                                           \
1187     if ((L & 0x8000) != (H & 0x8000)) {                                 \
1188       if ((L & 0x4000) && !(H & 0x4000)) {                              \
1189         /* underflow case */                                            \
1190         C ^= 0x4000; L &= 0x3FFF; H |= 0x4000;                          \
1191       }                                                                 \
1192       else break;                                                       \
1193     }                                                                   \
1194     L <<= 1; H = (H << 1) | 1;                                          \
1195     Q_FILL_BUFFER;                                                      \
1196     C  = (C << 1) | Q_PEEK_BITS(1);                                     \
1197     Q_REMOVE_BITS(1);                                                   \
1198   }                                                                     \
1199                                                                         \
1200   QTMupdatemodel(&(QTM(m)), i);                                         \
1201 } while (0)
1202
1203
1204 int QTMdecompress(int inlen, int outlen) {
1205   UBYTE *inpos  = CAB(inbuf);
1206   UBYTE *window = QTM(window);
1207   UBYTE *runsrc, *rundest;
1208
1209   ULONG window_posn = QTM(window_posn);
1210   ULONG window_size = QTM(window_size);
1211
1212   /* used by bitstream macros */
1213   register int bitsleft, bitrun, bitsneed;
1214   register ULONG bitbuf;
1215
1216   /* used by GET_SYMBOL */
1217   ULONG range;
1218   UWORD symf;
1219   int i;
1220
1221   int extra, togo = outlen, match_length, copy_length;
1222   UBYTE selector, sym;
1223   ULONG match_offset;
1224
1225   UWORD H = 0xFFFF, L = 0, C;
1226
1227   /* read initial value of C */
1228   Q_INIT_BITSTREAM;
1229   Q_READ_BITS(C, 16);
1230
1231   /* apply 2^x-1 mask */
1232   window_posn &= window_size - 1;
1233   /* runs can't straddle the window wraparound */
1234   if ((window_posn + togo) > window_size) {
1235     D(("straddled run\n"))
1236     return DECR_DATAFORMAT;
1237   }
1238
1239   while (togo > 0) {
1240     GET_SYMBOL(model7, selector);
1241     switch (selector) {
1242     case 0:
1243       GET_SYMBOL(model00, sym); window[window_posn++] = sym; togo--;
1244       break;
1245     case 1:
1246       GET_SYMBOL(model40, sym); window[window_posn++] = sym; togo--;
1247       break;
1248     case 2:
1249       GET_SYMBOL(model80, sym); window[window_posn++] = sym; togo--;
1250       break;
1251     case 3:
1252       GET_SYMBOL(modelC0, sym); window[window_posn++] = sym; togo--;
1253       break;
1254
1255     case 4:
1256       /* selector 4 = fixed length of 3 */
1257       GET_SYMBOL(model4, sym);
1258       Q_READ_BITS(extra, q_extra_bits[sym]);
1259       match_offset = q_position_base[sym] + extra + 1;
1260       match_length = 3;
1261       break;
1262
1263     case 5:
1264       /* selector 5 = fixed length of 4 */
1265       GET_SYMBOL(model5, sym);
1266       Q_READ_BITS(extra, q_extra_bits[sym]);
1267       match_offset = q_position_base[sym] + extra + 1;
1268       match_length = 4;
1269       break;
1270
1271     case 6:
1272       /* selector 6 = variable length */
1273       GET_SYMBOL(model6len, sym);
1274       Q_READ_BITS(extra, q_length_extra[sym]);
1275       match_length = q_length_base[sym] + extra + 5;
1276       GET_SYMBOL(model6pos, sym);
1277       Q_READ_BITS(extra, q_extra_bits[sym]);
1278       match_offset = q_position_base[sym] + extra + 1;
1279       break;
1280
1281     default:
1282       D(("Selector is bogus\n"))
1283       return DECR_ILLEGALDATA;
1284     }
1285
1286     /* if this is a match */
1287     if (selector >= 4) {
1288       rundest = window + window_posn;
1289       togo -= match_length;
1290
1291       /* copy any wrapped around source data */
1292       if (window_posn >= match_offset) {
1293         /* no wrap */
1294         runsrc = rundest - match_offset;
1295       } else {
1296         runsrc = rundest + (window_size - match_offset);
1297         copy_length = match_offset - window_posn;
1298         if (copy_length < match_length) {
1299           match_length -= copy_length;
1300           window_posn += copy_length;
1301           while (copy_length-- > 0) *rundest++ = *runsrc++;
1302           runsrc = window;
1303         }
1304       }
1305       window_posn += match_length;
1306
1307       /* copy match data - no worries about destination wraps */
1308       while (match_length-- > 0) *rundest++ = *runsrc++;
1309     }
1310   } /* while (togo > 0) */
1311
1312   if (togo != 0) {
1313     D(("Frame overflow, this_run = %d\n", togo))
1314     return DECR_ILLEGALDATA;
1315   }
1316
1317   memcpy(CAB(outbuf), window + ((!window_posn) ? window_size : window_posn) -
1318     outlen, outlen);
1319
1320   QTM(window_posn) = window_posn;
1321   return DECR_OK;
1322 }
1323
1324
1325
1326 /* LZX decruncher */
1327
1328 /* Microsoft's LZX document and their implementation of the
1329  * com.ms.util.cab Java package do not concur.
1330  *
1331  * In the LZX document, there is a table showing the correlation between
1332  * window size and the number of position slots. It states that the 1MB
1333  * window = 40 slots and the 2MB window = 42 slots. In the implementation,
1334  * 1MB = 42 slots, 2MB = 50 slots. The actual calculation is 'find the
1335  * first slot whose position base is equal to or more than the required
1336  * window size'. This would explain why other tables in the document refer
1337  * to 50 slots rather than 42.
1338  *
1339  * The constant NUM_PRIMARY_LENGTHS used in the decompression pseudocode
1340  * is not defined in the specification.
1341  *
1342  * The LZX document does not state the uncompressed block has an
1343  * uncompressed length field. Where does this length field come from, so
1344  * we can know how large the block is? The implementation has it as the 24
1345  * bits following after the 3 blocktype bits, before the alignment
1346  * padding.
1347  *
1348  * The LZX document states that aligned offset blocks have their aligned
1349  * offset huffman tree AFTER the main and length trees. The implementation
1350  * suggests that the aligned offset tree is BEFORE the main and length
1351  * trees.
1352  *
1353  * The LZX document decoding algorithm states that, in an aligned offset
1354  * block, if an extra_bits value is 1, 2 or 3, then that number of bits
1355  * should be read and the result added to the match offset. This is
1356  * correct for 1 and 2, but not 3, where just a huffman symbol (using the
1357  * aligned tree) should be read.
1358  *
1359  * Regarding the E8 preprocessing, the LZX document states 'No translation
1360  * may be performed on the last 6 bytes of the input block'. This is
1361  * correct.  However, the pseudocode provided checks for the *E8 leader*
1362  * up to the last 6 bytes. If the leader appears between -10 and -7 bytes
1363  * from the end, this would cause the next four bytes to be modified, at
1364  * least one of which would be in the last 6 bytes, which is not allowed
1365  * according to the spec.
1366  *
1367  * The specification states that the huffman trees must always contain at
1368  * least one element. However, many CAB files contain blocks where the
1369  * length tree is completely empty (because there are no matches), and
1370  * this is expected to succeed.
1371  */
1372
1373
1374 /* LZX uses what it calls 'position slots' to represent match offsets.
1375  * What this means is that a small 'position slot' number and a small
1376  * offset from that slot are encoded instead of one large offset for
1377  * every match.
1378  * - lzx_position_base is an index to the position slot bases
1379  * - lzx_extra_bits states how many bits of offset-from-base data is needed.
1380  */
1381 static ULONG lzx_position_base[51];
1382 static UBYTE extra_bits[51];
1383
1384 int LZXinit(int window) {
1385   ULONG wndsize = 1 << window;
1386   int i, j, posn_slots;
1387
1388   /* LZX supports window sizes of 2^15 (32Kb) through 2^21 (2Mb) */
1389   /* if a previously allocated window is big enough, keep it     */
1390   if (window < 15 || window > 21) return DECR_DATAFORMAT;
1391   if (LZX(actual_size) < wndsize) {
1392     if (LZX(window)) free(LZX(window));
1393     LZX(window) = NULL;
1394   }
1395   if (!LZX(window)) {
1396     if (!(LZX(window) = malloc(wndsize))) return DECR_NOMEMORY;
1397     LZX(actual_size) = wndsize;
1398   }
1399   LZX(window_size) = wndsize;
1400
1401   /* initialise static tables */
1402   for (i=0, j=0; i <= 50; i += 2) {
1403     extra_bits[i] = extra_bits[i+1] = j; /* 0,0,0,0,1,1,2,2,3,3... */
1404     if ((i != 0) && (j < 17)) j++; /* 0,0,1,2,3,4...15,16,17,17,17,17... */
1405   }
1406   for (i=0, j=0; i <= 50; i++) {
1407     lzx_position_base[i] = j; /* 0,1,2,3,4,6,8,12,16,24,32,... */
1408     j += 1 << extra_bits[i]; /* 1,1,1,1,2,2,4,4,8,8,16,16,32,32,... */
1409   }
1410
1411   /* calculate required position slots */
1412        if (window == 20) posn_slots = 42;
1413   else if (window == 21) posn_slots = 50;
1414   else posn_slots = window << 1;
1415
1416   /*posn_slots=i=0; while (i < wndsize) i += 1 << extra_bits[posn_slots++]; */
1417   
1418
1419   LZX(R0)  =  LZX(R1)  = LZX(R2) = 1;
1420   LZX(main_elements)   = LZX_NUM_CHARS + (posn_slots << 3);
1421   LZX(header_read)     = 0;
1422   LZX(frames_read)     = 0;
1423   LZX(block_remaining) = 0;
1424   LZX(block_type)      = LZX_BLOCKTYPE_INVALID;
1425   LZX(intel_curpos)    = 0;
1426   LZX(intel_started)   = 0;
1427   LZX(window_posn)     = 0;
1428
1429   /* initialise tables to 0 (because deltas will be applied to them) */
1430   for (i = 0; i < LZX_MAINTREE_MAXSYMBOLS; i++) LZX(MAINTREE_len)[i] = 0;
1431   for (i = 0; i < LZX_LENGTH_MAXSYMBOLS; i++)   LZX(LENGTH_len)[i]   = 0;
1432
1433   return DECR_OK;
1434 }
1435
1436 /* Bitstream reading macros (LZX / intel little-endian byte order)
1437  *
1438  * INIT_BITSTREAM    should be used first to set up the system
1439  * READ_BITS(var,n)  takes N bits from the buffer and puts them in var
1440  *
1441  * ENSURE_BITS(n)    ensures there are at least N bits in the bit buffer.
1442  *                   it can guarantee up to 17 bits (i.e. it can read in
1443  *                   16 new bits when there is down to 1 bit in the buffer,
1444  *                   and it can read 32 bits when there are 0 bits in the
1445  *                   buffer).
1446  * PEEK_BITS(n)      extracts (without removing) N bits from the bit buffer
1447  * REMOVE_BITS(n)    removes N bits from the bit buffer
1448  *
1449  * These bit access routines work by using the area beyond the MSB and the
1450  * LSB as a free source of zeroes. This avoids having to mask any bits.
1451  * So we have to know the bit width of the bitbuffer variable.
1452  */
1453
1454 #define INIT_BITSTREAM do { bitsleft = 0; bitbuf = 0; } while (0)
1455
1456 /* Quantum reads bytes in normal order; LZX is little-endian order */
1457 #define ENSURE_BITS(n)                                                  \
1458   while (bitsleft < (n)) {                                              \
1459     bitbuf |= ((inpos[1]<<8)|inpos[0]) << (ULONG_BITS-16 - bitsleft);   \
1460     bitsleft += 16; inpos+=2;                                           \
1461   }
1462
1463 #define PEEK_BITS(n)   (bitbuf >> (ULONG_BITS - (n)))
1464 #define REMOVE_BITS(n) ((bitbuf <<= (n)), (bitsleft -= (n)))
1465
1466 #define READ_BITS(v,n) do {                                             \
1467   if (n) {                                                              \
1468     ENSURE_BITS(n);                                                     \
1469     (v) = PEEK_BITS(n);                                                 \
1470     REMOVE_BITS(n);                                                     \
1471   }                                                                     \
1472   else {                                                                \
1473     (v) = 0;                                                            \
1474   }                                                                     \
1475 } while (0)
1476
1477 /* Huffman macros */
1478
1479 #define TABLEBITS(tbl)   (LZX_##tbl##_TABLEBITS)
1480 #define MAXSYMBOLS(tbl)  (LZX_##tbl##_MAXSYMBOLS)
1481 #define SYMTABLE(tbl)    (LZX(tbl##_table))
1482 #define LENTABLE(tbl)    (LZX(tbl##_len))
1483
1484 /* BUILD_TABLE(tablename) builds a huffman lookup table from code lengths.
1485  * In reality, it just calls make_decode_table() with the appropriate
1486  * values - they're all fixed by some #defines anyway, so there's no point
1487  * writing each call out in full by hand.
1488  */
1489 #define BUILD_TABLE(tbl)                                                \
1490   if (make_decode_table(                                                \
1491     MAXSYMBOLS(tbl), TABLEBITS(tbl), LENTABLE(tbl), SYMTABLE(tbl)       \
1492   )) { return DECR_ILLEGALDATA; }
1493
1494
1495 /* READ_HUFFSYM(tablename, var) decodes one huffman symbol from the
1496  * bitstream using the stated table and puts it in var.
1497  */
1498 #define READ_HUFFSYM(tbl,var) do {                                      \
1499   ENSURE_BITS(16);                                                      \
1500   hufftbl = SYMTABLE(tbl);                                              \
1501   if ((i = hufftbl[PEEK_BITS(TABLEBITS(tbl))]) >= MAXSYMBOLS(tbl)) {    \
1502     j = 1 << (ULONG_BITS - TABLEBITS(tbl));                             \
1503     do {                                                                \
1504       j >>= 1; i <<= 1; i |= (bitbuf & j) ? 1 : 0;                      \
1505       if (!j) { return DECR_ILLEGALDATA; }                              \
1506     } while ((i = hufftbl[i]) >= MAXSYMBOLS(tbl));                      \
1507   }                                                                     \
1508   j = LENTABLE(tbl)[(var) = i];                                         \
1509   REMOVE_BITS(j);                                                       \
1510 } while (0)
1511
1512
1513 /* READ_LENGTHS(tablename, first, last) reads in code lengths for symbols
1514  * first to last in the given table. The code lengths are stored in their
1515  * own special LZX way.
1516  */
1517 #define READ_LENGTHS(tbl,first,last) do { \
1518   lb.bb = bitbuf; lb.bl = bitsleft; lb.ip = inpos; \
1519   if (lzx_read_lens(LENTABLE(tbl),(first),(last),&lb)) { \
1520     return DECR_ILLEGALDATA; \
1521   } \
1522   bitbuf = lb.bb; bitsleft = lb.bl; inpos = lb.ip; \
1523 } while (0)
1524
1525
1526 /* make_decode_table(nsyms, nbits, length[], table[])
1527  *
1528  * This function was coded by David Tritscher. It builds a fast huffman
1529  * decoding table out of just a canonical huffman code lengths table.
1530  *
1531  * nsyms  = total number of symbols in this huffman tree.
1532  * nbits  = any symbols with a code length of nbits or less can be decoded
1533  *          in one lookup of the table.
1534  * length = A table to get code lengths from [0 to syms-1]
1535  * table  = The table to fill up with decoded symbols and pointers.
1536  *
1537  * Returns 0 for OK or 1 for error
1538  */
1539
1540 int make_decode_table(ULONG nsyms, ULONG nbits, UBYTE *length, UWORD *table) {
1541   register UWORD sym;
1542   register ULONG leaf;
1543   register UBYTE bit_num = 1;
1544   ULONG fill;
1545   ULONG pos         = 0; /* the current position in the decode table */
1546   ULONG table_mask  = 1 << nbits;
1547   ULONG bit_mask    = table_mask >> 1; /* don't do 0 length codes */
1548   ULONG next_symbol = bit_mask; /* base of allocation for long codes */
1549
1550   /* fill entries for codes short enough for a direct mapping */
1551   while (bit_num <= nbits) {
1552     for (sym = 0; sym < nsyms; sym++) {
1553       if (length[sym] == bit_num) {
1554         leaf = pos;
1555
1556         if((pos += bit_mask) > table_mask) return 1; /* table overrun */
1557
1558         /* fill all possible lookups of this symbol with the symbol itself */
1559         fill = bit_mask;
1560         while (fill-- > 0) table[leaf++] = sym;
1561       }
1562     }
1563     bit_mask >>= 1;
1564     bit_num++;
1565   }
1566
1567   /* if there are any codes longer than nbits */
1568   if (pos != table_mask) {
1569     /* clear the remainder of the table */
1570     for (sym = pos; sym < table_mask; sym++) table[sym] = 0;
1571
1572     /* give ourselves room for codes to grow by up to 16 more bits */
1573     pos <<= 16;
1574     table_mask <<= 16;
1575     bit_mask = 1 << 15;
1576
1577     while (bit_num <= 16) {
1578       for (sym = 0; sym < nsyms; sym++) {
1579         if (length[sym] == bit_num) {
1580           leaf = pos >> 16;
1581           for (fill = 0; fill < bit_num - nbits; fill++) {
1582             /* if this path hasn't been taken yet, 'allocate' two entries */
1583             if (table[leaf] == 0) {
1584               table[(next_symbol << 1)] = 0;
1585               table[(next_symbol << 1) + 1] = 0;
1586               table[leaf] = next_symbol++;
1587             }
1588             /* follow the path and select either left or right for next bit */
1589             leaf = table[leaf] << 1;
1590             if ((pos >> (15-fill)) & 1) leaf++;
1591           }
1592           table[leaf] = sym;
1593
1594           if ((pos += bit_mask) > table_mask) return 1; /* table overflow */
1595         }
1596       }
1597       bit_mask >>= 1;
1598       bit_num++;
1599     }
1600   }
1601
1602   /* full table? */
1603   if (pos == table_mask) return 0;
1604
1605   /* either erroneous table, or all elements are 0 - let's find out. */
1606   for (sym = 0; sym < nsyms; sym++) if (length[sym]) return 1;
1607   return 0;
1608 }
1609
1610 struct lzx_bits {
1611   ULONG bb;
1612   int bl;
1613   UBYTE *ip;
1614 };
1615
1616 int lzx_read_lens(UBYTE *lens, ULONG first, ULONG last, struct lzx_bits *lb) {
1617   ULONG i,j, x,y;
1618   int z;
1619
1620   register ULONG bitbuf = lb->bb;
1621   register int bitsleft = lb->bl;
1622   UBYTE *inpos = lb->ip;
1623   UWORD *hufftbl;
1624   
1625   for (x = 0; x < 20; x++) {
1626     READ_BITS(y, 4);
1627     LENTABLE(PRETREE)[x] = y;
1628   }
1629   BUILD_TABLE(PRETREE);
1630
1631   for (x = first; x < last; ) {
1632     READ_HUFFSYM(PRETREE, z);
1633     if (z == 17) {
1634       READ_BITS(y, 4); y += 4;
1635       while (y--) lens[x++] = 0;
1636     }
1637     else if (z == 18) {
1638       READ_BITS(y, 5); y += 20;
1639       while (y--) lens[x++] = 0;
1640     }
1641     else if (z == 19) {
1642       READ_BITS(y, 1); y += 4;
1643       READ_HUFFSYM(PRETREE, z);
1644       z = lens[x] - z; if (z < 0) z += 17;
1645       while (y--) lens[x++] = z;
1646     }
1647     else {
1648       z = lens[x] - z; if (z < 0) z += 17;
1649       lens[x++] = z;
1650     }
1651   }
1652
1653   lb->bb = bitbuf;
1654   lb->bl = bitsleft;
1655   lb->ip = inpos;
1656   return 0;
1657 }
1658
1659 int LZXdecompress(int inlen, int outlen) {
1660   UBYTE *inpos  = CAB(inbuf);
1661   UBYTE *endinp = inpos + inlen;
1662   UBYTE *window = LZX(window);
1663   UBYTE *runsrc, *rundest;
1664   UWORD *hufftbl; /* used in READ_HUFFSYM macro as chosen decoding table */
1665
1666   ULONG window_posn = LZX(window_posn);
1667   ULONG window_size = LZX(window_size);
1668   ULONG R0 = LZX(R0);
1669   ULONG R1 = LZX(R1);
1670   ULONG R2 = LZX(R2);
1671
1672   register ULONG bitbuf;
1673   register int bitsleft;
1674   ULONG match_offset, i,j,k; /* ijk used in READ_HUFFSYM macro */
1675   struct lzx_bits lb; /* used in READ_LENGTHS macro */
1676
1677   int togo = outlen, this_run, main_element, aligned_bits;
1678   int match_length, copy_length, length_footer, extra, verbatim_bits;
1679
1680   INIT_BITSTREAM;
1681
1682   /* read header if necessary */
1683   if (!LZX(header_read)) {
1684     i = j = 0;
1685     READ_BITS(k, 1); if (k) { READ_BITS(i,16); READ_BITS(j,16); }
1686     LZX(intel_filesize) = (i << 16) | j; /* or 0 if not encoded */
1687     LZX(header_read) = 1;
1688   }
1689
1690   /* main decoding loop */
1691   while (togo > 0) {
1692     /* last block finished, new block expected */
1693     if (LZX(block_remaining) == 0) {
1694       if (LZX(block_type) == LZX_BLOCKTYPE_UNCOMPRESSED) {
1695         if (LZX(block_length) & 1) inpos++; /* realign bitstream to word */
1696         INIT_BITSTREAM;
1697       }
1698
1699       READ_BITS(LZX(block_type), 3);
1700       READ_BITS(i, 16);
1701       READ_BITS(j, 8);
1702       LZX(block_remaining) = LZX(block_length) = (i << 8) | j;
1703
1704       switch (LZX(block_type)) {
1705       case LZX_BLOCKTYPE_ALIGNED:
1706         for (i = 0; i < 8; i++) { READ_BITS(j, 3); LENTABLE(ALIGNED)[i] = j; }
1707         BUILD_TABLE(ALIGNED);
1708         /* rest of aligned header is same as verbatim */
1709
1710       case LZX_BLOCKTYPE_VERBATIM:
1711         READ_LENGTHS(MAINTREE, 0, 256);
1712         READ_LENGTHS(MAINTREE, 256, LZX(main_elements));
1713         BUILD_TABLE(MAINTREE);
1714         if (LENTABLE(MAINTREE)[0xE8] != 0) LZX(intel_started) = 1;
1715
1716         READ_LENGTHS(LENGTH, 0, LZX_NUM_SECONDARY_LENGTHS);
1717         BUILD_TABLE(LENGTH);
1718         break;
1719
1720       case LZX_BLOCKTYPE_UNCOMPRESSED:
1721         LZX(intel_started) = 1; /* because we can't assume otherwise */
1722         ENSURE_BITS(16); /* get up to 16 pad bits into the buffer */
1723         if (bitsleft > 16) inpos -= 2; /* and align the bitstream! */
1724         R0 = inpos[0]|(inpos[1]<<8)|(inpos[2]<<16)|(inpos[3]<<24);inpos+=4;
1725         R1 = inpos[0]|(inpos[1]<<8)|(inpos[2]<<16)|(inpos[3]<<24);inpos+=4;
1726         R2 = inpos[0]|(inpos[1]<<8)|(inpos[2]<<16)|(inpos[3]<<24);inpos+=4;
1727         break;
1728
1729       default:
1730         return DECR_ILLEGALDATA;
1731       }
1732     }
1733
1734     /* buffer exhaustion check */
1735     if (inpos > endinp) {
1736       /* it's possible to have a file where the next run is less than
1737        * 16 bits in size. In this case, the READ_HUFFSYM() macro used
1738        * in building the tables will exhaust the buffer, so we should
1739        * allow for this, but not allow those accidentally read bits to
1740        * be used (so we check that there are at least 16 bits
1741        * remaining - in this boundary case they aren't really part of
1742        * the compressed data)
1743        */
1744       if (inpos > (endinp+2) || bitsleft < 16) return DECR_ILLEGALDATA;
1745     }
1746
1747     while ((this_run = LZX(block_remaining)) > 0 && togo > 0) {
1748       if (this_run > togo) this_run = togo;
1749       togo -= this_run;
1750       LZX(block_remaining) -= this_run;
1751
1752       /* apply 2^x-1 mask */
1753       window_posn &= window_size - 1;
1754       /* runs can't straddle the window wraparound */
1755       if ((window_posn + this_run) > window_size)
1756         return DECR_DATAFORMAT;
1757
1758       switch (LZX(block_type)) {
1759
1760       case LZX_BLOCKTYPE_VERBATIM:
1761         while (this_run > 0) {
1762           READ_HUFFSYM(MAINTREE, main_element);
1763
1764           if (main_element < LZX_NUM_CHARS) {
1765             /* literal: 0 to LZX_NUM_CHARS-1 */
1766             window[window_posn++] = main_element;
1767             this_run--;
1768           }
1769           else {
1770             /* match: LZX_NUM_CHARS + ((slot<<3) | length_header (3 bits)) */
1771             main_element -= LZX_NUM_CHARS;
1772   
1773             match_length = main_element & LZX_NUM_PRIMARY_LENGTHS;
1774             if (match_length == LZX_NUM_PRIMARY_LENGTHS) {
1775               READ_HUFFSYM(LENGTH, length_footer);
1776               match_length += length_footer;
1777             }
1778             match_length += LZX_MIN_MATCH;
1779   
1780             match_offset = main_element >> 3;
1781   
1782             if (match_offset > 2) {
1783               /* not repeated offset */
1784               if (match_offset != 3) {
1785                 extra = extra_bits[match_offset];
1786                 READ_BITS(verbatim_bits, extra);
1787                 match_offset = lzx_position_base[match_offset] 
1788                                - 2 + verbatim_bits;
1789               }
1790               else {
1791                 match_offset = 1;
1792               }
1793   
1794               /* update repeated offset LRU queue */
1795               R2 = R1; R1 = R0; R0 = match_offset;
1796             }
1797             else if (match_offset == 0) {
1798               match_offset = R0;
1799             }
1800             else if (match_offset == 1) {
1801               match_offset = R1;
1802               R1 = R0; R0 = match_offset;
1803             }
1804             else /* match_offset == 2 */ {
1805               match_offset = R2;
1806               R2 = R0; R0 = match_offset;
1807             }
1808
1809             rundest = window + window_posn;
1810             this_run -= match_length;
1811
1812             /* copy any wrapped around source data */
1813             if (window_posn >= match_offset) {
1814               /* no wrap */
1815               runsrc = rundest - match_offset;
1816             } else {
1817               runsrc = rundest + (window_size - match_offset);
1818               copy_length = match_offset - window_posn;
1819               if (copy_length < match_length) {
1820                 match_length -= copy_length;
1821                 window_posn += copy_length;
1822                 while (copy_length-- > 0) *rundest++ = *runsrc++;
1823                 runsrc = window;
1824               }
1825             }
1826             window_posn += match_length;
1827
1828             /* copy match data - no worries about destination wraps */
1829             while (match_length-- > 0) *rundest++ = *runsrc++;
1830           }
1831         }
1832         break;
1833
1834       case LZX_BLOCKTYPE_ALIGNED:
1835         while (this_run > 0) {
1836           READ_HUFFSYM(MAINTREE, main_element);
1837   
1838           if (main_element < LZX_NUM_CHARS) {
1839             /* literal: 0 to LZX_NUM_CHARS-1 */
1840             window[window_posn++] = main_element;
1841             this_run--;
1842           }
1843           else {
1844             /* match: LZX_NUM_CHARS + ((slot<<3) | length_header (3 bits)) */
1845             main_element -= LZX_NUM_CHARS;
1846   
1847             match_length = main_element & LZX_NUM_PRIMARY_LENGTHS;
1848             if (match_length == LZX_NUM_PRIMARY_LENGTHS) {
1849               READ_HUFFSYM(LENGTH, length_footer);
1850               match_length += length_footer;
1851             }
1852             match_length += LZX_MIN_MATCH;
1853   
1854             match_offset = main_element >> 3;
1855   
1856             if (match_offset > 2) {
1857               /* not repeated offset */
1858               extra = extra_bits[match_offset];
1859               match_offset = lzx_position_base[match_offset] - 2;
1860               if (extra > 3) {
1861                 /* verbatim and aligned bits */
1862                 extra -= 3;
1863                 READ_BITS(verbatim_bits, extra);
1864                 match_offset += (verbatim_bits << 3);
1865                 READ_HUFFSYM(ALIGNED, aligned_bits);
1866                 match_offset += aligned_bits;
1867               }
1868               else if (extra == 3) {
1869                 /* aligned bits only */
1870                 READ_HUFFSYM(ALIGNED, aligned_bits);
1871                 match_offset += aligned_bits;
1872               }
1873               else if (extra > 0) { /* extra==1, extra==2 */
1874                 /* verbatim bits only */
1875                 READ_BITS(verbatim_bits, extra);
1876                 match_offset += verbatim_bits;
1877               }
1878               else /* extra == 0 */ {
1879                 /* ??? */
1880                 match_offset = 1;
1881               }
1882   
1883               /* update repeated offset LRU queue */
1884               R2 = R1; R1 = R0; R0 = match_offset;
1885             }
1886             else if (match_offset == 0) {
1887               match_offset = R0;
1888             }
1889             else if (match_offset == 1) {
1890               match_offset = R1;
1891               R1 = R0; R0 = match_offset;
1892             }
1893             else /* match_offset == 2 */ {
1894               match_offset = R2;
1895               R2 = R0; R0 = match_offset;
1896             }
1897
1898             rundest = window + window_posn;
1899             this_run -= match_length;
1900
1901             /* copy any wrapped around source data */
1902             if (window_posn >= match_offset) {
1903               /* no wrap */
1904               runsrc = rundest - match_offset;
1905             } else {
1906               runsrc = rundest + (window_size - match_offset);
1907               copy_length = match_offset - window_posn;
1908               if (copy_length < match_length) {
1909                 match_length -= copy_length;
1910                 window_posn += copy_length;
1911                 while (copy_length-- > 0) *rundest++ = *runsrc++;
1912                 runsrc = window;
1913               }
1914             }
1915             window_posn += match_length;
1916
1917             /* copy match data - no worries about destination wraps */
1918             while (match_length-- > 0) *rundest++ = *runsrc++;
1919           }
1920         }
1921         break;
1922
1923       case LZX_BLOCKTYPE_UNCOMPRESSED:
1924         if ((inpos + this_run) > endinp) return DECR_ILLEGALDATA;
1925         memcpy(window + window_posn, inpos, (size_t) this_run);
1926         inpos += this_run; window_posn += this_run;
1927         break;
1928
1929       default:
1930         return DECR_ILLEGALDATA; /* might as well */
1931       }
1932
1933     }
1934   }
1935
1936   if (togo != 0) return DECR_ILLEGALDATA;
1937   memcpy(CAB(outbuf), window + ((!window_posn) ? window_size : window_posn) -
1938     outlen, (size_t) outlen);
1939
1940   LZX(window_posn) = window_posn;
1941   LZX(R0) = R0;
1942   LZX(R1) = R1;
1943   LZX(R2) = R2;
1944
1945   /* intel E8 decoding */
1946   if ((LZX(frames_read)++ < 32768) && LZX(intel_filesize) != 0) {
1947     if (outlen <= 6 || !LZX(intel_started)) {
1948       LZX(intel_curpos) += outlen;
1949     }
1950     else {
1951       UBYTE *data    = CAB(outbuf);
1952       UBYTE *dataend = data + outlen - 10;
1953       LONG curpos    = LZX(intel_curpos);
1954       LONG filesize  = LZX(intel_filesize);
1955       LONG abs_off, rel_off;
1956
1957       LZX(intel_curpos) = curpos + outlen;
1958
1959       while (data < dataend) {
1960         if (*data++ != 0xE8) { curpos++; continue; }
1961         abs_off = data[0] | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
1962         if ((abs_off >= -curpos) && (abs_off < filesize)) {
1963           rel_off = (abs_off >= 0) ? abs_off - curpos : abs_off + filesize;
1964           data[0] = (UBYTE) rel_off;
1965           data[1] = (UBYTE) (rel_off >> 8);
1966           data[2] = (UBYTE) (rel_off >> 16);
1967           data[3] = (UBYTE) (rel_off >> 24);
1968         }
1969         data += 4;
1970         curpos += 5;
1971       }
1972     }
1973   }
1974   return DECR_OK;
1975 }
1976
1977
1978
1979
1980 /* all the file IO is abstracted into these routines:
1981  * cabinet_(open|close|read|seek|skip|getoffset)
1982  * file_(open|close|write)
1983  */
1984
1985 /* ensure_filepath("a/b/c/d.txt") ensures a, a/b and a/b/c exist as dirs */
1986 int ensure_filepath(char *path) {
1987   struct stat st_buf;
1988   mode_t m;
1989   char *p;
1990   int ok;
1991
1992   m = umask(0); umask(m); /* obtain user's umask */
1993
1994   for (p = path; *p; p++) {
1995     if ((p != path) && (*p == '/')) {
1996       *p = 0;
1997       ok = (stat(path, &st_buf) == 0) && S_ISDIR(st_buf.st_mode);
1998       if (!ok) ok = (mkdir(path, 0777 & ~m) == 0);
1999       *p = '/';
2000       if (!ok) return 0;
2001     }
2002   }
2003   return 1;
2004 }
2005
2006 /* opens a file for output, returns success */
2007 int file_open(struct file *fi, int lower, char *dir) {
2008   char c, *s, *d, *name;
2009   int ok = 0;
2010
2011   if (!(name = malloc(strlen(fi->filename) + (dir ? strlen(dir) : 0) + 2))) {
2012     fprintf(stderr, "out of memory!\n");
2013     return 0;
2014   }
2015   
2016   /* start with blank name */
2017   *name = 0;
2018
2019   /* add output directory if needed */
2020   if (dir) {
2021     strcpy(name, dir);
2022     strcat(name, "/");
2023   }
2024
2025
2026   /* remove leading slashes */
2027   s = fi->filename;
2028   while (*s == '\\') s++;
2029
2030   /* copy from fi->filename to new name, converting MS-DOS slashes to UNIX
2031    * slashes as we go. Also lowercases characters if needed.
2032    */
2033   d = &name[strlen(name)];
2034   do {
2035     c = *s++;
2036     *d++ = (c=='/') ? '\\' : ((c=='\\') ? '/' :
2037            (lower ? tolower((unsigned char) c) : c));
2038   } while (c);
2039   
2040   /* create directories if needed, attempt to write file */
2041   if (ensure_filepath(name)) {
2042     fi->fh = fopen(name, "wb");
2043     if (fi->fh) ok = 1;
2044   }
2045
2046   /* as full filename is no longer needed, free it */
2047   free(name);
2048
2049   if (!ok) {
2050     perror(fi->filename);
2051   }
2052   return ok;
2053 }
2054
2055 /* closes a completed file, updates protections and timestamp */
2056 void file_close(struct file *fi) {
2057   struct utimbuf utb;
2058   struct tm time;
2059   mode_t m;
2060
2061   if (fi->fh) {
2062     fclose(fi->fh);
2063   }
2064   fi->fh = NULL;
2065
2066   m = umask(0); umask(m); /* obtain user's umask */
2067   chmod(fi->filename,
2068     ((mode_t) 0444
2069     | (fi->attribs & cffile_A_EXEC   ? 0111 : 0)
2070     | (fi->attribs & cffile_A_RDONLY ? 0 : 0222)) & ~ m
2071   );
2072
2073
2074   time.tm_sec   = (fi->time << 1)   & 0x3e;
2075   time.tm_min   = (fi->time >> 5)   & 0x3f;
2076   time.tm_hour  = (fi->time >> 11);
2077   time.tm_mday  =  fi->date         & 0x1f;
2078   time.tm_mon   =((fi->date >> 5)   & 0xf) - 1;
2079   time.tm_year  = (fi->date >> 9)   + 80;
2080   time.tm_isdst = -1;
2081 #ifdef HAVE_UTIME
2082   utb.actime = utb.modtime = mktime(&time);
2083   utime(fi->filename, &utb);
2084 #endif
2085 }
2086
2087 int file_write(struct file *fi, UBYTE *buf, size_t length) {
2088   if (fwrite((void *)buf, 1, length, fi->fh) != length) {
2089     perror(fi->filename);
2090     return 0;
2091   }
2092   return 1;
2093 }
2094
2095
2096 void cabinet_close(struct cabinet *cab) {
2097   if (cab->fh) {
2098     fclose(cab->fh);
2099   }
2100   cab->fh = NULL;
2101 }
2102
2103 void cabinet_seek(struct cabinet *cab, off_t offset) {
2104   if (fseek(cab->fh, offset, SEEK_SET) < 0) {
2105     perror(cab->filename);
2106   }
2107 }
2108
2109 void cabinet_skip(struct cabinet *cab, off_t distance) {
2110   if (fseek(cab->fh, distance, SEEK_CUR) < 0) {
2111     perror(cab->filename);
2112   }
2113 }
2114
2115 off_t cabinet_getoffset(struct cabinet *cab) {
2116   return ftell(cab->fh);
2117 }
2118
2119 /* read data from a cabinet, returns success */
2120 int cabinet_read(struct cabinet *cab, UBYTE *buf, size_t length) {
2121   size_t avail = (size_t) (cab->filelen - cabinet_getoffset(cab));
2122   if (length > avail) {
2123     fprintf(stderr, "%s: WARNING; cabinet is truncated\n", cab->filename);
2124     length = avail;
2125   }
2126   if (fread((void *)buf, 1, length, cab->fh) != length) {
2127     perror(cab->filename);
2128     return 0;
2129   }
2130   return 1;
2131 }
2132
2133 /* try to open a cabinet file, returns success */
2134 int cabinet_open(struct cabinet *cab) {
2135   char *name = cab->filename;
2136   FILE *fh;
2137
2138   /* note: this is now case sensitive */
2139   if (!(fh = fopen(name, "rb"))) {
2140     perror(name);
2141     return 0;
2142   }
2143
2144   /* seek to end of file */
2145   if (fseek(fh, 0, SEEK_END) != 0) {
2146     perror(name);
2147     fclose(fh);
2148     return 0;
2149   }
2150
2151   /* get length of file */
2152   cab->filelen = ftell(fh);
2153
2154   /* return to the start of the file */
2155   if (fseek(fh, 0, SEEK_SET) != 0) {
2156     perror(name);
2157     fclose(fh);
2158     return 0;
2159   }
2160
2161   cab->fh = fh;
2162   return 1;
2163 }
2164
2165 /* allocate and read an aribitrarily long string from the cabinet */
2166 char *cabinet_read_string(struct cabinet *cab) {
2167   off_t len=256, base = cabinet_getoffset(cab), maxlen = cab->filelen - base;
2168   int ok = 0, i;
2169   UBYTE *buf = NULL;
2170   do {
2171     if (len > maxlen) len = maxlen;
2172     if (!(buf = realloc(buf, (size_t) len))) break;
2173     if (!cabinet_read(cab, buf, (size_t) len)) break;
2174
2175     /* search for a null terminator in what we've just read */
2176     for (i=0; i < len; i++) {
2177       if (!buf[i]) {ok=1; break;}
2178     }
2179
2180     if (!ok) {
2181       if (len == maxlen) {
2182         fprintf(stderr, "%s: WARNING; cabinet is truncated\n", cab->filename);
2183         break;
2184       }
2185       len += 256;
2186       cabinet_seek(cab, base);
2187     }
2188   } while (!ok);
2189
2190   if (!ok) {
2191     if (buf) free(buf); else fprintf(stderr, "out of memory!\n");
2192     return NULL;
2193   }
2194
2195   /* otherwise, set the stream to just after the string and return */
2196   cabinet_seek(cab, base + ((off_t) strlen((char *) buf)) + 1);
2197   return (char *) buf;
2198 }
2199
2200 /* reads the header and all folder and file entries in this cabinet */
2201 int cabinet_read_entries(struct cabinet *cab) {
2202   int num_folders, num_files, header_resv, folder_resv = 0, i;
2203   struct folder *fol, *linkfol = NULL;
2204   struct file *file, *linkfile = NULL;
2205   off_t base_offset;
2206   UBYTE buf[64];
2207
2208   /* read in the CFHEADER */
2209   base_offset = cabinet_getoffset(cab);
2210   if (!cabinet_read(cab, buf, cfhead_SIZEOF)) {
2211     return 0;
2212   }
2213   
2214   /* check basic MSCF signature */
2215   if (EndGetI32(buf+cfhead_Signature) != 0x4643534d) {
2216     fprintf(stderr, "%s: not a Microsoft cabinet file\n", cab->filename);
2217     return 0;
2218   }
2219
2220   /* get the number of folders */
2221   num_folders = EndGetI16(buf+cfhead_NumFolders);
2222   if (num_folders == 0) {
2223     fprintf(stderr, "%s: no folders in cabinet\n", cab->filename);
2224     return 0;
2225   }
2226
2227   /* get the number of files */
2228   num_files = EndGetI16(buf+cfhead_NumFiles);
2229   if (num_files == 0) {
2230     fprintf(stderr, "%s: no files in cabinet\n", cab->filename);
2231     return 0;
2232   }
2233
2234   /* just check the header revision */
2235   if ((buf[cfhead_MajorVersion] > 1) ||
2236       (buf[cfhead_MajorVersion] == 1 && buf[cfhead_MinorVersion] > 3))
2237   {
2238     fprintf(stderr, "%s: WARNING; cabinet format version > 1.3\n",
2239             cab->filename);
2240   }
2241
2242   /* read the reserved-sizes part of header, if present */
2243   cab->flags = EndGetI16(buf+cfhead_Flags);
2244   if (cab->flags & cfheadRESERVE_PRESENT) {
2245     if (!cabinet_read(cab, buf, cfheadext_SIZEOF)) return 0;
2246     header_resv     = EndGetI16(buf+cfheadext_HeaderReserved);
2247     folder_resv     = buf[cfheadext_FolderReserved];
2248     cab->block_resv = buf[cfheadext_DataReserved];
2249
2250     if (header_resv > 60000) {
2251       fprintf(stderr, "%s: WARNING; header reserved space > 60000\n",
2252               cab->filename);
2253     }
2254
2255     /* skip the reserved header */
2256     if (header_resv) fseek(cab->fh, (off_t) header_resv, SEEK_CUR);
2257   }
2258
2259   if (cab->flags & cfheadPREV_CABINET) {
2260     cab->prevname = cabinet_read_string(cab);
2261     if (!cab->prevname) return 0;
2262     cab->previnfo = cabinet_read_string(cab);
2263   }
2264
2265   if (cab->flags & cfheadNEXT_CABINET) {
2266     cab->nextname = cabinet_read_string(cab);
2267     if (!cab->nextname) return 0;
2268     cab->nextinfo = cabinet_read_string(cab);
2269   }
2270
2271   /* read folders */
2272   for (i = 0; i < num_folders; i++) {
2273     if (!cabinet_read(cab, buf, cffold_SIZEOF)) return 0;
2274     if (folder_resv) cabinet_skip(cab, folder_resv);
2275
2276     fol = (struct folder *) calloc(1, sizeof(struct folder));
2277     if (!fol) { fprintf(stderr, "out of memory!\n"); return 0; }
2278
2279     fol->cab[0]     = cab;
2280     fol->offset[0]  = base_offset + (off_t) EndGetI32(buf+cffold_DataOffset);
2281     fol->num_blocks = EndGetI16(buf+cffold_NumBlocks);
2282     fol->comp_type  = EndGetI16(buf+cffold_CompType);
2283
2284     if (!linkfol) cab->folders = fol; else linkfol->next = fol;
2285     linkfol = fol;
2286   }
2287
2288   /* read files */
2289   for (i = 0; i < num_files; i++) {
2290     if (!cabinet_read(cab, buf, cffile_SIZEOF)) return 0;
2291     file = (struct file *) calloc(1, sizeof(struct file));
2292     if (!file) { fprintf(stderr, "out of memory!\n"); return 0; }
2293       
2294     file->length   = EndGetI32(buf+cffile_UncompressedSize);
2295     file->offset   = EndGetI32(buf+cffile_FolderOffset);
2296     file->index    = EndGetI16(buf+cffile_FolderIndex);
2297     file->time     = EndGetI16(buf+cffile_Time);
2298     file->date     = EndGetI16(buf+cffile_Date);
2299     file->attribs  = EndGetI16(buf+cffile_Attribs);
2300     file->filename = cabinet_read_string(cab);
2301     if (!file->filename) return 0;
2302     if (!linkfile) cab->files = file; else linkfile->next = file;
2303     linkfile = file;
2304   }
2305   return 1;
2306 }
2307
2308
2309 /* this does the tricky job of running through every file in the cabinet,
2310  * including spanning cabinets, and working out which file is in which
2311  * folder in which cabinet. It also throws out the duplicate file entries
2312  * that appear in spanning cabinets. There is memory leakage here because
2313  * those entries are not freed. See the XAD CAB client for an
2314  * implementation of this that correctly frees the discarded file entries.
2315  */
2316 struct file *process_files(struct cabinet *basecab) {
2317   struct cabinet *cab;
2318   struct file *outfi = NULL, *linkfi = NULL, *nextfi, *fi, *cfi;
2319   struct folder *fol, *firstfol, *lastfol = NULL, *predfol;
2320   int i, mergeok;
2321
2322   for (cab = basecab; cab; cab = cab->nextcab) {
2323     /* firstfol = first folder in this cabinet */
2324     /* lastfol  = last folder in this cabinet */
2325     /* predfol  = last folder in previous cabinet (or NULL if first cabinet) */
2326     predfol = lastfol;
2327     firstfol = cab->folders;
2328     for (lastfol = firstfol; lastfol->next;) lastfol = lastfol->next;
2329     mergeok = 1;
2330
2331     for (fi = cab->files; fi; fi = nextfi) {
2332       i = fi->index;
2333       nextfi = fi->next;
2334
2335       if (i < cffileCONTINUED_FROM_PREV) {
2336         for (fol = firstfol; fol && i--; ) fol = fol->next;
2337         fi->folder = fol; /* NULL if an invalid folder index */
2338       }
2339       else {
2340         /* folder merging */
2341         if (i == cffileCONTINUED_TO_NEXT
2342         ||  i == cffileCONTINUED_PREV_AND_NEXT) {
2343           if (cab->nextcab && !lastfol->contfile) lastfol->contfile = fi;
2344         }
2345
2346         if (i == cffileCONTINUED_FROM_PREV
2347         ||  i == cffileCONTINUED_PREV_AND_NEXT) {
2348           /* these files are to be continued in yet another
2349            * cabinet, don't merge them in just yet */
2350           if (i == cffileCONTINUED_PREV_AND_NEXT) mergeok = 0;
2351
2352           /* only merge once per cabinet */
2353           if (predfol) {
2354             if ((cfi = predfol->contfile)
2355             && (cfi->offset == fi->offset)
2356             && (cfi->length == fi->length)
2357             && (strcmp(cfi->filename, fi->filename) == 0)
2358             && (predfol->comp_type == firstfol->comp_type)) {
2359               /* increase the number of splits */
2360               if ((i = ++(predfol->num_splits)) > CAB_SPLITMAX) {
2361                 mergeok = 0;
2362                 fprintf(stderr, "%s: internal error, increase CAB_SPLITMAX\n",
2363                   basecab->filename);
2364               }
2365               else {
2366                 /* copy information across from the merged folder */
2367                 predfol->offset[i] = firstfol->offset[0];
2368                 predfol->cab[i]    = firstfol->cab[0];
2369                 predfol->next      = firstfol->next;
2370                 predfol->contfile  = firstfol->contfile;
2371
2372                 if (firstfol == lastfol) lastfol = predfol;
2373                 firstfol = predfol;
2374                 predfol = NULL; /* don't merge again within this cabinet */
2375               }
2376             }
2377             else {
2378               /* if the folders won't merge, don't add their files */
2379               mergeok = 0;
2380             }
2381           }
2382
2383           if (mergeok) fi->folder = firstfol;
2384         }
2385       }
2386
2387       if (fi->folder) {
2388         if (linkfi) linkfi->next = fi; else outfi = fi;
2389         linkfi = fi;
2390       }
2391     } /* for (fi= .. */
2392   } /* for (cab= ...*/
2393
2394   return outfi;
2395 }
2396
2397 /* validates and reads file entries from a cabinet at offset [offset] in
2398  * file [name]. Returns a cabinet structure if successful, or NULL
2399  * otherwise.
2400  */
2401 struct cabinet *load_cab_offset(char *name, off_t offset) {
2402   struct cabinet *cab = (struct cabinet *) calloc(1, sizeof(struct cabinet));
2403   int ok;
2404   if (!cab) return NULL;
2405
2406   cab->filename = name;
2407   if ((ok = cabinet_open(cab))) {
2408     cabinet_seek(cab, offset);
2409     ok = cabinet_read_entries(cab);
2410     cabinet_close(cab);
2411   }
2412
2413   if (ok) return cab;
2414   free(cab);
2415   return NULL;
2416 }
2417
2418 /* Searches a file for embedded cabinets (also succeeds on just normal
2419  * cabinet files). The first result of this search will be returned, and
2420  * the remaining results will be chained to it via the cab->next structure
2421  * member.
2422  */
2423 #define SEARCH_SIZE (32*1024)
2424 UBYTE search_buf[SEARCH_SIZE];
2425
2426 struct cabinet *find_cabs_in_file(char *name) {
2427   struct cabinet *cab, *cab2, *firstcab = NULL, *linkcab = NULL;
2428   UBYTE *pstart = &search_buf[0], *pend, *p;
2429   ULONG offset, caboff, cablen, foffset, filelen;
2430   size_t length;
2431   int state = 0, found = 0, ok = 0;
2432
2433   /* open the file and search for cabinet headers */
2434   if ((cab = (struct cabinet *) calloc(1, sizeof(struct cabinet)))) {
2435     cab->filename = name;
2436     if (cabinet_open(cab)) {
2437       filelen = (ULONG) cab->filelen;
2438       for (offset = 0; offset < filelen; offset += length) {
2439         /* search length is either the full length of the search buffer,
2440          * or the amount of data remaining to the end of the file,
2441          * whichever is less.
2442          */
2443         length = filelen - offset;
2444         if (length > SEARCH_SIZE) length = SEARCH_SIZE;
2445
2446         /* fill the search buffer with data from disk */
2447         if (!cabinet_read(cab, search_buf, length)) break;
2448
2449         /* read through the entire buffer. */
2450         p = pstart;
2451         pend = &search_buf[length];
2452         while (p < pend) {
2453           switch (state) {
2454           /* starting state */
2455           case 0:
2456             /* we spend most of our time in this while loop, looking for
2457              * a leading 'M' of the 'MSCF' signature
2458              */
2459             while (*p++ != 0x4D && p < pend);
2460             if (p < pend) state = 1; /* if we found tht 'M', advance state */
2461             break;
2462
2463           /* verify that the next 3 bytes are 'S', 'C' and 'F' */
2464           case 1: state = (*p++ == 0x53) ? 2 : 0; break;
2465           case 2: state = (*p++ == 0x43) ? 3 : 0; break;
2466           case 3: state = (*p++ == 0x46) ? 4 : 0; break;
2467
2468           /* we don't care about bytes 4-7 */
2469           /* bytes 8-11 are the overall length of the cabinet */
2470           case 8:  cablen  = *p++;       state++; break;
2471           case 9:  cablen |= *p++ << 8;  state++; break;
2472           case 10: cablen |= *p++ << 16; state++; break;
2473           case 11: cablen |= *p++ << 24; state++; break;
2474
2475           /* we don't care about bytes 12-15 */
2476           /* bytes 16-19 are the offset within the cabinet of the filedata */
2477           case 16: foffset  = *p++;       state++; break;
2478           case 17: foffset |= *p++ << 8;  state++; break;
2479           case 18: foffset |= *p++ << 16; state++; break;
2480           case 19: foffset |= *p++ << 24;
2481             /* now we have recieved 20 bytes of potential cab header. */
2482             /* work out the offset in the file of this potential cabinet */
2483             caboff = offset + (p-pstart) - 20;
2484
2485             /* check that the files offset is less than the alleged length
2486              * of the cabinet, and that the offset + the alleged length are
2487              * 'roughly' within the end of overall file length
2488              */
2489             if ((foffset < cablen) &&
2490                 ((caboff + foffset) < (filelen + 32)) &&
2491                 ((caboff + cablen) < (filelen + 32)) )
2492             {
2493               /* found a potential result - try loading it */
2494               found++;
2495               cab2 = load_cab_offset(name, (off_t) caboff);
2496               if (cab2) {
2497                 /* success */
2498                 ok++;
2499
2500                 /* cause the search to restart after this cab's data. */
2501                 offset = caboff + cablen;
2502                 if (offset < cab->filelen) cabinet_seek(cab, offset);
2503                 length = 0;
2504                 p = pend;
2505
2506                 /* link the cab into the list */
2507                 if (linkcab == NULL) firstcab = cab2;
2508                 else linkcab->next = cab2;
2509                 linkcab = cab2;
2510               }
2511             }
2512             state = 0;
2513             break;
2514           default:
2515             p++, state++; break;
2516           }
2517         }
2518       }
2519       cabinet_close(cab);
2520     }
2521     free(cab);
2522   }
2523
2524   /* if there were cabinets that were found but are not ok, point this out */
2525   if (found > ok) {
2526     fprintf(stderr, "%s: WARNING; found %d bad cabinets\n", name, found-ok);
2527   }
2528
2529   /* if no cabinets were found, let the user know */
2530   if (!firstcab) {
2531     fprintf(stderr, "%s: not a Microsoft cabinet file.\n", name);
2532   }
2533   return firstcab;
2534 }
2535
2536 /* UTF translates two-byte unicode characters into 1, 2 or 3 bytes.
2537  * %000000000xxxxxxx -> %0xxxxxxx
2538  * %00000xxxxxyyyyyy -> %110xxxxx %10yyyyyy
2539  * %xxxxyyyyyyzzzzzz -> %1110xxxx %10yyyyyy %10zzzzzz
2540  *
2541  * Therefore, the inverse is as follows:
2542  * First char:
2543  *  0x00 - 0x7F = one byte char
2544  *  0x80 - 0xBF = invalid
2545  *  0xC0 - 0xDF = 2 byte char (next char only 0x80-0xBF is valid)
2546  *  0xE0 - 0xEF = 3 byte char (next 2 chars only 0x80-0xBF is valid)
2547  *  0xF0 - 0xFF = invalid
2548  */
2549
2550 /* translate UTF -> ASCII */
2551 int convertUTF(UBYTE *in) {
2552   UBYTE c, *out = in, *end = in + strlen((char *) in) + 1;
2553   ULONG x;
2554
2555   do {
2556     /* read unicode character */
2557     if ((c = *in++) < 0x80) x = c;
2558     else {
2559       if (c < 0xC0) return 0;
2560       else if (c < 0xE0) {
2561         x = (c & 0x1F) << 6;
2562         if ((c = *in++) < 0x80 || c > 0xBF) return 0; else x |= (c & 0x3F);
2563       }
2564       else if (c < 0xF0) {
2565         x = (c & 0xF) << 12;
2566         if ((c = *in++) < 0x80 || c > 0xBF) return 0; else x |= (c & 0x3F)<<6;
2567         if ((c = *in++) < 0x80 || c > 0xBF) return 0; else x |= (c & 0x3F);
2568       }
2569       else return 0;
2570     }
2571
2572     /* terrible unicode -> ASCII conversion */
2573     if (x > 127) x = '_';
2574
2575     if (in > end) return 0; /* just in case */
2576   } while ((*out++ = (UBYTE) x));
2577   return 1;
2578 }
2579
2580 void print_fileinfo(struct file *fi) {
2581   int d = fi->date, t = fi->time;
2582   char *fname = NULL;
2583
2584   if (fi->attribs & cffile_A_NAME_IS_UTF) {
2585     fname = malloc(strlen(fi->filename) + 1);
2586     if (fname) {
2587       strcpy(fname, fi->filename);
2588       convertUTF((UBYTE *) fname);
2589     }
2590   }
2591
2592   printf("%9u | %02d.%02d.%04d %02d:%02d:%02d | %s\n",
2593     fi->length, 
2594     d & 0x1f, (d>>5) & 0xf, (d>>9) + 1980,
2595     t >> 11, (t>>5) & 0x3f, (t << 1) & 0x3e,
2596     fname ? fname : fi->filename
2597   );
2598
2599   if (fname) free(fname);
2600 }
2601
2602 int NONEdecompress(int inlen, int outlen) {
2603   if (inlen != outlen) return DECR_ILLEGALDATA;
2604   memcpy(CAB(outbuf), CAB(inbuf), (size_t) inlen);
2605   return DECR_OK;
2606 }
2607
2608 ULONG checksum(UBYTE *data, UWORD bytes, ULONG csum) {
2609   int len;
2610   ULONG ul = 0;
2611
2612   for (len = bytes >> 2; len--; data += 4) {
2613     csum ^= ((data[0]) | (data[1]<<8) | (data[2]<<16) | (data[3]<<24));
2614   }
2615
2616   switch (bytes & 3) {
2617   case 3: ul |= *data++ << 16;
2618   case 2: ul |= *data++ <<  8;
2619   case 1: ul |= *data;
2620   }
2621   csum ^= ul;
2622
2623   return csum;
2624 }
2625
2626 int decompress(struct file *fi, int savemode, int fix) {
2627   ULONG bytes = savemode ? fi->length : fi->offset - CAB(offset);
2628   struct cabinet *cab = CAB(current)->cab[CAB(split)];
2629   UBYTE buf[cfdata_SIZEOF], *data;
2630   UWORD inlen, len, outlen, cando;
2631   ULONG cksum;
2632   LONG err;
2633
2634   while (bytes > 0) {
2635     /* cando = the max number of bytes we can do */
2636     cando = CAB(outlen);
2637     if (cando > bytes) cando = bytes;
2638
2639     /* if cando != 0 */
2640     if (cando && savemode) file_write(fi, CAB(outpos), cando);
2641
2642     CAB(outpos) += cando;
2643     CAB(outlen) -= cando;
2644     bytes -= cando; if (!bytes) break;
2645
2646     /* we only get here if we emptied the output buffer */
2647
2648     /* read data header + data */
2649     inlen = outlen = 0;
2650     while (outlen == 0) {
2651       /* read the block header, skip the reserved part */
2652       if (!cabinet_read(cab, buf, cfdata_SIZEOF)) return DECR_INPUT;
2653       cabinet_skip(cab, cab->block_resv);
2654
2655       /* we shouldn't get blocks over CAB_INPUTMAX in size */
2656       data = CAB(inbuf) + inlen;
2657       len = EndGetI16(buf+cfdata_CompressedSize);
2658       inlen += len;
2659       if (inlen > CAB_INPUTMAX) return DECR_INPUT;
2660       if (!cabinet_read(cab, data, len)) return DECR_INPUT;
2661
2662       /* clear two bytes after read-in data */
2663       data[len+1] = data[len+2] = 0;
2664
2665       /* perform checksum test on the block (if one is stored) */
2666       cksum = EndGetI32(buf+cfdata_CheckSum);
2667       if (cksum && cksum != checksum(buf+4, 4, checksum(data, len, 0))) {
2668         /* checksum is wrong */
2669         if (fix && ((fi->folder->comp_type & cffoldCOMPTYPE_MASK)
2670                     == cffoldCOMPTYPE_MSZIP))
2671         {
2672           fprintf(stderr, "%s: WARNING; checksum failed\n", fi->filename); 
2673         }
2674         else {
2675           return DECR_CHECKSUM;
2676         }
2677       }
2678
2679       /* outlen=0 means this block was part of a split block */
2680       outlen = EndGetI16(buf+cfdata_UncompressedSize);
2681       if (outlen == 0) {
2682         cabinet_close(cab);
2683         cab = CAB(current)->cab[++CAB(split)];
2684         if (!cabinet_open(cab)) return DECR_INPUT;
2685         cabinet_seek(cab, CAB(current)->offset[CAB(split)]);
2686       }
2687     }
2688
2689     /* decompress block */
2690     if ((err = CAB(decompress)(inlen, outlen))) {
2691       if (fix && ((fi->folder->comp_type & cffoldCOMPTYPE_MASK)
2692                   == cffoldCOMPTYPE_MSZIP))
2693       {
2694         fprintf(stderr, "%s: WARNING; failed decrunching block\n",
2695                 fi->filename); 
2696       }
2697       else {
2698         return err;
2699       }
2700     }
2701     CAB(outlen) = outlen;
2702     CAB(outpos) = CAB(outbuf);
2703   }
2704
2705   return DECR_OK;
2706 }
2707
2708
2709 void extract_file(struct file *fi, int lower, int fix, char *dir) {
2710   struct folder *fol = fi->folder, *oldfol = CAB(current);
2711   LONG err = DECR_OK;
2712
2713   /* is a change of folder needed? do we need to reset the current folder? */
2714   if (fol != oldfol || fi->offset < CAB(offset)) {
2715     UWORD comptype = fol->comp_type;
2716     int ct1 = comptype & cffoldCOMPTYPE_MASK;
2717     int ct2 = oldfol ? (oldfol->comp_type & cffoldCOMPTYPE_MASK) : 0;
2718
2719     /* if the archiver has changed, call the old archiver's free() function */
2720     if (ct1 != ct2) {
2721       switch (ct2) {
2722       case cffoldCOMPTYPE_LZX:
2723         if (LZX(window)) {
2724           free(LZX(window));
2725           LZX(window) = NULL;
2726         }
2727         break;
2728       case cffoldCOMPTYPE_QUANTUM:
2729         if (QTM(window)) {
2730           free(QTM(window));
2731           QTM(window) = NULL;
2732         }
2733         break;
2734       }
2735     }
2736
2737     switch (ct1) {
2738     case cffoldCOMPTYPE_NONE:
2739       CAB(decompress) = NONEdecompress;
2740       break;
2741
2742     case cffoldCOMPTYPE_MSZIP:
2743       CAB(decompress) = ZIPdecompress;
2744       break;
2745
2746     case cffoldCOMPTYPE_QUANTUM:
2747       CAB(decompress) = QTMdecompress;
2748       err = QTMinit((comptype >> 8) & 0x1f, (comptype >> 4) & 0xF);
2749       break;
2750
2751     case cffoldCOMPTYPE_LZX:
2752       CAB(decompress) = LZXdecompress;
2753       err = LZXinit((comptype >> 8) & 0x1f);
2754       break;
2755
2756     default:
2757       err = DECR_DATAFORMAT;
2758     }
2759     if (err) goto exit_handler;
2760
2761     /* initialisation OK, set current folder and reset offset */
2762     if (oldfol) cabinet_close(oldfol->cab[CAB(split)]);
2763     if (!cabinet_open(fol->cab[0])) goto exit_handler;
2764     cabinet_seek(fol->cab[0], fol->offset[0]);
2765     CAB(current) = fol;
2766     CAB(offset) = 0;
2767     CAB(outlen) = 0; /* discard existing block */
2768     CAB(split)  = 0;
2769   }
2770
2771   if (fi->offset > CAB(offset)) {
2772     /* decode bytes and send them to /dev/null */
2773     if ((err = decompress(fi, 0, fix))) goto exit_handler;
2774     CAB(offset) = fi->offset;
2775   }
2776   if (!file_open(fi, lower, dir)) return;
2777   err = decompress(fi, 1, fix);
2778   if (err) CAB(current) = NULL; else CAB(offset) += fi->length;
2779   file_close(fi);
2780
2781 exit_handler:
2782   if (err) {
2783     char *errmsg, *cabname;
2784     switch (err) {
2785     case DECR_NOMEMORY:
2786       errmsg = "out of memory!\n"; break;
2787     case DECR_ILLEGALDATA:
2788       errmsg = "%s: illegal or corrupt data\n"; break;
2789     case DECR_DATAFORMAT:
2790       errmsg = "%s: unsupported data format\n"; break;
2791     case DECR_CHECKSUM:
2792       errmsg = "%s: checksum error\n"; break;
2793     case DECR_INPUT:
2794       errmsg = "%s: input error\n"; break;
2795     case DECR_OUTPUT:
2796       errmsg = "%s: output error\n"; break;
2797     default:
2798       errmsg = "%s: unknown error (BUG)\n";
2799     }
2800
2801     if (CAB(current)) {
2802       cabname = CAB(current)->cab[CAB(split)]->filename;
2803     }
2804     else {
2805       cabname = fi->folder->cab[0]->filename;
2806     }
2807
2808     fprintf(stderr, errmsg, cabname);
2809   }
2810 }
2811
2812 /* tries to find *cabname, from the directory path of origcab, correcting the
2813  * case of *cabname if necessary, If found, writes back to *cabname.
2814  */
2815 void find_cabinet_file(char **cabname, char *origcab) {
2816   char *tail, *cab, *name, *nextpart;
2817   struct dirent *entry;
2818   struct stat st_buf;
2819   int found = 0, len;
2820   DIR *dir;
2821
2822   /* ensure we have a cabinet name at all */
2823   if (!(name = *cabname)) return;
2824
2825   /* find if there's a directory path in the origcab */
2826   tail = origcab ? strrchr(origcab, '/') : NULL;
2827
2828   if ((cab = (char *) malloc((tail ? tail-origcab : 1) + strlen(name) + 2))) {
2829     /* add the directory path from the original cabinet name */
2830     if (tail) {
2831       memcpy(cab, origcab, tail-origcab);
2832       cab[tail-origcab] = '\0';
2833     }
2834     else {
2835       /* default directory path of '.' */
2836       cab[0] = '.';
2837       cab[1] = '\0';
2838     }
2839
2840     do {
2841       /* we don't want null cabinet filenames */
2842       if (name[0] == '\0') break;
2843
2844       /* if there is a directory component in the cabinet name,
2845        * look for that alone first
2846        */
2847       nextpart = strchr(name, '\\');
2848       if (nextpart) *nextpart = '\0';
2849
2850       /* try accessing the component with its current name (case-sensitive) */
2851       len = strlen(cab); strcat(cab, "/"); strcat(cab, name);
2852       found = (stat(cab, &st_buf) == 0) && 
2853         nextpart ? S_ISDIR(st_buf.st_mode) : S_ISREG(st_buf.st_mode);
2854
2855       /* if the component was not found, look for it in the current dir */
2856       if (!found) {
2857         cab[len] = '\0';
2858         if ((dir = opendir(cab))) {
2859           while ((entry = readdir(dir))) {
2860             if (strcasecmp(name, entry->d_name) == 0) {
2861               strcat(cab, "/"); strcat(cab, entry->d_name); found = 1;
2862             }
2863           }
2864           closedir(dir);
2865         }
2866       }
2867       
2868       /* restore the real name and skip to the next directory component
2869        * or actual cabinet name
2870        */
2871       if (nextpart) *nextpart = '\\', name = &nextpart[1];
2872
2873       /* while there is another directory component, and while we
2874        * successfully found the current component
2875        */
2876     } while (nextpart && found);
2877
2878
2879     /* if we found the cabinet, change the next cabinet's name.
2880      * otherwise, pretend nothing happened
2881      */
2882     if (found) {
2883       free((void *) *cabname);
2884       *cabname = cab;
2885     }
2886     else {
2887       free((void *) cab);
2888     }
2889   }
2890 }
2891
2892 /* process_cabinet() is called by main() for every file listed on the
2893  * command line. It will find every cabinet file in that file, and will
2894  * search for every chained cabinet attached to those cabinets, then it
2895  * will either extract or list the cabinet(s). Returns 0 for success or 1
2896  * for failure (unlike most cabextract functions).
2897  */
2898 int process_cabinet(char *cabname, char *dir,
2899                     int fix, int view, int lower, int quiet) {
2900  
2901   struct cabinet *basecab, *cab, *cab1, *cab2;
2902   struct file *filelist, *fi;
2903
2904   /* has the list-mode header been seen before? */
2905   int viewhdr = 0;
2906
2907   if (view || !quiet) {
2908     printf("%s cabinet: %s\n", view ? "Viewing" : "Extracting", cabname);
2909   }
2910
2911   /* load the file requested */
2912   basecab = find_cabs_in_file(cabname);
2913   if (!basecab) return 1;
2914
2915   /* iterate over all cabinets found in that file */
2916   for (cab = basecab; cab; cab=cab->next) {
2917
2918     /* bi-directionally load any spanning cabinets -- backwards */
2919     for (cab1 = cab; cab1->flags & cfheadPREV_CABINET; cab1 = cab1->prevcab) {
2920       if (!quiet) printf("%s: extends backwards to %s (%s)\n", cabname,
2921                          cab1->prevname, cab1->previnfo);
2922       find_cabinet_file(&(cab1->prevname), cabname);
2923       if (!(cab1->prevcab = load_cab_offset(cab1->prevname, 0))) {
2924         fprintf(stderr, "%s: can't read previous cabinet %s\n",
2925                 cabname, cab1->prevname);
2926         break;
2927       }
2928       cab1->prevcab->nextcab = cab1;
2929     }
2930
2931     /* bi-directionally load any spanning cabinets -- forwards */
2932     for (cab2 = cab; cab2->flags & cfheadNEXT_CABINET; cab2 = cab2->nextcab) {
2933       if (!quiet) printf("%s: extends to %s (%s)\n", cabname,
2934                          cab2->nextname, cab2->nextinfo);
2935       find_cabinet_file(&(cab2->nextname), cabname);
2936       if (!(cab2->nextcab = load_cab_offset(cab2->nextname, 0))) {
2937         fprintf(stderr, "%s: can't read next cabinet %s\n",
2938                 cabname, cab2->nextname);
2939         break;
2940       }
2941       cab2->nextcab->prevcab = cab2;
2942     }
2943
2944     filelist = process_files(cab1);
2945     CAB(current) = NULL;
2946
2947     if (view && !viewhdr) {
2948       printf("File size | Date       Time     | Name\n");
2949       printf("----------+---------------------+-------------\n");
2950       viewhdr = 1;
2951     }
2952     for (fi = filelist; fi; fi = fi->next) {
2953       if (view) {
2954         print_fileinfo(fi);
2955       }
2956       else {
2957         if (!quiet) printf("  extracting: %s\n", fi->filename);
2958         extract_file(fi, lower, fix, dir);
2959       }
2960     }
2961   }
2962
2963   if (view) printf("\n");
2964   else if (!quiet) printf("Finished processing cabinet.\n\n");
2965   return 0;
2966 }
2967
2968
2969 struct option opts[] = {
2970   { "version",   0, NULL, 'v' },
2971   { "help",      0, NULL, 'h' },
2972   { "list",      0, NULL, 'l' },
2973   { "quiet",     0, NULL, 'q' },
2974   { "lowercase", 0, NULL, 'L' },
2975   { "fix",       0, NULL, 'f' },
2976   { "directory", 1, NULL, 'd' },
2977   { NULL,        0, NULL, 0   }
2978 };
2979
2980 int main(int argc, char *argv[]) {
2981   int help=0, list=0, lower=0, view=0, quiet=0, fix=0, x, err=0;
2982   char *dir = NULL;
2983   while ((x = getopt_long(argc, argv, "vhlqLfd:", opts, NULL)) != -1) {
2984     switch (x) {
2985     case 'v': view  = 1;      break;
2986     case 'h': help  = 1;      break;
2987     case 'l': list  = 1;      break;
2988     case 'q': quiet = 1;      break;
2989     case 'L': lower = 1;      break;
2990     case 'f': fix   = 1;      break;
2991     case 'd': dir   = optarg; break;
2992     }
2993   }
2994
2995   if (help) {
2996     fprintf(stderr,
2997       "Usage: %s [options] [-d dir] <cabinet file(s)>\n\n"
2998       "This will extract all files from a cabinet or executable cabinet.\n"
2999       "For multi-part cabinets, only specify the first file in the set.\n\n"
3000       "Options:\n"
3001       "  -v   --version     print version / list cabinet\n"
3002       "  -h   --help        show this help page\n"
3003       "  -l   --list        list contents of cabinet\n"
3004       "  -q   --quiet       only print errors and warnings\n"
3005       "  -L   --lowercase   make filenames lowercase\n"
3006       "  -f   --fix         fix (some) corrupted cabinets\n"
3007       "  -d   --directory   extract all files to the given directory\n\n"
3008       "cabextract %s (C) 2000-2002 Stuart Caie <kyzer@4u.net>\n"
3009       "This is free software with ABSOLUTELY NO WARRANTY.\n",
3010       argv[0], VERSION
3011     );
3012     return 1;
3013   }
3014
3015   if (optind == argc) {
3016     /* no arguments other than the options */
3017     if (view) {
3018       printf("cabextract version %s\n", VERSION);
3019       return 0;
3020     }
3021     else {
3022       fprintf(stderr, "cabextract: No cabinet files specified.\n"
3023                       "Try '%s --help' for more information.\n", argv[0]);
3024       return 1;
3025     }
3026   }
3027
3028   while (optind != argc) {
3029     err |= process_cabinet(argv[optind++], dir, fix, view||list, lower, quiet);
3030   }
3031
3032   return err;
3033 }