summaryrefslogtreecommitdiffstats
path: root/fbreader/src/formats/chm/CHMFile.cpp
blob: 8c62bca26eab109a8cdf606cb817c1c09a8a07ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
 * Copyright (C) 2004-2012 Geometer Plus <[email protected]>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include <cstring>

#include <ZLFile.h>
#include <ZLStringUtil.h>
#include <ZLUnicodeUtil.h>
#include <ZLInputStream.h>

#include "CHMFile.h"
#include "CHMReferenceCollection.h"

#include "LZXDecompressor.h"

static std::string readString(ZLInputStream &stream, std::size_t length) {
	std::string string(length, ' ');
	stream.read(const_cast<char*>(string.data()), length);
	return string;
}

static unsigned short readUnsignedWord(ZLInputStream &stream) {
	unsigned char buffer[2];
	stream.read((char*)buffer, 2);
	unsigned short result = buffer[1];
	result = result << 8;
	result += buffer[0];
	return result;
}

static unsigned long readUnsignedDWord(ZLInputStream &stream) {
	unsigned long lowPart = readUnsignedWord(stream);
	unsigned long highPart = readUnsignedWord(stream);
	return (highPart << 16) + lowPart;
}

static unsigned long long readUnsignedQWord(ZLInputStream &stream) {
	unsigned long long lowPart = readUnsignedDWord(stream);
	unsigned long long highPart = readUnsignedDWord(stream);
	return (highPart << 32) + lowPart;
}

static unsigned long long readEncodedInteger(ZLInputStream &stream) {
	unsigned long long result = 0;
	char part;
	do {
		result = result << 7;
		stream.read(&part, 1);
		result += part & 0x7F;
	} while (part & -0x80);
	return result;
}

CHMInputStream::CHMInputStream(shared_ptr<ZLInputStream> base, const CHMFileInfo::SectionInfo &sectionInfo, std::size_t offset, std::size_t size) : myBase(base), mySectionInfo(sectionInfo), mySize(size) {
	myBaseStartIndex = offset / 0x8000;
	myBaseStartIndex -= myBaseStartIndex % sectionInfo.ResetInterval;
	myBytesToSkip = offset - myBaseStartIndex * 0x8000;
	myOutData = new unsigned char[0x8000];
}

CHMInputStream::~CHMInputStream() {
	close();
	delete[] myOutData;
}

bool CHMInputStream::open() {
	myOffset = 0;
	myDoSkip = true;
	myBaseIndex = myBaseStartIndex;
	if (myDecompressor.isNull()) {
		myDecompressor = new LZXDecompressor(mySectionInfo.WindowSizeIndex);
	} else {
		myDecompressor->reset();
	}
	myOutDataOffset = 0;
	myOutDataLength = 0;
	return true;
}

std::size_t CHMInputStream::read(char *buffer, std::size_t maxSize) {
	if (myDoSkip) {
		do_read(0, myBytesToSkip);
		myDoSkip = false;
	}
	std::size_t realSize = do_read(buffer, std::min(maxSize, mySize - myOffset));
	myOffset += realSize;
	return realSize;
}

std::size_t CHMInputStream::do_read(char *buffer, std::size_t maxSize) {
	std::size_t realSize = 0;
	do {
		if (myOutDataLength == 0) {
			if (myBaseIndex >= mySectionInfo.ResetTable.size()) {
				break;
			}
			const bool isTail = myBaseIndex + 1 == mySectionInfo.ResetTable.size();
			const std::size_t start = mySectionInfo.ResetTable[myBaseIndex];
			const std::size_t end = isTail ? mySectionInfo.CompressedSize : mySectionInfo.ResetTable[myBaseIndex + 1];
			myOutDataLength = isTail ? mySectionInfo.UncompressedSize % 0x8000 : 0x8000;
			myOutDataOffset = 0;

			myInData.erase();
			myInData.append(end - start, '\0');
			myBase->seek(mySectionInfo.Offset + start, true);
			myBase->read((char*)myInData.data(), myInData.length());
			if (myBaseIndex % mySectionInfo.ResetInterval == 0) {
				myDecompressor->reset();
			}
			++myBaseIndex;

			if (!myDecompressor->decompress(myInData, myOutData, myOutDataLength)) {
				break;
			}
		}
		const std::size_t partSize = std::min(myOutDataLength, maxSize);
		if (buffer != 0) {
			std::memcpy(buffer + realSize, myOutData + myOutDataOffset, partSize);
		}
		maxSize -= partSize;
		realSize += partSize;
		myOutDataLength -= partSize;
		myOutDataOffset += partSize;
	} while (maxSize != 0);
	return realSize;
}

