nf 0.1.0

A port of the netfilter framework written entirely in rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#![allow(non_snake_case, non_upper_case_globals, non_camel_case_types)]

use libc::_SC_PAGESIZE;
use libc::{
    bind, c_void, getsockname, getsockopt, recvmsg, setsockopt, sockaddr, sysconf, AF_NETLINK,
    MSG_TRUNC, SOCK_RAW,
};
use libc::{close, iovec, msghdr, SOL_NETLINK};

/// Represents a netlink socket connection
///
/// Manages netlink socket communication including file descriptor
/// and socket address information.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(C)]
pub struct Socket {
    /// File descriptor for the socket
    pub fd: i32,
    /// Netlink socket address
    pub addr: Sockaddr,
}

/// Represents a netlink socket address
///
/// Contains addressing information for netlink sockets including
/// family, process ID, and multicast group membership.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(C)]
pub struct Sockaddr {
    /// Address family (AF_NETLINK)
    pub family: u16,
    /// Padding to align structure
    pad: u16,
    /// Process ID (0 for kernel)
    pub pid: u32,
    /// Multicast groups mask
    pub groups: u32,
}

impl Socket {
    /// Special value indicating that the kernel should assign a unique port ID
    pub const AUTOPID: u32 = 0;
    
    /// Default buffer size for netlink message dumps
    pub const DUMP_SIZE: usize = 32768;

    /// Creates a new socket with default values
    ///
    /// # Returns
    /// A new Socket instance with file descriptor set to -1 (invalid)
    /// and default Sockaddr values
    pub const fn new() -> Socket {
        Socket {
            fd: -1,
            addr: Sockaddr {
                family: AF_NETLINK as u16,
                pad: 0,
                pid: Socket::AUTOPID,
                groups: 0,
            },
        }
    }

    /// Sets socket file descriptor and address values
    ///
    /// # Parameters
    /// * `fd` - File descriptor for the socket
    /// * `addr` - Socket address structure
    pub const fn set(&mut self, fd: i32, addr: Sockaddr) {
        self.fd = fd;
        self.addr = addr;
    }

    /// Gets the socket file descriptor
    ///
    /// # Returns
    /// The socket file descriptor
    pub const fn fd(&self) -> i32 {
        self.fd
    }

    /// Gets the socket address
    ///
    /// # Returns
    /// The socket address structure
    pub const fn addr(&self) -> Sockaddr {
        self.addr
    }

    /// Resets the socket to default values
    ///
    /// Sets the file descriptor to -1 and initializes the address
    /// with default values.
    pub fn reset(&mut self) {
        self.fd = -1;
        self.addr = Sockaddr {
            family: AF_NETLINK as u16,
            pad: 0,
            pid: Socket::AUTOPID,
            groups: 0,
        };
    }

    /// Gets a const pointer to this socket
    ///
    /// # Returns
    /// A const pointer to this socket
    pub fn as_ptr(&self) -> *const Self {
        self
    }

    /// Gets a mutable pointer to this socket
    ///
    /// # Returns
    /// A mutable pointer to this socket
    pub fn as_mut_ptr(&mut self) -> *mut Self {
        self
    }

    /// Determines the optimal buffer size for netlink communications
    ///
    /// Uses system page size, capped at 8192 bytes.
    ///
    /// # Returns
    /// The recommended buffer size in bytes
    pub fn buffer_size() -> usize {
        unsafe { sysconf(_SC_PAGESIZE).min(8192) as usize }
    }

    /// Gets the port ID assigned to this socket
    ///
    /// # Returns
    /// The port ID from the socket address
    pub const fn portid(&self) -> u32 {
        self.addr.pid
    }

    /// Internal helper to open a netlink socket with flags
    ///
    /// # Parameters
    /// * `bus` - Netlink bus/protocol to use
    /// * `flags` - Additional socket flags
    ///
    /// # Returns
    /// Mutable pointer to this socket, or null pointer on error
    pub fn __open(&mut self, bus: i32, flags: i32) -> *mut Socket {
        unsafe {
            self.fd = libc::socket(AF_NETLINK, SOCK_RAW | flags, bus);
            if self.fd == -1 {
                return std::ptr::null_mut();
            }
            self
        }
    }

    /// Opens a netlink socket with default flags
    ///
    /// # Parameters
    /// * `bus` - Netlink bus/protocol to use
    ///
    /// # Returns
    /// Mutable pointer to this socket, or null pointer on error
    pub fn open(&mut self, bus: i32) -> *mut Socket {
        self.__open(bus, 0)
    }

    /// Opens a netlink socket with specified flags
    ///
    /// # Parameters
    /// * `bus` - Netlink bus/protocol to use
    /// * `flags` - Additional socket flags
    ///
    /// # Returns
    /// Mutable pointer to this socket, or null pointer on error
    pub fn open2(&mut self, bus: i32, flags: i32) -> *mut Socket {
        self.__open(bus, flags)
    }

