socketcan 4.0.0

Linux SocketCAN library. Send and receive CAN frames via CANbus on Linux.
Documentation
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
// socketcan/src/socket.rs
//
// Implements sockets for CANbus 2.0 and FD for SocketCAN on Linux.
//
// 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.

//! Implementation of sockets for CANbus 2.0 and FD for SocketCAN on Linux.

use crate::{
    CanAddr, CanAnyFrame, CanFdFrame, CanFrame, CanRawFrame, Error, IoError, IoErrorKind, IoResult,
    Result, as_bytes, as_bytes_mut,
    frame::{AsPtr, can_frame_default, canfd_frame_default},
    id::CAN_ERR_MASK,
    timestamp::CanTimestamps,
};
pub use embedded_can::{
    self, ExtendedId, Frame as EmbeddedFrame, Id, StandardId, blocking::Can as BlockingCan,
    nb::Can as NonBlockingCan,
};
use libc::{AF_CAN, EINPROGRESS, SOL_SOCKET, canid_t, socklen_t};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use socket2::SockAddr;
use std::{
    fmt,
    io::{Read, Write},
    mem::{size_of, size_of_val, zeroed},
    os::{
        raw::{c_int, c_void},
        unix::io::{AsFd, AsRawFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd},
    },
    ptr,
    time::{Duration, SystemTime},
};

pub use libc::{
    CAN_MTU, CAN_RAW, CAN_RAW_ERR_FILTER, CAN_RAW_FD_FRAMES, CAN_RAW_FILTER, CAN_RAW_JOIN_FILTERS,
    CAN_RAW_LOOPBACK, CAN_RAW_RECV_OWN_MSGS, CANFD_MTU, SOL_CAN_BASE, SOL_CAN_RAW,
};

/// The CAN protocol numbers from `linux/can.h`, for the `protocol` argument
/// of `socket(2)`.
///
/// The socket types in this module speak [`CAN_RAW`], the only one they open.
/// The rest are re-exported for code implementing another protocol on top of
/// this crate: create the socket yourself with the protocol you want — as
/// `SOCK_DGRAM` for [`CAN_BCM`], [`CAN_ISOTP`] and [`CAN_J1939`] — and bind
/// it with [`CanAddr::into_sock_addr()`](crate::CanAddr::into_sock_addr).
/// Those sockets carry reassembled payloads, or the protocol's own message
/// structs, rather than `can_frame`s, so the frame-shaped socket types here
/// do not apply to them.
///
/// Not every number is a usable protocol. [`CAN_TP16`], [`CAN_TP20`] and
/// [`CAN_MCNET`] are reserved in the header with no in-tree implementation,
/// so `socket()` reports `EPROTONOSUPPORT` for them, and [`CAN_NPROTO`] is
/// the count of protocol numbers rather than one of them.
pub use libc::{CAN_BCM, CAN_ISOTP, CAN_J1939, CAN_MCNET, CAN_NPROTO, CAN_TP16, CAN_TP20};

/// The `setsockopt`/`getsockopt` level for J1939 socket options.
///
/// Pair it with the `SO_J1939_*` option names from `libc` and the
/// [`SocketOptions`] methods. The option names themselves are not re-exported
/// here: they belong to the protocol, not to this crate.
pub use libc::SOL_CAN_J1939;

/// Check an error return value for timeouts.
///
/// Due to the fact that timeouts are reported as errors, calling `read_frame`
/// on a socket with a timeout that does not receive a frame in time will
/// result in an error being returned. This trait adds a `should_retry` method
/// to `Error` and `Result` to check for this condition.
pub trait ShouldRetry {
    /// Check for timeout
    ///
    /// If `true`, the error is probably due to a timeout.
    fn should_retry(&self) -> bool;
}

impl ShouldRetry for IoError {
    fn should_retry(&self) -> bool {
        // EAGAIN, EWOULDBLOCK and EINPROGRESS are the three codes that can
        // come back when a timeout occurs. The stdlib maps the first two onto
        // `WouldBlock`, but EINPROGRESS has no `ErrorKind` this crate can name:
        // it decodes to `ErrorKind::InProgress`, which is still unstable. So
        // that one is matched on the errno itself rather than on the kind.
        self.kind() == IoErrorKind::WouldBlock
            || matches!(self.raw_os_error(), Some(errno) if errno == EINPROGRESS)
    }
}

impl<E: fmt::Debug> ShouldRetry for IoResult<E> {
    fn should_retry(&self) -> bool {
        match *self {
            Err(ref e) => e.should_retry(),
            _ => false,
        }
    }
}

// ===== Private local helper functions =====

/// Tries to open the CAN socket by the interface number and then vind it
/// to the address.
fn raw_open_socket(addr: &CanAddr) -> IoResult<socket2::Socket> {
    let af_can = socket2::Domain::from(AF_CAN);
    let can_raw = socket2::Protocol::from(CAN_RAW);

    let sock = socket2::Socket::new_raw(af_can, socket2::Type::RAW, Some(can_raw))?;
    sock.bind(&SockAddr::from(*addr))?;
    Ok(sock)
}

// ===== Common 'Socket' trait =====

/// Common trait for SocketCAN sockets.
///
/// Note that a socket it created by opening it, and then closed by
/// dropping it.
pub trait Socket: AsRawFd {
    /// Open a named CAN device.
    ///
    /// Usually the more common case, opens a socket can device by name, such
    /// as "can0", "vcan0", or "socan0".
    fn open(ifname: &str) -> IoResult<Self>
    where
        Self: Sized,
    {
        let addr = CanAddr::from_iface(ifname)?;
        Self::open_addr(&addr)
    }

    /// Open CAN device by interface number.
    ///
    /// Opens a CAN device by kernel interface number.
    fn open_iface(ifindex: u32) -> IoResult<Self>
    where
        Self: Sized,
    {
        let addr = CanAddr::new(ifindex);
        Self::open_addr(&addr)
    }

    /// Open a CAN socket by address.
    fn open_addr(addr: &CanAddr) -> IoResult<Self>
    where
        Self: Sized;

    /// Gets a shared reference to the underlying socket object
    fn as_raw_socket(&self) -> &socket2::Socket;

    /// Gets a mutable reference to the underlying socket object
    fn as_raw_socket_mut(&mut self) -> &mut socket2::Socket;

    /// Determines if the socket is currently in nonblocking mode.
    fn nonblocking(&self) -> IoResult<bool> {
        self.as_raw_socket().nonblocking()
    }

    /// Change socket to non-blocking mode or back to blocking mode.
    fn set_nonblocking(&self, nonblocking: bool) -> IoResult<()> {
        self.as_raw_socket().set_nonblocking(nonblocking)
    }

    /// The type of CAN frame that can be read and written by the socket.
    ///
    /// This is typically distinguished by the size of the supported frame,
    /// with the primary difference between a `CanFrame` and a `CanFdFrame`.
    type FrameType;

    /// Gets the read timeout on the socket, if any.
    fn read_timeout(&self) -> IoResult<Option<Duration>> {
        self.as_raw_socket().read_timeout()
    }

