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