    /// Opens an existing file descriptor as a netlink socket
    ///
    /// # Returns
    /// Mutable pointer to this socket, or null pointer on error
    pub fn fdopen(&mut self) -> *mut Socket {
        unsafe {
            self.addr = Sockaddr::new();
            let mut addr_len = size_of::<Sockaddr>() as u32;
            if getsockname(
                self.fd,
                &mut self.addr as *mut Sockaddr as *mut sockaddr,
                &mut addr_len,
            ) == -1
            {
                return std::ptr::null_mut();
            }
            self
        }
    }

    /// Binds the socket to a specific address
    ///
    /// # Parameters
    /// * `groups` - Multicast groups to join
    /// * `pid` - Process ID to use (0 for kernel)
    ///
    /// # Returns
    /// 0 on success, -1 on error
    pub fn bind(&mut self, groups: u32, pid: u32) -> i32 {
        unsafe {
            self.addr.set(AF_NETLINK as u16, pid, groups);
            let addr_size = size_of::<Sockaddr>() as u32;

            if bind(
                self.fd,
                &self.addr as *const Sockaddr as *const sockaddr,
                addr_size,
            ) < 0
            {
                return -1;
            }

            let mut actual_len = addr_size;
            if getsockname(
                self.fd,
                &mut self.addr as *mut Sockaddr as *mut sockaddr,
                &mut actual_len,
            ) < 0
            {
                return -1;
            }

            if actual_len != addr_size || self.addr.family != AF_NETLINK as u16 {
                return -1;
            }

            0
        }
    }

    /// Sends a message over the socket
    ///
    /// # Parameters
    /// * `buf` - Message buffer
    /// * `len` - Message length
    ///
    /// # Returns
    /// Number of bytes sent, or -1 on error
    pub fn sendto(&mut self, buf: *const u8, len: usize) -> isize {
        unsafe {
            libc::sendto(
                self.fd,
                buf as *const c_void,
                len,
                0,
                &self.addr as *const Sockaddr as *const sockaddr,
                size_of::<Sockaddr>() as u32,
            )
        }
    }

    /// Receives a message over the socket
    ///
    /// # Parameters
    /// * `buf` - Message buffer
    /// * `bufsiz` - Message buffer size
    ///
    /// # Returns
    /// Number of bytes received, or -1 on error
    pub fn recvfrom(&mut self, buf: *mut u8, bufsiz: usize) -> isize {
        unsafe {
            let mut iov = iovec {
                iov_base: buf as *mut c_void,
                iov_len: bufsiz,
            };

            let mut msg = msghdr {
                msg_name: &mut self.addr as *mut Sockaddr as *mut c_void,
                msg_namelen: size_of::<Sockaddr>() as u32,
                msg_iov: &mut iov,
                msg_iovlen: 1,
                msg_control: std::ptr::null_mut(),
                msg_controllen: 0,
                msg_flags: 0,
            };

            let ret = recvmsg(self.fd, &mut msg, 0);
            if ret == -1 {
                return ret;
            }

            if (msg.msg_flags & MSG_TRUNC) != 0 {
                eprintln!("Message truncated");
                return -1;
            }

            if msg.msg_namelen != size_of::<Sockaddr>() as u32 {
                eprintln!("Unexpected address length {}", msg.msg_namelen);
                return -1;
            }

            ret
        }
    }

    /// Closes the socket
    ///
    /// # Returns
    /// 0 on success, -1 on error
    pub fn close(&mut self) -> i32 {
        unsafe { close(self.fd) }
    }

    /// Sets a socket option
    ///
    /// # Parameters
    /// * `type_` - Option type
    /// * `buf` - Option value buffer
    /// * `len` - Option value length
    ///
    /// # Returns
    /// 0 on success, -1 on error
    pub fn setsockopt(&mut self, type_: i32, buf: *mut u8, len: u32) -> i32 {
        unsafe { setsockopt(self.fd, SOL_NETLINK as i32, type_, buf as *mut c_void, len) }
    }

    /// Gets a socket option
    ///
    /// # Parameters
    /// * `type_` - Option type
    /// * `buf` - Option value buffer
    /// * `len` - Option value length pointer
    ///
    /// # Returns
    /// 0 on success, -1 on error
    pub fn getsockopt(&mut self, type_: i32, buf: *mut u8, len: *mut u32) -> i32 {
        unsafe { getsockopt(self.fd, SOL_NETLINK as i32, type_, buf as *mut c_void, len) }
    }
}

impl Sockaddr {
    /// Creates a new socket address with default values
    ///
    /// # Returns
    /// A new Sockaddr instance with default values
    pub const fn new() -> Sockaddr {
        Sockaddr {
            family: AF_NETLINK as u16,
            pad: 0,
            pid: 0,
            groups: 0,
        }
    }

