1use kernel::{
12 alloc::{self, AllocError},
13 error::to_result,
14 num::casts::u16_as_usize,
15 prelude::*,
16 transmute::AsBytes,
17 types::Opaque,
18 ThisModule,
19};
20
21use core::{
22 mem::ManuallyDrop,
23 ptr::NonNull, };
25
26pub const GENLMSG_DEFAULT_SIZE: usize = bindings::GENLMSG_DEFAULT_SIZE;
28
29pub struct NetlinkSkBuff {
38 skb: NonNull<kernel::bindings::sk_buff>,
39}
40
41impl NetlinkSkBuff {
42 pub fn new(size: usize, flags: alloc::Flags) -> Result<NetlinkSkBuff, AllocError> {
44 let skb = unsafe { bindings::genlmsg_new(size, flags.as_raw()) };
46 let skb = NonNull::new(skb).ok_or(AllocError)?;
47 Ok(NetlinkSkBuff { skb })
48 }
49
50 pub fn genlmsg_put(
52 self,
53 portid: u32,
54 seq: u32,
55 family: &'static Family,
56 cmd: u8,
57 ) -> Result<GenlMsg, AllocError> {
58 let skb = self.skb.as_ptr();
59 let hdr = unsafe { bindings::genlmsg_put(skb, portid, seq, family.as_raw(), 0, cmd) };
61 let hdr = NonNull::new(hdr).ok_or(AllocError)?;
62 Ok(GenlMsg { skb: self, hdr })
63 }
64}
65
66impl Drop for NetlinkSkBuff {
67 fn drop(&mut self) {
68 unsafe { bindings::nlmsg_free(self.skb.as_ptr()) }
70 }
71}
72
73pub struct GenlMsg {
79 skb: NetlinkSkBuff,
80 hdr: NonNull<c_void>,
81}
82
83impl GenlMsg {
84 #[inline]
86 fn put<T>(&mut self, attrtype: c_int, value: &T) -> Result
87 where
88 T: ?Sized + AsBytes,
89 {
90 const MAX_PAYLOAD_LEN: usize = u16_as_usize(u16::MAX) - size_of::<bindings::nlattr>();
94
95 let skb = self.skb.skb.as_ptr();
96 let len = size_of_val(value);
97 let ptr = core::ptr::from_ref(value).cast::<c_void>();
98 if len > MAX_PAYLOAD_LEN {
99 return Err(EMSGSIZE);
100 }
101 to_result(unsafe { bindings::nla_put(skb, attrtype, len as c_int, ptr) })
104 }
105
106 #[inline]
108 pub fn put_u32(&mut self, attrtype: c_int, value: u32) -> Result {
109 self.put(attrtype, &value)
110 }
111
112 #[inline]
114 pub fn put_string(&mut self, attrtype: c_int, value: &CStr) -> Result {
115 self.put(attrtype, value.to_bytes_with_nul())
116 }
117
118 #[inline]
120 pub fn put_flag(&mut self, attrtype: c_int) -> Result {
121 let skb = self.skb.skb.as_ptr();
122 to_result(unsafe { bindings::nla_put(skb, attrtype, 0, core::ptr::null()) })
125 }
126
127 #[inline]
129 pub fn multicast(
130 self,
131 family: &'static Family,
132 portid: u32,
133 group: u32,
134 flags: alloc::Flags,
135 ) -> Result {
136 let me = ManuallyDrop::new(self);
137 unsafe {
140 bindings::genlmsg_end(me.skb.skb.as_ptr(), me.hdr.as_ptr());
141 to_result(bindings::genlmsg_multicast(
142 family.as_raw(),
143 me.skb.skb.as_ptr(),
144 portid,
145 group,
146 flags.as_raw(),
147 ))
148 }
149 }
150}
151impl Drop for GenlMsg {
152 fn drop(&mut self) {
153 unsafe { bindings::genlmsg_cancel(self.skb.skb.as_ptr(), self.hdr.as_ptr()) };
155 }
156}
157
158struct FamilyFlags {
160 netnsok: bool,
162 parallel_ops: bool,
164}
165
166impl FamilyFlags {
167 const fn into_bitfield(self) -> bindings::__BindgenBitfieldUnit<[u8; 1]> {
169 let mut bits = 0;
175 if self.netnsok {
176 bits |= 1 << 0;
177 }
178 if self.parallel_ops {
179 bits |= 1 << 1;
180 }
181 bits = u8::from_le(bits);
183 unsafe { core::mem::transmute::<u8, bindings::__BindgenBitfieldUnit<[u8; 1]>>(bits) }
185 }
186}
187
188#[repr(transparent)]
190pub struct Family {
191 inner: Opaque<bindings::genl_family>,
192}
193
194unsafe impl Sync for Family {}
196
197impl Family {
198 pub const fn const_new(
205 module: &ThisModule,
206 name: &[u8],
207 version: u32,
208 mcgrps: &'static [MulticastGroup],
209 ) -> Family {
210 let n_mcgrps = mcgrps.len() as u8;
211 if n_mcgrps as usize != mcgrps.len() {
212 panic!("too many mcgrps");
213 }
214 let mut genl_family = bindings::genl_family {
215 version,
216 _bitfield_1: FamilyFlags {
217 netnsok: true,
218 parallel_ops: true,
219 }
220 .into_bitfield(),
221 module: module.as_ptr(),
222 mcgrps: mcgrps.as_ptr().cast(),
223 n_mcgrps,
224 ..pin_init::zeroed()
225 };
226 if CStr::from_bytes_with_nul(name).is_err() {
227 panic!("genl_family name not nul-terminated");
228 }
229 if genl_family.name.len() < name.len() {
230 panic!("genl_family name too long");
231 }
232 let mut i = 0;
233 while i < name.len() {
234 genl_family.name[i] = name[i];
235 i += 1;
236 }
237 Family {
238 inner: Opaque::new(genl_family),
239 }
240 }
241
242 pub fn has_listeners(&self, group: u32) -> bool {
244 unsafe {
246 bindings::genl_has_listeners(self.as_raw(), &raw mut bindings::init_net, group) != 0
247 }
248 }
249
250 pub fn as_raw(&self) -> *mut bindings::genl_family {
252 self.inner.get()
253 }
254}
255
256#[repr(transparent)]
258pub struct MulticastGroup {
259 group: bindings::genl_multicast_group,
261}
262
263unsafe impl Sync for MulticastGroup {}
265
266impl MulticastGroup {
267 pub const fn const_new(name: &CStr) -> MulticastGroup {
271 let mut group: bindings::genl_multicast_group = pin_init::zeroed();
272
273 let name = name.to_bytes_with_nul();
274 if group.name.len() < name.len() {
275 panic!("genl_multicast_group name too long");
276 }
277 let mut i = 0;
278 while i < name.len() {
279 group.name[i] = name[i];
280 i += 1;
281 }
282
283 MulticastGroup { group }
284 }
285}
286
287pub struct Registration {
296 family: &'static Family,
297}
298
299impl Family {
300 pub fn register(&'static self) -> Result<Registration> {
302 to_result(unsafe { bindings::genl_register_family(self.as_raw()) })?;
305 Ok(Registration { family: self })
306 }
307}
308
309impl Drop for Registration {
310 fn drop(&mut self) {
311 unsafe { bindings::genl_unregister_family(self.family.as_raw()) };
315 }
316}
317
318#[macros::kunit_tests(rust_netlink)]
319mod tests {
320 use super::*;
321
322 #[test]
323 fn test_family_flags_bitfield() {
324 for netnsok in [false, true] {
325 for parallel_ops in [false, true] {
326 let mut b_fam = bindings::genl_family {
327 ..Default::default()
328 };
329 b_fam.set_netnsok(if netnsok { 1 } else { 0 });
330 b_fam.set_parallel_ops(if parallel_ops { 1 } else { 0 });
331
332 let c_bitfield = FamilyFlags {
333 netnsok,
334 parallel_ops,
335 }
336 .into_bitfield();
337
338 let b_val: u8 = unsafe { core::mem::transmute(b_fam._bitfield_1) };
340 let c_val: u8 = unsafe { core::mem::transmute(c_bitfield) };
342 assert_eq!(b_val, c_val);
343 }
344 }
345 }
346}