    /// Sets the read timeout on the socket
    ///
    /// For convenience, the result value can be checked using
    /// `ShouldRetry::should_retry` when a timeout is set.
    ///
    /// If the duration is set to `None` then write calls will block
    /// indefinitely.
    fn set_read_timeout<D>(&self, duration: D) -> IoResult<()>
    where
        D: Into<Option<Duration>>,
    {
        self.as_raw_socket().set_read_timeout(duration.into())
    }

    /// Gets the write timeout on the socket, if any.
    fn write_timeout(&self) -> IoResult<Option<Duration>> {
        self.as_raw_socket().write_timeout()
    }

    /// Sets the write timeout on the socket
    ///
    /// If the duration is set to `None` then write calls will block
    /// indefinitely.
    fn set_write_timeout<D>(&self, duration: D) -> IoResult<()>
    where
        D: Into<Option<Duration>>,
    {
        self.as_raw_socket().set_write_timeout(duration.into())
    }

    /// Blocking read a single can frame.
    ///
    /// Concurrent readers: each `recvmsg()` consumes one frame from the
    /// socket's kernel receive queue. If two tasks call `read_frame*` on the
    /// same socket concurrently (via shared references), each will receive a
    /// disjoint subset of frames, but no two will ever observe the same
    /// frame. The frames are not duplicated and the call is safe, but the
    /// per-reader stream is not deterministic — design with that in mind.
    fn read_frame(&self) -> IoResult<Self::FrameType>;

    /// Blocking read a single can frame with timeout.
    fn read_frame_timeout(&self, timeout: Duration) -> IoResult<Self::FrameType> {
        use nix::poll::{PollFd, PollFlags, PollTimeout, poll};
        let pollfd = PollFd::new(
            unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) },
            PollFlags::POLLIN,
        );

        match poll(
            &mut [pollfd],
            timeout.try_into().unwrap_or(PollTimeout::MAX),
        )? {
            0 => Err(IoErrorKind::TimedOut.into()),
            _ => self.read_frame(),
        }
    }

    /// Blocking read a CAN frame and its socket-layer arrival timestamp.
    ///
    /// Requires [`SocketOptions::set_recv_timestamp`] to be called with `true`
    /// before this method. Returns an `InvalidData` error if no
    /// `SO_TIMESTAMPNS` control message was delivered.
    fn read_frame_with_timestamp(&self) -> IoResult<(Self::FrameType, SystemTime)> {
        Err(IoError::from_raw_os_error(libc::ENOSYS))
    }

    /// Blocking read a CAN frame and its raw hardware clock timestamp.
    ///
    /// Requires [`SocketOptions::set_timestamping`] to be called with
    /// `SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_OPT_CMSG` (and any
    /// other desired flags) before this method. Returns an `InvalidData` error
    /// if no hardware timestamp was delivered.
    fn read_frame_with_hw_timestamp(&self) -> IoResult<(Self::FrameType, Duration)> {
        Err(IoError::from_raw_os_error(libc::ENOSYS))
    }

    /// Blocking read a CAN frame and all available timestamps.
    ///
    /// Populates whichever [`CanTimestamps`] fields correspond to the
    /// `SO_TIMESTAMPNS` and/or `SO_TIMESTAMPING` modes that were enabled on
    /// the socket before the call. Fields for disabled modes are `None`.
    fn read_frame_with_timestamps(&self) -> IoResult<(Self::FrameType, CanTimestamps)> {
        Err(IoError::from_raw_os_error(libc::ENOSYS))
    }

    /// Writes a normal CAN 2.0 frame to the socket.
    fn write_frame<F>(&self, frame: &F) -> IoResult<()>
    where
        F: Into<Self::FrameType> + AsPtr;

    /// Blocking write a single can frame, retrying until it gets sent
    /// successfully.
    fn write_frame_insist<F>(&self, frame: &F) -> IoResult<()>
    where
        F: Into<Self::FrameType> + AsPtr,
    {
        loop {
            match self.write_frame(frame) {
                Ok(v) => return Ok(v),
                Err(e) if e.should_retry() => (),
                Err(e) => return Err(e),
            }
        }
    }
}

/// Traits for setting CAN socket options.
///
/// These are blocking calls, even when implemented on asynchronous sockets.
pub trait SocketOptions: AsRawFd {
    /// Sets a socket option from raw bytes.
    ///
    /// This is the primitive the other setters go through: everything
    /// `setsockopt()` accepts is a length-counted byte buffer, whatever type
    /// the caller started from.
    ///
    /// An empty buffer sends a null pointer with a zero length, which is
    /// usually how an option is cleared.
    ///
    /// It is the caller's job to match the option's expected layout; the
    /// kernel reports `EINVAL` for a length it does not expect.
    fn set_socket_option_bytes(&self, level: c_int, name: c_int, buf: &[u8]) -> IoResult<()> {
        // A zero-length slice still has a (dangling) pointer, which the kernel
        // must not see; send a null one instead.
        let (val, len) = match buf.is_empty() {
            true => (ptr::null(), 0),
            false => (buf.as_ptr().cast::<c_void>(), buf.len() as socklen_t),
        };

        let ret = unsafe { libc::setsockopt(self.as_raw_fd(), level, name, val, len) };

        match ret {
            0 => Ok(()),
            _ => Err(IoError::last_os_error()),
        }
    }

    /// Sets a socket option that holds a single integer.
    ///
    /// The safe, non-generic setter for the case that covers most CAN
    /// options.
    fn set_socket_option_int(&self, level: c_int, name: c_int, val: c_int) -> IoResult<()> {
        self.set_socket_option_bytes(level, name, &val.to_ne_bytes())
    }

    /// Sets an option on the socket.
    ///
    /// The libc `setsockopt` function is set to set various options on a socket.
    /// `set_socket_option` offers a somewhat type-safe wrapper that does not
    /// require messing around with `*const c_void`s.
    ///
    /// A proper `std::io::Error` will be returned on failure.
    ///
    /// Example use:
    ///
    /// ```text
    /// unsafe { sock.set_socket_option(SOL_CAN_RAW, CAN_RAW_LOOPBACK, &1_i32) }
    /// ```
    ///
    /// An option that is a single integer needs none of this: reach for
    /// [`set_socket_option_int()`](Self::set_socket_option_int), which is safe.
    /// This one is for a typed value the kernel expects as a struct.
    ///
    /// # Safety
    ///
    /// The value is sent as its raw bytes, so every byte of `T` must be
    /// initialised: `T` must be a plain-data type with no padding, laid out
    /// the way the kernel expects for this option — an integer, or a
    /// `#[repr(C)]` struct of them.
    unsafe fn set_socket_option<T>(&self, level: c_int, name: c_int, val: &T) -> IoResult<()> {
        // SAFETY: the caller guarantees every byte of `T` is initialised. The
        // slice is only read, and lives no longer than the borrow of `val`.
        let buf = unsafe { as_bytes(val) };
        self.set_socket_option_bytes(level, name, buf)
    }

