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
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
//! pcap is a packet capture library available on Linux, Windows and Mac. This
//! crate supports creating and configuring capture contexts, sniffing packets,
//! sending packets to interfaces, listing devices, and recording packet captures
//! to pcap-format dump files.
//!
//! # Capturing packets
//! The easiest way to open an active capture handle and begin sniffing is to
//! use `.open()` on a `Device`. You can obtain the "default" device using
//! `Device::lookup()`, or you can obtain the device(s) you need via `Device::list()`.
//!
//! ```ignore
//! use pcap::Device;
//!
//! fn main() {
//!     let mut cap = Device::lookup().unwrap().open().unwrap();
//!
//!     while let Ok(packet) = cap.next_packet() {
//!         println!("received packet! {:?}", packet);
//!     }
//! }
//! ```
//!
//! `Capture`'s `.next_packet()` will produce a `Packet` which can be dereferenced to access the
//! `&[u8]` packet contents.
//!
//! # Custom configuration
//!
//! You may want to configure the `timeout`, `snaplen` or other parameters for the capture
//! handle. In this case, use `Capture::from_device()` to obtain a `Capture<Inactive>`, and
//! proceed to configure the capture handle. When you're finished, run `.open()` on it to
//! turn it into a `Capture<Active>`.
//!
//! ```ignore
//! use pcap::{Device,Capture};
//!
//! fn main() {
//!     let main_device = Device::lookup().unwrap();
//!     let mut cap = Capture::from_device(main_device).unwrap()
//!                       .promisc(true)
//!                       .snaplen(5000)
//!                       .open().unwrap();
//!
//!     while let Ok(packet) = cap.next_packet() {
//!         println!("received packet! {:?}", packet);
//!     }
//! }
//! ```
//!
//! # Abstracting over different capture types
//!
//! You can abstract over live captures (`Capture<Active>`) and file captures
//! (`Capture<Offline>`) using generics and the [`Activated`] trait, for example:
//!
//! ```
//! use pcap::{Activated, Capture};
//!
//! fn read_packets<T: Activated>(mut capture: Capture<T>) {
//!     while let Ok(packet) = capture.next_packet() {
//!         println!("received packet! {:?}", packet);
//!     }
//! }
//! ```

use bitflags::bitflags;
use std::borrow::Borrow;
use std::convert::TryFrom;
use std::ffi::{self, CStr, CString};
use std::fmt;
use std::marker::PhantomData;
use std::mem;
use std::net::IpAddr;
use std::ops::Deref;
#[cfg(not(windows))]
use std::os::unix::io::{AsRawFd, RawFd};
use std::path::Path;
use std::ptr::{self, NonNull};
use std::slice;

use self::Error::*;

#[cfg(target_os = "windows")]
use windows_sys::Win32::Networking::WinSock::{AF_INET, AF_INET6, SOCKADDR_IN, SOCKADDR_IN6};

#[cfg(target_os = "windows")]
use windows_sys::Win32::Foundation::HANDLE;

mod raw;
#[cfg(windows)]
pub mod sendqueue;
#[cfg(feature = "capture-stream")]
mod stream;
#[cfg(feature = "capture-stream")]
pub use stream::PacketStream;

mod iterator;
pub use iterator::PacketIter;

mod codec;
pub use codec::PacketCodec;

/// An error received from pcap
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
    /// The underlying library returned invalid UTF-8
    MalformedError(std::str::Utf8Error),
    /// The underlying library returned a null string
    InvalidString,
    /// The unerlying library returned an error
    PcapError(String),
    /// The linktype was invalid or unknown
    InvalidLinktype,
    /// The timeout expired while reading from a live capture
    TimeoutExpired,
    /// No more packets to read from the file
    NoMorePackets,
    /// Must be in non-blocking mode to function
    NonNonBlock,
    /// There is not sufficent memory to create a dead capture
    InsufficientMemory,
    /// An invalid input string (internal null)
    InvalidInputString,
    /// An IO error occurred
    IoError(std::io::ErrorKind),
    #[cfg(not(windows))]
    /// An invalid raw file descriptor was provided
    InvalidRawFd,
    /// Errno error
    ErrnoError(errno::Errno),
    /// Buffer size overflows capacity
    BufferOverflow,
}

impl Error {
    unsafe fn new(ptr: *const libc::c_char) -> Error {
        match cstr_to_string(ptr) {
            Err(e) => e as Error,
            Ok(string) => PcapError(string.unwrap_or_default()),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            MalformedError(ref e) => write!(f, "libpcap returned invalid UTF-8: {}", e),
            InvalidString => write!(f, "libpcap returned a null string"),
            PcapError(ref e) => write!(f, "libpcap error: {}", e),
            InvalidLinktype => write!(f, "invalid or unknown linktype"),
            TimeoutExpired => write!(f, "timeout expired while reading from a live capture"),
            NonNonBlock => write!(f, "must be in non-blocking mode to function"),
            NoMorePackets => write!(f, "no more packets to read from the file"),
            InsufficientMemory => write!(f, "insufficient memory"),
            InvalidInputString => write!(f, "invalid input string (internal null)"),
            IoError(ref e) => write!(f, "io error occurred: {:?}", e),
            #[cfg(not(windows))]
            InvalidRawFd => write!(f, "invalid raw file descriptor provided"),
            ErrnoError(ref e) => write!(f, "libpcap os errno: {}", e),
            BufferOverflow => write!(f, "buffer size too large"),
        }
    }
}

impl std::error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            MalformedError(..) => "libpcap returned invalid UTF-8",
            PcapError(..) => "libpcap FFI error",
            InvalidString => "libpcap returned a null string",
            InvalidLinktype => "invalid or unknown linktype",
            TimeoutExpired => "timeout expired while reading from a live capture",
            NonNonBlock => "must be in non-blocking mode to function",
            NoMorePackets => "no more packets to read from the file",
            InsufficientMemory => "insufficient memory",
            InvalidInputString => "invalid input string (internal null)",
            IoError(..) => "io error occurred",
            #[cfg(not(windows))]
            InvalidRawFd => "invalid raw file descriptor provided",
            ErrnoError(..) => "internal error, providing errno",
            BufferOverflow => "buffer size too large",
        }
    }

    fn cause(&self) -> Option<&dyn std::error::Error> {
        match *self {
            MalformedError(ref e) => Some(e),
            _ => None,
        }
    }
}

impl From<ffi::NulError> for Error {
    fn from(_: ffi::NulError) -> Error {
        InvalidInputString
    }
}

impl From<std::str::Utf8Error> for Error {
    fn from(obj: std::str::Utf8Error) -> Error {
        MalformedError(obj)
    }
}

impl From<std::io::Error> for Error {
    fn from(obj: std::io::Error) -> Error {
        IoError(obj.kind())
    }
}

impl From<std::io::ErrorKind> for Error {
    fn from(obj: std::io::ErrorKind) -> Error {
        IoError(obj)
    }
}

