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
// core

use core::{cmp::min, mem::size_of};

// crate
use crate::error::LxError;
// use crate::net::Endpoint;

// smoltcp
pub use smoltcp::wire::{IpAddress, Ipv4Address};

use crate::net::*;
use kernel_hal::user::{UserInOutPtr, UserOutPtr};
// use numeric_enum_macro::numeric_enum;
use super::MsgHdr;

/// missing documentation
#[repr(C)]
pub union SockAddr {
    /// missing documentation
    pub family: u16,
    /// missing documentation
    pub addr_in: SockAddrIn,
    /// missing documentation
    pub addr_un: SockAddrUn,
    /// missing documentation
    pub addr_ll: SockAddrLl,
    /// missing documentation
    pub addr_nl: SockAddrNl,
    /// missing documentation
    pub addr_ph: SockAddrPlaceholder,
}

/// missing documentation
#[derive(Clone, Copy)]
#[repr(C)]
pub struct SockAddrIn {
    /// missing documentation
    pub sin_family: u16,
    /// missing documentation
    pub sin_port: u16,
    /// missing documentation
    pub sin_addr: u32,
    /// missing documentation
    pub sin_zero: [u8; 8],
}

/// missing documentation
#[derive(Clone, Copy)]
#[repr(C)]
pub struct SockAddrUn {
    /// missing documentation
    pub sun_family: u16,
    /// missing documentation
    pub sun_path: [u8; 108],
}

/// missing documentation
#[derive(Clone, Copy)]
#[repr(C)]
pub struct SockAddrLl {
    /// missing documentation
    pub sll_family: u16,
    /// missing documentation
    pub sll_protocol: u16,
    /// missing documentation
    pub sll_ifindex: u32,
    /// missing documentation
    pub sll_hatype: u16,
    /// missing documentation
    pub sll_pkttype: u8,
    /// missing documentation
    pub sll_halen: u8,
    /// missing documentation
    pub sll_addr: [u8; 8],
}

/// missing documentation
#[derive(Clone, Copy)]
#[repr(C)]
pub struct SockAddrNl {
    nl_family: u16,
    nl_pad: u16,
    nl_pid: u32,
    nl_groups: u32,
}

/// missing documentation
#[derive(Clone, Copy)]
#[repr(C)]
pub struct SockAddrPlaceholder {
    /// missing documentation
    pub family: u16,
    /// missing documentation
    pub data: [u8; 14],
}

// ============= Endpoint =============

use smoltcp::wire::IpEndpoint;

/// missing documentation
#[derive(Clone, Debug)]
pub enum Endpoint {
    /// missing documentation
    Ip(IpEndpoint),
    /// missing documentation
    LinkLevel(LinkLevelEndpoint),
    /// missing documentation
    Netlink(NetlinkEndpoint),
}

/// missing documentation
#[derive(Clone, Debug)]
pub struct LinkLevelEndpoint {
    /// missing documentation
    pub interface_index: usize,
}

impl LinkLevelEndpoint {
    /// missing documentation
    pub fn new(ifindex: usize) -> Self {
        LinkLevelEndpoint {
            interface_index: ifindex,
        }
    }
}

/// missing documentation
#[derive(Clone, Debug)]
pub struct NetlinkEndpoint {
    /// missing documentation
    pub port_id: u32,
    /// missing documentation
    pub multicast_groups_mask: u32,
}

impl NetlinkEndpoint {
    /// missing documentation
    pub fn new(port_id: u32, multicast_groups_mask: u32) -> Self {
        NetlinkEndpoint {
            port_id,
            multicast_groups_mask,
        }
    }
}

// ============= Endpoint =============

