file_access.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. /*************************************************************************/
  2. /* file_access.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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_pack.h"
  34. #include "core/io/marshalls.h"
  35. #include "core/os/os.h"
  36. FileAccess::CreateFunc FileAccess::create_func[ACCESS_MAX] = { nullptr, nullptr };
  37. FileAccess::FileCloseFailNotify FileAccess::close_fail_notify = nullptr;
  38. bool FileAccess::backup_save = false;
  39. Ref<FileAccess> FileAccess::create(AccessType p_access) {
  40. ERR_FAIL_INDEX_V(p_access, ACCESS_MAX, nullptr);
  41. Ref<FileAccess> ret = create_func[p_access]();
  42. ret->_set_access_type(p_access);
  43. return ret;
  44. }
  45. bool FileAccess::exists(const String &p_name) {
  46. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && PackedData::get_singleton()->has_path(p_name)) {
  47. return true;
  48. }
  49. Ref<FileAccess> f = open(p_name, READ);
  50. if (f.is_null()) {
  51. return false;
  52. }
  53. return true;
  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://")) {
  61. ret = create(ACCESS_RESOURCES);
  62. } else if (p_path.begins_with("user://")) {
  63. ret = create(ACCESS_USERDATA);
  64. } else {
  65. ret = create(ACCESS_FILESYSTEM);
  66. }
  67. return ret;
  68. }
  69. Error FileAccess::reopen(const String &p_path, int p_mode_flags) {
  70. return _open(p_path, p_mode_flags);
  71. }
  72. Ref<FileAccess> FileAccess::open(const String &p_path, int p_mode_flags, Error *r_error) {
  73. //try packed data first
  74. Ref<FileAccess> ret;
  75. if (!(p_mode_flags & WRITE) && PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled()) {
  76. ret = PackedData::get_singleton()->try_open_path(p_path);
  77. if (ret.is_valid()) {
  78. if (r_error) {
  79. *r_error = OK;
  80. }
  81. return ret;
  82. }
  83. }
  84. ret = create_for_path(p_path);
  85. Error err = ret->_open(p_path, p_mode_flags);
  86. if (r_error) {
  87. *r_error = err;
  88. }
  89. if (err != OK) {
  90. ret.unref();
  91. }
  92. return ret;
  93. }
  94. FileAccess::CreateFunc FileAccess::get_create_func(AccessType p_access) {
  95. return create_func[p_access];
  96. }
  97. String FileAccess::fix_path(const String &p_path) const {
  98. //helper used by file accesses that use a single filesystem
  99. String r_path = p_path.replace("\\", "/");
  100. switch (_access_type) {
  101. case ACCESS_RESOURCES: {
  102. if (ProjectSettings::get_singleton()) {
  103. if (r_path.begins_with("res://")) {
  104. String resource_path = ProjectSettings::get_singleton()->get_resource_path();
  105. if (!resource_path.is_empty()) {
  106. return r_path.replace("res:/", resource_path);
  107. }
  108. return r_path.replace("res://", "");
  109. }
  110. }
  111. } break;
  112. case ACCESS_USERDATA: {
  113. if (r_path.begins_with("user://")) {
  114. String data_dir = OS::get_singleton()->get_user_data_dir();
  115. if (!data_dir.is_empty()) {
  116. return r_path.replace("user:/", data_dir);
  117. }
  118. return r_path.replace("user://", "");
  119. }
  120. } break;
  121. case ACCESS_FILESYSTEM: {
  122. return r_path;
  123. } break;
  124. case ACCESS_MAX:
  125. break; // Can't happen, but silences warning
  126. }
  127. return r_path;
  128. }
  129. /* these are all implemented for ease of porting, then can later be optimized */
  130. uint16_t FileAccess::get_16() const {
  131. uint16_t res;
  132. uint8_t a, b;
  133. a = get_8();
  134. b = get_8();
  135. if (big_endian) {
  136. SWAP(a, b);
  137. }
  138. res = b;
  139. res <<= 8;
  140. res |= a;
  141. return res;
  142. }
  143. uint32_t FileAccess::get_32() const {
  144. uint32_t res;
  145. uint16_t a, b;
  146. a = get_16();
  147. b = get_16();
  148. if (big_endian) {
  149. SWAP(a, b);
  150. }
  151. res = b;
  152. res <<= 16;
  153. res |= a;
  154. return res;
  155. }
  156. uint64_t FileAccess::get_64() const {
  157. uint64_t res;
  158. uint32_t a, b;
  159. a = get_32();
  160. b = get_32();
  161. if (big_endian) {
  162. SWAP(a, b);
  163. }
  164. res = b;
  165. res <<= 32;
  166. res |= a;
  167. return res;
  168. }
  169. float FileAccess::get_float() const {
  170. MarshallFloat m;
  171. m.i = get_32();
  172. return m.f;
  173. }
  174. real_t FileAccess::get_real() const {
  175. if (real_is_double) {
  176. return get_double();
  177. } else {
  178. return get_float();
  179. }
  180. }
  181. double FileAccess::get_double() const {
  182. MarshallDouble m;
  183. m.l = get_64();
  184. return m.d;
  185. }
  186. String FileAccess::get_token() const {
  187. CharString token;
  188. char32_t c = get_8();
  189. while (!eof_reached()) {
  190. if (c <= ' ') {
  191. if (token.length()) {
  192. break;
  193. }
  194. } else {
  195. token += c;
  196. }
  197. c = get_8();
  198. }
  199. return String::utf8(token.get_data());
  200. }
  201. class CharBuffer {
  202. Vector<char> vector;
  203. char stack_buffer[256];
  204. char *buffer = nullptr;
  205. int capacity = 0;
  206. int written = 0;
  207. bool grow() {
  208. if (vector.resize(next_power_of_2(1 + written)) != OK) {
  209. return false;
  210. }
  211. if (buffer == stack_buffer) { // first chunk?
  212. for (int i = 0; i < written; i++) {
  213. vector.write[i] = stack_buffer[i];
  214. }
  215. }
  216. buffer = vector.ptrw();
  217. capacity = vector.size();
  218. ERR_FAIL_COND_V(written >= capacity, false);
  219. return true;
  220. }
  221. public:
  222. _FORCE_INLINE_ CharBuffer() :
  223. buffer(stack_buffer),
  224. capacity(sizeof(stack_buffer) / sizeof(char)) {
  225. }
  226. _FORCE_INLINE_ void push_back(char c) {
  227. if (written >= capacity) {
  228. ERR_FAIL_COND(!grow());
  229. }
  230. buffer[written++] = c;
  231. }
  232. _FORCE_INLINE_ const char *get_data() const {
  233. return buffer;
  234. }
  235. };
  236. String FileAccess::get_line() const {
  237. CharBuffer line;
  238. char32_t c = get_8();
  239. while (!eof_reached()) {
  240. if (c == '\n' || c == '\0') {
  241. line.push_back(0);
  242. return String::utf8(line.get_data());
  243. } else if (c != '\r') {
  244. line.push_back(c);
  245. }
  246. c = get_8();
  247. }
  248. line.push_back(0);
  249. return String::utf8(line.get_data());
  250. }
  251. Vector<String> FileAccess::get_csv_line(const String &p_delim) const {
  252. ERR_FAIL_COND_V_MSG(p_delim.length() != 1, Vector<String>(), "Only single character delimiters are supported to parse CSV lines.");
  253. ERR_FAIL_COND_V_MSG(p_delim[0] == '"', Vector<String>(), "The double quotation mark character (\") is not supported as a delimiter for CSV lines.");
  254. String line;
  255. // CSV can support entries with line breaks as long as they are enclosed
  256. // in double quotes. So our "line" might be more than a single line in the
  257. // text file.
  258. int qc = 0;
  259. do {
  260. if (eof_reached()) {
  261. break;
  262. }
  263. line += get_line() + "\n";
  264. qc = 0;
  265. for (int i = 0; i < line.length(); i++) {
  266. if (line[i] == '"') {
  267. qc++;
  268. }
  269. }
  270. } while (qc % 2);
  271. // Remove the extraneous newline we've added above.
  272. line = line.substr(0, line.length() - 1);
  273. Vector<String> strings;
  274. bool in_quote = false;
  275. String current;
  276. for (int i = 0; i < line.length(); i++) {
  277. char32_t c = line[i];
  278. // A delimiter ends the current entry, unless it's in a quoted string.
  279. if (!in_quote && c == p_delim[0]) {
  280. strings.push_back(current);
  281. current = String();
  282. } else if (c == '"') {
  283. // Doubled quotes are escapes for intentional quotes in the string.
  284. if (line[i + 1] == '"' && in_quote) {
  285. current += '"';
  286. i++;
  287. } else {
  288. in_quote = !in_quote;
  289. }
  290. } else {
  291. current += c;
  292. }
  293. }
  294. strings.push_back(current);
  295. return strings;
  296. }
  297. uint64_t FileAccess::get_buffer(uint8_t *p_dst, uint64_t p_length) const {
  298. ERR_FAIL_COND_V(!p_dst && p_length > 0, -1);
  299. uint64_t i = 0;
  300. for (i = 0; i < p_length && !eof_reached(); i++) {
  301. p_dst[i] = get_8();
  302. }
  303. return i;
  304. }
  305. String FileAccess::get_as_utf8_string(bool p_skip_cr) const {
  306. Vector<uint8_t> sourcef;
  307. uint64_t len = get_length();
  308. sourcef.resize(len + 1);
  309. uint8_t *w = sourcef.ptrw();
  310. uint64_t r = get_buffer(w, len);
  311. ERR_FAIL_COND_V(r != len, String());
  312. w[len] = 0;
  313. String s;
  314. s.parse_utf8((const char *)w, -1, p_skip_cr);
  315. return s;
  316. }
  317. void FileAccess::store_16(uint16_t p_dest) {
  318. uint8_t a, b;
  319. a = p_dest & 0xFF;
  320. b = p_dest >> 8;
  321. if (big_endian) {
  322. SWAP(a, b);
  323. }
  324. store_8(a);
  325. store_8(b);
  326. }
  327. void FileAccess::store_32(uint32_t p_dest) {
  328. uint16_t a, b;
  329. a = p_dest & 0xFFFF;
  330. b = p_dest >> 16;
  331. if (big_endian) {
  332. SWAP(a, b);
  333. }
  334. store_16(a);
  335. store_16(b);
  336. }
  337. void FileAccess::store_64(uint64_t p_dest) {
  338. uint32_t a, b;
  339. a = p_dest & 0xFFFFFFFF;
  340. b = p_dest >> 32;
  341. if (big_endian) {
  342. SWAP(a, b);
  343. }
  344. store_32(a);
  345. store_32(b);
  346. }
  347. void FileAccess::store_real(real_t p_real) {
  348. if (sizeof(real_t) == 4) {
  349. store_float(p_real);
  350. } else {
  351. store_double(p_real);
  352. }
  353. }
  354. void FileAccess::store_float(float p_dest) {
  355. MarshallFloat m;
  356. m.f = p_dest;
  357. store_32(m.i);
  358. }
  359. void FileAccess::store_double(double p_dest) {
  360. MarshallDouble m;
  361. m.d = p_dest;
  362. store_64(m.l);
  363. }
  364. uint64_t FileAccess::get_modified_time(const String &p_file) {
  365. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  366. return 0;
  367. }
  368. Ref<FileAccess> fa = create_for_path(p_file);
  369. ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "Cannot create FileAccess for path '" + p_file + "'.");
  370. uint64_t mt = fa->_get_modified_time(p_file);
  371. return mt;
  372. }
  373. uint32_t FileAccess::get_unix_permissions(const String &p_file) {
  374. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  375. return 0;
  376. }
  377. Ref<FileAccess> fa = create_for_path(p_file);
  378. ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "Cannot create FileAccess for path '" + p_file + "'.");
  379. uint32_t mt = fa->_get_unix_permissions(p_file);
  380. return mt;
  381. }
  382. Error FileAccess::set_unix_permissions(const String &p_file, uint32_t p_permissions) {
  383. if (PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled() && (PackedData::get_singleton()->has_path(p_file) || PackedData::get_singleton()->has_directory(p_file))) {
  384. return ERR_UNAVAILABLE;
  385. }
  386. Ref<FileAccess> fa = create_for_path(p_file);
  387. ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, "Cannot create FileAccess for path '" + p_file + "'.");
  388. Error err = fa->_set_unix_permissions(p_file, p_permissions);
  389. return err;
  390. }
  391. void FileAccess::store_string(const String &p_string) {
  392. if (p_string.length() == 0) {
  393. return;
  394. }
  395. CharString cs = p_string.utf8();
  396. store_buffer((uint8_t *)&cs[0], cs.length());
  397. }
  398. void FileAccess::store_pascal_string(const String &p_string) {
  399. CharString cs = p_string.utf8();
  400. store_32(cs.length());
  401. store_buffer((uint8_t *)&cs[0], cs.length());
  402. }
  403. String FileAccess::get_pascal_string() {
  404. uint32_t sl = get_32();
  405. CharString cs;
  406. cs.resize(sl + 1);
  407. get_buffer((uint8_t *)cs.ptr(), sl);
  408. cs[sl] = 0;
  409. String ret;
  410. ret.parse_utf8(cs.ptr());
  411. return ret;
  412. }
  413. void FileAccess::store_line(const String &p_line) {
  414. store_string(p_line);
  415. store_8('\n');
  416. }
  417. void FileAccess::store_csv_line(const Vector<String> &p_values, const String &p_delim) {
  418. ERR_FAIL_COND(p_delim.length() != 1);
  419. String line = "";
  420. int size = p_values.size();
  421. for (int i = 0; i < size; ++i) {
  422. String value = p_values[i];
  423. if (value.contains("\"") || value.contains(p_delim) || value.contains("\n")) {
  424. value = "\"" + value.replace("\"", "\"\"") + "\"";
  425. }
  426. if (i < size - 1) {
  427. value += p_delim;
  428. }
  429. line += value;
  430. }
  431. store_line(line);
  432. }
  433. void FileAccess::store_buffer(const uint8_t *p_src, uint64_t p_length) {
  434. ERR_FAIL_COND(!p_src && p_length > 0);
  435. for (uint64_t i = 0; i < p_length; i++) {
  436. store_8(p_src[i]);
  437. }
  438. }
  439. Vector<uint8_t> FileAccess::get_file_as_array(const String &p_path, Error *r_error) {
  440. Ref<FileAccess> f = FileAccess::open(p_path, READ, r_error);
  441. if (f.is_null()) {
  442. if (r_error) { // if error requested, do not throw error
  443. return Vector<uint8_t>();
  444. }
  445. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Can't open file from path '" + String(p_path) + "'.");
  446. }
  447. Vector<uint8_t> data;
  448. data.resize(f->get_length());
  449. f->get_buffer(data.ptrw(), data.size());
  450. return data;
  451. }
  452. String FileAccess::get_file_as_string(const String &p_path, Error *r_error) {
  453. Error err;
  454. Vector<uint8_t> array = get_file_as_array(p_path, &err);
  455. if (r_error) {
  456. *r_error = err;
  457. }
  458. if (err != OK) {
  459. if (r_error) {
  460. return String();
  461. }
  462. ERR_FAIL_V_MSG(String(), "Can't get file as string from path '" + String(p_path) + "'.");
  463. }
  464. String ret;
  465. ret.parse_utf8((const char *)array.ptr(), array.size());
  466. return ret;
  467. }
  468. String FileAccess::get_md5(const String &p_file) {
  469. Ref<FileAccess> f = FileAccess::open(p_file, READ);
  470. if (f.is_null()) {
  471. return String();
  472. }
  473. CryptoCore::MD5Context ctx;
  474. ctx.start();
  475. unsigned char step[32768];
  476. while (true) {
  477. uint64_t br = f->get_buffer(step, 32768);
  478. if (br > 0) {
  479. ctx.update(step, br);
  480. }
  481. if (br < 4096) {
  482. break;
  483. }
  484. }
  485. unsigned char hash[16];
  486. ctx.finish(hash);
  487. return String::md5(hash);
  488. }
  489. String FileAccess::get_multiple_md5(const Vector<String> &p_file) {
  490. CryptoCore::MD5Context ctx;
  491. ctx.start();
  492. for (int i = 0; i < p_file.size(); i++) {
  493. Ref<FileAccess> f = FileAccess::open(p_file[i], READ);
  494. ERR_CONTINUE(f.is_null());
  495. unsigned char step[32768];
  496. while (true) {
  497. uint64_t br = f->get_buffer(step, 32768);
  498. if (br > 0) {
  499. ctx.update(step, br);
  500. }
  501. if (br < 4096) {
  502. break;
  503. }
  504. }
  505. }
  506. unsigned char hash[16];
  507. ctx.finish(hash);
  508. return String::md5(hash);
  509. }
  510. String FileAccess::get_sha256(const String &p_file) {
  511. Ref<FileAccess> f = FileAccess::open(p_file, READ);
  512. if (f.is_null()) {
  513. return String();
  514. }
  515. CryptoCore::SHA256Context ctx;
  516. ctx.start();
  517. unsigned char step[32768];
  518. while (true) {
  519. uint64_t br = f->get_buffer(step, 32768);
  520. if (br > 0) {
  521. ctx.update(step, br);
  522. }
  523. if (br < 4096) {
  524. break;
  525. }
  526. }
  527. unsigned char hash[32];
  528. ctx.finish(hash);
  529. return String::hex_encode_buffer(hash, 32);
  530. }