http_client.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. /*************************************************************************/
  2. /* http_client.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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_client.h"
  31. #include "core/io/stream_peer_ssl.h"
  32. #include "core/version.h"
  33. const char *HTTPClient::_methods[METHOD_MAX] = {
  34. "GET",
  35. "HEAD",
  36. "POST",
  37. "PUT",
  38. "DELETE",
  39. "OPTIONS",
  40. "TRACE",
  41. "CONNECT",
  42. "PATCH"
  43. };
  44. #ifndef JAVASCRIPT_ENABLED
  45. Error HTTPClient::connect_to_host(const String &p_host, int p_port, bool p_ssl, bool p_verify_host) {
  46. close();
  47. conn_port = p_port;
  48. conn_host = p_host;
  49. ssl = p_ssl;
  50. ssl_verify_host = p_verify_host;
  51. String host_lower = conn_host.to_lower();
  52. if (host_lower.begins_with("http://")) {
  53. conn_host = conn_host.substr(7, conn_host.length() - 7);
  54. } else if (host_lower.begins_with("https://")) {
  55. ssl = true;
  56. conn_host = conn_host.substr(8, conn_host.length() - 8);
  57. }
  58. ERR_FAIL_COND_V(conn_host.length() < HOST_MIN_LEN, ERR_INVALID_PARAMETER);
  59. if (conn_port < 0) {
  60. if (ssl) {
  61. conn_port = PORT_HTTPS;
  62. } else {
  63. conn_port = PORT_HTTP;
  64. }
  65. }
  66. connection = tcp_connection;
  67. if (conn_host.is_valid_ip_address()) {
  68. // Host contains valid IP
  69. Error err = tcp_connection->connect_to_host(IP_Address(conn_host), p_port);
  70. if (err) {
  71. status = STATUS_CANT_CONNECT;
  72. return err;
  73. }
  74. status = STATUS_CONNECTING;
  75. } else {
  76. // Host contains hostname and needs to be resolved to IP
  77. resolving = IP::get_singleton()->resolve_hostname_queue_item(conn_host);
  78. status = STATUS_RESOLVING;
  79. }
  80. return OK;
  81. }
  82. void HTTPClient::set_connection(const Ref<StreamPeer> &p_connection) {
  83. ERR_FAIL_COND_MSG(p_connection.is_null(), "Connection is not a reference to a valid StreamPeer object.");
  84. if (connection == p_connection) {
  85. return;
  86. }
  87. close();
  88. connection = p_connection;
  89. status = STATUS_CONNECTED;
  90. }
  91. Ref<StreamPeer> HTTPClient::get_connection() const {
  92. return connection;
  93. }
  94. static bool _check_request_url(HTTPClient::Method p_method, const String &p_url) {
  95. switch (p_method) {
  96. case HTTPClient::METHOD_CONNECT: {
  97. // Authority in host:port format, as in RFC7231
  98. int pos = p_url.find_char(':');
  99. return 0 < pos && pos < p_url.length() - 1;
  100. }
  101. case HTTPClient::METHOD_OPTIONS: {
  102. if (p_url == "*") {
  103. return true;
  104. }
  105. FALLTHROUGH;
  106. }
  107. default:
  108. // Absolute path or absolute URL
  109. return p_url.begins_with("/") || p_url.begins_with("http://") || p_url.begins_with("https://");
  110. }
  111. }
  112. Error HTTPClient::request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const PoolVector<uint8_t> &p_body) {
  113. ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER);
  114. ERR_FAIL_COND_V(!_check_request_url(p_method, p_url), ERR_INVALID_PARAMETER);
  115. ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER);
  116. ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA);
  117. String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n";
  118. bool add_host = true;
  119. bool add_clen = p_body.size() > 0;
  120. bool add_uagent = true;
  121. bool add_accept = true;
  122. for (int i = 0; i < p_headers.size(); i++) {
  123. request += p_headers[i] + "\r\n";
  124. if (add_host && p_headers[i].findn("Host:") == 0) {
  125. add_host = false;
  126. }
  127. if (add_clen && p_headers[i].findn("Content-Length:") == 0) {
  128. add_clen = false;
  129. }
  130. if (add_uagent && p_headers[i].findn("User-Agent:") == 0) {
  131. add_uagent = false;
  132. }
  133. if (add_accept && p_headers[i].findn("Accept:") == 0) {
  134. add_accept = false;
  135. }
  136. }
  137. if (add_host) {
  138. if ((ssl && conn_port == PORT_HTTPS) || (!ssl && conn_port == PORT_HTTP)) {
  139. // Don't append the standard ports
  140. request += "Host: " + conn_host + "\r\n";
  141. } else {
  142. request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n";
  143. }
  144. }
  145. if (add_clen) {
  146. request += "Content-Length: " + itos(p_body.size()) + "\r\n";
  147. // Should it add utf8 encoding?
  148. }
  149. if (add_uagent) {
  150. request += "User-Agent: GodotEngine/" + String(VERSION_FULL_BUILD) + " (" + OS::get_singleton()->get_name() + ")\r\n";
  151. }
  152. if (add_accept) {
  153. request += "Accept: */*\r\n";
  154. }
  155. request += "\r\n";
  156. CharString cs = request.utf8();
  157. PoolVector<uint8_t> data;
  158. data.resize(cs.length());
  159. {
  160. PoolVector<uint8_t>::Write data_write = data.write();
  161. for (int i = 0; i < cs.length(); i++) {
  162. data_write[i] = cs[i];
  163. }
  164. }
  165. data.append_array(p_body);
  166. PoolVector<uint8_t>::Read r = data.read();
  167. Error err = connection->put_data(&r[0], data.size());
  168. if (err) {
  169. close();
  170. status = STATUS_CONNECTION_ERROR;
  171. return err;
  172. }
  173. status = STATUS_REQUESTING;
  174. head_request = p_method == METHOD_HEAD;
  175. return OK;
  176. }
  177. Error HTTPClient::request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body) {
  178. ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER);
  179. ERR_FAIL_COND_V(!_check_request_url(p_method, p_url), ERR_INVALID_PARAMETER);
  180. ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER);
  181. ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA);
  182. String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n";
  183. bool add_host = true;
  184. bool add_uagent = true;
  185. bool add_accept = true;
  186. bool add_clen = p_body.length() > 0;
  187. for (int i = 0; i < p_headers.size(); i++) {
  188. request += p_headers[i] + "\r\n";
  189. if (add_host && p_headers[i].findn("Host:") == 0) {
  190. add_host = false;
  191. }
  192. if (add_clen && p_headers[i].findn("Content-Length:") == 0) {
  193. add_clen = false;
  194. }
  195. if (add_uagent && p_headers[i].findn("User-Agent:") == 0) {
  196. add_uagent = false;
  197. }
  198. if (add_accept && p_headers[i].findn("Accept:") == 0) {
  199. add_accept = false;
  200. }
  201. }
  202. if (add_host) {
  203. if ((ssl && conn_port == PORT_HTTPS) || (!ssl && conn_port == PORT_HTTP)) {
  204. // Don't append the standard ports
  205. request += "Host: " + conn_host + "\r\n";
  206. } else {
  207. request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n";
  208. }
  209. }
  210. if (add_clen) {
  211. request += "Content-Length: " + itos(p_body.utf8().length()) + "\r\n";
  212. // Should it add utf8 encoding?
  213. }
  214. if (add_uagent) {
  215. request += "User-Agent: GodotEngine/" + String(VERSION_FULL_BUILD) + " (" + OS::get_singleton()->get_name() + ")\r\n";
  216. }
  217. if (add_accept) {
  218. request += "Accept: */*\r\n";
  219. }
  220. request += "\r\n";
  221. request += p_body;
  222. CharString cs = request.utf8();
  223. Error err = connection->put_data((const uint8_t *)cs.ptr(), cs.length());
  224. if (err) {
  225. close();
  226. status = STATUS_CONNECTION_ERROR;
  227. return err;
  228. }
  229. status = STATUS_REQUESTING;
  230. head_request = p_method == METHOD_HEAD;
  231. return OK;
  232. }
  233. bool HTTPClient::has_response() const {
  234. return response_headers.size() != 0;
  235. }
  236. bool HTTPClient::is_response_chunked() const {
  237. return chunked;
  238. }
  239. int HTTPClient::get_response_code() const {
  240. return response_num;
  241. }
  242. Error HTTPClient::get_response_headers(List<String> *r_response) {
  243. if (!response_headers.size())
  244. return ERR_INVALID_PARAMETER;
  245. for (int i = 0; i < response_headers.size(); i++) {
  246. r_response->push_back(response_headers[i]);
  247. }
  248. response_headers.clear();
  249. return OK;
  250. }
  251. void HTTPClient::close() {
  252. if (tcp_connection->get_status() != StreamPeerTCP::STATUS_NONE)
  253. tcp_connection->disconnect_from_host();
  254. connection.unref();
  255. status = STATUS_DISCONNECTED;
  256. head_request = false;
  257. if (resolving != IP::RESOLVER_INVALID_ID) {
  258. IP::get_singleton()->erase_resolve_item(resolving);
  259. resolving = IP::RESOLVER_INVALID_ID;
  260. }
  261. response_headers.clear();
  262. response_str.clear();
  263. body_size = -1;
  264. body_left = 0;
  265. chunk_left = 0;
  266. chunk_trailer_part = 0;
  267. read_until_eof = false;
  268. response_num = 0;
  269. handshaking = false;
  270. }
  271. Error HTTPClient::poll() {
  272. switch (status) {
  273. case STATUS_RESOLVING: {
  274. ERR_FAIL_COND_V(resolving == IP::RESOLVER_INVALID_ID, ERR_BUG);
  275. IP::ResolverStatus rstatus = IP::get_singleton()->get_resolve_item_status(resolving);
  276. switch (rstatus) {
  277. case IP::RESOLVER_STATUS_WAITING:
  278. return OK; // Still resolving
  279. case IP::RESOLVER_STATUS_DONE: {
  280. IP_Address host = IP::get_singleton()->get_resolve_item_address(resolving);
  281. Error err = tcp_connection->connect_to_host(host, conn_port);
  282. IP::get_singleton()->erase_resolve_item(resolving);
  283. resolving = IP::RESOLVER_INVALID_ID;
  284. if (err) {
  285. status = STATUS_CANT_CONNECT;
  286. return err;
  287. }
  288. status = STATUS_CONNECTING;
  289. } break;
  290. case IP::RESOLVER_STATUS_NONE:
  291. case IP::RESOLVER_STATUS_ERROR: {
  292. IP::get_singleton()->erase_resolve_item(resolving);
  293. resolving = IP::RESOLVER_INVALID_ID;
  294. close();
  295. status = STATUS_CANT_RESOLVE;
  296. return ERR_CANT_RESOLVE;
  297. } break;
  298. }
  299. } break;
  300. case STATUS_CONNECTING: {
  301. StreamPeerTCP::Status s = tcp_connection->get_status();
  302. switch (s) {
  303. case StreamPeerTCP::STATUS_CONNECTING: {
  304. return OK;
  305. } break;
  306. case StreamPeerTCP::STATUS_CONNECTED: {
  307. if (ssl) {
  308. Ref<StreamPeerSSL> ssl;
  309. if (!handshaking) {
  310. // Connect the StreamPeerSSL and start handshaking
  311. ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
  312. ssl->set_blocking_handshake_enabled(false);
  313. Error err = ssl->connect_to_stream(tcp_connection, ssl_verify_host, conn_host);
  314. if (err != OK) {
  315. close();
  316. status = STATUS_SSL_HANDSHAKE_ERROR;
  317. return ERR_CANT_CONNECT;
  318. }
  319. connection = ssl;
  320. handshaking = true;
  321. } else {
  322. // We are already handshaking, which means we can use your already active SSL connection
  323. ssl = static_cast<Ref<StreamPeerSSL> >(connection);
  324. if (ssl.is_null()) {
  325. close();
  326. status = STATUS_SSL_HANDSHAKE_ERROR;
  327. return ERR_CANT_CONNECT;
  328. }
  329. ssl->poll(); // Try to finish the handshake
  330. }
  331. if (ssl->get_status() == StreamPeerSSL::STATUS_CONNECTED) {
  332. // Handshake has been successful
  333. handshaking = false;
  334. status = STATUS_CONNECTED;
  335. return OK;
  336. } else if (ssl->get_status() != StreamPeerSSL::STATUS_HANDSHAKING) {
  337. // Handshake has failed
  338. close();
  339. status = STATUS_SSL_HANDSHAKE_ERROR;
  340. return ERR_CANT_CONNECT;
  341. }
  342. // ... we will need to poll more for handshake to finish
  343. } else {
  344. status = STATUS_CONNECTED;
  345. }
  346. return OK;
  347. } break;
  348. case StreamPeerTCP::STATUS_ERROR:
  349. case StreamPeerTCP::STATUS_NONE: {
  350. close();
  351. status = STATUS_CANT_CONNECT;
  352. return ERR_CANT_CONNECT;
  353. } break;
  354. }
  355. } break;
  356. case STATUS_BODY:
  357. case STATUS_CONNECTED: {
  358. // Check if we are still connected
  359. if (ssl) {
  360. Ref<StreamPeerSSL> tmp = connection;
  361. tmp->poll();
  362. if (tmp->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
  363. status = STATUS_CONNECTION_ERROR;
  364. return ERR_CONNECTION_ERROR;
  365. }
  366. } else if (tcp_connection->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  367. status = STATUS_CONNECTION_ERROR;
  368. return ERR_CONNECTION_ERROR;
  369. }
  370. // Connection established, requests can now be made
  371. return OK;
  372. } break;
  373. case STATUS_REQUESTING: {
  374. while (true) {
  375. uint8_t byte;
  376. int rec = 0;
  377. Error err = _get_http_data(&byte, 1, rec);
  378. if (err != OK) {
  379. close();
  380. status = STATUS_CONNECTION_ERROR;
  381. return ERR_CONNECTION_ERROR;
  382. }
  383. if (rec == 0)
  384. return OK; // Still requesting, keep trying!
  385. response_str.push_back(byte);
  386. int rs = response_str.size();
  387. if (
  388. (rs >= 2 && response_str[rs - 2] == '\n' && response_str[rs - 1] == '\n') ||
  389. (rs >= 4 && response_str[rs - 4] == '\r' && response_str[rs - 3] == '\n' && response_str[rs - 2] == '\r' && response_str[rs - 1] == '\n')) {
  390. // End of response, parse.
  391. response_str.push_back(0);
  392. String response;
  393. response.parse_utf8((const char *)response_str.ptr());
  394. Vector<String> responses = response.split("\n");
  395. body_size = -1;
  396. chunked = false;
  397. body_left = 0;
  398. chunk_left = 0;
  399. chunk_trailer_part = false;
  400. read_until_eof = false;
  401. response_str.clear();
  402. response_headers.clear();
  403. response_num = RESPONSE_OK;
  404. // Per the HTTP 1.1 spec, keep-alive is the default.
  405. // Not following that specification breaks standard implementations.
  406. // Broken web servers should be fixed.
  407. bool keep_alive = true;
  408. for (int i = 0; i < responses.size(); i++) {
  409. String header = responses[i].strip_edges();
  410. String s = header.to_lower();
  411. if (s.length() == 0)
  412. continue;
  413. if (s.begins_with("content-length:")) {
  414. body_size = s.substr(s.find(":") + 1, s.length()).strip_edges().to_int();
  415. body_left = body_size;
  416. } else if (s.begins_with("transfer-encoding:")) {
  417. String encoding = header.substr(header.find(":") + 1, header.length()).strip_edges();
  418. if (encoding == "chunked") {
  419. chunked = true;
  420. }
  421. } else if (s.begins_with("connection: close")) {
  422. keep_alive = false;
  423. }
  424. if (i == 0 && responses[i].begins_with("HTTP")) {
  425. String num = responses[i].get_slicec(' ', 1);
  426. response_num = num.to_int();
  427. } else {
  428. response_headers.push_back(header);
  429. }
  430. }
  431. // This is a HEAD request, we won't receive anything.
  432. if (head_request) {
  433. body_size = 0;
  434. body_left = 0;
  435. }
  436. if (body_size != -1 || chunked) {
  437. status = STATUS_BODY;
  438. } else if (!keep_alive) {
  439. read_until_eof = true;
  440. status = STATUS_BODY;
  441. } else {
  442. status = STATUS_CONNECTED;
  443. }
  444. return OK;
  445. }
  446. }
  447. } break;
  448. case STATUS_DISCONNECTED: {
  449. return ERR_UNCONFIGURED;
  450. } break;
  451. case STATUS_CONNECTION_ERROR:
  452. case STATUS_SSL_HANDSHAKE_ERROR: {
  453. return ERR_CONNECTION_ERROR;
  454. } break;
  455. case STATUS_CANT_CONNECT: {
  456. return ERR_CANT_CONNECT;
  457. } break;
  458. case STATUS_CANT_RESOLVE: {
  459. return ERR_CANT_RESOLVE;
  460. } break;
  461. }
  462. return OK;
  463. }
  464. int HTTPClient::get_response_body_length() const {
  465. return body_size;
  466. }
  467. PoolByteArray HTTPClient::read_response_body_chunk() {
  468. ERR_FAIL_COND_V(status != STATUS_BODY, PoolByteArray());
  469. PoolByteArray ret;
  470. Error err = OK;
  471. if (chunked) {
  472. while (true) {
  473. if (chunk_trailer_part) {
  474. // We need to consume the trailer part too or keep-alive will break
  475. uint8_t b;
  476. int rec = 0;
  477. err = _get_http_data(&b, 1, rec);
  478. if (rec == 0)
  479. break;
  480. chunk.push_back(b);
  481. int cs = chunk.size();
  482. if ((cs >= 2 && chunk[cs - 2] == '\r' && chunk[cs - 1] == '\n')) {
  483. if (cs == 2) {
  484. // Finally over
  485. chunk_trailer_part = false;
  486. status = STATUS_CONNECTED;
  487. chunk.clear();
  488. break;
  489. } else {
  490. // We do not process nor return the trailer data
  491. chunk.clear();
  492. }
  493. }
  494. } else if (chunk_left == 0) {
  495. // Reading length
  496. uint8_t b;
  497. int rec = 0;
  498. err = _get_http_data(&b, 1, rec);
  499. if (rec == 0)
  500. break;
  501. chunk.push_back(b);
  502. if (chunk.size() > 32) {
  503. ERR_PRINT("HTTP Invalid chunk hex len");
  504. status = STATUS_CONNECTION_ERROR;
  505. break;
  506. }
  507. if (chunk.size() > 2 && chunk[chunk.size() - 2] == '\r' && chunk[chunk.size() - 1] == '\n') {
  508. int len = 0;
  509. for (int i = 0; i < chunk.size() - 2; i++) {
  510. char c = chunk[i];
  511. int v = 0;
  512. if (c >= '0' && c <= '9')
  513. v = c - '0';
  514. else if (c >= 'a' && c <= 'f')
  515. v = c - 'a' + 10;
  516. else if (c >= 'A' && c <= 'F')
  517. v = c - 'A' + 10;
  518. else {
  519. ERR_PRINT("HTTP Chunk len not in hex!!");
  520. status = STATUS_CONNECTION_ERROR;
  521. break;
  522. }
  523. len <<= 4;
  524. len |= v;
  525. if (len > (1 << 24)) {
  526. ERR_PRINT("HTTP Chunk too big!! >16mb");
  527. status = STATUS_CONNECTION_ERROR;
  528. break;
  529. }
  530. }
  531. if (len == 0) {
  532. // End reached!
  533. chunk_trailer_part = true;
  534. chunk.clear();
  535. break;
  536. }
  537. chunk_left = len + 2;
  538. chunk.resize(chunk_left);
  539. }
  540. } else {
  541. int rec = 0;
  542. err = _get_http_data(&chunk.write[chunk.size() - chunk_left], chunk_left, rec);
  543. if (rec == 0) {
  544. break;
  545. }
  546. chunk_left -= rec;
  547. if (chunk_left == 0) {
  548. if (chunk[chunk.size() - 2] != '\r' || chunk[chunk.size() - 1] != '\n') {
  549. ERR_PRINT("HTTP Invalid chunk terminator (not \\r\\n)");
  550. status = STATUS_CONNECTION_ERROR;
  551. break;
  552. }
  553. ret.resize(chunk.size() - 2);
  554. PoolByteArray::Write w = ret.write();
  555. copymem(w.ptr(), chunk.ptr(), chunk.size() - 2);
  556. chunk.clear();
  557. }
  558. break;
  559. }
  560. }
  561. } else {
  562. int to_read = !read_until_eof ? MIN(body_left, read_chunk_size) : read_chunk_size;
  563. ret.resize(to_read);
  564. int _offset = 0;
  565. while (to_read > 0) {
  566. int rec = 0;
  567. {
  568. PoolByteArray::Write w = ret.write();
  569. err = _get_http_data(w.ptr() + _offset, to_read, rec);
  570. }
  571. if (rec <= 0) { // Ended up reading less
  572. ret.resize(_offset);
  573. break;
  574. } else {
  575. _offset += rec;
  576. to_read -= rec;
  577. if (!read_until_eof) {
  578. body_left -= rec;
  579. }
  580. }
  581. if (err != OK)
  582. break;
  583. }
  584. }
  585. if (err != OK) {
  586. close();
  587. if (err == ERR_FILE_EOF) {
  588. status = STATUS_DISCONNECTED; // Server disconnected
  589. } else {
  590. status = STATUS_CONNECTION_ERROR;
  591. }
  592. } else if (body_left == 0 && !chunked && !read_until_eof) {
  593. status = STATUS_CONNECTED;
  594. }
  595. return ret;
  596. }
  597. HTTPClient::Status HTTPClient::get_status() const {
  598. return status;
  599. }
  600. void HTTPClient::set_blocking_mode(bool p_enable) {
  601. blocking = p_enable;
  602. }
  603. bool HTTPClient::is_blocking_mode_enabled() const {
  604. return blocking;
  605. }
  606. Error HTTPClient::_get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
  607. if (blocking) {
  608. // We can't use StreamPeer.get_data, since when reaching EOF we will get an
  609. // error without knowing how many bytes we received.
  610. Error err = ERR_FILE_EOF;
  611. int read = 0;
  612. int left = p_bytes;
  613. r_received = 0;
  614. while (left > 0) {
  615. err = connection->get_partial_data(p_buffer + r_received, left, read);
  616. if (err == OK) {
  617. r_received += read;
  618. } else if (err == ERR_FILE_EOF) {
  619. r_received += read;
  620. return err;
  621. } else {
  622. return err;
  623. }
  624. left -= read;
  625. }
  626. return err;
  627. } else {
  628. return connection->get_partial_data(p_buffer, p_bytes, r_received);
  629. }
  630. }
  631. void HTTPClient::set_read_chunk_size(int p_size) {
  632. ERR_FAIL_COND(p_size < 256 || p_size > (1 << 24));
  633. read_chunk_size = p_size;
  634. }
  635. int HTTPClient::get_read_chunk_size() const {
  636. return read_chunk_size;
  637. }
  638. HTTPClient::HTTPClient() {
  639. tcp_connection.instance();
  640. resolving = IP::RESOLVER_INVALID_ID;
  641. status = STATUS_DISCONNECTED;
  642. head_request = false;
  643. conn_port = -1;
  644. body_size = -1;
  645. chunked = false;
  646. body_left = 0;
  647. read_until_eof = false;
  648. chunk_left = 0;
  649. chunk_trailer_part = false;
  650. response_num = 0;
  651. ssl = false;
  652. blocking = false;
  653. handshaking = false;
  654. // 64 KiB by default (favors fast download speeds at the cost of memory usage).
  655. read_chunk_size = 65536;
  656. }
  657. HTTPClient::~HTTPClient() {
  658. }
  659. #endif // #ifndef JAVASCRIPT_ENABLED
  660. String HTTPClient::query_string_from_dict(const Dictionary &p_dict) {
  661. String query = "";
  662. Array keys = p_dict.keys();
  663. for (int i = 0; i < keys.size(); ++i) {
  664. String encoded_key = String(keys[i]).http_escape();
  665. Variant value = p_dict[keys[i]];
  666. switch (value.get_type()) {
  667. case Variant::ARRAY: {
  668. // Repeat the key with every values
  669. Array values = value;
  670. for (int j = 0; j < values.size(); ++j) {
  671. query += "&" + encoded_key + "=" + String(values[j]).http_escape();
  672. }
  673. break;
  674. }
  675. case Variant::NIL: {
  676. // Add the key with no value
  677. query += "&" + encoded_key;
  678. break;
  679. }
  680. default: {
  681. // Add the key-value pair
  682. query += "&" + encoded_key + "=" + String(value).http_escape();
  683. }
  684. }
  685. }
  686. query.erase(0, 1);
  687. return query;
  688. }
  689. Dictionary HTTPClient::_get_response_headers_as_dictionary() {
  690. List<String> rh;
  691. get_response_headers(&rh);
  692. Dictionary ret;
  693. for (const List<String>::Element *E = rh.front(); E; E = E->next()) {
  694. const String &s = E->get();
  695. int sp = s.find(":");
  696. if (sp == -1)
  697. continue;
  698. String key = s.substr(0, sp).strip_edges();
  699. String value = s.substr(sp + 1, s.length()).strip_edges();
  700. ret[key] = value;
  701. }
  702. return ret;
  703. }
  704. PoolStringArray HTTPClient::_get_response_headers() {
  705. List<String> rh;
  706. get_response_headers(&rh);
  707. PoolStringArray ret;
  708. ret.resize(rh.size());
  709. int idx = 0;
  710. for (const List<String>::Element *E = rh.front(); E; E = E->next()) {
  711. ret.set(idx++, E->get());
  712. }
  713. return ret;
  714. }
  715. void HTTPClient::_bind_methods() {
  716. ClassDB::bind_method(D_METHOD("connect_to_host", "host", "port", "use_ssl", "verify_host"), &HTTPClient::connect_to_host, DEFVAL(-1), DEFVAL(false), DEFVAL(true));
  717. ClassDB::bind_method(D_METHOD("set_connection", "connection"), &HTTPClient::set_connection);
  718. ClassDB::bind_method(D_METHOD("get_connection"), &HTTPClient::get_connection);
  719. ClassDB::bind_method(D_METHOD("request_raw", "method", "url", "headers", "body"), &HTTPClient::request_raw);
  720. ClassDB::bind_method(D_METHOD("request", "method", "url", "headers", "body"), &HTTPClient::request, DEFVAL(String()));
  721. ClassDB::bind_method(D_METHOD("close"), &HTTPClient::close);
  722. ClassDB::bind_method(D_METHOD("has_response"), &HTTPClient::has_response);
  723. ClassDB::bind_method(D_METHOD("is_response_chunked"), &HTTPClient::is_response_chunked);
  724. ClassDB::bind_method(D_METHOD("get_response_code"), &HTTPClient::get_response_code);
  725. ClassDB::bind_method(D_METHOD("get_response_headers"), &HTTPClient::_get_response_headers);
  726. ClassDB::bind_method(D_METHOD("get_response_headers_as_dictionary"), &HTTPClient::_get_response_headers_as_dictionary);
  727. ClassDB::bind_method(D_METHOD("get_response_body_length"), &HTTPClient::get_response_body_length);
  728. ClassDB::bind_method(D_METHOD("read_response_body_chunk"), &HTTPClient::read_response_body_chunk);
  729. ClassDB::bind_method(D_METHOD("set_read_chunk_size", "bytes"), &HTTPClient::set_read_chunk_size);
  730. ClassDB::bind_method(D_METHOD("get_read_chunk_size"), &HTTPClient::get_read_chunk_size);
  731. ClassDB::bind_method(D_METHOD("set_blocking_mode", "enabled"), &HTTPClient::set_blocking_mode);
  732. ClassDB::bind_method(D_METHOD("is_blocking_mode_enabled"), &HTTPClient::is_blocking_mode_enabled);
  733. ClassDB::bind_method(D_METHOD("get_status"), &HTTPClient::get_status);
  734. ClassDB::bind_method(D_METHOD("poll"), &HTTPClient::poll);
  735. ClassDB::bind_method(D_METHOD("query_string_from_dict", "fields"), &HTTPClient::query_string_from_dict);
  736. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "blocking_mode_enabled"), "set_blocking_mode", "is_blocking_mode_enabled");
  737. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "connection", PROPERTY_HINT_RESOURCE_TYPE, "StreamPeer", 0), "set_connection", "get_connection");
  738. ADD_PROPERTY(PropertyInfo(Variant::INT, "read_chunk_size", PROPERTY_HINT_RANGE, "256,16777216"), "set_read_chunk_size", "get_read_chunk_size");
  739. BIND_ENUM_CONSTANT(METHOD_GET);
  740. BIND_ENUM_CONSTANT(METHOD_HEAD);
  741. BIND_ENUM_CONSTANT(METHOD_POST);
  742. BIND_ENUM_CONSTANT(METHOD_PUT);
  743. BIND_ENUM_CONSTANT(METHOD_DELETE);
  744. BIND_ENUM_CONSTANT(METHOD_OPTIONS);
  745. BIND_ENUM_CONSTANT(METHOD_TRACE);
  746. BIND_ENUM_CONSTANT(METHOD_CONNECT);
  747. BIND_ENUM_CONSTANT(METHOD_PATCH);
  748. BIND_ENUM_CONSTANT(METHOD_MAX);
  749. BIND_ENUM_CONSTANT(STATUS_DISCONNECTED);
  750. BIND_ENUM_CONSTANT(STATUS_RESOLVING); // Resolving hostname (if hostname was passed in)
  751. BIND_ENUM_CONSTANT(STATUS_CANT_RESOLVE);
  752. BIND_ENUM_CONSTANT(STATUS_CONNECTING); // Connecting to IP
  753. BIND_ENUM_CONSTANT(STATUS_CANT_CONNECT);
  754. BIND_ENUM_CONSTANT(STATUS_CONNECTED); // Connected, now accepting requests
  755. BIND_ENUM_CONSTANT(STATUS_REQUESTING); // Request in progress
  756. BIND_ENUM_CONSTANT(STATUS_BODY); // Request resulted in body which must be read
  757. BIND_ENUM_CONSTANT(STATUS_CONNECTION_ERROR);
  758. BIND_ENUM_CONSTANT(STATUS_SSL_HANDSHAKE_ERROR);
  759. BIND_ENUM_CONSTANT(RESPONSE_CONTINUE);
  760. BIND_ENUM_CONSTANT(RESPONSE_SWITCHING_PROTOCOLS);
  761. BIND_ENUM_CONSTANT(RESPONSE_PROCESSING);
  762. // 2xx successful
  763. BIND_ENUM_CONSTANT(RESPONSE_OK);
  764. BIND_ENUM_CONSTANT(RESPONSE_CREATED);
  765. BIND_ENUM_CONSTANT(RESPONSE_ACCEPTED);
  766. BIND_ENUM_CONSTANT(RESPONSE_NON_AUTHORITATIVE_INFORMATION);
  767. BIND_ENUM_CONSTANT(RESPONSE_NO_CONTENT);
  768. BIND_ENUM_CONSTANT(RESPONSE_RESET_CONTENT);
  769. BIND_ENUM_CONSTANT(RESPONSE_PARTIAL_CONTENT);
  770. BIND_ENUM_CONSTANT(RESPONSE_MULTI_STATUS);
  771. BIND_ENUM_CONSTANT(RESPONSE_ALREADY_REPORTED);
  772. BIND_ENUM_CONSTANT(RESPONSE_IM_USED);
  773. // 3xx redirection
  774. BIND_ENUM_CONSTANT(RESPONSE_MULTIPLE_CHOICES);
  775. BIND_ENUM_CONSTANT(RESPONSE_MOVED_PERMANENTLY);
  776. BIND_ENUM_CONSTANT(RESPONSE_FOUND);
  777. BIND_ENUM_CONSTANT(RESPONSE_SEE_OTHER);
  778. BIND_ENUM_CONSTANT(RESPONSE_NOT_MODIFIED);
  779. BIND_ENUM_CONSTANT(RESPONSE_USE_PROXY);
  780. BIND_ENUM_CONSTANT(RESPONSE_SWITCH_PROXY);
  781. BIND_ENUM_CONSTANT(RESPONSE_TEMPORARY_REDIRECT);
  782. BIND_ENUM_CONSTANT(RESPONSE_PERMANENT_REDIRECT);
  783. // 4xx client error
  784. BIND_ENUM_CONSTANT(RESPONSE_BAD_REQUEST);
  785. BIND_ENUM_CONSTANT(RESPONSE_UNAUTHORIZED);
  786. BIND_ENUM_CONSTANT(RESPONSE_PAYMENT_REQUIRED);
  787. BIND_ENUM_CONSTANT(RESPONSE_FORBIDDEN);
  788. BIND_ENUM_CONSTANT(RESPONSE_NOT_FOUND);
  789. BIND_ENUM_CONSTANT(RESPONSE_METHOD_NOT_ALLOWED);
  790. BIND_ENUM_CONSTANT(RESPONSE_NOT_ACCEPTABLE);
  791. BIND_ENUM_CONSTANT(RESPONSE_PROXY_AUTHENTICATION_REQUIRED);
  792. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_TIMEOUT);
  793. BIND_ENUM_CONSTANT(RESPONSE_CONFLICT);
  794. BIND_ENUM_CONSTANT(RESPONSE_GONE);
  795. BIND_ENUM_CONSTANT(RESPONSE_LENGTH_REQUIRED);
  796. BIND_ENUM_CONSTANT(RESPONSE_PRECONDITION_FAILED);
  797. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_ENTITY_TOO_LARGE);
  798. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_URI_TOO_LONG);
  799. BIND_ENUM_CONSTANT(RESPONSE_UNSUPPORTED_MEDIA_TYPE);
  800. BIND_ENUM_CONSTANT(RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE);
  801. BIND_ENUM_CONSTANT(RESPONSE_EXPECTATION_FAILED);
  802. BIND_ENUM_CONSTANT(RESPONSE_IM_A_TEAPOT);
  803. BIND_ENUM_CONSTANT(RESPONSE_MISDIRECTED_REQUEST);
  804. BIND_ENUM_CONSTANT(RESPONSE_UNPROCESSABLE_ENTITY);
  805. BIND_ENUM_CONSTANT(RESPONSE_LOCKED);
  806. BIND_ENUM_CONSTANT(RESPONSE_FAILED_DEPENDENCY);
  807. BIND_ENUM_CONSTANT(RESPONSE_UPGRADE_REQUIRED);
  808. BIND_ENUM_CONSTANT(RESPONSE_PRECONDITION_REQUIRED);
  809. BIND_ENUM_CONSTANT(RESPONSE_TOO_MANY_REQUESTS);
  810. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_HEADER_FIELDS_TOO_LARGE);
  811. BIND_ENUM_CONSTANT(RESPONSE_UNAVAILABLE_FOR_LEGAL_REASONS);
  812. // 5xx server error
  813. BIND_ENUM_CONSTANT(RESPONSE_INTERNAL_SERVER_ERROR);
  814. BIND_ENUM_CONSTANT(RESPONSE_NOT_IMPLEMENTED);
  815. BIND_ENUM_CONSTANT(RESPONSE_BAD_GATEWAY);
  816. BIND_ENUM_CONSTANT(RESPONSE_SERVICE_UNAVAILABLE);
  817. BIND_ENUM_CONSTANT(RESPONSE_GATEWAY_TIMEOUT);
  818. BIND_ENUM_CONSTANT(RESPONSE_HTTP_VERSION_NOT_SUPPORTED);
  819. BIND_ENUM_CONSTANT(RESPONSE_VARIANT_ALSO_NEGOTIATES);
  820. BIND_ENUM_CONSTANT(RESPONSE_INSUFFICIENT_STORAGE);
  821. BIND_ENUM_CONSTANT(RESPONSE_LOOP_DETECTED);
  822. BIND_ENUM_CONSTANT(RESPONSE_NOT_EXTENDED);
  823. BIND_ENUM_CONSTANT(RESPONSE_NETWORK_AUTH_REQUIRED);
  824. }