forked from nfcgate/server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·229 lines (182 loc) · 8.89 KB
/
Copy pathserver.py
File metadata and controls
executable file
·229 lines (182 loc) · 8.89 KB
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
#!/usr/bin/env python3
import argparse
import socket
import socketserver
import ssl
import struct
import datetime
import sys
import threading
HOST = "0.0.0.0"
PORT = 5566
class PluginHandler:
def __init__(self, plugins):
self.plugin_list = []
for modname in plugins:
self.plugin_list.append((modname, __import__("plugins.mod_%s" % modname, fromlist=["plugins"])))
print("Loaded", "mod_%s" % modname)
def filter(self, client, data):
for modname, plugin in self.plugin_list:
if type(data) == list:
first = data[0]
else:
first = data
first = plugin.handle_data(lambda *x: client.log(*x, tag=modname), first, client.state)
if type(data) == list:
data = [first] + data[1:]
else:
data = first
return data
class NFCGateClientHandler(socketserver.StreamRequestHandler):
def __init__(self, request, client_address, srv):
super().__init__(request, client_address, srv)
def log(self, *args, tag="server"):
self.server.log(*args, origin=self.client_address, tag=tag)
def setup(self):
super().setup()
self.session = None
self.write_lock = threading.Lock()
self.state = {}
self.request.settimeout(300)
# Disable Nagle (LATENCIA_OPTIMIZACION.md Fase E). The relay exchanges tiny
# length-prefixed frames strictly lock-step, and StreamRequestHandler's
# wfile is unbuffered (wbufsize=0), so a frame's 4-byte header and payload
# went out as two separate TCP segments. With Nagle on, the payload segment
# waits for the header's ACK — or the ~40 ms delayed-ACK timer — on EVERY
# server->board relay (2 of the 4 hops per APDU pair), i.e. up to ~40 ms of
# dead time per hop. TCP_NODELAY sends each segment immediately; combined
# with the single coalesced write in send_to_clients it removes the stall.
try:
self.request.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except OSError:
pass # e.g. non-TCP transport; nothing to tune
self.log("server", "connected")
def handle(self):
super().handle()
while True:
try:
msg_len_data = self.rfile.read(5)
except socket.timeout:
self.log("server", "Timeout")
break
if len(msg_len_data) < 5:
break
msg_len, session = struct.unpack("!IB", msg_len_data)
data = self.rfile.read(msg_len)
# Per-frame hex dump is a HOT-PATH cost (Fase H, LATENCIA_OPTIMIZACION.md).
# The relay is strictly lock-step and this log runs synchronously BETWEEN
# reading a frame and forwarding it, so building bytes(data)'s repr (up to
# 256 B) + datetime.now() + print()/flush lands on the causal chain on every
# one of the ~36 relayed frames per transaction — the server-side analog of
# H1 (Debug logging per APDU on the board). Gated behind --verbose so the
# default relay path never pays it; enable -v only to diagnose.
if self.server.verbose:
self.log("server", "data:", bytes(data))
# no data was sent or no session number supplied and none set yet
if msg_len == 0 or session == 0 and self.session is None:
break
# change in session number detected
if self.session != session:
# remove from old association
self.server.remove_client(self, self.session)
# update and add association
self.session = session
self.server.add_client(self, session)
# allow plugins to filter data before sending it to all clients in the session
self.server.send_to_clients(self.session, self.server.plugins.filter(self, data), self)
def finish(self):
super().finish()
self.server.remove_client(self, self.session)
self.log("server", "disconnected")
class NFCGateServer(socketserver.ThreadingTCPServer):
def __init__(self, server_address, request_handler, plugins, tls_options=None, bind_and_activate=True,
verbose=False):
self.allow_reuse_address = True
super().__init__(server_address, request_handler, bind_and_activate)
# Fase H: when False (default) the per-frame hot-path logs are skipped so a
# relay run stays quiet and fast; -v turns them back on for diagnostics.
self.verbose = verbose
self.clients = {}
self.plugins = PluginHandler(plugins)
# TLS
self.tls_options = tls_options
self.log("NFCGate server listening on", server_address)
if self.tls_options:
self.log("TLS enabled with cert {} and key {}".format(self.tls_options["cert_file"],
self.tls_options["key_file"]))
def get_request(self):
client_socket, from_addr = super().get_request()
if not self.tls_options:
return client_socket, from_addr
# if TLS enabled, wrap the socket
return self.tls_options["context"].wrap_socket(client_socket, server_side=True), from_addr
def log(self, *args, origin="0", tag="server"):
print(datetime.datetime.now(), "["+tag+"]", origin, *args)
def add_client(self, client, session):
if session is None:
return
if session not in self.clients:
self.clients[session] = []
self.clients[session].append(client)
client.log("joined session", session)
def remove_client(self, client, session):
if session is None or session not in self.clients:
return
self.clients[session].remove(client)
client.log("left session", session)
def send_to_clients(self, session, msgs, origin):
if session is None or session not in self.clients:
return
for client in self.clients[session]:
# do not send message back to originator
if client is origin:
continue
if type(msgs) != list:
msgs = [msgs]
with client.write_lock:
for msg in msgs:
# Single coalesced write so the 4-byte length header and the
# payload leave as ONE TCP segment (Fase E): with the unbuffered
# wfile the previous two writes produced two segments and, under
# Nagle, a ~40 ms delayed-ACK stall between them on every relay.
client.wfile.write(int.to_bytes(len(msg), 4, byteorder='big') + bytes(msg))
# Also a hot-path per-frame log (Fase H): the forward already happened above,
# but this print still steals the thread (and the GIL) once per relayed frame.
# Gated behind --verbose like the receive-side dump.
if self.verbose:
self.log("Publish reached", len(self.clients[session]) - 1, "clients")
def parse_args():
parser = argparse.ArgumentParser(prog="NFCGate server")
parser.add_argument("plugins", type=str, nargs="*", help="List of plugin modules to load.")
parser.add_argument("-v", "--verbose", help="Log every relayed frame (per-APDU hex dump + "
"'Publish reached'). Off by default: those logs are on the lock-step relay "
"hot path (Fase H), so leaving them off cuts per-frame latency.",
default=False, action="store_true")
parser.add_argument("-s", "--tls", help="Enable TLS. You must specify certificate and key.",
default=False, action="store_true")
parser.add_argument("--tls_cert", help="TLS certificate file in PEM format.", action="store")
parser.add_argument("--tls_key", help="TLS key file in PEM format.", action="store")
args = parser.parse_args()
tls_options = None
if args.tls:
# check cert and key file
if args.tls_cert is None or args.tls_key is None:
print("You must specify tls_cert and tls_key!")
sys.exit(1)
tls_options = {
"cert_file": args.tls_cert,
"key_file": args.tls_key
}
try:
tls_options["context"] = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
tls_options["context"].load_cert_chain(tls_options["cert_file"], tls_options["key_file"])
except ssl.SSLError:
print("Certificate or key could not be loaded. Please check format and file permissions!")
sys.exit(1)
return args.plugins, tls_options, args.verbose
def main():
plugins, tls_options, verbose = parse_args()
NFCGateServer((HOST, PORT), NFCGateClientHandler, plugins, tls_options,
verbose=verbose).serve_forever()
if __name__ == "__main__":
main()