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
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
use crate::mnl::attr::DataType::{FLAG, MAX, NESTED, NUL_STRING, STRING};
use std::ptr::{copy_nonoverlapping, write_bytes};

use crate::mnl::cb::Callback;
use crate::mnl::nlmsg::Header;
use crate::mnl::{ALIGN, MNL_CB_OK};
use libc::{c_void, strlen, ERANGE};

/// Represents different data types for netlink attributes
///
/// These types are used to validate and handle attribute data appropriately
/// in netlink communications.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
pub enum DataType {
    /// Unspecified data type
    UNSPEC,
    /// 8-bit unsigned integer
    U8,
    /// 16-bit unsigned integer
    U16,
    /// 32-bit unsigned integer
    U32,
    /// 64-bit unsigned integer
    U64,
    /// Null-terminated string
    STRING,
    /// Flag (no data, presence is the value)
    FLAG,
    /// Milliseconds (u64)
    MSECS,
    /// Nested attribute
    NESTED,
    /// Backward compatibility for nested attribute
    NESTED_COMPAT,
    /// Null string (with explicit null terminator)
    NUL_STRING,
    /// Binary blob
    BINARY,
    /// Maximum value (used for validation)
    MAX,
}
impl From<u32> for DataType {
    fn from(value: u32) -> Self {
        match value {
            0 => DataType::UNSPEC,
            1 => DataType::U8,
            2 => DataType::U16,
            3 => DataType::U32,
            4 => DataType::U64,
            5 => STRING,
            6 => FLAG,
            7 => DataType::MSECS,
            8 => NESTED,
            9 => DataType::NESTED_COMPAT,
            10 => NUL_STRING,
            11 => DataType::BINARY,
            _ => MAX,
        }
    }
}

/// Function pointer type for attribute callback handlers
///
/// Callbacks receive a pointer to the current attribute and user-provided data,
/// and return an integer status code.
/// 
/// # Parameters
/// * `attr` - Pointer to the current netlink attribute being processed
/// * `data` - User-provided data pointer that's passed to the callback
/// 
/// # Returns
/// Integer status code indicating whether processing should continue
pub type attr_callback_t = *mut fn(attr: *const Attribute, data: *mut u8) -> i32;

/// Represents a netlink attribute with type-length-value (TLV) format
///
/// Netlink attributes use a TLV format where each attribute consists of:
/// - A length field (including header and payload)
/// - A type field (which may include flags like NESTED and NET_BYTEORDER)
/// - A variable-length payload
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Attribute {
    pub len: u16,   // Total length of attribute (header + payload)
    pub type_: u16, // Type of attribute (including flags)
}

impl Attribute {
    /// Flag bit indicating a nested attribute
    pub const NESTED: i32 = 1 << 15;

    /// Flag bit indicating the attribute value is in network byte order
    pub const NET_BYTEORDER: i32 = 1 << 14;

    /// Mask to extract the attribute type without flag bits
    pub const TYPE_MASK: i32 = !(Self::NESTED | Self::NET_BYTEORDER);

    /// Alignment size for netlink attributes (4 bytes)
    pub const ALIGNTO: usize = 4;

    /// Size of attribute header, aligned to ALIGNTO boundary
    pub const HDRLEN: usize = Self::align(size_of::<Self>());

    /// Creates a new empty attribute
    ///
    /// # Returns
    /// A zeroed attribute structure
    pub const fn new() -> Self {
        Self { len: 0, type_: 0 }
    }

    /// Aligns a length to the attribute alignment boundary
    ///
    /// This ensures proper memory alignment for netlink attributes.
    ///
    /// # Parameters
    /// * `len` - The length to align
    ///
    /// # Returns
    /// The length aligned to ALIGNTO boundary
    pub const fn align(len: usize) -> usize {
        (len + Self::ALIGNTO - 1) & !(Self::ALIGNTO - 1)
    }

