]> www.average.org Git - loctrkd.git/blob - gps303/collector.py
collector: do not remove clients before all sends
[loctrkd.git] / gps303 / collector.py
1 """ TCP server that communicates with terminals """
2
3 from configparser import ConfigParser
4 from logging import getLogger
5 from os import umask
6 from socket import (
7     socket,
8     AF_INET6,
9     SOCK_STREAM,
10     SOL_SOCKET,
11     SO_KEEPALIVE,
12     SO_REUSEADDR,
13 )
14 from struct import pack
15 from time import time
16 from typing import Dict, List, Optional, Tuple
17 import zmq
18
19 from . import common
20 from .gps303proto import (
21     HIBERNATION,
22     LOGIN,
23     inline_response,
24     parse_message,
25     proto_of_message,
26 )
27 from .zmsg import Bcast, Resp
28
29 log = getLogger("gps303/collector")
30
31 MAXBUFFER: int = 4096
32
33
34 class Client:
35     """Connected socket to the terminal plus buffer and metadata"""
36
37     def __init__(self, sock: socket, addr: Tuple[str, int]) -> None:
38         self.sock = sock
39         self.addr = addr
40         self.buffer = b""
41         self.imei: Optional[str] = None
42
43     def close(self) -> None:
44         log.debug("Closing fd %d (IMEI %s)", self.sock.fileno(), self.imei)
45         self.sock.close()
46         self.buffer = b""
47
48     def recv(self) -> Optional[List[Tuple[float, Tuple[str, int], bytes]]]:
49         """Read from the socket and parse complete messages"""
50         try:
51             segment = self.sock.recv(MAXBUFFER)
52         except OSError as e:
53             log.warning(
54                 "Reading from fd %d (IMEI %s): %s",
55                 self.sock.fileno(),
56                 self.imei,
57                 e,
58             )
59             return None
60         if not segment:  # Terminal has closed connection
61             log.info(
62                 "EOF reading from fd %d (IMEI %s)",
63                 self.sock.fileno(),
64                 self.imei,
65             )
66             return None
67         when = time()
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)
72             self.buffer = b""
73         msgs = []
74         while True:
75             framestart = self.buffer.find(b"xx")
76             if framestart == -1:  # No frames, return whatever we have
77                 break
78             if framestart > 0:  # Should not happen, report
79                 log.warning(
80                     'Undecodable data (%d) "%s" from fd %d (IMEI %s)',
81                     framestart,
82                     self.buffer[:framestart][:64].hex(),
83                     self.sock.fileno(),
84                     self.imei,
85                 )
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
89                 break
90             exp_end = self.buffer[2] + 3  # Expect '\r\n' here
91             frameend = 0
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'.
98             while True:
99                 frameend = self.buffer.find(b"\r\n", frameend + 1)
100                 if frameend == -1 or frameend >= (
101                     exp_end - 3
102                 ):  # Found realistic match or none
103                     break
104             if frameend == -1:  # Incomplete frame, return what we have
105                 break
106             packet = self.buffer[2:frameend]
107             self.buffer = self.buffer[frameend + 2 :]
108             if len(packet) < 2:  # frameend comes too early
109                 log.warning("Packet too short: %s", packet)
110                 break
111             if proto_of_message(packet) == LOGIN.PROTO:
112                 msg = parse_message(packet)
113                 if isinstance(msg, LOGIN):  # Can be unparseable
114                     self.imei = msg.imei
115                     log.info(
116                         "LOGIN from fd %d (IMEI %s)",
117                         self.sock.fileno(),
118                         self.imei,
119                     )
120             msgs.append((when, self.addr, packet))
121         return msgs
122
123     def send(self, buffer: bytes) -> None:
124         try:
125             self.sock.send(b"xx" + buffer + b"\r\n")
126         except OSError as e:
127             log.error(
128                 "Sending to fd %d (IMEI %s): %s",
129                 self.sock.fileno(),
130                 self.imei,
131                 e,
132             )
133
134
135 class Clients:
136     def __init__(self) -> None:
137         self.by_fd: Dict[int, Client] = {}
138         self.by_imei: Dict[str, Client] = {}
139
140     def add(self, clntsock: socket, clntaddr: Tuple[str, int]) -> int:
141         fd = clntsock.fileno()
142         log.info("Start serving fd %d from %s", fd, clntaddr)
143         self.by_fd[fd] = Client(clntsock, clntaddr)
144         return fd
145
146     def stop(self, fd: int) -> None:
147         clnt = self.by_fd[fd]
148         log.info("Stop serving fd %d (IMEI %s)", clnt.sock.fileno(), clnt.imei)
149         clnt.close()
150         if clnt.imei:
151             del self.by_imei[clnt.imei]
152         del self.by_fd[fd]
153
154     def recv(
155         self, fd: int
156     ) -> Optional[List[Tuple[Optional[str], float, Tuple[str, int], bytes]]]:
157         clnt = self.by_fd[fd]
158         msgs = clnt.recv()
159         if msgs is None:
160             return None
161         result = []
162         for when, peeraddr, packet in msgs:
163             if proto_of_message(packet) == LOGIN.PROTO:  # Could do blindly...
164                 if clnt.imei:
165                     self.by_imei[clnt.imei] = clnt
166                 else:
167                     log.warning(
168                         "Login message from %s: %s, but client imei unfilled",
169                         peeraddr,
170                         packet,
171                     )
172             result.append((clnt.imei, when, peeraddr, packet))
173             log.debug(
174                 "Received from %s (IMEI %s): %s",
175                 peeraddr,
176                 clnt.imei,
177                 packet.hex(),
178             )
179         return result
180
181     def response(self, resp: Resp) -> None:
182         if resp.imei in self.by_imei:
183             self.by_imei[resp.imei].send(resp.packet)
184         else:
185             log.info("Not connected (IMEI %s)", resp.imei)
186
187
188 def runserver(conf: ConfigParser, handle_hibernate: bool = True) -> None:
189     # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
190     zctx = zmq.Context()  # type: ignore
191     zpub = zctx.socket(zmq.PUB)  # type: ignore
192     zpull = zctx.socket(zmq.PULL)  # type: ignore
193     oldmask = umask(0o117)
194     zpub.bind(conf.get("collector", "publishurl"))
195     zpull.bind(conf.get("collector", "listenurl"))
196     umask(oldmask)
197     tcpl = socket(AF_INET6, SOCK_STREAM)
198     tcpl.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
199     tcpl.bind(("", conf.getint("collector", "port")))
200     tcpl.listen(5)
201     tcpfd = tcpl.fileno()
202     poller = zmq.Poller()  # type: ignore
203     poller.register(zpull, flags=zmq.POLLIN)
204     poller.register(tcpfd, flags=zmq.POLLIN)
205     clients = Clients()
206     try:
207         while True:
208             tosend = []
209             topoll = []
210             tostop = []
211             events = poller.poll(1000)
212             for sk, fl in events:
213                 if sk is zpull:
214                     while True:
215                         try:
216                             msg = zpull.recv(zmq.NOBLOCK)
217                             zmsg = Resp(msg)
218                             tosend.append(zmsg)
219                         except zmq.Again:
220                             break
221                 elif sk == tcpfd:
222                     clntsock, clntaddr = tcpl.accept()
223                     clntsock.setsockopt(SOL_SOCKET, SO_KEEPALIVE, 1)
224                     topoll.append((clntsock, clntaddr))
225                 elif fl & zmq.POLLIN:
226                     received = clients.recv(sk)
227                     if received is None:
228                         log.debug("Terminal gone from fd %d", sk)
229                         tostop.append(sk)
230                     else:
231                         for imei, when, peeraddr, packet in received:
232                             proto = proto_of_message(packet)
233                             zpub.send(
234                                 Bcast(
235                                     proto=proto,
236                                     imei=imei,
237                                     when=when,
238                                     peeraddr=peeraddr,
239                                     packet=packet,
240                                 ).packed
241                             )
242                             if proto == HIBERNATION.PROTO and handle_hibernate:
243                                 log.debug(
244                                     "HIBERNATION from fd %d (IMEI %s)",
245                                     sk,
246                                     imei,
247                                 )
248                                 tostop.append(sk)
249                             respmsg = inline_response(packet)
250                             if respmsg is not None:
251                                 tosend.append(
252                                     Resp(imei=imei, when=when, packet=respmsg)
253                                 )
254                 else:
255                     log.debug("Stray event: %s on socket %s", fl, sk)
256             # poll queue consumed, make changes now
257             for zmsg in tosend:
258                 zpub.send(
259                     Bcast(
260                         is_incoming=False,
261                         proto=proto_of_message(zmsg.packet),
262                         when=zmsg.when,
263                         imei=zmsg.imei,
264                         packet=zmsg.packet,
265                     ).packed
266                 )
267                 log.debug("Sending to the client: %s", zmsg)
268                 clients.response(zmsg)
269             for fd in tostop:
270                 poller.unregister(fd)  # type: ignore
271                 clients.stop(fd)
272             for clntsock, clntaddr in topoll:
273                 fd = clients.add(clntsock, clntaddr)
274                 poller.register(fd, flags=zmq.POLLIN)
275     except KeyboardInterrupt:
276         zpub.close()
277         zpull.close()
278         zctx.destroy()  # type: ignore
279         tcpl.close()
280
281
282 if __name__.endswith("__main__"):
283     runserver(common.init(log))