http_request.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. /*************************************************************************/
  2. /* http_request.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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. #include "http_request.h"
  31. void HTTPRequest::_redirect_request(const String &p_new_url) {
  32. }
  33. Error HTTPRequest::_request() {
  34. return client->connect_to_host(url, port, use_ssl, validate_ssl);
  35. }
  36. Error HTTPRequest::_parse_url(const String &p_url) {
  37. url = p_url;
  38. use_ssl = false;
  39. request_string = "";
  40. port = 80;
  41. request_sent = false;
  42. got_response = false;
  43. body_len = -1;
  44. body.resize(0);
  45. downloaded = 0;
  46. redirections = 0;
  47. String url_lower = url.to_lower();
  48. if (url_lower.begins_with("http://")) {
  49. url = url.substr(7, url.length() - 7);
  50. } else if (url_lower.begins_with("https://")) {
  51. url = url.substr(8, url.length() - 8);
  52. use_ssl = true;
  53. port = 443;
  54. } else {
  55. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Malformed URL: " + url + ".");
  56. }
  57. ERR_FAIL_COND_V_MSG(url.length() < 1, ERR_INVALID_PARAMETER, "URL too short: " + url + ".");
  58. int slash_pos = url.find("/");
  59. if (slash_pos != -1) {
  60. request_string = url.substr(slash_pos, url.length());
  61. url = url.substr(0, slash_pos);
  62. } else {
  63. request_string = "/";
  64. }
  65. int colon_pos = url.find(":");
  66. if (colon_pos != -1) {
  67. port = url.substr(colon_pos + 1, url.length()).to_int();
  68. url = url.substr(0, colon_pos);
  69. ERR_FAIL_COND_V(port < 1 || port > 65535, ERR_INVALID_PARAMETER);
  70. }
  71. return OK;
  72. }
  73. Error HTTPRequest::request(const String &p_url, const Vector<String> &p_custom_headers, bool p_ssl_validate_domain, HTTPClient::Method p_method, const String &p_request_data) {
  74. ERR_FAIL_COND_V(!is_inside_tree(), ERR_UNCONFIGURED);
  75. ERR_FAIL_COND_V_MSG(requesting, ERR_BUSY, "HTTPRequest is processing a request. Wait for completion or cancel it before attempting a new one.");
  76. if (timeout > 0) {
  77. timer->stop();
  78. timer->start(timeout);
  79. }
  80. method = p_method;
  81. Error err = _parse_url(p_url);
  82. if (err)
  83. return err;
  84. validate_ssl = p_ssl_validate_domain;
  85. headers = p_custom_headers;
  86. request_data = p_request_data;
  87. requesting = true;
  88. if (use_threads) {
  89. thread_done = false;
  90. thread_request_quit = false;
  91. client->set_blocking_mode(true);
  92. thread = Thread::create(_thread_func, this);
  93. } else {
  94. client->set_blocking_mode(false);
  95. err = _request();
  96. if (err != OK) {
  97. call_deferred("_request_done", RESULT_CANT_CONNECT, 0, PoolStringArray(), PoolByteArray());
  98. return ERR_CANT_CONNECT;
  99. }
  100. set_process_internal(true);
  101. }
  102. return OK;
  103. }
  104. void HTTPRequest::_thread_func(void *p_userdata) {
  105. HTTPRequest *hr = (HTTPRequest *)p_userdata;
  106. Error err = hr->_request();
  107. if (err != OK) {
  108. hr->call_deferred("_request_done", RESULT_CANT_CONNECT, 0, PoolStringArray(), PoolByteArray());
  109. } else {
  110. while (!hr->thread_request_quit) {
  111. bool exit = hr->_update_connection();
  112. if (exit)
  113. break;
  114. OS::get_singleton()->delay_usec(1);
  115. }
  116. }
  117. hr->thread_done = true;
  118. }
  119. void HTTPRequest::cancel_request() {
  120. timer->stop();
  121. if (!requesting)
  122. return;
  123. if (!use_threads) {
  124. set_process_internal(false);
  125. } else {
  126. thread_request_quit = true;
  127. Thread::wait_to_finish(thread);
  128. memdelete(thread);
  129. thread = NULL;
  130. }
  131. if (file) {
  132. memdelete(file);
  133. file = NULL;
  134. }
  135. client->close();
  136. body.resize(0);
  137. got_response = false;
  138. response_code = -1;
  139. request_sent = false;
  140. requesting = false;
  141. }
  142. bool HTTPRequest::_handle_response(bool *ret_value) {
  143. if (!client->has_response()) {
  144. call_deferred("_request_done", RESULT_NO_RESPONSE, 0, PoolStringArray(), PoolByteArray());
  145. *ret_value = true;
  146. return true;
  147. }
  148. got_response = true;
  149. response_code = client->get_response_code();
  150. List<String> rheaders;
  151. client->get_response_headers(&rheaders);
  152. response_headers.resize(0);
  153. downloaded = 0;
  154. for (List<String>::Element *E = rheaders.front(); E; E = E->next()) {
  155. response_headers.push_back(E->get());
  156. }
  157. if (response_code == 301 || response_code == 302) {
  158. // Handle redirect
  159. if (max_redirects >= 0 && redirections >= max_redirects) {
  160. call_deferred("_request_done", RESULT_REDIRECT_LIMIT_REACHED, response_code, response_headers, PoolByteArray());
  161. *ret_value = true;
  162. return true;
  163. }
  164. String new_request;
  165. for (List<String>::Element *E = rheaders.front(); E; E = E->next()) {
  166. if (E->get().findn("Location: ") != -1) {
  167. new_request = E->get().substr(9, E->get().length()).strip_edges();
  168. }
  169. }
  170. if (new_request != "") {
  171. // Process redirect
  172. client->close();
  173. int new_redirs = redirections + 1; // Because _request() will clear it
  174. Error err;
  175. if (new_request.begins_with("http")) {
  176. // New url, request all again
  177. _parse_url(new_request);
  178. } else {
  179. request_string = new_request;
  180. }
  181. err = _request();
  182. if (err == OK) {
  183. request_sent = false;
  184. got_response = false;
  185. body_len = -1;
  186. body.resize(0);
  187. downloaded = 0;
  188. redirections = new_redirs;
  189. *ret_value = false;
  190. return true;
  191. }
  192. }
  193. }
  194. return false;
  195. }
  196. bool HTTPRequest::_update_connection() {
  197. switch (client->get_status()) {
  198. case HTTPClient::STATUS_DISCONNECTED: {
  199. call_deferred("_request_done", RESULT_CANT_CONNECT, 0, PoolStringArray(), PoolByteArray());
  200. return true; // End it, since it's doing something
  201. } break;
  202. case HTTPClient::STATUS_RESOLVING: {
  203. client->poll();
  204. // Must wait
  205. return false;
  206. } break;
  207. case HTTPClient::STATUS_CANT_RESOLVE: {
  208. call_deferred("_request_done", RESULT_CANT_RESOLVE, 0, PoolStringArray(), PoolByteArray());
  209. return true;
  210. } break;
  211. case HTTPClient::STATUS_CONNECTING: {
  212. client->poll();
  213. // Must wait
  214. return false;
  215. } break; // Connecting to IP
  216. case HTTPClient::STATUS_CANT_CONNECT: {
  217. call_deferred("_request_done", RESULT_CANT_CONNECT, 0, PoolStringArray(), PoolByteArray());
  218. return true;
  219. } break;
  220. case HTTPClient::STATUS_CONNECTED: {
  221. if (request_sent) {
  222. if (!got_response) {
  223. // No body
  224. bool ret_value;
  225. if (_handle_response(&ret_value))
  226. return ret_value;
  227. call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, PoolByteArray());
  228. return true;
  229. }
  230. if (body_len < 0) {
  231. // Chunked transfer is done
  232. call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, body);
  233. return true;
  234. }
  235. call_deferred("_request_done", RESULT_CHUNKED_BODY_SIZE_MISMATCH, response_code, response_headers, PoolByteArray());
  236. return true;
  237. // Request migh have been done
  238. } else {
  239. // Did not request yet, do request
  240. Error err = client->request(method, request_string, headers, request_data);
  241. if (err != OK) {
  242. call_deferred("_request_done", RESULT_CONNECTION_ERROR, 0, PoolStringArray(), PoolByteArray());
  243. return true;
  244. }
  245. request_sent = true;
  246. return false;
  247. }
  248. } break; // Connected: break requests only accepted here
  249. case HTTPClient::STATUS_REQUESTING: {
  250. // Must wait, still requesting
  251. client->poll();
  252. return false;
  253. } break; // Request in progress
  254. case HTTPClient::STATUS_BODY: {
  255. if (!got_response) {
  256. bool ret_value;
  257. if (_handle_response(&ret_value))
  258. return ret_value;
  259. if (!client->is_response_chunked() && client->get_response_body_length() == 0) {
  260. call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, PoolByteArray());
  261. return true;
  262. }
  263. // No body len (-1) if chunked or no content-length header was provided.
  264. // Change your webserver configuration if you want body len.
  265. body_len = client->get_response_body_length();
  266. if (body_size_limit >= 0 && body_len > body_size_limit) {
  267. call_deferred("_request_done", RESULT_BODY_SIZE_LIMIT_EXCEEDED, response_code, response_headers, PoolByteArray());
  268. return true;
  269. }
  270. if (download_to_file != String()) {
  271. file = FileAccess::open(download_to_file, FileAccess::WRITE);
  272. if (!file) {
  273. call_deferred("_request_done", RESULT_DOWNLOAD_FILE_CANT_OPEN, response_code, response_headers, PoolByteArray());
  274. return true;
  275. }
  276. }
  277. }
  278. client->poll();
  279. if (client->get_status() != HTTPClient::STATUS_BODY) {
  280. return false;
  281. }
  282. PoolByteArray chunk = client->read_response_body_chunk();
  283. downloaded += chunk.size();
  284. if (file) {
  285. PoolByteArray::Read r = chunk.read();
  286. file->store_buffer(r.ptr(), chunk.size());
  287. if (file->get_error() != OK) {
  288. call_deferred("_request_done", RESULT_DOWNLOAD_FILE_WRITE_ERROR, response_code, response_headers, PoolByteArray());
  289. return true;
  290. }
  291. } else {
  292. body.append_array(chunk);
  293. }
  294. if (body_size_limit >= 0 && downloaded > body_size_limit) {
  295. call_deferred("_request_done", RESULT_BODY_SIZE_LIMIT_EXCEEDED, response_code, response_headers, PoolByteArray());
  296. return true;
  297. }
  298. if (body_len >= 0) {
  299. if (downloaded == body_len) {
  300. call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, body);
  301. return true;
  302. }
  303. } else if (client->get_status() == HTTPClient::STATUS_DISCONNECTED) {
  304. // We read till EOF, with no errors. Request is done.
  305. call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, body);
  306. }
  307. return false;
  308. } break; // Request resulted in body: break which must be read
  309. case HTTPClient::STATUS_CONNECTION_ERROR: {
  310. call_deferred("_request_done", RESULT_CONNECTION_ERROR, 0, PoolStringArray(), PoolByteArray());
  311. return true;
  312. } break;
  313. case HTTPClient::STATUS_SSL_HANDSHAKE_ERROR: {
  314. call_deferred("_request_done", RESULT_SSL_HANDSHAKE_ERROR, 0, PoolStringArray(), PoolByteArray());
  315. return true;
  316. } break;
  317. }
  318. ERR_FAIL_V(false);
  319. }
  320. void HTTPRequest::_request_done(int p_status, int p_code, const PoolStringArray &headers, const PoolByteArray &p_data) {
  321. cancel_request();
  322. emit_signal("request_completed", p_status, p_code, headers, p_data);
  323. }
  324. void HTTPRequest::_notification(int p_what) {
  325. if (p_what == NOTIFICATION_INTERNAL_PROCESS) {
  326. if (use_threads)
  327. return;
  328. bool done = _update_connection();
  329. if (done) {
  330. set_process_internal(false);
  331. // cancel_request(); called from _request done now
  332. }
  333. }
  334. if (p_what == NOTIFICATION_EXIT_TREE) {
  335. if (requesting) {
  336. cancel_request();
  337. }
  338. }
  339. }
  340. void HTTPRequest::set_use_threads(bool p_use) {
  341. ERR_FAIL_COND(get_http_client_status() != HTTPClient::STATUS_DISCONNECTED);
  342. use_threads = p_use;
  343. }
  344. bool HTTPRequest::is_using_threads() const {
  345. return use_threads;
  346. }
  347. void HTTPRequest::set_body_size_limit(int p_bytes) {
  348. ERR_FAIL_COND(get_http_client_status() != HTTPClient::STATUS_DISCONNECTED);
  349. body_size_limit = p_bytes;
  350. }
  351. int HTTPRequest::get_body_size_limit() const {
  352. return body_size_limit;
  353. }
  354. void HTTPRequest::set_download_file(const String &p_file) {
  355. ERR_FAIL_COND(get_http_client_status() != HTTPClient::STATUS_DISCONNECTED);
  356. download_to_file = p_file;
  357. }
  358. String HTTPRequest::get_download_file() const {
  359. return download_to_file;
  360. }
  361. void HTTPRequest::set_download_chunk_size(int p_chunk_size) {
  362. ERR_FAIL_COND(get_http_client_status() != HTTPClient::STATUS_DISCONNECTED);
  363. client->set_read_chunk_size(p_chunk_size);
  364. }
  365. int HTTPRequest::get_download_chunk_size() const {
  366. return client->get_read_chunk_size();
  367. }
  368. HTTPClient::Status HTTPRequest::get_http_client_status() const {
  369. return client->get_status();
  370. }
  371. void HTTPRequest::set_max_redirects(int p_max) {
  372. max_redirects = p_max;
  373. }
  374. int HTTPRequest::get_max_redirects() const {
  375. return max_redirects;
  376. }
  377. int HTTPRequest::get_downloaded_bytes() const {
  378. return downloaded;
  379. }
  380. int HTTPRequest::get_body_size() const {
  381. return body_len;
  382. }
  383. void HTTPRequest::set_timeout(int p_timeout) {
  384. ERR_FAIL_COND(p_timeout < 0);
  385. timeout = p_timeout;
  386. }
  387. int HTTPRequest::get_timeout() {
  388. return timeout;
  389. }
  390. void HTTPRequest::_timeout() {
  391. cancel_request();
  392. call_deferred("_request_done", RESULT_TIMEOUT, 0, PoolStringArray(), PoolByteArray());
  393. }
  394. void HTTPRequest::_bind_methods() {
  395. ClassDB::bind_method(D_METHOD("request", "url", "custom_headers", "ssl_validate_domain", "method", "request_data"), &HTTPRequest::request, DEFVAL(PoolStringArray()), DEFVAL(true), DEFVAL(HTTPClient::METHOD_GET), DEFVAL(String()));
  396. ClassDB::bind_method(D_METHOD("cancel_request"), &HTTPRequest::cancel_request);
  397. ClassDB::bind_method(D_METHOD("get_http_client_status"), &HTTPRequest::get_http_client_status);
  398. ClassDB::bind_method(D_METHOD("set_use_threads", "enable"), &HTTPRequest::set_use_threads);
  399. ClassDB::bind_method(D_METHOD("is_using_threads"), &HTTPRequest::is_using_threads);
  400. ClassDB::bind_method(D_METHOD("set_body_size_limit", "bytes"), &HTTPRequest::set_body_size_limit);
  401. ClassDB::bind_method(D_METHOD("get_body_size_limit"), &HTTPRequest::get_body_size_limit);
  402. ClassDB::bind_method(D_METHOD("set_max_redirects", "amount"), &HTTPRequest::set_max_redirects);
  403. ClassDB::bind_method(D_METHOD("get_max_redirects"), &HTTPRequest::get_max_redirects);
  404. ClassDB::bind_method(D_METHOD("set_download_file", "path"), &HTTPRequest::set_download_file);
  405. ClassDB::bind_method(D_METHOD("get_download_file"), &HTTPRequest::get_download_file);
  406. ClassDB::bind_method(D_METHOD("get_downloaded_bytes"), &HTTPRequest::get_downloaded_bytes);
  407. ClassDB::bind_method(D_METHOD("get_body_size"), &HTTPRequest::get_body_size);
  408. ClassDB::bind_method(D_METHOD("_redirect_request"), &HTTPRequest::_redirect_request);
  409. ClassDB::bind_method(D_METHOD("_request_done"), &HTTPRequest::_request_done);
  410. ClassDB::bind_method(D_METHOD("set_timeout", "timeout"), &HTTPRequest::set_timeout);
  411. ClassDB::bind_method(D_METHOD("get_timeout"), &HTTPRequest::get_timeout);
  412. ClassDB::bind_method(D_METHOD("set_download_chunk_size"), &HTTPRequest::set_download_chunk_size);
  413. ClassDB::bind_method(D_METHOD("get_download_chunk_size"), &HTTPRequest::get_download_chunk_size);
  414. ClassDB::bind_method(D_METHOD("_timeout"), &HTTPRequest::_timeout);
  415. ADD_PROPERTY(PropertyInfo(Variant::STRING, "download_file", PROPERTY_HINT_FILE), "set_download_file", "get_download_file");
  416. ADD_PROPERTY(PropertyInfo(Variant::INT, "download_chunk_size", PROPERTY_HINT_RANGE, "256,16777216"), "set_download_chunk_size", "get_download_chunk_size");
  417. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_threads"), "set_use_threads", "is_using_threads");
  418. ADD_PROPERTY(PropertyInfo(Variant::INT, "body_size_limit", PROPERTY_HINT_RANGE, "-1,2000000000"), "set_body_size_limit", "get_body_size_limit");
  419. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_redirects", PROPERTY_HINT_RANGE, "-1,64"), "set_max_redirects", "get_max_redirects");
  420. ADD_PROPERTY(PropertyInfo(Variant::INT, "timeout", PROPERTY_HINT_RANGE, "0,86400"), "set_timeout", "get_timeout");
  421. ADD_SIGNAL(MethodInfo("request_completed", PropertyInfo(Variant::INT, "result"), PropertyInfo(Variant::INT, "response_code"), PropertyInfo(Variant::POOL_STRING_ARRAY, "headers"), PropertyInfo(Variant::POOL_BYTE_ARRAY, "body")));
  422. BIND_ENUM_CONSTANT(RESULT_SUCCESS);
  423. //BIND_ENUM_CONSTANT( RESULT_NO_BODY );
  424. BIND_ENUM_CONSTANT(RESULT_CHUNKED_BODY_SIZE_MISMATCH);
  425. BIND_ENUM_CONSTANT(RESULT_CANT_CONNECT);
  426. BIND_ENUM_CONSTANT(RESULT_CANT_RESOLVE);
  427. BIND_ENUM_CONSTANT(RESULT_CONNECTION_ERROR);
  428. BIND_ENUM_CONSTANT(RESULT_SSL_HANDSHAKE_ERROR);
  429. BIND_ENUM_CONSTANT(RESULT_NO_RESPONSE);
  430. BIND_ENUM_CONSTANT(RESULT_BODY_SIZE_LIMIT_EXCEEDED);
  431. BIND_ENUM_CONSTANT(RESULT_REQUEST_FAILED);
  432. BIND_ENUM_CONSTANT(RESULT_DOWNLOAD_FILE_CANT_OPEN);
  433. BIND_ENUM_CONSTANT(RESULT_DOWNLOAD_FILE_WRITE_ERROR);
  434. BIND_ENUM_CONSTANT(RESULT_REDIRECT_LIMIT_REACHED);
  435. BIND_ENUM_CONSTANT(RESULT_TIMEOUT);
  436. }
  437. HTTPRequest::HTTPRequest() {
  438. thread = NULL;
  439. port = 80;
  440. redirections = 0;
  441. max_redirects = 8;
  442. body_len = -1;
  443. got_response = false;
  444. validate_ssl = false;
  445. use_ssl = false;
  446. response_code = 0;
  447. request_sent = false;
  448. requesting = false;
  449. client.instance();
  450. use_threads = false;
  451. thread_done = false;
  452. downloaded = 0;
  453. body_size_limit = -1;
  454. file = NULL;
  455. timer = memnew(Timer);
  456. timer->set_one_shot(true);
  457. timer->connect("timeout", this, "_timeout");
  458. add_child(timer);
  459. timeout = 0;
  460. }
  461. HTTPRequest::~HTTPRequest() {
  462. if (file)
  463. memdelete(file);
  464. }