-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathfilesystem_steam.cpp
More file actions
1536 lines (1330 loc) · 42.4 KB
/
filesystem_steam.cpp
File metadata and controls
1536 lines (1330 loc) · 42.4 KB
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:
//
// $NoKeywords: $
//=============================================================================//
#include "basefilesystem.h"
#include "steamcommon.h"
#include "SteamInterface.h"
#include "tier0/dbg.h"
#include "tier0/icommandline.h"
#include "steam/steam_api.h"
#ifdef POSIX
#include <fcntl.h>
#ifdef LINUX
#include <sys/file.h>
#endif
#include <dlfcn.h>
#define _S_IWRITE S_IWRITE
#define _S_IWRITE S_IWRITE
#define _S_IFREG S_IFREG
#define FILE_ATTRIBUTE_OFFLINE 0x1000
#endif
#ifdef _WIN32
extern "C"
{
__declspec(dllimport) int __stdcall IsDebuggerPresent();
}
#endif
ISteamInterface *steam = NULL;
static SteamHandle_t g_pLastErrorFile;
static TSteamError g_tLastError;
static TSteamError g_tLastErrorNoFile;
void CheckError( SteamHandle_t fp, TSteamError & steamError)
{
if (steamError.eSteamError == eSteamErrorContentServerConnect)
{
// fatal error
#ifdef WIN32
// kill the current window so the user can see the error
HWND hwnd = GetForegroundWindow();
if (hwnd)
{
DestroyWindow(hwnd);
}
// show the error
MessageBox(NULL, "Could not acquire necessary game files because the connection to Steam servers was lost.", "Source - Fatal Error", MB_OK | MB_ICONEXCLAMATION);
// get out of here immediately
TerminateProcess(GetCurrentProcess(), 0);
#else
fprintf( stderr, "Could not acquire necessary game files because the connection to Steam servers was lost." );
exit(-1);
#endif
return;
}
if (fp)
{
if (steamError.eSteamError != eSteamErrorNone || g_tLastError.eSteamError != eSteamErrorNone)
{
g_pLastErrorFile = fp;
g_tLastError = steamError;
}
}
else
{
// write to the NULL error checker
if (steamError.eSteamError != eSteamErrorNone || g_tLastErrorNoFile.eSteamError != eSteamErrorNone)
{
g_tLastErrorNoFile = steamError;
}
}
}
#ifdef POSIX
class CSteamFile
{
public:
explicit CSteamFile( SteamHandle_t file, bool bWriteable, const char *pchName ) : m_File( file ), m_bWriteable( bWriteable ), m_FileName(pchName) {}
~CSteamFile() {}
SteamHandle_t Handle() { return m_File; }
bool BWriteable() { return m_bWriteable; }
CUtlSymbol GetFileName() { return m_FileName; }
private:
SteamHandle_t m_File;
bool m_bWriteable;
CUtlSymbol m_FileName;
};
#endif
class CFileSystem_Steam : public CBaseFileSystem
{
public:
CFileSystem_Steam();
~CFileSystem_Steam();
// Methods of IAppSystem
virtual InitReturnVal_t Init();
virtual void Shutdown();
virtual void * QueryInterface( const char *pInterfaceName );
// Higher level filesystem methods requiring specific behavior
virtual void GetLocalCopy( const char *pFileName );
virtual int HintResourceNeed( const char *hintlist, int forgetEverything );
virtual CSysModule * LoadModule( const char *pFileName, const char *pPathID, bool bValidatedDllOnly );
virtual bool IsFileImmediatelyAvailable(const char *pFileName);
// resource waiting
virtual WaitForResourcesHandle_t WaitForResources( const char *resourcelist );
virtual bool GetWaitForResourcesProgress( WaitForResourcesHandle_t handle, float *progress /* out */ , bool *complete /* out */ );
virtual void CancelWaitForResources( WaitForResourcesHandle_t handle );
virtual bool IsSteam() const { return true; }
virtual FilesystemMountRetval_t MountSteamContent( int nExtraAppId = -1 );
protected:
// implementation of CBaseFileSystem virtual functions
virtual FILE *FS_fopen( const char *filename, const char *options, unsigned flags, int64 *size, CFileLoadInfo *pInfo );
virtual void FS_setbufsize( FILE *fp, unsigned nBytes );
virtual void FS_fclose( FILE *fp );
virtual void FS_fseek( FILE *fp, int64 pos, int seekType );
virtual long FS_ftell( FILE *fp );
virtual int FS_feof( FILE *fp );
virtual size_t FS_fread( void *dest, size_t destSize, size_t size, FILE *fp );
virtual size_t FS_fwrite( const void *src, size_t size, FILE *fp );
virtual size_t FS_vfprintf( FILE *fp, const char *fmt, va_list list );
virtual int FS_ferror( FILE *fp );
virtual int FS_fflush( FILE *fp );
virtual char *FS_fgets( char *dest, int destSize, FILE *fp );
virtual int FS_stat( const char *path, struct _stat *buf, bool *pbLoadedFromSteamCache=NULL );
virtual int FS_chmod( const char *path, int pmode );
virtual HANDLE FS_FindFirstFile(const char *findname, WIN32_FIND_DATA *dat);
virtual bool FS_FindNextFile(HANDLE handle, WIN32_FIND_DATA *dat);
virtual bool FS_FindClose(HANDLE handle);
private:
bool IsFileInSteamCache( const char *file );
bool IsFileInSteamCache2( const char *file );
void ViewSteamCache( const char* szDir, bool bRecurse );
bool m_bSteamInitialized;
bool m_bCurrentlyLoading;
bool m_bAssertFilesImmediatelyAvailable;
bool m_bCanAsync;
bool m_bSelfMounted;
bool m_bContentLoaded;
bool m_bSDKToolMode;
SteamCallHandle_t m_hWaitForResourcesCallHandle;
int m_iCurrentReturnedCallHandle;
HMODULE m_hSteamDLL;
void LoadAndStartSteam();
#ifdef POSIX
static CUtlMap< int, CInterlockedInt > m_LockedFDMap;
#endif
};
#ifdef POSIX
CUtlMap< int, CInterlockedInt> CFileSystem_Steam::m_LockedFDMap;
#endif
//-----------------------------------------------------------------------------
// singleton
//-----------------------------------------------------------------------------
static CFileSystem_Steam g_FileSystem_Steam;
#if defined(DEDICATED)
CBaseFileSystem *BaseFileSystem_Steam( void )
{
return &g_FileSystem_Steam;
}
#endif
#ifdef DEDICATED // "hack" to allow us to not export a stdio version of the FILESYSTEM_INTERFACE_VERSION anywhere
IFileSystem *g_pFileSystemSteam = &g_FileSystem_Steam;
IBaseFileSystem *g_pBaseFileSystemSteam = &g_FileSystem_Steam;
#else
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CFileSystem_Steam, IFileSystem, FILESYSTEM_INTERFACE_VERSION, g_FileSystem_Steam );
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CFileSystem_Steam, IBaseFileSystem, BASEFILESYSTEM_INTERFACE_VERSION, g_FileSystem_Steam );
#endif
//-----------------------------------------------------------------------------
// constructor
//-----------------------------------------------------------------------------
CFileSystem_Steam::CFileSystem_Steam()
{
m_bSteamInitialized = false;
m_bCurrentlyLoading = false;
m_bAssertFilesImmediatelyAvailable = false;
m_bCanAsync = true;
m_bContentLoaded = false;
m_hWaitForResourcesCallHandle = STEAM_INVALID_CALL_HANDLE;
m_iCurrentReturnedCallHandle = 1;
m_hSteamDLL = NULL;
m_bSDKToolMode = false;
#ifdef POSIX
SetDefLessFunc( m_LockedFDMap );
#endif
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CFileSystem_Steam::~CFileSystem_Steam()
{
m_bSteamInitialized = false;
}
bool CFileSystem_Steam::IsFileInSteamCache2( const char *file )
{
if ( !m_bContentLoaded || m_bSDKToolMode)
{
return true;
}
// see if the file exists
TSteamElemInfo info;
TSteamError error;
SteamHandle_t h = steam->FindFirst( file, eSteamFindRemoteOnly, &info, &error );
if ( h == STEAM_INVALID_HANDLE )
{
return false;
}
else
{
steam->FindClose( h, &error );
}
return true;
}
void MountDependencies( int iAppId, CUtlVector<unsigned int> &depList )
{
TSteamError steamError;
// Setup the buffers for the TSteamApp structure.
char buffers[4][2048];
TSteamApp steamApp;
steamApp.szName = buffers[0];
steamApp.uMaxNameChars = sizeof( buffers[0] );
steamApp.szLatestVersionLabel = buffers[1];
steamApp.uMaxLatestVersionLabelChars = sizeof( buffers[1] );
steamApp.szCurrentVersionLabel = buffers[2];
steamApp.uMaxCurrentVersionLabelChars = sizeof( buffers[2] );
steamApp.szInstallDirName = buffers[3];
steamApp.uMaxInstallDirNameChars = sizeof( buffers[3] );
// Ask how many caches depend on this app ID.
steam->EnumerateApp( iAppId, &steamApp, &steamError );
if ( steamError.eSteamError != eSteamErrorNone )
Error( "EnumerateApp( %d ) failed: %s", iAppId, steamError.szDesc );
// Mount each cache.
for ( int i=0; i < (int)steamApp.uNumDependencies; i++ )
{
TSteamAppDependencyInfo appDependencyInfo;
steam->EnumerateAppDependency( iAppId, i, &appDependencyInfo, &steamError );
if ( steamError.eSteamError != eSteamErrorNone )
Error( "EnumerateAppDependency( %d, %d ) failed: %s", iAppId, i, steamError.szDesc );
if ( depList.Find( appDependencyInfo.uAppId ) == -1 )
{
depList.AddToTail( appDependencyInfo.uAppId );
// Make sure that the user owns the app before attempting to mount it
int isSubscribed = false, isPending = false;
steam->IsAppSubscribed( appDependencyInfo.uAppId, &isSubscribed, &isPending, &steamError );
if ( isSubscribed )
{
steam->MountFilesystem( appDependencyInfo.uAppId, "", &steamError );
if ( steamError.eSteamError != eSteamErrorNone && steamError.eSteamError != eSteamErrorNotSubscribed )
{
Error( "MountFilesystem( %d ) failed: %s", appDependencyInfo.uAppId, steamError.szDesc );
}
}
}
}
}
//-----------------------------------------------------------------------------
// QueryInterface:
//-----------------------------------------------------------------------------
void *CFileSystem_Steam::QueryInterface( const char *pInterfaceName )
{
// We also implement the IMatSystemSurface interface
if (!Q_strncmp( pInterfaceName, FILESYSTEM_INTERFACE_VERSION, Q_strlen(FILESYSTEM_INTERFACE_VERSION) + 1))
return (IFileSystem*)this;
return CBaseFileSystem::QueryInterface( pInterfaceName );
}
//-----------------------------------------------------------------------------
// Methods of IAppSystem
//-----------------------------------------------------------------------------
InitReturnVal_t CFileSystem_Steam::Init()
{
m_bSteamInitialized = true;
m_bSelfMounted = false;
LoadAndStartSteam();
return CBaseFileSystem::Init();
}
void CFileSystem_Steam::Shutdown()
{
Assert( m_bSteamInitialized );
if ( !steam )
return;
TSteamError steamError;
// If we're not running Steam in local mode, remove all mount points from the STEAM VFS.
if ( !CommandLine()->CheckParm("-steamlocal") && !m_bSelfMounted && !steam->UnmountAppFilesystem(&steamError) )
{
#ifdef WIN32
OutputDebugString(steamError.szDesc);
#endif
Assert(!("STEAM VFS failed to unmount"));
// just continue on as if nothing happened
// ::MessageBox(NULL, szErrorMsg, "Half-Life FileSystem_Steam Error", MB_OK);
// exit( -1 );
}
steam->Cleanup(&steamError);
if ( m_hSteamDLL )
{
Sys_UnloadModule( (CSysModule *)m_hSteamDLL );
m_hSteamDLL = NULL;
}
m_bSteamInitialized = false;
}
void CFileSystem_Steam::LoadAndStartSteam()
{
if ( !m_hSteamDLL )
{
const char *pchSteamInstallPath = SteamAPI_GetSteamInstallPath();
if ( pchSteamInstallPath )
{
char szSteamDLLPath[ MAX_PATH ];
#ifdef WIN32
V_ComposeFileName( pchSteamInstallPath, "steam" DLL_EXT_STRING, szSteamDLLPath, Q_ARRAYSIZE(szSteamDLLPath) );
#elif defined(POSIX)
V_ComposeFileName( pchSteamInstallPath, "libsteam" DLL_EXT_STRING, szSteamDLLPath, Q_ARRAYSIZE(szSteamDLLPath) );
#else
#error
#endif
// try to load the steam.dll from the running steam process first
m_hSteamDLL = (HMODULE)Sys_LoadModule( szSteamDLLPath );
}
if ( !m_hSteamDLL )
#ifdef WIN32
m_hSteamDLL = (HMODULE)Sys_LoadModule( "steam" DLL_EXT_STRING );
#elif defined(POSIX)
m_hSteamDLL = (HMODULE)Sys_LoadModule( "libsteam" DLL_EXT_STRING );
#else
#error
#endif
}
if ( m_hSteamDLL )
{
typedef void *(*PFSteamCreateInterface)( const char *pchSteam );
#ifdef WIN32
PFSteamCreateInterface pfnSteamCreateInterface = (PFSteamCreateInterface)GetProcAddress( m_hSteamDLL, "_f" );
#else
PFSteamCreateInterface pfnSteamCreateInterface = (PFSteamCreateInterface)dlsym( (void *)m_hSteamDLL, "_f" );
#endif
if ( pfnSteamCreateInterface )
steam = (ISteamInterface *)pfnSteamCreateInterface( STEAM_INTERFACE_VERSION );
}
if ( !steam )
{
Error("CFileSystem_Steam::Init() failed: failed to find steam interface\n");
#ifdef WIN32
::DestroyWindow( GetForegroundWindow() );
::MessageBox(NULL, "CFileSystem_Steam::Init() failed: failed to find steam interface", "Half-Life FileSystem_Steam Error", MB_OK);
#endif
_exit( -1 );
}
TSteamError steamError;
if (!steam->Startup(STEAM_USING_FILESYSTEM | STEAM_USING_LOGGING | STEAM_USING_USERID | STEAM_USING_ACCOUNT, &steamError))
{
Error("SteamStartup() failed: %s\n", steamError.szDesc);
#ifdef WIN32
::DestroyWindow( GetForegroundWindow() );
::MessageBox(NULL, steamError.szDesc, "Half-Life FileSystem_Steam Error", MB_OK);
#endif
_exit( -1 );
}
}
//-----------------------------------------------------------------------------
// Methods of IAppSystem
//-----------------------------------------------------------------------------
FilesystemMountRetval_t CFileSystem_Steam::MountSteamContent( int nExtraAppId )
{
m_bContentLoaded = true;
FilesystemMountRetval_t retval = FILESYSTEM_MOUNT_OK;
// MWD: This is here because of Hammer's funky startup sequence that requires MountSteamContent() be called in CHammerApp::PreInit(). Once that root problem is addressed this will be removed;
if ( NULL == steam )
{
LoadAndStartSteam();
}
// only mount if we're already logged in
// if we're not logged in, assume the app will login & mount the cache itself
// this enables both the game and the platform to use this same code, even though they mount caches at different times
int loggedIn = 0;
TSteamError steamError;
int result = steam->IsLoggedIn(&loggedIn, &steamError);
if (!result || loggedIn)
{
if ( nExtraAppId != -1 )
{
m_bSDKToolMode = true;
CUtlVector<unsigned int> depList;
if ( nExtraAppId < -1 )
{
// Special way to tell them to mount a specific App ID's depots.
MountDependencies( -nExtraAppId, depList );
return FILESYSTEM_MOUNT_OK;
}
else
{
const char *pMainAppId = NULL;
// If they specified extra app IDs they want to mount after the main one, then we mount
// the caches manually here.
#ifdef _WIN32
// Use GetEnvironmentVariable instead of getenv because getenv doesn't pick up changes
// to the process environment after the DLL was loaded.
char szMainAppId[128];
if ( GetEnvironmentVariable( "steamappid", szMainAppId, sizeof( szMainAppId ) ) != 0 )
{
pMainAppId = szMainAppId;
}
#else
// LINUX BUG: see above
pMainAppId = getenv( "SteamAppId" );
#endif // _WIN32
if ( !pMainAppId )
Error( "Extra App ID set to %d, but no SteamAppId.", nExtraAppId );
//swapping this mount order ensures the most current engine binaries are used by tools
MountDependencies( nExtraAppId, depList );
MountDependencies( atoi( pMainAppId ), depList );
return FILESYSTEM_MOUNT_OK;
}
}
else if (!steam->MountAppFilesystem(&steamError))
{
Error("MountAppFilesystem() failed: %s\n", steamError.szDesc);
#ifdef WIN32
::DestroyWindow( GetForegroundWindow() );
::MessageBox(NULL, steamError.szDesc, "Half-Life FileSystem_Steam Error", MB_OK);
#endif
_exit( -1 );
}
}
else
{
m_bSelfMounted = true;
}
return retval;
}
//-----------------------------------------------------------------------------
// Purpose: low-level filesystem wrapper
//-----------------------------------------------------------------------------
FILE *CFileSystem_Steam::FS_fopen( const char *filenameT, const char *options, unsigned flags, int64 *size, CFileLoadInfo *pInfo )
{
char filename[MAX_PATH];
FixUpPath ( filenameT, filename, sizeof( filename ) );
// make sure the file is immediately available
if (m_bAssertFilesImmediatelyAvailable && !m_bCurrentlyLoading)
{
if (!IsFileImmediatelyAvailable(filename))
{
Msg("Steam FS: '%s' not immediately available when not in loading dialog", filename);
}
}
if ( !steam )
{
AssertMsg( 0, "CFileSystem_Steam::FS_fopen used with null steam interface!" );
return NULL;
}
CFileLoadInfo dummyInfo;
if ( !pInfo )
{
dummyInfo.m_bSteamCacheOnly = false;
pInfo = &dummyInfo;
}
SteamHandle_t f = 0;
#ifdef POSIX
FILE *pFile = NULL;
bool bWriteable = false;
if ( strchr(options,'w') || strchr(options,'a') )
bWriteable = true;
if ( bWriteable )
{
pFile = fopen( filename, options );
if (pFile && size)
{
// todo: replace with filelength()?
struct _stat buf;
int rt = _stat( filename, &buf );
if (rt == 0)
{
*size = buf.st_size;
}
}
if ( pFile )
{
// Win32 has an undocumented feature that is serialized ALL writes to a file across threads (i.e only 1 thread can open a file at a time)
// so use flock here to mimic that behavior
ThreadId_t curThread = ThreadGetCurrentId();
{
CThreadFastMutex Locklock;
AUTO_LOCK( Locklock );
int fd = fileno_unlocked( pFile );
int iLockID = m_LockedFDMap.Find( fd );
int ret = flock( fd, LOCK_EX | LOCK_NB );
if ( ret < 0 )
{
if ( errno == EWOULDBLOCK )
{
if ( iLockID != m_LockedFDMap.InvalidIndex() &&
m_LockedFDMap[iLockID] != -1 &&
curThread != m_LockedFDMap[iLockID] )
{
ret = flock( fd, LOCK_EX );
if ( ret < 0 )
{
fclose( pFile );
return NULL;
}
}
}
else
{
fclose( pFile );
return NULL;
}
}
if ( iLockID != m_LockedFDMap.InvalidIndex() )
m_LockedFDMap[iLockID] = curThread;
else
m_LockedFDMap.Insert( fd, curThread );
}
rewind( pFile );
}
}
else
{
#endif
TSteamError steamError;
unsigned int fileSize;
int bLocal = 0;
f = steam->OpenFileEx(filename, options, pInfo->m_bSteamCacheOnly, &fileSize, &bLocal, &steamError);
pInfo->m_bLoadedFromSteamCache = (bLocal == 0);
if (size)
{
*size = fileSize;
}
CheckError( f, steamError );
#ifdef POSIX
}
if ( f || pFile )
{
CSteamFile *steamFile = new CSteamFile( pFile ? (SteamHandle_t)pFile : f, bWriteable, filename );
f = (SteamHandle_t)steamFile;
}
#endif
return (FILE *)f;
}
//-----------------------------------------------------------------------------
// Purpose: low-level filesystem wrapper
//-----------------------------------------------------------------------------
void CFileSystem_Steam::FS_setbufsize( FILE *fp, unsigned nBytes )
{
}
//-----------------------------------------------------------------------------
// Purpose: steam call, unnecessary in stdio
//-----------------------------------------------------------------------------
WaitForResourcesHandle_t CFileSystem_Steam::WaitForResources( const char *resourcelist )
{
char szResourceList[MAX_PATH];
Q_strncpy( szResourceList, resourcelist, sizeof(szResourceList) );
Q_DefaultExtension( szResourceList, ".lst", sizeof(szResourceList) );
// cancel any old call
TSteamError steamError;
m_hWaitForResourcesCallHandle = steam->WaitForResources(szResourceList, &steamError);
if (steamError.eSteamError == eSteamErrorNone)
{
// return a new call handle
return (WaitForResourcesHandle_t)(++m_iCurrentReturnedCallHandle);
}
Msg("SteamWaitForResources() failed: %s\n", steamError.szDesc);
return (WaitForResourcesHandle_t)FILESYSTEM_INVALID_HANDLE;
}
//-----------------------------------------------------------------------------
// Purpose: steam call, unnecessary in stdio
//-----------------------------------------------------------------------------
bool CFileSystem_Steam::GetWaitForResourcesProgress( WaitForResourcesHandle_t handle, float *progress /* out */ , bool *complete /* out */ )
{
// clear the input
*progress = 0.0f;
*complete = true;
// check to see if they're using an old handle
if (m_iCurrentReturnedCallHandle != handle)
return false;
if (m_hWaitForResourcesCallHandle == STEAM_INVALID_CALL_HANDLE)
return false;
// get the progress
TSteamError steamError;
TSteamProgress steamProgress;
int result = steam->ProcessCall(m_hWaitForResourcesCallHandle, &steamProgress, &steamError);
if (result && steamError.eSteamError == eSteamErrorNone)
{
// we've finished successfully
m_hWaitForResourcesCallHandle = STEAM_INVALID_CALL_HANDLE;
*complete = true;
*progress = 1.0f;
return true;
}
else if (steamError.eSteamError != eSteamErrorNotFinishedProcessing)
{
// we have an error, just call it done
m_hWaitForResourcesCallHandle = STEAM_INVALID_CALL_HANDLE;
Msg("SteamProcessCall(SteamWaitForResources()) failed: %s\n", steamError.szDesc);
return false;
}
// return the progress
if (steamProgress.bValid)
{
*progress = (float)steamProgress.uPercentDone / (100.0f * STEAM_PROGRESS_PERCENT_SCALE);
}
else
{
*progress = 0;
}
*complete = false;
return (steamProgress.bValid != false);
}
//-----------------------------------------------------------------------------
// Purpose: steam call, unnecessary in stdio
//-----------------------------------------------------------------------------
void CFileSystem_Steam::CancelWaitForResources( WaitForResourcesHandle_t handle )
{
// check to see if they're using an old handle
if (m_iCurrentReturnedCallHandle != handle)
return;
if (m_hWaitForResourcesCallHandle == STEAM_INVALID_CALL_HANDLE)
return;
TSteamError steamError;
steam->AbortCall(m_hWaitForResourcesCallHandle, &steamError);
m_hWaitForResourcesCallHandle = STEAM_INVALID_CALL_HANDLE;
}
//-----------------------------------------------------------------------------
// Purpose: helper for posix file handle wrapper
//-----------------------------------------------------------------------------
#ifdef POSIX
FILE *GetFileHandle( CSteamFile *steamFile )
{
if ( !steamFile )
return NULL;
return (FILE *)steamFile->Handle();
}
bool BWriteable( CSteamFile *steamFile )
{
return steamFile && steamFile->BWriteable();
}
#endif
//-----------------------------------------------------------------------------
// Purpose: low-level filesystem wrapper
//-----------------------------------------------------------------------------
void CFileSystem_Steam::FS_fclose( FILE *fp )
{
#ifdef POSIX
CSteamFile *steamFile = (CSteamFile *)fp;
fp = GetFileHandle( steamFile );
if ( BWriteable( steamFile ) )
{
int fd = fileno_unlocked( fp );
fflush( fp );
flock( fd, LOCK_UN );
int iLockID = m_LockedFDMap.Find( fd );
if ( iLockID != m_LockedFDMap.InvalidIndex() )
m_LockedFDMap[ iLockID ] = -1;
fclose( fp );
}
else
{
#endif
TSteamError steamError;
steam->CloseFile((SteamHandle_t)fp, &steamError);
CheckError( (SteamHandle_t)fp, steamError );
#ifdef POSIX
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: low-level filesystem wrapper
//-----------------------------------------------------------------------------
void CFileSystem_Steam::FS_fseek( FILE *fp, int64 pos, int seekType )
{
#ifdef POSIX
CSteamFile *steamFile = (CSteamFile *)fp;
fp = GetFileHandle( steamFile );
if ( BWriteable( steamFile ) )
{
fseek( fp, pos, seekType );
}
else
{
#endif
TSteamError steamError;
int result;
result = steam->SeekFile((SteamHandle_t)fp, (int32)pos, (ESteamSeekMethod)seekType, &steamError);
CheckError((SteamHandle_t)fp, steamError);
#ifdef POSIX
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: low-level filesystem wrapper
//-----------------------------------------------------------------------------
long CFileSystem_Steam::FS_ftell( FILE *fp )
{
#ifdef POSIX
CSteamFile *steamFile = (CSteamFile *)fp;
fp = GetFileHandle( steamFile );
if ( BWriteable( steamFile ) )
{
return ftell(fp);
}
else
{
#endif
long steam_offset;
TSteamError steamError;
steam_offset = steam->TellFile((SteamHandle_t)fp, &steamError);
if ( steamError.eSteamError != eSteamErrorNone )
{
CheckError((SteamHandle_t)fp, steamError);
return -1L;
}
return steam_offset;
#ifdef POSIX
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: low-level filesystem wrapper
//-----------------------------------------------------------------------------
int CFileSystem_Steam::FS_feof( FILE *fp )
{
#ifdef POSIX
CSteamFile *steamFile = (CSteamFile *)fp;
fp = GetFileHandle( steamFile );
if ( BWriteable( steamFile ) )
{
return feof(fp);
}
else
{
#endif
long orig_pos;
// Figure out where in the file we currently are...
orig_pos = FS_ftell(fp);
if ( (SteamHandle_t)fp == g_pLastErrorFile && g_tLastError.eSteamError == eSteamErrorEOF )
return 1;
if ( g_tLastError.eSteamError != eSteamErrorNone )
return 0;
// Jump to the end...
FS_fseek(fp, 0L, SEEK_END);
// If we were already at the end, return true
if ( orig_pos == FS_ftell(fp) )
return 1;
// Otherwise, go back to the original spot and return false.
FS_fseek(fp, orig_pos, SEEK_SET);
return 0;
#ifdef POSIX
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: low-level filesystem wrapper
//-----------------------------------------------------------------------------
size_t CFileSystem_Steam::FS_fread( void *dest, size_t destSize, size_t size, FILE *fp )
{
#ifdef POSIX
CSteamFile *steamFile = (CSteamFile *)fp;
fp = GetFileHandle( steamFile );
if ( BWriteable( steamFile ) )
{
return fread( dest, 1, size, fp );
}
else
{
#endif
TSteamError steamError;
int blocksRead = steam->ReadFile(dest, 1, size, (SteamHandle_t)fp, &steamError);
CheckError((SteamHandle_t)fp, steamError);
return blocksRead; // steam reads in atomic blocks of "size" bytes
#ifdef POSIX
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: low-level filesystem wrapper
//-----------------------------------------------------------------------------
size_t CFileSystem_Steam::FS_fwrite( const void *src, size_t size, FILE *fp )
{
#ifdef POSIX
CSteamFile *steamFile = (CSteamFile *)fp;
fp = GetFileHandle( steamFile );
if ( BWriteable( steamFile ) )
{
#define WRITE_CHUNK (256 * 1024)
if ( size > WRITE_CHUNK )
{
size_t remaining = size;
const byte* current = (const byte *) src;
size_t total = 0;
while ( remaining > 0 )
{
size_t bytesToCopy = min(remaining, WRITE_CHUNK);
total += fwrite(current, 1, bytesToCopy, fp);
remaining -= bytesToCopy;
current += bytesToCopy;
}
Assert( total == size );
return total;
}
return fwrite(src, 1, size, fp);// return number of bytes written (because we have size = 1, count = bytes, so it return bytes)
}
else
{
#endif
TSteamError steamError;
int result = steam->WriteFile(src, 1, size, (SteamHandle_t)fp, &steamError);
CheckError((SteamHandle_t)fp, steamError);
return result;
#ifdef POSIX
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: low-level filesystem wrapper
//-----------------------------------------------------------------------------
size_t CFileSystem_Steam::FS_vfprintf( FILE *fp, const char *fmt, va_list list )
{
#ifdef POSIX
CSteamFile *steamFile = (CSteamFile *)fp;
fp = GetFileHandle( steamFile );
if ( BWriteable( steamFile ) )
{
return vfprintf(fp, fmt, list);
}
else
{
#endif
int blen, plen;
char *buf;
if ( !fp || !fmt )
return 0;
// Open the null device...used by vfprintf to determine the length of
// the formatted string.
FILE *nullDeviceFP = fopen("nul:", "w");
if ( !nullDeviceFP )
return 0;
// Figure out how long the formatted string will be...dump formatted
// string to the bit bucket.
blen = vfprintf(nullDeviceFP, fmt, list);
fclose(nullDeviceFP);
if ( !blen )
{
return 0;
}
// Get buffer in which to build the formatted string.
buf = (char *)malloc(blen+1);
if ( !buf )
{
return 0;
}
// Build the formatted string.
plen = _vsnprintf(buf, blen, fmt, list);
va_end(list);
if ( plen != blen )
{
free(buf);
return 0;
}
buf[ blen ] = 0;
// Write out the formatted string.
if ( plen != (int)FS_fwrite(buf, plen, fp) )
{
free(buf);
return 0;
}
free(buf);
return plen;
#ifdef POSIX