void CHMInputStream::close() {
	myDecompressor = 0;
}

void CHMInputStream::seek(int offset, bool absoluteOffset) {
	if (absoluteOffset) {
		offset -= myOffset;
	}
	if (offset > 0) {
		read(0, offset);
	} else if (offset < 0) {
		open();
		read(0, std::max(offset + (int)myOffset, 0));
	}
}

std::size_t CHMInputStream::offset() const {
	return myOffset;
}

std::size_t CHMInputStream::sizeOfOpened() {
	return mySize;
}

shared_ptr<ZLInputStream> CHMFileInfo::entryStream(shared_ptr<ZLInputStream> base, const std::string &name) const {
	RecordMap::const_iterator it = myRecords.find(ZLUnicodeUtil::toLower(name));
	if (it == myRecords.end()) {
		return 0;
	}
	const RecordInfo &recordInfo = it->second;
	if (recordInfo.Length == 0) {
		return 0;
	}
	if (recordInfo.Section == 0) {
		// TODO: implement
		return 0;
	}
	if (recordInfo.Section > mySectionInfos.size()) {
		return 0;
	}
	const SectionInfo &sectionInfo = mySectionInfos[recordInfo.Section - 1];
	if (recordInfo.Offset + recordInfo.Length > sectionInfo.UncompressedSize) {
		return 0;
	}

	return new CHMInputStream(base, sectionInfo, recordInfo.Offset, recordInfo.Length);
}

CHMFileInfo::CHMFileInfo(const ZLFile &file) : myFilePath(file.path()) {
}

bool CHMFileInfo::moveToEntry(ZLInputStream &stream, const std::string &entryName) {
	RecordMap::const_iterator it = myRecords.find(entryName);
	if (it == myRecords.end()) {
		return false;
	}
	RecordInfo recordInfo = it->second;
	if (recordInfo.Section > mySectionInfos.size()) {
		return false;
	}
	if (recordInfo.Section != 0) {
		// TODO: ???
		return false;
	}

	stream.seek(mySection0Offset + recordInfo.Offset, true);
	return true;
}