    /// Checks if the attribute is empty (all bytes are zero)
    ///
    /// Used to determine if the attribute has been initialized or reset.
    ///
    /// # Returns
    /// `true` if all bytes in the attribute are zero, `false` otherwise
    pub fn is_empty(&self) -> bool {
        unsafe {
            let bytes = self as *const Self as *const u8;
            for i in 0..size_of::<Self>() {
                if *bytes.add(i) != 0 {
                    return false;
                }
            }
            true
        }
    }

    /// Clears the attribute by zeroing its memory
    ///
    /// Resets all bytes of the attribute to zero, effectively clearing it.
    /// Does nothing if the attribute is already empty.
    pub fn reset(&mut self) {
        unsafe {
            if !self.is_empty() {
                write_bytes(self as *mut Self, 0, 1);
            }
        }
    }

    /// Iterates through all attributes in a netlink message
    ///
    /// Provides access to each attribute within the message payload.
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header containing the attributes
    /// * `offset` - Offset in bytes from the start of the payload to the first attribute
    pub fn for_each(&mut self, nlh: &mut Header, offset: usize) {
        unsafe {
            let mut attr = nlh.get_payload_offset(offset) as *mut Self;
            let payload_tail = nlh.get_payload_tail();

            while attr < payload_tail as *mut Self
                && (*attr).is_ok((payload_tail as isize - attr as isize) as i32)
            {
                // Process the attribute here if needed
                attr = (*attr).next();
            }
        }
    }

    /// Internal helper for iterating through attributes in a nested attribute
    fn __for_each_nested(&mut self) -> *mut Self {
        unsafe {
            let mut current = self.get_payload() as *mut Self;
            let payload_len = self.get_payload_len() as isize;
            let payload_start = self.get_payload() as isize;

            while (*current).is_ok(payload_len as i32 - (current as isize - payload_start) as i32) {
                current = (*current).next();
            }
            current
        }
    }
    /// Iterates through attributes in a nested attribute
    ///
    /// Provides access to each attribute within a nested attribute.
    /// 
    /// # Returns
    /// Pointer to the first attribute within the nested attribute
    ///
    /// # Panics
    /// In debug mode, panics if this attribute is not a nested attribute
    pub fn for_each_nested(&mut self) -> *mut Self {
        // Debug assertion to check if this attribute is actually a nested attribute
        debug_assert!(
            (self.type_ & Self::NESTED as u16) != 0,
            "for_each_nested called on a non-nested attribute"
        );

        self.__for_each_nested()
    }

    /// Iterates through attributes in a raw payload buffer
    ///
    /// Used when processing a raw buffer containing netlink attributes.
    ///
    /// # Parameters
    /// * `payload_size` - Size in bytes of the payload buffer
    ///
    /// # Returns
    /// Pointer to the first attribute in the payload
    pub fn for_each_payload(&mut self, payload_size: usize) -> *mut Self {
        unsafe {
            let mut current = self as *mut Self;
            let end_addr = (current as *mut u8).add(payload_size) as *mut Self;

            while current < end_addr
                && (*current).is_ok((end_addr as isize - current as isize) as i32)
            {
                current = (*current).next();
            }
            current
        }
    }

    /// Gets the attribute type value without flag bits
    ///
    /// # Returns
    /// The attribute type with the NESTED and NET_BYTEORDER flag bits masked out
    pub fn get_type(&self) -> u16 {
        self.type_ & Self::TYPE_MASK as u16
    }

    /// Gets the total length of the netlink attribute
    ///
    /// # Returns
    /// The total length of the attribute in bytes, including header and payload
    pub fn len(&self) -> u16 {
        self.len
    }

    /// Gets the length of the attribute payload (value part)
    ///
    /// # Returns
    /// The length of the attribute payload in bytes
    pub fn get_payload_len(&self) -> u16 {
        self.len.saturating_sub(Self::HDRLEN as u16)
    }

    /// Gets pointer to the attribute payload
    ///
    /// # Returns
    /// A mutable pointer to the attribute's payload (value part)
    pub fn get_payload(&self) -> *mut () {
        unsafe { (self as *const Self as *mut u8).add(Self::HDRLEN) as *mut () }
    }