    /// Sets a collection of multiple socket options with one call.
    ///
    /// An empty slice clears the option.
    ///
    /// # Safety
    ///
    /// The same requirement as [`set_socket_option()`](Self::set_socket_option):
    /// every byte of `T` must be initialised, which for a slice means `T` has
    /// no padding at all.
    unsafe fn set_socket_option_mult<T>(
        &self,
        level: c_int,
        name: c_int,
        values: &[T],
    ) -> IoResult<()> {
        // SAFETY: the caller guarantees `T` has no uninitialised bytes, so the
        // whole run is readable. `size_of_val` gives its exact extent.
        let buf = unsafe {
            std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), size_of_val(values))
        };
        self.set_socket_option_bytes(level, name, buf)
    }

    /// Reads back a socket option that holds a single integer.
    ///
    /// This is the `getsockopt()` counterpart to
    /// [`set_socket_option()`](Self::set_socket_option), for the scalar case
    /// that covers nearly every CAN option — `CAN_RAW_LOOPBACK`,
    /// `CAN_RAW_RECV_OWN_MSGS`, `CAN_RAW_FD_FRAMES`, `CAN_RAW_JOIN_FILTERS`,
    /// and the J1939 options such as `SO_J1939_PROMISC`.
    ///
    /// Unlike the setter this is not generic: reading into an arbitrary `T`
    /// would mean creating one from whatever bytes the kernel wrote, which is
    /// only sound for plain-data types. Use
    /// [`get_socket_option_bytes()`](Self::get_socket_option_bytes) for an
    /// option that is a struct or an array.
    ///
    /// Returns `InvalidData` if the option turned out not to be integer-sized.
    fn get_socket_option_int(&self, level: c_int, name: c_int) -> IoResult<c_int> {
        let mut val: c_int = 0;
        let mut len = size_of::<c_int>() as socklen_t;

        let ret = unsafe {
            libc::getsockopt(
                self.as_raw_fd(),
                level,
                name,
                &mut val as *mut _ as *mut c_void,
                &mut len,
            )
        };

        if ret != 0 {
            return Err(IoError::last_os_error());
        }
        if len as usize != size_of::<c_int>() {
            return Err(IoError::new(
                IoErrorKind::InvalidData,
                format!("socket option is {len} bytes, not an integer"),
            ));
        }
        Ok(val)
    }

    /// Reads back a socket option of any size, into a caller-provided buffer.
    ///
    /// Returns the number of bytes the kernel wrote, which for a
    /// variable-length option — a filter list, say — is how the caller learns
    /// how much came back. Interpreting those bytes as a struct is left to
    /// the caller, since only it knows what the option holds.
    ///
    /// A buffer shorter than the option is not an error for every option:
    /// some truncate and report the length written, others fail with
    /// `EINVAL`. That is the kernel's behavior for the option in question,
    /// not this crate's.
    fn get_socket_option_bytes(
        &self,
        level: c_int,
        name: c_int,
        buf: &mut [u8],
    ) -> IoResult<usize> {
        let mut len = buf.len() as socklen_t;

        let ret = unsafe {
            libc::getsockopt(
                self.as_raw_fd(),
                level,
                name,
                buf.as_mut_ptr().cast::<c_void>(),
                &mut len,
            )
        };

        match ret {
            0 => Ok(len as usize),
            _ => Err(IoError::last_os_error()),
        }
    }

    /// Sets CAN ID filters on the socket.
    ///
    /// CAN packages received by SocketCAN are matched against these filters,
    /// only matching packets are returned by the interface.
    ///
    /// See [`CanFilter`] for details on how filtering works. By default a
    /// single filter matching all incoming frames is installed.
    fn set_filters<F>(&self, filters: &[F]) -> IoResult<()>
    where
        F: Into<CanFilter> + Copy,
    {
        let filters: Vec<CanFilter> = filters.iter().map(|f| (*f).into()).collect();
        // SAFETY: `CanFilter` wraps `libc::can_filter` with no padding
        unsafe { self.set_socket_option_mult(SOL_CAN_RAW, CAN_RAW_FILTER, &filters) }
    }

    /// Disable reception of CAN frames.
    ///
    /// Sets a completely empty filter; disabling all CAN frame reception.
    fn set_filter_drop_all(&self) -> IoResult<()> {
        let filters: &[CanFilter] = &[];
        // SAFETY: for an empty slice, the call sends a null ptrr with len zero.
        unsafe { self.set_socket_option_mult(SOL_CAN_RAW, CAN_RAW_FILTER, filters) }
    }

    /// Accept all frames, disabling any kind of filtering.
    ///
    /// Replace the current filter with one containing a single rule that
    /// acceps all CAN frames.
    fn set_filter_accept_all(&self) -> IoResult<()> {
        // safe unwrap: 0, 0 is a valid mask/id pair
        self.set_filters(&[(0, 0)])
    }

    /// Sets the error mask on the socket.
    ///
    /// By default (`ERR_MASK_NONE`) no error conditions are reported as
    /// special error frames by the socket. Enabling error conditions by
    /// setting `ERR_MASK_ALL` or another non-empty error mask causes the
    /// socket to receive notification about the specified conditions.
    fn set_error_filter(&self, mask: u32) -> IoResult<()> {
        // The mask is a `can_err_mask_t`, i.e. a `u32`, so it goes out as its
        // bytes rather than through the `c_int` setter and a sign-changing cast.
        self.set_socket_option_bytes(SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &mask.to_ne_bytes())
    }

    /// Reads back the error mask on the socket.
    ///
    /// Zero — `ERR_MASK_NONE` — means no error conditions are reported as
    /// error frames.
    ///
    /// Read as raw bytes rather than through
    /// [`get_socket_option_int()`](Self::get_socket_option_int) for the same
    /// reason [`set_error_filter()`](Self::set_error_filter) writes them: the
    /// mask is a `can_err_mask_t`, a `u32`, and routing it through a `c_int`
    /// would mean a sign-changing cast.
    fn error_filter(&self) -> IoResult<u32> {
        let mut buf = [0u8; size_of::<u32>()];
        let n = self.get_socket_option_bytes(SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &mut buf)?;

        if n != buf.len() {
            return Err(IoError::new(
                IoErrorKind::InvalidData,
                format!("error mask is {n} bytes, not a u32"),
            ));
        }
        Ok(u32::from_ne_bytes(buf))
    }

    /// Sets the error mask on the socket to reject all errors.
    #[inline(always)]
    fn set_error_filter_drop_all(&self) -> IoResult<()> {
        self.set_error_filter(0)
    }

    /// Sets the error mask on the socket to accept all errors.
    #[inline(always)]
    fn set_error_filter_accept_all(&self) -> IoResult<()> {
        self.set_error_filter(CAN_ERR_MASK)
    }

    /// Sets the error mask on the socket.
    ///
    /// This is another name for [`set_error_filter()`](Self::set_error_filter)
    /// — both set `CAN_RAW_ERR_FILTER` — kept because the mask spelling reads
    /// naturally alongside the `ERR_MASK_ALL` and `ERR_MASK_NONE` constants.
    #[inline]
    fn set_error_mask(&self, mask: u32) -> IoResult<()> {
        self.set_error_filter(mask)
    }

    /// Reads back the error mask on the socket.
    ///
    /// Another name for [`error_filter()`](Self::error_filter), pairing with
    /// [`set_error_mask()`](Self::set_error_mask).
    #[inline]
    fn error_mask(&self) -> IoResult<u32> {
        self.error_filter()
    }

    /// Enable or disable loopback.
    ///
    /// By default, loopback is enabled, causing other applications that open
    /// the same CAN bus to see frames emitted by different applications on
    /// the same system.
    fn set_loopback(&self, enabled: bool) -> IoResult<()> {
        let loopback = c_int::from(enabled);
        self.set_socket_option_int(SOL_CAN_RAW, CAN_RAW_LOOPBACK, loopback)
    }

    /// Determines whether loopback is enabled.
    fn loopback(&self) -> IoResult<bool> {
        Ok(self.get_socket_option_int(SOL_CAN_RAW, CAN_RAW_LOOPBACK)? != 0)
    }

    /// Enable or disable receiving of own frames.
    ///
    /// When loopback is enabled, this settings controls if CAN frames sent
    /// are received back immediately by sender. Default is off.
    fn set_recv_own_msgs(&self, enabled: bool) -> IoResult<()> {
        let recv_own_msgs = c_int::from(enabled);
        self.set_socket_option_int(SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS, recv_own_msgs)
    }

    /// Determines whether the socket receives the frames it sends.
    fn recv_own_msgs(&self) -> IoResult<bool> {
        Ok(self.get_socket_option_int(SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS)? != 0)
    }

    /// Enable or disable join filters.
    ///
    /// By default a frame is accepted if it matches any of the filters set
    /// with `set_filters`. If join filters is enabled, a frame has to match
    /// _all_ filters to be accepted.
    fn set_join_filters(&self, enabled: bool) -> IoResult<()> {
        let join_filters = c_int::from(enabled);
        self.set_socket_option_int(SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS, join_filters)
    }

    /// Determines whether a frame must match every filter, rather than any
    /// of them, to be accepted.
    fn join_filters(&self) -> IoResult<bool> {
        Ok(self.get_socket_option_int(SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS)? != 0)
    }

    /// Enable or disable `SO_TIMESTAMPNS` on the socket.
    ///
    /// When enabled, `recvmsg()` delivers a `SCM_TIMESTAMPNS` control message
    /// containing the socket-layer arrival time as a `timespec`. Call this
    /// before using [`Socket::read_frame_with_timestamp`].
    ///
    /// This option is independent of [`set_timestamping`]; both can be
    /// enabled simultaneously and the resulting timestamps land in
    /// separate fields of [`CanTimestamps`].
    ///
    /// [`set_timestamping`]: Self::set_timestamping
    /// [`CanTimestamps`]: crate::CanTimestamps
    fn set_recv_timestamp(&self, enable: bool) -> IoResult<()> {
        let val = c_int::from(enable);
        self.set_socket_option_int(SOL_SOCKET, libc::SO_TIMESTAMPNS, val)
    }

    /// Set `SO_TIMESTAMPING` flags on the socket.
    ///
    /// `flags` is a bitmask of `SOF_TIMESTAMPING_*` constants. Each
    /// timestamp source needs two flags — one to select **when** it is
    /// taken, and one to request that it be **reported** in the ancillary
    /// data:
    ///
    /// | When (selector)                  | Report (in ancillary data)            |
    /// |----------------------------------|---------------------------------------|
    /// | [`SOF_TIMESTAMPING_RX_SOFTWARE`] | [`SOF_TIMESTAMPING_SOFTWARE`]         |
    /// | [`SOF_TIMESTAMPING_RX_HARDWARE`] | [`SOF_TIMESTAMPING_RAW_HARDWARE`]     |
    ///
    /// Setting only a selector flag silently delivers no timestamps;
    /// setting only a reporter flag captures nothing to report.
    ///
    /// In addition, [`SOF_TIMESTAMPING_OPT_CMSG`] is required for RX
    /// timestamps to actually appear in the cmsg returned by `recvmsg()`
    /// on non-IP sockets (which includes CAN raw).
    ///
    /// Call this before using [`Socket::read_frame_with_timestamps`] or
    /// [`Socket::read_frame_with_hw_timestamp`].
    ///
    /// [`SOF_TIMESTAMPING_OPT_CMSG`]: crate::timestamp::SOF_TIMESTAMPING_OPT_CMSG
    /// [`SOF_TIMESTAMPING_RX_SOFTWARE`]: crate::timestamp::SOF_TIMESTAMPING_RX_SOFTWARE
    /// [`SOF_TIMESTAMPING_SOFTWARE`]: crate::timestamp::SOF_TIMESTAMPING_SOFTWARE
    /// [`SOF_TIMESTAMPING_RX_HARDWARE`]: crate::timestamp::SOF_TIMESTAMPING_RX_HARDWARE
    /// [`SOF_TIMESTAMPING_RAW_HARDWARE`]: crate::timestamp::SOF_TIMESTAMPING_RAW_HARDWARE
    fn set_timestamping(&self, flags: u32) -> IoResult<()> {
        let val = flags as c_int;
        self.set_socket_option_int(SOL_SOCKET, libc::SO_TIMESTAMPING, val)
    }
}

