1 /*************************************************************************/
2 /*  wsl_server.cpp                                                       */
3 /*************************************************************************/
4 /*                       This file is part of:                           */
5 /*                           GODOT ENGINE                                */
6 /*                      https://godotengine.org                          */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
9 /* Copyright (c) 2014-2020 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 
31 #ifndef JAVASCRIPT_ENABLED
32 
33 #include "wsl_server.h"
34 #include "core/os/os.h"
35 #include "core/project_settings.h"
36 
PendingPeer()37 WSLServer::PendingPeer::PendingPeer() {
38 	use_ssl = false;
39 	time = 0;
40 	has_request = false;
41 	response_sent = 0;
42 	req_pos = 0;
43 	memset(req_buf, 0, sizeof(req_buf));
44 }
45 
_parse_request(const Vector<String> p_protocols)46 bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols) {
47 	Vector<String> psa = String((char *)req_buf).split("\r\n");
48 	int len = psa.size();
49 	ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
50 
51 	Vector<String> req = psa[0].split(" ", false);
52 	ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code.");
53 
54 	// Wrong protocol
55 	ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version.");
56 
57 	Map<String, String> headers;
58 	for (int i = 1; i < len; i++) {
59 		Vector<String> header = psa[i].split(":", false, 1);
60 		ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]);
61 		String name = header[0].to_lower();
62 		String value = header[1].strip_edges();
63 		if (headers.has(name))
64 			headers[name] += "," + value;
65 		else
66 			headers[name] = value;
67 	}
68 #define _WSL_CHECK(NAME, VALUE)                                                         \
69 	ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
70 			"Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
71 #define _WSL_CHECK_EX(NAME) \
72 	ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'.");
73 	_WSL_CHECK("upgrade", "websocket");
74 	_WSL_CHECK("sec-websocket-version", "13");
75 	_WSL_CHECK_EX("sec-websocket-key");
76 	_WSL_CHECK_EX("connection");
77 #undef _WSL_CHECK_EX
78 #undef _WSL_CHECK
79 	key = headers["sec-websocket-key"];
80 	if (headers.has("sec-websocket-protocol")) {
81 		Vector<String> protos = headers["sec-websocket-protocol"].split(",");
82 		for (int i = 0; i < protos.size(); i++) {
83 			String proto = protos[i].strip_edges();
84 			// Check if we have the given protocol
85 			for (int j = 0; j < p_protocols.size(); j++) {
86 				if (proto != p_protocols[j])
87 					continue;
88 				protocol = proto;
89 				break;
90 			}
91 			// Found a protocol
92 			if (protocol != "")
93 				break;
94 		}
95 		if (protocol == "") // Invalid protocol(s) requested
96 			return false;
97 	} else if (p_protocols.size() > 0) // No protocol requested, but we need one
98 		return false;
99 	return true;
100 }
101 
do_handshake(const Vector<String> p_protocols)102 Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols) {
103 	if (OS::get_singleton()->get_ticks_msec() - time > WSL_SERVER_TIMEOUT)
104 		return ERR_TIMEOUT;
105 	if (use_ssl) {
106 		Ref<StreamPeerSSL> ssl = static_cast<Ref<StreamPeerSSL> >(connection);
107 		if (ssl.is_null())
108 			return FAILED;
109 		ssl->poll();
110 		if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING)
111 			return ERR_BUSY;
112 		else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED)
113 			return FAILED;
114 	}
115 	if (!has_request) {
116 		int read = 0;
117 		while (true) {
118 			ERR_FAIL_COND_V_MSG(req_pos >= WSL_MAX_HEADER_SIZE, ERR_OUT_OF_MEMORY, "Response headers too big.");
119 			Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
120 			if (err != OK) // Got an error
121 				return FAILED;
122 			else if (read != 1) // Busy, wait next poll
123 				return ERR_BUSY;
124 			char *r = (char *)req_buf;
125 			int l = req_pos;
126 			if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
127 				r[l - 3] = '\0';
128 				if (!_parse_request(p_protocols)) {
129 					return FAILED;
130 				}
131 				String s = "HTTP/1.1 101 Switching Protocols\r\n";
132 				s += "Upgrade: websocket\r\n";
133 				s += "Connection: Upgrade\r\n";
134 				s += "Sec-WebSocket-Accept: " + WSLPeer::compute_key_response(key) + "\r\n";
135 				if (protocol != "")
136 					s += "Sec-WebSocket-Protocol: " + protocol + "\r\n";
137 				s += "\r\n";
138 				response = s.utf8();
139 				has_request = true;
140 				break;
141 			}
142 			req_pos += 1;
143 		}
144 	}
145 	if (has_request && response_sent < response.size() - 1) {
146 		int sent = 0;
147 		Error err = connection->put_partial_data((const uint8_t *)response.get_data() + response_sent, response.size() - response_sent - 1, sent);
148 		if (err != OK) {
149 			return err;
150 		}
151 		response_sent += sent;
152 	}
153 	if (response_sent < response.size() - 1)
154 		return ERR_BUSY;
155 	return OK;
156 }
157 
listen(int p_port,const Vector<String> p_protocols,bool gd_mp_api)158 Error WSLServer::listen(int p_port, const Vector<String> p_protocols, bool gd_mp_api) {
159 	ERR_FAIL_COND_V(is_listening(), ERR_ALREADY_IN_USE);
160 
161 	_is_multiplayer = gd_mp_api;
162 	// Strip edges from protocols.
163 	_protocols.resize(p_protocols.size());
164 	String *pw = _protocols.ptrw();
165 	for (int i = 0; i < p_protocols.size(); i++) {
166 		pw[i] = p_protocols[i].strip_edges();
167 	}
168 	return _server->listen(p_port, bind_ip);
169 }
170 
poll()171 void WSLServer::poll() {
172 
173 	List<int> remove_ids;
174 	for (Map<int, Ref<WebSocketPeer> >::Element *E = _peer_map.front(); E; E = E->next()) {
175 		Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
176 		peer->poll();
177 		if (!peer->is_connected_to_host()) {
178 			_on_disconnect(E->key(), peer->close_code != -1);
179 			remove_ids.push_back(E->key());
180 		}
181 	}
182 	for (List<int>::Element *E = remove_ids.front(); E; E = E->next()) {
183 		_peer_map.erase(E->get());
184 	}
185 	remove_ids.clear();
186 
187 	List<Ref<PendingPeer> > remove_peers;
188 	for (List<Ref<PendingPeer> >::Element *E = _pending.front(); E; E = E->next()) {
189 		Ref<PendingPeer> ppeer = E->get();
190 		Error err = ppeer->do_handshake(_protocols);
191 		if (err == ERR_BUSY) {
192 			continue;
193 		} else if (err != OK) {
194 			remove_peers.push_back(ppeer);
195 			continue;
196 		}
197 		// Creating new peer
198 		int32_t id = _gen_unique_id();
199 
200 		WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
201 		data->obj = this;
202 		data->conn = ppeer->connection;
203 		data->tcp = ppeer->tcp;
204 		data->is_server = true;
205 		data->id = id;
206 
207 		Ref<WSLPeer> ws_peer = memnew(WSLPeer);
208 		ws_peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
209 		ws_peer->set_no_delay(true);
210 
211 		_peer_map[id] = ws_peer;
212 		remove_peers.push_back(ppeer);
213 		_on_connect(id, ppeer->protocol);
214 	}
215 	for (List<Ref<PendingPeer> >::Element *E = remove_peers.front(); E; E = E->next()) {
216 		_pending.erase(E->get());
217 	}
218 	remove_peers.clear();
219 
220 	if (!_server->is_listening())
221 		return;
222 
223 	while (_server->is_connection_available()) {
224 		Ref<StreamPeerTCP> conn = _server->take_connection();
225 		if (is_refusing_new_connections())
226 			continue; // Conn will go out-of-scope and be closed.
227 
228 		Ref<PendingPeer> peer = memnew(PendingPeer);
229 		if (private_key.is_valid() && ssl_cert.is_valid()) {
230 			Ref<StreamPeerSSL> ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
231 			ssl->set_blocking_handshake_enabled(false);
232 			ssl->accept_stream(conn, private_key, ssl_cert, ca_chain);
233 			peer->connection = ssl;
234 			peer->use_ssl = true;
235 		} else {
236 			peer->connection = conn;
237 		}
238 		peer->tcp = conn;
239 		peer->time = OS::get_singleton()->get_ticks_msec();
240 		_pending.push_back(peer);
241 	}
242 }
243 
is_listening() const244 bool WSLServer::is_listening() const {
245 	return _server->is_listening();
246 }
247 
get_max_packet_size() const248 int WSLServer::get_max_packet_size() const {
249 	return (1 << _out_buf_size) - PROTO_SIZE;
250 }
251 
stop()252 void WSLServer::stop() {
253 	_server->stop();
254 	for (Map<int, Ref<WebSocketPeer> >::Element *E = _peer_map.front(); E; E = E->next()) {
255 		Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
256 		peer->close_now();
257 	}
258 	_pending.clear();
259 	_peer_map.clear();
260 	_protocols.clear();
261 }
262 
has_peer(int p_id) const263 bool WSLServer::has_peer(int p_id) const {
264 	return _peer_map.has(p_id);
265 }
266 
get_peer(int p_id) const267 Ref<WebSocketPeer> WSLServer::get_peer(int p_id) const {
268 	ERR_FAIL_COND_V(!has_peer(p_id), NULL);
269 	return _peer_map[p_id];
270 }
271 
get_peer_address(int p_peer_id) const272 IP_Address WSLServer::get_peer_address(int p_peer_id) const {
273 	ERR_FAIL_COND_V(!has_peer(p_peer_id), IP_Address());
274 
275 	return _peer_map[p_peer_id]->get_connected_host();
276 }
277 
get_peer_port(int p_peer_id) const278 int WSLServer::get_peer_port(int p_peer_id) const {
279 	ERR_FAIL_COND_V(!has_peer(p_peer_id), 0);
280 
281 	return _peer_map[p_peer_id]->get_connected_port();
282 }
283 
disconnect_peer(int p_peer_id,int p_code,String p_reason)284 void WSLServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
285 	ERR_FAIL_COND(!has_peer(p_peer_id));
286 
287 	get_peer(p_peer_id)->close(p_code, p_reason);
288 }
289 
set_buffers(int p_in_buffer,int p_in_packets,int p_out_buffer,int p_out_packets)290 Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
291 	ERR_FAIL_COND_V_MSG(_server->is_listening(), FAILED, "Buffers sizes can only be set before listening or connecting.");
292 
293 	_in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
294 	_in_pkt_size = nearest_shift(p_in_packets - 1);
295 	_out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
296 	_out_pkt_size = nearest_shift(p_out_packets - 1);
297 	return OK;
298 }
299 
WSLServer()300 WSLServer::WSLServer() {
301 	_in_buf_size = nearest_shift((int)GLOBAL_GET(WSS_IN_BUF) - 1) + 10;
302 	_in_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_IN_PKT) - 1);
303 	_out_buf_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_BUF) - 1) + 10;
304 	_out_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_PKT) - 1);
305 	_server.instance();
306 }
307 
~WSLServer()308 WSLServer::~WSLServer() {
309 	stop();
310 }
311 
312 #endif // JAVASCRIPT_ENABLED
313