better websocket header handling

This commit is contained in:
Jakob Ketterl 2019-10-02 11:28:41 +02:00
parent 774b71f8f0
commit 630a542ed6

View File

@ -42,17 +42,16 @@ class WebSocketConnection(object):
(self.interruptPipeRecv, self.interruptPipeSend) = Pipe(duplex=False) (self.interruptPipeRecv, self.interruptPipeSend) = Pipe(duplex=False)
self.open = True self.open = True
self.sendLock = threading.Lock() self.sendLock = threading.Lock()
my_headers = self.handler.headers.items()
my_header_keys = list(map(lambda x: x[0], my_headers)) headers = {key.lower(): value for key, value in self.handler.headers.items()}
h_key_exists = lambda x: my_header_keys.count(x) if not "upgrade" in headers:
h_value = lambda x: my_headers[my_header_keys.index(x)][1] raise WebSocketException("Upgrade header not found")
if ( if headers["upgrade"].lower() != "websocket":
(not h_key_exists("Upgrade")) raise WebSocketException("Upgrade header does not contain expected value")
or not (h_value("Upgrade") == "websocket") if not "sec-websocket-key" in headers:
or (not h_key_exists("Sec-WebSocket-Key")) raise WebSocketException("Websocket key not provided")
):
raise WebSocketException ws_key = headers["sec-websocket-key"]
ws_key = h_value("Sec-WebSocket-Key")
shakey = hashlib.sha1() shakey = hashlib.sha1()
shakey.update("{ws_key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11".format(ws_key=ws_key).encode()) shakey.update("{ws_key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11".format(ws_key=ws_key).encode())
ws_key_toreturn = base64.b64encode(shakey.digest()) ws_key_toreturn = base64.b64encode(shakey.digest())