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