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]:
227 htmlfile = conf.get("wsgateway", "htmlfile")
229 zsub = zctx.socket(zmq.SUB)
230 zsub.connect(conf.get("lookaside", "publishurl"))
231 zsub.setsockopt(zmq.SUBSCRIBE, b"")
232 tcpl = socket(AF_INET6, SOCK_STREAM)
233 tcpl.setblocking(False)
234 tcpl.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
235 tcpl.bind(("", conf.getint("wsgateway", "port")))
237 tcpfd = tcpl.fileno()
238 poller = zmq.Poller()
239 poller.register(zsub, flags=zmq.POLLIN)
240 poller.register(tcpfd, flags=zmq.POLLIN)
249 events = poller.poll()
250 for sk, fl in events:
254 zmsg = LocEvt(zsub.recv(zmq.NOBLOCK))
259 clntsock, clntaddr = tcpl.accept()
260 topoll.append((clntsock, clntaddr))
261 elif fl & zmq.POLLIN:
262 received = clients.recv(sk)
264 log.debug("Client gone from fd %d", sk)
269 log.debug("Received from %d: %s", sk, msg)
271 elif fl & zmq.POLLOUT:
272 log.debug("Write now open for fd %d", sk)
276 log.debug("Stray event: %s on socket %s", fl, sk)
277 # poll queue consumed, make changes now
279 poller.unregister(fd)
282 log.debug("Sending to the clients: %s", zmsg)
283 towrite |= clients.send(zmsg)
284 for clntsock, clntaddr in topoll:
285 fd = clients.add(clntsock, clntaddr)
286 poller.register(fd, flags=zmq.POLLIN)
287 # Deal with actually writing the data out
288 trywrite = towrite - towait
289 morewait = clients.write(trywrite)
291 "towait %s, tried %s, still busy %s",
296 for fd in morewait - trywrite: # new fds waiting for write
297 poller.modify(fd, flags=zmq.POLLIN | zmq.POLLOUT)
298 for fd in trywrite - morewait: # no longer waiting for write
299 poller.modify(fd, flags=zmq.POLLIN)
302 except KeyboardInterrupt:
306 if __name__.endswith("__main__"):
307 runserver(common.init(log))