impl From<Endpoint> for SockAddr {
    fn from(endpoint: Endpoint) -> Self {
        #[allow(warnings)]
        if let Endpoint::Ip(ip) = endpoint {
            match ip.addr {
                IpAddress::Ipv4(ipv4) => SockAddr {
                    addr_in: SockAddrIn {
                        sin_family: AddressFamily::Internet.into(),
                        sin_port: u16::to_be(ip.port),
                        sin_addr: u32::to_be(u32::from_be_bytes(ipv4.0)),
                        sin_zero: [0; 8],
                    },
                },
                IpAddress::Unspecified => SockAddr {
                    addr_ph: SockAddrPlaceholder {
                        family: AddressFamily::Unspecified.into(),
                        data: [0; 14],
                    },
                },
                _ => unimplemented!("only ipv4"),
            }
        } else if let Endpoint::LinkLevel(link_level) = endpoint {
            SockAddr {
                addr_ll: SockAddrLl {
                    sll_family: AddressFamily::Packet.into(),
                    sll_protocol: 0,
                    sll_ifindex: link_level.interface_index as u32,
                    sll_hatype: 0,
                    sll_pkttype: 0,
                    sll_halen: 0,
                    sll_addr: [0; 8],
                },
            }
        } else if let Endpoint::Netlink(netlink) = endpoint {
            SockAddr {
                addr_nl: SockAddrNl {
                    nl_family: AddressFamily::Netlink.into(),
                    nl_pad: 0,
                    nl_pid: netlink.port_id,
                    nl_groups: netlink.multicast_groups_mask,
                },
            }
        } else {
            unimplemented!("not match");
        }
    }
}

/// missing documentation
pub fn sockaddr_to_endpoint(addr: SockAddr, len: usize) -> Result<Endpoint, LxError> {
    if len < size_of::<u16>() {
        return Err(LxError::EINVAL);
    }
    // let addr = unsafe { vm.check_read_ptr(addr)? };
    if len < addr.len()? {
        return Err(LxError::EINVAL);
    }
    #[allow(unsafe_code)]
    unsafe {
        match AddressFamily::from(addr.family) {
            AddressFamily::Internet => {
                let port = u16::from_be(addr.addr_in.sin_port);
                let addr = IpAddress::from(Ipv4Address::from_bytes(
                    &u32::from_be(addr.addr_in.sin_addr).to_be_bytes()[..],
                ));
                Ok(Endpoint::Ip((addr, port).into()))
            }
            AddressFamily::Unix => Err(LxError::EINVAL),
            // AddressFamily::Packet => Ok(Endpoint::LinkLevel(LinkLevelEndpoint::new(
            //     addr.addr_ll.sll_ifindex as usize,
            // ))),
            AddressFamily::Netlink => Ok(Endpoint::Netlink(NetlinkEndpoint::new(
                addr.addr_nl.nl_pid,
                addr.addr_nl.nl_groups,
            ))),
            _ => Err(LxError::EINVAL),
        }
    }
}

impl SockAddr {
    fn len(&self) -> Result<usize, LxError> {
        #[allow(unsafe_code)]
        match AddressFamily::from(unsafe { self.family }) {
            AddressFamily::Internet => Ok(size_of::<SockAddrIn>()),
            AddressFamily::Packet => Ok(size_of::<SockAddrLl>()),
            AddressFamily::Netlink => Ok(size_of::<SockAddrNl>()),
            AddressFamily::Unix => Err(LxError::EINVAL),
            _ => Err(LxError::EINVAL),
        }
    }

    /// # Safety
    /// Write to user sockaddr
    /// Check mutability for user
    #[allow(dead_code)]
    pub fn write_to(
        self,
        addr: UserOutPtr<SockAddr>,
        mut addr_len: UserInOutPtr<u32>,
    ) -> SysResult {
        // Ignore NULL
        if addr.is_null() {
            return Ok(0);
        }
        let max_addr_len = addr_len.read()? as usize;
        let full_len = self.len()?;
        let written_len = min(max_addr_len, full_len);
        if written_len > 0 {
            #[allow(unsafe_code)]
            let source = unsafe {
                core::slice::from_raw_parts(&self as *const SockAddr as *const u8, written_len)
            };
            #[allow(unsafe_code)]
            let mut addr: UserOutPtr<u8> = unsafe { core::mem::transmute(addr) };
            addr.write_array(source)?;
        }
        addr_len.write(full_len as u32)?;
        Ok(0)
    }

