summaryrefslogtreecommitdiff
path: root/modules/websocket/wsl_server.cpp
blob: e3101d99d719d3bd85aa46f58330ee1ba15b094e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/*************************************************************************/
/*  wsl_server.cpp                                                       */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef JAVASCRIPT_ENABLED

#include "wsl_server.h"
#include "core/os/os.h"
#include "core/project_settings.h"

WSLServer::PendingPeer::PendingPeer() {
	use_ssl = false;
	time = 0;
	has_request = false;
	response_sent = 0;
	req_pos = 0;
	memset(req_buf, 0, sizeof(req_buf));
}

bool WSLServer::PendingPeer::_parse_request(const PoolStringArray p_protocols) {
	Vector<String> psa = String((char *)req_buf).split("\r\n");
	int len = psa.size();
	ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");

	Vector<String> req = psa[0].split(" ", false);
	ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code.");

	// Wrong protocol
	ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version.");

	Map<String, String> headers;
	for (int i = 1; i < len; i++) {
		Vector<String> header = psa[i].split(":", false, 1);
		ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]);
		String name = header[0].to_lower();
		String value = header[1].strip_edges();
		if (headers.has(name))
			headers[name] += "," + value;
		else
			headers[name] = value;
	}
#define _WSL_CHECK(NAME, VALUE)                                                         \
	ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
			"Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
#define _WSL_CHECK_EX(NAME) \
	ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'.");
	_WSL_CHECK("upgrade", "websocket");
	_WSL_CHECK("sec-websocket-version", "13");
	_WSL_CHECK_EX("sec-websocket-key");
	_WSL_CHECK_EX("connection");
#undef _WSL_CHECK_EX
#undef _WSL_CHECK
	key = headers["sec-websocket-key"];
	if (headers.has("sec-websocket-protocol")) {
		Vector<String> protos = headers["sec-websocket-protocol"].split(",");
		for (int i = 0; i < protos.size(); i++) {
			// Check if we have the given protocol
			for (int j = 0; j < p_protocols.size(); j++) {
				if (protos[i] != p_protocols[j])
					continue;
				protocol = protos[i];
				break;
			}
			// Found a protocol
			if (protocol != "")
				break;
		}
		if (protocol == "") // Invalid protocol(s) requested
			return false;
	} else if (p_protocols.size() > 0) // No protocol requested, but we need one
		return false;
	return true;
}

Error WSLServer::PendingPeer::do_handshake(PoolStringArray p_protocols) {
	if (OS::get_singleton()->get_ticks_msec() - time > WSL_SERVER_TIMEOUT)
		return ERR_TIMEOUT;
	if (use_ssl) {
		Ref<StreamPeerSSL> ssl = static_cast<Ref<StreamPeerSSL> >(connection);
		if (ssl.is_null())
			return FAILED;
		ssl->poll();
		if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING)
			return ERR_BUSY;
		else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED)
			return FAILED;
	}
	if (!has_request) {
		int read = 0;
		while (true) {
			ERR_FAIL_COND_V_MSG(req_pos >= WSL_MAX_HEADER_SIZE, ERR_OUT_OF_MEMORY, "Response headers too big.");
			Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
			if (err != OK) // Got an error
				return FAILED;
			else if (read != 1) // Busy, wait next poll
				return ERR_BUSY;
			char *r = (char *)req_buf;
			int l = req_pos;
			if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
				r[l - 3] = '\0';
				if (!_parse_request(p_protocols)) {
					return FAILED;
				}
				String s = "HTTP/1.1 101 Switching Protocols\r\n";
				s += "Upgrade: websocket\r\n";
				s += "Connection: Upgrade\r\n";
				s += "Sec-WebSocket-Accept: " + WSLPeer::compute_key_response(key) + "\r\n";
				if (protocol != "")
					s += "Sec-WebSocket-Protocol: " + protocol + "\r\n";
				s += "\r\n";
				response = s.utf8();
				has_request = true;
				break;
			}
			req_pos += 1;
		}
	}
	if (has_request && response_sent < response.size() - 1) {
		int sent = 0;
		Error err = connection->put_partial_data((const uint8_t *)response.get_data() + response_sent, response.size() - response_sent - 1, sent);
		if (err != OK) {
			return err;
		}
		response_sent += sent;
	}
	if (response_sent < response.size() - 1)
		return ERR_BUSY;
	return OK;
}

Error WSLServer::listen(int p_port, PoolVector<String> p_protocols, bool gd_mp_api) {
	ERR_FAIL_COND_V(is_listening(), ERR_ALREADY_IN_USE);

	_is_multiplayer = gd_mp_api;
	_protocols = p_protocols;
	_server->listen(p_port);

	return OK;
}