bitflags! {
    /// Network device flags.
    pub struct IfFlags: u32 {
        /// Set if the device is a loopback interface
        const LOOPBACK = raw::PCAP_IF_LOOPBACK;
        /// Set if the device is up
        const UP = raw::PCAP_IF_UP;
        /// Set if the device is running
        const RUNNING = raw::PCAP_IF_RUNNING;
        /// Set if the device is a wireless interface; this includes IrDA as well as radio-based
        /// networks such as IEEE 802.15.4 and IEEE 802.11, so it doesn't just mean Wi-Fi
        const WIRELESS = raw::PCAP_IF_WIRELESS;
    }
}

impl From<u32> for IfFlags {
    fn from(flags: u32) -> Self {
        IfFlags::from_bits_truncate(flags)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Indication of whether the adapter is connected or not; for wireless interfaces, "connected"
/// means "associated with a network".
pub enum ConnectionStatus {
    /// It's unknown whether the adapter is connected or not
    Unknown,
    /// The adapter is connected
    Connected,
    /// The adapter is disconnected
    Disconnected,
    /// The notion of "connected" and "disconnected" don't apply to this interface; for example, it
    /// doesn't apply to a loopback device
    NotApplicable,
}

impl From<u32> for ConnectionStatus {
    fn from(flags: u32) -> Self {
        match flags & raw::PCAP_IF_CONNECTION_STATUS {
            raw::PCAP_IF_CONNECTION_STATUS_UNKNOWN => ConnectionStatus::Unknown,
            raw::PCAP_IF_CONNECTION_STATUS_CONNECTED => ConnectionStatus::Connected,
            raw::PCAP_IF_CONNECTION_STATUS_DISCONNECTED => ConnectionStatus::Disconnected,
            raw::PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE => ConnectionStatus::NotApplicable,
            // DeviceFlags::CONNECTION_STATUS should be a 2-bit mask which means that the four
            // values should cover all the possibilities.
            _ => unreachable!(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct DeviceFlags {
    pub if_flags: IfFlags,
    pub connection_status: ConnectionStatus,
}

impl From<u32> for DeviceFlags {
    fn from(flags: u32) -> Self {
        DeviceFlags {
            if_flags: flags.into(),
            connection_status: flags.into(),
        }
    }
}

impl DeviceFlags {
    pub fn empty() -> Self {
        DeviceFlags {
            if_flags: IfFlags::empty(),
            connection_status: ConnectionStatus::Unknown,
        }
    }

    pub fn contains(&self, if_flags: IfFlags) -> bool {
        self.if_flags.contains(if_flags)
    }

    pub fn is_loopback(&self) -> bool {
        self.contains(IfFlags::LOOPBACK)
    }

    pub fn is_up(&self) -> bool {
        self.contains(IfFlags::UP)
    }

    pub fn is_running(&self) -> bool {
        self.contains(IfFlags::RUNNING)
    }

    pub fn is_wireless(&self) -> bool {
        self.contains(IfFlags::WIRELESS)
    }
}

#[derive(Debug, Clone)]
/// A network device name and pcap's description of it.
pub struct Device {
    /// The name of the interface
    pub name: String,
    /// A textual description of the interface, if available
    pub desc: Option<String>,
    /// Addresses associated with this interface
    pub addresses: Vec<Address>,
    /// Interface flags
    pub flags: DeviceFlags,
}

impl Device {
    fn new(
        name: String,
        desc: Option<String>,
        addresses: Vec<Address>,
        flags: DeviceFlags,
    ) -> Device {
        Device {
            name,
            desc,
            addresses,
            flags,
        }
    }

    /// Opens a `Capture<Active>` on this device.
    pub fn open(self) -> Result<Capture<Active>, Error> {
        Capture::from_device(self)?.open()
    }

    /// Returns the default Device suitable for captures according to pcap_findalldevs,
    /// or an error from pcap. Note that there may be no suitable devices.
    pub fn lookup() -> Result<Option<Device>, Error> {
        unsafe {
            Device::with_all_devs(|all_devs| {
                let dev = all_devs;
                Ok(if !dev.is_null() {
                    Some(Device::try_from(&*dev)?)
                } else {
                    None
                })
            })
        }
    }

    /// Returns a vector of `Device`s known by pcap via pcap_findalldevs.
    pub fn list() -> Result<Vec<Device>, Error> {
        unsafe {
            Device::with_all_devs(|all_devs| {
                let mut devices = vec![];
                let mut dev = all_devs;
                while !dev.is_null() {
                    devices.push(Device::try_from(&*dev)?);
                    dev = (*dev).next;
                }
                Ok(devices)
            })
        }
    }

    unsafe fn with_all_devs<T, F>(func: F) -> Result<T, Error>
    where
        F: FnOnce(*mut raw::pcap_if_t) -> Result<T, Error>,
    {
        let all_devs = with_errbuf(|err| {
            let mut all_devs: *mut raw::pcap_if_t = ptr::null_mut();
            if raw::pcap_findalldevs(&mut all_devs, err) != 0 {
                return Err(Error::new(err));
            }
            Ok(all_devs)
        })?;
        let result = func(all_devs);
        raw::pcap_freealldevs(all_devs);
        result
    }
}

impl From<&str> for Device {
    fn from(name: &str) -> Self {
        Device::new(name.into(), None, Vec::new(), DeviceFlags::empty())
    }
}

impl TryFrom<&raw::pcap_if_t> for Device {
    type Error = Error;

    fn try_from(dev: &raw::pcap_if_t) -> Result<Self, Error> {
        Ok(Device::new(
            unsafe { cstr_to_string(dev.name)?.ok_or(InvalidString)? },
            unsafe { cstr_to_string(dev.description)? },
            unsafe { Address::new_vec(dev.addresses) },
            DeviceFlags::from(dev.flags),
        ))
    }
}

#[derive(Debug, Clone)]
/// Address information for an interface
pub struct Address {
    /// The address
    pub addr: IpAddr,
    /// Network mask for this address
    pub netmask: Option<IpAddr>,
    /// Broadcast address for this address
    pub broadcast_addr: Option<IpAddr>,
    /// P2P destination address for this address
    pub dst_addr: Option<IpAddr>,
}

impl Address {
    unsafe fn new_vec(mut ptr: *const raw::pcap_addr_t) -> Vec<Address> {
        let mut vec = Vec::new();
        while !ptr.is_null() {
            if let Some(addr) = Address::new(ptr) {
                vec.push(addr);
            }
            ptr = (*ptr).next;
        }
        vec
    }

    unsafe fn new(ptr: *const raw::pcap_addr_t) -> Option<Address> {
        Self::convert_sockaddr((*ptr).addr).map(|addr| Address {
            addr,
            netmask: Self::convert_sockaddr((*ptr).netmask),
            broadcast_addr: Self::convert_sockaddr((*ptr).broadaddr),
            dst_addr: Self::convert_sockaddr((*ptr).dstaddr),
        })
    }

    #[cfg(not(target_os = "windows"))]
    unsafe fn convert_sockaddr(ptr: *const libc::sockaddr) -> Option<IpAddr> {
        if ptr.is_null() {
            return None;
        }

        match (*ptr).sa_family as i32 {
            libc::AF_INET => {
                let ptr: *const libc::sockaddr_in = std::mem::transmute(ptr);
                Some(IpAddr::V4(u32::from_be((*ptr).sin_addr.s_addr).into()))
            }

            libc::AF_INET6 => {
                let ptr: *const libc::sockaddr_in6 = std::mem::transmute(ptr);
                Some(IpAddr::V6((*ptr).sin6_addr.s6_addr.into()))
            }

            _ => None,
        }
    }

    #[cfg(target_os = "windows")]
    unsafe fn convert_sockaddr(ptr: *const libc::sockaddr) -> Option<IpAddr> {
        if ptr.is_null() {
            return None;
        }

        match (*ptr).sa_family as u32 {
            AF_INET => {
                let ptr: *const SOCKADDR_IN = std::mem::transmute(ptr);
                let addr: [u8; 4] = ((*ptr).sin_addr.S_un.S_addr).to_ne_bytes();
                Some(IpAddr::from(addr))
            }
            AF_INET6 => {
                let ptr: *const SOCKADDR_IN6 = std::mem::transmute(ptr);
                let addr = (*ptr).sin6_addr.u.Byte;
                Some(IpAddr::from(addr))
            }

            _ => None,
        }
    }
}

/// This is a datalink link type.
///
/// As an example, `Linktype(1)` is ethernet. A full list of linktypes is available
/// [here](http://www.tcpdump.org/linktypes.html). The const bellow are not exhaustive.
/// ```rust
/// use pcap::Linktype;
///
/// let lt = Linktype(1);
/// assert_eq!(Linktype::ETHERNET, lt);
/// ```
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Linktype(pub i32);

impl Linktype {
    /// Gets the name of the link type, such as EN10MB
    pub fn get_name(&self) -> Result<String, Error> {
        unsafe { cstr_to_string(raw::pcap_datalink_val_to_name(self.0)) }?.ok_or(InvalidLinktype)
    }

    /// Gets the description of a link type.
    pub fn get_description(&self) -> Result<String, Error> {
        unsafe { cstr_to_string(raw::pcap_datalink_val_to_description(self.0)) }?
            .ok_or(InvalidLinktype)
    }

    /// Gets the linktype from a name string
    pub fn from_name(name: &str) -> Result<Linktype, Error> {
        let name = CString::new(name)?;
        let val = unsafe { raw::pcap_datalink_name_to_val(name.as_ptr()) };
        if val == -1 {
            return Err(InvalidLinktype);
        }

        Ok(Linktype(val))
    }

    pub const NULL: Self = Self(0);
    pub const ETHERNET: Self = Self(1);
    pub const AX25: Self = Self(3);
    pub const IEEE802_5: Self = Self(6);
    pub const ARCNET_BSD: Self = Self(7);
    pub const SLIP: Self = Self(8);
    pub const PPP: Self = Self(9);
    pub const FDDI: Self = Self(10);
    pub const PPP_HDLC: Self = Self(50);
    pub const PPP_ETHER: Self = Self(51);
    pub const ATM_RFC1483: Self = Self(100);
    pub const RAW: Self = Self(101);
    pub const C_HDLC: Self = Self(104);
    pub const IEEE802_11: Self = Self(105);
    pub const FRELAY: Self = Self(107);
    pub const LOOP: Self = Self(108);
    pub const LINUX_SLL: Self = Self(113);
    pub const LTALK: Self = Self(114);
    pub const PFLOG: Self = Self(117);
    pub const IEEE802_11_PRISM: Self = Self(119);
    pub const IP_OVER_FC: Self = Self(122);
    pub const SUNATM: Self = Self(123);
    pub const IEEE802_11_RADIOTAP: Self = Self(127);
    pub const ARCNET_LINUX: Self = Self(129);
    pub const APPLE_IP_OVER_IEEE1394: Self = Self(138);
    pub const MTP2_WITH_PHDR: Self = Self(139);
    pub const MTP2: Self = Self(140);
    pub const MTP3: Self = Self(141);
    pub const SCCP: Self = Self(142);
    pub const DOCSIS: Self = Self(143);
    pub const LINUX_IRDA: Self = Self(144);
    pub const USER0: Self = Self(147);
    pub const USER1: Self = Self(148);
    pub const USER2: Self = Self(149);
    pub const USER3: Self = Self(150);
    pub const USER4: Self = Self(151);
    pub const USER5: Self = Self(152);
    pub const USER6: Self = Self(153);
    pub const USER7: Self = Self(154);
    pub const USER8: Self = Self(155);
    pub const USER9: Self = Self(156);
    pub const USER10: Self = Self(157);
    pub const USER11: Self = Self(158);
    pub const USER12: Self = Self(159);
    pub const USER13: Self = Self(160);
    pub const USER14: Self = Self(161);
    pub const USER15: Self = Self(162);
    pub const IEEE802_11_AVS: Self = Self(163);
    pub const BACNET_MS_TP: Self = Self(165);
    pub const PPP_PPPD: Self = Self(166);
    pub const GPRS_LLC: Self = Self(169);
    pub const GPF_T: Self = Self(170);
    pub const GPF_F: Self = Self(171);
    pub const LINUX_LAPD: Self = Self(177);
    pub const MFR: Self = Self(182);
    pub const BLUETOOTH_HCI_H4: Self = Self(187);
    pub const USB_LINUX: Self = Self(189);
    pub const PPI: Self = Self(192);
    pub const IEEE802_15_4_WITHFCS: Self = Self(195);
    pub const SITA: Self = Self(196);
    pub const ERF: Self = Self(197);
    pub const BLUETOOTH_HCI_H4_WITH_PHDR: Self = Self(201);
    pub const AX25_KISS: Self = Self(202);
    pub const LAPD: Self = Self(203);
    pub const PPP_WITH_DIR: Self = Self(204);
    pub const C_HDLC_WITH_DIR: Self = Self(205);
    pub const FRELAY_WITH_DIR: Self = Self(206);
    pub const LAPB_WITH_DIR: Self = Self(207);
    pub const IPMB_LINUX: Self = Self(209);
    pub const IEEE802_15_4_NONASK_PHY: Self = Self(215);
    pub const USB_LINUX_MMAPPED: Self = Self(220);
    pub const FC_2: Self = Self(224);
    pub const FC_2_WITH_FRAME_DELIMS: Self = Self(225);
    pub const IPNET: Self = Self(226);
    pub const CAN_SOCKETCAN: Self = Self(227);
    pub const IPV4: Self = Self(228);
    pub const IPV6: Self = Self(229);
    pub const IEEE802_15_4_NOFCS: Self = Self(230);
    pub const DBUS: Self = Self(231);
    pub const DVB_CI: Self = Self(235);
    pub const MUX27010: Self = Self(236);
    pub const STANAG_5066_D_PDU: Self = Self(237);
    pub const NFLOG: Self = Self(239);
    pub const NETANALYZER: Self = Self(240);
    pub const NETANALYZER_TRANSPARENT: Self = Self(241);
    pub const IPOIB: Self = Self(242);
    pub const MPEG_2_TS: Self = Self(243);
    pub const NG40: Self = Self(244);
    pub const NFC_LLCP: Self = Self(245);
    pub const INFINIBAND: Self = Self(247);
    pub const SCTP: Self = Self(248);
    pub const USBPCAP: Self = Self(249);
    pub const RTAC_SERIAL: Self = Self(250);
    pub const BLUETOOTH_LE_LL: Self = Self(251);
    pub const NETLINK: Self = Self(253);
    pub const BLUETOOTH_LINUX_MONITOR: Self = Self(254);
    pub const BLUETOOTH_BREDR_BB: Self = Self(255);
    pub const BLUETOOTH_LE_LL_WITH_PHDR: Self = Self(256);
    pub const PROFIBUS_DL: Self = Self(257);
    pub const PKTAP: Self = Self(258);
    pub const EPON: Self = Self(259);
    pub const IPMI_HPM_2: Self = Self(260);
    pub const ZWAVE_R1_R2: Self = Self(261);
    pub const ZWAVE_R3: Self = Self(262);
    pub const WATTSTOPPER_DLM: Self = Self(263);
    pub const ISO_14443: Self = Self(264);
    pub const RDS: Self = Self(265);
    pub const USB_DARWIN: Self = Self(266);
    pub const SDLC: Self = Self(268);
    pub const LORATAP: Self = Self(270);
    pub const VSOCK: Self = Self(271);
    pub const NORDIC_BLE: Self = Self(272);
    pub const DOCSIS31_XRA31: Self = Self(273);
    pub const ETHERNET_MPACKET: Self = Self(274);
    pub const DISPLAYPORT_AUX: Self = Self(275);
    pub const LINUX_SLL2: Self = Self(276);
    pub const OPENVIZSLA: Self = Self(278);
    pub const EBHSCR: Self = Self(279);
    pub const VPP_DISPATCH: Self = Self(280);
    pub const DSA_TAG_BRCM: Self = Self(281);
    pub const DSA_TAG_BRCM_PREPEND: Self = Self(282);
    pub const IEEE802_15_4_TAP: Self = Self(283);
    pub const DSA_TAG_DSA: Self = Self(284);
    pub const DSA_TAG_EDSA: Self = Self(285);
    pub const ELEE: Self = Self(286);
    pub const Z_WAVE_SERIAL: Self = Self(287);
    pub const USB_2_0: Self = Self(288);
    pub const ATSC_ALP: Self = Self(289);
}

/// Represents a packet returned from pcap.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Packet<'a> {
    /// The packet header provided by pcap, including the timeval, captured length, and packet
    /// length
    pub header: &'a PacketHeader,
    /// The captured packet data
    pub data: &'a [u8],
}

impl<'a> Packet<'a> {
    #[doc(hidden)]
    pub fn new(header: &'a PacketHeader, data: &'a [u8]) -> Packet<'a> {
        Packet { header, data }
    }
}

impl<'b> Deref for Packet<'b> {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        self.data
    }
}

#[repr(C)]
#[derive(Copy, Clone)]
/// Represents a packet header provided by pcap, including the timeval, caplen and len.
pub struct PacketHeader {
    /// The time when the packet was captured
    pub ts: libc::timeval,
    /// The number of bytes of the packet that are available from the capture
    pub caplen: u32,
    /// The length of the packet, in bytes (which might be more than the number of bytes available
    /// from the capture, if the length of the packet is larger than the maximum number of bytes to
    /// capture)
    pub len: u32,
}

impl fmt::Debug for PacketHeader {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "PacketHeader {{ ts: {}.{:06}, caplen: {}, len: {} }}",
            self.ts.tv_sec, self.ts.tv_usec, self.caplen, self.len
        )
    }
}

impl PartialEq for PacketHeader {
    fn eq(&self, rhs: &PacketHeader) -> bool {
        self.ts.tv_sec == rhs.ts.tv_sec
            && self.ts.tv_usec == rhs.ts.tv_usec
            && self.caplen == rhs.caplen
            && self.len == rhs.len
    }
}

impl Eq for PacketHeader {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Packet statistics for a capture
pub struct Stat {
    /// Number of packets received
    pub received: u32,
    /// Number of packets dropped because there was no room in the operating system's buffer when
    /// they arrived, because packets weren't being read fast enough
    pub dropped: u32,
    /// Number of packets dropped by the network interface or its driver
    pub if_dropped: u32,
}

impl Stat {
    fn new(received: u32, dropped: u32, if_dropped: u32) -> Stat {
        Stat {
            received,
            dropped,
            if_dropped,
        }
    }
}

#[repr(u32)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// Timestamp resolution types
///
/// Not all systems and interfaces will necessarily support all of these resolutions when doing
/// live captures; all of them can be requested when reading a safefile.
pub enum Precision {
    /// Use timestamps with microsecond precision. This is the default.
    Micro = 0,
    /// Use timestamps with nanosecond precision.
    Nano = 1,
}

/// Phantom type representing an inactive capture handle.
pub enum Inactive {}

/// Phantom type representing an active capture handle.
pub enum Active {}

/// Phantom type representing an offline capture handle, from a pcap dump file.
/// Implements `Activated` because it behaves nearly the same as a live handle.
pub enum Offline {}

/// Phantom type representing a dead capture handle.  This can be use to create
/// new save files that are not generated from an active capture.
/// Implements `Activated` because it behaves nearly the same as a live handle.
pub enum Dead {}

/// `Capture`s can be in different states at different times, and in these states they
/// may or may not have particular capabilities. This trait is implemented by phantom
/// types which allows us to punt these invariants to the type system to avoid runtime
/// errors.
pub trait Activated: State {}

impl Activated for Active {}

impl Activated for Offline {}

impl Activated for Dead {}

/// `Capture`s can be in different states at different times, and in these states they
/// may or may not have particular capabilities. This trait is implemented by phantom
/// types which allows us to punt these invariants to the type system to avoid runtime
/// errors.
pub trait State {}

impl State for Inactive {}

impl State for Active {}

impl State for Offline {}

impl State for Dead {}

/// This is a pcap capture handle which is an abstraction over the `pcap_t` provided by pcap.
/// There are many ways to instantiate and interact with a pcap handle, so phantom types are
/// used to express these behaviors.
///
/// **`Capture<Inactive>`** is created via `Capture::from_device()`. This handle is inactive,
/// so you cannot (yet) obtain packets from it. However, you can configure things like the
/// buffer size, snaplen, timeout, and promiscuity before you activate it.
///
/// **`Capture<Active>`** is created by calling `.open()` on a `Capture<Inactive>`. This
/// activates the capture handle, allowing you to get packets with `.next_packet()` or apply filters
/// with `.filter()`.
///
/// **`Capture<Offline>`** is created via `Capture::from_file()`. This allows you to read a
/// pcap format dump file as if you were opening an interface -- very useful for testing or
/// analysis.
///
/// **`Capture<Dead>`** is created via `Capture::dead()`. This allows you to create a pcap
/// format dump file without needing an active capture.
///
/// # Example:
///
/// ```ignore
/// let cap = Capture::from_device(Device::lookup().unwrap()) // open the "default" interface
///               .unwrap() // assume the device exists and we are authorized to open it
///               .open() // activate the handle
///               .unwrap(); // assume activation worked
///
/// while let Ok(packet) = cap.next_packet() {
///     println!("received packet! {:?}", packet);
/// }
/// ```
pub struct Capture<T: State + ?Sized> {
    nonblock: bool,
    handle: NonNull<raw::pcap_t>,
    _marker: PhantomData<T>,
}

// A Capture is safe to Send as it encapsulates the entire lifetime of `raw::pcap_t *`, but it is
// not safe to Sync as libpcap does not promise thread-safe access to the same `raw::pcap_t *` from
// multiple threads.
unsafe impl<T: State + ?Sized> Send for Capture<T> {}

impl<T: State + ?Sized> From<NonNull<raw::pcap_t>> for Capture<T> {
    fn from(handle: NonNull<raw::pcap_t>) -> Self {
        Capture {
            nonblock: false,
            handle,
            _marker: PhantomData,
        }
    }
}

impl<T: State + ?Sized> Capture<T> {
    fn new_raw<F>(path: Option<&str>, func: F) -> Result<Capture<T>, Error>
    where
        F: FnOnce(*const libc::c_char, *mut libc::c_char) -> *mut raw::pcap_t,
    {
        with_errbuf(|err| {
            let handle = match path {
                None => func(ptr::null(), err),
                Some(path) => {
                    let path = CString::new(path)?;
                    func(path.as_ptr(), err)
                }
            };
            Ok(Capture::from(
                NonNull::<raw::pcap_t>::new(handle).ok_or_else(|| unsafe { Error::new(err) })?,
            ))
        })
    }