// ===== Private helpers =====

/// Returns true if the interface bound to `fd` reports RX hardware timestamp support.
///
/// Issues a `SIOCETHTOOL` / `ETHTOOL_GET_TS_INFO` ioctl and checks the
/// `SOF_TIMESTAMPING_RX_HARDWARE` bit.
///
/// Returns `false` on any error (unbound socket, unsupported ioctl,
/// unknown interface, etc).
fn hw_timestamps_supported(fd: RawFd) -> bool {
    use crate::timestamp::{ETHTOOL_GET_TS_INFO, EthtoolTsInfo, SOF_TIMESTAMPING_RX_HARDWARE};

    // Ioctl is u64 in glibc and i32 in musl.
    // This ensures the correct type is used for both.
    const SIOCETHTOOL: libc::Ioctl = libc::SIOCETHTOOL as libc::Ioctl;

    // Retrieve the interface index from the bound socket address.
    let ifindex = unsafe {
        let mut addr: libc::sockaddr_can = zeroed();
        let mut addrlen = size_of::<libc::sockaddr_can>() as socklen_t;
        let ret = libc::getsockname(fd, &mut addr as *mut _ as *mut libc::sockaddr, &mut addrlen);
        if ret != 0 || addr.can_ifindex <= 0 {
            return false;
        }
        addr.can_ifindex as libc::c_uint
    };

    // Convert interface index to a name string.
    let mut ifname = [0 as libc::c_char; libc::IF_NAMESIZE];
    if unsafe { libc::if_indextoname(ifindex, ifname.as_mut_ptr()) }.is_null() {
        return false;
    }

    // Query hardware timestamping capabilities via SIOCETHTOOL.
    let mut ts_info = EthtoolTsInfo {
        cmd: ETHTOOL_GET_TS_INFO,
        so_timestamping: 0,
        phc_index: 0,
        tx_types: 0,
        tx_reserved: [0; 3],
        rx_filters: 0,
        rx_reserved: [0; 3],
    };

    let ret = unsafe {
        let mut ifr: libc::ifreq = zeroed();
        ifr.ifr_name.copy_from_slice(&ifname);
        ifr.ifr_ifru.ifru_data = (&mut ts_info as *mut EthtoolTsInfo).cast();
        libc::ioctl(fd, SIOCETHTOOL, &mut ifr)
    };

    ret == 0 && ts_info.so_timestamping & SOF_TIMESTAMPING_RX_HARDWARE != 0
}

