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
//!
//! # UAU
//!
//! Unix(Unix Domain Socket) Abstract Udp
//!
//! An abstract socket address is distinguished (from a pathname socket)
//! by the fact that sun_path[0] is a null byte ('\0').
//! The socket's address in this namespace is given
//! by the additional bytes in sun_path that are covered
//! by the specified length of the address structure.
//! Null bytes in the name have no special  significance.
//! The name has no connection with filesystem pathnames.
//! When the address of an abstract socket is returned,
//! the returned addrlen is greater than sizeof(sa_family_t) (i.e., greater than 2),
//! and the name of the socket is contained in the first (addrlen - sizeof(sa_family_t)) bytes of sun_path.
//!
//! `man unix(7)` for more infomation.
//!

use crate::*;
use nix::{
    sys::{
        socket::{
            bind, recvfrom, sendto, setsockopt, socket, sockopt,
            AddressFamily, MsgFlags, SockFlag, SockType, UnixAddr,
        },
        time::{TimeVal, TimeValLike},
    },
    unistd::close,
};
use std::os::{fd::OwnedFd, unix::io::AsRawFd};

/// Wrap raw data
pub struct UauSock {
    fd: OwnedFd,
    sa: UnixAddr,
}

impl Drop for UauSock {
    fn drop(&mut self) {
        info_omit!(close(self.fd.as_raw_fd()));
    }
}

impl UauSock {
    /// NOTE:
    ///
    /// The Unix Socket that needs to receive messages must be bound to an explicit address;
    /// If you send msg anonymously, you will not receive the reply msg from the peer.
    ///
    /// So the `addr` parameter should not be empty.
    pub fn new(addr: &[u8], recv_timeout: Option<i64>) -> Result<Self> {
        let fd = socket(
            AddressFamily::Unix,
            SockType::Datagram,
            SockFlag::empty(),
            None,
        )
        .c(d!())?;

        setsockopt(&fd, sockopt::ReuseAddr, &true).c(d!())?;
        setsockopt(&fd, sockopt::ReusePort, &true).c(d!())?;
        if let Some(to) = recv_timeout {
            setsockopt(
                &fd,
                sockopt::ReceiveTimeout,
                &TimeVal::milliseconds(to),
            )
            .c(d!())?;
        }

        let sa = UnixAddr::new_abstract(addr).c(d!())?;
        bind(fd.as_raw_fd(), &sa).c(d!())?;

        Ok(UauSock { fd, sa })
    }

    /// Generate a random instance
    #[inline(always)]
    pub fn gen(recv_timeout: Option<i64>) -> Result<Self> {
        let addr = (ts!() as u32 ^ rand::random::<u32>()).to_ne_bytes();
        Self::new(&addr, recv_timeout).c(d!())
    }

    /// Get the addr of UauSock
    #[inline(always)]
    pub fn addr(&self) -> &UnixAddr {
        &self.sa
    }

    /// Send msg to another peer
    #[inline(always)]
    pub fn send(&self, msg: &[u8], peeraddr: &UnixAddr) -> Result<()> {
        sendto(self.fd.as_raw_fd(), msg, peeraddr, MsgFlags::empty())
            .c(d!())
            .map(|_| ())
    }

    /// Receive msg with a 64-bytes buffer
    #[inline(always)]
    pub fn recv_64(&self) -> Result<(Vec<u8>, UnixAddr)> {
        let mut buf = [0u8; 64];
        self.recv(&mut buf)
            .c(d!())
            .map(|(n, peer)| (buf[..n].to_vec(), peer))
    }

    /// Receive msg with a 128-bytes buffer
    #[inline(always)]
    pub fn recv_128(&self) -> Result<(Vec<u8>, UnixAddr)> {
        let mut buf = [0u8; 128];
        self.recv(&mut buf)
            .c(d!())
            .map(|(n, peer)| (buf[..n].to_vec(), peer))
    }

