forked from shokunin000/te120
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzip_utils.cpp
1718 lines (1468 loc) · 46.9 KB
/
zip_utils.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
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
// If we are going to include windows.h then we need to disable protected_things.h
// or else we get many warnings.
#undef PROTECTED_THINGS_ENABLE
#include <tier0/platform.h>
#ifdef IS_WINDOWS_PC
#include <windows.h>
#else
#define INVALID_HANDLE_VALUE (void *)0
#define FILE_BEGIN SEEK_SET
#define FILE_END SEEK_END
#endif
#include "utlbuffer.h"
#include "utllinkedlist.h"
#include "zip_utils.h"
#include "zip_uncompressed.h"
#include "checksum_crc.h"
#include "byteswap.h"
#include "utlstring.h"
// Data descriptions for byte swapping - only needed
// for structures that are written to file for use by the game.
BEGIN_BYTESWAP_DATADESC( ZIP_EndOfCentralDirRecord )
DEFINE_FIELD( signature, FIELD_INTEGER ),
DEFINE_FIELD( numberOfThisDisk, FIELD_SHORT ),
DEFINE_FIELD( numberOfTheDiskWithStartOfCentralDirectory, FIELD_SHORT ),
DEFINE_FIELD( nCentralDirectoryEntries_ThisDisk, FIELD_SHORT ),
DEFINE_FIELD( nCentralDirectoryEntries_Total, FIELD_SHORT ),
DEFINE_FIELD( centralDirectorySize, FIELD_INTEGER ),
DEFINE_FIELD( startOfCentralDirOffset, FIELD_INTEGER ),
DEFINE_FIELD( commentLength, FIELD_SHORT ),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC( ZIP_FileHeader )
DEFINE_FIELD( signature, FIELD_INTEGER ),
DEFINE_FIELD( versionMadeBy, FIELD_SHORT ),
DEFINE_FIELD( versionNeededToExtract, FIELD_SHORT ),
DEFINE_FIELD( flags, FIELD_SHORT ),
DEFINE_FIELD( compressionMethod, FIELD_SHORT ),
DEFINE_FIELD( lastModifiedTime, FIELD_SHORT ),
DEFINE_FIELD( lastModifiedDate, FIELD_SHORT ),
DEFINE_FIELD( crc32, FIELD_INTEGER ),
DEFINE_FIELD( compressedSize, FIELD_INTEGER ),
DEFINE_FIELD( uncompressedSize, FIELD_INTEGER ),
DEFINE_FIELD( fileNameLength, FIELD_SHORT ),
DEFINE_FIELD( extraFieldLength, FIELD_SHORT ),
DEFINE_FIELD( fileCommentLength, FIELD_SHORT ),
DEFINE_FIELD( diskNumberStart, FIELD_SHORT ),
DEFINE_FIELD( internalFileAttribs, FIELD_SHORT ),
DEFINE_FIELD( externalFileAttribs, FIELD_INTEGER ),
DEFINE_FIELD( relativeOffsetOfLocalHeader, FIELD_INTEGER ),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC( ZIP_LocalFileHeader )
DEFINE_FIELD( signature, FIELD_INTEGER ),
DEFINE_FIELD( versionNeededToExtract, FIELD_SHORT ),
DEFINE_FIELD( flags, FIELD_SHORT ),
DEFINE_FIELD( compressionMethod, FIELD_SHORT ),
DEFINE_FIELD( lastModifiedTime, FIELD_SHORT ),
DEFINE_FIELD( lastModifiedDate, FIELD_SHORT ),
DEFINE_FIELD( crc32, FIELD_INTEGER ),
DEFINE_FIELD( compressedSize, FIELD_INTEGER ),
DEFINE_FIELD( uncompressedSize, FIELD_INTEGER ),
DEFINE_FIELD( fileNameLength, FIELD_SHORT ),
DEFINE_FIELD( extraFieldLength, FIELD_SHORT ),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC( ZIP_PreloadHeader )
DEFINE_FIELD( Version, FIELD_INTEGER ),
DEFINE_FIELD( DirectoryEntries, FIELD_INTEGER ),
DEFINE_FIELD( PreloadDirectoryEntries, FIELD_INTEGER ),
DEFINE_FIELD( Alignment, FIELD_INTEGER ),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC( ZIP_PreloadDirectoryEntry )
DEFINE_FIELD( Length, FIELD_INTEGER ),
DEFINE_FIELD( DataOffset, FIELD_INTEGER ),
END_BYTESWAP_DATADESC()
#ifdef WIN32
//-----------------------------------------------------------------------------
// For >2 GB File Support
//-----------------------------------------------------------------------------
class CWin32File
{
public:
static HANDLE CreateTempFile( CUtlString &WritePath, CUtlString &FileName )
{
char tempFileName[MAX_PATH];
if ( WritePath.IsEmpty() )
{
// use a safe name in the cwd
char *pBuffer = tmpnam( NULL );
if ( !pBuffer )
{
return INVALID_HANDLE_VALUE;
}
if ( pBuffer[0] == '\\' )
{
pBuffer++;
}
if ( pBuffer[strlen( pBuffer )-1] == '.' )
{
pBuffer[strlen( pBuffer )-1] = '\0';
}
V_snprintf( tempFileName, sizeof( tempFileName ), "_%s.tmp", pBuffer );
}
else
{
// generate safe name at the desired prefix
char uniqueFilename[MAX_PATH];
SYSTEMTIME sysTime; \
GetLocalTime( &sysTime );
sprintf( uniqueFilename, "%d_%d_%d_%d_%d.tmp", sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds ); \
V_ComposeFileName( WritePath.String(), uniqueFilename, tempFileName, sizeof( tempFileName ) );
}
FileName = tempFileName;
HANDLE hFile = CreateFile( tempFileName, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
return hFile;
}
static unsigned int FileSeek( HANDLE hFile, unsigned int distance, DWORD MoveMethod )
{
LARGE_INTEGER li;
li.QuadPart = distance;
li.LowPart = SetFilePointer( hFile, li.LowPart, &li.HighPart, MoveMethod);
if ( li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR )
{
li.QuadPart = -1;
}
return ( unsigned int )li.QuadPart;
}
static unsigned int FileTell( HANDLE hFile )
{
return FileSeek( hFile, 0, FILE_CURRENT );
}
static bool FileRead( HANDLE hFile, void *pBuffer, unsigned int size )
{
DWORD numBytesRead;
BOOL bSuccess = ::ReadFile( hFile, pBuffer, size, &numBytesRead, NULL );
return bSuccess && ( numBytesRead == size );
}
static bool FileWrite( HANDLE hFile, void *pBuffer, unsigned int size )
{
DWORD numBytesWritten;
BOOL bSuccess = WriteFile( hFile, pBuffer, size, &numBytesWritten, NULL );
return bSuccess && ( numBytesWritten == size );
}
};
#else
class CWin32File
{
public:
static HANDLE CreateTempFile( CUtlString &WritePath, CUtlString &FileName )
{
char tempFileName[MAX_PATH];
if ( WritePath.IsEmpty() )
{
// use a safe name in the cwd
char *pBuffer = tmpnam( NULL );
if ( !pBuffer )
{
return INVALID_HANDLE_VALUE;
}
if ( pBuffer[0] == '\\' )
{
pBuffer++;
}
if ( pBuffer[strlen( pBuffer )-1] == '.' )
{
pBuffer[strlen( pBuffer )-1] = '\0';
}
V_snprintf( tempFileName, sizeof( tempFileName ), "_%s.tmp", pBuffer );
}
else
{
char uniqueFilename[MAX_PATH];
static int counter = 0;
time_t now = time( NULL );
struct tm *tm = localtime( &now );
sprintf( uniqueFilename, "%d_%d_%d_%d_%d.tmp", tm->tm_wday, tm->tm_hour, tm->tm_min, tm->tm_sec, ++counter ); \
V_ComposeFileName( WritePath.String(), uniqueFilename, tempFileName, sizeof( tempFileName ) );
}
FileName = tempFileName;
FILE *hFile = fopen( tempFileName, "rw+" );
return (HANDLE)hFile;
}
static unsigned int FileSeek( HANDLE hFile, unsigned int distance, DWORD MoveMethod )
{
if ( fseeko( (FILE *)hFile, distance, MoveMethod ) == 0 )
{
return FileTell( hFile );
}
return 0;
}
static unsigned int FileTell( HANDLE hFile )
{
return ftello( (FILE *)hFile );
}
static bool FileRead( HANDLE hFile, void *pBuffer, unsigned int size )
{
size_t bytesRead = fread( pBuffer, 1, size, (FILE *)hFile );
return bytesRead == size;
}
static bool FileWrite( HANDLE hFile, void *pBuffer, unsigned int size )
{
size_t bytesWrtitten = fwrite( pBuffer, 1, size, (FILE *)hFile );
return bytesWrtitten == size;
}
};
#endif
//-----------------------------------------------------------------------------
// Purpose: Interface to allow abstraction of zip file output methods, and
// avoid duplication of code. Files may be written to a CUtlBuffer or a filestream
//-----------------------------------------------------------------------------
abstract_class IWriteStream
{
public:
virtual void Put( const void* pMem, int size ) = 0;
virtual unsigned int Tell( void ) = 0;
};
//-----------------------------------------------------------------------------
// Purpose: Wrapper for CUtlBuffer methods
//-----------------------------------------------------------------------------
class CBufferStream : public IWriteStream
{
public:
CBufferStream( CUtlBuffer& buff ) : IWriteStream(), m_buff( &buff ) {}
// Implementing IWriteStream method
virtual void Put( const void* pMem, int size ) { m_buff->Put( pMem, size ); }
// Implementing IWriteStream method
virtual unsigned int Tell( void ) { return m_buff->TellPut(); }
private:
CUtlBuffer *m_buff;
};
//-----------------------------------------------------------------------------
// Purpose: Wrapper for file I/O methods
//-----------------------------------------------------------------------------
class CFileStream : public IWriteStream
{
public:
CFileStream( FILE *fout ) : IWriteStream(), m_file( fout ), m_hFile( INVALID_HANDLE_VALUE ) {}
CFileStream( HANDLE hOutFile ) : IWriteStream(), m_file( NULL ), m_hFile( hOutFile ) {}
// Implementing IWriteStream method
virtual void Put( const void* pMem, int size )
{
if ( m_file )
{
fwrite( pMem, size, 1, m_file );
}
#ifdef WIN32
else
{
DWORD numBytesWritten;
WriteFile( m_hFile, pMem, size, &numBytesWritten, NULL );
}
#endif
}
// Implementing IWriteStream method
virtual unsigned int Tell( void )
{
if ( m_file )
{
return ftell( m_file );
}
else
{
#ifdef WIN32
return CWin32File::FileTell( m_hFile );
#else
return 0;
#endif
}
}
private:
FILE *m_file;
HANDLE m_hFile;
};
//-----------------------------------------------------------------------------
// Purpose: Container for modifiable pak file which is embedded inside the .bsp file
// itself. It's used to allow one-off files to be stored local to the map and it is
// hooked into the file system as an override for searching for named files.
//-----------------------------------------------------------------------------
class CZipFile
{
public:
// Construction
CZipFile( const char *pDiskCacheWritePath, bool bSortByName );
~CZipFile( void );
// Public API
// Clear all existing data
void Reset( void );
// Add file to zip under relative name
void AddFileToZip( const char *relativename, const char *fullpath );
// Delete file from zip
void RemoveFileFromZip( const char *relativename );
// Add buffer to zip as a file with given name
void AddBufferToZip( const char *relativename, void *data, int length, bool bTextMode );
// Check if a file already exists in the zip.
bool FileExistsInZip( const char *relativename );
// Reads a file from a zip file
bool ReadFileFromZip( const char *relativename, bool bTextMode, CUtlBuffer &buf );
bool ReadFileFromZip( HANDLE hZipFile, const char *relativename, bool bTextMode, CUtlBuffer &buf );
// Initialize the zip file from a buffer
void ParseFromBuffer( void *buffer, int bufferlength );
HANDLE ParseFromDisk( const char *pFilename );
// Estimate the size of the zip file (including header, padding, etc.)
unsigned int EstimateSize();
// Print out a directory of files in the zip.
void PrintDirectory( void );
// Use to iterate directory, pass 0 for first element
// returns nonzero element id with filled buffer, or -1 at list conclusion
int GetNextFilename( int id, char *pBuffer, int bufferSize, int &fileSize );
// Write the zip to a buffer
void SaveToBuffer( CUtlBuffer& buffer );
// Write the zip to a filestream
void SaveToDisk( FILE *fout );
void SaveToDisk( HANDLE hOutFile );
unsigned int CalculateSize( void );
void ForceAlignment( bool aligned, bool bCompatibleFormat, unsigned int alignmentSize );
unsigned int GetAlignment();
void SetBigEndian( bool bigEndian );
void ActivateByteSwapping( bool bActivate );
private:
enum
{
MAX_FILES_IN_ZIP = 32768,
};
typedef struct
{
CUtlSymbol m_Name;
unsigned int filepos;
int filelen;
} TmpFileInfo_t;
CByteswap m_Swap;
unsigned int m_AlignmentSize;
bool m_bForceAlignment;
bool m_bCompatibleFormat;
unsigned short CalculatePadding( unsigned int filenameLen, unsigned int pos );
void SaveDirectory( IWriteStream& stream );
int MakeXZipCommentString( char *pComment );
void ParseXZipCommentString( const char *pComment );
// Internal entry for faster searching, etc.
class CZipEntry
{
public:
CZipEntry( void );
~CZipEntry( void );
CZipEntry( const CZipEntry& src );
// RB tree compare function
static bool ZipFileLessFunc( CZipEntry const& src1, CZipEntry const& src2 );
static bool ZipFileLessFunc_CaselessSort( CZipEntry const& src1, CZipEntry const& src2 );
// Name of entry
CUtlSymbol m_Name;
// Lenth of data element
int m_Length;
// Raw data, could be null and data may be in disk write cache
void *m_pData;
// Offset in Zip ( set and valid during final write )
unsigned int m_ZipOffset;
// CRC of blob ( set and valid during final write )
CRC32_t m_ZipCRC;
// Location of data in disk cache
unsigned int m_DiskCacheOffset;
unsigned int m_SourceDiskOffset;
};
// For fast name lookup and sorting
CUtlRBTree< CZipEntry, int > m_Files;
// Used to buffer zip data, instead of ram
bool m_bUseDiskCacheForWrites;
HANDLE m_hDiskCacheWriteFile;
CUtlString m_DiskCacheName;
CUtlString m_DiskCacheWritePath;
};
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CZipFile::CZipEntry::CZipEntry( void )
{
m_Name = "";
m_Length = 0;
m_pData = NULL;
m_ZipOffset = 0;
m_ZipCRC = 0;
m_DiskCacheOffset = 0;
m_SourceDiskOffset = 0;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : src -
//-----------------------------------------------------------------------------
CZipFile::CZipEntry::CZipEntry( const CZipFile::CZipEntry& src )
{
m_Name = src.m_Name;
m_Length = src.m_Length;
if ( src.m_Length > 0 && src.m_pData )
{
m_pData = malloc( src.m_Length );
memcpy( m_pData, src.m_pData, src.m_Length );
}
else
{
m_pData = NULL;
}
m_ZipOffset = src.m_ZipOffset;
m_ZipCRC = src.m_ZipCRC;
m_DiskCacheOffset = src.m_DiskCacheOffset;
m_SourceDiskOffset = src.m_SourceDiskOffset;
}
//-----------------------------------------------------------------------------
// Purpose: Clear any leftover data
//-----------------------------------------------------------------------------
CZipFile::CZipEntry::~CZipEntry( void )
{
if ( m_pData )
{
free( m_pData );
}
}
//-----------------------------------------------------------------------------
// Purpose: Construction
//-----------------------------------------------------------------------------
CZipFile::CZipFile( const char *pDiskCacheWritePath, bool bSortByName )
: m_Files( 0, 32 )
{
m_AlignmentSize = 0;
m_bForceAlignment = false;
m_bCompatibleFormat = true;
m_bUseDiskCacheForWrites = ( pDiskCacheWritePath != NULL );
m_DiskCacheWritePath = pDiskCacheWritePath;
m_hDiskCacheWriteFile = INVALID_HANDLE_VALUE;
if ( bSortByName )
{
m_Files.SetLessFunc( CZipEntry::ZipFileLessFunc_CaselessSort );
}
else
{
m_Files.SetLessFunc( CZipEntry::ZipFileLessFunc );
}
}
//-----------------------------------------------------------------------------
// Purpose: Destroy zip data
//-----------------------------------------------------------------------------
CZipFile::~CZipFile( void )
{
m_bUseDiskCacheForWrites = false;
Reset();
}
//-----------------------------------------------------------------------------
// Purpose: Delete all current data
//-----------------------------------------------------------------------------
void CZipFile::Reset( void )
{
m_Files.RemoveAll();
if ( m_hDiskCacheWriteFile != INVALID_HANDLE_VALUE )
{
#ifdef WIN32
CloseHandle( m_hDiskCacheWriteFile );
DeleteFile( m_DiskCacheName.String() );
#else
fclose( (FILE *)m_hDiskCacheWriteFile );
unlink( m_DiskCacheName.String() );
#endif
m_hDiskCacheWriteFile = INVALID_HANDLE_VALUE;
}
if ( m_bUseDiskCacheForWrites )
{
m_hDiskCacheWriteFile = CWin32File::CreateTempFile( m_DiskCacheWritePath, m_DiskCacheName );
}
}
//-----------------------------------------------------------------------------
// Purpose: Comparison for sorting entries
// Input : src1 -
// src2 -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CZipFile::CZipEntry::ZipFileLessFunc( CZipEntry const& src1, CZipEntry const& src2 )
{
return ( src1.m_Name < src2.m_Name );
}
bool CZipFile::CZipEntry::ZipFileLessFunc_CaselessSort( CZipEntry const& src1, CZipEntry const& src2 )
{
return ( V_stricmp( src1.m_Name.String(), src2.m_Name.String() ) < 0 );
}
void CZipFile::ForceAlignment( bool bAligned, bool bCompatibleFormat, unsigned int alignment )
{
m_bForceAlignment = bAligned;
m_AlignmentSize = alignment;
m_bCompatibleFormat = bCompatibleFormat;
if ( !bAligned )
{
m_AlignmentSize = 0;
}
else if ( !IsPowerOfTwo( m_AlignmentSize ) )
{
m_AlignmentSize = 0;
}
}
unsigned int CZipFile::GetAlignment()
{
if ( !m_bForceAlignment || !m_AlignmentSize )
{
return 0;
}
return m_AlignmentSize;
}
void CZipFile::SetBigEndian( bool bigEndian )
{
m_Swap.SetTargetBigEndian( bigEndian );
}
void CZipFile::ActivateByteSwapping( bool bActivate )
{
m_Swap.ActivateByteSwapping( bActivate );
}
//-----------------------------------------------------------------------------
// Purpose: Load pak file from raw buffer
// Input : *buffer -
// bufferlength -
//-----------------------------------------------------------------------------
void CZipFile::ParseFromBuffer( void *buffer, int bufferlength )
{
// Throw away old data
Reset();
// Initialize a buffer
CUtlBuffer buf( 0, bufferlength +1 ); // +1 for null termination
// need to swap bytes, so set the buffer opposite the machine's endian
buf.ActivateByteSwapping( m_Swap.IsSwappingBytes() );
buf.Put( buffer, bufferlength );
buf.SeekGet( CUtlBuffer::SEEK_TAIL, 0 );
unsigned int fileLen = buf.TellGet();
// Start from beginning
buf.SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
ZIP_EndOfCentralDirRecord rec = { 0 };
bool bFoundEndOfCentralDirRecord = false;
unsigned int offset = fileLen - sizeof( ZIP_EndOfCentralDirRecord );
// If offset is ever greater than startOffset then it means that it has
// wrapped. This used to be a tautological >= 0 test.
ANALYZE_SUPPRESS( 6293 ); // warning C6293: Ill-defined for-loop: counts down from minimum
for ( unsigned int startOffset = offset; offset <= startOffset; offset-- )
{
buf.SeekGet( CUtlBuffer::SEEK_HEAD, offset );
buf.GetObjects( &rec );
if ( rec.signature == PKID( 5, 6 ) )
{
bFoundEndOfCentralDirRecord = true;
// Set any xzip configuration
if ( rec.commentLength )
{
char commentString[128];
int commentLength = min( rec.commentLength, sizeof( commentString ) );
buf.Get( commentString, commentLength );
if ( commentLength == sizeof( commentString ) )
--commentLength;
commentString[commentLength] = '\0';
ParseXZipCommentString( commentString );
}
break;
}
else
{
// wrong record
rec.nCentralDirectoryEntries_Total = 0;
}
}
Assert( bFoundEndOfCentralDirRecord );
// Make sure there are some files to parse
int numzipfiles = rec.nCentralDirectoryEntries_Total;
if ( numzipfiles <= 0 )
{
// No files
return;
}
buf.SeekGet( CUtlBuffer::SEEK_HEAD, rec.startOfCentralDirOffset );
// Allocate space for directory
TmpFileInfo_t *newfiles = new TmpFileInfo_t[numzipfiles];
Assert( newfiles );
// build directory
int i;
for ( i = 0; i < rec.nCentralDirectoryEntries_Total; i++ )
{
ZIP_FileHeader zipFileHeader;
buf.GetObjects( &zipFileHeader );
Assert( zipFileHeader.signature == PKID( 1, 2 ) );
Assert( zipFileHeader.compressionMethod == 0 );
char tmpString[1024];
buf.Get( tmpString, zipFileHeader.fileNameLength );
tmpString[zipFileHeader.fileNameLength] = '\0';
Q_strlower( tmpString );
// can determine actual filepos, assuming a well formed zip
newfiles[i].m_Name = tmpString;
newfiles[i].filelen = zipFileHeader.compressedSize;
newfiles[i].filepos = zipFileHeader.relativeOffsetOfLocalHeader +
sizeof( ZIP_LocalFileHeader ) +
zipFileHeader.fileNameLength +
zipFileHeader.extraFieldLength;
int nextOffset;
if ( m_bCompatibleFormat )
{
nextOffset = zipFileHeader.extraFieldLength + zipFileHeader.fileCommentLength;
}
else
{
nextOffset = 0;
}
buf.SeekGet( CUtlBuffer::SEEK_CURRENT, nextOffset );
}
// Insert current data into rb tree
for ( i=0; i<numzipfiles; i++ )
{
CZipEntry e;
e.m_Name = newfiles[i].m_Name;
e.m_Length = newfiles[i].filelen;
// Make sure length is reasonable
if ( e.m_Length > 0 )
{
e.m_pData = malloc( e.m_Length );
// Copy in data
buf.SeekGet( CUtlBuffer::SEEK_HEAD, newfiles[i].filepos );
buf.Get( e.m_pData, e.m_Length );
}
else
{
e.m_pData = NULL;
}
// Add to tree
m_Files.Insert( e );
}
// Through away directory
delete[] newfiles;
}
//-----------------------------------------------------------------------------
// Purpose: Mount pak file from disk
//-----------------------------------------------------------------------------
HANDLE CZipFile::ParseFromDisk( const char *pFilename )
{
#ifdef WIN32
HANDLE hFile = CreateFile( pFilename, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if ( hFile == INVALID_HANDLE_VALUE )
{
// not found
return NULL;
}
#else
HANDLE hFile = fopen( pFilename, "rw+" );
if ( !hFile )
{
// not found
return NULL;
}
#endif
unsigned int fileLen = CWin32File::FileSeek( hFile, 0, FILE_END );
CWin32File::FileSeek( hFile, 0, FILE_BEGIN );
if ( fileLen < sizeof( ZIP_EndOfCentralDirRecord ) )
{
// bad format
#ifdef WIN32
CloseHandle( hFile );
#else
fclose( (FILE *)hFile );
#endif
return NULL;
}
// need to get the central dir
ZIP_EndOfCentralDirRecord rec = { 0 };
unsigned int offset = fileLen - sizeof( ZIP_EndOfCentralDirRecord );
// If offset is ever greater than startOffset then it means that it has
// wrapped. This used to be a tautological >= 0 test.
ANALYZE_SUPPRESS( 6293 ); // warning C6293: Ill-defined for-loop: counts down from minimum
for ( unsigned int startOffset = offset; offset <= startOffset; offset-- )
{
CWin32File::FileSeek( hFile, offset, FILE_BEGIN );
CWin32File::FileRead( hFile, &rec, sizeof( rec ) );
m_Swap.SwapFieldsToTargetEndian( &rec );
if ( rec.signature == PKID( 5, 6 ) )
{
// Set any xzip configuration
if ( rec.commentLength )
{
char commentString[128];
int commentLength = min( rec.commentLength, sizeof( commentString ) );
CWin32File::FileRead( hFile, commentString, commentLength );
if ( commentLength == sizeof( commentString ) )
--commentLength;
commentString[commentLength] = '\0';
ParseXZipCommentString( commentString );
}
break;
}
else
{
// wrong record
rec.nCentralDirectoryEntries_Total = 0;
}
}
// Make sure there are some files to parse
int numZipFiles = rec.nCentralDirectoryEntries_Total;
if ( numZipFiles <= 0 )
{
// No files
#ifdef WIN32
CloseHandle( hFile );
#else
fclose( (FILE *)hFile );
#endif
return NULL;
}
CWin32File::FileSeek( hFile, rec.startOfCentralDirOffset, FILE_BEGIN );
// read entire central dir into memory
CUtlBuffer zipDirBuff( 0, rec.centralDirectorySize, 0 );
zipDirBuff.ActivateByteSwapping( m_Swap.IsSwappingBytes() );
CWin32File::FileRead( hFile, zipDirBuff.Base(), rec.centralDirectorySize );
zipDirBuff.SeekPut( CUtlBuffer::SEEK_HEAD, rec.centralDirectorySize );
// build directory
for ( int i = 0; i < numZipFiles; i++ )
{
ZIP_FileHeader zipFileHeader;
zipDirBuff.GetObjects( &zipFileHeader );
if ( zipFileHeader.signature != PKID( 1, 2 ) || zipFileHeader.compressionMethod != 0 )
{
// bad contents
#ifdef WIN32
CloseHandle( hFile );
#else
fclose( (FILE *)hFile );
#endif
return NULL;
}
char fileName[1024];
zipDirBuff.Get( fileName, zipFileHeader.fileNameLength );
fileName[zipFileHeader.fileNameLength] = '\0';
Q_strlower( fileName );
// can determine actual filepos, assuming a well formed zip
CZipEntry e;
e.m_Name = fileName;
e.m_Length = zipFileHeader.compressedSize;
e.m_SourceDiskOffset = zipFileHeader.relativeOffsetOfLocalHeader +
sizeof( ZIP_LocalFileHeader ) +
zipFileHeader.fileNameLength +
zipFileHeader.extraFieldLength;
// Add to tree
m_Files.Insert( e );
int nextOffset;
if ( m_bCompatibleFormat )
{
nextOffset = zipFileHeader.extraFieldLength + zipFileHeader.fileCommentLength;
}
else
{
nextOffset = 0;
}
zipDirBuff.SeekGet( CUtlBuffer::SEEK_CURRENT, nextOffset );
}
return hFile;
}
static int GetLengthOfBinStringAsText( const char *pSrc, int srcSize )
{
const char *pSrcScan = pSrc;
const char *pSrcEnd = pSrc + srcSize;
int numChars = 0;
for( ; pSrcScan < pSrcEnd; pSrcScan++ )
{
if( *pSrcScan == '\n' )
{
numChars += 2;
}
else
{
numChars++;
}
}
return numChars;
}
//-----------------------------------------------------------------------------
// Copies text data from a form appropriate for disk to a normal string
//-----------------------------------------------------------------------------
static void ReadTextData( const char *pSrc, int nSrcSize, CUtlBuffer &buf )
{
buf.EnsureCapacity( nSrcSize + 1 );
const char *pSrcEnd = pSrc + nSrcSize;
for ( const char *pSrcScan = pSrc; pSrcScan < pSrcEnd; ++pSrcScan )
{
if ( *pSrcScan == '\r' )
{
if ( pSrcScan[1] == '\n' )
{
buf.PutChar( '\n' );
++pSrcScan;
continue;
}
}
buf.PutChar( *pSrcScan );
}
// Null terminate
buf.PutChar( '\0' );
}
//-----------------------------------------------------------------------------
// Copies text data into a form appropriate for disk
//-----------------------------------------------------------------------------
static void CopyTextData( char *pDst, const char *pSrc, int dstSize, int srcSize )
{
const char *pSrcScan = pSrc;
const char *pSrcEnd = pSrc + srcSize;
char *pDstScan = pDst;
#ifdef DBGFLAG_ASSERT
char *pDstEnd = pDst + dstSize;
#endif
for ( ; pSrcScan < pSrcEnd; pSrcScan++ )
{
if ( *pSrcScan == '\n' )
{
*pDstScan = '\r';
pDstScan++;
*pDstScan = '\n';
pDstScan++;
}
else
{
*pDstScan = *pSrcScan;
pDstScan++;
}
}
Assert( pSrcScan == pSrcEnd );
Assert( pDstScan == pDstEnd );
}
//-----------------------------------------------------------------------------
// Purpose: Adds a new lump, or overwrites existing one
// Input : *relativename -
// *data -
// length -
//-----------------------------------------------------------------------------
void CZipFile::AddBufferToZip( const char *relativename, void *data, int length, bool bTextMode )
{
// Lower case only
char name[512];
Q_strcpy( name, relativename );
Q_strlower( name );
int dstLength = length;
if ( bTextMode )
{
dstLength = GetLengthOfBinStringAsText( ( const char * )data, length );
}
// See if entry is in list already
CZipEntry e;
e.m_Name = name;
int index = m_Files.Find( e );
// If already existing, throw away old data and update data and length
if ( index != m_Files.InvalidIndex() )
{
CZipEntry *update = &m_Files[ index ];
if ( update->m_pData )
{
free( update->m_pData );
}
if ( bTextMode )
{
update->m_pData = malloc( dstLength );
CopyTextData( ( char * )update->m_pData, ( char * )data, dstLength, length );
update->m_Length = dstLength;
}
else
{
update->m_pData = malloc( length );
memcpy( update->m_pData, data, length );
update->m_Length = length;
}
if ( m_hDiskCacheWriteFile != INVALID_HANDLE_VALUE )
{
update->m_DiskCacheOffset = CWin32File::FileTell( m_hDiskCacheWriteFile );
CWin32File::FileWrite( m_hDiskCacheWriteFile, update->m_pData, update->m_Length );
free( update->m_pData );
update->m_pData = NULL;
}
}