user32: Only try to remove the MDI document icon from the frame menu when needed.
[wine] / dlls / itss / chm_lib.c
1 /***************************************************************************
2  *             chm_lib.c - CHM archive manipulation routines               *
3  *                           -------------------                           *
4  *                                                                         *
5  *  author:     Jed Wing <jedwin@ugcs.caltech.edu>                         *
6  *  version:    0.3                                                        *
7  *  notes:      These routines are meant for the manipulation of microsoft *
8  *              .chm (compiled html help) files, but may likely be used    *
9  *              for the manipulation of any ITSS archive, if ever ITSS     *
10  *              archives are used for any other purpose.                   *
11  *                                                                         *
12  *              Note also that the section names are statically handled.   *
13  *              To be entirely correct, the section names should be read   *
14  *              from the section names meta-file, and then the various     *
15  *              content sections and the "transforms" to apply to the data *
16  *              they contain should be inferred from the section name and  *
17  *              the meta-files referenced using that name; however, all of *
18  *              the files I've been able to get my hands on appear to have *
19  *              only two sections: Uncompressed and MSCompressed.          *
20  *              Additionally, the ITSS.DLL file included with Windows does *
21  *              not appear to handle any different transforms than the     *
22  *              simple LZX-transform.  Furthermore, the list of transforms *
23  *              to apply is broken, in that only half the required space   *
24  *              is allocated for the list.  (It appears as though the      *
25  *              space is allocated for ASCII strings, but the strings are  *
26  *              written as unicode.  As a result, only the first half of   *
27  *              the string appears.)  So this is probably not too big of   *
28  *              a deal, at least until CHM v4 (MS .lit files), which also  *
29  *              incorporate encryption, of some description.               *
30  *                                                                         *
31  ***************************************************************************/
32
33 /***************************************************************************
34  *                                                                         *
35  *   This library is free software; you can redistribute it and/or modify  *
36  *   it under the terms of the GNU Lesser General Public License as        *
37  *   published by the Free Software Foundation; either version 2.1 of the  *
38  *   License, or (at your option) any later version.                       *
39  *                                                                         *
40  ***************************************************************************/
41
42 /***************************************************************************
43  *                                                                         *
44  * Adapted for Wine by Mike McCormack                                      *
45  *                                                                         *
46  ***************************************************************************/
47
48 #include "config.h"
49 #include "wine/port.h"
50
51 #include <stdarg.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55
56 #include "windef.h"
57 #include "winbase.h"
58 #include "wine/unicode.h"
59
60 #include "chm_lib.h"
61 #include "lzx.h"
62
63 #define CHM_ACQUIRE_LOCK(a) do {                        \
64         EnterCriticalSection(&(a));                     \
65     } while(0)
66 #define CHM_RELEASE_LOCK(a) do {                        \
67         LeaveCriticalSection(&(a));                     \
68     } while(0)
69
70 #define CHM_NULL_FD (INVALID_HANDLE_VALUE)
71 #define CHM_CLOSE_FILE(fd) CloseHandle((fd))
72
73 /*
74  * defines related to tuning
75  */
76 #ifndef CHM_MAX_BLOCKS_CACHED
77 #define CHM_MAX_BLOCKS_CACHED 5
78 #endif
79 #define CHM_PARAM_MAX_BLOCKS_CACHED 0
80
81 /*
82  * architecture specific defines
83  *
84  * Note: as soon as C99 is more widespread, the below defines should
85  * probably just use the C99 sized-int types.
86  *
87  * The following settings will probably work for many platforms.  The sizes
88  * don't have to be exactly correct, but the types must accommodate at least as
89  * many bits as they specify.
90  */
91
92 /* i386, 32-bit, Windows */
93 typedef BYTE   UChar;
94 typedef SHORT  Int16;
95 typedef USHORT UInt16;
96 typedef LONG   Int32;
97 typedef DWORD      UInt32;
98 typedef LONGLONG   Int64;
99 typedef ULONGLONG  UInt64;
100
101 /* utilities for unmarshalling data */
102 static int _unmarshal_char_array(unsigned char **pData,
103                                  unsigned int *pLenRemain,
104                                  char *dest,
105                                  int count)
106 {
107     if (count <= 0  ||  (unsigned int)count > *pLenRemain)
108         return 0;
109     memcpy(dest, (*pData), count);
110     *pData += count;
111     *pLenRemain -= count;
112     return 1;
113 }
114
115 static int _unmarshal_uchar_array(unsigned char **pData,
116                                   unsigned int *pLenRemain,
117                                   unsigned char *dest,
118                                   int count)
119 {
120         if (count <= 0  ||  (unsigned int)count > *pLenRemain)
121         return 0;
122     memcpy(dest, (*pData), count);
123     *pData += count;
124     *pLenRemain -= count;
125     return 1;
126 }
127
128 static int _unmarshal_int32(unsigned char **pData,
129                             unsigned int *pLenRemain,
130                             Int32 *dest)
131 {
132     if (4 > *pLenRemain)
133         return 0;
134     *dest = (*pData)[0] | (*pData)[1]<<8 | (*pData)[2]<<16 | (*pData)[3]<<24;
135     *pData += 4;
136     *pLenRemain -= 4;
137     return 1;
138 }
139
140 static int _unmarshal_uint32(unsigned char **pData,
141                              unsigned int *pLenRemain,
142                              UInt32 *dest)
143 {
144     if (4 > *pLenRemain)
145         return 0;
146     *dest = (*pData)[0] | (*pData)[1]<<8 | (*pData)[2]<<16 | (*pData)[3]<<24;
147     *pData += 4;
148     *pLenRemain -= 4;
149     return 1;
150 }
151
152 static int _unmarshal_int64(unsigned char **pData,
153                             unsigned int *pLenRemain,
154                             Int64 *dest)
155 {
156     Int64 temp;
157     int i;
158     if (8 > *pLenRemain)
159         return 0;
160     temp=0;
161     for(i=8; i>0; i--)
162     {
163         temp <<= 8;
164         temp |= (*pData)[i-1];
165     }
166     *dest = temp;
167     *pData += 8;
168     *pLenRemain -= 8;
169     return 1;
170 }
171
172 static int _unmarshal_uint64(unsigned char **pData,
173                              unsigned int *pLenRemain,
174                              UInt64 *dest)
175 {
176     UInt64 temp;
177     int i;
178     if (8 > *pLenRemain)
179         return 0;
180     temp=0;
181     for(i=8; i>0; i--)
182     {
183         temp <<= 8;
184         temp |= (*pData)[i-1];
185     }
186     *dest = temp;
187     *pData += 8;
188     *pLenRemain -= 8;
189     return 1;
190 }
191
192 static int _unmarshal_uuid(unsigned char **pData,
193                            unsigned int *pDataLen,
194                            unsigned char *dest)
195 {
196     return _unmarshal_uchar_array(pData, pDataLen, dest, 16);
197 }
198
199 /* names of sections essential to decompression */
200 static const WCHAR _CHMU_RESET_TABLE[] = {
201 ':',':','D','a','t','a','S','p','a','c','e','/',
202         'S','t','o','r','a','g','e','/',
203         'M','S','C','o','m','p','r','e','s','s','e','d','/',
204         'T','r','a','n','s','f','o','r','m','/',
205         '{','7','F','C','2','8','9','4','0','-','9','D','3','1',
206           '-','1','1','D','0','-','9','B','2','7','-',
207           '0','0','A','0','C','9','1','E','9','C','7','C','}','/',
208         'I','n','s','t','a','n','c','e','D','a','t','a','/',
209         'R','e','s','e','t','T','a','b','l','e',0
210 };
211 static const WCHAR _CHMU_LZXC_CONTROLDATA[] = {
212 ':',':','D','a','t','a','S','p','a','c','e','/',
213         'S','t','o','r','a','g','e','/',
214         'M','S','C','o','m','p','r','e','s','s','e','d','/',
215         'C','o','n','t','r','o','l','D','a','t','a',0
216 };
217 static const WCHAR _CHMU_CONTENT[] = {
218 ':',':','D','a','t','a','S','p','a','c','e','/',
219         'S','t','o','r','a','g','e','/',
220         'M','S','C','o','m','p','r','e','s','s','e','d','/',
221         'C','o','n','t','e','n','t',0
222 };
223
224 /*
225  * structures local to this module
226  */
227
228 /* structure of ITSF headers */
229 #define _CHM_ITSF_V2_LEN (0x58)
230 #define _CHM_ITSF_V3_LEN (0x60)
231 struct chmItsfHeader
232 {
233     char        signature[4];           /*  0 (ITSF) */
234     Int32       version;                /*  4 */
235     Int32       header_len;             /*  8 */
236     Int32       unknown_000c;           /*  c */
237     UInt32      last_modified;          /* 10 */
238     UInt32      lang_id;                /* 14 */
239     UChar       dir_uuid[16];           /* 18 */
240     UChar       stream_uuid[16];        /* 28 */
241     UInt64      unknown_offset;         /* 38 */
242     UInt64      unknown_len;            /* 40 */
243     UInt64      dir_offset;             /* 48 */
244     UInt64      dir_len;                /* 50 */
245     UInt64      data_offset;            /* 58 (Not present before V3) */
246 }; /* __attribute__ ((aligned (1))); */
247
248 static int _unmarshal_itsf_header(unsigned char **pData,
249                                   unsigned int *pDataLen,
250                                   struct chmItsfHeader *dest)
251 {
252     /* we only know how to deal with the 0x58 and 0x60 byte structures */
253     if (*pDataLen != _CHM_ITSF_V2_LEN  &&  *pDataLen != _CHM_ITSF_V3_LEN)
254         return 0;
255
256     /* unmarshal common fields */
257     _unmarshal_char_array(pData, pDataLen,  dest->signature, 4);
258     _unmarshal_int32     (pData, pDataLen, &dest->version);
259     _unmarshal_int32     (pData, pDataLen, &dest->header_len);
260     _unmarshal_int32     (pData, pDataLen, &dest->unknown_000c);
261     _unmarshal_uint32    (pData, pDataLen, &dest->last_modified);
262     _unmarshal_uint32    (pData, pDataLen, &dest->lang_id);
263     _unmarshal_uuid      (pData, pDataLen,  dest->dir_uuid);
264     _unmarshal_uuid      (pData, pDataLen,  dest->stream_uuid);
265     _unmarshal_uint64    (pData, pDataLen, &dest->unknown_offset);
266     _unmarshal_uint64    (pData, pDataLen, &dest->unknown_len);
267     _unmarshal_uint64    (pData, pDataLen, &dest->dir_offset);
268     _unmarshal_uint64    (pData, pDataLen, &dest->dir_len);
269
270     /* error check the data */
271     /* XXX: should also check UUIDs, probably, though with a version 3 file,
272      * current MS tools do not seem to use them.
273      */
274     if (memcmp(dest->signature, "ITSF", 4) != 0)
275         return 0;
276     if (dest->version == 2)
277     {
278         if (dest->header_len < _CHM_ITSF_V2_LEN)
279             return 0;
280     }
281     else if (dest->version == 3)
282     {
283         if (dest->header_len < _CHM_ITSF_V3_LEN)
284             return 0;
285     }
286     else
287         return 0;
288
289     /* now, if we have a V3 structure, unmarshal the rest.
290      * otherwise, compute it
291      */
292     if (dest->version == 3)
293     {
294         if (*pDataLen != 0)
295             _unmarshal_uint64(pData, pDataLen, &dest->data_offset);
296         else
297             return 0;
298     }
299     else
300         dest->data_offset = dest->dir_offset + dest->dir_len;
301
302     return 1;
303 }
304
305 /* structure of ITSP headers */
306 #define _CHM_ITSP_V1_LEN (0x54)
307 struct chmItspHeader
308 {
309     char        signature[4];           /*  0 (ITSP) */
310     Int32       version;                /*  4 */
311     Int32       header_len;             /*  8 */
312     Int32       unknown_000c;           /*  c */
313     UInt32      block_len;              /* 10 */
314     Int32       blockidx_intvl;         /* 14 */
315     Int32       index_depth;            /* 18 */
316     Int32       index_root;             /* 1c */
317     Int32       index_head;             /* 20 */
318     Int32       unknown_0024;           /* 24 */
319     UInt32      num_blocks;             /* 28 */
320     Int32       unknown_002c;           /* 2c */
321     UInt32      lang_id;                /* 30 */
322     UChar       system_uuid[16];        /* 34 */
323     UChar       unknown_0044[16];       /* 44 */
324 }; /* __attribute__ ((aligned (1))); */
325
326 static int _unmarshal_itsp_header(unsigned char **pData,
327                                   unsigned int *pDataLen,
328                                   struct chmItspHeader *dest)
329 {
330     /* we only know how to deal with a 0x54 byte structures */
331     if (*pDataLen != _CHM_ITSP_V1_LEN)
332         return 0;
333
334     /* unmarshal fields */
335     _unmarshal_char_array(pData, pDataLen,  dest->signature, 4);
336     _unmarshal_int32     (pData, pDataLen, &dest->version);
337     _unmarshal_int32     (pData, pDataLen, &dest->header_len);
338     _unmarshal_int32     (pData, pDataLen, &dest->unknown_000c);
339     _unmarshal_uint32    (pData, pDataLen, &dest->block_len);
340     _unmarshal_int32     (pData, pDataLen, &dest->blockidx_intvl);
341     _unmarshal_int32     (pData, pDataLen, &dest->index_depth);
342     _unmarshal_int32     (pData, pDataLen, &dest->index_root);
343     _unmarshal_int32     (pData, pDataLen, &dest->index_head);
344     _unmarshal_int32     (pData, pDataLen, &dest->unknown_0024);
345     _unmarshal_uint32    (pData, pDataLen, &dest->num_blocks);
346     _unmarshal_int32     (pData, pDataLen, &dest->unknown_002c);
347     _unmarshal_uint32    (pData, pDataLen, &dest->lang_id);
348     _unmarshal_uuid      (pData, pDataLen,  dest->system_uuid);
349     _unmarshal_uchar_array(pData, pDataLen, dest->unknown_0044, 16);
350
351     /* error check the data */
352     if (memcmp(dest->signature, "ITSP", 4) != 0)
353         return 0;
354     if (dest->version != 1)
355         return 0;
356     if (dest->header_len != _CHM_ITSP_V1_LEN)
357         return 0;
358
359     return 1;
360 }
361
362 /* structure of PMGL headers */
363 static const char _chm_pmgl_marker[4] = "PMGL";
364 #define _CHM_PMGL_LEN (0x14)
365 struct chmPmglHeader
366 {
367     char        signature[4];           /*  0 (PMGL) */
368     UInt32      free_space;             /*  4 */
369     UInt32      unknown_0008;           /*  8 */
370     Int32       block_prev;             /*  c */
371     Int32       block_next;             /* 10 */
372 }; /* __attribute__ ((aligned (1))); */
373
374 static int _unmarshal_pmgl_header(unsigned char **pData,
375                                   unsigned int *pDataLen,
376                                   struct chmPmglHeader *dest)
377 {
378     /* we only know how to deal with a 0x14 byte structures */
379     if (*pDataLen != _CHM_PMGL_LEN)
380         return 0;
381
382     /* unmarshal fields */
383     _unmarshal_char_array(pData, pDataLen,  dest->signature, 4);
384     _unmarshal_uint32    (pData, pDataLen, &dest->free_space);
385     _unmarshal_uint32    (pData, pDataLen, &dest->unknown_0008);
386     _unmarshal_int32     (pData, pDataLen, &dest->block_prev);
387     _unmarshal_int32     (pData, pDataLen, &dest->block_next);
388
389     /* check structure */
390     if (memcmp(dest->signature, _chm_pmgl_marker, 4) != 0)
391         return 0;
392
393     return 1;
394 }
395
396 /* structure of PMGI headers */
397 static const char _chm_pmgi_marker[4] = "PMGI";
398 #define _CHM_PMGI_LEN (0x08)
399 struct chmPmgiHeader
400 {
401     char        signature[4];           /*  0 (PMGI) */
402     UInt32      free_space;             /*  4 */
403 }; /* __attribute__ ((aligned (1))); */
404
405 static int _unmarshal_pmgi_header(unsigned char **pData,
406                                   unsigned int *pDataLen,
407                                   struct chmPmgiHeader *dest)
408 {
409     /* we only know how to deal with a 0x8 byte structures */
410     if (*pDataLen != _CHM_PMGI_LEN)
411         return 0;
412
413     /* unmarshal fields */
414     _unmarshal_char_array(pData, pDataLen,  dest->signature, 4);
415     _unmarshal_uint32    (pData, pDataLen, &dest->free_space);
416
417     /* check structure */
418     if (memcmp(dest->signature, _chm_pmgi_marker, 4) != 0)
419         return 0;
420
421     return 1;
422 }
423
424 /* structure of LZXC reset table */
425 #define _CHM_LZXC_RESETTABLE_V1_LEN (0x28)
426 struct chmLzxcResetTable
427 {
428     UInt32      version;
429     UInt32      block_count;
430     UInt32      unknown;
431     UInt32      table_offset;
432     UInt64      uncompressed_len;
433     UInt64      compressed_len;
434     UInt64      block_len;     
435 }; /* __attribute__ ((aligned (1))); */
436
437 static int _unmarshal_lzxc_reset_table(unsigned char **pData,
438                                        unsigned int *pDataLen,
439                                        struct chmLzxcResetTable *dest)
440 {
441     /* we only know how to deal with a 0x28 byte structures */
442     if (*pDataLen != _CHM_LZXC_RESETTABLE_V1_LEN)
443         return 0;
444
445     /* unmarshal fields */
446     _unmarshal_uint32    (pData, pDataLen, &dest->version);
447     _unmarshal_uint32    (pData, pDataLen, &dest->block_count);
448     _unmarshal_uint32    (pData, pDataLen, &dest->unknown);
449     _unmarshal_uint32    (pData, pDataLen, &dest->table_offset);
450     _unmarshal_uint64    (pData, pDataLen, &dest->uncompressed_len);
451     _unmarshal_uint64    (pData, pDataLen, &dest->compressed_len);
452     _unmarshal_uint64    (pData, pDataLen, &dest->block_len);
453
454     /* check structure */
455     if (dest->version != 2)
456         return 0;
457
458     return 1;
459 }
460
461 /* structure of LZXC control data block */
462 #define _CHM_LZXC_MIN_LEN (0x18)
463 #define _CHM_LZXC_V2_LEN (0x1c)
464 struct chmLzxcControlData
465 {
466     UInt32      size;                   /*  0        */
467     char        signature[4];           /*  4 (LZXC) */
468     UInt32      version;                /*  8        */
469     UInt32      resetInterval;          /*  c        */
470     UInt32      windowSize;             /* 10        */
471     UInt32      windowsPerReset;        /* 14        */
472     UInt32      unknown_18;             /* 18        */
473 };
474
475 static int _unmarshal_lzxc_control_data(unsigned char **pData,
476                                         unsigned int *pDataLen,
477                                         struct chmLzxcControlData *dest)
478 {
479     /* we want at least 0x18 bytes */
480     if (*pDataLen < _CHM_LZXC_MIN_LEN)
481         return 0;
482
483     /* unmarshal fields */
484     _unmarshal_uint32    (pData, pDataLen, &dest->size);
485     _unmarshal_char_array(pData, pDataLen,  dest->signature, 4);
486     _unmarshal_uint32    (pData, pDataLen, &dest->version);
487     _unmarshal_uint32    (pData, pDataLen, &dest->resetInterval);
488     _unmarshal_uint32    (pData, pDataLen, &dest->windowSize);
489     _unmarshal_uint32    (pData, pDataLen, &dest->windowsPerReset);
490
491     if (*pDataLen >= _CHM_LZXC_V2_LEN)
492         _unmarshal_uint32    (pData, pDataLen, &dest->unknown_18);
493     else
494         dest->unknown_18 = 0;
495
496     if (dest->version == 2)
497     {
498         dest->resetInterval *= 0x8000;
499         dest->windowSize *= 0x8000;
500     }
501     if (dest->windowSize == 0  ||  dest->resetInterval == 0)
502         return 0;
503
504     /* for now, only support resetInterval a multiple of windowSize/2 */
505     if (dest->windowSize == 1)
506         return 0;
507     if ((dest->resetInterval % (dest->windowSize/2)) != 0)
508         return 0;
509
510     /* check structure */
511     if (memcmp(dest->signature, "LZXC", 4) != 0)
512         return 0;
513
514     return 1;
515 }
516
517 /* the structure used for chm file handles */
518 struct chmFile
519 {
520     HANDLE              fd;
521
522     CRITICAL_SECTION    mutex;
523     CRITICAL_SECTION    lzx_mutex;
524     CRITICAL_SECTION    cache_mutex;
525
526     UInt64              dir_offset;
527     UInt64              dir_len;    
528     UInt64              data_offset;
529     Int32               index_root;
530     Int32               index_head;
531     UInt32              block_len;     
532
533     UInt64              span;
534     struct chmUnitInfo  rt_unit;
535     struct chmUnitInfo  cn_unit;
536     struct chmLzxcResetTable reset_table;
537
538     /* LZX control data */
539     int                 compression_enabled;
540     UInt32              window_size;
541     UInt32              reset_interval;
542     UInt32              reset_blkcount;
543
544     /* decompressor state */
545     struct LZXstate    *lzx_state;
546     int                 lzx_last_block;
547
548     /* cache for decompressed blocks */
549     UChar             **cache_blocks;
550     Int64              *cache_block_indices;
551     Int32               cache_num_blocks;
552 };
553
554 /*
555  * utility functions local to this module
556  */
557
558 /* utility function to handle differences between {pread,read}(64)? */
559 static Int64 _chm_fetch_bytes(struct chmFile *h,
560                               UChar *buf,
561                               UInt64 os,
562                               Int64 len)
563 {
564     Int64 readLen=0;
565     if (h->fd  ==  CHM_NULL_FD)
566         return readLen;
567
568     CHM_ACQUIRE_LOCK(h->mutex);
569     /* NOTE: this might be better done with CreateFileMapping, et cetera... */
570     {
571         LARGE_INTEGER old_pos, new_pos;
572         DWORD actualLen=0;
573
574         /* awkward Win32 Seek/Tell */
575         new_pos.QuadPart = 0;
576         SetFilePointerEx( h->fd, new_pos, &old_pos, FILE_CURRENT );
577         new_pos.QuadPart = os;
578         SetFilePointerEx( h->fd, new_pos, NULL, FILE_BEGIN );
579
580         /* read the data */
581         if (ReadFile(h->fd,
582                      buf,
583                      (DWORD)len,
584                      &actualLen,
585                      NULL))
586             readLen = actualLen;
587         else
588             readLen = 0;
589
590         /* restore original position */
591         SetFilePointerEx( h->fd, old_pos, NULL, FILE_BEGIN );
592     }
593     CHM_RELEASE_LOCK(h->mutex);
594     return readLen;
595 }
596
597 /*
598  * set a parameter on the file handle.
599  * valid parameter types:
600  *          CHM_PARAM_MAX_BLOCKS_CACHED:
601  *                 how many decompressed blocks should be cached?  A simple
602  *                 caching scheme is used, wherein the index of the block is
603  *                 used as a hash value, and hash collision results in the
604  *                 invalidation of the previously cached block.
605  */
606 static void chm_set_param(struct chmFile *h,
607                           int paramType,
608                           int paramVal)
609 {
610     switch (paramType)
611     {
612         case CHM_PARAM_MAX_BLOCKS_CACHED:
613             CHM_ACQUIRE_LOCK(h->cache_mutex);
614             if (paramVal != h->cache_num_blocks)
615             {
616                 UChar **newBlocks;
617                 Int64 *newIndices;
618                 int     i;
619
620                 /* allocate new cached blocks */
621                 newBlocks = malloc(paramVal * sizeof (UChar *));
622                 newIndices = malloc(paramVal * sizeof (UInt64));
623                 for (i=0; i<paramVal; i++)
624                 {
625                     newBlocks[i] = NULL;
626                     newIndices[i] = 0;
627                 }
628
629                 /* re-distribute old cached blocks */
630                 if (h->cache_blocks)
631                 {
632                     for (i=0; i<h->cache_num_blocks; i++)
633                     {
634                         int newSlot = (int)(h->cache_block_indices[i] % paramVal);
635
636                         if (h->cache_blocks[i])
637                         {
638                             /* in case of collision, destroy newcomer */
639                             if (newBlocks[newSlot])
640                             {
641                                 free(h->cache_blocks[i]);
642                                 h->cache_blocks[i] = NULL;
643                             }
644                             else
645                             {
646                                 newBlocks[newSlot] = h->cache_blocks[i];
647                                 newIndices[newSlot] =
648                                             h->cache_block_indices[i];
649                             }
650                         }
651                     }
652
653                     free(h->cache_blocks);
654                     free(h->cache_block_indices);
655                 }
656
657                 /* now, set new values */
658                 h->cache_blocks = newBlocks;
659                 h->cache_block_indices = newIndices;
660                 h->cache_num_blocks = paramVal;
661             }
662             CHM_RELEASE_LOCK(h->cache_mutex);
663             break;
664
665         default:
666             break;
667     }
668 }
669
670 /* open an ITS archive */
671 struct chmFile *chm_openW(const WCHAR *filename)
672 {
673     unsigned char               sbuffer[256];
674     unsigned int                sremain;
675     unsigned char              *sbufpos;
676     struct chmFile             *newHandle=NULL;
677     struct chmItsfHeader        itsfHeader;
678     struct chmItspHeader        itspHeader;
679 #if 0
680     struct chmUnitInfo          uiSpan;
681 #endif
682     struct chmUnitInfo          uiLzxc;
683     struct chmLzxcControlData   ctlData;
684
685     /* allocate handle */
686     newHandle = malloc(sizeof(struct chmFile));
687     newHandle->fd = CHM_NULL_FD;
688     newHandle->lzx_state = NULL;
689     newHandle->cache_blocks = NULL;
690     newHandle->cache_block_indices = NULL;
691     newHandle->cache_num_blocks = 0;
692
693     /* open file */
694     if ((newHandle->fd=CreateFileW(filename,
695                                    GENERIC_READ,
696                                    FILE_SHARE_READ,
697                                    NULL,
698                                    OPEN_EXISTING,
699                                    FILE_ATTRIBUTE_NORMAL,
700                                    NULL)) == CHM_NULL_FD)
701     {
702         free(newHandle);
703         return NULL;
704     }
705
706     /* initialize mutexes, if needed */
707     InitializeCriticalSection(&newHandle->mutex);
708     InitializeCriticalSection(&newHandle->lzx_mutex);
709     InitializeCriticalSection(&newHandle->cache_mutex);
710
711     /* read and verify header */
712     sremain = _CHM_ITSF_V3_LEN;
713     sbufpos = sbuffer;
714     if (_chm_fetch_bytes(newHandle, sbuffer, (UInt64)0, sremain) != sremain    ||
715         !_unmarshal_itsf_header(&sbufpos, &sremain, &itsfHeader))
716     {
717         chm_close(newHandle);
718         return NULL;
719     }
720
721     /* stash important values from header */
722     newHandle->dir_offset  = itsfHeader.dir_offset;
723     newHandle->dir_len     = itsfHeader.dir_len;
724     newHandle->data_offset = itsfHeader.data_offset;
725
726     /* now, read and verify the directory header chunk */
727     sremain = _CHM_ITSP_V1_LEN;
728     sbufpos = sbuffer;
729     if (_chm_fetch_bytes(newHandle, sbuffer,
730                          (UInt64)itsfHeader.dir_offset, sremain) != sremain       ||
731         !_unmarshal_itsp_header(&sbufpos, &sremain, &itspHeader))
732     {
733         chm_close(newHandle);
734         return NULL;
735     }
736
737     /* grab essential information from ITSP header */
738     newHandle->dir_offset += itspHeader.header_len;
739     newHandle->dir_len    -= itspHeader.header_len;
740     newHandle->index_root  = itspHeader.index_root;
741     newHandle->index_head  = itspHeader.index_head;
742     newHandle->block_len   = itspHeader.block_len;
743
744     /* if the index root is -1, this means we don't have any PMGI blocks.
745      * as a result, we must use the sole PMGL block as the index root
746      */
747     if (newHandle->index_root == -1)
748         newHandle->index_root = newHandle->index_head;
749
750     /* By default, compression is enabled. */
751     newHandle->compression_enabled = 1;
752
753     /* prefetch most commonly needed unit infos */
754     if (CHM_RESOLVE_SUCCESS != chm_resolve_object(newHandle,
755                                                   _CHMU_RESET_TABLE,
756                                                   &newHandle->rt_unit)    ||
757         newHandle->rt_unit.space == CHM_COMPRESSED                        ||
758         CHM_RESOLVE_SUCCESS != chm_resolve_object(newHandle,
759                                                   _CHMU_CONTENT,
760                                                   &newHandle->cn_unit)    ||
761         newHandle->cn_unit.space == CHM_COMPRESSED                        ||
762         CHM_RESOLVE_SUCCESS != chm_resolve_object(newHandle,
763                                                   _CHMU_LZXC_CONTROLDATA,
764                                                   &uiLzxc)                ||
765         uiLzxc.space == CHM_COMPRESSED)
766     {
767         newHandle->compression_enabled = 0;
768     }
769
770     /* read reset table info */
771     if (newHandle->compression_enabled)
772     {
773         sremain = _CHM_LZXC_RESETTABLE_V1_LEN;
774         sbufpos = sbuffer;
775         if (chm_retrieve_object(newHandle, &newHandle->rt_unit, sbuffer,
776                                 0, sremain) != sremain                        ||
777             !_unmarshal_lzxc_reset_table(&sbufpos, &sremain,
778                                          &newHandle->reset_table))
779         {
780             newHandle->compression_enabled = 0;
781         }
782     }
783
784     /* read control data */
785     if (newHandle->compression_enabled)
786     {
787         sremain = (unsigned long)uiLzxc.length;
788         sbufpos = sbuffer;
789         if (chm_retrieve_object(newHandle, &uiLzxc, sbuffer,
790                                 0, sremain) != sremain                       ||
791             !_unmarshal_lzxc_control_data(&sbufpos, &sremain,
792                                           &ctlData))
793         {
794             newHandle->compression_enabled = 0;
795         }
796
797         newHandle->window_size = ctlData.windowSize;
798         newHandle->reset_interval = ctlData.resetInterval;
799
800 /* Jed, Mon Jun 28: Experimentally, it appears that the reset block count */
801 /*       must be multiplied by this formerly unknown ctrl data field in   */
802 /*       order to decompress some files.                                  */
803 #if 0
804         newHandle->reset_blkcount = newHandle->reset_interval /
805                     (newHandle->window_size / 2);
806 #else
807         newHandle->reset_blkcount = newHandle->reset_interval    /
808                                     (newHandle->window_size / 2) *
809                                     ctlData.windowsPerReset;
810 #endif
811     }
812
813     /* initialize cache */
814     chm_set_param(newHandle, CHM_PARAM_MAX_BLOCKS_CACHED,
815                   CHM_MAX_BLOCKS_CACHED);
816
817     return newHandle;
818 }
819
820 /* close an ITS archive */
821 void chm_close(struct chmFile *h)
822 {
823     if (h != NULL)
824     {
825         if (h->fd != CHM_NULL_FD)
826             CHM_CLOSE_FILE(h->fd);
827         h->fd = CHM_NULL_FD;
828
829         DeleteCriticalSection(&h->mutex);
830         DeleteCriticalSection(&h->lzx_mutex);
831         DeleteCriticalSection(&h->cache_mutex);
832
833         if (h->lzx_state)
834             LZXteardown(h->lzx_state);
835         h->lzx_state = NULL;
836
837         if (h->cache_blocks)
838         {
839             int i;
840             for (i=0; i<h->cache_num_blocks; i++)
841             {
842                 if (h->cache_blocks[i])
843                     free(h->cache_blocks[i]);
844             }
845             free(h->cache_blocks);
846             h->cache_blocks = NULL;
847         }
848
849         free(h->cache_block_indices);
850         h->cache_block_indices = NULL;
851
852         free(h);
853     }
854 }
855
856 /*
857  * helper methods for chm_resolve_object
858  */
859
860 /* skip a compressed dword */
861 static void _chm_skip_cword(UChar **pEntry)
862 {
863     while (*(*pEntry)++ >= 0x80)
864         ;
865 }
866
867 /* skip the data from a PMGL entry */
868 static void _chm_skip_PMGL_entry_data(UChar **pEntry)
869 {
870     _chm_skip_cword(pEntry);
871     _chm_skip_cword(pEntry);
872     _chm_skip_cword(pEntry);
873 }
874
875 /* parse a compressed dword */
876 static UInt64 _chm_parse_cword(UChar **pEntry)
877 {
878     UInt64 accum = 0;
879     UChar temp;
880     while ((temp=*(*pEntry)++) >= 0x80)
881     {
882         accum <<= 7;
883         accum += temp & 0x7f;
884     }
885
886     return (accum << 7) + temp;
887 }
888
889 /* parse a utf-8 string into an ASCII char buffer */
890 static int _chm_parse_UTF8(UChar **pEntry, UInt64 count, WCHAR *path)
891 {
892     /* MJM - Modified to return real Unicode strings */ 
893     while (count != 0)
894     {
895         *path++ = (*(*pEntry)++);
896         --count;
897     }
898
899     *path = '\0';
900     return 1;
901 }
902
903 /* parse a PMGL entry into a chmUnitInfo struct; return 1 on success. */
904 static int _chm_parse_PMGL_entry(UChar **pEntry, struct chmUnitInfo *ui)
905 {
906     UInt64 strLen;
907
908     /* parse str len */
909     strLen = _chm_parse_cword(pEntry);
910     if (strLen > CHM_MAX_PATHLEN)
911         return 0;
912
913     /* parse path */
914     if (! _chm_parse_UTF8(pEntry, strLen, ui->path))
915         return 0;
916
917     /* parse info */
918     ui->space  = (int)_chm_parse_cword(pEntry);
919     ui->start  = _chm_parse_cword(pEntry);
920     ui->length = _chm_parse_cword(pEntry);
921     return 1;
922 }
923
924 /* find an exact entry in PMGL; return NULL if we fail */
925 static UChar *_chm_find_in_PMGL(UChar *page_buf,
926                          UInt32 block_len,
927                          const WCHAR *objPath)
928 {
929     /* XXX: modify this to do a binary search using the nice index structure
930      *      that is provided for us.
931      */
932     struct chmPmglHeader header;
933     UInt32 hremain;
934     UChar *end;
935     UChar *cur;
936     UChar *temp;
937     UInt64 strLen;
938     WCHAR buffer[CHM_MAX_PATHLEN+1];
939
940     /* figure out where to start and end */
941     cur = page_buf;
942     hremain = _CHM_PMGL_LEN;
943     if (! _unmarshal_pmgl_header(&cur, &hremain, &header))
944         return NULL;
945     end = page_buf + block_len - (header.free_space);
946
947     /* now, scan progressively */
948     while (cur < end)
949     {
950         /* grab the name */
951         temp = cur;
952         strLen = _chm_parse_cword(&cur);
953         if (! _chm_parse_UTF8(&cur, strLen, buffer))
954             return NULL;
955
956         /* check if it is the right name */
957         if (! strcmpiW(buffer, objPath))
958             return temp;
959
960         _chm_skip_PMGL_entry_data(&cur);
961     }
962
963     return NULL;
964 }
965
966 /* find which block should be searched next for the entry; -1 if no block */
967 static Int32 _chm_find_in_PMGI(UChar *page_buf,
968                         UInt32 block_len,
969                         const WCHAR *objPath)
970 {
971     /* XXX: modify this to do a binary search using the nice index structure
972      *      that is provided for us
973      */
974     struct chmPmgiHeader header;
975     UInt32 hremain;
976     int page=-1;
977     UChar *end;
978     UChar *cur;
979     UInt64 strLen;
980     WCHAR buffer[CHM_MAX_PATHLEN+1];
981
982     /* figure out where to start and end */
983     cur = page_buf;
984     hremain = _CHM_PMGI_LEN;
985     if (! _unmarshal_pmgi_header(&cur, &hremain, &header))
986         return -1;
987     end = page_buf + block_len - (header.free_space);
988
989     /* now, scan progressively */
990     while (cur < end)
991     {
992         /* grab the name */
993         strLen = _chm_parse_cword(&cur);
994         if (! _chm_parse_UTF8(&cur, strLen, buffer))
995             return -1;
996
997         /* check if it is the right name */
998         if (strcmpiW(buffer, objPath) > 0)
999             return page;
1000
1001         /* load next value for path */
1002         page = (int)_chm_parse_cword(&cur);
1003     }
1004
1005     return page;
1006 }
1007
1008 /* resolve a particular object from the archive */
1009 int chm_resolve_object(struct chmFile *h,
1010                        const WCHAR *objPath,
1011                        struct chmUnitInfo *ui)
1012 {
1013     /*
1014      * XXX: implement caching scheme for dir pages
1015      */
1016
1017     Int32 curPage;
1018
1019     /* buffer to hold whatever page we're looking at */
1020     UChar *page_buf = HeapAlloc(GetProcessHeap(), 0, h->block_len);
1021
1022     /* starting page */
1023     curPage = h->index_root;
1024
1025     /* until we have either returned or given up */
1026     while (curPage != -1)
1027     {
1028
1029         /* try to fetch the index page */
1030         if (_chm_fetch_bytes(h, page_buf,
1031                              (UInt64)h->dir_offset + (UInt64)curPage*h->block_len,
1032                              h->block_len) != h->block_len)
1033         {
1034             HeapFree(GetProcessHeap(), 0, page_buf);
1035             return CHM_RESOLVE_FAILURE;
1036         }
1037
1038         /* now, if it is a leaf node: */
1039         if (memcmp(page_buf, _chm_pmgl_marker, 4) == 0)
1040         {
1041             /* scan block */
1042             UChar *pEntry = _chm_find_in_PMGL(page_buf,
1043                                               h->block_len,
1044                                               objPath);
1045             if (pEntry == NULL)
1046             {
1047                 HeapFree(GetProcessHeap(), 0, page_buf);
1048                 return CHM_RESOLVE_FAILURE;
1049             }
1050
1051             /* parse entry and return */
1052             _chm_parse_PMGL_entry(&pEntry, ui);
1053             HeapFree(GetProcessHeap(), 0, page_buf);
1054             return CHM_RESOLVE_SUCCESS;
1055         }
1056
1057         /* else, if it is a branch node: */
1058         else if (memcmp(page_buf, _chm_pmgi_marker, 4) == 0)
1059             curPage = _chm_find_in_PMGI(page_buf, h->block_len, objPath);
1060
1061         /* else, we are confused.  give up. */
1062         else
1063         {
1064             HeapFree(GetProcessHeap(), 0, page_buf);
1065             return CHM_RESOLVE_FAILURE;
1066         }
1067     }
1068
1069     /* didn't find anything.  fail. */
1070     HeapFree(GetProcessHeap(), 0, page_buf);
1071     return CHM_RESOLVE_FAILURE;
1072 }
1073
1074 /*
1075  * utility methods for dealing with compressed data
1076  */
1077
1078 /* get the bounds of a compressed block.  return 0 on failure */
1079 static int _chm_get_cmpblock_bounds(struct chmFile *h,
1080                              UInt64 block,
1081                              UInt64 *start,
1082                              Int64 *len)
1083 {
1084     UChar buffer[8], *dummy;
1085     UInt32 remain;
1086
1087     /* for all but the last block, use the reset table */
1088     if (block < h->reset_table.block_count-1)
1089     {
1090         /* unpack the start address */
1091         dummy = buffer;
1092         remain = 8;
1093         if (_chm_fetch_bytes(h, buffer,
1094                              (UInt64)h->data_offset
1095                                 + (UInt64)h->rt_unit.start
1096                                 + (UInt64)h->reset_table.table_offset
1097                                 + (UInt64)block*8,
1098                              remain) != remain                            ||
1099             !_unmarshal_uint64(&dummy, &remain, start))
1100             return 0;
1101
1102         /* unpack the end address */
1103         dummy = buffer;
1104         remain = 8;
1105         if (_chm_fetch_bytes(h, buffer,
1106                          (UInt64)h->data_offset
1107                                 + (UInt64)h->rt_unit.start
1108                                 + (UInt64)h->reset_table.table_offset
1109                                 + (UInt64)block*8 + 8,
1110                          remain) != remain                                ||
1111             !_unmarshal_int64(&dummy, &remain, len))
1112             return 0;
1113     }
1114
1115     /* for the last block, use the span in addition to the reset table */
1116     else
1117     {
1118         /* unpack the start address */
1119         dummy = buffer;
1120         remain = 8;
1121         if (_chm_fetch_bytes(h, buffer,
1122                              (UInt64)h->data_offset
1123                                 + (UInt64)h->rt_unit.start
1124                                 + (UInt64)h->reset_table.table_offset
1125                                 + (UInt64)block*8,
1126                              remain) != remain                            ||
1127             !_unmarshal_uint64(&dummy, &remain, start))
1128             return 0;
1129
1130         *len = h->reset_table.compressed_len;
1131     }
1132
1133     /* compute the length and absolute start address */
1134     *len -= *start;
1135     *start += h->data_offset + h->cn_unit.start;
1136
1137     return 1;
1138 }
1139
1140 /* decompress the block.  must have lzx_mutex. */
1141 static Int64 _chm_decompress_block(struct chmFile *h,
1142                                    UInt64 block,
1143                                    UChar **ubuffer)
1144 {
1145     UChar *cbuffer = HeapAlloc( GetProcessHeap(), 0,
1146                               ((unsigned int)h->reset_table.block_len + 6144));
1147     UInt64 cmpStart;                                    /* compressed start  */
1148     Int64 cmpLen;                                       /* compressed len    */
1149     int indexSlot;                                      /* cache index slot  */
1150     UChar *lbuffer;                                     /* local buffer ptr  */
1151     UInt32 blockAlign = (UInt32)(block % h->reset_blkcount); /* reset intvl. aln. */
1152     UInt32 i;                                           /* local loop index  */
1153
1154     /* let the caching system pull its weight! */
1155     if (block - blockAlign <= h->lzx_last_block  &&
1156         block              >= h->lzx_last_block)
1157         blockAlign = (block - h->lzx_last_block);
1158
1159     /* check if we need previous blocks */
1160     if (blockAlign != 0)
1161     {
1162         /* fetch all required previous blocks since last reset */
1163         for (i = blockAlign; i > 0; i--)
1164         {
1165             UInt32 curBlockIdx = block - i;
1166
1167             /* check if we most recently decompressed the previous block */
1168             if (h->lzx_last_block != curBlockIdx)
1169             {
1170                 if ((curBlockIdx % h->reset_blkcount) == 0)
1171                 {
1172 #ifdef CHM_DEBUG
1173                     fprintf(stderr, "***RESET (1)***\n");
1174 #endif
1175                     LZXreset(h->lzx_state);
1176                 }
1177
1178                 indexSlot = (int)((curBlockIdx) % h->cache_num_blocks);
1179                 h->cache_block_indices[indexSlot] = curBlockIdx;
1180                 if (! h->cache_blocks[indexSlot])
1181                     h->cache_blocks[indexSlot] = malloc( (unsigned int)(h->reset_table.block_len));
1182                 lbuffer = h->cache_blocks[indexSlot];
1183
1184                 /* decompress the previous block */
1185 #ifdef CHM_DEBUG
1186                 fprintf(stderr, "Decompressing block #%4d (EXTRA)\n", curBlockIdx);
1187 #endif
1188                 if (!_chm_get_cmpblock_bounds(h, curBlockIdx, &cmpStart, &cmpLen) ||
1189                     _chm_fetch_bytes(h, cbuffer, cmpStart, cmpLen) != cmpLen      ||
1190                     LZXdecompress(h->lzx_state, cbuffer, lbuffer, (int)cmpLen,
1191                                   (int)h->reset_table.block_len) != DECR_OK)
1192                 {
1193 #ifdef CHM_DEBUG
1194                     fprintf(stderr, "   (DECOMPRESS FAILED!)\n");
1195 #endif
1196                     HeapFree(GetProcessHeap(), 0, cbuffer);
1197                     return (Int64)0;
1198                 }
1199
1200                 h->lzx_last_block = (int)curBlockIdx;
1201             }
1202         }
1203     }
1204     else
1205     {
1206         if ((block % h->reset_blkcount) == 0)
1207         {
1208 #ifdef CHM_DEBUG
1209             fprintf(stderr, "***RESET (2)***\n");
1210 #endif
1211             LZXreset(h->lzx_state);
1212         }
1213     }
1214
1215     /* allocate slot in cache */
1216     indexSlot = (int)(block % h->cache_num_blocks);
1217     h->cache_block_indices[indexSlot] = block;
1218     if (! h->cache_blocks[indexSlot])
1219         h->cache_blocks[indexSlot] = malloc( ((unsigned int)h->reset_table.block_len));
1220     lbuffer = h->cache_blocks[indexSlot];
1221     *ubuffer = lbuffer;
1222
1223     /* decompress the block we actually want */
1224 #ifdef CHM_DEBUG
1225     fprintf(stderr, "Decompressing block #%4d (REAL )\n", block);
1226 #endif
1227     if (! _chm_get_cmpblock_bounds(h, block, &cmpStart, &cmpLen)          ||
1228         _chm_fetch_bytes(h, cbuffer, cmpStart, cmpLen) != cmpLen          ||
1229         LZXdecompress(h->lzx_state, cbuffer, lbuffer, (int)cmpLen,
1230                       (int)h->reset_table.block_len) != DECR_OK)
1231     {
1232 #ifdef CHM_DEBUG
1233         fprintf(stderr, "   (DECOMPRESS FAILED!)\n");
1234 #endif
1235         HeapFree(GetProcessHeap(), 0, cbuffer);
1236         return (Int64)0;
1237     }
1238     h->lzx_last_block = (int)block;
1239
1240     /* XXX: modify LZX routines to return the length of the data they
1241      * decompressed and return that instead, for an extra sanity check.
1242      */
1243     HeapFree(GetProcessHeap(), 0, cbuffer);
1244     return h->reset_table.block_len;
1245 }
1246
1247 /* grab a region from a compressed block */
1248 static Int64 _chm_decompress_region(struct chmFile *h,
1249                                     UChar *buf,
1250                                     UInt64 start,
1251                                     Int64 len)
1252 {
1253     UInt64 nBlock, nOffset;
1254     UInt64 nLen;
1255     UInt64 gotLen;
1256     UChar *ubuffer = NULL;
1257
1258         if (len <= 0)
1259                 return (Int64)0;
1260
1261     /* figure out what we need to read */
1262     nBlock = start / h->reset_table.block_len;
1263     nOffset = start % h->reset_table.block_len;
1264     nLen = len;
1265     if (nLen > (h->reset_table.block_len - nOffset))
1266         nLen = h->reset_table.block_len - nOffset;
1267
1268     /* if block is cached, return data from it. */
1269     CHM_ACQUIRE_LOCK(h->lzx_mutex);
1270     CHM_ACQUIRE_LOCK(h->cache_mutex);
1271     if (h->cache_block_indices[nBlock % h->cache_num_blocks] == nBlock    &&
1272         h->cache_blocks[nBlock % h->cache_num_blocks] != NULL)
1273     {
1274         memcpy(buf,
1275                h->cache_blocks[nBlock % h->cache_num_blocks] + nOffset,
1276                (unsigned int)nLen);
1277         CHM_RELEASE_LOCK(h->cache_mutex);
1278         CHM_RELEASE_LOCK(h->lzx_mutex);
1279         return nLen;
1280     }
1281     CHM_RELEASE_LOCK(h->cache_mutex);
1282
1283     /* data request not satisfied, so... start up the decompressor machine */
1284     if (! h->lzx_state)
1285     {
1286         int window_size = ffs(h->window_size) - 1;
1287         h->lzx_last_block = -1;
1288         h->lzx_state = LZXinit(window_size);
1289     }
1290
1291     /* decompress some data */
1292     gotLen = _chm_decompress_block(h, nBlock, &ubuffer);
1293     if (gotLen < nLen)
1294         nLen = gotLen;
1295     memcpy(buf, ubuffer+nOffset, (unsigned int)nLen);
1296     CHM_RELEASE_LOCK(h->lzx_mutex);
1297     return nLen;
1298 }
1299
1300 /* retrieve (part of) an object */
1301 LONGINT64 chm_retrieve_object(struct chmFile *h,
1302                                struct chmUnitInfo *ui,
1303                                unsigned char *buf,
1304                                LONGUINT64 addr,
1305                                LONGINT64 len)
1306 {
1307     /* must be valid file handle */
1308     if (h == NULL)
1309         return (Int64)0;
1310
1311     /* starting address must be in correct range */
1312     if (addr < 0  ||  addr >= ui->length)
1313         return (Int64)0;
1314
1315     /* clip length */
1316     if (addr + len > ui->length)
1317         len = ui->length - addr;
1318
1319     /* if the file is uncompressed, it's simple */
1320     if (ui->space == CHM_UNCOMPRESSED)
1321     {
1322         /* read data */
1323         return _chm_fetch_bytes(h,
1324                                 buf,
1325                                 (UInt64)h->data_offset + (UInt64)ui->start + (UInt64)addr,
1326                                 len);
1327     }
1328
1329     /* else if the file is compressed, it's a little trickier */
1330     else /* ui->space == CHM_COMPRESSED */
1331     {
1332         Int64 swath=0, total=0;
1333
1334         /* if compression is not enabled for this file... */
1335         if (! h->compression_enabled)
1336             return total;
1337
1338         do {
1339
1340             /* swill another mouthful */
1341             swath = _chm_decompress_region(h, buf, ui->start + addr, len);
1342
1343             /* if we didn't get any... */
1344             if (swath == 0)
1345                 return total;
1346
1347             /* update stats */
1348             total += swath;
1349             len -= swath;
1350             addr += swath;
1351             buf += swath;
1352
1353         } while (len != 0);
1354
1355         return total;
1356     }
1357 }
1358
1359 /* enumerate the objects in the .chm archive */
1360 int chm_enumerate(struct chmFile *h,
1361                   int what,
1362                   CHM_ENUMERATOR e,
1363                   void *context)
1364 {
1365     Int32 curPage;
1366
1367     /* buffer to hold whatever page we're looking at */
1368     UChar *page_buf = HeapAlloc(GetProcessHeap(), 0, (unsigned int)h->block_len);
1369     struct chmPmglHeader header;
1370     UChar *end;
1371     UChar *cur;
1372     unsigned int lenRemain;
1373     UInt64 ui_path_len;
1374
1375     /* the current ui */
1376     struct chmUnitInfo ui;
1377     int flag;
1378
1379     /* starting page */
1380     curPage = h->index_head;
1381
1382     /* until we have either returned or given up */
1383     while (curPage != -1)
1384     {
1385
1386         /* try to fetch the index page */
1387         if (_chm_fetch_bytes(h,
1388                              page_buf,
1389                              (UInt64)h->dir_offset + (UInt64)curPage*h->block_len,
1390                              h->block_len) != h->block_len)
1391         {
1392             HeapFree(GetProcessHeap(), 0, page_buf);
1393             return 0;
1394         }
1395
1396         /* figure out start and end for this page */
1397         cur = page_buf;
1398         lenRemain = _CHM_PMGL_LEN;
1399         if (! _unmarshal_pmgl_header(&cur, &lenRemain, &header))
1400         {
1401             HeapFree(GetProcessHeap(), 0, page_buf);
1402             return 0;
1403         }
1404         end = page_buf + h->block_len - (header.free_space);
1405
1406         /* loop over this page */
1407         while (cur < end)
1408         {
1409             if (! _chm_parse_PMGL_entry(&cur, &ui))
1410             {
1411                 HeapFree(GetProcessHeap(), 0, page_buf);
1412                 return 0;
1413             }
1414
1415             /* get the length of the path */
1416             ui_path_len = strlenW(ui.path)-1;
1417
1418             /* check for DIRS */
1419             if (ui.path[ui_path_len] == '/'  &&  !(what & CHM_ENUMERATE_DIRS))
1420                 continue;
1421
1422             /* check for FILES */
1423             if (ui.path[ui_path_len] != '/'  &&  !(what & CHM_ENUMERATE_FILES))
1424                 continue;
1425
1426             /* check for NORMAL vs. META */
1427             if (ui.path[0] == '/')
1428             {
1429
1430                 /* check for NORMAL vs. SPECIAL */
1431                 if (ui.path[1] == '#'  ||  ui.path[1] == '$')
1432                     flag = CHM_ENUMERATE_SPECIAL;
1433                 else
1434                     flag = CHM_ENUMERATE_NORMAL;
1435             }
1436             else
1437                 flag = CHM_ENUMERATE_META;
1438             if (! (what & flag))
1439                 continue;
1440
1441             /* call the enumerator */
1442             {
1443                 int status = (*e)(h, &ui, context);
1444                 switch (status)
1445                 {
1446                     case CHM_ENUMERATOR_FAILURE:
1447                         HeapFree(GetProcessHeap(), 0, page_buf);
1448                         return 0;
1449                     case CHM_ENUMERATOR_CONTINUE:
1450                         break;
1451                     case CHM_ENUMERATOR_SUCCESS:
1452                         HeapFree(GetProcessHeap(), 0, page_buf);
1453                         return 1;
1454                     default:
1455                         break;
1456                 }
1457             }
1458         }
1459
1460         /* advance to next page */
1461         curPage = header.block_next;
1462     }
1463
1464     HeapFree(GetProcessHeap(), 0, page_buf);
1465     return 1;
1466 }
1467
1468 int chm_enumerate_dir(struct chmFile *h,
1469                       const WCHAR *prefix,
1470                       int what,
1471                       CHM_ENUMERATOR e,
1472                       void *context)
1473 {
1474     /*
1475      * XXX: do this efficiently (i.e. using the tree index)
1476      */
1477
1478     Int32 curPage;
1479
1480     /* buffer to hold whatever page we're looking at */
1481     UChar *page_buf = HeapAlloc(GetProcessHeap(), 0, (unsigned int)h->block_len);
1482     struct chmPmglHeader header;
1483     UChar *end;
1484     UChar *cur;
1485     unsigned int lenRemain;
1486
1487     /* set to 1 once we've started */
1488     int it_has_begun=0;
1489
1490     /* the current ui */
1491     struct chmUnitInfo ui;
1492     int flag;
1493     UInt64 ui_path_len;
1494
1495     /* the length of the prefix */
1496     WCHAR prefixRectified[CHM_MAX_PATHLEN+1];
1497     int prefixLen;
1498     WCHAR lastPath[CHM_MAX_PATHLEN];
1499     int lastPathLen;
1500
1501     /* starting page */
1502     curPage = h->index_head;
1503
1504     /* initialize pathname state */
1505     lstrcpynW(prefixRectified, prefix, CHM_MAX_PATHLEN);
1506     prefixLen = strlenW(prefixRectified);
1507     if (prefixLen != 0)
1508     {
1509         if (prefixRectified[prefixLen-1] != '/')
1510         {
1511             prefixRectified[prefixLen] = '/';
1512             prefixRectified[prefixLen+1] = '\0';
1513             ++prefixLen;
1514         }
1515     }
1516     lastPath[0] = '\0';
1517     lastPathLen = -1;
1518
1519     /* until we have either returned or given up */
1520     while (curPage != -1)
1521     {
1522
1523         /* try to fetch the index page */
1524         if (_chm_fetch_bytes(h,
1525                              page_buf,
1526                              (UInt64)h->dir_offset + (UInt64)curPage*h->block_len,
1527                              h->block_len) != h->block_len)
1528         {
1529             HeapFree(GetProcessHeap(), 0, page_buf);
1530             return 0;
1531         }
1532
1533         /* figure out start and end for this page */
1534         cur = page_buf;
1535         lenRemain = _CHM_PMGL_LEN;
1536         if (! _unmarshal_pmgl_header(&cur, &lenRemain, &header))
1537         {
1538             HeapFree(GetProcessHeap(), 0, page_buf);
1539             return 0;
1540         }
1541         end = page_buf + h->block_len - (header.free_space);
1542
1543         /* loop over this page */
1544         while (cur < end)
1545         {
1546             if (! _chm_parse_PMGL_entry(&cur, &ui))
1547             {
1548                 HeapFree(GetProcessHeap(), 0, page_buf);
1549                 return 0;
1550             }
1551
1552             /* check if we should start */
1553             if (! it_has_begun)
1554             {
1555                 if (ui.length == 0  &&  strncmpiW(ui.path, prefixRectified, prefixLen) == 0)
1556                     it_has_begun = 1;
1557                 else
1558                     continue;
1559
1560                 if (ui.path[prefixLen] == '\0')
1561                     continue;
1562             }
1563
1564             /* check if we should stop */
1565             else
1566             {
1567                 if (strncmpiW(ui.path, prefixRectified, prefixLen) != 0)
1568                 {
1569                     HeapFree(GetProcessHeap(), 0, page_buf);
1570                     return 1;
1571                 }
1572             }
1573
1574             /* check if we should include this path */
1575             if (lastPathLen != -1)
1576             {
1577                 if (strncmpiW(ui.path, lastPath, lastPathLen) == 0)
1578                     continue;
1579             }
1580             strcpyW(lastPath, ui.path);
1581             lastPathLen = strlenW(lastPath);
1582
1583             /* get the length of the path */
1584             ui_path_len = strlenW(ui.path)-1;
1585
1586             /* check for DIRS */
1587             if (ui.path[ui_path_len] == '/'  &&  !(what & CHM_ENUMERATE_DIRS))
1588                 continue;
1589
1590             /* check for FILES */
1591             if (ui.path[ui_path_len] != '/'  &&  !(what & CHM_ENUMERATE_FILES))
1592                 continue;
1593
1594             /* check for NORMAL vs. META */
1595             if (ui.path[0] == '/')
1596             {
1597
1598                 /* check for NORMAL vs. SPECIAL */
1599                 if (ui.path[1] == '#'  ||  ui.path[1] == '$')
1600                     flag = CHM_ENUMERATE_SPECIAL;
1601                 else
1602                     flag = CHM_ENUMERATE_NORMAL;
1603             }
1604             else
1605                 flag = CHM_ENUMERATE_META;
1606             if (! (what & flag))
1607                 continue;
1608
1609             /* call the enumerator */
1610             {
1611                 int status = (*e)(h, &ui, context);
1612                 switch (status)
1613                 {
1614                     case CHM_ENUMERATOR_FAILURE:
1615                         HeapFree(GetProcessHeap(), 0, page_buf);
1616                         return 0;
1617                     case CHM_ENUMERATOR_CONTINUE:
1618                         break;
1619                     case CHM_ENUMERATOR_SUCCESS:
1620                         HeapFree(GetProcessHeap(), 0, page_buf);
1621                         return 1;
1622                     default:
1623                         break;
1624                 }
1625             }
1626         }
1627
1628         /* advance to next page */
1629         curPage = header.block_next;
1630     }
1631
1632     HeapFree(GetProcessHeap(), 0, page_buf);
1633     return 1;
1634 }