xref: /DragonOS/kernel/src/net/socket/mod.rs (revision dfe53cf087ef4c7b6db63d992906b062dc63e93f)
1 use core::{any::Any, fmt::Debug, sync::atomic::AtomicUsize};
2 
3 use alloc::{
4     boxed::Box,
5     collections::LinkedList,
6     string::String,
7     sync::{Arc, Weak},
8     vec::Vec,
9 };
10 use hashbrown::HashMap;
11 use smoltcp::{
12     iface::{SocketHandle, SocketSet},
13     socket::{self, tcp, udp},
14 };
15 use system_error::SystemError;
16 
17 use crate::{
18     arch::{rand::rand, sched::sched},
19     filesystem::vfs::{
20         file::FileMode, syscall::ModeType, FilePrivateData, FileSystem, FileType, IndexNode,
21         Metadata,
22     },
23     libs::{
24         rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
25         spinlock::{SpinLock, SpinLockGuard},
26         wait_queue::EventWaitQueue,
27     },
28 };
29 
30 use self::{
31     inet::{RawSocket, TcpSocket, UdpSocket},
32     unix::{SeqpacketSocket, StreamSocket},
33 };
34 
35 use super::{
36     event_poll::{EPollEventType, EPollItem, EventPoll},
37     net_core::poll_ifaces,
38     Endpoint, Protocol, ShutdownType,
39 };
40 
41 pub mod inet;
42 pub mod unix;
43 
44 lazy_static! {
45     /// 所有socket的集合
46     /// TODO: 优化这里,自己实现SocketSet!!!现在这样的话,不管全局有多少个网卡,每个时间点都只会有1个进程能够访问socket
47     pub static ref SOCKET_SET: SpinLock<SocketSet<'static >> = SpinLock::new(SocketSet::new(vec![]));
48     /// SocketHandle表,每个SocketHandle对应一个SocketHandleItem,
49     /// 注意!:在网卡中断中需要拿到这张表的��,在获取读锁时应该确保关中断避免死锁
50     pub static ref HANDLE_MAP: RwLock<HashMap<SocketHandle, SocketHandleItem>> = RwLock::new(HashMap::new());
51     /// 端口管理器
52     pub static ref PORT_MANAGER: PortManager = PortManager::new();
53 }
54 
55 /* For setsockopt(2) */
56 // See: linux-5.19.10/include/uapi/asm-generic/socket.h#9
57 pub const SOL_SOCKET: u8 = 1;
58 
59 /// 根据地址族、socket类型和协议创建socket
60 pub(super) fn new_socket(
61     address_family: AddressFamily,
62     socket_type: PosixSocketType,
63     protocol: Protocol,
64 ) -> Result<Box<dyn Socket>, SystemError> {
65     let socket: Box<dyn Socket> = match address_family {
66         AddressFamily::Unix => match socket_type {
67             PosixSocketType::Stream => Box::new(StreamSocket::new(SocketOptions::default())),
68             PosixSocketType::SeqPacket => Box::new(SeqpacketSocket::new(SocketOptions::default())),
69             _ => {
70                 return Err(SystemError::EINVAL);
71             }
72         },
73         AddressFamily::INet => match socket_type {
74             PosixSocketType::Stream => Box::new(TcpSocket::new(SocketOptions::default())),
75             PosixSocketType::Datagram => Box::new(UdpSocket::new(SocketOptions::default())),
76             PosixSocketType::Raw => Box::new(RawSocket::new(protocol, SocketOptions::default())),
77             _ => {
78                 return Err(SystemError::EINVAL);
79             }
80         },
81         _ => {
82             return Err(SystemError::EAFNOSUPPORT);
83         }
84     };
85     Ok(socket)
86 }
87 
88 pub trait Socket: Sync + Send + Debug + Any {
89     /// @brief 从socket中读取数据,如果socket是阻塞的,那么直到读取到数据才返回
90     ///
91     /// @param buf 读取到的数据存放的缓冲区
92     ///
93     /// @return - 成功:(返回读取的数据的长度,读取数据的端点).
94     ///         - 失败:错误码
95     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint);
96 
97     /// @brief 向socket中写入数据。如果socket是阻塞的,那么直到写入的数据全部写入socket中才返回
98     ///
99     /// @param buf 要写入的数据
100     /// @param to 要写入的目的端点,如果是None,那么写入的数据将会被丢弃
101     ///
102     /// @return 返回写入的数据的长度
103     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError>;
104 
105     /// @brief 对应于POSIX的connect函数,用于连接到指定的远程服务器端点
106     ///
107     /// It is used to establish a connection to a remote server.
108     /// When a socket is connected to a remote server,
109     /// the operating system will establish a network connection with the server
110     /// and allow data to be sent and received between the local socket and the remote server.
111     ///
112     /// @param endpoint 要连接的端点
113     ///
114     /// @return 返回连接是否成功
115     fn connect(&mut self, _endpoint: Endpoint) -> Result<(), SystemError>;
116 
117     /// @brief 对应于POSIX的bind函数,用于绑定到本机指定的端点
118     ///
119     /// The bind() function is used to associate a socket with a particular IP address and port number on the local machine.
120     ///
121     /// @param endpoint 要绑定的端点
122     ///
123     /// @return 返回绑定是否成功
124     fn bind(&mut self, _endpoint: Endpoint) -> Result<(), SystemError> {
125         Err(SystemError::ENOSYS)
126     }
127 
128     /// @brief 对应于 POSIX 的 shutdown 函数,用于关闭socket。
129     ///
130     /// shutdown() 函数用于启动网络连接的正常关闭。
131     /// 当在两个端点之间建立网络连接时,任一端点都可以通过调用其端点对象上的 shutdown() 函数来启动关闭序列。
132     /// 此函数向远程端点发送关闭消息以指示本地端点不再接受新数据。
133     ///
134     /// @return 返回是否成功关闭
135     fn shutdown(&mut self, _type: ShutdownType) -> Result<(), SystemError> {
136         Err(SystemError::ENOSYS)
137     }
138 
139     /// @brief 对应于POSIX的listen函数,用于监听端点
140     ///
141     /// @param backlog 最大的等待连接数
142     ///
143     /// @return 返回监听是否成功
144     fn listen(&mut self, _backlog: usize) -> Result<(), SystemError> {
145         Err(SystemError::ENOSYS)
146     }
147 
148     /// @brief 对应于POSIX的accept函数,用于接受连接
149     ///
150     /// @param endpoint 对端的端点
151     ///
152     /// @return 返回接受连接是否成功
153     fn accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError> {
154         Err(SystemError::ENOSYS)
155     }
156 
157     /// @brief 获取socket的端点
158     ///
159     /// @return 返回socket的端点
160     fn endpoint(&self) -> Option<Endpoint> {
161         None
162     }
163 
164     /// @brief 获取socket的对端端点
165     ///
166     /// @return 返回socket的对端端点
167     fn peer_endpoint(&self) -> Option<Endpoint> {
168         None
169     }
170 
171     /// @brief
172     ///     The purpose of the poll function is to provide
173     ///     a non-blocking way to check if a socket is ready for reading or writing,
174     ///     so that you can efficiently handle multiple sockets in a single thread or event loop.
175     ///
176     /// @return (in, out, err)
177     ///
178     ///     The first boolean value indicates whether the socket is ready for reading. If it is true, then there is data available to be read from the socket without blocking.
179     ///     The second boolean value indicates whether the socket is ready for writing. If it is true, then data can be written to the socket without blocking.
180     ///     The third boolean value indicates whether the socket has encountered an error condition. If it is true, then the socket is in an error state and should be closed or reset
181     ///
182     fn poll(&self) -> EPollEventType {
183         EPollEventType::empty()
184     }
185 
186     /// @brief socket的ioctl函数
187     ///
188     /// @param cmd ioctl命令
189     /// @param arg0 ioctl命令的第一个参数
190     /// @param arg1 ioctl命令的第二个参数
191     /// @param arg2 ioctl命令的第三个参数
192     ///
193     /// @return 返回ioctl命令的返回值
194     fn ioctl(
195         &self,
196         _cmd: usize,
197         _arg0: usize,
198         _arg1: usize,
199         _arg2: usize,
200     ) -> Result<usize, SystemError> {
201         Ok(0)
202     }
203 
204     /// @brief 获取socket的元数据
205     fn metadata(&self) -> SocketMetadata;
206 
207     fn box_clone(&self) -> Box<dyn Socket>;
208 
209     /// @brief 设置socket的选项
210     ///
211     /// @param level 选项的层次
212     /// @param optname 选项的名称
213     /// @param optval 选项的值
214     ///
215     /// @return 返回设置是否成功, 如果不支持该选项,返回ENOSYS
216     fn setsockopt(
217         &self,
218         _level: usize,
219         _optname: usize,
220         _optval: &[u8],
221     ) -> Result<(), SystemError> {
222         kwarn!("setsockopt is not implemented");
223         Ok(())
224     }
225 
226     fn socket_handle(&self) -> SocketHandle {
227         todo!()
228     }
229 
230     fn write_buffer(&self, _buf: &[u8]) -> Result<usize, SystemError> {
231         todo!()
232     }
233 
234     fn as_any_ref(&self) -> &dyn Any;
235 
236     fn as_any_mut(&mut self) -> &mut dyn Any;
237 
238     fn add_epoll(&mut self, epitem: Arc<EPollItem>) -> Result<(), SystemError> {
239         HANDLE_MAP
240             .write_irqsave()
241             .get_mut(&self.socket_handle())
242             .unwrap()
243             .add_epoll(epitem);
244         Ok(())
245     }
246 
247     fn remove_epoll(&mut self, epoll: &Weak<SpinLock<EventPoll>>) -> Result<(), SystemError> {
248         HANDLE_MAP
249             .write_irqsave()
250             .get_mut(&self.socket_handle())
251             .unwrap()
252             .remove_epoll(epoll)?;
253 
254         Ok(())
255     }
256 
257     fn clear_epoll(&mut self) -> Result<(), SystemError> {
258         let mut handle_map_guard = HANDLE_MAP.write_irqsave();
259         let handle_item = handle_map_guard.get_mut(&self.socket_handle()).unwrap();
260 
261         for epitem in handle_item.epitems.lock_irqsave().iter() {
262             let epoll = epitem.epoll();
263             if epoll.upgrade().is_some() {
264                 EventPoll::ep_remove(
265                     &mut epoll.upgrade().unwrap().lock_irqsave(),
266                     epitem.fd(),
267                     None,
268                 )?;
269             }
270         }
271 
272         Ok(())
273     }
274 }
275 
276 impl Clone for Box<dyn Socket> {
277     fn clone(&self) -> Box<dyn Socket> {
278         self.box_clone()
279     }
280 }
281 
282 /// # Socket在文件系统中的inode封装
283 #[derive(Debug)]
284 pub struct SocketInode(SpinLock<Box<dyn Socket>>, AtomicUsize);
285 
286 impl SocketInode {
287     pub fn new(socket: Box<dyn Socket>) -> Arc<Self> {
288         Arc::new(Self(SpinLock::new(socket), AtomicUsize::new(0)))
289     }
290 
291     #[inline]
292     pub fn inner(&self) -> SpinLockGuard<Box<dyn Socket>> {
293         self.0.lock()
294     }
295 
296     pub unsafe fn inner_no_preempt(&self) -> SpinLockGuard<Box<dyn Socket>> {
297         self.0.lock_no_preempt()
298     }
299 }
300 
301 impl IndexNode for SocketInode {
302     fn open(
303         &self,
304         _data: SpinLockGuard<FilePrivateData>,
305         _mode: &FileMode,
306     ) -> Result<(), SystemError> {
307         self.1.fetch_add(1, core::sync::atomic::Ordering::SeqCst);
308         Ok(())
309     }
310 
311     fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> {
312         let prev_ref_count = self.1.fetch_sub(1, core::sync::atomic::Ordering::SeqCst);
313         if prev_ref_count == 1 {
314             // 最后一次关闭,需要释放
315             let mut socket = self.0.lock_irqsave();
316 
317             if socket.metadata().socket_type == SocketType::Unix {
318                 return Ok(());
319             }
320 
321             if let Some(Endpoint::Ip(Some(ip))) = socket.endpoint() {
322                 PORT_MANAGER.unbind_port(socket.metadata().socket_type, ip.port)?;
323             }
324 
325             socket.clear_epoll()?;
326 
327             HANDLE_MAP
328                 .write_irqsave()
329                 .remove(&socket.socket_handle())
330                 .unwrap();
331         }
332         Ok(())
333     }
334 
335     fn read_at(
336         &self,
337         _offset: usize,
338         len: usize,
339         buf: &mut [u8],
340         _data: SpinLockGuard<FilePrivateData>,
341     ) -> Result<usize, SystemError> {
342         self.0.lock_no_preempt().read(&mut buf[0..len]).0
343     }
344 
345     fn write_at(
346         &self,
347         _offset: usize,
348         len: usize,
349         buf: &[u8],
350         _data: SpinLockGuard<FilePrivateData>,
351     ) -> Result<usize, SystemError> {
352         self.0.lock_no_preempt().write(&buf[0..len], None)
353     }
354 
355     fn poll(&self, _private_data: &FilePrivateData) -> Result<usize, SystemError> {
356         let events = self.0.lock_irqsave().poll();
357         return Ok(events.bits() as usize);
358     }
359 
360     fn fs(&self) -> Arc<dyn FileSystem> {
361         todo!()
362     }
363 
364     fn as_any_ref(&self) -> &dyn Any {
365         self
366     }
367 
368     fn list(&self) -> Result<Vec<String>, SystemError> {
369         return Err(SystemError::ENOTDIR);
370     }
371 
372     fn metadata(&self) -> Result<Metadata, SystemError> {
373         let meta = Metadata {
374             mode: ModeType::from_bits_truncate(0o755),
375             file_type: FileType::Socket,
376             ..Default::default()
377         };
378 
379         return Ok(meta);
380     }
381 
382     fn resize(&self, _len: usize) -> Result<(), SystemError> {
383         return Ok(());
384     }
385 }
386 
387 #[derive(Debug)]
388 pub struct SocketHandleItem {
389     /// shutdown状态
390     pub shutdown_type: RwLock<ShutdownType>,
391     /// socket的waitqueue
392     pub wait_queue: EventWaitQueue,
393     /// epitems,考虑写在这是否是最优解?
394     pub epitems: SpinLock<LinkedList<Arc<EPollItem>>>,
395 }
396 
397 impl SocketHandleItem {
398     pub fn new() -> Self {
399         Self {
400             shutdown_type: RwLock::new(ShutdownType::empty()),
401             wait_queue: EventWaitQueue::new(),
402             epitems: SpinLock::new(LinkedList::new()),
403         }
404     }
405 
406     /// ## 在socket的等待队列上睡眠
407     pub fn sleep(
408         socket_handle: SocketHandle,
409         events: u64,
410         handle_map_guard: RwLockReadGuard<'_, HashMap<SocketHandle, SocketHandleItem>>,
411     ) {
412         unsafe {
413             handle_map_guard
414                 .get(&socket_handle)
415                 .unwrap()
416                 .wait_queue
417                 .sleep_without_schedule(events)
418         };
419         drop(handle_map_guard);
420         sched();
421     }
422 
423     pub fn shutdown_type(&self) -> ShutdownType {
424         *self.shutdown_type.read()
425     }
426 
427     pub fn shutdown_type_writer(&mut self) -> RwLockWriteGuard<ShutdownType> {
428         self.shutdown_type.write_irqsave()
429     }
430 
431     pub fn add_epoll(&mut self, epitem: Arc<EPollItem>) {
432         self.epitems.lock_irqsave().push_back(epitem)
433     }
434 
435     pub fn remove_epoll(&mut self, epoll: &Weak<SpinLock<EventPoll>>) -> Result<(), SystemError> {
436         let is_remove = !self
437             .epitems
438             .lock_irqsave()
439             .extract_if(|x| x.epoll().ptr_eq(epoll))
440             .collect::<Vec<_>>()
441             .is_empty();
442 
443         if is_remove {
444             return Ok(());
445         }
446 
447         Err(SystemError::ENOENT)
448     }
449 }
450 
451 /// # TCP 和 UDP 的端口管理器。
452 /// 如果 TCP/UDP 的 socket 绑定了某个端口,它会在对应的表中记录,以检测端口冲突。
453 pub struct PortManager {
454     // TCP 端口记录表
455     tcp_port_table: SpinLock<HashMap<u16, Arc<GlobalSocketHandle>>>,
456     // UDP 端口记录表
457     udp_port_table: SpinLock<HashMap<u16, Arc<GlobalSocketHandle>>>,
458 }
459 
460 impl PortManager {
461     pub fn new() -> Self {
462         return Self {
463             tcp_port_table: SpinLock::new(HashMap::new()),
464             udp_port_table: SpinLock::new(HashMap::new()),
465         };
466     }
467 
468     /// @brief 自动分配一个相对应协议中未被使用的PORT,如果动态端口均已被占用,返回错误码 EADDRINUSE
469     pub fn get_ephemeral_port(&self, socket_type: SocketType) -> Result<u16, SystemError> {
470         // TODO: selects non-conflict high port
471 
472         static mut EPHEMERAL_PORT: u16 = 0;
473         unsafe {
474             if EPHEMERAL_PORT == 0 {
475                 EPHEMERAL_PORT = (49152 + rand() % (65536 - 49152)) as u16;
476             }
477         }
478 
479         let mut remaining = 65536 - 49152; // 剩余尝试分配端口次数
480         let mut port: u16;
481         while remaining > 0 {
482             unsafe {
483                 if EPHEMERAL_PORT == 65535 {
484                     EPHEMERAL_PORT = 49152;
485                 } else {
486                     EPHEMERAL_PORT += 1;
487                 }
488                 port = EPHEMERAL_PORT;
489             }
490 
491             // 使用 ListenTable 检查端口是否被占用
492             let listen_table_guard = match socket_type {
493                 SocketType::Udp => self.udp_port_table.lock(),
494                 SocketType::Tcp => self.tcp_port_table.lock(),
495                 _ => panic!("{:?} cann't get a port", socket_type),
496             };
497             if listen_table_guard.get(&port).is_none() {
498                 drop(listen_table_guard);
499                 return Ok(port);
500             }
501             remaining -= 1;
502         }
503         return Err(SystemError::EADDRINUSE);
504     }
505 
506     /// @brief 检测给定端口是否已被占用,如果未被占用则在 TCP/UDP 对应的表中记录
507     ///
508     /// TODO: 增加支持端口复用的逻辑
509     pub fn bind_port(
510         &self,
511         socket_type: SocketType,
512         port: u16,
513         handle: Arc<GlobalSocketHandle>,
514     ) -> Result<(), SystemError> {
515         if port > 0 {
516             let mut listen_table_guard = match socket_type {
517                 SocketType::Udp => self.udp_port_table.lock(),
518                 SocketType::Tcp => self.tcp_port_table.lock(),
519                 _ => panic!("{:?} cann't bind a port", socket_type),
520             };
521             match listen_table_guard.get(&port) {
522                 Some(_) => return Err(SystemError::EADDRINUSE),
523                 None => listen_table_guard.insert(port, handle),
524             };
525             drop(listen_table_guard);
526         }
527         return Ok(());
528     }
529 
530     /// @brief 在对应的端口记录表中将端口和 socket 解绑
531     pub fn unbind_port(&self, socket_type: SocketType, port: u16) -> Result<(), SystemError> {
532         let mut listen_table_guard = match socket_type {
533             SocketType::Udp => self.udp_port_table.lock(),
534             SocketType::Tcp => self.tcp_port_table.lock(),
535             _ => return Ok(()),
536         };
537         listen_table_guard.remove(&port);
538         drop(listen_table_guard);
539         return Ok(());
540     }
541 }
542 
543 /// # socket的句柄管理组件
544 /// 它在smoltcp的SocketHandle上封装了一层,增加更多的功能。
545 /// 比如,在socket被关闭时,自动释放socket的资源,通知系统的其他组件。
546 #[derive(Debug)]
547 pub struct GlobalSocketHandle(SocketHandle);
548 
549 impl GlobalSocketHandle {
550     pub fn new(handle: SocketHandle) -> Arc<Self> {
551         return Arc::new(Self(handle));
552     }
553 }
554 
555 impl Clone for GlobalSocketHandle {
556     fn clone(&self) -> Self {
557         Self(self.0)
558     }
559 }
560 
561 impl Drop for GlobalSocketHandle {
562     fn drop(&mut self) {
563         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
564         socket_set_guard.remove(self.0); // 删除的时候,会发送一条FINISH的信息?
565         drop(socket_set_guard);
566         poll_ifaces();
567     }
568 }
569 
570 /// @brief socket的类型
571 #[derive(Debug, Clone, Copy, PartialEq)]
572 pub enum SocketType {
573     /// 原始的socket
574     Raw,
575     /// 用于Tcp通信的 Socket
576     Tcp,
577     /// 用于Udp通信的 Socket
578     Udp,
579     /// unix域的 Socket
580     Unix,
581 }
582 
583 bitflags! {
584     /// @brief socket的选项
585     #[derive(Default)]
586     pub struct SocketOptions: u32 {
587         /// 是否阻塞
588         const BLOCK = 1 << 0;
589         /// 是否允许广播
590         const BROADCAST = 1 << 1;
591         /// 是否允许多播
592         const MULTICAST = 1 << 2;
593         /// 是否允许重用地址
594         const REUSEADDR = 1 << 3;
595         /// 是否允许重用端口
596         const REUSEPORT = 1 << 4;
597     }
598 }
599 
600 #[derive(Debug, Clone)]
601 /// @brief 在trait Socket的metadata函数中返回该结构体供外部使用
602 pub struct SocketMetadata {
603     /// socket的类型
604     pub socket_type: SocketType,
605     /// 接收缓冲区的大小
606     pub rx_buf_size: usize,
607     /// 发送缓冲区的大小
608     pub tx_buf_size: usize,
609     /// 元数据的缓冲区的大小
610     pub metadata_buf_size: usize,
611     /// socket的选项
612     pub options: SocketOptions,
613 }
614 
615 impl SocketMetadata {
616     fn new(
617         socket_type: SocketType,
618         rx_buf_size: usize,
619         tx_buf_size: usize,
620         metadata_buf_size: usize,
621         options: SocketOptions,
622     ) -> Self {
623         Self {
624             socket_type,
625             rx_buf_size,
626             tx_buf_size,
627             metadata_buf_size,
628             options,
629         }
630     }
631 }
632 
633 /// @brief 地址族的枚举
634 ///
635 /// 参考:https://code.dragonos.org.cn/xref/linux-5.19.10/include/linux/socket.h#180
636 #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
637 pub enum AddressFamily {
638     /// AF_UNSPEC 表示地址族未指定
639     Unspecified = 0,
640     /// AF_UNIX 表示Unix域的socket (与AF_LOCAL相同)
641     Unix = 1,
642     ///  AF_INET 表示IPv4的socket
643     INet = 2,
644     /// AF_AX25 表示AMPR AX.25的socket
645     AX25 = 3,
646     /// AF_IPX 表示IPX的socket
647     IPX = 4,
648     /// AF_APPLETALK 表示Appletalk的socket
649     Appletalk = 5,
650     /// AF_NETROM 表示AMPR NET/ROM的socket
651     Netrom = 6,
652     /// AF_BRIDGE 表示多协议桥接的socket
653     Bridge = 7,
654     /// AF_ATMPVC 表示ATM PVCs的socket
655     Atmpvc = 8,
656     /// AF_X25 表示X.25的socket
657     X25 = 9,
658     /// AF_INET6 表示IPv6的socket
659     INet6 = 10,
660     /// AF_ROSE 表示AMPR ROSE的socket
661     Rose = 11,
662     /// AF_DECnet Reserved for DECnet project
663     Decnet = 12,
664     /// AF_NETBEUI Reserved for 802.2LLC project
665     Netbeui = 13,
666     /// AF_SECURITY 表示Security callback的伪AF
667     Security = 14,
668     /// AF_KEY 表示Key management API
669     Key = 15,
670     /// AF_NETLINK 表示Netlink的socket
671     Netlink = 16,
672     /// AF_PACKET 表示Low level packet interface
673     Packet = 17,
674     /// AF_ASH 表示Ash
675     Ash = 18,
676     /// AF_ECONET 表示Acorn Econet
677     Econet = 19,
678     /// AF_ATMSVC 表示ATM SVCs
679     Atmsvc = 20,
680     /// AF_RDS 表示Reliable Datagram Sockets
681     Rds = 21,
682     /// AF_SNA 表示Linux SNA Project
683     Sna = 22,
684     /// AF_IRDA 表示IRDA sockets
685     Irda = 23,
686     /// AF_PPPOX 表示PPPoX sockets
687     Pppox = 24,
688     /// AF_WANPIPE 表示WANPIPE API sockets
689     WanPipe = 25,
690     /// AF_LLC 表示Linux LLC
691     Llc = 26,
692     /// AF_IB 表示Native InfiniBand address
693     /// 介绍:https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html-single/configuring_infiniband_and_rdma_networks/index#understanding-infiniband-and-rdma_configuring-infiniband-and-rdma-networks
694     Ib = 27,
695     /// AF_MPLS 表示MPLS
696     Mpls = 28,
697     /// AF_CAN 表示Controller Area Network
698     Can = 29,
699     /// AF_TIPC 表示TIPC sockets
700     Tipc = 30,
701     /// AF_BLUETOOTH 表示Bluetooth sockets
702     Bluetooth = 31,
703     /// AF_IUCV 表示IUCV sockets
704     Iucv = 32,
705     /// AF_RXRPC 表示RxRPC sockets
706     Rxrpc = 33,
707     /// AF_ISDN 表示mISDN sockets
708     Isdn = 34,
709     /// AF_PHONET 表示Phonet sockets
710     Phonet = 35,
711     /// AF_IEEE802154 表示IEEE 802.15.4 sockets
712     Ieee802154 = 36,
713     /// AF_CAIF 表示CAIF sockets
714     Caif = 37,
715     /// AF_ALG 表示Algorithm sockets
716     Alg = 38,
717     /// AF_NFC 表示NFC sockets
718     Nfc = 39,
719     /// AF_VSOCK 表示vSockets
720     Vsock = 40,
721     /// AF_KCM 表示Kernel Connection Multiplexor
722     Kcm = 41,
723     /// AF_QIPCRTR 表示Qualcomm IPC Router
724     Qipcrtr = 42,
725     /// AF_SMC 表示SMC-R sockets.
726     /// reserve number for PF_SMC protocol family that reuses AF_INET address family
727     Smc = 43,
728     /// AF_XDP 表示XDP sockets
729     Xdp = 44,
730     /// AF_MCTP 表示Management Component Transport Protocol
731     Mctp = 45,
732     /// AF_MAX 表示最大的地址族
733     Max = 46,
734 }
735 
736 impl TryFrom<u16> for AddressFamily {
737     type Error = SystemError;
738     fn try_from(x: u16) -> Result<Self, Self::Error> {
739         use num_traits::FromPrimitive;
740         return <Self as FromPrimitive>::from_u16(x).ok_or(SystemError::EINVAL);
741     }
742 }
743 
744 /// @brief posix套接字类型的枚举(这些值与linux内核中的值一致)
745 #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
746 pub enum PosixSocketType {
747     Stream = 1,
748     Datagram = 2,
749     Raw = 3,
750     Rdm = 4,
751     SeqPacket = 5,
752     Dccp = 6,
753     Packet = 10,
754 }
755 
756 impl TryFrom<u8> for PosixSocketType {
757     type Error = SystemError;
758     fn try_from(x: u8) -> Result<Self, Self::Error> {
759         use num_traits::FromPrimitive;
760         return <Self as FromPrimitive>::from_u8(x).ok_or(SystemError::EINVAL);
761     }
762 }
763 
764 /// ### 为socket提供无锁的poll方法
765 ///
766 /// 因为在网卡中断中,需要轮询socket的状态,如果使用socket文件或者其inode来poll
767 /// 在当前的设计,会必然死锁,所以引用这一个设计来解决,提供无��的poll
768 pub struct SocketPollMethod;
769 
770 impl SocketPollMethod {
771     pub fn poll(socket: &socket::Socket, shutdown: ShutdownType) -> EPollEventType {
772         match socket {
773             socket::Socket::Udp(udp) => Self::udp_poll(udp, shutdown),
774             socket::Socket::Tcp(tcp) => Self::tcp_poll(tcp, shutdown),
775             _ => todo!(),
776         }
777     }
778 
779     pub fn tcp_poll(socket: &tcp::Socket, shutdown: ShutdownType) -> EPollEventType {
780         let mut events = EPollEventType::empty();
781         if socket.is_listening() && socket.is_active() {
782             events.insert(EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM);
783             return events;
784         }
785 
786         // socket已经关闭
787         if !socket.is_open() {
788             events.insert(EPollEventType::EPOLLHUP)
789         }
790         if shutdown.contains(ShutdownType::RCV_SHUTDOWN) {
791             events.insert(
792                 EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM | EPollEventType::EPOLLRDHUP,
793             );
794         }
795 
796         let state = socket.state();
797         if state != tcp::State::SynSent && state != tcp::State::SynReceived {
798             // socket有可读数据
799             if socket.can_recv() {
800                 events.insert(EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM);
801             }
802 
803             if !(shutdown.contains(ShutdownType::SEND_SHUTDOWN)) {
804                 // 缓冲区可写
805                 if socket.send_queue() < socket.send_capacity() {
806                     events.insert(EPollEventType::EPOLLOUT | EPollEventType::EPOLLWRNORM);
807                 } else {
808                     // TODO:触发缓冲区已满的信号
809                     todo!("A signal that the buffer is full needs to be sent");
810                 }
811             } else {
812                 // 如果我们的socket关闭了SEND_SHUTDOWN,epoll事件就是EPOLLOUT
813                 events.insert(EPollEventType::EPOLLOUT | EPollEventType::EPOLLWRNORM);
814             }
815         } else if state == tcp::State::SynSent {
816             events.insert(EPollEventType::EPOLLOUT | EPollEventType::EPOLLWRNORM);
817         }
818 
819         // socket发生错误
820         if !socket.is_active() {
821             events.insert(EPollEventType::EPOLLERR);
822         }
823 
824         events
825     }
826 
827     pub fn udp_poll(socket: &udp::Socket, shutdown: ShutdownType) -> EPollEventType {
828         let mut event = EPollEventType::empty();
829 
830         if shutdown.contains(ShutdownType::RCV_SHUTDOWN) {
831             event.insert(
832                 EPollEventType::EPOLLRDHUP | EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM,
833             );
834         }
835         if shutdown.contains(ShutdownType::SHUTDOWN_MASK) {
836             event.insert(EPollEventType::EPOLLHUP);
837         }
838 
839         if socket.can_recv() {
840             event.insert(EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM);
841         }
842 
843         if socket.can_send() {
844             event.insert(
845                 EPollEventType::EPOLLOUT
846                     | EPollEventType::EPOLLWRNORM
847                     | EPollEventType::EPOLLWRBAND,
848             );
849         } else {
850             // TODO: 缓冲区空间不够,需要使用信号处理
851             todo!()
852         }
853 
854         return event;
855     }
856 }
857