/// Size of the `recvmsg()` ancillary control buffer.
///
/// Comfortably larger than what we need today:
/// `CMSG_SPACE(sizeof(timespec))`            — `SO_TIMESTAMPNS` cmsg
/// `+ CMSG_SPACE(3 * sizeof(timespec))`      — `SO_TIMESTAMPING` cmsg
/// ≈ 80 bytes on 64-bit Linux. 256 leaves headroom for future cmsg types.
const CTRL_BUF_SIZE: usize = 256;

/// Properly-aligned backing storage for the `recvmsg()` ancillary buffer.
///
/// `CMSG_FIRSTHDR`/`CMSG_NXTHDR` interpret the buffer as a sequence of
/// `cmsghdr` structures, which require `usize` alignment on Linux. A raw
/// `[u8; N]` has alignment 1; aligning to 8 bytes satisfies the contract
/// on all supported architectures.
#[repr(C, align(8))]
struct CtrlBuf([u8; CTRL_BUF_SIZE]);

/// Issues `recvmsg()` on `fd`, writing frame bytes into `frame_buf`, and
/// parses any `SOL_SOCKET` timestamp control messages into a [`CanTimestamps`].
///
/// Returns `(bytes_received, timestamps)`. The returned byte count is the
/// *real* packet size on the wire (via `MSG_TRUNC`), even if it exceeds
/// `frame_buf.len()`; callers should compare against `CAN_MTU`/`CANFD_MTU`
/// before trusting the buffer contents. Timestamp fields are `None` when
/// the corresponding socket option was not enabled before the call.
///
/// Returns `InvalidData` if the kernel sets `MSG_CTRUNC`, indicating the
/// ancillary buffer was too small to hold all delivered cmsgs.
fn recvmsg_with_ctrl(fd: RawFd, frame_buf: &mut [u8]) -> IoResult<(usize, CanTimestamps)> {
    use crate::timestamp::{timespec_to_duration, timespec_to_system_time};

    let mut iov = libc::iovec {
        iov_base: frame_buf.as_mut_ptr() as *mut libc::c_void,
        iov_len: frame_buf.len(),
    };

    let mut ctrl = CtrlBuf([0u8; CTRL_BUF_SIZE]);
    let mut msg: libc::msghdr = unsafe { zeroed() };
    msg.msg_iov = &mut iov;
    msg.msg_iovlen = 1;
    msg.msg_control = ctrl.0.as_mut_ptr() as *mut libc::c_void;
    msg.msg_controllen = ctrl.0.len() as _;

    // MSG_TRUNC: return the real packet length even if the iov was too small,
    // so callers can distinguish classic vs. FD frames by byte count rather
    // than silently truncating an FD frame into a classic-sized buffer.
    let n = unsafe { libc::recvmsg(fd, &mut msg, libc::MSG_TRUNC) };
    if n < 0 {
        return Err(IoError::last_os_error());
    }

    if msg.msg_flags & libc::MSG_CTRUNC != 0 {
        return Err(IoError::new(
            IoErrorKind::InvalidData,
            "recvmsg ancillary control buffer overflowed (MSG_CTRUNC)",
        ));
    }

    // Minimum cmsg_len for the two payload types we accept. A shorter cmsg
    // means the payload is truncated; skip rather than reading past it.
    let ns_min = unsafe { libc::CMSG_LEN(size_of::<libc::timespec>() as u32) } as usize;
    let scm_min = unsafe { libc::CMSG_LEN((3 * size_of::<libc::timespec>()) as u32) } as usize;

    let mut ts = CanTimestamps::default();
    let mut cmsg = unsafe { libc::CMSG_FIRSTHDR(&msg) };

    while !cmsg.is_null() {
        let (level, typ, len) = unsafe {
            (
                (*cmsg).cmsg_level,
                (*cmsg).cmsg_type,
                (*cmsg).cmsg_len as usize,
            )
        };
        let data = unsafe { libc::CMSG_DATA(cmsg) };
        match (level, typ) {
            (SOL_SOCKET, libc::SO_TIMESTAMPNS) if len >= ns_min => {
                let timespec = unsafe { ptr::read_unaligned(data.cast::<libc::timespec>()) };
                ts.socket = Some(timespec_to_system_time(timespec));
            }
            (SOL_SOCKET, libc::SO_TIMESTAMPING) if len >= scm_min => {
                // scm_timestamping: [timespec; 3]
                // [0] = RX_SOFTWARE (sw), [1] deprecated (zero), [2] = HW
                let tss = unsafe { ptr::read_unaligned(data.cast::<[libc::timespec; 3]>()) };
                if tss[0].tv_sec != 0 || tss[0].tv_nsec != 0 {
                    ts.sw = Some(timespec_to_system_time(tss[0]));
                }
                if tss[2].tv_sec != 0 || tss[2].tv_nsec != 0 {
                    ts.hw = Some(timespec_to_duration(tss[2]));
                }
            }
            _ => {}
        }
        cmsg = unsafe { libc::CMSG_NXTHDR(&msg, cmsg) };
    }

    Ok((n as usize, ts))
}

// ===== CanSocket =====

/// A socket for classic CAN 2.0 devices.
///
/// This provides an interface to read and write classic CAN 2.0 frames to
/// the bus, with up to 8 bytes of data per frame. It wraps a Linux socket
/// descriptor to a Raw SocketCAN socket.
///
/// The socket is automatically closed when the object is dropped. To close
/// manually, use std::drop::Drop. Internally this is just a wrapped socket
/// (file) descriptor.
#[allow(missing_copy_implementations)]
#[derive(Debug)]
pub struct CanSocket(socket2::Socket);

impl CanSocket {
    /// Reads a low-level libc `can_frame` from the socket.
    pub fn read_raw_frame(&self) -> IoResult<libc::can_frame> {
        let mut frame = can_frame_default();
        // SAFETY: `frame` is fully zero-initialised by `can_frame_default`.
        self.as_raw_socket()
            .read_exact(unsafe { as_bytes_mut(&mut frame) })?;
        Ok(frame)
    }

    /// Returns `true` if the bound interface supports hardware receive timestamps.
    ///
    /// Returns `false` if the socket is unbound, the interface does not exist,
    /// or the driver does not implement the ethtool timestamp query.
    pub fn has_hw_timestamps(&self) -> bool {
        hw_timestamps_supported(self.as_raw_fd())
    }
}

impl Socket for CanSocket {
    /// CanSocket reads/writes classic CAN 2.0 frames.
    type FrameType = CanFrame;

    /// Opens the socket by interface index.
    fn open_addr(addr: &CanAddr) -> IoResult<Self> {
        let sock = raw_open_socket(addr)?;
        Ok(Self(sock))
    }

    /// Gets a shared reference to the underlying socket object
    fn as_raw_socket(&self) -> &socket2::Socket {
        &self.0
    }

    /// Gets a mutable reference to the underlying socket object
    fn as_raw_socket_mut(&mut self) -> &mut socket2::Socket {
        &mut self.0
    }

    /// Writes a normal CAN 2.0 frame to the socket.
    fn write_frame<F>(&self, frame: &F) -> IoResult<()>
    where
        F: Into<CanFrame> + AsPtr,
    {
        // SAFETY: the frame's inner `can_frame`/`canfd_frame` is fully
        // initialised — constructors zero the struct via `*_default()`
        // (`mem::zeroed`) before writing fields — so reading every byte
        // (including padding) is sound.
        self.as_raw_socket().write_all(unsafe { frame.as_bytes() })
    }