    /// Checks if there is room for an attribute in a buffer
    ///
    /// Verifies that a buffer containing an attribute has enough space
    /// for the attribute, ensuring it is neither malformed nor truncated.
    ///
    /// # Parameters
    /// * `len` - The length of the buffer in bytes
    ///
    /// # Returns
    /// `true` if the attribute fits within the buffer, `false` otherwise
    pub fn is_ok(&self, len: i32) -> bool {
        unsafe {
            len >= size_of::<Self>() as i32
                && self.len >= size_of::<Self>() as u16
                && self.len as i32 <= len
        }
    }
    /// Gets the next attribute in a sequence
    ///
    /// # Returns
    /// A pointer to the next attribute in a sequence, accounting for alignment
    pub fn next(&self) -> *mut Self {
        unsafe { (self as *const Self as *mut u8).add(Self::align(self.len as usize)) as *mut Self }
    }

    /// Verifies if the attribute type is within the supported range
    ///
    /// # Parameters
    /// * `max` - The maximum valid attribute type value
    ///
    /// # Returns
    /// 0 on error, 1 on success
    pub fn type_valid(&self, max: u16) -> i32 {
        if self.get_type() > max {
            println!("Unsupported attribute type");
            return -1;
        }
        1
    }

    /// Internal validation function for netlink attributes
    ///
    /// # Parameters
    /// * `type_` - The expected data type of the attribute
    /// * `exp_len` - The expected length of the attribute payload
    ///
    /// # Returns
    /// 0 on success, negative error code on failure
    pub fn __validate(&self, type_: DataType, exp_len: usize) -> i32 {
        let attr_len = self.get_payload_len() as usize;

        // Handle common validation first
        if type_ == FLAG {
            return if attr_len == 0 { 0 } else { -ERANGE };
        }

        // Check minimum size requirements
        if attr_len < exp_len && type_ != NESTED {
            return -ERANGE;
        }

        match type_ {
            NUL_STRING => {
                if attr_len == 0 {
                    return -ERANGE;
                }
                let attr_data = self.get_payload() as *const i8;
                unsafe {
                    if attr_data.add(attr_len - 1).read() != 0 {
                        return -ERANGE;
                    }
                }
            }
            STRING => {
                if attr_len == 0 {
                    return -ERANGE;
                }
            }
            NESTED => {
                // Empty nested attributes are OK
                if attr_len > 0 && attr_len < Self::HDRLEN {
                    return -ERANGE;
                }
            }
            _ => {
                if exp_len > 0 && attr_len > exp_len {
                    return -ERANGE;
                }
            }
        }

        0
    }

    /// Size lookup table for standard data types
    pub const data_type_len: [usize; 5] = [
        size_of::<u8>(),  // MNL_TYPE_U8
        size_of::<u16>(), // MNL_TYPE_U16
        size_of::<u32>(), // MNL_TYPE_U32
        size_of::<u64>(), // MNL_TYPE_U64
        size_of::<u64>(), // MNL_TYPE_MSECS
    ];

    /// Validates a netlink attribute against its expected data type
    ///
    /// Ensures that integer attributes have sufficient space allocated.
    ///
    /// # Parameters
    /// * `type_` - The expected data type of the attribute
    ///
    /// # Returns
    /// 0 on success, negative error code on failure
    ///
    /// # Panics
    /// In debug mode, panics if the attribute has zero length
    pub fn validate(&self, type_: DataType) -> i32 {
        // Debug assertion to check if the attribute has non-zero length
        debug_assert!(
            self.get_payload_len() > 0,
            "Attribute has zero payload length in validate()"
        );

        if type_ >= MAX {
            println!("Unsupported attribute type");
            return -1;
        }
        let exp_len = Self::data_type_len[type_ as usize];
        self.__validate(type_, exp_len)
    }

    /// Extended validation for attributes with variable size
    ///
    /// Allows more precise validation for attributes with variable data sizes.
    ///
    /// # Parameters
    /// * `type_` - The expected data type of the attribute
    /// * `exp_len` - The expected length of the attribute payload
    ///
    /// # Returns
    /// 0 on success, negative error code on failure
    pub fn validate2(&self, type_: DataType, exp_len: usize) -> i32 {
        if type_ >= MAX {
            println!("Unsupported attribute type");
            return -1;
        }
        self.__validate(type_, exp_len)
    }

