/
FileSystem.cpp
2565 lines (2318 loc) · 68.6 KB
/
FileSystem.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
/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2013-2016, Daemon Developers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Daemon developers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL DAEMON DEVELOPERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===========================================================================
*/
#include "minizip/unzip.h"
#ifdef BUILD_VM
#include "shared/VMMain.h"
#else
#include "engine/qcommon/qcommon.h"
#endif
#include "IPC/CommonSyscalls.h"
#ifdef _WIN32
#include <windows.h>
#include <shlobj.h>
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#undef MoveFile
#undef CopyFile
#undef DeleteFile
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#endif
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
Log::Logger fsLogs(VM_STRING_PREFIX "fs", "[FS]", Log::Level::NOTICE);
// SerializeTraits for PakInfo/LoadedPakInfo
namespace Util {
template<> struct SerializeTraits<FS::PakInfo> {
static void Write(Writer& stream, const FS::PakInfo& value)
{
stream.Write<std::string>(value.name);
stream.Write<std::string>(value.version);
stream.Write<Util::optional<uint32_t>>(value.checksum);
stream.Write<uint32_t>(Util::ordinal(value.type));
stream.Write<std::string>(value.path);
}
static FS::PakInfo Read(Reader& stream)
{
FS::PakInfo value;
value.name = stream.Read<std::string>();
value.version = stream.Read<std::string>();
value.checksum = stream.Read<Util::optional<uint32_t>>();
value.type = static_cast<FS::pakType_t>(stream.Read<uint32_t>());
value.path = stream.Read<std::string>();
return value;
}
};
template<> struct SerializeTraits<FS::LoadedPakInfo> {
static void Write(Writer& stream, const FS::LoadedPakInfo& value)
{
stream.Write<std::string>(value.name);
stream.Write<std::string>(value.version);
stream.Write<Util::optional<uint32_t>>(value.checksum);
stream.Write<uint32_t>(Util::ordinal(value.type));
stream.Write<std::string>(value.path);
stream.Write<Util::optional<uint32_t>>(value.realChecksum);
stream.Write<uint64_t>(std::chrono::system_clock::to_time_t(value.timestamp));
stream.Write<bool>(value.fd != -1);
if (value.fd != -1)
stream.Write<IPC::FileHandle>(IPC::FileHandle(value.fd, IPC::FileOpenMode::MODE_READ));
stream.Write<std::string>(value.pathPrefix);
}
static FS::LoadedPakInfo Read(Reader& stream)
{
FS::LoadedPakInfo value;
value.name = stream.Read<std::string>();
value.version = stream.Read<std::string>();
value.checksum = stream.Read<Util::optional<uint32_t>>();
value.type = static_cast<FS::pakType_t>(stream.Read<uint32_t>());
value.path = stream.Read<std::string>();
value.realChecksum = stream.Read<Util::optional<uint32_t>>();
value.timestamp = std::chrono::system_clock::from_time_t(stream.Read<uint64_t>());
if (stream.Read<bool>())
value.fd = stream.Read<IPC::FileHandle>().GetHandle();
else
value.fd = -1;
value.pathPrefix = stream.Read<std::string>();
return value;
}
};
} // namespace Util
namespace FS {
// Pak zip and directory extensions
#define PAK_ZIP_EXT ".pk3"
#define PAK_DIR_EXT ".pk3dir/"
// Error variable used by throws(). This is never written to and always
// represents a success value.
std::error_code throw_err;
// Dependencies file in packages
#define PAK_DEPS_FILE "DEPS"
// Whether the search paths have been initialized yet. This can be used to delay
// writing log files until the filesystem is initialized.
static bool isInitialized = false;
// Pak search paths
static std::vector<std::string> pakPaths;
// Library & executable path
static std::string libPath;
// Home path
static std::string homePath;
// List of available paks
static std::vector<PakInfo> availablePaks;
// Clean up platform compatibility issues
enum class openMode_t {
MODE_READ,
MODE_WRITE,
MODE_APPEND,
MODE_EDIT
};
inline int my_open(Str::StringRef path, openMode_t mode)
{
int mode_ = Util::ordinal(mode);
int modes[] = {O_RDONLY, O_WRONLY | O_TRUNC | O_CREAT, O_WRONLY | O_APPEND | O_CREAT, O_RDWR | O_CREAT};
#ifdef _WIN32
// Allow open files to be deleted & renamed
DWORD access[] = {GENERIC_READ, GENERIC_WRITE, GENERIC_WRITE, GENERIC_READ | GENERIC_WRITE};
DWORD create[] = {OPEN_EXISTING, CREATE_ALWAYS, OPEN_ALWAYS, OPEN_ALWAYS};
HANDLE h = CreateFileW(Str::UTF8To16(path).c_str(), access[mode_], FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, create[mode_], FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) {
_doserrno = GetLastError();
errno = _doserrno == ERROR_FILE_NOT_FOUND || _doserrno == ERROR_PATH_NOT_FOUND ? ENOENT : 0; // Needed to check if we need to create the path
return -1;
}
int fd = _open_osfhandle(reinterpret_cast<intptr_t>(h), modes[mode_] | O_BINARY | O_NOINHERIT);
if (fd == -1)
CloseHandle(h);
#elif defined(__APPLE__)
// O_CLOEXEC is supported from 10.7 onwards
int fd = open(path.c_str(), modes[mode_] | O_CLOEXEC, 0666);
#elif defined(__linux__)
int fd = open64(path.c_str(), modes[mode_] | O_CLOEXEC | O_LARGEFILE, 0666);
#elif defined(__native_client__)
// This doesn't actually work, but it's not used anyways
int fd = open(path.c_str(), modes[mode_], 0666);
#endif
#ifndef _WIN32
// Don't allow opening directories
if (mode == openMode_t::MODE_READ && fd != -1) {
struct stat st;
if (fstat(fd, &st) == -1) {
close(fd);
return -1;
}
if (S_ISDIR(st.st_mode)) {
close(fd);
errno = EISDIR;
return -1;
}
}
#endif
return fd;
}
inline FILE* my_fopen(Str::StringRef path, openMode_t mode)
{
int fd = my_open(path, mode);
if (fd == -1)
return nullptr;
const char* modes[] = {"rb", "wb", "ab", "rb+"};
int mode_ = Util::ordinal(mode);
FILE* fp = fdopen(fd, modes[mode_]);
if (!fp)
close(fd);
return fp;
}
inline offset_t my_ftell(FILE* fd)
{
#ifdef _WIN32
return _ftelli64(fd);
#elif defined(__APPLE__) || defined(__native_client__)
return ftello(fd);
#elif defined(__linux__)
return ftello64(fd);
#endif
}
inline int my_fseek(FILE* fd, offset_t off, int whence)
{
#ifdef _WIN32
return _fseeki64(fd, off, whence);
#elif defined(__APPLE__) || defined(__native_client__)
return fseeko(fd, off, whence);
#elif defined(__linux__)
return fseeko64(fd, off, whence);
#endif
}
#ifdef _WIN32
typedef struct _stati64 my_stat_t;
#elif defined(__APPLE__) || defined(__native_client__)
using my_stat_t = struct stat;
#elif defined(__linux__)
using my_stat_t = struct stat64;
#endif
inline int my_fstat(int fd, my_stat_t* st)
{
#ifdef _WIN32
return _fstati64(fd, st);
#elif defined(__APPLE__) || defined(__native_client__)
return fstat(fd, st);
#elif defined(__linux__)
return fstat64(fd, st);
#endif
}
inline int my_stat(Str::StringRef path, my_stat_t* st)
{
#ifdef _WIN32
return _wstati64(Str::UTF8To16(path).c_str(), st);
#elif defined(__APPLE__) || defined(__native_client__)
return stat(path.c_str(), st);
#elif defined(__linux__)
return stat64(path.c_str(), st);
#endif
}
inline intptr_t my_pread(int fd, void* buf, size_t count, offset_t offset)
{
#ifdef _WIN32
OVERLAPPED overlapped;
DWORD bytesRead;
memset(&overlapped, 0, sizeof(overlapped));
overlapped.Offset = offset & 0xffffffff;
overlapped.OffsetHigh = offset >> 32;
if (!ReadFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd)), buf, count, &bytesRead, &overlapped)) {
_doserrno = GetLastError();
return -1;
}
return bytesRead;
#elif defined(__APPLE__) || defined(__native_client__)
return pread(fd, buf, count, offset);
#elif defined(__linux__)
return pread64(fd, buf, count, offset);
#endif
}
// std::error_code support for minizip
class minizip_category_impl: public std::error_category
{
public:
virtual const char* name() const NOEXCEPT OVERRIDE FINAL
{
return "unzip";
}
virtual std::string message(int ev) const OVERRIDE FINAL
{
switch (ev) {
case UNZ_OK:
return "Success";
case UNZ_END_OF_LIST_OF_FILE:
return "End of list of file";
case UNZ_ERRNO:
return "I/O error";
case UNZ_PARAMERROR:
return "Invalid parameter";
case UNZ_BADZIPFILE:
return "Bad zip file";
case UNZ_INTERNALERROR:
return "Internal error";
case UNZ_CRCERROR:
return "CRC error";
default:
return "Unknown error";
}
}
};
static const minizip_category_impl& minizip_category()
{
static minizip_category_impl instance;
return instance;
}
// Filesystem-specific error codes
enum class filesystem_error {
no_filesystem_error,
invalid_filename,
no_such_file,
no_such_directory,
wrong_pak_checksum,
missing_dependency
};
class filesystem_category_impl: public std::error_category
{
public:
virtual const char* name() const NOEXCEPT OVERRIDE FINAL
{
return "filesystem";
}
virtual std::string message(int ev) const OVERRIDE FINAL
{
switch (Util::enum_cast<filesystem_error>(ev)) {
case filesystem_error::invalid_filename:
return "Filename contains invalid characters";
case filesystem_error::no_such_file:
return "No such file";
case filesystem_error::no_such_directory:
return "No such directory";
case filesystem_error::wrong_pak_checksum:
return "Pak checksum incorrect";
case filesystem_error::missing_dependency:
return "Missing dependency";
default:
return "Unknown error";
}
}
};
static const filesystem_category_impl& filesystem_category()
{
static filesystem_category_impl instance;
return instance;
}
// Support code for error handling
static void SetErrorCode(std::error_code& err, int ec, const std::error_category& ecat)
{
std::error_code ecode(ec, ecat);
if (&err == &throws())
throw std::system_error(ecode);
else
err = ecode;
}
static void ClearErrorCode(std::error_code& err)
{
if (&err != &throws())
err = std::error_code();
}
static void SetErrorCodeSystem(std::error_code& err)
{
#ifdef _WIN32
SetErrorCode(err, _doserrno, std::system_category());
#else
SetErrorCode(err, errno, std::generic_category());
#endif
}
static void SetErrorCodeFilesystem(std::error_code& err, filesystem_error ec)
{
SetErrorCode(err, Util::ordinal(ec), filesystem_category());
}
static void SetErrorCodeZlib(std::error_code& err, int num)
{
if (num == UNZ_ERRNO)
SetErrorCodeSystem(err);
else
SetErrorCode(err, num, minizip_category());
}
// Determine whether a character is a OS-dependent path separator
inline bool isdirsep(unsigned int c)
{
#ifdef _WIN32
return c == '/' || c == '\\';
#else
return c == '/';
#endif
}
namespace Path {
bool IsValid(Str::StringRef path, bool allowDir)
{
char prev = '/';
for (char c: path) {
// Check if the character is allowed
if (!Str::cisalnum(c) && c != '/' && c != '-' && c != '_' && c != '.' && c != '+' && c != '~')
return false;
// Disallow 2 consecutive / or .
if ((c == '/' || c == '.') && (prev == '/' || prev == '.'))
return false;
prev = c;
}
// An empty path or a path ending with / is a directory
if (prev == '/' && !allowDir)
return false;
// Disallow paths ending with .
if (prev == '.')
return false;
return true;
}
std::string Build(Str::StringRef base, Str::StringRef path)
{
if (base.empty())
return path;
if (path.empty())
return base;
std::string out;
out.reserve(base.size() + 1 + path.size());
out.assign(base.data(), base.size());
if (!isdirsep(out.back()))
out.push_back('/');
out.append(path.data(), path.size());
return out;
}
std::string DirName(Str::StringRef path)
{
if (path.empty())
return "";
// Trim to last slash, excluding any trailing slash
size_t lastSlash = path.rfind('/', path.size() - 2);
if (lastSlash != Str::StringRef::npos)
return path.substr(0, lastSlash);
else
return "";
}
std::string BaseName(Str::StringRef path)
{
if (path.empty())
return "";
// Trim from last slash, excluding any trailing slash
size_t lastSlash = path.rfind('/', path.size() - 2);
return path.substr(lastSlash + 1);
}
std::string Extension(Str::StringRef path)
{
if (path.empty())
return "";
if (path.back() == '/')
return "/";
// Find a dot or slash, searching from the end of the string
for (const char* p = path.end(); p != path.begin(); p--) {
if (p[-1] == '/')
return "";
if (p[-1] == '.')
return std::string(p - 1, path.end());
}
return "";
}
std::string StripExtension(Str::StringRef path)
{
if (path.empty())
return "";
if (path.back() == '/')
return path.substr(path.size() - 1);
// Find a dot or slash, searching from the end of the string
for (const char* p = path.end(); p != path.begin(); p--) {
if (p[-1] == '/')
return path;
if (p[-1] == '.')
return std::string(path.begin(), p - 1);
}
return path;
}
std::string BaseNameStripExtension(Str::StringRef path)
{
if (path.empty())
return "";
// Find a dot or slash, searching from the end of the string
const char* end = path.end();
if (path.back() == '/')
end = path.end() - 1;
for (const char* p = end; p != path.begin(); p--) {
if (p[-1] == '/')
return std::string(p, end);
if (p[-1] == '.' && end == path.end())
end = p - 1;
}
return std::string(path.begin(), end);
}
} // namespace Path
void File::Close(std::error_code& err)
{
if (fd) {
// Always clear fd, even if we throw an exception
FILE* tmp = fd;
fd = nullptr;
if (fclose(tmp) != 0)
SetErrorCodeSystem(err);
else
ClearErrorCode(err);
}
}
offset_t File::Length(std::error_code& err) const
{
my_stat_t st;
if (my_fstat(fileno(fd), &st) != 0) {
SetErrorCodeSystem(err);
return 0;
} else {
ClearErrorCode(err);
return st.st_size;
}
}
std::chrono::system_clock::time_point File::Timestamp(std::error_code& err) const
{
my_stat_t st;
if (my_fstat(fileno(fd), &st) != 0) {
SetErrorCodeSystem(err);
return {};
} else {
ClearErrorCode(err);
return std::chrono::system_clock::from_time_t(std::max(st.st_ctime, st.st_mtime));
}
}
void File::SeekCur(offset_t off, std::error_code& err) const
{
if (my_fseek(fd, off, SEEK_CUR) != 0)
SetErrorCodeSystem(err);
else
ClearErrorCode(err);
}
void File::SeekSet(offset_t off, std::error_code& err) const
{
if (my_fseek(fd, off, SEEK_SET) != 0)
SetErrorCodeSystem(err);
else
ClearErrorCode(err);
}
void File::SeekEnd(offset_t off, std::error_code& err) const
{
if (my_fseek(fd, off, SEEK_END) != 0)
SetErrorCodeSystem(err);
else
ClearErrorCode(err);
}
offset_t File::Tell() const
{
return my_ftell(fd);
}
size_t File::Read(void* buffer, size_t length, std::error_code& err) const
{
size_t result = fread(buffer, 1, length, fd);
if (result != length && ferror(fd))
SetErrorCodeSystem(err);
else
ClearErrorCode(err);
return result;
}
void File::Write(const void* data, size_t length, std::error_code& err) const
{
if (fwrite(data, 1, length, fd) != length)
SetErrorCodeSystem(err);
else
ClearErrorCode(err);
}
void File::Flush(std::error_code& err) const
{
if (fflush(fd) != 0)
SetErrorCodeSystem(err);
else
ClearErrorCode(err);
}
std::string File::ReadAll(std::error_code& err) const
{
std::string out;
offset_t length = Length(err);
if (err)
return out;
out.resize(length);
auto actual = Read(&out[0], length, err);
// The size of data read may not always match the file size even if just obtained.
// One reason is that if a file is opened in text mode on Windows \r\n's
// are translated into shorter \n on read/fread resulting in an overall
// smaller string in memory than what is on disk.
// So we resize the string to lose the excess data and ensure the
// string's length() matches it's valid content as actually read.
out.resize(actual);
return out;
}
void File::CopyTo(const File& dest, std::error_code& err) const
{
char buffer[65536];
while (true) {
size_t read = Read(buffer, sizeof(buffer), err);
if (err || read == 0)
return;
dest.Write(buffer, read, err);
if (err)
return;
}
}
void File::SetLineBuffered(bool enable, std::error_code& err) const
{
if (setvbuf(fd, nullptr, enable ? _IOLBF : _IOFBF, BUFSIZ) != 0)
SetErrorCodeSystem(err);
else
ClearErrorCode(err);
}
#ifdef BUILD_VM
// Convert an IPC file handle to a File object
static File FileFromIPC(Util::optional<IPC::OwnedFileHandle> ipcFile, openMode_t mode, std::error_code& err)
{
if (!ipcFile) {
SetErrorCodeFilesystem(err, filesystem_error::no_such_file);
return File();
}
int fd = ipcFile->GetHandle();
const char* modes[] = {"rb", "wb", "ab", "rb+"};
FILE* fp = fdopen(fd, modes[Util::ordinal(mode)]);
if (!fp) {
close(fd);
SetErrorCodeSystem(err);
return File();
}
return File(fp);
}
#endif
#ifdef BUILD_ENGINE
// Convert a File object to an ipc file handle
static IPC::OwnedFileHandle FileToIPC(File file, openMode_t mode)
{
IPC::FileOpenMode ipcMode;
switch (mode) {
default:
case openMode_t::MODE_READ:
ipcMode = IPC::FileOpenMode::MODE_READ;
break;
case openMode_t::MODE_WRITE:
ipcMode = IPC::FileOpenMode::MODE_WRITE;
break;
case openMode_t::MODE_APPEND:
ipcMode = IPC::FileOpenMode::MODE_WRITE_APPEND;
break;
case openMode_t::MODE_EDIT:
ipcMode = IPC::FileOpenMode::MODE_RW;
break;
}
int newfd = dup(fileno(file.GetHandle()));
if (newfd == -1)
return IPC::OwnedFileHandle();
return IPC::OwnedFileHandle(newfd, ipcMode);
}
#endif
// Workaround for GCC 4.7.2 bug: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=55015
namespace {
// Class representing an open zip archive
class ZipArchive {
public:
ZipArchive()
: zipFile(nullptr) {}
// Noncopyable
ZipArchive(const ZipArchive&) = delete;
ZipArchive& operator=(const ZipArchive&) = delete;
ZipArchive(ZipArchive&& other)
: zipFile(other.zipFile)
{
other.zipFile = nullptr;
}
ZipArchive& operator=(ZipArchive&& other)
{
std::swap(zipFile, other.zipFile);
return *this;
}
// Close archive
~ZipArchive()
{
if (zipFile)
unzClose(zipFile);
}
// Open an archive from an existing file descriptor
static ZipArchive Open(int fd, std::error_code& err)
{
// Initialize the zlib I/O functions
zlib_filefunc64_def funcs;
struct zipData_t {
int fd;
char buffer[1024];
offset_t pos;
offset_t bufferPos;
offset_t bufferLen;
offset_t fileLen;
};
funcs.zopen64_file = [](voidpf opaque, const void* filename, int mode) -> voidpf {
// Just forward the filename as the stream handle
Q_UNUSED(opaque);
Q_UNUSED(mode);
return const_cast<void*>(filename);
};
funcs.zread_file = [](voidpf opaque, voidpf stream, void* buf, uLong size) -> uLong {
Q_UNUSED(opaque);
zipData_t* zipData = static_cast<zipData_t*>(stream);
// Use pread directly for large reads
if (size > sizeof(zipData->buffer)) {
intptr_t result = my_pread(zipData->fd, buf, size, zipData->pos);
if (result == -1)
return 0;
zipData->pos += result;
return result;
}
// Refill the buffer if the request can't be satisfied from it
if (zipData->pos < zipData->bufferPos || zipData->pos + (long) size > zipData->bufferPos + zipData->bufferLen) {
intptr_t result = my_pread(zipData->fd, zipData->buffer, sizeof(zipData->buffer), zipData->pos);
if (result == -1)
return 0;
zipData->bufferPos = zipData->pos;
zipData->bufferLen = result;
}
// Read from the buffer, but handle short reads
size_t offset = zipData->pos - zipData->bufferPos;
size_t readLen = zipData->bufferLen - offset < size ? zipData->bufferLen - offset : size;
memcpy(buf, zipData->buffer + offset, readLen);
zipData->pos += readLen;
return readLen;
};
funcs.zwrite_file = nullptr; // Writing to zip files is not supported
funcs.ztell64_file = [](voidpf opaque, voidpf stream) -> ZPOS64_T {
Q_UNUSED(opaque);
zipData_t* zipData = static_cast<zipData_t*>(stream);
return zipData->pos;
};
funcs.zseek64_file = [](voidpf opaque, voidpf stream, ZPOS64_T offset, int origin) -> long {
Q_UNUSED(opaque);
zipData_t* zipData = static_cast<zipData_t*>(stream);
switch (origin) {
case ZLIB_FILEFUNC_SEEK_CUR:
zipData->pos += offset;
break;
case ZLIB_FILEFUNC_SEEK_END:
zipData->pos = zipData->fileLen + offset;
break;
case ZLIB_FILEFUNC_SEEK_SET:
zipData->pos = offset;
break;
default:
errno = EINVAL;
return -1;
}
return 0;
};
funcs.zclose_file = [](voidpf opaque, voidpf stream) -> int {
Q_UNUSED(opaque);
zipData_t* zipData = static_cast<zipData_t*>(stream);
delete zipData;
return 0;
};
funcs.zerror_file = [](voidpf opaque, voidpf stream) -> int {
Q_UNUSED(opaque);
zipData_t* zipData = static_cast<zipData_t*>(stream);
return zipData->pos >= zipData->fileLen;
};
// Get the file length
my_stat_t st;
if (my_fstat(fd, &st) == -1) {
SetErrorCodeSystem(err);
return ZipArchive();
}
// Open the zip with zlib
zipData_t* zipData = new zipData_t;
zipData->fd = fd;
zipData->pos = 0;
zipData->bufferPos = 0;
zipData->bufferLen = 0;
zipData->fileLen = st.st_size;
unzFile zipFile = unzOpen2_64(zipData, &funcs);
if (!zipFile) {
// Unfortunately unzOpen doesn't return an error code, so we assume UNZ_BADZIPFILE
SetErrorCodeZlib(err, UNZ_BADZIPFILE);
return ZipArchive();
}
ClearErrorCode(err);
ZipArchive out;
out.zipFile = zipFile;
return out;
}
// Iterate through all the files in the archive and invoke the callback.
// Callback signature: void(Str::StringRef filename, offset_t offset, uint32_t crc)
template<typename Func> void ForEachFile(Func&& func, std::error_code& err)
{
unz_global_info64 globalInfo;
int result = unzGetGlobalInfo64(zipFile, &globalInfo);
if (result != UNZ_OK) {
SetErrorCodeZlib(err, result);
return;
}
result = unzGoToFirstFile(zipFile);
if (result != UNZ_OK) {
SetErrorCodeZlib(err, result);
return;
}
for (ZPOS64_T i = 0; i != globalInfo.number_entry; i++) {
unz_file_info64 fileInfo;
char filename[65537]; // The zip format has a maximum filename size of 64K
result = unzGetCurrentFileInfo64(zipFile, &fileInfo, filename, sizeof(filename), nullptr, 0, nullptr, 0);
if (result != UNZ_OK) {
SetErrorCodeZlib(err, result);
return;
}
offset_t offset = unzGetOffset64(zipFile);
uint32_t crc = fileInfo.crc;
func(filename, offset, crc);
if (i + 1 != globalInfo.number_entry) {
result = unzGoToNextFile(zipFile);
if (result != UNZ_OK) {
SetErrorCodeZlib(err, result);
return;
}
}
}
ClearErrorCode(err);
}
// Open a file in the archive
void OpenFile(offset_t offset, std::error_code& err) const
{
// Set position in zip
int result = unzSetOffset64(zipFile, offset);
if (result != UNZ_OK) {
SetErrorCodeZlib(err, result);
return;
}
// Open file in zip
result = unzOpenCurrentFile(zipFile);
if (result != UNZ_OK)
SetErrorCodeZlib(err, result);
else
ClearErrorCode(err);
}
// Get the length of the currently open file
offset_t FileLength(std::error_code& err) const
{
unz_file_info64 fileInfo;
int result = unzGetCurrentFileInfo64(zipFile, &fileInfo, nullptr, 0, nullptr, 0, nullptr, 0);
if (result != UNZ_OK) {
SetErrorCodeZlib(err, result);
return 0;
}
ClearErrorCode(err);
return fileInfo.uncompressed_size;
}
// Read from the currently open file
size_t ReadFile(void* buffer, size_t length, std::error_code& err) const
{
// zlib read returns an int, which means that we can only read 2G at once
size_t read = 0;
while (read != length) {
size_t currentRead = std::min<size_t>(length - read, INT_MAX);
int result = unzReadCurrentFile(zipFile, buffer, currentRead);
if (result < 0) {
SetErrorCodeZlib(err, result);
return read;
}
if (result == 0)
break;
buffer = static_cast<char*>(buffer) + result;
read += result;
}
ClearErrorCode(err);
return read;
}
// Close the currently open file and check for CRC errors
void CloseFile(std::error_code& err) const
{
int result = unzCloseCurrentFile(zipFile);
if (result != UNZ_OK)
SetErrorCodeZlib(err, result);
else
ClearErrorCode(err);
}
private:
unzFile zipFile;
};
} // GCC bug workaround
namespace PakPath {
// List of loaded pak files
static std::vector<LoadedPakInfo> loadedPaks;
// Guard object to ensure that the fds in loadedPaks are closed on shutdown
struct LoadedPakGuard {
~LoadedPakGuard() {
for (LoadedPakInfo& x: loadedPaks) {
if (x.fd != -1)
close(x.fd);
}
}
};
static LoadedPakGuard loadedPaksGuard;
// Map of filenames to pak files. The size_t is an offset into loadedPaks and
// the offset_t is the position within the zip archive (unused for PAK_DIR).
static std::unordered_map<std::string, std::pair<uint32_t, offset_t>> fileMap;
#ifndef BUILD_VM
// Parse the dependencies file of a package
// Each line of the dependencies file is a name followed by an optional version
static void ParseDeps(const PakInfo& parent, Str::StringRef depsData, std::error_code& err)
{
auto lineStart = depsData.begin();
int line = 0;
while (lineStart != depsData.end()) {
// Get the end of the line or the end of the file
line++;
auto lineEnd = std::find(lineStart, depsData.end(), '\n');
// Skip spaces
while (lineStart != lineEnd && Str::cisspace(*lineStart))
lineStart++;
if (lineStart == lineEnd) {
lineStart = lineEnd == depsData.end() ? lineEnd : lineEnd + 1;
continue;
}
// Read the package name
std::string name;
while (lineStart != lineEnd && !Str::cisspace(*lineStart))
name.push_back(*lineStart++);
// Skip spaces
while (lineStart != lineEnd && Str::cisspace(*lineStart))
lineStart++;
// If this is the end of the line, load a package by name
if (lineStart == lineEnd) {
const PakInfo* pak = FindPak(name);
if (!pak) {
fsLogs.Warn("Could not find pak '%s' required by '%s'", name, parent.path);
SetErrorCodeFilesystem(err, filesystem_error::missing_dependency);