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
31#include "http_client.h"
32
33const 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
45HTTPClient *HTTPClient::create() {
46 if (_create) {
47 return _create();
48 }
49 return nullptr;
50}
51
52void HTTPClient::set_http_proxy(const String &p_host, int p_port) {
53 WARN_PRINT("HTTP proxy feature is not available");
54}
55
56void HTTPClient::set_https_proxy(const String &p_host, int p_port) {
57 WARN_PRINT("HTTPS proxy feature is not available");
58}
59
60Error HTTPClient::_request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const Vector<uint8_t> &p_body) {
61 int size = p_body.size();
62 return request(p_method, p_url, p_headers, size > 0 ? p_body.ptr() : nullptr, size);
63}
64
65Error HTTPClient::_request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body) {
66 CharString body_utf8 = p_body.utf8();
67 int size = body_utf8.length();
68 return request(p_method, p_url, p_headers, size > 0 ? (const uint8_t *)body_utf8.get_data() : nullptr, size);
69}
70
71String HTTPClient::query_string_from_dict(const Dictionary &p_dict) {
72 String query = "";
73 Array keys = p_dict.keys();
74 for (int i = 0; i < keys.size(); ++i) {
75 String encoded_key = String(keys[i]).uri_encode();
76 Variant value = p_dict[keys[i]];
77 switch (value.get_type()) {
78 case Variant::ARRAY: {
79 // Repeat the key with every values
80 Array values = value;
81 for (int j = 0; j < values.size(); ++j) {
82 query += "&" + encoded_key + "=" + String(values[j]).uri_encode();
83 }
84 break;
85 }
86 case Variant::NIL: {
87 // Add the key with no value
88 query += "&" + encoded_key;
89 break;
90 }
91 default: {
92 // Add the key-value pair
93 query += "&" + encoded_key + "=" + String(value).uri_encode();
94 }
95 }
96 }
97 return query.substr(1);
98}
99
100Error HTTPClient::verify_headers(const Vector<String> &p_headers) {
101 for (int i = 0; i < p_headers.size(); i++) {
102 String sanitized = p_headers[i].strip_edges();
103 ERR_FAIL_COND_V_MSG(sanitized.is_empty(), ERR_INVALID_PARAMETER, "Invalid HTTP header at index " + itos(i) + ": empty.");
104 ERR_FAIL_COND_V_MSG(sanitized.find(":") < 1, ERR_INVALID_PARAMETER,
105 "Invalid HTTP header at index " + itos(i) + ": String must contain header-value pair, delimited by ':', but was: " + p_headers[i]);
106 }
107
108 return OK;
109}
110
111Dictionary HTTPClient::_get_response_headers_as_dictionary() {
112 List<String> rh;
113 get_response_headers(&rh);
114 Dictionary ret;
115 for (const String &s : rh) {
116 int sp = s.find(":");
117 if (sp == -1) {
118 continue;
119 }
120 String key = s.substr(0, sp).strip_edges();
121 String value = s.substr(sp + 1, s.length()).strip_edges();
122 ret[key] = value;
123 }
124
125 return ret;
126}
127
128PackedStringArray HTTPClient::_get_response_headers() {
129 List<String> rh;
130 get_response_headers(&rh);
131 PackedStringArray ret;
132 ret.resize(rh.size());
133 int idx = 0;
134 for (const String &E : rh) {
135 ret.set(idx++, E);
136 }
137
138 return ret;
139}
140
141void HTTPClient::_bind_methods() {
142 ClassDB::bind_method(D_METHOD("connect_to_host", "host", "port", "tls_options"), &HTTPClient::connect_to_host, DEFVAL(-1), DEFVAL(Ref<TLSOptions>()));
143 ClassDB::bind_method(D_METHOD("set_connection", "connection"), &HTTPClient::set_connection);
144 ClassDB::bind_method(D_METHOD("get_connection"), &HTTPClient::get_connection);
145 ClassDB::bind_method(D_METHOD("request_raw", "method", "url", "headers", "body"), &HTTPClient::_request_raw);
146 ClassDB::bind_method(D_METHOD("request", "method", "url", "headers", "body"), &HTTPClient::_request, DEFVAL(String()));
147 ClassDB::bind_method(D_METHOD("close"), &HTTPClient::close);
148
149 ClassDB::bind_method(D_METHOD("has_response"), &HTTPClient::has_response);
150 ClassDB::bind_method(D_METHOD("is_response_chunked"), &HTTPClient::is_response_chunked);
151 ClassDB::bind_method(D_METHOD("get_response_code"), &HTTPClient::get_response_code);
152 ClassDB::bind_method(D_METHOD("get_response_headers"), &HTTPClient::_get_response_headers);
153 ClassDB::bind_method(D_METHOD("get_response_headers_as_dictionary"), &HTTPClient::_get_response_headers_as_dictionary);
154 ClassDB::bind_method(D_METHOD("get_response_body_length"), &HTTPClient::get_response_body_length);
155 ClassDB::bind_method(D_METHOD("read_response_body_chunk"), &HTTPClient::read_response_body_chunk);
156 ClassDB::bind_method(D_METHOD("set_read_chunk_size", "bytes"), &HTTPClient::set_read_chunk_size);
157 ClassDB::bind_method(D_METHOD("get_read_chunk_size"), &HTTPClient::get_read_chunk_size);
158
159 ClassDB::bind_method(D_METHOD("set_blocking_mode", "enabled"), &HTTPClient::set_blocking_mode);
160 ClassDB::bind_method(D_METHOD("is_blocking_mode_enabled"), &HTTPClient::is_blocking_mode_enabled);
161
162 ClassDB::bind_method(D_METHOD("get_status"), &HTTPClient::get_status);
163 ClassDB::bind_method(D_METHOD("poll"), &HTTPClient::poll);
164
165 ClassDB::bind_method(D_METHOD("set_http_proxy", "host", "port"), &HTTPClient::set_http_proxy);
166 ClassDB::bind_method(D_METHOD("set_https_proxy", "host", "port"), &HTTPClient::set_https_proxy);
167
168 ClassDB::bind_method(D_METHOD("query_string_from_dict", "fields"), &HTTPClient::query_string_from_dict);
169
170 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "blocking_mode_enabled"), "set_blocking_mode", "is_blocking_mode_enabled");
171 ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "connection", PROPERTY_HINT_RESOURCE_TYPE, "StreamPeer", PROPERTY_USAGE_NONE), "set_connection", "get_connection");
172 ADD_PROPERTY(PropertyInfo(Variant::INT, "read_chunk_size", PROPERTY_HINT_RANGE, "256,16777216"), "set_read_chunk_size", "get_read_chunk_size");
173
174 BIND_ENUM_CONSTANT(METHOD_GET);
175 BIND_ENUM_CONSTANT(METHOD_HEAD);
176 BIND_ENUM_CONSTANT(METHOD_POST);
177 BIND_ENUM_CONSTANT(METHOD_PUT);
178 BIND_ENUM_CONSTANT(METHOD_DELETE);
179 BIND_ENUM_CONSTANT(METHOD_OPTIONS);
180 BIND_ENUM_CONSTANT(METHOD_TRACE);
181 BIND_ENUM_CONSTANT(METHOD_CONNECT);
182 BIND_ENUM_CONSTANT(METHOD_PATCH);
183 BIND_ENUM_CONSTANT(METHOD_MAX);
184
185 BIND_ENUM_CONSTANT(STATUS_DISCONNECTED);
186 BIND_ENUM_CONSTANT(STATUS_RESOLVING); // Resolving hostname (if hostname was passed in)
187 BIND_ENUM_CONSTANT(STATUS_CANT_RESOLVE);
188 BIND_ENUM_CONSTANT(STATUS_CONNECTING); // Connecting to IP
189 BIND_ENUM_CONSTANT(STATUS_CANT_CONNECT);
190 BIND_ENUM_CONSTANT(STATUS_CONNECTED); // Connected, now accepting requests
191 BIND_ENUM_CONSTANT(STATUS_REQUESTING); // Request in progress
192 BIND_ENUM_CONSTANT(STATUS_BODY); // Request resulted in body which must be read
193 BIND_ENUM_CONSTANT(STATUS_CONNECTION_ERROR);
194 BIND_ENUM_CONSTANT(STATUS_TLS_HANDSHAKE_ERROR);
195
196 BIND_ENUM_CONSTANT(RESPONSE_CONTINUE);
197 BIND_ENUM_CONSTANT(RESPONSE_SWITCHING_PROTOCOLS);
198 BIND_ENUM_CONSTANT(RESPONSE_PROCESSING);
199
200 // 2xx successful
201 BIND_ENUM_CONSTANT(RESPONSE_OK);
202 BIND_ENUM_CONSTANT(RESPONSE_CREATED);
203 BIND_ENUM_CONSTANT(RESPONSE_ACCEPTED);
204 BIND_ENUM_CONSTANT(RESPONSE_NON_AUTHORITATIVE_INFORMATION);
205 BIND_ENUM_CONSTANT(RESPONSE_NO_CONTENT);
206 BIND_ENUM_CONSTANT(RESPONSE_RESET_CONTENT);
207 BIND_ENUM_CONSTANT(RESPONSE_PARTIAL_CONTENT);
208 BIND_ENUM_CONSTANT(RESPONSE_MULTI_STATUS);
209 BIND_ENUM_CONSTANT(RESPONSE_ALREADY_REPORTED);
210 BIND_ENUM_CONSTANT(RESPONSE_IM_USED);
211
212 // 3xx redirection
213 BIND_ENUM_CONSTANT(RESPONSE_MULTIPLE_CHOICES);
214 BIND_ENUM_CONSTANT(RESPONSE_MOVED_PERMANENTLY);
215 BIND_ENUM_CONSTANT(RESPONSE_FOUND);
216 BIND_ENUM_CONSTANT(RESPONSE_SEE_OTHER);
217 BIND_ENUM_CONSTANT(RESPONSE_NOT_MODIFIED);
218 BIND_ENUM_CONSTANT(RESPONSE_USE_PROXY);
219 BIND_ENUM_CONSTANT(RESPONSE_SWITCH_PROXY);
220 BIND_ENUM_CONSTANT(RESPONSE_TEMPORARY_REDIRECT);
221 BIND_ENUM_CONSTANT(RESPONSE_PERMANENT_REDIRECT);
222
223 // 4xx client error
224 BIND_ENUM_CONSTANT(RESPONSE_BAD_REQUEST);
225 BIND_ENUM_CONSTANT(RESPONSE_UNAUTHORIZED);
226 BIND_ENUM_CONSTANT(RESPONSE_PAYMENT_REQUIRED);
227 BIND_ENUM_CONSTANT(RESPONSE_FORBIDDEN);
228 BIND_ENUM_CONSTANT(RESPONSE_NOT_FOUND);
229 BIND_ENUM_CONSTANT(RESPONSE_METHOD_NOT_ALLOWED);
230 BIND_ENUM_CONSTANT(RESPONSE_NOT_ACCEPTABLE);
231 BIND_ENUM_CONSTANT(RESPONSE_PROXY_AUTHENTICATION_REQUIRED);
232 BIND_ENUM_CONSTANT(RESPONSE_REQUEST_TIMEOUT);
233 BIND_ENUM_CONSTANT(RESPONSE_CONFLICT);
234 BIND_ENUM_CONSTANT(RESPONSE_GONE);
235 BIND_ENUM_CONSTANT(RESPONSE_LENGTH_REQUIRED);
236 BIND_ENUM_CONSTANT(RESPONSE_PRECONDITION_FAILED);
237 BIND_ENUM_CONSTANT(RESPONSE_REQUEST_ENTITY_TOO_LARGE);
238 BIND_ENUM_CONSTANT(RESPONSE_REQUEST_URI_TOO_LONG);
239 BIND_ENUM_CONSTANT(RESPONSE_UNSUPPORTED_MEDIA_TYPE);
240 BIND_ENUM_CONSTANT(RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE);
241 BIND_ENUM_CONSTANT(RESPONSE_EXPECTATION_FAILED);
242 BIND_ENUM_CONSTANT(RESPONSE_IM_A_TEAPOT);
243 BIND_ENUM_CONSTANT(RESPONSE_MISDIRECTED_REQUEST);
244 BIND_ENUM_CONSTANT(RESPONSE_UNPROCESSABLE_ENTITY);
245 BIND_ENUM_CONSTANT(RESPONSE_LOCKED);
246 BIND_ENUM_CONSTANT(RESPONSE_FAILED_DEPENDENCY);
247 BIND_ENUM_CONSTANT(RESPONSE_UPGRADE_REQUIRED);
248 BIND_ENUM_CONSTANT(RESPONSE_PRECONDITION_REQUIRED);
249 BIND_ENUM_CONSTANT(RESPONSE_TOO_MANY_REQUESTS);
250 BIND_ENUM_CONSTANT(RESPONSE_REQUEST_HEADER_FIELDS_TOO_LARGE);
251 BIND_ENUM_CONSTANT(RESPONSE_UNAVAILABLE_FOR_LEGAL_REASONS);
252
253 // 5xx server error
254 BIND_ENUM_CONSTANT(RESPONSE_INTERNAL_SERVER_ERROR);
255 BIND_ENUM_CONSTANT(RESPONSE_NOT_IMPLEMENTED);
256 BIND_ENUM_CONSTANT(RESPONSE_BAD_GATEWAY);
257 BIND_ENUM_CONSTANT(RESPONSE_SERVICE_UNAVAILABLE);
258 BIND_ENUM_CONSTANT(RESPONSE_GATEWAY_TIMEOUT);
259 BIND_ENUM_CONSTANT(RESPONSE_HTTP_VERSION_NOT_SUPPORTED);
260 BIND_ENUM_CONSTANT(RESPONSE_VARIANT_ALSO_NEGOTIATES);
261 BIND_ENUM_CONSTANT(RESPONSE_INSUFFICIENT_STORAGE);
262 BIND_ENUM_CONSTANT(RESPONSE_LOOP_DETECTED);
263 BIND_ENUM_CONSTANT(RESPONSE_NOT_EXTENDED);
264 BIND_ENUM_CONSTANT(RESPONSE_NETWORK_AUTH_REQUIRED);
265}
266