    /// Parses attributes in a netlink message
    ///
    /// Iterates over the sequence of attributes in the message,
    /// calling the provided callback function for each attribute.
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header containing attributes to parse
    /// * `offset` - Offset in bytes from the start of the payload to the first attribute
    /// * `cb` - Callback function to call for each attribute
    /// * `data` - User data to pass to the callback function
    ///
    /// # Returns
    /// Status code from the last callback, or error code
    pub fn parse(nlh: &mut Header, offset: u32, cb: attr_callback_t, data: *mut u8) -> i32 {
        unsafe {
            let mut ret: i32 = Callback::OK;
            let payload_len = nlh.len as usize - offset as usize;
            let mut attr = nlh.get_payload_offset(offset as usize) as *mut Self;

            while !attr.is_null()
                && (*attr).is_ok(
                    payload_len as i32
                        - (attr as usize - nlh.get_payload_offset(offset as usize) as usize) as i32,
                )
            {
                ret = (*cb)(attr, data);
                if ret <= Callback::STOP {
                    return ret;
                }
                attr = (*attr).next();
            }
            ret
        }
    }

    /// Parses attributes inside a nested attribute
    ///
    /// Processes attributes contained within a nested attribute,
    /// calling the provided callback for each one.
    ///
    /// # Parameters
    /// * `cb` - Callback function to call for each attribute
    /// * `data` - User data to pass to the callback function
    ///
    /// # Returns
    /// Status code from the last callback, or error code
    pub fn parse_nested(&mut self, cb: attr_callback_t, data: *mut u8) -> i32 {
        unsafe {
            let mut ret: i32 = Callback::OK;
            let payload_len = self.get_payload_len() as usize;
            let mut attr = self.get_payload() as *mut Self;

            // Debug assertion to check if this attribute is actually a nested attribute
            debug_assert!(
                (self.type_ & Self::NESTED as u16) != 0,
                "parse_nested called on a non-nested attribute"
            );

            while !attr.is_null()
                && (*attr).is_ok(
                    payload_len as i32 - (attr as usize - self.get_payload() as usize) as i32,
                )
            {
                #[cfg(debug_assertions)]
                {
                    let attr_type = (*attr).get_type();
                    eprintln!("Processing nested attribute: type={}", attr_type);
                }

                ret = (*cb)(attr, data);
                if ret <= Callback::STOP {
                    return ret;
                }
                attr = (*attr).next();
            }
            ret
        }
    }
    /// Parses attributes in a raw payload buffer
    ///
    /// Processes attributes contained within a raw buffer,
    /// calling the provided callback for each one.
    ///
    /// # Parameters
    /// * `payload_len` - Length of the payload in bytes
    /// * `cb` - Callback function to call for each attribute
    /// * `data` - User data to pass to the callback function
    ///
    /// # Returns
    /// Status code from the last callback, or error code
    pub fn parse_payload(&mut self, payload_len: usize, cb: attr_callback_t, data: *mut u8) -> i32 {
        unsafe {
            let mut ret: i32 = MNL_CB_OK;
            let payload = self.get_payload();
            let mut attr = payload as *mut Self;

            // Debug assertion to check if payload is aligned properly
            debug_assert!(
                (payload as usize) % align_of::<Self>() == 0,
                "Payload pointer is not properly aligned"
            );

            while !attr.is_null()
                && (*attr).is_ok(payload_len as i32 - (attr as usize - payload as usize) as i32)
            {
                #[cfg(debug_assertions)]
                {
                    let attr_type = (*attr).get_type();
                    let attr_len = (*attr).len;
                    eprintln!("Processing attribute: type={}, len={}", attr_type, attr_len);
                }

                ret = (*cb)(attr, data);
                if ret <= Callback::STOP {
                    return ret;
                }
                attr = (*attr).next();
            }
            ret
        }
    }

