diff --git a/can/interfaces/udp_multicast/bus.py b/can/interfaces/udp_multicast/bus.py index 3747f3700..cf4918eaf 100644 --- a/can/interfaces/udp_multicast/bus.py +++ b/can/interfaces/udp_multicast/bus.py @@ -131,15 +131,21 @@ def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]: if not result: return None, False - data, _, timestamp = result + data, sender_address, timestamp = result try: can_message = unpack_message( data, replace={"timestamp": timestamp}, check=True ) - except Exception as exception: - raise can.CanOperationError( - "could not unpack received message" - ) from exception + except Exception as exception: # noqa: BLE001 + # A datagram that does not decode to a valid message is bad input from the + # sender, not a fault of this bus or its socket: log it, drop it and keep + # receiving instead of letting a single malformed datagram stop reception. + log.warning( + "could not unpack received message from %s: %s", + sender_address, + exception, + ) + return None, False if self._can_protocol is not CanProtocol.CAN_FD and can_message.is_fd: return None, False diff --git a/doc/changelog.d/2173.fixed.rst b/doc/changelog.d/2173.fixed.rst new file mode 100644 index 000000000..1eeb27522 --- /dev/null +++ b/doc/changelog.d/2173.fixed.rst @@ -0,0 +1 @@ +``UdpMulticastBus`` now logs and drops a received datagram that is not a valid message, instead of raising a ``CanOperationError`` that stopped a ``Notifier``'s receive thread for good. diff --git a/test/back2back_test.py b/test/back2back_test.py index 8567f52ab..7e9290cf2 100644 --- a/test/back2back_test.py +++ b/test/back2back_test.py @@ -5,6 +5,7 @@ """ import random +import socket import unittest from multiprocessing.dummy import Pool as ThreadPool from time import sleep, time @@ -311,6 +312,17 @@ def test_unique_message_instances(self): with self.assertRaises(CanInterfaceNotImplementedError): super().test_unique_message_instances() + def test_malformed_datagram_is_dropped(self): + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + sock.sendto(b"\x00", (self.CHANNEL_2, 43113)) + sender_port = sock.getsockname()[1] + msg = can.Message(arbitration_id=0x42) + self.bus1.send(msg) + + with self.assertLogs("can.interfaces.udp_multicast.bus", "WARNING") as logs: + self._check_received_message(self.bus2.recv(self.TIMEOUT), msg) + self.assertIn(f", {sender_port})", logs.output[0]) + @unittest.skipUnless( is_msgpack_installed(raise_exception=False),