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