    /// Reads a normal CAN 2.0 frame from the socket.
    fn read_frame(&self) -> IoResult<CanFrame> {
        let frame = self.read_raw_frame()?;
        Ok(frame.into())
    }

    fn read_frame_with_timestamp(&self) -> IoResult<(CanFrame, SystemTime)> {
        let (frame, ts) = self.read_frame_with_timestamps()?;
        let timestamp = ts.socket.ok_or_else(|| {
            IoError::new(
                IoErrorKind::InvalidData,
                "no SO_TIMESTAMPNS control message received",
            )
        })?;
        Ok((frame, timestamp))
    }

    fn read_frame_with_hw_timestamp(&self) -> IoResult<(CanFrame, Duration)> {
        let (frame, ts) = self.read_frame_with_timestamps()?;
        let hw_ts = ts.hw.ok_or_else(|| {
            IoError::new(
                IoErrorKind::InvalidData,
                "no SO_TIMESTAMPING hardware timestamp received",
            )
        })?;
        Ok((frame, hw_ts))
    }

    fn read_frame_with_timestamps(&self) -> IoResult<(CanFrame, CanTimestamps)> {
        let mut frame = can_frame_default();
        // SAFETY: `frame` is fully zero-initialised by `can_frame_default`.
        let buf = unsafe { as_bytes_mut(&mut frame) };
        let (n, ts) = recvmsg_with_ctrl(self.as_raw_fd(), buf)?;
        if n != CAN_MTU {
            return Err(IoError::from(IoErrorKind::InvalidData));
        }
        Ok((CanFrame::from(frame), ts))
    }
}

// ===== embedded_can I/O traits =====

impl embedded_can::blocking::Can for CanSocket {
    type Frame = CanFrame;
    type Error = Error;

    /// Blocking call to receive the next frame from the bus.
    ///
    /// This block and wait for the next frame to be received from the bus.
    /// If an error frame is received, it will be converted to a `CanError`
    /// and returned as an error.
    fn receive(&mut self) -> Result<Self::Frame> {
        match self.read_frame() {
            Ok(CanFrame::Error(frame)) => Err(frame.into_error().into()),
            Ok(frame) => Ok(frame),
            Err(e) => Err(e.into()),
        }
    }

    /// Blocking transmit of a frame to the bus.
    fn transmit(&mut self, frame: &Self::Frame) -> Result<()> {
        self.write_frame_insist(frame)?;
        Ok(())
    }
}

impl SocketOptions for CanSocket {}

impl embedded_can::nb::Can for CanSocket {
    type Frame = CanFrame;
    type Error = Error;

    /// Non-blocking call to receive the next frame from the bus.
    ///
    /// If an error frame is received, it will be converted to a `CanError`
    /// and returned as an error.
    /// If no frame is available, it returns a `WouldBlock` error.
    fn receive(&mut self) -> nb::Result<Self::Frame, Self::Error> {
        match self.read_frame() {
            Ok(CanFrame::Error(frame)) => Err(Error::from(frame.into_error()).into()),
            Ok(frame) => Ok(frame),
            Err(err) if err.should_retry() => Err(nb::Error::WouldBlock),
            Err(err) => Err(Error::from(err).into()),
        }
    }

    /// Non-blocking transmit of a frame to the bus.
    fn transmit(&mut self, frame: &Self::Frame) -> nb::Result<Option<Self::Frame>, Self::Error> {
        match self.write_frame(frame) {
            Ok(_) => Ok(None),
            Err(err) if err.should_retry() => Err(nb::Error::WouldBlock),
            Err(err) => Err(Error::from(err).into()),
        }
    }
}

// Has no effect: #[deprecated(since = "3.1", note = "Use AsFd::as_fd() instead.")]
impl AsRawFd for CanSocket {
    fn as_raw_fd(&self) -> RawFd {
        self.0.as_raw_fd()
    }
}

impl From<OwnedFd> for CanSocket {
    fn from(fd: OwnedFd) -> Self {
        Self(socket2::Socket::from(fd))
    }
}

impl IntoRawFd for CanSocket {
    fn into_raw_fd(self) -> RawFd {
        self.0.into_raw_fd()
    }
}

impl AsFd for CanSocket {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.0.as_fd()
    }
}

impl Read for CanSocket {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        self.0.read(buf)
    }
}

impl Write for CanSocket {
    fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
        self.0.write(buf)
    }

    fn flush(&mut self) -> IoResult<()> {
        self.0.flush()
    }
}

// ===== CanFdSocket =====

/// A socket for CAN FD devices.
///
/// This can transmit and receive CAN 2.0 frames with up to 8-bytes of data,
/// or CAN Flexible Data (FD) frames with up to 64-bytes of data.
#[allow(missing_copy_implementations)]
#[derive(Debug)]
pub struct CanFdSocket(socket2::Socket);

impl CanFdSocket {
    // Enable or disable FD mode on a socket.
    fn set_fd_mode(sock: socket2::Socket, enable: bool) -> IoResult<socket2::Socket> {
        let enable = enable as c_int;

        let ret = unsafe {
            libc::setsockopt(
                sock.as_raw_fd(),
                SOL_CAN_RAW,
                CAN_RAW_FD_FRAMES,
                &enable as *const _ as *const c_void,
                size_of::<c_int>() as u32,
            )
        };

        match ret {
            0 => Ok(sock),
            _ => Err(IoError::last_os_error()),
        }
    }

    // Figures out the type of frame from the MTU len read in.
    // This assumes a socket read a raw packet into a `canfd_frame` and
    // now needs to figure out which type it is by the MTU size.
    fn convert_raw_frame(mtu_len: usize, raw_frame: libc::canfd_frame) -> IoResult<CanAnyFrame> {
        match mtu_len {
            CAN_MTU => {
                let mut frame = can_frame_default();
                // SAFETY: `frame` is zero-initialised; `raw_frame` was either
                // filled by the kernel or zero-initialised before partial fill,
                // so all its bytes are valid for read.
                unsafe {
                    as_bytes_mut(&mut frame)[..CAN_MTU]
                        .copy_from_slice(&as_bytes(&raw_frame)[..CAN_MTU]);
                }
                Ok(CanFrame::from(frame).into())
            }
            CANFD_MTU => Ok(CanFdFrame::from(raw_frame).into()),
            _ => Err(IoError::from(IoErrorKind::InvalidData)),
        }
    }

    /// Returns `true` if the bound interface supports hardware receive timestamps.
    ///
    /// Returns `false` if the socket is unbound, the interface does not exist,
    /// or the driver does not implement the ethtool timestamp query.
    pub fn has_hw_timestamps(&self) -> bool {
        hw_timestamps_supported(self.as_raw_fd())
    }

