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