file_access.cpp 32 KB

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