Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/core/io/file_access_pack.cpp
9973 views
1
/**************************************************************************/
2
/* file_access_pack.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#include "file_access_pack.h"
32
33
#include "core/io/file_access_encrypted.h"
34
#include "core/object/script_language.h"
35
#include "core/os/os.h"
36
#include "core/version.h"
37
38
Error PackedData::add_pack(const String &p_path, bool p_replace_files, uint64_t p_offset) {
39
for (int i = 0; i < sources.size(); i++) {
40
if (sources[i]->try_open_pack(p_path, p_replace_files, p_offset)) {
41
return OK;
42
}
43
}
44
45
return ERR_FILE_UNRECOGNIZED;
46
}
47
48
void PackedData::add_path(const String &p_pkg_path, const String &p_path, uint64_t p_ofs, uint64_t p_size, const uint8_t *p_md5, PackSource *p_src, bool p_replace_files, bool p_encrypted, bool p_bundle) {
49
String simplified_path = p_path.simplify_path().trim_prefix("res://");
50
PathMD5 pmd5(simplified_path.md5_buffer());
51
52
bool exists = files.has(pmd5);
53
54
PackedFile pf;
55
pf.encrypted = p_encrypted;
56
pf.bundle = p_bundle;
57
pf.pack = p_pkg_path;
58
pf.offset = p_ofs;
59
pf.size = p_size;
60
for (int i = 0; i < 16; i++) {
61
pf.md5[i] = p_md5[i];
62
}
63
pf.src = p_src;
64
65
if (!exists || p_replace_files) {
66
files[pmd5] = pf;
67
}
68
69
if (!exists) {
70
// Search for directory.
71
PackedDir *cd = root;
72
73
if (simplified_path.contains_char('/')) { // In a subdirectory.
74
Vector<String> ds = simplified_path.get_base_dir().split("/");
75
76
for (int j = 0; j < ds.size(); j++) {
77
if (!cd->subdirs.has(ds[j])) {
78
PackedDir *pd = memnew(PackedDir);
79
pd->name = ds[j];
80
pd->parent = cd;
81
cd->subdirs[pd->name] = pd;
82
cd = pd;
83
} else {
84
cd = cd->subdirs[ds[j]];
85
}
86
}
87
}
88
String filename = simplified_path.get_file();
89
// Don't add as a file if the path points to a directory.
90
if (!filename.is_empty()) {
91
cd->files.insert(filename);
92
}
93
}
94
}
95
96
void PackedData::remove_path(const String &p_path) {
97
String simplified_path = p_path.simplify_path().trim_prefix("res://");
98
PathMD5 pmd5(simplified_path.md5_buffer());
99
if (!files.has(pmd5)) {
100
return;
101
}
102
103
// Search for directory.
104
PackedDir *cd = root;
105
106
if (simplified_path.contains_char('/')) { // In a subdirectory.
107
Vector<String> ds = simplified_path.get_base_dir().split("/");
108
109
for (int j = 0; j < ds.size(); j++) {
110
if (!cd->subdirs.has(ds[j])) {
111
return; // Subdirectory does not exist, do not bother creating.
112
} else {
113
cd = cd->subdirs[ds[j]];
114
}
115
}
116
}
117
118
cd->files.erase(simplified_path.get_file());
119
120
files.erase(pmd5);
121
}
122
123
void PackedData::add_pack_source(PackSource *p_source) {
124
if (p_source != nullptr) {
125
sources.push_back(p_source);
126
}
127
}
128
129
uint8_t *PackedData::get_file_hash(const String &p_path) {
130
String simplified_path = p_path.simplify_path().trim_prefix("res://");
131
PathMD5 pmd5(simplified_path.md5_buffer());
132
HashMap<PathMD5, PackedFile, PathMD5>::Iterator E = files.find(pmd5);
133
if (!E) {
134
return nullptr;
135
}
136
137
return E->value.md5;
138
}
139
140
HashSet<String> PackedData::get_file_paths() const {
141
HashSet<String> file_paths;
142
_get_file_paths(root, root->name, file_paths);
143
return file_paths;
144
}
145
146
void PackedData::_get_file_paths(PackedDir *p_dir, const String &p_parent_dir, HashSet<String> &r_paths) const {
147
for (const String &E : p_dir->files) {
148
r_paths.insert(p_parent_dir.path_join(E));
149
}
150
151
for (const KeyValue<String, PackedDir *> &E : p_dir->subdirs) {
152
_get_file_paths(E.value, p_parent_dir.path_join(E.key), r_paths);
153
}
154
}
155
156
void PackedData::clear() {
157
files.clear();
158
_free_packed_dirs(root);
159
root = memnew(PackedDir);
160
}
161
162
PackedData::PackedData() {
163
singleton = this;
164
root = memnew(PackedDir);
165
166
add_pack_source(memnew(PackedSourcePCK));
167
}
168
169
void PackedData::_free_packed_dirs(PackedDir *p_dir) {
170
for (const KeyValue<String, PackedDir *> &E : p_dir->subdirs) {
171
_free_packed_dirs(E.value);
172
}
173
memdelete(p_dir);
174
}
175
176
PackedData::~PackedData() {
177
if (singleton == this) {
178
singleton = nullptr;
179
}
180
181
for (int i = 0; i < sources.size(); i++) {
182
memdelete(sources[i]);
183
}
184
_free_packed_dirs(root);
185
}
186
187
//////////////////////////////////////////////////////////////////
188
189
bool PackedSourcePCK::try_open_pack(const String &p_path, bool p_replace_files, uint64_t p_offset) {
190
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
191
if (f.is_null()) {
192
return false;
193
}
194
195
bool pck_header_found = false;
196
197
// Search for the header at the start offset - standalone PCK file.
198
f->seek(p_offset);
199
uint32_t magic = f->get_32();
200
if (magic == PACK_HEADER_MAGIC) {
201
pck_header_found = true;
202
}
203
204
// Search for the header in the executable "pck" section - self contained executable.
205
if (!pck_header_found) {
206
// Loading with offset feature not supported for self contained exe files.
207
if (p_offset != 0) {
208
ERR_FAIL_V_MSG(false, "Loading self-contained executable with offset not supported.");
209
}
210
211
int64_t pck_off = OS::get_singleton()->get_embedded_pck_offset();
212
if (pck_off != 0) {
213
// Search for the header, in case PCK start and section have different alignment.
214
for (int i = 0; i < 8; i++) {
215
f->seek(pck_off);
216
magic = f->get_32();
217
if (magic == PACK_HEADER_MAGIC) {
218
#ifdef DEBUG_ENABLED
219
print_verbose("PCK header found in executable pck section, loading from offset 0x" + String::num_int64(pck_off - 4, 16));
220
#endif
221
pck_header_found = true;
222
break;
223
}
224
pck_off++;
225
}
226
}
227
}
228
229
// Search for the header at the end of file - self contained executable.
230
if (!pck_header_found) {
231
// Loading with offset feature not supported for self contained exe files.
232
if (p_offset != 0) {
233
ERR_FAIL_V_MSG(false, "Loading self-contained executable with offset not supported.");
234
}
235
236
f->seek_end();
237
f->seek(f->get_position() - 4);
238
magic = f->get_32();
239
240
if (magic == PACK_HEADER_MAGIC) {
241
f->seek(f->get_position() - 12);
242
uint64_t ds = f->get_64();
243
f->seek(f->get_position() - ds - 8);
244
magic = f->get_32();
245
if (magic == PACK_HEADER_MAGIC) {
246
#ifdef DEBUG_ENABLED
247
print_verbose("PCK header found at the end of executable, loading from offset 0x" + String::num_int64(f->get_position() - 4, 16));
248
#endif
249
pck_header_found = true;
250
}
251
}
252
}
253
254
if (!pck_header_found) {
255
return false;
256
}
257
258
int64_t pck_start_pos = f->get_position() - 4;
259
260
// Read header.
261
uint32_t version = f->get_32();
262
uint32_t ver_major = f->get_32();
263
uint32_t ver_minor = f->get_32();
264
uint32_t ver_patch = f->get_32(); // Not used for validation.
265
266
ERR_FAIL_COND_V_MSG(version != PACK_FORMAT_VERSION_V3 && version != PACK_FORMAT_VERSION_V2, false, vformat("Pack version unsupported: %d.", version));
267
ERR_FAIL_COND_V_MSG(ver_major > GODOT_VERSION_MAJOR || (ver_major == GODOT_VERSION_MAJOR && ver_minor > GODOT_VERSION_MINOR), false, vformat("Pack created with a newer version of the engine: %d.%d.%d.", ver_major, ver_minor, ver_patch));
268
269
uint32_t pack_flags = f->get_32();
270
bool enc_directory = (pack_flags & PACK_DIR_ENCRYPTED);
271
bool rel_filebase = (pack_flags & PACK_REL_FILEBASE); // Note: Always enabled for V3.
272
bool sparse_bundle = (pack_flags & PACK_SPARSE_BUNDLE);
273
274
uint64_t file_base = f->get_64();
275
if ((version == PACK_FORMAT_VERSION_V3) || (version == PACK_FORMAT_VERSION_V2 && rel_filebase)) {
276
file_base += pck_start_pos;
277
}
278
279
if (version == PACK_FORMAT_VERSION_V3) {
280
// V3: Read directory offset and skip reserved part of the header.
281
uint64_t dir_offset = f->get_64() + pck_start_pos;
282
f->seek(dir_offset);
283
} else if (version == PACK_FORMAT_VERSION_V2) {
284
// V2: Directory directly after the header.
285
for (int i = 0; i < 16; i++) {
286
f->get_32(); // Reserved.
287
}
288
}
289
290
// Read directory.
291
int file_count = f->get_32();
292
if (enc_directory) {
293
Ref<FileAccessEncrypted> fae;
294
fae.instantiate();
295
ERR_FAIL_COND_V_MSG(fae.is_null(), false, "Can't open encrypted pack directory.");
296
297
Vector<uint8_t> key;
298
key.resize(32);
299
for (int i = 0; i < key.size(); i++) {
300
key.write[i] = script_encryption_key[i];
301
}
302
303
Error err = fae->open_and_parse(f, key, FileAccessEncrypted::MODE_READ, false);
304
ERR_FAIL_COND_V_MSG(err, false, "Can't open encrypted pack directory.");
305
f = fae;
306
}
307
308
for (int i = 0; i < file_count; i++) {
309
uint32_t sl = f->get_32();
310
CharString cs;
311
cs.resize_uninitialized(sl + 1);
312
f->get_buffer((uint8_t *)cs.ptr(), sl);
313
cs[sl] = 0;
314
315
String path = String::utf8(cs.ptr(), sl);
316
uint64_t ofs = f->get_64();
317
uint64_t size = f->get_64();
318
uint8_t md5[16];
319
f->get_buffer(md5, 16);
320
uint32_t flags = f->get_32();
321
322
if (flags & PACK_FILE_REMOVAL) { // The file was removed.
323
PackedData::get_singleton()->remove_path(path);
324
} else {
325
PackedData::get_singleton()->add_path(p_path, path, file_base + ofs, size, md5, this, p_replace_files, (flags & PACK_FILE_ENCRYPTED), sparse_bundle);
326
}
327
}
328
329
return true;
330
}
331
332
Ref<FileAccess> PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile *p_file) {
333
return memnew(FileAccessPack(p_path, *p_file));
334
}
335
336
//////////////////////////////////////////////////////////////////
337
338
bool PackedSourceDirectory::try_open_pack(const String &p_path, bool p_replace_files, uint64_t p_offset) {
339
// Load with offset feature only supported for PCK files.
340
ERR_FAIL_COND_V_MSG(p_offset != 0, false, "Invalid PCK data. Note that loading files with a non-zero offset isn't supported with directories.");
341
342
if (p_path != "res://") {
343
return false;
344
}
345
add_directory(p_path, p_replace_files);
346
return true;
347
}
348
349
Ref<FileAccess> PackedSourceDirectory::get_file(const String &p_path, PackedData::PackedFile *p_file) {
350
Ref<FileAccess> ret = FileAccess::create_for_path(p_path);
351
ret->reopen(p_path, FileAccess::READ);
352
return ret;
353
}
354
355
void PackedSourceDirectory::add_directory(const String &p_path, bool p_replace_files) {
356
Ref<DirAccess> da = DirAccess::open(p_path);
357
if (da.is_null()) {
358
return;
359
}
360
da->set_include_hidden(true);
361
362
for (const String &file_name : da->get_files()) {
363
String file_path = p_path.path_join(file_name);
364
uint8_t md5[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
365
PackedData::get_singleton()->add_path(p_path, file_path, 0, 0, md5, this, p_replace_files, false, false);
366
}
367
368
for (const String &sub_dir_name : da->get_directories()) {
369
String sub_dir_path = p_path.path_join(sub_dir_name);
370
add_directory(sub_dir_path, p_replace_files);
371
}
372
}
373
374
//////////////////////////////////////////////////////////////////
375
376
Error FileAccessPack::open_internal(const String &p_path, int p_mode_flags) {
377
ERR_PRINT("Can't open pack-referenced file.");
378
return ERR_UNAVAILABLE;
379
}
380
381
bool FileAccessPack::is_open() const {
382
if (f.is_valid()) {
383
return f->is_open();
384
} else {
385
return false;
386
}
387
}
388
389
void FileAccessPack::seek(uint64_t p_position) {
390
ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use.");
391
392
if (p_position > pf.size) {
393
eof = true;
394
} else {
395
eof = false;
396
}
397
398
f->seek(off + p_position);
399
pos = p_position;
400
}
401
402
void FileAccessPack::seek_end(int64_t p_position) {
403
seek(pf.size + p_position);
404
}
405
406
uint64_t FileAccessPack::get_position() const {
407
return pos;
408
}
409
410
uint64_t FileAccessPack::get_length() const {
411
return pf.size;
412
}
413
414
bool FileAccessPack::eof_reached() const {
415
return eof;
416
}
417
418
uint64_t FileAccessPack::get_buffer(uint8_t *p_dst, uint64_t p_length) const {
419
ERR_FAIL_COND_V_MSG(f.is_null(), -1, "File must be opened before use.");
420
ERR_FAIL_COND_V(!p_dst && p_length > 0, -1);
421
422
if (eof) {
423
return 0;
424
}
425
426
int64_t to_read = p_length;
427
if (to_read + pos > pf.size) {
428
eof = true;
429
to_read = (int64_t)pf.size - (int64_t)pos;
430
}
431
432
pos += to_read;
433
434
if (to_read <= 0) {
435
return 0;
436
}
437
f->get_buffer(p_dst, to_read);
438
439
return to_read;
440
}
441
442
void FileAccessPack::set_big_endian(bool p_big_endian) {
443
ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use.");
444
445
FileAccess::set_big_endian(p_big_endian);
446
f->set_big_endian(p_big_endian);
447
}
448
449
Error FileAccessPack::get_error() const {
450
if (eof) {
451
return ERR_FILE_EOF;
452
}
453
return OK;
454
}
455
456
void FileAccessPack::flush() {
457
ERR_FAIL();
458
}
459
460
bool FileAccessPack::store_buffer(const uint8_t *p_src, uint64_t p_length) {
461
ERR_FAIL_V(false);
462
}
463
464
bool FileAccessPack::file_exists(const String &p_name) {
465
return false;
466
}
467
468
void FileAccessPack::close() {
469
f = Ref<FileAccess>();
470
}
471
472
FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file) {
473
pf = p_file;
474
if (pf.bundle) {
475
String simplified_path = p_path.simplify_path();
476
f = FileAccess::open(simplified_path, FileAccess::READ | FileAccess::SKIP_PACK);
477
off = 0; // For the sparse pack offset is always zero.
478
} else {
479
f = FileAccess::open(pf.pack, FileAccess::READ);
480
f->seek(pf.offset);
481
off = pf.offset;
482
}
483
484
ERR_FAIL_COND_MSG(f.is_null(), vformat("Can't open pack-referenced file '%s'.", String(pf.pack)));
485
486
if (pf.encrypted) {
487
Ref<FileAccessEncrypted> fae;
488
fae.instantiate();
489
ERR_FAIL_COND_MSG(fae.is_null(), vformat("Can't open encrypted pack-referenced file '%s'.", String(pf.pack)));
490
491
Vector<uint8_t> key;
492
key.resize(32);
493
for (int i = 0; i < key.size(); i++) {
494
key.write[i] = script_encryption_key[i];
495
}
496
497
Error err = fae->open_and_parse(f, key, FileAccessEncrypted::MODE_READ, false);
498
ERR_FAIL_COND_MSG(err, vformat("Can't open encrypted pack-referenced file '%s'.", String(pf.pack)));
499
f = fae;
500
off = 0;
501
}
502
pos = 0;
503
eof = false;
504
}
505
506
//////////////////////////////////////////////////////////////////////////////////
507
// DIR ACCESS
508
//////////////////////////////////////////////////////////////////////////////////
509
510
Error DirAccessPack::list_dir_begin() {
511
list_dirs.clear();
512
list_files.clear();
513
514
for (const KeyValue<String, PackedData::PackedDir *> &E : current->subdirs) {
515
list_dirs.push_back(E.key);
516
}
517
518
for (const String &E : current->files) {
519
list_files.push_back(E);
520
}
521
522
return OK;
523
}
524
525
String DirAccessPack::get_next() {
526
if (list_dirs.size()) {
527
cdir = true;
528
String d = list_dirs.front()->get();
529
list_dirs.pop_front();
530
return d;
531
} else if (list_files.size()) {
532
cdir = false;
533
String f = list_files.front()->get();
534
list_files.pop_front();
535
return f;
536
} else {
537
return String();
538
}
539
}
540
541
bool DirAccessPack::current_is_dir() const {
542
return cdir;
543
}
544
545
bool DirAccessPack::current_is_hidden() const {
546
return false;
547
}
548
549
void DirAccessPack::list_dir_end() {
550
list_dirs.clear();
551
list_files.clear();
552
}
553
554
int DirAccessPack::get_drive_count() {
555
return 0;
556
}
557
558
String DirAccessPack::get_drive(int p_drive) {
559
return "";
560
}
561
562
PackedData::PackedDir *DirAccessPack::_find_dir(const String &p_dir) {
563
String nd = p_dir.replace_char('\\', '/');
564
565
// Special handling since simplify_path() will forbid it
566
if (p_dir == "..") {
567
return current->parent;
568
}
569
570
bool absolute = false;
571
if (nd.begins_with("res://")) {
572
nd = nd.replace_first("res://", "");
573
absolute = true;
574
}
575
576
nd = nd.simplify_path();
577
578
if (nd.is_empty()) {
579
nd = ".";
580
}
581
582
if (nd.begins_with("/")) {
583
nd = nd.replace_first("/", "");
584
absolute = true;
585
}
586
587
Vector<String> paths = nd.split("/");
588
589
PackedData::PackedDir *pd;
590
591
if (absolute) {
592
pd = PackedData::get_singleton()->root;
593
} else {
594
pd = current;
595
}
596
597
for (int i = 0; i < paths.size(); i++) {
598
const String &p = paths[i];
599
if (p == ".") {
600
continue;
601
} else if (p == "..") {
602
if (pd->parent) {
603
pd = pd->parent;
604
}
605
} else if (pd->subdirs.has(p)) {
606
pd = pd->subdirs[p];
607
608
} else {
609
return nullptr;
610
}
611
}
612
613
return pd;
614
}
615
616
Error DirAccessPack::change_dir(String p_dir) {
617
PackedData::PackedDir *pd = _find_dir(p_dir);
618
if (pd) {
619
current = pd;
620
return OK;
621
} else {
622
return ERR_INVALID_PARAMETER;
623
}
624
}
625
626
String DirAccessPack::get_current_dir(bool p_include_drive) const {
627
PackedData::PackedDir *pd = current;
628
String p = current->name;
629
630
while (pd->parent) {
631
pd = pd->parent;
632
p = pd->name.path_join(p);
633
}
634
635
return "res://" + p;
636
}
637
638
bool DirAccessPack::file_exists(String p_file) {
639
PackedData::PackedDir *pd = _find_dir(p_file.get_base_dir());
640
if (!pd) {
641
return false;
642
}
643
return pd->files.has(p_file.get_file());
644
}
645
646
bool DirAccessPack::dir_exists(String p_dir) {
647
return _find_dir(p_dir) != nullptr;
648
}
649
650
Error DirAccessPack::make_dir(String p_dir) {
651
return ERR_UNAVAILABLE;
652
}
653
654
Error DirAccessPack::rename(String p_from, String p_to) {
655
return ERR_UNAVAILABLE;
656
}
657
658
Error DirAccessPack::remove(String p_name) {
659
return ERR_UNAVAILABLE;
660
}
661
662
uint64_t DirAccessPack::get_space_left() {
663
return 0;
664
}
665
666
String DirAccessPack::get_filesystem_type() const {
667
return "PCK";
668
}
669
670
DirAccessPack::DirAccessPack() {
671
current = PackedData::get_singleton()->root;
672
}
673
674