    /// Set the minumum amount of data received by the kernel in a single call.
    ///
    /// Note that this value is set to 0 when the capture is set to immediate mode. You should not
    /// call `min_to_copy` on captures in immediate mode if you want them to stay in immediate mode.
    #[cfg(windows)]
    pub fn min_to_copy(self, to: i32) -> Capture<T> {
        unsafe {
            raw::pcap_setmintocopy(self.handle.as_ptr(), to as _);
        }
        self
    }

    /// Get handle to the Capture context's internal Win32 event semaphore.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the `Capture` context outlives the returned `HANDLE` since it is
    /// a kernel object owned by the `Capture`'s pcap context.
    #[cfg(windows)]
    pub unsafe fn get_event(&self) -> HANDLE {
        raw::pcap_getevent(self.handle.as_ptr())
    }

    fn check_err(&self, success: bool) -> Result<(), Error> {
        if success {
            Ok(())
        } else {
            Err(unsafe { Error::new(raw::pcap_geterr(self.handle.as_ptr())) })
        }
    }
}

impl Capture<Offline> {
    /// Opens an offline capture handle from a pcap dump file, given a path.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Capture<Offline>, Error> {
        Capture::new_raw(path.as_ref().to_str(), |path, err| unsafe {
            raw::pcap_open_offline(path, err)
        })
    }

