diff --git a/can/cli.py b/can/cli.py index f678628ba..361679e0f 100644 --- a/can/cli.py +++ b/can/cli.py @@ -5,7 +5,11 @@ import can from can.typechecking import CanFilter, TAdditionalCliArgs -from can.util import _dict2timing, cast_from_string +from can.util import _dict2timing, cast_from_string, load_config + +#: Linux ``CAN_INV_FILTER`` flag in the ``can_id`` of a filter. Only the SocketCAN +#: kernel interprets it; for every other interface it is an ordinary ``can_id`` bit. +_CAN_INV_FILTER = 0x20000000 def add_bus_arguments( @@ -199,12 +203,42 @@ def create_bus_from_namespace( config[keyword] = value try: + if any( + filt["can_id"] & _CAN_INV_FILTER for filt in config.get("can_filters", ()) + ): + _ignore_inverted_filters(config) return can.Bus(**config) except Exception as exc: err_msg = f"Unable to instantiate bus from arguments {vars(namespace)}." raise argparse.ArgumentError(None, err_msg) from exc +def _ignore_inverted_filters(config: dict[str, Any]) -> None: + """Make inverted CLI filters (``~``) harmless on interfaces + that cannot honour them. + + The inversion is encoded with ``CAN_INV_FILTER``, which only SocketCAN passes on + to the kernel. Everywhere else the filter would be read as a regular + ``can_id``/``can_mask`` pair and match only the frame it should exclude. Use a mask + of 0 there, so that the filter lets every frame through. + """ + interface = config.get("interface") or load_config( + config=config, context=config.get("config_context") + ).get("interface") + if interface == "socketcan": + return + + can.log.warning( + "Inverted filters (~) are only supported by the " + "socketcan interface and are ignored by %s.", + interface, + ) + config["can_filters"] = [ + {**filt, "can_mask": 0} if filt["can_id"] & _CAN_INV_FILTER else filt + for filt in config["can_filters"] + ] + + class _CanFilterAction(argparse.Action): def __call__( self, @@ -226,8 +260,8 @@ def __call__( can_mask = int(parts[1], base=16) elif "~" in filt: parts = filt.split("~") - can_id = int(parts[0], base=16) | 0x20000000 # CAN_INV_FILTER - can_mask = int(parts[1], base=16) & 0x20000000 # socket.CAN_ERR_FLAG + can_id = int(parts[0], base=16) | _CAN_INV_FILTER + can_mask = int(parts[1], base=16) & ~0x20000000 # ~CAN_ERR_FLAG else: raise argparse.ArgumentError(self, "Invalid filter argument") can_filters.append({"can_id": can_id, "can_mask": can_mask}) diff --git a/doc/changelog.d/2181.fixed.rst b/doc/changelog.d/2181.fixed.rst new file mode 100644 index 000000000..039868a76 --- /dev/null +++ b/doc/changelog.d/2181.fixed.rst @@ -0,0 +1 @@ +Fixed the ``~`` filter syntax of ``can.logger``, ``can.viewer`` and ``can.cli.add_bus_arguments`` dropping the mask, so an inverted filter blocked every frame on SocketCAN. The mask now keeps all bits except ``CAN_ERR_FLAG``, as in ``candump``. Other interfaces cannot invert a filter and ignore it with a warning, as before. diff --git a/test/test_cli.py b/test/test_cli.py index e4ef6016c..3d45f8509 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -2,6 +2,7 @@ import unittest from unittest.mock import patch +import can from can.cli import add_bus_arguments, create_bus_from_namespace @@ -49,9 +50,7 @@ def test_add_bus_arguments(self): self.assertEqual(parsed_args.test_can_filters[0]["can_id"], 0x100) self.assertEqual(parsed_args.test_can_filters[0]["can_mask"], 0x7FF) self.assertEqual(parsed_args.test_can_filters[1]["can_id"], 0x200 | 0x20000000) - self.assertEqual( - parsed_args.test_can_filters[1]["can_mask"], 0x7F0 & 0x20000000 - ) + self.assertEqual(parsed_args.test_can_filters[1]["can_mask"], 0x7F0) self.assertEqual(parsed_args.test_bus_kwargs["app_name"], "MyApp") self.assertEqual(parsed_args.test_bus_kwargs["serial"], 1234) @@ -93,7 +92,7 @@ def test_add_bus_arguments_no_prefix(self): self.assertEqual(parsed_args.can_filters[0]["can_id"], 0x100) self.assertEqual(parsed_args.can_filters[0]["can_mask"], 0x7FF) self.assertEqual(parsed_args.can_filters[1]["can_id"], 0x200 | 0x20000000) - self.assertEqual(parsed_args.can_filters[1]["can_mask"], 0x7F0 & 0x20000000) + self.assertEqual(parsed_args.can_filters[1]["can_mask"], 0x7F0) self.assertEqual(parsed_args.bus_kwargs["app_name"], "MyApp") self.assertEqual(parsed_args.bus_kwargs["serial"], 1234) @@ -182,3 +181,89 @@ def test_create_bus_from_namespace_no_prefix(self, mock_bus): if __name__ == "__main__": unittest.main() + + +class TestInvertedFilters(unittest.TestCase): + """``~`` is encoded with ``CAN_INV_FILTER``, which only + SocketCAN understands.""" + + @staticmethod + def _parse(interface, *filters): + parser = argparse.ArgumentParser() + add_bus_arguments(parser, filter_arg=True) + return parser.parse_args(["-i", interface, "--filter", *filters]) + + def test_mask_keeps_all_bits_but_error_flag(self): + namespace = self._parse("socketcan", "123~7FF", "123~200007FF") + + for can_filter in namespace.can_filters: + self.assertEqual(can_filter["can_id"], 0x123 | 0x20000000) + self.assertEqual(can_filter["can_mask"], 0x7FF) + + @patch("can.Bus") + def test_socketcan_gets_inverted_filter(self, mock_bus): + namespace = self._parse("socketcan", "100:7FF", "123~7FF") + + create_bus_from_namespace(namespace) + + self.assertEqual( + mock_bus.call_args.kwargs["can_filters"], + [ + {"can_id": 0x100, "can_mask": 0x7FF}, + {"can_id": 0x123 | 0x20000000, "can_mask": 0x7FF}, + ], + ) + + @patch("can.Bus") + def test_other_interface_ignores_inverted_filter(self, mock_bus): + namespace = self._parse("virtual", "100:7FF", "123~7FF") + + with self.assertLogs("can", level="WARNING") as logs: + create_bus_from_namespace(namespace) + + self.assertIn("only supported by the socketcan interface", logs.output[0]) + self.assertEqual( + mock_bus.call_args.kwargs["can_filters"], + [ + {"can_id": 0x100, "can_mask": 0x7FF}, + {"can_id": 0x123 | 0x20000000, "can_mask": 0}, + ], + ) + + @patch("can.Bus") + def test_interface_from_config_is_used(self, mock_bus): + namespace = argparse.Namespace( + can_filters=[{"can_id": 0x20000123, "can_mask": 0x7FF}] + ) + + with patch.dict("os.environ", {"CAN_INTERFACE": "socketcan"}): + create_bus_from_namespace(namespace) + self.assertEqual(mock_bus.call_args.kwargs["can_filters"][0]["can_mask"], 0x7FF) + + with ( + patch.dict("os.environ", {"CAN_INTERFACE": "virtual"}), + self.assertLogs("can", level="WARNING"), + ): + create_bus_from_namespace(namespace) + self.assertEqual(mock_bus.call_args.kwargs["can_filters"][0]["can_mask"], 0) + + def test_virtual_bus_is_not_narrowed_to_excluded_id(self): + namespace = self._parse("virtual", "123~7FF") + namespace.channel = "inverted_filter_test" + + with ( + self.assertLogs("can", level="WARNING"), + create_bus_from_namespace(namespace) as receiver, + can.Bus("inverted_filter_test", interface="virtual") as sender, + ): + for arbitration_id in (0x123, 0x456): + sender.send( + can.Message(arbitration_id=arbitration_id, is_extended_id=False) + ) + + received = { + receiver.recv(timeout=1).arbitration_id, + receiver.recv(timeout=1).arbitration_id, + } + + self.assertEqual(received, {0x123, 0x456}) diff --git a/test/test_viewer.py b/test/test_viewer.py index affa36666..993187abc 100644 --- a/test/test_viewer.py +++ b/test/test_viewer.py @@ -666,7 +666,7 @@ def test_parse_args(self): self.assertIsInstance(parsed_args.can_filters, list) self.assertIsInstance(parsed_args.can_filters[0], dict) self.assertEqual(parsed_args.can_filters[0]["can_id"], 0x100 | 0x20000000) - self.assertEqual(parsed_args.can_filters[0]["can_mask"], 0x7FF & 0x20000000) + self.assertEqual(parsed_args.can_filters[0]["can_mask"], 0x7FF) parsed_args, _ = _parse_viewer_args(["-i", "socketcan"]) self.assertEqual(parsed_args.interface, "socketcan")