2016-04-22 16:18:06 +01:00
|
|
|
import sys
|
2020-02-27 04:36:53 +00:00
|
|
|
|
2016-04-22 16:18:06 +01:00
|
|
|
try:
|
|
|
|
import ubinascii as binascii
|
|
|
|
except:
|
|
|
|
import binascii
|
|
|
|
try:
|
|
|
|
import uhashlib as hashlib
|
|
|
|
except:
|
|
|
|
import hashlib
|
|
|
|
|
2016-04-22 16:19:54 +01:00
|
|
|
DEBUG = 0
|
2016-04-22 16:18:06 +01:00
|
|
|
|
2020-02-27 04:36:53 +00:00
|
|
|
|
2016-04-22 16:18:06 +01:00
|
|
|
def server_handshake(sock):
|
|
|
|
clr = sock.makefile("rwb", 0)
|
|
|
|
l = clr.readline()
|
2020-02-27 04:36:53 +00:00
|
|
|
# sys.stdout.write(repr(l))
|
2016-04-22 16:18:06 +01:00
|
|
|
|
|
|
|
webkey = None
|
|
|
|
|
|
|
|
while 1:
|
|
|
|
l = clr.readline()
|
|
|
|
if not l:
|
|
|
|
raise OSError("EOF in headers")
|
|
|
|
if l == b"\r\n":
|
|
|
|
break
|
2020-02-27 04:36:53 +00:00
|
|
|
# sys.stdout.write(l)
|
2016-04-22 16:18:06 +01:00
|
|
|
h, v = [x.strip() for x in l.split(b":", 1)]
|
2016-04-22 16:19:54 +01:00
|
|
|
if DEBUG:
|
|
|
|
print((h, v))
|
2020-02-27 04:36:53 +00:00
|
|
|
if h == b"Sec-WebSocket-Key":
|
2016-04-22 16:18:06 +01:00
|
|
|
webkey = v
|
|
|
|
|
|
|
|
if not webkey:
|
|
|
|
raise OSError("Not a websocket request")
|
|
|
|
|
2016-04-22 16:19:54 +01:00
|
|
|
if DEBUG:
|
|
|
|
print("Sec-WebSocket-Key:", webkey, len(webkey))
|
2016-04-22 16:18:06 +01:00
|
|
|
|
2016-06-29 22:02:45 +01:00
|
|
|
d = hashlib.sha1(webkey)
|
|
|
|
d.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
|
|
|
|
respkey = d.digest()
|
2016-04-22 16:18:06 +01:00
|
|
|
respkey = binascii.b2a_base64(respkey)[:-1]
|
2016-06-29 22:02:45 +01:00
|
|
|
if DEBUG:
|
2016-06-30 11:34:58 +01:00
|
|
|
print("respkey:", respkey)
|
2016-04-22 16:18:06 +01:00
|
|
|
|
2020-02-27 04:36:53 +00:00
|
|
|
sock.send(
|
|
|
|
b"""\
|
2016-04-22 16:18:06 +01:00
|
|
|
HTTP/1.1 101 Switching Protocols\r
|
|
|
|
Upgrade: websocket\r
|
|
|
|
Connection: Upgrade\r
|
2020-02-27 04:36:53 +00:00
|
|
|
Sec-WebSocket-Accept: """
|
|
|
|
)
|
2016-06-29 22:02:45 +01:00
|
|
|
sock.send(respkey)
|
|
|
|
sock.send("\r\n\r\n")
|
2016-04-22 16:18:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
# Very simplified client handshake, works for MicroPython's
|
|
|
|
# websocket server implementation, but probably not for other
|
|
|
|
# servers.
|
|
|
|
def client_handshake(sock):
|
|
|
|
cl = sock.makefile("rwb", 0)
|
2020-02-27 04:36:53 +00:00
|
|
|
cl.write(
|
|
|
|
b"""\
|
2016-04-22 16:18:06 +01:00
|
|
|
GET / HTTP/1.1\r
|
|
|
|
Host: echo.websocket.org\r
|
|
|
|
Connection: Upgrade\r
|
|
|
|
Upgrade: websocket\r
|
|
|
|
Sec-WebSocket-Key: foo\r
|
|
|
|
\r
|
2020-02-27 04:36:53 +00:00
|
|
|
"""
|
|
|
|
)
|
2016-04-22 16:18:06 +01:00
|
|
|
l = cl.readline()
|
2020-02-27 04:36:53 +00:00
|
|
|
# print(l)
|
2016-04-22 16:18:06 +01:00
|
|
|
while 1:
|
|
|
|
l = cl.readline()
|
|
|
|
if l == b"\r\n":
|
|
|
|
break
|
2020-02-27 04:36:53 +00:00
|
|
|
|
|
|
|
|
2016-04-22 16:18:06 +01:00
|
|
|
# sys.stdout.write(l)
|