http_client.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. blocking = false;
  752. handshaking = false;
  753. // 64 KiB by default (favors fast download speeds at the cost of memory usage).
  754. read_chunk_size = 65536;
  755. }
  756. HTTPClient::~HTTPClient() {
  757. }
  758. #endif // #ifndef JAVASCRIPT_ENABLED
  759. void HTTPClient::set_http_proxy(const String &p_host, int p_port) {
  760. #ifdef JAVASCRIPT_ENABLED
  761. WARN_PRINT("HTTP proxy feature is not available");
  762. #else
  763. if (p_host.empty() || p_port == -1) {
  764. http_proxy_host = "";
  765. http_proxy_port = -1;
  766. } else {
  767. http_proxy_host = p_host;
  768. http_proxy_port = p_port;
  769. }
  770. #endif
  771. }
  772. void HTTPClient::set_https_proxy(const String &p_host, int p_port) {
  773. #ifdef JAVASCRIPT_ENABLED
  774. WARN_PRINT("HTTPS proxy feature is not available");
  775. #else
  776. if (p_host.empty() || p_port == -1) {
  777. https_proxy_host = "";
  778. https_proxy_port = -1;
  779. } else {
  780. https_proxy_host = p_host;
  781. https_proxy_port = p_port;
  782. }
  783. #endif
  784. }
  785. String HTTPClient::query_string_from_dict(const Dictionary &p_dict) {
  786. String query = "";
  787. Array keys = p_dict.keys();
  788. for (int i = 0; i < keys.size(); ++i) {
  789. String encoded_key = String(keys[i]).http_escape();
  790. Variant value = p_dict[keys[i]];
  791. switch (value.get_type()) {
  792. case Variant::ARRAY: {
  793. // Repeat the key with every values
  794. Array values = value;
  795. for (int j = 0; j < values.size(); ++j) {
  796. query += "&" + encoded_key + "=" + String(values[j]).http_escape();
  797. }
  798. break;
  799. }
  800. case Variant::NIL: {
  801. // Add the key with no value
  802. query += "&" + encoded_key;
  803. break;
  804. }
  805. default: {
  806. // Add the key-value pair
  807. query += "&" + encoded_key + "=" + String(value).http_escape();
  808. }
  809. }
  810. }
  811. query.erase(0, 1);
  812. return query;
  813. }
  814. Dictionary HTTPClient::_get_response_headers_as_dictionary() {
  815. List<String> rh;
  816. get_response_headers(&rh);
  817. Dictionary ret;
  818. for (const List<String>::Element *E = rh.front(); E; E = E->next()) {
  819. const String &s = E->get();
  820. int sp = s.find(":");
  821. if (sp == -1) {
  822. continue;
  823. }
  824. String key = s.substr(0, sp).strip_edges();
  825. String value = s.substr(sp + 1, s.length()).strip_edges();
  826. ret[key] = value;
  827. }
  828. return ret;
  829. }
  830. PoolStringArray HTTPClient::_get_response_headers() {
  831. List<String> rh;
  832. get_response_headers(&rh);
  833. PoolStringArray ret;
  834. ret.resize(rh.size());
  835. int idx = 0;
  836. for (const List<String>::Element *E = rh.front(); E; E = E->next()) {
  837. ret.set(idx++, E->get());
  838. }
  839. return ret;
  840. }
  841. void HTTPClient::_bind_methods() {
  842. ClassDB::bind_method(D_METHOD("connect_to_host", "host", "port", "use_ssl", "verify_host"), &HTTPClient::connect_to_host, DEFVAL(-1), DEFVAL(false), DEFVAL(true));
  843. ClassDB::bind_method(D_METHOD("set_connection", "connection"), &HTTPClient::set_connection);
  844. ClassDB::bind_method(D_METHOD("get_connection"), &HTTPClient::get_connection);
  845. ClassDB::bind_method(D_METHOD("request_raw", "method", "url", "headers", "body"), &HTTPClient::request_raw);
  846. ClassDB::bind_method(D_METHOD("request", "method", "url", "headers", "body"), &HTTPClient::request, DEFVAL(String()));
  847. ClassDB::bind_method(D_METHOD("close"), &HTTPClient::close);
  848. ClassDB::bind_method(D_METHOD("has_response"), &HTTPClient::has_response);
  849. ClassDB::bind_method(D_METHOD("is_response_chunked"), &HTTPClient::is_response_chunked);
  850. ClassDB::bind_method(D_METHOD("get_response_code"), &HTTPClient::get_response_code);
  851. ClassDB::bind_method(D_METHOD("get_response_headers"), &HTTPClient::_get_response_headers);
  852. ClassDB::bind_method(D_METHOD("get_response_headers_as_dictionary"), &HTTPClient::_get_response_headers_as_dictionary);
  853. ClassDB::bind_method(D_METHOD("get_response_body_length"), &HTTPClient::get_response_body_length);
  854. ClassDB::bind_method(D_METHOD("read_response_body_chunk"), &HTTPClient::read_response_body_chunk);
  855. ClassDB::bind_method(D_METHOD("set_read_chunk_size", "bytes"), &HTTPClient::set_read_chunk_size);
  856. ClassDB::bind_method(D_METHOD("get_read_chunk_size"), &HTTPClient::get_read_chunk_size);
  857. ClassDB::bind_method(D_METHOD("set_blocking_mode", "enabled"), &HTTPClient::set_blocking_mode);
  858. ClassDB::bind_method(D_METHOD("is_blocking_mode_enabled"), &HTTPClient::is_blocking_mode_enabled);
  859. ClassDB::bind_method(D_METHOD("get_status"), &HTTPClient::get_status);
  860. ClassDB::bind_method(D_METHOD("poll"), &HTTPClient::poll);
  861. ClassDB::bind_method(D_METHOD("set_http_proxy", "host", "port"), &HTTPClient::set_http_proxy);
  862. ClassDB::bind_method(D_METHOD("set_https_proxy", "host", "port"), &HTTPClient::set_https_proxy);
  863. ClassDB::bind_method(D_METHOD("query_string_from_dict", "fields"), &HTTPClient::query_string_from_dict);
  864. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "blocking_mode_enabled"), "set_blocking_mode", "is_blocking_mode_enabled");
  865. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "connection", PROPERTY_HINT_RESOURCE_TYPE, "StreamPeer", 0), "set_connection", "get_connection");
  866. ADD_PROPERTY(PropertyInfo(Variant::INT, "read_chunk_size", PROPERTY_HINT_RANGE, "256,16777216"), "set_read_chunk_size", "get_read_chunk_size");
  867. BIND_ENUM_CONSTANT(METHOD_GET);
  868. BIND_ENUM_CONSTANT(METHOD_HEAD);
  869. BIND_ENUM_CONSTANT(METHOD_POST);
  870. BIND_ENUM_CONSTANT(METHOD_PUT);
  871. BIND_ENUM_CONSTANT(METHOD_DELETE);
  872. BIND_ENUM_CONSTANT(METHOD_OPTIONS);
  873. BIND_ENUM_CONSTANT(METHOD_TRACE);
  874. BIND_ENUM_CONSTANT(METHOD_CONNECT);
  875. BIND_ENUM_CONSTANT(METHOD_PATCH);
  876. BIND_ENUM_CONSTANT(METHOD_MAX);
  877. BIND_ENUM_CONSTANT(STATUS_DISCONNECTED);
  878. BIND_ENUM_CONSTANT(STATUS_RESOLVING); // Resolving hostname (if hostname was passed in)
  879. BIND_ENUM_CONSTANT(STATUS_CANT_RESOLVE);
  880. BIND_ENUM_CONSTANT(STATUS_CONNECTING); // Connecting to IP
  881. BIND_ENUM_CONSTANT(STATUS_CANT_CONNECT);
  882. BIND_ENUM_CONSTANT(STATUS_CONNECTED); // Connected, now accepting requests
  883. BIND_ENUM_CONSTANT(STATUS_REQUESTING); // Request in progress
  884. BIND_ENUM_CONSTANT(STATUS_BODY); // Request resulted in body which must be read
  885. BIND_ENUM_CONSTANT(STATUS_CONNECTION_ERROR);
  886. BIND_ENUM_CONSTANT(STATUS_SSL_HANDSHAKE_ERROR);
  887. BIND_ENUM_CONSTANT(RESPONSE_CONTINUE);
  888. BIND_ENUM_CONSTANT(RESPONSE_SWITCHING_PROTOCOLS);
  889. BIND_ENUM_CONSTANT(RESPONSE_PROCESSING);
  890. // 2xx successful
  891. BIND_ENUM_CONSTANT(RESPONSE_OK);
  892. BIND_ENUM_CONSTANT(RESPONSE_CREATED);
  893. BIND_ENUM_CONSTANT(RESPONSE_ACCEPTED);
  894. BIND_ENUM_CONSTANT(RESPONSE_NON_AUTHORITATIVE_INFORMATION);
  895. BIND_ENUM_CONSTANT(RESPONSE_NO_CONTENT);
  896. BIND_ENUM_CONSTANT(RESPONSE_RESET_CONTENT);
  897. BIND_ENUM_CONSTANT(RESPONSE_PARTIAL_CONTENT);
  898. BIND_ENUM_CONSTANT(RESPONSE_MULTI_STATUS);
  899. BIND_ENUM_CONSTANT(RESPONSE_ALREADY_REPORTED);
  900. BIND_ENUM_CONSTANT(RESPONSE_IM_USED);
  901. // 3xx redirection
  902. BIND_ENUM_CONSTANT(RESPONSE_MULTIPLE_CHOICES);
  903. BIND_ENUM_CONSTANT(RESPONSE_MOVED_PERMANENTLY);
  904. BIND_ENUM_CONSTANT(RESPONSE_FOUND);
  905. BIND_ENUM_CONSTANT(RESPONSE_SEE_OTHER);
  906. BIND_ENUM_CONSTANT(RESPONSE_NOT_MODIFIED);
  907. BIND_ENUM_CONSTANT(RESPONSE_USE_PROXY);
  908. BIND_ENUM_CONSTANT(RESPONSE_SWITCH_PROXY);
  909. BIND_ENUM_CONSTANT(RESPONSE_TEMPORARY_REDIRECT);
  910. BIND_ENUM_CONSTANT(RESPONSE_PERMANENT_REDIRECT);
  911. // 4xx client error
  912. BIND_ENUM_CONSTANT(RESPONSE_BAD_REQUEST);
  913. BIND_ENUM_CONSTANT(RESPONSE_UNAUTHORIZED);
  914. BIND_ENUM_CONSTANT(RESPONSE_PAYMENT_REQUIRED);
  915. BIND_ENUM_CONSTANT(RESPONSE_FORBIDDEN);
  916. BIND_ENUM_CONSTANT(RESPONSE_NOT_FOUND);
  917. BIND_ENUM_CONSTANT(RESPONSE_METHOD_NOT_ALLOWED);
  918. BIND_ENUM_CONSTANT(RESPONSE_NOT_ACCEPTABLE);
  919. BIND_ENUM_CONSTANT(RESPONSE_PROXY_AUTHENTICATION_REQUIRED);
  920. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_TIMEOUT);
  921. BIND_ENUM_CONSTANT(RESPONSE_CONFLICT);
  922. BIND_ENUM_CONSTANT(RESPONSE_GONE);
  923. BIND_ENUM_CONSTANT(RESPONSE_LENGTH_REQUIRED);
  924. BIND_ENUM_CONSTANT(RESPONSE_PRECONDITION_FAILED);
  925. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_ENTITY_TOO_LARGE);
  926. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_URI_TOO_LONG);
  927. BIND_ENUM_CONSTANT(RESPONSE_UNSUPPORTED_MEDIA_TYPE);
  928. BIND_ENUM_CONSTANT(RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE);
  929. BIND_ENUM_CONSTANT(RESPONSE_EXPECTATION_FAILED);
  930. BIND_ENUM_CONSTANT(RESPONSE_IM_A_TEAPOT);
  931. BIND_ENUM_CONSTANT(RESPONSE_MISDIRECTED_REQUEST);
  932. BIND_ENUM_CONSTANT(RESPONSE_UNPROCESSABLE_ENTITY);
  933. BIND_ENUM_CONSTANT(RESPONSE_LOCKED);
  934. BIND_ENUM_CONSTANT(RESPONSE_FAILED_DEPENDENCY);
  935. BIND_ENUM_CONSTANT(RESPONSE_UPGRADE_REQUIRED);
  936. BIND_ENUM_CONSTANT(RESPONSE_PRECONDITION_REQUIRED);
  937. BIND_ENUM_CONSTANT(RESPONSE_TOO_MANY_REQUESTS);
  938. BIND_ENUM_CONSTANT(RESPONSE_REQUEST_HEADER_FIELDS_TOO_LARGE);
  939. BIND_ENUM_CONSTANT(RESPONSE_UNAVAILABLE_FOR_LEGAL_REASONS);
  940. // 5xx server error
  941. BIND_ENUM_CONSTANT(RESPONSE_INTERNAL_SERVER_ERROR);
  942. BIND_ENUM_CONSTANT(RESPONSE_NOT_IMPLEMENTED);
  943. BIND_ENUM_CONSTANT(RESPONSE_BAD_GATEWAY);
  944. BIND_ENUM_CONSTANT(RESPONSE_SERVICE_UNAVAILABLE);
  945. BIND_ENUM_CONSTANT(RESPONSE_GATEWAY_TIMEOUT);
  946. BIND_ENUM_CONSTANT(RESPONSE_HTTP_VERSION_NOT_SUPPORTED);
  947. BIND_ENUM_CONSTANT(RESPONSE_VARIANT_ALSO_NEGOTIATES);
  948. BIND_ENUM_CONSTANT(RESPONSE_INSUFFICIENT_STORAGE);
  949. BIND_ENUM_CONSTANT(RESPONSE_LOOP_DETECTED);
  950. BIND_ENUM_CONSTANT(RESPONSE_NOT_EXTENDED);
  951. BIND_ENUM_CONSTANT(RESPONSE_NETWORK_AUTH_REQUIRED);
  952. }