Fixed definitions of TTTOOLINFOA/W_V1_SIZE and
[wine] / dlls / lzexpand / lzexpand_main.c
1 /*
2  * LZ Decompression functions
3  *
4  * Copyright 1996 Marcus Meissner
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 /*
21  * FIXME: return values might be wrong
22  */
23
24 #include "config.h"
25
26 #include <string.h>
27 #include <ctype.h>
28 #include <sys/types.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "lzexpand.h"
38
39 #include "wine/unicode.h"
40
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(file);
44
45 /* The readahead length of the decompressor. Reading single bytes
46  * using _lread() would be SLOW.
47  */
48 #define GETLEN  2048
49
50 /* Format of first 14 byte of LZ compressed file */
51 struct lzfileheader {
52         BYTE    magic[8];
53         BYTE    compressiontype;
54         CHAR    lastchar;
55         DWORD   reallength;
56 };
57 static BYTE LZMagic[8]={'S','Z','D','D',0x88,0xf0,0x27,0x33};
58
59 struct lzstate {
60         HFILE   realfd;         /* the real filedescriptor */
61         CHAR    lastchar;       /* the last char of the filename */
62
63         DWORD   reallength;     /* the decompressed length of the file */
64         DWORD   realcurrent;    /* the position the decompressor currently is */
65         DWORD   realwanted;     /* the position the user wants to read from */
66
67         BYTE    table[0x1000];  /* the rotating LZ table */
68         UINT    curtabent;      /* CURrent TABle ENTry */
69
70         BYTE    stringlen;      /* length and position of current string */
71         DWORD   stringpos;      /* from stringtable */
72
73
74         WORD    bytetype;       /* bitmask within blocks */
75
76         BYTE    *get;           /* GETLEN bytes */
77         DWORD   getcur;         /* current read */
78         DWORD   getlen;         /* length last got */
79 };
80
81 #define MAX_LZSTATES 16
82 static struct lzstate *lzstates[MAX_LZSTATES];
83
84 #define IS_LZ_HANDLE(h) (((h) >= 0x400) && ((h) < 0x400+MAX_LZSTATES))
85 #define GET_LZ_STATE(h) (IS_LZ_HANDLE(h) ? lzstates[(h)-0x400] : NULL)
86
87 /* reads one compressed byte, including buffering */
88 #define GET(lzs,b)      _lzget(lzs,&b)
89 #define GET_FLUSH(lzs)  lzs->getcur=lzs->getlen;
90
91 static int
92 _lzget(struct lzstate *lzs,BYTE *b) {
93         if (lzs->getcur<lzs->getlen) {
94                 *b              = lzs->get[lzs->getcur++];
95                 return          1;
96         } else {
97                 int ret = _lread(lzs->realfd,lzs->get,GETLEN);
98                 if (ret==HFILE_ERROR)
99                         return HFILE_ERROR;
100                 if (ret==0)
101                         return 0;
102                 lzs->getlen     = ret;
103                 lzs->getcur     = 1;
104                 *b              = *(lzs->get);
105                 return 1;
106         }
107 }
108 /* internal function, reads lzheader
109  * returns BADINHANDLE for non filedescriptors
110  * return 0 for file not compressed using LZ
111  * return UNKNOWNALG for unknown algorithm
112  * returns lzfileheader in *head
113  */
114 static INT read_header(HFILE fd,struct lzfileheader *head)
115 {
116         BYTE    buf[14];
117
118         if (_llseek(fd,0,SEEK_SET)==-1)
119                 return LZERROR_BADINHANDLE;
120
121         /* We can't directly read the lzfileheader struct due to
122          * structure element alignment
123          */
124         if (_lread(fd,buf,14)<14)
125                 return 0;
126         memcpy(head->magic,buf,8);
127         memcpy(&(head->compressiontype),buf+8,1);
128         memcpy(&(head->lastchar),buf+9,1);
129
130         /* FIXME: consider endianess on non-intel architectures */
131         memcpy(&(head->reallength),buf+10,4);
132
133         if (memcmp(head->magic,LZMagic,8))
134                 return 0;
135         if (head->compressiontype!='A')
136                 return LZERROR_UNKNOWNALG;
137         return 1;
138 }
139
140
141 /***********************************************************************
142  *           LZStart   (LZ32.@)
143  */
144 INT WINAPI LZStart(void)
145 {
146     TRACE("(void)\n");
147     return 1;
148 }
149
150
151 /***********************************************************************
152  *           LZInit   (LZ32.@)
153  *
154  * initializes internal decompression buffers, returns lzfiledescriptor.
155  * (return value the same as hfSrc, if hfSrc is not compressed)
156  * on failure, returns error code <0
157  * lzfiledescriptors range from 0x400 to 0x410 (only 16 open files per process)
158  *
159  * since _llseek uses the same types as libc.lseek, we just use the macros of
160  *  libc
161  */
162 HFILE WINAPI LZInit( HFILE hfSrc )
163 {
164
165         struct  lzfileheader    head;
166         struct  lzstate         *lzs;
167         DWORD   ret;
168         int i;
169
170         TRACE("(%d)\n",hfSrc);
171         ret=read_header(hfSrc,&head);
172         if (ret<=0) {
173                 _llseek(hfSrc,0,SEEK_SET);
174                 return ret?ret:hfSrc;
175         }
176         for (i = 0; i < MAX_LZSTATES; i++) if (!lzstates[i]) break;
177         if (i == MAX_LZSTATES) return LZERROR_GLOBALLOC;
178         lzstates[i] = lzs = HeapAlloc( GetProcessHeap(), 0, sizeof(struct lzstate) );
179         if(lzs == NULL) return LZERROR_GLOBALLOC;
180
181         memset(lzs,'\0',sizeof(*lzs));
182         lzs->realfd     = hfSrc;
183         lzs->lastchar   = head.lastchar;
184         lzs->reallength = head.reallength;
185
186         lzs->get        = HeapAlloc( GetProcessHeap(), 0, GETLEN );
187         lzs->getlen     = 0;
188         lzs->getcur     = 0;
189
190         if(lzs->get == NULL) {
191                 HeapFree(GetProcessHeap(), 0, lzs);
192                 lzstates[i] = NULL;
193                 return LZERROR_GLOBALLOC;
194         }
195
196         /* Yes, preinitialize with spaces */
197         memset(lzs->table,' ',0x1000);
198         /* Yes, start 16 byte from the END of the table */
199         lzs->curtabent  = 0xff0;
200         return 0x400 + i;
201 }
202
203
204 /***********************************************************************
205  *           LZDone   (LZEXPAND.9)
206  *           LZDone   (LZ32.@)
207  */
208 void WINAPI LZDone(void)
209 {
210     TRACE("(void)\n");
211 }
212
213
214 /***********************************************************************
215  *           GetExpandedNameA   (LZ32.@)
216  *
217  * gets the full filename of the compressed file 'in' by opening it
218  * and reading the header
219  *
220  * "file." is being translated to "file"
221  * "file.bl_" (with lastchar 'a') is being translated to "file.bla"
222  * "FILE.BL_" (with lastchar 'a') is being translated to "FILE.BLA"
223  */
224
225 INT WINAPI GetExpandedNameA( LPSTR in, LPSTR out )
226 {
227         struct lzfileheader     head;
228         HFILE           fd;
229         OFSTRUCT        ofs;
230         INT             fnislowercased,ret,len;
231         LPSTR           s,t;
232
233         TRACE("(%s)\n",in);
234         fd=OpenFile(in,&ofs,OF_READ);
235         if (fd==HFILE_ERROR)
236                 return (INT)(INT16)LZERROR_BADINHANDLE;
237         strcpy(out,in);
238         ret=read_header(fd,&head);
239         if (ret<=0) {
240                 /* not a LZ compressed file, so the expanded name is the same
241                  * as the input name */
242                 _lclose(fd);
243                 return 1;
244         }
245
246
247         /* look for directory prefix and skip it. */
248         s=out;
249         while (NULL!=(t=strpbrk(s,"/\\:")))
250                 s=t+1;
251
252         /* now mangle the basename */
253         if (!*s) {
254                 /* FIXME: hmm. shouldn't happen? */
255                 WARN("Specified a directory or what? (%s)\n",in);
256                 _lclose(fd);
257                 return 1;
258         }
259         /* see if we should use lowercase or uppercase on the last char */
260         fnislowercased=1;
261         t=s+strlen(s)-1;
262         while (t>=out) {
263                 if (!isalpha(*t)) {
264                         t--;
265                         continue;
266                 }
267                 fnislowercased=islower(*t);
268                 break;
269         }
270         if (isalpha(head.lastchar)) {
271                 if (fnislowercased)
272                         head.lastchar=tolower(head.lastchar);
273                 else
274                         head.lastchar=toupper(head.lastchar);
275         }
276
277         /* now look where to replace the last character */
278         if (NULL!=(t=strchr(s,'.'))) {
279                 if (t[1]=='\0') {
280                         t[0]='\0';
281                 } else {
282                         len=strlen(t)-1;
283                         if (t[len]=='_')
284                                 t[len]=head.lastchar;
285                 }
286         } /* else no modification necessary */
287         _lclose(fd);
288         return 1;
289 }
290
291
292 /***********************************************************************
293  *           GetExpandedNameW   (LZ32.@)
294  */
295 INT WINAPI GetExpandedNameW( LPWSTR in, LPWSTR out )
296 {
297     INT ret;
298     DWORD len = WideCharToMultiByte( CP_ACP, 0, in, -1, NULL, 0, NULL, NULL );
299     char *xin = HeapAlloc( GetProcessHeap(), 0, len );
300     char *xout = HeapAlloc( GetProcessHeap(), 0, len+3 );
301     WideCharToMultiByte( CP_ACP, 0, in, -1, xin, len, NULL, NULL );
302     if ((ret = GetExpandedNameA( xin, xout )) > 0)
303         MultiByteToWideChar( CP_ACP, 0, xout, -1, out, strlenW(in)+4 );
304     HeapFree( GetProcessHeap(), 0, xin );
305     HeapFree( GetProcessHeap(), 0, xout );
306     return ret;
307 }
308
309
310 /***********************************************************************
311  *           LZRead   (LZ32.@)
312  */
313 INT WINAPI LZRead( HFILE fd, LPSTR vbuf, INT toread )
314 {
315         int     howmuch;
316         BYTE    b,*buf;
317         struct  lzstate *lzs;
318
319         buf=(LPBYTE)vbuf;
320         TRACE("(%d,%p,%d)\n",fd,buf,toread);
321         howmuch=toread;
322         if (!(lzs = GET_LZ_STATE(fd))) return _lread(fd,buf,toread);
323
324 /* The decompressor itself is in a define, cause we need it twice
325  * in this function. (the decompressed byte will be in b)
326  */
327 #define DECOMPRESS_ONE_BYTE                                             \
328                 if (lzs->stringlen) {                                   \
329                         b               = lzs->table[lzs->stringpos];   \
330                         lzs->stringpos  = (lzs->stringpos+1)&0xFFF;     \
331                         lzs->stringlen--;                               \
332                 } else {                                                \
333                         if (!(lzs->bytetype&0x100)) {                   \
334                                 if (1!=GET(lzs,b))                      \
335                                         return toread-howmuch;          \
336                                 lzs->bytetype = b|0xFF00;               \
337                         }                                               \
338                         if (lzs->bytetype & 1) {                        \
339                                 if (1!=GET(lzs,b))                      \
340                                         return toread-howmuch;          \
341                         } else {                                        \
342                                 BYTE    b1,b2;                          \
343                                                                         \
344                                 if (1!=GET(lzs,b1))                     \
345                                         return toread-howmuch;          \
346                                 if (1!=GET(lzs,b2))                     \
347                                         return toread-howmuch;          \
348                                 /* Format:                              \
349                                  * b1 b2                                \
350                                  * AB CD                                \
351                                  * where CAB is the stringoffset in the table\
352                                  * and D+3 is the len of the string     \
353                                  */                                     \
354                                 lzs->stringpos  = b1|((b2&0xf0)<<4);    \
355                                 lzs->stringlen  = (b2&0xf)+2;           \
356                                 /* 3, but we use a  byte already below ... */\
357                                 b               = lzs->table[lzs->stringpos];\
358                                 lzs->stringpos  = (lzs->stringpos+1)&0xFFF;\
359                         }                                               \
360                         lzs->bytetype>>=1;                              \
361                 }                                                       \
362                 /* store b in table */                                  \
363                 lzs->table[lzs->curtabent++]= b;                        \
364                 lzs->curtabent  &= 0xFFF;                               \
365                 lzs->realcurrent++;
366
367         /* if someone has seeked, we have to bring the decompressor
368          * to that position
369          */
370         if (lzs->realcurrent!=lzs->realwanted) {
371                 /* if the wanted position is before the current position
372                  * I see no easy way to unroll ... We have to restart at
373                  * the beginning. *sigh*
374                  */
375                 if (lzs->realcurrent>lzs->realwanted) {
376                         /* flush decompressor state */
377                         _llseek(lzs->realfd,14,SEEK_SET);
378                         GET_FLUSH(lzs);
379                         lzs->realcurrent= 0;
380                         lzs->bytetype   = 0;
381                         lzs->stringlen  = 0;
382                         memset(lzs->table,' ',0x1000);
383                         lzs->curtabent  = 0xFF0;
384                 }
385                 while (lzs->realcurrent<lzs->realwanted) {
386                         DECOMPRESS_ONE_BYTE;
387                 }
388         }
389
390         while (howmuch) {
391                 DECOMPRESS_ONE_BYTE;
392                 lzs->realwanted++;
393                 *buf++          = b;
394                 howmuch--;
395         }
396         return  toread;
397 #undef DECOMPRESS_ONE_BYTE
398 }
399
400
401 /***********************************************************************
402  *           LZSeek   (LZ32.@)
403  */
404 LONG WINAPI LZSeek( HFILE fd, LONG off, INT type )
405 {
406         struct  lzstate *lzs;
407         LONG    newwanted;
408
409         TRACE("(%d,%ld,%d)\n",fd,off,type);
410         /* not compressed? just use normal _llseek() */
411         if (!(lzs = GET_LZ_STATE(fd))) return _llseek(fd,off,type);
412         newwanted = lzs->realwanted;
413         switch (type) {
414         case 1: /* SEEK_CUR */
415                 newwanted      += off;
416                 break;
417         case 2: /* SEEK_END */
418                 newwanted       = lzs->reallength-off;
419                 break;
420         default:/* SEEK_SET */
421                 newwanted       = off;
422                 break;
423         }
424         if (newwanted>lzs->reallength)
425                 return LZERROR_BADVALUE;
426         if (newwanted<0)
427                 return LZERROR_BADVALUE;
428         lzs->realwanted = newwanted;
429         return newwanted;
430 }
431
432
433 /***********************************************************************
434  *           LZCopy   (LZ32.@)
435  *
436  * Copies everything from src to dest
437  * if src is a LZ compressed file, it will be uncompressed.
438  * will return the number of bytes written to dest or errors.
439  */
440 LONG WINAPI LZCopy( HFILE src, HFILE dest )
441 {
442         int     usedlzinit = 0, ret, wret;
443         LONG    len;
444         HFILE   oldsrc = src, srcfd;
445         FILETIME filetime;
446         struct  lzstate *lzs;
447 #define BUFLEN  1000
448         BYTE    buf[BUFLEN];
449         /* we need that weird typedef, for i can't seem to get function pointer
450          * casts right. (Or they probably just do not like WINAPI in general)
451          */
452         typedef UINT    (WINAPI *_readfun)(HFILE,LPVOID,UINT);
453
454         _readfun        xread;
455
456         TRACE("(%d,%d)\n",src,dest);
457         if (!IS_LZ_HANDLE(src)) {
458                 src = LZInit(src);
459                 if ((INT)src <= 0) return 0;
460                 if (src != oldsrc) usedlzinit=1;
461         }
462
463         /* not compressed? just copy */
464         if (!IS_LZ_HANDLE(src))
465                 xread=_lread;
466         else
467                 xread=(_readfun)LZRead;
468         len=0;
469         while (1) {
470                 ret=xread(src,buf,BUFLEN);
471                 if (ret<=0) {
472                         if (ret==0)
473                                 break;
474                         if (ret==-1)
475                                 return LZERROR_READ;
476                         return ret;
477                 }
478                 len    += ret;
479                 wret    = _lwrite(dest,buf,ret);
480                 if (wret!=ret)
481                         return LZERROR_WRITE;
482         }
483
484         /* Maintain the timestamp of source file to destination file */
485         srcfd = (!(lzs = GET_LZ_STATE(src))) ? src : lzs->realfd;
486         GetFileTime((HANDLE)srcfd, NULL, NULL, &filetime);
487         SetFileTime((HANDLE)dest, NULL, NULL, &filetime);
488
489         /* close handle */
490         if (usedlzinit)
491                 LZClose(src);
492         return len;
493 #undef BUFLEN
494 }
495
496 /* reverses GetExpandedPathname */
497 static LPSTR LZEXPAND_MangleName( LPCSTR fn )
498 {
499     char *p;
500     char *mfn = (char *)HeapAlloc( GetProcessHeap(), 0,
501                                    strlen(fn) + 3 ); /* "._" and \0 */
502     if(mfn == NULL) return NULL;
503     strcpy( mfn, fn );
504     if (!(p = strrchr( mfn, '\\' ))) p = mfn;
505     if ((p = strchr( p, '.' )))
506     {
507         p++;
508         if (strlen(p) < 3) strcat( p, "_" );  /* append '_' */
509         else p[strlen(p)-1] = '_';  /* replace last character */
510     }
511     else strcat( mfn, "._" );   /* append "._" */
512     return mfn;
513 }
514
515
516 /***********************************************************************
517  *           LZOpenFileA   (LZ32.@)
518  *
519  * Opens a file. If not compressed, open it as a normal file.
520  */
521 HFILE WINAPI LZOpenFileA( LPSTR fn, LPOFSTRUCT ofs, WORD mode )
522 {
523         HFILE   fd,cfd;
524
525         TRACE("(%s,%p,%d)\n",fn,ofs,mode);
526         /* 0x70 represents all OF_SHARE_* flags, ignore them for the check */
527         fd=OpenFile(fn,ofs,mode);
528         if (fd==HFILE_ERROR)
529         {
530             LPSTR mfn = LZEXPAND_MangleName(fn);
531             fd = OpenFile(mfn,ofs,mode);
532             HeapFree( GetProcessHeap(), 0, mfn );
533         }
534         if ((mode&~0x70)!=OF_READ)
535                 return fd;
536         if (fd==HFILE_ERROR)
537                 return HFILE_ERROR;
538         cfd=LZInit(fd);
539         if ((INT)cfd <= 0) return fd;
540         return cfd;
541 }
542
543
544 /***********************************************************************
545  *           LZOpenFileW   (LZ32.@)
546  */
547 HFILE WINAPI LZOpenFileW( LPWSTR fn, LPOFSTRUCT ofs, WORD mode )
548 {
549     HFILE ret;
550     DWORD len = WideCharToMultiByte( CP_ACP, 0, fn, -1, NULL, 0, NULL, NULL );
551     LPSTR xfn = HeapAlloc( GetProcessHeap(), 0, len );
552     WideCharToMultiByte( CP_ACP, 0, fn, -1, xfn, len, NULL, NULL );
553     ret = LZOpenFileA(xfn,ofs,mode);
554     HeapFree( GetProcessHeap(), 0, xfn );
555     return ret;
556 }
557
558
559 /***********************************************************************
560  *           LZClose   (LZ32.@)
561  */
562 void WINAPI LZClose( HFILE fd )
563 {
564         struct lzstate *lzs;
565
566         TRACE("(%d)\n",fd);
567         if (!(lzs = GET_LZ_STATE(fd))) _lclose(fd);
568         else
569         {
570             if (lzs->get) HeapFree( GetProcessHeap(), 0, lzs->get );
571             CloseHandle((HANDLE)lzs->realfd);
572             lzstates[fd - 0x400] = NULL;
573             HeapFree( GetProcessHeap(), 0, lzs );
574         }
575 }
576
577
578 /***********************************************************************
579  *           CopyLZFile  (LZ32.@)
580  *
581  * Copy src to dest (including uncompressing src).
582  * NOTE: Yes. This is exactly the same function as LZCopy.
583  */
584 LONG WINAPI CopyLZFile( HFILE src, HFILE dest )
585 {
586     TRACE("(%d,%d)\n",src,dest);
587     return LZCopy(src,dest);
588 }