    /// Opens an offline capture handle from a pcap dump file, given a path.
    /// Takes an additional precision argument specifying the time stamp precision desired.
    #[cfg(libpcap_1_5_0)]
    pub fn from_file_with_precision<P: AsRef<Path>>(
        path: P,
        precision: Precision,
    ) -> Result<Capture<Offline>, Error> {
        Capture::new_raw(path.as_ref().to_str(), |path, err| unsafe {
            raw::pcap_open_offline_with_tstamp_precision(path, precision as _, err)
        })
    }

    /// Opens an offline capture handle from a pcap dump file, given a file descriptor.
    ///
    /// # Safety
    ///
    /// Unsafe, because the returned Capture assumes it is the sole owner of the file descriptor.
    #[cfg(not(windows))]
    pub unsafe fn from_raw_fd(fd: RawFd) -> Result<Capture<Offline>, Error> {
        open_raw_fd(fd, b'r')
            .and_then(|file| Capture::new_raw(None, |_, err| raw::pcap_fopen_offline(file, err)))
    }

    /// Opens an offline capture handle from a pcap dump file, given a file descriptor. Takes an
    /// additional precision argument specifying the time stamp precision desired.
    ///
    /// # Safety
    ///
    /// Unsafe, because the returned Capture assumes it is the sole owner of the file descriptor.
    #[cfg(all(not(windows), libpcap_1_5_0))]
    pub unsafe fn from_raw_fd_with_precision(
        fd: RawFd,
        precision: Precision,
    ) -> Result<Capture<Offline>, Error> {
        open_raw_fd(fd, b'r').and_then(|file| {
            Capture::new_raw(None, |_, err| {
                raw::pcap_fopen_offline_with_tstamp_precision(file, precision as _, err)
            })
        })
    }

