file_access.cpp 15 KB

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