1use std::io;
4use std::time::Duration;
5
6use crate::MacAddress;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct Received {
11 pub source: MacAddress,
12 pub length: usize,
14 pub group: bool,
16}
17
18pub struct Socket {
21 inner: platform::Socket,
22 mac: MacAddress,
23}
24
25impl Socket {
26 pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
29 let mac = crate::interfaces::mac_of(interface).ok_or_else(|| {
30 io::Error::new(
31 io::ErrorKind::NotFound,
32 format!("no Ethernet interface named {interface}"),
33 )
34 })?;
35 Ok(Self {
36 inner: platform::Socket::open(interface, ethertype)?,
37 mac,
38 })
39 }
40
41 pub fn mac(&self) -> MacAddress {
43 self.mac
44 }
45
46 pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
48 self.inner.join_multicast(group)
49 }
50
51 pub fn set_promiscuous(&self, on: bool) -> io::Result<()> {
58 self.inner.set_promiscuous(on)
59 }
60
61 pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
62 self.inner.send(destination, payload)
63 }
64
65 pub fn ignore_outgoing(&self) -> io::Result<()> {
70 self.inner.ignore_outgoing()
71 }
72
73 pub fn keep_payloads_starting(&self, first: std::ops::RangeInclusive<u8>) -> io::Result<()> {
77 self.inner
78 .keep_payloads_starting(*first.start(), *first.end())
79 }
80
81 pub fn receive(
88 &self,
89 buffer: &mut [u8],
90 timeout: Option<Duration>,
91 ) -> io::Result<Option<Received>> {
92 self.inner.receive(buffer, timeout)
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum Blocked {
101 RawCapability,
103 CaptureDevices,
105 Npcap,
107 NpcapAdministrators,
109}
110
111impl Blocked {
112 pub fn of(error: &io::Error) -> Option<Self> {
114 error.get_ref()?.downcast_ref::<Self>().copied()
115 }
116
117 #[cfg_attr(
118 not(any(target_os = "linux", target_os = "macos", windows)),
119 allow(dead_code)
120 )]
121 fn error(self) -> io::Error {
122 let kind = match self {
123 Self::Npcap => io::ErrorKind::NotFound,
124 _ => io::ErrorKind::PermissionDenied,
125 };
126 io::Error::new(kind, self)
127 }
128}
129
130impl std::fmt::Display for Blocked {
131 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132 match self {
133 Self::RawCapability => {
134 #[cfg(target_os = "linux")]
136 let program = crate::broker::needs_capability();
137 #[cfg(not(target_os = "linux"))]
138 let program = std::env::current_exe().ok();
139 let program = program
140 .map(|path| path.display().to_string())
141 .unwrap_or_else(|| "the program".to_owned());
142 write!(
143 formatter,
144 "raw Ethernet needs CAP_NET_RAW; grant it with: sudo setcap cap_net_raw+ep \
145 {program}"
146 )
147 }
148 Self::CaptureDevices => formatter.write_str(
149 "raw Ethernet needs access to /dev/bpf*: install a capture helper, such as \
150 Wireshark's ChmodBPF, and log in again",
151 ),
152 Self::Npcap => formatter.write_str(
153 "raw Ethernet needs Npcap: install it from https://npcap.com, then start the program again",
154 ),
155 Self::NpcapAdministrators => formatter.write_str(
156 "Npcap lets only administrators capture: run the program as administrator, or \
157 reinstall Npcap without \"Restrict Npcap driver's access to Administrators \
158 only\"",
159 ),
160 }
161 }
162}
163
164impl std::error::Error for Blocked {}
165
166#[cfg(target_os = "linux")]
168pub(crate) fn raw_capability() -> io::Error {
169 Blocked::RawCapability.error()
170}
171
172pub fn check_access() -> io::Result<()> {
175 platform::check_access()
176}
177
178#[cfg(target_os = "linux")]
179#[allow(unsafe_code)]
180mod platform {
181 use std::io;
182 use std::mem::{size_of, zeroed};
183 use std::os::fd::{AsRawFd, OwnedFd};
184 use std::sync::atomic::{AtomicBool, Ordering};
185 use std::time::Duration;
186
187 use super::{Received, Sent};
188 use crate::MacAddress;
189
190 pub struct Socket {
191 fd: OwnedFd,
192 index: i32,
193 ethertype: u16,
194 sent: Sent,
195 promiscuous: AtomicBool,
197 }
198
199 pub fn check_access() -> io::Result<()> {
202 crate::broker::open(crate::broker::Kind::Datagram).map(drop)
203 }
204
205 impl Socket {
206 pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
207 let index = crate::interfaces::index_of(interface).ok_or_else(|| {
208 io::Error::new(
209 io::ErrorKind::NotFound,
210 format!("no interface named {interface}"),
211 )
212 })?;
213 let fd = crate::broker::open(crate::broker::Kind::Datagram)?;
218 let socket = Self {
219 fd,
220 index,
221 ethertype,
222 sent: Sent::default(),
223 promiscuous: AtomicBool::new(false),
224 };
225 socket.attach(&socket.program(None))?;
226 let mut address = socket.address(None);
227 address.sll_protocol = (libc::ETH_P_ALL as u16).to_be();
228 let bound = unsafe {
231 libc::bind(
232 socket.fd.as_raw_fd(),
233 (&raw const address).cast(),
234 size_of::<libc::sockaddr_ll>() as libc::socklen_t,
235 )
236 };
237 if bound < 0 {
238 return Err(io::Error::last_os_error());
239 }
240 Ok(socket)
241 }
242
243 fn address(&self, destination: Option<MacAddress>) -> libc::sockaddr_ll {
246 let mut address: libc::sockaddr_ll = unsafe { zeroed() };
248 address.sll_family = libc::AF_PACKET as u16;
249 address.sll_protocol = self.ethertype.to_be();
250 address.sll_ifindex = self.index;
251 if let Some(destination) = destination {
252 address.sll_halen = 6;
253 address.sll_addr[..6].copy_from_slice(&destination.0);
254 }
255 address
256 }
257
258 pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
259 self.membership(
260 libc::PACKET_ADD_MEMBERSHIP,
261 libc::PACKET_MR_MULTICAST,
262 Some(group),
263 )
264 }
265
266 pub fn set_promiscuous(&self, on: bool) -> io::Result<()> {
267 if self.promiscuous.load(Ordering::Relaxed) == on {
268 return Ok(());
269 }
270 let change = if on {
271 libc::PACKET_ADD_MEMBERSHIP
272 } else {
273 libc::PACKET_DROP_MEMBERSHIP
274 };
275 self.membership(change, libc::PACKET_MR_PROMISC, None)?;
276 self.promiscuous.store(on, Ordering::Relaxed);
277 Ok(())
278 }
279
280 fn membership(
284 &self,
285 change: libc::c_int,
286 kind: libc::c_int,
287 group: Option<MacAddress>,
288 ) -> io::Result<()> {
289 let mut request: libc::packet_mreq = unsafe { zeroed() };
291 request.mr_ifindex = self.index;
292 request.mr_type = kind as u16;
293 if let Some(group) = group {
294 request.mr_alen = 6;
295 request.mr_address[..6].copy_from_slice(&group.0);
296 }
297 let changed = unsafe {
300 libc::setsockopt(
301 self.fd.as_raw_fd(),
302 libc::SOL_PACKET,
303 change,
304 (&raw const request).cast(),
305 size_of::<libc::packet_mreq>() as libc::socklen_t,
306 )
307 };
308 if changed < 0 {
309 return Err(io::Error::last_os_error());
310 }
311 Ok(())
312 }
313
314 fn program(&self, first: Option<(u8, u8)>) -> Vec<libc::sock_filter> {
319 let step = |code: u16, jt: u8, jf: u8, k: u32| libc::sock_filter { code, jt, jf, k };
320 let protocol = 0xffff_f000; match first {
322 None => vec![
323 step(0x20, 0, 0, protocol), step(0x15, 0, 1, u32::from(self.ethertype)), step(0x06, 0, 0, u32::MAX), step(0x06, 0, 0, 0), ],
328 Some((first, last)) => vec![
329 step(0x20, 0, 0, protocol), step(0x15, 0, 4, u32::from(self.ethertype)), step(0x30, 0, 0, 0), step(0x35, 0, 2, u32::from(first)), step(0x25, 1, 0, u32::from(last)), step(0x06, 0, 0, u32::MAX), step(0x06, 0, 0, 0), ],
337 }
338 }
339
340 fn attach(&self, program: &[libc::sock_filter]) -> io::Result<()> {
341 let filter = libc::sock_fprog {
342 len: program.len() as u16,
343 filter: program.as_ptr().cast_mut(),
344 };
345 let attached = unsafe {
348 libc::setsockopt(
349 self.fd.as_raw_fd(),
350 libc::SOL_SOCKET,
351 libc::SO_ATTACH_FILTER,
352 (&raw const filter).cast(),
353 size_of::<libc::sock_fprog>() as libc::socklen_t,
354 )
355 };
356 if attached < 0 {
357 return Err(io::Error::last_os_error());
358 }
359 Ok(())
360 }
361
362 pub fn keep_payloads_starting(&self, first: u8, last: u8) -> io::Result<()> {
363 self.attach(&self.program(Some((first, last))))
364 }
365
366 pub fn ignore_outgoing(&self) -> io::Result<()> {
367 let on: libc::c_int = 1;
368 let set = unsafe {
371 libc::setsockopt(
372 self.fd.as_raw_fd(),
373 libc::SOL_PACKET,
374 libc::PACKET_IGNORE_OUTGOING,
375 (&raw const on).cast(),
376 size_of::<libc::c_int>() as libc::socklen_t,
377 )
378 };
379 if set < 0 {
380 return Err(io::Error::last_os_error());
381 }
382 Ok(())
383 }
384
385 pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
386 self.sent.note(payload);
387 let address = self.address(Some(destination));
388 let sent = unsafe {
391 libc::sendto(
392 self.fd.as_raw_fd(),
393 payload.as_ptr().cast(),
394 payload.len(),
395 0,
396 (&raw const address).cast(),
397 size_of::<libc::sockaddr_ll>() as libc::socklen_t,
398 )
399 };
400 if sent < 0 {
401 return Err(io::Error::last_os_error());
402 }
403 Ok(())
404 }
405
406 pub fn receive(
407 &self,
408 buffer: &mut [u8],
409 timeout: Option<Duration>,
410 ) -> io::Result<Option<Received>> {
411 let milliseconds = match timeout {
412 Some(timeout) => {
414 timeout.as_nanos().div_ceil(1_000_000).min(i32::MAX as u128) as i32
415 }
416 None => -1,
417 };
418 let mut poll = libc::pollfd {
419 fd: self.fd.as_raw_fd(),
420 events: libc::POLLIN,
421 revents: 0,
422 };
423 let ready = unsafe { libc::poll(&raw mut poll, 1, milliseconds) };
425 if ready < 0 {
426 let error = io::Error::last_os_error();
427 return match error.kind() {
428 io::ErrorKind::Interrupted => Ok(None),
429 _ => Err(error),
430 };
431 }
432 if ready == 0 {
433 return Ok(None);
434 }
435 loop {
436 let mut address: libc::sockaddr_ll = unsafe { zeroed() };
438 let mut length = size_of::<libc::sockaddr_ll>() as libc::socklen_t;
439 let received = unsafe {
442 libc::recvfrom(
443 self.fd.as_raw_fd(),
444 buffer.as_mut_ptr().cast(),
445 buffer.len(),
446 libc::MSG_DONTWAIT,
447 (&raw mut address).cast(),
448 &raw mut length,
449 )
450 };
451 if received < 0 {
452 let error = io::Error::last_os_error();
453 return match error.kind() {
454 io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => Ok(None),
455 _ => Err(error),
456 };
457 }
458 let outgoing = address.sll_pkttype == libc::PACKET_OUTGOING;
461 if outgoing && self.sent.heard_back(&buffer[..received as usize]) {
462 continue;
463 }
464 let mut source = [0; 6];
465 source.copy_from_slice(&address.sll_addr[..6]);
466 return Ok(Some(Received {
467 source: MacAddress(source),
468 length: received as usize,
469 group: matches!(
470 address.sll_pkttype,
471 libc::PACKET_MULTICAST | libc::PACKET_BROADCAST
472 ),
473 }));
474 }
475 }
476 }
477}
478
479#[cfg(any(target_os = "linux", target_os = "macos", windows))]
485#[derive(Default)]
486struct Sent {
487 recent: std::sync::Mutex<std::collections::VecDeque<(u64, std::time::Instant)>>,
488}
489
490#[cfg(any(target_os = "linux", target_os = "macos", windows))]
491impl Sent {
492 const KEPT_FOR: Duration = Duration::from_secs(2);
494 const MOST: usize = 256;
495
496 fn key(frame: &[u8]) -> u64 {
497 use std::hash::{Hash, Hasher};
498 let mut hasher = std::collections::hash_map::DefaultHasher::new();
499 frame.hash(&mut hasher);
500 hasher.finish()
501 }
502
503 fn note(&self, frame: &[u8]) {
505 let now = std::time::Instant::now();
506 let mut recent = self
507 .recent
508 .lock()
509 .unwrap_or_else(std::sync::PoisonError::into_inner);
510 while recent
511 .front()
512 .is_some_and(|&(_, at)| now.duration_since(at) > Self::KEPT_FOR)
513 || recent.len() >= Self::MOST
514 {
515 recent.pop_front();
516 }
517 recent.push_back((Self::key(frame), now));
518 }
519
520 fn heard_back(&self, frame: &[u8]) -> bool {
523 let key = Self::key(frame);
524 let mut recent = self
525 .recent
526 .lock()
527 .unwrap_or_else(std::sync::PoisonError::into_inner);
528 match recent.iter().position(|&(sent, _)| sent == key) {
529 Some(place) => {
530 recent.remove(place);
531 true
532 }
533 None => false,
534 }
535 }
536}
537
538#[cfg(any(target_os = "macos", windows))]
541fn frame(source: MacAddress, destination: MacAddress, ethertype: u16, payload: &[u8]) -> Vec<u8> {
542 const LEAST: usize = 60;
543 let mut frame = Vec::with_capacity((14 + payload.len()).max(LEAST));
544 frame.extend_from_slice(&destination.0);
545 frame.extend_from_slice(&source.0);
546 frame.extend_from_slice(ðertype.to_be_bytes());
547 frame.extend_from_slice(payload);
548 frame.resize(frame.len().max(LEAST), 0);
549 frame
550}
551
552#[cfg(any(target_os = "macos", windows))]
555fn take(frame: &[u8], ethertype: u16, sent: &Sent, buffer: &mut [u8]) -> Option<Received> {
556 if frame.len() < 14 || frame[12..14] != ethertype.to_be_bytes() || sent.heard_back(frame) {
557 return None;
558 }
559 let payload = &frame[14..];
560 let length = payload.len().min(buffer.len());
561 buffer[..length].copy_from_slice(&payload[..length]);
562 let mut source = [0; 6];
563 source.copy_from_slice(&frame[6..12]);
564 Some(Received {
565 source: MacAddress(source),
566 length,
567 group: frame[0] & 1 == 1,
568 })
569}
570
571#[cfg(any(target_os = "macos", windows))]
573#[repr(C)]
574struct Instruction {
575 code: u16,
576 jump_true: u8,
577 jump_false: u8,
578 value: u32,
579}
580
581#[cfg(any(target_os = "macos", windows))]
583#[repr(C)]
584struct Program {
585 length: u32,
586 instructions: *mut Instruction,
587}
588
589#[cfg(any(target_os = "macos", windows))]
591fn filter(ethertype: Option<u16>) -> Vec<Instruction> {
592 let reject = Instruction {
593 code: 0x06, jump_true: 0,
595 jump_false: 0,
596 value: 0,
597 };
598 let Some(ethertype) = ethertype else {
599 return vec![reject];
600 };
601 vec![
603 Instruction {
604 code: 0x28, jump_true: 0,
606 jump_false: 0,
607 value: 12,
608 },
609 Instruction {
610 code: 0x15, jump_true: 0,
612 jump_false: 1,
613 value: u32::from(ethertype),
614 },
615 Instruction {
616 code: 0x06, jump_true: 0,
618 jump_false: 0,
619 value: u32::MAX,
620 },
621 reject,
622 ]
623}
624
625#[cfg(any(target_os = "macos", windows))]
628fn payload_filter(ethertype: u16, first: u8, last: u8) -> Vec<Instruction> {
629 let step = |code: u16, jump_true: u8, jump_false: u8, value: u32| Instruction {
630 code,
631 jump_true,
632 jump_false,
633 value,
634 };
635 vec![
636 step(0x28, 0, 0, 12), step(0x15, 0, 4, u32::from(ethertype)), step(0x30, 0, 0, 14), step(0x35, 0, 2, u32::from(first)), step(0x25, 1, 0, u32::from(last)), step(0x06, 0, 0, u32::MAX), step(0x06, 0, 0, 0), ]
644}
645
646#[cfg(target_os = "macos")]
647#[allow(unsafe_code)]
648mod platform {
649 use std::io;
650 use std::mem::{size_of, zeroed};
651 use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
652 use std::sync::Mutex;
653 use std::time::{Duration, Instant};
654
655 use super::{Program, Received, Sent};
656 use crate::MacAddress;
657
658 const SEE_SENT: libc::c_ulong = 0x8004_4277;
661 const ADD_MULTICAST: libc::c_ulong = 0x8020_6931;
663 const DELETE_MULTICAST: libc::c_ulong = 0x8020_6932;
664 const BUFFER: u32 = 1 << 16;
666
667 struct Pending {
669 data: Vec<u8>,
670 start: usize,
671 end: usize,
672 }
673
674 pub struct Socket {
675 fd: OwnedFd,
676 interface: String,
677 ethertype: u16,
678 mac: MacAddress,
679 pending: Mutex<Pending>,
680 sent: Sent,
681 joined: Mutex<Vec<MacAddress>>,
683 }
684
685 fn request(interface: &str) -> io::Result<libc::ifreq> {
687 let mut request: libc::ifreq = unsafe { zeroed() };
689 let bytes = interface.as_bytes();
690 if bytes.len() >= request.ifr_name.len() {
691 return Err(io::Error::new(
692 io::ErrorKind::InvalidInput,
693 format!("no interface named {interface}"),
694 ));
695 }
696 for (place, &byte) in request.ifr_name.iter_mut().zip(bytes) {
697 *place = byte as libc::c_char;
698 }
699 Ok(request)
700 }
701
702 fn control(fd: &OwnedFd, code: libc::c_ulong, value: &mut u32) -> io::Result<()> {
703 if unsafe { libc::ioctl(fd.as_raw_fd(), code, std::ptr::from_mut(value)) } < 0 {
706 return Err(io::Error::last_os_error());
707 }
708 Ok(())
709 }
710
711 pub fn check_access() -> io::Result<()> {
713 open_device().map(drop)
714 }
715
716 fn open_device() -> io::Result<OwnedFd> {
718 let mut denied = false;
719 for index in 0..256 {
720 let path = format!("/dev/bpf{index}\0");
721 let raw = unsafe { libc::open(path.as_ptr().cast(), libc::O_RDWR | libc::O_CLOEXEC) };
723 if raw >= 0 {
724 return Ok(unsafe { OwnedFd::from_raw_fd(raw) });
726 }
727 match io::Error::last_os_error().raw_os_error() {
728 Some(libc::EBUSY) => {}
729 Some(libc::EACCES | libc::EPERM) => denied = true,
730 Some(libc::ENOENT) => break,
731 _ => {}
732 }
733 }
734 Err(if denied {
735 super::Blocked::CaptureDevices.error()
736 } else {
737 io::Error::other("no free /dev/bpf device")
738 })
739 }
740
741 impl Socket {
742 pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
743 let mac = crate::interfaces::mac_of(interface).ok_or_else(|| {
744 io::Error::new(
745 io::ErrorKind::NotFound,
746 format!("no interface named {interface}"),
747 )
748 })?;
749 let fd = open_device()?;
750 let mut size = BUFFER;
752 control(&fd, libc::BIOCSBLEN, &mut size)?;
753 let mut bound = request(interface)?;
754 if unsafe { libc::ioctl(fd.as_raw_fd(), libc::BIOCSETIF, &raw mut bound) } < 0 {
756 return Err(io::Error::last_os_error());
757 }
758 control(&fd, libc::BIOCIMMEDIATE, &mut 1)?;
759 control(&fd, libc::BIOCSHDRCMPLT, &mut 1)?;
761 control(&fd, SEE_SENT, &mut 1)?;
762 let mut instructions = super::filter(Some(ethertype));
763 let mut program = Program {
764 length: instructions.len() as u32,
765 instructions: instructions.as_mut_ptr(),
766 };
767 if unsafe { libc::ioctl(fd.as_raw_fd(), libc::BIOCSETF, &raw mut program) } < 0 {
770 return Err(io::Error::last_os_error());
771 }
772 let mut length = 0;
773 control(&fd, libc::BIOCGBLEN, &mut length)?;
774 Ok(Self {
775 fd,
776 interface: interface.to_owned(),
777 ethertype,
778 mac,
779 pending: Mutex::new(Pending {
780 data: vec![0; length.max(BUFFER) as usize],
781 start: 0,
782 end: 0,
783 }),
784 sent: Sent::default(),
785 joined: Mutex::new(Vec::new()),
786 })
787 }
788
789 fn membership(&self, group: MacAddress, code: libc::c_ulong) -> io::Result<()> {
791 let mut changed = request(&self.interface)?;
792 unsafe {
795 let mut address: libc::sockaddr = zeroed();
796 address.sa_len = size_of::<libc::sockaddr>() as u8;
797 address.sa_family = libc::AF_UNSPEC as u8;
798 for (place, &octet) in address.sa_data.iter_mut().zip(&group.0) {
799 *place = octet as libc::c_char;
800 }
801 changed.ifr_ifru.ifru_addr = address;
802 }
803 let raw = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0) };
805 if raw < 0 {
806 return Err(io::Error::last_os_error());
807 }
808 let query = unsafe { OwnedFd::from_raw_fd(raw) };
810 if unsafe { libc::ioctl(query.as_raw_fd(), code, &raw mut changed) } < 0 {
812 return Err(io::Error::last_os_error());
813 }
814 Ok(())
815 }
816
817 pub fn ignore_outgoing(&self) -> io::Result<()> {
818 Err(io::Error::new(
819 io::ErrorKind::Unsupported,
820 "leaving out outgoing frames is for Linux",
821 ))
822 }
823
824 pub fn keep_payloads_starting(&self, first: u8, last: u8) -> io::Result<()> {
825 let mut instructions = super::payload_filter(self.ethertype, first, last);
826 let mut program = Program {
827 length: instructions.len() as u32,
828 instructions: instructions.as_mut_ptr(),
829 };
830 if unsafe { libc::ioctl(self.fd.as_raw_fd(), libc::BIOCSETF, &raw mut program) } < 0 {
833 return Err(io::Error::last_os_error());
834 }
835 Ok(())
836 }
837
838 pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
839 match self.membership(group, ADD_MULTICAST) {
842 Ok(()) => {
843 self.joined
844 .lock()
845 .unwrap_or_else(std::sync::PoisonError::into_inner)
846 .push(group);
847 Ok(())
848 }
849 Err(_) => self.set_promiscuous(true),
850 }
851 }
852
853 pub fn set_promiscuous(&self, on: bool) -> io::Result<()> {
854 if !on {
856 return Ok(());
857 }
858 if unsafe { libc::ioctl(self.fd.as_raw_fd(), libc::BIOCPROMISC as _) } < 0 {
860 return Err(io::Error::last_os_error());
861 }
862 Ok(())
863 }
864
865 pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
866 let frame = super::frame(self.mac, destination, self.ethertype, payload);
867 self.sent.note(&frame);
868 let written =
870 unsafe { libc::write(self.fd.as_raw_fd(), frame.as_ptr().cast(), frame.len()) };
871 if written < 0 {
872 return Err(io::Error::last_os_error());
873 }
874 Ok(())
875 }
876
877 pub fn receive(
878 &self,
879 buffer: &mut [u8],
880 timeout: Option<Duration>,
881 ) -> io::Result<Option<Received>> {
882 let deadline = timeout.map(|timeout| Instant::now() + timeout);
883 let mut pending = self
884 .pending
885 .lock()
886 .unwrap_or_else(std::sync::PoisonError::into_inner);
887 loop {
888 while pending.start + size_of::<libc::bpf_hdr>() <= pending.end {
891 let at = pending.start;
892 let header: libc::bpf_hdr =
895 unsafe { std::ptr::read_unaligned(pending.data.as_ptr().add(at).cast()) };
896 let start = at + usize::from(header.bh_hdrlen);
897 let end = start + header.bh_caplen as usize;
898 pending.start = (end + 3) & !3;
899 if end > pending.end {
900 pending.start = pending.end;
901 break;
902 }
903 if let Some(received) = super::take(
904 &pending.data[start..end],
905 self.ethertype,
906 &self.sent,
907 buffer,
908 ) {
909 return Ok(Some(received));
910 }
911 }
912 let wait =
915 deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()));
916 if !self.readable(wait)? {
917 return Ok(None);
918 }
919 let capacity = pending.data.len();
920 let read = unsafe {
923 libc::read(
924 self.fd.as_raw_fd(),
925 pending.data.as_mut_ptr().cast(),
926 capacity,
927 )
928 };
929 if read < 0 {
930 let error = io::Error::last_os_error();
931 return match error.kind() {
932 io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => Ok(None),
933 _ => Err(error),
934 };
935 }
936 pending.start = 0;
937 pending.end = read as usize;
938 }
939 }
940
941 fn readable(&self, wait: Option<Duration>) -> io::Result<bool> {
943 let fd = self.fd.as_raw_fd();
944 let mut set: libc::fd_set = unsafe { zeroed() };
947 unsafe { libc::FD_SET(fd, &raw mut set) };
948 let mut time = wait.map(|wait| libc::timeval {
949 tv_sec: wait.as_secs() as libc::time_t,
950 tv_usec: wait.subsec_micros() as libc::suseconds_t,
951 });
952 let timeout = time
953 .as_mut()
954 .map_or(std::ptr::null_mut(), std::ptr::from_mut);
955 let ready = unsafe {
957 libc::select(
958 fd + 1,
959 &raw mut set,
960 std::ptr::null_mut(),
961 std::ptr::null_mut(),
962 timeout,
963 )
964 };
965 if ready < 0 {
966 let error = io::Error::last_os_error();
967 return match error.kind() {
968 io::ErrorKind::Interrupted => Ok(false),
969 _ => Err(error),
970 };
971 }
972 Ok(ready > 0)
973 }
974 }
975
976 impl Drop for Socket {
977 fn drop(&mut self) {
978 let joined = std::mem::take(
979 &mut *self
980 .joined
981 .lock()
982 .unwrap_or_else(std::sync::PoisonError::into_inner),
983 );
984 for group in joined {
985 let _ = self.membership(group, DELETE_MULTICAST);
986 }
987 }
988 }
989}
990
991#[cfg(windows)]
992#[allow(unsafe_code)]
993mod platform {
994 use std::ffi::{CStr, CString, c_char, c_int, c_void};
995 use std::io;
996 use std::sync::{Mutex, OnceLock, PoisonError};
997 use std::time::{Duration, Instant};
998
999 use windows_sys::Win32::Foundation::{HANDLE, WAIT_FAILED};
1000 use windows_sys::Win32::System::LibraryLoader::{
1001 GetProcAddress, LOAD_WITH_ALTERED_SEARCH_PATH, LoadLibraryExW,
1002 };
1003 use windows_sys::Win32::System::SystemInformation::GetSystemDirectoryW;
1004 use windows_sys::Win32::System::Threading::{INFINITE, WaitForSingleObject};
1005
1006 use super::{Program, Received, Sent};
1007 use crate::MacAddress;
1008
1009 const ERROR_ROOM: usize = 256;
1011 const SNAPSHOT: c_int = 65_535;
1013 const BUFFER: c_int = 1 << 20;
1014 const PERMISSION_DENIED: c_int = -8;
1018 const NO_SUCH_DEVICE: c_int = -5;
1019
1020 type Capture = *mut c_void;
1022
1023 #[repr(C)]
1026 struct PacketHeader {
1027 seconds: i32,
1028 microseconds: i32,
1029 captured: u32,
1030 length: u32,
1031 }
1032
1033 struct Npcap {
1035 create: unsafe extern "C" fn(*const c_char, *mut c_char) -> Capture,
1036 set_snaplen: unsafe extern "C" fn(Capture, c_int) -> c_int,
1037 set_promisc: unsafe extern "C" fn(Capture, c_int) -> c_int,
1038 set_immediate_mode: unsafe extern "C" fn(Capture, c_int) -> c_int,
1039 set_buffer_size: unsafe extern "C" fn(Capture, c_int) -> c_int,
1040 activate: unsafe extern "C" fn(Capture) -> c_int,
1041 setfilter: unsafe extern "C" fn(Capture, *mut Program) -> c_int,
1042 setnonblock: unsafe extern "C" fn(Capture, c_int, *mut c_char) -> c_int,
1043 getevent: unsafe extern "C" fn(Capture) -> HANDLE,
1044 next_ex: unsafe extern "C" fn(Capture, *mut *mut PacketHeader, *mut *const u8) -> c_int,
1045 sendpacket: unsafe extern "C" fn(Capture, *const u8, c_int) -> c_int,
1046 geterr: unsafe extern "C" fn(Capture) -> *const c_char,
1047 close: unsafe extern "C" fn(Capture),
1048 }
1049
1050 fn npcap() -> io::Result<&'static Npcap> {
1052 static LOADED: OnceLock<Option<Npcap>> = OnceLock::new();
1053 LOADED
1054 .get_or_init(load)
1055 .as_ref()
1056 .ok_or_else(|| super::Blocked::Npcap.error())
1057 }
1058
1059 pub fn check_access() -> io::Result<()> {
1061 npcap().map(|_| ())
1062 }
1063
1064 #[allow(clippy::missing_transmute_annotations)]
1066 fn load() -> Option<Npcap> {
1067 let mut system = [0u16; 260];
1070 let length =
1072 unsafe { GetSystemDirectoryW(system.as_mut_ptr(), system.len() as u32) } as usize;
1073 if length == 0 || length >= system.len() {
1074 return None;
1075 }
1076 let mut path = system[..length].to_vec();
1077 path.extend("\\Npcap\\wpcap.dll".encode_utf16());
1078 path.push(0);
1079 let library = unsafe {
1082 LoadLibraryExW(
1083 path.as_ptr(),
1084 std::ptr::null_mut(),
1085 LOAD_WITH_ALTERED_SEARCH_PATH,
1086 )
1087 };
1088 if library.is_null() {
1089 return None;
1090 }
1091 macro_rules! function {
1094 ($name:literal) => {{
1095 let address = unsafe { GetProcAddress(library, concat!($name, "\0").as_ptr()) }?;
1097 unsafe { std::mem::transmute(address) }
1100 }};
1101 }
1102 Some(Npcap {
1103 create: function!("pcap_create"),
1104 set_snaplen: function!("pcap_set_snaplen"),
1105 set_promisc: function!("pcap_set_promisc"),
1106 set_immediate_mode: function!("pcap_set_immediate_mode"),
1107 set_buffer_size: function!("pcap_set_buffer_size"),
1108 activate: function!("pcap_activate"),
1109 setfilter: function!("pcap_setfilter"),
1110 setnonblock: function!("pcap_setnonblock"),
1111 getevent: function!("pcap_getevent"),
1112 next_ex: function!("pcap_next_ex"),
1113 sendpacket: function!("pcap_sendpacket"),
1114 geterr: function!("pcap_geterr"),
1115 close: function!("pcap_close"),
1116 })
1117 }
1118
1119 struct Handle(Capture);
1121
1122 unsafe impl Send for Handle {}
1125
1126 impl Drop for Handle {
1127 fn drop(&mut self) {
1128 if let Ok(npcap) = npcap() {
1129 unsafe { (npcap.close)(self.0) };
1131 }
1132 }
1133 }
1134
1135 fn message(error: &[c_char]) -> String {
1137 unsafe { CStr::from_ptr(error.as_ptr()) }
1139 .to_string_lossy()
1140 .into_owned()
1141 }
1142
1143 fn last_error(npcap: &Npcap, handle: &Handle) -> io::Error {
1145 let text = unsafe { CStr::from_ptr((npcap.geterr)(handle.0)) }
1148 .to_string_lossy()
1149 .into_owned();
1150 io::Error::other(text)
1151 }
1152
1153 fn capture(
1156 npcap: &Npcap,
1157 device: &CStr,
1158 interface: &str,
1159 promiscuous: bool,
1160 ethertype: Option<u16>,
1161 ) -> io::Result<Handle> {
1162 let mut error = [0 as c_char; ERROR_ROOM];
1163 let opened = unsafe { (npcap.create)(device.as_ptr(), error.as_mut_ptr()) };
1166 if opened.is_null() {
1167 return Err(io::Error::other(message(&error)));
1168 }
1169 let handle = Handle(opened);
1170 let activated = unsafe {
1172 (npcap.set_snaplen)(opened, SNAPSHOT);
1173 (npcap.set_promisc)(opened, c_int::from(promiscuous));
1174 (npcap.set_immediate_mode)(opened, 1);
1175 (npcap.set_buffer_size)(opened, BUFFER);
1176 (npcap.activate)(opened)
1177 };
1178 match activated {
1179 PERMISSION_DENIED => return Err(super::Blocked::NpcapAdministrators.error()),
1180 NO_SUCH_DEVICE => {
1181 return Err(io::Error::new(
1182 io::ErrorKind::NotFound,
1183 format!("Npcap does not capture on {interface}"),
1184 ));
1185 }
1186 failed if failed < 0 => return Err(last_error(npcap, &handle)),
1187 _ => {}
1188 }
1189 let mut instructions = super::filter(ethertype);
1190 let mut program = Program {
1191 length: instructions.len() as u32,
1192 instructions: instructions.as_mut_ptr(),
1193 };
1194 if unsafe { (npcap.setfilter)(opened, &raw mut program) } != 0 {
1197 return Err(last_error(npcap, &handle));
1198 }
1199 if unsafe { (npcap.setnonblock)(opened, 1, error.as_mut_ptr()) } != 0 {
1201 return Err(io::Error::other(message(&error)));
1202 }
1203 Ok(handle)
1204 }
1205
1206 pub struct Socket {
1207 receiver: Mutex<Handle>,
1210 sender: Mutex<Handle>,
1211 event: usize,
1214 ethertype: u16,
1215 mac: MacAddress,
1216 sent: Sent,
1217 }
1218
1219 impl Socket {
1220 pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
1221 let npcap = npcap()?;
1222 let not_found = || {
1223 io::Error::new(
1224 io::ErrorKind::NotFound,
1225 format!("no interface named {interface}"),
1226 )
1227 };
1228 let mac = crate::interfaces::mac_of(interface).ok_or_else(not_found)?;
1229 let device = crate::interfaces::device_of(interface)
1230 .and_then(|device| CString::new(device).ok())
1231 .ok_or_else(not_found)?;
1232 let receiver = match capture(npcap, &device, interface, true, Some(ethertype)) {
1235 Ok(receiver) => receiver,
1236 Err(error)
1237 if matches!(
1238 error.kind(),
1239 io::ErrorKind::PermissionDenied | io::ErrorKind::NotFound
1240 ) =>
1241 {
1242 return Err(error);
1243 }
1244 Err(_) => capture(npcap, &device, interface, false, Some(ethertype))?,
1245 };
1246 let sender = capture(npcap, &device, interface, false, None)?;
1247 let event = unsafe { (npcap.getevent)(receiver.0) };
1249 if event.is_null() {
1250 return Err(last_error(npcap, &receiver));
1251 }
1252 Ok(Self {
1253 receiver: Mutex::new(receiver),
1254 sender: Mutex::new(sender),
1255 event: event as usize,
1256 ethertype,
1257 mac,
1258 sent: Sent::default(),
1259 })
1260 }
1261
1262 pub fn join_multicast(&self, _group: MacAddress) -> io::Result<()> {
1263 Ok(())
1266 }
1267
1268 pub fn set_promiscuous(&self, _on: bool) -> io::Result<()> {
1269 Ok(())
1270 }
1271
1272 pub fn ignore_outgoing(&self) -> io::Result<()> {
1273 Err(io::Error::new(
1274 io::ErrorKind::Unsupported,
1275 "leaving out outgoing frames is for Linux",
1276 ))
1277 }
1278
1279 pub fn keep_payloads_starting(&self, first: u8, last: u8) -> io::Result<()> {
1280 let npcap = npcap()?;
1281 let receiver = self.receiver.lock().unwrap_or_else(PoisonError::into_inner);
1282 let mut instructions = super::payload_filter(self.ethertype, first, last);
1283 let mut program = Program {
1284 length: instructions.len() as u32,
1285 instructions: instructions.as_mut_ptr(),
1286 };
1287 if unsafe { (npcap.setfilter)(receiver.0, &raw mut program) } != 0 {
1290 return Err(last_error(npcap, &receiver));
1291 }
1292 Ok(())
1293 }
1294
1295 pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
1296 let npcap = npcap()?;
1297 let frame = super::frame(self.mac, destination, self.ethertype, payload);
1298 self.sent.note(&frame);
1299 let sender = self.sender.lock().unwrap_or_else(PoisonError::into_inner);
1300 if unsafe { (npcap.sendpacket)(sender.0, frame.as_ptr(), frame.len() as c_int) } != 0 {
1302 return Err(last_error(npcap, &sender));
1303 }
1304 Ok(())
1305 }
1306
1307 pub fn receive(
1308 &self,
1309 buffer: &mut [u8],
1310 timeout: Option<Duration>,
1311 ) -> io::Result<Option<Received>> {
1312 let npcap = npcap()?;
1313 let deadline = timeout.map(|timeout| Instant::now() + timeout);
1314 let receiver = self.receiver.lock().unwrap_or_else(PoisonError::into_inner);
1315 loop {
1316 loop {
1318 let mut header: *mut PacketHeader = std::ptr::null_mut();
1319 let mut data: *const u8 = std::ptr::null();
1320 let read =
1323 unsafe { (npcap.next_ex)(receiver.0, &raw mut header, &raw mut data) };
1324 match read {
1325 1 => {
1326 let frame = unsafe {
1329 std::slice::from_raw_parts(data, (*header).captured as usize)
1330 };
1331 if let Some(received) =
1332 super::take(frame, self.ethertype, &self.sent, buffer)
1333 {
1334 return Ok(Some(received));
1335 }
1336 }
1337 0 => break,
1338 _ => return Err(last_error(npcap, &receiver)),
1339 }
1340 }
1341 let milliseconds = match deadline {
1342 Some(deadline) => {
1343 let left = deadline.saturating_duration_since(Instant::now());
1344 if left.is_zero() {
1345 return Ok(None);
1346 }
1347 left.as_nanos()
1350 .div_ceil(1_000_000)
1351 .min(u128::from(INFINITE - 1)) as u32
1352 }
1353 None => INFINITE,
1354 };
1355 if unsafe { WaitForSingleObject(self.event as HANDLE, milliseconds) } == WAIT_FAILED
1360 {
1361 return Err(io::Error::last_os_error());
1362 }
1363 }
1364 }
1365 }
1366}
1367
1368#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
1369mod platform {
1370 use std::io;
1371 use std::time::Duration;
1372
1373 use super::Received;
1374 use crate::MacAddress;
1375
1376 pub struct Socket;
1378
1379 fn unsupported() -> io::Error {
1380 io::Error::new(
1381 io::ErrorKind::Unsupported,
1382 "raw Ethernet is not supported on this system yet",
1383 )
1384 }
1385
1386 pub fn check_access() -> io::Result<()> {
1387 Err(unsupported())
1388 }
1389
1390 impl Socket {
1391 pub fn open(_interface: &str, _ethertype: u16) -> io::Result<Self> {
1392 Err(unsupported())
1393 }
1394
1395 pub fn join_multicast(&self, _group: MacAddress) -> io::Result<()> {
1396 Err(unsupported())
1397 }
1398
1399 pub fn set_promiscuous(&self, _on: bool) -> io::Result<()> {
1400 Err(unsupported())
1401 }
1402
1403 pub fn send(&self, _destination: MacAddress, _payload: &[u8]) -> io::Result<()> {
1404 Err(unsupported())
1405 }
1406
1407 pub fn keep_payloads_starting(&self, _first: u8, _last: u8) -> io::Result<()> {
1408 Err(unsupported())
1409 }
1410
1411 pub fn ignore_outgoing(&self) -> io::Result<()> {
1412 Err(unsupported())
1413 }
1414
1415 pub fn receive(
1416 &self,
1417 _buffer: &mut [u8],
1418 _timeout: Option<Duration>,
1419 ) -> io::Result<Option<Received>> {
1420 Err(unsupported())
1421 }
1422 }
1423}