1 """ TCP server that communicates with terminals """
3 from configparser import ConfigParser
4 from logging import getLogger
14 from struct import pack
16 from typing import Dict, List, Optional, Tuple
20 from .gps303proto import (
27 from .zmsg import Bcast, Resp
29 log = getLogger("gps303/collector")
35 """Connected socket to the terminal plus buffer and metadata"""
37 def __init__(self, sock: socket, addr: Tuple[str, int]) -> None:
41 self.imei: Optional[str] = None
43 def close(self) -> None:
44 log.debug("Closing fd %d (IMEI %s)", self.sock.fileno(), self.imei)
48 def recv(self) -> Optional[List[Tuple[float, Tuple[str, int], bytes]]]:
49 """Read from the socket and parse complete messages"""
51 segment = self.sock.recv(MAXBUFFER)
54 "Reading from fd %d (IMEI %s): %s",
60 if not segment: # Terminal has closed connection
62 "EOF reading from fd %d (IMEI %s)",
68 self.buffer += segment
69 if len(self.buffer) > MAXBUFFER:
70 # We are receiving junk. Let's drop it or we run out of memory.
71 log.warning("More than %d unparseable data, dropping", MAXBUFFER)
75 framestart = self.buffer.find(b"xx")
76 if framestart == -1: # No frames, return whatever we have
78 if framestart > 0: # Should not happen, report
80 'Undecodable data (%d) "%s" from fd %d (IMEI %s)',
82 self.buffer[:framestart][:64].hex(),
86 self.buffer = self.buffer[framestart:]
87 # At this point, buffer starts with a packet
88 if len(self.buffer) < 6: # no len and proto - cannot proceed
90 exp_end = self.buffer[2] + 3 # Expect '\r\n' here
92 # Length field can legitimeely be much less than the
93 # length of the packet (e.g. WiFi positioning), but
94 # it _should not_ be greater. Still sometimes it is.
95 # Luckily, not by too much: by maybe two or three bytes?
96 # Do this embarrassing hack to avoid accidental match
97 # of some binary data in the packet against '\r\n'.
99 frameend = self.buffer.find(b"\r\n", frameend + 1)
100 if frameend == -1 or frameend >= (
102 ): # Found realistic match or none
104 if frameend == -1: # Incomplete frame, return what we have
106 packet = self.buffer[2:frameend]
107 self.buffer = self.buffer[frameend + 2 :]
108 if proto_of_message(packet) == LOGIN.PROTO:
109 self.imei = parse_message(packet).imei
111 "LOGIN from fd %d (IMEI %s)", self.sock.fileno(), self.imei
113 msgs.append((when, self.addr, packet))
116 def send(self, buffer: bytes) -> None:
118 self.sock.send(b"xx" + buffer + b"\r\n")
121 "Sending to fd %d (IMEI %s): %s",
129 def __init__(self) -> None:
130 self.by_fd: Dict[int, Client] = {}
131 self.by_imei: Dict[str, Client] = {}
133 def add(self, clntsock: socket, clntaddr: Tuple[str, int]) -> int:
134 fd = clntsock.fileno()
135 log.info("Start serving fd %d from %s", fd, clntaddr)
136 self.by_fd[fd] = Client(clntsock, clntaddr)
139 def stop(self, fd: int) -> None:
140 clnt = self.by_fd[fd]
141 log.info("Stop serving fd %d (IMEI %s)", clnt.sock.fileno(), clnt.imei)
144 del self.by_imei[clnt.imei]
149 ) -> Optional[List[Tuple[Optional[str], float, Tuple[str, int], bytes]]]:
150 clnt = self.by_fd[fd]
155 for when, peeraddr, packet in msgs:
156 if proto_of_message(packet) == LOGIN.PROTO: # Could do blindly...
158 self.by_imei[clnt.imei] = clnt
161 "Login message from %s: %s, but client imei unfilled",
165 result.append((clnt.imei, when, peeraddr, packet))
167 "Received from %s (IMEI %s): %s",
174 def response(self, resp: Resp) -> None:
175 if resp.imei in self.by_imei:
176 self.by_imei[resp.imei].send(resp.packet)
178 log.info("Not connected (IMEI %s)", resp.imei)
181 def runserver(conf: ConfigParser, handle_hibernate: bool = True) -> None:
182 # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
183 zctx = zmq.Context() # type: ignore
184 zpub = zctx.socket(zmq.PUB) # type: ignore
185 zpull = zctx.socket(zmq.PULL) # type: ignore
186 oldmask = umask(0o117)
187 zpub.bind(conf.get("collector", "publishurl"))
188 zpull.bind(conf.get("collector", "listenurl"))
190 tcpl = socket(AF_INET6, SOCK_STREAM)
191 tcpl.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
192 tcpl.bind(("", conf.getint("collector", "port")))
194 tcpfd = tcpl.fileno()
195 poller = zmq.Poller() # type: ignore
196 poller.register(zpull, flags=zmq.POLLIN)
197 poller.register(tcpfd, flags=zmq.POLLIN)
204 events = poller.poll(1000)
205 for sk, fl in events:
209 msg = zpull.recv(zmq.NOBLOCK)
215 clntsock, clntaddr = tcpl.accept()
216 clntsock.setsockopt(SOL_SOCKET, SO_KEEPALIVE, 1)
217 topoll.append((clntsock, clntaddr))
218 elif fl & zmq.POLLIN:
219 received = clients.recv(sk)
221 log.debug("Terminal gone from fd %d", sk)
224 for imei, when, peeraddr, packet in received:
225 proto = proto_of_message(packet)
235 if proto == HIBERNATION.PROTO and handle_hibernate:
237 "HIBERNATION from fd %d (IMEI %s)",
242 respmsg = inline_response(packet)
243 if respmsg is not None:
245 Resp(imei=imei, when=when, packet=respmsg)
248 log.debug("Stray event: %s on socket %s", fl, sk)
249 # poll queue consumed, make changes now
251 poller.unregister(fd) # type: ignore
257 proto=proto_of_message(zmsg.packet),
263 log.debug("Sending to the client: %s", zmsg)
264 clients.response(zmsg)
265 for clntsock, clntaddr in topoll:
266 fd = clients.add(clntsock, clntaddr)
267 poller.register(fd, flags=zmq.POLLIN)
268 except KeyboardInterrupt:
271 zctx.destroy() # type: ignore
275 if __name__.endswith("__main__"):
276 runserver(common.init(log))