2
0

http_client.cpp 26 KB

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