bool CHMFileInfo::init(ZLInputStream &stream) {
	{
		// header start
		if (readString(stream, 4) != "ITSF") {
			return false;
		}

		unsigned long version = readUnsignedDWord(stream);

		// DWORD total length
		// DWORD unknown
		// DWORD timestamp
		// DWORD language id
		// 0x10 bytes 1st GUID
		// 0x10 bytes 2nd GUID
		// QWORD section 0 offset
		// QWORD section 0 length
		stream.seek(4 * 4 + 2 * 0x10 + 2 * 8, false);
		
		unsigned long long sectionOffset1 = readUnsignedQWord(stream);
		unsigned long long sectionLength1 = readUnsignedQWord(stream);
		mySection0Offset = sectionOffset1 + sectionLength1;
		// header end

		// additional header data start
		if (version > 2) {
			mySection0Offset = readUnsignedQWord(stream);
		}
		// additional header data end

		stream.seek(sectionOffset1, true);
		// header section 1 start
		// directory header start
		if (readString(stream, 4) != "ITSP") {
			return false;
		}

		// DWORD version
		// DWORD length
		// DWORD 0x000A
		// DWORD chunk size
		// DWORD density
		// DWORD depth
		// DWORD root chunk number
		// DWORD first chunk number
		// DWORD last chunk number
		// DWORD -1
		stream.seek(10 * 4, false);
		unsigned long dirChunkNumber = readUnsignedDWord(stream);
		// ...
		stream.seek(36, false);
		// header section 1 end

		std::size_t nextOffset = stream.offset();
		for (unsigned long i = 0; i < dirChunkNumber; ++i) {
			nextOffset += 4096;
			std::string header = readString(stream, 4);
			if (header == "PMGL") {
				unsigned long quickRefAreaSize = readUnsignedDWord(stream) % 4096;
				stream.seek(12, false);
				std::size_t startOffset = stream.offset();
				std::size_t oldOffset = startOffset;
				while (startOffset < nextOffset - quickRefAreaSize) {
					int nameLength = readEncodedInteger(stream);
					std::string name = readString(stream, nameLength);
					int contentSection = readEncodedInteger(stream);
					int offset = readEncodedInteger(stream);
					int length = readEncodedInteger(stream);
					if (name.substr(0, 2) != "::") {
						name = ZLUnicodeUtil::toLower(name);
					}
					myRecords.insert(
						std::make_pair(
							name,
							CHMFileInfo::RecordInfo(contentSection, offset, length)
						)
					);
					startOffset = stream.offset();
					if (oldOffset == startOffset) {
						break;
					}
					oldOffset = startOffset;
				}
			} else if (header == "PMGI") {
				unsigned long quickRefAreaSize = readUnsignedDWord(stream);
				std::size_t startOffset = stream.offset();
				std::size_t oldOffset = startOffset;
				while (startOffset < nextOffset - quickRefAreaSize) {
					int nameLength = readEncodedInteger(stream);
					std::string name = readString(stream, nameLength);
					// chunk number
					readEncodedInteger(stream);
					startOffset = stream.offset();
					if (oldOffset == startOffset) {
						break;
					}
					oldOffset = startOffset;
				}
			}
			stream.seek(nextOffset, true);
			if (stream.offset() != nextOffset) {
				break;
			}
		}
	}

	{
		if (!moveToEntry(stream, "::DataSpace/NameList")) {
			return false;
		}
		stream.seek(2, false);
		const int sectionNumber = readUnsignedWord(stream);
		for (int i = 0; i < sectionNumber; ++i) {
			const int length = readUnsignedWord(stream);
			std::string sectionName;
			sectionName.reserve(length);
			for (int j = 0; j < length; ++j) {
				sectionName += (char)readUnsignedWord(stream);
			}
			stream.seek(2, false);
			mySectionNames.push_back(sectionName);
		}
	}

	{
		for (unsigned int i = 1; i < mySectionNames.size(); ++i) {
			RecordMap::const_iterator it =
				myRecords.find("::DataSpace/Storage/" + mySectionNames[i] + "/Content");
			if (it == myRecords.end()) {
				return false;
			}
			RecordInfo recordInfo = it->second;
			if (recordInfo.Section != 0) {
				return false;
			}
			mySectionInfos.push_back(SectionInfo());
			SectionInfo &info = mySectionInfos.back();
			info.Offset = mySection0Offset + recordInfo.Offset;
			info.Length = recordInfo.Length;

			if (!moveToEntry(stream, "::DataSpace/Storage/" + mySectionNames[i] + "/ControlData")) {
				return false;
			}
			stream.seek(4, false);
			std::string lzxc = readString(stream, 4);
			if (lzxc != "LZXC") {
				return false;
			}
			const int version = readUnsignedDWord(stream);
			if ((version <= 0) || (version > 2)) {
				return false;
			}
			info.ResetInterval = readUnsignedDWord(stream);
			if (version == 1) {
				info.ResetInterval /= 0x8000;
			}
			info.WindowSizeIndex = (version == 1) ? 0 : 15;
			{
				int ws = readUnsignedDWord(stream);
				if (ws > 0) {
					while ((ws & 1) == 0) {
						ws >>= 1;
						info.WindowSizeIndex++;
					}
				}
			}

			if (!moveToEntry(stream, "::DataSpace/Storage/" + mySectionNames[i] + "/Transform/{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable")) {
				return false;
			}
			stream.seek(4, false);
			const std::size_t entriesNumber = readUnsignedDWord(stream);
			if (entriesNumber == 0) {
				return false;
			}
			if (entriesNumber > 2048) {
				// file size is greater than 60 Mb
				return false;
			}
			info.ResetTable.reserve(entriesNumber);
			stream.seek(8, false);
			info.UncompressedSize = readUnsignedQWord(stream);
			if ((info.UncompressedSize - 1) / 0x8000 != entriesNumber - 1) {
				return false;
			}
			info.CompressedSize = readUnsignedQWord(stream);
			stream.seek(8, false);
			std::size_t previous = 0;
			for (std::size_t j = 0; j < entriesNumber; ++j) {
				std::size_t value = readUnsignedQWord(stream);
				if ((j > 0) == (value <= previous)) {
					return false;
				}
				info.ResetTable.push_back(value);
				previous = value;
			}
		}
	}

	return true;
}

