Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/drivers/unix/file_access_unix.cpp
20957 views
1
/**************************************************************************/
2
/* file_access_unix.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_unix.h"
32
33
#if defined(UNIX_ENABLED)
34
35
#include "core/os/os.h"
36
#include "core/string/print_string.h"
37
38
#include <fcntl.h>
39
#include <sys/stat.h>
40
#include <sys/types.h>
41
#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(WEB_ENABLED)
42
#include <sys/xattr.h>
43
#endif
44
#include <unistd.h>
45
#include <cerrno>
46
47
#if defined(TOOLS_ENABLED)
48
#include <climits>
49
#include <cstdlib>
50
#endif
51
52
void FileAccessUnix::check_errors(bool p_write) const {
53
ERR_FAIL_NULL_MSG(f, "File must be opened before use.");
54
55
last_error = OK;
56
if (ferror(f)) {
57
if (p_write) {
58
last_error = ERR_FILE_CANT_WRITE;
59
} else {
60
last_error = ERR_FILE_CANT_READ;
61
}
62
}
63
if (!p_write && feof(f)) {
64
last_error = ERR_FILE_EOF;
65
}
66
}
67
68
Error FileAccessUnix::open_internal(const String &p_path, int p_mode_flags) {
69
_close();
70
71
path_src = p_path;
72
path = fix_path(p_path);
73
//printf("opening %s, %i\n", path.utf8().get_data(), Memory::get_static_mem_usage());
74
75
ERR_FAIL_COND_V_MSG(f, ERR_ALREADY_IN_USE, "File is already in use.");
76
const char *mode_string;
77
78
if (p_mode_flags == READ) {
79
mode_string = "rb";
80
} else if (p_mode_flags == WRITE) {
81
mode_string = "wb";
82
} else if (p_mode_flags == READ_WRITE) {
83
mode_string = "rb+";
84
} else if (p_mode_flags == WRITE_READ) {
85
mode_string = "wb+";
86
} else {
87
return ERR_INVALID_PARAMETER;
88
}
89
90
/* pretty much every implementation that uses fopen as primary
91
backend (unix-compatible mostly) supports utf8 encoding */
92
93
//printf("opening %s as %s\n", p_path.utf8().get_data(), path.utf8().get_data());
94
struct stat st = {};
95
int err = stat(path.utf8().get_data(), &st);
96
if (!err) {
97
switch (st.st_mode & S_IFMT) {
98
case S_IFLNK:
99
case S_IFREG:
100
break;
101
default:
102
return ERR_FILE_CANT_OPEN;
103
}
104
}
105
106
#if defined(TOOLS_ENABLED)
107
if (p_mode_flags & READ) {
108
String real_path = get_real_path();
109
if (real_path != path) {
110
// Don't warn on symlinks, since they can be used to simply share addons on multiple projects.
111
if (real_path.to_lower() == path.to_lower()) {
112
// The File system is case insensitive, but other platforms can be sensitive to it
113
// To ease cross-platform development, we issue a warning if users try to access
114
// a file using the wrong case (which *works* on Windows and macOS, but won't on other
115
// platforms).
116
WARN_PRINT(vformat("Case mismatch opening requested file '%s', stored as '%s' in the filesystem. This file will not open when exported to other case-sensitive platforms.", path, real_path));
117
}
118
}
119
}
120
#endif
121
122
if (is_backup_save_enabled() && (p_mode_flags == WRITE)) {
123
// Set save path to the symlink target, not the link itself.
124
String link;
125
bool is_link = false;
126
{
127
CharString cs = path.utf8();
128
struct stat lst = {};
129
if (lstat(cs.get_data(), &lst) == 0) {
130
is_link = S_ISLNK(lst.st_mode);
131
}
132
if (is_link) {
133
char buf[PATH_MAX];
134
memset(buf, 0, PATH_MAX);
135
ssize_t len = readlink(cs.get_data(), buf, sizeof(buf));
136
if (len > 0) {
137
link.append_utf8(buf, len);
138
}
139
if (!link.is_absolute_path()) {
140
link = path.get_base_dir().path_join(link);
141
}
142
}
143
}
144
save_path = is_link ? link : path;
145
146
// Create a temporary file in the same directory as the target file.
147
path = path + "-XXXXXX";
148
CharString cs = path.utf8();
149
int fd = mkstemp(cs.ptrw());
150
if (fd == -1) {
151
last_error = ERR_FILE_CANT_OPEN;
152
return last_error;
153
}
154
155
struct stat file_stat = {};
156
int error = stat(save_path.utf8().get_data(), &file_stat);
157
if (!error) {
158
fchmod(fd, file_stat.st_mode & 0xFFF); // Mask to remove file type
159
} else {
160
fchmod(fd, 0644); // Fallback permissions
161
}
162
163
path = String::utf8(cs.ptr());
164
165
f = fdopen(fd, mode_string);
166
if (f == nullptr) {
167
// Delete temp file and close descriptor if open failed.
168
::unlink(cs.ptr());
169
::close(fd);
170
last_error = ERR_FILE_CANT_OPEN;
171
return last_error;
172
}
173
} else {
174
f = fopen(path.utf8().get_data(), mode_string);
175
}
176
177
if (f == nullptr) {
178
switch (errno) {
179
case ENOENT: {
180
last_error = ERR_FILE_NOT_FOUND;
181
} break;
182
default: {
183
last_error = ERR_FILE_CANT_OPEN;
184
} break;
185
}
186
return last_error;
187
}
188
189
// Set close on exec to avoid leaking it to subprocesses.
190
int fd = fileno(f);
191
192
if (fd != -1) {
193
int opts = fcntl(fd, F_GETFD);
194
fcntl(fd, F_SETFD, opts | FD_CLOEXEC);
195
}
196
197
last_error = OK;
198
flags = p_mode_flags;
199
return OK;
200
}
201
202
void FileAccessUnix::_close() {
203
if (!f) {
204
return;
205
}
206
207
fclose(f);
208
f = nullptr;
209
210
if (close_notification_func) {
211
close_notification_func(path, flags);
212
}
213
214
if (!save_path.is_empty()) {
215
int rename_error = rename(path.utf8().get_data(), save_path.utf8().get_data());
216
217
if (rename_error && close_fail_notify) {
218
close_fail_notify(save_path);
219
}
220
221
save_path = "";
222
ERR_FAIL_COND(rename_error != 0);
223
}
224
}
225
226
bool FileAccessUnix::is_open() const {
227
return (f != nullptr);
228
}
229
230
String FileAccessUnix::get_path() const {
231
return path_src;
232
}
233
234
String FileAccessUnix::get_path_absolute() const {
235
return path;
236
}
237
238
#if defined(TOOLS_ENABLED)
239
String FileAccessUnix::get_real_path() const {
240
char *resolved_path = ::realpath(path.utf8().get_data(), nullptr);
241
242
if (!resolved_path) {
243
return path;
244
}
245
246
String result;
247
Error parse_ok = result.append_utf8(resolved_path);
248
::free(resolved_path);
249
250
if (parse_ok != OK) {
251
return path;
252
}
253
254
return result.simplify_path();
255
}
256
#endif
257
258
void FileAccessUnix::seek(uint64_t p_position) {
259
ERR_FAIL_NULL_MSG(f, "File must be opened before use.");
260
261
if (fseeko(f, p_position, SEEK_SET)) {
262
check_errors();
263
}
264
}
265
266
void FileAccessUnix::seek_end(int64_t p_position) {
267
ERR_FAIL_NULL_MSG(f, "File must be opened before use.");
268
269
if (fseeko(f, p_position, SEEK_END)) {
270
check_errors();
271
}
272
}
273
274
uint64_t FileAccessUnix::get_position() const {
275
ERR_FAIL_NULL_V_MSG(f, 0, "File must be opened before use.");
276
277
int64_t pos = ftello(f);
278
if (pos < 0) {
279
check_errors();
280
ERR_FAIL_V(0);
281
}
282
return pos;
283
}
284
285
uint64_t FileAccessUnix::get_length() const {
286
ERR_FAIL_NULL_V_MSG(f, 0, "File must be opened before use.");
287
288
int64_t pos = ftello(f);
289
ERR_FAIL_COND_V(pos < 0, 0);
290
ERR_FAIL_COND_V(fseeko(f, 0, SEEK_END), 0);
291
int64_t size = ftello(f);
292
ERR_FAIL_COND_V(size < 0, 0);
293
ERR_FAIL_COND_V(fseeko(f, pos, SEEK_SET), 0);
294
295
return size;
296
}
297
298
bool FileAccessUnix::eof_reached() const {
299
return feof(f);
300
}
301
302
uint64_t FileAccessUnix::get_buffer(uint8_t *p_dst, uint64_t p_length) const {
303
ERR_FAIL_NULL_V_MSG(f, -1, "File must be opened before use.");
304
ERR_FAIL_COND_V(!p_dst && p_length > 0, -1);
305
306
uint64_t read = fread(p_dst, 1, p_length, f);
307
check_errors();
308
309
return read;
310
}
311
312
Error FileAccessUnix::get_error() const {
313
return last_error;
314
}
315
316
Error FileAccessUnix::resize(int64_t p_length) {
317
ERR_FAIL_NULL_V_MSG(f, FAILED, "File must be opened before use.");
318
int res = ::ftruncate(fileno(f), p_length);
319
switch (res) {
320
case 0:
321
return OK;
322
case EBADF:
323
return ERR_FILE_CANT_OPEN;
324
case EFBIG:
325
return ERR_OUT_OF_MEMORY;
326
case EINVAL:
327
return ERR_INVALID_PARAMETER;
328
default:
329
return FAILED;
330
}
331
}
332
333
void FileAccessUnix::flush() {
334
ERR_FAIL_NULL_MSG(f, "File must be opened before use.");
335
fflush(f);
336
}
337
338
bool FileAccessUnix::store_buffer(const uint8_t *p_src, uint64_t p_length) {
339
ERR_FAIL_NULL_V_MSG(f, false, "File must be opened before use.");
340
ERR_FAIL_COND_V(!p_src && p_length > 0, false);
341
bool res = fwrite(p_src, 1, p_length, f) == p_length;
342
check_errors(true);
343
return res;
344
}
345
346
bool FileAccessUnix::file_exists(const String &p_path) {
347
struct stat st = {};
348
const CharString filename_utf8 = fix_path(p_path).utf8();
349
350
// Does the name exist at all?
351
if (stat(filename_utf8.get_data(), &st)) {
352
return false;
353
}
354
355
// See if we have access to the file
356
if (access(filename_utf8.get_data(), F_OK)) {
357
return false;
358
}
359
360
// See if this is a regular file
361
switch (st.st_mode & S_IFMT) {
362
case S_IFLNK:
363
case S_IFREG:
364
return true;
365
default:
366
return false;
367
}
368
}
369
370
uint64_t FileAccessUnix::_get_modified_time(const String &p_file) {
371
String file = fix_path(p_file);
372
struct stat st = {};
373
int err = stat(file.utf8().get_data(), &st);
374
375
if (!err) {
376
uint64_t modified_time = 0;
377
if ((st.st_mode & S_IFMT) == S_IFLNK || (st.st_mode & S_IFMT) == S_IFREG || (st.st_mode & S_IFDIR) == S_IFDIR) {
378
modified_time = st.st_mtime;
379
}
380
#ifdef ANDROID_ENABLED
381
// Workaround for GH-101007
382
//FIXME: After saving, all timestamps (st_mtime, st_ctime, st_atime) are set to the same value.
383
// After exporting or after some time, only 'modified_time' resets to a past timestamp.
384
uint64_t created_time = st.st_ctime;
385
if (modified_time < created_time) {
386
modified_time = created_time;
387
}
388
#endif
389
return modified_time;
390
} else {
391
return 0;
392
}
393
}
394
395
uint64_t FileAccessUnix::_get_access_time(const String &p_file) {
396
String file = fix_path(p_file);
397
struct stat st = {};
398
int err = stat(file.utf8().get_data(), &st);
399
400
if (!err) {
401
if ((st.st_mode & S_IFMT) == S_IFLNK || (st.st_mode & S_IFMT) == S_IFREG || (st.st_mode & S_IFDIR) == S_IFDIR) {
402
return st.st_atime;
403
}
404
}
405
ERR_FAIL_V_MSG(0, "Failed to get access time for: " + p_file + "");
406
}
407
408
int64_t FileAccessUnix::_get_size(const String &p_file) {
409
String file = fix_path(p_file);
410
struct stat st = {};
411
int err = stat(file.utf8().get_data(), &st);
412
413
if (!err) {
414
if ((st.st_mode & S_IFMT) == S_IFLNK || (st.st_mode & S_IFMT) == S_IFREG) {
415
return st.st_size;
416
}
417
}
418
ERR_FAIL_V_MSG(-1, "Failed to get size for: " + p_file + "");
419
}
420
421
BitField<FileAccess::UnixPermissionFlags> FileAccessUnix::_get_unix_permissions(const String &p_file) {
422
String file = fix_path(p_file);
423
struct stat status = {};
424
int err = stat(file.utf8().get_data(), &status);
425
426
if (!err) {
427
return status.st_mode & 0xFFF; //only permissions
428
} else {
429
ERR_FAIL_V_MSG(0, "Failed to get unix permissions for: " + p_file + ".");
430
}
431
}
432
433
Error FileAccessUnix::_set_unix_permissions(const String &p_file, BitField<FileAccess::UnixPermissionFlags> p_permissions) {
434
String file = fix_path(p_file);
435
436
int err = chmod(file.utf8().get_data(), p_permissions);
437
if (!err) {
438
return OK;
439
}
440
441
return FAILED;
442
}
443
444
bool FileAccessUnix::_get_hidden_attribute(const String &p_file) {
445
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__APPLE__)
446
String file = fix_path(p_file);
447
448
struct stat st = {};
449
int err = stat(file.utf8().get_data(), &st);
450
ERR_FAIL_COND_V_MSG(err, false, "Failed to get attributes for: " + p_file);
451
452
return (st.st_flags & UF_HIDDEN);
453
#else
454
return false;
455
#endif
456
}
457
458
Error FileAccessUnix::_set_hidden_attribute(const String &p_file, bool p_hidden) {
459
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__APPLE__)
460
String file = fix_path(p_file);
461
462
struct stat st = {};
463
int err = stat(file.utf8().get_data(), &st);
464
ERR_FAIL_COND_V_MSG(err, FAILED, "Failed to get attributes for: " + p_file);
465
466
if (p_hidden) {
467
err = chflags(file.utf8().get_data(), st.st_flags | UF_HIDDEN);
468
} else {
469
err = chflags(file.utf8().get_data(), st.st_flags & ~UF_HIDDEN);
470
}
471
ERR_FAIL_COND_V_MSG(err, FAILED, "Failed to set attributes for: " + p_file);
472
return OK;
473
#else
474
return ERR_UNAVAILABLE;
475
#endif
476
}
477
478
bool FileAccessUnix::_get_read_only_attribute(const String &p_file) {
479
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
480
String file = fix_path(p_file);
481
482
struct stat st = {};
483
int err = stat(file.utf8().get_data(), &st);
484
ERR_FAIL_COND_V_MSG(err, false, "Failed to get attributes for: " + p_file);
485
486
return st.st_flags & UF_IMMUTABLE;
487
#else
488
return false;
489
#endif
490
}
491
492
Error FileAccessUnix::_set_read_only_attribute(const String &p_file, bool p_ro) {
493
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
494
String file = fix_path(p_file);
495
496
struct stat st = {};
497
int err = stat(file.utf8().get_data(), &st);
498
ERR_FAIL_COND_V_MSG(err, FAILED, "Failed to get attributes for: " + p_file);
499
500
if (p_ro) {
501
err = chflags(file.utf8().get_data(), st.st_flags | UF_IMMUTABLE);
502
} else {
503
err = chflags(file.utf8().get_data(), st.st_flags & ~UF_IMMUTABLE);
504
}
505
ERR_FAIL_COND_V_MSG(err, FAILED, "Failed to set attributes for: " + p_file);
506
return OK;
507
#else
508
return ERR_UNAVAILABLE;
509
#endif
510
}
511
512
PackedByteArray FileAccessUnix::_get_extended_attribute(const String &p_file, const String &p_attribute_name) {
513
ERR_FAIL_COND_V(p_attribute_name.is_empty(), PackedByteArray());
514
515
String file = fix_path(p_file);
516
PackedByteArray data;
517
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(WEB_ENABLED)
518
// Not supported.
519
#elif defined(__APPLE__)
520
CharString attr_name = p_attribute_name.utf8();
521
ssize_t attr_size = getxattr(file.utf8().get_data(), attr_name.get_data(), nullptr, 0, 0, 0);
522
if (attr_size <= 0) {
523
return PackedByteArray();
524
}
525
526
data.resize(attr_size);
527
attr_size = getxattr(file.utf8().get_data(), attr_name.get_data(), (void *)data.ptrw(), data.size(), 0, 0);
528
ERR_FAIL_COND_V_MSG(attr_size != data.size(), PackedByteArray(), "Failed to set extended attributes for: " + p_file);
529
#else
530
CharString attr_name = ("user." + p_attribute_name).utf8();
531
ssize_t attr_size = getxattr(file.utf8().get_data(), attr_name.get_data(), nullptr, 0);
532
if (attr_size <= 0) {
533
return PackedByteArray();
534
}
535
536
data.resize(attr_size);
537
attr_size = getxattr(file.utf8().get_data(), attr_name.get_data(), (void *)data.ptrw(), data.size());
538
ERR_FAIL_COND_V_MSG(attr_size != data.size(), PackedByteArray(), "Failed to set extended attributes for: " + p_file);
539
#endif
540
return data;
541
}
542
543
Error FileAccessUnix::_set_extended_attribute(const String &p_file, const String &p_attribute_name, const PackedByteArray &p_data) {
544
ERR_FAIL_COND_V(p_attribute_name.is_empty(), FAILED);
545
546
String file = fix_path(p_file);
547
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(WEB_ENABLED)
548
// Not supported.
549
#elif defined(__APPLE__)
550
int err = setxattr(file.utf8().get_data(), p_attribute_name.utf8().get_data(), (const void *)p_data.ptr(), p_data.size(), 0, 0);
551
if (err != 0) {
552
return FAILED;
553
}
554
#else
555
int err = setxattr(file.utf8().get_data(), ("user." + p_attribute_name).utf8().get_data(), (const void *)p_data.ptr(), p_data.size(), 0);
556
if (err != 0) {
557
return FAILED;
558
}
559
#endif
560
return OK;
561
}
562
563
Error FileAccessUnix::_remove_extended_attribute(const String &p_file, const String &p_attribute_name) {
564
ERR_FAIL_COND_V(p_attribute_name.is_empty(), FAILED);
565
566
String file = fix_path(p_file);
567
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(WEB_ENABLED)
568
// Not supported.
569
#elif defined(__APPLE__)
570
int err = removexattr(file.utf8().get_data(), p_attribute_name.utf8().get_data(), 0);
571
if (err != 0) {
572
return FAILED;
573
}
574
#else
575
int err = removexattr(file.utf8().get_data(), ("user." + p_attribute_name).utf8().get_data());
576
if (err != 0) {
577
return FAILED;
578
}
579
#endif
580
return OK;
581
}
582
583
PackedStringArray FileAccessUnix::_get_extended_attributes_list(const String &p_file) {
584
PackedStringArray ret;
585
String file = fix_path(p_file);
586
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(WEB_ENABLED)
587
// Not supported.
588
#elif defined(__APPLE__)
589
size_t size = listxattr(file.utf8().get_data(), nullptr, 0, 0);
590
if (size > 0) {
591
PackedByteArray data;
592
data.resize(size);
593
listxattr(file.utf8().get_data(), (char *)data.ptrw(), data.size(), 0);
594
int64_t start = 0;
595
for (int64_t x = 0; x < data.size(); x++) {
596
if (x != start && data[x] == 0) {
597
ret.push_back(String::utf8((const char *)(data.ptr() + start), x - start));
598
start = x + 1;
599
}
600
}
601
}
602
#else
603
size_t size = listxattr(file.utf8().get_data(), nullptr, 0);
604
if (size > 0) {
605
PackedByteArray data;
606
data.resize(size);
607
listxattr(file.utf8().get_data(), (char *)data.ptrw(), data.size());
608
int64_t start = 0;
609
for (int64_t x = 0; x < data.size(); x++) {
610
if (x != start && data[x] == 0) {
611
String name = String::utf8((const char *)(data.ptr() + start), x - start);
612
if (name.begins_with("user.")) {
613
ret.push_back(name.trim_prefix("user."));
614
}
615
start = x + 1;
616
}
617
}
618
}
619
#endif
620
return ret;
621
}
622
623
void FileAccessUnix::close() {
624
_close();
625
}
626
627
FileAccessUnix::CloseNotificationFunc FileAccessUnix::close_notification_func = nullptr;
628
629
FileAccessUnix::~FileAccessUnix() {
630
_close();
631
}
632
633
#endif // UNIX_ENABLED
634
635