remote_filesystem_client.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /**************************************************************************/
  2. /* remote_filesystem_client.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 "remote_filesystem_client.h"
  31. #include "core/io/dir_access.h"
  32. #include "core/io/file_access.h"
  33. #include "core/io/stream_peer_tcp.h"
  34. #include "core/string/string_builder.h"
  35. #define FILESYSTEM_CACHE_VERSION 1
  36. #define FILESYSTEM_PROTOCOL_VERSION 1
  37. #define PASSWORD_LENGTH 32
  38. #define FILES_SUBFOLDER "remote_filesystem_files"
  39. #define FILES_CACHE_FILE "remote_filesystem.cache"
  40. Vector<RemoteFilesystemClient::FileCache> RemoteFilesystemClient::_load_cache_file() {
  41. Ref<FileAccess> fa = FileAccess::open(cache_path.path_join(FILES_CACHE_FILE), FileAccess::READ);
  42. if (!fa.is_valid()) {
  43. return Vector<FileCache>(); // No cache, return empty
  44. }
  45. int version = fa->get_line().to_int();
  46. if (version != FILESYSTEM_CACHE_VERSION) {
  47. return Vector<FileCache>(); // Version mismatch, ignore everything.
  48. }
  49. String file_path = cache_path.path_join(FILES_SUBFOLDER);
  50. Vector<FileCache> file_cache;
  51. while (!fa->eof_reached()) {
  52. String l = fa->get_line();
  53. Vector<String> fields = l.split("::");
  54. if (fields.size() != 3) {
  55. break;
  56. }
  57. FileCache fc;
  58. fc.path = fields[0];
  59. fc.server_modified_time = fields[1].to_int();
  60. fc.modified_time = fields[2].to_int();
  61. String full_path = file_path.path_join(fc.path);
  62. if (!FileAccess::exists(full_path)) {
  63. continue; // File is gone.
  64. }
  65. if (FileAccess::get_modified_time(full_path) != fc.modified_time) {
  66. DirAccess::remove_absolute(full_path); // Take the chance to remove this file and assume we no longer have it.
  67. continue;
  68. }
  69. file_cache.push_back(fc);
  70. }
  71. return file_cache;
  72. }
  73. Error RemoteFilesystemClient::_store_file(const String &p_path, const LocalVector<uint8_t> &p_file, uint64_t &modified_time) {
  74. modified_time = 0;
  75. String full_path = cache_path.path_join(FILES_SUBFOLDER).path_join(p_path);
  76. String base_file_dir = full_path.get_base_dir();
  77. if (!validated_directories.has(base_file_dir)) {
  78. // Verify that path exists before writing file, but only verify once for performance.
  79. DirAccess::make_dir_recursive_absolute(base_file_dir);
  80. validated_directories.insert(base_file_dir);
  81. }
  82. Ref<FileAccess> f = FileAccess::open(full_path, FileAccess::WRITE);
  83. ERR_FAIL_COND_V_MSG(f.is_null(), ERR_FILE_CANT_OPEN, "Unable to open file for writing to remote filesystem cache: " + p_path);
  84. f->store_buffer(p_file.ptr(), p_file.size());
  85. Error err = f->get_error();
  86. if (err) {
  87. return err;
  88. }
  89. f.unref(); // Unref to ensure file is not locked and modified time can be obtained.
  90. modified_time = FileAccess::get_modified_time(full_path);
  91. return OK;
  92. }
  93. Error RemoteFilesystemClient::_remove_file(const String &p_path) {
  94. return DirAccess::remove_absolute(cache_path.path_join(FILES_SUBFOLDER).path_join(p_path));
  95. }
  96. Error RemoteFilesystemClient::_store_cache_file(const Vector<FileCache> &p_cache) {
  97. String full_path = cache_path.path_join(FILES_CACHE_FILE);
  98. String base_file_dir = full_path.get_base_dir();
  99. Error err = DirAccess::make_dir_recursive_absolute(base_file_dir);
  100. ERR_FAIL_COND_V_MSG(err != OK && err != ERR_ALREADY_EXISTS, err, "Unable to create base directory to store cache file: " + base_file_dir);
  101. Ref<FileAccess> f = FileAccess::open(full_path, FileAccess::WRITE);
  102. ERR_FAIL_COND_V_MSG(f.is_null(), ERR_FILE_CANT_OPEN, "Unable to open the remote cache file for writing: " + full_path);
  103. f->store_line(itos(FILESYSTEM_CACHE_VERSION));
  104. for (int i = 0; i < p_cache.size(); i++) {
  105. String l = p_cache[i].path + "::" + itos(p_cache[i].server_modified_time) + "::" + itos(p_cache[i].modified_time);
  106. f->store_line(l);
  107. }
  108. return OK;
  109. }
  110. Error RemoteFilesystemClient::synchronize_with_server(const String &p_host, int p_port, const String &p_password, String &r_cache_path) {
  111. Error err = _synchronize_with_server(p_host, p_port, p_password, r_cache_path);
  112. // Ensure no memory is kept
  113. validated_directories.reset();
  114. cache_path = String();
  115. return err;
  116. }
  117. void RemoteFilesystemClient::_update_cache_path(String &r_cache_path) {
  118. r_cache_path = cache_path.path_join(FILES_SUBFOLDER);
  119. }
  120. Error RemoteFilesystemClient::_synchronize_with_server(const String &p_host, int p_port, const String &p_password, String &r_cache_path) {
  121. cache_path = r_cache_path;
  122. {
  123. Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  124. dir->change_dir(cache_path);
  125. cache_path = dir->get_current_dir();
  126. }
  127. Ref<StreamPeerTCP> tcp_client;
  128. tcp_client.instantiate();
  129. IPAddress ip = p_host.is_valid_ip_address() ? IPAddress(p_host) : IP::get_singleton()->resolve_hostname(p_host);
  130. ERR_FAIL_COND_V_MSG(!ip.is_valid(), ERR_INVALID_PARAMETER, "Unable to resolve remote filesystem server hostname: " + p_host);
  131. print_verbose(vformat("Remote Filesystem: Connecting to host %s, port %d.", ip, p_port));
  132. Error err = tcp_client->connect_to_host(ip, p_port);
  133. ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to open connection to remote file server (" + String(p_host) + ", port " + itos(p_port) + ") failed.");
  134. while (tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTING) {
  135. tcp_client->poll();
  136. OS::get_singleton()->delay_usec(100);
  137. }
  138. if (tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  139. ERR_FAIL_V_MSG(ERR_CANT_CONNECT, "Connection to remote file server (" + String(p_host) + ", port " + itos(p_port) + ") failed.");
  140. }
  141. // Connection OK, now send the current file state.
  142. print_verbose("Remote Filesystem: Connection OK.");
  143. // Header (GRFS) - Godot Remote File System
  144. print_verbose("Remote Filesystem: Sending header");
  145. tcp_client->put_u8('G');
  146. tcp_client->put_u8('R');
  147. tcp_client->put_u8('F');
  148. tcp_client->put_u8('S');
  149. // Protocol version
  150. tcp_client->put_32(FILESYSTEM_PROTOCOL_VERSION);
  151. print_verbose("Remote Filesystem: Sending password");
  152. uint8_t password[PASSWORD_LENGTH]; // Send fixed size password, since it's easier and safe to validate.
  153. for (int i = 0; i < PASSWORD_LENGTH; i++) {
  154. if (i < p_password.length()) {
  155. password[i] = p_password[i];
  156. } else {
  157. password[i] = 0;
  158. }
  159. }
  160. tcp_client->put_data(password, PASSWORD_LENGTH);
  161. print_verbose("Remote Filesystem: Tags.");
  162. Vector<String> tags;
  163. {
  164. tags.push_back(OS::get_singleton()->get_identifier());
  165. switch (OS::get_singleton()->get_preferred_texture_format()) {
  166. case OS::PREFERRED_TEXTURE_FORMAT_S3TC_BPTC: {
  167. tags.push_back("bptc");
  168. tags.push_back("s3tc");
  169. } break;
  170. case OS::PREFERRED_TEXTURE_FORMAT_ETC2_ASTC: {
  171. tags.push_back("etc2");
  172. tags.push_back("astc");
  173. } break;
  174. }
  175. }
  176. tcp_client->put_32(tags.size());
  177. for (int i = 0; i < tags.size(); i++) {
  178. tcp_client->put_utf8_string(tags[i]);
  179. }
  180. // Size of compressed list of files
  181. print_verbose("Remote Filesystem: Sending file list");
  182. Vector<FileCache> file_cache = _load_cache_file();
  183. // Encode file cache to send it via network.
  184. Vector<uint8_t> file_cache_buffer;
  185. if (file_cache.size()) {
  186. StringBuilder sbuild;
  187. for (int i = 0; i < file_cache.size(); i++) {
  188. sbuild.append(file_cache[i].path);
  189. sbuild.append("::");
  190. sbuild.append(itos(file_cache[i].server_modified_time));
  191. sbuild.append("\n");
  192. }
  193. String s = sbuild.as_string();
  194. CharString cs = s.utf8();
  195. file_cache_buffer.resize(Compression::get_max_compressed_buffer_size(cs.length(), Compression::MODE_ZSTD));
  196. int res_len = Compression::compress(file_cache_buffer.ptrw(), (const uint8_t *)cs.ptr(), cs.length(), Compression::MODE_ZSTD);
  197. file_cache_buffer.resize(res_len);
  198. tcp_client->put_32(cs.length()); // Size of buffer uncompressed
  199. tcp_client->put_32(file_cache_buffer.size()); // Size of buffer compressed
  200. tcp_client->put_data(file_cache_buffer.ptr(), file_cache_buffer.size()); // Buffer
  201. } else {
  202. tcp_client->put_32(0); // No file cache buffer
  203. }
  204. tcp_client->poll();
  205. ERR_FAIL_COND_V_MSG(tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED, ERR_CONNECTION_ERROR, "Remote filesystem server disconnected after sending header.");
  206. uint32_t file_count = tcp_client->get_32();
  207. ERR_FAIL_COND_V_MSG(tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED, ERR_CONNECTION_ERROR, "Remote filesystem server disconnected while waiting for file list");
  208. LocalVector<uint8_t> file_buffer;
  209. Vector<FileCache> temp_file_cache;
  210. HashSet<String> files_processed;
  211. for (uint32_t i = 0; i < file_count; i++) {
  212. String file = tcp_client->get_utf8_string();
  213. ERR_FAIL_COND_V_MSG(file == String(), ERR_CONNECTION_ERROR, "Invalid file name received from remote filesystem.");
  214. uint64_t server_modified_time = tcp_client->get_u64();
  215. ERR_FAIL_COND_V_MSG(tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED, ERR_CONNECTION_ERROR, "Remote filesystem server disconnected while waiting for file info.");
  216. FileCache fc;
  217. fc.path = file;
  218. fc.server_modified_time = server_modified_time;
  219. temp_file_cache.push_back(fc);
  220. files_processed.insert(file);
  221. }
  222. Vector<FileCache> new_file_cache;
  223. // Get the actual files. As a robustness measure, if the connection is interrupted here, any file not yet received will be considered removed.
  224. // Since the file changed anyway, this makes it the easiest way to keep robustness.
  225. bool server_disconnected = false;
  226. for (uint32_t i = 0; i < file_count; i++) {
  227. String file = temp_file_cache[i].path;
  228. if (temp_file_cache[i].server_modified_time == 0 || server_disconnected) {
  229. // File was removed, or server disconnected before transferring it. Since it's no longer valid, remove anyway.
  230. _remove_file(file);
  231. continue;
  232. }
  233. uint64_t file_size = tcp_client->get_u64();
  234. file_buffer.resize(file_size);
  235. err = tcp_client->get_data(file_buffer.ptr(), file_size);
  236. if (err != OK) {
  237. ERR_PRINT("Error retrieving file from remote filesystem: " + file);
  238. server_disconnected = true;
  239. }
  240. if (tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  241. // Early disconnect, stop accepting files.
  242. server_disconnected = true;
  243. }
  244. if (server_disconnected) {
  245. // No more server, transfer is invalid, remove this file.
  246. _remove_file(file);
  247. continue;
  248. }
  249. uint64_t modified_time = 0;
  250. err = _store_file(file, file_buffer, modified_time);
  251. if (err != OK) {
  252. server_disconnected = true;
  253. continue;
  254. }
  255. FileCache fc = temp_file_cache[i];
  256. fc.modified_time = modified_time;
  257. new_file_cache.push_back(fc);
  258. }
  259. print_verbose("Remote Filesystem: Updating the cache file.");
  260. // Go through the list of local files read initially (file_cache) and see which ones are
  261. // unchanged (not sent again from the server).
  262. // These need to be re-saved in the new list (new_file_cache).
  263. for (int i = 0; i < file_cache.size(); i++) {
  264. if (files_processed.has(file_cache[i].path)) {
  265. continue; // This was either added or removed, so skip.
  266. }
  267. new_file_cache.push_back(file_cache[i]);
  268. }
  269. err = _store_cache_file(new_file_cache);
  270. ERR_FAIL_COND_V_MSG(err != OK, ERR_FILE_CANT_OPEN, "Error writing the remote filesystem file cache.");
  271. print_verbose("Remote Filesystem: Update success.");
  272. _update_cache_path(r_cache_path);
  273. return OK;
  274. }