static std::string readNTString(ZLInputStream &stream) {
	std::string s;
	char c;
	while (stream.read(&c, 1) == 1) {
		if (c == '\0') {
			break;
		} else {
			s += c;
		}
	}
	return CHMReferenceCollection::fullReference("/", s);
}

bool CHMFileInfo::FileNames::empty() const {
	return Start.empty() && TOC.empty() && Home.empty() && Index.empty();
}

CHMFileInfo::FileNames CHMFileInfo::sectionNames(shared_ptr<ZLInputStream> base) const {
	FileNames names;
	shared_ptr<ZLInputStream> stringsStream = entryStream(base, "/#STRINGS");
	if (!stringsStream.isNull() && stringsStream->open()) {
		std::vector<std::string> fileNames;
		int tocIndex = -1;
		int indexIndex = -1;
		for (int i = 0; i < 12; ++i) {
			std::string argument = readNTString(*stringsStream);
			if (argument.empty() || (argument[argument.length() - 1] == '/')) {
				continue;
			}
			if (myRecords.find(argument) == myRecords.end()) {
				continue;
			}
			if ((tocIndex == -1) && ZLStringUtil::stringEndsWith(argument, ".hhc")) {
				tocIndex = fileNames.size();
				names.TOC = argument;
			} else if ((indexIndex == -1) && ZLStringUtil::stringEndsWith(argument, ".hhk")) {
				indexIndex = fileNames.size();
				names.Index = argument;
			}
			fileNames.push_back(argument);
		}
		std::size_t startIndex = std::max(3, std::max(tocIndex, indexIndex) + 1);
		if (startIndex < 11) {
			if (startIndex < fileNames.size()) {
				names.Start = fileNames[startIndex];
			}
			if (startIndex + 1 < fileNames.size()) {
				names.Home = fileNames[startIndex + 1];
			}
		}
		stringsStream->close();
	}
	if (names.TOC.empty()) {
		for (RecordMap::const_iterator it = myRecords.begin(); it != myRecords.end(); ++it) {
			if (ZLStringUtil::stringEndsWith(it->first, ".hhc")) {
				names.TOC = it->first;
				break;
			}
		}
	}
	if (names.empty()) {
		for (RecordMap::const_iterator it = myRecords.begin(); it != myRecords.end(); ++it) {
			if ((ZLStringUtil::stringEndsWith(it->first, ".htm")) ||
			    (ZLStringUtil::stringEndsWith(it->first, ".html"))) {
				names.Start = it->first;
				break;
			}
		}
	}

	return names;
}

const std::string CHMFileInfo::filePath() const {
	return myFilePath;
}