file_access.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. /**************************************************************************/
  2. /* file_access.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. #include "file_access.h"
  31. #include "file_access.compat.inc"
  32. #include "core/config/project_settings.h"
  33. #include "core/crypto/crypto_core.h"
  34. #include "core/io/file_access_compressed.h"
  35. #include "core/io/file_access_encrypted.h"
  36. #include "core/io/file_access_pack.h"
  37. #include "core/io/marshalls.h"
  38. #include "core/os/os.h"
  39. #include "core/os/time.h"
  40. FileAccess::CreateFunc FileAccess::create_func[ACCESS_MAX] = {};
  41. FileAccess::FileCloseFailNotify FileAccess::close_fail_notify = nullptr;
  42. bool FileAccess::backup_save = false;
  43. thread_local Error FileAccess::last_file_open_error = OK;
  44. Ref<FileAccess> FileAccess::create(AccessType p_access) {
  45. ERR_FAIL_INDEX_V(p_access, ACCESS_MAX, nullptr);
  46. ERR_FAIL_NULL_V(create_func[p_access], nullptr);
  47. Ref<FileAccess> ret = create_func[p_access]();
  48. ret->_set_access_type(p_access);
  49. return ret;
  50. }
  51. bool FileAccess::exists(const String &p_name) {
  52. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && PackedData::get_singleton()->has_path(p_name)) {
  53. return true;
  54. }
  55. // Using file_exists because it's faster than trying to open the file.
  56. Ref<FileAccess> ret = create_for_path(p_name);
  57. return ret->file_exists(p_name);
  58. }
  59. void FileAccess::_set_access_type(AccessType p_access) {
  60. _access_type = p_access;
  61. }
  62. Ref<FileAccess> FileAccess::create_for_path(const String &p_path) {
  63. Ref<FileAccess> ret;
  64. if (p_path.begins_with("res://") || p_path.begins_with("uid://")) {
  65. ret = create(ACCESS_RESOURCES);
  66. } else if (p_path.begins_with("user://")) {
  67. ret = create(ACCESS_USERDATA);
  68. } else if (p_path.begins_with("pipe://")) {
  69. ret = create(ACCESS_PIPE);
  70. } else {
  71. ret = create(ACCESS_FILESYSTEM);
  72. }
  73. return ret;
  74. }
  75. Ref<FileAccess> FileAccess::create_temp(int p_mode_flags, const String &p_prefix, const String &p_extension, bool p_keep, Error *r_error) {
  76. const String ERROR_COMMON_PREFIX = "Error while creating temporary file";
  77. if (!p_prefix.is_valid_filename()) {
  78. *r_error = ERR_FILE_BAD_PATH;
  79. ERR_FAIL_V_MSG(Ref<FileAccess>(), vformat(R"(%s: "%s" is not a valid prefix.)", ERROR_COMMON_PREFIX, p_prefix));
  80. }
  81. if (!p_extension.is_valid_filename()) {
  82. *r_error = ERR_FILE_BAD_PATH;
  83. ERR_FAIL_V_MSG(Ref<FileAccess>(), vformat(R"(%s: "%s" is not a valid extension.)", ERROR_COMMON_PREFIX, p_extension));
  84. }
  85. const String TEMP_DIR = OS::get_singleton()->get_temp_path();
  86. String extension = p_extension.trim_prefix(".");
  87. uint32_t suffix_i = 0;
  88. String path;
  89. while (true) {
  90. String datetime = Time::get_singleton()->get_datetime_string_from_system().remove_chars("-T:");
  91. datetime += itos(Time::get_singleton()->get_ticks_usec());
  92. String suffix = datetime + (suffix_i > 0 ? itos(suffix_i) : "");
  93. path = TEMP_DIR.path_join((p_prefix.is_empty() ? "" : p_prefix + "-") + suffix + (extension.is_empty() ? "" : "." + extension));
  94. if (!DirAccess::exists(path)) {
  95. break;
  96. }
  97. suffix_i += 1;
  98. }
  99. Error err;
  100. {
  101. // Create file first with WRITE mode.
  102. // Otherwise, it would fail to open with a READ mode.
  103. Ref<FileAccess> ret = FileAccess::open(path, FileAccess::ModeFlags::WRITE, &err);
  104. if (err != OK) {
  105. *r_error = err;
  106. ERR_FAIL_V_MSG(Ref<FileAccess>(), vformat(R"(%s: could not create "%s".)", ERROR_COMMON_PREFIX, path));
  107. }
  108. ret->flush();
  109. }
  110. // Open then the temp file with the correct mode flag.
  111. Ref<FileAccess> ret = FileAccess::open(path, p_mode_flags, &err);
  112. if (err != OK) {
  113. *r_error = err;
  114. ERR_FAIL_V_MSG(Ref<FileAccess>(), vformat(R"(%s: could not open "%s".)", ERROR_COMMON_PREFIX, path));
  115. }
  116. if (ret.is_valid()) {
  117. ret->_is_temp_file = true;
  118. ret->_temp_keep_after_use = p_keep;
  119. ret->_temp_path = ret->get_path_absolute();
  120. }
  121. *r_error = OK;
  122. return ret;
  123. }
  124. Ref<FileAccess> FileAccess::_create_temp(int p_mode_flags, const String &p_prefix, const String &p_extension, bool p_keep) {
  125. return create_temp(p_mode_flags, p_prefix, p_extension, p_keep, &last_file_open_error);
  126. }
  127. void FileAccess::_delete_temp() {
  128. if (!_is_temp_file || _temp_keep_after_use) {
  129. return;
  130. }
  131. if (!FileAccess::exists(_temp_path)) {
  132. return;
  133. }
  134. DirAccess::remove_absolute(_temp_path);
  135. }
  136. Error FileAccess::reopen(const String &p_path, int p_mode_flags) {
  137. return open_internal(p_path, p_mode_flags);
  138. }
  139. Ref<FileAccess> FileAccess::open(const String &p_path, int p_mode_flags, Error *r_error) {
  140. //try packed data first
  141. Ref<FileAccess> ret;
  142. if (!(p_mode_flags & WRITE) && PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled()) {
  143. ret = PackedData::get_singleton()->try_open_path(p_path);
  144. if (ret.is_valid()) {
  145. if (r_error) {
  146. *r_error = OK;
  147. }
  148. return ret;
  149. }
  150. }
  151. ret = create_for_path(p_path);
  152. Error err = ret->open_internal(p_path, p_mode_flags);
  153. if (r_error) {
  154. *r_error = err;
  155. }
  156. if (err != OK) {
  157. ret.unref();
  158. }
  159. return ret;
  160. }
  161. Ref<FileAccess> FileAccess::_open(const String &p_path, ModeFlags p_mode_flags) {
  162. Error err = OK;
  163. Ref<FileAccess> fa = open(p_path, p_mode_flags, &err);
  164. last_file_open_error = err;
  165. if (err) {
  166. return Ref<FileAccess>();
  167. }
  168. return fa;
  169. }
  170. Ref<FileAccess> FileAccess::open_encrypted(const String &p_path, ModeFlags p_mode_flags, const Vector<uint8_t> &p_key, const Vector<uint8_t> &p_iv) {
  171. Ref<FileAccess> fa = _open(p_path, p_mode_flags);
  172. if (fa.is_null()) {
  173. return fa;
  174. }
  175. Ref<FileAccessEncrypted> fae;
  176. fae.instantiate();
  177. Error err = fae->open_and_parse(fa, p_key, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ, true, p_iv);
  178. last_file_open_error = err;
  179. if (err) {
  180. return Ref<FileAccess>();
  181. }
  182. return fae;
  183. }
  184. Ref<FileAccess> FileAccess::open_encrypted_pass(const String &p_path, ModeFlags p_mode_flags, const String &p_pass) {
  185. Ref<FileAccess> fa = _open(p_path, p_mode_flags);
  186. if (fa.is_null()) {
  187. return fa;
  188. }
  189. Ref<FileAccessEncrypted> fae;
  190. fae.instantiate();
  191. Error err = fae->open_and_parse_password(fa, p_pass, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ);
  192. last_file_open_error = err;
  193. if (err) {
  194. return Ref<FileAccess>();
  195. }
  196. return fae;
  197. }
  198. Ref<FileAccess> FileAccess::open_compressed(const String &p_path, ModeFlags p_mode_flags, CompressionMode p_compress_mode) {
  199. Ref<FileAccessCompressed> fac;
  200. fac.instantiate();
  201. fac->configure("GCPF", (Compression::Mode)p_compress_mode);
  202. Error err = fac->open_internal(p_path, p_mode_flags);
  203. last_file_open_error = err;
  204. if (err) {
  205. return Ref<FileAccess>();
  206. }
  207. return fac;
  208. }
  209. Error FileAccess::get_open_error() {
  210. return last_file_open_error;
  211. }
  212. FileAccess::CreateFunc FileAccess::get_create_func(AccessType p_access) {
  213. return create_func[p_access];
  214. }
  215. FileAccess::AccessType FileAccess::get_access_type() const {
  216. return _access_type;
  217. }
  218. String FileAccess::fix_path(const String &p_path) const {
  219. // Helper used by file accesses that use a single filesystem.
  220. String r_path = p_path.replace("\\", "/");
  221. switch (_access_type) {
  222. case ACCESS_RESOURCES: {
  223. if (ProjectSettings::get_singleton()) {
  224. if (r_path.begins_with("uid://")) {
  225. r_path = ResourceUID::uid_to_path(r_path);
  226. }
  227. if (r_path.begins_with("res://")) {
  228. String resource_path = ProjectSettings::get_singleton()->get_resource_path();
  229. if (!resource_path.is_empty()) {
  230. return r_path.replace("res:/", resource_path);
  231. }
  232. return r_path.replace("res://", "");
  233. }
  234. }
  235. } break;
  236. case ACCESS_USERDATA: {
  237. if (r_path.begins_with("user://")) {
  238. String data_dir = OS::get_singleton()->get_user_data_dir();
  239. if (!data_dir.is_empty()) {
  240. return r_path.replace("user:/", data_dir);
  241. }
  242. return r_path.replace("user://", "");
  243. }
  244. } break;
  245. case ACCESS_PIPE: {
  246. return r_path;
  247. } break;
  248. case ACCESS_FILESYSTEM: {
  249. return r_path;
  250. } break;
  251. case ACCESS_MAX:
  252. break; // Can't happen, but silences warning
  253. }
  254. return r_path;
  255. }
  256. /* these are all implemented for ease of porting, then can later be optimized */
  257. uint8_t FileAccess::get_8() const {
  258. uint8_t data = 0;
  259. get_buffer(&data, sizeof(uint8_t));
  260. return data;
  261. }
  262. uint16_t FileAccess::get_16() const {
  263. uint16_t data = 0;
  264. get_buffer(reinterpret_cast<uint8_t *>(&data), sizeof(uint16_t));
  265. if (big_endian) {
  266. data = BSWAP16(data);
  267. }
  268. return data;
  269. }
  270. uint32_t FileAccess::get_32() const {
  271. uint32_t data = 0;
  272. get_buffer(reinterpret_cast<uint8_t *>(&data), sizeof(uint32_t));
  273. if (big_endian) {
  274. data = BSWAP32(data);
  275. }
  276. return data;
  277. }
  278. uint64_t FileAccess::get_64() const {
  279. uint64_t data = 0;
  280. get_buffer(reinterpret_cast<uint8_t *>(&data), sizeof(uint64_t));
  281. if (big_endian) {
  282. data = BSWAP64(data);
  283. }
  284. return data;
  285. }
  286. float FileAccess::get_half() const {
  287. return Math::half_to_float(get_16());
  288. }
  289. float FileAccess::get_float() const {
  290. MarshallFloat m;
  291. m.i = get_32();
  292. return m.f;
  293. }
  294. real_t FileAccess::get_real() const {
  295. if (real_is_double) {
  296. return get_double();
  297. } else {
  298. return get_float();
  299. }
  300. }
  301. Variant FileAccess::get_var(bool p_allow_objects) const {
  302. uint32_t len = get_32();
  303. Vector<uint8_t> buff = get_buffer(len);
  304. ERR_FAIL_COND_V((uint32_t)buff.size() != len, Variant());
  305. const uint8_t *r = buff.ptr();
  306. Variant v;
  307. Error err = decode_variant(v, &r[0], len, nullptr, p_allow_objects);
  308. ERR_FAIL_COND_V_MSG(err != OK, Variant(), "Error when trying to encode Variant.");
  309. return v;
  310. }
  311. double FileAccess::get_double() const {
  312. MarshallDouble m;
  313. m.l = get_64();
  314. return m.d;
  315. }
  316. String FileAccess::get_token() const {
  317. CharString token;
  318. uint8_t c = get_8();
  319. while (!eof_reached()) {
  320. if (c <= ' ') {
  321. if (token.length()) {
  322. break;
  323. }
  324. } else {
  325. token += char(c);
  326. }
  327. c = get_8();
  328. }
  329. return String::utf8(token.get_data());
  330. }
  331. class CharBuffer {
  332. Vector<char> vector;
  333. char stack_buffer[256];
  334. char *buffer = nullptr;
  335. int capacity = 0;
  336. int written = 0;
  337. bool grow() {
  338. if (vector.resize(next_power_of_2(1 + written)) != OK) {
  339. return false;
  340. }
  341. if (buffer == stack_buffer) { // first chunk?
  342. for (int i = 0; i < written; i++) {
  343. vector.write[i] = stack_buffer[i];
  344. }
  345. }
  346. buffer = vector.ptrw();
  347. capacity = vector.size();
  348. ERR_FAIL_COND_V(written >= capacity, false);
  349. return true;
  350. }
  351. public:
  352. _FORCE_INLINE_ CharBuffer() :
  353. buffer(stack_buffer),
  354. capacity(std::size(stack_buffer)) {
  355. }
  356. _FORCE_INLINE_ void push_back(char c) {
  357. if (written >= capacity) {
  358. ERR_FAIL_COND(!grow());
  359. }
  360. buffer[written++] = c;
  361. }
  362. _FORCE_INLINE_ const char *get_data() const {
  363. return buffer;
  364. }
  365. };
  366. String FileAccess::get_line() const {
  367. CharBuffer line;
  368. uint8_t c = get_8();
  369. while (!eof_reached()) {
  370. if (c == '\n' || c == '\0' || get_error() != OK) {
  371. line.push_back(0);
  372. return String::utf8(line.get_data());
  373. } else if (c != '\r') {
  374. line.push_back(char(c));
  375. }
  376. c = get_8();
  377. }
  378. line.push_back(0);
  379. return String::utf8(line.get_data());
  380. }
  381. Vector<String> FileAccess::get_csv_line(const String &p_delim) const {
  382. ERR_FAIL_COND_V_MSG(p_delim.length() != 1, Vector<String>(), "Only single character delimiters are supported to parse CSV lines.");
  383. ERR_FAIL_COND_V_MSG(p_delim[0] == '"', Vector<String>(), "The double quotation mark character (\") is not supported as a delimiter for CSV lines.");
  384. String line;
  385. // CSV can support entries with line breaks as long as they are enclosed
  386. // in double quotes. So our "line" might be more than a single line in the
  387. // text file.
  388. int qc = 0;
  389. do {
  390. if (eof_reached()) {
  391. break;
  392. }
  393. line += get_line() + "\n";
  394. qc = 0;
  395. for (int i = 0; i < line.length(); i++) {
  396. if (line[i] == '"') {
  397. qc++;
  398. }
  399. }
  400. } while (qc % 2);
  401. // Remove the extraneous newline we've added above.
  402. line = line.substr(0, line.length() - 1);
  403. Vector<String> strings;
  404. bool in_quote = false;
  405. String current;
  406. for (int i = 0; i < line.length(); i++) {
  407. char32_t c = line[i];
  408. // A delimiter ends the current entry, unless it's in a quoted string.
  409. if (!in_quote && c == p_delim[0]) {
  410. strings.push_back(current);
  411. current = String();
  412. } else if (c == '"') {
  413. // Doubled quotes are escapes for intentional quotes in the string.
  414. if (line[i + 1] == '"' && in_quote) {
  415. current += '"';
  416. i++;
  417. } else {
  418. in_quote = !in_quote;
  419. }
  420. } else {
  421. current += c;
  422. }
  423. }
  424. if (in_quote) {
  425. WARN_PRINT(vformat("Reached end of file before closing '\"' in CSV file '%s'.", get_path()));
  426. }
  427. strings.push_back(current);
  428. return strings;
  429. }
  430. String FileAccess::get_as_text(bool p_skip_cr) const {
  431. uint64_t original_pos = get_position();
  432. const_cast<FileAccess *>(this)->seek(0);
  433. String text = get_as_utf8_string(p_skip_cr);
  434. const_cast<FileAccess *>(this)->seek(original_pos);
  435. return text;
  436. }
  437. Vector<uint8_t> FileAccess::get_buffer(int64_t p_length) const {
  438. Vector<uint8_t> data;
  439. ERR_FAIL_COND_V_MSG(p_length < 0, data, "Length of buffer cannot be smaller than 0.");
  440. if (p_length == 0) {
  441. return data;
  442. }
  443. Error err = data.resize(p_length);
  444. ERR_FAIL_COND_V_MSG(err != OK, data, vformat("Can't resize data to %d elements.", p_length));
  445. uint8_t *w = data.ptrw();
  446. int64_t len = get_buffer(w, p_length);
  447. if (len < p_length) {
  448. data.resize(len);
  449. }
  450. return data;
  451. }
  452. String FileAccess::get_as_utf8_string(bool p_skip_cr) const {
  453. Vector<uint8_t> sourcef;
  454. uint64_t len = get_length();
  455. sourcef.resize(len + 1);
  456. uint8_t *w = sourcef.ptrw();
  457. uint64_t r = get_buffer(w, len);
  458. ERR_FAIL_COND_V(r != len, String());
  459. w[len] = 0;
  460. String s;
  461. s.append_utf8((const char *)w, len, p_skip_cr);
  462. return s;
  463. }
  464. bool FileAccess::store_8(uint8_t p_dest) {
  465. return store_buffer(&p_dest, sizeof(uint8_t));
  466. }
  467. bool FileAccess::store_16(uint16_t p_dest) {
  468. if (big_endian) {
  469. p_dest = BSWAP16(p_dest);
  470. }
  471. return store_buffer(reinterpret_cast<uint8_t *>(&p_dest), sizeof(uint16_t));
  472. }
  473. bool FileAccess::store_32(uint32_t p_dest) {
  474. if (big_endian) {
  475. p_dest = BSWAP32(p_dest);
  476. }
  477. return store_buffer(reinterpret_cast<uint8_t *>(&p_dest), sizeof(uint32_t));
  478. }
  479. bool FileAccess::store_64(uint64_t p_dest) {
  480. if (big_endian) {
  481. p_dest = BSWAP64(p_dest);
  482. }
  483. return store_buffer(reinterpret_cast<uint8_t *>(&p_dest), sizeof(uint64_t));
  484. }
  485. bool FileAccess::store_real(real_t p_real) {
  486. if constexpr (sizeof(real_t) == 4) {
  487. return store_float(p_real);
  488. } else {
  489. return store_double(p_real);
  490. }
  491. }
  492. bool FileAccess::store_half(float p_dest) {
  493. return store_16(Math::make_half_float(p_dest));
  494. }
  495. bool FileAccess::store_float(float p_dest) {
  496. MarshallFloat m;
  497. m.f = p_dest;
  498. return store_32(m.i);
  499. }
  500. bool FileAccess::store_double(double p_dest) {
  501. MarshallDouble m;
  502. m.d = p_dest;
  503. return store_64(m.l);
  504. }
  505. uint64_t FileAccess::get_modified_time(const String &p_file) {
  506. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  507. return 0;
  508. }
  509. Ref<FileAccess> fa = create_for_path(p_file);
  510. ERR_FAIL_COND_V_MSG(fa.is_null(), 0, vformat("Cannot create FileAccess for path '%s'.", p_file));
  511. return fa->_get_modified_time(p_file);
  512. }
  513. uint64_t FileAccess::get_access_time(const String &p_file) {
  514. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  515. return 0;
  516. }
  517. Ref<FileAccess> fa = create_for_path(p_file);
  518. ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "Cannot create FileAccess for path '" + p_file + "'.");
  519. return fa->_get_access_time(p_file);
  520. }
  521. int64_t FileAccess::get_size(const String &p_file) {
  522. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  523. return PackedData::get_singleton()->get_size(p_file);
  524. }
  525. Ref<FileAccess> fa = create_for_path(p_file);
  526. ERR_FAIL_COND_V_MSG(fa.is_null(), -1, "Cannot create FileAccess for path '" + p_file + "'.");
  527. return fa->_get_size(p_file);
  528. }
  529. BitField<FileAccess::UnixPermissionFlags> FileAccess::get_unix_permissions(const String &p_file) {
  530. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  531. return 0;
  532. }
  533. Ref<FileAccess> fa = create_for_path(p_file);
  534. ERR_FAIL_COND_V_MSG(fa.is_null(), 0, vformat("Cannot create FileAccess for path '%s'.", p_file));
  535. return fa->_get_unix_permissions(p_file);
  536. }
  537. Error FileAccess::set_unix_permissions(const String &p_file, BitField<FileAccess::UnixPermissionFlags> p_permissions) {
  538. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  539. return ERR_UNAVAILABLE;
  540. }
  541. Ref<FileAccess> fa = create_for_path(p_file);
  542. ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, vformat("Cannot create FileAccess for path '%s'.", p_file));
  543. Error err = fa->_set_unix_permissions(p_file, p_permissions);
  544. return err;
  545. }
  546. bool FileAccess::get_hidden_attribute(const String &p_file) {
  547. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  548. return false;
  549. }
  550. Ref<FileAccess> fa = create_for_path(p_file);
  551. ERR_FAIL_COND_V_MSG(fa.is_null(), false, vformat("Cannot create FileAccess for path '%s'.", p_file));
  552. return fa->_get_hidden_attribute(p_file);
  553. }
  554. Error FileAccess::set_hidden_attribute(const String &p_file, bool p_hidden) {
  555. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  556. return ERR_UNAVAILABLE;
  557. }
  558. Ref<FileAccess> fa = create_for_path(p_file);
  559. ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, vformat("Cannot create FileAccess for path '%s'.", p_file));
  560. Error err = fa->_set_hidden_attribute(p_file, p_hidden);
  561. return err;
  562. }
  563. bool FileAccess::get_read_only_attribute(const String &p_file) {
  564. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  565. return false;
  566. }
  567. Ref<FileAccess> fa = create_for_path(p_file);
  568. ERR_FAIL_COND_V_MSG(fa.is_null(), false, vformat("Cannot create FileAccess for path '%s'.", p_file));
  569. return fa->_get_read_only_attribute(p_file);
  570. }
  571. Error FileAccess::set_read_only_attribute(const String &p_file, bool p_ro) {
  572. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  573. return ERR_UNAVAILABLE;
  574. }
  575. Ref<FileAccess> fa = create_for_path(p_file);
  576. ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, vformat("Cannot create FileAccess for path '%s'.", p_file));
  577. Error err = fa->_set_read_only_attribute(p_file, p_ro);
  578. return err;
  579. }
  580. bool FileAccess::store_string(const String &p_string) {
  581. if (p_string.length() == 0) {
  582. return true;
  583. }
  584. CharString cs = p_string.utf8();
  585. return store_buffer((uint8_t *)&cs[0], cs.length());
  586. }
  587. bool FileAccess::store_pascal_string(const String &p_string) {
  588. CharString cs = p_string.utf8();
  589. return store_32(cs.length()) && store_buffer((uint8_t *)&cs[0], cs.length());
  590. }
  591. String FileAccess::get_pascal_string() {
  592. uint32_t sl = get_32();
  593. CharString cs;
  594. cs.resize(sl + 1);
  595. get_buffer((uint8_t *)cs.ptr(), sl);
  596. cs[sl] = 0;
  597. String ret;
  598. ret.append_utf8(cs.ptr(), sl);
  599. return ret;
  600. }
  601. bool FileAccess::store_line(const String &p_line) {
  602. return store_string(p_line) && store_8('\n');
  603. }
  604. bool FileAccess::store_csv_line(const Vector<String> &p_values, const String &p_delim) {
  605. ERR_FAIL_COND_V(p_delim.length() != 1, false);
  606. String line = "";
  607. int size = p_values.size();
  608. for (int i = 0; i < size; ++i) {
  609. String value = p_values[i];
  610. if (value.contains_char('"') || value.contains(p_delim) || value.contains_char('\n')) {
  611. value = "\"" + value.replace("\"", "\"\"") + "\"";
  612. }
  613. if (i < size - 1) {
  614. value += p_delim;
  615. }
  616. line += value;
  617. }
  618. return store_line(line);
  619. }
  620. bool FileAccess::store_buffer(const Vector<uint8_t> &p_buffer) {
  621. uint64_t len = p_buffer.size();
  622. if (len == 0) {
  623. return true;
  624. }
  625. const uint8_t *r = p_buffer.ptr();
  626. return store_buffer(r, len);
  627. }
  628. bool FileAccess::store_buffer(const uint8_t *p_src, uint64_t p_length) {
  629. ERR_FAIL_COND_V(!p_src && p_length > 0, false);
  630. for (uint64_t i = 0; i < p_length; i++) {
  631. if (unlikely(!store_8(p_src[i]))) {
  632. return false;
  633. }
  634. }
  635. return true;
  636. }
  637. bool FileAccess::store_var(const Variant &p_var, bool p_full_objects) {
  638. int len;
  639. Error err = encode_variant(p_var, nullptr, len, p_full_objects);
  640. ERR_FAIL_COND_V_MSG(err != OK, false, "Error when trying to encode Variant.");
  641. Vector<uint8_t> buff;
  642. buff.resize(len);
  643. uint8_t *w = buff.ptrw();
  644. err = encode_variant(p_var, &w[0], len, p_full_objects);
  645. ERR_FAIL_COND_V_MSG(err != OK, false, "Error when trying to encode Variant.");
  646. return store_32(uint32_t(len)) && store_buffer(buff);
  647. }
  648. Vector<uint8_t> FileAccess::get_file_as_bytes(const String &p_path, Error *r_error) {
  649. Ref<FileAccess> f = FileAccess::open(p_path, READ, r_error);
  650. if (f.is_null()) {
  651. if (r_error) { // if error requested, do not throw error
  652. return Vector<uint8_t>();
  653. }
  654. ERR_FAIL_V_MSG(Vector<uint8_t>(), vformat("Can't open file from path '%s'.", String(p_path)));
  655. }
  656. Vector<uint8_t> data;
  657. data.resize(f->get_length());
  658. f->get_buffer(data.ptrw(), data.size());
  659. return data;
  660. }
  661. String FileAccess::get_file_as_string(const String &p_path, Error *r_error) {
  662. Error err;
  663. Vector<uint8_t> array = get_file_as_bytes(p_path, &err);
  664. if (r_error) {
  665. *r_error = err;
  666. }
  667. if (err != OK) {
  668. if (r_error) {
  669. return String();
  670. }
  671. ERR_FAIL_V_MSG(String(), vformat("Can't get file as string from path '%s'.", String(p_path)));
  672. }
  673. String ret;
  674. ret.append_utf8((const char *)array.ptr(), array.size());
  675. return ret;
  676. }
  677. String FileAccess::get_md5(const String &p_file) {
  678. Ref<FileAccess> f = FileAccess::open(p_file, READ);
  679. if (f.is_null()) {
  680. return String();
  681. }
  682. CryptoCore::MD5Context ctx;
  683. ctx.start();
  684. unsigned char step[32768];
  685. while (true) {
  686. uint64_t br = f->get_buffer(step, 32768);
  687. if (br > 0) {
  688. ctx.update(step, br);
  689. }
  690. if (br < 4096) {
  691. break;
  692. }
  693. }
  694. unsigned char hash[16];
  695. ctx.finish(hash);
  696. return String::md5(hash);
  697. }
  698. String FileAccess::get_multiple_md5(const Vector<String> &p_file) {
  699. CryptoCore::MD5Context ctx;
  700. ctx.start();
  701. for (int i = 0; i < p_file.size(); i++) {
  702. Ref<FileAccess> f = FileAccess::open(p_file[i], READ);
  703. ERR_CONTINUE(f.is_null());
  704. unsigned char step[32768];
  705. while (true) {
  706. uint64_t br = f->get_buffer(step, 32768);
  707. if (br > 0) {
  708. ctx.update(step, br);
  709. }
  710. if (br < 4096) {
  711. break;
  712. }
  713. }
  714. }
  715. unsigned char hash[16];
  716. ctx.finish(hash);
  717. return String::md5(hash);
  718. }
  719. String FileAccess::get_sha256(const String &p_file) {
  720. Ref<FileAccess> f = FileAccess::open(p_file, READ);
  721. if (f.is_null()) {
  722. return String();
  723. }
  724. CryptoCore::SHA256Context ctx;
  725. ctx.start();
  726. unsigned char step[32768];
  727. while (true) {
  728. uint64_t br = f->get_buffer(step, 32768);
  729. if (br > 0) {
  730. ctx.update(step, br);
  731. }
  732. if (br < 4096) {
  733. break;
  734. }
  735. }
  736. unsigned char hash[32];
  737. ctx.finish(hash);
  738. return String::hex_encode_buffer(hash, 32);
  739. }
  740. void FileAccess::_bind_methods() {
  741. ClassDB::bind_static_method("FileAccess", D_METHOD("open", "path", "flags"), &FileAccess::_open);
  742. ClassDB::bind_static_method("FileAccess", D_METHOD("open_encrypted", "path", "mode_flags", "key", "iv"), &FileAccess::open_encrypted, DEFVAL(Vector<uint8_t>()));
  743. ClassDB::bind_static_method("FileAccess", D_METHOD("open_encrypted_with_pass", "path", "mode_flags", "pass"), &FileAccess::open_encrypted_pass);
  744. ClassDB::bind_static_method("FileAccess", D_METHOD("open_compressed", "path", "mode_flags", "compression_mode"), &FileAccess::open_compressed, DEFVAL(0));
  745. ClassDB::bind_static_method("FileAccess", D_METHOD("get_open_error"), &FileAccess::get_open_error);
  746. ClassDB::bind_static_method("FileAccess", D_METHOD("create_temp", "mode_flags", "prefix", "extension", "keep"), &FileAccess::_create_temp, DEFVAL(""), DEFVAL(""), DEFVAL(false));
  747. ClassDB::bind_static_method("FileAccess", D_METHOD("get_file_as_bytes", "path"), &FileAccess::_get_file_as_bytes);
  748. ClassDB::bind_static_method("FileAccess", D_METHOD("get_file_as_string", "path"), &FileAccess::_get_file_as_string);
  749. ClassDB::bind_method(D_METHOD("resize", "length"), &FileAccess::resize);
  750. ClassDB::bind_method(D_METHOD("flush"), &FileAccess::flush);
  751. ClassDB::bind_method(D_METHOD("get_path"), &FileAccess::get_path);
  752. ClassDB::bind_method(D_METHOD("get_path_absolute"), &FileAccess::get_path_absolute);
  753. ClassDB::bind_method(D_METHOD("is_open"), &FileAccess::is_open);
  754. ClassDB::bind_method(D_METHOD("seek", "position"), &FileAccess::seek);
  755. ClassDB::bind_method(D_METHOD("seek_end", "position"), &FileAccess::seek_end, DEFVAL(0));
  756. ClassDB::bind_method(D_METHOD("get_position"), &FileAccess::get_position);
  757. ClassDB::bind_method(D_METHOD("get_length"), &FileAccess::get_length);
  758. ClassDB::bind_method(D_METHOD("eof_reached"), &FileAccess::eof_reached);
  759. ClassDB::bind_method(D_METHOD("get_8"), &FileAccess::get_8);
  760. ClassDB::bind_method(D_METHOD("get_16"), &FileAccess::get_16);
  761. ClassDB::bind_method(D_METHOD("get_32"), &FileAccess::get_32);
  762. ClassDB::bind_method(D_METHOD("get_64"), &FileAccess::get_64);
  763. ClassDB::bind_method(D_METHOD("get_half"), &FileAccess::get_half);
  764. ClassDB::bind_method(D_METHOD("get_float"), &FileAccess::get_float);
  765. ClassDB::bind_method(D_METHOD("get_double"), &FileAccess::get_double);
  766. ClassDB::bind_method(D_METHOD("get_real"), &FileAccess::get_real);
  767. ClassDB::bind_method(D_METHOD("get_buffer", "length"), (Vector<uint8_t>(FileAccess::*)(int64_t) const) & FileAccess::get_buffer);
  768. ClassDB::bind_method(D_METHOD("get_line"), &FileAccess::get_line);
  769. ClassDB::bind_method(D_METHOD("get_csv_line", "delim"), &FileAccess::get_csv_line, DEFVAL(","));
  770. ClassDB::bind_method(D_METHOD("get_as_text", "skip_cr"), &FileAccess::get_as_text, DEFVAL(false));
  771. ClassDB::bind_static_method("FileAccess", D_METHOD("get_md5", "path"), &FileAccess::get_md5);
  772. ClassDB::bind_static_method("FileAccess", D_METHOD("get_sha256", "path"), &FileAccess::get_sha256);
  773. ClassDB::bind_method(D_METHOD("is_big_endian"), &FileAccess::is_big_endian);
  774. ClassDB::bind_method(D_METHOD("set_big_endian", "big_endian"), &FileAccess::set_big_endian);
  775. ClassDB::bind_method(D_METHOD("get_error"), &FileAccess::get_error);
  776. ClassDB::bind_method(D_METHOD("get_var", "allow_objects"), &FileAccess::get_var, DEFVAL(false));
  777. ClassDB::bind_method(D_METHOD("store_8", "value"), &FileAccess::store_8);
  778. ClassDB::bind_method(D_METHOD("store_16", "value"), &FileAccess::store_16);
  779. ClassDB::bind_method(D_METHOD("store_32", "value"), &FileAccess::store_32);
  780. ClassDB::bind_method(D_METHOD("store_64", "value"), &FileAccess::store_64);
  781. ClassDB::bind_method(D_METHOD("store_half", "value"), &FileAccess::store_half);
  782. ClassDB::bind_method(D_METHOD("store_float", "value"), &FileAccess::store_float);
  783. ClassDB::bind_method(D_METHOD("store_double", "value"), &FileAccess::store_double);
  784. ClassDB::bind_method(D_METHOD("store_real", "value"), &FileAccess::store_real);
  785. ClassDB::bind_method(D_METHOD("store_buffer", "buffer"), (bool(FileAccess::*)(const Vector<uint8_t> &)) & FileAccess::store_buffer);
  786. ClassDB::bind_method(D_METHOD("store_line", "line"), &FileAccess::store_line);
  787. ClassDB::bind_method(D_METHOD("store_csv_line", "values", "delim"), &FileAccess::store_csv_line, DEFVAL(","));
  788. ClassDB::bind_method(D_METHOD("store_string", "string"), &FileAccess::store_string);
  789. ClassDB::bind_method(D_METHOD("store_var", "value", "full_objects"), &FileAccess::store_var, DEFVAL(false));
  790. ClassDB::bind_method(D_METHOD("store_pascal_string", "string"), &FileAccess::store_pascal_string);
  791. ClassDB::bind_method(D_METHOD("get_pascal_string"), &FileAccess::get_pascal_string);
  792. ClassDB::bind_method(D_METHOD("close"), &FileAccess::close);
  793. ClassDB::bind_static_method("FileAccess", D_METHOD("file_exists", "path"), &FileAccess::exists);
  794. ClassDB::bind_static_method("FileAccess", D_METHOD("get_modified_time", "file"), &FileAccess::get_modified_time);
  795. ClassDB::bind_static_method("FileAccess", D_METHOD("get_access_time", "file"), &FileAccess::get_access_time);
  796. ClassDB::bind_static_method("FileAccess", D_METHOD("get_size", "file"), &FileAccess::get_size);
  797. ClassDB::bind_static_method("FileAccess", D_METHOD("get_unix_permissions", "file"), &FileAccess::get_unix_permissions);
  798. ClassDB::bind_static_method("FileAccess", D_METHOD("set_unix_permissions", "file", "permissions"), &FileAccess::set_unix_permissions);
  799. ClassDB::bind_static_method("FileAccess", D_METHOD("get_hidden_attribute", "file"), &FileAccess::get_hidden_attribute);
  800. ClassDB::bind_static_method("FileAccess", D_METHOD("set_hidden_attribute", "file", "hidden"), &FileAccess::set_hidden_attribute);
  801. ClassDB::bind_static_method("FileAccess", D_METHOD("set_read_only_attribute", "file", "ro"), &FileAccess::set_read_only_attribute);
  802. ClassDB::bind_static_method("FileAccess", D_METHOD("get_read_only_attribute", "file"), &FileAccess::get_read_only_attribute);
  803. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "big_endian"), "set_big_endian", "is_big_endian");
  804. BIND_ENUM_CONSTANT(READ);
  805. BIND_ENUM_CONSTANT(WRITE);
  806. BIND_ENUM_CONSTANT(READ_WRITE);
  807. BIND_ENUM_CONSTANT(WRITE_READ);
  808. BIND_ENUM_CONSTANT(COMPRESSION_FASTLZ);
  809. BIND_ENUM_CONSTANT(COMPRESSION_DEFLATE);
  810. BIND_ENUM_CONSTANT(COMPRESSION_ZSTD);
  811. BIND_ENUM_CONSTANT(COMPRESSION_GZIP);
  812. BIND_ENUM_CONSTANT(COMPRESSION_BROTLI);
  813. BIND_BITFIELD_FLAG(UNIX_READ_OWNER);
  814. BIND_BITFIELD_FLAG(UNIX_WRITE_OWNER);
  815. BIND_BITFIELD_FLAG(UNIX_EXECUTE_OWNER);
  816. BIND_BITFIELD_FLAG(UNIX_READ_GROUP);
  817. BIND_BITFIELD_FLAG(UNIX_WRITE_GROUP);
  818. BIND_BITFIELD_FLAG(UNIX_EXECUTE_GROUP);
  819. BIND_BITFIELD_FLAG(UNIX_READ_OTHER);
  820. BIND_BITFIELD_FLAG(UNIX_WRITE_OTHER);
  821. BIND_BITFIELD_FLAG(UNIX_EXECUTE_OTHER);
  822. BIND_BITFIELD_FLAG(UNIX_SET_USER_ID);
  823. BIND_BITFIELD_FLAG(UNIX_SET_GROUP_ID);
  824. BIND_BITFIELD_FLAG(UNIX_RESTRICTED_DELETE);
  825. }
  826. FileAccess::~FileAccess() {
  827. _delete_temp();
  828. }