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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
use crate::frame::CanFrame;
use crate::err::{CanSocketOpenError, ConstructionError};
use crate::util::{set_socket_option, set_socket_option_mult, system_time_from_timespec};
use crate::constants::*;
use libc::{socket, SOCK_RAW, close, bind, sockaddr, read,
write, SOL_SOCKET, SO_RCVTIMEO, timespec, timeval, EINPROGRESS, SO_SNDTIMEO, time_t,
suseconds_t, fcntl, F_GETFL, F_SETFL, O_NONBLOCK};
use nix::net::if_::if_nametoindex;
use std::{
os::raw::{c_int, c_short, c_void, c_uint, c_ulong},
fmt,
io,
time,
mem::size_of,
};
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
pub trait ShouldRetry {
fn should_retry(&self) -> bool;
}
impl ShouldRetry for io::Error {
fn should_retry(&self) -> bool {
match self.kind() {
io::ErrorKind::WouldBlock => true,
io::ErrorKind::Other => {
if let Some(i) = self.raw_os_error() {
i == EINPROGRESS
} else {
false
}
}
_ => false,
}
}
}
impl<E: fmt::Debug> ShouldRetry for io::Result<E> {
fn should_retry(&self) -> bool {
if let Err(ref e) = *self {
e.should_retry()
} else {
false
}
}
}
fn c_timeval_new(t: time::Duration) -> timeval {
timeval {
tv_sec: t.as_secs() as time_t,
tv_usec: t.subsec_micros() as suseconds_t,
}
}
#[derive(Debug)]
#[repr(C)]
struct CanAddr {
_af_can: c_short,
if_index: c_int,
rx_id: u32,
tx_id: u32,
}
#[derive(Debug)]
pub struct CanSocket {
fd: c_int,
}
impl CanSocket {
pub fn open(ifname: &str) -> Result<CanSocket, CanSocketOpenError> {
let if_index = if_nametoindex(ifname)?;
CanSocket::open_if(if_index)
}
pub fn open_if(if_index: c_uint) -> Result<CanSocket, CanSocketOpenError> {
let addr = CanAddr {
_af_can: AF_CAN as c_short,
if_index: if_index as c_int,
rx_id: 0,
tx_id: 0,
};
let sock_fd;
unsafe {
sock_fd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
}
if sock_fd == -1 {
return Err(CanSocketOpenError::from(io::Error::last_os_error()));
}
let bind_rv;
unsafe {
let sockaddr_ptr = &addr as *const CanAddr;
bind_rv = bind(sock_fd,
sockaddr_ptr as *const sockaddr,
size_of::<CanAddr>() as u32);
}
if bind_rv == -1 {
let e = io::Error::last_os_error();
unsafe {
close(sock_fd);
}
return Err(CanSocketOpenError::from(e));
}
Ok(CanSocket { fd: sock_fd })
}
fn close(&mut self) -> io::Result<()> {
unsafe {
let rv = close(self.fd);
if rv != -1 {
return Err(io::Error::last_os_error());
}
}
Ok(())
}
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
let oldfl = unsafe { fcntl(self.fd, F_GETFL) };
if oldfl == -1 {
return Err(io::Error::last_os_error());
}
let newfl = if nonblocking {
oldfl | O_NONBLOCK
} else {
oldfl & !O_NONBLOCK
};
let rv = unsafe { fcntl(self.fd, F_SETFL, newfl) };
if rv != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub fn set_read_timeout(&self, duration: time::Duration) -> io::Result<()> {
set_socket_option(self.fd, SOL_SOCKET, SO_RCVTIMEO, &c_timeval_new(duration))
}
pub fn set_write_timeout(&self, duration: time::Duration) -> io::Result<()> {
set_socket_option(self.fd, SOL_SOCKET, SO_SNDTIMEO, &c_timeval_new(duration))
}
pub fn read_frame(&self) -> io::Result<CanFrame> {
let mut frame = CanFrame::default();
let read_rv = unsafe {
let frame_ptr = &mut frame as *mut CanFrame;
read(self.fd, frame_ptr as *mut c_void, size_of::<CanFrame>())
};
if read_rv as usize != size_of::<CanFrame>() {
return Err(io::Error::last_os_error());
}
Ok(frame)
}
pub fn read_frame_with_timestamp(&mut self) -> io::Result<(CanFrame, time::SystemTime)> {
let frame = self.read_frame()?;
let mut ts = timespec { tv_sec: 0, tv_nsec: 0 };
let rval = unsafe {
libc::ioctl(self.fd, SIOCGSTAMPNS as c_ulong, &mut ts as *mut timespec)
};
if rval == -1 {
return Err(io::Error::last_os_error());
}
Ok((frame, system_time_from_timespec(ts)))
}
pub fn write_frame(&self, frame: &CanFrame) -> io::Result<()> {
let write_rv = unsafe {
let frame_ptr = frame as *const CanFrame;
write(self.fd, frame_ptr as *const c_void, size_of::<CanFrame>())
};
if write_rv as usize != size_of::<CanFrame>() {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub fn write_frame_insist(&self, frame: &CanFrame) -> io::Result<()> {
loop {
match self.write_frame(frame) {
Ok(v) => return Ok(v),
Err(e) => {
if !e.should_retry() {
return Err(e);
}
}
}
}
}
pub fn set_filters(&self, filters: &[CanFilter]) -> io::Result<()> {
set_socket_option_mult(self.fd, SOL_CAN_RAW, CAN_RAW_FILTER, filters)
}
#[inline]
pub fn set_error_mask(&self, mask: u32) -> io::Result<()> {
set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &mask)
}
#[inline]
pub fn set_loopback(&self, enabled: bool) -> io::Result<()> {
let loopback: c_int = if enabled { 1 } else { 0 };
set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback)
}
pub fn set_recv_own_msgs(&self, enabled: bool) -> io::Result<()> {
let recv_own_msgs: c_int = if enabled { 1 } else { 0 };
set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS, &recv_own_msgs)
}
pub fn set_join_filters(&self, enabled: bool) -> io::Result<()> {
let join_filters: c_int = if enabled { 1 } else { 0 };
set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS, &join_filters)
}
}
impl AsRawFd for CanSocket {
fn as_raw_fd(&self) -> RawFd {
self.fd
}
}
impl FromRawFd for CanSocket {
unsafe fn from_raw_fd(fd: RawFd) -> CanSocket {
CanSocket { fd, }
}
}
impl IntoRawFd for CanSocket {
fn into_raw_fd(self) -> RawFd {
self.fd
}
}
impl Drop for CanSocket {
fn drop(&mut self) {
self.close().ok();
}
}
#[derive(Debug, Copy, Clone)]
#[repr(C)]
pub struct CanFilter {
_id: u32,
_mask: u32,
}
impl CanFilter {
pub fn new(id: u32, mask: u32) -> Result<CanFilter, ConstructionError> {
Ok(CanFilter {
_id: id,
_mask: mask,
})
}
}