http_request.cpp 17 KB

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