    /// # Safety
    /// Write to user sockaddr
    /// Check mutability for user
    #[allow(dead_code)]
    pub fn write_to_inout(
        self,
        addr: UserInOutPtr<SockAddr>,
        mut addr_len: UserInOutPtr<u32>,
    ) -> SysResult {
        // Ignore NULL
        if addr.is_null() {
            return Ok(0);
        }

        let max_addr_len = addr_len.read()? as usize;
        let full_len = self.len()?;

        let written_len = min(max_addr_len, full_len);
        if written_len > 0 {
            #[allow(unsafe_code)]
            let source = unsafe {
                core::slice::from_raw_parts(&self as *const SockAddr as *const u8, written_len)
            };
            #[allow(unsafe_code)]
            let mut addr: UserOutPtr<u8> = unsafe { core::mem::transmute(addr) };
            addr.write_array(source)?;
        }
        addr_len.write(full_len as u32)?;
        Ok(0)
    }

    /// # Safety
    /// Write to msg
    /// Check mutability for user
    #[allow(dead_code)]
    pub fn write_to_msg(self, msg: UserInOutPtr<MsgHdr>) -> SysResult {
        if msg.is_null() {
            return Ok(0);
        }
        let mut hdr = msg.read().unwrap();

        let max_addr_len = hdr.msg_namelen as usize;
        let full_len = self.len()?;
        let written_len = min(max_addr_len, full_len);
        hdr.set_msg_name_len(full_len as u32);

        use core::slice;

        #[allow(unsafe_code)]
        unsafe {
            let source = slice::from_raw_parts(&self as *const SockAddr as *const u8, written_len);
            let mut addr: UserOutPtr<u8> = core::mem::transmute(hdr.msg_name);
            addr.write_array(source)?;
        }
        Ok(0)
    }
}

/// missing documentation
#[macro_export]
macro_rules! enum_with_unknown {
    (
        $( #[$enum_attr:meta] )*
        pub enum $name:ident($ty:ty) {
            $( $variant:ident = $value:expr ),+ $(,)*
        }
    ) => {
        enum_with_unknown! {
            $( #[$enum_attr] )*
            pub doc enum $name($ty) {
                $( #[doc(shown)] $variant = $value ),+
            }
        }
    };
    (
        $( #[$enum_attr:meta] )*
        pub doc enum $name:ident($ty:ty) {
            $(
              $( #[$variant_attr:meta] )+
              $variant:ident = $value:expr $(,)*
            ),+
        }
    ) => {
        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
        $( #[$enum_attr] )*
        pub enum $name {
            $(
              $( #[$variant_attr] )*
              $variant
            ),*,
            /// missing documentation
            Unknown($ty)
        }

        impl ::core::convert::From<$ty> for $name {
            fn from(value: $ty) -> Self {
                match value {
                    $( $value => $name::$variant ),*,
                    other => $name::Unknown(other)
                }
            }
        }

        impl ::core::convert::From<$name> for $ty {
            fn from(value: $name) -> Self {
                match value {
                    $( $name::$variant => $value ),*,
                    $name::Unknown(other) => other
                }
            }
        }
    }
}

enum_with_unknown! {
    /// Address families
    pub doc enum AddressFamily(u16) {
        /// Unspecified
        Unspecified = 0,
        /// Unix domain sockets
        Unix = 1,
        /// Internet IP Protocol
        Internet = 2,
        /// Netlink
        Netlink = 16,
        /// Packet family
        Packet = 17,
    }
}

/// missing documentation
#[repr(C)]
pub struct ArpReq {
    /// missing documentation
    pub arp_pa: SockAddrPlaceholder,
    /// missing documentation
    pub arp_ha: SockAddrPlaceholder,
    /// missing documentation
    pub arp_flags: u32,
    /// missing documentation
    pub arp_netmask: SockAddrPlaceholder,
    /// missing documentation
    pub arp_dev: [u8; 16],
}