1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// socketcan/src/lib.rs
//
// The main lib file for the Rust SocketCAN library.
//
// This file is part of the Rust 'socketcan-rs' library.
//
// Licensed under the MIT license:
// <LICENSE or http://opensource.org/licenses/MIT>
// This file may not be copied, modified, or distributed except according
// to those terms.
//! SocketCAN support.
//!
//! The Linux kernel supports using CAN-devices through a network-like API
//! (see <https://www.kernel.org/doc/Documentation/networking/can.txt>). This
//! crate allows easy access to this functionality without having to wrestle
//! libc calls.
//!
//! # An introduction to CAN
//!
//! The CAN bus was originally designed to allow microcontrollers inside a
//! vehicle to communicate over a single shared bus. Messages called
//! *frames* are multicast to all devices on the bus.
//!
//! Every frame consists of an ID and a payload of up to 8 bytes. If two
//! devices attempt to send a frame at the same time, the device with the
//! higher ID will notice the conflict, stop sending and reattempt to sent its
//! frame in the next time slot. This means that the lower the ID, the higher
//! the priority. Since most devices have a limited buffer for outgoing frames,
//! a single device with a high priority (== low ID) can block communication
//! on that bus by sending messages too fast.
//!
//! The CAN Flexible Data-Rate (CAN FD) standard extended the data payload up to
//! 64 bytes and added the ability to increase the the bitrate for the data bit
//! in the frame.
//!
//! The Linux socketcan subsystem makes the CAN bus available as a regular
//! networking device. Opening a network interface allows an application to
//! receive all CAN messages from the bus and/or to filter for specific messages
//! based on the CAN ID field. A device can be opened multiple times, every
//! client will receive all CAN frames simultaneously.
//!
//! Similarly, CAN frames can be sent to the bus by multiple client
//! simultaneously as well.
//!
//! # Hardware and more information
//!
//! More information on CAN can be found on
//! [Wikipedia](https://en.wikipedia.org/wiki/CAN_bus).
//! When not running on an embedded platform with already integrated CAN components,
//! [Thomas Fischl's USBtin](http://www.fischl.de/usbtin/) (see
//! [section 2.4](http://www.fischl.de/usbtin/#socketcan)) is one of many ways
//! to get started.
//!
//! # RawFd and OwnedFd
//!
//! Raw access to the underlying file descriptor and construction through one
//! is available through the `AsRawFd`, `IntoRawFd` and `FromRawFd`, and
//! similar implementations.
//!
//! # Other CAN protocols: J1939, ISO-TP, BCM
//!
//! The socket types here speak `CAN_RAW`, reading and writing whole CAN
//! frames. The kernel's other CAN protocols are not frame-shaped — an ISO-TP
//! or J1939 socket carries a reassembled payload, a BCM socket its own
//! message structs — so this crate does not wrap them: a socket type built
//! around [`CanFrame`] would misread every message.
//!
//! What it does provide is the pieces a separate crate needs to implement
//! one of them:
//!
//! * [`CanAddr`] builds any `sockaddr_can`, the J1939 and ISO-TP fields
//! included, and hands it to the kernel as a `socket2::SockAddr`
//! ([`into_sock_addr()`](CanAddr::into_sock_addr)), a pointer
//! ([`as_sockaddr_ptr()`](CanAddr::as_sockaddr_ptr)) or a byte slice
//! ([`as_bytes()`](CanAddr::as_bytes)).
//! * Accessors — [`j1939_name()`](CanAddr::j1939_name),
//! [`tp_rx_id()`](CanAddr::tp_rx_id) and friends — read an address back
//! without touching the union yourself, which is what inspecting a
//! `recvfrom()` peer needs.
//! * The protocol numbers ([`CAN_J1939`](socket::CAN_J1939),
//! [`CAN_ISOTP`](socket::CAN_ISOTP), [`CAN_BCM`](socket::CAN_BCM)), the
//! [`SOL_CAN_J1939`](socket::SOL_CAN_J1939) option level, and the J1939
//! "unset" markers ([`J1939_NO_ADDR`](addr::J1939_NO_ADDR) and company).
//! * [`SocketOptions`] is implementable by your own socket type — one empty
//! `impl` given [`AsRawFd`](std::os::unix::io::AsRawFd) — for
//! `setsockopt`/`getsockopt` on the protocol's own options.
//! * [`timespec_to_system_time()`](timestamp::timespec_to_system_time) and
//! [`timespec_to_duration()`](timestamp::timespec_to_duration) convert the
//! timestamps in an `SCM_TIMESTAMPNS`/`SCM_TIMESTAMPING` control message,
//! for code running its own `recvmsg()`, into a [`CanTimestamps`].
//! * And if you implement the transport over `CAN_RAW` yourself rather than
//! using the kernel module — a common choice for J1939, since it puts the
//! segmentation under your control — then the frame, identifier, filter
//! and error-decoding types here are the whole toolkit already.
//!
//! Opening such a socket is three steps: create it with the protocol you
//! want, as a datagram socket, and bind the address.
//!
//! ```no_run
//! use socket2::{Domain, Protocol, Socket, Type};
//! use socketcan::{
//! CanAddr,
//! addr::{AF_CAN, J1939_NO_ADDR, J1939_NO_NAME, J1939_NO_PGN},
//! socket::CAN_J1939,
//! };
//!
//! # fn main() -> std::io::Result<()> {
//! let addr = CanAddr::from_iface_j1939("can0", J1939_NO_NAME, J1939_NO_PGN, J1939_NO_ADDR)?;
//!
//! let sock = Socket::new_raw(
//! Domain::from(AF_CAN),
//! Type::DGRAM,
//! Some(Protocol::from(CAN_J1939)),
//! )?;
//! sock.bind(&addr.into_sock_addr())?;
//! # Ok(())
//! # }
//! ```
//!
//! From there the protocol is yours: its socket options, its ancillary data,
//! and reads that yield payloads rather than frames.
//!
//! # Crate Features
//!
//! ### Default
//!
//! * **netlink** -
//! Whether to include programmable CAN interface configuration capabilities
//! based on netlink kernel communications. This brings in the
//! [neli](https://docs.rs/neli/latest/neli/) library and its dependencies.
//!
//! * **dump** -
//! Whether to include candump parsing capabilities.
//!
//! ### Non-default
//!
//! * **enumerate** -
//! Include the `enumerate` module which can be used to get a list of the CANbus
//! network interfaces attached to the host. This brings in the dependency for
//! [udev](https://crates.io/crates/udev)
//!
//! * **utils** -
//! Whether to build command-line utilities. This brings in additional
//! dependencies like [anyhow](https://docs.rs/anyhow/latest/anyhow/) and
//! [clap](https://docs.rs/clap/latest/clap/)
//!
//! * **tokio** -
//! Include support for async/await using [tokio](https://crates.io/crates/tokio).
//!
//! * **smol** -
//! Include support for async/await using [smol](https://crates.io/crates/smol).
//!
//! * **serde** -
//! Implement [serde](https://crates.io/crates/serde)'s `Serialize` and
//! `Deserialize` for frames, identifiers, filters, timestamps, the error
//! types, candump records, and the netlink interface configuration types.
//! Useful in particular for keeping interface configuration in a JSON or
//! TOML file.
//!
//! ### Test Features
//!
//! Additional test can be built and run, but have requirements:
//!
//! * **vcan_tests** -
//! Requires a virtual CAN interface to be installed on the host. This can be done
//! by running the `vcan.sh` script included with the crate.
//!
//! * **netlink_tests** -
//! Requires superuser privileges to run/pass.
//!
// clippy: do not warn about things like "SocketCAN" inside the docs
// Some lints
use size_of;
// Re-export the embedded_can crate so that applications can rely on
// finding the same version we use.
pub use ;
pub use ;
pub use CanAddr;
pub use CanId;
pub use ;
pub use ;
// The `SOF_TIMESTAMPING_*` flags are deliberately not re-exported here: they
// belong with the rest of the timestamping API, in `timestamp`.
pub use CanTimestamps;
pub use ;
/// Optional support for tokio runtime.
/// Optional support for smol runtime.
// Using the specific definition for 'smol'
//#[cfg(feature = "smol")]
//pub use crate::smol::*;
pub use available_interfaces;
// ===== helper functions =====
/// Reinterprets a sized value as a byte slice.
///
/// # Safety
///
/// All `size_of::<T>()` bytes of `*val` — including any padding — must be
/// initialised at the time of this call. Reading the returned slice is
/// undefined behaviour otherwise. The simplest way to satisfy this is to
/// initialise `*val` with `mem::zeroed()` (or a helper such as
/// [`can_frame_default`]/[`canfd_frame_default`]) and write only through
/// typed field accesses before calling this fn.
///
/// [`can_frame_default`]: crate::frame::can_frame_default
/// [`canfd_frame_default`]: crate::frame::canfd_frame_default
pub unsafe
/// Reinterprets a sized value as a mutable byte slice.
///
/// # Safety
///
/// Either all `size_of::<T>()` bytes of `*val` must be initialised at the
/// time of the call, OR the caller must overwrite the entire slice before
/// reading from it. Constructing the slice itself is sound for any `T`,
/// but reading uninitialised bytes through it is undefined behaviour.
pub unsafe