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
//! Rust library for attaching BPF filters to sockets.
//!
//! This library provides a simple interface for creating and attaching
//! Berkeley Packet Filter (BPF) programs to sockets on Linux systems.
//! On non-Linux systems, it provides dummy implementations that maintain
//! API compatibility but don't perform any actual filtering.
//!
//! BPF is a technology used in the Linux kernel to filter network packets
//! at the socket level. It allows applications to efficiently filter packets
//! in kernel space before they're delivered to user space, reducing unnecessary
//! data copies and improving performance.
//!
//! # Features
//!
//! - Create and attach BPF filters to sockets
//! - Detach filters when no longer needed
//! - Lock filters to prevent unauthorized modification
//! - Simple macro syntax for defining BPF programs
//! - Cross-platform API (real implementation on Linux, dummy on other platforms)
//!
//! # Basic Usage
//!
//! ```rust
//! use bpf::{bpfprog, BpfFilterAttachable};
//! use std::net::UdpSocket;
//!
//! fn main() -> std::io::Result<()> {
//! // Create a socket
//! let socket = UdpSocket::bind("0.0.0.0:0")?;
//!
//! // Create a BPF program that only accepts UDP packets on port 53 (DNS)
//! let filter = bpfprog!(2,
//! 0x30 0 0 0x00000011, // Load byte at position 17 (IP protocol)
//! 0x15 0 1 0x00000011 // If UDP (17), accept, else drop
//! );
//!
//! // Attach the filter to the socket using the trait
//! socket.attach_filter(filter)?;
//!
//! // Later, detach if needed
//! socket.detach_filter()?;
//!
//! Ok(())
//! }
//! ```
use AsRawFd;
pub use *;
pub use *;
/// Trait for types that can have BPF filters attached.
///
/// This trait is automatically implemented for any type that implements `AsRawFd`,
/// allowing you to directly call BPF operations on any socket type without having
/// to manually extract the file descriptor.
///
/// # Examples
///
/// ```rust
/// use bpf::{bpfprog, BpfFilterAttachable};
/// use std::net::{TcpListener, UdpSocket};
///
/// // Works with TcpListener
/// let tcp = TcpListener::bind("127.0.0.1:0").unwrap();
/// let tcp_filter = bpfprog!(1, 0x06 0 0 0x00000001); // ret #1
/// tcp.attach_filter(tcp_filter).unwrap();
///
/// // Works with UdpSocket
/// let udp = UdpSocket::bind("127.0.0.1:0").unwrap();
/// let udp_filter = bpfprog!(1, 0x06 0 0 0x00000001); // ret #1
/// udp.attach_filter(udp_filter).unwrap();
/// ```
// Implement the trait for any type that implements AsRawFd