    /// Get the major version number of the pcap dump file format.
    pub fn major_version(&self) -> i32 {
        unsafe { raw::pcap_major_version(self.handle.as_ptr()) }
    }

    /// Get the minor version number of the pcap dump file format.
    pub fn minor_version(&self) -> i32 {
        unsafe { raw::pcap_minor_version(self.handle.as_ptr()) }
    }

    /// Get the (major, minor) version number of the pcap dump file format.
    pub fn version(&self) -> (i32, i32) {
        (self.major_version(), self.minor_version())
    }
}

#[repr(i32)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// Timestamp types
///
/// Not all systems and interfaces will necessarily support all of these.
///
/// Note that time stamps synchronized with the system clock can go backwards, as the system clock
/// can go backwards.  If a clock is not in sync with the system clock, that could be because the
/// system clock isn't keeping accurate time, because the other clock isn't keeping accurate time,
/// or both.
///
/// Note that host-provided time stamps generally correspond to the time when the time-stamping
/// code sees the packet; this could be some unknown amount of time after the first or last bit of
/// the packet is received by the network adapter, due to batching of interrupts for packet
/// arrival, queueing delays, etc..
pub enum TimestampType {
    /// Timestamps are provided by the host machine, rather than by the capture device.
    ///
    /// The characteristics of the timestamp are unknown.
    Host = 0,
    /// A timestamp provided by the host machine that is low precision but relatively cheap to
    /// fetch.
    ///
    /// This is normally done using the system clock, so it's normally synchornized with times
    /// you'd fetch from system calls.
    HostLowPrec = 1,
    /// A timestamp provided by the host machine that is high precision. It might be more expensive
    /// to fetch.
    ///
    /// The timestamp might or might not be synchronized with the system clock, and might have
    /// problems with time stamps for packets received on different CPUs, depending on the
    /// platform.
    HostHighPrec = 2,
    /// The timestamp is a high-precision time stamp supplied by the capture device.
    ///
    /// The timestamp is synchronized with the system clock.
    Adapter = 3,
    /// The timestamp is a high-precision time stamp supplied by the capture device.
    ///
    /// The timestamp is not synchronized with the system clock.
    AdapterUnsynced = 4,
}

#[deprecated(note = "Renamed to TimestampType")]
/// An old name for `TimestampType`, kept around for backward-compatibility.
pub type TstampType = TimestampType;

#[repr(u32)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// The direction of packets to be captured. Use with `Capture::direction`.
pub enum Direction {
    /// Capture packets received by or sent by the device. This is the default.
    InOut = raw::PCAP_D_INOUT,
    /// Only capture packets received by the device.
    In = raw::PCAP_D_IN,
    /// Only capture packets sent by the device.
    Out = raw::PCAP_D_OUT,
}

impl Capture<Inactive> {
    /// Opens a capture handle for a device. You can pass a `Device` or an `&str` device
    /// name here. The handle is inactive, but can be activated via `.open()`.
    ///
    /// # Example
    /// ```
    /// use pcap::*;
    ///
    /// // Usage 1: Capture from a single owned device
    /// let dev: Device = pcap::Device::lookup()
    ///     .expect("device lookup failed")
    ///     .expect("no device available");
    /// let cap1 = Capture::from_device(dev);
    ///
    /// // Usage 2: Capture from an element of device list.
    /// let list: Vec<Device> = pcap::Device::list().unwrap();
    /// let cap2 = Capture::from_device(list[0].clone());
    ///
    /// // Usage 3: Capture from `&str` device name
    /// let cap3 = Capture::from_device("eth0");
    /// ```
    pub fn from_device<D: Into<Device>>(device: D) -> Result<Capture<Inactive>, Error> {
        let device: Device = device.into();
        Capture::new_raw(Some(&device.name), |name, err| unsafe {
            raw::pcap_create(name, err)
        })
    }

