-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
websocket.py
182 lines (138 loc) · 5.31 KB
/
websocket.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# -*- coding: utf-8 -*-
#
# gdb-frontend is a easy, flexible and extensionable gui debugger
#
# https://github.com/rohanrhu/gdb-frontend
# https://oguzhaneroglu.com/projects/gdb-frontend/
#
# Licensed under GNU/GPLv3
# Copyright (C) 2019, Oğuzhan Eroğlu (https://oguzhaneroglu.com/) <[email protected]>
"""
GDBFrontend's WebSocket Server
(gdbfrontend.websocket.HTTPServer is wrapped by gdbfrontend.http_server.GDBFrontendHTTPServer)
WebSocket methods are not thread-safe by itself.
WebSocket client connections are threaded and you must be careful
while using WebSocketHandler.wsSend(message) because of thread-safety.
"""
import sys
import socket
import socketserver
import struct
import base64
import hashlib
import threading
import config
import util
import http.server
MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
client_id_i = 1
wsSend_lock = threading.Lock()
class WebSocketHandler(http.server.BaseHTTPRequestHandler):
message = None
ws_connected = False
client_id = 0
def __init__(self, request, client_address, server):
global client_id_i
http.server.BaseHTTPRequestHandler.__init__(self, request, client_address, server)
def wsHandle(self, path):
global client_id_i
if self.path != path:
return False
connection = self.headers.get("Connection")
if connection:
connection = connection.split(", ")
else:
connection = []
if "Upgrade" not in connection or self.headers.get("Upgrade") != "websocket":
return True
key = self.headers.get("Sec-WebSocket-Key")
extensions = self.headers.get("Sec-WebSocket-Extensions")
if extensions:
extensions = extensions.split("; ")
accept = base64.b64encode(
hashlib.sha1(
(key + MAGIC).encode("ascii")
).digest()
).decode("ascii")
self.wfile.write(b"HTTP/1.1 101 Switching Protocols\r\n")
self.send_header('Upgrade', 'websocket')
self.send_header('Connection', 'Upgrade')
self.send_header('Sec-WebSocket-Accept', accept)
self.end_headers()
self.client_id = client_id_i
client_id_i += 1
self.ws_connected = True
self.handleConnection()
self._wsRead()
return True
def _wsRead(self):
while self.ws_connected:
header0_16 = None
is_masked = False
plen = 0
mkey = None
try:
header0_16 = struct.unpack("!BB", self.connection.recv(2, socket.MSG_WAITALL))
opcode = header0_16[0] & 0b00001111
if opcode == 8:
self.ws_connected = False
self.handleClose()
break
is_masked = header0_16[1] & -128
plen = header0_16[1] & 127
if plen == 126:
plen = int.from_bytes(struct.unpack("!BB", self.connection.recv(2, socket.MSG_WAITALL)), "big")
elif plen == 127:
plen = int.from_bytes(struct.unpack("!BBBBBBBB", self.connection.recv(2, socket.MSG_WAITALL)), "big")
if is_masked:
mkey = struct.unpack("!BBBB", self.connection.recv(4, socket.MSG_WAITALL))
self.message = list(self.connection.recv(plen, socket.MSG_WAITALL))
if is_masked:
for i in range(plen):
self.message[i] = self.message[i] ^ mkey[i%4]
self.message = bytes(self.message).decode("utf-8")
self.handleMessage()
except Exception as e:
util.verbose(
"Websocket read error:",
e,
"(" + sys.exc_info()[-1].tb_frame.f_code.co_filename + ":" + str(sys.exc_info()[-1].tb_lineno) + ")"
)
if (config.VERBOSE):
raise e
self.ws_connected = False
self.handleClose()
def wsSend(self, message):
wsSend_lock.acquire()
try:
if isinstance(message, str):
message = message.encode("utf-8")
mlen = len(message)
if mlen < 126:
frame = struct.pack("!BB", 0b10000001, mlen)
elif mlen < (1 << 16):
frame = struct.pack("!BBH", 0b10000001, 126, mlen)
else:
frame = struct.pack("!BBQ", 0b10000001, 127, mlen)
self.wfile.write(frame)
self.wfile.write(message)
except:
wsSend_lock.release()
finally:
wsSend_lock.release()
def handleMessage(self):
pass
def handleConnection(self):
pass
def handleClose(self):
pass
class HTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
ws_clients = []
def getClientById(self, client_id):
for client in self.ws_clients:
if client.client_id == client_id:
return client
return False
def wsSendAll(self, message):
for client in self.ws_clients:
client.wsSend(message)