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
//! Socket filter programs.
use ;
use ;
use ;
use Error;
use crate::;
/// The type returned when a [`SocketFilter`] socket option operation fails.
/// A program used to inspect and filter incoming packets on a socket.
///
/// This is a `BPF_PROG_TYPE_SOCKET_FILTER` program attached as a regular
/// socket filter. The same kernel program type can also be attached to
/// `SO_REUSEPORT` groups through [`ReusePortSocketFilter`].
///
/// Since both abstractions use the same libbpf `SEC("socket")` section,
/// converting from [`crate::programs::Program`] with `try_into` selects this
/// abstraction from the caller's requested type rather than from distinct load
/// metadata.
///
/// The return value is interpreted as a packet length: `0` drops the packet, a
/// value greater than or equal to the packet length accepts the whole packet,
/// and a smaller positive value trims the packet to that length.
///
/// Regular socket filters are scoped to one socket. `SO_ATTACH_BPF` writes the
/// socket's `sk->sk_filter` field:
/// <https://github.com/torvalds/linux/blob/v6.9/net/core/filter.c#L1476-L1478>
///
/// Attaching a new program replaces the current program in that slot, and
/// detaching clears the slot regardless of which program installed it. On the
/// same socket, [`SocketFilter`] and [`ReusePortSocketFilter`] use different
/// kernel slots and do not affect each other. For that reason, [`SocketFilter`]
/// does not expose a link-style attachment handle or automatically track
/// attachments for cleanup. Dropping [`SocketFilter`] or [`crate::Ebpf`] does
/// not detach the program; call [`SocketFilter::detach`] explicitly when you
/// want to remove it, or close the socket.
///
/// # Minimum kernel version
///
/// `BPF_PROG_TYPE_SOCKET_FILTER` and `SO_ATTACH_BPF` are present in Linux 3.19:
/// <https://github.com/torvalds/linux/blob/v3.19/include/uapi/linux/bpf.h#L118-L120>
/// <https://github.com/torvalds/linux/blob/v3.19/include/uapi/asm-generic/socket.h#L87-L88>
///
/// # Examples
///
/// ```no_run
/// # #[derive(Debug, thiserror::Error)]
/// # enum Error {
/// # #[error(transparent)]
/// # IO(#[from] std::io::Error),
/// # #[error(transparent)]
/// # Map(#[from] aya::maps::MapError),
/// # #[error(transparent)]
/// # Program(#[from] aya::programs::ProgramError),
/// # #[error(transparent)]
/// # Ebpf(#[from] aya::EbpfError)
/// # }
/// # let mut bpf = aya::Ebpf::load(&[])?;
/// use std::net::TcpStream;
/// use aya::programs::SocketFilter;
///
/// let mut client = TcpStream::connect("127.0.0.1:1234")?;
/// let prog: &mut SocketFilter = bpf.program_mut("filter_packets").unwrap().try_into()?;
/// prog.load()?;
/// prog.attach(&client)?;
/// # Ok::<(), Error>(())
/// ```
// Invariant: `TryFrom<Program>` casts references between `SocketFilter` and
// `ReusePortSocketFilter`. Keep both types as transparent wrappers around the
// same `ProgramData<FdLink>` field.
/// A socket filter program used as a `SO_REUSEPORT` group selector.
///
/// This is a `BPF_PROG_TYPE_SOCKET_FILTER` program attached through
/// `SO_ATTACH_REUSEPORT_EBPF`. The same kernel program type can also be
/// attached as a regular socket filter through [`SocketFilter`].
///
/// Since both abstractions use the same libbpf `SEC("socket")` section,
/// converting from [`crate::programs::Program`] with `try_into` selects this
/// abstraction from the caller's requested type rather than from distinct load
/// metadata.
///
/// The program return value is interpreted as the selected socket index in the
/// reuseport group. The socket must already be configured with `SO_REUSEPORT`.
///
/// Regular [`SocketFilter`] programs and [`ReusePortSocketFilter`] programs use
/// separate kernel-managed slots. Regular filters are scoped to one socket;
/// reuseport selectors are scoped to the whole `SO_REUSEPORT` group.
/// `SO_ATTACH_REUSEPORT_EBPF` writes the group's `reuse->prog` field:
/// <https://github.com/torvalds/linux/blob/v6.9/net/core/sock_reuseport.c#L706-L708>
///
/// Attaching or detaching one type does not affect the other. For reuseport
/// groups, attaching through any socket in the group replaces the program used
/// by the entire group, and detaching through any socket in the group clears
/// the selector. [`ReusePortSocketFilter`] does not expose a link-style
/// attachment handle or automatically track group attachments for cleanup.
/// Dropping [`ReusePortSocketFilter`] or [`crate::Ebpf`] does not detach the
/// program; call [`ReusePortSocketFilter::detach`] explicitly when you want to
/// remove it, or close all sockets in the group so the group itself is
/// destroyed.
///
/// [`SkReuseport`](crate::programs::SkReuseport) is the purpose-built program
/// type for `SO_REUSEPORT` selection on newer kernels; `ReusePortSocketFilter`
/// is useful when you need the older `SO_ATTACH_REUSEPORT_EBPF` socket-filter
/// path or want to attach an existing `SEC("socket")` program to a reuseport
/// group.
///
/// # Minimum kernel version
///
/// `SO_ATTACH_REUSEPORT_EBPF` can attach socket filter programs to UDP
/// `SO_REUSEPORT` groups starting in Linux 4.5 and TCP groups starting in
/// Linux 4.6:
/// <https://github.com/torvalds/linux/blob/v4.5/net/ipv4/udp.c#L521-L522>
/// <https://github.com/torvalds/linux/blob/v4.6/net/ipv4/inet_hashtables.c#L237-L239>
///
/// `SO_DETACH_REUSEPORT_BPF` is handled starting in Linux 5.3:
/// <https://github.com/torvalds/linux/blob/v5.3/net/core/sock.c#L1042-L1044>
///
/// # Examples
///
/// ```no_run
/// # #[derive(Debug, thiserror::Error)]
/// # enum Error {
/// # #[error(transparent)]
/// # IO(#[from] std::io::Error),
/// # #[error(transparent)]
/// # Map(#[from] aya::maps::MapError),
/// # #[error(transparent)]
/// # Program(#[from] aya::programs::ProgramError),
/// # #[error(transparent)]
/// # Ebpf(#[from] aya::EbpfError)
/// # }
/// # let mut bpf = aya::Ebpf::load(&[])?;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4, TcpListener},
/// os::fd::AsRawFd,
/// };
///
/// use aya::programs::ReusePortSocketFilter;
/// use nix::sys::socket::{
/// AddressFamily, Backlog, SockFlag, SockType, SockaddrIn, bind, listen, setsockopt,
/// socket, sockopt::ReusePort,
/// };
///
/// // `SO_REUSEPORT` must be set before `bind(2)`. `std::net::TcpListener`
/// // does not expose that pre-bind socket setup step, so this example uses
/// // `nix` to create and configure the socket directly.
/// fn reuseport_listener(port: u16) -> io::Result<TcpListener> {
/// let fd = socket(
/// AddressFamily::Inet,
/// SockType::Stream,
/// SockFlag::empty(),
/// None,
/// )
/// .map_err(io::Error::other)?;
///
/// setsockopt(&fd, ReusePort, &true).map_err(io::Error::other)?;
///
/// let addr = SockaddrIn::from(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port));
/// bind(fd.as_raw_fd(), &addr).map_err(io::Error::other)?;
/// listen(&fd, Backlog::MAXCONN).map_err(io::Error::other)?;
///
/// Ok(TcpListener::from(fd))
/// }
///
/// # #[cfg(target_os = "linux")] {
/// let listener = reuseport_listener(8080)?;
/// let program: &mut ReusePortSocketFilter = bpf.program_mut("select_socket").unwrap().try_into()?;
/// program.load()?;
/// program.attach(&listener)?;
/// # }
/// # Ok::<(), Error>(())
/// ```
// Invariant: `TryFrom<Program>` casts references between `SocketFilter` and
// `ReusePortSocketFilter`. Keep both types as transparent wrappers around the
// same `ProgramData<FdLink>` field.