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
// SPDX-License-Identifier: MIT

//! Message definition and method implementations

use crate::{buffer::GenlBuffer, header::GenlHeader, traits::*};
use netlink_packet_core::{
    DecodeError,
    NetlinkDeserializable,
    NetlinkHeader,
    NetlinkPayload,
    NetlinkSerializable,
};
use netlink_packet_utils::{Emitable, ParseableParametrized};
use std::fmt::Debug;

#[cfg(doc)]
use netlink_packet_core::NetlinkMessage;

/// Represent the generic netlink messages
///
/// This type can wrap data types `F` which represents a generic family payload.
/// The message can be serialize/deserialize if the type `F` implements [`GenlFamily`],
/// [`Emitable`], and [`ParseableParametrized<[u8], GenlHeader>`](ParseableParametrized).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GenlMessage<F> {
    pub header: GenlHeader,
    pub payload: F,
    resolved_family_id: u16,
}

impl<F> GenlMessage<F>
where
    F: Debug,
{
    /// Construct the message
    pub fn new(header: GenlHeader, payload: F, family_id: u16) -> Self {
        Self {
            header,
            payload,
            resolved_family_id: family_id,
        }
    }

    /// Construct the message by the given header and payload
    pub fn from_parts(header: GenlHeader, payload: F) -> Self {
        Self {
            header,
            payload,
            resolved_family_id: 0,
        }
    }

    /// Consume this message and return its header and payload
    pub fn into_parts(self) -> (GenlHeader, F) {
        (self.header, self.payload)
    }

    /// Return the previously set resolved family ID in this message.
    ///
    /// This value would be used to serialize the message only if
    /// the ([`GenlFamily::family_id()`]) return 0 in the underlying type.
    pub fn resolved_family_id(&self) -> u16 {
        self.resolved_family_id
    }

    /// Set the resolved dynamic family ID of the message, if the generic family
    /// uses dynamic generated ID by kernel.
    ///
    /// This method is a interface to provide other high level library to
    /// set the resolved family ID before the message is serialized.
    ///
    /// # Usage
    /// Normally, you don't have to call this function directly if you are
    /// using library which helps you handle the dynamic family id.
    ///
    /// If you are the developer of some high level generic netlink library,
    /// you can call this method to set the family id resolved by your resolver.
    /// Without having to modify the `message_type` field of the serialized
    /// netlink packet header before sending it.
    pub fn set_resolved_family_id(&mut self, family_id: u16) {
        self.resolved_family_id = family_id;
    }
}

impl<F> GenlMessage<F>
where
    F: GenlFamily + Debug,
{
    /// Build the message from the payload
    ///
    /// This function would automatically fill the header for you. You can directly emit
    /// the message without having to call [`finalize()`](Self::finalize).
    pub fn from_payload(payload: F) -> Self {
        Self {
            header: GenlHeader {
                cmd: payload.command(),
                version: payload.version(),
            },
            payload,
            resolved_family_id: 0,
        }
    }

    /// Ensure the header ([`GenlHeader`]) is consistent with the payload (`F: GenlFamily`):
    ///
    /// - Fill the command and version number into the header
    ///
    /// If you are not 100% sure the header is correct, this method should be called before calling
    /// [`Emitable::emit()`], as it could get error result if the header is inconsistent with the message.
    pub fn finalize(&mut self) {
        self.header.cmd = self.payload.command();
        self.header.version = self.payload.version();
    }

    /// Return the resolved family ID which should be filled into the `message_type`
    /// field in [`NetlinkHeader`].
    ///
    /// The implementation of [`NetlinkSerializable::message_type()`] would use
    /// this function's result as its the return value. Thus, the family id can
    /// be automatically filled into the `message_type` during the call to
    /// [`NetlinkMessage::finalize()`].
    pub fn family_id(&self) -> u16 {
        let static_id = self.payload.family_id();
        if static_id == 0 {
            self.resolved_family_id
        } else {
            static_id
        }
    }
}

impl<F> Emitable for GenlMessage<F>
where
    F: GenlFamily + Emitable + Debug,
{
    fn buffer_len(&self) -> usize {
        self.header.buffer_len() + self.payload.buffer_len()
    }

    fn emit(&self, buffer: &mut [u8]) {
        self.header.emit(buffer);

        let buffer = &mut buffer[self.header.buffer_len()..];
        self.payload.emit(buffer);
    }
}

impl<F> NetlinkSerializable for GenlMessage<F>
where
    F: GenlFamily + Emitable + Debug,
{
    fn message_type(&self) -> u16 {
        self.family_id()
    }

    fn buffer_len(&self) -> usize {
        <Self as Emitable>::buffer_len(self)
    }

    fn serialize(&self, buffer: &mut [u8]) {
        self.emit(buffer)
    }
}

impl<F> NetlinkDeserializable for GenlMessage<F>
where
    F: ParseableParametrized<[u8], GenlHeader> + Debug,
{
    type Error = DecodeError;
    fn deserialize(header: &NetlinkHeader, payload: &[u8]) -> Result<Self, Self::Error> {
        let buffer = GenlBuffer::new_checked(payload)?;
        GenlMessage::parse_with_param(&buffer, header.message_type)
    }
}

impl<F> From<GenlMessage<F>> for NetlinkPayload<GenlMessage<F>>
where
    F: Debug,
{
    fn from(message: GenlMessage<F>) -> Self {
        NetlinkPayload::InnerMessage(message)
    }
}