@@ -565,10 +565,6 @@ async def matlab_view(req):
565565 Returns:
566566 WebSocketResponse or HTTPResponse: based on the Request type.
567567 """
568- # Special keys for web socket requests
569- CONNECTION = "connection"
570- UPGRADE = "upgrade"
571-
572568 reqH = req .headers .copy ()
573569
574570 state = req .app ["state" ]
@@ -589,14 +585,7 @@ async def matlab_view(req):
589585 raise web .HTTPServiceUnavailable ()
590586
591587 # WebSocket
592- # According to according to RFC6455 (https://www.rfc-editor.org/rfc/rfc6455.html)
593- # the values of 'connection' and 'upgrade' keys of request header
594- # should be ASCII case-insensitive matches.
595- if (
596- reqH .get (CONNECTION , "" ).lower () == UPGRADE
597- and reqH .get (UPGRADE , "" ).lower () == "websocket"
598- and req .method == "GET"
599- ):
588+ if _is_websocket_upgrade_request (req .method , reqH ):
600589 ws_server = web .WebSocketResponse (
601590 max_msg_size = constants .MAX_WEBSOCKET_MESSAGE_SIZE_IN_MB , compress = True
602591 )
@@ -756,6 +745,30 @@ async def wsforward(ws_from, ws_to):
756745 raise web .HTTPNotFound ()
757746
758747
748+ def _is_websocket_upgrade_request (request_method , request_headers ):
749+ """Check if the request is a WebSocket upgrade request.
750+
751+ Args:
752+ method (str): The HTTP method
753+ headers (dict): The request headers
754+
755+ Returns:
756+ bool: True if the request is a WebSocket upgrade request, False otherwise
757+ """
758+ # According to RFC6455 (https://www.rfc-editor.org/rfc/rfc6455.html)
759+ # the values of 'connection' and 'upgrade' keys of request header
760+ # should be ASCII case-insensitive matches.
761+ #
762+ # Different browsers may send different values for connection header, so we check if literal 'upgrade'
763+ # is present in the header value. E.g. Firefox sets connection header to "keep-alive, Upgrade"
764+ # while Chrome sets it to "Upgrade".
765+ return (
766+ "upgrade" in request_headers .get ("connection" , "" ).lower ()
767+ and request_headers .get ("upgrade" , "" ).lower () == "websocket"
768+ and request_method == "GET"
769+ )
770+
771+
759772async def transform_request_url (req , matlab_base_url ):
760773 """
761774 Performs any transformations that may be required on the URL.
0 commit comments