diff --git a/can/interfaces/slcan.py b/can/interfaces/slcan.py index daaea17f9..8e160ce45 100644 --- a/can/interfaces/slcan.py +++ b/can/interfaces/slcan.py @@ -35,6 +35,20 @@ serial = None +def _decode_data(string: str, start: int, length: int) -> bytearray: + """Decode ``length`` data bytes from the hex digits at ``string[start:]``. + + :raises ValueError: + If the digits are not valid hex or fewer than ``length`` bytes are present. + :meth:`bytearray.fromhex` skips whitespace, so a line cut short after an + even number of digits would otherwise decode to fewer bytes without error. + """ + data = bytearray.fromhex(string[start : start + length * 2]) + if len(data) != length: + raise ValueError(f"expected {length} data bytes, got {len(data)}") + return data + + class slcanBus(BusABC): """ slcan interface @@ -282,61 +296,68 @@ def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]: else: string = self._read(timeout) - if not string: - pass - elif string[0] in ( - "T", - "x", # x is an alternative extended message identifier for CANDapter - ): - # extended frame - canId = int(string[1:9], 16) - dlc = int(string[9]) - extended = True - data = bytearray.fromhex(string[10 : 10 + dlc * 2]) - elif string[0] == "t": - # normal frame - canId = int(string[1:4], 16) - dlc = int(string[4]) - data = bytearray.fromhex(string[5 : 5 + dlc * 2]) - elif string[0] == "r": - # remote frame - canId = int(string[1:4], 16) - dlc = int(string[4]) - remote = True - elif string[0] == "R": - # remote extended frame - canId = int(string[1:9], 16) - dlc = int(string[9]) - extended = True - remote = True - elif string[0] == "d": - # FD standard frame - canId = int(string[1:4], 16) - dlc = int(string[4], 16) - isFd = True - data = bytearray.fromhex(string[5 : 5 + CAN_FD_DLC[dlc] * 2]) - elif string[0] == "D": - # FD extended frame - canId = int(string[1:9], 16) - dlc = int(string[9], 16) - extended = True - isFd = True - data = bytearray.fromhex(string[10 : 10 + CAN_FD_DLC[dlc] * 2]) - elif string[0] == "b": - # FD with bitrate switch - canId = int(string[1:4], 16) - dlc = int(string[4], 16) - isFd = True - fdBrs = True - data = bytearray.fromhex(string[5 : 5 + CAN_FD_DLC[dlc] * 2]) - elif string[0] == "B": - # FD extended with bitrate switch - canId = int(string[1:9], 16) - dlc = int(string[9], 16) - extended = True - isFd = True - fdBrs = True - data = bytearray.fromhex(string[10 : 10 + CAN_FD_DLC[dlc] * 2]) + try: + if not string: + pass + elif string[0] in ( + "T", + "x", # x is an alternative extended message identifier for CANDapter + ): + # extended frame + canId = int(string[1:9], 16) + dlc = int(string[9]) + extended = True + data = _decode_data(string, 10, dlc) + elif string[0] == "t": + # normal frame + canId = int(string[1:4], 16) + dlc = int(string[4]) + data = _decode_data(string, 5, dlc) + elif string[0] == "r": + # remote frame + canId = int(string[1:4], 16) + dlc = int(string[4]) + remote = True + elif string[0] == "R": + # remote extended frame + canId = int(string[1:9], 16) + dlc = int(string[9]) + extended = True + remote = True + elif string[0] == "d": + # FD standard frame + canId = int(string[1:4], 16) + dlc = int(string[4], 16) + isFd = True + data = _decode_data(string, 5, CAN_FD_DLC[dlc]) + elif string[0] == "D": + # FD extended frame + canId = int(string[1:9], 16) + dlc = int(string[9], 16) + extended = True + isFd = True + data = _decode_data(string, 10, CAN_FD_DLC[dlc]) + elif string[0] == "b": + # FD with bitrate switch + canId = int(string[1:4], 16) + dlc = int(string[4], 16) + isFd = True + fdBrs = True + data = _decode_data(string, 5, CAN_FD_DLC[dlc]) + elif string[0] == "B": + # FD extended with bitrate switch + canId = int(string[1:9], 16) + dlc = int(string[9], 16) + extended = True + isFd = True + fdBrs = True + data = _decode_data(string, 10, CAN_FD_DLC[dlc]) + except (IndexError, ValueError) as exception: + # A frame line that is cut short or contains invalid characters is + # corrupted serial input, not a fault of this bus: log it, drop it and + # keep receiving instead of letting one bad line stop a Notifier. + logger.warning("dropping malformed slcan frame %r: %s", string, exception) + return None, False if canId is not None: msg = Message( diff --git a/doc/changelog.d/1821.fixed.rst b/doc/changelog.d/1821.fixed.rst new file mode 100644 index 000000000..49fe12889 --- /dev/null +++ b/doc/changelog.d/1821.fixed.rst @@ -0,0 +1 @@ +``slcanBus`` now logs and drops a received frame line that is cut short or not valid, instead of raising a ``ValueError`` that stopped a ``Notifier``'s receive thread, or returning a message with fewer data bytes than its DLC. diff --git a/test/test_slcan.py b/test/test_slcan.py index b20140cc1..61d9f5be9 100644 --- a/test/test_slcan.py +++ b/test/test_slcan.py @@ -464,6 +464,28 @@ def test_partial_recv(self): msg = self.bus.recv(TIMEOUT) self.assertIsNotNone(msg) + def test_recv_malformed_frame_is_dropped(self): + valid = b"t4563112233\r" + for malformed in ( + b"t1238112233445566778\r", # 15 of 16 data digits + b"t12381\r", # 1 of 16 data digits + b"t1238112233\r", # 3 of 8 data bytes + b"T12ABCDEF8AABB\r", # 2 of 8 data bytes + b"d123F1122334455\r", # 5 of 64 data bytes + b"t12G2AA55\r", # invalid identifier + b"t123X\r", # invalid DLC + b"t123\r", # no DLC + b"R12\r", # cut short inside the identifier + ): + with self.subTest(malformed=malformed): + self.serial.set_input_buffer(malformed + valid) + with self.assertLogs("can.interfaces.slcan", "WARNING"): + msg = self.bus.recv(1) + self.assertIsNotNone(msg) + self.assertEqual(msg.arbitration_id, 0x456) + self.assertEqual(msg.dlc, 3) + self.assertSequenceEqual(msg.data, [0x11, 0x22, 0x33]) + def test_version(self): hw_ver, sw_ver = self.bus.get_version(0) self.assertEqual(b"V\r", self.serial.get_output_buffer())