export_server.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*************************************************************************/
  2. /* export_server.h */
  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. #ifndef JAVASCRIPT_EXPORT_SERVER_H
  31. #define JAVASCRIPT_EXPORT_SERVER_H
  32. #include "core/io/image_loader.h"
  33. #include "core/io/stream_peer_ssl.h"
  34. #include "core/io/tcp_server.h"
  35. #include "core/io/zip_io.h"
  36. #include "editor/editor_paths.h"
  37. class EditorHTTPServer : public RefCounted {
  38. private:
  39. Ref<TCPServer> server;
  40. HashMap<String, String> mimes;
  41. Ref<StreamPeerTCP> tcp;
  42. Ref<StreamPeerSSL> ssl;
  43. Ref<StreamPeer> peer;
  44. Ref<CryptoKey> key;
  45. Ref<X509Certificate> cert;
  46. bool use_ssl = false;
  47. uint64_t time = 0;
  48. uint8_t req_buf[4096];
  49. int req_pos = 0;
  50. void _clear_client() {
  51. peer = Ref<StreamPeer>();
  52. ssl = Ref<StreamPeerSSL>();
  53. tcp = Ref<StreamPeerTCP>();
  54. memset(req_buf, 0, sizeof(req_buf));
  55. time = 0;
  56. req_pos = 0;
  57. }
  58. void _set_internal_certs(Ref<Crypto> p_crypto) {
  59. const String cache_path = EditorPaths::get_singleton()->get_cache_dir();
  60. const String key_path = cache_path.plus_file("html5_server.key");
  61. const String crt_path = cache_path.plus_file("html5_server.crt");
  62. bool regen = !FileAccess::exists(key_path) || !FileAccess::exists(crt_path);
  63. if (!regen) {
  64. key = Ref<CryptoKey>(CryptoKey::create());
  65. cert = Ref<X509Certificate>(X509Certificate::create());
  66. if (key->load(key_path) != OK || cert->load(crt_path) != OK) {
  67. regen = true;
  68. }
  69. }
  70. if (regen) {
  71. key = p_crypto->generate_rsa(2048);
  72. key->save(key_path);
  73. cert = p_crypto->generate_self_signed_certificate(key, "CN=godot-debug.local,O=A Game Dev,C=XXA", "20140101000000", "20340101000000");
  74. cert->save(crt_path);
  75. }
  76. }
  77. public:
  78. EditorHTTPServer() {
  79. mimes["html"] = "text/html";
  80. mimes["js"] = "application/javascript";
  81. mimes["json"] = "application/json";
  82. mimes["pck"] = "application/octet-stream";
  83. mimes["png"] = "image/png";
  84. mimes["svg"] = "image/svg";
  85. mimes["wasm"] = "application/wasm";
  86. server.instantiate();
  87. stop();
  88. }
  89. void stop() {
  90. server->stop();
  91. _clear_client();
  92. }
  93. Error listen(int p_port, IPAddress p_address, bool p_use_ssl, String p_ssl_key, String p_ssl_cert) {
  94. use_ssl = p_use_ssl;
  95. if (use_ssl) {
  96. Ref<Crypto> crypto = Crypto::create();
  97. if (crypto.is_null()) {
  98. return ERR_UNAVAILABLE;
  99. }
  100. if (!p_ssl_key.is_empty() && !p_ssl_cert.is_empty()) {
  101. key = Ref<CryptoKey>(CryptoKey::create());
  102. Error err = key->load(p_ssl_key);
  103. ERR_FAIL_COND_V(err != OK, err);
  104. cert = Ref<X509Certificate>(X509Certificate::create());
  105. err = cert->load(p_ssl_cert);
  106. ERR_FAIL_COND_V(err != OK, err);
  107. } else {
  108. _set_internal_certs(crypto);
  109. }
  110. }
  111. return server->listen(p_port, p_address);
  112. }
  113. bool is_listening() const {
  114. return server->is_listening();
  115. }
  116. void _send_response() {
  117. Vector<String> psa = String((char *)req_buf).split("\r\n");
  118. int len = psa.size();
  119. ERR_FAIL_COND_MSG(len < 4, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
  120. Vector<String> req = psa[0].split(" ", false);
  121. ERR_FAIL_COND_MSG(req.size() < 2, "Invalid protocol or status code.");
  122. // Wrong protocol
  123. ERR_FAIL_COND_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", "Invalid method or HTTP version.");
  124. const int query_index = req[1].find_char('?');
  125. const String path = (query_index == -1) ? req[1] : req[1].substr(0, query_index);
  126. const String req_file = path.get_file();
  127. const String req_ext = path.get_extension();
  128. const String cache_path = EditorPaths::get_singleton()->get_cache_dir().plus_file("web");
  129. const String filepath = cache_path.plus_file(req_file);
  130. if (!mimes.has(req_ext) || !FileAccess::exists(filepath)) {
  131. String s = "HTTP/1.1 404 Not Found\r\n";
  132. s += "Connection: Close\r\n";
  133. s += "\r\n";
  134. CharString cs = s.utf8();
  135. peer->put_data((const uint8_t *)cs.get_data(), cs.size() - 1);
  136. return;
  137. }
  138. const String ctype = mimes[req_ext];
  139. Ref<FileAccess> f = FileAccess::open(filepath, FileAccess::READ);
  140. ERR_FAIL_COND(f.is_null());
  141. String s = "HTTP/1.1 200 OK\r\n";
  142. s += "Connection: Close\r\n";
  143. s += "Content-Type: " + ctype + "\r\n";
  144. s += "Access-Control-Allow-Origin: *\r\n";
  145. s += "Cross-Origin-Opener-Policy: same-origin\r\n";
  146. s += "Cross-Origin-Embedder-Policy: require-corp\r\n";
  147. s += "Cache-Control: no-store, max-age=0\r\n";
  148. s += "\r\n";
  149. CharString cs = s.utf8();
  150. Error err = peer->put_data((const uint8_t *)cs.get_data(), cs.size() - 1);
  151. if (err != OK) {
  152. ERR_FAIL();
  153. }
  154. while (true) {
  155. uint8_t bytes[4096];
  156. uint64_t read = f->get_buffer(bytes, 4096);
  157. if (read == 0) {
  158. break;
  159. }
  160. err = peer->put_data(bytes, read);
  161. if (err != OK) {
  162. ERR_FAIL();
  163. }
  164. }
  165. }
  166. void poll() {
  167. if (!server->is_listening()) {
  168. return;
  169. }
  170. if (tcp.is_null()) {
  171. if (!server->is_connection_available()) {
  172. return;
  173. }
  174. tcp = server->take_connection();
  175. peer = tcp;
  176. time = OS::get_singleton()->get_ticks_usec();
  177. }
  178. if (OS::get_singleton()->get_ticks_usec() - time > 1000000) {
  179. _clear_client();
  180. return;
  181. }
  182. if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  183. return;
  184. }
  185. if (use_ssl) {
  186. if (ssl.is_null()) {
  187. ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
  188. peer = ssl;
  189. ssl->set_blocking_handshake_enabled(false);
  190. if (ssl->accept_stream(tcp, key, cert) != OK) {
  191. _clear_client();
  192. return;
  193. }
  194. }
  195. ssl->poll();
  196. if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) {
  197. // Still handshaking, keep waiting.
  198. return;
  199. }
  200. if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
  201. _clear_client();
  202. return;
  203. }
  204. }
  205. while (true) {
  206. char *r = (char *)req_buf;
  207. int l = req_pos - 1;
  208. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  209. _send_response();
  210. _clear_client();
  211. return;
  212. }
  213. int read = 0;
  214. ERR_FAIL_COND(req_pos >= 4096);
  215. Error err = peer->get_partial_data(&req_buf[req_pos], 1, read);
  216. if (err != OK) {
  217. // Got an error
  218. _clear_client();
  219. return;
  220. } else if (read != 1) {
  221. // Busy, wait next poll
  222. return;
  223. }
  224. req_pos += read;
  225. }
  226. }
  227. };
  228. #endif // JAVASCRIPT_EXPORT_SERVER_H