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