http_client.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /**************************************************************************/
  2. /* http_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 "http_client.h"
  31. const char *HTTPClient::_methods[METHOD_MAX] = {
  32. "GET",
  33. "HEAD",
  34. "POST",
  35. "PUT",
  36. "DELETE",
  37. "OPTIONS",
  38. "TRACE",
  39. "CONNECT",
  40. "PATCH"
  41. };
  42. HTTPClient *HTTPClient::create() {
  43. if (_create) {
  44. return _create();
  45. }
  46. return nullptr;
  47. }
  48. void HTTPClient::set_http_proxy(const String &p_host, int p_port) {
  49. WARN_PRINT("HTTP proxy feature is not available");
  50. }
  51. void HTTPClient::set_https_proxy(const String &p_host, int p_port) {
  52. WARN_PRINT("HTTPS proxy feature is not available");
  53. }
  54. Error HTTPClient::_request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const Vector<uint8_t> &p_body) {
  55. int size = p_body.size();
  56. return request(p_method, p_url, p_headers, size > 0 ? p_body.ptr() : nullptr, size);
  57. }
  58. Error HTTPClient::_request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body) {
  59. CharString body_utf8 = p_body.utf8();
  60. int size = body_utf8.length();
  61. return request(p_method, p_url, p_headers, size > 0 ? (const uint8_t *)body_utf8.get_data() : nullptr, size);
  62. }
  63. String HTTPClient::query_string_from_dict(const Dictionary &p_dict) {
  64. String query = "";
  65. Array keys = p_dict.keys();
  66. for (int i = 0; i < keys.size(); ++i) {
  67. String encoded_key = String(keys[i]).uri_encode();
  68. const Variant &value = p_dict[keys[i]];
  69. switch (value.get_type()) {
  70. case Variant::ARRAY: {
  71. // Repeat the key with every values
  72. Array values = value;
  73. for (int j = 0; j < values.size(); ++j) {
  74. query += "&" + encoded_key + "=" + String(values[j]).uri_encode();
  75. }
  76. break;
  77. }
  78. case Variant::NIL: {
  79. // Add the key with no value
  80. query += "&" + encoded_key;
  81. break;
  82. }
  83. default: {
  84. // Add the key-value pair
  85. query += "&" + encoded_key + "=" + String(value).uri_encode();
  86. }
  87. }
  88. }
  89. return query.substr(1);
  90. }
  91. Error HTTPClient::verify_headers(const Vector<String> &p_headers) {
  92. for (int i = 0; i < p_headers.size(); i++) {
  93. String sanitized = p_headers[i].strip_edges();
  94. ERR_FAIL_COND_V_MSG(sanitized.is_empty(), ERR_INVALID_PARAMETER, "Invalid HTTP header at index " + itos(i) + ": empty.");
  95. ERR_FAIL_COND_V_MSG(sanitized.find(":") < 1, ERR_INVALID_PARAMETER,
  96. "Invalid HTTP header at index " + itos(i) + ": String must contain header-value pair, delimited by ':', but was: " + p_headers[i]);
  97. }
  98. return OK;
  99. }
  100. Dictionary HTTPClient::_get_response_headers_as_dictionary() {
  101. List<String> rh;
  102. get_response_headers(&rh);
  103. Dictionary ret;
  104. for (const String &s : rh) {
  105. int sp = s.find(":");
  106. if (sp == -1) {
  107. continue;
  108. }
  109. String key = s.substr(0, sp).strip_edges();
  110. String value = s.substr(sp + 1, s.length()).strip_edges();
  111. ret[key] = value;
  112. }
  113. return ret;
  114. }
  115. PackedStringArray HTTPClient::_get_response_headers() {
  116. List<String> rh;
  117. get_response_headers(&rh);
  118. PackedStringArray ret;
  119. ret.resize(rh.size());
  120. int idx = 0;
  121. for (const String &E : rh) {
  122. ret.set(idx++, E);
  123. }
  124. return ret;
  125. }
  126. void HTTPClient::_bind_methods() {
  127. ClassDB::bind_method(D_METHOD("connect_to_host", "host", "port", "tls_options"), &HTTPClient::connect_to_host, DEFVAL(-1), DEFVAL(Ref<TLSOptions>()));
  128. ClassDB::bind_method(D_METHOD("set_connection", "connection"), &HTTPClient::set_connection);
  129. ClassDB::bind_method(D_METHOD("get_connection"), &HTTPClient::get_connection);
  130. ClassDB::bind_method(D_METHOD("request_raw", "method", "url", "headers", "body"), &HTTPClient::_request_raw);
  131. ClassDB::bind_method(D_METHOD("request", "method", "url", "headers", "body"), &HTTPClient::_request, DEFVAL(String()));
  132. ClassDB::bind_method(D_METHOD("close"), &HTTPClient::close);
  133. ClassDB::bind_method(D_METHOD("has_response"), &HTTPClient::has_response);
  134. ClassDB::bind_method(D_METHOD("is_response_chunked"), &HTTPClient::is_response_chunked);
  135. ClassDB::bind_method(D_METHOD("get_response_code"), &HTTPClient::get_response_code);
  136. ClassDB::bind_method(D_METHOD("get_response_headers"), &HTTPClient::_get_response_headers);
  137. ClassDB::bind_method(D_METHOD("get_response_headers_as_dictionary"), &HTTPClient::_get_response_headers_as_dictionary);
  138. ClassDB::bind_method(D_METHOD("get_response_body_length"), &HTTPClient::get_response_body_length);
  139. ClassDB::bind_method(D_METHOD("read_response_body_chunk"), &HTTPClient::read_response_body_chunk);
  140. ClassDB::bind_method(D_METHOD("set_read_chunk_size", "bytes"), &HTTPClient::set_read_chunk_size);
  141. ClassDB::bind_method(D_METHOD("get_read_chunk_size"), &HTTPClient::get_read_chunk_size);
  142. ClassDB::bind_method(D_METHOD("set_blocking_mode", "enabled"), &HTTPClient::set_blocking_mode);
  143. ClassDB::bind_method(D_METHOD("is_blocking_mode_enabled"), &HTTPClient::is_blocking_mode_enabled);
  144. ClassDB::bind_method(D_METHOD("get_status"), &HTTPClient::get_status);
  145. ClassDB::bind_method(D_METHOD("poll"), &HTTPClient::poll);
  146. ClassDB::bind_method(D_METHOD("set_http_proxy", "host", "port"), &HTTPClient::set_http_proxy);
  147. ClassDB::bind_method(D_METHOD("set_https_proxy", "host", "port"), &HTTPClient::set_https_proxy);
  148. ClassDB::bind_method(D_METHOD("query_string_from_dict", "fields"), &HTTPClient::query_string_from_dict);
  149. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "blocking_mode_enabled"), "set_blocking_mode", "is_blocking_mode_enabled");
  150. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "connection", PROPERTY_HINT_RESOURCE_TYPE, "StreamPeer", PROPERTY_USAGE_NONE), "set_connection", "get_connection");
  151. ADD_PROPERTY(PropertyInfo(Variant::INT, "read_chunk_size", PROPERTY_HINT_RANGE, "256,16777216"), "set_read_chunk_size", "get_read_chunk_size");
  152. BIND_ENUM_CONSTANT(METHOD_GET);
  153. BIND_ENUM_CONSTANT(METHOD_HEAD);
  154. BIND_ENUM_CONSTANT(METHOD_POST);
  155. BIND_ENUM_CONSTANT(METHOD_PUT);
  156. BIND_ENUM_CONSTANT(METHOD_DELETE);
  157. BIND_ENUM_CONSTANT(METHOD_OPTIONS);
  158. BIND_ENUM_CONSTANT(METHOD_TRACE);
  159. BIND_ENUM_CONSTANT(METHOD_CONNECT);
  160. BIND_ENUM_CONSTANT(METHOD_PATCH);
  161. BIND_ENUM_CONSTANT(METHOD_MAX);
  162. BIND_ENUM_CONSTANT(STATUS_DISCONNECTED);
  163. BIND_ENUM_CONSTANT(STATUS_RESOLVING); // Resolving hostname (if hostname was passed in)
  164. BIND_ENUM_CONSTANT(STATUS_CANT_RESOLVE);
  165. BIND_ENUM_CONSTANT(STATUS_CONNECTING); // Connecting to IP
  166. BIND_ENUM_CONSTANT(STATUS_CANT_CONNECT);
  167. BIND_ENUM_CONSTANT(STATUS_CONNECTED); // Connected, now accepting requests
  168. BIND_ENUM_CONSTANT(STATUS_REQUESTING); // Request in progress
  169. BIND_ENUM_CONSTANT(STATUS_BODY); // Request resulted in body which must be read
  170. BIND_ENUM_CONSTANT(STATUS_CONNECTION_ERROR);
  171. BIND_ENUM_CONSTANT(STATUS_TLS_HANDSHAKE_ERROR);
  172. BIND_ENUM_CONSTANT(RESPONSE_CONTINUE);
  173. BIND_ENUM_CONSTANT(RESPONSE_SWITCHING_PROTOCOLS);
  174. BIND_ENUM_CONSTANT(RESPONSE_PROCESSING);
  175. // 2xx successful
  176. BIND_ENUM_CONSTANT(RESPONSE_OK);
  177. BIND_ENUM_CONSTANT(RESPONSE_CREATED);
  178. BIND_ENUM_CONSTANT(RESPONSE_ACCEPTED);
  179. BIND_ENUM_CONSTANT(RESPONSE_NON_AUTHORITATIVE_INFORMATION);
  180. BIND_ENUM_CONSTANT(RESPONSE_NO_CONTENT);
  181. BIND_ENUM_CONSTANT(RESPONSE_RESET_CONTENT);
  182. BIND_ENUM_CONSTANT(RESPONSE_PARTIAL_CONTENT);
  183. BIND_ENUM_CONSTANT(RESPONSE_MULTI_STATUS);
  184. BIND_ENUM_CONSTANT(RESPONSE_ALREADY_REPORTED);
  185. BIND_ENUM_CONSTANT(RESPONSE_IM_USED);
  186. // 3xx redirection
  187. BIND_ENUM_CONSTANT(RESPONSE_MULTIPLE_CHOICES);
  188. BIND_ENUM_CONSTANT(RESPONSE_MOVED_PERMANENTLY);
  189. BIND_ENUM_CONSTANT(RESPONSE_FOUND);
  190. BIND_ENUM_CONSTANT(RESPONSE_SEE_OTHER);
  191. BIND_ENUM_CONSTANT(RESPONSE_NOT_MODIFIED);
  192. BIND_ENUM_CONSTANT(RESPONSE_USE_PROXY);
  193. BIND_ENUM_CONSTANT(RESPONSE_SWITCH_PROXY);
  194. BIND_ENUM_CONSTANT(RESPONSE_TEMPORARY_REDIRECT);
  195. BIND_ENUM_CONSTANT(RESPONSE_PERMANENT_REDIRECT);
  196. // 4xx client error
  197. BIND_ENUM_CONSTANT(RESPONSE_BAD_REQUEST);
  198. BIND_ENUM_CONSTANT(RESPONSE_UNAUTHORIZED);
  199. BIND_ENUM_CONSTANT(RESPONSE_PAYMENT_REQUIRED);
  200. BIND_ENUM_CONSTANT(RESPONSE_FORBIDDEN);
  201. BIND_ENUM_CONSTANT(RESPONSE_NOT_FOUND);
  202. BIND_ENUM_CONSTANT(RESPONSE_METHOD_NOT_ALLOWED);
  203. BIND_ENUM_CONSTANT(RESPONSE_NOT_ACCEPTABLE);
  204. BIND_ENUM_CONSTANT(RESPONSE_PROXY_AUTHENTICATION_REQUIRED);
  205. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_TIMEOUT);
  206. BIND_ENUM_CONSTANT(RESPONSE_CONFLICT);
  207. BIND_ENUM_CONSTANT(RESPONSE_GONE);
  208. BIND_ENUM_CONSTANT(RESPONSE_LENGTH_REQUIRED);
  209. BIND_ENUM_CONSTANT(RESPONSE_PRECONDITION_FAILED);
  210. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_ENTITY_TOO_LARGE);
  211. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_URI_TOO_LONG);
  212. BIND_ENUM_CONSTANT(RESPONSE_UNSUPPORTED_MEDIA_TYPE);
  213. BIND_ENUM_CONSTANT(RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE);
  214. BIND_ENUM_CONSTANT(RESPONSE_EXPECTATION_FAILED);
  215. BIND_ENUM_CONSTANT(RESPONSE_IM_A_TEAPOT);
  216. BIND_ENUM_CONSTANT(RESPONSE_MISDIRECTED_REQUEST);
  217. BIND_ENUM_CONSTANT(RESPONSE_UNPROCESSABLE_ENTITY);
  218. BIND_ENUM_CONSTANT(RESPONSE_LOCKED);
  219. BIND_ENUM_CONSTANT(RESPONSE_FAILED_DEPENDENCY);
  220. BIND_ENUM_CONSTANT(RESPONSE_UPGRADE_REQUIRED);
  221. BIND_ENUM_CONSTANT(RESPONSE_PRECONDITION_REQUIRED);
  222. BIND_ENUM_CONSTANT(RESPONSE_TOO_MANY_REQUESTS);
  223. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_HEADER_FIELDS_TOO_LARGE);
  224. BIND_ENUM_CONSTANT(RESPONSE_UNAVAILABLE_FOR_LEGAL_REASONS);
  225. // 5xx server error
  226. BIND_ENUM_CONSTANT(RESPONSE_INTERNAL_SERVER_ERROR);
  227. BIND_ENUM_CONSTANT(RESPONSE_NOT_IMPLEMENTED);
  228. BIND_ENUM_CONSTANT(RESPONSE_BAD_GATEWAY);
  229. BIND_ENUM_CONSTANT(RESPONSE_SERVICE_UNAVAILABLE);
  230. BIND_ENUM_CONSTANT(RESPONSE_GATEWAY_TIMEOUT);
  231. BIND_ENUM_CONSTANT(RESPONSE_HTTP_VERSION_NOT_SUPPORTED);
  232. BIND_ENUM_CONSTANT(RESPONSE_VARIANT_ALSO_NEGOTIATES);
  233. BIND_ENUM_CONSTANT(RESPONSE_INSUFFICIENT_STORAGE);
  234. BIND_ENUM_CONSTANT(RESPONSE_LOOP_DETECTED);
  235. BIND_ENUM_CONSTANT(RESPONSE_NOT_EXTENDED);
  236. BIND_ENUM_CONSTANT(RESPONSE_NETWORK_AUTH_REQUIRED);
  237. }