    /// Gets the 8-bit unsigned integer value from an attribute
    ///
    /// # Returns
    /// The 8-bit unsigned integer value contained in the attribute
    pub fn get_u8(&self) -> u8 {
        unsafe {
            let value = *(self.get_payload() as *const u8);

            // Debug assertion to verify payload length is correct for u8
            debug_assert!(
                self.get_payload_len() >= size_of::<u8>() as u16,
                "get_u8 called on attribute with insufficient payload size"
            );

            value
        }
    }
    /// Gets the 16-bit unsigned integer value from an attribute
    ///
    /// Reads the value in an alignment-safe manner.
    ///
    /// # Returns
    /// The 16-bit unsigned integer value contained in the attribute
    pub fn get_u16(&self) -> u16 {
        unsafe {
            let value = *(self.get_payload() as *const u16);

            // Debug assertion to verify payload length is correct for u16
            debug_assert!(
                self.get_payload_len() >= size_of::<u16>() as u16,
                "get_u16 called on attribute with insufficient payload size"
            );

            value
        }
    }

    /// Gets the 32-bit unsigned integer value from an attribute
    ///
    /// # Returns
    /// The 32-bit unsigned integer value contained in the attribute
    pub fn get_u32(&self) -> u32 {
        unsafe {
            let value = *(self.get_payload() as *const u32);

            // Debug assertion to verify payload length is correct for u32
            debug_assert!(
                self.get_payload_len() >= size_of::<u32>() as u16,
                "get_u32 called on attribute with insufficient payload size"
            );

            value
        }
    }

    /// Gets the 64-bit unsigned integer value from an attribute
    ///
    /// Reads the value in an alignment-safe manner.
    ///
    /// # Returns
    /// The 64-bit unsigned integer value contained in the attribute
    pub fn get_u64(&self) -> u64 {
        unsafe {
            let mut tmp: u64 = 0;

            // Debug assertion to verify payload length is correct for u64
            debug_assert!(
                self.get_payload_len() >= size_of::<u64>() as u16,
                "get_u64 called on attribute with insufficient payload size"
            );

            copy_nonoverlapping(self.get_payload() as *const u64, &mut tmp as *mut u64, 1);
            tmp
        }
    }
    /// Gets a variable-sized integer from an attribute
    ///
    /// Handles attributes containing 8-bit, 16-bit, 32-bit, or 64-bit integers.
    ///
    /// # Returns
    /// The integer value as a u64, regardless of the actual size
    pub fn get_uint(&self) -> u64 {
        let len = self.get_payload_len() as usize;

        // Log the actual payload length for debugging
        #[cfg(debug_assertions)]
        eprintln!("get_uint: attribute payload length = {}", len);

        match len {
            1 => self.get_u8() as u64,
            2 => self.get_u16() as u64,
            4 => self.get_u32() as u64,
            8 => self.get_u64(),
            _ => {
                // Debug assertion to check if we have a valid payload length
                debug_assert!(false, "Invalid payload length for get_uint: {}", len);
                u64::MAX
            }
        }
    }

    /// Gets a pointer to the string value in an attribute
    ///
    /// # Returns
    /// A pointer to the C-style string contained in the attribute
    pub fn get_str(&self) -> *const i8 {
        // Debug assertion to ensure we have a non-empty payload
        #[cfg(debug_assertions)]
        {
            let payload_len = self.get_payload_len();
            debug_assert!(
                payload_len > 0,
                "get_str called on attribute with empty payload"
            );
        }

        self.get_payload() as *const i8
    }

    /// Adds an attribute to a netlink message
    ///
    /// Updates the length field of the message by adding the size of the new attribute.
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header to add the attribute to
    /// * `type_` - Type of the attribute
    /// * `len` - Length of the attribute payload in bytes
    /// * `data` - Pointer to the attribute payload data
    pub fn put(nlh: &mut Header, type_: u16, len: usize, data: *const u8) {
        unsafe {
            let attr = (*nlh).get_payload_tail() as *mut Self;
            let payload_len = (Self::HDRLEN + len) as u16;
            (*attr).type_ = type_;
            (*attr).len = payload_len;
            copy_nonoverlapping(
                data as *const c_void,
                (*attr).get_payload() as *mut c_void,
                len,
            );

            let pad = ALIGN(len) - len;
            if pad > 0 {
                write_bytes((*attr).get_payload().add(len), 0, pad);
            }

            (*nlh).len += ALIGN(payload_len as usize) as u32;
        }
    }
    /// Adds an 8-bit unsigned integer attribute to a netlink message
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header to add the attribute to
    /// * `type_` - Type of the attribute
    /// * `data` - The 8-bit unsigned integer value to add
    pub fn put_u8(nlh: &mut Header, type_: u16, data: u8) {
        Self::put(nlh, type_, size_of::<u8>(), &data as *const u8);
    }

