1use crate::{
15 as_bytes, as_bytes_mut,
16 frame::{can_frame_default, canfd_frame_default, AsPtr},
17 id::CAN_ERR_MASK,
18 CanAnyFrame, CanFdFrame, CanFrame, CanRawFrame, Error, IoError, IoErrorKind, IoResult, Result,
19};
20pub use embedded_can::{
21 self, blocking::Can as BlockingCan, nb::Can as NonBlockingCan, ExtendedId,
22 Frame as EmbeddedFrame, Id, StandardId,
23};
24use libc::{canid_t, socklen_t, AF_CAN, EINPROGRESS};
25use socket2::SockAddr;
26use std::{
27 fmt,
28 io::{Read, Write},
29 mem::{size_of, size_of_val},
30 os::{
31 raw::{c_int, c_void},
32 unix::io::{AsFd, AsRawFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd},
33 },
34 ptr,
35 time::Duration,
36};
37
38pub use libc::{
39 CANFD_MTU, CAN_MTU, CAN_RAW, CAN_RAW_ERR_FILTER, CAN_RAW_FD_FRAMES, CAN_RAW_FILTER,
40 CAN_RAW_JOIN_FILTERS, CAN_RAW_LOOPBACK, CAN_RAW_RECV_OWN_MSGS, SOL_CAN_BASE, SOL_CAN_RAW,
41};
42
43pub use crate::CanAddr;
45
46pub trait ShouldRetry {
53 fn should_retry(&self) -> bool;
57}
58
59impl ShouldRetry for IoError {
60 fn should_retry(&self) -> bool {
61 match self.kind() {
62 IoErrorKind::WouldBlock => true,
66 IoErrorKind::Other => {
68 matches!(self.raw_os_error(), Some(errno) if errno == EINPROGRESS)
69 }
70 _ => false,
71 }
72 }
73}
74
75impl<E: fmt::Debug> ShouldRetry for IoResult<E> {
76 fn should_retry(&self) -> bool {
77 match *self {
78 Err(ref e) => e.should_retry(),
79 _ => false,
80 }
81 }
82}
83
84fn raw_open_socket(addr: &CanAddr) -> IoResult<socket2::Socket> {
88 let af_can = socket2::Domain::from(AF_CAN);
89 let can_raw = socket2::Protocol::from(CAN_RAW);
90
91 let sock = socket2::Socket::new_raw(af_can, socket2::Type::RAW, Some(can_raw))?;
92 sock.bind(&SockAddr::from(*addr))?;
93 Ok(sock)
94}
95
96#[deprecated(since = "3.4.0", note = "Moved into `SocketOptions` trait")]
115#[inline]
116pub fn set_socket_option<T>(fd: c_int, level: c_int, name: c_int, val: &T) -> IoResult<()> {
117 let ret = unsafe {
118 libc::setsockopt(
119 fd,
120 level,
121 name,
122 val as *const _ as *const c_void,
123 size_of::<T>() as socklen_t,
124 )
125 };
126
127 match ret {
128 0 => Ok(()),
129 _ => Err(IoError::last_os_error()),
130 }
131}
132
133#[deprecated(since = "3.4.0", note = "Moved into `SocketOptions` trait")]
135pub fn set_socket_option_mult<T>(
136 fd: c_int,
137 level: c_int,
138 name: c_int,
139 values: &[T],
140) -> IoResult<()> {
141 let ret = if values.is_empty() {
142 unsafe { libc::setsockopt(fd, level, name, ptr::null(), 0) }
144 } else {
145 unsafe {
146 libc::setsockopt(
147 fd,
148 level,
149 name,
150 values.as_ptr().cast(),
151 size_of_val(values) as socklen_t,
152 )
153 }
154 };
155
156 match ret {
157 0 => Ok(()),
158 _ => Err(IoError::last_os_error()),
159 }
160}
161
162pub trait Socket: AsRawFd {
169 fn open(ifname: &str) -> IoResult<Self>
174 where
175 Self: Sized,
176 {
177 let addr = CanAddr::from_iface(ifname)?;
178 Self::open_addr(&addr)
179 }
180
181 fn open_iface(ifindex: u32) -> IoResult<Self>
185 where
186 Self: Sized,
187 {
188 let addr = CanAddr::new(ifindex);
189 Self::open_addr(&addr)
190 }
191
192 fn open_addr(addr: &CanAddr) -> IoResult<Self>
194 where
195 Self: Sized;
196
197 fn as_raw_socket(&self) -> &socket2::Socket;
199
200 fn as_raw_socket_mut(&mut self) -> &mut socket2::Socket;
202
203 fn nonblocking(&self) -> IoResult<bool> {
205 self.as_raw_socket().nonblocking()
206 }
207
208 fn set_nonblocking(&self, nonblocking: bool) -> IoResult<()> {
210 self.as_raw_socket().set_nonblocking(nonblocking)
211 }
212
213 type FrameType;
218
219 fn read_timeout(&self) -> IoResult<Option<Duration>> {
221 self.as_raw_socket().read_timeout()
222 }
223
224 fn set_read_timeout<D>(&self, duration: D) -> IoResult<()>
232 where
233 D: Into<Option<Duration>>,
234 {
235 self.as_raw_socket().set_read_timeout(duration.into())
236 }
237
238 fn write_timeout(&self) -> IoResult<Option<Duration>> {
240 self.as_raw_socket().write_timeout()
241 }
242
243 fn set_write_timeout<D>(&self, duration: D) -> IoResult<()>
248 where
249 D: Into<Option<Duration>>,
250 {
251 self.as_raw_socket().set_write_timeout(duration.into())
252 }
253
254 fn read_frame(&self) -> IoResult<Self::FrameType>;
256
257 fn read_frame_timeout(&self, timeout: Duration) -> IoResult<Self::FrameType> {
259 use nix::poll::{poll, PollFd, PollFlags, PollTimeout};
260 let pollfd = PollFd::new(
261 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) },
262 PollFlags::POLLIN,
263 );
264
265 match poll(
266 &mut [pollfd],
267 timeout.try_into().unwrap_or(PollTimeout::MAX),
268 )? {
269 0 => Err(IoErrorKind::TimedOut.into()),
270 _ => self.read_frame(),
271 }
272 }
273
274 fn write_frame<F>(&self, frame: &F) -> IoResult<()>
284 where
285 F: Into<Self::FrameType> + AsPtr;
286
287 fn write_frame_insist<F>(&self, frame: &F) -> IoResult<()>
290 where
291 F: Into<Self::FrameType> + AsPtr,
292 {
293 loop {
294 match self.write_frame(frame) {
295 Ok(v) => return Ok(v),
296 Err(e) if e.should_retry() => (),
297 Err(e) => return Err(e),
298 }
299 }
300 }
301}
302
303pub trait SocketOptions: AsRawFd {
307 fn set_socket_option<T>(&self, level: c_int, name: c_int, val: &T) -> IoResult<()> {
325 let ret = unsafe {
326 libc::setsockopt(
327 self.as_raw_fd(),
328 level,
329 name,
330 val as *const _ as *const c_void,
331 size_of::<T>() as socklen_t,
332 )
333 };
334
335 match ret {
336 0 => Ok(()),
337 _ => Err(IoError::last_os_error()),
338 }
339 }
340
341 fn set_socket_option_mult<T>(&self, level: c_int, name: c_int, values: &[T]) -> IoResult<()> {
343 let ret = if values.is_empty() {
344 unsafe { libc::setsockopt(self.as_raw_fd(), level, name, ptr::null(), 0) }
346 } else {
347 unsafe {
348 libc::setsockopt(
349 self.as_raw_fd(),
350 level,
351 name,
352 values.as_ptr().cast(),
353 size_of_val(values) as socklen_t,
354 )
355 }
356 };
357
358 match ret {
359 0 => Ok(()),
360 _ => Err(IoError::last_os_error()),
361 }
362 }
363
364 fn set_filters<F>(&self, filters: &[F]) -> IoResult<()>
372 where
373 F: Into<CanFilter> + Copy,
374 {
375 let filters: Vec<CanFilter> = filters.iter().map(|f| (*f).into()).collect();
376 self.set_socket_option_mult(SOL_CAN_RAW, CAN_RAW_FILTER, &filters)
377 }
378
379 fn set_filter_drop_all(&self) -> IoResult<()> {
383 let filters: &[CanFilter] = &[];
384 self.set_socket_option_mult(SOL_CAN_RAW, CAN_RAW_FILTER, filters)
385 }
386
387 fn set_filter_accept_all(&self) -> IoResult<()> {
392 self.set_filters(&[(0, 0)])
394 }
395
396 fn set_error_filter(&self, mask: u32) -> IoResult<()> {
403 self.set_socket_option(SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &mask)
404 }
405
406 #[inline(always)]
408 fn set_error_filter_drop_all(&self) -> IoResult<()> {
409 self.set_error_filter(0)
410 }
411
412 #[inline(always)]
414 fn set_error_filter_accept_all(&self) -> IoResult<()> {
415 self.set_error_filter(CAN_ERR_MASK)
416 }
417
418 fn set_error_mask(&self, mask: u32) -> IoResult<()> {
425 self.set_socket_option(SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &mask)
426 }
427
428 fn set_loopback(&self, enabled: bool) -> IoResult<()> {
434 let loopback = c_int::from(enabled);
435 self.set_socket_option(SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback)
436 }
437
438 fn set_recv_own_msgs(&self, enabled: bool) -> IoResult<()> {
443 let recv_own_msgs = c_int::from(enabled);
444 self.set_socket_option(SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS, &recv_own_msgs)
445 }
446
447 fn set_join_filters(&self, enabled: bool) -> IoResult<()> {
453 let join_filters = c_int::from(enabled);
454 self.set_socket_option(SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS, &join_filters)
455 }
456}
457
458#[allow(missing_copy_implementations)]
498#[derive(Debug)]
499pub struct CanSocket(socket2::Socket);
500
501impl CanSocket {
502 pub fn read_raw_frame(&self) -> IoResult<libc::can_frame> {
504 let mut frame = can_frame_default();
505 self.as_raw_socket().read_exact(as_bytes_mut(&mut frame))?;
506 Ok(frame)
507 }
508}
509
510impl Socket for CanSocket {
511 type FrameType = CanFrame;
513
514 fn open_addr(addr: &CanAddr) -> IoResult<Self> {
516 let sock = raw_open_socket(addr)?;
517 Ok(Self(sock))
518 }
519
520 fn as_raw_socket(&self) -> &socket2::Socket {
522 &self.0
523 }
524
525 fn as_raw_socket_mut(&mut self) -> &mut socket2::Socket {
527 &mut self.0
528 }
529
530 fn write_frame<F>(&self, frame: &F) -> IoResult<()>
532 where
533 F: Into<CanFrame> + AsPtr,
534 {
535 self.as_raw_socket().write_all(frame.as_bytes())
536 }
537
538 fn read_frame(&self) -> IoResult<CanFrame> {
540 let frame = self.read_raw_frame()?;
541 Ok(frame.into())
542 }
543}
544
545impl embedded_can::blocking::Can for CanSocket {
548 type Frame = CanFrame;
549 type Error = Error;
550
551 fn receive(&mut self) -> Result<Self::Frame> {
557 match self.read_frame() {
558 Ok(CanFrame::Error(frame)) => Err(frame.into_error().into()),
559 Ok(frame) => Ok(frame),
560 Err(e) => Err(e.into()),
561 }
562 }
563
564 fn transmit(&mut self, frame: &Self::Frame) -> Result<()> {
566 self.write_frame_insist(frame)?;
567 Ok(())
568 }
569}
570
571impl SocketOptions for CanSocket {}
572
573impl embedded_can::nb::Can for CanSocket {
574 type Frame = CanFrame;
575 type Error = Error;
576
577 fn receive(&mut self) -> nb::Result<Self::Frame, Self::Error> {
583 match self.read_frame() {
584 Ok(CanFrame::Error(frame)) => Err(Error::from(frame.into_error()).into()),
585 Ok(frame) => Ok(frame),
586 Err(err) if err.should_retry() => Err(nb::Error::WouldBlock),
587 Err(err) => Err(Error::from(err).into()),
588 }
589 }
590
591 fn transmit(&mut self, frame: &Self::Frame) -> nb::Result<Option<Self::Frame>, Self::Error> {
593 match self.write_frame(frame) {
594 Ok(_) => Ok(None),
595 Err(err) if err.should_retry() => Err(nb::Error::WouldBlock),
596 Err(err) => Err(Error::from(err).into()),
597 }
598 }
599}
600
601impl AsRawFd for CanSocket {
603 fn as_raw_fd(&self) -> RawFd {
604 self.0.as_raw_fd()
605 }
606}
607
608impl From<OwnedFd> for CanSocket {
609 fn from(fd: OwnedFd) -> Self {
610 Self(socket2::Socket::from(fd))
611 }
612}
613
614impl IntoRawFd for CanSocket {
615 fn into_raw_fd(self) -> RawFd {
616 self.0.into_raw_fd()
617 }
618}
619
620impl AsFd for CanSocket {
621 fn as_fd(&self) -> BorrowedFd<'_> {
622 self.0.as_fd()
623 }
624}
625
626impl Read for CanSocket {
627 fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
628 self.0.read(buf)
629 }
630}
631
632impl Write for CanSocket {
633 fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
634 self.0.write(buf)
635 }
636
637 fn flush(&mut self) -> IoResult<()> {
638 self.0.flush()
639 }
640}
641
642#[allow(missing_copy_implementations)]
649#[derive(Debug)]
650pub struct CanFdSocket(socket2::Socket);
651
652impl CanFdSocket {
653 fn set_fd_mode(sock: socket2::Socket, enable: bool) -> IoResult<socket2::Socket> {
655 let enable = enable as c_int;
656
657 let ret = unsafe {
658 libc::setsockopt(
659 sock.as_raw_fd(),
660 SOL_CAN_RAW,
661 CAN_RAW_FD_FRAMES,
662 &enable as *const _ as *const c_void,
663 size_of::<c_int>() as u32,
664 )
665 };
666
667 match ret {
668 0 => Ok(sock),
669 _ => Err(IoError::last_os_error()),
670 }
671 }
672
673 pub fn read_raw_frame(&self) -> IoResult<CanRawFrame> {
678 let mut fdframe = canfd_frame_default();
679
680 match self.as_raw_socket().read(as_bytes_mut(&mut fdframe))? {
681 CAN_MTU => {
685 let mut frame = can_frame_default();
686 as_bytes_mut(&mut frame)[..CAN_MTU].copy_from_slice(&as_bytes(&fdframe)[..CAN_MTU]);
687 Ok(frame.into())
688 }
689 CANFD_MTU => Ok(fdframe.into()),
690 _ => Err(IoError::last_os_error()),
691 }
692 }
693}
694
695impl Socket for CanFdSocket {
696 type FrameType = CanAnyFrame;
698
699 fn open_addr(addr: &CanAddr) -> IoResult<Self> {
701 raw_open_socket(addr)
702 .and_then(|sock| Self::set_fd_mode(sock, true))
703 .map(Self)
704 }
705
706 fn as_raw_socket(&self) -> &socket2::Socket {
708 &self.0
709 }
710
711 fn as_raw_socket_mut(&mut self) -> &mut socket2::Socket {
713 &mut self.0
714 }
715
716 fn write_frame<F>(&self, frame: &F) -> IoResult<()>
718 where
719 F: Into<Self::FrameType> + AsPtr,
720 {
721 self.as_raw_socket().write_all(frame.as_bytes())
722 }
723
724 fn read_frame(&self) -> IoResult<CanAnyFrame> {
726 let mut fdframe = canfd_frame_default();
727
728 match self.as_raw_socket().read(as_bytes_mut(&mut fdframe))? {
729 CAN_MTU => {
733 let mut frame = can_frame_default();
734 as_bytes_mut(&mut frame)[..CAN_MTU].copy_from_slice(&as_bytes(&fdframe)[..CAN_MTU]);
735 Ok(CanFrame::from(frame).into())
736 }
737 CANFD_MTU => Ok(CanFdFrame::from(fdframe).into()),
738 _ => Err(IoError::last_os_error()),
739 }
740 }
741}
742
743impl SocketOptions for CanFdSocket {}
744
745impl embedded_can::blocking::Can for CanFdSocket {
746 type Frame = CanAnyFrame;
747 type Error = Error;
748
749 fn receive(&mut self) -> Result<Self::Frame> {
755 match self.read_frame() {
756 Ok(CanAnyFrame::Error(frame)) => Err(frame.into_error().into()),
757 Ok(frame) => Ok(frame),
758 Err(e) => Err(e.into()),
759 }
760 }
761
762 fn transmit(&mut self, frame: &Self::Frame) -> Result<()> {
764 self.write_frame_insist(frame)?;
765 Ok(())
766 }
767}
768
769impl embedded_can::nb::Can for CanFdSocket {
770 type Frame = CanAnyFrame;
771 type Error = Error;
772
773 fn receive(&mut self) -> nb::Result<Self::Frame, Self::Error> {
779 match self.read_frame() {
780 Ok(CanAnyFrame::Error(frame)) => Err(Error::from(frame.into_error()).into()),
781 Ok(frame) => Ok(frame),
782 Err(err) if err.should_retry() => Err(nb::Error::WouldBlock),
783 Err(err) => Err(Error::from(err).into()),
784 }
785 }
786
787 fn transmit(&mut self, frame: &Self::Frame) -> nb::Result<Option<Self::Frame>, Self::Error> {
789 match self.write_frame(frame) {
790 Ok(_) => Ok(None),
791 Err(err) if err.should_retry() => Err(nb::Error::WouldBlock),
792 Err(err) => Err(Error::from(err).into()),
793 }
794 }
795}
796
797impl AsRawFd for CanFdSocket {
799 fn as_raw_fd(&self) -> RawFd {
800 self.0.as_raw_fd()
801 }
802}
803
804impl From<OwnedFd> for CanFdSocket {
805 fn from(fd: OwnedFd) -> CanFdSocket {
806 Self(socket2::Socket::from(fd))
807 }
808}
809
810impl TryFrom<CanSocket> for CanFdSocket {
811 type Error = IoError;
812
813 fn try_from(sock: CanSocket) -> std::result::Result<Self, Self::Error> {
814 let CanSocket(sock2) = sock;
815 let sock = CanFdSocket::set_fd_mode(sock2, true)?;
816 Ok(CanFdSocket(sock))
817 }
818}
819
820impl IntoRawFd for CanFdSocket {
821 fn into_raw_fd(self) -> RawFd {
822 self.0.into_raw_fd()
823 }
824}
825
826impl AsFd for CanFdSocket {
827 fn as_fd(&self) -> BorrowedFd<'_> {
828 self.0.as_fd()
829 }
830}
831
832impl Read for CanFdSocket {
833 fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
834 self.0.read(buf)
835 }
836}
837
838impl Write for CanFdSocket {
839 fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
840 self.0.write(buf)
841 }
842
843 fn flush(&mut self) -> IoResult<()> {
844 self.0.flush()
845 }
846}
847
848#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
859pub struct CanFilter(libc::can_filter);
860
861impl CanFilter {
862 pub fn new(id: canid_t, mask: canid_t) -> Self {
864 Self(libc::can_filter {
865 can_id: id,
866 can_mask: mask,
867 })
868 }
869
870 pub fn new_inverted(id: canid_t, mask: canid_t) -> Self {
872 Self::new(id | libc::CAN_INV_FILTER, mask)
873 }
874}
875
876impl From<libc::can_filter> for CanFilter {
877 fn from(filt: libc::can_filter) -> Self {
878 Self(filt)
879 }
880}
881
882impl From<(u32, u32)> for CanFilter {
883 fn from(filt: (u32, u32)) -> Self {
884 CanFilter::new(filt.0, filt.1)
885 }
886}
887
888impl AsRef<libc::can_filter> for CanFilter {
889 fn as_ref(&self) -> &libc::can_filter {
890 &self.0
891 }
892}