    /// Receive msg with a 256-bytes buffer
    #[inline(always)]
    pub fn recv_256(&self) -> Result<(Vec<u8>, UnixAddr)> {
        let mut buf = [0u8; 256];
        self.recv(&mut buf)
            .c(d!())
            .map(|(n, peer)| (buf[..n].to_vec(), peer))
    }

    /// Receive msg with a 512-bytes buffer
    #[inline(always)]
    pub fn recv_512(&self) -> Result<(Vec<u8>, UnixAddr)> {
        let mut buf = [0u8; 512];
        self.recv(&mut buf)
            .c(d!())
            .map(|(n, peer)| (buf[..n].to_vec(), peer))
    }

    /// Receive msg with a 1024-bytes buffer
    #[inline(always)]
    pub fn recv_1024(&self) -> Result<(Vec<u8>, UnixAddr)> {
        let mut buf = [0u8; 1024];
        self.recv(&mut buf)
            .c(d!())
            .map(|(n, peer)| (buf[..n].to_vec(), peer))
    }

    /// Receive msg with a 64-bytes buffer
    #[inline(always)]
    pub fn recvonly_64(&self) -> Result<Vec<u8>> {
        self.recv_64().map(|(b, _)| b)
    }

    /// Receive msg with a 128-bytes buffer
    #[inline(always)]
    pub fn recvonly_128(&self) -> Result<Vec<u8>> {
        self.recv_128().map(|(b, _)| b)
    }

    /// Receive msg with a 256-bytes buffer
    #[inline(always)]
    pub fn recvonly_256(&self) -> Result<Vec<u8>> {
        self.recv_256().map(|(b, _)| b)
    }

    /// Receive msg with a 512-bytes buffer
    #[inline(always)]
    pub fn recvonly_512(&self) -> Result<Vec<u8>> {
        self.recv_512().map(|(b, _)| b)
    }

    /// Receive msg with a 1024-bytes buffer
    #[inline(always)]
    pub fn recvonly_1024(&self) -> Result<Vec<u8>> {
        self.recv_1024().map(|(b, _)| b)
    }

    /// Receive msg with a given buffer
    #[inline(always)]
    pub fn recv(&self, buf: &mut [u8]) -> Result<(usize, UnixAddr)> {
        match recvfrom::<UnixAddr>(self.fd.as_raw_fd(), buf) {
            Ok((n, Some(peer))) => Ok((n, peer)),
            Err(e) => Err(eg!(e)),
            _ => Err(eg!("peer address is unknown")),
        }
    }

    /// Try to convert a user-given addr to SockAddr(unix sock)
    pub fn addr_to_sock(addr: &[u8]) -> Result<UnixAddr> {
        UnixAddr::new_abstract(addr).c(d!())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn t_send_recv() {
        let sender = pnk!(UauSock::gen(None));
        let receiver = pnk!(UauSock::gen(None));

        pnk!(sender.send(&987654321_u32.to_ne_bytes()[..], receiver.addr()));
        assert_eq!(
            &987654321_u32.to_ne_bytes()[..],
            &pnk!(receiver.recvonly_64())
        );

        pnk!(sender.send(&987654321_u32.to_ne_bytes()[..], receiver.addr()));
        assert_eq!(
            &987654321_u32.to_ne_bytes()[..],
            &pnk!(receiver.recvonly_128())
        );

        pnk!(sender.send(&987654321_u32.to_ne_bytes()[..], receiver.addr()));
        assert_eq!(
            &987654321_u32.to_ne_bytes()[..],
            &pnk!(receiver.recvonly_256())
        );

        pnk!(sender.send(&987654321_u32.to_ne_bytes()[..], receiver.addr()));
        assert_eq!(
            &987654321_u32.to_ne_bytes()[..],
            &pnk!(receiver.recvonly_512())
        );

        pnk!(sender.send(&987654321_u32.to_ne_bytes()[..], receiver.addr()));
        assert_eq!(
            &987654321_u32.to_ne_bytes()[..],
            &pnk!(receiver.recvonly_1024())
        );
    }
}