file_access.cpp 33 KB

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