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