-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.py
319 lines (276 loc) · 9.42 KB
/
client.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import os
from enum import Enum
import jstyleson as json
import websocket, ssl
from websocket import ABNF
from urllib.parse import urlparse
from utils import *
from logger import WSHandler
from thread import StoppableThread
import plugin
DEFAULT_TIME_INTERVAL = 5
DEFAULT_TIME_OUT = 30
DEFAULT_DEBUG_TRACE = False
PREFS_FILE_NAME = normalize_path("preferences/prefs.json")
class icon_t(str, Enum):
none = ""
down = ":/icons/arrow-down.png"
up = ":/icons/arrow-up.png"
class color_t(str, Enum):
# status
success = "green"
normal = "black"
warn = "orange"
error = "red"
# color
red = "red"
orange = "orange"
class data_t(int, Enum):
text = 0
binary = 1
class log_t(int, Enum):
simple = 0
detail = 1
class WSClient:
""" Websocket Client """
m_prefs = {}
m_ws = None
m_ws_codes = {}
m_endpoint = ""
m_message = ""
m_sslfile = ""
m_autossl = True
m_debug = DEFAULT_DEBUG_TRACE
m_timeout = DEFAULT_TIME_OUT
m_custom_header = {}
m_autoping = False
m_ping_interval = DEFAULT_TIME_INTERVAL
m_ping_timeout = DEFAULT_TIME_OUT
m_ping_message = ""
m_ws_threads = {}
m_ws_temp_files = []
def __init__(self, *args, **kwargs):
pass
def update_ui(self, update_values=False):
assert False, "missing implementation"
def log(self, text, color=color_t.normal, icon=icon_t.none):
assert False, "missing implementation"
def status(self, text, color=color_t.normal):
assert False, "missing implementation"
def prefs_get(self, name, default=""):
parts = name.split(".")
if len(parts) == 1:
prefs = self.m_prefs
elif len(parts) == 2:
if parts[0] in self.m_prefs.keys():
prefs = self.m_prefs[parts[0]]
name = parts[1]
else: assert False, "prefs get faied -> unsupported"
return prefs[name] if name in prefs.keys() else default
def prefs_set(self, name, value):
parts = name.split(".")
if len(parts) == 1:
prefs = self.m_prefs
elif len(parts) == 2:
if not parts[0] in self.m_prefs.keys():
self.m_prefs[parts[0]] = {}
prefs = self.m_prefs[parts[0]]
name = parts[1]
else: assert False, "prefs set faied -> unsupported"
prefs[name] = value
def prefs_load_from_file(self):
try:
if os.path.exists(PREFS_FILE_NAME):
with open(PREFS_FILE_NAME, "r+") as f:
self.m_prefs = json.loads(f.read())
# connection
self.m_endpoint = self.prefs_get("endpoint").strip()
self.m_timeout = self.prefs_get("timeout", DEFAULT_TIME_OUT)
self.m_debug = self.prefs_get("show_debug_window", False)
self.m_message = self.prefs_get("default_message")
self.m_custom_header = self.prefs_get("default_custom_header", {})
# auto ssl
self.m_autossl = self.prefs_get("autossl", True)
self.m_sslfile = self.prefs_get("sslfile").strip()
self.m_sslfile = normalize_path(self.m_sslfile)
# auto ping
self.m_autoping = self.prefs_get("ping.enabled", False)
self.m_ping_interval = self.prefs_get("ping.interval", DEFAULT_TIME_INTERVAL)
self.m_ping_timeout = self.prefs_get("ping.timeout", DEFAULT_TIME_OUT)
self.m_ping_message= self.prefs_get("ping.message")
# others
self.m_ws_codes = self.prefs_get("websocket_codes", {})
except:
self.status("Loading preferences file failed", color_t.error)
self.update_ui(True)
def prefs_save_to_file(self):
# connection
self.prefs_set("endpoint", self.m_endpoint)
self.prefs_set("timeout", self.m_timeout)
self.prefs_set("show_debug_window", self.m_debug)
self.prefs_set("default_message", self.m_message)
self.prefs_set("default_custom_header", self.m_custom_header)
# auto ssl
self.prefs_set("autossl", self.m_autossl)
self.prefs_set("sslfile", self.m_sslfile)
# auto ping
self.prefs_set("ping.enabled", self.m_autoping)
self.prefs_set("ping.interval", self.m_ping_interval)
self.prefs_set("ping.timeout", self.m_ping_timeout)
self.prefs_set("ping.message", self.m_ping_message)
# save to file
with open(PREFS_FILE_NAME, "w+") as f:
f.write(json.dumps(self.m_prefs, indent=4))
def remember_to_delete_temp_file(self, temp_file):
self.m_ws_temp_files.append(temp_file)
def stop_thread(self, ws):
if ws in self.m_ws_threads.keys():
self.m_ws_threads[ws].stop()
del self.m_ws_threads[ws]
def ws_spotcheck_params(self):
result = self.m_timeout > 0 and self.m_endpoint.startswith(("ws:", "wss:"))
if self.m_autoping:
result = result and self.m_ping_interval > 0 and self.m_ping_timeout > 0
return result
def ws_on_open(self, ws):
self.m_ws = ws
self.status("Opened", color_t.success)
self.update_ui()
for e in plugin.plugins(): e.on_open(e, ws)
def ws_on_close(self, ws, close_status_code, close_msg):
text = "Closed"
color = color_t.normal
if close_msg:
text = close_msg
color = color_t.error
elif close_status_code:
msg = None
ws_close_codes = self.m_ws_codes.get("close")
if ws_close_codes: msg = ws_close_codes.get(str(close_status_code))
text = f"Close code {close_status_code}" if msg is None else msg
color = color_t.error
if self.ws_ready(): self.status(text, color)
self.stop_thread(ws)
self.m_ws = None
self.update_ui()
for e in plugin.plugins(): e.on_close(e, ws, close_status_code, close_msg)
def ws_on_error(self, ws, error):
self.m_ws = None
self.status(str(error), color_t.error)
self.update_ui()
for e in plugin.plugins(): e.on_error(e, ws, error)
if error: raise error
def ws_on_ping(self, ws, message):
try:
if isinstance(message, bytes): message = message.decode("utf-8")
except UnicodeDecodeError:
message = hex_view(message)
self.log(message, color_t.red, icon_t.up)
for e in plugin.plugins(): e.on_ping(e, ws, message)
def ws_on_pong(self, ws, message):
try:
if isinstance(message, bytes): message = message.decode("utf-8")
except UnicodeDecodeError:
message = hex_view(message)
self.log(message, color_t.red, icon_t.down)
for e in plugin.plugins(): e.on_pong(e, ws, message)
def ws_on_data(self, ws, data, type, continuous):
if type == ABNF.OPCODE_TEXT:
self.log(data, color_t.red, icon_t.down)
elif type == ABNF.OPCODE_BINARY:
log_type = self.selected_log_type()
if log_type == log_t.simple:
text_size = format_bytes(len(data));
self.log(f"<binary> {text_size}", color_t.red, icon_t.down)
else:
self.log(hex_view(data), color_t.red, icon_t.down)
else:
print("received data type did not support", ABNF.OPCODE_MAP.get(type))
for e in plugin.plugins(): e.on_recv(e, ws, data, type, continuous)
def ws_send(self, data, opcode=ABNF.OPCODE_TEXT):
if self.ws_ready():
self.m_ws.send(data, opcode)
for e in plugin.plugins(): e.on_send(e, self.m_ws, data, opcode)
def ws_ping(self, payload=""):
if self.ws_ready():
self.m_ws.sock.ping(payload)
for e in plugin.plugins(): e.on_ping(e, self.m_ws, payload)
def ws_ready(self):
return not self.m_ws is None
def ws_start(self, use_ssl):
websocket.enableTrace(traceable=True, handler=WSHandler(self))
websocket.setdefaulttimeout(self.m_timeout)
if use_ssl: self.status("Initializing SSL connection ...", color_t.warn)
ssl_opt = None
if use_ssl: # websocket secure
sslfile = ""
try:
# generate certificate for ssl connection
if self.m_autossl:
# get signed certificate from default ca trusted root certificates
sslfile = ssl_default_ca_file = get_default_ca_trust_root_certificates()
# get self-signed certificate chain from server
url = urlparse(self.m_endpoint)
ssl_self_signed_file = get_cert_chains_certificates(url.hostname, url.port or 443)
self.remember_to_delete_temp_file(ssl_self_signed_file)
# combine them all into one and save to a single file in temporary folder
if os.path.exists(ssl_default_ca_file) and os.path.exists(ssl_self_signed_file):
content = ""
with open(ssl_default_ca_file, "r") as f: content += f.read() + "\n"
with open(ssl_self_signed_file, "r") as f: content += f.read() + "\n"
sslfile = store_as_temporary_file(content.encode())
self.remember_to_delete_temp_file(sslfile)
elif os.path.exists(self.m_sslfile): # get from specified cert file
sslfile = self.m_sslfile
# create ssl context
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_verify_locations(sslfile)
ssl_opt = {"context": ssl_context}
except Exception as e:
self.status(str(e), color_t.error)
return
self.status("Connecting to server ...", color_t.warn)
ws = websocket.WebSocketApp(
self.m_endpoint,
header=self.m_custom_header,
on_open=self.ws_on_open,
on_close=self.ws_on_close,
on_data=self.ws_on_data,
on_error=self.ws_on_error,
on_ping=self.ws_on_ping,
on_pong=self.ws_on_pong,
)
ping_interval = 0
ping_timeout = None
ping_payload = ""
if self.m_autoping:
ping_interval = self.m_ping_interval
ping_timeout = self.m_ping_timeout
ping_payload = self.m_ping_message
def run(*args):
try:
ws.run_forever(
sslopt=ssl_opt,
ping_interval=ping_interval,
ping_timeout=ping_timeout,
ping_payload=ping_payload,
)
except Exception as e:
ws.close()
self.stop_thread(ws)
self.m_ws_threads[ws] = StoppableThread(target=run)
self.m_ws_threads[ws].start()
def ws_close(self):
if self.ws_ready():
self.status("Closing connection ...", color_t.warn)
self.m_ws.close()
self.stop_thread(self.m_ws)
self.status("Closed")
def ws_cleanup(self):
self.ws_close()
for ws in self.m_ws_threads.keys():
ws.close()
self.stop_thread(ws)
for e in self.m_ws_temp_files:
if os.path.exists(e):
os.unlink(e)