file_access.cpp 27 KB

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