http_client_web.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /**************************************************************************/
  2. /* http_client_web.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 "http_client_web.h"
  31. void HTTPClientWeb::_parse_headers(int p_len, const char **p_headers, void *p_ref) {
  32. HTTPClientWeb *client = static_cast<HTTPClientWeb *>(p_ref);
  33. for (int i = 0; i < p_len; i++) {
  34. client->response_headers.push_back(String::utf8(p_headers[i]));
  35. }
  36. }
  37. Error HTTPClientWeb::connect_to_host(const String &p_host, int p_port, Ref<TLSOptions> p_tls_options) {
  38. ERR_FAIL_COND_V(p_tls_options.is_valid() && p_tls_options->is_server(), ERR_INVALID_PARAMETER);
  39. close();
  40. port = p_port;
  41. use_tls = p_tls_options.is_valid();
  42. host = p_host;
  43. String host_lower = host.to_lower();
  44. if (host_lower.begins_with("http://")) {
  45. host = host.substr(7, host.length() - 7);
  46. use_tls = false;
  47. } else if (host_lower.begins_with("https://")) {
  48. use_tls = true;
  49. host = host.substr(8, host.length() - 8);
  50. }
  51. ERR_FAIL_COND_V(host.length() < HOST_MIN_LEN, ERR_INVALID_PARAMETER);
  52. if (port < 0) {
  53. if (use_tls) {
  54. port = PORT_HTTPS;
  55. } else {
  56. port = PORT_HTTP;
  57. }
  58. }
  59. status = host.is_valid_ip_address() ? STATUS_CONNECTING : STATUS_RESOLVING;
  60. return OK;
  61. }
  62. void HTTPClientWeb::set_connection(const Ref<StreamPeer> &p_connection) {
  63. ERR_FAIL_MSG("Accessing an HTTPClientWeb's StreamPeer is not supported for the Web platform.");
  64. }
  65. Ref<StreamPeer> HTTPClientWeb::get_connection() const {
  66. ERR_FAIL_V_MSG(Ref<RefCounted>(), "Accessing an HTTPClientWeb's StreamPeer is not supported for the Web platform.");
  67. }
  68. Error HTTPClientWeb::request(Method p_method, const String &p_url, const Vector<String> &p_headers, const uint8_t *p_body, int p_body_len) {
  69. ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER);
  70. ERR_FAIL_COND_V_MSG(p_method == METHOD_TRACE || p_method == METHOD_CONNECT, ERR_UNAVAILABLE, "HTTP methods TRACE and CONNECT are not supported for the Web platform.");
  71. ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER);
  72. ERR_FAIL_COND_V(host.is_empty(), ERR_UNCONFIGURED);
  73. ERR_FAIL_COND_V(port < 0, ERR_UNCONFIGURED);
  74. ERR_FAIL_COND_V(!p_url.begins_with("/"), ERR_INVALID_PARAMETER);
  75. Error err = verify_headers(p_headers);
  76. if (err) {
  77. return err;
  78. }
  79. String url = (use_tls ? "https://" : "http://") + host + ":" + itos(port) + p_url;
  80. Vector<CharString> keeper;
  81. Vector<const char *> c_strings;
  82. for (int i = 0; i < p_headers.size(); i++) {
  83. keeper.push_back(p_headers[i].utf8());
  84. c_strings.push_back(keeper[i].get_data());
  85. }
  86. if (js_id) {
  87. godot_js_fetch_free(js_id);
  88. }
  89. js_id = godot_js_fetch_create(_methods[p_method], url.utf8().get_data(), c_strings.ptrw(), c_strings.size(), p_body, p_body_len);
  90. status = STATUS_REQUESTING;
  91. return OK;
  92. }
  93. void HTTPClientWeb::close() {
  94. host = "";
  95. port = -1;
  96. use_tls = false;
  97. status = STATUS_DISCONNECTED;
  98. polled_response_code = 0;
  99. response_headers.resize(0);
  100. response_buffer.resize(0);
  101. if (js_id) {
  102. godot_js_fetch_free(js_id);
  103. js_id = 0;
  104. }
  105. }
  106. HTTPClientWeb::Status HTTPClientWeb::get_status() const {
  107. return status;
  108. }
  109. bool HTTPClientWeb::has_response() const {
  110. return response_headers.size() > 0;
  111. }
  112. bool HTTPClientWeb::is_response_chunked() const {
  113. return godot_js_fetch_is_chunked(js_id);
  114. }
  115. int HTTPClientWeb::get_response_code() const {
  116. return polled_response_code;
  117. }
  118. Error HTTPClientWeb::get_response_headers(List<String> *r_response) {
  119. if (!response_headers.size()) {
  120. return ERR_INVALID_PARAMETER;
  121. }
  122. for (int i = 0; i < response_headers.size(); i++) {
  123. r_response->push_back(response_headers[i]);
  124. }
  125. response_headers.clear();
  126. return OK;
  127. }
  128. int64_t HTTPClientWeb::get_response_body_length() const {
  129. // Body length cannot be consistently retrieved from the web.
  130. // Reading the "content-length" value will return a meaningless value when the response is compressed,
  131. // as reading will return uncompressed chunks in any case, resulting in a mismatch between the detected
  132. // body size and the actual size returned by repeatedly calling read_response_body_chunk.
  133. // Additionally, while "content-length" is considered a safe CORS header, "content-encoding" is not,
  134. // so using the "content-encoding" to decide if "content-length" is meaningful is not an option either.
  135. // We simply must accept the fact that browsers are awful when it comes to networking APIs.
  136. // See GH-47597, and GH-79327.
  137. return -1;
  138. }
  139. PackedByteArray HTTPClientWeb::read_response_body_chunk() {
  140. ERR_FAIL_COND_V(status != STATUS_BODY, PackedByteArray());
  141. if (response_buffer.size() != read_limit) {
  142. response_buffer.resize(read_limit);
  143. }
  144. int read = godot_js_fetch_read_chunk(js_id, response_buffer.ptrw(), read_limit);
  145. // Check if the stream is over.
  146. godot_js_fetch_state_t state = godot_js_fetch_state_get(js_id);
  147. if (state == GODOT_JS_FETCH_STATE_DONE) {
  148. status = STATUS_DISCONNECTED;
  149. } else if (state != GODOT_JS_FETCH_STATE_BODY) {
  150. status = STATUS_CONNECTION_ERROR;
  151. }
  152. PackedByteArray chunk;
  153. if (!read) {
  154. return chunk;
  155. }
  156. chunk.resize(read);
  157. memcpy(chunk.ptrw(), response_buffer.ptr(), read);
  158. return chunk;
  159. }
  160. void HTTPClientWeb::set_blocking_mode(bool p_enable) {
  161. ERR_FAIL_COND_MSG(p_enable, "HTTPClientWeb blocking mode is not supported for the Web platform.");
  162. }
  163. bool HTTPClientWeb::is_blocking_mode_enabled() const {
  164. return false;
  165. }
  166. void HTTPClientWeb::set_read_chunk_size(int p_size) {
  167. read_limit = p_size;
  168. }
  169. int HTTPClientWeb::get_read_chunk_size() const {
  170. return read_limit;
  171. }
  172. Error HTTPClientWeb::poll() {
  173. switch (status) {
  174. case STATUS_DISCONNECTED:
  175. return ERR_UNCONFIGURED;
  176. case STATUS_RESOLVING:
  177. status = STATUS_CONNECTING;
  178. return OK;
  179. case STATUS_CONNECTING:
  180. status = STATUS_CONNECTED;
  181. return OK;
  182. case STATUS_CONNECTED:
  183. return OK;
  184. case STATUS_BODY: {
  185. godot_js_fetch_state_t state = godot_js_fetch_state_get(js_id);
  186. if (state == GODOT_JS_FETCH_STATE_DONE) {
  187. status = STATUS_DISCONNECTED;
  188. } else if (state != GODOT_JS_FETCH_STATE_BODY) {
  189. status = STATUS_CONNECTION_ERROR;
  190. return ERR_CONNECTION_ERROR;
  191. }
  192. return OK;
  193. }
  194. case STATUS_CONNECTION_ERROR:
  195. return ERR_CONNECTION_ERROR;
  196. case STATUS_REQUESTING: {
  197. #ifdef DEBUG_ENABLED
  198. // forcing synchronous requests is not possible on the web
  199. if (last_polling_frame == Engine::get_singleton()->get_process_frames()) {
  200. WARN_PRINT("HTTPClientWeb polled multiple times in one frame, "
  201. "but request cannot progress more than once per "
  202. "frame on the Web platform.");
  203. }
  204. last_polling_frame = Engine::get_singleton()->get_process_frames();
  205. #endif
  206. polled_response_code = godot_js_fetch_http_status_get(js_id);
  207. godot_js_fetch_state_t js_state = godot_js_fetch_state_get(js_id);
  208. if (js_state == GODOT_JS_FETCH_STATE_REQUESTING) {
  209. return OK;
  210. } else if (js_state == GODOT_JS_FETCH_STATE_ERROR) {
  211. // Fetch is in error state.
  212. status = STATUS_CONNECTION_ERROR;
  213. return ERR_CONNECTION_ERROR;
  214. }
  215. if (godot_js_fetch_read_headers(js_id, &_parse_headers, this)) {
  216. // Failed to parse headers.
  217. status = STATUS_CONNECTION_ERROR;
  218. return ERR_CONNECTION_ERROR;
  219. }
  220. status = STATUS_BODY;
  221. break;
  222. }
  223. default:
  224. ERR_FAIL_V(ERR_BUG);
  225. }
  226. return OK;
  227. }
  228. HTTPClient *HTTPClientWeb::_create_func(bool p_notify_postinitialize) {
  229. return static_cast<HTTPClient *>(ClassDB::creator<HTTPClientWeb>(p_notify_postinitialize));
  230. }
  231. HTTPClient *(*HTTPClient::_create)(bool p_notify_postinitialize) = HTTPClientWeb::_create_func;
  232. HTTPClientWeb::HTTPClientWeb() {
  233. }
  234. HTTPClientWeb::~HTTPClientWeb() {
  235. close();
  236. }