    /// Activates an inactive capture created from `Capture::from_device()` or returns
    /// an error.
    pub fn open(self) -> Result<Capture<Active>, Error> {
        unsafe {
            self.check_err(raw::pcap_activate(self.handle.as_ptr()) == 0)?;
            Ok(mem::transmute(self))
        }
    }

    /// Set the read timeout for the Capture. By default, this is 0, so it will block
    /// indefinitely.
    pub fn timeout(self, ms: i32) -> Capture<Inactive> {
        unsafe { raw::pcap_set_timeout(self.handle.as_ptr(), ms) };
        self
    }

    /// Set the time stamp type to be used by a capture device.
    #[cfg(libpcap_1_2_1)]
    pub fn tstamp_type(self, tstamp_type: TimestampType) -> Capture<Inactive> {
        unsafe { raw::pcap_set_tstamp_type(self.handle.as_ptr(), tstamp_type as _) };
        self
    }

    /// Set promiscuous mode on or off. By default, this is off.
    pub fn promisc(self, to: bool) -> Capture<Inactive> {
        unsafe { raw::pcap_set_promisc(self.handle.as_ptr(), to as _) };
        self
    }

    /// Set immediate mode on or off. By default, this is off.
    ///
    /// Note that in WinPcap immediate mode is set by passing a 0 argument to `min_to_copy`.
    /// Immediate mode will be unset if `min_to_copy` is later called with a non-zero argument.
    /// Immediate mode is unset by resetting `min_to_copy` to the WinPcap default possibly changing
    /// a previously set value. When using `min_to_copy`, it is best to avoid `immediate_mode`.
    #[cfg(any(libpcap_1_5_0, windows))]
    pub fn immediate_mode(self, to: bool) -> Capture<Inactive> {
        // Prior to 1.5.0 when `pcap_set_immediate_mode` was introduced, the necessary steps to set
        // immediate mode were more complicated, depended on the OS, and in some configurations had
        // to be set on an active capture. See
        // https://www.tcpdump.org/manpages/pcap_set_immediate_mode.3pcap.html. Since we do not
        // expect pre-1.5.0 version on unix systems in the wild, we simply ignore those cases.
        #[cfg(libpcap_1_5_0)]
        unsafe {
            raw::pcap_set_immediate_mode(self.handle.as_ptr(), to as _)
        };

        // In WinPcap we use `pcap_setmintocopy` as it does not have `pcap_set_immediate_mode`.
        #[cfg(all(windows, not(libpcap_1_5_0)))]
        unsafe {
            raw::pcap_setmintocopy(
                self.handle.as_ptr(),
                if to {
                    0
                } else {
                    raw::WINPCAP_MINTOCOPY_DEFAULT
                },
            )
        };

        self
    }

    /// Set rfmon mode on or off. The default is maintained by pcap.
    #[cfg(not(windows))]
    pub fn rfmon(self, to: bool) -> Capture<Inactive> {
        unsafe { raw::pcap_set_rfmon(self.handle.as_ptr(), to as _) };
        self
    }

    /// Set the buffer size for incoming packet data.
    ///
    /// The default is 1000000. This should always be larger than the snaplen.
    pub fn buffer_size(self, to: i32) -> Capture<Inactive> {
        unsafe { raw::pcap_set_buffer_size(self.handle.as_ptr(), to) };
        self
    }

    /// Set the time stamp precision returned in captures.
    #[cfg(libpcap_1_5_0)]
    pub fn precision(self, precision: Precision) -> Capture<Inactive> {
        unsafe { raw::pcap_set_tstamp_precision(self.handle.as_ptr(), precision as _) };
        self
    }

    /// Set the snaplen size (the maximum length of a packet captured into the buffer).
    /// Useful if you only want certain headers, but not the entire packet.
    ///
    /// The default is 65535.
    pub fn snaplen(self, to: i32) -> Capture<Inactive> {
        unsafe { raw::pcap_set_snaplen(self.handle.as_ptr(), to) };
        self
    }
}

///# Activated captures include `Capture<Active>` and `Capture<Offline>`.
impl<T: Activated + ?Sized> Capture<T> {
    /// List the datalink types that this captured device supports.
    pub fn list_datalinks(&self) -> Result<Vec<Linktype>, Error> {
        unsafe {
            let mut links: *mut i32 = ptr::null_mut();
            let num = raw::pcap_list_datalinks(self.handle.as_ptr(), &mut links);
            let mut vec = vec![];
            if num > 0 {
                vec.extend(
                    slice::from_raw_parts(links, num as _)
                        .iter()
                        .cloned()
                        .map(Linktype),
                )
            }
            raw::pcap_free_datalinks(links);
            self.check_err(num > 0).and(Ok(vec))
        }
    }

    /// Set the datalink type for the current capture handle.
    pub fn set_datalink(&mut self, linktype: Linktype) -> Result<(), Error> {
        self.check_err(unsafe { raw::pcap_set_datalink(self.handle.as_ptr(), linktype.0) == 0 })
    }

    /// Get the current datalink type for this capture handle.
    pub fn get_datalink(&self) -> Linktype {
        unsafe { Linktype(raw::pcap_datalink(self.handle.as_ptr())) }
    }

    /// Create a `Savefile` context for recording captured packets using this `Capture`'s
    /// configurations.
    pub fn savefile<P: AsRef<Path>>(&self, path: P) -> Result<Savefile, Error> {
        let name = CString::new(path.as_ref().to_str().unwrap())?;
        let handle_opt = NonNull::<raw::pcap_dumper_t>::new(unsafe {
            raw::pcap_dump_open(self.handle.as_ptr(), name.as_ptr())
        });
        let handle = self
            .check_err(handle_opt.is_some())
            .map(|_| handle_opt.unwrap())?;
        Ok(Savefile::from(handle))
    }

