From f928d1232b2086fb4938c56dc0e90cba3b1feb25 Mon Sep 17 00:00:00 2001 From: "Ugur Celik (ucsurf)" <337280806+ucsurf@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:23:07 +0300 Subject: [PATCH 1/2] Log and drop malformed UDP multicast datagrams instead of raising A datagram that does not decode to a can.Message is bad input from a sender, not a bus or socket fault. Log it and keep receiving so a thread-based Notifier is not stopped. Socket, select and timestamp errors from recv() are still raised as CanOperationError. --- can/interfaces/udp_multicast/bus.py | 14 +++- ...udp-multicast-malformed-datagram.fixed.rst | 1 + test/test_udp_multicast.py | 82 +++++++++++++++++++ 3 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 doc/changelog.d/+udp-multicast-malformed-datagram.fixed.rst create mode 100644 test/test_udp_multicast.py diff --git a/can/interfaces/udp_multicast/bus.py b/can/interfaces/udp_multicast/bus.py index 3747f3700..f1ed3d69a 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 + # 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/+udp-multicast-malformed-datagram.fixed.rst b/doc/changelog.d/+udp-multicast-malformed-datagram.fixed.rst new file mode 100644 index 000000000..1eeb27522 --- /dev/null +++ b/doc/changelog.d/+udp-multicast-malformed-datagram.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/test_udp_multicast.py b/test/test_udp_multicast.py new file mode 100644 index 000000000..9cb13dea0 --- /dev/null +++ b/test/test_udp_multicast.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python + +""" +Unit tests for the udp_multicast interface that do not need a multicast socket. +The socket layer is replaced by a mock, so they run on every host. + +Run only this test: +pytest test/test_udp_multicast.py +""" + +import unittest +from unittest.mock import patch + +try: + import msgpack +except ImportError: + msgpack = None + +import can +from can.interfaces.udp_multicast import UdpMulticastBus +from can.interfaces.udp_multicast import bus as udp_multicast_bus +from can.interfaces.udp_multicast.utils import is_msgpack_installed, pack_message + + +@unittest.skipUnless( + is_msgpack_installed(raise_exception=False), + "msgpack not installed", +) +class UdpMulticastBusTestCase(unittest.TestCase): + SENDER = ("192.168.0.23", 43113) + + def setUp(self): + # replace the socket layer so that no multicast group is joined + patcher = patch.object(udp_multicast_bus, "GeneralPurposeUdpMulticastBus") + # this is the GeneralPurposeUdpMulticastBus instance that self.bus reads from + self.udp_socket = patcher.start().return_value + self.addCleanup(patcher.stop) + + self.bus = UdpMulticastBus(channel=UdpMulticastBus.DEFAULT_GROUP_IPv4) + self.addCleanup(self.bus.shutdown) + + def test_valid_message_is_received(self): + sent = can.Message(arbitration_id=0x123, data=[1, 2, 3], is_extended_id=False) + datagram = pack_message(sent) + self.udp_socket.recv.return_value = (datagram, self.SENDER, 1.5) + + msg, already_filtered = self.bus._recv_internal(0.0) + + self.assertIsInstance(msg, can.Message) + self.assertEqual(msg.arbitration_id, 0x123) + self.assertEqual(msg.data, bytearray([1, 2, 3])) + # the timestamp of the transport replaces the one packed into the datagram + self.assertEqual(msg.timestamp, 1.5) + self.assertFalse(already_filtered) + + def test_malformed_datagram_is_dropped(self): + """ + A datagram that is not a valid message is bad input from another host and must + not raise out of the bus, since that would stop a Notifier's receive thread. + """ + malformed_datagrams = ( + b"\x00", # a msgpack integer instead of a map + b"", # no data at all + msgpack.packb({"arbitration_id": -1}), # rejected by Message._check() + ) + for data in malformed_datagrams: + with self.subTest(data=data): + self.udp_socket.recv.return_value = (data, self.SENDER, 0.0) + + with self.assertLogs( + "can.interfaces.udp_multicast.bus", level="WARNING" + ) as logs: + self.assertEqual(self.bus._recv_internal(0.0), (None, False)) + + # the sender is named so that the offending host can be found + self.assertTrue(any(str(self.SENDER) in line for line in logs.output)) + + def test_socket_error_is_still_raised(self): + self.udp_socket.recv.side_effect = can.CanOperationError("socket went down") + + with self.assertRaises(can.CanOperationError): + self.bus._recv_internal(0.0) From 8da1ed731167d1b50a1a88a4f271a7792fbbe489 Mon Sep 17 00:00:00 2001 From: ucsurf Date: Tue, 1 Dec 2026 03:12:51 +0300 Subject: [PATCH 2/2] Address review: lint, back2back test, and news fragment Keep the broad except with a BLE001 noqa, test the drop through a real socket on BasicTestUdpMulticastBusIPv4, remove the mock-based unit file, and rename the news fragment to 2173.fixed.rst. --- can/interfaces/udp_multicast/bus.py | 2 +- ...rmed-datagram.fixed.rst => 2173.fixed.rst} | 0 test/back2back_test.py | 12 +++ test/test_udp_multicast.py | 82 ------------------- 4 files changed, 13 insertions(+), 83 deletions(-) rename doc/changelog.d/{+udp-multicast-malformed-datagram.fixed.rst => 2173.fixed.rst} (100%) delete mode 100644 test/test_udp_multicast.py diff --git a/can/interfaces/udp_multicast/bus.py b/can/interfaces/udp_multicast/bus.py index f1ed3d69a..cf4918eaf 100644 --- a/can/interfaces/udp_multicast/bus.py +++ b/can/interfaces/udp_multicast/bus.py @@ -136,7 +136,7 @@ def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]: can_message = unpack_message( data, replace={"timestamp": timestamp}, check=True ) - except Exception as 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. diff --git a/doc/changelog.d/+udp-multicast-malformed-datagram.fixed.rst b/doc/changelog.d/2173.fixed.rst similarity index 100% rename from doc/changelog.d/+udp-multicast-malformed-datagram.fixed.rst rename to doc/changelog.d/2173.fixed.rst 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), diff --git a/test/test_udp_multicast.py b/test/test_udp_multicast.py deleted file mode 100644 index 9cb13dea0..000000000 --- a/test/test_udp_multicast.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python - -""" -Unit tests for the udp_multicast interface that do not need a multicast socket. -The socket layer is replaced by a mock, so they run on every host. - -Run only this test: -pytest test/test_udp_multicast.py -""" - -import unittest -from unittest.mock import patch - -try: - import msgpack -except ImportError: - msgpack = None - -import can -from can.interfaces.udp_multicast import UdpMulticastBus -from can.interfaces.udp_multicast import bus as udp_multicast_bus -from can.interfaces.udp_multicast.utils import is_msgpack_installed, pack_message - - -@unittest.skipUnless( - is_msgpack_installed(raise_exception=False), - "msgpack not installed", -) -class UdpMulticastBusTestCase(unittest.TestCase): - SENDER = ("192.168.0.23", 43113) - - def setUp(self): - # replace the socket layer so that no multicast group is joined - patcher = patch.object(udp_multicast_bus, "GeneralPurposeUdpMulticastBus") - # this is the GeneralPurposeUdpMulticastBus instance that self.bus reads from - self.udp_socket = patcher.start().return_value - self.addCleanup(patcher.stop) - - self.bus = UdpMulticastBus(channel=UdpMulticastBus.DEFAULT_GROUP_IPv4) - self.addCleanup(self.bus.shutdown) - - def test_valid_message_is_received(self): - sent = can.Message(arbitration_id=0x123, data=[1, 2, 3], is_extended_id=False) - datagram = pack_message(sent) - self.udp_socket.recv.return_value = (datagram, self.SENDER, 1.5) - - msg, already_filtered = self.bus._recv_internal(0.0) - - self.assertIsInstance(msg, can.Message) - self.assertEqual(msg.arbitration_id, 0x123) - self.assertEqual(msg.data, bytearray([1, 2, 3])) - # the timestamp of the transport replaces the one packed into the datagram - self.assertEqual(msg.timestamp, 1.5) - self.assertFalse(already_filtered) - - def test_malformed_datagram_is_dropped(self): - """ - A datagram that is not a valid message is bad input from another host and must - not raise out of the bus, since that would stop a Notifier's receive thread. - """ - malformed_datagrams = ( - b"\x00", # a msgpack integer instead of a map - b"", # no data at all - msgpack.packb({"arbitration_id": -1}), # rejected by Message._check() - ) - for data in malformed_datagrams: - with self.subTest(data=data): - self.udp_socket.recv.return_value = (data, self.SENDER, 0.0) - - with self.assertLogs( - "can.interfaces.udp_multicast.bus", level="WARNING" - ) as logs: - self.assertEqual(self.bus._recv_internal(0.0), (None, False)) - - # the sender is named so that the offending host can be found - self.assertTrue(any(str(self.SENDER) in line for line in logs.output)) - - def test_socket_error_is_still_raised(self): - self.udp_socket.recv.side_effect = can.CanOperationError("socket went down") - - with self.assertRaises(can.CanOperationError): - self.bus._recv_internal(0.0)