void WSLServer::poll() {

	List<int> remove_ids;
	for (Map<int, Ref<WebSocketPeer> >::Element *E = _peer_map.front(); E; E = E->next()) {
		Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
		peer->poll();
		if (!peer->is_connected_to_host()) {
			_on_disconnect(E->key(), peer->close_code != -1);
			remove_ids.push_back(E->key());
		}
	}
	for (List<int>::Element *E = remove_ids.front(); E; E = E->next()) {
		_peer_map.erase(E->get());
	}
	remove_ids.clear();

	List<Ref<PendingPeer> > remove_peers;
	for (List<Ref<PendingPeer> >::Element *E = _pending.front(); E; E = E->next()) {
		Ref<PendingPeer> ppeer = E->get();
		Error err = ppeer->do_handshake(_protocols);
		if (err == ERR_BUSY) {
			continue;
		} else if (err != OK) {
			remove_peers.push_back(ppeer);
			continue;
		}
		// Creating new peer
		int32_t id = _gen_unique_id();

		WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
		data->obj = this;
		data->conn = ppeer->connection;
		data->tcp = ppeer->tcp;
		data->is_server = true;
		data->id = id;

		Ref<WSLPeer> ws_peer = memnew(WSLPeer);
		ws_peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);

		_peer_map[id] = ws_peer;
		remove_peers.push_back(ppeer);
		_on_connect(id, ppeer->protocol);
	}
	for (List<Ref<PendingPeer> >::Element *E = remove_peers.front(); E; E = E->next()) {
		_pending.erase(E->get());
	}
	remove_peers.clear();

	if (!_server->is_listening())
		return;

	while (_server->is_connection_available()) {
		Ref<StreamPeerTCP> conn = _server->take_connection();
		if (is_refusing_new_connections())
			continue; // Conn will go out-of-scope and be closed.

		Ref<PendingPeer> peer = memnew(PendingPeer);
		if (private_key.is_valid() && ssl_cert.is_valid()) {
			Ref<StreamPeerSSL> ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
			ssl->set_blocking_handshake_enabled(false);
			ssl->accept_stream(conn, private_key, ssl_cert, ca_chain);
			peer->connection = ssl;
			peer->use_ssl = true;
		} else {
			peer->connection = conn;
		}
		peer->tcp = conn;
		peer->time = OS::get_singleton()->get_ticks_msec();
		_pending.push_back(peer);
	}
}

bool WSLServer::is_listening() const {
	return _server->is_listening();
}

int WSLServer::get_max_packet_size() const {
	return (1 << _out_buf_size) - PROTO_SIZE;
}

void WSLServer::stop() {
	_server->stop();
	for (Map<int, Ref<WebSocketPeer> >::Element *E = _peer_map.front(); E; E = E->next()) {
		Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
		peer->close_now();
	}
	_pending.clear();
	_peer_map.clear();
}

bool WSLServer::has_peer(int p_id) const {
	return _peer_map.has(p_id);
}

Ref<WebSocketPeer> WSLServer::get_peer(int p_id) const {
	ERR_FAIL_COND_V(!has_peer(p_id), NULL);
	return _peer_map[p_id];
}

IP_Address WSLServer::get_peer_address(int p_peer_id) const {
	ERR_FAIL_COND_V(!has_peer(p_peer_id), IP_Address());

	return _peer_map[p_peer_id]->get_connected_host();
}

int WSLServer::get_peer_port(int p_peer_id) const {
	ERR_FAIL_COND_V(!has_peer(p_peer_id), 0);

	return _peer_map[p_peer_id]->get_connected_port();
}

void WSLServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
	ERR_FAIL_COND(!has_peer(p_peer_id));

	get_peer(p_peer_id)->close(p_code, p_reason);
}

Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
	ERR_FAIL_COND_V_MSG(_server->is_listening(), FAILED, "Buffers sizes can only be set before listening or connecting.");

	_in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
	_in_pkt_size = nearest_shift(p_in_packets - 1);
	_out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
	_out_pkt_size = nearest_shift(p_out_packets - 1);
	return OK;
}

WSLServer::WSLServer() {
	_in_buf_size = nearest_shift((int)GLOBAL_GET(WSS_IN_BUF) - 1) + 10;
	_in_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_IN_PKT) - 1);
	_out_buf_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_BUF) - 1) + 10;
	_out_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_PKT) - 1);
	_server.instance();
}

WSLServer::~WSLServer() {
	stop();
}

#endif // JAVASCRIPT_ENABLED