|
| 1 | +""" |
| 2 | +Contains handling of pcapng logging files. |
| 3 | +
|
| 4 | +pcapng file is a binary file format used for packet capture files. |
| 5 | +Spec: https://www.ietf.org/archive/id/draft-tuexen-opsawg-pcapng-03.html |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +from typing import Any, BinaryIO, Dict, Optional, Union |
| 10 | + |
| 11 | +from ..message import Message |
| 12 | +from ..socketcan_common import CAN_FRAME_HEADER_STRUCT_BE, build_can_frame |
| 13 | +from ..typechecking import Channel, StringPathLike |
| 14 | +from .generic import BinaryIOMessageWriter |
| 15 | + |
| 16 | +logger = logging.getLogger("can.io.pcapng") |
| 17 | + |
| 18 | +try: |
| 19 | + import pcapng |
| 20 | + from pcapng import blocks |
| 21 | +except ImportError: |
| 22 | + pcapng = None |
| 23 | + |
| 24 | + |
| 25 | +# https://www.tcpdump.org/linktypes.html |
| 26 | +# https://www.tcpdump.org/linktypes/LINKTYPE_CAN_SOCKETCAN.html |
| 27 | +LINKTYPE_CAN_SOCKETCAN = 227 |
| 28 | + |
| 29 | + |
| 30 | +class PcapngWriter(BinaryIOMessageWriter): |
| 31 | + """ |
| 32 | + Logs CAN data to an pcapng file supported by Wireshark and other tools. |
| 33 | + """ |
| 34 | + |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + file: Union[StringPathLike, BinaryIO], |
| 38 | + append: bool = False, |
| 39 | + tsresol: int = 9, |
| 40 | + **kwargs: Any, |
| 41 | + ) -> None: |
| 42 | + """ |
| 43 | + :param file: |
| 44 | + A path-like object or as file-like object to write to. |
| 45 | + If this is a file-like object, is has to be opened in |
| 46 | + binary write mode, not text write mode. |
| 47 | +
|
| 48 | + :param append: |
| 49 | + If True, the file will be opened in append mode. Otherwise, |
| 50 | + it will be opened in write mode. The default is False. |
| 51 | +
|
| 52 | + :param tsresol: |
| 53 | + The time resolution of the timestamps in the pcapng file, |
| 54 | + expressed as -log10(unit in seconds), |
| 55 | + e.g. 9 for nanoseconds, 6 for microseconds. |
| 56 | + The default is 9, which corresponds to nanoseconds. |
| 57 | + . |
| 58 | + """ |
| 59 | + if pcapng is None: |
| 60 | + raise NotImplementedError( |
| 61 | + "The python-pcapng package was not found. Install python-can with " |
| 62 | + "the optional dependency [pcapng] to use the PcapngWriter." |
| 63 | + ) |
| 64 | + |
| 65 | + mode = "wb+" |
| 66 | + if append: |
| 67 | + mode = "ab+" |
| 68 | + |
| 69 | + # pcapng supports concatenation, and thus append |
| 70 | + super().__init__(file, mode=mode) |
| 71 | + self._header_block = blocks.SectionHeader(endianness=">") |
| 72 | + self._writer = pcapng.FileWriter(self.file, self._header_block) |
| 73 | + self._idbs: Dict[Channel, blocks.InterfaceDescription] = {} |
| 74 | + self.tsresol = tsresol |
| 75 | + |
| 76 | + def _resolve_idb(self, channel: Optional[Channel]) -> Any: |
| 77 | + channel_name = str(channel) |
| 78 | + if channel is None: |
| 79 | + channel_name = "can0" |
| 80 | + |
| 81 | + if channel_name not in self._idbs: |
| 82 | + idb = blocks.InterfaceDescription( |
| 83 | + section=self._header_block.section, |
| 84 | + link_type=LINKTYPE_CAN_SOCKETCAN, |
| 85 | + options={ |
| 86 | + "if_name": channel_name, |
| 87 | + "if_tsresol": bytes([self.tsresol]), # nanoseconds |
| 88 | + }, |
| 89 | + endianness=">", # big |
| 90 | + ) |
| 91 | + self._header_block.register_interface(idb) |
| 92 | + self._writer.write_block(idb) |
| 93 | + self._idbs[channel_name] = idb |
| 94 | + |
| 95 | + return self._idbs[channel_name] |
| 96 | + |
| 97 | + def on_message_received(self, msg: Message) -> None: |
| 98 | + idb: blocks.InterfaceDescription = self._resolve_idb(msg.channel) |
| 99 | + timestamp_units = int(msg.timestamp * 10**self.tsresol) |
| 100 | + self._writer.write_block( |
| 101 | + blocks.EnhancedPacket( |
| 102 | + self._header_block.section, |
| 103 | + interface_id=idb.interface_id, |
| 104 | + packet_data=build_can_frame(msg, structure=CAN_FRAME_HEADER_STRUCT_BE), |
| 105 | + # timestamp (in tsresol units) = timestamp_high << 32 + timestamp_low |
| 106 | + timestamp_high=timestamp_units >> 32, |
| 107 | + timestamp_low=timestamp_units & 0xFFFFFFFF, |
| 108 | + endianness=">", # big |
| 109 | + ) |
| 110 | + ) |
0 commit comments