/*1* File Decompression Interface2*3* Copyright 2000-2002 Stuart Caie4* Copyright 2002 Patrik Stridvall5* Copyright 2003 Greg Turner6*7* This library is free software; you can redistribute it and/or8* modify it under the terms of the GNU Lesser General Public9* License as published by the Free Software Foundation; either10* version 2.1 of the License, or (at your option) any later version.11*12* This library is distributed in the hope that it will be useful,13* but WITHOUT ANY WARRANTY; without even the implied warranty of14* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU15* Lesser General Public License for more details.16*17* You should have received a copy of the GNU Lesser General Public18* License along with this library; if not, write to the Free Software19* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA20*21*22* This is a largely redundant reimplementation of the stuff in cabextract.c. It23* would be theoretically preferable to have only one, shared implementation, however24* there are semantic differences which may discourage efforts to unify the two. It25* should be possible, if awkward, to go back and reimplement cabextract.c using FDI.26* But this approach would be quite a bit less performant. Probably a better way27* would be to create a "library" of routines in cabextract.c which do the actual28* decompression, and have both fdi.c and cabextract share those routines. The rest29* of the code is not sufficiently similar to merit a shared implementation.30*31* The worst thing about this API is the bug. "The bug" is this: when you extract a32* cabinet, it /always/ informs you (via the hasnext field of PFDICABINETINFO), that33* there is no subsequent cabinet, even if there is one. wine faithfully reproduces34* this behavior.35*36* TODO:37*38* Wine does not implement the AFAIK undocumented "enumerate" callback during39* FDICopy. It is implemented in Windows and therefore worth investigating...40*41* Lots of pointers flying around here... am I leaking RAM?42*43* WTF is FDITruncate?44*45* Probably, I need to weed out some dead code-paths.46*47* Test unit(s).48*49* The fdintNEXT_CABINET callbacks are probably not working quite as they should.50* There are several FIXMEs in the source describing some of the deficiencies in51* some detail. Additionally, we do not do a very good job of returning the right52* error codes to this callback.53*54* FDICopy and fdi_decomp are incomprehensibly large; separating these into smaller55* functions would be nice.56*57* -gmt58*/5960#include <stdarg.h>61#include <stdio.h>62#include <sys/stat.h>63#include <fcntl.h>6465#include "windef.h"66#include "winbase.h"67#include "winerror.h"68#include "fdi.h"69#include "cabinet.h"7071#include "wine/debug.h"7273WINE_DEFAULT_DEBUG_CHANNEL(cabinet);7475THOSE_ZIP_CONSTS;7677struct fdi_file {78struct fdi_file *next; /* next file in sequence */79LPSTR filename; /* output name of file */80int fh; /* open file handle or NULL */81cab_ULONG length; /* uncompressed length of file */82cab_ULONG offset; /* uncompressed offset in folder */83cab_UWORD index; /* magic index number of folder */84cab_UWORD time, date, attribs; /* MS-DOS time/date/attributes */85BOOL oppressed; /* never to be processed */86};8788struct fdi_folder {89struct fdi_folder *next;90cab_off_t offset; /* offset to data blocks (32 bit) */91cab_UWORD comp_type; /* compression format/window size */92cab_ULONG comp_size; /* compressed size of folder */93cab_UBYTE num_splits; /* number of split blocks + 1 */94cab_UWORD num_blocks; /* total number of blocks */95};9697/*98* this structure fills the gaps between what is available in a PFDICABINETINFO99* vs what is needed by FDICopy. Memory allocated for these becomes the responsibility100* of the caller to free. Yes, I am aware that this is totally, utterly inelegant.101* To make things even more unnecessarily confusing, we now attach these to the102* fdi_decomp_state.103*/104typedef struct {105char *prevname, *previnfo;106char *nextname, *nextinfo;107BOOL hasnext; /* bug free indicator */108int folder_resv, header_resv;109cab_UBYTE block_resv;110} MORE_ISCAB_INFO, *PMORE_ISCAB_INFO;111112typedef struct113{114unsigned int magic;115PFNALLOC alloc;116PFNFREE free;117PFNOPEN open;118PFNREAD read;119PFNWRITE write;120PFNCLOSE close;121PFNSEEK seek;122PERF perf;123} FDI_Int;124125#define FDI_INT_MAGIC 0xfdfdfd05126127/*128* ugh, well, this ended up being pretty damn silly...129* now that I've conceded to build equivalent structures to struct cab.*,130* I should have just used those, or, better yet, unified the two... sue me.131* (Note to Microsoft: That's a joke. Please /don't/ actually sue me! -gmt).132* Nevertheless, I've come this far, it works, so I'm not gonna change it133* for now. This implementation has significant semantic differences anyhow.134*/135136typedef struct fdi_cds_fwd {137FDI_Int *fdi; /* the hfdi we are using */138INT_PTR filehf, cabhf; /* file handle we are using */139struct fdi_folder *current; /* current folder we're extracting from */140cab_ULONG offset; /* uncompressed offset within folder */141cab_UBYTE *outpos; /* (high level) start of data to use up */142cab_UWORD outlen; /* (high level) amount of data to use up */143int (*decompress)(int, int, struct fdi_cds_fwd *); /* chosen compress fn */144cab_UBYTE inbuf[CAB_INPUTMAX+2]; /* +2 for lzx bitbuffer overflows! */145cab_UBYTE outbuf[CAB_BLOCKMAX];146union {147struct ZIPstate zip;148struct QTMstate qtm;149struct LZXstate lzx;150} methods;151/* some temp variables for use during decompression */152cab_UBYTE q_length_base[27], q_length_extra[27], q_extra_bits[42];153cab_ULONG q_position_base[42];154cab_ULONG lzx_position_base[51];155cab_UBYTE extra_bits[51];156USHORT setID; /* Cabinet set ID */157USHORT iCabinet; /* Cabinet number in set (0 based) */158struct fdi_cds_fwd *decomp_cab;159MORE_ISCAB_INFO mii;160struct fdi_folder *firstfol;161struct fdi_file *firstfile;162struct fdi_cds_fwd *next;163} fdi_decomp_state;164165#define ZIPNEEDBITS(n) {while(k<(n)){cab_LONG c=*(ZIP(inpos)++);\166b|=((cab_ULONG)c)<<k;k+=8;}}167#define ZIPDUMPBITS(n) {b>>=(n);k-=(n);}168169/* endian-neutral reading of little-endian data */170#define EndGetI32(a) ((((a)[3])<<24)|(((a)[2])<<16)|(((a)[1])<<8)|((a)[0]))171#define EndGetI16(a) ((((a)[1])<<8)|((a)[0]))172173#define CAB(x) (decomp_state->x)174#define ZIP(x) (decomp_state->methods.zip.x)175#define QTM(x) (decomp_state->methods.qtm.x)176#define LZX(x) (decomp_state->methods.lzx.x)177#define DECR_OK (0)178#define DECR_DATAFORMAT (1)179#define DECR_ILLEGALDATA (2)180#define DECR_NOMEMORY (3)181#define DECR_CHECKSUM (4)182#define DECR_INPUT (5)183#define DECR_OUTPUT (6)184#define DECR_USERABORT (7)185186static void set_error( FDI_Int *fdi, int oper, int err )187{188fdi->perf->erfOper = oper;189fdi->perf->erfType = err;190fdi->perf->fError = TRUE;191if (err) SetLastError( err );192}193194static FDI_Int *get_fdi_ptr( HFDI hfdi )195{196FDI_Int *fdi= (FDI_Int *)hfdi;197198if (!fdi || fdi->magic != FDI_INT_MAGIC)199{200SetLastError( ERROR_INVALID_HANDLE );201return NULL;202}203return fdi;204}205206/****************************************************************207* QTMupdatemodel (internal)208*/209static void QTMupdatemodel(struct QTMmodel *model, int sym) {210struct QTMmodelsym temp;211int i, j;212213for (i = 0; i < sym; i++) model->syms[i].cumfreq += 8;214215if (model->syms[0].cumfreq > 3800) {216if (--model->shiftsleft) {217for (i = model->entries - 1; i >= 0; i--) {218/* -1, not -2; the 0 entry saves this */219model->syms[i].cumfreq >>= 1;220if (model->syms[i].cumfreq <= model->syms[i+1].cumfreq) {221model->syms[i].cumfreq = model->syms[i+1].cumfreq + 1;222}223}224}225else {226model->shiftsleft = 50;227for (i = 0; i < model->entries ; i++) {228/* no -1, want to include the 0 entry */229/* this converts cumfreqs into frequencies, then shifts right */230model->syms[i].cumfreq -= model->syms[i+1].cumfreq;231model->syms[i].cumfreq++; /* avoid losing things entirely */232model->syms[i].cumfreq >>= 1;233}234235/* now sort by frequencies, decreasing order -- this must be an236* inplace selection sort, or a sort with the same (in)stability237* characteristics238*/239for (i = 0; i < model->entries - 1; i++) {240for (j = i + 1; j < model->entries; j++) {241if (model->syms[i].cumfreq < model->syms[j].cumfreq) {242temp = model->syms[i];243model->syms[i] = model->syms[j];244model->syms[j] = temp;245}246}247}248249/* then convert frequencies back to cumfreq */250for (i = model->entries - 1; i >= 0; i--) {251model->syms[i].cumfreq += model->syms[i+1].cumfreq;252}253/* then update the other part of the table */254for (i = 0; i < model->entries; i++) {255model->tabloc[model->syms[i].sym] = i;256}257}258}259}260261/*************************************************************************262* make_decode_table (internal)263*264* This function was coded by David Tritscher. It builds a fast huffman265* decoding table out of just a canonical huffman code lengths table.266*267* PARAMS268* nsyms: total number of symbols in this huffman tree.269* nbits: any symbols with a code length of nbits or less can be decoded270* in one lookup of the table.271* length: A table to get code lengths from [0 to syms-1]272* table: The table to fill up with decoded symbols and pointers.273*274* RETURNS275* OK: 0276* error: 1277*/278static int make_decode_table(cab_ULONG nsyms, cab_ULONG nbits,279const cab_UBYTE *length, cab_UWORD *table) {280register cab_UWORD sym;281register cab_ULONG leaf;282register cab_UBYTE bit_num = 1;283cab_ULONG fill;284cab_ULONG pos = 0; /* the current position in the decode table */285cab_ULONG table_mask = 1 << nbits;286cab_ULONG bit_mask = table_mask >> 1; /* don't do 0 length codes */287cab_ULONG next_symbol = bit_mask; /* base of allocation for long codes */288289/* fill entries for codes short enough for a direct mapping */290while (bit_num <= nbits) {291for (sym = 0; sym < nsyms; sym++) {292if (length[sym] == bit_num) {293leaf = pos;294295if((pos += bit_mask) > table_mask) return 1; /* table overrun */296297/* fill all possible lookups of this symbol with the symbol itself */298fill = bit_mask;299while (fill-- > 0) table[leaf++] = sym;300}301}302bit_mask >>= 1;303bit_num++;304}305306/* if there are any codes longer than nbits */307if (pos != table_mask) {308/* clear the remainder of the table */309for (sym = pos; sym < table_mask; sym++) table[sym] = 0;310311/* give ourselves room for codes to grow by up to 16 more bits */312pos <<= 16;313table_mask <<= 16;314bit_mask = 1 << 15;315316while (bit_num <= 16) {317for (sym = 0; sym < nsyms; sym++) {318if (length[sym] == bit_num) {319leaf = pos >> 16;320for (fill = 0; fill < bit_num - nbits; fill++) {321/* if this path hasn't been taken yet, 'allocate' two entries */322if (table[leaf] == 0) {323table[(next_symbol << 1)] = 0;324table[(next_symbol << 1) + 1] = 0;325table[leaf] = next_symbol++;326}327/* follow the path and select either left or right for next bit */328leaf = table[leaf] << 1;329if ((pos >> (15-fill)) & 1) leaf++;330}331table[leaf] = sym;332333if ((pos += bit_mask) > table_mask) return 1; /* table overflow */334}335}336bit_mask >>= 1;337bit_num++;338}339}340341/* full table? */342if (pos == table_mask) return 0;343344/* either erroneous table, or all elements are 0 - let's find out. */345for (sym = 0; sym < nsyms; sym++) if (length[sym]) return 1;346return 0;347}348349/*************************************************************************350* checksum (internal)351*/352static cab_ULONG checksum(const cab_UBYTE *data, cab_UWORD bytes, cab_ULONG csum) {353int len;354cab_ULONG ul = 0;355356for (len = bytes >> 2; len--; data += 4) {357csum ^= ((data[0]) | (data[1]<<8) | (data[2]<<16) | (data[3]<<24));358}359360switch (bytes & 3) {361case 3: ul |= *data++ << 16;362/* fall through */363case 2: ul |= *data++ << 8;364/* fall through */365case 1: ul |= *data;366}367csum ^= ul;368369return csum;370}371372/***********************************************************************373* FDICreate (CABINET.20)374*375* Provided with several callbacks (all of them are mandatory),376* returns a handle which can be used to perform operations377* on cabinet files.378*379* PARAMS380* pfnalloc [I] A pointer to a function which allocates ram. Uses381* the same interface as malloc.382* pfnfree [I] A pointer to a function which frees ram. Uses the383* same interface as free.384* pfnopen [I] A pointer to a function which opens a file. Uses385* the same interface as _open.386* pfnread [I] A pointer to a function which reads from a file into387* a caller-provided buffer. Uses the same interface388* as _read389* pfnwrite [I] A pointer to a function which writes to a file from390* a caller-provided buffer. Uses the same interface391* as _write.392* pfnclose [I] A pointer to a function which closes a file handle.393* Uses the same interface as _close.394* pfnseek [I] A pointer to a function which seeks in a file.395* Uses the same interface as _lseek.396* cpuType [I] The type of CPU; ignored in wine (recommended value:397* cpuUNKNOWN, aka -1).398* perf [IO] A pointer to an ERF structure. When FDICreate399* returns an error condition, error information may400* be found here as well as from GetLastError.401*402* RETURNS403* On success, returns an FDI handle of type HFDI.404* On failure, the NULL file handle is returned. Error405* info can be retrieved from perf.406*407* INCLUDES408* fdi.h409*410*/411HFDI __cdecl FDICreate(412PFNALLOC pfnalloc,413PFNFREE pfnfree,414PFNOPEN pfnopen,415PFNREAD pfnread,416PFNWRITE pfnwrite,417PFNCLOSE pfnclose,418PFNSEEK pfnseek,419int cpuType,420PERF perf)421{422FDI_Int *fdi;423424TRACE("(pfnalloc == ^%p, pfnfree == ^%p, pfnopen == ^%p, pfnread == ^%p, pfnwrite == ^%p, "425"pfnclose == ^%p, pfnseek == ^%p, cpuType == %d, perf == ^%p)\n",426pfnalloc, pfnfree, pfnopen, pfnread, pfnwrite, pfnclose, pfnseek,427cpuType, perf);428429if ((!pfnalloc) || (!pfnfree)) {430perf->erfOper = FDIERROR_NONE;431perf->erfType = ERROR_BAD_ARGUMENTS;432perf->fError = TRUE;433434SetLastError(ERROR_BAD_ARGUMENTS);435return NULL;436}437438if (!((fdi = pfnalloc(sizeof(FDI_Int))))) {439perf->erfOper = FDIERROR_ALLOC_FAIL;440perf->erfType = 0;441perf->fError = TRUE;442return NULL;443}444445fdi->magic = FDI_INT_MAGIC;446fdi->alloc = pfnalloc;447fdi->free = pfnfree;448fdi->open = pfnopen;449fdi->read = pfnread;450fdi->write = pfnwrite;451fdi->close = pfnclose;452fdi->seek = pfnseek;453/* no-brainer: we ignore the cpu type; this is only used454for the 16-bit versions in Windows anyhow... */455fdi->perf = perf;456457return (HFDI)fdi;458}459460/*******************************************************************461* FDI_getoffset (internal)462*463* returns the file pointer position of a file handle.464*/465static LONG FDI_getoffset(FDI_Int *fdi, INT_PTR hf)466{467return fdi->seek(hf, 0, SEEK_CUR);468}469470/**********************************************************************471* FDI_read_string (internal)472*473* allocate and read an arbitrarily long string from the cabinet474*/475static char *FDI_read_string(FDI_Int *fdi, INT_PTR hf, long cabsize)476{477size_t len=256,478base = FDI_getoffset(fdi, hf),479maxlen = cabsize - base;480BOOL ok = FALSE;481unsigned int i;482cab_UBYTE *buf = NULL;483484TRACE("(fdi == %p, hf == %Id, cabsize == %ld)\n", fdi, hf, cabsize);485486do {487if (len > maxlen) len = maxlen;488if (!(buf = fdi->alloc(len))) break;489if (!fdi->read(hf, buf, len)) break;490491/* search for a null terminator in what we've just read */492for (i=0; i < len; i++) {493if (!buf[i]) {ok=TRUE; break;}494}495496if (!ok) {497if (len == maxlen) {498ERR("cabinet is truncated\n");499break;500}501/* The buffer is too small for the string. Reset the file to the point502* where we started, free the buffer and increase the size for the next try503*/504fdi->seek(hf, base, SEEK_SET);505fdi->free(buf);506buf = NULL;507len *= 2;508}509} while (!ok);510511if (!ok) {512if (buf)513fdi->free(buf);514else515ERR("out of memory!\n");516return NULL;517}518519/* otherwise, set the stream to just after the string and return */520fdi->seek(hf, base + strlen((char *)buf) + 1, SEEK_SET);521522return (char *) buf;523}524525/******************************************************************526* FDI_read_entries (internal)527*528* process the cabinet header in the style of FDIIsCabinet, but529* without the sanity checks (and bug)530*/531static BOOL FDI_read_entries(532FDI_Int *fdi,533INT_PTR hf,534PFDICABINETINFO pfdici,535PMORE_ISCAB_INFO pmii)536{537int num_folders, num_files, header_resv, folder_resv = 0;538LONG cabsize;539USHORT setid, cabidx, flags;540cab_UBYTE buf[64], block_resv;541char *prevname = NULL, *previnfo = NULL, *nextname = NULL, *nextinfo = NULL;542543TRACE("(fdi == ^%p, hf == %Id, pfdici == ^%p)\n", fdi, hf, pfdici);544545/* read in the CFHEADER */546if (fdi->read(hf, buf, cfhead_SIZEOF) != cfhead_SIZEOF) {547if (pmii) set_error( fdi, FDIERROR_NOT_A_CABINET, 0 );548return FALSE;549}550551/* check basic MSCF signature */552if (EndGetI32(buf+cfhead_Signature) != 0x4643534d) {553if (pmii) set_error( fdi, FDIERROR_NOT_A_CABINET, 0 );554return FALSE;555}556557/* get the cabinet size */558cabsize = EndGetI32(buf+cfhead_CabinetSize);559560/* get the number of folders */561num_folders = EndGetI16(buf+cfhead_NumFolders);562563/* get the number of files */564num_files = EndGetI16(buf+cfhead_NumFiles);565566/* setid */567setid = EndGetI16(buf+cfhead_SetID);568569/* cabinet (set) index */570cabidx = EndGetI16(buf+cfhead_CabinetIndex);571572/* check the header revision */573if ((buf[cfhead_MajorVersion] > 1) ||574(buf[cfhead_MajorVersion] == 1 && buf[cfhead_MinorVersion] > 3))575{576WARN("cabinet format version > 1.3\n");577if (pmii) set_error( fdi, FDIERROR_UNKNOWN_CABINET_VERSION, 0 /* ? */ );578return FALSE;579}580581/* pull the flags out */582flags = EndGetI16(buf+cfhead_Flags);583584/* read the reserved-sizes part of header, if present */585if (flags & cfheadRESERVE_PRESENT) {586if (fdi->read(hf, buf, cfheadext_SIZEOF) != cfheadext_SIZEOF) {587ERR("bunk reserve-sizes?\n");588if (pmii) set_error( fdi, FDIERROR_CORRUPT_CABINET, 0 /* ? */ );589return FALSE;590}591592header_resv = EndGetI16(buf+cfheadext_HeaderReserved);593if (pmii) pmii->header_resv = header_resv;594folder_resv = buf[cfheadext_FolderReserved];595if (pmii) pmii->folder_resv = folder_resv;596block_resv = buf[cfheadext_DataReserved];597if (pmii) pmii->block_resv = block_resv;598599if (header_resv > 60000) {600WARN("WARNING; header reserved space > 60000\n");601}602603/* skip the reserved header */604if ((header_resv) && (fdi->seek(hf, header_resv, SEEK_CUR) == -1)) {605ERR("seek failure: header_resv\n");606if (pmii) set_error( fdi, FDIERROR_CORRUPT_CABINET, 0 /* ? */ );607return FALSE;608}609}610611if (flags & cfheadPREV_CABINET) {612prevname = FDI_read_string(fdi, hf, cabsize);613if (!prevname) {614if (pmii) set_error( fdi, FDIERROR_CORRUPT_CABINET, 0 /* ? */ );615return FALSE;616} else617if (pmii)618pmii->prevname = prevname;619else620fdi->free(prevname);621previnfo = FDI_read_string(fdi, hf, cabsize);622if (previnfo) {623if (pmii)624pmii->previnfo = previnfo;625else626fdi->free(previnfo);627}628}629630if (flags & cfheadNEXT_CABINET) {631if (pmii)632pmii->hasnext = TRUE;633nextname = FDI_read_string(fdi, hf, cabsize);634if (!nextname) {635if ((flags & cfheadPREV_CABINET) && pmii) {636if (pmii->prevname) fdi->free(prevname);637if (pmii->previnfo) fdi->free(previnfo);638}639set_error( fdi, FDIERROR_CORRUPT_CABINET, 0 /* ? */ );640return FALSE;641} else642if (pmii)643pmii->nextname = nextname;644else645fdi->free(nextname);646nextinfo = FDI_read_string(fdi, hf, cabsize);647if (nextinfo) {648if (pmii)649pmii->nextinfo = nextinfo;650else651fdi->free(nextinfo);652}653}654655/* we could process the whole cabinet searching for problems;656instead lets stop here. Now let's fill out the paperwork */657pfdici->cbCabinet = cabsize;658pfdici->cFolders = num_folders;659pfdici->cFiles = num_files;660pfdici->setID = setid;661pfdici->iCabinet = cabidx;662pfdici->fReserve = (flags & cfheadRESERVE_PRESENT) != 0;663pfdici->hasprev = (flags & cfheadPREV_CABINET) != 0;664pfdici->hasnext = (flags & cfheadNEXT_CABINET) != 0;665return TRUE;666}667668/***********************************************************************669* FDIIsCabinet (CABINET.21)670*671* Informs the caller as to whether or not the provided file handle is672* really a cabinet or not, filling out the provided PFDICABINETINFO673* structure with information about the cabinet. Brief explanations of674* the elements of this structure are available as comments accompanying675* its definition in wine's include/fdi.h.676*677* PARAMS678* hfdi [I] An HFDI from FDICreate679* hf [I] The file handle about which the caller inquires680* pfdici [IO] Pointer to a PFDICABINETINFO structure which will681* be filled out with information about the cabinet682* file indicated by hf if, indeed, it is determined683* to be a cabinet.684*685* RETURNS686* TRUE if the file is a cabinet. The info pointed to by pfdici will687* be provided.688* FALSE if the file is not a cabinet, or if an error was encountered689* while processing the cabinet. The PERF structure provided to690* FDICreate can be queried for more error information.691*692* INCLUDES693* fdi.c694*/695BOOL __cdecl FDIIsCabinet(HFDI hfdi, INT_PTR hf, PFDICABINETINFO pfdici)696{697BOOL rv;698FDI_Int *fdi = get_fdi_ptr( hfdi );699700TRACE("(hfdi == ^%p, hf == ^%Id, pfdici == ^%p)\n", hfdi, hf, pfdici);701702if (!fdi) return FALSE;703704if (!pfdici) {705SetLastError(ERROR_BAD_ARGUMENTS);706return FALSE;707}708rv = FDI_read_entries(fdi, hf, pfdici, NULL);709710if (rv)711pfdici->hasnext = FALSE; /* yuck. duplicate apparent cabinet.dll bug */712713return rv;714}715716/******************************************************************717* QTMfdi_initmodel (internal)718*719* Initialize a model which decodes symbols from [s] to [s]+[n]-1720*/721static void QTMfdi_initmodel(struct QTMmodel *m, struct QTMmodelsym *sym, int n, int s) {722int i;723m->shiftsleft = 4;724m->entries = n;725m->syms = sym;726memset(m->tabloc, 0xFF, sizeof(m->tabloc)); /* clear out look-up table */727for (i = 0; i < n; i++) {728m->tabloc[i+s] = i; /* set up a look-up entry for symbol */729m->syms[i].sym = i+s; /* actual symbol */730m->syms[i].cumfreq = n-i; /* current frequency of that symbol */731}732m->syms[n].cumfreq = 0;733}734735/******************************************************************736* QTMfdi_init (internal)737*/738static int QTMfdi_init(int window, int level, fdi_decomp_state *decomp_state) {739unsigned int wndsize = 1 << window;740int msz = window * 2, i;741cab_ULONG j;742743/* QTM supports window sizes of 2^10 (1Kb) through 2^21 (2Mb) */744/* if a previously allocated window is big enough, keep it */745if (window < 10 || window > 21) return DECR_DATAFORMAT;746if (QTM(actual_size) < wndsize) {747if (QTM(window)) CAB(fdi)->free(QTM(window));748QTM(window) = NULL;749}750if (!QTM(window)) {751if (!(QTM(window) = CAB(fdi)->alloc(wndsize))) return DECR_NOMEMORY;752QTM(actual_size) = wndsize;753}754QTM(window_size) = wndsize;755QTM(window_posn) = 0;756757/* initialize static slot/extrabits tables */758for (i = 0, j = 0; i < 27; i++) {759CAB(q_length_extra)[i] = (i == 26) ? 0 : (i < 2 ? 0 : i - 2) >> 2;760CAB(q_length_base)[i] = j; j += 1 << ((i == 26) ? 5 : CAB(q_length_extra)[i]);761}762for (i = 0, j = 0; i < 42; i++) {763CAB(q_extra_bits)[i] = (i < 2 ? 0 : i-2) >> 1;764CAB(q_position_base)[i] = j; j += 1 << CAB(q_extra_bits)[i];765}766767/* initialize arithmetic coding models */768769QTMfdi_initmodel(&QTM(model7), QTM(m7sym), 7, 0);770771QTMfdi_initmodel(&QTM(model00), QTM(m00sym), 0x40, 0x00);772QTMfdi_initmodel(&QTM(model40), QTM(m40sym), 0x40, 0x40);773QTMfdi_initmodel(&QTM(model80), QTM(m80sym), 0x40, 0x80);774QTMfdi_initmodel(&QTM(modelC0), QTM(mC0sym), 0x40, 0xC0);775776/* model 4 depends on table size, ranges from 20 to 24 */777QTMfdi_initmodel(&QTM(model4), QTM(m4sym), (msz < 24) ? msz : 24, 0);778/* model 5 depends on table size, ranges from 20 to 36 */779QTMfdi_initmodel(&QTM(model5), QTM(m5sym), (msz < 36) ? msz : 36, 0);780/* model 6pos depends on table size, ranges from 20 to 42 */781QTMfdi_initmodel(&QTM(model6pos), QTM(m6psym), msz, 0);782QTMfdi_initmodel(&QTM(model6len), QTM(m6lsym), 27, 0);783784return DECR_OK;785}786787/************************************************************788* LZXfdi_init (internal)789*/790static int LZXfdi_init(int window, fdi_decomp_state *decomp_state) {791static const cab_UBYTE bits[] =792{ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,7937, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14,79415, 15, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,79517, 17, 17};796static const cab_ULONG base[] =797{ 0, 1, 2, 3, 4, 6, 8, 12,79816, 24, 32, 48, 64, 96, 128, 192,799256, 384, 512, 768, 1024, 1536, 2048, 3072,8004096, 6144, 8192, 12288, 16384, 24576, 32768, 49152,80165536, 98304, 131072, 196608, 262144, 393216, 524288, 655360,802786432, 917504, 1048576, 1179648, 1310720, 1441792, 1572864, 1703936,8031835008, 1966080, 2097152};804cab_ULONG wndsize = 1 << window;805int posn_slots;806807/* LZX supports window sizes of 2^15 (32Kb) through 2^21 (2Mb) */808/* if a previously allocated window is big enough, keep it */809if (window < 15 || window > 21) return DECR_DATAFORMAT;810if (LZX(actual_size) < wndsize) {811if (LZX(window)) CAB(fdi)->free(LZX(window));812LZX(window) = NULL;813}814if (!LZX(window)) {815if (!(LZX(window) = CAB(fdi)->alloc(wndsize))) return DECR_NOMEMORY;816LZX(actual_size) = wndsize;817}818LZX(window_size) = wndsize;819820/* initialize static tables */821memcpy(CAB(extra_bits), bits, sizeof(bits));822memcpy(CAB(lzx_position_base), base, sizeof(base));823824/* calculate required position slots */825if (window == 20) posn_slots = 42;826else if (window == 21) posn_slots = 50;827else posn_slots = window << 1;828829/*posn_slots=i=0; while (i < wndsize) i += 1 << CAB(extra_bits)[posn_slots++]; */830831LZX(R0) = LZX(R1) = LZX(R2) = 1;832LZX(main_elements) = LZX_NUM_CHARS + (posn_slots << 3);833LZX(header_read) = 0;834LZX(frames_read) = 0;835LZX(block_remaining) = 0;836LZX(block_type) = LZX_BLOCKTYPE_INVALID;837LZX(intel_curpos) = 0;838LZX(intel_started) = 0;839LZX(window_posn) = 0;840841/* initialize tables to 0 (because deltas will be applied to them) */842memset(LZX(MAINTREE_len), 0, sizeof(LZX(MAINTREE_len)));843memset(LZX(LENGTH_len), 0, sizeof(LZX(LENGTH_len)));844845return DECR_OK;846}847848/****************************************************849* NONEfdi_decomp(internal)850*/851static int NONEfdi_decomp(int inlen, int outlen, fdi_decomp_state *decomp_state)852{853if (inlen != outlen) return DECR_ILLEGALDATA;854if (outlen > CAB_BLOCKMAX) return DECR_DATAFORMAT;855memcpy(CAB(outbuf), CAB(inbuf), (size_t) inlen);856return DECR_OK;857}858859/********************************************************860* Ziphuft_free (internal)861*/862static void fdi_Ziphuft_free(FDI_Int *fdi, struct Ziphuft *t)863{864register struct Ziphuft *p, *q;865866/* Go through linked list, freeing from the allocated (t[-1]) address. */867p = t;868while (p != NULL)869{870q = (--p)->v.t;871fdi->free(p);872p = q;873}874}875876/*********************************************************877* fdi_Ziphuft_build (internal)878*/879static cab_LONG fdi_Ziphuft_build(cab_ULONG *b, cab_ULONG n, cab_ULONG s, const cab_UWORD *d, const cab_UWORD *e,880struct Ziphuft **t, cab_LONG *m, fdi_decomp_state *decomp_state)881{882cab_ULONG a; /* counter for codes of length k */883cab_ULONG el; /* length of EOB code (value 256) */884cab_ULONG f; /* i repeats in table every f entries */885cab_LONG g; /* maximum code length */886cab_LONG h; /* table level */887register cab_ULONG i; /* counter, current code */888register cab_ULONG j; /* counter */889register cab_LONG k; /* number of bits in current code */890cab_LONG *l; /* stack of bits per table */891register cab_ULONG *p; /* pointer into ZIP(c)[],ZIP(b)[],ZIP(v)[] */892register struct Ziphuft *q; /* points to current table */893struct Ziphuft r; /* table entry for structure assignment */894register cab_LONG w; /* bits before this table == (l * h) */895cab_ULONG *xp; /* pointer into x */896cab_LONG y; /* number of dummy codes added */897cab_ULONG z; /* number of entries in current table */898899l = ZIP(lx)+1;900901/* Generate counts for each bit length */902el = n > 256 ? b[256] : ZIPBMAX; /* set length of EOB code, if any */903904for(i = 0; i < ZIPBMAX+1; ++i)905ZIP(c)[i] = 0;906p = b; i = n;907do908{909ZIP(c)[*p]++; p++; /* assume all entries <= ZIPBMAX */910} while (--i);911if (ZIP(c)[0] == n) /* null input--all zero length codes */912{913*t = NULL;914*m = 0;915return 0;916}917918/* Find minimum and maximum length, bound *m by those */919for (j = 1; j <= ZIPBMAX; j++)920if (ZIP(c)[j])921break;922k = j; /* minimum code length */923if ((cab_ULONG)*m < j)924*m = j;925for (i = ZIPBMAX; i; i--)926if (ZIP(c)[i])927break;928g = i; /* maximum code length */929if ((cab_ULONG)*m > i)930*m = i;931932/* Adjust last length count to fill out codes, if needed */933for (y = 1 << j; j < i; j++, y <<= 1)934if ((y -= ZIP(c)[j]) < 0)935return 2; /* bad input: more codes than bits */936if ((y -= ZIP(c)[i]) < 0)937return 2;938ZIP(c)[i] += y;939940/* Generate starting offsets LONGo the value table for each length */941ZIP(x)[1] = j = 0;942p = ZIP(c) + 1; xp = ZIP(x) + 2;943while (--i)944{ /* note that i == g from above */945*xp++ = (j += *p++);946}947948/* Make a table of values in order of bit lengths */949p = b; i = 0;950do{951if ((j = *p++) != 0)952ZIP(v)[ZIP(x)[j]++] = i;953} while (++i < n);954955956/* Generate the Huffman codes and for each, make the table entries */957ZIP(x)[0] = i = 0; /* first Huffman code is zero */958p = ZIP(v); /* grab values in bit order */959h = -1; /* no tables yet--level -1 */960w = l[-1] = 0; /* no bits decoded yet */961ZIP(u)[0] = NULL; /* just to keep compilers happy */962q = NULL; /* ditto */963z = 0; /* ditto */964965/* go through the bit lengths (k already is bits in shortest code) */966for (; k <= g; k++)967{968a = ZIP(c)[k];969while (a--)970{971/* here i is the Huffman code of length k bits for value *p */972/* make tables up to required level */973while (k > w + l[h])974{975w += l[h++]; /* add bits already decoded */976977/* compute minimum size table less than or equal to *m bits */978if ((z = g - w) > (cab_ULONG)*m) /* upper limit */979z = *m;980if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */981{ /* too few codes for k-w bit table */982f -= a + 1; /* deduct codes from patterns left */983xp = ZIP(c) + k;984while (++j < z) /* try smaller tables up to z bits */985{986if ((f <<= 1) <= *++xp)987break; /* enough codes to use up j bits */988f -= *xp; /* else deduct codes from patterns */989}990}991if ((cab_ULONG)w + j > el && (cab_ULONG)w < el)992j = el - w; /* make EOB code end at table */993z = 1 << j; /* table entries for j-bit table */994l[h] = j; /* set table size in stack */995996/* allocate and link in new table */997if (!(q = CAB(fdi)->alloc((z + 1)*sizeof(struct Ziphuft))))998{999if(h)1000fdi_Ziphuft_free(CAB(fdi), ZIP(u)[0]);1001return 3; /* not enough memory */1002}1003*t = q + 1; /* link to list for Ziphuft_free() */1004*(t = &(q->v.t)) = NULL;1005ZIP(u)[h] = ++q; /* table starts after link */10061007/* connect to last table, if there is one */1008if (h)1009{1010ZIP(x)[h] = i; /* save pattern for backing up */1011r.b = (cab_UBYTE)l[h-1]; /* bits to dump before this table */1012r.e = (cab_UBYTE)(16 + j); /* bits in this table */1013r.v.t = q; /* pointer to this table */1014j = (i & ((1 << w) - 1)) >> (w - l[h-1]);1015ZIP(u)[h-1][j] = r; /* connect to last table */1016}1017}10181019/* set up table entry in r */1020r.b = (cab_UBYTE)(k - w);1021if (p >= ZIP(v) + n)1022r.e = 99; /* out of values--invalid code */1023else if (*p < s)1024{1025r.e = (cab_UBYTE)(*p < 256 ? 16 : 15); /* 256 is end-of-block code */1026r.v.n = *p++; /* simple code is just the value */1027}1028else1029{1030r.e = (cab_UBYTE)e[*p - s]; /* non-simple--look up in lists */1031r.v.n = d[*p++ - s];1032}10331034/* fill code-like entries with r */1035f = 1 << (k - w);1036for (j = i >> w; j < z; j += f)1037q[j] = r;10381039/* backwards increment the k-bit code i */1040for (j = 1 << (k - 1); i & j; j >>= 1)1041i ^= j;1042i ^= j;10431044/* backup over finished tables */1045while ((i & ((1 << w) - 1)) != ZIP(x)[h])1046w -= l[--h]; /* don't need to update q */1047}1048}10491050/* return actual size of base table */1051*m = l[0];10521053/* Return true (1) if we were given an incomplete table */1054return y != 0 && g != 1;1055}10561057/*********************************************************1058* fdi_Zipinflate_codes (internal)1059*/1060static cab_LONG fdi_Zipinflate_codes(const struct Ziphuft *tl, const struct Ziphuft *td,1061cab_LONG bl, cab_LONG bd, fdi_decomp_state *decomp_state)1062{1063register cab_ULONG e; /* table entry flag/number of extra bits */1064cab_ULONG n, d; /* length and index for copy */1065cab_ULONG w; /* current window position */1066const struct Ziphuft *t; /* pointer to table entry */1067cab_ULONG ml, md; /* masks for bl and bd bits */1068register cab_ULONG b; /* bit buffer */1069register cab_ULONG k; /* number of bits in bit buffer */10701071/* make local copies of globals */1072b = ZIP(bb); /* initialize bit buffer */1073k = ZIP(bk);1074w = ZIP(window_posn); /* initialize window position */10751076/* inflate the coded data */1077ml = Zipmask[bl]; /* precompute masks for speed */1078md = Zipmask[bd];10791080for(;;)1081{1082ZIPNEEDBITS((cab_ULONG)bl)1083if((e = (t = tl + (b & ml))->e) > 16)1084do1085{1086if (e == 99)1087return 1;1088ZIPDUMPBITS(t->b)1089e -= 16;1090ZIPNEEDBITS(e)1091} while ((e = (t = t->v.t + (b & Zipmask[e]))->e) > 16);1092ZIPDUMPBITS(t->b)1093if (e == 16) /* then it's a literal */1094CAB(outbuf)[w++] = (cab_UBYTE)t->v.n;1095else /* it's an EOB or a length */1096{1097/* exit if end of block */1098if(e == 15)1099break;11001101/* get length of block to copy */1102ZIPNEEDBITS(e)1103n = t->v.n + (b & Zipmask[e]);1104ZIPDUMPBITS(e);11051106/* decode distance of block to copy */1107ZIPNEEDBITS((cab_ULONG)bd)1108if ((e = (t = td + (b & md))->e) > 16)1109do {1110if (e == 99)1111return 1;1112ZIPDUMPBITS(t->b)1113e -= 16;1114ZIPNEEDBITS(e)1115} while ((e = (t = t->v.t + (b & Zipmask[e]))->e) > 16);1116ZIPDUMPBITS(t->b)1117ZIPNEEDBITS(e)1118d = w - t->v.n - (b & Zipmask[e]);1119ZIPDUMPBITS(e)1120do1121{1122d &= ZIPWSIZE - 1;1123e = ZIPWSIZE - max(d, w);1124e = min(e, n);1125n -= e;1126do1127{1128CAB(outbuf)[w++] = CAB(outbuf)[d++];1129} while (--e);1130} while (n);1131}1132}11331134/* restore the globals from the locals */1135ZIP(window_posn) = w; /* restore global window pointer */1136ZIP(bb) = b; /* restore global bit buffer */1137ZIP(bk) = k;11381139/* done */1140return 0;1141}11421143/***********************************************************1144* Zipinflate_stored (internal)1145*/1146static cab_LONG fdi_Zipinflate_stored(fdi_decomp_state *decomp_state)1147/* "decompress" an inflated type 0 (stored) block. */1148{1149cab_ULONG n; /* number of bytes in block */1150cab_ULONG w; /* current window position */1151register cab_ULONG b; /* bit buffer */1152register cab_ULONG k; /* number of bits in bit buffer */11531154/* make local copies of globals */1155b = ZIP(bb); /* initialize bit buffer */1156k = ZIP(bk);1157w = ZIP(window_posn); /* initialize window position */11581159/* go to byte boundary */1160n = k & 7;1161ZIPDUMPBITS(n);11621163/* get the length and its complement */1164ZIPNEEDBITS(16)1165n = (b & 0xffff);1166ZIPDUMPBITS(16)1167ZIPNEEDBITS(16)1168if (n != ((~b) & 0xffff))1169return 1; /* error in compressed data */1170ZIPDUMPBITS(16)11711172/* read and output the compressed data */1173while(n--)1174{1175ZIPNEEDBITS(8)1176CAB(outbuf)[w++] = (cab_UBYTE)b;1177ZIPDUMPBITS(8)1178}11791180/* restore the globals from the locals */1181ZIP(window_posn) = w; /* restore global window pointer */1182ZIP(bb) = b; /* restore global bit buffer */1183ZIP(bk) = k;1184return 0;1185}11861187/******************************************************1188* fdi_Zipinflate_fixed (internal)1189*/1190static cab_LONG fdi_Zipinflate_fixed(fdi_decomp_state *decomp_state)1191{1192struct Ziphuft *fixed_tl;1193struct Ziphuft *fixed_td;1194cab_LONG fixed_bl, fixed_bd;1195cab_LONG i; /* temporary variable */1196cab_ULONG *l;11971198l = ZIP(ll);11991200/* literal table */1201for(i = 0; i < 144; i++)1202l[i] = 8;1203for(; i < 256; i++)1204l[i] = 9;1205for(; i < 280; i++)1206l[i] = 7;1207for(; i < 288; i++) /* make a complete, but wrong code set */1208l[i] = 8;1209fixed_bl = 7;1210if((i = fdi_Ziphuft_build(l, 288, 257, Zipcplens, Zipcplext, &fixed_tl, &fixed_bl, decomp_state)))1211return i;12121213/* distance table */1214for(i = 0; i < 30; i++) /* make an incomplete code set */1215l[i] = 5;1216fixed_bd = 5;1217if((i = fdi_Ziphuft_build(l, 30, 0, Zipcpdist, Zipcpdext, &fixed_td, &fixed_bd, decomp_state)) > 1)1218{1219fdi_Ziphuft_free(CAB(fdi), fixed_tl);1220return i;1221}12221223/* decompress until an end-of-block code */1224i = fdi_Zipinflate_codes(fixed_tl, fixed_td, fixed_bl, fixed_bd, decomp_state);12251226fdi_Ziphuft_free(CAB(fdi), fixed_td);1227fdi_Ziphuft_free(CAB(fdi), fixed_tl);1228return i;1229}12301231/**************************************************************1232* fdi_Zipinflate_dynamic (internal)1233*/1234static cab_LONG fdi_Zipinflate_dynamic(fdi_decomp_state *decomp_state)1235/* decompress an inflated type 2 (dynamic Huffman codes) block. */1236{1237cab_LONG i; /* temporary variables */1238cab_ULONG j;1239cab_ULONG *ll;1240cab_ULONG l; /* last length */1241cab_ULONG m; /* mask for bit lengths table */1242cab_ULONG n; /* number of lengths to get */1243struct Ziphuft *tl; /* literal/length code table */1244struct Ziphuft *td; /* distance code table */1245cab_LONG bl; /* lookup bits for tl */1246cab_LONG bd; /* lookup bits for td */1247cab_ULONG nb; /* number of bit length codes */1248cab_ULONG nl; /* number of literal/length codes */1249cab_ULONG nd; /* number of distance codes */1250register cab_ULONG b; /* bit buffer */1251register cab_ULONG k; /* number of bits in bit buffer */12521253/* make local bit buffer */1254b = ZIP(bb);1255k = ZIP(bk);1256ll = ZIP(ll);12571258/* read in table lengths */1259ZIPNEEDBITS(5)1260nl = 257 + (b & 0x1f); /* number of literal/length codes */1261ZIPDUMPBITS(5)1262ZIPNEEDBITS(5)1263nd = 1 + (b & 0x1f); /* number of distance codes */1264ZIPDUMPBITS(5)1265ZIPNEEDBITS(4)1266nb = 4 + (b & 0xf); /* number of bit length codes */1267ZIPDUMPBITS(4)1268if(nl > 288 || nd > 32)1269return 1; /* bad lengths */12701271/* read in bit-length-code lengths */1272for(j = 0; j < nb; j++)1273{1274ZIPNEEDBITS(3)1275ll[Zipborder[j]] = b & 7;1276ZIPDUMPBITS(3)1277}1278for(; j < 19; j++)1279ll[Zipborder[j]] = 0;12801281/* build decoding table for trees--single level, 7 bit lookup */1282bl = 7;1283if((i = fdi_Ziphuft_build(ll, 19, 19, NULL, NULL, &tl, &bl, decomp_state)) != 0)1284{1285if(i == 1)1286fdi_Ziphuft_free(CAB(fdi), tl);1287return i; /* incomplete code set */1288}12891290/* read in literal and distance code lengths */1291n = nl + nd;1292m = Zipmask[bl];1293i = l = 0;1294while((cab_ULONG)i < n)1295{1296ZIPNEEDBITS((cab_ULONG)bl)1297j = (td = tl + (b & m))->b;1298ZIPDUMPBITS(j)1299j = td->v.n;1300if (j < 16) /* length of code in bits (0..15) */1301ll[i++] = l = j; /* save last length in l */1302else if (j == 16) /* repeat last length 3 to 6 times */1303{1304ZIPNEEDBITS(2)1305j = 3 + (b & 3);1306ZIPDUMPBITS(2)1307if((cab_ULONG)i + j > n)1308return 1;1309while (j--)1310ll[i++] = l;1311}1312else if (j == 17) /* 3 to 10 zero length codes */1313{1314ZIPNEEDBITS(3)1315j = 3 + (b & 7);1316ZIPDUMPBITS(3)1317if ((cab_ULONG)i + j > n)1318return 1;1319while (j--)1320ll[i++] = 0;1321l = 0;1322}1323else /* j == 18: 11 to 138 zero length codes */1324{1325ZIPNEEDBITS(7)1326j = 11 + (b & 0x7f);1327ZIPDUMPBITS(7)1328if ((cab_ULONG)i + j > n)1329return 1;1330while (j--)1331ll[i++] = 0;1332l = 0;1333}1334}13351336/* free decoding table for trees */1337fdi_Ziphuft_free(CAB(fdi), tl);13381339/* restore the global bit buffer */1340ZIP(bb) = b;1341ZIP(bk) = k;13421343/* build the decoding tables for literal/length and distance codes */1344bl = ZIPLBITS;1345if((i = fdi_Ziphuft_build(ll, nl, 257, Zipcplens, Zipcplext, &tl, &bl, decomp_state)) != 0)1346{1347if(i == 1)1348fdi_Ziphuft_free(CAB(fdi), tl);1349return i; /* incomplete code set */1350}1351bd = ZIPDBITS;1352fdi_Ziphuft_build(ll + nl, nd, 0, Zipcpdist, Zipcpdext, &td, &bd, decomp_state);13531354/* decompress until an end-of-block code */1355if(fdi_Zipinflate_codes(tl, td, bl, bd, decomp_state))1356return 1;13571358/* free the decoding tables, return */1359fdi_Ziphuft_free(CAB(fdi), tl);1360fdi_Ziphuft_free(CAB(fdi), td);1361return 0;1362}13631364/*****************************************************1365* fdi_Zipinflate_block (internal)1366*/1367static cab_LONG fdi_Zipinflate_block(cab_LONG *e, fdi_decomp_state *decomp_state) /* e == last block flag */1368{ /* decompress an inflated block */1369cab_ULONG t; /* block type */1370register cab_ULONG b; /* bit buffer */1371register cab_ULONG k; /* number of bits in bit buffer */13721373/* make local bit buffer */1374b = ZIP(bb);1375k = ZIP(bk);13761377/* read in last block bit */1378ZIPNEEDBITS(1)1379*e = (cab_LONG)b & 1;1380ZIPDUMPBITS(1)13811382/* read in block type */1383ZIPNEEDBITS(2)1384t = b & 3;1385ZIPDUMPBITS(2)13861387/* restore the global bit buffer */1388ZIP(bb) = b;1389ZIP(bk) = k;13901391/* inflate that block type */1392if(t == 2)1393return fdi_Zipinflate_dynamic(decomp_state);1394if(t == 0)1395return fdi_Zipinflate_stored(decomp_state);1396if(t == 1)1397return fdi_Zipinflate_fixed(decomp_state);1398/* bad block type */1399return 2;1400}14011402/****************************************************1403* ZIPfdi_decomp(internal)1404*/1405static int ZIPfdi_decomp(int inlen, int outlen, fdi_decomp_state *decomp_state)1406{1407cab_LONG e; /* last block flag */14081409TRACE("(inlen == %d, outlen == %d)\n", inlen, outlen);14101411ZIP(inpos) = CAB(inbuf);1412ZIP(bb) = ZIP(bk) = ZIP(window_posn) = 0;1413if(outlen > ZIPWSIZE)1414return DECR_DATAFORMAT;14151416/* CK = Chris Kirmse, official Microsoft purloiner */1417if(ZIP(inpos)[0] != 0x43 || ZIP(inpos)[1] != 0x4B)1418return DECR_ILLEGALDATA;1419ZIP(inpos) += 2;14201421do {1422if(fdi_Zipinflate_block(&e, decomp_state))1423return DECR_ILLEGALDATA;1424} while(!e);14251426/* return success */1427return DECR_OK;1428}14291430/*******************************************************************1431* QTMfdi_decomp(internal)1432*/1433static int QTMfdi_decomp(int inlen, int outlen, fdi_decomp_state *decomp_state)1434{1435cab_UBYTE *inpos = CAB(inbuf);1436cab_UBYTE *window = QTM(window);1437cab_UBYTE *runsrc, *rundest;1438cab_ULONG window_posn = QTM(window_posn);1439cab_ULONG window_size = QTM(window_size);14401441/* used by bitstream macros */1442register int bitsleft, bitrun, bitsneed;1443register cab_ULONG bitbuf;14441445/* used by GET_SYMBOL */1446cab_ULONG range;1447cab_UWORD symf;1448int i;14491450int extra, togo = outlen, match_length = 0, copy_length;1451cab_UBYTE selector, sym;1452cab_ULONG match_offset = 0;14531454cab_UWORD H = 0xFFFF, L = 0, C;14551456TRACE("(inlen == %d, outlen == %d)\n", inlen, outlen);14571458/* read initial value of C */1459Q_INIT_BITSTREAM;1460Q_READ_BITS(C, 16);14611462/* apply 2^x-1 mask */1463window_posn &= window_size - 1;1464/* runs can't straddle the window wraparound */1465if ((window_posn + togo) > window_size) {1466TRACE("straddled run\n");1467return DECR_DATAFORMAT;1468}14691470while (togo > 0) {1471GET_SYMBOL(model7, selector);1472switch (selector) {1473case 0:1474GET_SYMBOL(model00, sym); window[window_posn++] = sym; togo--;1475break;1476case 1:1477GET_SYMBOL(model40, sym); window[window_posn++] = sym; togo--;1478break;1479case 2:1480GET_SYMBOL(model80, sym); window[window_posn++] = sym; togo--;1481break;1482case 3:1483GET_SYMBOL(modelC0, sym); window[window_posn++] = sym; togo--;1484break;14851486case 4:1487/* selector 4 = fixed length of 3 */1488GET_SYMBOL(model4, sym);1489Q_READ_BITS(extra, CAB(q_extra_bits)[sym]);1490match_offset = CAB(q_position_base)[sym] + extra + 1;1491match_length = 3;1492break;14931494case 5:1495/* selector 5 = fixed length of 4 */1496GET_SYMBOL(model5, sym);1497Q_READ_BITS(extra, CAB(q_extra_bits)[sym]);1498match_offset = CAB(q_position_base)[sym] + extra + 1;1499match_length = 4;1500break;15011502case 6:1503/* selector 6 = variable length */1504GET_SYMBOL(model6len, sym);1505Q_READ_BITS(extra, CAB(q_length_extra)[sym]);1506match_length = CAB(q_length_base)[sym] + extra + 5;1507GET_SYMBOL(model6pos, sym);1508Q_READ_BITS(extra, CAB(q_extra_bits)[sym]);1509match_offset = CAB(q_position_base)[sym] + extra + 1;1510break;15111512default:1513TRACE("Selector is bogus\n");1514return DECR_ILLEGALDATA;1515}15161517/* if this is a match */1518if (selector >= 4) {1519rundest = window + window_posn;1520togo -= match_length;15211522/* copy any wrapped around source data */1523if (window_posn >= match_offset) {1524/* no wrap */1525runsrc = rundest - match_offset;1526} else {1527runsrc = rundest + (window_size - match_offset);1528copy_length = match_offset - window_posn;1529if (copy_length < match_length) {1530match_length -= copy_length;1531window_posn += copy_length;1532while (copy_length-- > 0) *rundest++ = *runsrc++;1533runsrc = window;1534}1535}1536window_posn += match_length;15371538/* copy match data - no worries about destination wraps */1539while (match_length-- > 0) *rundest++ = *runsrc++;1540}1541} /* while (togo > 0) */15421543if (togo != 0) {1544TRACE("Frame overflow, this_run = %d\n", togo);1545return DECR_ILLEGALDATA;1546}15471548memcpy(CAB(outbuf), window + ((!window_posn) ? window_size : window_posn) -1549outlen, outlen);15501551QTM(window_posn) = window_posn;1552return DECR_OK;1553}15541555/************************************************************1556* fdi_lzx_read_lens (internal)1557*/1558static int fdi_lzx_read_lens(cab_UBYTE *lens, cab_ULONG first, cab_ULONG last, struct lzx_bits *lb,1559fdi_decomp_state *decomp_state) {1560cab_ULONG i,j, x,y;1561int z;15621563register cab_ULONG bitbuf = lb->bb;1564register int bitsleft = lb->bl;1565cab_UBYTE *inpos = lb->ip;1566cab_UWORD *hufftbl;15671568for (x = 0; x < 20; x++) {1569READ_BITS(y, 4);1570LENTABLE(PRETREE)[x] = y;1571}1572BUILD_TABLE(PRETREE);15731574for (x = first; x < last; ) {1575READ_HUFFSYM(PRETREE, z);1576if (z == 17) {1577READ_BITS(y, 4); y += 4;1578while (y--) lens[x++] = 0;1579}1580else if (z == 18) {1581READ_BITS(y, 5); y += 20;1582while (y--) lens[x++] = 0;1583}1584else if (z == 19) {1585READ_BITS(y, 1); y += 4;1586READ_HUFFSYM(PRETREE, z);1587z = lens[x] - z; if (z < 0) z += 17;1588while (y--) lens[x++] = z;1589}1590else {1591z = lens[x] - z; if (z < 0) z += 17;1592lens[x++] = z;1593}1594}15951596lb->bb = bitbuf;1597lb->bl = bitsleft;1598lb->ip = inpos;1599return 0;1600}16011602/*******************************************************1603* LZXfdi_decomp(internal)1604*/1605static int LZXfdi_decomp(int inlen, int outlen, fdi_decomp_state *decomp_state) {1606cab_UBYTE *inpos = CAB(inbuf);1607const cab_UBYTE *endinp = inpos + inlen;1608cab_UBYTE *window = LZX(window);1609cab_UBYTE *runsrc, *rundest;1610cab_UWORD *hufftbl; /* used in READ_HUFFSYM macro as chosen decoding table */16111612cab_ULONG window_posn = LZX(window_posn);1613cab_ULONG window_size = LZX(window_size);1614cab_ULONG R0 = LZX(R0);1615cab_ULONG R1 = LZX(R1);1616cab_ULONG R2 = LZX(R2);16171618register cab_ULONG bitbuf;1619register int bitsleft;1620cab_ULONG match_offset, i,j,k; /* ijk used in READ_HUFFSYM macro */1621struct lzx_bits lb; /* used in READ_LENGTHS macro */16221623int togo = outlen, this_run, main_element, aligned_bits;1624int match_length, copy_length, length_footer, extra, verbatim_bits;16251626TRACE("(inlen == %d, outlen == %d)\n", inlen, outlen);16271628INIT_BITSTREAM;16291630/* read header if necessary */1631if (!LZX(header_read)) {1632i = j = 0;1633READ_BITS(k, 1); if (k) { READ_BITS(i,16); READ_BITS(j,16); }1634LZX(intel_filesize) = (i << 16) | j; /* or 0 if not encoded */1635LZX(header_read) = 1;1636}16371638/* main decoding loop */1639while (togo > 0) {1640/* last block finished, new block expected */1641if (LZX(block_remaining) == 0) {1642if (LZX(block_type) == LZX_BLOCKTYPE_UNCOMPRESSED) {1643if (LZX(block_length) & 1) inpos++; /* realign bitstream to word */1644INIT_BITSTREAM;1645}16461647READ_BITS(LZX(block_type), 3);1648READ_BITS(i, 16);1649READ_BITS(j, 8);1650LZX(block_remaining) = LZX(block_length) = (i << 8) | j;16511652switch (LZX(block_type)) {1653case LZX_BLOCKTYPE_ALIGNED:1654for (i = 0; i < 8; i++) { READ_BITS(j, 3); LENTABLE(ALIGNED)[i] = j; }1655BUILD_TABLE(ALIGNED);1656/* rest of aligned header is same as verbatim */16571658case LZX_BLOCKTYPE_VERBATIM:1659READ_LENGTHS(MAINTREE, 0, 256, fdi_lzx_read_lens);1660READ_LENGTHS(MAINTREE, 256, LZX(main_elements), fdi_lzx_read_lens);1661BUILD_TABLE(MAINTREE);1662if (LENTABLE(MAINTREE)[0xE8] != 0) LZX(intel_started) = 1;16631664READ_LENGTHS(LENGTH, 0, LZX_NUM_SECONDARY_LENGTHS, fdi_lzx_read_lens);1665BUILD_TABLE(LENGTH);1666break;16671668case LZX_BLOCKTYPE_UNCOMPRESSED:1669LZX(intel_started) = 1; /* because we can't assume otherwise */1670ENSURE_BITS(16); /* get up to 16 pad bits into the buffer */1671if (bitsleft > 16) inpos -= 2; /* and align the bitstream! */1672R0 = inpos[0]|(inpos[1]<<8)|(inpos[2]<<16)|(inpos[3]<<24);inpos+=4;1673R1 = inpos[0]|(inpos[1]<<8)|(inpos[2]<<16)|(inpos[3]<<24);inpos+=4;1674R2 = inpos[0]|(inpos[1]<<8)|(inpos[2]<<16)|(inpos[3]<<24);inpos+=4;1675break;16761677default:1678return DECR_ILLEGALDATA;1679}1680}16811682/* buffer exhaustion check */1683if (inpos > endinp) {1684/* it's possible to have a file where the next run is less than1685* 16 bits in size. In this case, the READ_HUFFSYM() macro used1686* in building the tables will exhaust the buffer, so we should1687* allow for this, but not allow those accidentally read bits to1688* be used (so we check that there are at least 16 bits1689* remaining - in this boundary case they aren't really part of1690* the compressed data)1691*/1692if (inpos > (endinp+2) || bitsleft < 16) return DECR_ILLEGALDATA;1693}16941695while ((this_run = LZX(block_remaining)) > 0 && togo > 0) {1696if (this_run > togo) this_run = togo;1697togo -= this_run;1698LZX(block_remaining) -= this_run;16991700/* apply 2^x-1 mask */1701window_posn &= window_size - 1;1702/* runs can't straddle the window wraparound */1703if ((window_posn + this_run) > window_size)1704return DECR_DATAFORMAT;17051706switch (LZX(block_type)) {17071708case LZX_BLOCKTYPE_VERBATIM:1709while (this_run > 0) {1710READ_HUFFSYM(MAINTREE, main_element);17111712if (main_element < LZX_NUM_CHARS) {1713/* literal: 0 to LZX_NUM_CHARS-1 */1714window[window_posn++] = main_element;1715this_run--;1716}1717else {1718/* match: LZX_NUM_CHARS + ((slot<<3) | length_header (3 bits)) */1719main_element -= LZX_NUM_CHARS;17201721match_length = main_element & LZX_NUM_PRIMARY_LENGTHS;1722if (match_length == LZX_NUM_PRIMARY_LENGTHS) {1723READ_HUFFSYM(LENGTH, length_footer);1724match_length += length_footer;1725}1726match_length += LZX_MIN_MATCH;17271728match_offset = main_element >> 3;17291730if (match_offset > 2) {1731/* not repeated offset */1732if (match_offset != 3) {1733extra = CAB(extra_bits)[match_offset];1734READ_BITS(verbatim_bits, extra);1735match_offset = CAB(lzx_position_base)[match_offset]1736- 2 + verbatim_bits;1737}1738else {1739match_offset = 1;1740}17411742/* update repeated offset LRU queue */1743R2 = R1; R1 = R0; R0 = match_offset;1744}1745else if (match_offset == 0) {1746match_offset = R0;1747}1748else if (match_offset == 1) {1749match_offset = R1;1750R1 = R0; R0 = match_offset;1751}1752else /* match_offset == 2 */ {1753match_offset = R2;1754R2 = R0; R0 = match_offset;1755}17561757rundest = window + window_posn;1758this_run -= match_length;17591760/* copy any wrapped around source data */1761if (window_posn >= match_offset) {1762/* no wrap */1763runsrc = rundest - match_offset;1764} else {1765runsrc = rundest + (window_size - match_offset);1766copy_length = match_offset - window_posn;1767if (copy_length < match_length) {1768match_length -= copy_length;1769window_posn += copy_length;1770while (copy_length-- > 0) *rundest++ = *runsrc++;1771runsrc = window;1772}1773}1774window_posn += match_length;17751776/* copy match data - no worries about destination wraps */1777while (match_length-- > 0) *rundest++ = *runsrc++;1778}1779}1780break;17811782case LZX_BLOCKTYPE_ALIGNED:1783while (this_run > 0) {1784READ_HUFFSYM(MAINTREE, main_element);17851786if (main_element < LZX_NUM_CHARS) {1787/* literal: 0 to LZX_NUM_CHARS-1 */1788window[window_posn++] = main_element;1789this_run--;1790}1791else {1792/* match: LZX_NUM_CHARS + ((slot<<3) | length_header (3 bits)) */1793main_element -= LZX_NUM_CHARS;17941795match_length = main_element & LZX_NUM_PRIMARY_LENGTHS;1796if (match_length == LZX_NUM_PRIMARY_LENGTHS) {1797READ_HUFFSYM(LENGTH, length_footer);1798match_length += length_footer;1799}1800match_length += LZX_MIN_MATCH;18011802match_offset = main_element >> 3;18031804if (match_offset > 2) {1805/* not repeated offset */1806extra = CAB(extra_bits)[match_offset];1807match_offset = CAB(lzx_position_base)[match_offset] - 2;1808if (extra > 3) {1809/* verbatim and aligned bits */1810extra -= 3;1811READ_BITS(verbatim_bits, extra);1812match_offset += (verbatim_bits << 3);1813READ_HUFFSYM(ALIGNED, aligned_bits);1814match_offset += aligned_bits;1815}1816else if (extra == 3) {1817/* aligned bits only */1818READ_HUFFSYM(ALIGNED, aligned_bits);1819match_offset += aligned_bits;1820}1821else if (extra > 0) { /* extra==1, extra==2 */1822/* verbatim bits only */1823READ_BITS(verbatim_bits, extra);1824match_offset += verbatim_bits;1825}1826else /* extra == 0 */ {1827/* ??? */1828match_offset = 1;1829}18301831/* update repeated offset LRU queue */1832R2 = R1; R1 = R0; R0 = match_offset;1833}1834else if (match_offset == 0) {1835match_offset = R0;1836}1837else if (match_offset == 1) {1838match_offset = R1;1839R1 = R0; R0 = match_offset;1840}1841else /* match_offset == 2 */ {1842match_offset = R2;1843R2 = R0; R0 = match_offset;1844}18451846rundest = window + window_posn;1847this_run -= match_length;18481849/* copy any wrapped around source data */1850if (window_posn >= match_offset) {1851/* no wrap */1852runsrc = rundest - match_offset;1853} else {1854runsrc = rundest + (window_size - match_offset);1855copy_length = match_offset - window_posn;1856if (copy_length < match_length) {1857match_length -= copy_length;1858window_posn += copy_length;1859while (copy_length-- > 0) *rundest++ = *runsrc++;1860runsrc = window;1861}1862}1863window_posn += match_length;18641865/* copy match data - no worries about destination wraps */1866while (match_length-- > 0) *rundest++ = *runsrc++;1867}1868}1869break;18701871case LZX_BLOCKTYPE_UNCOMPRESSED:1872if ((inpos + this_run) > endinp) return DECR_ILLEGALDATA;1873memcpy(window + window_posn, inpos, (size_t) this_run);1874inpos += this_run; window_posn += this_run;1875break;18761877default:1878return DECR_ILLEGALDATA; /* might as well */1879}18801881}1882}18831884if (togo != 0) return DECR_ILLEGALDATA;1885memcpy(CAB(outbuf), window + ((!window_posn) ? window_size : window_posn) -1886outlen, (size_t) outlen);18871888LZX(window_posn) = window_posn;1889LZX(R0) = R0;1890LZX(R1) = R1;1891LZX(R2) = R2;18921893/* intel E8 decoding */1894if ((LZX(frames_read)++ < 32768) && LZX(intel_filesize) != 0) {1895if (outlen <= 6 || !LZX(intel_started)) {1896LZX(intel_curpos) += outlen;1897}1898else {1899cab_UBYTE *data = CAB(outbuf);1900cab_UBYTE *dataend = data + outlen - 10;1901cab_LONG curpos = LZX(intel_curpos);1902cab_LONG filesize = LZX(intel_filesize);1903cab_LONG abs_off, rel_off;19041905LZX(intel_curpos) = curpos + outlen;19061907while (data < dataend) {1908if (*data++ != 0xE8) { curpos++; continue; }1909abs_off = data[0] | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);1910if ((abs_off >= -curpos) && (abs_off < filesize)) {1911rel_off = (abs_off >= 0) ? abs_off - curpos : abs_off + filesize;1912data[0] = (cab_UBYTE) rel_off;1913data[1] = (cab_UBYTE) (rel_off >> 8);1914data[2] = (cab_UBYTE) (rel_off >> 16);1915data[3] = (cab_UBYTE) (rel_off >> 24);1916}1917data += 4;1918curpos += 5;1919}1920}1921}1922return DECR_OK;1923}19241925/**********************************************************1926* fdi_decomp (internal)1927*1928* Decompress the requested number of bytes. If savemode is zero,1929* do not save the output anywhere, just plow through blocks until we1930* reach the specified (uncompressed) distance from the starting point,1931* and remember the position of the cabfile pointer (and which cabfile)1932* after we are done; otherwise, save the data out to CAB(filehf),1933* decompressing the requested number of bytes and writing them out. This1934* is also where we jump to additional cabinets in the case of split1935* cab's, and provide (some of) the NEXT_CABINET notification semantics.1936*/1937static int fdi_decomp(const struct fdi_file *fi, int savemode, fdi_decomp_state *decomp_state,1938char *pszCabPath, PFNFDINOTIFY pfnfdin, void *pvUser)1939{1940cab_ULONG bytes = savemode ? fi->length : fi->offset - CAB(offset);1941cab_UBYTE buf[cfdata_SIZEOF], *data;1942cab_UWORD inlen, len, outlen, cando;1943cab_ULONG cksum;1944cab_LONG err;1945fdi_decomp_state *cab = (savemode && CAB(decomp_cab)) ? CAB(decomp_cab) : decomp_state;19461947TRACE("(fi == ^%p, savemode == %d, bytes == %d)\n", fi, savemode, bytes);19481949while (bytes > 0) {1950/* cando = the max number of bytes we can do */1951cando = CAB(outlen);1952if (cando > bytes) cando = bytes;19531954/* if cando != 0 */1955if (cando && savemode)1956CAB(fdi)->write(CAB(filehf), CAB(outpos), cando);19571958CAB(outpos) += cando;1959CAB(outlen) -= cando;1960bytes -= cando; if (!bytes) break;19611962/* we only get here if we emptied the output buffer */19631964/* read data header + data */1965inlen = outlen = 0;1966while (outlen == 0) {1967/* read the block header, skip the reserved part */1968if (CAB(fdi)->read(cab->cabhf, buf, cfdata_SIZEOF) != cfdata_SIZEOF)1969return DECR_INPUT;19701971if (CAB(fdi)->seek(cab->cabhf, cab->mii.block_resv, SEEK_CUR) == -1)1972return DECR_INPUT;19731974/* we shouldn't get blocks over CAB_INPUTMAX in size */1975data = CAB(inbuf) + inlen;1976len = EndGetI16(buf+cfdata_CompressedSize);1977inlen += len;1978if (inlen > CAB_INPUTMAX) return DECR_INPUT;1979if (CAB(fdi)->read(cab->cabhf, data, len) != len)1980return DECR_INPUT;19811982/* clear two bytes after read-in data */1983data[len+1] = data[len+2] = 0;19841985/* perform checksum test on the block (if one is stored) */1986cksum = EndGetI32(buf+cfdata_CheckSum);1987if (cksum && cksum != checksum(buf+4, 4, checksum(data, len, 0)))1988return DECR_CHECKSUM; /* checksum is wrong */19891990outlen = EndGetI16(buf+cfdata_UncompressedSize);19911992/* outlen=0 means this block was the last contiguous part1993of a split block, continued in the next cabinet */1994if (outlen == 0) {1995int pathlen, filenamelen;1996INT_PTR cabhf;1997char fullpath[MAX_PATH], userpath[256];1998FDINOTIFICATION fdin;1999FDICABINETINFO fdici;2000char emptystring = '\0';2001cab_UBYTE buf2[64];2002BOOL success = FALSE;2003struct fdi_folder *fol = NULL, *linkfol = NULL;2004struct fdi_file *file = NULL, *linkfile = NULL;20052006tryanothercab:20072008/* set up the next decomp_state... */2009if (!(cab->next)) {2010unsigned int i;20112012if (!cab->mii.hasnext) return DECR_INPUT;20132014if (!((cab->next = CAB(fdi)->alloc(sizeof(fdi_decomp_state)))))2015return DECR_NOMEMORY;20162017ZeroMemory(cab->next, sizeof(fdi_decomp_state));20182019/* copy pszCabPath to userpath */2020ZeroMemory(userpath, 256);2021pathlen = pszCabPath ? strlen(pszCabPath) : 0;2022if (pathlen) {2023if (pathlen < 256) /* else we are in a weird place... let's leave it blank and see if the user fixes it */2024strcpy(userpath, pszCabPath);2025}20262027/* initial fdintNEXT_CABINET notification */2028ZeroMemory(&fdin, sizeof(FDINOTIFICATION));2029fdin.psz1 = cab->mii.nextname ? cab->mii.nextname : &emptystring;2030fdin.psz2 = cab->mii.nextinfo ? cab->mii.nextinfo : &emptystring;2031fdin.psz3 = userpath;2032fdin.fdie = FDIERROR_NONE;2033fdin.pv = pvUser;20342035if (((*pfnfdin)(fdintNEXT_CABINET, &fdin))) return DECR_USERABORT;20362037do {20382039pathlen = strlen(userpath);2040filenamelen = cab->mii.nextname ? strlen(cab->mii.nextname) : 0;20412042/* slight overestimation here to save CPU cycles in the developer's brain */2043if ((pathlen + filenamelen + 3) > MAX_PATH) {2044ERR("MAX_PATH exceeded.\n");2045return DECR_ILLEGALDATA;2046}20472048/* paste the path and filename together */2049fullpath[0] = '\0';2050if (pathlen) {2051strcpy(fullpath, userpath);2052if (fullpath[pathlen - 1] != '\\')2053strcat(fullpath, "\\");2054}2055if (filenamelen)2056strcat(fullpath, cab->mii.nextname);2057else if (fullpath[0])2058fullpath[strlen(fullpath)-1] = 0; /* remove trailing backslash */20592060TRACE("full cab path/file name: %s\n", debugstr_a(fullpath));20612062/* try to get a handle to the cabfile */2063cabhf = CAB(fdi)->open(fullpath, _O_RDONLY|_O_BINARY, _S_IREAD | _S_IWRITE);2064if (cabhf == -1) {2065/* no file. allow the user to try again */2066fdin.fdie = FDIERROR_CABINET_NOT_FOUND;2067if (((*pfnfdin)(fdintNEXT_CABINET, &fdin))) return DECR_USERABORT;2068continue;2069}20702071if (cabhf == 0) {2072ERR("PFDI_OPEN returned zero for %s.\n", fullpath);2073fdin.fdie = FDIERROR_CABINET_NOT_FOUND;2074if (((*pfnfdin)(fdintNEXT_CABINET, &fdin))) return DECR_USERABORT;2075continue;2076}20772078/* check if it's really a cabfile. Note that this doesn't implement the bug */2079if (!FDI_read_entries(CAB(fdi), cabhf, &fdici, &(cab->next->mii))) {2080WARN("FDIIsCabinet failed.\n");2081CAB(fdi)->close(cabhf);2082fdin.fdie = FDIERROR_NOT_A_CABINET;2083if (((*pfnfdin)(fdintNEXT_CABINET, &fdin))) return DECR_USERABORT;2084continue;2085}20862087if ((fdici.setID != cab->setID) || (fdici.iCabinet != (cab->iCabinet + 1))) {2088WARN("Wrong Cabinet.\n");2089CAB(fdi)->close(cabhf);2090fdin.fdie = FDIERROR_WRONG_CABINET;2091if (((*pfnfdin)(fdintNEXT_CABINET, &fdin))) return DECR_USERABORT;2092continue;2093}20942095break;20962097} while (1);20982099/* cabinet notification */2100ZeroMemory(&fdin, sizeof(FDINOTIFICATION));2101fdin.setID = fdici.setID;2102fdin.iCabinet = fdici.iCabinet;2103fdin.pv = pvUser;2104fdin.psz1 = (cab->next->mii.nextname) ? cab->next->mii.nextname : &emptystring;2105fdin.psz2 = (cab->next->mii.nextinfo) ? cab->next->mii.nextinfo : &emptystring;2106fdin.psz3 = pszCabPath;21072108if (((*pfnfdin)(fdintCABINET_INFO, &fdin))) return DECR_USERABORT;21092110cab->next->setID = fdici.setID;2111cab->next->iCabinet = fdici.iCabinet;2112cab->next->fdi = CAB(fdi);2113cab->next->filehf = CAB(filehf);2114cab->next->cabhf = cabhf;2115cab->next->decompress = CAB(decompress); /* crude, but unused anyhow */21162117cab = cab->next; /* advance to the next cabinet */21182119/* read folders */2120for (i = 0; i < fdici.cFolders; i++) {2121if (CAB(fdi)->read(cab->cabhf, buf2, cffold_SIZEOF) != cffold_SIZEOF)2122return DECR_INPUT;21232124if (cab->mii.folder_resv > 0)2125CAB(fdi)->seek(cab->cabhf, cab->mii.folder_resv, SEEK_CUR);21262127fol = CAB(fdi)->alloc(sizeof(struct fdi_folder));2128if (!fol) {2129ERR("out of memory!\n");2130return DECR_NOMEMORY;2131}2132ZeroMemory(fol, sizeof(struct fdi_folder));2133if (!(cab->firstfol)) cab->firstfol = fol;21342135fol->offset = (cab_off_t) EndGetI32(buf2+cffold_DataOffset);2136fol->num_blocks = EndGetI16(buf2+cffold_NumBlocks);2137fol->comp_type = EndGetI16(buf2+cffold_CompType);21382139if (linkfol)2140linkfol->next = fol;2141linkfol = fol;2142}21432144/* read files */2145for (i = 0; i < fdici.cFiles; i++) {2146if (CAB(fdi)->read(cab->cabhf, buf2, cffile_SIZEOF) != cffile_SIZEOF)2147return DECR_INPUT;21482149file = CAB(fdi)->alloc(sizeof(struct fdi_file));2150if (!file) {2151ERR("out of memory!\n");2152return DECR_NOMEMORY;2153}2154ZeroMemory(file, sizeof(struct fdi_file));2155if (!(cab->firstfile)) cab->firstfile = file;21562157file->length = EndGetI32(buf2+cffile_UncompressedSize);2158file->offset = EndGetI32(buf2+cffile_FolderOffset);2159file->index = EndGetI16(buf2+cffile_FolderIndex);2160file->time = EndGetI16(buf2+cffile_Time);2161file->date = EndGetI16(buf2+cffile_Date);2162file->attribs = EndGetI16(buf2+cffile_Attribs);2163file->filename = FDI_read_string(CAB(fdi), cab->cabhf, fdici.cbCabinet);21642165if (!file->filename) return DECR_INPUT;21662167if (linkfile)2168linkfile->next = file;2169linkfile = file;2170}21712172} else2173cab = cab->next; /* advance to the next cabinet */21742175/* iterate files -- if we encounter the continued file, process it --2176otherwise, jump to the label above and keep looking */21772178for (file = cab->firstfile; (file); file = file->next) {2179if ((file->index & cffileCONTINUED_FROM_PREV) == cffileCONTINUED_FROM_PREV) {2180/* check to ensure a real match */2181if (lstrcmpiA(fi->filename, file->filename) == 0) {2182success = TRUE;2183if (CAB(fdi)->seek(cab->cabhf, cab->firstfol->offset, SEEK_SET) == -1)2184return DECR_INPUT;2185break;2186}2187}2188}2189if (!success) goto tryanothercab; /* FIXME: shouldn't this trigger2190"Wrong Cabinet" notification? */2191}2192}21932194/* decompress block */2195if ((err = CAB(decompress)(inlen, outlen, decomp_state)))2196return err;2197CAB(outlen) = outlen;2198CAB(outpos) = CAB(outbuf);2199}22002201CAB(decomp_cab) = cab;2202return DECR_OK;2203}22042205static void free_decompression_temps(FDI_Int *fdi, const struct fdi_folder *fol,2206fdi_decomp_state *decomp_state)2207{2208switch (fol->comp_type & cffoldCOMPTYPE_MASK) {2209case cffoldCOMPTYPE_LZX:2210if (LZX(window)) {2211fdi->free(LZX(window));2212LZX(window) = NULL;2213}2214break;2215case cffoldCOMPTYPE_QUANTUM:2216if (QTM(window)) {2217fdi->free(QTM(window));2218QTM(window) = NULL;2219}2220break;2221}2222}22232224static void free_decompression_mem(FDI_Int *fdi, fdi_decomp_state *decomp_state)2225{2226struct fdi_folder *fol;2227while (decomp_state) {2228fdi_decomp_state *prev_fds;22292230fdi->close(CAB(cabhf));22312232/* free the storage remembered by mii */2233if (CAB(mii).nextname) fdi->free(CAB(mii).nextname);2234if (CAB(mii).nextinfo) fdi->free(CAB(mii).nextinfo);2235if (CAB(mii).prevname) fdi->free(CAB(mii).prevname);2236if (CAB(mii).previnfo) fdi->free(CAB(mii).previnfo);22372238while (CAB(firstfol)) {2239fol = CAB(firstfol);2240CAB(firstfol) = CAB(firstfol)->next;2241fdi->free(fol);2242}2243while (CAB(firstfile)) {2244struct fdi_file *file = CAB(firstfile);2245if (file->filename) fdi->free(file->filename);2246CAB(firstfile) = CAB(firstfile)->next;2247fdi->free(file);2248}2249prev_fds = decomp_state;2250decomp_state = CAB(next);2251fdi->free(prev_fds);2252}2253}22542255/***********************************************************************2256* FDICopy (CABINET.22)2257*2258* Iterates through the files in the Cabinet file indicated by name and2259* file-location. May chain forward to additional cabinets (typically2260* only one) if files which begin in this Cabinet are continued in another2261* cabinet. For each file which is partially contained in this cabinet,2262* and partially contained in a prior cabinet, provides fdintPARTIAL_FILE2263* notification to the pfnfdin callback. For each file which begins in2264* this cabinet, fdintCOPY_FILE notification is provided to the pfnfdin2265* callback, and the file is optionally decompressed and saved to disk.2266* Notification is not provided for files which are not at least partially2267* contained in the specified cabinet file.2268*2269* See below for a thorough explanation of the various notification2270* callbacks.2271*2272* PARAMS2273* hfdi [I] An HFDI from FDICreate2274* pszCabinet [I] C-style string containing the filename of the cabinet2275* pszCabPath [I] C-style string containing the file path of the cabinet2276* flags [I] "Decoder parameters". Ignored. Suggested value: 0.2277* pfnfdin [I] Pointer to a notification function. See CALLBACKS below.2278* pfnfdid [I] Pointer to a decryption function. Ignored. Suggested2279* value: NULL.2280* pvUser [I] arbitrary void * value which is passed to callbacks.2281*2282* RETURNS2283* TRUE if successful.2284* FALSE if unsuccessful (error information is provided in the ERF structure2285* associated with the provided decompression handle by FDICreate).2286*2287* CALLBACKS2288*2289* Two pointers to callback functions are provided as parameters to FDICopy:2290* pfnfdin(of type PFNFDINOTIFY), and pfnfdid (of type PFNFDIDECRYPT). These2291* types are as follows:2292*2293* typedef INT_PTR (__cdecl *PFNFDINOTIFY) ( FDINOTIFICATIONTYPE fdint,2294* PFDINOTIFICATION pfdin );2295*2296* typedef int (__cdecl *PFNFDIDECRYPT) ( PFDIDECRYPT pfdid );2297*2298* You can create functions of this type using the FNFDINOTIFY() and2299* FNFDIDECRYPT() macros, respectively. For example:2300*2301* FNFDINOTIFY(mycallback) {2302* / * use variables fdint and pfdin to process notification * /2303* }2304*2305* The second callback, which could be used for decrypting encrypted data,2306* is not used at all.2307*2308* Each notification informs the user of some event which has occurred during2309* decompression of the cabinet file; each notification is also an opportunity2310* for the callee to abort decompression. The information provided to the2311* callback and the meaning of the callback's return value vary drastically2312* across the various types of notification. The type of notification is the2313* fdint parameter; all other information is provided to the callback in2314* notification-specific parts of the FDINOTIFICATION structure pointed to by2315* pfdin. The only part of that structure which is assigned for every callback2316* is the pv element, which contains the arbitrary value which was passed to2317* FDICopy in the pvUser argument (psz1 is also used each time, but its meaning2318* is highly dependent on fdint).2319*2320* If you encounter unknown notifications, you should return zero if you want2321* decompression to continue (or -1 to abort). All strings used in the2322* callbacks are regular C-style strings. Detailed descriptions of each2323* notification type follow:2324*2325* fdintCABINET_INFO:2326*2327* This is the first notification provided after calling FDICopy, and provides2328* the user with various information about the cabinet. Note that this is2329* called for each cabinet FDICopy opens, not just the first one. In the2330* structure pointed to by pfdin, psz1 contains a pointer to the name of the2331* next cabinet file in the set after the one just loaded (if any), psz22332* contains a pointer to the name or "info" of the next disk, psz32333* contains a pointer to the file-path of the current cabinet, setID2334* contains an arbitrary constant associated with this set of cabinet files,2335* and iCabinet contains the numerical index of the current cabinet within2336* that set. Return zero, or -1 to abort.2337*2338* fdintPARTIAL_FILE:2339*2340* This notification is provided when FDICopy encounters a part of a file2341* contained in this cabinet which is missing its beginning. Files can be2342* split across cabinets, so this is not necessarily an abnormality; it just2343* means that the file in question begins in another cabinet. No file2344* corresponding to this notification is extracted from the cabinet. In the2345* structure pointed to by pfdin, psz1 contains a pointer to the name of the2346* partial file, psz2 contains a pointer to the file name of the cabinet in2347* which this file begins, and psz3 contains a pointer to the disk name or2348* "info" of the cabinet where the file begins. Return zero, or -1 to abort.2349*2350* fdintCOPY_FILE:2351*2352* This notification is provided when FDICopy encounters a file which starts2353* in the cabinet file, provided to FDICopy in pszCabinet. (FDICopy will not2354* look for files in cabinets after the first one). One notification will be2355* sent for each such file, before the file is decompressed. By returning2356* zero, the callback can instruct FDICopy to skip the file. In the structure2357* pointed to by pfdin, psz1 contains a pointer to the file's name, cb contains2358* the size of the file (uncompressed), attribs contains the file attributes,2359* and date and time contain the date and time of the file. attributes, date,2360* and time are of the 16-bit ms-dos variety. Return -1 to abort decompression2361* for the entire cabinet, 0 to skip just this file but continue scanning the2362* cabinet for more files, or an FDIClose()-compatible file-handle.2363*2364* fdintCLOSE_FILE_INFO:2365*2366* This notification is important, don't forget to implement it. This2367* notification indicates that a file has been successfully uncompressed and2368* written to disk. Upon receipt of this notification, the callee is expected2369* to close the file handle, to set the attributes and date/time of the2370* closed file, and possibly to execute the file. In the structure pointed to2371* by pfdin, psz1 contains a pointer to the name of the file, hf will be the2372* open file handle (close it), cb contains 1 or zero, indicating respectively2373* that the callee should or should not execute the file, and date, time2374* and attributes will be set as in fdintCOPY_FILE. Bizarrely, the Cabinet SDK2375* specifies that _A_EXEC will be xor'ed out of attributes! wine does not do2376* do so. Return TRUE, or FALSE to abort decompression.2377*2378* fdintNEXT_CABINET:2379*2380* This notification is called when FDICopy must load in another cabinet. This2381* can occur when a file's data is "split" across multiple cabinets. The2382* callee has the opportunity to request that FDICopy look in a different file2383* path for the specified cabinet file, by writing that data into a provided2384* buffer (see below for more information). This notification will be received2385* more than once per-cabinet in the instance that FDICopy failed to find a2386* valid cabinet at the location specified by the first per-cabinet2387* fdintNEXT_CABINET notification. In such instances, the fdie element of the2388* structure pointed to by pfdin indicates the error which prevented FDICopy2389* from proceeding successfully. Return zero to indicate success, or -1 to2390* indicate failure and abort FDICopy.2391*2392* Upon receipt of this notification, the structure pointed to by pfdin will2393* contain the following values: psz1 pointing to the name of the cabinet2394* which FDICopy is attempting to open, psz2 pointing to the name ("info") of2395* the next disk, psz3 pointing to the presumed file-location of the cabinet,2396* and fdie containing either FDIERROR_NONE, or one of the following:2397*2398* FDIERROR_CABINET_NOT_FOUND, FDIERROR_NOT_A_CABINET,2399* FDIERROR_UNKNOWN_CABINET_VERSION, FDIERROR_CORRUPT_CABINET,2400* FDIERROR_BAD_COMPR_TYPE, FDIERROR_RESERVE_MISMATCH, and2401* FDIERROR_WRONG_CABINET.2402*2403* The callee may choose to change the path where FDICopy will look for the2404* cabinet after this notification. To do so, the caller may write the new2405* pathname to the buffer pointed to by psz3, which is 256 characters in2406* length, including the terminating null character, before returning zero.2407*2408* fdintENUMERATE:2409*2410* Undocumented and unimplemented in wine, this seems to be sent each time2411* a cabinet is opened, along with the fdintCABINET_INFO notification. It2412* probably has an interface similar to that of fdintCABINET_INFO; maybe this2413* provides information about the current cabinet instead of the next one....2414* this is just a guess, it has not been looked at closely.2415*2416* INCLUDES2417* fdi.c2418*/2419BOOL __cdecl FDICopy(2420HFDI hfdi,2421char *pszCabinet,2422char *pszCabPath,2423int flags,2424PFNFDINOTIFY pfnfdin,2425PFNFDIDECRYPT pfnfdid,2426void *pvUser)2427{2428FDICABINETINFO fdici;2429FDINOTIFICATION fdin;2430INT_PTR cabhf, filehf = 0;2431unsigned int i;2432char fullpath[MAX_PATH];2433size_t pathlen, filenamelen;2434char emptystring = '\0';2435cab_UBYTE buf[64];2436struct fdi_folder *fol = NULL, *linkfol = NULL;2437struct fdi_file *file = NULL, *linkfile = NULL;2438fdi_decomp_state *decomp_state;2439FDI_Int *fdi = get_fdi_ptr( hfdi );24402441TRACE("(hfdi == ^%p, pszCabinet == %s, pszCabPath == %s, flags == %x, "2442"pfnfdin == ^%p, pfnfdid == ^%p, pvUser == ^%p)\n",2443hfdi, debugstr_a(pszCabinet), debugstr_a(pszCabPath), flags, pfnfdin, pfnfdid, pvUser);24442445if (!fdi) return FALSE;24462447if (!(decomp_state = fdi->alloc(sizeof(fdi_decomp_state))))2448{2449SetLastError(ERROR_NOT_ENOUGH_MEMORY);2450return FALSE;2451}2452ZeroMemory(decomp_state, sizeof(fdi_decomp_state));24532454pathlen = pszCabPath ? strlen(pszCabPath) : 0;2455filenamelen = pszCabinet ? strlen(pszCabinet) : 0;24562457/* slight overestimation here to save CPU cycles in the developer's brain */2458if ((pathlen + filenamelen + 3) > MAX_PATH) {2459ERR("MAX_PATH exceeded.\n");2460fdi->free(decomp_state);2461set_error( fdi, FDIERROR_CABINET_NOT_FOUND, ERROR_FILE_NOT_FOUND );2462return FALSE;2463}24642465/* paste the path and filename together */2466fullpath[0] = '\0';2467if (pathlen)2468strcpy(fullpath, pszCabPath);2469if (filenamelen)2470strcat(fullpath, pszCabinet);24712472TRACE("full cab path/file name: %s\n", debugstr_a(fullpath));24732474/* get a handle to the cabfile */2475cabhf = fdi->open(fullpath, _O_RDONLY|_O_BINARY, _S_IREAD | _S_IWRITE);2476if (cabhf == -1) {2477fdi->free(decomp_state);2478set_error( fdi, FDIERROR_CABINET_NOT_FOUND, 0 );2479SetLastError(ERROR_FILE_NOT_FOUND);2480return FALSE;2481}24822483/* check if it's really a cabfile. Note that this doesn't implement the bug */2484if (!FDI_read_entries(fdi, cabhf, &fdici, &(CAB(mii)))) {2485WARN("FDI_read_entries failed: %u\n", fdi->perf->erfOper);2486fdi->free(decomp_state);2487fdi->close(cabhf);2488return FALSE;2489}24902491/* cabinet notification */2492ZeroMemory(&fdin, sizeof(FDINOTIFICATION));2493fdin.setID = fdici.setID;2494fdin.iCabinet = fdici.iCabinet;2495fdin.pv = pvUser;2496fdin.psz1 = (CAB(mii).nextname) ? CAB(mii).nextname : &emptystring;2497fdin.psz2 = (CAB(mii).nextinfo) ? CAB(mii).nextinfo : &emptystring;2498fdin.psz3 = pszCabPath;24992500if (pfnfdin(fdintCABINET_INFO, &fdin) == -1) {2501set_error( fdi, FDIERROR_USER_ABORT, 0 );2502goto bail_and_fail;2503}25042505CAB(setID) = fdici.setID;2506CAB(iCabinet) = fdici.iCabinet;2507CAB(cabhf) = cabhf;25082509/* read folders */2510for (i = 0; i < fdici.cFolders; i++) {2511if (fdi->read(cabhf, buf, cffold_SIZEOF) != cffold_SIZEOF) {2512set_error( fdi, FDIERROR_CORRUPT_CABINET, 0 );2513goto bail_and_fail;2514}25152516if (CAB(mii).folder_resv > 0)2517fdi->seek(cabhf, CAB(mii).folder_resv, SEEK_CUR);25182519fol = fdi->alloc(sizeof(struct fdi_folder));2520if (!fol) {2521ERR("out of memory!\n");2522set_error( fdi, FDIERROR_ALLOC_FAIL, ERROR_NOT_ENOUGH_MEMORY );2523goto bail_and_fail;2524}2525ZeroMemory(fol, sizeof(struct fdi_folder));2526if (!CAB(firstfol)) CAB(firstfol) = fol;25272528fol->offset = (cab_off_t) EndGetI32(buf+cffold_DataOffset);2529fol->num_blocks = EndGetI16(buf+cffold_NumBlocks);2530fol->comp_type = EndGetI16(buf+cffold_CompType);25312532if (linkfol)2533linkfol->next = fol;2534linkfol = fol;2535}25362537/* read files */2538for (i = 0; i < fdici.cFiles; i++) {2539if (fdi->read(cabhf, buf, cffile_SIZEOF) != cffile_SIZEOF) {2540set_error( fdi, FDIERROR_CORRUPT_CABINET, 0 );2541goto bail_and_fail;2542}25432544file = fdi->alloc(sizeof(struct fdi_file));2545if (!file) {2546ERR("out of memory!\n");2547set_error( fdi, FDIERROR_ALLOC_FAIL, ERROR_NOT_ENOUGH_MEMORY );2548goto bail_and_fail;2549}2550ZeroMemory(file, sizeof(struct fdi_file));2551if (!CAB(firstfile)) CAB(firstfile) = file;25522553file->length = EndGetI32(buf+cffile_UncompressedSize);2554file->offset = EndGetI32(buf+cffile_FolderOffset);2555file->index = EndGetI16(buf+cffile_FolderIndex);2556file->time = EndGetI16(buf+cffile_Time);2557file->date = EndGetI16(buf+cffile_Date);2558file->attribs = EndGetI16(buf+cffile_Attribs);2559file->filename = FDI_read_string(fdi, cabhf, fdici.cbCabinet);25602561if (!file->filename) {2562set_error( fdi, FDIERROR_CORRUPT_CABINET, 0 );2563goto bail_and_fail;2564}25652566if (linkfile)2567linkfile->next = file;2568linkfile = file;2569}25702571for (file = CAB(firstfile); (file); file = file->next) {25722573/*2574* FIXME: This implementation keeps multiple cabinet files open at once2575* when encountering a split cabinet. It is a quirk of this implementation2576* that sometimes we decrypt the same block of data more than once, to find2577* the right starting point for a file, moving the file-pointer backwards.2578* If we kept a cache of certain file-pointer information, we could eliminate2579* that behavior... in fact I am not sure that the caching we already have2580* is not sufficient.2581*2582* The current implementation seems to work fine in straightforward situations2583* where all the cabinet files needed for decryption are simultaneously2584* available. But presumably, the API is supposed to support cabinets which2585* are split across multiple CDROMS; we may need to change our implementation2586* to strictly serialize its file usage so that it opens only one cabinet2587* at a time. Some experimentation with Windows is needed to figure out the2588* precise semantics required. The relevant code is here and in fdi_decomp().2589*/25902591/* partial-file notification */2592if ((file->index & cffileCONTINUED_FROM_PREV) == cffileCONTINUED_FROM_PREV) {2593/*2594* FIXME: Need to create a Cabinet with a single file spanning multiple files2595* and perform some tests to figure out the right behavior. The SDK says2596* FDICopy will notify the user of the filename and "disk name" (info) of2597* the cabinet where the spanning file /started/.2598*2599* That would certainly be convenient for the API-user, who could abort,2600* everything (or parallelize, if that's allowed (it is in wine)), and call2601* FDICopy again with the provided filename, so as to avoid partial file2602* notification and successfully unpack. This task could be quite unpleasant2603* from wine's perspective: the information specifying the "start cabinet" for2604* a file is associated nowhere with the file header and is not to be found in2605* the cabinet header. We have only the index of the cabinet wherein the folder2606* begins, which contains the file. To find that cabinet, we must consider the2607* index of the current cabinet, and chain backwards, cabinet-by-cabinet (for2608* each cabinet refers to its "next" and "previous" cabinet only, like a linked2609* list).2610*2611* Bear in mind that, in the spirit of CABINET.DLL, we must assume that any2612* cabinet other than the active one might be at another filepath than the2613* current one, or on another CDROM. This could get rather dicey, especially2614* if we imagine parallelized access to the FDICopy API.2615*2616* The current implementation punts -- it just returns the previous cabinet and2617* its info from the header of this cabinet. This provides the right answer in2618* 95% of the cases; it's worth checking if Microsoft cuts the same corner before2619* we "fix" it.2620*/2621ZeroMemory(&fdin, sizeof(FDINOTIFICATION));2622fdin.pv = pvUser;2623fdin.psz1 = (char *)file->filename;2624fdin.psz2 = (CAB(mii).prevname) ? CAB(mii).prevname : &emptystring;2625fdin.psz3 = (CAB(mii).previnfo) ? CAB(mii).previnfo : &emptystring;26262627if (pfnfdin(fdintPARTIAL_FILE, &fdin) == -1) {2628set_error( fdi, FDIERROR_USER_ABORT, 0 );2629goto bail_and_fail;2630}2631/* I don't think we are supposed to decompress partial files. This prevents it. */2632file->oppressed = TRUE;2633}2634if (file->oppressed) {2635filehf = 0;2636} else {2637ZeroMemory(&fdin, sizeof(FDINOTIFICATION));2638fdin.pv = pvUser;2639fdin.psz1 = (char *)file->filename;2640fdin.cb = file->length;2641fdin.date = file->date;2642fdin.time = file->time;2643fdin.attribs = file->attribs;2644fdin.iFolder = file->index;2645if ((filehf = ((*pfnfdin)(fdintCOPY_FILE, &fdin))) == -1) {2646set_error( fdi, FDIERROR_USER_ABORT, 0 );2647filehf = 0;2648goto bail_and_fail;2649}2650}26512652/* find the folder for this file if necc. */2653if (filehf) {2654fol = CAB(firstfol);2655if ((file->index & cffileCONTINUED_TO_NEXT) == cffileCONTINUED_TO_NEXT) {2656/* pick the last folder */2657while (fol->next) fol = fol->next;2658} else {2659unsigned int i2;26602661for (i2 = 0; (i2 < file->index); i2++)2662if (fol->next) /* bug resistance, should always be true */2663fol = fol->next;2664}2665}26662667if (filehf) {2668cab_UWORD comptype = fol->comp_type;2669int ct1 = comptype & cffoldCOMPTYPE_MASK;2670int ct2 = CAB(current) ? (CAB(current)->comp_type & cffoldCOMPTYPE_MASK) : 0;2671int err = 0;26722673TRACE("Extracting file %s as requested by callee.\n", debugstr_a(file->filename));26742675/* set up decomp_state */2676CAB(fdi) = fdi;2677CAB(filehf) = filehf;26782679/* Was there a change of folder? Compression type? Did we somehow go backwards? */2680if ((ct1 != ct2) || (CAB(current) != fol) || (file->offset < CAB(offset))) {26812682TRACE("Resetting folder for file %s.\n", debugstr_a(file->filename));26832684/* free stuff for the old decompressor */2685switch (ct2) {2686case cffoldCOMPTYPE_LZX:2687if (LZX(window)) {2688fdi->free(LZX(window));2689LZX(window) = NULL;2690}2691break;2692case cffoldCOMPTYPE_QUANTUM:2693if (QTM(window)) {2694fdi->free(QTM(window));2695QTM(window) = NULL;2696}2697break;2698}26992700CAB(decomp_cab) = NULL;2701CAB(fdi)->seek(CAB(cabhf), fol->offset, SEEK_SET);2702CAB(offset) = 0;2703CAB(outlen) = 0;27042705/* initialize the new decompressor */2706switch (ct1) {2707case cffoldCOMPTYPE_NONE:2708CAB(decompress) = NONEfdi_decomp;2709break;2710case cffoldCOMPTYPE_MSZIP:2711CAB(decompress) = ZIPfdi_decomp;2712break;2713case cffoldCOMPTYPE_QUANTUM:2714CAB(decompress) = QTMfdi_decomp;2715err = QTMfdi_init((comptype >> 8) & 0x1f, (comptype >> 4) & 0xF, decomp_state);2716break;2717case cffoldCOMPTYPE_LZX:2718CAB(decompress) = LZXfdi_decomp;2719err = LZXfdi_init((comptype >> 8) & 0x1f, decomp_state);2720break;2721default:2722err = DECR_DATAFORMAT;2723}2724}27252726CAB(current) = fol;27272728switch (err) {2729case DECR_OK:2730break;2731case DECR_NOMEMORY:2732set_error( fdi, FDIERROR_ALLOC_FAIL, ERROR_NOT_ENOUGH_MEMORY );2733goto bail_and_fail;2734default:2735set_error( fdi, FDIERROR_CORRUPT_CABINET, 0 );2736goto bail_and_fail;2737}27382739if (file->offset > CAB(offset)) {2740/* decode bytes and send them to /dev/null */2741switch (fdi_decomp(file, 0, decomp_state, pszCabPath, pfnfdin, pvUser)) {2742case DECR_OK:2743break;2744case DECR_USERABORT:2745set_error( fdi, FDIERROR_USER_ABORT, 0 );2746goto bail_and_fail;2747case DECR_NOMEMORY:2748set_error( fdi, FDIERROR_ALLOC_FAIL, ERROR_NOT_ENOUGH_MEMORY );2749goto bail_and_fail;2750default:2751set_error( fdi, FDIERROR_CORRUPT_CABINET, 0 );2752goto bail_and_fail;2753}2754CAB(offset) = file->offset;2755}27562757/* now do the actual decompression */2758err = fdi_decomp(file, 1, decomp_state, pszCabPath, pfnfdin, pvUser);2759if (err) CAB(current) = NULL; else CAB(offset) += file->length;27602761/* fdintCLOSE_FILE_INFO notification */2762ZeroMemory(&fdin, sizeof(FDINOTIFICATION));2763fdin.pv = pvUser;2764fdin.psz1 = (char *)file->filename;2765fdin.hf = filehf;2766fdin.cb = (file->attribs & cffile_A_EXEC) != 0; /* FIXME: is that right? */2767fdin.date = file->date;2768fdin.time = file->time;2769fdin.attribs = file->attribs; /* FIXME: filter _A_EXEC? */2770fdin.iFolder = file->index;2771((*pfnfdin)(fdintCLOSE_FILE_INFO, &fdin));2772filehf = 0;27732774switch (err) {2775case DECR_OK:2776break;2777case DECR_USERABORT:2778set_error( fdi, FDIERROR_USER_ABORT, 0 );2779goto bail_and_fail;2780case DECR_NOMEMORY:2781set_error( fdi, FDIERROR_ALLOC_FAIL, ERROR_NOT_ENOUGH_MEMORY );2782goto bail_and_fail;2783default:2784set_error( fdi, FDIERROR_CORRUPT_CABINET, 0 );2785goto bail_and_fail;2786}2787}2788}27892790if (fol) free_decompression_temps(fdi, fol, decomp_state);2791free_decompression_mem(fdi, decomp_state);27922793return TRUE;27942795bail_and_fail: /* here we free ram before error returns */27962797if (fol) free_decompression_temps(fdi, fol, decomp_state);27982799if (filehf) fdi->close(filehf);28002801free_decompression_mem(fdi, decomp_state);28022803return FALSE;2804}28052806/***********************************************************************2807* FDIDestroy (CABINET.23)2808*2809* Frees a handle created by FDICreate. Do /not/ call this in the middle2810* of FDICopy. Only reason for failure would be an invalid handle.2811*2812* PARAMS2813* hfdi [I] The HFDI to free2814*2815* RETURNS2816* TRUE for success2817* FALSE for failure2818*/2819BOOL __cdecl FDIDestroy(HFDI hfdi)2820{2821FDI_Int *fdi = get_fdi_ptr( hfdi );28222823TRACE("(hfdi == ^%p)\n", hfdi);2824if (!fdi) return FALSE;2825fdi->magic = 0; /* paranoia */2826fdi->free(fdi);2827return TRUE;2828}28292830/***********************************************************************2831* FDITruncateCabinet (CABINET.24)2832*2833* Removes all folders of a cabinet file after and including the2834* specified folder number.2835*2836* PARAMS2837* hfdi [I] Handle to the FDI context.2838* pszCabinetName [I] Filename of the cabinet.2839* iFolderToDelete [I] Index of the first folder to delete.2840*2841* RETURNS2842* Success: TRUE.2843* Failure: FALSE.2844*2845* NOTES2846* The PFNWRITE function supplied to FDICreate must truncate the2847* file at the current position if the number of bytes to write is 0.2848*/2849BOOL __cdecl FDITruncateCabinet(2850HFDI hfdi,2851char *pszCabinetName,2852USHORT iFolderToDelete)2853{2854FDI_Int *fdi = get_fdi_ptr( hfdi );28552856FIXME("(hfdi == ^%p, pszCabinetName == %s, iFolderToDelete == %hu): stub\n",2857hfdi, debugstr_a(pszCabinetName), iFolderToDelete);28582859if (!fdi) return FALSE;28602861SetLastError(ERROR_CALL_NOT_IMPLEMENTED);2862return FALSE;2863}286428652866