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