| 1 | /**************************************************************************/ |
| 2 | /* wsl_peer.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 "wsl_peer.h" |
| 32 | |
| 33 | #ifndef WEB_ENABLED |
| 34 | |
| 35 | #include "core/io/stream_peer_tls.h" |
| 36 | |
| 37 | CryptoCore::RandomGenerator *WSLPeer::_static_rng = nullptr; |
| 38 | |
| 39 | void WSLPeer::initialize() { |
| 40 | WebSocketPeer::_create = WSLPeer::_create; |
| 41 | _static_rng = memnew(CryptoCore::RandomGenerator); |
| 42 | _static_rng->init(); |
| 43 | } |
| 44 | |
| 45 | void WSLPeer::deinitialize() { |
| 46 | if (_static_rng) { |
| 47 | memdelete(_static_rng); |
| 48 | _static_rng = nullptr; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | /// |
| 53 | /// Resolver |
| 54 | /// |
| 55 | void WSLPeer::Resolver::start(const String &p_host, int p_port) { |
| 56 | stop(); |
| 57 | |
| 58 | port = p_port; |
| 59 | if (p_host.is_valid_ip_address()) { |
| 60 | ip_candidates.push_back(IPAddress(p_host)); |
| 61 | } else { |
| 62 | // Queue hostname for resolution. |
| 63 | resolver_id = IP::get_singleton()->resolve_hostname_queue_item(p_host); |
| 64 | ERR_FAIL_COND(resolver_id == IP::RESOLVER_INVALID_ID); |
| 65 | // Check if it was found in cache. |
| 66 | IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(resolver_id); |
| 67 | if (ip_status == IP::RESOLVER_STATUS_DONE) { |
| 68 | ip_candidates = IP::get_singleton()->get_resolve_item_addresses(resolver_id); |
| 69 | IP::get_singleton()->erase_resolve_item(resolver_id); |
| 70 | resolver_id = IP::RESOLVER_INVALID_ID; |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | void WSLPeer::Resolver::stop() { |
| 76 | if (resolver_id != IP::RESOLVER_INVALID_ID) { |
| 77 | IP::get_singleton()->erase_resolve_item(resolver_id); |
| 78 | resolver_id = IP::RESOLVER_INVALID_ID; |
| 79 | } |
| 80 | port = 0; |
| 81 | } |
| 82 | |
| 83 | void WSLPeer::Resolver::try_next_candidate(const Ref<StreamPeerTCP> &p_tcp) { |
| 84 | // Check if we still need resolving. |
| 85 | if (resolver_id != IP::RESOLVER_INVALID_ID) { |
| 86 | IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(resolver_id); |
| 87 | if (ip_status == IP::RESOLVER_STATUS_WAITING) { |
| 88 | return; |
| 89 | } |
| 90 | if (ip_status == IP::RESOLVER_STATUS_DONE) { |
| 91 | ip_candidates = IP::get_singleton()->get_resolve_item_addresses(resolver_id); |
| 92 | } |
| 93 | IP::get_singleton()->erase_resolve_item(resolver_id); |
| 94 | resolver_id = IP::RESOLVER_INVALID_ID; |
| 95 | } |
| 96 | |
| 97 | // Try the current candidate if we have one. |
| 98 | if (p_tcp->get_status() != StreamPeerTCP::STATUS_NONE) { |
| 99 | p_tcp->poll(); |
| 100 | StreamPeerTCP::Status status = p_tcp->get_status(); |
| 101 | if (status == StreamPeerTCP::STATUS_CONNECTED) { |
| 102 | // On Windows, setting TCP_NODELAY may fail if the socket is still connecting. |
| 103 | p_tcp->set_no_delay(true); |
| 104 | ip_candidates.clear(); |
| 105 | return; |
| 106 | } else if (status == StreamPeerTCP::STATUS_CONNECTING) { |
| 107 | return; // Keep connecting. |
| 108 | } else { |
| 109 | p_tcp->disconnect_from_host(); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | // Keep trying next candidate. |
| 114 | while (ip_candidates.size()) { |
| 115 | Error err = p_tcp->connect_to_host(ip_candidates.pop_front(), port); |
| 116 | if (err == OK) { |
| 117 | return; |
| 118 | } else { |
| 119 | p_tcp->disconnect_from_host(); |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /// |
| 125 | /// Server functions |
| 126 | /// |
| 127 | Error WSLPeer::accept_stream(const Ref<StreamPeer> &p_stream) { |
| 128 | ERR_FAIL_COND_V(p_stream.is_null(), ERR_INVALID_PARAMETER); |
| 129 | ERR_FAIL_COND_V(ready_state != STATE_CLOSED && ready_state != STATE_CLOSING, ERR_ALREADY_IN_USE); |
| 130 | |
| 131 | _clear(); |
| 132 | |
| 133 | if (p_stream->is_class_ptr(StreamPeerTCP::get_class_ptr_static())) { |
| 134 | tcp = p_stream; |
| 135 | connection = p_stream; |
| 136 | use_tls = false; |
| 137 | } else if (p_stream->is_class_ptr(StreamPeerTLS::get_class_ptr_static())) { |
| 138 | Ref<StreamPeer> base_stream = static_cast<Ref<StreamPeerTLS>>(p_stream)->get_stream(); |
| 139 | ERR_FAIL_COND_V(base_stream.is_null() || !base_stream->is_class_ptr(StreamPeerTCP::get_class_ptr_static()), ERR_INVALID_PARAMETER); |
| 140 | tcp = static_cast<Ref<StreamPeerTCP>>(base_stream); |
| 141 | connection = p_stream; |
| 142 | use_tls = true; |
| 143 | } |
| 144 | ERR_FAIL_COND_V(connection.is_null() || tcp.is_null(), ERR_INVALID_PARAMETER); |
| 145 | is_server = true; |
| 146 | tcp->set_no_delay(true); |
| 147 | ready_state = STATE_CONNECTING; |
| 148 | handshake_buffer->resize(WSL_MAX_HEADER_SIZE); |
| 149 | handshake_buffer->seek(0); |
| 150 | return OK; |
| 151 | } |
| 152 | |
| 153 | bool WSLPeer::_parse_client_request() { |
| 154 | Vector<String> psa = String::ascii(Span((const char *)handshake_buffer->get_data_array().ptr(), handshake_buffer->get_position() - 4)).split("\r\n"); |
| 155 | int len = psa.size(); |
| 156 | ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4."); |
| 157 | |
| 158 | Vector<String> req = psa[0].split(" ", false); |
| 159 | ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code."); |
| 160 | |
| 161 | // Wrong protocol |
| 162 | ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version."); |
| 163 | |
| 164 | HashMap<String, String> headers; |
| 165 | for (int i = 1; i < len; i++) { |
| 166 | Vector<String> header = psa[i].split(":", false, 1); |
| 167 | ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]); |
| 168 | String name = header[0].to_lower(); |
| 169 | String value = header[1].strip_edges(); |
| 170 | if (headers.has(name)) { |
| 171 | headers[name] += "," + value; |
| 172 | } else { |
| 173 | headers[name] = value; |
| 174 | } |
| 175 | } |
| 176 | requested_host = headers.has("host") ? headers.get("host") : ""; |
| 177 | requested_url = (use_tls ? "wss://" : "ws://") + requested_host + req[1]; |
| 178 | #define WSL_CHECK(NAME, VALUE) \ |
| 179 | ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \ |
| 180 | "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); |
| 181 | #define WSL_CHECK_EX(NAME) \ |
| 182 | ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'."); |
| 183 | WSL_CHECK("upgrade", "websocket"); |
| 184 | WSL_CHECK("sec-websocket-version", "13"); |
| 185 | WSL_CHECK_EX("sec-websocket-key"); |
| 186 | WSL_CHECK_EX("connection"); |
| 187 | #undef WSL_CHECK_EX |
| 188 | #undef WSL_CHECK |
| 189 | session_key = headers["sec-websocket-key"]; |
| 190 | if (headers.has("sec-websocket-protocol")) { |
| 191 | Vector<String> protos = headers["sec-websocket-protocol"].split(","); |
| 192 | for (int i = 0; i < protos.size(); i++) { |
| 193 | String proto = protos[i].strip_edges(); |
| 194 | // Check if we have the given protocol |
| 195 | for (int j = 0; j < supported_protocols.size(); j++) { |
| 196 | if (proto != supported_protocols[j]) { |
| 197 | continue; |
| 198 | } |
| 199 | selected_protocol = proto; |
| 200 | break; |
| 201 | } |
| 202 | // Found a protocol |
| 203 | if (!selected_protocol.is_empty()) { |
| 204 | break; |
| 205 | } |
| 206 | } |
| 207 | if (selected_protocol.is_empty()) { // Invalid protocol(s) requested |
| 208 | return false; |
| 209 | } |
| 210 | } else if (supported_protocols.size() > 0) { // No protocol requested, but we need one |
| 211 | return false; |
| 212 | } |
| 213 | return true; |
| 214 | } |
| 215 | |
| 216 | Error WSLPeer::_do_server_handshake() { |
| 217 | if (use_tls) { |
| 218 | Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(connection); |
| 219 | if (tls.is_null()) { |
| 220 | ERR_FAIL_V_MSG(ERR_BUG, "Couldn't get StreamPeerTLS for WebSocket handshake."); |
| 221 | close(-1); |
| 222 | return FAILED; |
| 223 | } |
| 224 | tls->poll(); |
| 225 | if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { |
| 226 | return OK; // Pending handshake |
| 227 | } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) { |
| 228 | print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerTLS status code %d).", tls->get_status())); |
| 229 | close(-1); |
| 230 | return FAILED; |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | if (pending_request) { |
| 235 | int read = 0; |
| 236 | while (true) { |
| 237 | ERR_FAIL_COND_V_MSG(handshake_buffer->get_available_bytes() < 1, ERR_OUT_OF_MEMORY, "WebSocket response headers are too big."); |
| 238 | int pos = handshake_buffer->get_position(); |
| 239 | uint8_t byte; |
| 240 | Error err = connection->get_partial_data(&byte, 1, read); |
| 241 | if (err != OK) { // Got an error |
| 242 | print_verbose(vformat("WebSocket error while getting partial data (StreamPeer error code %d).", err)); |
| 243 | close(-1); |
| 244 | return FAILED; |
| 245 | } else if (read != 1) { // Busy, wait next poll |
| 246 | return OK; |
| 247 | } |
| 248 | handshake_buffer->put_u8(byte); |
| 249 | const char *r = (const char *)handshake_buffer->get_data_array().ptr(); |
| 250 | int l = pos; |
| 251 | if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') { |
| 252 | if (!_parse_client_request()) { |
| 253 | close(-1); |
| 254 | return FAILED; |
| 255 | } |
| 256 | String s = "HTTP/1.1 101 Switching Protocols\r\n"; |
| 257 | s += "Upgrade: websocket\r\n"; |
| 258 | s += "Connection: Upgrade\r\n"; |
| 259 | s += "Sec-WebSocket-Accept: " + _compute_key_response(session_key) + "\r\n"; |
| 260 | if (!selected_protocol.is_empty()) { |
| 261 | s += "Sec-WebSocket-Protocol: " + selected_protocol + "\r\n"; |
| 262 | } |
| 263 | for (int i = 0; i < handshake_headers.size(); i++) { |
| 264 | s += handshake_headers[i] + "\r\n"; |
| 265 | } |
| 266 | s += "\r\n"; |
| 267 | CharString cs = s.utf8(); |
| 268 | handshake_buffer->clear(); |
| 269 | handshake_buffer->put_data((const uint8_t *)cs.get_data(), cs.length()); |
| 270 | handshake_buffer->seek(0); |
| 271 | pending_request = false; |
| 272 | break; |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | if (pending_request) { // Still pending. |
| 278 | return OK; |
| 279 | } |
| 280 | |
| 281 | int left = handshake_buffer->get_available_bytes(); |
| 282 | if (left) { |
| 283 | Vector<uint8_t> data = handshake_buffer->get_data_array(); |
| 284 | int pos = handshake_buffer->get_position(); |
| 285 | int sent = 0; |
| 286 | Error err = connection->put_partial_data(data.ptr() + pos, left, sent); |
| 287 | if (err != OK) { |
| 288 | print_verbose(vformat("WebSocket error while putting partial data (StreamPeer error code %d).", err)); |
| 289 | close(-1); |
| 290 | return err; |
| 291 | } |
| 292 | handshake_buffer->seek(pos + sent); |
| 293 | left -= sent; |
| 294 | if (left == 0) { |
| 295 | resolver.stop(); |
| 296 | // Response sent, initialize wslay context. |
| 297 | wslay_event_context_server_init(&wsl_ctx, &_wsl_callbacks, this); |
| 298 | wslay_event_config_set_no_buffering(wsl_ctx, 1); |
| 299 | wslay_event_config_set_max_recv_msg_length(wsl_ctx, inbound_buffer_size); |
| 300 | in_buffer.resize(nearest_shift((uint32_t)inbound_buffer_size), max_queued_packets); |
| 301 | packet_buffer.resize(inbound_buffer_size); |
| 302 | ready_state = STATE_OPEN; |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | return OK; |
| 307 | } |
| 308 | |
| 309 | /// |
| 310 | /// Client functions |
| 311 | /// |
| 312 | void WSLPeer::_do_client_handshake() { |
| 313 | ERR_FAIL_COND(tcp.is_null()); |
| 314 | |
| 315 | // Try to connect to candidates. |
| 316 | if (resolver.has_more_candidates() || tcp->get_status() == StreamPeerTCP::STATUS_CONNECTING) { |
| 317 | resolver.try_next_candidate(tcp); |
| 318 | if (resolver.has_more_candidates()) { |
| 319 | return; // Still pending. |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | tcp->poll(); |
| 324 | if (tcp->get_status() == StreamPeerTCP::STATUS_CONNECTING) { |
| 325 | return; // Keep connecting. |
| 326 | } else if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) { |
| 327 | close(-1); // Failed to connect. |
| 328 | return; |
| 329 | } |
| 330 | |
| 331 | if (use_tls) { |
| 332 | Ref<StreamPeerTLS> tls; |
| 333 | if (connection == tcp) { |
| 334 | // Start SSL handshake |
| 335 | tls = Ref<StreamPeerTLS>(StreamPeerTLS::create()); |
| 336 | ERR_FAIL_COND(tls.is_null()); |
| 337 | if (tls->connect_to_stream(tcp, requested_host, tls_options) != OK) { |
| 338 | close(-1); |
| 339 | return; // Error. |
| 340 | } |
| 341 | connection = tls; |
| 342 | } else { |
| 343 | tls = static_cast<Ref<StreamPeerTLS>>(connection); |
| 344 | ERR_FAIL_COND(tls.is_null()); |
| 345 | tls->poll(); |
| 346 | } |
| 347 | if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { |
| 348 | return; // Need more polling. |
| 349 | } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) { |
| 350 | close(-1); |
| 351 | return; // Error. |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | // Do websocket handshake. |
| 356 | if (pending_request) { |
| 357 | int left = handshake_buffer->get_available_bytes(); |
| 358 | int pos = handshake_buffer->get_position(); |
| 359 | const Vector<uint8_t> data = handshake_buffer->get_data_array(); |
| 360 | int sent = 0; |
| 361 | Error err = connection->put_partial_data(data.ptr() + pos, left, sent); |
| 362 | // Sending handshake failed |
| 363 | if (err != OK) { |
| 364 | close(-1); |
| 365 | return; // Error. |
| 366 | } |
| 367 | handshake_buffer->seek(pos + sent); |
| 368 | if (handshake_buffer->get_available_bytes() == 0) { |
| 369 | pending_request = false; |
| 370 | handshake_buffer->clear(); |
| 371 | handshake_buffer->resize(WSL_MAX_HEADER_SIZE); |
| 372 | handshake_buffer->seek(0); |
| 373 | } |
| 374 | } else { |
| 375 | int read = 0; |
| 376 | while (true) { |
| 377 | int left = handshake_buffer->get_available_bytes(); |
| 378 | int pos = handshake_buffer->get_position(); |
| 379 | if (left == 0) { |
| 380 | // Header is too big |
| 381 | close(-1); |
| 382 | ERR_FAIL_MSG("Response headers too big."); |
| 383 | } |
| 384 | |
| 385 | uint8_t byte; |
| 386 | Error err = connection->get_partial_data(&byte, 1, read); |
| 387 | if (err != OK) { |
| 388 | // Got some error. |
| 389 | close(-1); |
| 390 | return; |
| 391 | } else if (read != 1) { |
| 392 | // Busy, wait next poll. |
| 393 | break; |
| 394 | } |
| 395 | handshake_buffer->put_u8(byte); |
| 396 | |
| 397 | // Check "\r\n\r\n" header terminator |
| 398 | const char *r = (const char *)handshake_buffer->get_data_array().ptr(); |
| 399 | int l = pos; |
| 400 | if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') { |
| 401 | // Response is over, verify headers and initialize wslay context/ |
| 402 | if (!_verify_server_response()) { |
| 403 | close(-1); |
| 404 | ERR_FAIL_MSG("Invalid response headers."); |
| 405 | } |
| 406 | wslay_event_context_client_init(&wsl_ctx, &_wsl_callbacks, this); |
| 407 | wslay_event_config_set_no_buffering(wsl_ctx, 1); |
| 408 | wslay_event_config_set_max_recv_msg_length(wsl_ctx, inbound_buffer_size); |
| 409 | in_buffer.resize(nearest_shift((uint32_t)inbound_buffer_size), max_queued_packets); |
| 410 | packet_buffer.resize(inbound_buffer_size); |
| 411 | ready_state = STATE_OPEN; |
| 412 | break; |
| 413 | } |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | bool WSLPeer::_verify_server_response() { |
| 419 | Vector<String> psa = String::ascii(Span((const char *)handshake_buffer->get_data_array().ptr(), handshake_buffer->get_position() - 4)).split("\r\n"); |
| 420 | int len = psa.size(); |
| 421 | ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers. Got: " + itos(len) + ", expected >= 4."); |
| 422 | |
| 423 | Vector<String> req = psa[0].split(" ", false); |
| 424 | ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code. Got '" + psa[0] + "', expected 'HTTP/1.1 101'."); |
| 425 | |
| 426 | // Wrong protocol |
| 427 | ERR_FAIL_COND_V_MSG(req[0] != "HTTP/1.1", false, "Invalid protocol. Got: '" + req[0] + "', expected 'HTTP/1.1'."); |
| 428 | ERR_FAIL_COND_V_MSG(req[1] != "101", false, "Invalid status code. Got: '" + req[1] + "', expected '101'."); |
| 429 | |
| 430 | HashMap<String, String> headers; |
| 431 | for (int i = 1; i < len; i++) { |
| 432 | Vector<String> header = psa[i].split(":", false, 1); |
| 433 | ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i] + "."); |
| 434 | String name = header[0].to_lower(); |
| 435 | String value = header[1].strip_edges(); |
| 436 | if (headers.has(name)) { |
| 437 | headers[name] += "," + value; |
| 438 | } else { |
| 439 | headers[name] = value; |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | #define WSL_CHECK(NAME, VALUE) \ |
| 444 | ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \ |
| 445 | "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); |
| 446 | #define WSL_CHECK_NC(NAME, VALUE) \ |
| 447 | ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME] != VALUE, false, \ |
| 448 | "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); |
| 449 | WSL_CHECK("connection", "upgrade"); |
| 450 | WSL_CHECK("upgrade", "websocket"); |
| 451 | WSL_CHECK_NC("sec-websocket-accept", _compute_key_response(session_key)); |
| 452 | #undef WSL_CHECK_NC |
| 453 | #undef WSL_CHECK |
| 454 | if (supported_protocols.is_empty()) { |
| 455 | // We didn't request a custom protocol |
| 456 | ERR_FAIL_COND_V_MSG(headers.has("sec-websocket-protocol"), false, "Received unrequested sub-protocol -> " + headers["sec-websocket-protocol"]); |
| 457 | } else { |
| 458 | // We requested at least one custom protocol but didn't receive one |
| 459 | ERR_FAIL_COND_V_MSG(!headers.has("sec-websocket-protocol"), false, "Requested sub-protocol(s) but received none."); |
| 460 | // Check received sub-protocol was one of those requested. |
| 461 | selected_protocol = headers["sec-websocket-protocol"]; |
| 462 | bool valid = false; |
| 463 | for (int i = 0; i < supported_protocols.size(); i++) { |
| 464 | if (supported_protocols[i] != selected_protocol) { |
| 465 | continue; |
| 466 | } |
| 467 | valid = true; |
| 468 | break; |
| 469 | } |
| 470 | if (!valid) { |
| 471 | ERR_FAIL_V_MSG(false, "Received unrequested sub-protocol -> " + selected_protocol); |
| 472 | } |
| 473 | } |
| 474 | return true; |
| 475 | } |
| 476 | |
| 477 | Error WSLPeer::connect_to_url(const String &p_url, const Ref<TLSOptions> &p_options) { |
| 478 | ERR_FAIL_COND_V(p_url.is_empty(), ERR_INVALID_PARAMETER); |
| 479 | ERR_FAIL_COND_V(p_options.is_valid() && p_options->is_server(), ERR_INVALID_PARAMETER); |
| 480 | ERR_FAIL_COND_V(ready_state != STATE_CLOSED && ready_state != STATE_CLOSING, ERR_ALREADY_IN_USE); |
| 481 | |
| 482 | _clear(); |
| 483 | |
| 484 | String host; |
| 485 | String path; |
| 486 | String scheme; |
| 487 | String fragment; |
| 488 | int port = 0; |
| 489 | Error err = p_url.parse_url(scheme, host, port, path, fragment); |
| 490 | ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url); |
| 491 | if (scheme.is_empty()) { |
| 492 | scheme = "ws://"; |
| 493 | } |
| 494 | ERR_FAIL_COND_V_MSG(scheme != "ws://" && scheme != "wss://", ERR_INVALID_PARAMETER, vformat("Invalid protocol: \"%s\" (must be either \"ws://\" or \"wss://\").", scheme)); |
| 495 | |
| 496 | use_tls = false; |
| 497 | if (scheme == "wss://") { |
| 498 | use_tls = true; |
| 499 | } |
| 500 | if (port == 0) { |
| 501 | port = use_tls ? 443 : 80; |
| 502 | } |
| 503 | if (path.is_empty()) { |
| 504 | path = "/"; |
| 505 | } |
| 506 | |
| 507 | ERR_FAIL_COND_V_MSG(use_tls && !StreamPeerTLS::is_available(), ERR_UNAVAILABLE, "WSS is not available in this build."); |
| 508 | |
| 509 | requested_url = p_url; |
| 510 | requested_host = host; |
| 511 | |
| 512 | if (p_options.is_valid()) { |
| 513 | tls_options = p_options; |
| 514 | } else { |
| 515 | tls_options = TLSOptions::client(); |
| 516 | } |
| 517 | |
| 518 | tcp.instantiate(); |
| 519 | |
| 520 | resolver.start(host, port); |
| 521 | resolver.try_next_candidate(tcp); |
| 522 | |
| 523 | if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTING && tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED && !resolver.has_more_candidates()) { |
| 524 | _clear(); |
| 525 | return FAILED; |
| 526 | } |
| 527 | connection = tcp; |
| 528 | |
| 529 | // Prepare handshake request. |
| 530 | session_key = _generate_key(); |
| 531 | String request = "GET " + path + " HTTP/1.1\r\n"; |
| 532 | String port_string; |
| 533 | if ((port != 80 && !use_tls) || (port != 443 && use_tls)) { |
| 534 | port_string = ":" + itos(port); |
| 535 | } |
| 536 | request += "Host: " + host + port_string + "\r\n"; |
| 537 | request += "Upgrade: websocket\r\n"; |
| 538 | request += "Connection: Upgrade\r\n"; |
| 539 | request += "Sec-WebSocket-Key: " + session_key + "\r\n"; |
| 540 | request += "Sec-WebSocket-Version: 13\r\n"; |
| 541 | if (supported_protocols.size() > 0) { |
| 542 | request += "Sec-WebSocket-Protocol: "; |
| 543 | for (int i = 0; i < supported_protocols.size(); i++) { |
| 544 | if (i != 0) { |
| 545 | request += ","; |
| 546 | } |
| 547 | request += supported_protocols[i]; |
| 548 | } |
| 549 | request += "\r\n"; |
| 550 | } |
| 551 | for (int i = 0; i < handshake_headers.size(); i++) { |
| 552 | request += handshake_headers[i] + "\r\n"; |
| 553 | } |
| 554 | request += "\r\n"; |
| 555 | CharString cs = request.utf8(); |
| 556 | handshake_buffer->put_data((const uint8_t *)cs.get_data(), cs.length()); |
| 557 | handshake_buffer->seek(0); |
| 558 | ready_state = STATE_CONNECTING; |
| 559 | is_server = false; |
| 560 | return OK; |
| 561 | } |
| 562 | |
| 563 | /// |
| 564 | /// Callback functions. |
| 565 | /// |
| 566 | ssize_t WSLPeer::_wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data) { |
| 567 | WSLPeer *peer = (WSLPeer *)user_data; |
| 568 | Ref<StreamPeer> conn = peer->connection; |
| 569 | if (conn.is_null()) { |
| 570 | wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE); |
| 571 | return -1; |
| 572 | } |
| 573 | // Make sure we don't read more than what our buffer can hold. |
| 574 | size_t buffer_limit = MIN(peer->in_buffer.payload_space_left(), peer->in_buffer.packets_space_left() * 2); // The minimum size of a websocket message is 2 bytes. |
| 575 | size_t to_read = MIN(len, buffer_limit); |
| 576 | if (to_read == 0) { |
| 577 | wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK); |
| 578 | return -1; |
| 579 | } |
| 580 | int read = 0; |
| 581 | Error err = conn->get_partial_data(data, to_read, read); |
| 582 | if (err != OK) { |
| 583 | print_verbose("Websocket get data error: " + itos(err) + ", read (should be 0!): " + itos(read)); |
| 584 | wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE); |
| 585 | return -1; |
| 586 | } |
| 587 | if (read == 0) { |
| 588 | wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK); |
| 589 | return -1; |
| 590 | } |
| 591 | return read; |
| 592 | } |
| 593 | |
| 594 | void WSLPeer::_wsl_recv_start_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_frame_recv_start_arg *arg, void *user_data) { |
| 595 | WSLPeer *peer = (WSLPeer *)user_data; |
| 596 | uint8_t op = arg->opcode; |
| 597 | if (op == WSLAY_TEXT_FRAME || op == WSLAY_BINARY_FRAME) { |
| 598 | // Get ready to process a data package. |
| 599 | PendingMessage &pm = peer->pending_message; |
| 600 | pm.opcode = op; |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | void WSLPeer::_wsl_frame_recv_chunk_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_frame_recv_chunk_arg *arg, void *user_data) { |
| 605 | WSLPeer *peer = (WSLPeer *)user_data; |
| 606 | PendingMessage &pm = peer->pending_message; |
| 607 | if (pm.opcode != 0) { |
| 608 | // Only write the payload. |
| 609 | peer->in_buffer.write_packet(arg->data, arg->data_length, nullptr); |
| 610 | pm.payload_size += arg->data_length; |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | ssize_t WSLPeer::_wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) { |
| 615 | WSLPeer *peer = (WSLPeer *)user_data; |
| 616 | Ref<StreamPeer> conn = peer->connection; |
| 617 | if (conn.is_null()) { |
| 618 | wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE); |
| 619 | return -1; |
| 620 | } |
| 621 | int sent = 0; |
| 622 | Error err = conn->put_partial_data(data, len, sent); |
| 623 | if (err != OK) { |
| 624 | wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE); |
| 625 | return -1; |
| 626 | } |
| 627 | if (sent == 0) { |
| 628 | wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK); |
| 629 | return -1; |
| 630 | } |
| 631 | return sent; |
| 632 | } |
| 633 | |
| 634 | int WSLPeer::_wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) { |
| 635 | ERR_FAIL_NULL_V(_static_rng, WSLAY_ERR_CALLBACK_FAILURE); |
| 636 | Error err = _static_rng->get_random_bytes(buf, len); |
| 637 | ERR_FAIL_COND_V(err != OK, WSLAY_ERR_CALLBACK_FAILURE); |
| 638 | return 0; |
| 639 | } |
| 640 | |
| 641 | void WSLPeer::_wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) { |
| 642 | WSLPeer *peer = (WSLPeer *)user_data; |
| 643 | uint8_t op = arg->opcode; |
| 644 | |
| 645 | if (op == WSLAY_CONNECTION_CLOSE) { |
| 646 | // Close request or confirmation. |
| 647 | peer->close_code = arg->status_code; |
| 648 | size_t len = arg->msg_length; |
| 649 | peer->close_reason.clear(); |
| 650 | if (len > 2 /* first 2 bytes = close code */) { |
| 651 | peer->close_reason.append_utf8((char *)arg->msg + 2, len - 2); |
| 652 | } |
| 653 | if (peer->ready_state == STATE_OPEN) { |
| 654 | peer->ready_state = STATE_CLOSING; |
| 655 | } |
| 656 | return; |
| 657 | } |
| 658 | |
| 659 | if (op == WSLAY_PONG) { |
| 660 | peer->heartbeat_waiting = false; |
| 661 | } else if (op == WSLAY_TEXT_FRAME || op == WSLAY_BINARY_FRAME) { |
| 662 | PendingMessage &pm = peer->pending_message; |
| 663 | ERR_FAIL_COND(pm.opcode != op); |
| 664 | // Only write the packet (since it's now completed). |
| 665 | uint8_t is_string = pm.opcode == WSLAY_TEXT_FRAME ? 1 : 0; |
| 666 | peer->in_buffer.write_packet(nullptr, pm.payload_size, &is_string); |
| 667 | pm.clear(); |
| 668 | } |
| 669 | // Ping. |
| 670 | } |
| 671 | |
| 672 | wslay_event_callbacks WSLPeer::_wsl_callbacks = { |
| 673 | _wsl_recv_callback, |
| 674 | _wsl_send_callback, |
| 675 | _wsl_genmask_callback, |
| 676 | _wsl_recv_start_callback, |
| 677 | _wsl_frame_recv_chunk_callback, |
| 678 | nullptr, |
| 679 | _wsl_msg_recv_callback |
| 680 | }; |
| 681 | |
| 682 | String WSLPeer::_generate_key() { |
| 683 | // Random key |
| 684 | Vector<uint8_t> bkey; |
| 685 | int len = 16; // 16 bytes, as per RFC |
| 686 | bkey.resize(len); |
| 687 | _wsl_genmask_callback(nullptr, bkey.ptrw(), len, nullptr); |
| 688 | return CryptoCore::b64_encode_str(bkey.ptrw(), len); |
| 689 | } |
| 690 | |
| 691 | String WSLPeer::_compute_key_response(const String &p_key) { |
| 692 | String key = p_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Magic UUID as per RFC |
| 693 | Vector<uint8_t> sha = key.sha1_buffer(); |
| 694 | return CryptoCore::b64_encode_str(sha.ptr(), sha.size()); |
| 695 | } |
| 696 | |
| 697 | void WSLPeer::poll() { |
| 698 | // Nothing to do. |
| 699 | if (ready_state == STATE_CLOSED) { |
| 700 | return; |
| 701 | } |
| 702 | |
| 703 | if (ready_state == STATE_CONNECTING) { |
| 704 | if (is_server) { |
| 705 | _do_server_handshake(); |
| 706 | } else { |
| 707 | _do_client_handshake(); |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | if (ready_state == STATE_OPEN || ready_state == STATE_CLOSING) { |
| 712 | ERR_FAIL_NULL(wsl_ctx); |
| 713 | uint64_t ticks = OS::get_singleton()->get_ticks_msec(); |
| 714 | int err = 0; |
| 715 | if (heartbeat_interval_msec != 0 && ticks - last_heartbeat > heartbeat_interval_msec && ready_state == STATE_OPEN) { |
| 716 | if (heartbeat_waiting) { |
| 717 | wslay_event_context_free(wsl_ctx); |
| 718 | wsl_ctx = nullptr; |
| 719 | close(-1); |
| 720 | return; |
| 721 | } |
| 722 | heartbeat_waiting = true; |
| 723 | struct wslay_event_msg msg; |
| 724 | msg.opcode = WSLAY_PING; |
| 725 | msg.msg = nullptr; |
| 726 | msg.msg_length = 0; |
| 727 | err = wslay_event_queue_msg(wsl_ctx, &msg); |
| 728 | if (err == 0) { |
| 729 | last_heartbeat = ticks; |
| 730 | } else { |
| 731 | print_verbose("Websocket (wslay) failed to send ping: " + itos(err)); |
| 732 | wslay_event_context_free(wsl_ctx); |
| 733 | wsl_ctx = nullptr; |
| 734 | close(-1); |
| 735 | return; |
| 736 | } |
| 737 | } |
| 738 | if ((err = wslay_event_recv(wsl_ctx)) != 0 || (err = wslay_event_send(wsl_ctx)) != 0) { |
| 739 | // Error close. |
| 740 | print_verbose("Websocket (wslay) poll error: " + itos(err)); |
| 741 | wslay_event_context_free(wsl_ctx); |
| 742 | wsl_ctx = nullptr; |
| 743 | close(-1); |
| 744 | return; |
| 745 | } |
| 746 | if (wslay_event_get_close_sent(wsl_ctx)) { |
| 747 | if (wslay_event_get_close_received(wsl_ctx)) { |
| 748 | // Clean close. |
| 749 | wslay_event_context_free(wsl_ctx); |
| 750 | wsl_ctx = nullptr; |
| 751 | close(-1); |
| 752 | return; |
| 753 | } else if (!wslay_event_get_read_enabled(wsl_ctx)) { |
| 754 | // Some protocol error caused wslay to stop processing incoming events, we'll never receive a close from the other peer. |
| 755 | close_code = wslay_event_get_status_code_sent(wsl_ctx); |
| 756 | switch (close_code) { |
| 757 | case WSLAY_CODE_MESSAGE_TOO_BIG: |
| 758 | close_reason = "Message too big"; |
| 759 | break; |
| 760 | case WSLAY_CODE_PROTOCOL_ERROR: |
| 761 | close_reason = "Protocol error"; |
| 762 | break; |
| 763 | case WSLAY_CODE_ABNORMAL_CLOSURE: |
| 764 | close_reason = "Abnormal closure"; |
| 765 | break; |
| 766 | case WSLAY_CODE_INVALID_FRAME_PAYLOAD_DATA: |
| 767 | close_reason = "Invalid frame payload data"; |
| 768 | break; |
| 769 | default: |
| 770 | close_reason = "Unknown"; |
| 771 | } |
| 772 | wslay_event_context_free(wsl_ctx); |
| 773 | wsl_ctx = nullptr; |
| 774 | close(-1); |
| 775 | return; |
| 776 | } |
| 777 | } |
| 778 | } |
| 779 | } |
| 780 | |
| 781 | Error WSLPeer::_send(const uint8_t *p_buffer, int p_buffer_size, wslay_opcode p_opcode) { |
| 782 | ERR_FAIL_COND_V(ready_state != STATE_OPEN, FAILED); |
| 783 | ERR_FAIL_COND_V(wslay_event_get_queued_msg_count(wsl_ctx) >= (uint32_t)max_queued_packets, ERR_OUT_OF_MEMORY); |
| 784 | ERR_FAIL_COND_V(outbound_buffer_size > 0 && (wslay_event_get_queued_msg_length(wsl_ctx) + p_buffer_size > (uint32_t)outbound_buffer_size), ERR_OUT_OF_MEMORY); |
| 785 | |
| 786 | struct wslay_event_msg msg; |
| 787 | msg.opcode = p_opcode; |
| 788 | msg.msg = p_buffer; |
| 789 | msg.msg_length = p_buffer_size; |
| 790 | |
| 791 | // Queue & send message. |
| 792 | if (wslay_event_queue_msg(wsl_ctx, &msg) != 0 || wslay_event_send(wsl_ctx) != 0) { |
| 793 | close(-1); |
| 794 | return FAILED; |
| 795 | } |
| 796 | return OK; |
| 797 | } |
| 798 | |
| 799 | Error WSLPeer::send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) { |
| 800 | wslay_opcode opcode = p_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME; |
| 801 | return _send(p_buffer, p_buffer_size, opcode); |
| 802 | } |
| 803 | |
| 804 | Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { |
| 805 | return _send(p_buffer, p_buffer_size, WSLAY_BINARY_FRAME); |
| 806 | } |
| 807 | |
| 808 | Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { |
| 809 | r_buffer_size = 0; |
| 810 | |
| 811 | ERR_FAIL_COND_V(ready_state != STATE_OPEN, FAILED); |
| 812 | |
| 813 | if (in_buffer.packets_left() == 0) { |
| 814 | return ERR_UNAVAILABLE; |
| 815 | } |
| 816 | |
| 817 | int read = 0; |
| 818 | uint8_t *rw = packet_buffer.ptrw(); |
| 819 | in_buffer.read_packet(rw, packet_buffer.size(), &was_string, read); |
| 820 | |
| 821 | *r_buffer = rw; |
| 822 | r_buffer_size = read; |
| 823 | |
| 824 | return OK; |
| 825 | } |
| 826 | |
| 827 | int WSLPeer::get_available_packet_count() const { |
| 828 | if (ready_state != STATE_OPEN) { |
| 829 | return 0; |
| 830 | } |
| 831 | |
| 832 | return in_buffer.packets_left(); |
| 833 | } |
| 834 | |
| 835 | int WSLPeer::get_current_outbound_buffered_amount() const { |
| 836 | if (ready_state != STATE_OPEN) { |
| 837 | return 0; |
| 838 | } |
| 839 | |
| 840 | return wslay_event_get_queued_msg_length(wsl_ctx); |
| 841 | } |
| 842 | |
| 843 | void WSLPeer::close(int p_code, const String &p_reason) { |
| 844 | if (p_code < 0) { |
| 845 | // Force immediate close. |
| 846 | ready_state = STATE_CLOSED; |
| 847 | } |
| 848 | |
| 849 | if (ready_state == STATE_OPEN && !wslay_event_get_close_sent(wsl_ctx)) { |
| 850 | CharString cs = p_reason.utf8(); |
| 851 | wslay_event_queue_close(wsl_ctx, p_code, (uint8_t *)cs.ptr(), cs.length()); |
| 852 | wslay_event_send(wsl_ctx); |
| 853 | ready_state = STATE_CLOSING; |
| 854 | } else if (ready_state == STATE_CONNECTING || ready_state == STATE_CLOSED) { |
| 855 | ready_state = STATE_CLOSED; |
| 856 | connection.unref(); |
| 857 | if (tcp.is_valid()) { |
| 858 | tcp->disconnect_from_host(); |
| 859 | tcp.unref(); |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | if (ready_state == STATE_CLOSED) { |
| 864 | heartbeat_waiting = false; |
| 865 | in_buffer.clear(); |
| 866 | packet_buffer.resize(0); |
| 867 | pending_message.clear(); |
| 868 | } |
| 869 | } |
| 870 | |
| 871 | IPAddress WSLPeer::get_connected_host() const { |
| 872 | ERR_FAIL_COND_V(tcp.is_null(), IPAddress()); |
| 873 | return tcp->get_connected_host(); |
| 874 | } |
| 875 | |
| 876 | uint16_t WSLPeer::get_connected_port() const { |
| 877 | ERR_FAIL_COND_V(tcp.is_null(), 0); |
| 878 | return tcp->get_connected_port(); |
| 879 | } |
| 880 | |
| 881 | String WSLPeer::get_selected_protocol() const { |
| 882 | return selected_protocol; |
| 883 | } |
| 884 | |
| 885 | String WSLPeer::get_requested_url() const { |
| 886 | return requested_url; |
| 887 | } |
| 888 | |
| 889 | void WSLPeer::set_no_delay(bool p_enabled) { |
| 890 | ERR_FAIL_COND(tcp.is_null()); |
| 891 | tcp->set_no_delay(p_enabled); |
| 892 | } |
| 893 | |
| 894 | void WSLPeer::_clear() { |
| 895 | // Connection info. |
| 896 | ready_state = STATE_CLOSED; |
| 897 | is_server = false; |
| 898 | connection.unref(); |
| 899 | if (tcp.is_valid()) { |
| 900 | tcp->disconnect_from_host(); |
| 901 | tcp.unref(); |
| 902 | } |
| 903 | if (wsl_ctx) { |
| 904 | wslay_event_context_free(wsl_ctx); |
| 905 | wsl_ctx = nullptr; |
| 906 | } |
| 907 | |
| 908 | resolver.stop(); |
| 909 | requested_url.clear(); |
| 910 | requested_host.clear(); |
| 911 | pending_request = true; |
| 912 | handshake_buffer->clear(); |
| 913 | selected_protocol.clear(); |
| 914 | session_key.clear(); |
| 915 | |
| 916 | // Pending packets info. |
| 917 | was_string = 0; |
| 918 | in_buffer.clear(); |
| 919 | packet_buffer.clear(); |
| 920 | |
| 921 | // Close code info. |
| 922 | close_code = -1; |
| 923 | close_reason.clear(); |
| 924 | } |
| 925 | |
| 926 | WSLPeer::WSLPeer() { |
| 927 | handshake_buffer.instantiate(); |
| 928 | } |
| 929 | |
| 930 | WSLPeer::~WSLPeer() { |
| 931 | close(-1); |
| 932 | } |
| 933 | |
| 934 | #endif // WEB_ENABLED |