file_access.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  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. #ifdef BIG_ENDIAN_ENABLED
  266. if (!big_endian) {
  267. data = BSWAP16(data);
  268. }
  269. #else
  270. if (big_endian) {
  271. data = BSWAP16(data);
  272. }
  273. #endif
  274. return data;
  275. }
  276. uint32_t FileAccess::get_32() const {
  277. uint32_t data = 0;
  278. get_buffer(reinterpret_cast<uint8_t *>(&data), sizeof(uint32_t));
  279. #ifdef BIG_ENDIAN_ENABLED
  280. if (!big_endian) {
  281. data = BSWAP32(data);
  282. }
  283. #else
  284. if (big_endian) {
  285. data = BSWAP32(data);
  286. }
  287. #endif
  288. return data;
  289. }
  290. uint64_t FileAccess::get_64() const {
  291. uint64_t data = 0;
  292. get_buffer(reinterpret_cast<uint8_t *>(&data), sizeof(uint64_t));
  293. #ifdef BIG_ENDIAN_ENABLED
  294. if (!big_endian) {
  295. data = BSWAP64(data);
  296. }
  297. #else
  298. if (big_endian) {
  299. data = BSWAP64(data);
  300. }
  301. #endif
  302. return data;
  303. }
  304. float FileAccess::get_half() const {
  305. return Math::half_to_float(get_16());
  306. }
  307. float FileAccess::get_float() const {
  308. MarshallFloat m;
  309. m.i = get_32();
  310. return m.f;
  311. }
  312. real_t FileAccess::get_real() const {
  313. if (real_is_double) {
  314. return get_double();
  315. } else {
  316. return get_float();
  317. }
  318. }
  319. Variant FileAccess::get_var(bool p_allow_objects) const {
  320. uint32_t len = get_32();
  321. Vector<uint8_t> buff = get_buffer(len);
  322. ERR_FAIL_COND_V((uint32_t)buff.size() != len, Variant());
  323. const uint8_t *r = buff.ptr();
  324. Variant v;
  325. Error err = decode_variant(v, &r[0], len, nullptr, p_allow_objects);
  326. ERR_FAIL_COND_V_MSG(err != OK, Variant(), "Error when trying to encode Variant.");
  327. return v;
  328. }
  329. double FileAccess::get_double() const {
  330. MarshallDouble m;
  331. m.l = get_64();
  332. return m.d;
  333. }
  334. String FileAccess::get_token() const {
  335. CharString token;
  336. uint8_t c = get_8();
  337. while (!eof_reached()) {
  338. if (c <= ' ') {
  339. if (token.length()) {
  340. break;
  341. }
  342. } else {
  343. token += char(c);
  344. }
  345. c = get_8();
  346. }
  347. return String::utf8(token.get_data());
  348. }
  349. class CharBuffer {
  350. Vector<char> vector;
  351. char stack_buffer[256];
  352. char *buffer = nullptr;
  353. int capacity = 0;
  354. int written = 0;
  355. bool grow() {
  356. if (vector.resize(next_power_of_2(1 + written)) != OK) {
  357. return false;
  358. }
  359. if (buffer == stack_buffer) { // first chunk?
  360. for (int i = 0; i < written; i++) {
  361. vector.write[i] = stack_buffer[i];
  362. }
  363. }
  364. buffer = vector.ptrw();
  365. capacity = vector.size();
  366. ERR_FAIL_COND_V(written >= capacity, false);
  367. return true;
  368. }
  369. public:
  370. _FORCE_INLINE_ CharBuffer() :
  371. buffer(stack_buffer),
  372. capacity(std::size(stack_buffer)) {
  373. }
  374. _FORCE_INLINE_ void push_back(char c) {
  375. if (written >= capacity) {
  376. ERR_FAIL_COND(!grow());
  377. }
  378. buffer[written++] = c;
  379. }
  380. _FORCE_INLINE_ const char *get_data() const {
  381. return buffer;
  382. }
  383. };
  384. String FileAccess::get_line() const {
  385. CharBuffer line;
  386. uint8_t c = get_8();
  387. while (!eof_reached()) {
  388. if (c == '\n' || c == '\0' || get_error() != OK) {
  389. line.push_back(0);
  390. return String::utf8(line.get_data());
  391. } else if (c != '\r') {
  392. line.push_back(char(c));
  393. }
  394. c = get_8();
  395. }
  396. line.push_back(0);
  397. return String::utf8(line.get_data());
  398. }
  399. Vector<String> FileAccess::get_csv_line(const String &p_delim) const {
  400. ERR_FAIL_COND_V_MSG(p_delim.length() != 1, Vector<String>(), "Only single character delimiters are supported to parse CSV lines.");
  401. ERR_FAIL_COND_V_MSG(p_delim[0] == '"', Vector<String>(), "The double quotation mark character (\") is not supported as a delimiter for CSV lines.");
  402. String line;
  403. // CSV can support entries with line breaks as long as they are enclosed
  404. // in double quotes. So our "line" might be more than a single line in the
  405. // text file.
  406. int qc = 0;
  407. do {
  408. if (eof_reached()) {
  409. break;
  410. }
  411. line += get_line() + "\n";
  412. qc = 0;
  413. for (int i = 0; i < line.length(); i++) {
  414. if (line[i] == '"') {
  415. qc++;
  416. }
  417. }
  418. } while (qc % 2);
  419. // Remove the extraneous newline we've added above.
  420. line = line.substr(0, line.length() - 1);
  421. Vector<String> strings;
  422. bool in_quote = false;
  423. String current;
  424. for (int i = 0; i < line.length(); i++) {
  425. char32_t c = line[i];
  426. // A delimiter ends the current entry, unless it's in a quoted string.
  427. if (!in_quote && c == p_delim[0]) {
  428. strings.push_back(current);
  429. current = String();
  430. } else if (c == '"') {
  431. // Doubled quotes are escapes for intentional quotes in the string.
  432. if (line[i + 1] == '"' && in_quote) {
  433. current += '"';
  434. i++;
  435. } else {
  436. in_quote = !in_quote;
  437. }
  438. } else {
  439. current += c;
  440. }
  441. }
  442. if (in_quote) {
  443. WARN_PRINT(vformat("Reached end of file before closing '\"' in CSV file '%s'.", get_path()));
  444. }
  445. strings.push_back(current);
  446. return strings;
  447. }
  448. String FileAccess::get_as_text(bool p_skip_cr) const {
  449. uint64_t original_pos = get_position();
  450. const_cast<FileAccess *>(this)->seek(0);
  451. String text = get_as_utf8_string(p_skip_cr);
  452. const_cast<FileAccess *>(this)->seek(original_pos);
  453. return text;
  454. }
  455. Vector<uint8_t> FileAccess::get_buffer(int64_t p_length) const {
  456. Vector<uint8_t> data;
  457. ERR_FAIL_COND_V_MSG(p_length < 0, data, "Length of buffer cannot be smaller than 0.");
  458. if (p_length == 0) {
  459. return data;
  460. }
  461. Error err = data.resize(p_length);
  462. ERR_FAIL_COND_V_MSG(err != OK, data, vformat("Can't resize data to %d elements.", p_length));
  463. uint8_t *w = data.ptrw();
  464. int64_t len = get_buffer(w, p_length);
  465. if (len < p_length) {
  466. data.resize(len);
  467. }
  468. return data;
  469. }
  470. String FileAccess::get_as_utf8_string(bool p_skip_cr) const {
  471. Vector<uint8_t> sourcef;
  472. uint64_t len = get_length();
  473. sourcef.resize(len + 1);
  474. uint8_t *w = sourcef.ptrw();
  475. uint64_t r = get_buffer(w, len);
  476. ERR_FAIL_COND_V(r != len, String());
  477. w[len] = 0;
  478. String s;
  479. s.append_utf8((const char *)w, len, p_skip_cr);
  480. return s;
  481. }
  482. bool FileAccess::store_8(uint8_t p_dest) {
  483. return store_buffer(&p_dest, sizeof(uint8_t));
  484. }
  485. bool FileAccess::store_16(uint16_t p_dest) {
  486. #ifdef BIG_ENDIAN_ENABLED
  487. if (!big_endian) {
  488. p_dest = BSWAP16(p_dest);
  489. }
  490. #else
  491. if (big_endian) {
  492. p_dest = BSWAP16(p_dest);
  493. }
  494. #endif
  495. return store_buffer(reinterpret_cast<uint8_t *>(&p_dest), sizeof(uint16_t));
  496. }
  497. bool FileAccess::store_32(uint32_t p_dest) {
  498. #ifdef BIG_ENDIAN_ENABLED
  499. if (!big_endian) {
  500. p_dest = BSWAP32(p_dest);
  501. }
  502. #else
  503. if (big_endian) {
  504. p_dest = BSWAP32(p_dest);
  505. }
  506. #endif
  507. return store_buffer(reinterpret_cast<uint8_t *>(&p_dest), sizeof(uint32_t));
  508. }
  509. bool FileAccess::store_64(uint64_t p_dest) {
  510. #ifdef BIG_ENDIAN_ENABLED
  511. if (!big_endian) {
  512. p_dest = BSWAP64(p_dest);
  513. }
  514. #else
  515. if (big_endian) {
  516. p_dest = BSWAP64(p_dest);
  517. }
  518. #endif
  519. return store_buffer(reinterpret_cast<uint8_t *>(&p_dest), sizeof(uint64_t));
  520. }
  521. bool FileAccess::store_real(real_t p_real) {
  522. if constexpr (sizeof(real_t) == 4) {
  523. return store_float(p_real);
  524. } else {
  525. return store_double(p_real);
  526. }
  527. }
  528. bool FileAccess::store_half(float p_dest) {
  529. return store_16(Math::make_half_float(p_dest));
  530. }
  531. bool FileAccess::store_float(float p_dest) {
  532. MarshallFloat m;
  533. m.f = p_dest;
  534. return store_32(m.i);
  535. }
  536. bool FileAccess::store_double(double p_dest) {
  537. MarshallDouble m;
  538. m.d = p_dest;
  539. return store_64(m.l);
  540. }
  541. uint64_t FileAccess::get_modified_time(const String &p_file) {
  542. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  543. return 0;
  544. }
  545. Ref<FileAccess> fa = create_for_path(p_file);
  546. ERR_FAIL_COND_V_MSG(fa.is_null(), 0, vformat("Cannot create FileAccess for path '%s'.", p_file));
  547. return fa->_get_modified_time(p_file);
  548. }
  549. uint64_t FileAccess::get_access_time(const String &p_file) {
  550. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  551. return 0;
  552. }
  553. Ref<FileAccess> fa = create_for_path(p_file);
  554. ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "Cannot create FileAccess for path '" + p_file + "'.");
  555. return fa->_get_access_time(p_file);
  556. }
  557. int64_t FileAccess::get_size(const String &p_file) {
  558. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  559. return PackedData::get_singleton()->get_size(p_file);
  560. }
  561. Ref<FileAccess> fa = create_for_path(p_file);
  562. ERR_FAIL_COND_V_MSG(fa.is_null(), -1, "Cannot create FileAccess for path '" + p_file + "'.");
  563. return fa->_get_size(p_file);
  564. }
  565. BitField<FileAccess::UnixPermissionFlags> FileAccess::get_unix_permissions(const String &p_file) {
  566. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  567. return 0;
  568. }
  569. Ref<FileAccess> fa = create_for_path(p_file);
  570. ERR_FAIL_COND_V_MSG(fa.is_null(), 0, vformat("Cannot create FileAccess for path '%s'.", p_file));
  571. return fa->_get_unix_permissions(p_file);
  572. }
  573. Error FileAccess::set_unix_permissions(const String &p_file, BitField<FileAccess::UnixPermissionFlags> p_permissions) {
  574. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  575. return ERR_UNAVAILABLE;
  576. }
  577. Ref<FileAccess> fa = create_for_path(p_file);
  578. ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, vformat("Cannot create FileAccess for path '%s'.", p_file));
  579. Error err = fa->_set_unix_permissions(p_file, p_permissions);
  580. return err;
  581. }
  582. bool FileAccess::get_hidden_attribute(const String &p_file) {
  583. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  584. return false;
  585. }
  586. Ref<FileAccess> fa = create_for_path(p_file);
  587. ERR_FAIL_COND_V_MSG(fa.is_null(), false, vformat("Cannot create FileAccess for path '%s'.", p_file));
  588. return fa->_get_hidden_attribute(p_file);
  589. }
  590. Error FileAccess::set_hidden_attribute(const String &p_file, bool p_hidden) {
  591. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  592. return ERR_UNAVAILABLE;
  593. }
  594. Ref<FileAccess> fa = create_for_path(p_file);
  595. ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, vformat("Cannot create FileAccess for path '%s'.", p_file));
  596. Error err = fa->_set_hidden_attribute(p_file, p_hidden);
  597. return err;
  598. }
  599. bool FileAccess::get_read_only_attribute(const String &p_file) {
  600. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  601. return false;
  602. }
  603. Ref<FileAccess> fa = create_for_path(p_file);
  604. ERR_FAIL_COND_V_MSG(fa.is_null(), false, vformat("Cannot create FileAccess for path '%s'.", p_file));
  605. return fa->_get_read_only_attribute(p_file);
  606. }
  607. Error FileAccess::set_read_only_attribute(const String &p_file, bool p_ro) {
  608. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  609. return ERR_UNAVAILABLE;
  610. }
  611. Ref<FileAccess> fa = create_for_path(p_file);
  612. ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, vformat("Cannot create FileAccess for path '%s'.", p_file));
  613. Error err = fa->_set_read_only_attribute(p_file, p_ro);
  614. return err;
  615. }
  616. bool FileAccess::store_string(const String &p_string) {
  617. if (p_string.length() == 0) {
  618. return true;
  619. }
  620. CharString cs = p_string.utf8();
  621. return store_buffer((uint8_t *)&cs[0], cs.length());
  622. }
  623. bool FileAccess::store_pascal_string(const String &p_string) {
  624. CharString cs = p_string.utf8();
  625. return store_32(cs.length()) && store_buffer((uint8_t *)&cs[0], cs.length());
  626. }
  627. String FileAccess::get_pascal_string() {
  628. uint32_t sl = get_32();
  629. CharString cs;
  630. cs.resize(sl + 1);
  631. get_buffer((uint8_t *)cs.ptr(), sl);
  632. cs[sl] = 0;
  633. return String::utf8(cs.ptr(), sl);
  634. }
  635. bool FileAccess::store_line(const String &p_line) {
  636. return store_string(p_line) && store_8('\n');
  637. }
  638. bool FileAccess::store_csv_line(const Vector<String> &p_values, const String &p_delim) {
  639. ERR_FAIL_COND_V(p_delim.length() != 1, false);
  640. String line = "";
  641. int size = p_values.size();
  642. for (int i = 0; i < size; ++i) {
  643. String value = p_values[i];
  644. if (value.contains_char('"') || value.contains(p_delim) || value.contains_char('\n')) {
  645. value = "\"" + value.replace("\"", "\"\"") + "\"";
  646. }
  647. if (i < size - 1) {
  648. value += p_delim;
  649. }
  650. line += value;
  651. }
  652. return store_line(line);
  653. }
  654. bool FileAccess::store_buffer(const Vector<uint8_t> &p_buffer) {
  655. uint64_t len = p_buffer.size();
  656. if (len == 0) {
  657. return true;
  658. }
  659. const uint8_t *r = p_buffer.ptr();
  660. return store_buffer(r, len);
  661. }
  662. bool FileAccess::store_buffer(const uint8_t *p_src, uint64_t p_length) {
  663. ERR_FAIL_COND_V(!p_src && p_length > 0, false);
  664. for (uint64_t i = 0; i < p_length; i++) {
  665. if (unlikely(!store_8(p_src[i]))) {
  666. return false;
  667. }
  668. }
  669. return true;
  670. }
  671. bool FileAccess::store_var(const Variant &p_var, bool p_full_objects) {
  672. int len;
  673. Error err = encode_variant(p_var, nullptr, len, p_full_objects);
  674. ERR_FAIL_COND_V_MSG(err != OK, false, "Error when trying to encode Variant.");
  675. Vector<uint8_t> buff;
  676. buff.resize(len);
  677. uint8_t *w = buff.ptrw();
  678. err = encode_variant(p_var, &w[0], len, p_full_objects);
  679. ERR_FAIL_COND_V_MSG(err != OK, false, "Error when trying to encode Variant.");
  680. return store_32(uint32_t(len)) && store_buffer(buff);
  681. }
  682. Vector<uint8_t> FileAccess::get_file_as_bytes(const String &p_path, Error *r_error) {
  683. Ref<FileAccess> f = FileAccess::open(p_path, READ, r_error);
  684. if (f.is_null()) {
  685. if (r_error) { // if error requested, do not throw error
  686. return Vector<uint8_t>();
  687. }
  688. ERR_FAIL_V_MSG(Vector<uint8_t>(), vformat("Can't open file from path '%s'.", String(p_path)));
  689. }
  690. Vector<uint8_t> data;
  691. data.resize(f->get_length());
  692. f->get_buffer(data.ptrw(), data.size());
  693. return data;
  694. }
  695. String FileAccess::get_file_as_string(const String &p_path, Error *r_error) {
  696. Error err;
  697. Vector<uint8_t> array = get_file_as_bytes(p_path, &err);
  698. if (r_error) {
  699. *r_error = err;
  700. }
  701. if (err != OK) {
  702. if (r_error) {
  703. return String();
  704. }
  705. ERR_FAIL_V_MSG(String(), vformat("Can't get file as string from path '%s'.", String(p_path)));
  706. }
  707. String ret;
  708. ret.append_utf8((const char *)array.ptr(), array.size());
  709. return ret;
  710. }
  711. String FileAccess::get_md5(const String &p_file) {
  712. Ref<FileAccess> f = FileAccess::open(p_file, READ);
  713. if (f.is_null()) {
  714. return String();
  715. }
  716. CryptoCore::MD5Context ctx;
  717. ctx.start();
  718. unsigned char step[32768];
  719. while (true) {
  720. uint64_t br = f->get_buffer(step, 32768);
  721. if (br > 0) {
  722. ctx.update(step, br);
  723. }
  724. if (br < 4096) {
  725. break;
  726. }
  727. }
  728. unsigned char hash[16];
  729. ctx.finish(hash);
  730. return String::md5(hash);
  731. }
  732. String FileAccess::get_multiple_md5(const Vector<String> &p_file) {
  733. CryptoCore::MD5Context ctx;
  734. ctx.start();
  735. for (int i = 0; i < p_file.size(); i++) {
  736. Ref<FileAccess> f = FileAccess::open(p_file[i], READ);
  737. ERR_CONTINUE(f.is_null());
  738. unsigned char step[32768];
  739. while (true) {
  740. uint64_t br = f->get_buffer(step, 32768);
  741. if (br > 0) {
  742. ctx.update(step, br);
  743. }
  744. if (br < 4096) {
  745. break;
  746. }
  747. }
  748. }
  749. unsigned char hash[16];
  750. ctx.finish(hash);
  751. return String::md5(hash);
  752. }
  753. String FileAccess::get_sha256(const String &p_file) {
  754. Ref<FileAccess> f = FileAccess::open(p_file, READ);
  755. if (f.is_null()) {
  756. return String();
  757. }
  758. CryptoCore::SHA256Context ctx;
  759. ctx.start();
  760. unsigned char step[32768];
  761. while (true) {
  762. uint64_t br = f->get_buffer(step, 32768);
  763. if (br > 0) {
  764. ctx.update(step, br);
  765. }
  766. if (br < 4096) {
  767. break;
  768. }
  769. }
  770. unsigned char hash[32];
  771. ctx.finish(hash);
  772. return String::hex_encode_buffer(hash, 32);
  773. }
  774. void FileAccess::_bind_methods() {
  775. ClassDB::bind_static_method("FileAccess", D_METHOD("open", "path", "flags"), &FileAccess::_open);
  776. ClassDB::bind_static_method("FileAccess", D_METHOD("open_encrypted", "path", "mode_flags", "key", "iv"), &FileAccess::open_encrypted, DEFVAL(Vector<uint8_t>()));
  777. ClassDB::bind_static_method("FileAccess", D_METHOD("open_encrypted_with_pass", "path", "mode_flags", "pass"), &FileAccess::open_encrypted_pass);
  778. ClassDB::bind_static_method("FileAccess", D_METHOD("open_compressed", "path", "mode_flags", "compression_mode"), &FileAccess::open_compressed, DEFVAL(0));
  779. ClassDB::bind_static_method("FileAccess", D_METHOD("get_open_error"), &FileAccess::get_open_error);
  780. ClassDB::bind_static_method("FileAccess", D_METHOD("create_temp", "mode_flags", "prefix", "extension", "keep"), &FileAccess::_create_temp, DEFVAL(""), DEFVAL(""), DEFVAL(false));
  781. ClassDB::bind_static_method("FileAccess", D_METHOD("get_file_as_bytes", "path"), &FileAccess::_get_file_as_bytes);
  782. ClassDB::bind_static_method("FileAccess", D_METHOD("get_file_as_string", "path"), &FileAccess::_get_file_as_string);
  783. ClassDB::bind_method(D_METHOD("resize", "length"), &FileAccess::resize);
  784. ClassDB::bind_method(D_METHOD("flush"), &FileAccess::flush);
  785. ClassDB::bind_method(D_METHOD("get_path"), &FileAccess::get_path);
  786. ClassDB::bind_method(D_METHOD("get_path_absolute"), &FileAccess::get_path_absolute);
  787. ClassDB::bind_method(D_METHOD("is_open"), &FileAccess::is_open);
  788. ClassDB::bind_method(D_METHOD("seek", "position"), &FileAccess::seek);
  789. ClassDB::bind_method(D_METHOD("seek_end", "position"), &FileAccess::seek_end, DEFVAL(0));
  790. ClassDB::bind_method(D_METHOD("get_position"), &FileAccess::get_position);
  791. ClassDB::bind_method(D_METHOD("get_length"), &FileAccess::get_length);
  792. ClassDB::bind_method(D_METHOD("eof_reached"), &FileAccess::eof_reached);
  793. ClassDB::bind_method(D_METHOD("get_8"), &FileAccess::get_8);
  794. ClassDB::bind_method(D_METHOD("get_16"), &FileAccess::get_16);
  795. ClassDB::bind_method(D_METHOD("get_32"), &FileAccess::get_32);
  796. ClassDB::bind_method(D_METHOD("get_64"), &FileAccess::get_64);
  797. ClassDB::bind_method(D_METHOD("get_half"), &FileAccess::get_half);
  798. ClassDB::bind_method(D_METHOD("get_float"), &FileAccess::get_float);
  799. ClassDB::bind_method(D_METHOD("get_double"), &FileAccess::get_double);
  800. ClassDB::bind_method(D_METHOD("get_real"), &FileAccess::get_real);
  801. ClassDB::bind_method(D_METHOD("get_buffer", "length"), (Vector<uint8_t> (FileAccess::*)(int64_t) const) & FileAccess::get_buffer);
  802. ClassDB::bind_method(D_METHOD("get_line"), &FileAccess::get_line);
  803. ClassDB::bind_method(D_METHOD("get_csv_line", "delim"), &FileAccess::get_csv_line, DEFVAL(","));
  804. ClassDB::bind_method(D_METHOD("get_as_text", "skip_cr"), &FileAccess::get_as_text, DEFVAL(false));
  805. ClassDB::bind_static_method("FileAccess", D_METHOD("get_md5", "path"), &FileAccess::get_md5);
  806. ClassDB::bind_static_method("FileAccess", D_METHOD("get_sha256", "path"), &FileAccess::get_sha256);
  807. ClassDB::bind_method(D_METHOD("is_big_endian"), &FileAccess::is_big_endian);
  808. ClassDB::bind_method(D_METHOD("set_big_endian", "big_endian"), &FileAccess::set_big_endian);
  809. ClassDB::bind_method(D_METHOD("get_error"), &FileAccess::get_error);
  810. ClassDB::bind_method(D_METHOD("get_var", "allow_objects"), &FileAccess::get_var, DEFVAL(false));
  811. ClassDB::bind_method(D_METHOD("store_8", "value"), &FileAccess::store_8);
  812. ClassDB::bind_method(D_METHOD("store_16", "value"), &FileAccess::store_16);
  813. ClassDB::bind_method(D_METHOD("store_32", "value"), &FileAccess::store_32);
  814. ClassDB::bind_method(D_METHOD("store_64", "value"), &FileAccess::store_64);
  815. ClassDB::bind_method(D_METHOD("store_half", "value"), &FileAccess::store_half);
  816. ClassDB::bind_method(D_METHOD("store_float", "value"), &FileAccess::store_float);
  817. ClassDB::bind_method(D_METHOD("store_double", "value"), &FileAccess::store_double);
  818. ClassDB::bind_method(D_METHOD("store_real", "value"), &FileAccess::store_real);
  819. ClassDB::bind_method(D_METHOD("store_buffer", "buffer"), (bool (FileAccess::*)(const Vector<uint8_t> &))&FileAccess::store_buffer);
  820. ClassDB::bind_method(D_METHOD("store_line", "line"), &FileAccess::store_line);
  821. ClassDB::bind_method(D_METHOD("store_csv_line", "values", "delim"), &FileAccess::store_csv_line, DEFVAL(","));
  822. ClassDB::bind_method(D_METHOD("store_string", "string"), &FileAccess::store_string);
  823. ClassDB::bind_method(D_METHOD("store_var", "value", "full_objects"), &FileAccess::store_var, DEFVAL(false));
  824. ClassDB::bind_method(D_METHOD("store_pascal_string", "string"), &FileAccess::store_pascal_string);
  825. ClassDB::bind_method(D_METHOD("get_pascal_string"), &FileAccess::get_pascal_string);
  826. ClassDB::bind_method(D_METHOD("close"), &FileAccess::close);
  827. ClassDB::bind_static_method("FileAccess", D_METHOD("file_exists", "path"), &FileAccess::exists);
  828. ClassDB::bind_static_method("FileAccess", D_METHOD("get_modified_time", "file"), &FileAccess::get_modified_time);
  829. ClassDB::bind_static_method("FileAccess", D_METHOD("get_access_time", "file"), &FileAccess::get_access_time);
  830. ClassDB::bind_static_method("FileAccess", D_METHOD("get_size", "file"), &FileAccess::get_size);
  831. ClassDB::bind_static_method("FileAccess", D_METHOD("get_unix_permissions", "file"), &FileAccess::get_unix_permissions);
  832. ClassDB::bind_static_method("FileAccess", D_METHOD("set_unix_permissions", "file", "permissions"), &FileAccess::set_unix_permissions);
  833. ClassDB::bind_static_method("FileAccess", D_METHOD("get_hidden_attribute", "file"), &FileAccess::get_hidden_attribute);
  834. ClassDB::bind_static_method("FileAccess", D_METHOD("set_hidden_attribute", "file", "hidden"), &FileAccess::set_hidden_attribute);
  835. ClassDB::bind_static_method("FileAccess", D_METHOD("set_read_only_attribute", "file", "ro"), &FileAccess::set_read_only_attribute);
  836. ClassDB::bind_static_method("FileAccess", D_METHOD("get_read_only_attribute", "file"), &FileAccess::get_read_only_attribute);
  837. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "big_endian"), "set_big_endian", "is_big_endian");
  838. BIND_ENUM_CONSTANT(READ);
  839. BIND_ENUM_CONSTANT(WRITE);
  840. BIND_ENUM_CONSTANT(READ_WRITE);
  841. BIND_ENUM_CONSTANT(WRITE_READ);
  842. BIND_ENUM_CONSTANT(COMPRESSION_FASTLZ);
  843. BIND_ENUM_CONSTANT(COMPRESSION_DEFLATE);
  844. BIND_ENUM_CONSTANT(COMPRESSION_ZSTD);
  845. BIND_ENUM_CONSTANT(COMPRESSION_GZIP);
  846. BIND_ENUM_CONSTANT(COMPRESSION_BROTLI);
  847. BIND_BITFIELD_FLAG(UNIX_READ_OWNER);
  848. BIND_BITFIELD_FLAG(UNIX_WRITE_OWNER);
  849. BIND_BITFIELD_FLAG(UNIX_EXECUTE_OWNER);
  850. BIND_BITFIELD_FLAG(UNIX_READ_GROUP);
  851. BIND_BITFIELD_FLAG(UNIX_WRITE_GROUP);
  852. BIND_BITFIELD_FLAG(UNIX_EXECUTE_GROUP);
  853. BIND_BITFIELD_FLAG(UNIX_READ_OTHER);
  854. BIND_BITFIELD_FLAG(UNIX_WRITE_OTHER);
  855. BIND_BITFIELD_FLAG(UNIX_EXECUTE_OTHER);
  856. BIND_BITFIELD_FLAG(UNIX_SET_USER_ID);
  857. BIND_BITFIELD_FLAG(UNIX_SET_GROUP_ID);
  858. BIND_BITFIELD_FLAG(UNIX_RESTRICTED_DELETE);
  859. }
  860. FileAccess::~FileAccess() {
  861. _delete_temp();
  862. }