http_client.cpp 32 KB

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