If using the default values, also set dwType to REG_SZ as our default
[wine] / dlls / cabinet / cabextract.c
1 /*
2  * cabextract.c
3  *
4  * Copyright 2000-2002 Stuart Caie
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library 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 GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * Principal author: Stuart Caie <kyzer@4u.net>
21  *
22  * Based on specification documents from Microsoft Corporation
23  * Quantum decompression researched and implemented by Matthew Russoto
24  * Huffman code adapted from unlzx by Dave Tritscher.
25  * InfoZip team's INFLATE implementation adapted to MSZIP by Dirk Stoecker.
26  * Major LZX fixes by Jae Jung.
27  */
28  
29 #include "config.h"
30
31 #include <stdarg.h>
32 #include <stdlib.h>
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winerror.h"
37
38 #include "cabinet.h"
39
40 #include "wine/debug.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(cabinet);
43
44 THOSE_ZIP_CONSTS;
45
46 /* all the file IO is abstracted into these routines:
47  * cabinet_(open|close|read|seek|skip|getoffset)
48  * file_(open|close|write)
49  */
50
51 /* try to open a cabinet file, returns success */
52 BOOL cabinet_open(struct cabinet *cab)
53 {
54   char *name = (char *)cab->filename;
55   HANDLE fh;
56
57   TRACE("(cab == ^%p)\n", cab);
58
59   if ((fh = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
60               NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL )) == INVALID_HANDLE_VALUE) {
61     ERR("Couldn't open %s\n", debugstr_a(name));
62     return FALSE;
63   }
64
65   /* seek to end of file and get the length */
66   if ((cab->filelen = SetFilePointer(fh, 0, NULL, FILE_END)) == INVALID_SET_FILE_POINTER) {
67     if (GetLastError() != NO_ERROR) {
68       ERR("Seek END failed: %s", debugstr_a(name));
69       CloseHandle(fh);
70       return FALSE;
71     }
72   }
73
74   /* return to the start of the file */
75   if (SetFilePointer(fh, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
76     ERR("Seek BEGIN failed: %s", debugstr_a(name));
77     CloseHandle(fh);
78     return FALSE;
79   }
80
81   cab->fh = fh;
82   return TRUE;
83 }
84
85 /*******************************************************************
86  * cabinet_close (internal)
87  *
88  * close the file handle in a struct cabinet.
89  */
90 void cabinet_close(struct cabinet *cab) {
91   TRACE("(cab == ^%p)\n", cab);
92   if (cab->fh) CloseHandle(cab->fh);
93   cab->fh = 0;
94 }
95
96 /*******************************************************
97  * ensure_filepath2 (internal)
98  */
99 BOOL ensure_filepath2(char *path) {
100   BOOL ret = TRUE;
101   int len;
102   char *new_path;
103
104   new_path = HeapAlloc(GetProcessHeap(), 0, (strlen(path) + 1));
105   strcpy(new_path, path);
106
107   while((len = strlen(new_path)) && new_path[len - 1] == '\\')
108     new_path[len - 1] = 0;
109
110   TRACE("About to try to create directory %s\n", debugstr_a(new_path));
111   while(!CreateDirectoryA(new_path, NULL)) {
112     char *slash;
113     DWORD last_error = GetLastError();
114
115     if(last_error == ERROR_ALREADY_EXISTS)
116       break;
117
118     if(last_error != ERROR_PATH_NOT_FOUND) {
119       ret = FALSE;
120       break;
121     }
122
123     if(!(slash = strrchr(new_path, '\\'))) {
124       ret = FALSE;
125       break;
126     }
127
128     len = slash - new_path;
129     new_path[len] = 0;
130     if(! ensure_filepath2(new_path)) {
131       ret = FALSE;
132       break;
133     }
134     new_path[len] = '\\';
135     TRACE("New path in next iteration: %s\n", debugstr_a(new_path));
136   }
137
138   HeapFree(GetProcessHeap(), 0, new_path);
139   return ret;
140 }
141
142
143 /**********************************************************************
144  * ensure_filepath (internal)
145  *
146  * ensure_filepath("a\b\c\d.txt") ensures a, a\b and a\b\c exist as dirs
147  */
148 BOOL ensure_filepath(char *path) {
149   char new_path[MAX_PATH];
150   int len, i, lastslashpos = -1;
151
152   TRACE("(path == %s)\n", debugstr_a(path));
153
154   strcpy(new_path, path); 
155   /* remove trailing slashes (shouldn't need to but wth...) */
156   while ((len = strlen(new_path)) && new_path[len - 1] == '\\')
157     new_path[len - 1] = 0;
158   /* find the position of the last '\\' */
159   for (i=0; i<MAX_PATH; i++) {
160     if (new_path[i] == 0) break; 
161     if (new_path[i] == '\\')
162       lastslashpos = i;
163   }
164   if (lastslashpos > 0) {
165     new_path[lastslashpos] = 0;
166     /* may be trailing slashes but ensure_filepath2 will chop them */
167     return ensure_filepath2(new_path);
168   } else
169     return TRUE; /* ? */
170 }
171
172 /*******************************************************************
173  * file_open (internal)
174  *
175  * opens a file for output, returns success
176  */
177 BOOL file_open(struct cab_file *fi, BOOL lower, LPCSTR dir)
178 {
179   char c, *s, *d, *name;
180   BOOL ok = FALSE;
181
182   TRACE("(fi == ^%p, lower == %s, dir == %s)\n", fi, lower ? "TRUE" : "FALSE", debugstr_a(dir));
183
184   if (!(name = malloc(strlen(fi->filename) + (dir ? strlen(dir) : 0) + 2))) {
185     ERR("out of memory!\n");
186     return FALSE;
187   }
188   
189   /* start with blank name */
190   *name = 0;
191
192   /* add output directory if needed */
193   if (dir) {
194     strcpy(name, dir);
195     strcat(name, "\\");
196   }
197
198   /* remove leading slashes */
199   s = (char *) fi->filename;
200   while (*s == '\\') s++;
201
202   /* copy from fi->filename to new name.
203    * lowercases characters if needed.
204    */
205   d = &name[strlen(name)];
206   do {
207     c = *s++;
208     *d++ = (lower ? tolower((unsigned char) c) : c);
209   } while (c);
210
211   /* create directories if needed, attempt to write file */
212   if (ensure_filepath(name)) {
213     fi->fh = CreateFileA(name, GENERIC_WRITE, 0, NULL,
214                          CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
215     if (fi->fh != INVALID_HANDLE_VALUE)
216       ok = TRUE;
217     else {
218       ERR("CreateFileA returned INVALID_HANDLE_VALUE\n");
219       fi->fh = 0;
220     }
221   } else 
222     ERR("Couldn't ensure filepath for %s", debugstr_a(name));
223
224   if (!ok) {
225     ERR("Couldn't open file %s for writing\n", debugstr_a(name));
226   }
227
228   /* as full filename is no longer needed, free it */
229   free(name);
230
231   return ok;
232 }
233
234 /********************************************************
235  * close_file (internal)
236  *
237  * closes a completed file
238  */
239 void file_close(struct cab_file *fi)
240 {
241   TRACE("(fi == ^%p)\n", fi);
242
243   if (fi->fh) {
244     CloseHandle(fi->fh);
245   }
246   fi->fh = 0;
247 }
248
249 /******************************************************************
250  * file_write (internal)
251  *
252  * writes from buf to a file specified as a cab_file struct.
253  * returns success/failure
254  */
255 BOOL file_write(struct cab_file *fi, cab_UBYTE *buf, cab_off_t length)
256 {
257   DWORD bytes_written;
258
259   TRACE("(fi == ^%p, buf == ^%p, length == %u)\n", fi, buf, length);
260
261   if ((!WriteFile( fi->fh, (LPCVOID) buf, length, &bytes_written, FALSE) ||
262       (bytes_written != length))) {
263     ERR("Error writing file: %s\n", debugstr_a(fi->filename));
264     return FALSE;
265   }
266   return TRUE;
267 }
268
269
270 /*******************************************************************
271  * cabinet_skip (internal)
272  *
273  * advance the file pointer associated with the cab structure
274  * by distance bytes
275  */
276 void cabinet_skip(struct cabinet *cab, cab_off_t distance)
277 {
278   TRACE("(cab == ^%p, distance == %u)\n", cab, distance);
279   if (SetFilePointer(cab->fh, distance, NULL, FILE_CURRENT) == INVALID_SET_FILE_POINTER) {
280     if (distance != INVALID_SET_FILE_POINTER)
281       ERR("%s", debugstr_a((char *) cab->filename));
282   }
283 }
284
285 /*******************************************************************
286  * cabinet_seek (internal)
287  *
288  * seek to the specified absolute offset in a cab
289  */
290 void cabinet_seek(struct cabinet *cab, cab_off_t offset) {
291   TRACE("(cab == ^%p, offset == %u)\n", cab, offset);
292   if (SetFilePointer(cab->fh, offset, NULL, FILE_BEGIN) != offset)
293     ERR("%s seek failure\n", debugstr_a((char *)cab->filename));
294 }
295
296 /*******************************************************************
297  * cabinet_getoffset (internal)
298  *
299  * returns the file pointer position of a cab
300  */
301 cab_off_t cabinet_getoffset(struct cabinet *cab) 
302 {
303   return SetFilePointer(cab->fh, 0, NULL, FILE_CURRENT);
304 }
305
306 /*******************************************************************
307  * cabinet_read (internal)
308  *
309  * read data from a cabinet, returns success
310  */
311 BOOL cabinet_read(struct cabinet *cab, cab_UBYTE *buf, cab_off_t length)
312 {
313   DWORD bytes_read;
314   cab_off_t avail = cab->filelen - cabinet_getoffset(cab);
315
316   TRACE("(cab == ^%p, buf == ^%p, length == %u)\n", cab, buf, length);
317
318   if (length > avail) {
319     WARN("%s: WARNING; cabinet is truncated\n", debugstr_a((char *)cab->filename));
320     length = avail;
321   }
322
323   if (! ReadFile( cab->fh, (LPVOID) buf, length, &bytes_read, NULL )) {
324     ERR("%s read error\n", debugstr_a((char *) cab->filename));
325     return FALSE;
326   } else if (bytes_read != length) {
327     ERR("%s read size mismatch\n", debugstr_a((char *) cab->filename));
328     return FALSE;
329   }
330
331   return TRUE;
332 }
333
334 /**********************************************************************
335  * cabinet_read_string (internal)
336  *
337  * allocate and read an aribitrarily long string from the cabinet
338  */
339 char *cabinet_read_string(struct cabinet *cab)
340 {
341   cab_off_t len=256, base = cabinet_getoffset(cab), maxlen = cab->filelen - base;
342   BOOL ok = FALSE;
343   int i;
344   cab_UBYTE *buf = NULL;
345
346   TRACE("(cab == ^%p)\n", cab);
347
348   do {
349     if (len > maxlen) len = maxlen;
350     if (!(buf = realloc(buf, (size_t) len))) break;
351     if (!cabinet_read(cab, buf, (size_t) len)) break;
352
353     /* search for a null terminator in what we've just read */
354     for (i=0; i < len; i++) {
355       if (!buf[i]) {ok=TRUE; break;}
356     }
357
358     if (!ok) {
359       if (len == maxlen) {
360         ERR("%s: WARNING; cabinet is truncated\n", debugstr_a((char *) cab->filename));
361         break;
362       }
363       len += 256;
364       cabinet_seek(cab, base);
365     }
366   } while (!ok);
367
368   if (!ok) {
369     if (buf)
370       free(buf);
371     else
372       ERR("out of memory!\n");
373     return NULL;
374   }
375
376   /* otherwise, set the stream to just after the string and return */
377   cabinet_seek(cab, base + ((cab_off_t) strlen((char *) buf)) + 1);
378
379   return (char *) buf;
380 }
381
382 /******************************************************************
383  * cabinet_read_entries (internal)
384  *
385  * reads the header and all folder and file entries in this cabinet
386  */
387 BOOL cabinet_read_entries(struct cabinet *cab)
388 {
389   int num_folders, num_files, header_resv, folder_resv = 0, i;
390   struct cab_folder *fol, *linkfol = NULL;
391   struct cab_file *file, *linkfile = NULL;
392   cab_off_t base_offset;
393   cab_UBYTE buf[64];
394
395   TRACE("(cab == ^%p)\n", cab);
396
397   /* read in the CFHEADER */
398   base_offset = cabinet_getoffset(cab);
399   if (!cabinet_read(cab, buf, cfhead_SIZEOF)) {
400     return FALSE;
401   }
402   
403   /* check basic MSCF signature */
404   if (EndGetI32(buf+cfhead_Signature) != 0x4643534d) {
405     ERR("%s: not a Microsoft cabinet file\n", debugstr_a((char *) cab->filename));
406     return FALSE;
407   }
408
409   /* get the number of folders */
410   num_folders = EndGetI16(buf+cfhead_NumFolders);
411   if (num_folders == 0) {
412     ERR("%s: no folders in cabinet\n", debugstr_a((char *) cab->filename));
413     return FALSE;
414   }
415
416   /* get the number of files */
417   num_files = EndGetI16(buf+cfhead_NumFiles);
418   if (num_files == 0) {
419     ERR("%s: no files in cabinet\n", debugstr_a((char *) cab->filename));
420     return FALSE;
421   }
422
423   /* just check the header revision */
424   if ((buf[cfhead_MajorVersion] > 1) ||
425       (buf[cfhead_MajorVersion] == 1 && buf[cfhead_MinorVersion] > 3))
426   {
427     WARN("%s: WARNING; cabinet format version > 1.3\n", debugstr_a((char *) cab->filename));
428   }
429
430   /* read the reserved-sizes part of header, if present */
431   cab->flags = EndGetI16(buf+cfhead_Flags);
432   if (cab->flags & cfheadRESERVE_PRESENT) {
433     if (!cabinet_read(cab, buf, cfheadext_SIZEOF)) return FALSE;
434     header_resv     = EndGetI16(buf+cfheadext_HeaderReserved);
435     folder_resv     = buf[cfheadext_FolderReserved];
436     cab->block_resv = buf[cfheadext_DataReserved];
437
438     if (header_resv > 60000) {
439       WARN("%s: WARNING; header reserved space > 60000\n", debugstr_a((char *) cab->filename));
440     }
441
442     /* skip the reserved header */
443     if (header_resv) 
444       if (SetFilePointer(cab->fh, (cab_off_t) header_resv, NULL, FILE_CURRENT) == INVALID_SET_FILE_POINTER)
445         ERR("seek failure: %s\n", debugstr_a((char *) cab->filename));
446   }
447
448   if (cab->flags & cfheadPREV_CABINET) {
449     cab->prevname = cabinet_read_string(cab);
450     if (!cab->prevname) return FALSE;
451     cab->previnfo = cabinet_read_string(cab);
452   }
453
454   if (cab->flags & cfheadNEXT_CABINET) {
455     cab->nextname = cabinet_read_string(cab);
456     if (!cab->nextname) return FALSE;
457     cab->nextinfo = cabinet_read_string(cab);
458   }
459
460   /* read folders */
461   for (i = 0; i < num_folders; i++) {
462     if (!cabinet_read(cab, buf, cffold_SIZEOF)) return FALSE;
463     if (folder_resv) cabinet_skip(cab, folder_resv);
464
465     fol = (struct cab_folder *) calloc(1, sizeof(struct cab_folder));
466     if (!fol) {
467       ERR("out of memory!\n");
468       return FALSE;
469     }
470
471     fol->cab[0]     = cab;
472     fol->offset[0]  = base_offset + (cab_off_t) EndGetI32(buf+cffold_DataOffset);
473     fol->num_blocks = EndGetI16(buf+cffold_NumBlocks);
474     fol->comp_type  = EndGetI16(buf+cffold_CompType);
475
476     if (!linkfol) 
477       cab->folders = fol; 
478     else 
479       linkfol->next = fol;
480
481     linkfol = fol;
482   }
483
484   /* read files */
485   for (i = 0; i < num_files; i++) {
486     if (!cabinet_read(cab, buf, cffile_SIZEOF))
487       return FALSE;
488
489     file = (struct cab_file *) calloc(1, sizeof(struct cab_file));
490     if (!file) { 
491       ERR("out of memory!\n"); 
492       return FALSE;
493     }
494       
495     file->length   = EndGetI32(buf+cffile_UncompressedSize);
496     file->offset   = EndGetI32(buf+cffile_FolderOffset);
497     file->index    = EndGetI16(buf+cffile_FolderIndex);
498     file->time     = EndGetI16(buf+cffile_Time);
499     file->date     = EndGetI16(buf+cffile_Date);
500     file->attribs  = EndGetI16(buf+cffile_Attribs);
501     file->filename = cabinet_read_string(cab);
502
503     if (!file->filename) {
504       free(file);
505       return FALSE;
506     }
507
508     if (!linkfile) 
509       cab->files = file;
510     else 
511       linkfile->next = file;
512
513     linkfile = file;
514   }
515   return TRUE;
516 }
517
518 /***********************************************************
519  * load_cab_offset (internal)
520  *
521  * validates and reads file entries from a cabinet at offset [offset] in
522  * file [name]. Returns a cabinet structure if successful, or NULL
523  * otherwise.
524  */
525 struct cabinet *load_cab_offset(LPCSTR name, cab_off_t offset)
526 {
527   struct cabinet *cab = (struct cabinet *) calloc(1, sizeof(struct cabinet));
528   int ok;
529
530   TRACE("(name == %s, offset == %u)\n", debugstr_a((char *) name), offset);
531
532   if (!cab) return NULL;
533
534   cab->filename = name;
535   if ((ok = cabinet_open(cab))) {
536     cabinet_seek(cab, offset);
537     ok = cabinet_read_entries(cab);
538     cabinet_close(cab);
539   }
540
541   if (ok) return cab;
542   free(cab);
543   return NULL;
544 }
545
546 /* MSZIP decruncher */
547
548 /* Dirk Stoecker wrote the ZIP decoder, based on the InfoZip deflate code */
549
550 /********************************************************
551  * Ziphuft_free (internal)
552  */
553 void Ziphuft_free(struct Ziphuft *t)
554 {
555   register struct Ziphuft *p, *q;
556
557   /* Go through linked list, freeing from the allocated (t[-1]) address. */
558   p = t;
559   while (p != (struct Ziphuft *)NULL)
560   {
561     q = (--p)->v.t;
562     free(p);
563     p = q;
564   } 
565 }
566
567 /*********************************************************
568  * Ziphuft_build (internal)
569  */
570 cab_LONG Ziphuft_build(cab_ULONG *b, cab_ULONG n, cab_ULONG s, cab_UWORD *d, cab_UWORD *e,
571 struct Ziphuft **t, cab_LONG *m, cab_decomp_state *decomp_state)
572 {
573   cab_ULONG a;                          /* counter for codes of length k */
574   cab_ULONG el;                         /* length of EOB code (value 256) */
575   cab_ULONG f;                          /* i repeats in table every f entries */
576   cab_LONG g;                           /* maximum code length */
577   cab_LONG h;                           /* table level */
578   register cab_ULONG i;                 /* counter, current code */
579   register cab_ULONG j;                 /* counter */
580   register cab_LONG k;                  /* number of bits in current code */
581   cab_LONG *l;                          /* stack of bits per table */
582   register cab_ULONG *p;                /* pointer into ZIP(c)[],ZIP(b)[],ZIP(v)[] */
583   register struct Ziphuft *q;           /* points to current table */
584   struct Ziphuft r;                     /* table entry for structure assignment */
585   register cab_LONG w;                  /* bits before this table == (l * h) */
586   cab_ULONG *xp;                        /* pointer into x */
587   cab_LONG y;                           /* number of dummy codes added */
588   cab_ULONG z;                          /* number of entries in current table */
589
590   l = ZIP(lx)+1;
591
592   /* Generate counts for each bit length */
593   el = n > 256 ? b[256] : ZIPBMAX; /* set length of EOB code, if any */
594
595   for(i = 0; i < ZIPBMAX+1; ++i)
596     ZIP(c)[i] = 0;
597   p = b;  i = n;
598   do
599   {
600     ZIP(c)[*p]++; p++;               /* assume all entries <= ZIPBMAX */
601   } while (--i);
602   if (ZIP(c)[0] == n)                /* null input--all zero length codes */
603   {
604     *t = (struct Ziphuft *)NULL;
605     *m = 0;
606     return 0;
607   }
608
609   /* Find minimum and maximum length, bound *m by those */
610   for (j = 1; j <= ZIPBMAX; j++)
611     if (ZIP(c)[j])
612       break;
613   k = j;                        /* minimum code length */
614   if ((cab_ULONG)*m < j)
615     *m = j;
616   for (i = ZIPBMAX; i; i--)
617     if (ZIP(c)[i])
618       break;
619   g = i;                        /* maximum code length */
620   if ((cab_ULONG)*m > i)
621     *m = i;
622
623   /* Adjust last length count to fill out codes, if needed */
624   for (y = 1 << j; j < i; j++, y <<= 1)
625     if ((y -= ZIP(c)[j]) < 0)
626       return 2;                 /* bad input: more codes than bits */
627   if ((y -= ZIP(c)[i]) < 0)
628     return 2;
629   ZIP(c)[i] += y;
630
631   /* Generate starting offsets LONGo the value table for each length */
632   ZIP(x)[1] = j = 0;
633   p = ZIP(c) + 1;  xp = ZIP(x) + 2;
634   while (--i)
635   {                 /* note that i == g from above */
636     *xp++ = (j += *p++);
637   }
638
639   /* Make a table of values in order of bit lengths */
640   p = b;  i = 0;
641   do{
642     if ((j = *p++) != 0)
643       ZIP(v)[ZIP(x)[j]++] = i;
644   } while (++i < n);
645
646
647   /* Generate the Huffman codes and for each, make the table entries */
648   ZIP(x)[0] = i = 0;                 /* first Huffman code is zero */
649   p = ZIP(v);                        /* grab values in bit order */
650   h = -1;                       /* no tables yet--level -1 */
651   w = l[-1] = 0;                /* no bits decoded yet */
652   ZIP(u)[0] = (struct Ziphuft *)NULL;   /* just to keep compilers happy */
653   q = (struct Ziphuft *)NULL;      /* ditto */
654   z = 0;                        /* ditto */
655
656   /* go through the bit lengths (k already is bits in shortest code) */
657   for (; k <= g; k++)
658   {
659     a = ZIP(c)[k];
660     while (a--)
661     {
662       /* here i is the Huffman code of length k bits for value *p */
663       /* make tables up to required level */
664       while (k > w + l[h])
665       {
666         w += l[h++];            /* add bits already decoded */
667
668         /* compute minimum size table less than or equal to *m bits */
669         z = (z = g - w) > (cab_ULONG)*m ? *m : z;        /* upper limit */
670         if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
671         {                       /* too few codes for k-w bit table */
672           f -= a + 1;           /* deduct codes from patterns left */
673           xp = ZIP(c) + k;
674           while (++j < z)       /* try smaller tables up to z bits */
675           {
676             if ((f <<= 1) <= *++xp)
677               break;            /* enough codes to use up j bits */
678             f -= *xp;           /* else deduct codes from patterns */
679           }
680         }
681         if ((cab_ULONG)w + j > el && (cab_ULONG)w < el)
682           j = el - w;           /* make EOB code end at table */
683         z = 1 << j;             /* table entries for j-bit table */
684         l[h] = j;               /* set table size in stack */
685
686         /* allocate and link in new table */
687         if (!(q = (struct Ziphuft *) malloc((z + 1)*sizeof(struct Ziphuft))))
688         {
689           if(h)
690             Ziphuft_free(ZIP(u)[0]);
691           return 3;             /* not enough memory */
692         }
693         *t = q + 1;             /* link to list for Ziphuft_free() */
694         *(t = &(q->v.t)) = (struct Ziphuft *)NULL;
695         ZIP(u)[h] = ++q;             /* table starts after link */
696
697         /* connect to last table, if there is one */
698         if (h)
699         {
700           ZIP(x)[h] = i;              /* save pattern for backing up */
701           r.b = (cab_UBYTE)l[h-1];    /* bits to dump before this table */
702           r.e = (cab_UBYTE)(16 + j);  /* bits in this table */
703           r.v.t = q;                  /* pointer to this table */
704           j = (i & ((1 << w) - 1)) >> (w - l[h-1]);
705           ZIP(u)[h-1][j] = r;        /* connect to last table */
706         }
707       }
708
709       /* set up table entry in r */
710       r.b = (cab_UBYTE)(k - w);
711       if (p >= ZIP(v) + n)
712         r.e = 99;               /* out of values--invalid code */
713       else if (*p < s)
714       {
715         r.e = (cab_UBYTE)(*p < 256 ? 16 : 15);    /* 256 is end-of-block code */
716         r.v.n = *p++;           /* simple code is just the value */
717       }
718       else
719       {
720         r.e = (cab_UBYTE)e[*p - s];   /* non-simple--look up in lists */
721         r.v.n = d[*p++ - s];
722       }
723
724       /* fill code-like entries with r */
725       f = 1 << (k - w);
726       for (j = i >> w; j < z; j += f)
727         q[j] = r;
728
729       /* backwards increment the k-bit code i */
730       for (j = 1 << (k - 1); i & j; j >>= 1)
731         i ^= j;
732       i ^= j;
733
734       /* backup over finished tables */
735       while ((i & ((1 << w) - 1)) != ZIP(x)[h])
736         w -= l[--h];            /* don't need to update q */
737     }
738   }
739
740   /* return actual size of base table */
741   *m = l[0];
742
743   /* Return true (1) if we were given an incomplete table */
744   return y != 0 && g != 1;
745 }
746
747 /*********************************************************
748  * Zipinflate_codes (internal)
749  */
750 cab_LONG Zipinflate_codes(struct Ziphuft *tl, struct Ziphuft *td,
751   cab_LONG bl, cab_LONG bd, cab_decomp_state *decomp_state)
752 {
753   register cab_ULONG e;  /* table entry flag/number of extra bits */
754   cab_ULONG n, d;        /* length and index for copy */
755   cab_ULONG w;           /* current window position */
756   struct Ziphuft *t;     /* pointer to table entry */
757   cab_ULONG ml, md;      /* masks for bl and bd bits */
758   register cab_ULONG b;  /* bit buffer */
759   register cab_ULONG k;  /* number of bits in bit buffer */
760
761   /* make local copies of globals */
762   b = ZIP(bb);                       /* initialize bit buffer */
763   k = ZIP(bk);
764   w = ZIP(window_posn);                       /* initialize window position */
765
766   /* inflate the coded data */
767   ml = Zipmask[bl];             /* precompute masks for speed */
768   md = Zipmask[bd];
769
770   for(;;)
771   {
772     ZIPNEEDBITS((cab_ULONG)bl)
773     if((e = (t = tl + ((cab_ULONG)b & ml))->e) > 16)
774       do
775       {
776         if (e == 99)
777           return 1;
778         ZIPDUMPBITS(t->b)
779         e -= 16;
780         ZIPNEEDBITS(e)
781       } while ((e = (t = t->v.t + ((cab_ULONG)b & Zipmask[e]))->e) > 16);
782     ZIPDUMPBITS(t->b)
783     if (e == 16)                /* then it's a literal */
784       CAB(outbuf)[w++] = (cab_UBYTE)t->v.n;
785     else                        /* it's an EOB or a length */
786     {
787       /* exit if end of block */
788       if(e == 15)
789         break;
790
791       /* get length of block to copy */
792       ZIPNEEDBITS(e)
793       n = t->v.n + ((cab_ULONG)b & Zipmask[e]);
794       ZIPDUMPBITS(e);
795
796       /* decode distance of block to copy */
797       ZIPNEEDBITS((cab_ULONG)bd)
798       if ((e = (t = td + ((cab_ULONG)b & md))->e) > 16)
799         do {
800           if (e == 99)
801             return 1;
802           ZIPDUMPBITS(t->b)
803           e -= 16;
804           ZIPNEEDBITS(e)
805         } while ((e = (t = t->v.t + ((cab_ULONG)b & Zipmask[e]))->e) > 16);
806       ZIPDUMPBITS(t->b)
807       ZIPNEEDBITS(e)
808       d = w - t->v.n - ((cab_ULONG)b & Zipmask[e]);
809       ZIPDUMPBITS(e)
810       do
811       {
812         n -= (e = (e = ZIPWSIZE - ((d &= ZIPWSIZE-1) > w ? d : w)) > n ?n:e);
813         do
814         {
815           CAB(outbuf)[w++] = CAB(outbuf)[d++];
816         } while (--e);
817       } while (n);
818     }
819   }
820
821   /* restore the globals from the locals */
822   ZIP(window_posn) = w;              /* restore global window pointer */
823   ZIP(bb) = b;                       /* restore global bit buffer */
824   ZIP(bk) = k;
825
826   /* done */
827   return 0;
828 }
829
830 /***********************************************************
831  * Zipinflate_stored (internal)
832  */
833 cab_LONG Zipinflate_stored(cab_decomp_state *decomp_state)
834 /* "decompress" an inflated type 0 (stored) block. */
835 {
836   cab_ULONG n;           /* number of bytes in block */
837   cab_ULONG w;           /* current window position */
838   register cab_ULONG b;  /* bit buffer */
839   register cab_ULONG k;  /* number of bits in bit buffer */
840
841   /* make local copies of globals */
842   b = ZIP(bb);                       /* initialize bit buffer */
843   k = ZIP(bk);
844   w = ZIP(window_posn);              /* initialize window position */
845
846   /* go to byte boundary */
847   n = k & 7;
848   ZIPDUMPBITS(n);
849
850   /* get the length and its complement */
851   ZIPNEEDBITS(16)
852   n = ((cab_ULONG)b & 0xffff);
853   ZIPDUMPBITS(16)
854   ZIPNEEDBITS(16)
855   if (n != (cab_ULONG)((~b) & 0xffff))
856     return 1;                   /* error in compressed data */
857   ZIPDUMPBITS(16)
858
859   /* read and output the compressed data */
860   while(n--)
861   {
862     ZIPNEEDBITS(8)
863     CAB(outbuf)[w++] = (cab_UBYTE)b;
864     ZIPDUMPBITS(8)
865   }
866
867   /* restore the globals from the locals */
868   ZIP(window_posn) = w;              /* restore global window pointer */
869   ZIP(bb) = b;                       /* restore global bit buffer */
870   ZIP(bk) = k;
871   return 0;
872 }
873
874 /******************************************************
875  * Zipinflate_fixed (internal)
876  */
877 cab_LONG Zipinflate_fixed(cab_decomp_state *decomp_state)
878 {
879   struct Ziphuft *fixed_tl;
880   struct Ziphuft *fixed_td;
881   cab_LONG fixed_bl, fixed_bd;
882   cab_LONG i;                /* temporary variable */
883   cab_ULONG *l;
884
885   l = ZIP(ll);
886
887   /* literal table */
888   for(i = 0; i < 144; i++)
889     l[i] = 8;
890   for(; i < 256; i++)
891     l[i] = 9;
892   for(; i < 280; i++)
893     l[i] = 7;
894   for(; i < 288; i++)          /* make a complete, but wrong code set */
895     l[i] = 8;
896   fixed_bl = 7;
897   if((i = Ziphuft_build(l, 288, 257, (cab_UWORD *) Zipcplens,
898   (cab_UWORD *) Zipcplext, &fixed_tl, &fixed_bl, decomp_state)))
899     return i;
900
901   /* distance table */
902   for(i = 0; i < 30; i++)      /* make an incomplete code set */
903     l[i] = 5;
904   fixed_bd = 5;
905   if((i = Ziphuft_build(l, 30, 0, (cab_UWORD *) Zipcpdist, (cab_UWORD *) Zipcpdext,
906   &fixed_td, &fixed_bd, decomp_state)) > 1)
907   {
908     Ziphuft_free(fixed_tl);
909     return i;
910   }
911
912   /* decompress until an end-of-block code */
913   i = Zipinflate_codes(fixed_tl, fixed_td, fixed_bl, fixed_bd, decomp_state);
914
915   Ziphuft_free(fixed_td);
916   Ziphuft_free(fixed_tl);
917   return i;
918 }
919
920 /**************************************************************
921  * Zipinflate_dynamic (internal)
922  */
923 cab_LONG Zipinflate_dynamic(cab_decomp_state *decomp_state)
924  /* decompress an inflated type 2 (dynamic Huffman codes) block. */
925 {
926   cab_LONG i;           /* temporary variables */
927   cab_ULONG j;
928   cab_ULONG *ll;
929   cab_ULONG l;                  /* last length */
930   cab_ULONG m;                  /* mask for bit lengths table */
931   cab_ULONG n;                  /* number of lengths to get */
932   struct Ziphuft *tl;           /* literal/length code table */
933   struct Ziphuft *td;           /* distance code table */
934   cab_LONG bl;                  /* lookup bits for tl */
935   cab_LONG bd;                  /* lookup bits for td */
936   cab_ULONG nb;                 /* number of bit length codes */
937   cab_ULONG nl;                 /* number of literal/length codes */
938   cab_ULONG nd;                 /* number of distance codes */
939   register cab_ULONG b;         /* bit buffer */
940   register cab_ULONG k;         /* number of bits in bit buffer */
941
942   /* make local bit buffer */
943   b = ZIP(bb);
944   k = ZIP(bk);
945   ll = ZIP(ll);
946
947   /* read in table lengths */
948   ZIPNEEDBITS(5)
949   nl = 257 + ((cab_ULONG)b & 0x1f);      /* number of literal/length codes */
950   ZIPDUMPBITS(5)
951   ZIPNEEDBITS(5)
952   nd = 1 + ((cab_ULONG)b & 0x1f);        /* number of distance codes */
953   ZIPDUMPBITS(5)
954   ZIPNEEDBITS(4)
955   nb = 4 + ((cab_ULONG)b & 0xf);         /* number of bit length codes */
956   ZIPDUMPBITS(4)
957   if(nl > 288 || nd > 32)
958     return 1;                   /* bad lengths */
959
960   /* read in bit-length-code lengths */
961   for(j = 0; j < nb; j++)
962   {
963     ZIPNEEDBITS(3)
964     ll[Zipborder[j]] = (cab_ULONG)b & 7;
965     ZIPDUMPBITS(3)
966   }
967   for(; j < 19; j++)
968     ll[Zipborder[j]] = 0;
969
970   /* build decoding table for trees--single level, 7 bit lookup */
971   bl = 7;
972   if((i = Ziphuft_build(ll, 19, 19, NULL, NULL, &tl, &bl, decomp_state)) != 0)
973   {
974     if(i == 1)
975       Ziphuft_free(tl);
976     return i;                   /* incomplete code set */
977   }
978
979   /* read in literal and distance code lengths */
980   n = nl + nd;
981   m = Zipmask[bl];
982   i = l = 0;
983   while((cab_ULONG)i < n)
984   {
985     ZIPNEEDBITS((cab_ULONG)bl)
986     j = (td = tl + ((cab_ULONG)b & m))->b;
987     ZIPDUMPBITS(j)
988     j = td->v.n;
989     if (j < 16)                 /* length of code in bits (0..15) */
990       ll[i++] = l = j;          /* save last length in l */
991     else if (j == 16)           /* repeat last length 3 to 6 times */
992     {
993       ZIPNEEDBITS(2)
994       j = 3 + ((cab_ULONG)b & 3);
995       ZIPDUMPBITS(2)
996       if((cab_ULONG)i + j > n)
997         return 1;
998       while (j--)
999         ll[i++] = l;
1000     }
1001     else if (j == 17)           /* 3 to 10 zero length codes */
1002     {
1003       ZIPNEEDBITS(3)
1004       j = 3 + ((cab_ULONG)b & 7);
1005       ZIPDUMPBITS(3)
1006       if ((cab_ULONG)i + j > n)
1007         return 1;
1008       while (j--)
1009         ll[i++] = 0;
1010       l = 0;
1011     }
1012     else                        /* j == 18: 11 to 138 zero length codes */
1013     {
1014       ZIPNEEDBITS(7)
1015       j = 11 + ((cab_ULONG)b & 0x7f);
1016       ZIPDUMPBITS(7)
1017       if ((cab_ULONG)i + j > n)
1018         return 1;
1019       while (j--)
1020         ll[i++] = 0;
1021       l = 0;
1022     }
1023   }
1024
1025   /* free decoding table for trees */
1026   Ziphuft_free(tl);
1027
1028   /* restore the global bit buffer */
1029   ZIP(bb) = b;
1030   ZIP(bk) = k;
1031
1032   /* build the decoding tables for literal/length and distance codes */
1033   bl = ZIPLBITS;
1034   if((i = Ziphuft_build(ll, nl, 257, (cab_UWORD *) Zipcplens, (cab_UWORD *) Zipcplext,
1035                         &tl, &bl, decomp_state)) != 0)
1036   {
1037     if(i == 1)
1038       Ziphuft_free(tl);
1039     return i;                   /* incomplete code set */
1040   }
1041   bd = ZIPDBITS;
1042   Ziphuft_build(ll + nl, nd, 0, (cab_UWORD *) Zipcpdist, (cab_UWORD *) Zipcpdext,
1043                 &td, &bd, decomp_state);
1044
1045   /* decompress until an end-of-block code */
1046   if(Zipinflate_codes(tl, td, bl, bd, decomp_state))
1047     return 1;
1048
1049   /* free the decoding tables, return */
1050   Ziphuft_free(tl);
1051   Ziphuft_free(td);
1052   return 0;
1053 }
1054
1055 /*****************************************************
1056  * Zipinflate_block (internal)
1057  */
1058 cab_LONG Zipinflate_block(cab_LONG *e, cab_decomp_state *decomp_state) /* e == last block flag */
1059 { /* decompress an inflated block */
1060   cab_ULONG t;                  /* block type */
1061   register cab_ULONG b;     /* bit buffer */
1062   register cab_ULONG k;     /* number of bits in bit buffer */
1063
1064   /* make local bit buffer */
1065   b = ZIP(bb);
1066   k = ZIP(bk);
1067
1068   /* read in last block bit */
1069   ZIPNEEDBITS(1)
1070   *e = (cab_LONG)b & 1;
1071   ZIPDUMPBITS(1)
1072
1073   /* read in block type */
1074   ZIPNEEDBITS(2)
1075   t = (cab_ULONG)b & 3;
1076   ZIPDUMPBITS(2)
1077
1078   /* restore the global bit buffer */
1079   ZIP(bb) = b;
1080   ZIP(bk) = k;
1081
1082   /* inflate that block type */
1083   if(t == 2)
1084     return Zipinflate_dynamic(decomp_state);
1085   if(t == 0)
1086     return Zipinflate_stored(decomp_state);
1087   if(t == 1)
1088     return Zipinflate_fixed(decomp_state);
1089   /* bad block type */
1090   return 2;
1091 }
1092
1093 /****************************************************
1094  * ZIPdecompress (internal)
1095  */
1096 int ZIPdecompress(int inlen, int outlen, cab_decomp_state *decomp_state)
1097 {
1098   cab_LONG e;               /* last block flag */
1099
1100   TRACE("(inlen == %d, outlen == %d)\n", inlen, outlen);
1101
1102   ZIP(inpos) = CAB(inbuf);
1103   ZIP(bb) = ZIP(bk) = ZIP(window_posn) = 0;
1104   if(outlen > ZIPWSIZE)
1105     return DECR_DATAFORMAT;
1106
1107   /* CK = Chris Kirmse, official Microsoft purloiner */
1108   if(ZIP(inpos)[0] != 0x43 || ZIP(inpos)[1] != 0x4B)
1109     return DECR_ILLEGALDATA;
1110   ZIP(inpos) += 2;
1111
1112   do
1113   {
1114     if(Zipinflate_block(&e, decomp_state))
1115       return DECR_ILLEGALDATA;
1116   } while(!e);
1117
1118   /* return success */
1119   return DECR_OK;
1120 }
1121
1122 /* Quantum decruncher */
1123
1124 /* This decruncher was researched and implemented by Matthew Russoto. */
1125 /* It has since been tidied up by Stuart Caie */
1126
1127 /******************************************************************
1128  * QTMinitmodel (internal)
1129  *
1130  * Initialise a model which decodes symbols from [s] to [s]+[n]-1
1131  */
1132 void QTMinitmodel(struct QTMmodel *m, struct QTMmodelsym *sym, int n, int s) {
1133   int i;
1134   m->shiftsleft = 4;
1135   m->entries    = n;
1136   m->syms       = sym;
1137   memset(m->tabloc, 0xFF, sizeof(m->tabloc)); /* clear out look-up table */
1138   for (i = 0; i < n; i++) {
1139     m->tabloc[i+s]     = i;   /* set up a look-up entry for symbol */
1140     m->syms[i].sym     = i+s; /* actual symbol */
1141     m->syms[i].cumfreq = n-i; /* current frequency of that symbol */
1142   }
1143   m->syms[n].cumfreq = 0;
1144 }
1145
1146 /******************************************************************
1147  * QTMinit (internal)
1148  */
1149 int QTMinit(int window, int level, cab_decomp_state *decomp_state) {
1150   int wndsize = 1 << window, msz = window * 2, i;
1151   cab_ULONG j;
1152
1153   /* QTM supports window sizes of 2^10 (1Kb) through 2^21 (2Mb) */
1154   /* if a previously allocated window is big enough, keep it    */
1155   if (window < 10 || window > 21) return DECR_DATAFORMAT;
1156   if (QTM(actual_size) < wndsize) {
1157     if (QTM(window)) free(QTM(window));
1158     QTM(window) = NULL;
1159   }
1160   if (!QTM(window)) {
1161     if (!(QTM(window) = malloc(wndsize))) return DECR_NOMEMORY;
1162     QTM(actual_size) = wndsize;
1163   }
1164   QTM(window_size) = wndsize;
1165   QTM(window_posn) = 0;
1166
1167   /* initialise static slot/extrabits tables */
1168   for (i = 0, j = 0; i < 27; i++) {
1169     CAB(q_length_extra)[i] = (i == 26) ? 0 : (i < 2 ? 0 : i - 2) >> 2;
1170     CAB(q_length_base)[i] = j; j += 1 << ((i == 26) ? 5 : CAB(q_length_extra)[i]);
1171   }
1172   for (i = 0, j = 0; i < 42; i++) {
1173     CAB(q_extra_bits)[i] = (i < 2 ? 0 : i-2) >> 1;
1174     CAB(q_position_base)[i] = j; j += 1 << CAB(q_extra_bits)[i];
1175   }
1176
1177   /* initialise arithmetic coding models */
1178
1179   QTMinitmodel(&QTM(model7), &QTM(m7sym)[0], 7, 0);
1180
1181   QTMinitmodel(&QTM(model00), &QTM(m00sym)[0], 0x40, 0x00);
1182   QTMinitmodel(&QTM(model40), &QTM(m40sym)[0], 0x40, 0x40);
1183   QTMinitmodel(&QTM(model80), &QTM(m80sym)[0], 0x40, 0x80);
1184   QTMinitmodel(&QTM(modelC0), &QTM(mC0sym)[0], 0x40, 0xC0);
1185
1186   /* model 4 depends on table size, ranges from 20 to 24  */
1187   QTMinitmodel(&QTM(model4), &QTM(m4sym)[0], (msz < 24) ? msz : 24, 0);
1188   /* model 5 depends on table size, ranges from 20 to 36  */
1189   QTMinitmodel(&QTM(model5), &QTM(m5sym)[0], (msz < 36) ? msz : 36, 0);
1190   /* model 6pos depends on table size, ranges from 20 to 42 */
1191   QTMinitmodel(&QTM(model6pos), &QTM(m6psym)[0], msz, 0);
1192   QTMinitmodel(&QTM(model6len), &QTM(m6lsym)[0], 27, 0);
1193
1194   return DECR_OK;
1195 }
1196
1197 /****************************************************************
1198  * QTMupdatemodel (internal)
1199  */
1200 void QTMupdatemodel(struct QTMmodel *model, int sym) {
1201   struct QTMmodelsym temp;
1202   int i, j;
1203
1204   for (i = 0; i < sym; i++) model->syms[i].cumfreq += 8;
1205
1206   if (model->syms[0].cumfreq > 3800) {
1207     if (--model->shiftsleft) {
1208       for (i = model->entries - 1; i >= 0; i--) {
1209         /* -1, not -2; the 0 entry saves this */
1210         model->syms[i].cumfreq >>= 1;
1211         if (model->syms[i].cumfreq <= model->syms[i+1].cumfreq) {
1212           model->syms[i].cumfreq = model->syms[i+1].cumfreq + 1;
1213         }
1214       }
1215     }
1216     else {
1217       model->shiftsleft = 50;
1218       for (i = 0; i < model->entries ; i++) {
1219         /* no -1, want to include the 0 entry */
1220         /* this converts cumfreqs into frequencies, then shifts right */
1221         model->syms[i].cumfreq -= model->syms[i+1].cumfreq;
1222         model->syms[i].cumfreq++; /* avoid losing things entirely */
1223         model->syms[i].cumfreq >>= 1;
1224       }
1225
1226       /* now sort by frequencies, decreasing order -- this must be an
1227        * inplace selection sort, or a sort with the same (in)stability
1228        * characteristics
1229        */
1230       for (i = 0; i < model->entries - 1; i++) {
1231         for (j = i + 1; j < model->entries; j++) {
1232           if (model->syms[i].cumfreq < model->syms[j].cumfreq) {
1233             temp = model->syms[i];
1234             model->syms[i] = model->syms[j];
1235             model->syms[j] = temp;
1236           }
1237         }
1238       }
1239     
1240       /* then convert frequencies back to cumfreq */
1241       for (i = model->entries - 1; i >= 0; i--) {
1242         model->syms[i].cumfreq += model->syms[i+1].cumfreq;
1243       }
1244       /* then update the other part of the table */
1245       for (i = 0; i < model->entries; i++) {
1246         model->tabloc[model->syms[i].sym] = i;
1247       }
1248     }
1249   }
1250 }
1251
1252 /*******************************************************************
1253  * QTMdecompress (internal)
1254  */
1255 int QTMdecompress(int inlen, int outlen, cab_decomp_state *decomp_state)
1256 {
1257   cab_UBYTE *inpos  = CAB(inbuf);
1258   cab_UBYTE *window = QTM(window);
1259   cab_UBYTE *runsrc, *rundest;
1260
1261   cab_ULONG window_posn = QTM(window_posn);
1262   cab_ULONG window_size = QTM(window_size);
1263
1264   /* used by bitstream macros */
1265   register int bitsleft, bitrun, bitsneed;
1266   register cab_ULONG bitbuf;
1267
1268   /* used by GET_SYMBOL */
1269   cab_ULONG range;
1270   cab_UWORD symf;
1271   int i;
1272
1273   int extra, togo = outlen, match_length = 0, copy_length;
1274   cab_UBYTE selector, sym;
1275   cab_ULONG match_offset = 0;
1276
1277   cab_UWORD H = 0xFFFF, L = 0, C;
1278
1279   TRACE("(inlen == %d, outlen == %d)\n", inlen, outlen);
1280
1281   /* read initial value of C */
1282   Q_INIT_BITSTREAM;
1283   Q_READ_BITS(C, 16);
1284
1285   /* apply 2^x-1 mask */
1286   window_posn &= window_size - 1;
1287   /* runs can't straddle the window wraparound */
1288   if ((window_posn + togo) > window_size) {
1289     TRACE("straddled run\n");
1290     return DECR_DATAFORMAT;
1291   }
1292
1293   while (togo > 0) {
1294     GET_SYMBOL(model7, selector);
1295     switch (selector) {
1296     case 0:
1297       GET_SYMBOL(model00, sym); window[window_posn++] = sym; togo--;
1298       break;
1299     case 1:
1300       GET_SYMBOL(model40, sym); window[window_posn++] = sym; togo--;
1301       break;
1302     case 2:
1303       GET_SYMBOL(model80, sym); window[window_posn++] = sym; togo--;
1304       break;
1305     case 3:
1306       GET_SYMBOL(modelC0, sym); window[window_posn++] = sym; togo--;
1307       break;
1308
1309     case 4:
1310       /* selector 4 = fixed length of 3 */
1311       GET_SYMBOL(model4, sym);
1312       Q_READ_BITS(extra, CAB(q_extra_bits)[sym]);
1313       match_offset = CAB(q_position_base)[sym] + extra + 1;
1314       match_length = 3;
1315       break;
1316
1317     case 5:
1318       /* selector 5 = fixed length of 4 */
1319       GET_SYMBOL(model5, sym);
1320       Q_READ_BITS(extra, CAB(q_extra_bits)[sym]);
1321       match_offset = CAB(q_position_base)[sym] + extra + 1;
1322       match_length = 4;
1323       break;
1324
1325     case 6:
1326       /* selector 6 = variable length */
1327       GET_SYMBOL(model6len, sym);
1328       Q_READ_BITS(extra, CAB(q_length_extra)[sym]);
1329       match_length = CAB(q_length_base)[sym] + extra + 5;
1330       GET_SYMBOL(model6pos, sym);
1331       Q_READ_BITS(extra, CAB(q_extra_bits)[sym]);
1332       match_offset = CAB(q_position_base)[sym] + extra + 1;
1333       break;
1334
1335     default:
1336       TRACE("Selector is bogus\n");
1337       return DECR_ILLEGALDATA;
1338     }
1339
1340     /* if this is a match */
1341     if (selector >= 4) {
1342       rundest = window + window_posn;
1343       togo -= match_length;
1344
1345       /* copy any wrapped around source data */
1346       if (window_posn >= match_offset) {
1347         /* no wrap */
1348         runsrc = rundest - match_offset;
1349       } else {
1350         runsrc = rundest + (window_size - match_offset);
1351         copy_length = match_offset - window_posn;
1352         if (copy_length < match_length) {
1353           match_length -= copy_length;
1354           window_posn += copy_length;
1355           while (copy_length-- > 0) *rundest++ = *runsrc++;
1356           runsrc = window;
1357         }
1358       }
1359       window_posn += match_length;
1360
1361       /* copy match data - no worries about destination wraps */
1362       while (match_length-- > 0) *rundest++ = *runsrc++;
1363     }
1364   } /* while (togo > 0) */
1365
1366   if (togo != 0) {
1367     TRACE("Frame overflow, this_run = %d\n", togo);
1368     return DECR_ILLEGALDATA;
1369   }
1370
1371   memcpy(CAB(outbuf), window + ((!window_posn) ? window_size : window_posn) -
1372     outlen, outlen);
1373
1374   QTM(window_posn) = window_posn;
1375   return DECR_OK;
1376 }
1377
1378 /* LZX decruncher */
1379
1380 /* Microsoft's LZX document and their implementation of the
1381  * com.ms.util.cab Java package do not concur.
1382  *
1383  * In the LZX document, there is a table showing the correlation between
1384  * window size and the number of position slots. It states that the 1MB
1385  * window = 40 slots and the 2MB window = 42 slots. In the implementation,
1386  * 1MB = 42 slots, 2MB = 50 slots. The actual calculation is 'find the
1387  * first slot whose position base is equal to or more than the required
1388  * window size'. This would explain why other tables in the document refer
1389  * to 50 slots rather than 42.
1390  *
1391  * The constant NUM_PRIMARY_LENGTHS used in the decompression pseudocode
1392  * is not defined in the specification.
1393  *
1394  * The LZX document does not state the uncompressed block has an
1395  * uncompressed length field. Where does this length field come from, so
1396  * we can know how large the block is? The implementation has it as the 24
1397  * bits following after the 3 blocktype bits, before the alignment
1398  * padding.
1399  *
1400  * The LZX document states that aligned offset blocks have their aligned
1401  * offset huffman tree AFTER the main and length trees. The implementation
1402  * suggests that the aligned offset tree is BEFORE the main and length
1403  * trees.
1404  *
1405  * The LZX document decoding algorithm states that, in an aligned offset
1406  * block, if an extra_bits value is 1, 2 or 3, then that number of bits
1407  * should be read and the result added to the match offset. This is
1408  * correct for 1 and 2, but not 3, where just a huffman symbol (using the
1409  * aligned tree) should be read.
1410  *
1411  * Regarding the E8 preprocessing, the LZX document states 'No translation
1412  * may be performed on the last 6 bytes of the input block'. This is
1413  * correct.  However, the pseudocode provided checks for the *E8 leader*
1414  * up to the last 6 bytes. If the leader appears between -10 and -7 bytes
1415  * from the end, this would cause the next four bytes to be modified, at
1416  * least one of which would be in the last 6 bytes, which is not allowed
1417  * according to the spec.
1418  *
1419  * The specification states that the huffman trees must always contain at
1420  * least one element. However, many CAB files contain blocks where the
1421  * length tree is completely empty (because there are no matches), and
1422  * this is expected to succeed.
1423  */
1424
1425
1426 /* LZX uses what it calls 'position slots' to represent match offsets.
1427  * What this means is that a small 'position slot' number and a small
1428  * offset from that slot are encoded instead of one large offset for
1429  * every match.
1430  * - lzx_position_base is an index to the position slot bases
1431  * - lzx_extra_bits states how many bits of offset-from-base data is needed.
1432  */
1433
1434 /************************************************************
1435  * LZXinit (internal)
1436  */
1437 int LZXinit(int window, cab_decomp_state *decomp_state) {
1438   cab_ULONG wndsize = 1 << window;
1439   int i, j, posn_slots;
1440
1441   /* LZX supports window sizes of 2^15 (32Kb) through 2^21 (2Mb) */
1442   /* if a previously allocated window is big enough, keep it     */
1443   if (window < 15 || window > 21) return DECR_DATAFORMAT;
1444   if (LZX(actual_size) < wndsize) {
1445     if (LZX(window)) free(LZX(window));
1446     LZX(window) = NULL;
1447   }
1448   if (!LZX(window)) {
1449     if (!(LZX(window) = malloc(wndsize))) return DECR_NOMEMORY;
1450     LZX(actual_size) = wndsize;
1451   }
1452   LZX(window_size) = wndsize;
1453
1454   /* initialise static tables */
1455   for (i=0, j=0; i <= 50; i += 2) {
1456     CAB(extra_bits)[i] = CAB(extra_bits)[i+1] = j; /* 0,0,0,0,1,1,2,2,3,3... */
1457     if ((i != 0) && (j < 17)) j++; /* 0,0,1,2,3,4...15,16,17,17,17,17... */
1458   }
1459   for (i=0, j=0; i <= 50; i++) {
1460     CAB(lzx_position_base)[i] = j; /* 0,1,2,3,4,6,8,12,16,24,32,... */
1461     j += 1 << CAB(extra_bits)[i]; /* 1,1,1,1,2,2,4,4,8,8,16,16,32,32,... */
1462   }
1463
1464   /* calculate required position slots */
1465        if (window == 20) posn_slots = 42;
1466   else if (window == 21) posn_slots = 50;
1467   else posn_slots = window << 1;
1468
1469   /*posn_slots=i=0; while (i < wndsize) i += 1 << CAB(extra_bits)[posn_slots++]; */
1470
1471   LZX(R0)  =  LZX(R1)  = LZX(R2) = 1;
1472   LZX(main_elements)   = LZX_NUM_CHARS + (posn_slots << 3);
1473   LZX(header_read)     = 0;
1474   LZX(frames_read)     = 0;
1475   LZX(block_remaining) = 0;
1476   LZX(block_type)      = LZX_BLOCKTYPE_INVALID;
1477   LZX(intel_curpos)    = 0;
1478   LZX(intel_started)   = 0;
1479   LZX(window_posn)     = 0;
1480
1481   /* initialise tables to 0 (because deltas will be applied to them) */
1482   for (i = 0; i < LZX_MAINTREE_MAXSYMBOLS; i++) LZX(MAINTREE_len)[i] = 0;
1483   for (i = 0; i < LZX_LENGTH_MAXSYMBOLS; i++)   LZX(LENGTH_len)[i]   = 0;
1484
1485   return DECR_OK;
1486 }
1487
1488 /*************************************************************************
1489  * make_decode_table (internal)
1490  *
1491  * This function was coded by David Tritscher. It builds a fast huffman
1492  * decoding table out of just a canonical huffman code lengths table.
1493  *
1494  * PARAMS
1495  *   nsyms:  total number of symbols in this huffman tree.
1496  *   nbits:  any symbols with a code length of nbits or less can be decoded
1497  *           in one lookup of the table.
1498  *   length: A table to get code lengths from [0 to syms-1]
1499  *   table:  The table to fill up with decoded symbols and pointers.
1500  *
1501  * RETURNS
1502  *   OK:    0
1503  *   error: 1
1504  */
1505 int make_decode_table(cab_ULONG nsyms, cab_ULONG nbits, cab_UBYTE *length, cab_UWORD *table) {
1506   register cab_UWORD sym;
1507   register cab_ULONG leaf;
1508   register cab_UBYTE bit_num = 1;
1509   cab_ULONG fill;
1510   cab_ULONG pos         = 0; /* the current position in the decode table */
1511   cab_ULONG table_mask  = 1 << nbits;
1512   cab_ULONG bit_mask    = table_mask >> 1; /* don't do 0 length codes */
1513   cab_ULONG next_symbol = bit_mask; /* base of allocation for long codes */
1514
1515   /* fill entries for codes short enough for a direct mapping */
1516   while (bit_num <= nbits) {
1517     for (sym = 0; sym < nsyms; sym++) {
1518       if (length[sym] == bit_num) {
1519         leaf = pos;
1520
1521         if((pos += bit_mask) > table_mask) return 1; /* table overrun */
1522
1523         /* fill all possible lookups of this symbol with the symbol itself */
1524         fill = bit_mask;
1525         while (fill-- > 0) table[leaf++] = sym;
1526       }
1527     }
1528     bit_mask >>= 1;
1529     bit_num++;
1530   }
1531
1532   /* if there are any codes longer than nbits */
1533   if (pos != table_mask) {
1534     /* clear the remainder of the table */
1535     for (sym = pos; sym < table_mask; sym++) table[sym] = 0;
1536
1537     /* give ourselves room for codes to grow by up to 16 more bits */
1538     pos <<= 16;
1539     table_mask <<= 16;
1540     bit_mask = 1 << 15;
1541
1542     while (bit_num <= 16) {
1543       for (sym = 0; sym < nsyms; sym++) {
1544         if (length[sym] == bit_num) {
1545           leaf = pos >> 16;
1546           for (fill = 0; fill < bit_num - nbits; fill++) {
1547             /* if this path hasn't been taken yet, 'allocate' two entries */
1548             if (table[leaf] == 0) {
1549               table[(next_symbol << 1)] = 0;
1550               table[(next_symbol << 1) + 1] = 0;
1551               table[leaf] = next_symbol++;
1552             }
1553             /* follow the path and select either left or right for next bit */
1554             leaf = table[leaf] << 1;
1555             if ((pos >> (15-fill)) & 1) leaf++;
1556           }
1557           table[leaf] = sym;
1558
1559           if ((pos += bit_mask) > table_mask) return 1; /* table overflow */
1560         }
1561       }
1562       bit_mask >>= 1;
1563       bit_num++;
1564     }
1565   }
1566
1567   /* full table? */
1568   if (pos == table_mask) return 0;
1569
1570   /* either erroneous table, or all elements are 0 - let's find out. */
1571   for (sym = 0; sym < nsyms; sym++) if (length[sym]) return 1;
1572   return 0;
1573 }
1574
1575 /************************************************************
1576  * lzx_read_lens (internal)
1577  */
1578 int lzx_read_lens(cab_UBYTE *lens, cab_ULONG first, cab_ULONG last, struct lzx_bits *lb,
1579                   cab_decomp_state *decomp_state) {
1580   cab_ULONG i,j, x,y;
1581   int z;
1582
1583   register cab_ULONG bitbuf = lb->bb;
1584   register int bitsleft = lb->bl;
1585   cab_UBYTE *inpos = lb->ip;
1586   cab_UWORD *hufftbl;
1587   
1588   for (x = 0; x < 20; x++) {
1589     READ_BITS(y, 4);
1590     LENTABLE(PRETREE)[x] = y;
1591   }
1592   BUILD_TABLE(PRETREE);
1593
1594   for (x = first; x < last; ) {
1595     READ_HUFFSYM(PRETREE, z);
1596     if (z == 17) {
1597       READ_BITS(y, 4); y += 4;
1598       while (y--) lens[x++] = 0;
1599     }
1600     else if (z == 18) {
1601       READ_BITS(y, 5); y += 20;
1602       while (y--) lens[x++] = 0;
1603     }
1604     else if (z == 19) {
1605       READ_BITS(y, 1); y += 4;
1606       READ_HUFFSYM(PRETREE, z);
1607       z = lens[x] - z; if (z < 0) z += 17;
1608       while (y--) lens[x++] = z;
1609     }
1610     else {
1611       z = lens[x] - z; if (z < 0) z += 17;
1612       lens[x++] = z;
1613     }
1614   }
1615
1616   lb->bb = bitbuf;
1617   lb->bl = bitsleft;
1618   lb->ip = inpos;
1619   return 0;
1620 }
1621
1622 /*******************************************************
1623  * LZXdecompress (internal)
1624  */
1625 int LZXdecompress(int inlen, int outlen, cab_decomp_state *decomp_state) {
1626   cab_UBYTE *inpos  = CAB(inbuf);
1627   cab_UBYTE *endinp = inpos + inlen;
1628   cab_UBYTE *window = LZX(window);
1629   cab_UBYTE *runsrc, *rundest;
1630   cab_UWORD *hufftbl; /* used in READ_HUFFSYM macro as chosen decoding table */
1631
1632   cab_ULONG window_posn = LZX(window_posn);
1633   cab_ULONG window_size = LZX(window_size);
1634   cab_ULONG R0 = LZX(R0);
1635   cab_ULONG R1 = LZX(R1);
1636   cab_ULONG R2 = LZX(R2);
1637
1638   register cab_ULONG bitbuf;
1639   register int bitsleft;
1640   cab_ULONG match_offset, i,j,k; /* ijk used in READ_HUFFSYM macro */
1641   struct lzx_bits lb; /* used in READ_LENGTHS macro */
1642
1643   int togo = outlen, this_run, main_element, aligned_bits;
1644   int match_length, copy_length, length_footer, extra, verbatim_bits;
1645
1646   TRACE("(inlen == %d, outlen == %d)\n", inlen, outlen);
1647
1648   INIT_BITSTREAM;
1649
1650   /* read header if necessary */
1651   if (!LZX(header_read)) {
1652     i = j = 0;
1653     READ_BITS(k, 1); if (k) { READ_BITS(i,16); READ_BITS(j,16); }
1654     LZX(intel_filesize) = (i << 16) | j; /* or 0 if not encoded */
1655     LZX(header_read) = 1;
1656   }
1657
1658   /* main decoding loop */
1659   while (togo > 0) {
1660     /* last block finished, new block expected */
1661     if (LZX(block_remaining) == 0) {
1662       if (LZX(block_type) == LZX_BLOCKTYPE_UNCOMPRESSED) {
1663         if (LZX(block_length) & 1) inpos++; /* realign bitstream to word */
1664         INIT_BITSTREAM;
1665       }
1666
1667       READ_BITS(LZX(block_type), 3);
1668       READ_BITS(i, 16);
1669       READ_BITS(j, 8);
1670       LZX(block_remaining) = LZX(block_length) = (i << 8) | j;
1671
1672       switch (LZX(block_type)) {
1673       case LZX_BLOCKTYPE_ALIGNED:
1674         for (i = 0; i < 8; i++) { READ_BITS(j, 3); LENTABLE(ALIGNED)[i] = j; }
1675         BUILD_TABLE(ALIGNED);
1676         /* rest of aligned header is same as verbatim */
1677
1678       case LZX_BLOCKTYPE_VERBATIM:
1679         READ_LENGTHS(MAINTREE, 0, 256, lzx_read_lens);
1680         READ_LENGTHS(MAINTREE, 256, LZX(main_elements), lzx_read_lens);
1681         BUILD_TABLE(MAINTREE);
1682         if (LENTABLE(MAINTREE)[0xE8] != 0) LZX(intel_started) = 1;
1683
1684         READ_LENGTHS(LENGTH, 0, LZX_NUM_SECONDARY_LENGTHS, lzx_read_lens);
1685         BUILD_TABLE(LENGTH);
1686         break;
1687
1688       case LZX_BLOCKTYPE_UNCOMPRESSED:
1689         LZX(intel_started) = 1; /* because we can't assume otherwise */
1690         ENSURE_BITS(16); /* get up to 16 pad bits into the buffer */
1691         if (bitsleft > 16) inpos -= 2; /* and align the bitstream! */
1692         R0 = inpos[0]|(inpos[1]<<8)|(inpos[2]<<16)|(inpos[3]<<24);inpos+=4;
1693         R1 = inpos[0]|(inpos[1]<<8)|(inpos[2]<<16)|(inpos[3]<<24);inpos+=4;
1694         R2 = inpos[0]|(inpos[1]<<8)|(inpos[2]<<16)|(inpos[3]<<24);inpos+=4;
1695         break;
1696
1697       default:
1698         return DECR_ILLEGALDATA;
1699       }
1700     }
1701
1702     /* buffer exhaustion check */
1703     if (inpos > endinp) {
1704       /* it's possible to have a file where the next run is less than
1705        * 16 bits in size. In this case, the READ_HUFFSYM() macro used
1706        * in building the tables will exhaust the buffer, so we should
1707        * allow for this, but not allow those accidentally read bits to
1708        * be used (so we check that there are at least 16 bits
1709        * remaining - in this boundary case they aren't really part of
1710        * the compressed data)
1711        */
1712       if (inpos > (endinp+2) || bitsleft < 16) return DECR_ILLEGALDATA;
1713     }
1714
1715     while ((this_run = LZX(block_remaining)) > 0 && togo > 0) {
1716       if (this_run > togo) this_run = togo;
1717       togo -= this_run;
1718       LZX(block_remaining) -= this_run;
1719
1720       /* apply 2^x-1 mask */
1721       window_posn &= window_size - 1;
1722       /* runs can't straddle the window wraparound */
1723       if ((window_posn + this_run) > window_size)
1724         return DECR_DATAFORMAT;
1725
1726       switch (LZX(block_type)) {
1727
1728       case LZX_BLOCKTYPE_VERBATIM:
1729         while (this_run > 0) {
1730           READ_HUFFSYM(MAINTREE, main_element);
1731
1732           if (main_element < LZX_NUM_CHARS) {
1733             /* literal: 0 to LZX_NUM_CHARS-1 */
1734             window[window_posn++] = main_element;
1735             this_run--;
1736           }
1737           else {
1738             /* match: LZX_NUM_CHARS + ((slot<<3) | length_header (3 bits)) */
1739             main_element -= LZX_NUM_CHARS;
1740   
1741             match_length = main_element & LZX_NUM_PRIMARY_LENGTHS;
1742             if (match_length == LZX_NUM_PRIMARY_LENGTHS) {
1743               READ_HUFFSYM(LENGTH, length_footer);
1744               match_length += length_footer;
1745             }
1746             match_length += LZX_MIN_MATCH;
1747   
1748             match_offset = main_element >> 3;
1749   
1750             if (match_offset > 2) {
1751               /* not repeated offset */
1752               if (match_offset != 3) {
1753                 extra = CAB(extra_bits)[match_offset];
1754                 READ_BITS(verbatim_bits, extra);
1755                 match_offset = CAB(lzx_position_base)[match_offset] 
1756                                - 2 + verbatim_bits;
1757               }
1758               else {
1759                 match_offset = 1;
1760               }
1761   
1762               /* update repeated offset LRU queue */
1763               R2 = R1; R1 = R0; R0 = match_offset;
1764             }
1765             else if (match_offset == 0) {
1766               match_offset = R0;
1767             }
1768             else if (match_offset == 1) {
1769               match_offset = R1;
1770               R1 = R0; R0 = match_offset;
1771             }
1772             else /* match_offset == 2 */ {
1773               match_offset = R2;
1774               R2 = R0; R0 = match_offset;
1775             }
1776
1777             rundest = window + window_posn;
1778             this_run -= match_length;
1779
1780             /* copy any wrapped around source data */
1781             if (window_posn >= match_offset) {
1782               /* no wrap */
1783               runsrc = rundest - match_offset;
1784             } else {
1785               runsrc = rundest + (window_size - match_offset);
1786               copy_length = match_offset - window_posn;
1787               if (copy_length < match_length) {
1788                 match_length -= copy_length;
1789                 window_posn += copy_length;
1790                 while (copy_length-- > 0) *rundest++ = *runsrc++;
1791                 runsrc = window;
1792               }
1793             }
1794             window_posn += match_length;
1795
1796             /* copy match data - no worries about destination wraps */
1797             while (match_length-- > 0) *rundest++ = *runsrc++;
1798           }
1799         }
1800         break;
1801
1802       case LZX_BLOCKTYPE_ALIGNED:
1803         while (this_run > 0) {
1804           READ_HUFFSYM(MAINTREE, main_element);
1805   
1806           if (main_element < LZX_NUM_CHARS) {
1807             /* literal: 0 to LZX_NUM_CHARS-1 */
1808             window[window_posn++] = main_element;
1809             this_run--;
1810           }
1811           else {
1812             /* match: LZX_NUM_CHARS + ((slot<<3) | length_header (3 bits)) */
1813             main_element -= LZX_NUM_CHARS;
1814   
1815             match_length = main_element & LZX_NUM_PRIMARY_LENGTHS;
1816             if (match_length == LZX_NUM_PRIMARY_LENGTHS) {
1817               READ_HUFFSYM(LENGTH, length_footer);
1818               match_length += length_footer;
1819             }
1820             match_length += LZX_MIN_MATCH;
1821   
1822             match_offset = main_element >> 3;
1823   
1824             if (match_offset > 2) {
1825               /* not repeated offset */
1826               extra = CAB(extra_bits)[match_offset];
1827               match_offset = CAB(lzx_position_base)[match_offset] - 2;
1828               if (extra > 3) {
1829                 /* verbatim and aligned bits */
1830                 extra -= 3;
1831                 READ_BITS(verbatim_bits, extra);
1832                 match_offset += (verbatim_bits << 3);
1833                 READ_HUFFSYM(ALIGNED, aligned_bits);
1834                 match_offset += aligned_bits;
1835               }
1836               else if (extra == 3) {
1837                 /* aligned bits only */
1838                 READ_HUFFSYM(ALIGNED, aligned_bits);
1839                 match_offset += aligned_bits;
1840               }
1841               else if (extra > 0) { /* extra==1, extra==2 */
1842                 /* verbatim bits only */
1843                 READ_BITS(verbatim_bits, extra);
1844                 match_offset += verbatim_bits;
1845               }
1846               else /* extra == 0 */ {
1847                 /* ??? */
1848                 match_offset = 1;
1849               }
1850   
1851               /* update repeated offset LRU queue */
1852               R2 = R1; R1 = R0; R0 = match_offset;
1853             }
1854             else if (match_offset == 0) {
1855               match_offset = R0;
1856             }
1857             else if (match_offset == 1) {
1858               match_offset = R1;
1859               R1 = R0; R0 = match_offset;
1860             }
1861             else /* match_offset == 2 */ {
1862               match_offset = R2;
1863               R2 = R0; R0 = match_offset;
1864             }
1865
1866             rundest = window + window_posn;
1867             this_run -= match_length;
1868
1869             /* copy any wrapped around source data */
1870             if (window_posn >= match_offset) {
1871               /* no wrap */
1872               runsrc = rundest - match_offset;
1873             } else {
1874               runsrc = rundest + (window_size - match_offset);
1875               copy_length = match_offset - window_posn;
1876               if (copy_length < match_length) {
1877                 match_length -= copy_length;
1878                 window_posn += copy_length;
1879                 while (copy_length-- > 0) *rundest++ = *runsrc++;
1880                 runsrc = window;
1881               }
1882             }
1883             window_posn += match_length;
1884
1885             /* copy match data - no worries about destination wraps */
1886             while (match_length-- > 0) *rundest++ = *runsrc++;
1887           }
1888         }
1889         break;
1890
1891       case LZX_BLOCKTYPE_UNCOMPRESSED:
1892         if ((inpos + this_run) > endinp) return DECR_ILLEGALDATA;
1893         memcpy(window + window_posn, inpos, (size_t) this_run);
1894         inpos += this_run; window_posn += this_run;
1895         break;
1896
1897       default:
1898         return DECR_ILLEGALDATA; /* might as well */
1899       }
1900
1901     }
1902   }
1903
1904   if (togo != 0) return DECR_ILLEGALDATA;
1905   memcpy(CAB(outbuf), window + ((!window_posn) ? window_size : window_posn) -
1906     outlen, (size_t) outlen);
1907
1908   LZX(window_posn) = window_posn;
1909   LZX(R0) = R0;
1910   LZX(R1) = R1;
1911   LZX(R2) = R2;
1912
1913   /* intel E8 decoding */
1914   if ((LZX(frames_read)++ < 32768) && LZX(intel_filesize) != 0) {
1915     if (outlen <= 6 || !LZX(intel_started)) {
1916       LZX(intel_curpos) += outlen;
1917     }
1918     else {
1919       cab_UBYTE *data    = CAB(outbuf);
1920       cab_UBYTE *dataend = data + outlen - 10;
1921       cab_LONG curpos    = LZX(intel_curpos);
1922       cab_LONG filesize  = LZX(intel_filesize);
1923       cab_LONG abs_off, rel_off;
1924
1925       LZX(intel_curpos) = curpos + outlen;
1926
1927       while (data < dataend) {
1928         if (*data++ != 0xE8) { curpos++; continue; }
1929         abs_off = data[0] | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
1930         if ((abs_off >= -curpos) && (abs_off < filesize)) {
1931           rel_off = (abs_off >= 0) ? abs_off - curpos : abs_off + filesize;
1932           data[0] = (cab_UBYTE) rel_off;
1933           data[1] = (cab_UBYTE) (rel_off >> 8);
1934           data[2] = (cab_UBYTE) (rel_off >> 16);
1935           data[3] = (cab_UBYTE) (rel_off >> 24);
1936         }
1937         data += 4;
1938         curpos += 5;
1939       }
1940     }
1941   }
1942   return DECR_OK;
1943 }
1944
1945 /*********************************************************
1946  * find_cabs_in_file (internal)
1947  */
1948 struct cabinet *find_cabs_in_file(LPCSTR name, cab_UBYTE search_buf[])
1949 {
1950   struct cabinet *cab, *cab2, *firstcab = NULL, *linkcab = NULL;
1951   cab_UBYTE *pstart = &search_buf[0], *pend, *p;
1952   cab_off_t offset, caboff, cablen = 0, foffset = 0, filelen, length;
1953   int state = 0, found = 0, ok = 0;
1954
1955   TRACE("(name == %s)\n", debugstr_a((char *) name));
1956
1957   /* open the file and search for cabinet headers */
1958   if ((cab = (struct cabinet *) calloc(1, sizeof(struct cabinet)))) {
1959     cab->filename = name;
1960     if (cabinet_open(cab)) {
1961       filelen = cab->filelen;
1962       for (offset = 0; (offset < filelen); offset += length) {
1963         /* search length is either the full length of the search buffer,
1964          * or the amount of data remaining to the end of the file,
1965          * whichever is less.
1966          */
1967         length = filelen - offset;
1968         if (length > CAB_SEARCH_SIZE) length = CAB_SEARCH_SIZE;
1969
1970         /* fill the search buffer with data from disk */
1971         if (!cabinet_read(cab, search_buf, length)) break;
1972
1973         /* read through the entire buffer. */
1974         p = pstart;
1975         pend = &search_buf[length];
1976         while (p < pend) {
1977           switch (state) {
1978           /* starting state */
1979           case 0:
1980             /* we spend most of our time in this while loop, looking for
1981              * a leading 'M' of the 'MSCF' signature
1982              */
1983             while (*p++ != 0x4D && p < pend);
1984             if (p < pend) state = 1; /* if we found tht 'M', advance state */
1985             break;
1986
1987           /* verify that the next 3 bytes are 'S', 'C' and 'F' */
1988           case 1: state = (*p++ == 0x53) ? 2 : 0; break;
1989           case 2: state = (*p++ == 0x43) ? 3 : 0; break;
1990           case 3: state = (*p++ == 0x46) ? 4 : 0; break;
1991
1992           /* we don't care about bytes 4-7 */
1993           /* bytes 8-11 are the overall length of the cabinet */
1994           case 8:  cablen  = *p++;       state++; break;
1995           case 9:  cablen |= *p++ << 8;  state++; break;
1996           case 10: cablen |= *p++ << 16; state++; break;
1997           case 11: cablen |= *p++ << 24; state++; break;
1998
1999           /* we don't care about bytes 12-15 */
2000           /* bytes 16-19 are the offset within the cabinet of the filedata */
2001           case 16: foffset  = *p++;       state++; break;
2002           case 17: foffset |= *p++ << 8;  state++; break;
2003           case 18: foffset |= *p++ << 16; state++; break;
2004           case 19: foffset |= *p++ << 24;
2005             /* now we have received 20 bytes of potential cab header. */
2006             /* work out the offset in the file of this potential cabinet */
2007             caboff = offset + (p-pstart) - 20;
2008
2009             /* check that the files offset is less than the alleged length
2010              * of the cabinet, and that the offset + the alleged length are
2011              * 'roughly' within the end of overall file length
2012              */
2013             if ((foffset < cablen) &&
2014                 ((caboff + foffset) < (filelen + 32)) &&
2015                 ((caboff + cablen) < (filelen + 32)) )
2016             {
2017               /* found a potential result - try loading it */
2018               found++;
2019               cab2 =  load_cab_offset(name, caboff);
2020               if (cab2) {
2021                 /* success */
2022                 ok++;
2023
2024                 /* cause the search to restart after this cab's data. */
2025                 offset = caboff + cablen;
2026                 if (offset < cab->filelen) cabinet_seek(cab, offset);
2027                 length = 0;
2028                 p = pend;
2029
2030                 /* link the cab into the list */
2031                 if (linkcab == NULL) firstcab = cab2;
2032                 else linkcab->next = cab2;
2033                 linkcab = cab2;
2034               }
2035             }
2036             state = 0;
2037             break;
2038           default:
2039             p++, state++; break;
2040           }
2041         }
2042       }
2043       cabinet_close(cab);
2044     }
2045     free(cab);
2046   }
2047
2048   /* if there were cabinets that were found but are not ok, point this out */
2049   if (found > ok) {
2050     WARN("%s: found %d bad cabinets\n", debugstr_a(name), found-ok);
2051   }
2052
2053   /* if no cabinets were found, let the user know */
2054   if (!firstcab) {
2055     WARN("%s: not a Microsoft cabinet file.\n", debugstr_a(name));
2056   }
2057   return firstcab;
2058 }
2059
2060 /***********************************************************************
2061  * find_cabinet_file (internal)
2062  *
2063  * tries to find *cabname, from the directory path of origcab, correcting the
2064  * case of *cabname if necessary, If found, writes back to *cabname.
2065  */
2066 void find_cabinet_file(char **cabname, LPCSTR origcab) {
2067
2068   char *tail, *cab, *name, *nextpart, nametmp[MAX_PATH], *filepart;
2069   int found = 0;
2070
2071   TRACE("(*cabname == ^%p, origcab == %s)\n", cabname ? *cabname : NULL, debugstr_a(origcab));
2072
2073   /* ensure we have a cabinet name at all */
2074   if (!(name = *cabname)) {
2075     WARN("no cabinet name at all\n");
2076   }
2077
2078   /* find if there's a directory path in the origcab */
2079   tail = origcab ? max(strrchr(origcab, '/'), strrchr(origcab, '\\')) : NULL;
2080
2081   if ((cab = (char *) malloc(MAX_PATH))) {
2082     /* add the directory path from the original cabinet name */
2083     if (tail) {
2084       memcpy(cab, origcab, tail - origcab);
2085       cab[tail - origcab] = '\0';
2086     } else {
2087       /* default directory path of '.' */
2088       cab[0] = '.';
2089       cab[1] = '\0';
2090     }
2091
2092     do {
2093       TRACE("trying cab == %s", debugstr_a(cab));
2094
2095       /* we don't want null cabinet filenames */
2096       if (name[0] == '\0') {
2097         WARN("null cab name\n");
2098         break;
2099       }
2100
2101       /* if there is a directory component in the cabinet name,
2102        * look for that alone first
2103        */
2104       nextpart = strchr(name, '\\');
2105       if (nextpart) *nextpart = '\0';
2106
2107       found = SearchPathA(cab, name, NULL, MAX_PATH, nametmp, &filepart);
2108
2109       /* if the component was not found, look for it in the current dir */
2110       if (!found) {
2111         found = SearchPathA(".", name, NULL, MAX_PATH, nametmp, &filepart);
2112       }
2113       
2114       if (found) 
2115         TRACE("found: %s\n", debugstr_a(nametmp));
2116       else
2117         TRACE("not found.\n");
2118
2119       /* restore the real name and skip to the next directory component
2120        * or actual cabinet name
2121        */
2122       if (nextpart) *nextpart = '\\', name = &nextpart[1];
2123
2124       /* while there is another directory component, and while we
2125        * successfully found the current component
2126        */
2127     } while (nextpart && found);
2128
2129     /* if we found the cabinet, change the next cabinet's name.
2130      * otherwise, pretend nothing happened
2131      */
2132     if (found) {
2133       free((void *) *cabname);
2134       *cabname = cab;
2135       strncpy(cab, nametmp, found+1);
2136       TRACE("result: %s\n", debugstr_a(cab));
2137     } else {
2138       free((void *) cab);
2139       TRACE("result: nothing\n");
2140     }
2141   }
2142 }
2143
2144 /************************************************************************
2145  * process_files (internal)
2146  *
2147  * this does the tricky job of running through every file in the cabinet,
2148  * including spanning cabinets, and working out which file is in which
2149  * folder in which cabinet. It also throws out the duplicate file entries
2150  * that appear in spanning cabinets. There is memory leakage here because
2151  * those entries are not freed. See the XAD CAB client (function CAB_GetInfo
2152  * in CAB.c) for an implementation of this that correctly frees the discarded
2153  * file entries.
2154  */
2155 struct cab_file *process_files(struct cabinet *basecab) {
2156   struct cabinet *cab;
2157   struct cab_file *outfi = NULL, *linkfi = NULL, *nextfi, *fi, *cfi;
2158   struct cab_folder *fol, *firstfol, *lastfol = NULL, *predfol;
2159   int i, mergeok;
2160
2161   FIXME("(basecab == ^%p): Memory leak.\n", basecab);
2162
2163   for (cab = basecab; cab; cab = cab->nextcab) {
2164     /* firstfol = first folder in this cabinet */
2165     /* lastfol  = last folder in this cabinet */
2166     /* predfol  = last folder in previous cabinet (or NULL if first cabinet) */
2167     predfol = lastfol;
2168     firstfol = cab->folders;
2169     for (lastfol = firstfol; lastfol->next;) lastfol = lastfol->next;
2170     mergeok = 1;
2171
2172     for (fi = cab->files; fi; fi = nextfi) {
2173       i = fi->index;
2174       nextfi = fi->next;
2175
2176       if (i < cffileCONTINUED_FROM_PREV) {
2177         for (fol = firstfol; fol && i--; ) fol = fol->next;
2178         fi->folder = fol; /* NULL if an invalid folder index */
2179       }
2180       else {
2181         /* folder merging */
2182         if (i == cffileCONTINUED_TO_NEXT
2183         ||  i == cffileCONTINUED_PREV_AND_NEXT) {
2184           if (cab->nextcab && !lastfol->contfile) lastfol->contfile = fi;
2185         }
2186
2187         if (i == cffileCONTINUED_FROM_PREV
2188         ||  i == cffileCONTINUED_PREV_AND_NEXT) {
2189           /* these files are to be continued in yet another
2190            * cabinet, don't merge them in just yet */
2191           if (i == cffileCONTINUED_PREV_AND_NEXT) mergeok = 0;
2192
2193           /* only merge once per cabinet */
2194           if (predfol) {
2195             if ((cfi = predfol->contfile)
2196             && (cfi->offset == fi->offset)
2197             && (cfi->length == fi->length)
2198             && (strcmp(cfi->filename, fi->filename) == 0)
2199             && (predfol->comp_type == firstfol->comp_type)) {
2200               /* increase the number of splits */
2201               if ((i = ++(predfol->num_splits)) > CAB_SPLITMAX) {
2202                 mergeok = 0;
2203                 ERR("%s: internal error: CAB_SPLITMAX exceeded. please report this to wine-devel@winehq.org)\n",
2204                     debugstr_a(basecab->filename));
2205               }
2206               else {
2207                 /* copy information across from the merged folder */
2208                 predfol->offset[i] = firstfol->offset[0];
2209                 predfol->cab[i]    = firstfol->cab[0];
2210                 predfol->next      = firstfol->next;
2211                 predfol->contfile  = firstfol->contfile;
2212
2213                 if (firstfol == lastfol) lastfol = predfol;
2214                 firstfol = predfol;
2215                 predfol = NULL; /* don't merge again within this cabinet */
2216               }
2217             }
2218             else {
2219               /* if the folders won't merge, don't add their files */
2220               mergeok = 0;
2221             }
2222           }
2223
2224           if (mergeok) fi->folder = firstfol;
2225         }
2226       }
2227
2228       if (fi->folder) {
2229         if (linkfi) linkfi->next = fi; else outfi = fi;
2230         linkfi = fi;
2231       }
2232     } /* for (fi= .. */
2233   } /* for (cab= ...*/
2234
2235   return outfi;
2236 }
2237
2238 /****************************************************************
2239  * convertUTF (internal)
2240  *
2241  * translate UTF -> ASCII
2242  *
2243  * UTF translates two-byte unicode characters into 1, 2 or 3 bytes.
2244  * %000000000xxxxxxx -> %0xxxxxxx
2245  * %00000xxxxxyyyyyy -> %110xxxxx %10yyyyyy
2246  * %xxxxyyyyyyzzzzzz -> %1110xxxx %10yyyyyy %10zzzzzz
2247  *
2248  * Therefore, the inverse is as follows:
2249  * First char:
2250  *  0x00 - 0x7F = one byte char
2251  *  0x80 - 0xBF = invalid
2252  *  0xC0 - 0xDF = 2 byte char (next char only 0x80-0xBF is valid)
2253  *  0xE0 - 0xEF = 3 byte char (next 2 chars only 0x80-0xBF is valid)
2254  *  0xF0 - 0xFF = invalid
2255  * 
2256  * FIXME: use a winapi to do this
2257  */
2258 int convertUTF(cab_UBYTE *in) {
2259   cab_UBYTE c, *out = in, *end = in + strlen((char *) in) + 1;
2260   cab_ULONG x;
2261
2262   do {
2263     /* read unicode character */
2264     if ((c = *in++) < 0x80) x = c;
2265     else {
2266       if (c < 0xC0) return 0;
2267       else if (c < 0xE0) {
2268         x = (c & 0x1F) << 6;
2269         if ((c = *in++) < 0x80 || c > 0xBF) return 0; else x |= (c & 0x3F);
2270       }
2271       else if (c < 0xF0) {
2272         x = (c & 0xF) << 12;
2273         if ((c = *in++) < 0x80 || c > 0xBF) return 0; else x |= (c & 0x3F)<<6;
2274         if ((c = *in++) < 0x80 || c > 0xBF) return 0; else x |= (c & 0x3F);
2275       }
2276       else return 0;
2277     }
2278
2279     /* terrible unicode -> ASCII conversion */
2280     if (x > 127) x = '_';
2281
2282     if (in > end) return 0; /* just in case */
2283   } while ((*out++ = (cab_UBYTE) x));
2284   return 1;
2285 }
2286
2287 /****************************************************
2288  * NONEdecompress (internal)
2289  */
2290 int NONEdecompress(int inlen, int outlen, cab_decomp_state *decomp_state)
2291 {
2292   if (inlen != outlen) return DECR_ILLEGALDATA;
2293   memcpy(CAB(outbuf), CAB(inbuf), (size_t) inlen);
2294   return DECR_OK;
2295 }
2296
2297 /**************************************************
2298  * checksum (internal)
2299  */
2300 cab_ULONG checksum(cab_UBYTE *data, cab_UWORD bytes, cab_ULONG csum) {
2301   int len;
2302   cab_ULONG ul = 0;
2303
2304   for (len = bytes >> 2; len--; data += 4) {
2305     csum ^= ((data[0]) | (data[1]<<8) | (data[2]<<16) | (data[3]<<24));
2306   }
2307
2308   switch (bytes & 3) {
2309   case 3: ul |= *data++ << 16;
2310   case 2: ul |= *data++ <<  8;
2311   case 1: ul |= *data;
2312   }
2313   csum ^= ul;
2314
2315   return csum;
2316 }
2317
2318 /**********************************************************
2319  * decompress (internal)
2320  */
2321 int decompress(struct cab_file *fi, int savemode, int fix, cab_decomp_state *decomp_state)
2322 {
2323   cab_ULONG bytes = savemode ? fi->length : fi->offset - CAB(offset);
2324   struct cabinet *cab = CAB(current)->cab[CAB(split)];
2325   cab_UBYTE buf[cfdata_SIZEOF], *data;
2326   cab_UWORD inlen, len, outlen, cando;
2327   cab_ULONG cksum;
2328   cab_LONG err;
2329
2330   TRACE("(fi == ^%p, savemode == %d, fix == %d)\n", fi, savemode, fix);
2331
2332   while (bytes > 0) {
2333     /* cando = the max number of bytes we can do */
2334     cando = CAB(outlen);
2335     if (cando > bytes) cando = bytes;
2336
2337     /* if cando != 0 */
2338     if (cando && savemode)
2339       file_write(fi, CAB(outpos), cando);
2340
2341     CAB(outpos) += cando;
2342     CAB(outlen) -= cando;
2343     bytes -= cando; if (!bytes) break;
2344
2345     /* we only get here if we emptied the output buffer */
2346
2347     /* read data header + data */
2348     inlen = outlen = 0;
2349     while (outlen == 0) {
2350       /* read the block header, skip the reserved part */
2351       if (!cabinet_read(cab, buf, cfdata_SIZEOF)) return DECR_INPUT;
2352       cabinet_skip(cab, cab->block_resv);
2353
2354       /* we shouldn't get blocks over CAB_INPUTMAX in size */
2355       data = CAB(inbuf) + inlen;
2356       len = EndGetI16(buf+cfdata_CompressedSize);
2357       inlen += len;
2358       if (inlen > CAB_INPUTMAX) return DECR_INPUT;
2359       if (!cabinet_read(cab, data, len)) return DECR_INPUT;
2360
2361       /* clear two bytes after read-in data */
2362       data[len+1] = data[len+2] = 0;
2363
2364       /* perform checksum test on the block (if one is stored) */
2365       cksum = EndGetI32(buf+cfdata_CheckSum);
2366       if (cksum && cksum != checksum(buf+4, 4, checksum(data, len, 0))) {
2367         /* checksum is wrong */
2368         if (fix && ((fi->folder->comp_type & cffoldCOMPTYPE_MASK)
2369                     == cffoldCOMPTYPE_MSZIP))
2370         {
2371           WARN("%s: checksum failed\n", debugstr_a(fi->filename)); 
2372         }
2373         else {
2374           return DECR_CHECKSUM;
2375         }
2376       }
2377
2378       /* outlen=0 means this block was part of a split block */
2379       outlen = EndGetI16(buf+cfdata_UncompressedSize);
2380       if (outlen == 0) {
2381         cabinet_close(cab);
2382         cab = CAB(current)->cab[++CAB(split)];
2383         if (!cabinet_open(cab)) return DECR_INPUT;
2384         cabinet_seek(cab, CAB(current)->offset[CAB(split)]);
2385       }
2386     }
2387
2388     /* decompress block */
2389     if ((err = CAB(decompress)(inlen, outlen, decomp_state))) {
2390       if (fix && ((fi->folder->comp_type & cffoldCOMPTYPE_MASK)
2391                   == cffoldCOMPTYPE_MSZIP))
2392       {
2393         ERR("%s: failed decrunching block\n", debugstr_a(fi->filename)); 
2394       }
2395       else {
2396         return err;
2397       }
2398     }
2399     CAB(outlen) = outlen;
2400     CAB(outpos) = CAB(outbuf);
2401   }
2402
2403   return DECR_OK;
2404 }
2405
2406 /****************************************************************
2407  * extract_file (internal)
2408  *
2409  * workhorse to extract a particular file from a cab
2410  */
2411 void extract_file(struct cab_file *fi, int lower, int fix, LPCSTR dir, cab_decomp_state *decomp_state)
2412 {
2413   struct cab_folder *fol = fi->folder, *oldfol = CAB(current);
2414   cab_LONG err = DECR_OK;
2415
2416   TRACE("(fi == ^%p, lower == %d, fix == %d, dir == %s)\n", fi, lower, fix, debugstr_a(dir));
2417
2418   /* is a change of folder needed? do we need to reset the current folder? */
2419   if (fol != oldfol || fi->offset < CAB(offset)) {
2420     cab_UWORD comptype = fol->comp_type;
2421     int ct1 = comptype & cffoldCOMPTYPE_MASK;
2422     int ct2 = oldfol ? (oldfol->comp_type & cffoldCOMPTYPE_MASK) : 0;
2423
2424     /* if the archiver has changed, call the old archiver's free() function */
2425     if (ct1 != ct2) {
2426       switch (ct2) {
2427       case cffoldCOMPTYPE_LZX:
2428         if (LZX(window)) {
2429           free(LZX(window));
2430           LZX(window) = NULL;
2431         }
2432         break;
2433       case cffoldCOMPTYPE_QUANTUM:
2434         if (QTM(window)) {
2435           free(QTM(window));
2436           QTM(window) = NULL;
2437         }
2438         break;
2439       }
2440     }
2441
2442     switch (ct1) {
2443     case cffoldCOMPTYPE_NONE:
2444       CAB(decompress) = NONEdecompress;
2445       break;
2446
2447     case cffoldCOMPTYPE_MSZIP:
2448       CAB(decompress) = ZIPdecompress;
2449       break;
2450
2451     case cffoldCOMPTYPE_QUANTUM:
2452       CAB(decompress) = QTMdecompress;
2453       err = QTMinit((comptype >> 8) & 0x1f, (comptype >> 4) & 0xF, decomp_state);
2454       break;
2455
2456     case cffoldCOMPTYPE_LZX:
2457       CAB(decompress) = LZXdecompress;
2458       err = LZXinit((comptype >> 8) & 0x1f, decomp_state);
2459       break;
2460
2461     default:
2462       err = DECR_DATAFORMAT;
2463     }
2464     if (err) goto exit_handler;
2465
2466     /* initialisation OK, set current folder and reset offset */
2467     if (oldfol) cabinet_close(oldfol->cab[CAB(split)]);
2468     if (!cabinet_open(fol->cab[0])) goto exit_handler;
2469     cabinet_seek(fol->cab[0], fol->offset[0]);
2470     CAB(current) = fol;
2471     CAB(offset) = 0;
2472     CAB(outlen) = 0; /* discard existing block */
2473     CAB(split)  = 0;
2474   }
2475
2476   if (fi->offset > CAB(offset)) {
2477     /* decode bytes and send them to /dev/null */
2478     if ((err = decompress(fi, 0, fix, decomp_state))) goto exit_handler;
2479     CAB(offset) = fi->offset;
2480   }
2481   
2482   if (!file_open(fi, lower, dir)) return;
2483   err = decompress(fi, 1, fix, decomp_state);
2484   if (err) CAB(current) = NULL; else CAB(offset) += fi->length;
2485   file_close(fi);
2486
2487 exit_handler:
2488   if (err) {
2489     const char *errmsg;
2490     char *cabname;
2491     switch (err) {
2492     case DECR_NOMEMORY:
2493       errmsg = "out of memory!\n"; break;
2494     case DECR_ILLEGALDATA:
2495       errmsg = "%s: illegal or corrupt data\n"; break;
2496     case DECR_DATAFORMAT:
2497       errmsg = "%s: unsupported data format\n"; break;
2498     case DECR_CHECKSUM:
2499       errmsg = "%s: checksum error\n"; break;
2500     case DECR_INPUT:
2501       errmsg = "%s: input error\n"; break;
2502     case DECR_OUTPUT:
2503       errmsg = "%s: output error\n"; break;
2504     default:
2505       errmsg = "%s: unknown error (BUG)\n";
2506     }
2507
2508     if (CAB(current)) {
2509       cabname = (char *) (CAB(current)->cab[CAB(split)]->filename);
2510     }
2511     else {
2512       cabname = (char *) (fi->folder->cab[0]->filename);
2513     }
2514
2515     ERR(errmsg, cabname);
2516   }
2517 }
2518
2519 /*********************************************************
2520  * print_fileinfo (internal)
2521  */
2522 void print_fileinfo(struct cab_file *fi) {
2523   int d = fi->date, t = fi->time;
2524   char *fname = NULL;
2525
2526   if (fi->attribs & cffile_A_NAME_IS_UTF) {
2527     fname = malloc(strlen(fi->filename) + 1);
2528     if (fname) {
2529       strcpy(fname, fi->filename);
2530       convertUTF((cab_UBYTE *) fname);
2531     }
2532   }
2533
2534   TRACE("%9u | %02d.%02d.%04d %02d:%02d:%02d | %s\n",
2535     fi->length, 
2536     d & 0x1f, (d>>5) & 0xf, (d>>9) + 1980,
2537     t >> 11, (t>>5) & 0x3f, (t << 1) & 0x3e,
2538     fname ? fname : fi->filename
2539   );
2540
2541   if (fname) free(fname);
2542 }
2543
2544 /****************************************************************************
2545  * process_cabinet (internal) 
2546  *
2547  * called to simply "extract" a cabinet file.  Will find every cabinet file
2548  * in that file, search for every chained cabinet attached to those cabinets,
2549  * and will either extract the cabinets, or ? (call a callback?)
2550  *
2551  * PARAMS
2552  *   cabname [I] name of the cabinet file to extract
2553  *   dir     [I] directory to extract to
2554  *   fix     [I] attempt to process broken cabinets
2555  *   lower   [I] ? (lower case something or other?)
2556  *
2557  * RETURNS
2558  *   Success: TRUE
2559  *   Failure: FALSE
2560  */
2561 BOOL process_cabinet(LPCSTR cabname, LPCSTR dir, BOOL fix, BOOL lower)
2562 {
2563   struct cabinet *basecab, *cab, *cab1, *cab2;
2564   struct cab_file *filelist, *fi;
2565
2566   /* The first result of a search will be returned, and
2567    * the remaining results will be chained to it via the cab->next structure
2568    * member.
2569    */
2570   cab_UBYTE search_buf[CAB_SEARCH_SIZE];
2571
2572   cab_decomp_state decomp_state_local;
2573   cab_decomp_state *decomp_state = &decomp_state_local;
2574
2575   /* has the list-mode header been seen before? */
2576   int viewhdr = 0;
2577
2578   ZeroMemory(decomp_state, sizeof(cab_decomp_state));
2579
2580   TRACE("Extract %s\n", debugstr_a(cabname));
2581
2582   /* load the file requested */
2583   basecab = find_cabs_in_file(cabname, search_buf);
2584   if (!basecab) return FALSE;
2585
2586   /* iterate over all cabinets found in that file */
2587   for (cab = basecab; cab; cab=cab->next) {
2588
2589     /* bi-directionally load any spanning cabinets -- backwards */
2590     for (cab1 = cab; cab1->flags & cfheadPREV_CABINET; cab1 = cab1->prevcab) {
2591       TRACE("%s: extends backwards to %s (%s)\n", debugstr_a(cabname),
2592             debugstr_a(cab1->prevname), debugstr_a(cab1->previnfo));
2593       find_cabinet_file(&(cab1->prevname), cabname);
2594       if (!(cab1->prevcab = load_cab_offset(cab1->prevname, 0))) {
2595         ERR("%s: can't read previous cabinet %s\n", debugstr_a(cabname), debugstr_a(cab1->prevname));
2596         break;
2597       }
2598       cab1->prevcab->nextcab = cab1;
2599     }
2600
2601     /* bi-directionally load any spanning cabinets -- forwards */
2602     for (cab2 = cab; cab2->flags & cfheadNEXT_CABINET; cab2 = cab2->nextcab) {
2603       TRACE("%s: extends to %s (%s)\n", debugstr_a(cabname),
2604             debugstr_a(cab2->nextname), debugstr_a(cab2->nextinfo));
2605       find_cabinet_file(&(cab2->nextname), cabname);
2606       if (!(cab2->nextcab = load_cab_offset(cab2->nextname, 0))) {
2607         ERR("%s: can't read next cabinet %s\n", debugstr_a(cabname), debugstr_a(cab2->nextname));
2608         break;
2609       }
2610       cab2->nextcab->prevcab = cab2;
2611     }
2612
2613     filelist = process_files(cab1);
2614     CAB(current) = NULL;
2615
2616     if (!viewhdr) {
2617       TRACE("File size | Date       Time     | Name\n");
2618       TRACE("----------+---------------------+-------------\n");
2619       viewhdr = 1;
2620     }
2621     for (fi = filelist; fi; fi = fi->next)
2622         print_fileinfo(fi);
2623     TRACE("Beginning Extraction...\n");
2624     for (fi = filelist; fi; fi = fi->next) {
2625         TRACE("  extracting: %s\n", debugstr_a(fi->filename));
2626         extract_file(fi, lower, fix, dir, decomp_state);
2627     }
2628   }
2629
2630   TRACE("Finished processing cabinet.\n");
2631
2632   return TRUE;
2633 }