1 /*****************************************************************************/
2 /* FileStream.cpp Copyright (c) Ladislav Zezula 2010 */
3 /*---------------------------------------------------------------------------*/
4 /* File stream support for StormLib */
5 /* */
6 /* Windows support: Written by Ladislav Zezula */
7 /* Mac support: Written by Sam Wilkins */
8 /* Linux support: Written by Sam Wilkins and Ivan Komissarov */
9 /* Big-endian: Written & debugged by Sam Wilkins */
10 /*---------------------------------------------------------------------------*/
11 /* Date Ver Who Comment */
12 /* -------- ---- --- ------- */
13 /* 11.06.10 1.00 Lad Derived from StormPortMac.cpp and StormPortLinux.cpp */
14 /*****************************************************************************/
15
16 #define __STORMLIB_SELF__
17 #include "StormLib.h"
18 #include "StormCommon.h"
19 #include "FileStream.h"
20
21 #ifdef _MSC_VER
22 #pragma comment(lib, "wininet.lib") // Internet functions for HTTP stream
23 #pragma warning(disable: 4800) // 'BOOL' : forcing value to bool 'true' or 'false' (performance warning)
24 #endif
25
26 //-----------------------------------------------------------------------------
27 // Local defines
28
29 #ifndef INVALID_HANDLE_VALUE
30 #define INVALID_HANDLE_VALUE ((HANDLE)-1)
31 #endif
32
33 //-----------------------------------------------------------------------------
34 // Local functions - platform-specific functions
35
36 #ifndef STORMLIB_WINDOWS
37 static thread_local DWORD dwLastError = ERROR_SUCCESS;
38
GetLastError()39 DWORD GetLastError()
40 {
41 return dwLastError;
42 }
43
SetLastError(DWORD dwErrCode)44 void SetLastError(DWORD dwErrCode)
45 {
46 dwLastError = dwErrCode;
47 }
48 #endif
49
StringToInt(const char * szString)50 static DWORD StringToInt(const char * szString)
51 {
52 DWORD dwValue = 0;
53
54 while('0' <= szString[0] && szString[0] <= '9')
55 {
56 dwValue = (dwValue * 10) + (szString[0] - '0');
57 szString++;
58 }
59
60 return dwValue;
61 }
62
CreateNameWithSuffix(LPTSTR szBuffer,size_t cchMaxChars,LPCTSTR szName,unsigned int nValue)63 static void CreateNameWithSuffix(LPTSTR szBuffer, size_t cchMaxChars, LPCTSTR szName, unsigned int nValue)
64 {
65 LPTSTR szBufferEnd = szBuffer + cchMaxChars - 1;
66
67 // Copy the name
68 while(szBuffer < szBufferEnd && szName[0] != 0)
69 *szBuffer++ = *szName++;
70
71 // Append "."
72 if(szBuffer < szBufferEnd)
73 *szBuffer++ = '.';
74
75 // Append the number
76 IntToString(szBuffer, szBufferEnd - szBuffer + 1, nValue);
77 }
78
79 //-----------------------------------------------------------------------------
80 // Dummy init function
81
BaseNone_Init(TFileStream *)82 static void BaseNone_Init(TFileStream *)
83 {
84 // Nothing here
85 }
86
87 //-----------------------------------------------------------------------------
88 // Local functions - base file support
89
BaseFile_Create(TFileStream * pStream)90 static bool BaseFile_Create(TFileStream * pStream)
91 {
92 #ifdef STORMLIB_WINDOWS
93 {
94 DWORD dwWriteShare = (pStream->dwFlags & STREAM_FLAG_WRITE_SHARE) ? FILE_SHARE_WRITE : 0;
95
96 pStream->Base.File.hFile = CreateFile(pStream->szFileName,
97 GENERIC_READ | GENERIC_WRITE,
98 dwWriteShare | FILE_SHARE_READ,
99 NULL,
100 CREATE_ALWAYS,
101 0,
102 NULL);
103 if(pStream->Base.File.hFile == INVALID_HANDLE_VALUE)
104 return false;
105 }
106 #endif
107
108 #if defined(STORMLIB_MAC) || defined(STORMLIB_LINUX)
109 {
110 intptr_t handle;
111
112 handle = open(pStream->szFileName, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
113 if(handle == -1)
114 {
115 pStream->Base.File.hFile = INVALID_HANDLE_VALUE;
116 dwLastError = errno;
117 return false;
118 }
119
120 pStream->Base.File.hFile = (HANDLE)handle;
121 }
122 #endif
123
124 // Reset the file size and position
125 pStream->Base.File.FileSize = 0;
126 pStream->Base.File.FilePos = 0;
127 return true;
128 }
129
BaseFile_Open(TFileStream * pStream,const TCHAR * szFileName,DWORD dwStreamFlags)130 static bool BaseFile_Open(TFileStream * pStream, const TCHAR * szFileName, DWORD dwStreamFlags)
131 {
132 #ifdef STORMLIB_WINDOWS
133 {
134 ULARGE_INTEGER FileSize;
135 DWORD dwWriteAccess = (dwStreamFlags & STREAM_FLAG_READ_ONLY) ? 0 : FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_ATTRIBUTES;
136 DWORD dwWriteShare = (dwStreamFlags & STREAM_FLAG_WRITE_SHARE) ? FILE_SHARE_WRITE : 0;
137
138 // Open the file
139 pStream->Base.File.hFile = CreateFile(szFileName,
140 FILE_READ_DATA | FILE_READ_ATTRIBUTES | dwWriteAccess,
141 FILE_SHARE_READ | dwWriteShare,
142 NULL,
143 OPEN_EXISTING,
144 0,
145 NULL);
146 if(pStream->Base.File.hFile == INVALID_HANDLE_VALUE)
147 return false;
148
149 // Query the file size
150 FileSize.LowPart = GetFileSize(pStream->Base.File.hFile, &FileSize.HighPart);
151 pStream->Base.File.FileSize = FileSize.QuadPart;
152
153 // Query last write time
154 GetFileTime(pStream->Base.File.hFile, NULL, NULL, (LPFILETIME)&pStream->Base.File.FileTime);
155 }
156 #endif
157
158 #if defined(STORMLIB_MAC) || defined(STORMLIB_LINUX)
159 {
160 struct stat64 fileinfo;
161 int oflag = (dwStreamFlags & STREAM_FLAG_READ_ONLY) ? O_RDONLY : O_RDWR;
162 intptr_t handle;
163
164 // Open the file
165 handle = open(szFileName, oflag | O_LARGEFILE);
166 if(handle == -1)
167 {
168 pStream->Base.File.hFile = INVALID_HANDLE_VALUE;
169 dwLastError = errno;
170 return false;
171 }
172
173 // Get the file size
174 if(fstat64(handle, &fileinfo) == -1)
175 {
176 pStream->Base.File.hFile = INVALID_HANDLE_VALUE;
177 dwLastError = errno;
178 close(handle);
179 return false;
180 }
181
182 // time_t is number of seconds since 1.1.1970, UTC.
183 // 1 second = 10000000 (decimal) in FILETIME
184 // Set the start to 1.1.1970 00:00:00
185 pStream->Base.File.FileTime = 0x019DB1DED53E8000ULL + (10000000 * fileinfo.st_mtime);
186 pStream->Base.File.FileSize = (ULONGLONG)fileinfo.st_size;
187 pStream->Base.File.hFile = (HANDLE)handle;
188 }
189 #endif
190
191 // Reset the file position
192 pStream->Base.File.FilePos = 0;
193 return true;
194 }
195
BaseFile_Read(TFileStream * pStream,ULONGLONG * pByteOffset,void * pvBuffer,DWORD dwBytesToRead)196 static bool BaseFile_Read(
197 TFileStream * pStream, // Pointer to an open stream
198 ULONGLONG * pByteOffset, // Pointer to file byte offset. If NULL, it reads from the current position
199 void * pvBuffer, // Pointer to data to be read
200 DWORD dwBytesToRead) // Number of bytes to read from the file
201 {
202 ULONGLONG ByteOffset = (pByteOffset != NULL) ? *pByteOffset : pStream->Base.File.FilePos;
203 DWORD dwBytesRead = 0; // Must be set by platform-specific code
204
205 #ifdef STORMLIB_WINDOWS
206 {
207 // Note: StormLib no longer supports Windows 9x.
208 // Thus, we can use the OVERLAPPED structure to specify
209 // file offset to read from file. This allows us to skip
210 // one system call to SetFilePointer
211
212 // Update the byte offset
213 pStream->Base.File.FilePos = ByteOffset;
214
215 // Read the data
216 if(dwBytesToRead != 0)
217 {
218 OVERLAPPED Overlapped;
219
220 Overlapped.OffsetHigh = (DWORD)(ByteOffset >> 32);
221 Overlapped.Offset = (DWORD)ByteOffset;
222 Overlapped.hEvent = NULL;
223 if(!ReadFile(pStream->Base.File.hFile, pvBuffer, dwBytesToRead, &dwBytesRead, &Overlapped))
224 return false;
225 }
226 }
227 #endif
228
229 #if defined(STORMLIB_MAC) || defined(STORMLIB_LINUX)
230 {
231 ssize_t bytes_read;
232
233 // If the byte offset is different from the current file position,
234 // we have to update the file position xxx
235 if(ByteOffset != pStream->Base.File.FilePos)
236 {
237 lseek64((intptr_t)pStream->Base.File.hFile, (off64_t)(ByteOffset), SEEK_SET);
238 pStream->Base.File.FilePos = ByteOffset;
239 }
240
241 // Perform the read operation
242 if(dwBytesToRead != 0)
243 {
244 bytes_read = read((intptr_t)pStream->Base.File.hFile, pvBuffer, (size_t)dwBytesToRead);
245 if(bytes_read == -1)
246 {
247 dwLastError = errno;
248 return false;
249 }
250
251 dwBytesRead = (DWORD)(size_t)bytes_read;
252 }
253 }
254 #endif
255
256 // Increment the current file position by number of bytes read
257 // If the number of bytes read doesn't match to required amount, return false
258 pStream->Base.File.FilePos = ByteOffset + dwBytesRead;
259 if(dwBytesRead != dwBytesToRead)
260 SetLastError(ERROR_HANDLE_EOF);
261 return (dwBytesRead == dwBytesToRead);
262 }
263
264 /**
265 * \a pStream Pointer to an open stream
266 * \a pByteOffset Pointer to file byte offset. If NULL, writes to current position
267 * \a pvBuffer Pointer to data to be written
268 * \a dwBytesToWrite Number of bytes to write to the file
269 */
270
BaseFile_Write(TFileStream * pStream,ULONGLONG * pByteOffset,const void * pvBuffer,DWORD dwBytesToWrite)271 static bool BaseFile_Write(TFileStream * pStream, ULONGLONG * pByteOffset, const void * pvBuffer, DWORD dwBytesToWrite)
272 {
273 ULONGLONG ByteOffset = (pByteOffset != NULL) ? *pByteOffset : pStream->Base.File.FilePos;
274 DWORD dwBytesWritten = 0; // Must be set by platform-specific code
275
276 #ifdef STORMLIB_WINDOWS
277 {
278 // Note: StormLib no longer supports Windows 9x.
279 // Thus, we can use the OVERLAPPED structure to specify
280 // file offset to read from file. This allows us to skip
281 // one system call to SetFilePointer
282
283 // Update the byte offset
284 pStream->Base.File.FilePos = ByteOffset;
285
286 // Read the data
287 if(dwBytesToWrite != 0)
288 {
289 OVERLAPPED Overlapped;
290
291 Overlapped.OffsetHigh = (DWORD)(ByteOffset >> 32);
292 Overlapped.Offset = (DWORD)ByteOffset;
293 Overlapped.hEvent = NULL;
294 if(!WriteFile(pStream->Base.File.hFile, pvBuffer, dwBytesToWrite, &dwBytesWritten, &Overlapped))
295 return false;
296 }
297 }
298 #endif
299
300 #if defined(STORMLIB_MAC) || defined(STORMLIB_LINUX)
301 {
302 ssize_t bytes_written;
303
304 // If the byte offset is different from the current file position,
305 // we have to update the file position
306 if(ByteOffset != pStream->Base.File.FilePos)
307 {
308 lseek64((intptr_t)pStream->Base.File.hFile, (off64_t)(ByteOffset), SEEK_SET);
309 pStream->Base.File.FilePos = ByteOffset;
310 }
311
312 // Perform the read operation
313 bytes_written = write((intptr_t)pStream->Base.File.hFile, pvBuffer, (size_t)dwBytesToWrite);
314 if(bytes_written == -1)
315 {
316 dwLastError = errno;
317 return false;
318 }
319
320 dwBytesWritten = (DWORD)(size_t)bytes_written;
321 }
322 #endif
323
324 // Increment the current file position by number of bytes read
325 pStream->Base.File.FilePos = ByteOffset + dwBytesWritten;
326
327 // Also modify the file size, if needed
328 if(pStream->Base.File.FilePos > pStream->Base.File.FileSize)
329 pStream->Base.File.FileSize = pStream->Base.File.FilePos;
330
331 if(dwBytesWritten != dwBytesToWrite)
332 SetLastError(ERROR_DISK_FULL);
333 return (dwBytesWritten == dwBytesToWrite);
334 }
335
336 /**
337 * \a pStream Pointer to an open stream
338 * \a NewFileSize New size of the file
339 */
BaseFile_Resize(TFileStream * pStream,ULONGLONG NewFileSize)340 static bool BaseFile_Resize(TFileStream * pStream, ULONGLONG NewFileSize)
341 {
342 #ifdef STORMLIB_WINDOWS
343 {
344 LONG FileSizeHi = (LONG)(NewFileSize >> 32);
345 LONG FileSizeLo;
346 DWORD dwNewPos;
347 bool bResult;
348
349 // Set the position at the new file size
350 dwNewPos = SetFilePointer(pStream->Base.File.hFile, (LONG)NewFileSize, &FileSizeHi, FILE_BEGIN);
351 if(dwNewPos == INVALID_SET_FILE_POINTER && GetLastError() != ERROR_SUCCESS)
352 return false;
353
354 // Set the current file pointer as the end of the file
355 bResult = (bool)SetEndOfFile(pStream->Base.File.hFile);
356 if(bResult)
357 pStream->Base.File.FileSize = NewFileSize;
358
359 // Restore the file position
360 FileSizeHi = (LONG)(pStream->Base.File.FilePos >> 32);
361 FileSizeLo = (LONG)(pStream->Base.File.FilePos);
362 SetFilePointer(pStream->Base.File.hFile, FileSizeLo, &FileSizeHi, FILE_BEGIN);
363 return bResult;
364 }
365 #endif
366
367 #if defined(STORMLIB_MAC) || defined(STORMLIB_LINUX)
368 {
369 if(ftruncate64((intptr_t)pStream->Base.File.hFile, (off64_t)NewFileSize) == -1)
370 {
371 dwLastError = errno;
372 return false;
373 }
374
375 pStream->Base.File.FileSize = NewFileSize;
376 return true;
377 }
378 #endif
379 }
380
381 // Gives the current file size
BaseFile_GetSize(TFileStream * pStream,ULONGLONG * pFileSize)382 static bool BaseFile_GetSize(TFileStream * pStream, ULONGLONG * pFileSize)
383 {
384 // Note: Used by all thre base providers.
385 // Requires the TBaseData union to have the same layout for all three base providers
386 *pFileSize = pStream->Base.File.FileSize;
387 return true;
388 }
389
390 // Gives the current file position
BaseFile_GetPos(TFileStream * pStream,ULONGLONG * pByteOffset)391 static bool BaseFile_GetPos(TFileStream * pStream, ULONGLONG * pByteOffset)
392 {
393 // Note: Used by all thre base providers.
394 // Requires the TBaseData union to have the same layout for all three base providers
395 *pByteOffset = pStream->Base.File.FilePos;
396 return true;
397 }
398
399 // Renames the file pointed by pStream so that it contains data from pNewStream
BaseFile_Replace(TFileStream * pStream,TFileStream * pNewStream)400 static bool BaseFile_Replace(TFileStream * pStream, TFileStream * pNewStream)
401 {
402 #ifdef STORMLIB_WINDOWS
403 // Delete the original stream file. Don't check the result value,
404 // because if the file doesn't exist, it would fail
405 DeleteFile(pStream->szFileName);
406
407 // Rename the new file to the old stream's file
408 return (bool)MoveFile(pNewStream->szFileName, pStream->szFileName);
409 #endif
410
411 #if defined(STORMLIB_MAC) || defined(STORMLIB_LINUX)
412 // "rename" on Linux also works if the target file exists
413 if(rename(pNewStream->szFileName, pStream->szFileName) == -1)
414 {
415 dwLastError = errno;
416 return false;
417 }
418
419 return true;
420 #endif
421 }
422
BaseFile_Close(TFileStream * pStream)423 static void BaseFile_Close(TFileStream * pStream)
424 {
425 if(pStream->Base.File.hFile != INVALID_HANDLE_VALUE)
426 {
427 #ifdef STORMLIB_WINDOWS
428 CloseHandle(pStream->Base.File.hFile);
429 #endif
430
431 #if defined(STORMLIB_MAC) || defined(STORMLIB_LINUX)
432 close((intptr_t)pStream->Base.File.hFile);
433 #endif
434 }
435
436 // Also invalidate the handle
437 pStream->Base.File.hFile = INVALID_HANDLE_VALUE;
438 }
439
440 // Initializes base functions for the disk file
BaseFile_Init(TFileStream * pStream)441 static void BaseFile_Init(TFileStream * pStream)
442 {
443 pStream->BaseCreate = BaseFile_Create;
444 pStream->BaseOpen = BaseFile_Open;
445 pStream->BaseRead = BaseFile_Read;
446 pStream->BaseWrite = BaseFile_Write;
447 pStream->BaseResize = BaseFile_Resize;
448 pStream->BaseGetSize = BaseFile_GetSize;
449 pStream->BaseGetPos = BaseFile_GetPos;
450 pStream->BaseClose = BaseFile_Close;
451 }
452
453 //-----------------------------------------------------------------------------
454 // Local functions - base memory-mapped file support
455
456 #ifdef STORMLIB_WINDOWS
457
458 typedef struct _SECTION_BASIC_INFORMATION
459 {
460 PVOID BaseAddress;
461 ULONG Attributes;
462 LARGE_INTEGER Size;
463 } SECTION_BASIC_INFORMATION, *PSECTION_BASIC_INFORMATION;
464
465 typedef ULONG (WINAPI * NTQUERYSECTION)(
466 IN HANDLE SectionHandle,
467 IN ULONG SectionInformationClass,
468 OUT PVOID SectionInformation,
469 IN SIZE_T Length,
470 OUT PSIZE_T ResultLength);
471
RetrieveFileMappingSize(HANDLE hSection,ULARGE_INTEGER & RefFileSize)472 static bool RetrieveFileMappingSize(HANDLE hSection, ULARGE_INTEGER & RefFileSize)
473 {
474 SECTION_BASIC_INFORMATION BasicInfo = {0};
475 NTQUERYSECTION PfnQuerySection;
476 HMODULE hNtdll;
477 SIZE_T ReturnLength = 0;
478
479 if((hNtdll = GetModuleHandle(_T("ntdll.dll"))) != NULL)
480 {
481 PfnQuerySection = (NTQUERYSECTION)GetProcAddress(hNtdll, "NtQuerySection");
482 if(PfnQuerySection != NULL)
483 {
484 if(PfnQuerySection(hSection, 0, &BasicInfo, sizeof(SECTION_BASIC_INFORMATION), &ReturnLength) == 0)
485 {
486 RefFileSize.HighPart = BasicInfo.Size.HighPart;
487 RefFileSize.LowPart = BasicInfo.Size.LowPart;
488 return true;
489 }
490 }
491 }
492
493 return false;
494 }
495 #endif
496
BaseMap_Open(TFileStream * pStream,LPCTSTR szFileName,DWORD dwStreamFlags)497 static bool BaseMap_Open(TFileStream * pStream, LPCTSTR szFileName, DWORD dwStreamFlags)
498 {
499 #ifdef STORMLIB_WINDOWS
500
501 ULARGE_INTEGER FileSize = {0};
502 HANDLE hFile = INVALID_HANDLE_VALUE;
503 HANDLE hMap = NULL;
504 bool bResult = false;
505
506 // Keep compiler happy
507 dwStreamFlags = dwStreamFlags;
508
509 // 1) Try to treat "szFileName" as a section name
510 hMap = OpenFileMapping(SECTION_QUERY | FILE_MAP_READ, FALSE, szFileName);
511 if(hMap != NULL)
512 {
513 // Try to retrieve the size of the mapping
514 if(!RetrieveFileMappingSize(hMap, FileSize))
515 {
516 CloseHandle(hMap);
517 hMap = NULL;
518 }
519 }
520
521 // 2) Treat the name as file name
522 else
523 {
524 hFile = CreateFile(szFileName, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
525 if(hFile != INVALID_HANDLE_VALUE)
526 {
527 // Retrieve file size. Don't allow mapping file of a zero size.
528 FileSize.LowPart = GetFileSize(hFile, &FileSize.HighPart);
529 if(FileSize.QuadPart != 0)
530 {
531 // Now create file mapping over the file
532 hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
533 }
534 }
535 }
536
537 // Did it succeed?
538 if(hMap != NULL)
539 {
540 // Map the entire view into memory
541 // Note that this operation will fail if the file can't fit
542 // into usermode address space
543 pStream->Base.Map.pbFile = (LPBYTE)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);
544 if(pStream->Base.Map.pbFile != NULL)
545 {
546 // Retrieve file time. If it's named section, put 0
547 if(hFile != INVALID_HANDLE_VALUE)
548 GetFileTime(hFile, NULL, NULL, (LPFILETIME)&pStream->Base.Map.FileTime);
549
550 // Retrieve file size and position
551 pStream->Base.Map.FileSize = FileSize.QuadPart;
552 pStream->Base.Map.FilePos = 0;
553 bResult = true;
554 }
555
556 // Close the map handle
557 CloseHandle(hMap);
558 }
559
560 // Close the file handle
561 if(hFile != INVALID_HANDLE_VALUE)
562 CloseHandle(hFile);
563
564 // Return the result of the operation
565 return bResult;
566
567 #elif defined(STORMLIB_HAS_MMAP)
568
569 struct stat64 fileinfo;
570 intptr_t handle;
571 bool bResult = false;
572
573 // Open the file
574 handle = open(szFileName, O_RDONLY);
575 if(handle != -1)
576 {
577 // Get the file size
578 if(fstat64(handle, &fileinfo) != -1)
579 {
580 pStream->Base.Map.pbFile = (LPBYTE)mmap(NULL, (size_t)fileinfo.st_size, PROT_READ, MAP_PRIVATE, handle, 0);
581 if(pStream->Base.Map.pbFile != NULL)
582 {
583 // time_t is number of seconds since 1.1.1970, UTC.
584 // 1 second = 10000000 (decimal) in FILETIME
585 // Set the start to 1.1.1970 00:00:00
586 pStream->Base.Map.FileTime = 0x019DB1DED53E8000ULL + (10000000 * fileinfo.st_mtime);
587 pStream->Base.Map.FileSize = (ULONGLONG)fileinfo.st_size;
588 pStream->Base.Map.FilePos = 0;
589 bResult = true;
590 }
591 }
592 close(handle);
593 }
594
595 // Did the mapping fail?
596 if(bResult == false)
597 dwLastError = errno;
598 return bResult;
599
600 #else
601
602 // File mapping is not supported
603 return false;
604
605 #endif
606 }
607
BaseMap_Read(TFileStream * pStream,ULONGLONG * pByteOffset,void * pvBuffer,DWORD dwBytesToRead)608 static bool BaseMap_Read(
609 TFileStream * pStream, // Pointer to an open stream
610 ULONGLONG * pByteOffset, // Pointer to file byte offset. If NULL, it reads from the current position
611 void * pvBuffer, // Pointer to data to be read
612 DWORD dwBytesToRead) // Number of bytes to read from the file
613 {
614 ULONGLONG ByteOffset = (pByteOffset != NULL) ? *pByteOffset : pStream->Base.Map.FilePos;
615
616 // Do we have to read anything at all?
617 if(dwBytesToRead != 0)
618 {
619 // Don't allow reading past file size
620 if((ByteOffset + dwBytesToRead) > pStream->Base.Map.FileSize)
621 return false;
622
623 // Copy the required data
624 memcpy(pvBuffer, pStream->Base.Map.pbFile + (size_t)ByteOffset, dwBytesToRead);
625 }
626
627 // Move the current file position
628 pStream->Base.Map.FilePos += dwBytesToRead;
629 return true;
630 }
631
BaseMap_Close(TFileStream * pStream)632 static void BaseMap_Close(TFileStream * pStream)
633 {
634
635 #ifdef STORMLIB_WINDOWS
636
637 if(pStream->Base.Map.pbFile != NULL)
638 UnmapViewOfFile(pStream->Base.Map.pbFile);
639
640 #elif defined(STORMLIB_HAS_MMAP)
641
642 if(pStream->Base.Map.pbFile != NULL)
643 munmap(pStream->Base.Map.pbFile, (size_t )pStream->Base.Map.FileSize);
644
645 #endif
646
647 pStream->Base.Map.pbFile = NULL;
648 }
649
650 // Initializes base functions for the mapped file
BaseMap_Init(TFileStream * pStream)651 static void BaseMap_Init(TFileStream * pStream)
652 {
653 // Supply the file stream functions
654 pStream->BaseOpen = BaseMap_Open;
655 pStream->BaseRead = BaseMap_Read;
656 pStream->BaseGetSize = BaseFile_GetSize; // Reuse BaseFile function
657 pStream->BaseGetPos = BaseFile_GetPos; // Reuse BaseFile function
658 pStream->BaseClose = BaseMap_Close;
659
660 // Mapped files are read-only
661 pStream->dwFlags |= STREAM_FLAG_READ_ONLY;
662 }
663
664 //-----------------------------------------------------------------------------
665 // Local functions - base HTTP file support
666
BaseHttp_ExtractServerName(const TCHAR * szFileName,TCHAR * szServerName)667 static const TCHAR * BaseHttp_ExtractServerName(const TCHAR * szFileName, TCHAR * szServerName)
668 {
669 // Check for HTTP
670 if(!_tcsnicmp(szFileName, _T("http://"), 7))
671 szFileName += 7;
672
673 // Cut off the server name
674 if(szServerName != NULL)
675 {
676 while(szFileName[0] != 0 && szFileName[0] != _T('/'))
677 *szServerName++ = *szFileName++;
678 *szServerName = 0;
679 }
680 else
681 {
682 while(szFileName[0] != 0 && szFileName[0] != _T('/'))
683 szFileName++;
684 }
685
686 // Return the remainder
687 return szFileName;
688 }
689
BaseHttp_Open(TFileStream * pStream,const TCHAR * szFileName,DWORD dwStreamFlags)690 static bool BaseHttp_Open(TFileStream * pStream, const TCHAR * szFileName, DWORD dwStreamFlags)
691 {
692 #ifdef STORMLIB_WINDOWS
693
694 HINTERNET hRequest;
695 DWORD dwTemp = 0;
696
697 // Keep compiler happy
698 dwStreamFlags = dwStreamFlags;
699
700 // Don't connect to the internet
701 if(!InternetGetConnectedState(&dwTemp, 0))
702 return false;
703
704 // Initiate the connection to the internet
705 pStream->Base.Http.hInternet = InternetOpen(_T("StormLib HTTP MPQ reader"),
706 INTERNET_OPEN_TYPE_PRECONFIG,
707 NULL,
708 NULL,
709 0);
710 if(pStream->Base.Http.hInternet != NULL)
711 {
712 TCHAR szServerName[MAX_PATH];
713 DWORD dwFlags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_UI | INTERNET_FLAG_NO_CACHE_WRITE;
714
715 // Initiate connection with the server
716 szFileName = BaseHttp_ExtractServerName(szFileName, szServerName);
717 pStream->Base.Http.hConnect = InternetConnect(pStream->Base.Http.hInternet,
718 szServerName,
719 INTERNET_DEFAULT_HTTP_PORT,
720 NULL,
721 NULL,
722 INTERNET_SERVICE_HTTP,
723 dwFlags,
724 0);
725 if(pStream->Base.Http.hConnect != NULL)
726 {
727 // Open HTTP request to the file
728 hRequest = HttpOpenRequest(pStream->Base.Http.hConnect, _T("GET"), szFileName, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);
729 if(hRequest != NULL)
730 {
731 if(HttpSendRequest(hRequest, NULL, 0, NULL, 0))
732 {
733 ULONGLONG FileTime = 0;
734 DWORD dwFileSize = 0;
735 DWORD dwDataSize;
736 DWORD dwIndex = 0;
737 TCHAR StatusCode[0x08];
738
739 // Check if the file succeeded to open
740 dwDataSize = sizeof(StatusCode);
741 if(HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE, StatusCode, &dwDataSize, &dwIndex))
742 {
743 if(_tcscmp(StatusCode, _T("200")))
744 {
745 InternetCloseHandle(hRequest);
746 SetLastError(ERROR_FILE_NOT_FOUND);
747 return false;
748 }
749 }
750
751 // Check if the MPQ has Last Modified field
752 dwDataSize = sizeof(ULONGLONG);
753 if(HttpQueryInfo(hRequest, HTTP_QUERY_LAST_MODIFIED | HTTP_QUERY_FLAG_SYSTEMTIME, &FileTime, &dwDataSize, &dwIndex))
754 pStream->Base.Http.FileTime = FileTime;
755
756 // Verify if the server supports random access
757 dwDataSize = sizeof(DWORD);
758 if(HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwFileSize, &dwDataSize, &dwIndex))
759 {
760 if(dwFileSize != 0)
761 {
762 InternetCloseHandle(hRequest);
763 pStream->Base.Http.FileSize = dwFileSize;
764 pStream->Base.Http.FilePos = 0;
765 return true;
766 }
767 }
768 }
769
770 // Close the request
771 InternetCloseHandle(hRequest);
772 }
773
774 // Close the connection handle
775 InternetCloseHandle(pStream->Base.Http.hConnect);
776 pStream->Base.Http.hConnect = NULL;
777 }
778
779 // Close the internet handle
780 InternetCloseHandle(pStream->Base.Http.hInternet);
781 pStream->Base.Http.hInternet = NULL;
782 }
783
784 // If the file is not there or is not available for random access, report error
785 pStream->BaseClose(pStream);
786 return false;
787
788 #else
789
790 // Not supported
791 SetLastError(ERROR_NOT_SUPPORTED);
792 pStream = pStream;
793 return false;
794
795 #endif
796 }
797
BaseHttp_Read(TFileStream * pStream,ULONGLONG * pByteOffset,void * pvBuffer,DWORD dwBytesToRead)798 static bool BaseHttp_Read(
799 TFileStream * pStream, // Pointer to an open stream
800 ULONGLONG * pByteOffset, // Pointer to file byte offset. If NULL, it reads from the current position
801 void * pvBuffer, // Pointer to data to be read
802 DWORD dwBytesToRead) // Number of bytes to read from the file
803 {
804 #ifdef STORMLIB_WINDOWS
805 ULONGLONG ByteOffset = (pByteOffset != NULL) ? *pByteOffset : pStream->Base.Http.FilePos;
806 DWORD dwTotalBytesRead = 0;
807
808 // Do we have to read anything at all?
809 if(dwBytesToRead != 0)
810 {
811 HINTERNET hRequest;
812 LPCTSTR szFileName;
813 LPBYTE pbBuffer = (LPBYTE)pvBuffer;
814 TCHAR szRangeRequest[0x80];
815 DWORD dwStartOffset = (DWORD)ByteOffset;
816 DWORD dwEndOffset = dwStartOffset + dwBytesToRead;
817
818 // Open HTTP request to the file
819 szFileName = BaseHttp_ExtractServerName(pStream->szFileName, NULL);
820 hRequest = HttpOpenRequest(pStream->Base.Http.hConnect, _T("GET"), szFileName, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);
821 if(hRequest != NULL)
822 {
823 // Add range request to the HTTP headers
824 // http://www.clevercomponents.com/articles/article015/resuming.asp
825 wsprintf(szRangeRequest, _T("Range: bytes=%u-%u"), (unsigned int)dwStartOffset, (unsigned int)dwEndOffset);
826 HttpAddRequestHeaders(hRequest, szRangeRequest, 0xFFFFFFFF, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
827
828 // Send the request to the server
829 if(HttpSendRequest(hRequest, NULL, 0, NULL, 0))
830 {
831 while(dwTotalBytesRead < dwBytesToRead)
832 {
833 DWORD dwBlockBytesToRead = dwBytesToRead - dwTotalBytesRead;
834 DWORD dwBlockBytesRead = 0;
835
836 // Read the block from the file
837 if(dwBlockBytesToRead > 0x200)
838 dwBlockBytesToRead = 0x200;
839 InternetReadFile(hRequest, pbBuffer, dwBlockBytesToRead, &dwBlockBytesRead);
840
841 // Check for end
842 if(dwBlockBytesRead == 0)
843 break;
844
845 // Move buffers
846 dwTotalBytesRead += dwBlockBytesRead;
847 pbBuffer += dwBlockBytesRead;
848 }
849 }
850 InternetCloseHandle(hRequest);
851 }
852 }
853
854 // Increment the current file position by number of bytes read
855 pStream->Base.Http.FilePos = ByteOffset + dwTotalBytesRead;
856
857 // If the number of bytes read doesn't match the required amount, return false
858 if(dwTotalBytesRead != dwBytesToRead)
859 SetLastError(ERROR_HANDLE_EOF);
860 return (dwTotalBytesRead == dwBytesToRead);
861
862 #else
863
864 // Not supported
865 pStream = pStream;
866 pByteOffset = pByteOffset;
867 pvBuffer = pvBuffer;
868 dwBytesToRead = dwBytesToRead;
869 SetLastError(ERROR_NOT_SUPPORTED);
870 return false;
871
872 #endif
873 }
874
BaseHttp_Close(TFileStream * pStream)875 static void BaseHttp_Close(TFileStream * pStream)
876 {
877 #ifdef STORMLIB_WINDOWS
878 if(pStream->Base.Http.hConnect != NULL)
879 InternetCloseHandle(pStream->Base.Http.hConnect);
880 pStream->Base.Http.hConnect = NULL;
881
882 if(pStream->Base.Http.hInternet != NULL)
883 InternetCloseHandle(pStream->Base.Http.hInternet);
884 pStream->Base.Http.hInternet = NULL;
885 #else
886 pStream = pStream;
887 #endif
888 }
889
890 // Initializes base functions for the mapped file
BaseHttp_Init(TFileStream * pStream)891 static void BaseHttp_Init(TFileStream * pStream)
892 {
893 // Supply the stream functions
894 pStream->BaseOpen = BaseHttp_Open;
895 pStream->BaseRead = BaseHttp_Read;
896 pStream->BaseGetSize = BaseFile_GetSize; // Reuse BaseFile function
897 pStream->BaseGetPos = BaseFile_GetPos; // Reuse BaseFile function
898 pStream->BaseClose = BaseHttp_Close;
899
900 // HTTP files are read-only
901 pStream->dwFlags |= STREAM_FLAG_READ_ONLY;
902 }
903
904 //-----------------------------------------------------------------------------
905 // Local functions - base block-based support
906
907 // Generic function that loads blocks from the file
908 // The function groups the block with the same availability,
909 // so the called BlockRead can finish the request in a single system call
BlockStream_Read(TBlockStream * pStream,ULONGLONG * pByteOffset,void * pvBuffer,DWORD dwBytesToRead)910 static bool BlockStream_Read(
911 TBlockStream * pStream, // Pointer to an open stream
912 ULONGLONG * pByteOffset, // Pointer to file byte offset. If NULL, it reads from the current position
913 void * pvBuffer, // Pointer to data to be read
914 DWORD dwBytesToRead) // Number of bytes to read from the file
915 {
916 ULONGLONG BlockOffset0;
917 ULONGLONG BlockOffset;
918 ULONGLONG ByteOffset;
919 ULONGLONG EndOffset;
920 LPBYTE TransferBuffer;
921 LPBYTE BlockBuffer;
922 DWORD BlockBufferOffset; // Offset of the desired data in the block buffer
923 DWORD BytesNeeded; // Number of bytes that really need to be read
924 DWORD BlockSize = pStream->BlockSize;
925 DWORD BlockCount;
926 bool bPrevBlockAvailable;
927 bool bCallbackCalled = false;
928 bool bBlockAvailable;
929 bool bResult = true;
930
931 // The base block read function must be present
932 assert(pStream->BlockRead != NULL);
933
934 // NOP reading of zero bytes
935 if(dwBytesToRead == 0)
936 return true;
937
938 // Get the current position in the stream
939 ByteOffset = (pByteOffset != NULL) ? pByteOffset[0] : pStream->StreamPos;
940 EndOffset = ByteOffset + dwBytesToRead;
941 if(EndOffset > pStream->StreamSize)
942 {
943 SetLastError(ERROR_HANDLE_EOF);
944 return false;
945 }
946
947 // Calculate the block parameters
948 BlockOffset0 = BlockOffset = ByteOffset & ~((ULONGLONG)BlockSize - 1);
949 BlockCount = (DWORD)(((EndOffset - BlockOffset) + (BlockSize - 1)) / BlockSize);
950 BytesNeeded = (DWORD)(EndOffset - BlockOffset);
951
952 // Remember where we have our data
953 assert((BlockSize & (BlockSize - 1)) == 0);
954 BlockBufferOffset = (DWORD)(ByteOffset & (BlockSize - 1));
955
956 // Allocate buffer for reading blocks
957 TransferBuffer = BlockBuffer = STORM_ALLOC(BYTE, (BlockCount * BlockSize));
958 if(TransferBuffer == NULL)
959 {
960 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
961 return false;
962 }
963
964 // If all blocks are available, just read all blocks at once
965 if(pStream->IsComplete == 0)
966 {
967 // Now parse the blocks and send the block read request
968 // to all blocks with the same availability
969 assert(pStream->BlockCheck != NULL);
970 bPrevBlockAvailable = pStream->BlockCheck(pStream, BlockOffset);
971
972 // Loop as long as we have something to read
973 while(BlockOffset < EndOffset)
974 {
975 // Determine availability of the next block
976 bBlockAvailable = pStream->BlockCheck(pStream, BlockOffset);
977
978 // If the availability has changed, read all blocks up to this one
979 if(bBlockAvailable != bPrevBlockAvailable)
980 {
981 // Call the file stream callback, if the block is not available
982 if(pStream->pMaster && pStream->pfnCallback && bPrevBlockAvailable == false)
983 {
984 pStream->pfnCallback(pStream->UserData, BlockOffset0, (DWORD)(BlockOffset - BlockOffset0));
985 bCallbackCalled = true;
986 }
987
988 // Load the continuous blocks with the same availability
989 assert(BlockOffset > BlockOffset0);
990 bResult = pStream->BlockRead(pStream, BlockOffset0, BlockOffset, BlockBuffer, BytesNeeded, bPrevBlockAvailable);
991 if(!bResult)
992 break;
993
994 // Move the block offset
995 BlockBuffer += (DWORD)(BlockOffset - BlockOffset0);
996 BytesNeeded -= (DWORD)(BlockOffset - BlockOffset0);
997 bPrevBlockAvailable = bBlockAvailable;
998 BlockOffset0 = BlockOffset;
999 }
1000
1001 // Move to the block offset in the stream
1002 BlockOffset += BlockSize;
1003 }
1004
1005 // If there is a block(s) remaining to be read, do it
1006 if(BlockOffset > BlockOffset0)
1007 {
1008 // Call the file stream callback, if the block is not available
1009 if(pStream->pMaster && pStream->pfnCallback && bPrevBlockAvailable == false)
1010 {
1011 pStream->pfnCallback(pStream->UserData, BlockOffset0, (DWORD)(BlockOffset - BlockOffset0));
1012 bCallbackCalled = true;
1013 }
1014
1015 // Read the complete blocks from the file
1016 if(BlockOffset > pStream->StreamSize)
1017 BlockOffset = pStream->StreamSize;
1018 bResult = pStream->BlockRead(pStream, BlockOffset0, BlockOffset, BlockBuffer, BytesNeeded, bPrevBlockAvailable);
1019 }
1020 }
1021 else
1022 {
1023 // Read the complete blocks from the file
1024 if(EndOffset > pStream->StreamSize)
1025 EndOffset = pStream->StreamSize;
1026 bResult = pStream->BlockRead(pStream, BlockOffset, EndOffset, BlockBuffer, BytesNeeded, true);
1027 }
1028
1029 // Now copy the data to the user buffer
1030 if(bResult)
1031 {
1032 memcpy(pvBuffer, TransferBuffer + BlockBufferOffset, dwBytesToRead);
1033 pStream->StreamPos = ByteOffset + dwBytesToRead;
1034 }
1035 else
1036 {
1037 // If the block read failed, set the last error
1038 SetLastError(ERROR_FILE_INCOMPLETE);
1039 }
1040
1041 // Call the callback to indicate we are done
1042 if(bCallbackCalled)
1043 pStream->pfnCallback(pStream->UserData, 0, 0);
1044
1045 // Free the block buffer and return
1046 STORM_FREE(TransferBuffer);
1047 return bResult;
1048 }
1049
BlockStream_GetSize(TFileStream * pStream,ULONGLONG * pFileSize)1050 static bool BlockStream_GetSize(TFileStream * pStream, ULONGLONG * pFileSize)
1051 {
1052 *pFileSize = pStream->StreamSize;
1053 return true;
1054 }
1055
BlockStream_GetPos(TFileStream * pStream,ULONGLONG * pByteOffset)1056 static bool BlockStream_GetPos(TFileStream * pStream, ULONGLONG * pByteOffset)
1057 {
1058 *pByteOffset = pStream->StreamPos;
1059 return true;
1060 }
1061
BlockStream_Close(TBlockStream * pStream)1062 static void BlockStream_Close(TBlockStream * pStream)
1063 {
1064 // Free the data map, if any
1065 if(pStream->FileBitmap != NULL)
1066 STORM_FREE(pStream->FileBitmap);
1067 pStream->FileBitmap = NULL;
1068
1069 // Call the base class for closing the stream
1070 pStream->BaseClose(pStream);
1071 }
1072
1073 //-----------------------------------------------------------------------------
1074 // File stream allocation function
1075
1076 static STREAM_INIT StreamBaseInit[4] =
1077 {
1078 BaseFile_Init,
1079 BaseMap_Init,
1080 BaseHttp_Init,
1081 BaseNone_Init
1082 };
1083
1084 // This function allocates an empty structure for the file stream
1085 // The stream structure is created as flat block, variable length
1086 // The file name is placed after the end of the stream structure data
AllocateFileStream(const TCHAR * szFileName,size_t StreamSize,DWORD dwStreamFlags)1087 static TFileStream * AllocateFileStream(
1088 const TCHAR * szFileName,
1089 size_t StreamSize,
1090 DWORD dwStreamFlags)
1091 {
1092 TFileStream * pMaster = NULL;
1093 TFileStream * pStream;
1094 const TCHAR * szNextFile = szFileName;
1095 size_t FileNameSize;
1096
1097 // Sanity check
1098 assert(StreamSize != 0);
1099
1100 // The caller can specify chain of files in the following form:
1101 // C:\archive.MPQ*http://www.server.com/MPQs/archive-server.MPQ
1102 // In that case, we use the part after "*" as master file name
1103 while(szNextFile[0] != 0 && szNextFile[0] != _T('*'))
1104 szNextFile++;
1105 FileNameSize = (size_t)((szNextFile - szFileName) * sizeof(TCHAR));
1106
1107 // If we have a next file, we need to open it as master stream
1108 // Note that we don't care if the master stream exists or not,
1109 // If it doesn't, later attempts to read missing file block will fail
1110 if(szNextFile[0] == _T('*'))
1111 {
1112 // Don't allow another master file in the string
1113 if(_tcschr(szNextFile + 1, _T('*')) != NULL)
1114 {
1115 SetLastError(ERROR_INVALID_PARAMETER);
1116 return NULL;
1117 }
1118
1119 // Open the master file
1120 pMaster = FileStream_OpenFile(szNextFile + 1, STREAM_FLAG_READ_ONLY);
1121 }
1122
1123 // Allocate the stream structure for the given stream type
1124 pStream = (TFileStream *)STORM_ALLOC(BYTE, StreamSize + FileNameSize + sizeof(TCHAR));
1125 if(pStream != NULL)
1126 {
1127 // Zero the entire structure
1128 memset(pStream, 0, StreamSize);
1129 pStream->pMaster = pMaster;
1130 pStream->dwFlags = dwStreamFlags;
1131
1132 // Initialize the file name
1133 pStream->szFileName = (TCHAR *)((BYTE *)pStream + StreamSize);
1134 memcpy(pStream->szFileName, szFileName, FileNameSize);
1135 pStream->szFileName[FileNameSize / sizeof(TCHAR)] = 0;
1136
1137 // Initialize the stream functions
1138 StreamBaseInit[dwStreamFlags & 0x03](pStream);
1139 }
1140
1141 return pStream;
1142 }
1143
1144 //-----------------------------------------------------------------------------
1145 // Local functions - flat stream support
1146
FlatStream_CheckFile(TBlockStream * pStream)1147 static DWORD FlatStream_CheckFile(TBlockStream * pStream)
1148 {
1149 LPBYTE FileBitmap = (LPBYTE)pStream->FileBitmap;
1150 DWORD WholeByteCount = (pStream->BlockCount / 8);
1151 DWORD ExtraBitsCount = (pStream->BlockCount & 7);
1152 BYTE ExpectedValue;
1153
1154 // Verify the whole bytes - their value must be 0xFF
1155 for(DWORD i = 0; i < WholeByteCount; i++)
1156 {
1157 if(FileBitmap[i] != 0xFF)
1158 return 0;
1159 }
1160
1161 // If there are extra bits, calculate the mask
1162 if(ExtraBitsCount != 0)
1163 {
1164 ExpectedValue = (BYTE)((1 << ExtraBitsCount) - 1);
1165 if(FileBitmap[WholeByteCount] != ExpectedValue)
1166 return 0;
1167 }
1168
1169 // Yes, the file is complete
1170 return 1;
1171 }
1172
FlatStream_LoadBitmap(TBlockStream * pStream)1173 static bool FlatStream_LoadBitmap(TBlockStream * pStream)
1174 {
1175 FILE_BITMAP_FOOTER Footer;
1176 ULONGLONG ByteOffset;
1177 LPBYTE FileBitmap;
1178 DWORD BlockCount;
1179 DWORD BitmapSize;
1180
1181 // Do not load the bitmap if we should not have to
1182 if(!(pStream->dwFlags & STREAM_FLAG_USE_BITMAP))
1183 return false;
1184
1185 // Only if the size is greater than size of bitmap footer
1186 if(pStream->Base.File.FileSize > sizeof(FILE_BITMAP_FOOTER))
1187 {
1188 // Load the bitmap footer
1189 ByteOffset = pStream->Base.File.FileSize - sizeof(FILE_BITMAP_FOOTER);
1190 if(pStream->BaseRead(pStream, &ByteOffset, &Footer, sizeof(FILE_BITMAP_FOOTER)))
1191 {
1192 // Make sure that the array is properly BSWAP-ed
1193 BSWAP_ARRAY32_UNSIGNED((LPDWORD)(&Footer), sizeof(FILE_BITMAP_FOOTER));
1194
1195 // Verify if there is actually a footer
1196 if(Footer.Signature == ID_FILE_BITMAP_FOOTER && Footer.Version == 0x03)
1197 {
1198 // Get the offset of the bitmap, number of blocks and size of the bitmap
1199 ByteOffset = MAKE_OFFSET64(Footer.MapOffsetHi, Footer.MapOffsetLo);
1200 BlockCount = (DWORD)(((ByteOffset - 1) / Footer.BlockSize) + 1);
1201 BitmapSize = ((BlockCount + 7) / 8);
1202
1203 // Check if the sizes match
1204 if(ByteOffset + BitmapSize + sizeof(FILE_BITMAP_FOOTER) == pStream->Base.File.FileSize)
1205 {
1206 // Allocate space for the bitmap
1207 FileBitmap = STORM_ALLOC(BYTE, BitmapSize);
1208 if(FileBitmap != NULL)
1209 {
1210 // Load the bitmap bits
1211 if(!pStream->BaseRead(pStream, &ByteOffset, FileBitmap, BitmapSize))
1212 {
1213 STORM_FREE(FileBitmap);
1214 return false;
1215 }
1216
1217 // Update the stream size
1218 pStream->BuildNumber = Footer.BuildNumber;
1219 pStream->StreamSize = ByteOffset;
1220
1221 // Fill the bitmap information
1222 pStream->FileBitmap = FileBitmap;
1223 pStream->BitmapSize = BitmapSize;
1224 pStream->BlockSize = Footer.BlockSize;
1225 pStream->BlockCount = BlockCount;
1226 pStream->IsComplete = FlatStream_CheckFile(pStream);
1227 return true;
1228 }
1229 }
1230 }
1231 }
1232 }
1233
1234 return false;
1235 }
1236
FlatStream_UpdateBitmap(TBlockStream * pStream,ULONGLONG StartOffset,ULONGLONG EndOffset)1237 static void FlatStream_UpdateBitmap(
1238 TBlockStream * pStream, // Pointer to an open stream
1239 ULONGLONG StartOffset,
1240 ULONGLONG EndOffset)
1241 {
1242 LPBYTE FileBitmap = (LPBYTE)pStream->FileBitmap;
1243 DWORD BlockIndex;
1244 DWORD BlockSize = pStream->BlockSize;
1245 DWORD ByteIndex;
1246 BYTE BitMask;
1247
1248 // Sanity checks
1249 assert((StartOffset & (BlockSize - 1)) == 0);
1250 assert(FileBitmap != NULL);
1251
1252 // Calculate the index of the block
1253 BlockIndex = (DWORD)(StartOffset / BlockSize);
1254 ByteIndex = (BlockIndex / 0x08);
1255 BitMask = (BYTE)(1 << (BlockIndex & 0x07));
1256
1257 // Set all bits for the specified range
1258 while(StartOffset < EndOffset)
1259 {
1260 // Set the bit
1261 FileBitmap[ByteIndex] |= BitMask;
1262
1263 // Move all
1264 StartOffset += BlockSize;
1265 ByteIndex += (BitMask >> 0x07);
1266 BitMask = (BitMask >> 0x07) | (BitMask << 0x01);
1267 }
1268
1269 // Increment the bitmap update count
1270 pStream->IsModified = 1;
1271 }
1272
FlatStream_BlockCheck(TBlockStream * pStream,ULONGLONG BlockOffset)1273 static bool FlatStream_BlockCheck(
1274 TBlockStream * pStream, // Pointer to an open stream
1275 ULONGLONG BlockOffset)
1276 {
1277 LPBYTE FileBitmap = (LPBYTE)pStream->FileBitmap;
1278 DWORD BlockIndex;
1279 BYTE BitMask;
1280
1281 // Sanity checks
1282 assert((BlockOffset & (pStream->BlockSize - 1)) == 0);
1283 assert(FileBitmap != NULL);
1284
1285 // Calculate the index of the block
1286 BlockIndex = (DWORD)(BlockOffset / pStream->BlockSize);
1287 BitMask = (BYTE)(1 << (BlockIndex & 0x07));
1288
1289 // Check if the bit is present
1290 return (FileBitmap[BlockIndex / 0x08] & BitMask) ? true : false;
1291 }
1292
FlatStream_BlockRead(TBlockStream * pStream,ULONGLONG StartOffset,ULONGLONG EndOffset,LPBYTE BlockBuffer,DWORD BytesNeeded,bool bAvailable)1293 static bool FlatStream_BlockRead(
1294 TBlockStream * pStream, // Pointer to an open stream
1295 ULONGLONG StartOffset,
1296 ULONGLONG EndOffset,
1297 LPBYTE BlockBuffer,
1298 DWORD BytesNeeded,
1299 bool bAvailable)
1300 {
1301 DWORD BytesToRead = (DWORD)(EndOffset - StartOffset);
1302
1303 // The starting offset must be aligned to size of the block
1304 assert(pStream->FileBitmap != NULL);
1305 assert((StartOffset & (pStream->BlockSize - 1)) == 0);
1306 assert(StartOffset < EndOffset);
1307
1308 // If the blocks are not available, we need to load them from the master
1309 // and then save to the mirror
1310 if(bAvailable == false)
1311 {
1312 // If we have no master, we cannot satisfy read request
1313 if(pStream->pMaster == NULL)
1314 return false;
1315
1316 // Load the blocks from the master stream
1317 // Note that we always have to read complete blocks
1318 // so they get properly stored to the mirror stream
1319 if(!FileStream_Read(pStream->pMaster, &StartOffset, BlockBuffer, BytesToRead))
1320 return false;
1321
1322 // Store the loaded blocks to the mirror file.
1323 // Note that this operation is not required to succeed
1324 if(pStream->BaseWrite(pStream, &StartOffset, BlockBuffer, BytesToRead))
1325 FlatStream_UpdateBitmap(pStream, StartOffset, EndOffset);
1326
1327 return true;
1328 }
1329 else
1330 {
1331 if(BytesToRead > BytesNeeded)
1332 BytesToRead = BytesNeeded;
1333 return pStream->BaseRead(pStream, &StartOffset, BlockBuffer, BytesToRead);
1334 }
1335 }
1336
FlatStream_Close(TBlockStream * pStream)1337 static void FlatStream_Close(TBlockStream * pStream)
1338 {
1339 FILE_BITMAP_FOOTER Footer;
1340
1341 if(pStream->FileBitmap && pStream->IsModified)
1342 {
1343 // Write the file bitmap
1344 pStream->BaseWrite(pStream, &pStream->StreamSize, pStream->FileBitmap, pStream->BitmapSize);
1345
1346 // Prepare and write the file footer
1347 Footer.Signature = ID_FILE_BITMAP_FOOTER;
1348 Footer.Version = 3;
1349 Footer.BuildNumber = pStream->BuildNumber;
1350 Footer.MapOffsetLo = (DWORD)(pStream->StreamSize & 0xFFFFFFFF);
1351 Footer.MapOffsetHi = (DWORD)(pStream->StreamSize >> 0x20);
1352 Footer.BlockSize = pStream->BlockSize;
1353 BSWAP_ARRAY32_UNSIGNED(&Footer, sizeof(FILE_BITMAP_FOOTER));
1354 pStream->BaseWrite(pStream, NULL, &Footer, sizeof(FILE_BITMAP_FOOTER));
1355 }
1356
1357 // Close the base class
1358 BlockStream_Close(pStream);
1359 }
1360
FlatStream_CreateMirror(TBlockStream * pStream)1361 static bool FlatStream_CreateMirror(TBlockStream * pStream)
1362 {
1363 ULONGLONG MasterSize = 0;
1364 ULONGLONG MirrorSize = 0;
1365 LPBYTE FileBitmap = NULL;
1366 DWORD dwBitmapSize;
1367 DWORD dwBlockCount;
1368 bool bNeedCreateMirrorStream = true;
1369 bool bNeedResizeMirrorStream = true;
1370
1371 // Do we have master function and base creation function?
1372 if(pStream->pMaster == NULL || pStream->BaseCreate == NULL)
1373 return false;
1374
1375 // Retrieve the master file size, block count and bitmap size
1376 FileStream_GetSize(pStream->pMaster, &MasterSize);
1377 dwBlockCount = (DWORD)((MasterSize + DEFAULT_BLOCK_SIZE - 1) / DEFAULT_BLOCK_SIZE);
1378 dwBitmapSize = (DWORD)((dwBlockCount + 7) / 8);
1379
1380 // Setup stream size and position
1381 pStream->BuildNumber = DEFAULT_BUILD_NUMBER; // BUGBUG: Really???
1382 pStream->StreamSize = MasterSize;
1383 pStream->StreamPos = 0;
1384
1385 // Open the base stream for write access
1386 if(pStream->BaseOpen(pStream, pStream->szFileName, 0))
1387 {
1388 // If the file open succeeded, check if the file size matches required size
1389 pStream->BaseGetSize(pStream, &MirrorSize);
1390 if(MirrorSize == MasterSize + dwBitmapSize + sizeof(FILE_BITMAP_FOOTER))
1391 {
1392 // Attempt to load an existing file bitmap
1393 if(FlatStream_LoadBitmap(pStream))
1394 return true;
1395
1396 // We need to create new file bitmap
1397 bNeedResizeMirrorStream = false;
1398 }
1399
1400 // We need to create mirror stream
1401 bNeedCreateMirrorStream = false;
1402 }
1403
1404 // Create a new stream, if needed
1405 if(bNeedCreateMirrorStream)
1406 {
1407 if(!pStream->BaseCreate(pStream))
1408 return false;
1409 }
1410
1411 // If we need to, then resize the mirror stream
1412 if(bNeedResizeMirrorStream)
1413 {
1414 if(!pStream->BaseResize(pStream, MasterSize + dwBitmapSize + sizeof(FILE_BITMAP_FOOTER)))
1415 return false;
1416 }
1417
1418 // Allocate the bitmap array
1419 FileBitmap = STORM_ALLOC(BYTE, dwBitmapSize);
1420 if(FileBitmap == NULL)
1421 return false;
1422
1423 // Initialize the bitmap
1424 memset(FileBitmap, 0, dwBitmapSize);
1425 pStream->FileBitmap = FileBitmap;
1426 pStream->BitmapSize = dwBitmapSize;
1427 pStream->BlockSize = DEFAULT_BLOCK_SIZE;
1428 pStream->BlockCount = dwBlockCount;
1429 pStream->IsComplete = 0;
1430 pStream->IsModified = 1;
1431
1432 // Note: Don't write the stream bitmap right away.
1433 // Doing so would cause sparse file resize on NTFS,
1434 // which would take long time on larger files.
1435 return true;
1436 }
1437
FlatStream_Open(const TCHAR * szFileName,DWORD dwStreamFlags)1438 static TFileStream * FlatStream_Open(const TCHAR * szFileName, DWORD dwStreamFlags)
1439 {
1440 TBlockStream * pStream;
1441 ULONGLONG ByteOffset = 0;
1442
1443 // Create new empty stream
1444 pStream = (TBlockStream *)AllocateFileStream(szFileName, sizeof(TBlockStream), dwStreamFlags);
1445 if(pStream == NULL)
1446 return NULL;
1447
1448 // Do we have a master stream?
1449 if(pStream->pMaster != NULL)
1450 {
1451 if(!FlatStream_CreateMirror(pStream))
1452 {
1453 FileStream_Close(pStream);
1454 SetLastError(ERROR_FILE_NOT_FOUND);
1455 return NULL;
1456 }
1457 }
1458 else
1459 {
1460 // Attempt to open the base stream
1461 if(!pStream->BaseOpen(pStream, pStream->szFileName, dwStreamFlags))
1462 {
1463 FileStream_Close(pStream);
1464 return NULL;
1465 }
1466
1467 // Load the bitmap, if required to
1468 if(dwStreamFlags & STREAM_FLAG_USE_BITMAP)
1469 FlatStream_LoadBitmap(pStream);
1470 }
1471
1472 // If we have a stream bitmap, set the reading functions
1473 // which check presence of each file block
1474 if(pStream->FileBitmap != NULL)
1475 {
1476 // Set the stream position to zero. Stream size is already set
1477 assert(pStream->StreamSize != 0);
1478 pStream->StreamPos = 0;
1479 pStream->dwFlags |= STREAM_FLAG_READ_ONLY;
1480
1481 // Supply the stream functions
1482 pStream->StreamRead = (STREAM_READ)BlockStream_Read;
1483 pStream->StreamGetSize = BlockStream_GetSize;
1484 pStream->StreamGetPos = BlockStream_GetPos;
1485 pStream->StreamClose = (STREAM_CLOSE)FlatStream_Close;
1486
1487 // Supply the block functions
1488 pStream->BlockCheck = (BLOCK_CHECK)FlatStream_BlockCheck;
1489 pStream->BlockRead = (BLOCK_READ)FlatStream_BlockRead;
1490 }
1491 else
1492 {
1493 // Reset the base position to zero
1494 pStream->BaseRead(pStream, &ByteOffset, NULL, 0);
1495
1496 // Setup stream size and position
1497 pStream->StreamSize = pStream->Base.File.FileSize;
1498 pStream->StreamPos = 0;
1499
1500 // Set the base functions
1501 pStream->StreamRead = pStream->BaseRead;
1502 pStream->StreamWrite = pStream->BaseWrite;
1503 pStream->StreamResize = pStream->BaseResize;
1504 pStream->StreamGetSize = pStream->BaseGetSize;
1505 pStream->StreamGetPos = pStream->BaseGetPos;
1506 pStream->StreamClose = pStream->BaseClose;
1507 }
1508
1509 return pStream;
1510 }
1511
1512 //-----------------------------------------------------------------------------
1513 // Local functions - partial stream support
1514
IsPartHeader(PPART_FILE_HEADER pPartHdr)1515 static bool IsPartHeader(PPART_FILE_HEADER pPartHdr)
1516 {
1517 // Version number must be 2
1518 if(pPartHdr->PartialVersion == 2)
1519 {
1520 // GameBuildNumber must be an ASCII number
1521 if(isdigit(pPartHdr->GameBuildNumber[0]) && isdigit(pPartHdr->GameBuildNumber[1]) && isdigit(pPartHdr->GameBuildNumber[2]))
1522 {
1523 // Block size must be power of 2
1524 if((pPartHdr->BlockSize & (pPartHdr->BlockSize - 1)) == 0)
1525 return true;
1526 }
1527 }
1528
1529 return false;
1530 }
1531
PartStream_CheckFile(TBlockStream * pStream)1532 static DWORD PartStream_CheckFile(TBlockStream * pStream)
1533 {
1534 PPART_FILE_MAP_ENTRY FileBitmap = (PPART_FILE_MAP_ENTRY)pStream->FileBitmap;
1535 DWORD dwBlockCount;
1536
1537 // Get the number of blocks
1538 dwBlockCount = (DWORD)((pStream->StreamSize + pStream->BlockSize - 1) / pStream->BlockSize);
1539
1540 // Check all blocks
1541 for(DWORD i = 0; i < dwBlockCount; i++, FileBitmap++)
1542 {
1543 // Few sanity checks
1544 assert(FileBitmap->LargeValueHi == 0);
1545 assert(FileBitmap->LargeValueLo == 0);
1546 assert(FileBitmap->Flags == 0 || FileBitmap->Flags == 3);
1547
1548 // Check if this block is present
1549 if(FileBitmap->Flags != 3)
1550 return 0;
1551 }
1552
1553 // Yes, the file is complete
1554 return 1;
1555 }
1556
PartStream_LoadBitmap(TBlockStream * pStream)1557 static bool PartStream_LoadBitmap(TBlockStream * pStream)
1558 {
1559 PPART_FILE_MAP_ENTRY FileBitmap;
1560 PART_FILE_HEADER PartHdr;
1561 ULONGLONG ByteOffset = 0;
1562 ULONGLONG StreamSize = 0;
1563 DWORD BlockCount;
1564 DWORD BitmapSize;
1565
1566 // Only if the size is greater than size of the bitmap header
1567 if(pStream->Base.File.FileSize > sizeof(PART_FILE_HEADER))
1568 {
1569 // Attempt to read PART file header
1570 if(pStream->BaseRead(pStream, &ByteOffset, &PartHdr, sizeof(PART_FILE_HEADER)))
1571 {
1572 // We need to swap PART file header on big-endian platforms
1573 BSWAP_ARRAY32_UNSIGNED(&PartHdr, sizeof(PART_FILE_HEADER));
1574
1575 // Verify the PART file header
1576 if(IsPartHeader(&PartHdr))
1577 {
1578 // Get the number of blocks and size of one block
1579 StreamSize = MAKE_OFFSET64(PartHdr.FileSizeHi, PartHdr.FileSizeLo);
1580 ByteOffset = sizeof(PART_FILE_HEADER);
1581 BlockCount = (DWORD)((StreamSize + PartHdr.BlockSize - 1) / PartHdr.BlockSize);
1582 BitmapSize = BlockCount * sizeof(PART_FILE_MAP_ENTRY);
1583
1584 // Check if sizes match
1585 if((ByteOffset + BitmapSize) < pStream->Base.File.FileSize)
1586 {
1587 // Allocate space for the array of PART_FILE_MAP_ENTRY
1588 FileBitmap = STORM_ALLOC(PART_FILE_MAP_ENTRY, BlockCount);
1589 if(FileBitmap != NULL)
1590 {
1591 // Load the block map
1592 if(!pStream->BaseRead(pStream, &ByteOffset, FileBitmap, BitmapSize))
1593 {
1594 STORM_FREE(FileBitmap);
1595 return false;
1596 }
1597
1598 // Make sure that the byte order is correct
1599 BSWAP_ARRAY32_UNSIGNED(FileBitmap, BitmapSize);
1600
1601 // Update the stream size
1602 pStream->BuildNumber = StringToInt(PartHdr.GameBuildNumber);
1603 pStream->StreamSize = StreamSize;
1604
1605 // Fill the bitmap information
1606 pStream->FileBitmap = FileBitmap;
1607 pStream->BitmapSize = BitmapSize;
1608 pStream->BlockSize = PartHdr.BlockSize;
1609 pStream->BlockCount = BlockCount;
1610 pStream->IsComplete = PartStream_CheckFile(pStream);
1611 return true;
1612 }
1613 }
1614 }
1615 }
1616 }
1617
1618 return false;
1619 }
1620
PartStream_UpdateBitmap(TBlockStream * pStream,ULONGLONG StartOffset,ULONGLONG EndOffset,ULONGLONG RealOffset)1621 static void PartStream_UpdateBitmap(
1622 TBlockStream * pStream, // Pointer to an open stream
1623 ULONGLONG StartOffset,
1624 ULONGLONG EndOffset,
1625 ULONGLONG RealOffset)
1626 {
1627 PPART_FILE_MAP_ENTRY FileBitmap;
1628 DWORD BlockSize = pStream->BlockSize;
1629
1630 // Sanity checks
1631 assert((StartOffset & (BlockSize - 1)) == 0);
1632 assert(pStream->FileBitmap != NULL);
1633
1634 // Calculate the first entry in the block map
1635 FileBitmap = (PPART_FILE_MAP_ENTRY)pStream->FileBitmap + (StartOffset / BlockSize);
1636
1637 // Set all bits for the specified range
1638 while(StartOffset < EndOffset)
1639 {
1640 // Set the bit
1641 FileBitmap->BlockOffsHi = (DWORD)(RealOffset >> 0x20);
1642 FileBitmap->BlockOffsLo = (DWORD)(RealOffset & 0xFFFFFFFF);
1643 FileBitmap->Flags = 3;
1644
1645 // Move all
1646 StartOffset += BlockSize;
1647 RealOffset += BlockSize;
1648 FileBitmap++;
1649 }
1650
1651 // Increment the bitmap update count
1652 pStream->IsModified = 1;
1653 }
1654
PartStream_BlockCheck(TBlockStream * pStream,ULONGLONG BlockOffset)1655 static bool PartStream_BlockCheck(
1656 TBlockStream * pStream, // Pointer to an open stream
1657 ULONGLONG BlockOffset)
1658 {
1659 PPART_FILE_MAP_ENTRY FileBitmap;
1660
1661 // Sanity checks
1662 assert((BlockOffset & (pStream->BlockSize - 1)) == 0);
1663 assert(pStream->FileBitmap != NULL);
1664
1665 // Calculate the block map entry
1666 FileBitmap = (PPART_FILE_MAP_ENTRY)pStream->FileBitmap + (BlockOffset / pStream->BlockSize);
1667
1668 // Check if the flags are present
1669 return (FileBitmap->Flags & 0x03) ? true : false;
1670 }
1671
PartStream_BlockRead(TBlockStream * pStream,ULONGLONG StartOffset,ULONGLONG EndOffset,LPBYTE BlockBuffer,DWORD BytesNeeded,bool bAvailable)1672 static bool PartStream_BlockRead(
1673 TBlockStream * pStream,
1674 ULONGLONG StartOffset,
1675 ULONGLONG EndOffset,
1676 LPBYTE BlockBuffer,
1677 DWORD BytesNeeded,
1678 bool bAvailable)
1679 {
1680 PPART_FILE_MAP_ENTRY FileBitmap;
1681 ULONGLONG ByteOffset;
1682 DWORD BytesToRead;
1683 DWORD BlockIndex = (DWORD)(StartOffset / pStream->BlockSize);
1684
1685 // The starting offset must be aligned to size of the block
1686 assert(pStream->FileBitmap != NULL);
1687 assert((StartOffset & (pStream->BlockSize - 1)) == 0);
1688 assert(StartOffset < EndOffset);
1689
1690 // If the blocks are not available, we need to load them from the master
1691 // and then save to the mirror
1692 if(bAvailable == false)
1693 {
1694 // If we have no master, we cannot satisfy read request
1695 if(pStream->pMaster == NULL)
1696 return false;
1697
1698 // Load the blocks from the master stream
1699 // Note that we always have to read complete blocks
1700 // so they get properly stored to the mirror stream
1701 BytesToRead = (DWORD)(EndOffset - StartOffset);
1702 if(!FileStream_Read(pStream->pMaster, &StartOffset, BlockBuffer, BytesToRead))
1703 return false;
1704
1705 // The loaded blocks are going to be stored to the end of the file
1706 // Note that this operation is not required to succeed
1707 if(pStream->BaseGetSize(pStream, &ByteOffset))
1708 {
1709 // Store the loaded blocks to the mirror file.
1710 if(pStream->BaseWrite(pStream, &ByteOffset, BlockBuffer, BytesToRead))
1711 {
1712 PartStream_UpdateBitmap(pStream, StartOffset, EndOffset, ByteOffset);
1713 }
1714 }
1715 }
1716 else
1717 {
1718 // Get the file map entry
1719 FileBitmap = (PPART_FILE_MAP_ENTRY)pStream->FileBitmap + BlockIndex;
1720
1721 // Read all blocks
1722 while(StartOffset < EndOffset)
1723 {
1724 // Get the number of bytes to be read
1725 BytesToRead = (DWORD)(EndOffset - StartOffset);
1726 if(BytesToRead > pStream->BlockSize)
1727 BytesToRead = pStream->BlockSize;
1728 if(BytesToRead > BytesNeeded)
1729 BytesToRead = BytesNeeded;
1730
1731 // Read the block
1732 ByteOffset = MAKE_OFFSET64(FileBitmap->BlockOffsHi, FileBitmap->BlockOffsLo);
1733 if(!pStream->BaseRead(pStream, &ByteOffset, BlockBuffer, BytesToRead))
1734 return false;
1735
1736 // Move the pointers
1737 StartOffset += pStream->BlockSize;
1738 BlockBuffer += pStream->BlockSize;
1739 BytesNeeded -= pStream->BlockSize;
1740 FileBitmap++;
1741 }
1742 }
1743
1744 return true;
1745 }
1746
PartStream_Close(TBlockStream * pStream)1747 static void PartStream_Close(TBlockStream * pStream)
1748 {
1749 PART_FILE_HEADER PartHeader;
1750 ULONGLONG ByteOffset = 0;
1751
1752 if(pStream->FileBitmap && pStream->IsModified)
1753 {
1754 // Prepare the part file header
1755 memset(&PartHeader, 0, sizeof(PART_FILE_HEADER));
1756 PartHeader.PartialVersion = 2;
1757 PartHeader.FileSizeHi = (DWORD)(pStream->StreamSize >> 0x20);
1758 PartHeader.FileSizeLo = (DWORD)(pStream->StreamSize & 0xFFFFFFFF);
1759 PartHeader.BlockSize = pStream->BlockSize;
1760
1761 // Make sure that the header is properly BSWAPed
1762 BSWAP_ARRAY32_UNSIGNED(&PartHeader, sizeof(PART_FILE_HEADER));
1763 IntToString(PartHeader.GameBuildNumber, _countof(PartHeader.GameBuildNumber), pStream->BuildNumber);
1764
1765 // Write the part header
1766 pStream->BaseWrite(pStream, &ByteOffset, &PartHeader, sizeof(PART_FILE_HEADER));
1767
1768 // Write the block bitmap
1769 BSWAP_ARRAY32_UNSIGNED(pStream->FileBitmap, pStream->BitmapSize);
1770 pStream->BaseWrite(pStream, NULL, pStream->FileBitmap, pStream->BitmapSize);
1771 }
1772
1773 // Close the base class
1774 BlockStream_Close(pStream);
1775 }
1776
PartStream_CreateMirror(TBlockStream * pStream)1777 static bool PartStream_CreateMirror(TBlockStream * pStream)
1778 {
1779 ULONGLONG RemainingSize;
1780 ULONGLONG MasterSize = 0;
1781 ULONGLONG MirrorSize = 0;
1782 LPBYTE FileBitmap = NULL;
1783 DWORD dwBitmapSize;
1784 DWORD dwBlockCount;
1785 bool bNeedCreateMirrorStream = true;
1786 bool bNeedResizeMirrorStream = true;
1787
1788 // Do we have master function and base creation function?
1789 if(pStream->pMaster == NULL || pStream->BaseCreate == NULL)
1790 return false;
1791
1792 // Retrieve the master file size, block count and bitmap size
1793 FileStream_GetSize(pStream->pMaster, &MasterSize);
1794 dwBlockCount = (DWORD)((MasterSize + DEFAULT_BLOCK_SIZE - 1) / DEFAULT_BLOCK_SIZE);
1795 dwBitmapSize = (DWORD)(dwBlockCount * sizeof(PART_FILE_MAP_ENTRY));
1796
1797 // Setup stream size and position
1798 pStream->BuildNumber = DEFAULT_BUILD_NUMBER; // BUGBUG: Really???
1799 pStream->StreamSize = MasterSize;
1800 pStream->StreamPos = 0;
1801
1802 // Open the base stream for write access
1803 if(pStream->BaseOpen(pStream, pStream->szFileName, 0))
1804 {
1805 // If the file open succeeded, check if the file size matches required size
1806 pStream->BaseGetSize(pStream, &MirrorSize);
1807 if(MirrorSize >= sizeof(PART_FILE_HEADER) + dwBitmapSize)
1808 {
1809 // Check if the remaining size is aligned to block
1810 RemainingSize = MirrorSize - sizeof(PART_FILE_HEADER) - dwBitmapSize;
1811 if((RemainingSize & (DEFAULT_BLOCK_SIZE - 1)) == 0 || RemainingSize == MasterSize)
1812 {
1813 // Attempt to load an existing file bitmap
1814 if(PartStream_LoadBitmap(pStream))
1815 return true;
1816 }
1817 }
1818
1819 // We need to create mirror stream
1820 bNeedCreateMirrorStream = false;
1821 }
1822
1823 // Create a new stream, if needed
1824 if(bNeedCreateMirrorStream)
1825 {
1826 if(!pStream->BaseCreate(pStream))
1827 return false;
1828 }
1829
1830 // If we need to, then resize the mirror stream
1831 if(bNeedResizeMirrorStream)
1832 {
1833 if(!pStream->BaseResize(pStream, sizeof(PART_FILE_HEADER) + dwBitmapSize))
1834 return false;
1835 }
1836
1837 // Allocate the bitmap array
1838 FileBitmap = STORM_ALLOC(BYTE, dwBitmapSize);
1839 if(FileBitmap == NULL)
1840 return false;
1841
1842 // Initialize the bitmap
1843 memset(FileBitmap, 0, dwBitmapSize);
1844 pStream->FileBitmap = FileBitmap;
1845 pStream->BitmapSize = dwBitmapSize;
1846 pStream->BlockSize = DEFAULT_BLOCK_SIZE;
1847 pStream->BlockCount = dwBlockCount;
1848 pStream->IsComplete = 0;
1849 pStream->IsModified = 1;
1850
1851 // Note: Don't write the stream bitmap right away.
1852 // Doing so would cause sparse file resize on NTFS,
1853 // which would take long time on larger files.
1854 return true;
1855 }
1856
1857
PartStream_Open(const TCHAR * szFileName,DWORD dwStreamFlags)1858 static TFileStream * PartStream_Open(const TCHAR * szFileName, DWORD dwStreamFlags)
1859 {
1860 TBlockStream * pStream;
1861
1862 // Create new empty stream
1863 pStream = (TBlockStream *)AllocateFileStream(szFileName, sizeof(TBlockStream), dwStreamFlags);
1864 if(pStream == NULL)
1865 return NULL;
1866
1867 // Do we have a master stream?
1868 if(pStream->pMaster != NULL)
1869 {
1870 if(!PartStream_CreateMirror(pStream))
1871 {
1872 FileStream_Close(pStream);
1873 SetLastError(ERROR_FILE_NOT_FOUND);
1874 return NULL;
1875 }
1876 }
1877 else
1878 {
1879 // Attempt to open the base stream
1880 if(!pStream->BaseOpen(pStream, pStream->szFileName, dwStreamFlags))
1881 {
1882 FileStream_Close(pStream);
1883 return NULL;
1884 }
1885
1886 // Load the part stream block map
1887 if(!PartStream_LoadBitmap(pStream))
1888 {
1889 FileStream_Close(pStream);
1890 SetLastError(ERROR_BAD_FORMAT);
1891 return NULL;
1892 }
1893 }
1894
1895 // Set the stream position to zero. Stream size is already set
1896 assert(pStream->StreamSize != 0);
1897 pStream->StreamPos = 0;
1898 pStream->dwFlags |= STREAM_FLAG_READ_ONLY;
1899
1900 // Set new function pointers
1901 pStream->StreamRead = (STREAM_READ)BlockStream_Read;
1902 pStream->StreamGetPos = BlockStream_GetPos;
1903 pStream->StreamGetSize = BlockStream_GetSize;
1904 pStream->StreamClose = (STREAM_CLOSE)PartStream_Close;
1905
1906 // Supply the block functions
1907 pStream->BlockCheck = (BLOCK_CHECK)PartStream_BlockCheck;
1908 pStream->BlockRead = (BLOCK_READ)PartStream_BlockRead;
1909 return pStream;
1910 }
1911
1912 //-----------------------------------------------------------------------------
1913 // Local functions - MPQE stream support
1914
1915 static const char * szKeyTemplate = "expand 32-byte k000000000000000000000000000000000000000000000000";
1916
1917 static const char * AuthCodeArray[] =
1918 {
1919 // Starcraft II (Heart of the Swarm)
1920 // Authentication code URL: http://dist.blizzard.com/mediakey/hots-authenticationcode-bgdl.txt
1921 // -0C- -1C--08- -18--04- -14--00- -10-
1922 "S48B6CDTN5XEQAKQDJNDLJBJ73FDFM3U", // SC2 Heart of the Swarm-all : "expand 32-byte kQAKQ0000FM3UN5XE000073FD6CDT0000LJBJS48B0000DJND"
1923
1924 // Diablo III: Agent.exe (1.0.0.954)
1925 // Address of decryption routine: 00502b00
1926 // Pointer to decryptor object: ECX
1927 // Pointer to key: ECX+0x5C
1928 // Authentication code URL: http://dist.blizzard.com/mediakey/d3-authenticationcode-enGB.txt
1929 // -0C- -1C--08- -18--04- -14--00- -10-
1930 "UCMXF6EJY352EFH4XFRXCFH2XC9MQRZK", // Diablo III Installer (deDE): "expand 32-byte kEFH40000QRZKY3520000XC9MF6EJ0000CFH2UCMX0000XFRX"
1931 "MMKVHY48RP7WXP4GHYBQ7SL9J9UNPHBP", // Diablo III Installer (enGB): "expand 32-byte kXP4G0000PHBPRP7W0000J9UNHY4800007SL9MMKV0000HYBQ"
1932 "8MXLWHQ7VGGLTZ9MQZQSFDCLJYET3CPP", // Diablo III Installer (enSG): "expand 32-byte kTZ9M00003CPPVGGL0000JYETWHQ70000FDCL8MXL0000QZQS"
1933 "EJ2R5TM6XFE2GUNG5QDGHKQ9UAKPWZSZ", // Diablo III Installer (enUS): "expand 32-byte kGUNG0000WZSZXFE20000UAKP5TM60000HKQ9EJ2R00005QDG"
1934 "PBGFBE42Z6LNK65UGJQ3WZVMCLP4HQQT", // Diablo III Installer (esES): "expand 32-byte kK65U0000HQQTZ6LN0000CLP4BE420000WZVMPBGF0000GJQ3"
1935 "X7SEJJS9TSGCW5P28EBSC47AJPEY8VU2", // Diablo III Installer (esMX): "expand 32-byte kW5P200008VU2TSGC0000JPEYJJS90000C47AX7SE00008EBS"
1936 "5KVBQA8VYE6XRY3DLGC5ZDE4XS4P7YA2", // Diablo III Installer (frFR): "expand 32-byte kRY3D00007YA2YE6X0000XS4PQA8V0000ZDE45KVB0000LGC5"
1937 "478JD2K56EVNVVY4XX8TDWYT5B8KB254", // Diablo III Installer (itIT): "expand 32-byte kVVY40000B2546EVN00005B8KD2K50000DWYT478J0000XX8T"
1938 "8TS4VNFQRZTN6YWHE9CHVDH9NVWD474A", // Diablo III Installer (koKR): "expand 32-byte k6YWH0000474ARZTN0000NVWDVNFQ0000VDH98TS40000E9CH"
1939 "LJ52Z32DF4LZ4ZJJXVKK3AZQA6GABLJB", // Diablo III Installer (plPL): "expand 32-byte k4ZJJ0000BLJBF4LZ0000A6GAZ32D00003AZQLJ520000XVKK"
1940 "K6BDHY2ECUE2545YKNLBJPVYWHE7XYAG", // Diablo III Installer (ptBR): "expand 32-byte k545Y0000XYAGCUE20000WHE7HY2E0000JPVYK6BD0000KNLB"
1941 "NDVW8GWLAYCRPGRNY8RT7ZZUQU63VLPR", // Diablo III Installer (ruRU): "expand 32-byte kXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
1942 "6VWCQTN8V3ZZMRUCZXV8A8CGUX2TAA8H", // Diablo III Installer (zhTW): "expand 32-byte kMRUC0000AA8HV3ZZ0000UX2TQTN80000A8CG6VWC0000ZXV8"
1943 // "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", // Diablo III Installer (zhCN): "expand 32-byte kXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
1944
1945 // Starcraft II (Wings of Liberty): Installer.exe (4.1.1.4219)
1946 // Address of decryption routine: 0053A3D0
1947 // Pointer to decryptor object: ECX
1948 // Pointer to key: ECX+0x5C
1949 // Authentication code URL: http://dist.blizzard.com/mediakey/sc2-authenticationcode-enUS.txt
1950 // -0C- -1C--08- -18--04- -14--00- -10-
1951 "Y45MD3CAK4KXSSXHYD9VY64Z8EKJ4XFX", // SC2 Wings of Liberty (deDE): "expand 32-byte kSSXH00004XFXK4KX00008EKJD3CA0000Y64ZY45M0000YD9V"
1952 "G8MN8UDG6NA2ANGY6A3DNY82HRGF29ZH", // SC2 Wings of Liberty (enGB): "expand 32-byte kANGY000029ZH6NA20000HRGF8UDG0000NY82G8MN00006A3D"
1953 "W9RRHLB2FDU9WW5B3ECEBLRSFWZSF7HW", // SC2 Wings of Liberty (enSG): "expand 32-byte kWW5B0000F7HWFDU90000FWZSHLB20000BLRSW9RR00003ECE"
1954 "3DH5RE5NVM5GTFD85LXGWT6FK859ETR5", // SC2 Wings of Liberty (enUS): "expand 32-byte kTFD80000ETR5VM5G0000K859RE5N0000WT6F3DH500005LXG"
1955 "8WLKUAXE94PFQU4Y249PAZ24N4R4XKTQ", // SC2 Wings of Liberty (esES): "expand 32-byte kQU4Y0000XKTQ94PF0000N4R4UAXE0000AZ248WLK0000249P"
1956 "A34DXX3VHGGXSQBRFE5UFFDXMF9G4G54", // SC2 Wings of Liberty (esMX): "expand 32-byte kSQBR00004G54HGGX0000MF9GXX3V0000FFDXA34D0000FE5U"
1957 "ZG7J9K938HJEFWPQUA768MA2PFER6EAJ", // SC2 Wings of Liberty (frFR): "expand 32-byte kFWPQ00006EAJ8HJE0000PFER9K9300008MA2ZG7J0000UA76"
1958 "NE7CUNNNTVAPXV7E3G2BSVBWGVMW8BL2", // SC2 Wings of Liberty (itIT): "expand 32-byte kXV7E00008BL2TVAP0000GVMWUNNN0000SVBWNE7C00003G2B"
1959 "3V9E2FTMBM9QQWK7U6MAMWAZWQDB838F", // SC2 Wings of Liberty (koKR): "expand 32-byte kQWK70000838FBM9Q0000WQDB2FTM0000MWAZ3V9E0000U6MA"
1960 "2NSFB8MELULJ83U6YHA3UP6K4MQD48L6", // SC2 Wings of Liberty (plPL): "expand 32-byte k83U6000048L6LULJ00004MQDB8ME0000UP6K2NSF0000YHA3"
1961 "QA2TZ9EWZ4CUU8BMB5WXCTY65F9CSW4E", // SC2 Wings of Liberty (ptBR): "expand 32-byte kU8BM0000SW4EZ4CU00005F9CZ9EW0000CTY6QA2T0000B5WX"
1962 "VHB378W64BAT9SH7D68VV9NLQDK9YEGT", // SC2 Wings of Liberty (ruRU): "expand 32-byte k9SH70000YEGT4BAT0000QDK978W60000V9NLVHB30000D68V"
1963 "U3NFQJV4M6GC7KBN9XQJ3BRDN3PLD9NE", // SC2 Wings of Liberty (zhTW): "expand 32-byte k7KBN0000D9NEM6GC0000N3PLQJV400003BRDU3NF00009XQJ"
1964
1965 NULL
1966 };
1967
Rol32(DWORD dwValue,DWORD dwRolCount)1968 static DWORD Rol32(DWORD dwValue, DWORD dwRolCount)
1969 {
1970 DWORD dwShiftRight = 32 - dwRolCount;
1971
1972 return (dwValue << dwRolCount) | (dwValue >> dwShiftRight);
1973 }
1974
CreateKeyFromAuthCode(LPBYTE pbKeyBuffer,const char * szAuthCode)1975 static void CreateKeyFromAuthCode(
1976 LPBYTE pbKeyBuffer,
1977 const char * szAuthCode)
1978 {
1979 LPDWORD KeyPosition = (LPDWORD)(pbKeyBuffer + 0x10);
1980 LPDWORD AuthCode32 = (LPDWORD)szAuthCode;
1981
1982 memcpy(pbKeyBuffer, szKeyTemplate, MPQE_CHUNK_SIZE);
1983 KeyPosition[0x00] = AuthCode32[0x03];
1984 KeyPosition[0x02] = AuthCode32[0x07];
1985 KeyPosition[0x03] = AuthCode32[0x02];
1986 KeyPosition[0x05] = AuthCode32[0x06];
1987 KeyPosition[0x06] = AuthCode32[0x01];
1988 KeyPosition[0x08] = AuthCode32[0x05];
1989 KeyPosition[0x09] = AuthCode32[0x00];
1990 KeyPosition[0x0B] = AuthCode32[0x04];
1991 BSWAP_ARRAY32_UNSIGNED(pbKeyBuffer, MPQE_CHUNK_SIZE);
1992 }
1993
DecryptFileChunk(DWORD * MpqData,LPBYTE pbKey,ULONGLONG ByteOffset,DWORD dwLength)1994 static void DecryptFileChunk(
1995 DWORD * MpqData,
1996 LPBYTE pbKey,
1997 ULONGLONG ByteOffset,
1998 DWORD dwLength)
1999 {
2000 ULONGLONG ChunkOffset;
2001 DWORD KeyShuffled[0x10];
2002 DWORD KeyMirror[0x10];
2003 DWORD RoundCount = 0x14;
2004
2005 // Prepare the key
2006 ChunkOffset = ByteOffset / MPQE_CHUNK_SIZE;
2007 memcpy(KeyMirror, pbKey, MPQE_CHUNK_SIZE);
2008 BSWAP_ARRAY32_UNSIGNED(KeyMirror, MPQE_CHUNK_SIZE);
2009 KeyMirror[0x05] = (DWORD)(ChunkOffset >> 32);
2010 KeyMirror[0x08] = (DWORD)(ChunkOffset);
2011
2012 while(dwLength >= MPQE_CHUNK_SIZE)
2013 {
2014 // Shuffle the key - part 1
2015 KeyShuffled[0x0E] = KeyMirror[0x00];
2016 KeyShuffled[0x0C] = KeyMirror[0x01];
2017 KeyShuffled[0x05] = KeyMirror[0x02];
2018 KeyShuffled[0x0F] = KeyMirror[0x03];
2019 KeyShuffled[0x0A] = KeyMirror[0x04];
2020 KeyShuffled[0x07] = KeyMirror[0x05];
2021 KeyShuffled[0x0B] = KeyMirror[0x06];
2022 KeyShuffled[0x09] = KeyMirror[0x07];
2023 KeyShuffled[0x03] = KeyMirror[0x08];
2024 KeyShuffled[0x06] = KeyMirror[0x09];
2025 KeyShuffled[0x08] = KeyMirror[0x0A];
2026 KeyShuffled[0x0D] = KeyMirror[0x0B];
2027 KeyShuffled[0x02] = KeyMirror[0x0C];
2028 KeyShuffled[0x04] = KeyMirror[0x0D];
2029 KeyShuffled[0x01] = KeyMirror[0x0E];
2030 KeyShuffled[0x00] = KeyMirror[0x0F];
2031
2032 // Shuffle the key - part 2
2033 for(DWORD i = 0; i < RoundCount; i += 2)
2034 {
2035 KeyShuffled[0x0A] = KeyShuffled[0x0A] ^ Rol32((KeyShuffled[0x0E] + KeyShuffled[0x02]), 0x07);
2036 KeyShuffled[0x03] = KeyShuffled[0x03] ^ Rol32((KeyShuffled[0x0A] + KeyShuffled[0x0E]), 0x09);
2037 KeyShuffled[0x02] = KeyShuffled[0x02] ^ Rol32((KeyShuffled[0x03] + KeyShuffled[0x0A]), 0x0D);
2038 KeyShuffled[0x0E] = KeyShuffled[0x0E] ^ Rol32((KeyShuffled[0x02] + KeyShuffled[0x03]), 0x12);
2039
2040 KeyShuffled[0x07] = KeyShuffled[0x07] ^ Rol32((KeyShuffled[0x0C] + KeyShuffled[0x04]), 0x07);
2041 KeyShuffled[0x06] = KeyShuffled[0x06] ^ Rol32((KeyShuffled[0x07] + KeyShuffled[0x0C]), 0x09);
2042 KeyShuffled[0x04] = KeyShuffled[0x04] ^ Rol32((KeyShuffled[0x06] + KeyShuffled[0x07]), 0x0D);
2043 KeyShuffled[0x0C] = KeyShuffled[0x0C] ^ Rol32((KeyShuffled[0x04] + KeyShuffled[0x06]), 0x12);
2044
2045 KeyShuffled[0x0B] = KeyShuffled[0x0B] ^ Rol32((KeyShuffled[0x05] + KeyShuffled[0x01]), 0x07);
2046 KeyShuffled[0x08] = KeyShuffled[0x08] ^ Rol32((KeyShuffled[0x0B] + KeyShuffled[0x05]), 0x09);
2047 KeyShuffled[0x01] = KeyShuffled[0x01] ^ Rol32((KeyShuffled[0x08] + KeyShuffled[0x0B]), 0x0D);
2048 KeyShuffled[0x05] = KeyShuffled[0x05] ^ Rol32((KeyShuffled[0x01] + KeyShuffled[0x08]), 0x12);
2049
2050 KeyShuffled[0x09] = KeyShuffled[0x09] ^ Rol32((KeyShuffled[0x0F] + KeyShuffled[0x00]), 0x07);
2051 KeyShuffled[0x0D] = KeyShuffled[0x0D] ^ Rol32((KeyShuffled[0x09] + KeyShuffled[0x0F]), 0x09);
2052 KeyShuffled[0x00] = KeyShuffled[0x00] ^ Rol32((KeyShuffled[0x0D] + KeyShuffled[0x09]), 0x0D);
2053 KeyShuffled[0x0F] = KeyShuffled[0x0F] ^ Rol32((KeyShuffled[0x00] + KeyShuffled[0x0D]), 0x12);
2054
2055 KeyShuffled[0x04] = KeyShuffled[0x04] ^ Rol32((KeyShuffled[0x0E] + KeyShuffled[0x09]), 0x07);
2056 KeyShuffled[0x08] = KeyShuffled[0x08] ^ Rol32((KeyShuffled[0x04] + KeyShuffled[0x0E]), 0x09);
2057 KeyShuffled[0x09] = KeyShuffled[0x09] ^ Rol32((KeyShuffled[0x08] + KeyShuffled[0x04]), 0x0D);
2058 KeyShuffled[0x0E] = KeyShuffled[0x0E] ^ Rol32((KeyShuffled[0x09] + KeyShuffled[0x08]), 0x12);
2059
2060 KeyShuffled[0x01] = KeyShuffled[0x01] ^ Rol32((KeyShuffled[0x0C] + KeyShuffled[0x0A]), 0x07);
2061 KeyShuffled[0x0D] = KeyShuffled[0x0D] ^ Rol32((KeyShuffled[0x01] + KeyShuffled[0x0C]), 0x09);
2062 KeyShuffled[0x0A] = KeyShuffled[0x0A] ^ Rol32((KeyShuffled[0x0D] + KeyShuffled[0x01]), 0x0D);
2063 KeyShuffled[0x0C] = KeyShuffled[0x0C] ^ Rol32((KeyShuffled[0x0A] + KeyShuffled[0x0D]), 0x12);
2064
2065 KeyShuffled[0x00] = KeyShuffled[0x00] ^ Rol32((KeyShuffled[0x05] + KeyShuffled[0x07]), 0x07);
2066 KeyShuffled[0x03] = KeyShuffled[0x03] ^ Rol32((KeyShuffled[0x00] + KeyShuffled[0x05]), 0x09);
2067 KeyShuffled[0x07] = KeyShuffled[0x07] ^ Rol32((KeyShuffled[0x03] + KeyShuffled[0x00]), 0x0D);
2068 KeyShuffled[0x05] = KeyShuffled[0x05] ^ Rol32((KeyShuffled[0x07] + KeyShuffled[0x03]), 0x12);
2069
2070 KeyShuffled[0x02] = KeyShuffled[0x02] ^ Rol32((KeyShuffled[0x0F] + KeyShuffled[0x0B]), 0x07);
2071 KeyShuffled[0x06] = KeyShuffled[0x06] ^ Rol32((KeyShuffled[0x02] + KeyShuffled[0x0F]), 0x09);
2072 KeyShuffled[0x0B] = KeyShuffled[0x0B] ^ Rol32((KeyShuffled[0x06] + KeyShuffled[0x02]), 0x0D);
2073 KeyShuffled[0x0F] = KeyShuffled[0x0F] ^ Rol32((KeyShuffled[0x0B] + KeyShuffled[0x06]), 0x12);
2074 }
2075
2076 // Decrypt one data chunk
2077 BSWAP_ARRAY32_UNSIGNED(MpqData, MPQE_CHUNK_SIZE);
2078 MpqData[0x00] = MpqData[0x00] ^ (KeyShuffled[0x0E] + KeyMirror[0x00]);
2079 MpqData[0x01] = MpqData[0x01] ^ (KeyShuffled[0x04] + KeyMirror[0x0D]);
2080 MpqData[0x02] = MpqData[0x02] ^ (KeyShuffled[0x08] + KeyMirror[0x0A]);
2081 MpqData[0x03] = MpqData[0x03] ^ (KeyShuffled[0x09] + KeyMirror[0x07]);
2082 MpqData[0x04] = MpqData[0x04] ^ (KeyShuffled[0x0A] + KeyMirror[0x04]);
2083 MpqData[0x05] = MpqData[0x05] ^ (KeyShuffled[0x0C] + KeyMirror[0x01]);
2084 MpqData[0x06] = MpqData[0x06] ^ (KeyShuffled[0x01] + KeyMirror[0x0E]);
2085 MpqData[0x07] = MpqData[0x07] ^ (KeyShuffled[0x0D] + KeyMirror[0x0B]);
2086 MpqData[0x08] = MpqData[0x08] ^ (KeyShuffled[0x03] + KeyMirror[0x08]);
2087 MpqData[0x09] = MpqData[0x09] ^ (KeyShuffled[0x07] + KeyMirror[0x05]);
2088 MpqData[0x0A] = MpqData[0x0A] ^ (KeyShuffled[0x05] + KeyMirror[0x02]);
2089 MpqData[0x0B] = MpqData[0x0B] ^ (KeyShuffled[0x00] + KeyMirror[0x0F]);
2090 MpqData[0x0C] = MpqData[0x0C] ^ (KeyShuffled[0x02] + KeyMirror[0x0C]);
2091 MpqData[0x0D] = MpqData[0x0D] ^ (KeyShuffled[0x06] + KeyMirror[0x09]);
2092 MpqData[0x0E] = MpqData[0x0E] ^ (KeyShuffled[0x0B] + KeyMirror[0x06]);
2093 MpqData[0x0F] = MpqData[0x0F] ^ (KeyShuffled[0x0F] + KeyMirror[0x03]);
2094 BSWAP_ARRAY32_UNSIGNED(MpqData, MPQE_CHUNK_SIZE);
2095
2096 // Update byte offset in the key
2097 KeyMirror[0x08]++;
2098 if(KeyMirror[0x08] == 0)
2099 KeyMirror[0x05]++;
2100
2101 // Move pointers and decrease number of bytes to decrypt
2102 MpqData += (MPQE_CHUNK_SIZE / sizeof(DWORD));
2103 dwLength -= MPQE_CHUNK_SIZE;
2104 }
2105 }
2106
MpqeStream_DetectFileKey(TEncryptedStream * pStream)2107 static bool MpqeStream_DetectFileKey(TEncryptedStream * pStream)
2108 {
2109 ULONGLONG ByteOffset = 0;
2110 BYTE EncryptedHeader[MPQE_CHUNK_SIZE];
2111 BYTE FileHeader[MPQE_CHUNK_SIZE];
2112
2113 // Read the first file chunk
2114 if(pStream->BaseRead(pStream, &ByteOffset, EncryptedHeader, sizeof(EncryptedHeader)))
2115 {
2116 // We just try all known keys one by one
2117 for(int i = 0; AuthCodeArray[i] != NULL; i++)
2118 {
2119 // Prepare they decryption key from game serial number
2120 CreateKeyFromAuthCode(pStream->Key, AuthCodeArray[i]);
2121
2122 // Try to decrypt with the given key
2123 memcpy(FileHeader, EncryptedHeader, MPQE_CHUNK_SIZE);
2124 DecryptFileChunk((LPDWORD)FileHeader, pStream->Key, ByteOffset, MPQE_CHUNK_SIZE);
2125
2126 // We check the decrypted data
2127 // All known encrypted MPQs have header at the begin of the file,
2128 // so we check for MPQ signature there.
2129 if(FileHeader[0] == 'M' && FileHeader[1] == 'P' && FileHeader[2] == 'Q')
2130 {
2131 // Update the stream size
2132 pStream->StreamSize = pStream->Base.File.FileSize;
2133
2134 // Fill the block information
2135 pStream->BlockSize = MPQE_CHUNK_SIZE;
2136 pStream->BlockCount = (DWORD)(pStream->Base.File.FileSize + MPQE_CHUNK_SIZE - 1) / MPQE_CHUNK_SIZE;
2137 pStream->IsComplete = 1;
2138 return true;
2139 }
2140 }
2141 }
2142
2143 // Key not found, sorry
2144 return false;
2145 }
2146
MpqeStream_BlockRead(TEncryptedStream * pStream,ULONGLONG StartOffset,ULONGLONG EndOffset,LPBYTE BlockBuffer,DWORD BytesNeeded,bool bAvailable)2147 static bool MpqeStream_BlockRead(
2148 TEncryptedStream * pStream,
2149 ULONGLONG StartOffset,
2150 ULONGLONG EndOffset,
2151 LPBYTE BlockBuffer,
2152 DWORD BytesNeeded,
2153 bool bAvailable)
2154 {
2155 DWORD dwBytesToRead;
2156
2157 assert((StartOffset & (pStream->BlockSize - 1)) == 0);
2158 assert(StartOffset < EndOffset);
2159 assert(bAvailable != false);
2160 BytesNeeded = BytesNeeded;
2161 bAvailable = bAvailable;
2162
2163 // Read the file from the stream as-is
2164 // Limit the reading to number of blocks really needed
2165 dwBytesToRead = (DWORD)(EndOffset - StartOffset);
2166 if(!pStream->BaseRead(pStream, &StartOffset, BlockBuffer, dwBytesToRead))
2167 return false;
2168
2169 // Decrypt the data
2170 dwBytesToRead = (dwBytesToRead + MPQE_CHUNK_SIZE - 1) & ~(MPQE_CHUNK_SIZE - 1);
2171 DecryptFileChunk((LPDWORD)BlockBuffer, pStream->Key, StartOffset, dwBytesToRead);
2172 return true;
2173 }
2174
MpqeStream_Open(const TCHAR * szFileName,DWORD dwStreamFlags)2175 static TFileStream * MpqeStream_Open(const TCHAR * szFileName, DWORD dwStreamFlags)
2176 {
2177 TEncryptedStream * pStream;
2178
2179 // Create new empty stream
2180 pStream = (TEncryptedStream *)AllocateFileStream(szFileName, sizeof(TEncryptedStream), dwStreamFlags);
2181 if(pStream == NULL)
2182 return NULL;
2183
2184 // Attempt to open the base stream
2185 assert(pStream->BaseOpen != NULL);
2186 if(!pStream->BaseOpen(pStream, pStream->szFileName, dwStreamFlags))
2187 return NULL;
2188
2189 // Determine the encryption key for the MPQ
2190 if(MpqeStream_DetectFileKey(pStream))
2191 {
2192 // Set the stream position and size
2193 assert(pStream->StreamSize != 0);
2194 pStream->StreamPos = 0;
2195 pStream->dwFlags |= STREAM_FLAG_READ_ONLY;
2196
2197 // Set new function pointers
2198 pStream->StreamRead = (STREAM_READ)BlockStream_Read;
2199 pStream->StreamGetPos = BlockStream_GetPos;
2200 pStream->StreamGetSize = BlockStream_GetSize;
2201 pStream->StreamClose = pStream->BaseClose;
2202
2203 // Supply the block functions
2204 pStream->BlockRead = (BLOCK_READ)MpqeStream_BlockRead;
2205 return pStream;
2206 }
2207
2208 // Cleanup the stream and return
2209 FileStream_Close(pStream);
2210 SetLastError(ERROR_UNKNOWN_FILE_KEY);
2211 return NULL;
2212 }
2213
2214 //-----------------------------------------------------------------------------
2215 // Local functions - Block4 stream support
2216
2217 #define BLOCK4_BLOCK_SIZE 0x4000 // Size of one block
2218 #define BLOCK4_HASH_SIZE 0x20 // Size of MD5 hash that is after each block
2219 #define BLOCK4_MAX_BLOCKS 0x00002000 // Maximum amount of blocks per file
2220 #define BLOCK4_MAX_FSIZE 0x08040000 // Max size of one file
2221
Block4Stream_BlockRead(TBlockStream * pStream,ULONGLONG StartOffset,ULONGLONG EndOffset,LPBYTE BlockBuffer,DWORD BytesNeeded,bool bAvailable)2222 static bool Block4Stream_BlockRead(
2223 TBlockStream * pStream, // Pointer to an open stream
2224 ULONGLONG StartOffset,
2225 ULONGLONG EndOffset,
2226 LPBYTE BlockBuffer,
2227 DWORD BytesNeeded,
2228 bool bAvailable)
2229 {
2230 TBaseProviderData * BaseArray = (TBaseProviderData *)pStream->FileBitmap;
2231 ULONGLONG ByteOffset;
2232 DWORD BytesToRead;
2233 DWORD StreamIndex;
2234 DWORD BlockIndex;
2235 bool bResult;
2236
2237 // The starting offset must be aligned to size of the block
2238 assert(pStream->FileBitmap != NULL);
2239 assert((StartOffset & (pStream->BlockSize - 1)) == 0);
2240 assert(StartOffset < EndOffset);
2241 assert(bAvailable == true);
2242
2243 // Keep compiler happy
2244 bAvailable = bAvailable;
2245 EndOffset = EndOffset;
2246
2247 while(BytesNeeded != 0)
2248 {
2249 // Calculate the block index and the file index
2250 StreamIndex = (DWORD)((StartOffset / pStream->BlockSize) / BLOCK4_MAX_BLOCKS);
2251 BlockIndex = (DWORD)((StartOffset / pStream->BlockSize) % BLOCK4_MAX_BLOCKS);
2252 if(StreamIndex > pStream->BitmapSize)
2253 return false;
2254
2255 // Calculate the block offset
2256 ByteOffset = ((ULONGLONG)BlockIndex * (BLOCK4_BLOCK_SIZE + BLOCK4_HASH_SIZE));
2257 BytesToRead = STORMLIB_MIN(BytesNeeded, BLOCK4_BLOCK_SIZE);
2258
2259 // Read from the base stream
2260 pStream->Base = BaseArray[StreamIndex];
2261 bResult = pStream->BaseRead(pStream, &ByteOffset, BlockBuffer, BytesToRead);
2262 BaseArray[StreamIndex] = pStream->Base;
2263
2264 // Did the result succeed?
2265 if(bResult == false)
2266 return false;
2267
2268 // Move pointers
2269 StartOffset += BytesToRead;
2270 BlockBuffer += BytesToRead;
2271 BytesNeeded -= BytesToRead;
2272 }
2273
2274 return true;
2275 }
2276
2277
Block4Stream_Close(TBlockStream * pStream)2278 static void Block4Stream_Close(TBlockStream * pStream)
2279 {
2280 TBaseProviderData * BaseArray = (TBaseProviderData *)pStream->FileBitmap;
2281
2282 // If we have a non-zero count of base streams,
2283 // we have to close them all
2284 if(BaseArray != NULL)
2285 {
2286 // Close all base streams
2287 for(DWORD i = 0; i < pStream->BitmapSize; i++)
2288 {
2289 memcpy(&pStream->Base, BaseArray + i, sizeof(TBaseProviderData));
2290 pStream->BaseClose(pStream);
2291 }
2292 }
2293
2294 // Free the data map, if any
2295 if(pStream->FileBitmap != NULL)
2296 STORM_FREE(pStream->FileBitmap);
2297 pStream->FileBitmap = NULL;
2298
2299 // Do not call the BaseClose function,
2300 // we closed all handles already
2301 return;
2302 }
2303
Block4Stream_Open(const TCHAR * szFileName,DWORD dwStreamFlags)2304 static TFileStream * Block4Stream_Open(const TCHAR * szFileName, DWORD dwStreamFlags)
2305 {
2306 TBaseProviderData * NewBaseArray = NULL;
2307 ULONGLONG RemainderBlock;
2308 ULONGLONG BlockCount;
2309 ULONGLONG FileSize;
2310 TBlockStream * pStream;
2311 TCHAR * szNameBuff;
2312 size_t nNameLength;
2313 DWORD dwBaseFiles = 0;
2314 DWORD dwBaseFlags;
2315
2316 // Create new empty stream
2317 pStream = (TBlockStream *)AllocateFileStream(szFileName, sizeof(TBlockStream), dwStreamFlags);
2318 if(pStream == NULL)
2319 return NULL;
2320
2321 // Sanity check
2322 assert(pStream->BaseOpen != NULL);
2323
2324 // Get the length of the file name without numeric suffix
2325 nNameLength = _tcslen(pStream->szFileName);
2326 if(pStream->szFileName[nNameLength - 2] == '.' && pStream->szFileName[nNameLength - 1] == '0')
2327 nNameLength -= 2;
2328 pStream->szFileName[nNameLength] = 0;
2329
2330 // Supply the stream functions
2331 pStream->StreamRead = (STREAM_READ)BlockStream_Read;
2332 pStream->StreamGetSize = BlockStream_GetSize;
2333 pStream->StreamGetPos = BlockStream_GetPos;
2334 pStream->StreamClose = (STREAM_CLOSE)Block4Stream_Close;
2335 pStream->BlockRead = (BLOCK_READ)Block4Stream_BlockRead;
2336
2337 // Allocate work space for numeric names
2338 szNameBuff = STORM_ALLOC(TCHAR, nNameLength + 4);
2339 if(szNameBuff != NULL)
2340 {
2341 // Set the base flags
2342 dwBaseFlags = (dwStreamFlags & STREAM_PROVIDERS_MASK) | STREAM_FLAG_READ_ONLY;
2343
2344 // Go all suffixes from 0 to 30
2345 for(int nSuffix = 0; nSuffix < 30; nSuffix++)
2346 {
2347 // Open the n-th file
2348 CreateNameWithSuffix(szNameBuff, nNameLength + 4, pStream->szFileName, nSuffix);
2349 if(!pStream->BaseOpen(pStream, szNameBuff, dwBaseFlags))
2350 break;
2351
2352 // If the open succeeded, we re-allocate the base provider array
2353 NewBaseArray = STORM_ALLOC(TBaseProviderData, dwBaseFiles + 1);
2354 if(NewBaseArray == NULL)
2355 {
2356 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2357 return NULL;
2358 }
2359
2360 // Copy the old base data array to the new base data array
2361 if(pStream->FileBitmap != NULL)
2362 {
2363 memcpy(NewBaseArray, pStream->FileBitmap, sizeof(TBaseProviderData) * dwBaseFiles);
2364 STORM_FREE(pStream->FileBitmap);
2365 }
2366
2367 // Also copy the opened base array
2368 memcpy(NewBaseArray + dwBaseFiles, &pStream->Base, sizeof(TBaseProviderData));
2369 pStream->FileBitmap = NewBaseArray;
2370 dwBaseFiles++;
2371
2372 // Get the size of the base stream
2373 pStream->BaseGetSize(pStream, &FileSize);
2374 assert(FileSize <= BLOCK4_MAX_FSIZE);
2375 RemainderBlock = FileSize % (BLOCK4_BLOCK_SIZE + BLOCK4_HASH_SIZE);
2376 BlockCount = FileSize / (BLOCK4_BLOCK_SIZE + BLOCK4_HASH_SIZE);
2377
2378 // Increment the stream size and number of blocks
2379 pStream->StreamSize += (BlockCount * BLOCK4_BLOCK_SIZE);
2380 pStream->BlockCount += (DWORD)BlockCount;
2381
2382 // Is this the last file?
2383 if(FileSize < BLOCK4_MAX_FSIZE)
2384 {
2385 if(RemainderBlock)
2386 {
2387 pStream->StreamSize += (RemainderBlock - BLOCK4_HASH_SIZE);
2388 pStream->BlockCount++;
2389 }
2390 break;
2391 }
2392 }
2393
2394 // Fill the remainining block stream variables
2395 pStream->BitmapSize = dwBaseFiles;
2396 pStream->BlockSize = BLOCK4_BLOCK_SIZE;
2397 pStream->IsComplete = 1;
2398 pStream->IsModified = 0;
2399
2400 // Fill the remaining stream variables
2401 pStream->StreamPos = 0;
2402 pStream->dwFlags |= STREAM_FLAG_READ_ONLY;
2403
2404 STORM_FREE(szNameBuff);
2405 }
2406
2407 // If we opened something, return success
2408 if(dwBaseFiles == 0)
2409 {
2410 FileStream_Close(pStream);
2411 SetLastError(ERROR_FILE_NOT_FOUND);
2412 pStream = NULL;
2413 }
2414
2415 return pStream;
2416 }
2417
2418 //-----------------------------------------------------------------------------
2419 // Public functions
2420
2421 /**
2422 * This function creates a new file for read-write access
2423 *
2424 * - If the current platform supports file sharing,
2425 * the file must be created for read sharing (i.e. another application
2426 * can open the file for read, but not for write)
2427 * - If the file does not exist, the function must create new one
2428 * - If the file exists, the function must rewrite it and set to zero size
2429 * - The parameters of the function must be validate by the caller
2430 * - The function must initialize all stream function pointers in TFileStream
2431 * - If the function fails from any reason, it must close all handles
2432 * and free all memory that has been allocated in the process of stream creation,
2433 * including the TFileStream structure itself
2434 *
2435 * \a szFileName Name of the file to create
2436 */
2437
FileStream_CreateFile(const TCHAR * szFileName,DWORD dwStreamFlags)2438 TFileStream * FileStream_CreateFile(
2439 const TCHAR * szFileName,
2440 DWORD dwStreamFlags)
2441 {
2442 TFileStream * pStream;
2443
2444 // We only support creation of flat, local file
2445 if((dwStreamFlags & (STREAM_PROVIDERS_MASK)) != (STREAM_PROVIDER_FLAT | BASE_PROVIDER_FILE))
2446 {
2447 SetLastError(ERROR_NOT_SUPPORTED);
2448 return NULL;
2449 }
2450
2451 // Allocate file stream structure for flat stream
2452 pStream = AllocateFileStream(szFileName, sizeof(TBlockStream), dwStreamFlags);
2453 if(pStream != NULL)
2454 {
2455 // Attempt to create the disk file
2456 if(BaseFile_Create(pStream))
2457 {
2458 // Fill the stream provider functions
2459 pStream->StreamRead = pStream->BaseRead;
2460 pStream->StreamWrite = pStream->BaseWrite;
2461 pStream->StreamResize = pStream->BaseResize;
2462 pStream->StreamGetSize = pStream->BaseGetSize;
2463 pStream->StreamGetPos = pStream->BaseGetPos;
2464 pStream->StreamClose = pStream->BaseClose;
2465 return pStream;
2466 }
2467
2468 // File create failed, delete the stream
2469 STORM_FREE(pStream);
2470 pStream = NULL;
2471 }
2472
2473 // Return the stream
2474 return pStream;
2475 }
2476
2477 /**
2478 * This function opens an existing file for read or read-write access
2479 * - If the current platform supports file sharing,
2480 * the file must be open for read sharing (i.e. another application
2481 * can open the file for read, but not for write)
2482 * - If the file does not exist, the function must return NULL
2483 * - If the file exists but cannot be open, then function must return NULL
2484 * - The parameters of the function must be validate by the caller
2485 * - The function must initialize all stream function pointers in TFileStream
2486 * - If the function fails from any reason, it must close all handles
2487 * and free all memory that has been allocated in the process of stream creation,
2488 * including the TFileStream structure itself
2489 *
2490 * \a szFileName Name of the file to open
2491 * \a dwStreamFlags specifies the provider and base storage type
2492 */
2493
FileStream_OpenFile(const TCHAR * szFileName,DWORD dwStreamFlags)2494 TFileStream * FileStream_OpenFile(
2495 const TCHAR * szFileName,
2496 DWORD dwStreamFlags)
2497 {
2498 DWORD dwProvider = dwStreamFlags & STREAM_PROVIDERS_MASK;
2499 size_t nPrefixLength = FileStream_Prefix(szFileName, &dwProvider);
2500
2501 // Re-assemble the stream flags
2502 dwStreamFlags = (dwStreamFlags & STREAM_OPTIONS_MASK) | dwProvider;
2503 szFileName += nPrefixLength;
2504
2505 // Perform provider-specific open
2506 switch(dwStreamFlags & STREAM_PROVIDER_MASK)
2507 {
2508 case STREAM_PROVIDER_FLAT:
2509 return FlatStream_Open(szFileName, dwStreamFlags);
2510
2511 case STREAM_PROVIDER_PARTIAL:
2512 return PartStream_Open(szFileName, dwStreamFlags);
2513
2514 case STREAM_PROVIDER_MPQE:
2515 return MpqeStream_Open(szFileName, dwStreamFlags);
2516
2517 case STREAM_PROVIDER_BLOCK4:
2518 return Block4Stream_Open(szFileName, dwStreamFlags);
2519
2520 default:
2521 SetLastError(ERROR_INVALID_PARAMETER);
2522 return NULL;
2523 }
2524 }
2525
2526 /**
2527 * Returns the file name of the stream
2528 *
2529 * \a pStream Pointer to an open stream
2530 */
FileStream_GetFileName(TFileStream * pStream)2531 const TCHAR * FileStream_GetFileName(TFileStream * pStream)
2532 {
2533 assert(pStream != NULL);
2534 return pStream->szFileName;
2535 }
2536
2537 /**
2538 * Returns the length of the provider prefix. Returns zero if no prefix
2539 *
2540 * \a szFileName Pointer to a stream name (file, mapped file, URL)
2541 * \a pdwStreamProvider Pointer to a DWORD variable that receives stream provider (STREAM_PROVIDER_XXX)
2542 */
2543
FileStream_Prefix(const TCHAR * szFileName,DWORD * pdwProvider)2544 size_t FileStream_Prefix(const TCHAR * szFileName, DWORD * pdwProvider)
2545 {
2546 size_t nPrefixLength1 = 0;
2547 size_t nPrefixLength2 = 0;
2548 DWORD dwProvider = 0;
2549
2550 if(szFileName != NULL)
2551 {
2552 //
2553 // Determine the stream provider
2554 //
2555
2556 if(!_tcsnicmp(szFileName, _T("flat-"), 5))
2557 {
2558 dwProvider |= STREAM_PROVIDER_FLAT;
2559 nPrefixLength1 = 5;
2560 }
2561
2562 else if(!_tcsnicmp(szFileName, _T("part-"), 5))
2563 {
2564 dwProvider |= STREAM_PROVIDER_PARTIAL;
2565 nPrefixLength1 = 5;
2566 }
2567
2568 else if(!_tcsnicmp(szFileName, _T("mpqe-"), 5))
2569 {
2570 dwProvider |= STREAM_PROVIDER_MPQE;
2571 nPrefixLength1 = 5;
2572 }
2573
2574 else if(!_tcsnicmp(szFileName, _T("blk4-"), 5))
2575 {
2576 dwProvider |= STREAM_PROVIDER_BLOCK4;
2577 nPrefixLength1 = 5;
2578 }
2579
2580 //
2581 // Determine the base provider
2582 //
2583
2584 if(!_tcsnicmp(szFileName+nPrefixLength1, _T("file:"), 5))
2585 {
2586 dwProvider |= BASE_PROVIDER_FILE;
2587 nPrefixLength2 = 5;
2588 }
2589
2590 else if(!_tcsnicmp(szFileName+nPrefixLength1, _T("map:"), 4))
2591 {
2592 dwProvider |= BASE_PROVIDER_MAP;
2593 nPrefixLength2 = 4;
2594 }
2595
2596 else if(!_tcsnicmp(szFileName+nPrefixLength1, _T("http:"), 5))
2597 {
2598 dwProvider |= BASE_PROVIDER_HTTP;
2599 nPrefixLength2 = 5;
2600 }
2601
2602 // Only accept stream provider if we recognized the base provider
2603 if(nPrefixLength2 != 0)
2604 {
2605 // It is also allowed to put "//" after the base provider, e.g. "file://", "http://"
2606 if(szFileName[nPrefixLength1+nPrefixLength2] == '/' && szFileName[nPrefixLength1+nPrefixLength2+1] == '/')
2607 nPrefixLength2 += 2;
2608
2609 if(pdwProvider != NULL)
2610 *pdwProvider = dwProvider;
2611 return nPrefixLength1 + nPrefixLength2;
2612 }
2613 }
2614
2615 return 0;
2616 }
2617
2618 /**
2619 * Sets a download callback. Whenever the stream needs to download one or more blocks
2620 * from the server, the callback is called
2621 *
2622 * \a pStream Pointer to an open stream
2623 * \a pfnCallback Pointer to callback function
2624 * \a pvUserData Arbitrary user pointer passed to the download callback
2625 */
2626
FileStream_SetCallback(TFileStream * pStream,SFILE_DOWNLOAD_CALLBACK pfnCallback,void * pvUserData)2627 bool FileStream_SetCallback(TFileStream * pStream, SFILE_DOWNLOAD_CALLBACK pfnCallback, void * pvUserData)
2628 {
2629 TBlockStream * pBlockStream = (TBlockStream *)pStream;
2630
2631 if(pStream->BlockRead == NULL)
2632 {
2633 SetLastError(ERROR_NOT_SUPPORTED);
2634 return false;
2635 }
2636
2637 pBlockStream->pfnCallback = pfnCallback;
2638 pBlockStream->UserData = pvUserData;
2639 return true;
2640 }
2641
2642 /**
2643 * This function gives the block map. The 'pvBitmap' pointer must point to a buffer
2644 * of at least sizeof(STREAM_BLOCK_MAP) size. It can also have size of the complete
2645 * block map (i.e. sizeof(STREAM_BLOCK_MAP) + BitmapSize). In that case, the function
2646 * also copies the bit-based block map.
2647 *
2648 * \a pStream Pointer to an open stream
2649 * \a pvBitmap Pointer to buffer where the block map will be stored
2650 * \a cbBitmap Length of the buffer, of the block map
2651 * \a cbLengthNeeded Length of the bitmap, in bytes
2652 */
2653
FileStream_GetBitmap(TFileStream * pStream,void * pvBitmap,DWORD cbBitmap,DWORD * pcbLengthNeeded)2654 bool FileStream_GetBitmap(TFileStream * pStream, void * pvBitmap, DWORD cbBitmap, DWORD * pcbLengthNeeded)
2655 {
2656 TStreamBitmap * pBitmap = (TStreamBitmap *)pvBitmap;
2657 TBlockStream * pBlockStream = (TBlockStream *)pStream;
2658 ULONGLONG BlockOffset;
2659 LPBYTE Bitmap = (LPBYTE)(pBitmap + 1);
2660 DWORD BitmapSize;
2661 DWORD BlockCount;
2662 DWORD BlockSize;
2663 bool bResult = false;
2664
2665 // Retrieve the size of one block
2666 if(pStream->BlockCheck != NULL)
2667 {
2668 BlockCount = pBlockStream->BlockCount;
2669 BlockSize = pBlockStream->BlockSize;
2670 }
2671 else
2672 {
2673 BlockCount = (DWORD)((pStream->StreamSize + DEFAULT_BLOCK_SIZE - 1) / DEFAULT_BLOCK_SIZE);
2674 BlockSize = DEFAULT_BLOCK_SIZE;
2675 }
2676
2677 // Fill-in the variables
2678 BitmapSize = (BlockCount + 7) / 8;
2679
2680 // Give the number of blocks
2681 if(pcbLengthNeeded != NULL)
2682 pcbLengthNeeded[0] = sizeof(TStreamBitmap) + BitmapSize;
2683
2684 // If the length of the buffer is not enough
2685 if(pvBitmap != NULL && cbBitmap != 0)
2686 {
2687 // Give the STREAM_BLOCK_MAP structure
2688 if(cbBitmap >= sizeof(TStreamBitmap))
2689 {
2690 pBitmap->StreamSize = pStream->StreamSize;
2691 pBitmap->BitmapSize = BitmapSize;
2692 pBitmap->BlockCount = BlockCount;
2693 pBitmap->BlockSize = BlockSize;
2694 pBitmap->IsComplete = (pStream->BlockCheck != NULL) ? pBlockStream->IsComplete : 1;
2695 bResult = true;
2696 }
2697
2698 // Give the block bitmap, if enough space
2699 if(cbBitmap >= sizeof(TStreamBitmap) + BitmapSize)
2700 {
2701 // Version with bitmap present
2702 if(pStream->BlockCheck != NULL)
2703 {
2704 DWORD ByteIndex = 0;
2705 BYTE BitMask = 0x01;
2706
2707 // Initialize the map with zeros
2708 memset(Bitmap, 0, BitmapSize);
2709
2710 // Fill the map
2711 for(BlockOffset = 0; BlockOffset < pStream->StreamSize; BlockOffset += BlockSize)
2712 {
2713 // Set the bit if the block is present
2714 if(pBlockStream->BlockCheck(pStream, BlockOffset))
2715 Bitmap[ByteIndex] |= BitMask;
2716
2717 // Move bit position
2718 ByteIndex += (BitMask >> 0x07);
2719 BitMask = (BitMask >> 0x07) | (BitMask << 0x01);
2720 }
2721 }
2722 else
2723 {
2724 memset(Bitmap, 0xFF, BitmapSize);
2725 }
2726 }
2727 }
2728
2729 // Set last error value and return
2730 if(bResult == false)
2731 SetLastError(ERROR_INSUFFICIENT_BUFFER);
2732 return bResult;
2733 }
2734
2735 /**
2736 * Reads data from the stream
2737 *
2738 * - Returns true if the read operation succeeded and all bytes have been read
2739 * - Returns false if either read failed or not all bytes have been read
2740 * - If the pByteOffset is NULL, the function must read the data from the current file position
2741 * - The function can be called with dwBytesToRead = 0. In that case, pvBuffer is ignored
2742 * and the function just adjusts file pointer.
2743 *
2744 * \a pStream Pointer to an open stream
2745 * \a pByteOffset Pointer to file byte offset. If NULL, it reads from the current position
2746 * \a pvBuffer Pointer to data to be read
2747 * \a dwBytesToRead Number of bytes to read from the file
2748 *
2749 * \returns
2750 * - If the function reads the required amount of bytes, it returns true.
2751 * - If the function reads less than required bytes, it returns false and GetLastError() returns ERROR_HANDLE_EOF
2752 * - If the function fails, it reads false and GetLastError() returns an error code different from ERROR_HANDLE_EOF
2753 */
FileStream_Read(TFileStream * pStream,ULONGLONG * pByteOffset,void * pvBuffer,DWORD dwBytesToRead)2754 bool FileStream_Read(TFileStream * pStream, ULONGLONG * pByteOffset, void * pvBuffer, DWORD dwBytesToRead)
2755 {
2756 assert(pStream->StreamRead != NULL);
2757 return pStream->StreamRead(pStream, pByteOffset, pvBuffer, dwBytesToRead);
2758 }
2759
2760 /**
2761 * This function writes data to the stream
2762 *
2763 * - Returns true if the write operation succeeded and all bytes have been written
2764 * - Returns false if either write failed or not all bytes have been written
2765 * - If the pByteOffset is NULL, the function must write the data to the current file position
2766 *
2767 * \a pStream Pointer to an open stream
2768 * \a pByteOffset Pointer to file byte offset. If NULL, it reads from the current position
2769 * \a pvBuffer Pointer to data to be written
2770 * \a dwBytesToWrite Number of bytes to write to the file
2771 */
FileStream_Write(TFileStream * pStream,ULONGLONG * pByteOffset,const void * pvBuffer,DWORD dwBytesToWrite)2772 bool FileStream_Write(TFileStream * pStream, ULONGLONG * pByteOffset, const void * pvBuffer, DWORD dwBytesToWrite)
2773 {
2774 if(pStream->dwFlags & STREAM_FLAG_READ_ONLY)
2775 {
2776 SetLastError(ERROR_ACCESS_DENIED);
2777 return false;
2778 }
2779
2780 assert(pStream->StreamWrite != NULL);
2781 return pStream->StreamWrite(pStream, pByteOffset, pvBuffer, dwBytesToWrite);
2782 }
2783
2784 /**
2785 * Returns the size of a file
2786 *
2787 * \a pStream Pointer to an open stream
2788 * \a FileSize Pointer where to store the file size
2789 */
FileStream_GetSize(TFileStream * pStream,ULONGLONG * pFileSize)2790 bool FileStream_GetSize(TFileStream * pStream, ULONGLONG * pFileSize)
2791 {
2792 assert(pStream->StreamGetSize != NULL);
2793 return pStream->StreamGetSize(pStream, pFileSize);
2794 }
2795
2796 /**
2797 * Sets the size of a file
2798 *
2799 * \a pStream Pointer to an open stream
2800 * \a NewFileSize File size to set
2801 */
FileStream_SetSize(TFileStream * pStream,ULONGLONG NewFileSize)2802 bool FileStream_SetSize(TFileStream * pStream, ULONGLONG NewFileSize)
2803 {
2804 if(pStream->dwFlags & STREAM_FLAG_READ_ONLY)
2805 {
2806 SetLastError(ERROR_ACCESS_DENIED);
2807 return false;
2808 }
2809
2810 assert(pStream->StreamResize != NULL);
2811 return pStream->StreamResize(pStream, NewFileSize);
2812 }
2813
2814 /**
2815 * This function returns the current file position
2816 * \a pStream
2817 * \a pByteOffset
2818 */
FileStream_GetPos(TFileStream * pStream,ULONGLONG * pByteOffset)2819 bool FileStream_GetPos(TFileStream * pStream, ULONGLONG * pByteOffset)
2820 {
2821 assert(pStream->StreamGetPos != NULL);
2822 return pStream->StreamGetPos(pStream, pByteOffset);
2823 }
2824
2825 /**
2826 * Returns the last write time of a file
2827 *
2828 * \a pStream Pointer to an open stream
2829 * \a pFileType Pointer where to store the file last write time
2830 */
FileStream_GetTime(TFileStream * pStream,ULONGLONG * pFileTime)2831 bool FileStream_GetTime(TFileStream * pStream, ULONGLONG * pFileTime)
2832 {
2833 // Just use the saved filetime value
2834 *pFileTime = pStream->Base.File.FileTime;
2835 return true;
2836 }
2837
2838 /**
2839 * Returns the stream flags
2840 *
2841 * \a pStream Pointer to an open stream
2842 * \a pdwStreamFlags Pointer where to store the stream flags
2843 */
FileStream_GetFlags(TFileStream * pStream,LPDWORD pdwStreamFlags)2844 bool FileStream_GetFlags(TFileStream * pStream, LPDWORD pdwStreamFlags)
2845 {
2846 *pdwStreamFlags = pStream->dwFlags;
2847 return true;
2848 }
2849
2850 /**
2851 * Switches a stream with another. Used for final phase of archive compacting.
2852 * Performs these steps:
2853 *
2854 * 1) Closes the handle to the existing MPQ
2855 * 2) Renames the temporary MPQ to the original MPQ, overwrites existing one
2856 * 3) Opens the MPQ stores the handle and stream position to the new stream structure
2857 *
2858 * \a pStream Pointer to an open stream
2859 * \a pNewStream Temporary ("working") stream (created during archive compacting)
2860 */
FileStream_Replace(TFileStream * pStream,TFileStream * pNewStream)2861 bool FileStream_Replace(TFileStream * pStream, TFileStream * pNewStream)
2862 {
2863 // Only supported on flat files
2864 if((pStream->dwFlags & STREAM_PROVIDERS_MASK) != (STREAM_PROVIDER_FLAT | BASE_PROVIDER_FILE))
2865 {
2866 SetLastError(ERROR_NOT_SUPPORTED);
2867 return false;
2868 }
2869
2870 // Not supported on read-only streams
2871 if(pStream->dwFlags & STREAM_FLAG_READ_ONLY)
2872 {
2873 SetLastError(ERROR_ACCESS_DENIED);
2874 return false;
2875 }
2876
2877 // Close both stream's base providers
2878 pNewStream->BaseClose(pNewStream);
2879 pStream->BaseClose(pStream);
2880
2881 // Now we have to delete the (now closed) old file and rename the new file
2882 if(!BaseFile_Replace(pStream, pNewStream))
2883 return false;
2884
2885 // Now open the base file again
2886 if(!BaseFile_Open(pStream, pStream->szFileName, pStream->dwFlags))
2887 return false;
2888
2889 // Cleanup the new stream
2890 FileStream_Close(pNewStream);
2891 return true;
2892 }
2893
2894 /**
2895 * This function closes an archive file and frees any data buffers
2896 * that have been allocated for stream management. The function must also
2897 * support partially allocated structure, i.e. one or more buffers
2898 * can be NULL, if there was an allocation failure during the process
2899 *
2900 * \a pStream Pointer to an open stream
2901 */
FileStream_Close(TFileStream * pStream)2902 void FileStream_Close(TFileStream * pStream)
2903 {
2904 // Check if the stream structure is allocated at all
2905 if(pStream != NULL)
2906 {
2907 // Free the master stream, if any
2908 if(pStream->pMaster != NULL)
2909 FileStream_Close(pStream->pMaster);
2910 pStream->pMaster = NULL;
2911
2912 // Close the stream provider
2913 if(pStream->StreamClose != NULL)
2914 pStream->StreamClose(pStream);
2915
2916 // ... or close base stream, if any
2917 else if(pStream->BaseClose != NULL)
2918 pStream->BaseClose(pStream);
2919
2920 // Free the stream itself
2921 STORM_FREE(pStream);
2922 }
2923 }
2924