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 "io/stream_peer_ssl.h"
32 
connect(const String & p_host,int p_port,bool p_ssl,bool p_verify_host)33 Error HTTPClient::connect(const String &p_host, int p_port, bool p_ssl, bool p_verify_host) {
34 
35 	close();
36 	conn_port = p_port;
37 	conn_host = p_host;
38 
39 	if (conn_host.begins_with("http://")) {
40 
41 		conn_host = conn_host.replace_first("http://", "");
42 	} else if (conn_host.begins_with("https://")) {
43 		//use https
44 		conn_host = conn_host.replace_first("https://", "");
45 	}
46 
47 	ssl = p_ssl;
48 	ssl_verify_host = p_verify_host;
49 	connection = tcp_connection;
50 
51 	if (conn_host.is_valid_ip_address()) {
52 		//is ip
53 		Error err = tcp_connection->connect(IP_Address(conn_host), p_port);
54 		if (err) {
55 			status = STATUS_CANT_CONNECT;
56 			return err;
57 		}
58 
59 		status = STATUS_CONNECTING;
60 	} else {
61 		//is hostname
62 		resolving = IP::get_singleton()->resolve_hostname_queue_item(conn_host);
63 		status = STATUS_RESOLVING;
64 	}
65 
66 	return OK;
67 }
68 
set_connection(const Ref<StreamPeer> & p_connection)69 void HTTPClient::set_connection(const Ref<StreamPeer> &p_connection) {
70 
71 	close();
72 	connection = p_connection;
73 	status = STATUS_CONNECTED;
74 }
75 
get_connection() const76 Ref<StreamPeer> HTTPClient::get_connection() const {
77 
78 	return connection;
79 }
80 
request_raw(Method p_method,const String & p_url,const Vector<String> & p_headers,const DVector<uint8_t> & p_body)81 Error HTTPClient::request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const DVector<uint8_t> &p_body) {
82 
83 	ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER);
84 	ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER);
85 	ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA);
86 
87 	static const char *_methods[METHOD_MAX] = {
88 		"GET",
89 		"HEAD",
90 		"POST",
91 		"PUT",
92 		"DELETE",
93 		"OPTIONS",
94 		"TRACE",
95 		"CONNECT"
96 	};
97 
98 	String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n";
99 	if ((ssl && conn_port == 443) || (!ssl && conn_port == 80)) {
100 		// don't append the standard ports
101 		request += "Host: " + conn_host + "\r\n";
102 	} else {
103 		request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n";
104 	}
105 	bool add_clen = p_body.size() > 0;
106 	for (int i = 0; i < p_headers.size(); i++) {
107 		request += p_headers[i] + "\r\n";
108 		if (add_clen && p_headers[i].find("Content-Length:") == 0) {
109 			add_clen = false;
110 		}
111 	}
112 	if (add_clen) {
113 		request += "Content-Length: " + itos(p_body.size()) + "\r\n";
114 		//should it add utf8 encoding? not sure
115 	}
116 	request += "\r\n";
117 	CharString cs = request.utf8();
118 
119 	DVector<uint8_t> data;
120 
121 	//Maybe this goes faster somehow?
122 	for (int i = 0; i < cs.length(); i++) {
123 		data.append(cs[i]);
124 	}
125 	data.append_array(p_body);
126 
127 	DVector<uint8_t>::Read r = data.read();
128 	Error err = connection->put_data(&r[0], data.size());
129 
130 	if (err) {
131 		close();
132 		status = STATUS_CONNECTION_ERROR;
133 		return err;
134 	}
135 
136 	status = STATUS_REQUESTING;
137 
138 	return OK;
139 }
140 
request(Method p_method,const String & p_url,const Vector<String> & p_headers,const String & p_body)141 Error HTTPClient::request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body) {
142 
143 	ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER);
144 	ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER);
145 	ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA);
146 
147 	static const char *_methods[METHOD_MAX] = {
148 		"GET",
149 		"HEAD",
150 		"POST",
151 		"PUT",
152 		"DELETE",
153 		"OPTIONS",
154 		"TRACE",
155 		"CONNECT"
156 	};
157 
158 	String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n";
159 	if ((ssl && conn_port == 443) || (!ssl && conn_port == 80)) {
160 		// don't append the standard ports
161 		request += "Host: " + conn_host + "\r\n";
162 	} else {
163 		request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n";
164 	}
165 	bool add_clen = p_body.length() > 0;
166 	for (int i = 0; i < p_headers.size(); i++) {
167 		request += p_headers[i] + "\r\n";
168 		if (add_clen && p_headers[i].find("Content-Length:") == 0) {
169 			add_clen = false;
170 		}
171 	}
172 	if (add_clen) {
173 		request += "Content-Length: " + itos(p_body.utf8().length()) + "\r\n";
174 		//should it add utf8 encoding? not sure
175 	}
176 	request += "\r\n";
177 	request += p_body;
178 
179 	CharString cs = request.utf8();
180 	Error err = connection->put_data((const uint8_t *)cs.ptr(), cs.length());
181 	if (err) {
182 		close();
183 		status = STATUS_CONNECTION_ERROR;
184 		return err;
185 	}
186 
187 	status = STATUS_REQUESTING;
188 
189 	return OK;
190 }
191 
send_body_text(const String & p_body)192 Error HTTPClient::send_body_text(const String &p_body) {
193 
194 	return OK;
195 }
196 
send_body_data(const ByteArray & p_body)197 Error HTTPClient::send_body_data(const ByteArray &p_body) {
198 
199 	return OK;
200 }
201 
has_response() const202 bool HTTPClient::has_response() const {
203 
204 	return response_headers.size() != 0;
205 }
206 
is_response_chunked() const207 bool HTTPClient::is_response_chunked() const {
208 
209 	return chunked;
210 }
211 
get_response_code() const212 int HTTPClient::get_response_code() const {
213 
214 	return response_num;
215 }
216 
get_response_headers(List<String> * r_response)217 Error HTTPClient::get_response_headers(List<String> *r_response) {
218 
219 	if (!response_headers.size())
220 		return ERR_INVALID_PARAMETER;
221 
222 	for (int i = 0; i < response_headers.size(); i++) {
223 
224 		r_response->push_back(response_headers[i]);
225 	}
226 
227 	response_headers.clear();
228 
229 	return OK;
230 }
231 
close()232 void HTTPClient::close() {
233 
234 	if (tcp_connection->get_status() != StreamPeerTCP::STATUS_NONE)
235 		tcp_connection->disconnect();
236 
237 	connection.unref();
238 	status = STATUS_DISCONNECTED;
239 	if (resolving != IP::RESOLVER_INVALID_ID) {
240 
241 		IP::get_singleton()->erase_resolve_item(resolving);
242 		resolving = IP::RESOLVER_INVALID_ID;
243 	}
244 
245 	response_headers.clear();
246 	response_str.clear();
247 	body_size = 0;
248 	body_left = 0;
249 	chunk_left = 0;
250 	response_num = 0;
251 }
252 
poll()253 Error HTTPClient::poll() {
254 
255 	switch (status) {
256 
257 		case STATUS_RESOLVING: {
258 			ERR_FAIL_COND_V(resolving == IP::RESOLVER_INVALID_ID, ERR_BUG);
259 
260 			IP::ResolverStatus rstatus = IP::get_singleton()->get_resolve_item_status(resolving);
261 			switch (rstatus) {
262 				case IP::RESOLVER_STATUS_WAITING:
263 					return OK; //still resolving
264 
265 				case IP::RESOLVER_STATUS_DONE: {
266 
267 					IP_Address host = IP::get_singleton()->get_resolve_item_address(resolving);
268 					Error err = tcp_connection->connect(host, conn_port);
269 					IP::get_singleton()->erase_resolve_item(resolving);
270 					resolving = IP::RESOLVER_INVALID_ID;
271 					if (err) {
272 						status = STATUS_CANT_CONNECT;
273 						return err;
274 					}
275 
276 					status = STATUS_CONNECTING;
277 				} break;
278 				case IP::RESOLVER_STATUS_NONE:
279 				case IP::RESOLVER_STATUS_ERROR: {
280 
281 					IP::get_singleton()->erase_resolve_item(resolving);
282 					resolving = IP::RESOLVER_INVALID_ID;
283 					close();
284 					status = STATUS_CANT_RESOLVE;
285 					return ERR_CANT_RESOLVE;
286 				} break;
287 			}
288 		} break;
289 		case STATUS_CONNECTING: {
290 
291 			StreamPeerTCP::Status s = tcp_connection->get_status();
292 			switch (s) {
293 
294 				case StreamPeerTCP::STATUS_CONNECTING: {
295 					return OK; //do none
296 				} break;
297 				case StreamPeerTCP::STATUS_CONNECTED: {
298 					if (ssl) {
299 						Ref<StreamPeerSSL> ssl = StreamPeerSSL::create();
300 						Error err = ssl->connect(tcp_connection, true, ssl_verify_host ? conn_host : String());
301 						if (err != OK) {
302 							close();
303 							status = STATUS_SSL_HANDSHAKE_ERROR;
304 							return ERR_CANT_CONNECT;
305 						}
306 						//print_line("SSL! TURNED ON!");
307 						connection = ssl;
308 					}
309 					status = STATUS_CONNECTED;
310 					return OK;
311 				} break;
312 				case StreamPeerTCP::STATUS_ERROR:
313 				case StreamPeerTCP::STATUS_NONE: {
314 
315 					close();
316 					status = STATUS_CANT_CONNECT;
317 					return ERR_CANT_CONNECT;
318 				} break;
319 			}
320 		} break;
321 		case STATUS_CONNECTED: {
322 			//request something please
323 			return OK;
324 		} break;
325 		case STATUS_REQUESTING: {
326 
327 			while (true) {
328 				uint8_t byte;
329 				int rec = 0;
330 				Error err = _get_http_data(&byte, 1, rec);
331 				if (err != OK) {
332 					close();
333 					status = STATUS_CONNECTION_ERROR;
334 					return ERR_CONNECTION_ERROR;
335 				}
336 
337 				if (rec == 0)
338 					return OK; //keep trying!
339 
340 				response_str.push_back(byte);
341 				int rs = response_str.size();
342 				if (
343 						(rs >= 2 && response_str[rs - 2] == '\n' && response_str[rs - 1] == '\n') ||
344 						(rs >= 4 && response_str[rs - 4] == '\r' && response_str[rs - 3] == '\n' && rs >= 4 && response_str[rs - 2] == '\r' && response_str[rs - 1] == '\n')) {
345 
346 					//end of response, parse.
347 					response_str.push_back(0);
348 					String response;
349 					response.parse_utf8((const char *)response_str.ptr());
350 					//print_line("END OF RESPONSE? :\n"+response+"\n------");
351 					Vector<String> responses = response.split("\n");
352 					body_size = 0;
353 					chunked = false;
354 					body_left = 0;
355 					chunk_left = 0;
356 					response_str.clear();
357 					response_headers.clear();
358 					response_num = RESPONSE_OK;
359 
360 					for (int i = 0; i < responses.size(); i++) {
361 
362 						String header = responses[i].strip_edges();
363 						String s = header.to_lower();
364 						if (s.length() == 0)
365 							continue;
366 						if (s.begins_with("content-length:")) {
367 							body_size = s.substr(s.find(":") + 1, s.length()).strip_edges().to_int();
368 							body_left = body_size;
369 						}
370 
371 						if (s.begins_with("transfer-encoding:")) {
372 							String encoding = header.substr(header.find(":") + 1, header.length()).strip_edges();
373 							//print_line("TRANSFER ENCODING: "+encoding);
374 							if (encoding == "chunked") {
375 								chunked = true;
376 							}
377 						}
378 
379 						if (i == 0 && responses[i].begins_with("HTTP")) {
380 
381 							String num = responses[i].get_slicec(' ', 1);
382 							response_num = num.to_int();
383 						} else {
384 
385 							response_headers.push_back(header);
386 						}
387 					}
388 
389 					if (body_size == 0 && !chunked) {
390 
391 						status = STATUS_CONNECTED; //ask for something again?
392 					} else {
393 						status = STATUS_BODY;
394 					}
395 					return OK;
396 				}
397 			}
398 			//wait for response
399 			return OK;
400 		} break;
401 		case STATUS_DISCONNECTED: {
402 			return ERR_UNCONFIGURED;
403 		} break;
404 		case STATUS_CONNECTION_ERROR: {
405 			return ERR_CONNECTION_ERROR;
406 		} break;
407 		case STATUS_CANT_CONNECT: {
408 			return ERR_CANT_CONNECT;
409 		} break;
410 		case STATUS_CANT_RESOLVE: {
411 			return ERR_CANT_RESOLVE;
412 		} break;
413 	}
414 
415 	return OK;
416 }
417 
_get_response_headers_as_dictionary()418 Dictionary HTTPClient::_get_response_headers_as_dictionary() {
419 
420 	List<String> rh;
421 	get_response_headers(&rh);
422 	Dictionary ret;
423 	for (const List<String>::Element *E = rh.front(); E; E = E->next()) {
424 		String s = E->get();
425 		int sp = s.find(":");
426 		if (sp == -1)
427 			continue;
428 		String key = s.substr(0, sp).strip_edges();
429 		String value = s.substr(sp + 1, s.length()).strip_edges();
430 		ret[key] = value;
431 	}
432 
433 	return ret;
434 }
435 
_get_response_headers()436 StringArray HTTPClient::_get_response_headers() {
437 
438 	List<String> rh;
439 	get_response_headers(&rh);
440 	StringArray ret;
441 	ret.resize(rh.size());
442 	int idx = 0;
443 	for (const List<String>::Element *E = rh.front(); E; E = E->next()) {
444 		ret.set(idx++, E->get());
445 	}
446 
447 	return ret;
448 }
449 
get_response_body_length() const450 int HTTPClient::get_response_body_length() const {
451 
452 	return body_size;
453 }
454 
read_response_body_chunk()455 ByteArray HTTPClient::read_response_body_chunk() {
456 
457 	ERR_FAIL_COND_V(status != STATUS_BODY, ByteArray());
458 
459 	Error err = OK;
460 
461 	if (chunked) {
462 
463 		while (true) {
464 
465 			if (chunk_left == 0) {
466 				//reading len
467 				uint8_t b;
468 				int rec = 0;
469 				err = _get_http_data(&b, 1, rec);
470 
471 				if (rec == 0)
472 					break;
473 
474 				chunk.push_back(b);
475 
476 				if (chunk.size() > 32) {
477 					ERR_PRINT("HTTP Invalid chunk hex len");
478 					status = STATUS_CONNECTION_ERROR;
479 					return ByteArray();
480 				}
481 
482 				if (chunk.size() > 2 && chunk[chunk.size() - 2] == '\r' && chunk[chunk.size() - 1] == '\n') {
483 
484 					int len = 0;
485 					for (int i = 0; i < chunk.size() - 2; i++) {
486 						char c = chunk[i];
487 						int v = 0;
488 						if (c >= '0' && c <= '9')
489 							v = c - '0';
490 						else if (c >= 'a' && c <= 'f')
491 							v = c - 'a' + 10;
492 						else if (c >= 'A' && c <= 'F')
493 							v = c - 'A' + 10;
494 						else {
495 							ERR_PRINT("HTTP Chunk len not in hex!!");
496 							status = STATUS_CONNECTION_ERROR;
497 							return ByteArray();
498 						}
499 						len <<= 4;
500 						len |= v;
501 						if (len > (1 << 24)) {
502 							ERR_PRINT("HTTP Chunk too big!! >16mb");
503 							status = STATUS_CONNECTION_ERROR;
504 							return ByteArray();
505 						}
506 					}
507 
508 					if (len == 0) {
509 						//end!
510 						status = STATUS_CONNECTED;
511 						chunk.clear();
512 						return ByteArray();
513 					}
514 
515 					chunk_left = len + 2;
516 					chunk.resize(chunk_left);
517 				}
518 			} else {
519 
520 				int rec = 0;
521 				err = _get_http_data(&chunk[chunk.size() - chunk_left], chunk_left, rec);
522 				if (rec == 0) {
523 					break;
524 				}
525 				chunk_left -= rec;
526 
527 				if (chunk_left == 0) {
528 
529 					if (chunk[chunk.size() - 2] != '\r' || chunk[chunk.size() - 1] != '\n') {
530 						ERR_PRINT("HTTP Invalid chunk terminator (not \\r\\n)");
531 						status = STATUS_CONNECTION_ERROR;
532 						return ByteArray();
533 					}
534 
535 					ByteArray ret;
536 					ret.resize(chunk.size() - 2);
537 					{
538 						ByteArray::Write w = ret.write();
539 						copymem(w.ptr(), chunk.ptr(), chunk.size() - 2);
540 					}
541 					chunk.clear();
542 
543 					return ret;
544 				}
545 
546 				break;
547 			}
548 		}
549 
550 	} else {
551 
552 		int to_read = MIN(body_left, read_chunk_size);
553 		ByteArray ret;
554 		ret.resize(to_read);
555 		int _offset = 0;
556 		while (to_read > 0) {
557 			int rec = 0;
558 			{
559 				ByteArray::Write w = ret.write();
560 				err = _get_http_data(w.ptr() + _offset, to_read, rec);
561 			}
562 			if (rec > 0) {
563 				body_left -= rec;
564 				to_read -= rec;
565 				_offset += rec;
566 			} else {
567 				if (to_read > 0) //ended up reading less
568 					ret.resize(_offset);
569 				break;
570 			}
571 		}
572 		if (body_left == 0) {
573 			status = STATUS_CONNECTED;
574 		}
575 		return ret;
576 	}
577 
578 	if (err != OK) {
579 		close();
580 		if (err == ERR_FILE_EOF) {
581 
582 			status = STATUS_DISCONNECTED; //server disconnected
583 		} else {
584 
585 			status = STATUS_CONNECTION_ERROR;
586 		}
587 	} else if (body_left == 0 && !chunked) {
588 
589 		status = STATUS_CONNECTED;
590 	}
591 
592 	return ByteArray();
593 }
594 
get_status() const595 HTTPClient::Status HTTPClient::get_status() const {
596 
597 	return status;
598 }
599 
set_blocking_mode(bool p_enable)600 void HTTPClient::set_blocking_mode(bool p_enable) {
601 
602 	blocking = p_enable;
603 }
604 
is_blocking_mode_enabled() const605 bool HTTPClient::is_blocking_mode_enabled() const {
606 
607 	return blocking;
608 }
609 
_get_http_data(uint8_t * p_buffer,int p_bytes,int & r_received)610 Error HTTPClient::_get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
611 
612 	if (blocking) {
613 
614 		Error err = connection->get_data(p_buffer, p_bytes);
615 		if (err == OK)
616 			r_received = p_bytes;
617 		else
618 			r_received = 0;
619 		return err;
620 	} else {
621 		return connection->get_partial_data(p_buffer, p_bytes, r_received);
622 	}
623 }
624 
_bind_methods()625 void HTTPClient::_bind_methods() {
626 
627 	ObjectTypeDB::bind_method(_MD("connect:Error", "host", "port", "use_ssl", "verify_host"), &HTTPClient::connect, DEFVAL(false), DEFVAL(true));
628 	ObjectTypeDB::bind_method(_MD("set_connection", "connection:StreamPeer"), &HTTPClient::set_connection);
629 	ObjectTypeDB::bind_method(_MD("get_connection:StreamPeer"), &HTTPClient::get_connection);
630 	ObjectTypeDB::bind_method(_MD("request_raw", "method", "url", "headers", "body"), &HTTPClient::request_raw);
631 	ObjectTypeDB::bind_method(_MD("request", "method", "url", "headers", "body"), &HTTPClient::request, DEFVAL(String()));
632 	ObjectTypeDB::bind_method(_MD("send_body_text", "body"), &HTTPClient::send_body_text);
633 	ObjectTypeDB::bind_method(_MD("send_body_data", "body"), &HTTPClient::send_body_data);
634 	ObjectTypeDB::bind_method(_MD("close"), &HTTPClient::close);
635 
636 	ObjectTypeDB::bind_method(_MD("has_response"), &HTTPClient::has_response);
637 	ObjectTypeDB::bind_method(_MD("is_response_chunked"), &HTTPClient::is_response_chunked);
638 	ObjectTypeDB::bind_method(_MD("get_response_code"), &HTTPClient::get_response_code);
639 	ObjectTypeDB::bind_method(_MD("get_response_headers"), &HTTPClient::_get_response_headers);
640 	ObjectTypeDB::bind_method(_MD("get_response_headers_as_dictionary"), &HTTPClient::_get_response_headers_as_dictionary);
641 	ObjectTypeDB::bind_method(_MD("get_response_body_length"), &HTTPClient::get_response_body_length);
642 	ObjectTypeDB::bind_method(_MD("read_response_body_chunk"), &HTTPClient::read_response_body_chunk);
643 	ObjectTypeDB::bind_method(_MD("set_read_chunk_size", "bytes"), &HTTPClient::set_read_chunk_size);
644 
645 	ObjectTypeDB::bind_method(_MD("set_blocking_mode", "enabled"), &HTTPClient::set_blocking_mode);
646 	ObjectTypeDB::bind_method(_MD("is_blocking_mode_enabled"), &HTTPClient::is_blocking_mode_enabled);
647 
648 	ObjectTypeDB::bind_method(_MD("get_status"), &HTTPClient::get_status);
649 	ObjectTypeDB::bind_method(_MD("poll:Error"), &HTTPClient::poll);
650 
651 	ObjectTypeDB::bind_method(_MD("query_string_from_dict:String", "fields"), &HTTPClient::query_string_from_dict);
652 
653 	BIND_CONSTANT(METHOD_GET);
654 	BIND_CONSTANT(METHOD_HEAD);
655 	BIND_CONSTANT(METHOD_POST);
656 	BIND_CONSTANT(METHOD_PUT);
657 	BIND_CONSTANT(METHOD_DELETE);
658 	BIND_CONSTANT(METHOD_OPTIONS);
659 	BIND_CONSTANT(METHOD_TRACE);
660 	BIND_CONSTANT(METHOD_CONNECT);
661 	BIND_CONSTANT(METHOD_MAX);
662 
663 	BIND_CONSTANT(STATUS_DISCONNECTED);
664 	BIND_CONSTANT(STATUS_RESOLVING); //resolving hostname (if passed a hostname)
665 	BIND_CONSTANT(STATUS_CANT_RESOLVE);
666 	BIND_CONSTANT(STATUS_CONNECTING); //connecting to ip
667 	BIND_CONSTANT(STATUS_CANT_CONNECT);
668 	BIND_CONSTANT(STATUS_CONNECTED); //connected );  requests only accepted here
669 	BIND_CONSTANT(STATUS_REQUESTING); // request in progress
670 	BIND_CONSTANT(STATUS_BODY); // request resulted in body );  which must be read
671 	BIND_CONSTANT(STATUS_CONNECTION_ERROR);
672 	BIND_CONSTANT(STATUS_SSL_HANDSHAKE_ERROR);
673 
674 	BIND_CONSTANT(RESPONSE_CONTINUE);
675 	BIND_CONSTANT(RESPONSE_SWITCHING_PROTOCOLS);
676 	BIND_CONSTANT(RESPONSE_PROCESSING);
677 
678 	// 2xx successful
679 	BIND_CONSTANT(RESPONSE_OK);
680 	BIND_CONSTANT(RESPONSE_CREATED);
681 	BIND_CONSTANT(RESPONSE_ACCEPTED);
682 	BIND_CONSTANT(RESPONSE_NON_AUTHORITATIVE_INFORMATION);
683 	BIND_CONSTANT(RESPONSE_NO_CONTENT);
684 	BIND_CONSTANT(RESPONSE_RESET_CONTENT);
685 	BIND_CONSTANT(RESPONSE_PARTIAL_CONTENT);
686 	BIND_CONSTANT(RESPONSE_MULTI_STATUS);
687 	BIND_CONSTANT(RESPONSE_IM_USED);
688 
689 	// 3xx redirection
690 	BIND_CONSTANT(RESPONSE_MULTIPLE_CHOICES);
691 	BIND_CONSTANT(RESPONSE_MOVED_PERMANENTLY);
692 	BIND_CONSTANT(RESPONSE_FOUND);
693 	BIND_CONSTANT(RESPONSE_SEE_OTHER);
694 	BIND_CONSTANT(RESPONSE_NOT_MODIFIED);
695 	BIND_CONSTANT(RESPONSE_USE_PROXY);
696 	BIND_CONSTANT(RESPONSE_TEMPORARY_REDIRECT);
697 
698 	// 4xx client error
699 	BIND_CONSTANT(RESPONSE_BAD_REQUEST);
700 	BIND_CONSTANT(RESPONSE_UNAUTHORIZED);
701 	BIND_CONSTANT(RESPONSE_PAYMENT_REQUIRED);
702 	BIND_CONSTANT(RESPONSE_FORBIDDEN);
703 	BIND_CONSTANT(RESPONSE_NOT_FOUND);
704 	BIND_CONSTANT(RESPONSE_METHOD_NOT_ALLOWED);
705 	BIND_CONSTANT(RESPONSE_NOT_ACCEPTABLE);
706 	BIND_CONSTANT(RESPONSE_PROXY_AUTHENTICATION_REQUIRED);
707 	BIND_CONSTANT(RESPONSE_REQUEST_TIMEOUT);
708 	BIND_CONSTANT(RESPONSE_CONFLICT);
709 	BIND_CONSTANT(RESPONSE_GONE);
710 	BIND_CONSTANT(RESPONSE_LENGTH_REQUIRED);
711 	BIND_CONSTANT(RESPONSE_PRECONDITION_FAILED);
712 	BIND_CONSTANT(RESPONSE_REQUEST_ENTITY_TOO_LARGE);
713 	BIND_CONSTANT(RESPONSE_REQUEST_URI_TOO_LONG);
714 	BIND_CONSTANT(RESPONSE_UNSUPPORTED_MEDIA_TYPE);
715 	BIND_CONSTANT(RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE);
716 	BIND_CONSTANT(RESPONSE_EXPECTATION_FAILED);
717 	BIND_CONSTANT(RESPONSE_UNPROCESSABLE_ENTITY);
718 	BIND_CONSTANT(RESPONSE_LOCKED);
719 	BIND_CONSTANT(RESPONSE_FAILED_DEPENDENCY);
720 	BIND_CONSTANT(RESPONSE_UPGRADE_REQUIRED);
721 
722 	// 5xx server error
723 	BIND_CONSTANT(RESPONSE_INTERNAL_SERVER_ERROR);
724 	BIND_CONSTANT(RESPONSE_NOT_IMPLEMENTED);
725 	BIND_CONSTANT(RESPONSE_BAD_GATEWAY);
726 	BIND_CONSTANT(RESPONSE_SERVICE_UNAVAILABLE);
727 	BIND_CONSTANT(RESPONSE_GATEWAY_TIMEOUT);
728 	BIND_CONSTANT(RESPONSE_HTTP_VERSION_NOT_SUPPORTED);
729 	BIND_CONSTANT(RESPONSE_INSUFFICIENT_STORAGE);
730 	BIND_CONSTANT(RESPONSE_NOT_EXTENDED);
731 }
732 
set_read_chunk_size(int p_size)733 void HTTPClient::set_read_chunk_size(int p_size) {
734 	ERR_FAIL_COND(p_size < 256 || p_size > (1 << 24));
735 	read_chunk_size = p_size;
736 }
737 
query_string_from_dict(const Dictionary & p_dict)738 String HTTPClient::query_string_from_dict(const Dictionary &p_dict) {
739 	String query = "";
740 	Array keys = p_dict.keys();
741 	for (int i = 0; i < keys.size(); ++i) {
742 		query += "&" + String(keys[i]).http_escape() + "=" + String(p_dict[keys[i]]).http_escape();
743 	}
744 	query.erase(0, 1);
745 	return query;
746 }
747 
HTTPClient()748 HTTPClient::HTTPClient() {
749 
750 	tcp_connection = StreamPeerTCP::create_ref();
751 	resolving = IP::RESOLVER_INVALID_ID;
752 	status = STATUS_DISCONNECTED;
753 	conn_port = 80;
754 	body_size = 0;
755 	chunked = false;
756 	body_left = 0;
757 	chunk_left = 0;
758 	response_num = 0;
759 	ssl = false;
760 	blocking = false;
761 	read_chunk_size = 4096;
762 }
763 
~HTTPClient()764 HTTPClient::~HTTPClient() {
765 }
766