    /// Create a `Savefile` context for recording captured packets using this `Capture`'s
    /// configurations. The output is written to a raw file descriptor which is opened in `"w"`
    /// mode.
    ///
    /// # Safety
    ///
    /// Unsafe, because the returned Savefile assumes it is the sole owner of the file descriptor.
    #[cfg(not(windows))]
    pub unsafe fn savefile_raw_fd(&self, fd: RawFd) -> Result<Savefile, Error> {
        open_raw_fd(fd, b'w').and_then(|file| {
            let handle_opt = NonNull::<raw::pcap_dumper_t>::new(raw::pcap_dump_fopen(
                self.handle.as_ptr(),
                file,
            ));
            let handle = self
                .check_err(handle_opt.is_some())
                .map(|_| handle_opt.unwrap())?;
            Ok(Savefile::from(handle))
        })
    }

    /// Reopen a `Savefile` context for recording captured packets using this `Capture`'s
    /// configurations. This is similar to `savefile()` but does not create the file if it
    /// does  not exist and, if it does already exist, and is a pcap file with the same
    /// byte order as the host opening the file, and has the same time stamp precision,
    /// link-layer header type,  and  snapshot length as p, it will write new packets
    /// at the end of the file.
    #[cfg(libpcap_1_7_2)]
    pub fn savefile_append<P: AsRef<Path>>(&self, path: P) -> Result<Savefile, Error> {
        let name = CString::new(path.as_ref().to_str().unwrap())?;
        let handle_opt = NonNull::<raw::pcap_dumper_t>::new(unsafe {
            raw::pcap_dump_open_append(self.handle.as_ptr(), name.as_ptr())
        });
        let handle = self
            .check_err(handle_opt.is_some())
            .map(|_| handle_opt.unwrap())?;
        Ok(Savefile::from(handle))
    }

    /// Set the direction of the capture
    pub fn direction(&self, direction: Direction) -> Result<(), Error> {
        self.check_err(unsafe {
            raw::pcap_setdirection(self.handle.as_ptr(), direction as u32 as _) == 0
        })
    }

    /// Blocks until a packet is returned from the capture handle or an error occurs.
    ///
    /// pcap captures packets and places them into a buffer which this function reads
    /// from.
    ///
    /// # Warning
    ///
    /// This buffer has a finite length, so if the buffer fills completely new
    /// packets will be discarded temporarily. This means that in realtime situations,
    /// you probably want to minimize the time between calls to next_packet() method.
    pub fn next_packet(&mut self) -> Result<Packet, Error> {
        unsafe {
            let mut header: *mut raw::pcap_pkthdr = ptr::null_mut();
            let mut packet: *const libc::c_uchar = ptr::null();
            let retcode = raw::pcap_next_ex(self.handle.as_ptr(), &mut header, &mut packet);
            self.check_err(retcode != -1)?; // -1 => an error occured while reading the packet
            match retcode {
                i if i >= 1 => {
                    // packet was read without issue
                    Ok(Packet::new(
                        &*(&*header as *const raw::pcap_pkthdr as *const PacketHeader),
                        slice::from_raw_parts(packet, (*header).caplen as _),
                    ))
                }
                0 => {
                    // packets are being read from a live capture and the
                    // timeout expired
                    Err(TimeoutExpired)
                }
                -2 => {
                    // packets are being read from a "savefile" and there are no
                    // more packets to read
                    Err(NoMorePackets)
                }
                _ => {
                    // libpcap only defines codes >=1, 0, -1, and -2
                    unreachable!()
                }
            }
        }
    }

    /// Return an iterator that call [`Self::next_packet()`] forever. Require a [`PacketCodec`]
    pub fn iter<C: PacketCodec>(self, codec: C) -> PacketIter<T, C> {
        PacketIter::new(self, codec)
    }

    /// Returns this capture as a [`futures::Stream`] of packets.
    ///
    /// # Errors
    ///
    /// If this capture is set to be blocking, or if the network device
    /// does not support `select()`, an error will be returned.
    #[cfg(feature = "capture-stream")]
    pub fn stream<C: PacketCodec>(self, codec: C) -> Result<PacketStream<T, C>, Error> {
        if !self.nonblock {
            return Err(NonNonBlock);
        }
        PacketStream::new(SelectableCapture::new(self)?, codec)
    }

    /// Sets the filter on the capture using the given BPF program string. Internally this is
    /// compiled using `pcap_compile()`. `optimize` controls whether optimization on the resulting
    /// code is performed
    ///
    /// See http://biot.com/capstats/bpf.html for more information about this syntax.
    pub fn filter(&mut self, program: &str, optimize: bool) -> Result<(), Error> {
        let program = CString::new(program)?;
        unsafe {
            let mut bpf_program: raw::bpf_program = mem::zeroed();
            let ret = raw::pcap_compile(
                self.handle.as_ptr(),
                &mut bpf_program,
                program.as_ptr(),
                optimize as libc::c_int,
                0,
            );
            self.check_err(ret != -1)?;
            let ret = raw::pcap_setfilter(self.handle.as_ptr(), &mut bpf_program);
            raw::pcap_freecode(&mut bpf_program);
            self.check_err(ret != -1)
        }
    }

    /// Get capture statistics about this capture. The values represent packet statistics from the
    /// start of the run to the time of the call.
    ///
    /// See https://www.tcpdump.org/manpages/pcap_stats.3pcap.html for per-platform caveats about
    /// how packet statistics are calculated.
    pub fn stats(&mut self) -> Result<Stat, Error> {
        unsafe {
            let mut stats: raw::pcap_stat = mem::zeroed();
            self.check_err(raw::pcap_stats(self.handle.as_ptr(), &mut stats) != -1)
                .map(|_| Stat::new(stats.ps_recv, stats.ps_drop, stats.ps_ifdrop))
        }
    }
}

impl Capture<Active> {
    /// Sends a packet over this capture handle's interface.
    pub fn sendpacket<B: Borrow<[u8]>>(&mut self, buf: B) -> Result<(), Error> {
        let buf = buf.borrow();
        self.check_err(unsafe {
            raw::pcap_sendpacket(self.handle.as_ptr(), buf.as_ptr() as _, buf.len() as _) == 0
        })
    }

    /// Set the capture to be non-blocking. When this is set, [`Self::next_packet()`] may return an error indicating
    /// that there is no packet available to be read.
    pub fn setnonblock(mut self) -> Result<Capture<Active>, Error> {
        with_errbuf(|err| unsafe {
            if raw::pcap_setnonblock(self.handle.as_ptr(), 1, err) != 0 {
                return Err(Error::new(err));
            }
            self.nonblock = true;
            Ok(self)
        })
    }
}

impl Capture<Dead> {
    /// Creates a "fake" capture handle for the given link type.
    pub fn dead(linktype: Linktype) -> Result<Capture<Dead>, Error> {
        let handle = unsafe { raw::pcap_open_dead(linktype.0, 65535) };
        Ok(Capture::from(
            NonNull::<raw::pcap_t>::new(handle).ok_or(InsufficientMemory)?,
        ))
    }