    /// Reads a raw CAN frame from the socket.
    ///
    /// This might be either type of CAN frame, a classic CAN 2.0 frame
    /// or an FD frame. A read of any other length is reported as
    /// `InvalidData`.
    pub fn read_raw_frame(&self) -> IoResult<CanRawFrame> {
        let mut fdframe = canfd_frame_default();

        // SAFETY: `fdframe` is fully zero-initialised by `canfd_frame_default`.
        let buf = unsafe { as_bytes_mut(&mut fdframe) };
        match self.as_raw_socket().read(buf)? {
            // If we only get 'can_frame' number of bytes, then the return is,
            // by definition, a can_frame, so we just copy the bytes into the
            // proper type.
            CAN_MTU => {
                let mut frame = can_frame_default();
                // SAFETY: `frame` zero-initialised; `fdframe` likewise (and
                // possibly partially overwritten by the kernel above).
                unsafe {
                    as_bytes_mut(&mut frame)[..CAN_MTU]
                        .copy_from_slice(&as_bytes(&fdframe)[..CAN_MTU]);
                }
                Ok(frame.into())
            }
            CANFD_MTU => Ok(fdframe.into()),
            // The read succeeded, so `last_os_error()` would report a stale
            // errno — or none at all. The length is the whole complaint.
            _ => Err(IoError::from(IoErrorKind::InvalidData)),
        }
    }
}

impl Socket for CanFdSocket {
    /// CanFdSocket can read/write classic CAN 2.0 or FD frames.
    type FrameType = CanAnyFrame;

    /// Opens the FD socket by interface index.
    fn open_addr(addr: &CanAddr) -> IoResult<Self> {
        raw_open_socket(addr)
            .and_then(|sock| Self::set_fd_mode(sock, true))
            .map(Self)
    }

    /// Gets a shared reference to the underlying socket object
    fn as_raw_socket(&self) -> &socket2::Socket {
        &self.0
    }

    /// Gets a mutable reference to the underlying socket object
    fn as_raw_socket_mut(&mut self) -> &mut socket2::Socket {
        &mut self.0
    }

    /// Writes any type of CAN frame to the socket.
    fn write_frame<F>(&self, frame: &F) -> IoResult<()>
    where
        F: Into<Self::FrameType> + AsPtr,
    {
        // SAFETY: the frame's inner `can_frame`/`canfd_frame` is fully
        // initialised — constructors zero the struct via `*_default()`
        // (`mem::zeroed`) before writing fields — so reading every byte
        // (including padding) is sound.
        self.as_raw_socket().write_all(unsafe { frame.as_bytes() })
    }

    /// Reads either type of CAN frame from the socket.
    fn read_frame(&self) -> IoResult<CanAnyFrame> {
        let mut fdframe = canfd_frame_default();

        // SAFETY: `fdframe` is fully zero-initialised by `canfd_frame_default`.
        let n = self
            .as_raw_socket()
            .read(unsafe { as_bytes_mut(&mut fdframe) })?;
        Self::convert_raw_frame(n, fdframe)
    }

    fn read_frame_with_timestamp(&self) -> IoResult<(CanAnyFrame, SystemTime)> {
        let (frame, ts) = self.read_frame_with_timestamps()?;
        let sw_ts = ts.socket.ok_or_else(|| {
            IoError::new(
                IoErrorKind::InvalidData,
                "no SO_TIMESTAMPNS control message received",
            )
        })?;
        Ok((frame, sw_ts))
    }

    fn read_frame_with_hw_timestamp(&self) -> IoResult<(CanAnyFrame, Duration)> {
        let (frame, ts) = self.read_frame_with_timestamps()?;
        let hw_ts = ts.hw.ok_or_else(|| {
            IoError::new(
                IoErrorKind::InvalidData,
                "no SO_TIMESTAMPING hardware timestamp received",
            )
        })?;
        Ok((frame, hw_ts))
    }

    fn read_frame_with_timestamps(&self) -> IoResult<(CanAnyFrame, CanTimestamps)> {
        let mut fdframe = canfd_frame_default();
        // SAFETY: `fdframe` is fully zero-initialised by `canfd_frame_default`.
        let buf = unsafe { as_bytes_mut(&mut fdframe) };
        let (n, ts) = recvmsg_with_ctrl(self.as_raw_fd(), buf)?;
        let any_frame = Self::convert_raw_frame(n, fdframe)?;
        Ok((any_frame, ts))
    }
}

impl SocketOptions for CanFdSocket {}

impl embedded_can::blocking::Can for CanFdSocket {
    type Frame = CanAnyFrame;
    type Error = Error;

    /// Blocking call to receive the next frame from the bus.
    ///
    /// This block and wait for the next frame to be received from the bus.
    /// If an error frame is received, it will be converted to a `CanError`
    /// and returned as an error.
    fn receive(&mut self) -> Result<Self::Frame> {
        match self.read_frame() {
            Ok(CanAnyFrame::Error(frame)) => Err(frame.into_error().into()),
            Ok(frame) => Ok(frame),
            Err(e) => Err(e.into()),
        }
    }

    /// Blocking transmit of a frame to the bus.
    fn transmit(&mut self, frame: &Self::Frame) -> Result<()> {
        self.write_frame_insist(frame)?;
        Ok(())
    }
}

impl embedded_can::nb::Can for CanFdSocket {
    type Frame = CanAnyFrame;
    type Error = Error;

    /// Non-blocking call to receive the next frame from the bus.
    ///
    /// If an error frame is received, it will be converted to a `CanError`
    /// and returned as an error.
    /// If no frame is available, it returns a `WouldBlck` error.
    fn receive(&mut self) -> nb::Result<Self::Frame, Self::Error> {
        match self.read_frame() {
            Ok(CanAnyFrame::Error(frame)) => Err(Error::from(frame.into_error()).into()),
            Ok(frame) => Ok(frame),
            Err(err) if err.should_retry() => Err(nb::Error::WouldBlock),
            Err(err) => Err(Error::from(err).into()),
        }
    }

    /// Non-blocking transmit of a frame to the bus.
    fn transmit(&mut self, frame: &Self::Frame) -> nb::Result<Option<Self::Frame>, Self::Error> {
        match self.write_frame(frame) {
            Ok(_) => Ok(None),
            Err(err) if err.should_retry() => Err(nb::Error::WouldBlock),
            Err(err) => Err(Error::from(err).into()),
        }
    }
}

// Has no effect: #[deprecated(since = "3.1", note = "Use AsFd::as_fd() instead.")]
impl AsRawFd for CanFdSocket {
    fn as_raw_fd(&self) -> RawFd {
        self.0.as_raw_fd()
    }
}

impl From<OwnedFd> for CanFdSocket {
    fn from(fd: OwnedFd) -> CanFdSocket {
        Self(socket2::Socket::from(fd))
    }
}

impl TryFrom<CanSocket> for CanFdSocket {
    type Error = IoError;

    fn try_from(sock: CanSocket) -> std::result::Result<Self, Self::Error> {
        let CanSocket(sock2) = sock;
        let sock = CanFdSocket::set_fd_mode(sock2, true)?;
        Ok(CanFdSocket(sock))
    }
}

impl IntoRawFd for CanFdSocket {
    fn into_raw_fd(self) -> RawFd {
        self.0.into_raw_fd()
    }
}

impl AsFd for CanFdSocket {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.0.as_fd()
    }
}

impl Read for CanFdSocket {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        self.0.read(buf)
    }
}

impl Write for CanFdSocket {
    fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
        self.0.write(buf)
    }

    fn flush(&mut self) -> IoResult<()> {
        self.0.flush()
    }
}

// ===== CanFilter =====

