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