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
use crate::mnl::attr::Attribute;
use crate::mnl::ALIGN;
use crate::tp;
use libc::{c_void, fileno, fprintf, isatty, FILE};
use std::ptr::{copy_nonoverlapping, write_bytes};
/// Represents a netlink message container
///
/// This structure provides a view of a netlink message, containing
/// both the header pointer and the data buffer.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Message {
/// Pointer to the netlink message header
pub hdr: *mut Header,
/// Pointer to the message data buffer
pub data: *mut u8,
/// Length of the message in bytes
pub len: usize,
}
/// Represents a netlink message header
///
/// All netlink messages start with this header which defines
/// the message length, type, flags, sequence number, and port ID.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Header {
/// Total message length including header
pub len: u32,
/// Message content type
pub type_: u16,
/// Additional message flags
pub flags: u16,
/// Sequence number
pub seq: u32,
/// Sender port ID
pub pid: u32,
}
/// Represents a batch of netlink messages
///
/// Used to efficiently send multiple netlink messages in a single buffer.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(C)]
pub struct Batch {
/// The buffer used to store the batch messages
pub buf: *mut u8,
/// Maximum size of the buffer
pub limit: usize,
/// Current used length of the buffer
pub buflen: usize,
/// Pointer to the current netlink message in the batch
pub cur: *mut u8,
/// Flag indicating if the batch buffer has overflowed
pub overflow: bool,
}
impl Message {
/// Flag for request messages
pub const REQUEST: u32 = 1; /* It is request message. */
/// Flag for multipart messages (terminated by NLMSG_DONE)
pub const MULTI: u32 = 2; /* Multipart message, terminated by NLMSG_DONE */
/// Flag for reply with acknowledgment
pub const ACK: u32 = 4; /* Reply with ack, with zero or error code */
/// Flag to request echo of the message
pub const ECHO: u32 = 8; /* Echo this request */
/// Flag indicating dump was interrupted due to sequence change
pub const DUMP_INTR: u32 = 16; /* Dump was inconsistent due to sequence change */
/* Modifiers to GET request */
/// Specifies tree root for GET requests
pub const ROOT: u32 = 0x100; /* specify tree root */
/// Returns all matching items for GET requests
pub const MATCH: u32 = 0x200; /* return all matching */
/// Requests atomic GET operation
pub const ATOMIC: u32 = 0x400; /* atomic GET */
/// Combination of ROOT and MATCH flags for dump operations
pub const DUMP: u32 = Self::ROOT | Self::MATCH;
/* Modifiers to NEW request */
/// Override existing object if it exists
pub const REPLACE: u32 = 0x100; /* Override existing */
/// Don't touch object if it already exists
pub const EXCLUDE: u32 = 0x200; /* Do not touch, if it exists */
/// Create object if it doesn't exist
pub const CREATE: u32 = 0x400; /* Create, if it does not exist */
/// Add to end of list
pub const APPEND: u32 = 0x800; /* Add to end of list */
/// Alignment boundary for netlink messages
pub const ALIGNTO: u32 = 4;
/* Netlink message types */
/// No operation message
pub const NOOP: u16 = 0x1; /* Nothing. */
/// Error message
pub const ERROR: u16 = 0x2; /* Error */
/// End of dump marker
pub const DONE: u16 = 0x3; /* End of a dump */
/// Data overflow indicator
pub const OVERRUN: u16 = 0x4; /* Data lost */
/// Minimum user-defined message type
pub const MIN_TYPE: u16 = 0x10; /* < 0x10: reserved control messages */
/// Size of the netlink message header, aligned
pub const HDRLEN: usize = ALIGN(size_of::<Header>());
/// Calculates the total message length including header
///
/// # Parameters
/// * `len` - Length of the payload
///
/// # Returns
/// Total message length including header
#[inline]
pub const fn len(len: usize) -> usize {
len + Self::HDRLEN
}
/// Calculates the aligned space needed for this message
///
/// # Returns
/// The aligned message size
#[inline]
pub fn space(&self) -> usize {
ALIGN(self.len)
}
/// Gets a pointer to the message data (payload)
///
/// # Parameters
/// * `nlh` - Pointer to the netlink header
///
/// # Returns
/// Pointer to the message payload
#[inline]
pub fn data(nlh: *const Header) -> *mut u8 {
unsafe { (nlh as *const u8).add(Self::HDRLEN) as *mut u8 }
}
/// Gets the next message in a sequence
///
/// Updates internal pointers and counters.
///
/// # Returns
/// Pointer to the next message header
#[inline]
pub fn next(&mut self) -> *const Header {
let len = unsafe { (*self.hdr).len };
let aligned_len = ALIGN(len as usize);
self.len -= aligned_len;
unsafe { (self.hdr as *const u8).add(aligned_len) as *const Header }
}
/// Checks if the message structure is valid
///
/// Verifies that the message header and length are consistent
/// with the buffer size.
///
/// # Returns
/// `true` if the message is valid, `false` otherwise
#[inline]
pub fn is_ok(&self) -> bool {
unsafe {
self.len >= size_of::<Header>()
&& (*self.hdr).len >= size_of::<Header>() as u32
&& (*self.hdr).len as usize <= self.len
}
}
/// Gets the payload length of the message
///
/// # Returns
/// Length of the message payload in bytes
#[inline]
pub fn payload(&self) -> u32 {
unsafe { (*self.hdr).len - Self::HDRLEN as u32 }
}
}
impl Header {
/// Gets a const pointer to this header
///
/// # Returns
/// A const pointer to this header
pub const fn as_ptr(&self) -> *const Self {
self as *const Self
}
/// Gets a mutable pointer to this header
///
/// # Returns
/// A mutable pointer to this header
pub const fn as_mut_ptr(&mut self) -> *mut Self {
self as *mut Self
}
/// Aligns the header to the next message boundary
///
/// # Parameters
/// * `nlh` - Pointer to the netlink header
///
/// # Returns
/// Pointer to the next aligned header
pub const fn align(nlh: *const Self) -> *const Self {
unsafe { (nlh as *const u8).wrapping_add(ALIGN((*nlh).len as usize)) as *const Self }
}
/// Size of the netlink message header
pub const HDRLEN: usize = size_of::<Self>();
/// Calculates the size of a message including header
///
/// # Parameters
/// * `len` - Length of the payload
///
/// # Returns
/// Total message length including header
pub const fn size(len: usize) -> usize {
len + Self::HDRLEN
}
/// Gets the payload length of a message
///
/// # Parameters
/// * `nlh` - Pointer to the netlink header
///
/// # Returns
/// Length of the message payload in bytes
pub const fn get_payload_len(nlh: *const Self) -> usize {
unsafe { (*nlh).len as usize - Self::HDRLEN }
}
/// Initializes a new netlink message header
///
/// # Parameters
/// * `buf` - Pointer to the message buffer
///
/// # Returns
/// Pointer to the initialized header
pub fn put_header(buf: *mut i8) -> *mut Self {
unsafe {
let len = ALIGN(size_of::<Self>()) as u32;
let nlh = buf as *mut Self;
write_bytes(buf, 0, len as usize);
(*nlh).len = len;
nlh
}
}
/// Initializes an extra header for this message
///
/// # Parameters
/// * `size` - Size of the extra header
///
/// # Returns
/// Pointer to the extra header
pub fn put_extra_header(&mut self, size: usize) -> *mut i8 {
unsafe {
let ptr = (self as *mut Self as *mut i8).add(self.len as usize);
let len = ALIGN(size);
write_bytes(ptr, 0, len);
self.len += len as u32;
ptr
}
}
/// Gets a pointer to the message payload
///
/// # Returns
/// Pointer to the message payload
pub fn get_payload(&self) -> *mut u8 {
unsafe { (self as *const Self as *mut u8).add(Self::HDRLEN) }
}
/// Gets a pointer to the message payload at a specific offset
///
/// # Parameters
/// * `offset` - Offset into the payload
///
/// # Returns
/// Pointer to the payload at the specified offset
pub fn get_payload_offset(&self, offset: usize) -> *mut u8 {
unsafe { (self as *const Self as *mut u8).add(Self::HDRLEN + ALIGN(offset)) }
}
/// Checks if the message header is valid
///
/// Verifies that the message header and length are consistent
/// with the buffer size.
///
/// # Parameters
/// * `len` - Length of the buffer
///
/// # Returns
/// `true` if the message is valid, `false` otherwise
pub fn is_ok(&self, len: i32) -> bool {
if len < 0 {
return false;
}
let ulen = len as usize;
ulen >= size_of::<Self>()
&& self.len as usize >= size_of::<Self>()
&& self.len as usize <= ulen
}
/// Gets the next message in a sequence
///
/// Updates internal pointers and counters.
///
/// # Parameters
/// * `len` - Pointer to the remaining buffer length
///
/// # Returns
/// Pointer to the next message header
pub fn next(&self, len: &mut i32) -> &mut Self {
unsafe {
*len -= ALIGN(self.len as usize) as i32;
(self as *const Self as *mut Self)
.add(ALIGN(self.len as usize) / size_of::<Self>())
.as_mut()
.unwrap()
}
}
/// Gets a pointer to the end of the message payload
///
/// # Returns
/// Pointer to the end of the message payload
pub fn get_payload_tail(&self) -> *mut u8 {
unsafe { (self as *const Self as *mut u8).add(self.len as usize) }
}
/// Checks if the sequence number matches
///
/// # Parameters
/// * `seq` - Sequence number to check
///
/// # Returns
/// `true` if the sequence numbers match, `false` otherwise
pub fn seq_ok(&self, seq: u32) -> bool {
if self.seq == 0 || seq == 0 {
return true;
}
self.seq == seq
}
/// Checks if the port ID matches
///
/// # Parameters
/// * `portid` - Port ID to check
///
/// # Returns
/// `true` if the port IDs match, `false` otherwise
pub fn portid_ok(&self, portid: u32) -> bool {
if self.pid == 0 || portid == 0 {
return true;
}
self.pid == portid
}
/// Prints the message header to a file
///
/// # Parameters
/// * `fd` - File descriptor to print to
pub fn fprintf_header(&self, fd: *mut FILE) {
unsafe {
fprintf(fd, tp!("----------------\t------------------\n"));
fprintf(fd, tp!("| %.010u |\t| message length |\n"), self.len);
fprintf(
fd,
tp!("| %.05u | %c%c%c%c |\t| type | flags |\n"),
self.type_ as u32,
if (self.flags as u32 & Message::REQUEST) == Message::REQUEST {
'R'
} else {
'-'
},
if (self.flags & Message::MULTI as u16) == Message::MULTI as u16 {
'M'
} else {
'-'
},
if (self.flags & Message::ACK as u16) == Message::ACK as u16 {
'A'
} else {
'-'
},
if (self.flags & Message::ECHO as u16) == Message::ECHO as u16 {
'E'
} else {
'-'
},
);
fprintf(fd, tp!("| %.010u |\t| sequence number|\n"), self.seq);
fprintf(fd, tp!("| %.010u |\t| port ID |\n"), self.pid);
fprintf(fd, tp!("----------------\t------------------\n"));
}
}
/// Prints an attribute to a file
///
/// # Parameters
/// * `fd` - File descriptor to print to
/// * `attr` - Attribute to print
pub fn fprintf_attr_color(fd: *mut FILE, attr: *const Attribute) {
unsafe {
fprintf(
fd,
tp!("|%c[%d;%dm%.5u%c[%dm|%c[%d;%dm%c%c%c[%dm|%c[%d;%dm%.5u%c[%dm|\t"),
27,
1,
31,
(*attr).len as u32,
27,
0,
27,
1,
32,
if ((*attr).type_ & Attribute::NESTED as u16) == Attribute::NESTED as u16 {
'N'
} else {
'-'
},
if ((*attr).type_ & Attribute::NET_BYTEORDER as u16)
== Attribute::NET_BYTEORDER as u16
{
'B'
} else {
'-'
},
27,
0,
27,
1,
34,
((*attr).type_ & Attribute::TYPE_MASK as u16) as u32,
27,
0,
);
}
}
/// Prints an attribute to a file in raw format
///
/// # Parameters
/// * `fd` - File descriptor to print to
/// * `attr` - Attribute to print
pub fn fprintf_attr_raw(fd: *mut FILE, attr: *const Attribute) {
unsafe {
fprintf(
fd,
tp!("|%.5u|%c%c|%.5u|\t"),
(*attr).len as u32,
if ((*attr).type_ & Attribute::NESTED as u16) == Attribute::NESTED as u16 {
'N'
} else {
'-'
},
if ((*attr).type_ & Attribute::NET_BYTEORDER as u16)
== Attribute::NET_BYTEORDER as u16
{
'B'
} else {
'-'
},
((*attr).type_ & Attribute::TYPE_MASK as u16) as u32,
);
}
}
/// Prints the message payload to a file
///
/// # Parameters
/// * `fd` - File descriptor to print to
/// * `extra_header_size` - Size of any extra headers
pub fn fprintf_payload(&self, fd: *mut FILE, mut extra_header_size: usize) {
unsafe {
const ANSI_SPACE: *mut i8 = 0x20 as *mut i8;
let colorize = if let Ok(fdnum) = fileno(fd).try_into() {
isatty(fdnum) != 0
} else {
false
};
let mut i = size_of::<Header>();
let mut rem = 0;
let base_ptr = self as *const Self as *const i8;
while i < self.len as usize {
let attr = base_ptr.add(i) as *const Attribute;
let ba = [
base_ptr.add(i),
base_ptr.add(i + 1),
base_ptr.add(i + 2),
base_ptr.add(i + 3),
];
// netlink control message
if self.type_ < Message::MIN_TYPE {
fprintf(
fd,
tp!("| %.2x %.2x %.2x %.2x |\t"),
0xff & *ba[0] as u32,
0xff & *ba[1] as u32,
0xff & *ba[2] as u32,
0xff & *ba[3] as u32,
);
fprintf(fd, tp!("| |\n"));
// special handling for the extra header
} else if extra_header_size > 0 {
extra_header_size = extra_header_size.saturating_sub(4);
fprintf(
fd,
tp!("| %.2x %.2x %.2x %.2x |\t"),
0xff & *ba[0] as u32,
0xff & *ba[1] as u32,
0xff & *ba[2] as u32,
0xff & *ba[3] as u32,
);
fprintf(fd, tp!("| extra header |\n"));
// this seems like an attribute header
} else if rem == 0 && ((*attr).type_ & Attribute::TYPE_MASK as u16) != 0 {
if colorize {
Self::fprintf_attr_color(fd, attr);
} else {
Self::fprintf_attr_raw(fd, attr);
}
fprintf(fd, tp!("|len |flags| type|\n"));
if ((*attr).type_ & Attribute::NESTED as u16) != Attribute::NESTED as u16 {
rem = (Attribute::align((*attr).len as usize) - size_of::<Attribute>())
as i32;
}
// this is the attribute payload
} else if rem > 0 {
rem -= 4;
fprintf(
fd,
tp!("| %.2x %.2x %.2x %.2x |\t"),
0xff & *ba[0] as u32,
0xff & *ba[1] as u32,
0xff & *ba[2] as u32,
0xff & *ba[3] as u32,
);
fprintf(fd, tp!("| data |"));
let chars = ba.map(|ptr| {
let c = *ptr;
if c == 0 { *ANSI_SPACE } else { c }
});
fprintf(
fd,
tp!("\t %c %c %c %c\n"),
chars[0] as i32,
chars[1] as i32,
chars[2] as i32,
chars[3] as i32,
);
}
i += 4;
}
fprintf(fd, tp!("----------------\t------------------\n"));
}
}
/// Prints the message to a file
///
/// # Parameters
/// * `fd` - File descriptor to print to
/// * `len` - Pointer to the remaining buffer length
/// * `extra_header_size` - Size of any extra headers
pub fn fprintf(&mut self, fd: *mut FILE, len: &mut i32, extra_header_size: usize) {
let mut current = self;
let mut remaining = len;
unsafe {
while current.is_ok(*remaining) {
current.fprintf_header(fd);
current.fprintf_payload(fd, extra_header_size);
current = current.next(remaining);
}
}
}
}
impl Batch {
/// Creates a new batch from a buffer
///
/// # Parameters
/// * `buf` - Pointer to the buffer
/// * `limit` - Maximum size of the buffer
///
/// # Returns
/// A new batch instance
pub fn new(buf: *mut u8, limit: usize) -> Self {
Batch {
buf,
limit,
buflen: 0,
cur: buf,
overflow: false,
}
}
/// Gets a pointer to this batch
///
/// # Returns
/// A pointer to this batch
pub fn as_ptr(&mut self) -> *mut Self {
self as *mut Self
}
/// Gets a mutable pointer to this batch
///
/// # Returns
/// A mutable pointer to this batch
pub fn as_mut_ptr(&mut self) -> *mut Self {
self as *mut Self
}
/// Starts a new batch from a buffer
///
/// # Parameters
/// * `buf` - Pointer to the buffer
/// * `limit` - Maximum size of the buffer
///
/// # Returns
/// A pointer to this batch
pub fn start(&mut self, buf: *mut u8, limit: usize) -> *mut Self {
self.buf = buf;
self.limit = limit;
self.buflen = 0;
self.cur = buf;
self.overflow = false;
self.as_mut_ptr()
}
/// Stops the batch and frees the buffer
pub fn stop(&mut self) {
unsafe {
libc::free(self.buf as *mut c_void);
}
}
/// Moves to the next message in the batch
///
/// # Returns
/// `true` if the next message is valid, `false` otherwise
pub fn next(&mut self) -> bool {
unsafe {
let nlh = self.cur as *mut Header;
let next_size = (*nlh).len as usize;
if self.buflen + next_size > self.limit {
self.overflow = true;
return false;
}
self.cur = self.buf.add(self.buflen);
self.buflen += next_size;
true
}
}
/// Resets the batch to its initial state
pub fn reset(&mut self) {
unsafe {
if self.overflow {
let nlh = self.cur as *mut Header;
let len = (*nlh).len as usize;
copy_nonoverlapping(self.cur, self.buf, len);
self.buflen = len;
self.cur = self.buf;
self.overflow = false;
} else {
self.buflen = 0;
self.cur = self.buf;
}
}
}
/// Gets the size of the batch
///
/// # Returns
/// The size of the batch in bytes
pub fn size(&self) -> usize {
self.buflen
}
/// Gets a pointer to the head of the batch
///
/// # Returns
/// A pointer to the head of the batch
pub fn head(&self) -> *mut u8 {
self.buf
}
/// Gets a pointer to the current message in the batch
///
/// # Returns
/// A pointer to the current message in the batch
pub fn current(&self) -> *mut u8 {
self.cur
}
/// Checks if the batch is empty
///
/// # Returns
/// `true` if the batch is empty, `false` otherwise
pub fn is_empty(&self) -> bool {
self.buflen == 0
}
}