-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileStream.cpp
2891 lines (2467 loc) · 101 KB
/
FileStream.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************/
/* FileStream.cpp Copyright (c) Ladislav Zezula 2010 */
/*---------------------------------------------------------------------------*/
/* File stream support for StormLib */
/* */
/* Windows support: Written by Ladislav Zezula */
/* Mac support: Written by Sam Wilkins */
/* Linux support: Written by Sam Wilkins and Ivan Komissarov */
/* Big-endian: Written & debugged by Sam Wilkins */
/*---------------------------------------------------------------------------*/
/* Date Ver Who Comment */
/* -------- ---- --- ------- */
/* 11.06.10 1.00 Lad Derived from StormPortMac.cpp and StormPortLinux.cpp */
/*****************************************************************************/
#define __STORMLIB_SELF__
#include "StormLib.h"
#include "StormCommon.h"
#include "FileStream.h"
#ifdef _MSC_VER
#pragma comment(lib, "wininet.lib") // Internet functions for HTTP stream
#pragma warning(disable: 4800) // 'BOOL' : forcing value to bool 'true' or 'false' (performance warning)
#endif
//-----------------------------------------------------------------------------
// Local defines
#ifndef INVALID_HANDLE_VALUE
#define INVALID_HANDLE_VALUE ((HANDLE)-1)
#endif
//-----------------------------------------------------------------------------
// Local functions - platform-specific functions
#ifndef PLATFORM_WINDOWS
static DWORD nLastError = ERROR_SUCCESS;
DWORD GetLastError()
{
return nLastError;
}
void SetLastError(DWORD nError)
{
nLastError = nError;
}
#endif
static DWORD StringToInt(const char * szString)
{
DWORD dwValue = 0;
while('0' <= szString[0] && szString[0] <= '9')
{
dwValue = (dwValue * 10) + (szString[0] - '9');
szString++;
}
return dwValue;
}
//-----------------------------------------------------------------------------
// Dummy init function
static void BaseNone_Init(TFileStream *)
{
// Nothing here
}
//-----------------------------------------------------------------------------
// Local functions - base file support
static bool BaseFile_Create(TFileStream * pStream)
{
#ifdef PLATFORM_WINDOWS
{
DWORD dwWriteShare = (pStream->dwFlags & STREAM_FLAG_WRITE_SHARE) ? FILE_SHARE_WRITE : 0;
pStream->Base.File.hFile = CreateFile(pStream->szFileName,
GENERIC_READ | GENERIC_WRITE,
dwWriteShare | FILE_SHARE_READ,
NULL,
CREATE_ALWAYS,
0,
NULL);
if(pStream->Base.File.hFile == INVALID_HANDLE_VALUE)
return false;
}
#endif
#if defined(PLATFORM_MAC) || defined(PLATFORM_LINUX)
{
intptr_t handle;
handle = open(pStream->szFileName, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if(handle == -1)
{
nLastError = errno;
return false;
}
pStream->Base.File.hFile = (HANDLE)handle;
}
#endif
// Reset the file size and position
pStream->Base.File.FileSize = 0;
pStream->Base.File.FilePos = 0;
return true;
}
static bool BaseFile_Open(TFileStream * pStream, const TCHAR * szFileName, DWORD dwStreamFlags)
{
#ifdef PLATFORM_WINDOWS
{
ULARGE_INTEGER FileSize;
DWORD dwWriteAccess = (dwStreamFlags & STREAM_FLAG_READ_ONLY) ? 0 : FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_ATTRIBUTES;
DWORD dwWriteShare = (dwStreamFlags & STREAM_FLAG_WRITE_SHARE) ? FILE_SHARE_WRITE : 0;
// Open the file
pStream->Base.File.hFile = CreateFile(szFileName,
FILE_READ_DATA | FILE_READ_ATTRIBUTES | dwWriteAccess,
FILE_SHARE_READ | dwWriteShare,
NULL,
OPEN_EXISTING,
0,
NULL);
if(pStream->Base.File.hFile == INVALID_HANDLE_VALUE)
return false;
// Query the file size
FileSize.LowPart = GetFileSize(pStream->Base.File.hFile, &FileSize.HighPart);
pStream->Base.File.FileSize = FileSize.QuadPart;
// Query last write time
GetFileTime(pStream->Base.File.hFile, NULL, NULL, (LPFILETIME)&pStream->Base.File.FileTime);
}
#endif
#if defined(PLATFORM_MAC) || defined(PLATFORM_LINUX)
{
struct stat64 fileinfo;
int oflag = (dwStreamFlags & STREAM_FLAG_READ_ONLY) ? O_RDONLY : O_RDWR;
intptr_t handle;
// Open the file
handle = open(szFileName, oflag | O_LARGEFILE);
if(handle == -1)
{
nLastError = errno;
return false;
}
// Get the file size
if(fstat64(handle, &fileinfo) == -1)
{
nLastError = errno;
close(handle);
return false;
}
// time_t is number of seconds since 1.1.1970, UTC.
// 1 second = 10000000 (decimal) in FILETIME
// Set the start to 1.1.1970 00:00:00
pStream->Base.File.FileTime = 0x019DB1DED53E8000ULL + (10000000 * fileinfo.st_mtime);
pStream->Base.File.FileSize = (ULONGLONG)fileinfo.st_size;
pStream->Base.File.hFile = (HANDLE)handle;
}
#endif
// Reset the file position
pStream->Base.File.FilePos = 0;
return true;
}
static bool BaseFile_Read(
TFileStream * pStream, // Pointer to an open stream
ULONGLONG * pByteOffset, // Pointer to file byte offset. If NULL, it reads from the current position
void * pvBuffer, // Pointer to data to be read
DWORD dwBytesToRead) // Number of bytes to read from the file
{
ULONGLONG ByteOffset = (pByteOffset != NULL) ? *pByteOffset : pStream->Base.File.FilePos;
DWORD dwBytesRead = 0; // Must be set by platform-specific code
#ifdef PLATFORM_WINDOWS
{
// Note: StormLib no longer supports Windows 9x.
// Thus, we can use the OVERLAPPED structure to specify
// file offset to read from file. This allows us to skip
// one system call to SetFilePointer
// Update the byte offset
pStream->Base.File.FilePos = ByteOffset;
// Read the data
if(dwBytesToRead != 0)
{
OVERLAPPED Overlapped;
Overlapped.OffsetHigh = (DWORD)(ByteOffset >> 32);
Overlapped.Offset = (DWORD)ByteOffset;
Overlapped.hEvent = NULL;
if(!ReadFile(pStream->Base.File.hFile, pvBuffer, dwBytesToRead, &dwBytesRead, &Overlapped))
return false;
}
}
#endif
#if defined(PLATFORM_MAC) || defined(PLATFORM_LINUX)
{
ssize_t bytes_read;
// If the byte offset is different from the current file position,
// we have to update the file position xxx
if(ByteOffset != pStream->Base.File.FilePos)
{
lseek64((intptr_t)pStream->Base.File.hFile, (off64_t)(ByteOffset), SEEK_SET);
pStream->Base.File.FilePos = ByteOffset;
}
// Perform the read operation
if(dwBytesToRead != 0)
{
bytes_read = read((intptr_t)pStream->Base.File.hFile, pvBuffer, (size_t)dwBytesToRead);
if(bytes_read == -1)
{
nLastError = errno;
return false;
}
dwBytesRead = (DWORD)(size_t)bytes_read;
}
}
#endif
// Increment the current file position by number of bytes read
// If the number of bytes read doesn't match to required amount, return false
pStream->Base.File.FilePos = ByteOffset + dwBytesRead;
if(dwBytesRead != dwBytesToRead)
SetLastError(ERROR_HANDLE_EOF);
return (dwBytesRead == dwBytesToRead);
}
/**
* \a pStream Pointer to an open stream
* \a pByteOffset Pointer to file byte offset. If NULL, writes to current position
* \a pvBuffer Pointer to data to be written
* \a dwBytesToWrite Number of bytes to write to the file
*/
static bool BaseFile_Write(TFileStream * pStream, ULONGLONG * pByteOffset, const void * pvBuffer, DWORD dwBytesToWrite)
{
ULONGLONG ByteOffset = (pByteOffset != NULL) ? *pByteOffset : pStream->Base.File.FilePos;
DWORD dwBytesWritten = 0; // Must be set by platform-specific code
#ifdef PLATFORM_WINDOWS
{
// Note: StormLib no longer supports Windows 9x.
// Thus, we can use the OVERLAPPED structure to specify
// file offset to read from file. This allows us to skip
// one system call to SetFilePointer
// Update the byte offset
pStream->Base.File.FilePos = ByteOffset;
// Read the data
if(dwBytesToWrite != 0)
{
OVERLAPPED Overlapped;
Overlapped.OffsetHigh = (DWORD)(ByteOffset >> 32);
Overlapped.Offset = (DWORD)ByteOffset;
Overlapped.hEvent = NULL;
if(!WriteFile(pStream->Base.File.hFile, pvBuffer, dwBytesToWrite, &dwBytesWritten, &Overlapped))
return false;
}
}
#endif
#if defined(PLATFORM_MAC) || defined(PLATFORM_LINUX)
{
ssize_t bytes_written;
// If the byte offset is different from the current file position,
// we have to update the file position
if(ByteOffset != pStream->Base.File.FilePos)
{
lseek64((intptr_t)pStream->Base.File.hFile, (off64_t)(ByteOffset), SEEK_SET);
pStream->Base.File.FilePos = ByteOffset;
}
// Perform the read operation
bytes_written = write((intptr_t)pStream->Base.File.hFile, pvBuffer, (size_t)dwBytesToWrite);
if(bytes_written == -1)
{
nLastError = errno;
return false;
}
dwBytesWritten = (DWORD)(size_t)bytes_written;
}
#endif
// Increment the current file position by number of bytes read
pStream->Base.File.FilePos = ByteOffset + dwBytesWritten;
// Also modify the file size, if needed
if(pStream->Base.File.FilePos > pStream->Base.File.FileSize)
pStream->Base.File.FileSize = pStream->Base.File.FilePos;
if(dwBytesWritten != dwBytesToWrite)
SetLastError(ERROR_DISK_FULL);
return (dwBytesWritten == dwBytesToWrite);
}
/**
* \a pStream Pointer to an open stream
* \a NewFileSize New size of the file
*/
static bool BaseFile_Resize(TFileStream * pStream, ULONGLONG NewFileSize)
{
#ifdef PLATFORM_WINDOWS
{
LONG FileSizeHi = (LONG)(NewFileSize >> 32);
LONG FileSizeLo;
DWORD dwNewPos;
bool bResult;
// Set the position at the new file size
dwNewPos = SetFilePointer(pStream->Base.File.hFile, (LONG)NewFileSize, &FileSizeHi, FILE_BEGIN);
if(dwNewPos == INVALID_SET_FILE_POINTER && GetLastError() != ERROR_SUCCESS)
return false;
// Set the current file pointer as the end of the file
bResult = (bool)SetEndOfFile(pStream->Base.File.hFile);
if(bResult)
pStream->Base.File.FileSize = NewFileSize;
// Restore the file position
FileSizeHi = (LONG)(pStream->Base.File.FilePos >> 32);
FileSizeLo = (LONG)(pStream->Base.File.FilePos);
SetFilePointer(pStream->Base.File.hFile, FileSizeLo, &FileSizeHi, FILE_BEGIN);
return bResult;
}
#endif
#if defined(PLATFORM_MAC) || defined(PLATFORM_LINUX)
{
if(ftruncate64((intptr_t)pStream->Base.File.hFile, (off64_t)NewFileSize) == -1)
{
nLastError = errno;
return false;
}
pStream->Base.File.FileSize = NewFileSize;
return true;
}
#endif
}
// Gives the current file size
static bool BaseFile_GetSize(TFileStream * pStream, ULONGLONG * pFileSize)
{
// Note: Used by all thre base providers.
// Requires the TBaseData union to have the same layout for all three base providers
*pFileSize = pStream->Base.File.FileSize;
return true;
}
// Gives the current file position
static bool BaseFile_GetPos(TFileStream * pStream, ULONGLONG * pByteOffset)
{
// Note: Used by all thre base providers.
// Requires the TBaseData union to have the same layout for all three base providers
*pByteOffset = pStream->Base.File.FilePos;
return true;
}
// Renames the file pointed by pStream so that it contains data from pNewStream
static bool BaseFile_Replace(TFileStream * pStream, TFileStream * pNewStream)
{
#ifdef PLATFORM_WINDOWS
// Delete the original stream file. Don't check the result value,
// because if the file doesn't exist, it would fail
DeleteFile(pStream->szFileName);
// Rename the new file to the old stream's file
return (bool)MoveFile(pNewStream->szFileName, pStream->szFileName);
#endif
#if defined(PLATFORM_MAC) || defined(PLATFORM_LINUX)
// "rename" on Linux also works if the target file exists
if(rename(pNewStream->szFileName, pStream->szFileName) == -1)
{
nLastError = errno;
return false;
}
return true;
#endif
}
static void BaseFile_Close(TFileStream * pStream)
{
if(pStream->Base.File.hFile != INVALID_HANDLE_VALUE)
{
#ifdef PLATFORM_WINDOWS
CloseHandle(pStream->Base.File.hFile);
#endif
#if defined(PLATFORM_MAC) || defined(PLATFORM_LINUX)
close((intptr_t)pStream->Base.File.hFile);
#endif
}
// Also invalidate the handle
pStream->Base.File.hFile = INVALID_HANDLE_VALUE;
}
// Initializes base functions for the disk file
static void BaseFile_Init(TFileStream * pStream)
{
pStream->BaseCreate = BaseFile_Create;
pStream->BaseOpen = BaseFile_Open;
pStream->BaseRead = BaseFile_Read;
pStream->BaseWrite = BaseFile_Write;
pStream->BaseResize = BaseFile_Resize;
pStream->BaseGetSize = BaseFile_GetSize;
pStream->BaseGetPos = BaseFile_GetPos;
pStream->BaseClose = BaseFile_Close;
}
//-----------------------------------------------------------------------------
// Local functions - base memory-mapped file support
static bool BaseMap_Open(TFileStream * pStream, const TCHAR * szFileName, DWORD dwStreamFlags)
{
#ifdef PLATFORM_WINDOWS
ULARGE_INTEGER FileSize;
HANDLE hFile;
HANDLE hMap;
bool bResult = false;
// Keep compiler happy
dwStreamFlags = dwStreamFlags;
// Open the file for read access
hFile = CreateFile(szFileName, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if(hFile != INVALID_HANDLE_VALUE)
{
// Retrieve file size. Don't allow mapping file of a zero size.
FileSize.LowPart = GetFileSize(hFile, &FileSize.HighPart);
if(FileSize.QuadPart != 0)
{
// Now create mapping object
hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if(hMap != NULL)
{
// Map the entire view into memory
// Note that this operation will fail if the file can't fit
// into usermode address space
pStream->Base.Map.pbFile = (LPBYTE)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);
if(pStream->Base.Map.pbFile != NULL)
{
// Retrieve file time
GetFileTime(hFile, NULL, NULL, (LPFILETIME)&pStream->Base.Map.FileTime);
// Retrieve file size and position
pStream->Base.Map.FileSize = FileSize.QuadPart;
pStream->Base.Map.FilePos = 0;
bResult = true;
}
// Close the map handle
CloseHandle(hMap);
}
}
// Close the file handle
CloseHandle(hFile);
}
// If the file is not there and is not available for random access,
// report error
if(bResult == false)
return false;
#endif
#if defined(PLATFORM_MAC) || defined(PLATFORM_LINUX)
struct stat64 fileinfo;
intptr_t handle;
bool bResult = false;
// Open the file
handle = open(szFileName, O_RDONLY);
if(handle != -1)
{
// Get the file size
if(fstat64(handle, &fileinfo) != -1)
{
pStream->Base.Map.pbFile = (LPBYTE)mmap(NULL, (size_t)fileinfo.st_size, PROT_READ, MAP_PRIVATE, handle, 0);
if(pStream->Base.Map.pbFile != NULL)
{
// time_t is number of seconds since 1.1.1970, UTC.
// 1 second = 10000000 (decimal) in FILETIME
// Set the start to 1.1.1970 00:00:00
pStream->Base.Map.FileTime = 0x019DB1DED53E8000ULL + (10000000 * fileinfo.st_mtime);
pStream->Base.Map.FileSize = (ULONGLONG)fileinfo.st_size;
pStream->Base.Map.FilePos = 0;
bResult = true;
}
}
close(handle);
}
// Did the mapping fail?
if(bResult == false)
{
nLastError = errno;
return false;
}
#endif
return true;
}
static bool BaseMap_Read(
TFileStream * pStream, // Pointer to an open stream
ULONGLONG * pByteOffset, // Pointer to file byte offset. If NULL, it reads from the current position
void * pvBuffer, // Pointer to data to be read
DWORD dwBytesToRead) // Number of bytes to read from the file
{
ULONGLONG ByteOffset = (pByteOffset != NULL) ? *pByteOffset : pStream->Base.Map.FilePos;
// Do we have to read anything at all?
if(dwBytesToRead != 0)
{
// Don't allow reading past file size
if((ByteOffset + dwBytesToRead) > pStream->Base.Map.FileSize)
return false;
// Copy the required data
memcpy(pvBuffer, pStream->Base.Map.pbFile + (size_t)ByteOffset, dwBytesToRead);
}
// Move the current file position
pStream->Base.Map.FilePos += dwBytesToRead;
return true;
}
static void BaseMap_Close(TFileStream * pStream)
{
#ifdef PLATFORM_WINDOWS
if(pStream->Base.Map.pbFile != NULL)
UnmapViewOfFile(pStream->Base.Map.pbFile);
#endif
#if defined(PLATFORM_MAC) || defined(PLATFORM_LINUX)
if(pStream->Base.Map.pbFile != NULL)
munmap(pStream->Base.Map.pbFile, (size_t )pStream->Base.Map.FileSize);
#endif
pStream->Base.Map.pbFile = NULL;
}
// Initializes base functions for the mapped file
static void BaseMap_Init(TFileStream * pStream)
{
// Supply the file stream functions
pStream->BaseOpen = BaseMap_Open;
pStream->BaseRead = BaseMap_Read;
pStream->BaseGetSize = BaseFile_GetSize; // Reuse BaseFile function
pStream->BaseGetPos = BaseFile_GetPos; // Reuse BaseFile function
pStream->BaseClose = BaseMap_Close;
// Mapped files are read-only
pStream->dwFlags |= STREAM_FLAG_READ_ONLY;
}
//-----------------------------------------------------------------------------
// Local functions - base HTTP file support
static const TCHAR * BaseHttp_ExtractServerName(const TCHAR * szFileName, TCHAR * szServerName)
{
// Check for HTTP
if(!_tcsnicmp(szFileName, _T("http://"), 7))
szFileName += 7;
// Cut off the server name
if(szServerName != NULL)
{
while(szFileName[0] != 0 && szFileName[0] != _T('/'))
*szServerName++ = *szFileName++;
*szServerName = 0;
}
else
{
while(szFileName[0] != 0 && szFileName[0] != _T('/'))
szFileName++;
}
// Return the remainder
return szFileName;
}
static bool BaseHttp_Open(TFileStream * pStream, const TCHAR * szFileName, DWORD dwStreamFlags)
{
#ifdef PLATFORM_WINDOWS
HINTERNET hRequest;
DWORD dwTemp = 0;
bool bFileAvailable = false;
int nError = ERROR_SUCCESS;
// Keep compiler happy
dwStreamFlags = dwStreamFlags;
// Don't connect to the internet
if(!InternetGetConnectedState(&dwTemp, 0))
return false;
// Initiate the connection to the internet
pStream->Base.Http.hInternet = InternetOpen(_T("StormLib HTTP MPQ reader"),
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
0);
if(pStream->Base.Http.hInternet == NULL)
return false;
// Connect to the server
if(nError == ERROR_SUCCESS)
{
TCHAR szServerName[MAX_PATH];
DWORD dwFlags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_UI | INTERNET_FLAG_NO_CACHE_WRITE;
// Initiate connection with the server
szFileName = BaseHttp_ExtractServerName(szFileName, szServerName);
pStream->Base.Http.hConnect = InternetConnect(pStream->Base.Http.hInternet,
szServerName,
INTERNET_DEFAULT_HTTP_PORT,
NULL,
NULL,
INTERNET_SERVICE_HTTP,
dwFlags,
0);
if(pStream->Base.Http.hConnect == NULL)
{
InternetCloseHandle(pStream->Base.Http.hInternet);
return false;
}
}
// Now try to query the file size
if(nError == ERROR_SUCCESS)
{
// Open HTTP request to the file
hRequest = HttpOpenRequest(pStream->Base.Http.hConnect, _T("GET"), szFileName, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);
if(hRequest != NULL)
{
if(HttpSendRequest(hRequest, NULL, 0, NULL, 0))
{
ULONGLONG FileTime = 0;
DWORD dwFileSize = 0;
DWORD dwDataSize;
DWORD dwIndex = 0;
// Check if the MPQ has Last Modified field
dwDataSize = sizeof(ULONGLONG);
if(HttpQueryInfo(hRequest, HTTP_QUERY_LAST_MODIFIED | HTTP_QUERY_FLAG_SYSTEMTIME, &FileTime, &dwDataSize, &dwIndex))
pStream->Base.Http.FileTime = FileTime;
// Verify if the server supports random access
dwDataSize = sizeof(DWORD);
if(HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwFileSize, &dwDataSize, &dwIndex))
{
if(dwFileSize != 0)
{
pStream->Base.Http.FileSize = dwFileSize;
pStream->Base.Http.FilePos = 0;
bFileAvailable = true;
}
}
}
InternetCloseHandle(hRequest);
}
}
// If the file is not there and is not available for random access,
// report error
if(bFileAvailable == false)
{
pStream->BaseClose(pStream);
return false;
}
return true;
#else
// Not supported
SetLastError(ERROR_NOT_SUPPORTED);
pStream = pStream;
return false;
#endif
}
static bool BaseHttp_Read(
TFileStream * pStream, // Pointer to an open stream
ULONGLONG * pByteOffset, // Pointer to file byte offset. If NULL, it reads from the current position
void * pvBuffer, // Pointer to data to be read
DWORD dwBytesToRead) // Number of bytes to read from the file
{
#ifdef PLATFORM_WINDOWS
ULONGLONG ByteOffset = (pByteOffset != NULL) ? *pByteOffset : pStream->Base.Http.FilePos;
DWORD dwTotalBytesRead = 0;
// Do we have to read anything at all?
if(dwBytesToRead != 0)
{
HINTERNET hRequest;
LPCTSTR szFileName;
LPBYTE pbBuffer = (LPBYTE)pvBuffer;
TCHAR szRangeRequest[0x80];
DWORD dwStartOffset = (DWORD)ByteOffset;
DWORD dwEndOffset = dwStartOffset + dwBytesToRead;
// Open HTTP request to the file
szFileName = BaseHttp_ExtractServerName(pStream->szFileName, NULL);
hRequest = HttpOpenRequest(pStream->Base.Http.hConnect, _T("GET"), szFileName, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);
if(hRequest != NULL)
{
// Add range request to the HTTP headers
// http://www.clevercomponents.com/articles/article015/resuming.asp
_stprintf(szRangeRequest, _T("Range: bytes=%u-%u"), (unsigned int)dwStartOffset, (unsigned int)dwEndOffset);
HttpAddRequestHeaders(hRequest, szRangeRequest, 0xFFFFFFFF, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
// Send the request to the server
if(HttpSendRequest(hRequest, NULL, 0, NULL, 0))
{
while(dwTotalBytesRead < dwBytesToRead)
{
DWORD dwBlockBytesToRead = dwBytesToRead - dwTotalBytesRead;
DWORD dwBlockBytesRead = 0;
// Read the block from the file
if(dwBlockBytesToRead > 0x200)
dwBlockBytesToRead = 0x200;
InternetReadFile(hRequest, pbBuffer, dwBlockBytesToRead, &dwBlockBytesRead);
// Check for end
if(dwBlockBytesRead == 0)
break;
// Move buffers
dwTotalBytesRead += dwBlockBytesRead;
pbBuffer += dwBlockBytesRead;
}
}
InternetCloseHandle(hRequest);
}
}
// Increment the current file position by number of bytes read
pStream->Base.Http.FilePos = ByteOffset + dwTotalBytesRead;
// If the number of bytes read doesn't match the required amount, return false
if(dwTotalBytesRead != dwBytesToRead)
SetLastError(ERROR_HANDLE_EOF);
return (dwTotalBytesRead == dwBytesToRead);
#else
// Not supported
pStream = pStream;
pByteOffset = pByteOffset;
pvBuffer = pvBuffer;
dwBytesToRead = dwBytesToRead;
SetLastError(ERROR_NOT_SUPPORTED);
return false;
#endif
}
static void BaseHttp_Close(TFileStream * pStream)
{
#ifdef PLATFORM_WINDOWS
if(pStream->Base.Http.hConnect != NULL)
InternetCloseHandle(pStream->Base.Http.hConnect);
pStream->Base.Http.hConnect = NULL;
if(pStream->Base.Http.hInternet != NULL)
InternetCloseHandle(pStream->Base.Http.hInternet);
pStream->Base.Http.hInternet = NULL;
#else
pStream = pStream;
#endif
}
// Initializes base functions for the mapped file
static void BaseHttp_Init(TFileStream * pStream)
{
// Supply the stream functions
pStream->BaseOpen = BaseHttp_Open;
pStream->BaseRead = BaseHttp_Read;
pStream->BaseGetSize = BaseFile_GetSize; // Reuse BaseFile function
pStream->BaseGetPos = BaseFile_GetPos; // Reuse BaseFile function
pStream->BaseClose = BaseHttp_Close;
// HTTP files are read-only
pStream->dwFlags |= STREAM_FLAG_READ_ONLY;
}
//-----------------------------------------------------------------------------
// Local functions - base block-based support
// Generic function that loads blocks from the file
// The function groups the block with the same availability,
// so the called BlockRead can finish the request in a single system call
static bool BlockStream_Read(
TBlockStream * pStream, // Pointer to an open stream
ULONGLONG * pByteOffset, // Pointer to file byte offset. If NULL, it reads from the current position
void * pvBuffer, // Pointer to data to be read
DWORD dwBytesToRead) // Number of bytes to read from the file
{
ULONGLONG BlockOffset0;
ULONGLONG BlockOffset;
ULONGLONG ByteOffset;
ULONGLONG EndOffset;
LPBYTE TransferBuffer;
LPBYTE BlockBuffer;
DWORD BlockBufferOffset; // Offset of the desired data in the block buffer
DWORD BytesNeeded; // Number of bytes that really need to be read
DWORD BlockSize = pStream->BlockSize;
DWORD BlockCount;
bool bPrevBlockAvailable;
bool bCallbackCalled = false;
bool bBlockAvailable;
bool bResult = true;
// The base block read function must be present
assert(pStream->BlockRead != NULL);
// NOP reading of zero bytes
if(dwBytesToRead == 0)
return true;
// Get the current position in the stream
ByteOffset = (pByteOffset != NULL) ? pByteOffset[0] : pStream->StreamPos;
EndOffset = ByteOffset + dwBytesToRead;
if(EndOffset > pStream->StreamSize)
{
SetLastError(ERROR_HANDLE_EOF);
return false;
}
// Calculate the block parameters
BlockOffset0 = BlockOffset = ByteOffset & ~((ULONGLONG)BlockSize - 1);
BlockCount = (DWORD)(((EndOffset - BlockOffset) + (BlockSize - 1)) / BlockSize);
BytesNeeded = (DWORD)(EndOffset - BlockOffset);
// Remember where we have our data
assert((BlockSize & (BlockSize - 1)) == 0);
BlockBufferOffset = (DWORD)(ByteOffset & (BlockSize - 1));
// Allocate buffer for reading blocks
TransferBuffer = BlockBuffer = STORM_ALLOC(BYTE, (BlockCount * BlockSize));
if(TransferBuffer == NULL)
{
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return false;
}
// If all blocks are available, just read all blocks at once
if(pStream->IsComplete == 0)
{
// Now parse the blocks and send the block read request
// to all blocks with the same availability
assert(pStream->BlockCheck != NULL);
bPrevBlockAvailable = pStream->BlockCheck(pStream, BlockOffset);
// Loop as long as we have something to read
while(BlockOffset < EndOffset)
{
// Determine availability of the next block
bBlockAvailable = pStream->BlockCheck(pStream, BlockOffset);
// If the availability has changed, read all blocks up to this one
if(bBlockAvailable != bPrevBlockAvailable)
{
// Call the file stream callback, if the block is not available
if(pStream->pMaster && pStream->pfnCallback && bPrevBlockAvailable == false)
{
pStream->pfnCallback(pStream->UserData, BlockOffset0, (DWORD)(BlockOffset - BlockOffset0));
bCallbackCalled = true;
}
// Load the continuous blocks with the same availability
assert(BlockOffset > BlockOffset0);
bResult = pStream->BlockRead(pStream, BlockOffset0, BlockOffset, BlockBuffer, BytesNeeded, bPrevBlockAvailable);
if(!bResult)
break;
// Move the block offset
BlockBuffer += (DWORD)(BlockOffset - BlockOffset0);
BytesNeeded -= (DWORD)(BlockOffset - BlockOffset0);
bPrevBlockAvailable = bBlockAvailable;
BlockOffset0 = BlockOffset;
}
// Move to the block offset in the stream
BlockOffset += BlockSize;
}
// If there is a block(s) remaining to be read, do it
if(BlockOffset > BlockOffset0)
{
// Call the file stream callback, if the block is not available
if(pStream->pMaster && pStream->pfnCallback && bPrevBlockAvailable == false)
{
pStream->pfnCallback(pStream->UserData, BlockOffset0, (DWORD)(BlockOffset - BlockOffset0));
bCallbackCalled = true;
}
// Read the complete blocks from the file
if(BlockOffset > pStream->StreamSize)
BlockOffset = pStream->StreamSize;
bResult = pStream->BlockRead(pStream, BlockOffset0, BlockOffset, BlockBuffer, BytesNeeded, bPrevBlockAvailable);
}
}
else
{
// Read the complete blocks from the file
if(EndOffset > pStream->StreamSize)
EndOffset = pStream->StreamSize;
bResult = pStream->BlockRead(pStream, BlockOffset, EndOffset, BlockBuffer, BytesNeeded, true);
}
// Now copy the data to the user buffer
if(bResult)
{
memcpy(pvBuffer, TransferBuffer + BlockBufferOffset, dwBytesToRead);
pStream->StreamPos = ByteOffset + dwBytesToRead;
}
else
{
// If the block read failed, set the last error
SetLastError(ERROR_FILE_INCOMPLETE);
}
// Call the callback to indicate we are done
if(bCallbackCalled)
pStream->pfnCallback(pStream->UserData, 0, 0);
// Free the block buffer and return
STORM_FREE(TransferBuffer);
return bResult;
}
static bool BlockStream_GetSize(TFileStream * pStream, ULONGLONG * pFileSize)
{
*pFileSize = pStream->StreamSize;
return true;
}
static bool BlockStream_GetPos(TFileStream * pStream, ULONGLONG * pByteOffset)
{
*pByteOffset = pStream->StreamPos;
return true;
}
static void BlockStream_Close(TBlockStream * pStream)
{
// Free the data map, if any
if(pStream->FileBitmap != NULL)
STORM_FREE(pStream->FileBitmap);
pStream->FileBitmap = NULL;
// Call the base class for closing the stream
pStream->BaseClose(pStream);
}
//-----------------------------------------------------------------------------
// File stream allocation function
static STREAM_INIT StreamBaseInit[4] =
{
BaseFile_Init,
BaseMap_Init,
BaseHttp_Init,
BaseNone_Init
};
// This function allocates an empty structure for the file stream
// The stream structure is created as flat block, variable length
// The file name is placed after the end of the stream structure data
static TFileStream * AllocateFileStream(