/// The CAN filter defines which ID's can be accepted on a socket.
///
/// Each filter contains an internal id and mask. Packets are considered to
/// be matched by a filter if `received_id & mask == filter_id & mask` holds
/// true.
///
/// A socket can be given multiple filters, and each one can be inverted
/// ([ref](https://docs.kernel.org/networking/can.html#raw-protocol-sockets-with-can-filters-sock-raw))
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(into = "CanFilterRepr", from = "CanFilterRepr")
)]
pub struct CanFilter(libc::can_filter);

/// Serialized form of a [`CanFilter`].
///
/// [`CanFilter`] wraps the C `can_filter`, which has no serde impls, so the
/// conversion goes through this. Both directions are infallible: any pair of
/// 32-bit words is a well-formed filter, with the inverted-match flag carried
/// in the high bit of `id` exactly as the kernel expects.
#[cfg(feature = "serde")]
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct CanFilterRepr {
    /// The identifier to match, including any `CAN_INV_FILTER` bit
    pub id: canid_t,
    /// The mask selecting which identifier bits must match
    pub mask: canid_t,
}

#[cfg(feature = "serde")]
impl From<CanFilter> for CanFilterRepr {
    fn from(filter: CanFilter) -> Self {
        Self {
            id: filter.0.can_id,
            mask: filter.0.can_mask,
        }
    }
}

#[cfg(feature = "serde")]
impl From<CanFilterRepr> for CanFilter {
    fn from(repr: CanFilterRepr) -> Self {
        Self::new(repr.id, repr.mask)
    }
}

impl CanFilter {
    /// Construct a new CAN filter.
    pub fn new(id: canid_t, mask: canid_t) -> Self {
        Self(libc::can_filter {
            can_id: id,
            can_mask: mask,
        })
    }

    /// Construct a new inverted CAN filter.
    pub fn new_inverted(id: canid_t, mask: canid_t) -> Self {
        Self::new(id | libc::CAN_INV_FILTER, mask)
    }
}

impl From<libc::can_filter> for CanFilter {
    fn from(filt: libc::can_filter) -> Self {
        Self(filt)
    }
}

impl From<(u32, u32)> for CanFilter {
    fn from(filt: (u32, u32)) -> Self {
        CanFilter::new(filt.0, filt.1)
    }
}

impl AsRef<libc::can_filter> for CanFilter {
    fn as_ref(&self) -> &libc::can_filter {
        &self.0
    }
}

/////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;

    /// Every errno that means "the operation would have blocked" is a retry,
    /// including EINPROGRESS.
    ///
    /// EINPROGRESS is the interesting case: it is matched on the errno because
    /// the `ErrorKind` it decodes to (`InProgress`) is unstable, so this crate
    /// cannot name it. Testing the kind instead — as this did until it was
    /// fixed — silently stopped working when the stdlib started mapping the
    /// errno onto that kind rather than leaving it as `Other`.
    #[test]
    fn timeout_errnos_are_retried() {
        for errno in [libc::EAGAIN, libc::EWOULDBLOCK, EINPROGRESS] {
            let err = IoError::from_raw_os_error(errno);
            assert!(
                err.should_retry(),
                "errno {errno} ({err}) should be a retry, kind is {:?}",
                err.kind()
            );
            let res: IoResult<()> = Err(err);
            assert!(res.should_retry());
        }
    }

    /// A genuine failure is not a retry, whether it carries an errno or not.
    #[test]
    fn real_errors_are_not_retried() {
        for errno in [libc::EPERM, libc::ENODEV, libc::EINVAL] {
            let err = IoError::from_raw_os_error(errno);
            assert!(!err.should_retry(), "errno {errno} ({err}) is not a retry");
        }

        // No errno at all, so only the kind can be consulted.
        assert!(!IoError::from(IoErrorKind::InvalidData).should_retry());
        assert!(!IoError::new(IoErrorKind::Other, "no errno here").should_retry());

        let ok: IoResult<()> = Ok(());
        assert!(!ok.should_retry());
    }

    /// The kind path stands on its own: a `WouldBlock` synthesized without an
    /// errno still retries, which is what the async wrappers hand back.
    #[test]
    fn would_block_without_an_errno_is_retried() {
        assert!(IoError::from(IoErrorKind::WouldBlock).should_retry());
    }

    /// The option getters read back what the kernel holds, in both the
    /// scalar and the byte-buffer form, and report a failure rather than a
    /// value for an option that does not exist.
    ///
    /// `SO_TYPE` is used as the subject because every socket has it, so the
    /// test needs neither a CAN interface nor privileges. `tests/cansocket.rs`
    /// covers a real CAN option round trip on `vcan0`.
    #[test]
    fn socket_option_getters() {
        use std::os::unix::net::UnixDatagram;

        let (sock, _peer) = UnixDatagram::pair().expect("socketpair");
        let sock = CanSocket::from(OwnedFd::from(sock));

        // Scalar form.
        let typ = sock
            .get_socket_option_int(SOL_SOCKET, libc::SO_TYPE)
            .expect("SO_TYPE");
        assert_eq!(typ, libc::SOCK_DGRAM);

        // Byte form: the same option, read as its raw four bytes.
        let mut buf = [0u8; 8];
        let n = sock
            .get_socket_option_bytes(SOL_SOCKET, libc::SO_TYPE, &mut buf)
            .expect("SO_TYPE as bytes");
        assert_eq!(n, size_of::<c_int>());
        assert_eq!(
            c_int::from_ne_bytes(buf[..n].try_into().unwrap()),
            libc::SOCK_DGRAM
        );

        // A nonexistent option fails instead of returning a made-up value.
        let err = sock
            .get_socket_option_int(SOL_SOCKET, 0x7FFF)
            .expect_err("bogus option");
        assert_eq!(err.raw_os_error(), Some(libc::ENOPROTOOPT), "{err}");
    }

    /// A datagram that is neither `CAN_MTU` nor `CANFD_MTU` long is reported
    /// as `InvalidData` by both read paths.
    ///
    /// A CAN socket cannot produce such a read, so the length is driven in
    /// over a Unix datagram pair instead — enough to exercise the arm, which
    /// used to return `last_os_error()` after a *successful* read and so
    /// reported a stale errno, or `Success (os error 0)`.
    #[test]
    fn odd_read_length_is_invalid_data() {
        use std::os::unix::net::UnixDatagram;

        for _ in 0..2 {
            let (tx, rx) = UnixDatagram::pair().expect("socketpair");
            tx.send(&[0u8; 20]).expect("send");
            let sock = CanFdSocket::from(OwnedFd::from(rx));

            // `CanRawFrame` has no `Debug`, so no `expect_err()` here.
            let err = match sock.read_raw_frame() {
                Err(err) => err,
                Ok(_) => panic!("20 bytes is not a frame"),
            };
            assert_eq!(err.kind(), IoErrorKind::InvalidData, "{err}");
            assert_eq!(err.raw_os_error(), None, "should not carry an errno");
        }

        // The typed path already reported this correctly; assert it still does,
        // so the two stay in step.
        let (tx, rx) = UnixDatagram::pair().expect("socketpair");
        tx.send(&[0u8; 20]).expect("send");
        let sock = CanFdSocket::from(OwnedFd::from(rx));
        let err = sock.read_frame().expect_err("20 bytes is not a frame");
        assert_eq!(err.kind(), IoErrorKind::InvalidData, "{err}");
    }
}