1 """ TCP server that communicates with terminals """
3 from configparser import ConfigParser
4 from logging import getLogger
6 from socket import socket, AF_INET6, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
7 from struct import pack
9 from typing import Dict, List, Optional, Tuple
13 from .gps303proto import (
20 from .zmsg import Bcast, Resp
22 log = getLogger("gps303/collector")
28 """Connected socket to the terminal plus buffer and metadata"""
30 def __init__(self, sock: socket, addr: Tuple[str, int]) -> None:
34 self.imei: Optional[str] = None
36 def close(self) -> None:
37 log.debug("Closing fd %d (IMEI %s)", self.sock.fileno(), self.imei)
41 def recv(self) -> Optional[List[Tuple[float, Tuple[str, int], bytes]]]:
42 """Read from the socket and parse complete messages"""
44 segment = self.sock.recv(MAXBUFFER)
47 "Reading from fd %d (IMEI %s): %s",
53 if not segment: # Terminal has closed connection
55 "EOF reading from fd %d (IMEI %s)",
61 self.buffer += segment
62 if len(self.buffer) > MAXBUFFER:
63 # We are receiving junk. Let's drop it or we run out of memory.
64 log.warning("More than %d unparseable data, dropping", MAXBUFFER)
68 framestart = self.buffer.find(b"xx")
69 if framestart == -1: # No frames, return whatever we have
71 if framestart > 0: # Should not happen, report
73 'Undecodable data (%d) "%s" from fd %d (IMEI %s)',
75 self.buffer[:framestart][:64].hex(),
79 self.buffer = self.buffer[framestart:]
80 # At this point, buffer starts with a packet
81 if len(self.buffer) < 6: # no len and proto - cannot proceed
83 exp_end = self.buffer[2] + 3 # Expect '\r\n' here
85 # Length field can legitimeely be much less than the
86 # length of the packet (e.g. WiFi positioning), but
87 # it _should not_ be greater. Still sometimes it is.
88 # Luckily, not by too much: by maybe two or three bytes?
89 # Do this embarrassing hack to avoid accidental match
90 # of some binary data in the packet against '\r\n'.
92 frameend = self.buffer.find(b"\r\n", frameend + 1)
93 if frameend == -1 or frameend >= (
95 ): # Found realistic match or none
97 if frameend == -1: # Incomplete frame, return what we have
99 packet = self.buffer[2:frameend]
100 self.buffer = self.buffer[frameend + 2 :]
101 if proto_of_message(packet) == LOGIN.PROTO:
102 self.imei = parse_message(packet).imei
104 "LOGIN from fd %d (IMEI %s)", self.sock.fileno(), self.imei
106 msgs.append((when, self.addr, packet))
109 def send(self, buffer: bytes) -> None:
111 self.sock.send(b"xx" + buffer + b"\r\n")
114 "Sending to fd %d (IMEI %s): %s",
122 def __init__(self) -> None:
123 self.by_fd: Dict[int, Client] = {}
124 self.by_imei: Dict[str, Client] = {}
126 def add(self, clntsock: socket, clntaddr: Tuple[str, int]) -> int:
127 fd = clntsock.fileno()
128 log.info("Start serving fd %d from %s", fd, clntaddr)
129 self.by_fd[fd] = Client(clntsock, clntaddr)
132 def stop(self, fd: int) -> None:
133 clnt = self.by_fd[fd]
134 log.info("Stop serving fd %d (IMEI %s)", clnt.sock.fileno(), clnt.imei)
137 del self.by_imei[clnt.imei]
142 ) -> Optional[List[Tuple[Optional[str], float, Tuple[str, int], bytes]]]:
143 clnt = self.by_fd[fd]
148 for when, peeraddr, packet in msgs:
149 if proto_of_message(packet) == LOGIN.PROTO: # Could do blindly...
151 self.by_imei[clnt.imei] = clnt
154 "Login message from %s: %s, but client imei unfilled",
158 result.append((clnt.imei, when, peeraddr, packet))
160 "Received from %s (IMEI %s): %s",
167 def response(self, resp: Resp) -> None:
168 if resp.imei in self.by_imei:
169 self.by_imei[resp.imei].send(resp.packet)
171 log.info("Not connected (IMEI %s)", resp.imei)
174 def runserver(conf: ConfigParser, handle_hibernate: bool = True) -> None:
175 # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
176 zctx = zmq.Context() # type: ignore
177 zpub = zctx.socket(zmq.PUB) # type: ignore
178 zpull = zctx.socket(zmq.PULL) # type: ignore
179 oldmask = umask(0o117)
180 zpub.bind(conf.get("collector", "publishurl"))
181 zpull.bind(conf.get("collector", "listenurl"))
183 tcpl = socket(AF_INET6, SOCK_STREAM)
184 tcpl.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
185 tcpl.bind(("", conf.getint("collector", "port")))
187 tcpfd = tcpl.fileno()
188 poller = zmq.Poller() # type: ignore
189 poller.register(zpull, flags=zmq.POLLIN)
190 poller.register(tcpfd, flags=zmq.POLLIN)
197 events = poller.poll(1000)
198 for sk, fl in events:
202 msg = zpull.recv(zmq.NOBLOCK)
208 clntsock, clntaddr = tcpl.accept()
209 topoll.append((clntsock, clntaddr))
210 elif fl & zmq.POLLIN:
211 received = clients.recv(sk)
213 log.debug("Terminal gone from fd %d", sk)
216 for imei, when, peeraddr, packet in received:
217 proto = proto_of_message(packet)
227 if proto == HIBERNATION.PROTO and handle_hibernate:
229 "HIBERNATION from fd %d (IMEI %s)",
234 respmsg = inline_response(packet)
235 if respmsg is not None:
237 Resp(imei=imei, when=when, packet=respmsg)
240 log.debug("Stray event: %s on socket %s", fl, sk)
241 # poll queue consumed, make changes now
243 poller.unregister(fd) # type: ignore
249 proto=proto_of_message(zmsg.packet),
255 log.debug("Sending to the client: %s", zmsg)
256 clients.response(zmsg)
257 for clntsock, clntaddr in topoll:
258 fd = clients.add(clntsock, clntaddr)
259 poller.register(fd, flags=zmq.POLLIN)
260 except KeyboardInterrupt:
263 zctx.destroy() # type: ignore
267 if __name__.endswith("__main__"):
268 runserver(common.init(log))