http_client.cpp 27 KB

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