file_access.cpp 32 KB

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