    /// Adds a 16-bit unsigned integer attribute to a netlink message
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header to add the attribute to
    /// * `type_` - Type of the attribute
    /// * `data` - The 16-bit unsigned integer value to add
    pub fn put_u16(nlh: &mut Header, type_: u16, data: u16) {
        Self::put(
            nlh,
            type_,
            size_of::<u16>(),
            &data as *const u16 as *const u8,
        );
    }
    /// Adds a 32-bit unsigned integer attribute to a netlink message
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header to add the attribute to
    /// * `type_` - Type of the attribute
    /// * `data` - The 32-bit unsigned integer value to add
    pub fn put_u32(nlh: &mut Header, type_: u16, data: u32) {
        Self::put(
            nlh,
            type_,
            size_of::<u32>(),
            &data as *const u32 as *const u8,
        );
    }
    /// Adds a 64-bit unsigned integer attribute to a netlink message
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header to add the attribute to
    /// * `type_` - Type of the attribute
    /// * `data` - The 64-bit unsigned integer value to add
    pub fn put_u64(nlh: &mut Header, type_: u16, data: u64) {
        Self::put(
            nlh,
            type_,
            size_of::<u64>(),
            &data as *const u64 as *const u8,
        );
    }
    /// Adds a string attribute to a netlink message
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header to add the attribute to
    /// * `type_` - Type of the attribute
    /// * `data` - Pointer to the null-terminated string to add
    pub fn put_str(nlh: &mut Header, type_: u16, data: *const i8) {
        unsafe {
            Self::put(nlh, type_, strlen(data), data as *const u8);
        }
    }
    /// Adds a null-terminated string attribute to a netlink message
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header to add the attribute to
    /// * `type_` - Type of the attribute
    /// * `data` - Pointer to the string to add (null terminator will be included)
    pub fn put_strz(nlh: &mut Header, type_: u16, data: *const i8) {
        unsafe {
            Self::put(nlh, type_, strlen(data) + 1, data as *const u8);
        }
    }
    /// Starts a nested attribute in a netlink message
    ///
    /// Returns a pointer to the nested attribute header for later use.
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header to add the nested attribute to
    /// * `type_` - Type of the attribute with the NESTED flag set
    ///
    /// # Returns
    /// Pointer to the nested attribute, to be used with `nest_end` or `nest_cancel`
    pub fn nest_start(nlh: &mut Header, type_: u16) -> *mut Self {
        unsafe {
            let start: *mut Self = (*nlh).get_payload_tail() as *mut Self;
            /* set start->len in nest_end() */
            (*start).type_ = Self::NESTED as u16 | type_;
            (*nlh).len += Self::HDRLEN as u32;
            start
        }
    }

    /// Finalizes a nested attribute by updating its length
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header containing the nested attribute
    /// * `start` - Pointer to the nested attribute as returned by `nest_start`
    pub fn nest_end(nlh: &mut Header, start: *mut Self) {
        unsafe {
            (*start).len = ((*nlh).get_payload_tail() as usize - start as usize) as u16;
        }
    }

    /// Cancels a nested attribute by rolling back the message length
    ///
    /// # Parameters
    /// * `nlh` - Netlink message header containing the nested attribute
    /// * `start` - Pointer to the nested attribute as returned by `nest_start`
    pub fn nest_cancel(nlh: &mut Header, start: *mut Self) {
        (*nlh).len -= ((*nlh).get_payload_tail() as usize - start as usize) as u32;
    }
}