file_access.cpp 33 KB

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