http_client_tcp.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. /*************************************************************************/
  2. /* http_client_tcp.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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. #ifndef JAVASCRIPT_ENABLED
  31. #include "http_client_tcp.h"
  32. #include "core/io/stream_peer_ssl.h"
  33. #include "core/version.h"
  34. HTTPClient *HTTPClientTCP::_create_func() {
  35. return memnew(HTTPClientTCP);
  36. }
  37. Error HTTPClientTCP::connect_to_host(const String &p_host, int p_port, bool p_ssl, bool p_verify_host) {
  38. close();
  39. conn_port = p_port;
  40. conn_host = p_host;
  41. ip_candidates.clear();
  42. ssl = p_ssl;
  43. ssl_verify_host = p_verify_host;
  44. String host_lower = conn_host.to_lower();
  45. if (host_lower.begins_with("http://")) {
  46. conn_host = conn_host.substr(7, conn_host.length() - 7);
  47. } else if (host_lower.begins_with("https://")) {
  48. ssl = true;
  49. conn_host = conn_host.substr(8, conn_host.length() - 8);
  50. }
  51. ERR_FAIL_COND_V(conn_host.length() < HOST_MIN_LEN, ERR_INVALID_PARAMETER);
  52. if (conn_port < 0) {
  53. if (ssl) {
  54. conn_port = PORT_HTTPS;
  55. } else {
  56. conn_port = PORT_HTTP;
  57. }
  58. }
  59. connection = tcp_connection;
  60. if (ssl && https_proxy_port != -1) {
  61. proxy_client.instantiate(); // Needs proxy negotiation.
  62. server_host = https_proxy_host;
  63. server_port = https_proxy_port;
  64. } else if (!ssl && http_proxy_port != -1) {
  65. server_host = http_proxy_host;
  66. server_port = http_proxy_port;
  67. } else {
  68. server_host = conn_host;
  69. server_port = conn_port;
  70. }
  71. if (server_host.is_valid_ip_address()) {
  72. // Host contains valid IP.
  73. Error err = tcp_connection->connect_to_host(IPAddress(server_host), server_port);
  74. if (err) {
  75. status = STATUS_CANT_CONNECT;
  76. return err;
  77. }
  78. status = STATUS_CONNECTING;
  79. } else {
  80. // Host contains hostname and needs to be resolved to IP.
  81. resolving = IP::get_singleton()->resolve_hostname_queue_item(server_host);
  82. status = STATUS_RESOLVING;
  83. }
  84. return OK;
  85. }
  86. void HTTPClientTCP::set_connection(const Ref<StreamPeer> &p_connection) {
  87. ERR_FAIL_COND_MSG(p_connection.is_null(), "Connection is not a reference to a valid StreamPeer object.");
  88. if (ssl) {
  89. ERR_FAIL_NULL_MSG(Object::cast_to<StreamPeerSSL>(p_connection.ptr()),
  90. "Connection is not a reference to a valid StreamPeerSSL object.");
  91. }
  92. if (connection == p_connection) {
  93. return;
  94. }
  95. close();
  96. connection = p_connection;
  97. status = STATUS_CONNECTED;
  98. }
  99. Ref<StreamPeer> HTTPClientTCP::get_connection() const {
  100. return connection;
  101. }
  102. static bool _check_request_url(HTTPClientTCP::Method p_method, const String &p_url) {
  103. switch (p_method) {
  104. case HTTPClientTCP::METHOD_CONNECT: {
  105. // Authority in host:port format, as in RFC7231.
  106. int pos = p_url.find_char(':');
  107. return 0 < pos && pos < p_url.length() - 1;
  108. }
  109. case HTTPClientTCP::METHOD_OPTIONS: {
  110. if (p_url == "*") {
  111. return true;
  112. }
  113. [[fallthrough]];
  114. }
  115. default:
  116. // Absolute path or absolute URL.
  117. return p_url.begins_with("/") || p_url.begins_with("http://") || p_url.begins_with("https://");
  118. }
  119. }
  120. Error HTTPClientTCP::request(Method p_method, const String &p_url, const Vector<String> &p_headers, const uint8_t *p_body, int p_body_size) {
  121. ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER);
  122. ERR_FAIL_COND_V(!_check_request_url(p_method, p_url), ERR_INVALID_PARAMETER);
  123. ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER);
  124. ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA);
  125. Error err = verify_headers(p_headers);
  126. if (err) {
  127. return err;
  128. }
  129. String uri = p_url;
  130. if (!ssl && http_proxy_port != -1) {
  131. uri = vformat("http://%s:%d%s", conn_host, conn_port, p_url);
  132. }
  133. String request = String(_methods[p_method]) + " " + uri + " HTTP/1.1\r\n";
  134. bool add_host = true;
  135. bool add_clen = p_body_size > 0;
  136. bool add_uagent = true;
  137. bool add_accept = true;
  138. for (int i = 0; i < p_headers.size(); i++) {
  139. request += p_headers[i] + "\r\n";
  140. if (add_host && p_headers[i].findn("Host:") == 0) {
  141. add_host = false;
  142. }
  143. if (add_clen && p_headers[i].findn("Content-Length:") == 0) {
  144. add_clen = false;
  145. }
  146. if (add_uagent && p_headers[i].findn("User-Agent:") == 0) {
  147. add_uagent = false;
  148. }
  149. if (add_accept && p_headers[i].findn("Accept:") == 0) {
  150. add_accept = false;
  151. }
  152. }
  153. if (add_host) {
  154. if ((ssl && conn_port == PORT_HTTPS) || (!ssl && conn_port == PORT_HTTP)) {
  155. // Don't append the standard ports.
  156. request += "Host: " + conn_host + "\r\n";
  157. } else {
  158. request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n";
  159. }
  160. }
  161. if (add_clen) {
  162. request += "Content-Length: " + itos(p_body_size) + "\r\n";
  163. // Should it add utf8 encoding?
  164. }
  165. if (add_uagent) {
  166. request += "User-Agent: GodotEngine/" + String(VERSION_FULL_BUILD) + " (" + OS::get_singleton()->get_name() + ")\r\n";
  167. }
  168. if (add_accept) {
  169. request += "Accept: */*\r\n";
  170. }
  171. request += "\r\n";
  172. CharString cs = request.utf8();
  173. request_buffer->clear();
  174. request_buffer->put_data((const uint8_t *)cs.get_data(), cs.length());
  175. if (p_body_size > 0) {
  176. request_buffer->put_data(p_body, p_body_size);
  177. }
  178. request_buffer->seek(0);
  179. status = STATUS_REQUESTING;
  180. head_request = p_method == METHOD_HEAD;
  181. return OK;
  182. }
  183. bool HTTPClientTCP::has_response() const {
  184. return response_headers.size() != 0;
  185. }
  186. bool HTTPClientTCP::is_response_chunked() const {
  187. return chunked;
  188. }
  189. int HTTPClientTCP::get_response_code() const {
  190. return response_num;
  191. }
  192. Error HTTPClientTCP::get_response_headers(List<String> *r_response) {
  193. if (!response_headers.size()) {
  194. return ERR_INVALID_PARAMETER;
  195. }
  196. for (int i = 0; i < response_headers.size(); i++) {
  197. r_response->push_back(response_headers[i]);
  198. }
  199. response_headers.clear();
  200. return OK;
  201. }
  202. void HTTPClientTCP::close() {
  203. if (tcp_connection->get_status() != StreamPeerTCP::STATUS_NONE) {
  204. tcp_connection->disconnect_from_host();
  205. }
  206. connection.unref();
  207. proxy_client.unref();
  208. status = STATUS_DISCONNECTED;
  209. head_request = false;
  210. if (resolving != IP::RESOLVER_INVALID_ID) {
  211. IP::get_singleton()->erase_resolve_item(resolving);
  212. resolving = IP::RESOLVER_INVALID_ID;
  213. }
  214. ip_candidates.clear();
  215. response_headers.clear();
  216. response_str.clear();
  217. request_buffer->clear();
  218. body_size = -1;
  219. body_left = 0;
  220. chunk_left = 0;
  221. chunk_trailer_part = false;
  222. read_until_eof = false;
  223. response_num = 0;
  224. handshaking = false;
  225. }
  226. Error HTTPClientTCP::poll() {
  227. if (tcp_connection.is_valid()) {
  228. tcp_connection->poll();
  229. }
  230. switch (status) {
  231. case STATUS_RESOLVING: {
  232. ERR_FAIL_COND_V(resolving == IP::RESOLVER_INVALID_ID, ERR_BUG);
  233. IP::ResolverStatus rstatus = IP::get_singleton()->get_resolve_item_status(resolving);
  234. switch (rstatus) {
  235. case IP::RESOLVER_STATUS_WAITING:
  236. return OK; // Still resolving.
  237. case IP::RESOLVER_STATUS_DONE: {
  238. ip_candidates = IP::get_singleton()->get_resolve_item_addresses(resolving);
  239. IP::get_singleton()->erase_resolve_item(resolving);
  240. resolving = IP::RESOLVER_INVALID_ID;
  241. Error err = ERR_BUG; // Should be at least one entry.
  242. while (ip_candidates.size() > 0) {
  243. err = tcp_connection->connect_to_host(ip_candidates.pop_front(), server_port);
  244. if (err == OK) {
  245. break;
  246. }
  247. }
  248. if (err) {
  249. status = STATUS_CANT_CONNECT;
  250. return err;
  251. }
  252. status = STATUS_CONNECTING;
  253. } break;
  254. case IP::RESOLVER_STATUS_NONE:
  255. case IP::RESOLVER_STATUS_ERROR: {
  256. IP::get_singleton()->erase_resolve_item(resolving);
  257. resolving = IP::RESOLVER_INVALID_ID;
  258. close();
  259. status = STATUS_CANT_RESOLVE;
  260. return ERR_CANT_RESOLVE;
  261. } break;
  262. }
  263. } break;
  264. case STATUS_CONNECTING: {
  265. StreamPeerTCP::Status s = tcp_connection->get_status();
  266. switch (s) {
  267. case StreamPeerTCP::STATUS_CONNECTING: {
  268. return OK;
  269. } break;
  270. case StreamPeerTCP::STATUS_CONNECTED: {
  271. if (ssl && proxy_client.is_valid()) {
  272. Error err = proxy_client->poll();
  273. if (err == ERR_UNCONFIGURED) {
  274. proxy_client->set_connection(tcp_connection);
  275. const Vector<String> headers;
  276. err = proxy_client->request(METHOD_CONNECT, vformat("%s:%d", conn_host, conn_port), headers, nullptr, 0);
  277. if (err != OK) {
  278. status = STATUS_CANT_CONNECT;
  279. return err;
  280. }
  281. } else if (err != OK) {
  282. status = STATUS_CANT_CONNECT;
  283. return err;
  284. }
  285. switch (proxy_client->get_status()) {
  286. case STATUS_REQUESTING: {
  287. return OK;
  288. } break;
  289. case STATUS_BODY: {
  290. proxy_client->read_response_body_chunk();
  291. return OK;
  292. } break;
  293. case STATUS_CONNECTED: {
  294. if (proxy_client->get_response_code() != RESPONSE_OK) {
  295. status = STATUS_CANT_CONNECT;
  296. return ERR_CANT_CONNECT;
  297. }
  298. proxy_client.unref();
  299. return OK;
  300. }
  301. case STATUS_DISCONNECTED:
  302. case STATUS_RESOLVING:
  303. case STATUS_CONNECTING: {
  304. status = STATUS_CANT_CONNECT;
  305. ERR_FAIL_V(ERR_BUG);
  306. } break;
  307. default: {
  308. status = STATUS_CANT_CONNECT;
  309. return ERR_CANT_CONNECT;
  310. } break;
  311. }
  312. } else if (ssl) {
  313. Ref<StreamPeerSSL> ssl;
  314. if (!handshaking) {
  315. // Connect the StreamPeerSSL and start handshaking.
  316. ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
  317. ssl->set_blocking_handshake_enabled(false);
  318. Error err = ssl->connect_to_stream(tcp_connection, ssl_verify_host, conn_host);
  319. if (err != OK) {
  320. close();
  321. status = STATUS_SSL_HANDSHAKE_ERROR;
  322. return ERR_CANT_CONNECT;
  323. }
  324. connection = ssl;
  325. handshaking = true;
  326. } else {
  327. // We are already handshaking, which means we can use your already active SSL connection.
  328. ssl = static_cast<Ref<StreamPeerSSL>>(connection);
  329. if (ssl.is_null()) {
  330. close();
  331. status = STATUS_SSL_HANDSHAKE_ERROR;
  332. return ERR_CANT_CONNECT;
  333. }
  334. ssl->poll(); // Try to finish the handshake.
  335. }
  336. if (ssl->get_status() == StreamPeerSSL::STATUS_CONNECTED) {
  337. // Handshake has been successful.
  338. handshaking = false;
  339. ip_candidates.clear();
  340. status = STATUS_CONNECTED;
  341. return OK;
  342. } else if (ssl->get_status() != StreamPeerSSL::STATUS_HANDSHAKING) {
  343. // Handshake has failed.
  344. close();
  345. status = STATUS_SSL_HANDSHAKE_ERROR;
  346. return ERR_CANT_CONNECT;
  347. }
  348. // ... we will need to poll more for handshake to finish.
  349. } else {
  350. ip_candidates.clear();
  351. status = STATUS_CONNECTED;
  352. }
  353. return OK;
  354. } break;
  355. case StreamPeerTCP::STATUS_ERROR:
  356. case StreamPeerTCP::STATUS_NONE: {
  357. Error err = ERR_CANT_CONNECT;
  358. while (ip_candidates.size() > 0) {
  359. tcp_connection->disconnect_from_host();
  360. err = tcp_connection->connect_to_host(ip_candidates.pop_front(), server_port);
  361. if (err == OK) {
  362. return OK;
  363. }
  364. }
  365. close();
  366. status = STATUS_CANT_CONNECT;
  367. return err;
  368. } break;
  369. }
  370. } break;
  371. case STATUS_BODY:
  372. case STATUS_CONNECTED: {
  373. // Check if we are still connected.
  374. if (ssl) {
  375. Ref<StreamPeerSSL> tmp = connection;
  376. tmp->poll();
  377. if (tmp->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
  378. status = STATUS_CONNECTION_ERROR;
  379. return ERR_CONNECTION_ERROR;
  380. }
  381. } else if (tcp_connection->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  382. status = STATUS_CONNECTION_ERROR;
  383. return ERR_CONNECTION_ERROR;
  384. }
  385. // Connection established, requests can now be made.
  386. return OK;
  387. } break;
  388. case STATUS_REQUESTING: {
  389. if (request_buffer->get_available_bytes()) {
  390. int avail = request_buffer->get_available_bytes();
  391. int pos = request_buffer->get_position();
  392. const Vector<uint8_t> data = request_buffer->get_data_array();
  393. int wrote = 0;
  394. Error err;
  395. if (blocking) {
  396. err = connection->put_data(data.ptr() + pos, avail);
  397. wrote += avail;
  398. } else {
  399. err = connection->put_partial_data(data.ptr() + pos, avail, wrote);
  400. }
  401. if (err != OK) {
  402. close();
  403. status = STATUS_CONNECTION_ERROR;
  404. return ERR_CONNECTION_ERROR;
  405. }
  406. pos += wrote;
  407. request_buffer->seek(pos);
  408. if (avail - wrote > 0) {
  409. return OK;
  410. }
  411. request_buffer->clear();
  412. }
  413. while (true) {
  414. uint8_t byte;
  415. int rec = 0;
  416. Error err = _get_http_data(&byte, 1, rec);
  417. if (err != OK) {
  418. close();
  419. status = STATUS_CONNECTION_ERROR;
  420. return ERR_CONNECTION_ERROR;
  421. }
  422. if (rec == 0) {
  423. return OK; // Still requesting, keep trying!
  424. }
  425. response_str.push_back(byte);
  426. int rs = response_str.size();
  427. if (
  428. (rs >= 2 && response_str[rs - 2] == '\n' && response_str[rs - 1] == '\n') ||
  429. (rs >= 4 && response_str[rs - 4] == '\r' && response_str[rs - 3] == '\n' && response_str[rs - 2] == '\r' && response_str[rs - 1] == '\n')) {
  430. // End of response, parse.
  431. response_str.push_back(0);
  432. String response;
  433. response.parse_utf8((const char *)response_str.ptr());
  434. Vector<String> responses = response.split("\n");
  435. body_size = -1;
  436. chunked = false;
  437. body_left = 0;
  438. chunk_left = 0;
  439. chunk_trailer_part = false;
  440. read_until_eof = false;
  441. response_str.clear();
  442. response_headers.clear();
  443. response_num = RESPONSE_OK;
  444. // Per the HTTP 1.1 spec, keep-alive is the default.
  445. // Not following that specification breaks standard implementations.
  446. // Broken web servers should be fixed.
  447. bool keep_alive = true;
  448. for (int i = 0; i < responses.size(); i++) {
  449. String header = responses[i].strip_edges();
  450. String s = header.to_lower();
  451. if (s.length() == 0) {
  452. continue;
  453. }
  454. if (s.begins_with("content-length:")) {
  455. body_size = s.substr(s.find(":") + 1, s.length()).strip_edges().to_int();
  456. body_left = body_size;
  457. } else if (s.begins_with("transfer-encoding:")) {
  458. String encoding = header.substr(header.find(":") + 1, header.length()).strip_edges();
  459. if (encoding == "chunked") {
  460. chunked = true;
  461. }
  462. } else if (s.begins_with("connection: close")) {
  463. keep_alive = false;
  464. }
  465. if (i == 0 && responses[i].begins_with("HTTP")) {
  466. String num = responses[i].get_slicec(' ', 1);
  467. response_num = num.to_int();
  468. } else {
  469. response_headers.push_back(header);
  470. }
  471. }
  472. // This is a HEAD request, we won't receive anything.
  473. if (head_request) {
  474. body_size = 0;
  475. body_left = 0;
  476. }
  477. if (body_size != -1 || chunked) {
  478. status = STATUS_BODY;
  479. } else if (!keep_alive) {
  480. read_until_eof = true;
  481. status = STATUS_BODY;
  482. } else {
  483. status = STATUS_CONNECTED;
  484. }
  485. return OK;
  486. }
  487. }
  488. } break;
  489. case STATUS_DISCONNECTED: {
  490. return ERR_UNCONFIGURED;
  491. } break;
  492. case STATUS_CONNECTION_ERROR:
  493. case STATUS_SSL_HANDSHAKE_ERROR: {
  494. return ERR_CONNECTION_ERROR;
  495. } break;
  496. case STATUS_CANT_CONNECT: {
  497. return ERR_CANT_CONNECT;
  498. } break;
  499. case STATUS_CANT_RESOLVE: {
  500. return ERR_CANT_RESOLVE;
  501. } break;
  502. }
  503. return OK;
  504. }
  505. int64_t HTTPClientTCP::get_response_body_length() const {
  506. return body_size;
  507. }
  508. PackedByteArray HTTPClientTCP::read_response_body_chunk() {
  509. ERR_FAIL_COND_V(status != STATUS_BODY, PackedByteArray());
  510. PackedByteArray ret;
  511. Error err = OK;
  512. if (chunked) {
  513. while (true) {
  514. if (chunk_trailer_part) {
  515. // We need to consume the trailer part too or keep-alive will break.
  516. uint8_t b;
  517. int rec = 0;
  518. err = _get_http_data(&b, 1, rec);
  519. if (rec == 0) {
  520. break;
  521. }
  522. chunk.push_back(b);
  523. int cs = chunk.size();
  524. if ((cs >= 2 && chunk[cs - 2] == '\r' && chunk[cs - 1] == '\n')) {
  525. if (cs == 2) {
  526. // Finally over.
  527. chunk_trailer_part = false;
  528. status = STATUS_CONNECTED;
  529. chunk.clear();
  530. break;
  531. } else {
  532. // We do not process nor return the trailer data.
  533. chunk.clear();
  534. }
  535. }
  536. } else if (chunk_left == 0) {
  537. // Reading length.
  538. uint8_t b;
  539. int rec = 0;
  540. err = _get_http_data(&b, 1, rec);
  541. if (rec == 0) {
  542. break;
  543. }
  544. chunk.push_back(b);
  545. if (chunk.size() > 32) {
  546. ERR_PRINT("HTTP Invalid chunk hex len");
  547. status = STATUS_CONNECTION_ERROR;
  548. break;
  549. }
  550. if (chunk.size() > 2 && chunk[chunk.size() - 2] == '\r' && chunk[chunk.size() - 1] == '\n') {
  551. int len = 0;
  552. for (int i = 0; i < chunk.size() - 2; i++) {
  553. char c = chunk[i];
  554. int v = 0;
  555. if (is_digit(c)) {
  556. v = c - '0';
  557. } else if (c >= 'a' && c <= 'f') {
  558. v = c - 'a' + 10;
  559. } else if (c >= 'A' && c <= 'F') {
  560. v = c - 'A' + 10;
  561. } else {
  562. ERR_PRINT("HTTP Chunk len not in hex!!");
  563. status = STATUS_CONNECTION_ERROR;
  564. break;
  565. }
  566. len <<= 4;
  567. len |= v;
  568. if (len > (1 << 24)) {
  569. ERR_PRINT("HTTP Chunk too big!! >16mb");
  570. status = STATUS_CONNECTION_ERROR;
  571. break;
  572. }
  573. }
  574. if (len == 0) {
  575. // End reached!
  576. chunk_trailer_part = true;
  577. chunk.clear();
  578. break;
  579. }
  580. chunk_left = len + 2;
  581. chunk.resize(chunk_left);
  582. }
  583. } else {
  584. int rec = 0;
  585. err = _get_http_data(&chunk.write[chunk.size() - chunk_left], chunk_left, rec);
  586. if (rec == 0) {
  587. break;
  588. }
  589. chunk_left -= rec;
  590. if (chunk_left == 0) {
  591. if (chunk[chunk.size() - 2] != '\r' || chunk[chunk.size() - 1] != '\n') {
  592. ERR_PRINT("HTTP Invalid chunk terminator (not \\r\\n)");
  593. status = STATUS_CONNECTION_ERROR;
  594. break;
  595. }
  596. ret.resize(chunk.size() - 2);
  597. uint8_t *w = ret.ptrw();
  598. memcpy(w, chunk.ptr(), chunk.size() - 2);
  599. chunk.clear();
  600. }
  601. break;
  602. }
  603. }
  604. } else {
  605. int to_read = !read_until_eof ? MIN(body_left, read_chunk_size) : read_chunk_size;
  606. ret.resize(to_read);
  607. int _offset = 0;
  608. while (to_read > 0) {
  609. int rec = 0;
  610. {
  611. uint8_t *w = ret.ptrw();
  612. err = _get_http_data(w + _offset, to_read, rec);
  613. }
  614. if (rec <= 0) { // Ended up reading less.
  615. ret.resize(_offset);
  616. break;
  617. } else {
  618. _offset += rec;
  619. to_read -= rec;
  620. if (!read_until_eof) {
  621. body_left -= rec;
  622. }
  623. }
  624. if (err != OK) {
  625. ret.resize(_offset);
  626. break;
  627. }
  628. }
  629. }
  630. if (err != OK) {
  631. close();
  632. if (err == ERR_FILE_EOF) {
  633. status = STATUS_DISCONNECTED; // Server disconnected.
  634. } else {
  635. status = STATUS_CONNECTION_ERROR;
  636. }
  637. } else if (body_left == 0 && !chunked && !read_until_eof) {
  638. status = STATUS_CONNECTED;
  639. }
  640. return ret;
  641. }
  642. HTTPClientTCP::Status HTTPClientTCP::get_status() const {
  643. return status;
  644. }
  645. void HTTPClientTCP::set_blocking_mode(bool p_enable) {
  646. blocking = p_enable;
  647. }
  648. bool HTTPClientTCP::is_blocking_mode_enabled() const {
  649. return blocking;
  650. }
  651. Error HTTPClientTCP::_get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
  652. if (blocking) {
  653. // We can't use StreamPeer.get_data, since when reaching EOF we will get an
  654. // error without knowing how many bytes we received.
  655. Error err = ERR_FILE_EOF;
  656. int read = 0;
  657. int left = p_bytes;
  658. r_received = 0;
  659. while (left > 0) {
  660. err = connection->get_partial_data(p_buffer + r_received, left, read);
  661. if (err == OK) {
  662. r_received += read;
  663. } else if (err == ERR_FILE_EOF) {
  664. r_received += read;
  665. return err;
  666. } else {
  667. return err;
  668. }
  669. left -= read;
  670. }
  671. return err;
  672. } else {
  673. return connection->get_partial_data(p_buffer, p_bytes, r_received);
  674. }
  675. }
  676. void HTTPClientTCP::set_read_chunk_size(int p_size) {
  677. ERR_FAIL_COND(p_size < 256 || p_size > (1 << 24));
  678. read_chunk_size = p_size;
  679. }
  680. int HTTPClientTCP::get_read_chunk_size() const {
  681. return read_chunk_size;
  682. }
  683. void HTTPClientTCP::set_http_proxy(const String &p_host, int p_port) {
  684. if (p_host.is_empty() || p_port == -1) {
  685. http_proxy_host = "";
  686. http_proxy_port = -1;
  687. } else {
  688. http_proxy_host = p_host;
  689. http_proxy_port = p_port;
  690. }
  691. }
  692. void HTTPClientTCP::set_https_proxy(const String &p_host, int p_port) {
  693. if (p_host.is_empty() || p_port == -1) {
  694. https_proxy_host = "";
  695. https_proxy_port = -1;
  696. } else {
  697. https_proxy_host = p_host;
  698. https_proxy_port = p_port;
  699. }
  700. }
  701. HTTPClientTCP::HTTPClientTCP() {
  702. tcp_connection.instantiate();
  703. request_buffer.instantiate();
  704. }
  705. HTTPClient *(*HTTPClient::_create)() = HTTPClientTCP::_create_func;
  706. #endif // #ifndef JAVASCRIPT_ENABLED