]> www.average.org Git - loctrkd.git/blobdiff - gps303/collector.py
test: better aquisition of free ports
[loctrkd.git] / gps303 / collector.py
index c2efd79b82182e13319526a644abccb0e85071b9..36a5f8a8efd9455b047da437ed60fbfe1c9853a3 100644 (file)
@@ -3,7 +3,14 @@
 from configparser import ConfigParser
 from logging import getLogger
 from os import umask
-from socket import socket, AF_INET6, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
+from socket import (
+    socket,
+    AF_INET6,
+    SOCK_STREAM,
+    SOL_SOCKET,
+    SO_KEEPALIVE,
+    SO_REUSEADDR,
+)
 from struct import pack
 from time import time
 from typing import Dict, List, Optional, Tuple
@@ -98,11 +105,18 @@ class Client:
                 break
             packet = self.buffer[2:frameend]
             self.buffer = self.buffer[frameend + 2 :]
+            if len(packet) < 2:  # frameend comes too early
+                log.warning("Packet too short: %s", packet)
+                break
             if proto_of_message(packet) == LOGIN.PROTO:
-                self.imei = parse_message(packet).imei
-                log.info(
-                    "LOGIN from fd %d (IMEI %s)", self.sock.fileno(), self.imei
-                )
+                msg = parse_message(packet)
+                if isinstance(msg, LOGIN):  # Can be unparseable
+                    self.imei = msg.imei
+                    log.info(
+                        "LOGIN from fd %d (IMEI %s)",
+                        self.sock.fileno(),
+                        self.imei,
+                    )
             msgs.append((when, self.addr, packet))
         return msgs
 
@@ -112,7 +126,7 @@ class Client:
         except OSError as e:
             log.error(
                 "Sending to fd %d (IMEI %s): %s",
-                self.sock.fileno,
+                self.sock.fileno(),
                 self.imei,
                 e,
             )
@@ -206,6 +220,7 @@ def runserver(conf: ConfigParser, handle_hibernate: bool = True) -> None:
                             break
                 elif sk == tcpfd:
                     clntsock, clntaddr = tcpl.accept()
+                    clntsock.setsockopt(SOL_SOCKET, SO_KEEPALIVE, 1)
                     topoll.append((clntsock, clntaddr))
                 elif fl & zmq.POLLIN:
                     received = clients.recv(sk)