    /// Sets the socket address values
    ///
    /// # Parameters
    /// * `family` - Address family (AF_NETLINK)
    /// * `pid` - Process ID (0 for kernel)
    /// * `groups` - Multicast groups mask
    pub const fn set(&mut self, family: u16, pid: u32, groups: u32) {
        self.family = family;
        self.pid = pid;
        self.groups = groups;
    }

    /// Resets the socket address to default values
    pub const fn reset(&mut self) {
        self.family = AF_NETLINK as u16;
        self.pid = 0;
        self.groups = 0;
    }

    /// Gets the address family
    ///
    /// # Returns
    /// The address family (AF_NETLINK)
    pub const fn family(&self) -> u16 {
        self.family
    }

    /// Gets the process ID
    ///
    /// # Returns
    /// The process ID (0 for kernel)
    pub const fn pid(&self) -> u32 {
        self.pid
    }

    /// Gets the multicast groups mask
    ///
    /// # Returns
    /// The multicast groups mask
    pub const fn groups(&self) -> u32 {
        self.groups
    }

    /// Gets a const pointer to this socket address
    ///
    /// # Returns
    /// A const pointer to this socket address
    pub fn as_ptr(&self) -> *const Sockaddr {
        self
    }

    /// Gets a mutable pointer to this socket address
    ///
    /// # Returns
    /// A mutable pointer to this socket address
    pub fn as_mut_ptr(&mut self) -> *mut Sockaddr {
        self
    }

    /// Gets the size of the socket address structure
    ///
    /// # Returns
    /// The size of the socket address structure in bytes
    pub const fn size() -> usize {
        size_of::<Sockaddr>()
    }
}

impl From<u128> for Socket {
    /// Converts a u128 value to a Socket instance
    ///
    /// # Parameters
    /// * `u` - u128 value to convert
    ///
    /// # Returns
    /// A new Socket instance
    fn from(u: u128) -> Socket {
        let bytes = u.to_ne_bytes();
        Socket {
            fd: i32::from_ne_bytes(bytes[0..4].try_into().unwrap()),
            addr: Sockaddr {
                family: u16::from_ne_bytes(bytes[4..6].try_into().unwrap()),
                pad: 0,
                pid: u32::from_ne_bytes(bytes[8..12].try_into().unwrap()),
                groups: u32::from_ne_bytes(bytes[12..16].try_into().unwrap()),
            },
        }
    }
}

impl From<Socket> for u128 {
    /// Converts a Socket instance to a u128 value
    ///
    /// # Parameters
    /// * `s` - Socket instance to convert
    ///
    /// # Returns
    /// A u128 value
    fn from(s: Socket) -> u128 {
        let mut bytes = [0u8; 16];
        bytes[0..4].copy_from_slice(&s.fd.to_ne_bytes());
        bytes[4..6].copy_from_slice(&s.addr.family.to_ne_bytes());
        // bytes 6-7 are already 0
        bytes[8..12].copy_from_slice(&s.addr.pid.to_ne_bytes());
        bytes[12..16].copy_from_slice(&s.addr.groups.to_ne_bytes());
        u128::from_ne_bytes(bytes)
    }
}

impl From<Sockaddr> for sockaddr {
    /// Converts a Sockaddr instance to a sockaddr instance
    ///
    /// # Parameters
    /// * `saddr` - Sockaddr instance to convert
    ///
    /// # Returns
    /// A sockaddr instance
    fn from(saddr: Sockaddr) -> sockaddr {
        let pid_bytes = saddr.pid.to_ne_bytes();
        let group_bytes = saddr.groups.to_ne_bytes();
        sockaddr {
            sa_family: saddr.family,
            sa_data: [
                0,
                0,
                pid_bytes[0] as i8,
                pid_bytes[1] as i8,
                pid_bytes[2] as i8,
                pid_bytes[3] as i8,
                group_bytes[0] as i8,
                group_bytes[1] as i8,
                group_bytes[2] as i8,
                group_bytes[3] as i8,
                0,
                0,
                0,
                0,
            ],
        }
    }
}

impl From<sockaddr> for Sockaddr {
    /// Converts a sockaddr instance to a Sockaddr instance
    ///
    /// # Parameters
    /// * `sa` - sockaddr instance to convert
    ///
    /// # Returns
    /// A Sockaddr instance
    fn from(sa: sockaddr) -> Sockaddr {
        let pid_bytes = [
            sa.sa_data[2] as u8,
            sa.sa_data[3] as u8,
            sa.sa_data[4] as u8,
            sa.sa_data[5] as u8,
        ];
        let groups_bytes = [
            sa.sa_data[6] as u8,
            sa.sa_data[7] as u8,
            sa.sa_data[8] as u8,
            sa.sa_data[9] as u8,
        ];

        Sockaddr {
            family: sa.sa_family,
            pad: 0,
            pid: u32::from_ne_bytes(pid_bytes),
            groups: u32::from_ne_bytes(groups_bytes),
        }
    }
}