    /// Creates a "fake" capture handle for the given link type and timestamp precision.
    #[cfg(libpcap_1_5_0)]
    pub fn dead_with_precision(
        linktype: Linktype,
        precision: Precision,
    ) -> Result<Capture<Dead>, Error> {
        let handle = unsafe {
            raw::pcap_open_dead_with_tstamp_precision(linktype.0, 65535, precision as u32)
        };
        Ok(Capture::from(
            NonNull::<raw::pcap_t>::new(handle).ok_or(InsufficientMemory)?,
        ))
    }

    /// Compiles the string into a filter program using `pcap_compile`.
    pub fn compile(&self, program: &str, optimize: bool) -> Result<BpfProgram, Error> {
        let program = CString::new(program).unwrap();

        unsafe {
            let mut bpf_program: raw::bpf_program = mem::zeroed();
            if -1
                == raw::pcap_compile(
                    self.handle.as_ptr(),
                    &mut bpf_program,
                    program.as_ptr(),
                    optimize as libc::c_int,
                    0,
                )
            {
                return Err(Error::new(raw::pcap_geterr(self.handle.as_ptr())));
            }
            Ok(BpfProgram(bpf_program))
        }
    }
}

#[cfg(not(windows))]
impl AsRawFd for Capture<Active> {
    /// Returns the file descriptor for a live capture.
    fn as_raw_fd(&self) -> RawFd {
        let fd = unsafe { raw::pcap_fileno(self.handle.as_ptr()) };
        assert!(fd != -1, "Unable to get file descriptor for live capture");
        fd
    }
}

/// Newtype [`Capture`] wrapper that exposes `pcap_get_selectable_fd()`.
#[cfg(feature = "capture-stream")]
struct SelectableCapture<T: State + ?Sized> {
    inner: Capture<T>,
    fd: RawFd,
}

#[cfg(feature = "capture-stream")]
impl<T: Activated + ?Sized> SelectableCapture<T> {
    fn new(capture: Capture<T>) -> Result<Self, Error> {
        let fd = unsafe { raw::pcap_get_selectable_fd(capture.handle.as_ptr()) };
        if fd == -1 {
            return Err(InvalidRawFd);
        }
        Ok(Self { inner: capture, fd })
    }
}

#[cfg(all(unix, feature = "capture-stream"))]
impl<T: Activated + ?Sized> AsRawFd for SelectableCapture<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl<T: State + ?Sized> Drop for Capture<T> {
    fn drop(&mut self) {
        unsafe { raw::pcap_close(self.handle.as_ptr()) }
    }
}

impl<T: Activated> From<Capture<T>> for Capture<dyn Activated> {
    fn from(cap: Capture<T>) -> Capture<dyn Activated> {
        unsafe { mem::transmute(cap) }
    }
}

/// Abstraction for writing pcap savefiles, which can be read afterwards via `Capture::from_file()`.
pub struct Savefile {
    handle: NonNull<raw::pcap_dumper_t>,
}

// Just like a Capture, a Savefile is safe to Send as it encapsulates the entire lifetime of
// `raw::pcap_dumper_t *`, but it is not safe to Sync as libpcap does not promise thread-safe access
// to the same `raw::pcap_dumper_t *` from multiple threads.
unsafe impl Send for Savefile {}

impl Savefile {
    /// Write a packet to a capture file
    pub fn write(&mut self, packet: &Packet) {
        unsafe {
            raw::pcap_dump(
                self.handle.as_ptr() as _,
                &*(packet.header as *const PacketHeader as *const raw::pcap_pkthdr),
                packet.data.as_ptr(),
            );
        }
    }

    /// Flushes all the packets that haven't been written to the savefile
    pub fn flush(&mut self) -> Result<(), Error> {
        if unsafe { raw::pcap_dump_flush(self.handle.as_ptr() as _) } != 0 {
            return Err(Error::ErrnoError(errno::errno()));
        }

        Ok(())
    }
}

impl From<NonNull<raw::pcap_dumper_t>> for Savefile {
    fn from(handle: NonNull<raw::pcap_dumper_t>) -> Self {
        Savefile { handle }
    }
}

impl Drop for Savefile {
    fn drop(&mut self) {
        unsafe { raw::pcap_dump_close(self.handle.as_ptr()) }
    }
}

#[cfg(not(windows))]
/// Open a raw file descriptor.
///
/// # Safety
///
/// Unsafe, because the returned FILE assumes it is the sole owner of the file descriptor.
pub unsafe fn open_raw_fd(fd: RawFd, mode: u8) -> Result<*mut libc::FILE, Error> {
    let mode = vec![mode, 0];
    libc::fdopen(fd, mode.as_ptr() as _)
        .as_mut()
        .map(|f| f as _)
        .ok_or(InvalidRawFd)
}

unsafe fn cstr_to_string(ptr: *const libc::c_char) -> Result<Option<String>, Error> {
    let string = if ptr.is_null() {
        None
    } else {
        Some(CStr::from_ptr(ptr as _).to_str()?.to_owned())
    };
    Ok(string)
}

fn with_errbuf<T, F>(func: F) -> Result<T, Error>
where
    F: FnOnce(*mut libc::c_char) -> Result<T, Error>,
{
    let mut errbuf = [0i8; 256];
    func(errbuf.as_mut_ptr() as _)
}

#[test]
fn test_struct_size() {
    use std::mem::size_of;
    assert_eq!(size_of::<PacketHeader>(), size_of::<raw::pcap_pkthdr>());
}

#[repr(transparent)]
pub struct BpfInstruction(raw::bpf_insn);
#[repr(transparent)]
pub struct BpfProgram(raw::bpf_program);

impl BpfProgram {
    /// checks whether a filter matches a packet
    pub fn filter(&self, buf: &[u8]) -> bool {
        let header: raw::pcap_pkthdr = raw::pcap_pkthdr {
            ts: libc::timeval {
                tv_sec: 0,
                tv_usec: 0,
            },
            caplen: buf.len() as u32,
            len: buf.len() as u32,
        };
        unsafe { raw::pcap_offline_filter(&self.0, &header, buf.as_ptr()) > 0 }
    }

    pub fn get_instructions(&self) -> &[BpfInstruction] {
        unsafe {
            slice::from_raw_parts(
                self.0.bf_insns as *const BpfInstruction,
                self.0.bf_len as usize,
            )
        }
    }
}

impl Clone for BpfProgram {
    // make a deep copy of the underlying program
    fn clone(&self) -> Self {
        let len = self.0.bf_len as usize;
        let size = len * mem::size_of::<raw::bpf_insn>();
        let storage = unsafe {
            let storage = libc::malloc(size) as *mut raw::bpf_insn;
            ptr::copy_nonoverlapping(self.0.bf_insns, storage, len);
            storage
        };
        BpfProgram(raw::bpf_program {
            bf_len: self.0.bf_len,
            bf_insns: storage,
        })
    }
}

impl Drop for BpfProgram {
    fn drop(&mut self) {
        unsafe { raw::pcap_freecode(&mut self.0) }
    }
}

impl fmt::Display for BpfInstruction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {} {} {}",
            self.0.code, self.0.jt, self.0.jf, self.0.k
        )
    }
}

unsafe impl Send for BpfProgram {}