1 """ Websocket Gateway """
4 from logging import getLogger
5 from socket import socket, AF_INET6, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
7 from wsproto import ConnectionType, WSConnection
8 from wsproto.events import (
16 from wsproto.utilities import RemoteProtocolError
20 from .zmsg import LocEvt
22 log = getLogger("gps303/wsgateway")
26 def try_http(data, fd, e):
29 lines = data.decode().split("\r\n")
32 op, resource, proto = request.split(" ")
34 "HTTP %s for %s, proto %s from fd %d, headers: %s",
42 pos = resource.index("?")
43 resource = resource[:pos]
49 f"{proto} 500 No data configured\r\n"
50 f"Content-Type: text/plain\r\n\r\n"
51 f"HTML data not configure on the server\r\n".encode()
55 with open(htmlfile, "rb") as fl:
57 length = len(htmldata)
60 f"Content-Type: text/html; charset=utf-8\r\n"
61 f"Content-Length: {len(htmldata):d}\r\n\r\n"
62 ).encode("utf-8") + htmldata
65 f"{proto} 500 File not found\r\n"
66 f"Content-Type: text/plain\r\n\r\n"
67 f"HTML file could not be opened\r\n".encode()
71 f"{proto} 404 File not found\r\n"
72 f"Content-Type: text/plain\r\n\r\n"
73 f'We can only serve "/"\r\n'.encode()
77 f"{proto} 400 Bad request\r\n"
78 "Content-Type: text/plain\r\n\r\n"
79 "Bad request\r\n".encode()
82 log.warning("Unparseable data from fd %d: %s", fd, data)
87 """Websocket connection to the client"""
89 def __init__(self, sock, addr):
92 self.ws = WSConnection(ConnectionType.SERVER)
98 log.debug("Closing fd %d", self.sock.fileno())
103 data = self.sock.recv(4096)
106 "Reading from fd %d: %s",
110 self.ws.receive_data(None)
112 if not data: # Client has closed connection
114 "EOF reading from fd %d",
117 self.ws.receive_data(None)
120 self.ws.receive_data(data)
121 except RemoteProtocolError as e:
123 "Websocket error on fd %d, try plain http (%s)",
127 self.ws_data = try_http(data, self.sock.fileno(), e)
128 self.write() # TODO this is a hack
129 log.debug("Sending HTTP response to %d", self.sock.fileno())
133 for event in self.ws.events():
134 if isinstance(event, Request):
135 log.debug("WebSocket upgrade on fd %d", self.sock.fileno())
136 # self.ws_data += self.ws.send(event.response()) # Why not?!
137 self.ws_data += self.ws.send(AcceptConnection())
139 elif isinstance(event, (CloseConnection, Ping)):
140 log.debug("%s on fd %d", event, self.sock.fileno())
141 self.ws_data += self.ws.send(event.response())
142 elif isinstance(event, TextMessage):
143 # TODO: save imei "subscription"
144 log.debug("%s on fd %d", event, self.sock.fileno())
145 msg = loads(event.data)
147 if msg.get("type", None) == "subscribe":
148 self.imeis = set(msg.get("imei", []))
150 "subs list on fd %s is %s",
155 log.warning("%s on fd %d", event, self.sock.fileno())
158 def wants(self, imei):
159 log.debug("wants %s? set is %s on fd %d", imei, self.imeis, self.sock.fileno())
160 return True # TODO: check subscriptions
162 def send(self, message):
163 if self.ready and message.imei in self.imeis:
164 self.ws_data += self.ws.send(Message(data=message.json))
169 sent = self.sock.send(self.ws_data)
170 self.ws_data = self.ws_data[sent:]
173 "Sending to fd %d: %s",
178 return bool(self.ws_data)
185 def add(self, clntsock, clntaddr):
186 fd = clntsock.fileno()
187 log.info("Start serving fd %d from %s", fd, clntaddr)
188 self.by_fd[fd] = Client(clntsock, clntaddr)
192 clnt = self.by_fd[fd]
193 log.info("Stop serving fd %d", clnt.sock.fileno())
198 clnt = self.by_fd[fd]
204 log.debug("Received: %s", msg)
210 for fd, clnt in self.by_fd.items():
211 if clnt.wants(msg.imei):
216 def write(self, towrite):
218 for fd, clnt in [(fd, self.by_fd.get(fd)) for fd in towrite]:
225 for clnt in self.by_fd.values():
233 htmlfile = conf.get("wsgateway", "htmlfile")
235 zsub = zctx.socket(zmq.SUB)
236 zsub.connect(conf.get("lookaside", "publishurl"))
237 tcpl = socket(AF_INET6, SOCK_STREAM)
238 tcpl.setblocking(False)
239 tcpl.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
240 tcpl.bind(("", conf.getint("wsgateway", "port")))
242 tcpfd = tcpl.fileno()
243 poller = zmq.Poller()
244 poller.register(zsub, flags=zmq.POLLIN)
245 poller.register(tcpfd, flags=zmq.POLLIN)
251 neededsubs = clients.subs()
252 for imei in neededsubs - activesubs:
253 zsub.setsockopt(zmq.SUBSCRIBE, imei.encode())
254 for imei in activesubs - neededsubs:
255 zsub.setsockopt(zmq.UNSUBSCRIBE, imei.encode())
256 activesubs = neededsubs
257 log.debug("Subscribed to: %s", activesubs)
262 events = poller.poll()
263 for sk, fl in events:
267 zmsg = LocEvt(zsub.recv(zmq.NOBLOCK))
272 clntsock, clntaddr = tcpl.accept()
273 topoll.append((clntsock, clntaddr))
274 elif fl & zmq.POLLIN:
275 received = clients.recv(sk)
277 log.debug("Client gone from fd %d", sk)
282 log.debug("Received from %d: %s", sk, msg)
284 elif fl & zmq.POLLOUT:
285 log.debug("Write now open for fd %d", sk)
289 log.debug("Stray event: %s on socket %s", fl, sk)
290 # poll queue consumed, make changes now
292 poller.unregister(fd)
295 log.debug("Sending to the clients: %s", zmsg)
296 towrite |= clients.send(zmsg)
297 for clntsock, clntaddr in topoll:
298 fd = clients.add(clntsock, clntaddr)
299 poller.register(fd, flags=zmq.POLLIN)
300 # Deal with actually writing the data out
301 trywrite = towrite - towait
302 morewait = clients.write(trywrite)
304 "towait %s, tried %s, still busy %s",
309 for fd in morewait - trywrite: # new fds waiting for write
310 poller.modify(fd, flags=zmq.POLLIN | zmq.POLLOUT)
311 for fd in trywrite - morewait: # no longer waiting for write
312 poller.modify(fd, flags=zmq.POLLIN)
315 except KeyboardInterrupt:
319 if __name__.endswith("__main__"):
320 runserver(common.init(log))