From 78630b0e02625f036c029072fceec16b5c5c2b7c Mon Sep 17 00:00:00 2001
From: Mau Abata <mauabata@gmail.com>
Date: Sun, 13 Dec 2020 17:55:59 -0600
Subject: [PATCH] Prevent crash on WebSocket request to non-WebSocket node.

---
 src/HTTPConnection.cpp | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)

diff --git a/src/HTTPConnection.cpp b/src/HTTPConnection.cpp
index 0ab739c..f2eb69b 100644
--- a/src/HTTPConnection.cpp
+++ b/src/HTTPConnection.cpp
@@ -519,9 +519,17 @@ void HTTPConnection::loop() {
 
           // Finally, after the handshake is done, we create the WebsocketHandler and change the internal state.
           if(websocketRequested) {
-            _wsHandler = ((WebsocketNode*)resolvedResource.getMatchingNode())->newHandler();
-            _wsHandler->initialize(this);  // make websocket with this connection 
-            _connectionState = STATE_WEBSOCKET;
+            HTTPNode *node = resolvedResource.getMatchingNode();
+
+            // Check for websocket request on non-websocket node:
+            if (node == nullptr || node->_nodeType != HTTPNodeType::WEBSOCKET) {
+              HTTPS_LOGW("Websocket request on non-websocket node rejected");
+              raiseError(404, "Not Found");
+            } else {
+              _wsHandler = ((WebsocketNode *) node)->newHandler();
+              _wsHandler->initialize(this);  // make websocket with this connection
+              _connectionState = STATE_WEBSOCKET;
+            }
           } else {
             // Handling the request is done
             HTTPS_LOGD("Handler function done, request complete");