xref: /DragonOS/kernel/src/net/syscall.rs (revision 406099704eb939ae23b18f0cfb3ed36c534c1c84)
1cde5492fSlogin use core::cmp::min;
2cde5492fSlogin 
3cde5492fSlogin use alloc::{boxed::Box, sync::Arc};
4cde5492fSlogin use num_traits::{FromPrimitive, ToPrimitive};
5cde5492fSlogin use smoltcp::wire;
6cde5492fSlogin 
7cde5492fSlogin use crate::{
8cde5492fSlogin     filesystem::vfs::{
9cde5492fSlogin         file::{File, FileMode},
10cde5492fSlogin         syscall::{IoVec, IoVecs},
11cde5492fSlogin     },
12ab5c8ca4Slogin     libs::spinlock::SpinLockGuard,
134fda81ceSLoGin     mm::{verify_area, VirtAddr},
14cde5492fSlogin     net::socket::{AddressFamily, SOL_SOCKET},
151496ba7bSLoGin     process::ProcessManager,
16ab5c8ca4Slogin     syscall::{Syscall, SystemError},
17cde5492fSlogin };
18cde5492fSlogin 
19cde5492fSlogin use super::{
20*40609970SGnoCiYeH     socket::{
21*40609970SGnoCiYeH         PosixSocketType, RawSocket, SocketHandleItem, SocketInode, SocketOptions, TcpSocket,
22*40609970SGnoCiYeH         UdpSocket, HANDLE_MAP,
23*40609970SGnoCiYeH     },
24cde5492fSlogin     Endpoint, Protocol, ShutdownType, Socket,
25cde5492fSlogin };
26cde5492fSlogin 
27c47fe904SLoGin /// Flags for socket, socketpair, accept4
28c47fe904SLoGin const SOCK_CLOEXEC: FileMode = FileMode::O_CLOEXEC;
29c47fe904SLoGin const SOCK_NONBLOCK: FileMode = FileMode::O_NONBLOCK;
30c47fe904SLoGin 
31ab5c8ca4Slogin impl Syscall {
32cde5492fSlogin     /// @brief sys_socket系统调用的实际执行函数
33cde5492fSlogin     ///
34cde5492fSlogin     /// @param address_family 地址族
35cde5492fSlogin     /// @param socket_type socket类型
36cde5492fSlogin     /// @param protocol 传输协议
37ab5c8ca4Slogin     pub fn socket(
38cde5492fSlogin         address_family: usize,
39cde5492fSlogin         socket_type: usize,
40cde5492fSlogin         protocol: usize,
41ab5c8ca4Slogin     ) -> Result<usize, SystemError> {
42cde5492fSlogin         let address_family = AddressFamily::try_from(address_family as u16)?;
43cde5492fSlogin         let socket_type = PosixSocketType::try_from((socket_type & 0xf) as u8)?;
44cde5492fSlogin         // kdebug!("do_socket: address_family: {address_family:?}, socket_type: {socket_type:?}, protocol: {protocol}");
45cde5492fSlogin         // 根据地址族和socket类型创建socket
46cde5492fSlogin         let socket: Box<dyn Socket> = match address_family {
47cde5492fSlogin             AddressFamily::Unix | AddressFamily::INet => match socket_type {
48cde5492fSlogin                 PosixSocketType::Stream => Box::new(TcpSocket::new(SocketOptions::default())),
49cde5492fSlogin                 PosixSocketType::Datagram => Box::new(UdpSocket::new(SocketOptions::default())),
50cde5492fSlogin                 PosixSocketType::Raw => Box::new(RawSocket::new(
51cde5492fSlogin                     Protocol::from(protocol as u8),
52cde5492fSlogin                     SocketOptions::default(),
53cde5492fSlogin                 )),
54cde5492fSlogin                 _ => {
55cde5492fSlogin                     // kdebug!("do_socket: EINVAL");
56cde5492fSlogin                     return Err(SystemError::EINVAL);
57cde5492fSlogin                 }
58cde5492fSlogin             },
59cde5492fSlogin             _ => {
60cde5492fSlogin                 // kdebug!("do_socket: EAFNOSUPPORT");
61cde5492fSlogin                 return Err(SystemError::EAFNOSUPPORT);
62cde5492fSlogin             }
63cde5492fSlogin         };
64*40609970SGnoCiYeH         let handle_item = SocketHandleItem::new(&socket);
65*40609970SGnoCiYeH         HANDLE_MAP
66*40609970SGnoCiYeH             .write_irqsave()
67*40609970SGnoCiYeH             .insert(socket.socket_handle(), handle_item);
68cde5492fSlogin         // kdebug!("do_socket: socket: {socket:?}");
69cde5492fSlogin         let socketinode: Arc<SocketInode> = SocketInode::new(socket);
70cde5492fSlogin         let f = File::new(socketinode, FileMode::O_RDWR)?;
71cde5492fSlogin         // kdebug!("do_socket: f: {f:?}");
72cde5492fSlogin         // 把socket添加到当前进程的文件描述符表中
731496ba7bSLoGin         let binding = ProcessManager::current_pcb().fd_table();
741496ba7bSLoGin         let mut fd_table_guard = binding.write();
751496ba7bSLoGin 
761496ba7bSLoGin         let fd = fd_table_guard.alloc_fd(f, None).map(|x| x as usize);
771496ba7bSLoGin         drop(fd_table_guard);
78cde5492fSlogin         // kdebug!("do_socket: fd: {fd:?}");
79cde5492fSlogin         return fd;
80cde5492fSlogin     }
81cde5492fSlogin 
82cde5492fSlogin     /// @brief sys_setsockopt系统调用的实际执行函数
83cde5492fSlogin     ///
84cde5492fSlogin     /// @param fd 文件描述符
85cde5492fSlogin     /// @param level 选项级别
86cde5492fSlogin     /// @param optname 选项名称
87cde5492fSlogin     /// @param optval 选项值
88cde5492fSlogin     /// @param optlen optval缓冲区长度
89ab5c8ca4Slogin     pub fn setsockopt(
90cde5492fSlogin         fd: usize,
91cde5492fSlogin         level: usize,
92cde5492fSlogin         optname: usize,
93ab5c8ca4Slogin         optval: &[u8],
94ab5c8ca4Slogin     ) -> Result<usize, SystemError> {
951496ba7bSLoGin         let socket_inode: Arc<SocketInode> = ProcessManager::current_pcb()
96cde5492fSlogin             .get_socket(fd as i32)
97cde5492fSlogin             .ok_or(SystemError::EBADF)?;
98cde5492fSlogin         // 获取内层的socket(真正的数据)
99ab5c8ca4Slogin         let socket: SpinLockGuard<Box<dyn Socket>> = socket_inode.inner();
100ab5c8ca4Slogin         return socket.setsockopt(level, optname, optval).map(|_| 0);
101cde5492fSlogin     }
102cde5492fSlogin 
103cde5492fSlogin     /// @brief sys_getsockopt系统调用的实际执行函数
104cde5492fSlogin     ///
105cde5492fSlogin     /// 参考:https://man7.org/linux/man-pages/man2/setsockopt.2.html
106cde5492fSlogin     ///
107cde5492fSlogin     /// @param fd 文件描述符
108cde5492fSlogin     /// @param level 选项级别
109cde5492fSlogin     /// @param optname 选项名称
110cde5492fSlogin     /// @param optval 返回的选项值
111cde5492fSlogin     /// @param optlen 返回的optval缓冲区长度
112ab5c8ca4Slogin     pub fn getsockopt(
113cde5492fSlogin         fd: usize,
114cde5492fSlogin         level: usize,
115cde5492fSlogin         optname: usize,
116cde5492fSlogin         optval: *mut u8,
117cde5492fSlogin         optlen: *mut u32,
118ab5c8ca4Slogin     ) -> Result<usize, SystemError> {
119cde5492fSlogin         // 获取socket
120cde5492fSlogin         let optval = optval as *mut u32;
1211496ba7bSLoGin         let binding: Arc<SocketInode> = ProcessManager::current_pcb()
122cde5492fSlogin             .get_socket(fd as i32)
123cde5492fSlogin             .ok_or(SystemError::EBADF)?;
124cde5492fSlogin         let socket = binding.inner();
125cde5492fSlogin 
126cde5492fSlogin         if level as u8 == SOL_SOCKET {
127ab5c8ca4Slogin             let optname = PosixSocketOption::try_from(optname as i32)
128ab5c8ca4Slogin                 .map_err(|_| SystemError::ENOPROTOOPT)?;
129cde5492fSlogin             match optname {
130cde5492fSlogin                 PosixSocketOption::SO_SNDBUF => {
131cde5492fSlogin                     // 返回发送缓冲区大小
132cde5492fSlogin                     unsafe {
133cde5492fSlogin                         *optval = socket.metadata()?.send_buf_size as u32;
134cde5492fSlogin                         *optlen = core::mem::size_of::<u32>() as u32;
135cde5492fSlogin                     }
136cde5492fSlogin                     return Ok(0);
137cde5492fSlogin                 }
138cde5492fSlogin                 PosixSocketOption::SO_RCVBUF => {
139cde5492fSlogin                     let optval = optval as *mut u32;
140cde5492fSlogin                     // 返回默认的接收缓冲区大小
141cde5492fSlogin                     unsafe {
142cde5492fSlogin                         *optval = socket.metadata()?.recv_buf_size as u32;
143cde5492fSlogin                         *optlen = core::mem::size_of::<u32>() as u32;
144cde5492fSlogin                     }
145cde5492fSlogin                     return Ok(0);
146cde5492fSlogin                 }
147cde5492fSlogin                 _ => {
148cde5492fSlogin                     return Err(SystemError::ENOPROTOOPT);
149cde5492fSlogin                 }
150cde5492fSlogin             }
151cde5492fSlogin         }
152cde5492fSlogin         drop(socket);
153cde5492fSlogin 
154cde5492fSlogin         // To manipulate options at any other level the
155cde5492fSlogin         // protocol number of the appropriate protocol controlling the
156cde5492fSlogin         // option is supplied.  For example, to indicate that an option is
157cde5492fSlogin         // to be interpreted by the TCP protocol, level should be set to the
158cde5492fSlogin         // protocol number of TCP.
159cde5492fSlogin 
160cde5492fSlogin         let posix_protocol =
161cde5492fSlogin             PosixIpProtocol::try_from(level as u16).map_err(|_| SystemError::ENOPROTOOPT)?;
162cde5492fSlogin         if posix_protocol == PosixIpProtocol::TCP {
163cde5492fSlogin             let optname = PosixTcpSocketOptions::try_from(optname as i32)
164cde5492fSlogin                 .map_err(|_| SystemError::ENOPROTOOPT)?;
165cde5492fSlogin             match optname {
166cde5492fSlogin                 PosixTcpSocketOptions::Congestion => return Ok(0),
167cde5492fSlogin                 _ => {
168cde5492fSlogin                     return Err(SystemError::ENOPROTOOPT);
169cde5492fSlogin                 }
170cde5492fSlogin             }
171cde5492fSlogin         }
172cde5492fSlogin         return Err(SystemError::ENOPROTOOPT);
173cde5492fSlogin     }
174cde5492fSlogin 
175cde5492fSlogin     /// @brief sys_connect系统调用的实际执行函数
176cde5492fSlogin     ///
177cde5492fSlogin     /// @param fd 文件描述符
178cde5492fSlogin     /// @param addr SockAddr
179cde5492fSlogin     /// @param addrlen 地址长度
180cde5492fSlogin     ///
181cde5492fSlogin     /// @return 成功返回0,失败返回错误码
182ab5c8ca4Slogin     pub fn connect(fd: usize, addr: *const SockAddr, addrlen: usize) -> Result<usize, SystemError> {
183cde5492fSlogin         let endpoint: Endpoint = SockAddr::to_endpoint(addr, addrlen)?;
1841496ba7bSLoGin         let socket: Arc<SocketInode> = ProcessManager::current_pcb()
185cde5492fSlogin             .get_socket(fd as i32)
186cde5492fSlogin             .ok_or(SystemError::EBADF)?;
1872f6f547aSGnoCiYeH         let mut socket = unsafe { socket.inner_no_preempt() };
188cde5492fSlogin         // kdebug!("connect to {:?}...", endpoint);
189cde5492fSlogin         socket.connect(endpoint)?;
190cde5492fSlogin         return Ok(0);
191cde5492fSlogin     }
192cde5492fSlogin 
193cde5492fSlogin     /// @brief sys_bind系统调用的实际执行函数
194cde5492fSlogin     ///
195cde5492fSlogin     /// @param fd 文件描述符
196cde5492fSlogin     /// @param addr SockAddr
197cde5492fSlogin     /// @param addrlen 地址长度
198cde5492fSlogin     ///
199cde5492fSlogin     /// @return 成功返回0,失败返回错误码
200ab5c8ca4Slogin     pub fn bind(fd: usize, addr: *const SockAddr, addrlen: usize) -> Result<usize, SystemError> {
201cde5492fSlogin         let endpoint: Endpoint = SockAddr::to_endpoint(addr, addrlen)?;
2021496ba7bSLoGin         let socket: Arc<SocketInode> = ProcessManager::current_pcb()
203cde5492fSlogin             .get_socket(fd as i32)
204cde5492fSlogin             .ok_or(SystemError::EBADF)?;
2052f6f547aSGnoCiYeH         let mut socket = unsafe { socket.inner_no_preempt() };
206cde5492fSlogin         socket.bind(endpoint)?;
207cde5492fSlogin         return Ok(0);
208cde5492fSlogin     }
209cde5492fSlogin 
210cde5492fSlogin     /// @brief sys_sendto系统调用的实际执行函数
211cde5492fSlogin     ///
212cde5492fSlogin     /// @param fd 文件描述符
213cde5492fSlogin     /// @param buf 发送缓冲区
214cde5492fSlogin     /// @param flags 标志
215cde5492fSlogin     /// @param addr SockAddr
216cde5492fSlogin     /// @param addrlen 地址长度
217cde5492fSlogin     ///
218cde5492fSlogin     /// @return 成功返回发送的字节数,失败返回错误码
219ab5c8ca4Slogin     pub fn sendto(
220cde5492fSlogin         fd: usize,
221ab5c8ca4Slogin         buf: &[u8],
222ab5c8ca4Slogin         _flags: u32,
223cde5492fSlogin         addr: *const SockAddr,
224cde5492fSlogin         addrlen: usize,
225ab5c8ca4Slogin     ) -> Result<usize, SystemError> {
226cde5492fSlogin         let endpoint = if addr.is_null() {
227cde5492fSlogin             None
228cde5492fSlogin         } else {
229cde5492fSlogin             Some(SockAddr::to_endpoint(addr, addrlen)?)
230cde5492fSlogin         };
231cde5492fSlogin 
2321496ba7bSLoGin         let socket: Arc<SocketInode> = ProcessManager::current_pcb()
233cde5492fSlogin             .get_socket(fd as i32)
234cde5492fSlogin             .ok_or(SystemError::EBADF)?;
2352f6f547aSGnoCiYeH         let socket = unsafe { socket.inner_no_preempt() };
236ab5c8ca4Slogin         return socket.write(buf, endpoint);
237cde5492fSlogin     }
238cde5492fSlogin 
239cde5492fSlogin     /// @brief sys_recvfrom系统调用的实际执行函数
240cde5492fSlogin     ///
241cde5492fSlogin     /// @param fd 文件描述符
242cde5492fSlogin     /// @param buf 接收缓冲区
243cde5492fSlogin     /// @param flags 标志
244cde5492fSlogin     /// @param addr SockAddr
245cde5492fSlogin     /// @param addrlen 地址长度
246cde5492fSlogin     ///
247cde5492fSlogin     /// @return 成功返回接收的字节数,失败返回错误码
248ab5c8ca4Slogin     pub fn recvfrom(
249cde5492fSlogin         fd: usize,
250ab5c8ca4Slogin         buf: &mut [u8],
251ab5c8ca4Slogin         _flags: u32,
252cde5492fSlogin         addr: *mut SockAddr,
253cde5492fSlogin         addrlen: *mut u32,
254ab5c8ca4Slogin     ) -> Result<usize, SystemError> {
2551496ba7bSLoGin         let socket: Arc<SocketInode> = ProcessManager::current_pcb()
256cde5492fSlogin             .get_socket(fd as i32)
257cde5492fSlogin             .ok_or(SystemError::EBADF)?;
258*40609970SGnoCiYeH         let mut socket = unsafe { socket.inner_no_preempt() };
259cde5492fSlogin 
260cde5492fSlogin         let (n, endpoint) = socket.read(buf);
261cde5492fSlogin         drop(socket);
262cde5492fSlogin 
263cde5492fSlogin         let n: usize = n?;
264cde5492fSlogin 
265cde5492fSlogin         // 如果有地址信息,将地址信息写入用户空间
266cde5492fSlogin         if !addr.is_null() {
267cde5492fSlogin             let sockaddr_in = SockAddr::from(endpoint);
268cde5492fSlogin             unsafe {
269cde5492fSlogin                 sockaddr_in.write_to_user(addr, addrlen)?;
270cde5492fSlogin             }
271cde5492fSlogin         }
272ab5c8ca4Slogin         return Ok(n);
273cde5492fSlogin     }
274cde5492fSlogin 
275cde5492fSlogin     /// @brief sys_recvmsg系统调用的实际执行函数
276cde5492fSlogin     ///
277cde5492fSlogin     /// @param fd 文件描述符
278cde5492fSlogin     /// @param msg MsgHdr
279ab5c8ca4Slogin     /// @param flags 标志,暂时未使用
280cde5492fSlogin     ///
281cde5492fSlogin     /// @return 成功返回接收的字节数,失败返回错误码
282ab5c8ca4Slogin     pub fn recvmsg(fd: usize, msg: &mut MsgHdr, _flags: u32) -> Result<usize, SystemError> {
283cde5492fSlogin         // 检查每个缓冲区地址是否合法,生成iovecs
284cde5492fSlogin         let mut iovs = unsafe { IoVecs::from_user(msg.msg_iov, msg.msg_iovlen, true)? };
285cde5492fSlogin 
2861496ba7bSLoGin         let socket: Arc<SocketInode> = ProcessManager::current_pcb()
287cde5492fSlogin             .get_socket(fd as i32)
288cde5492fSlogin             .ok_or(SystemError::EBADF)?;
289*40609970SGnoCiYeH         let mut socket = unsafe { socket.inner_no_preempt() };
290cde5492fSlogin 
291cde5492fSlogin         let mut buf = iovs.new_buf(true);
292cde5492fSlogin         // 从socket中读取数据
293cde5492fSlogin         let (n, endpoint) = socket.read(&mut buf);
294cde5492fSlogin         drop(socket);
295cde5492fSlogin 
296cde5492fSlogin         let n: usize = n?;
297cde5492fSlogin 
298cde5492fSlogin         // 将数据写入用户空间的iovecs
299cde5492fSlogin         iovs.scatter(&buf[..n]);
300cde5492fSlogin 
301cde5492fSlogin         let sockaddr_in = SockAddr::from(endpoint);
302cde5492fSlogin         unsafe {
303cde5492fSlogin             sockaddr_in.write_to_user(msg.msg_name, &mut msg.msg_namelen)?;
304cde5492fSlogin         }
305ab5c8ca4Slogin         return Ok(n);
306cde5492fSlogin     }
307cde5492fSlogin 
308cde5492fSlogin     /// @brief sys_listen系统调用的实际执行函数
309cde5492fSlogin     ///
310cde5492fSlogin     /// @param fd 文件描述符
311ab5c8ca4Slogin     /// @param backlog 队列最大连接数
312cde5492fSlogin     ///
313cde5492fSlogin     /// @return 成功返回0,失败返回错误码
314ab5c8ca4Slogin     pub fn listen(fd: usize, backlog: usize) -> Result<usize, SystemError> {
3151496ba7bSLoGin         let socket: Arc<SocketInode> = ProcessManager::current_pcb()
316cde5492fSlogin             .get_socket(fd as i32)
317cde5492fSlogin             .ok_or(SystemError::EBADF)?;
3182f6f547aSGnoCiYeH         let mut socket = unsafe { socket.inner_no_preempt() };
319cde5492fSlogin         socket.listen(backlog)?;
320cde5492fSlogin         return Ok(0);
321cde5492fSlogin     }
322cde5492fSlogin 
323cde5492fSlogin     /// @brief sys_shutdown系统调用的实际执行函数
324cde5492fSlogin     ///
325cde5492fSlogin     /// @param fd 文件描述符
326cde5492fSlogin     /// @param how 关闭方式
327cde5492fSlogin     ///
328cde5492fSlogin     /// @return 成功返回0,失败返回错误码
329ab5c8ca4Slogin     pub fn shutdown(fd: usize, how: usize) -> Result<usize, SystemError> {
3301496ba7bSLoGin         let socket: Arc<SocketInode> = ProcessManager::current_pcb()
331cde5492fSlogin             .get_socket(fd as i32)
332cde5492fSlogin             .ok_or(SystemError::EBADF)?;
333*40609970SGnoCiYeH         let mut socket = unsafe { socket.inner_no_preempt() };
334*40609970SGnoCiYeH         socket.shutdown(ShutdownType::from_bits_truncate(how as u8))?;
335cde5492fSlogin         return Ok(0);
336cde5492fSlogin     }
337cde5492fSlogin 
338cde5492fSlogin     /// @brief sys_accept系统调用的实际执行函数
339cde5492fSlogin     ///
340cde5492fSlogin     /// @param fd 文件描述符
341cde5492fSlogin     /// @param addr SockAddr
342cde5492fSlogin     /// @param addrlen 地址长度
343cde5492fSlogin     ///
344cde5492fSlogin     /// @return 成功返回新的文件描述符,失败返回错误码
345ab5c8ca4Slogin     pub fn accept(fd: usize, addr: *mut SockAddr, addrlen: *mut u32) -> Result<usize, SystemError> {
346c47fe904SLoGin         return Self::do_accept(fd, addr, addrlen, 0);
347c47fe904SLoGin     }
348c47fe904SLoGin 
349c47fe904SLoGin     /// sys_accept4 - accept a connection on a socket
350c47fe904SLoGin     ///
351c47fe904SLoGin     ///
352c47fe904SLoGin     /// If flags is 0, then accept4() is the same as accept().  The
353c47fe904SLoGin     ///    following values can be bitwise ORed in flags to obtain different
354c47fe904SLoGin     ///    behavior:
355c47fe904SLoGin     ///
356c47fe904SLoGin     /// - SOCK_NONBLOCK
357c47fe904SLoGin     ///     Set the O_NONBLOCK file status flag on the open file
358c47fe904SLoGin     ///     description (see open(2)) referred to by the new file
359c47fe904SLoGin     ///     descriptor.  Using this flag saves extra calls to fcntl(2)
360c47fe904SLoGin     ///     to achieve the same result.
361c47fe904SLoGin     ///
362c47fe904SLoGin     /// - SOCK_CLOEXEC
363c47fe904SLoGin     ///     Set the close-on-exec (FD_CLOEXEC) flag on the new file
364c47fe904SLoGin     ///     descriptor.  See the description of the O_CLOEXEC flag in
365c47fe904SLoGin     ///     open(2) for reasons why this may be useful.
366c47fe904SLoGin     pub fn accept4(
367c47fe904SLoGin         fd: usize,
368c47fe904SLoGin         addr: *mut SockAddr,
369c47fe904SLoGin         addrlen: *mut u32,
370c47fe904SLoGin         mut flags: u32,
371c47fe904SLoGin     ) -> Result<usize, SystemError> {
372c47fe904SLoGin         // 如果flags不合法,返回错误
373c47fe904SLoGin         if (flags & (!(SOCK_CLOEXEC | SOCK_NONBLOCK)).bits()) != 0 {
374c47fe904SLoGin             return Err(SystemError::EINVAL);
375c47fe904SLoGin         }
376c47fe904SLoGin 
377c47fe904SLoGin         if SOCK_NONBLOCK != FileMode::O_NONBLOCK && ((flags & SOCK_NONBLOCK.bits()) != 0) {
378c47fe904SLoGin             flags = (flags & !SOCK_NONBLOCK.bits()) | FileMode::O_NONBLOCK.bits();
379c47fe904SLoGin         }
380c47fe904SLoGin 
381c47fe904SLoGin         return Self::do_accept(fd, addr, addrlen, flags);
382c47fe904SLoGin     }
383c47fe904SLoGin 
384c47fe904SLoGin     fn do_accept(
385c47fe904SLoGin         fd: usize,
386c47fe904SLoGin         addr: *mut SockAddr,
387c47fe904SLoGin         addrlen: *mut u32,
388c47fe904SLoGin         flags: u32,
389c47fe904SLoGin     ) -> Result<usize, SystemError> {
3901496ba7bSLoGin         let socket: Arc<SocketInode> = ProcessManager::current_pcb()
391cde5492fSlogin             .get_socket(fd as i32)
392cde5492fSlogin             .ok_or(SystemError::EBADF)?;
393cde5492fSlogin         // kdebug!("accept: socket={:?}", socket);
3942f6f547aSGnoCiYeH         let mut socket = unsafe { socket.inner_no_preempt() };
395cde5492fSlogin         // 从socket中接收连接
396cde5492fSlogin         let (new_socket, remote_endpoint) = socket.accept()?;
397cde5492fSlogin         drop(socket);
398cde5492fSlogin 
399cde5492fSlogin         // kdebug!("accept: new_socket={:?}", new_socket);
400cde5492fSlogin         // Insert the new socket into the file descriptor vector
401cde5492fSlogin         let new_socket: Arc<SocketInode> = SocketInode::new(new_socket);
402c47fe904SLoGin 
403c47fe904SLoGin         let mut file_mode = FileMode::O_RDWR;
404c47fe904SLoGin         if flags & FileMode::O_NONBLOCK.bits() != 0 {
405c47fe904SLoGin             file_mode |= FileMode::O_NONBLOCK;
406c47fe904SLoGin         }
407c47fe904SLoGin         if flags & FileMode::O_CLOEXEC.bits() != 0 {
408c47fe904SLoGin             file_mode |= FileMode::O_CLOEXEC;
409c47fe904SLoGin         }
410c47fe904SLoGin 
4111496ba7bSLoGin         let new_fd = ProcessManager::current_pcb()
4121496ba7bSLoGin             .fd_table()
4131496ba7bSLoGin             .write()
414c47fe904SLoGin             .alloc_fd(File::new(new_socket, file_mode)?, None)?;
415cde5492fSlogin         // kdebug!("accept: new_fd={}", new_fd);
416cde5492fSlogin         if !addr.is_null() {
417cde5492fSlogin             // kdebug!("accept: write remote_endpoint to user");
418cde5492fSlogin             // 将对端地址写入用户空间
419cde5492fSlogin             let sockaddr_in = SockAddr::from(remote_endpoint);
420cde5492fSlogin             unsafe {
421cde5492fSlogin                 sockaddr_in.write_to_user(addr, addrlen)?;
422cde5492fSlogin             }
423cde5492fSlogin         }
424ab5c8ca4Slogin         return Ok(new_fd as usize);
425cde5492fSlogin     }
426cde5492fSlogin 
427cde5492fSlogin     /// @brief sys_getsockname系统调用的实际执行函数
428cde5492fSlogin     ///
429cde5492fSlogin     ///  Returns the current address to which the socket
430cde5492fSlogin     ///     sockfd is bound, in the buffer pointed to by addr.
431cde5492fSlogin     ///
432cde5492fSlogin     /// @param fd 文件描述符
433cde5492fSlogin     /// @param addr SockAddr
434cde5492fSlogin     /// @param addrlen 地址长度
435cde5492fSlogin     ///
436cde5492fSlogin     /// @return 成功返回0,失败返回错误码
437ab5c8ca4Slogin     pub fn getsockname(
438cde5492fSlogin         fd: usize,
439cde5492fSlogin         addr: *mut SockAddr,
440cde5492fSlogin         addrlen: *mut u32,
441ab5c8ca4Slogin     ) -> Result<usize, SystemError> {
442cde5492fSlogin         if addr.is_null() {
443cde5492fSlogin             return Err(SystemError::EINVAL);
444cde5492fSlogin         }
4451496ba7bSLoGin         let socket: Arc<SocketInode> = ProcessManager::current_pcb()
446cde5492fSlogin             .get_socket(fd as i32)
447cde5492fSlogin             .ok_or(SystemError::EBADF)?;
448cde5492fSlogin         let socket = socket.inner();
449cde5492fSlogin         let endpoint: Endpoint = socket.endpoint().ok_or(SystemError::EINVAL)?;
450cde5492fSlogin         drop(socket);
451cde5492fSlogin 
452cde5492fSlogin         let sockaddr_in = SockAddr::from(endpoint);
453cde5492fSlogin         unsafe {
454cde5492fSlogin             sockaddr_in.write_to_user(addr, addrlen)?;
455cde5492fSlogin         }
456cde5492fSlogin         return Ok(0);
457cde5492fSlogin     }
458cde5492fSlogin 
459cde5492fSlogin     /// @brief sys_getpeername系统调用的实际执行函数
460cde5492fSlogin     ///
461cde5492fSlogin     /// @param fd 文件描述符
462cde5492fSlogin     /// @param addr SockAddr
463cde5492fSlogin     /// @param addrlen 地址长度
464cde5492fSlogin     ///
465cde5492fSlogin     /// @return 成功返回0,失败返回错误码
466ab5c8ca4Slogin     pub fn getpeername(
467cde5492fSlogin         fd: usize,
468cde5492fSlogin         addr: *mut SockAddr,
469cde5492fSlogin         addrlen: *mut u32,
470ab5c8ca4Slogin     ) -> Result<usize, SystemError> {
471cde5492fSlogin         if addr.is_null() {
472cde5492fSlogin             return Err(SystemError::EINVAL);
473cde5492fSlogin         }
474cde5492fSlogin 
4751496ba7bSLoGin         let socket: Arc<SocketInode> = ProcessManager::current_pcb()
476cde5492fSlogin             .get_socket(fd as i32)
477cde5492fSlogin             .ok_or(SystemError::EBADF)?;
478cde5492fSlogin         let socket = socket.inner();
479cde5492fSlogin         let endpoint: Endpoint = socket.peer_endpoint().ok_or(SystemError::EINVAL)?;
480cde5492fSlogin         drop(socket);
481cde5492fSlogin 
482cde5492fSlogin         let sockaddr_in = SockAddr::from(endpoint);
483cde5492fSlogin         unsafe {
484cde5492fSlogin             sockaddr_in.write_to_user(addr, addrlen)?;
485cde5492fSlogin         }
486cde5492fSlogin         return Ok(0);
487cde5492fSlogin     }
488ab5c8ca4Slogin }
489cde5492fSlogin 
490cde5492fSlogin // 参考资料: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/netinet_in.h.html#tag_13_32
491cde5492fSlogin #[repr(C)]
492cde5492fSlogin #[derive(Debug, Clone, Copy)]
493cde5492fSlogin pub struct SockAddrIn {
494cde5492fSlogin     pub sin_family: u16,
495cde5492fSlogin     pub sin_port: u16,
496cde5492fSlogin     pub sin_addr: u32,
497cde5492fSlogin     pub sin_zero: [u8; 8],
498cde5492fSlogin }
499cde5492fSlogin 
500cde5492fSlogin #[repr(C)]
501cde5492fSlogin #[derive(Debug, Clone, Copy)]
502cde5492fSlogin pub struct SockAddrUn {
503cde5492fSlogin     pub sun_family: u16,
504cde5492fSlogin     pub sun_path: [u8; 108],
505cde5492fSlogin }
506cde5492fSlogin 
507cde5492fSlogin #[repr(C)]
508cde5492fSlogin #[derive(Debug, Clone, Copy)]
509cde5492fSlogin pub struct SockAddrLl {
510cde5492fSlogin     pub sll_family: u16,
511cde5492fSlogin     pub sll_protocol: u16,
512cde5492fSlogin     pub sll_ifindex: u32,
513cde5492fSlogin     pub sll_hatype: u16,
514cde5492fSlogin     pub sll_pkttype: u8,
515cde5492fSlogin     pub sll_halen: u8,
516cde5492fSlogin     pub sll_addr: [u8; 8],
517cde5492fSlogin }
518cde5492fSlogin 
519cde5492fSlogin #[repr(C)]
520cde5492fSlogin #[derive(Debug, Clone, Copy)]
521cde5492fSlogin pub struct SockAddrNl {
522cde5492fSlogin     nl_family: u16,
523cde5492fSlogin     nl_pad: u16,
524cde5492fSlogin     nl_pid: u32,
525cde5492fSlogin     nl_groups: u32,
526cde5492fSlogin }
527cde5492fSlogin 
528cde5492fSlogin #[repr(C)]
529cde5492fSlogin #[derive(Debug, Clone, Copy)]
530cde5492fSlogin pub struct SockAddrPlaceholder {
531cde5492fSlogin     pub family: u16,
532cde5492fSlogin     pub data: [u8; 14],
533cde5492fSlogin }
534cde5492fSlogin 
535cde5492fSlogin #[repr(C)]
536cde5492fSlogin #[derive(Clone, Copy)]
537cde5492fSlogin pub union SockAddr {
538cde5492fSlogin     pub family: u16,
539cde5492fSlogin     pub addr_in: SockAddrIn,
540cde5492fSlogin     pub addr_un: SockAddrUn,
541cde5492fSlogin     pub addr_ll: SockAddrLl,
542cde5492fSlogin     pub addr_nl: SockAddrNl,
543cde5492fSlogin     pub addr_ph: SockAddrPlaceholder,
544cde5492fSlogin }
545cde5492fSlogin 
546cde5492fSlogin impl SockAddr {
547cde5492fSlogin     /// @brief 把用户传入的SockAddr转换为Endpoint结构体
548cde5492fSlogin     pub fn to_endpoint(addr: *const SockAddr, len: usize) -> Result<Endpoint, SystemError> {
549cde5492fSlogin         verify_area(
5504fda81ceSLoGin             VirtAddr::new(addr as usize),
5514fda81ceSLoGin             core::mem::size_of::<SockAddr>(),
552cde5492fSlogin         )
5534fda81ceSLoGin         .map_err(|_| SystemError::EFAULT)?;
554cde5492fSlogin 
555cde5492fSlogin         let addr = unsafe { addr.as_ref() }.ok_or(SystemError::EFAULT)?;
556cde5492fSlogin         if len < addr.len()? {
557cde5492fSlogin             return Err(SystemError::EINVAL);
558cde5492fSlogin         }
559cde5492fSlogin         unsafe {
560cde5492fSlogin             match AddressFamily::try_from(addr.family)? {
561cde5492fSlogin                 AddressFamily::INet => {
562cde5492fSlogin                     let addr_in: SockAddrIn = addr.addr_in;
563cde5492fSlogin 
564cde5492fSlogin                     let ip: wire::IpAddress = wire::IpAddress::from(wire::Ipv4Address::from_bytes(
565cde5492fSlogin                         &u32::from_be(addr_in.sin_addr).to_be_bytes()[..],
566cde5492fSlogin                     ));
567cde5492fSlogin                     let port = u16::from_be(addr_in.sin_port);
568cde5492fSlogin 
569cde5492fSlogin                     return Ok(Endpoint::Ip(Some(wire::IpEndpoint::new(ip, port))));
570cde5492fSlogin                 }
571cde5492fSlogin                 AddressFamily::Packet => {
572cde5492fSlogin                     // TODO: support packet socket
573cde5492fSlogin                     return Err(SystemError::EINVAL);
574cde5492fSlogin                 }
575cde5492fSlogin                 AddressFamily::Netlink => {
576cde5492fSlogin                     // TODO: support netlink socket
577cde5492fSlogin                     return Err(SystemError::EINVAL);
578cde5492fSlogin                 }
579cde5492fSlogin                 AddressFamily::Unix => {
580cde5492fSlogin                     return Err(SystemError::EINVAL);
581cde5492fSlogin                 }
582cde5492fSlogin                 _ => {
583cde5492fSlogin                     return Err(SystemError::EINVAL);
584cde5492fSlogin                 }
585cde5492fSlogin             }
586cde5492fSlogin         }
587cde5492fSlogin     }
588cde5492fSlogin 
589cde5492fSlogin     /// @brief 获取地址长度
590cde5492fSlogin     pub fn len(&self) -> Result<usize, SystemError> {
591cde5492fSlogin         let ret = match AddressFamily::try_from(unsafe { self.family })? {
592cde5492fSlogin             AddressFamily::INet => Ok(core::mem::size_of::<SockAddrIn>()),
593cde5492fSlogin             AddressFamily::Packet => Ok(core::mem::size_of::<SockAddrLl>()),
594cde5492fSlogin             AddressFamily::Netlink => Ok(core::mem::size_of::<SockAddrNl>()),
595cde5492fSlogin             AddressFamily::Unix => Err(SystemError::EINVAL),
596cde5492fSlogin             _ => Err(SystemError::EINVAL),
597cde5492fSlogin         };
598cde5492fSlogin 
599cde5492fSlogin         return ret;
600cde5492fSlogin     }
601cde5492fSlogin 
602cde5492fSlogin     /// @brief 把SockAddr的数据写入用户空间
603cde5492fSlogin     ///
604cde5492fSlogin     /// @param addr 用户空间的SockAddr的地址
605cde5492fSlogin     /// @param len 要写入的长度
606cde5492fSlogin     ///
607cde5492fSlogin     /// @return 成功返回写入的长度,失败返回错误码
608cde5492fSlogin     pub unsafe fn write_to_user(
609cde5492fSlogin         &self,
610cde5492fSlogin         addr: *mut SockAddr,
611cde5492fSlogin         addr_len: *mut u32,
612cde5492fSlogin     ) -> Result<usize, SystemError> {
613cde5492fSlogin         // 当用户传入的地址或者长度为空时,直接返回0
614cde5492fSlogin         if addr.is_null() || addr_len.is_null() {
615cde5492fSlogin             return Ok(0);
616cde5492fSlogin         }
6174fda81ceSLoGin 
618cde5492fSlogin         // 检查用户传入的地址是否合法
6194fda81ceSLoGin         verify_area(
6204fda81ceSLoGin             VirtAddr::new(addr as usize),
6214fda81ceSLoGin             core::mem::size_of::<SockAddr>(),
6224fda81ceSLoGin         )
6234fda81ceSLoGin         .map_err(|_| SystemError::EFAULT)?;
6244fda81ceSLoGin 
6254fda81ceSLoGin         verify_area(
6264fda81ceSLoGin             VirtAddr::new(addr_len as usize),
6274fda81ceSLoGin             core::mem::size_of::<u32>(),
6284fda81ceSLoGin         )
6294fda81ceSLoGin         .map_err(|_| SystemError::EFAULT)?;
630cde5492fSlogin 
631cde5492fSlogin         let to_write = min(self.len()?, *addr_len as usize);
632cde5492fSlogin         if to_write > 0 {
633cde5492fSlogin             let buf = core::slice::from_raw_parts_mut(addr as *mut u8, to_write);
634cde5492fSlogin             buf.copy_from_slice(core::slice::from_raw_parts(
635cde5492fSlogin                 self as *const SockAddr as *const u8,
636cde5492fSlogin                 to_write,
637cde5492fSlogin             ));
638cde5492fSlogin         }
639cde5492fSlogin         *addr_len = self.len()? as u32;
640cde5492fSlogin         return Ok(to_write);
641cde5492fSlogin     }
642cde5492fSlogin }
643cde5492fSlogin 
644cde5492fSlogin impl From<Endpoint> for SockAddr {
645cde5492fSlogin     fn from(value: Endpoint) -> Self {
646cde5492fSlogin         match value {
647cde5492fSlogin             Endpoint::Ip(ip_endpoint) => {
648cde5492fSlogin                 // 未指定地址
649cde5492fSlogin                 if let None = ip_endpoint {
650cde5492fSlogin                     return SockAddr {
651cde5492fSlogin                         addr_ph: SockAddrPlaceholder {
652cde5492fSlogin                             family: AddressFamily::Unspecified as u16,
653cde5492fSlogin                             data: [0; 14],
654cde5492fSlogin                         },
655cde5492fSlogin                     };
656cde5492fSlogin                 }
657cde5492fSlogin                 // 指定了地址
658cde5492fSlogin                 let ip_endpoint = ip_endpoint.unwrap();
659cde5492fSlogin                 match ip_endpoint.addr {
660cde5492fSlogin                     wire::IpAddress::Ipv4(ipv4_addr) => {
661cde5492fSlogin                         let addr_in = SockAddrIn {
662cde5492fSlogin                             sin_family: AddressFamily::INet as u16,
663cde5492fSlogin                             sin_port: ip_endpoint.port.to_be(),
664cde5492fSlogin                             sin_addr: u32::from_be_bytes(ipv4_addr.0).to_be(),
665cde5492fSlogin                             sin_zero: [0; 8],
666cde5492fSlogin                         };
667cde5492fSlogin 
668cde5492fSlogin                         return SockAddr { addr_in };
669cde5492fSlogin                     }
670cde5492fSlogin                     _ => {
671cde5492fSlogin                         unimplemented!("not support ipv6");
672cde5492fSlogin                     }
673cde5492fSlogin                 }
674cde5492fSlogin             }
675cde5492fSlogin 
676cde5492fSlogin             Endpoint::LinkLayer(link_endpoint) => {
677cde5492fSlogin                 let addr_ll = SockAddrLl {
678cde5492fSlogin                     sll_family: AddressFamily::Packet as u16,
679cde5492fSlogin                     sll_protocol: 0,
680cde5492fSlogin                     sll_ifindex: link_endpoint.interface as u32,
681cde5492fSlogin                     sll_hatype: 0,
682cde5492fSlogin                     sll_pkttype: 0,
683cde5492fSlogin                     sll_halen: 0,
684cde5492fSlogin                     sll_addr: [0; 8],
685cde5492fSlogin                 };
686cde5492fSlogin 
687cde5492fSlogin                 return SockAddr { addr_ll };
688cde5492fSlogin             } // _ => {
689cde5492fSlogin               //     // todo: support other endpoint, like Netlink...
690cde5492fSlogin               //     unimplemented!("not support {value:?}");
691cde5492fSlogin               // }
692cde5492fSlogin         }
693cde5492fSlogin     }
694cde5492fSlogin }
695cde5492fSlogin 
696cde5492fSlogin #[repr(C)]
697cde5492fSlogin #[derive(Debug, Clone, Copy)]
698cde5492fSlogin pub struct MsgHdr {
699cde5492fSlogin     /// 指向一个SockAddr结构体的指针
700cde5492fSlogin     pub msg_name: *mut SockAddr,
701cde5492fSlogin     /// SockAddr结构体的大小
702cde5492fSlogin     pub msg_namelen: u32,
703cde5492fSlogin     /// scatter/gather array
704cde5492fSlogin     pub msg_iov: *mut IoVec,
705cde5492fSlogin     /// elements in msg_iov
706cde5492fSlogin     pub msg_iovlen: usize,
707cde5492fSlogin     /// 辅助数据
708cde5492fSlogin     pub msg_control: *mut u8,
709cde5492fSlogin     /// 辅助数据长度
710cde5492fSlogin     pub msg_controllen: usize,
711cde5492fSlogin     /// 接收到的消息的标志
712cde5492fSlogin     pub msg_flags: u32,
713cde5492fSlogin }
714cde5492fSlogin 
715cde5492fSlogin #[derive(Debug, Clone, Copy, FromPrimitive, ToPrimitive, PartialEq, Eq)]
716cde5492fSlogin pub enum PosixIpProtocol {
717cde5492fSlogin     /// Dummy protocol for TCP.
718cde5492fSlogin     IP = 0,
719cde5492fSlogin     /// Internet Control Message Protocol.
720cde5492fSlogin     ICMP = 1,
721cde5492fSlogin     /// Internet Group Management Protocol.
722cde5492fSlogin     IGMP = 2,
723cde5492fSlogin     /// IPIP tunnels (older KA9Q tunnels use 94).
724cde5492fSlogin     IPIP = 4,
725cde5492fSlogin     /// Transmission Control Protocol.
726cde5492fSlogin     TCP = 6,
727cde5492fSlogin     /// Exterior Gateway Protocol.
728cde5492fSlogin     EGP = 8,
729cde5492fSlogin     /// PUP protocol.
730cde5492fSlogin     PUP = 12,
731cde5492fSlogin     /// User Datagram Protocol.
732cde5492fSlogin     UDP = 17,
733cde5492fSlogin     /// XNS IDP protocol.
734cde5492fSlogin     IDP = 22,
735cde5492fSlogin     /// SO Transport Protocol Class 4.
736cde5492fSlogin     TP = 29,
737cde5492fSlogin     /// Datagram Congestion Control Protocol.
738cde5492fSlogin     DCCP = 33,
739cde5492fSlogin     /// IPv6-in-IPv4 tunnelling.
740cde5492fSlogin     IPv6 = 41,
741cde5492fSlogin     /// RSVP Protocol.
742cde5492fSlogin     RSVP = 46,
743cde5492fSlogin     /// Generic Routing Encapsulation. (Cisco GRE) (rfc 1701, 1702)
744cde5492fSlogin     GRE = 47,
745cde5492fSlogin     /// Encapsulation Security Payload protocol
746cde5492fSlogin     ESP = 50,
747cde5492fSlogin     /// Authentication Header protocol
748cde5492fSlogin     AH = 51,
749cde5492fSlogin     /// Multicast Transport Protocol.
750cde5492fSlogin     MTP = 92,
751cde5492fSlogin     /// IP option pseudo header for BEET
752cde5492fSlogin     BEETPH = 94,
753cde5492fSlogin     /// Encapsulation Header.
754cde5492fSlogin     ENCAP = 98,
755cde5492fSlogin     /// Protocol Independent Multicast.
756cde5492fSlogin     PIM = 103,
757cde5492fSlogin     /// Compression Header Protocol.
758cde5492fSlogin     COMP = 108,
759cde5492fSlogin     /// Stream Control Transport Protocol
760cde5492fSlogin     SCTP = 132,
761cde5492fSlogin     /// UDP-Lite protocol (RFC 3828)
762cde5492fSlogin     UDPLITE = 136,
763cde5492fSlogin     /// MPLS in IP (RFC 4023)
764cde5492fSlogin     MPLSINIP = 137,
765cde5492fSlogin     /// Ethernet-within-IPv6 Encapsulation
766cde5492fSlogin     ETHERNET = 143,
767cde5492fSlogin     /// Raw IP packets
768cde5492fSlogin     RAW = 255,
769cde5492fSlogin     /// Multipath TCP connection
770cde5492fSlogin     MPTCP = 262,
771cde5492fSlogin }
772cde5492fSlogin 
773cde5492fSlogin impl TryFrom<u16> for PosixIpProtocol {
774cde5492fSlogin     type Error = SystemError;
775cde5492fSlogin 
776cde5492fSlogin     fn try_from(value: u16) -> Result<Self, Self::Error> {
777cde5492fSlogin         match <Self as FromPrimitive>::from_u16(value) {
778cde5492fSlogin             Some(p) => Ok(p),
779cde5492fSlogin             None => Err(SystemError::EPROTONOSUPPORT),
780cde5492fSlogin         }
781cde5492fSlogin     }
782cde5492fSlogin }
783cde5492fSlogin 
784cde5492fSlogin impl Into<u16> for PosixIpProtocol {
785cde5492fSlogin     fn into(self) -> u16 {
786cde5492fSlogin         <Self as ToPrimitive>::to_u16(&self).unwrap()
787cde5492fSlogin     }
788cde5492fSlogin }
789cde5492fSlogin 
790cde5492fSlogin #[allow(non_camel_case_types)]
791cde5492fSlogin #[derive(Debug, Clone, Copy, FromPrimitive, ToPrimitive, PartialEq, Eq)]
792cde5492fSlogin pub enum PosixSocketOption {
793cde5492fSlogin     SO_DEBUG = 1,
794cde5492fSlogin     SO_REUSEADDR = 2,
795cde5492fSlogin     SO_TYPE = 3,
796cde5492fSlogin     SO_ERROR = 4,
797cde5492fSlogin     SO_DONTROUTE = 5,
798cde5492fSlogin     SO_BROADCAST = 6,
799cde5492fSlogin     SO_SNDBUF = 7,
800cde5492fSlogin     SO_RCVBUF = 8,
801cde5492fSlogin     SO_SNDBUFFORCE = 32,
802cde5492fSlogin     SO_RCVBUFFORCE = 33,
803cde5492fSlogin     SO_KEEPALIVE = 9,
804cde5492fSlogin     SO_OOBINLINE = 10,
805cde5492fSlogin     SO_NO_CHECK = 11,
806cde5492fSlogin     SO_PRIORITY = 12,
807cde5492fSlogin     SO_LINGER = 13,
808cde5492fSlogin     SO_BSDCOMPAT = 14,
809cde5492fSlogin     SO_REUSEPORT = 15,
810cde5492fSlogin     SO_PASSCRED = 16,
811cde5492fSlogin     SO_PEERCRED = 17,
812cde5492fSlogin     SO_RCVLOWAT = 18,
813cde5492fSlogin     SO_SNDLOWAT = 19,
814cde5492fSlogin     SO_RCVTIMEO_OLD = 20,
815cde5492fSlogin     SO_SNDTIMEO_OLD = 21,
816cde5492fSlogin 
817cde5492fSlogin     SO_SECURITY_AUTHENTICATION = 22,
818cde5492fSlogin     SO_SECURITY_ENCRYPTION_TRANSPORT = 23,
819cde5492fSlogin     SO_SECURITY_ENCRYPTION_NETWORK = 24,
820cde5492fSlogin 
821cde5492fSlogin     SO_BINDTODEVICE = 25,
822cde5492fSlogin 
823cde5492fSlogin     /// 与SO_GET_FILTER相同
824cde5492fSlogin     SO_ATTACH_FILTER = 26,
825cde5492fSlogin     SO_DETACH_FILTER = 27,
826cde5492fSlogin 
827cde5492fSlogin     SO_PEERNAME = 28,
828cde5492fSlogin 
829cde5492fSlogin     SO_ACCEPTCONN = 30,
830cde5492fSlogin 
831cde5492fSlogin     SO_PEERSEC = 31,
832cde5492fSlogin     SO_PASSSEC = 34,
833cde5492fSlogin 
834cde5492fSlogin     SO_MARK = 36,
835cde5492fSlogin 
836cde5492fSlogin     SO_PROTOCOL = 38,
837cde5492fSlogin     SO_DOMAIN = 39,
838cde5492fSlogin 
839cde5492fSlogin     SO_RXQ_OVFL = 40,
840cde5492fSlogin 
841cde5492fSlogin     /// 与SCM_WIFI_STATUS相同
842cde5492fSlogin     SO_WIFI_STATUS = 41,
843cde5492fSlogin     SO_PEEK_OFF = 42,
844cde5492fSlogin 
845cde5492fSlogin     /* Instruct lower device to use last 4-bytes of skb data as FCS */
846cde5492fSlogin     SO_NOFCS = 43,
847cde5492fSlogin 
848cde5492fSlogin     SO_LOCK_FILTER = 44,
849cde5492fSlogin     SO_SELECT_ERR_QUEUE = 45,
850cde5492fSlogin     SO_BUSY_POLL = 46,
851cde5492fSlogin     SO_MAX_PACING_RATE = 47,
852cde5492fSlogin     SO_BPF_EXTENSIONS = 48,
853cde5492fSlogin     SO_INCOMING_CPU = 49,
854cde5492fSlogin     SO_ATTACH_BPF = 50,
855cde5492fSlogin     // SO_DETACH_BPF = SO_DETACH_FILTER,
856cde5492fSlogin     SO_ATTACH_REUSEPORT_CBPF = 51,
857cde5492fSlogin     SO_ATTACH_REUSEPORT_EBPF = 52,
858cde5492fSlogin 
859cde5492fSlogin     SO_CNX_ADVICE = 53,
860cde5492fSlogin     SCM_TIMESTAMPING_OPT_STATS = 54,
861cde5492fSlogin     SO_MEMINFO = 55,
862cde5492fSlogin     SO_INCOMING_NAPI_ID = 56,
863cde5492fSlogin     SO_COOKIE = 57,
864cde5492fSlogin     SCM_TIMESTAMPING_PKTINFO = 58,
865cde5492fSlogin     SO_PEERGROUPS = 59,
866cde5492fSlogin     SO_ZEROCOPY = 60,
867cde5492fSlogin     /// 与SCM_TXTIME相同
868cde5492fSlogin     SO_TXTIME = 61,
869cde5492fSlogin 
870cde5492fSlogin     SO_BINDTOIFINDEX = 62,
871cde5492fSlogin 
872cde5492fSlogin     SO_TIMESTAMP_OLD = 29,
873cde5492fSlogin     SO_TIMESTAMPNS_OLD = 35,
874cde5492fSlogin     SO_TIMESTAMPING_OLD = 37,
875cde5492fSlogin     SO_TIMESTAMP_NEW = 63,
876cde5492fSlogin     SO_TIMESTAMPNS_NEW = 64,
877cde5492fSlogin     SO_TIMESTAMPING_NEW = 65,
878cde5492fSlogin 
879cde5492fSlogin     SO_RCVTIMEO_NEW = 66,
880cde5492fSlogin     SO_SNDTIMEO_NEW = 67,
881cde5492fSlogin 
882cde5492fSlogin     SO_DETACH_REUSEPORT_BPF = 68,
883cde5492fSlogin 
884cde5492fSlogin     SO_PREFER_BUSY_POLL = 69,
885cde5492fSlogin     SO_BUSY_POLL_BUDGET = 70,
886cde5492fSlogin 
887cde5492fSlogin     SO_NETNS_COOKIE = 71,
888cde5492fSlogin     SO_BUF_LOCK = 72,
889cde5492fSlogin     SO_RESERVE_MEM = 73,
890cde5492fSlogin     SO_TXREHASH = 74,
891cde5492fSlogin     SO_RCVMARK = 75,
892cde5492fSlogin }
893cde5492fSlogin 
894cde5492fSlogin impl TryFrom<i32> for PosixSocketOption {
895cde5492fSlogin     type Error = SystemError;
896cde5492fSlogin 
897cde5492fSlogin     fn try_from(value: i32) -> Result<Self, Self::Error> {
898cde5492fSlogin         match <Self as FromPrimitive>::from_i32(value) {
899cde5492fSlogin             Some(p) => Ok(p),
900cde5492fSlogin             None => Err(SystemError::EINVAL),
901cde5492fSlogin         }
902cde5492fSlogin     }
903cde5492fSlogin }
904cde5492fSlogin 
905cde5492fSlogin impl Into<i32> for PosixSocketOption {
906cde5492fSlogin     fn into(self) -> i32 {
907cde5492fSlogin         <Self as ToPrimitive>::to_i32(&self).unwrap()
908cde5492fSlogin     }
909cde5492fSlogin }
910cde5492fSlogin 
911cde5492fSlogin #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
912cde5492fSlogin pub enum PosixTcpSocketOptions {
913cde5492fSlogin     /// Turn off Nagle's algorithm.
914cde5492fSlogin     NoDelay = 1,
915cde5492fSlogin     /// Limit MSS.
916cde5492fSlogin     MaxSegment = 2,
917cde5492fSlogin     /// Never send partially complete segments.
918cde5492fSlogin     Cork = 3,
919cde5492fSlogin     /// Start keeplives after this period.
920cde5492fSlogin     KeepIdle = 4,
921cde5492fSlogin     /// Interval between keepalives.
922cde5492fSlogin     KeepIntvl = 5,
923cde5492fSlogin     /// Number of keepalives before death.
924cde5492fSlogin     KeepCnt = 6,
925cde5492fSlogin     /// Number of SYN retransmits.
926cde5492fSlogin     Syncnt = 7,
927cde5492fSlogin     /// Lifetime for orphaned FIN-WAIT-2 state.
928cde5492fSlogin     Linger2 = 8,
929cde5492fSlogin     /// Wake up listener only when data arrive.
930cde5492fSlogin     DeferAccept = 9,
931cde5492fSlogin     /// Bound advertised window
932cde5492fSlogin     WindowClamp = 10,
933cde5492fSlogin     /// Information about this connection.
934cde5492fSlogin     Info = 11,
935cde5492fSlogin     /// Block/reenable quick acks.
936cde5492fSlogin     QuickAck = 12,
937cde5492fSlogin     /// Congestion control algorithm.
938cde5492fSlogin     Congestion = 13,
939cde5492fSlogin     /// TCP MD5 Signature (RFC2385).
940cde5492fSlogin     Md5Sig = 14,
941cde5492fSlogin     /// Use linear timeouts for thin streams
942cde5492fSlogin     ThinLinearTimeouts = 16,
943cde5492fSlogin     /// Fast retrans. after 1 dupack.
944cde5492fSlogin     ThinDupack = 17,
945cde5492fSlogin     /// How long for loss retry before timeout.
946cde5492fSlogin     UserTimeout = 18,
947cde5492fSlogin     /// TCP sock is under repair right now.
948cde5492fSlogin     Repair = 19,
949cde5492fSlogin     RepairQueue = 20,
950cde5492fSlogin     QueueSeq = 21,
951cde5492fSlogin     RepairOptions = 22,
952cde5492fSlogin     /// Enable FastOpen on listeners
953cde5492fSlogin     FastOpen = 23,
954cde5492fSlogin     Timestamp = 24,
955cde5492fSlogin     /// Limit number of unsent bytes in write queue.
956cde5492fSlogin     NotSentLowat = 25,
957cde5492fSlogin     /// Get Congestion Control (optional) info.
958cde5492fSlogin     CCInfo = 26,
959cde5492fSlogin     /// Record SYN headers for new connections.
960cde5492fSlogin     SaveSyn = 27,
961cde5492fSlogin     /// Get SYN headers recorded for connection.
962cde5492fSlogin     SavedSyn = 28,
963cde5492fSlogin     /// Get/set window parameters.
964cde5492fSlogin     RepairWindow = 29,
965cde5492fSlogin     /// Attempt FastOpen with connect.
966cde5492fSlogin     FastOpenConnect = 30,
967cde5492fSlogin     /// Attach a ULP to a TCP connection.
968cde5492fSlogin     ULP = 31,
969cde5492fSlogin     /// TCP MD5 Signature with extensions.
970cde5492fSlogin     Md5SigExt = 32,
971cde5492fSlogin     /// Set the key for Fast Open(cookie).
972cde5492fSlogin     FastOpenKey = 33,
973cde5492fSlogin     /// Enable TFO without a TFO cookie.
974cde5492fSlogin     FastOpenNoCookie = 34,
975cde5492fSlogin     ZeroCopyReceive = 35,
976cde5492fSlogin     /// Notify bytes available to read as a cmsg on read.
977cde5492fSlogin     /// 与TCP_CM_INQ相同
978cde5492fSlogin     INQ = 36,
979cde5492fSlogin     /// delay outgoing packets by XX usec
980cde5492fSlogin     TxDelay = 37,
981cde5492fSlogin }
982cde5492fSlogin 
983cde5492fSlogin impl TryFrom<i32> for PosixTcpSocketOptions {
984cde5492fSlogin     type Error = SystemError;
985cde5492fSlogin 
986cde5492fSlogin     fn try_from(value: i32) -> Result<Self, Self::Error> {
987cde5492fSlogin         match <Self as FromPrimitive>::from_i32(value) {
988cde5492fSlogin             Some(p) => Ok(p),
989cde5492fSlogin             None => Err(SystemError::EINVAL),
990cde5492fSlogin         }
991cde5492fSlogin     }
992cde5492fSlogin }
993cde5492fSlogin 
994cde5492fSlogin impl Into<i32> for PosixTcpSocketOptions {
995cde5492fSlogin     fn into(self) -> i32 {
996cde5492fSlogin         <Self as ToPrimitive>::to_i32(&self).unwrap()
997cde5492fSlogin     }
998cde5492fSlogin }
999