xref: /DragonOS/kernel/src/net/socket/inet.rs (revision 881ff6f95e4addc373d815d66cb912bf721c20e6)
16046f775S裕依 use alloc::{boxed::Box, sync::Arc, vec::Vec};
26046f775S裕依 use smoltcp::{
3d623e902SGnoCiYeH     socket::{raw, tcp, udp, AnySocket},
46046f775S裕依     wire,
56046f775S裕依 };
66046f775S裕依 use system_error::SystemError;
76046f775S裕依 
86046f775S裕依 use crate::{
9c719ddc6SSaga1718     arch::rand::rand,
106046f775S裕依     driver::net::NetDriver,
116046f775S裕依     kerror, kwarn,
126046f775S裕依     libs::rwlock::RwLock,
136046f775S裕依     net::{
146046f775S裕依         event_poll::EPollEventType, net_core::poll_ifaces, Endpoint, Protocol, ShutdownType,
156046f775S裕依         NET_DRIVERS,
166046f775S裕依     },
176046f775S裕依 };
186046f775S裕依 
196046f775S裕依 use super::{
20d623e902SGnoCiYeH     handle::GlobalSocketHandle, Socket, SocketHandleItem, SocketMetadata, SocketOptions,
21d623e902SGnoCiYeH     SocketPollMethod, SocketType, HANDLE_MAP, PORT_MANAGER, SOCKET_SET,
226046f775S裕依 };
236046f775S裕依 
246046f775S裕依 /// @brief 表示原始的socket。原始套接字绕过传输层协议(如 TCP 或 UDP)并提供对网络层协议(如 IP)的直接访问。
256046f775S裕依 ///
266046f775S裕依 /// ref: https://man7.org/linux/man-pages/man7/raw.7.html
276046f775S裕依 #[derive(Debug, Clone)]
286046f775S裕依 pub struct RawSocket {
29d623e902SGnoCiYeH     handle: GlobalSocketHandle,
306046f775S裕依     /// 用户发送的数据包是否包含了IP头.
316046f775S裕依     /// 如果是true,用户发送的数据包,必须包含IP头。(即用户要自行设置IP头+数据)
326046f775S裕依     /// 如果是false,用户发送的数据包,不包含IP头。(即用户只要设置数据)
336046f775S裕依     header_included: bool,
346046f775S裕依     /// socket的metadata
356046f775S裕依     metadata: SocketMetadata,
366046f775S裕依 }
376046f775S裕依 
386046f775S裕依 impl RawSocket {
396046f775S裕依     /// 元数据的缓冲区的大小
406046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
416046f775S裕依     /// 默认的接收缓冲区的大小 receive
426046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 64 * 1024;
436046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
446046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 64 * 1024;
456046f775S裕依 
466046f775S裕依     /// @brief 创建一个原始的socket
476046f775S裕依     ///
486046f775S裕依     /// @param protocol 协议号
496046f775S裕依     /// @param options socket的选项
506046f775S裕依     ///
516046f775S裕依     /// @return 返回创建的原始的socket
526046f775S裕依     pub fn new(protocol: Protocol, options: SocketOptions) -> Self {
536046f775S裕依         let rx_buffer = raw::PacketBuffer::new(
546046f775S裕依             vec![raw::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
556046f775S裕依             vec![0; Self::DEFAULT_RX_BUF_SIZE],
566046f775S裕依         );
576046f775S裕依         let tx_buffer = raw::PacketBuffer::new(
586046f775S裕依             vec![raw::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
596046f775S裕依             vec![0; Self::DEFAULT_TX_BUF_SIZE],
606046f775S裕依         );
616046f775S裕依         let protocol: u8 = protocol.into();
626046f775S裕依         let socket = raw::Socket::new(
636046f775S裕依             wire::IpVersion::Ipv4,
646046f775S裕依             wire::IpProtocol::from(protocol),
656046f775S裕依             rx_buffer,
666046f775S裕依             tx_buffer,
676046f775S裕依         );
686046f775S裕依 
696046f775S裕依         // 把socket添加到socket集合中,并得到socket的句柄
70d623e902SGnoCiYeH         let handle = GlobalSocketHandle::new_smoltcp_handle(SOCKET_SET.lock_irqsave().add(socket));
716046f775S裕依 
726046f775S裕依         let metadata = SocketMetadata::new(
736046f775S裕依             SocketType::Raw,
746046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
756046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
766046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
776046f775S裕依             options,
786046f775S裕依         );
796046f775S裕依 
806046f775S裕依         return Self {
816046f775S裕依             handle,
826046f775S裕依             header_included: false,
836046f775S裕依             metadata,
846046f775S裕依         };
856046f775S裕依     }
866046f775S裕依 }
876046f775S裕依 
886046f775S裕依 impl Socket for RawSocket {
89d623e902SGnoCiYeH     fn close(&mut self) {
90d623e902SGnoCiYeH         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
91d623e902SGnoCiYeH         socket_set_guard.remove(self.handle.smoltcp_handle().unwrap()); // 删除的时候,会发送一条FINISH的信息?
92d623e902SGnoCiYeH         drop(socket_set_guard);
93d623e902SGnoCiYeH         poll_ifaces();
94d623e902SGnoCiYeH     }
95d623e902SGnoCiYeH 
966046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
976046f775S裕依         poll_ifaces();
986046f775S裕依         loop {
996046f775S裕依             // 如何优化这里?
1006046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
101d623e902SGnoCiYeH             let socket =
102d623e902SGnoCiYeH                 socket_set_guard.get_mut::<raw::Socket>(self.handle.smoltcp_handle().unwrap());
1036046f775S裕依 
1046046f775S裕依             match socket.recv_slice(buf) {
1056046f775S裕依                 Ok(len) => {
1066046f775S裕依                     let packet = wire::Ipv4Packet::new_unchecked(buf);
1076046f775S裕依                     return (
1086046f775S裕依                         Ok(len),
1096046f775S裕依                         Endpoint::Ip(Some(wire::IpEndpoint {
1106046f775S裕依                             addr: wire::IpAddress::Ipv4(packet.src_addr()),
1116046f775S裕依                             port: 0,
1126046f775S裕依                         })),
1136046f775S裕依                     );
1146046f775S裕依                 }
115*881ff6f9Syuyi2439                 Err(_) => {
1166046f775S裕依                     if !self.metadata.options.contains(SocketOptions::BLOCK) {
1176046f775S裕依                         // 如果是非阻塞的socket,就返回错误
1186046f775S裕依                         return (Err(SystemError::EAGAIN_OR_EWOULDBLOCK), Endpoint::Ip(None));
1196046f775S裕依                     }
1206046f775S裕依                 }
1216046f775S裕依             }
1226046f775S裕依             drop(socket_set_guard);
1236046f775S裕依             SocketHandleItem::sleep(
1246046f775S裕依                 self.socket_handle(),
1256046f775S裕依                 EPollEventType::EPOLLIN.bits() as u64,
1266046f775S裕依                 HANDLE_MAP.read_irqsave(),
1276046f775S裕依             );
1286046f775S裕依         }
1296046f775S裕依     }
1306046f775S裕依 
1316046f775S裕依     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError> {
1326046f775S裕依         // 如果用户发送的数据包,包含IP头,则直接发送
1336046f775S裕依         if self.header_included {
1346046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
135d623e902SGnoCiYeH             let socket =
136d623e902SGnoCiYeH                 socket_set_guard.get_mut::<raw::Socket>(self.handle.smoltcp_handle().unwrap());
1376046f775S裕依             match socket.send_slice(buf) {
1386046f775S裕依                 Ok(_) => {
1396046f775S裕依                     return Ok(buf.len());
1406046f775S裕依                 }
1416046f775S裕依                 Err(raw::SendError::BufferFull) => {
1426046f775S裕依                     return Err(SystemError::ENOBUFS);
1436046f775S裕依                 }
1446046f775S裕依             }
1456046f775S裕依         } else {
1466046f775S裕依             // 如果用户发送的数据包,不包含IP头,则需要自己构造IP头
1476046f775S裕依 
1486046f775S裕依             if let Some(Endpoint::Ip(Some(endpoint))) = to {
1496046f775S裕依                 let mut socket_set_guard = SOCKET_SET.lock_irqsave();
1506046f775S裕依                 let socket: &mut raw::Socket =
151d623e902SGnoCiYeH                     socket_set_guard.get_mut::<raw::Socket>(self.handle.smoltcp_handle().unwrap());
1526046f775S裕依 
1536046f775S裕依                 // 暴力解决方案:只考虑0号网卡。 TODO:考虑多网卡的情况!!!
1546046f775S裕依                 let iface = NET_DRIVERS.read_irqsave().get(&0).unwrap().clone();
1556046f775S裕依 
1566046f775S裕依                 // 构造IP头
1576046f775S裕依                 let ipv4_src_addr: Option<wire::Ipv4Address> =
1586046f775S裕依                     iface.inner_iface().lock().ipv4_addr();
1596046f775S裕依                 if ipv4_src_addr.is_none() {
1606046f775S裕依                     return Err(SystemError::ENETUNREACH);
1616046f775S裕依                 }
1626046f775S裕依                 let ipv4_src_addr = ipv4_src_addr.unwrap();
1636046f775S裕依 
1646046f775S裕依                 if let wire::IpAddress::Ipv4(ipv4_dst) = endpoint.addr {
1656046f775S裕依                     let len = buf.len();
1666046f775S裕依 
1676046f775S裕依                     // 创建20字节的IPv4头部
1686046f775S裕依                     let mut buffer: Vec<u8> = vec![0u8; len + 20];
1696046f775S裕依                     let mut packet: wire::Ipv4Packet<&mut Vec<u8>> =
1706046f775S裕依                         wire::Ipv4Packet::new_unchecked(&mut buffer);
1716046f775S裕依 
1726046f775S裕依                     // 封装ipv4 header
1736046f775S裕依                     packet.set_version(4);
1746046f775S裕依                     packet.set_header_len(20);
1756046f775S裕依                     packet.set_total_len((20 + len) as u16);
1766046f775S裕依                     packet.set_src_addr(ipv4_src_addr);
1776046f775S裕依                     packet.set_dst_addr(ipv4_dst);
1786046f775S裕依 
1796046f775S裕依                     // 设置ipv4 header的protocol字段
1806046f775S裕依                     packet.set_next_header(socket.ip_protocol());
1816046f775S裕依 
1826046f775S裕依                     // 获取IP数据包的负载字段
1836046f775S裕依                     let payload: &mut [u8] = packet.payload_mut();
1846046f775S裕依                     payload.copy_from_slice(buf);
1856046f775S裕依 
1866046f775S裕依                     // 填充checksum字段
1876046f775S裕依                     packet.fill_checksum();
1886046f775S裕依 
1896046f775S裕依                     // 发送数据包
1906046f775S裕依                     socket.send_slice(&buffer).unwrap();
1916046f775S裕依 
1926046f775S裕依                     iface.poll(&mut socket_set_guard).ok();
1936046f775S裕依 
1946046f775S裕依                     drop(socket_set_guard);
1956046f775S裕依                     return Ok(len);
1966046f775S裕依                 } else {
1976046f775S裕依                     kwarn!("Unsupport Ip protocol type!");
1986046f775S裕依                     return Err(SystemError::EINVAL);
1996046f775S裕依                 }
2006046f775S裕依             } else {
2016046f775S裕依                 // 如果没有指定目的地址,则返回错误
2026046f775S裕依                 return Err(SystemError::ENOTCONN);
2036046f775S裕依             }
2046046f775S裕依         }
2056046f775S裕依     }
2066046f775S裕依 
2076046f775S裕依     fn connect(&mut self, _endpoint: Endpoint) -> Result<(), SystemError> {
2086046f775S裕依         Ok(())
2096046f775S裕依     }
2106046f775S裕依 
2116046f775S裕依     fn metadata(&self) -> SocketMetadata {
2126046f775S裕依         self.metadata.clone()
2136046f775S裕依     }
2146046f775S裕依 
2156046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
2166046f775S裕依         Box::new(self.clone())
2176046f775S裕依     }
2186046f775S裕依 
219d623e902SGnoCiYeH     fn socket_handle(&self) -> GlobalSocketHandle {
220d623e902SGnoCiYeH         self.handle
2216046f775S裕依     }
2226046f775S裕依 
2236046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
2246046f775S裕依         self
2256046f775S裕依     }
2266046f775S裕依 
2276046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
2286046f775S裕依         self
2296046f775S裕依     }
2306046f775S裕依 }
2316046f775S裕依 
2326046f775S裕依 /// @brief 表示udp socket
2336046f775S裕依 ///
2346046f775S裕依 /// https://man7.org/linux/man-pages/man7/udp.7.html
2356046f775S裕依 #[derive(Debug, Clone)]
2366046f775S裕依 pub struct UdpSocket {
237d623e902SGnoCiYeH     pub handle: GlobalSocketHandle,
2386046f775S裕依     remote_endpoint: Option<Endpoint>, // 记录远程endpoint提供给connect(), 应该使用IP地址。
2396046f775S裕依     metadata: SocketMetadata,
2406046f775S裕依 }
2416046f775S裕依 
2426046f775S裕依 impl UdpSocket {
2436046f775S裕依     /// 元数据的缓冲区的大小
2446046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
2456046f775S裕依     /// 默认的接收缓冲区的大小 receive
2466046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 64 * 1024;
2476046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
2486046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 64 * 1024;
2496046f775S裕依 
2506046f775S裕依     /// @brief 创建一个udp的socket
2516046f775S裕依     ///
2526046f775S裕依     /// @param options socket的选项
2536046f775S裕依     ///
2546046f775S裕依     /// @return 返回创建的udp的socket
2556046f775S裕依     pub fn new(options: SocketOptions) -> Self {
2566046f775S裕依         let rx_buffer = udp::PacketBuffer::new(
2576046f775S裕依             vec![udp::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
2586046f775S裕依             vec![0; Self::DEFAULT_RX_BUF_SIZE],
2596046f775S裕依         );
2606046f775S裕依         let tx_buffer = udp::PacketBuffer::new(
2616046f775S裕依             vec![udp::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
2626046f775S裕依             vec![0; Self::DEFAULT_TX_BUF_SIZE],
2636046f775S裕依         );
2646046f775S裕依         let socket = udp::Socket::new(rx_buffer, tx_buffer);
2656046f775S裕依 
2666046f775S裕依         // 把socket添加到socket集合中,并得到socket的句柄
267d623e902SGnoCiYeH         let handle: GlobalSocketHandle =
268d623e902SGnoCiYeH             GlobalSocketHandle::new_smoltcp_handle(SOCKET_SET.lock_irqsave().add(socket));
2696046f775S裕依 
2706046f775S裕依         let metadata = SocketMetadata::new(
2716046f775S裕依             SocketType::Udp,
2726046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
2736046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
2746046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
2756046f775S裕依             options,
2766046f775S裕依         );
2776046f775S裕依 
2786046f775S裕依         return Self {
2796046f775S裕依             handle,
2806046f775S裕依             remote_endpoint: None,
2816046f775S裕依             metadata,
2826046f775S裕依         };
2836046f775S裕依     }
2846046f775S裕依 
2856046f775S裕依     fn do_bind(&self, socket: &mut udp::Socket, endpoint: Endpoint) -> Result<(), SystemError> {
2869d9a0984Ssun5etop         if let Endpoint::Ip(Some(mut ip)) = endpoint {
2879d9a0984Ssun5etop             // 端口为0则分配随机端口
2889d9a0984Ssun5etop             if ip.port == 0 {
2899d9a0984Ssun5etop                 ip.port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
2909d9a0984Ssun5etop             }
2916046f775S裕依             // 检测端口是否已被占用
292c719ddc6SSaga1718             PORT_MANAGER.bind_port(self.metadata.socket_type, ip.port, self.clone())?;
2936046f775S裕依 
2946046f775S裕依             let bind_res = if ip.addr.is_unspecified() {
2956046f775S裕依                 socket.bind(ip.port)
2966046f775S裕依             } else {
2976046f775S裕依                 socket.bind(ip)
2986046f775S裕依             };
2996046f775S裕依 
3006046f775S裕依             match bind_res {
3016046f775S裕依                 Ok(()) => return Ok(()),
3026046f775S裕依                 Err(_) => return Err(SystemError::EINVAL),
3036046f775S裕依             }
3046046f775S裕依         } else {
3056046f775S裕依             return Err(SystemError::EINVAL);
3066046f775S裕依         }
3076046f775S裕依     }
3086046f775S裕依 }
3096046f775S裕依 
3106046f775S裕依 impl Socket for UdpSocket {
311d623e902SGnoCiYeH     fn close(&mut self) {
312d623e902SGnoCiYeH         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
313d623e902SGnoCiYeH         socket_set_guard.remove(self.handle.smoltcp_handle().unwrap()); // 删除的时候,会发送一条FINISH的信息?
314d623e902SGnoCiYeH         drop(socket_set_guard);
315d623e902SGnoCiYeH         poll_ifaces();
316d623e902SGnoCiYeH     }
317d623e902SGnoCiYeH 
3186046f775S裕依     /// @brief 在read函数执行之前,请先bind到本地的指定端口
3196046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
3206046f775S裕依         loop {
3216046f775S裕依             // kdebug!("Wait22 to Read");
3226046f775S裕依             poll_ifaces();
3236046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
324d623e902SGnoCiYeH             let socket =
325d623e902SGnoCiYeH                 socket_set_guard.get_mut::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
3266046f775S裕依 
3276046f775S裕依             // kdebug!("Wait to Read");
3286046f775S裕依 
3296046f775S裕依             if socket.can_recv() {
330*881ff6f9Syuyi2439                 if let Ok((size, metadata)) = socket.recv_slice(buf) {
3316046f775S裕依                     drop(socket_set_guard);
3326046f775S裕依                     poll_ifaces();
333*881ff6f9Syuyi2439                     return (Ok(size), Endpoint::Ip(Some(metadata.endpoint)));
3346046f775S裕依                 }
3356046f775S裕依             } else {
3366046f775S裕依                 // 如果socket没有连接,则忙等
3376046f775S裕依                 // return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
3386046f775S裕依             }
3396046f775S裕依             drop(socket_set_guard);
3406046f775S裕依             SocketHandleItem::sleep(
3416046f775S裕依                 self.socket_handle(),
3426046f775S裕依                 EPollEventType::EPOLLIN.bits() as u64,
3436046f775S裕依                 HANDLE_MAP.read_irqsave(),
3446046f775S裕依             );
3456046f775S裕依         }
3466046f775S裕依     }
3476046f775S裕依 
3486046f775S裕依     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError> {
3496046f775S裕依         // kdebug!("udp to send: {:?}, len={}", to, buf.len());
3506046f775S裕依         let remote_endpoint: &wire::IpEndpoint = {
3516046f775S裕依             if let Some(Endpoint::Ip(Some(ref endpoint))) = to {
3526046f775S裕依                 endpoint
3536046f775S裕依             } else if let Some(Endpoint::Ip(Some(ref endpoint))) = self.remote_endpoint {
3546046f775S裕依                 endpoint
3556046f775S裕依             } else {
3566046f775S裕依                 return Err(SystemError::ENOTCONN);
3576046f775S裕依             }
3586046f775S裕依         };
3596046f775S裕依         // kdebug!("udp write: remote = {:?}", remote_endpoint);
3606046f775S裕依 
3616046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
362d623e902SGnoCiYeH         let socket = socket_set_guard.get_mut::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
3636046f775S裕依         // kdebug!("is open()={}", socket.is_open());
3646046f775S裕依         // kdebug!("socket endpoint={:?}", socket.endpoint());
3656046f775S裕依         if socket.can_send() {
3666046f775S裕依             // kdebug!("udp write: can send");
3676046f775S裕依             match socket.send_slice(buf, *remote_endpoint) {
3686046f775S裕依                 Ok(()) => {
3696046f775S裕依                     // kdebug!("udp write: send ok");
3706046f775S裕依                     drop(socket_set_guard);
3716046f775S裕依                     poll_ifaces();
3726046f775S裕依                     return Ok(buf.len());
3736046f775S裕依                 }
3746046f775S裕依                 Err(_) => {
3756046f775S裕依                     // kdebug!("udp write: send err");
3766046f775S裕依                     return Err(SystemError::ENOBUFS);
3776046f775S裕依                 }
3786046f775S裕依             }
3796046f775S裕依         } else {
3806046f775S裕依             // kdebug!("udp write: can not send");
3816046f775S裕依             return Err(SystemError::ENOBUFS);
3826046f775S裕依         };
3836046f775S裕依     }
3846046f775S裕依 
3856046f775S裕依     fn bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
3866046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
387d623e902SGnoCiYeH         let socket = sockets.get_mut::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
3886046f775S裕依         // kdebug!("UDP Bind to {:?}", endpoint);
3896046f775S裕依         return self.do_bind(socket, endpoint);
3906046f775S裕依     }
3916046f775S裕依 
3926046f775S裕依     fn poll(&self) -> EPollEventType {
3936046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
394d623e902SGnoCiYeH         let socket = sockets.get::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
3956046f775S裕依 
3966046f775S裕依         return SocketPollMethod::udp_poll(
3976046f775S裕依             socket,
3986046f775S裕依             HANDLE_MAP
3996046f775S裕依                 .read_irqsave()
4006046f775S裕依                 .get(&self.socket_handle())
4016046f775S裕依                 .unwrap()
4026046f775S裕依                 .shutdown_type(),
4036046f775S裕依         );
4046046f775S裕依     }
4056046f775S裕依 
4066046f775S裕依     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
4076046f775S裕依         if let Endpoint::Ip(_) = endpoint {
4086046f775S裕依             self.remote_endpoint = Some(endpoint);
4096046f775S裕依             Ok(())
4106046f775S裕依         } else {
4116046f775S裕依             Err(SystemError::EINVAL)
4126046f775S裕依         }
4136046f775S裕依     }
4146046f775S裕依 
4156046f775S裕依     fn ioctl(
4166046f775S裕依         &self,
4176046f775S裕依         _cmd: usize,
4186046f775S裕依         _arg0: usize,
4196046f775S裕依         _arg1: usize,
4206046f775S裕依         _arg2: usize,
4216046f775S裕依     ) -> Result<usize, SystemError> {
4226046f775S裕依         todo!()
4236046f775S裕依     }
4246046f775S裕依 
4256046f775S裕依     fn metadata(&self) -> SocketMetadata {
4266046f775S裕依         self.metadata.clone()
4276046f775S裕依     }
4286046f775S裕依 
4296046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
4306046f775S裕依         return Box::new(self.clone());
4316046f775S裕依     }
4326046f775S裕依 
4336046f775S裕依     fn endpoint(&self) -> Option<Endpoint> {
4346046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
435d623e902SGnoCiYeH         let socket = sockets.get::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
4366046f775S裕依         let listen_endpoint = socket.endpoint();
4376046f775S裕依 
4386046f775S裕依         if listen_endpoint.port == 0 {
4396046f775S裕依             return None;
4406046f775S裕依         } else {
4416046f775S裕依             // 如果listen_endpoint的address是None,意味着“监听所有的地址”。
4426046f775S裕依             // 这里假设所有的地址都是ipv4
4436046f775S裕依             // TODO: 支持ipv6
4446046f775S裕依             let result = wire::IpEndpoint::new(
4456046f775S裕依                 listen_endpoint
4466046f775S裕依                     .addr
4476046f775S裕依                     .unwrap_or(wire::IpAddress::v4(0, 0, 0, 0)),
4486046f775S裕依                 listen_endpoint.port,
4496046f775S裕依             );
4506046f775S裕依             return Some(Endpoint::Ip(Some(result)));
4516046f775S裕依         }
4526046f775S裕依     }
4536046f775S裕依 
4546046f775S裕依     fn peer_endpoint(&self) -> Option<Endpoint> {
4556046f775S裕依         return self.remote_endpoint.clone();
4566046f775S裕依     }
4576046f775S裕依 
458d623e902SGnoCiYeH     fn socket_handle(&self) -> GlobalSocketHandle {
459d623e902SGnoCiYeH         self.handle
4606046f775S裕依     }
4616046f775S裕依 
4626046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
4636046f775S裕依         self
4646046f775S裕依     }
4656046f775S裕依 
4666046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
4676046f775S裕依         self
4686046f775S裕依     }
4696046f775S裕依 }
4706046f775S裕依 
4716046f775S裕依 /// @brief 表示 tcp socket
4726046f775S裕依 ///
4736046f775S裕依 /// https://man7.org/linux/man-pages/man7/tcp.7.html
4746046f775S裕依 #[derive(Debug, Clone)]
4756046f775S裕依 pub struct TcpSocket {
476d623e902SGnoCiYeH     handles: Vec<GlobalSocketHandle>,
4776046f775S裕依     local_endpoint: Option<wire::IpEndpoint>, // save local endpoint for bind()
4786046f775S裕依     is_listening: bool,
4796046f775S裕依     metadata: SocketMetadata,
4806046f775S裕依 }
4816046f775S裕依 
4826046f775S裕依 impl TcpSocket {
4836046f775S裕依     /// 元数据的缓冲区的大小
4846046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
4856046f775S裕依     /// 默认的接收缓冲区的大小 receive
4866046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 512 * 1024;
4876046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
4886046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 512 * 1024;
4896046f775S裕依 
4906046f775S裕依     /// TcpSocket的特殊事件,用于在事件等待队列上sleep
4916046f775S裕依     pub const CAN_CONNECT: u64 = 1u64 << 63;
4926046f775S裕依     pub const CAN_ACCPET: u64 = 1u64 << 62;
4936046f775S裕依 
4946046f775S裕依     /// @brief 创建一个tcp的socket
4956046f775S裕依     ///
4966046f775S裕依     /// @param options socket的选项
4976046f775S裕依     ///
4986046f775S裕依     /// @return 返回创建的tcp的socket
4996046f775S裕依     pub fn new(options: SocketOptions) -> Self {
500c719ddc6SSaga1718         // 创建handles数组并把socket添加到socket集合中,并得到socket的句柄
501d623e902SGnoCiYeH         let handles: Vec<GlobalSocketHandle> = vec![GlobalSocketHandle::new_smoltcp_handle(
502c719ddc6SSaga1718             SOCKET_SET.lock_irqsave().add(Self::create_new_socket()),
503c719ddc6SSaga1718         )];
5046046f775S裕依 
5056046f775S裕依         let metadata = SocketMetadata::new(
5066046f775S裕依             SocketType::Tcp,
5076046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
5086046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
5096046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
5106046f775S裕依             options,
5116046f775S裕依         );
512c719ddc6SSaga1718         // kdebug!("when there's a new tcp socket,its'len: {}",handles.len());
5136046f775S裕依 
5146046f775S裕依         return Self {
515c719ddc6SSaga1718             handles,
5166046f775S裕依             local_endpoint: None,
5176046f775S裕依             is_listening: false,
5186046f775S裕依             metadata,
5196046f775S裕依         };
5206046f775S裕依     }
5216046f775S裕依 
5226046f775S裕依     fn do_listen(
5236046f775S裕依         &mut self,
5246046f775S裕依         socket: &mut tcp::Socket,
5256046f775S裕依         local_endpoint: wire::IpEndpoint,
5266046f775S裕依     ) -> Result<(), SystemError> {
5276046f775S裕依         let listen_result = if local_endpoint.addr.is_unspecified() {
5286046f775S裕依             // kdebug!("Tcp Socket Listen on port {}", local_endpoint.port);
5296046f775S裕依             socket.listen(local_endpoint.port)
5306046f775S裕依         } else {
5316046f775S裕依             // kdebug!("Tcp Socket Listen on {local_endpoint}");
5326046f775S裕依             socket.listen(local_endpoint)
5336046f775S裕依         };
5346046f775S裕依         return match listen_result {
5356046f775S裕依             Ok(()) => {
5366046f775S裕依                 // kdebug!(
5376046f775S裕依                 //     "Tcp Socket Listen on {local_endpoint}, open?:{}",
5386046f775S裕依                 //     socket.is_open()
5396046f775S裕依                 // );
5406046f775S裕依                 self.is_listening = true;
5416046f775S裕依 
5426046f775S裕依                 Ok(())
5436046f775S裕依             }
5446046f775S裕依             Err(_) => Err(SystemError::EINVAL),
5456046f775S裕依         };
5466046f775S裕依     }
547c719ddc6SSaga1718 
548c719ddc6SSaga1718     /// # create_new_socket - 创建新的TCP套接字
549c719ddc6SSaga1718     ///
550c719ddc6SSaga1718     /// 该函数用于创建一个新的TCP套接字,并返回该套接字的引用。
551c719ddc6SSaga1718     fn create_new_socket() -> tcp::Socket<'static> {
552c719ddc6SSaga1718         // 初始化tcp的buffer
553c719ddc6SSaga1718         let rx_buffer = tcp::SocketBuffer::new(vec![0; Self::DEFAULT_RX_BUF_SIZE]);
554c719ddc6SSaga1718         let tx_buffer = tcp::SocketBuffer::new(vec![0; Self::DEFAULT_TX_BUF_SIZE]);
555c719ddc6SSaga1718         tcp::Socket::new(rx_buffer, tx_buffer)
556c719ddc6SSaga1718     }
5576046f775S裕依 }
5586046f775S裕依 
5596046f775S裕依 impl Socket for TcpSocket {
560d623e902SGnoCiYeH     fn close(&mut self) {
561d623e902SGnoCiYeH         for handle in self.handles.iter() {
562d623e902SGnoCiYeH             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
563d623e902SGnoCiYeH             socket_set_guard.remove(handle.smoltcp_handle().unwrap()); // 删除的时候,会发送一条FINISH的信息?
564d623e902SGnoCiYeH             drop(socket_set_guard);
565d623e902SGnoCiYeH         }
566d623e902SGnoCiYeH         poll_ifaces();
567d623e902SGnoCiYeH     }
568d623e902SGnoCiYeH 
5696046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
5706046f775S裕依         if HANDLE_MAP
5716046f775S裕依             .read_irqsave()
5726046f775S裕依             .get(&self.socket_handle())
5736046f775S裕依             .unwrap()
5746046f775S裕依             .shutdown_type()
5756046f775S裕依             .contains(ShutdownType::RCV_SHUTDOWN)
5766046f775S裕依         {
5776046f775S裕依             return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
5786046f775S裕依         }
5796046f775S裕依         // kdebug!("tcp socket: read, buf len={}", buf.len());
580c719ddc6SSaga1718         // kdebug!("tcp socket:read, socket'len={}",self.handle.len());
5816046f775S裕依         loop {
5826046f775S裕依             poll_ifaces();
5836046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
584c719ddc6SSaga1718 
585d623e902SGnoCiYeH             let socket = socket_set_guard
586d623e902SGnoCiYeH                 .get_mut::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
5876046f775S裕依 
5886046f775S裕依             // 如果socket已经关闭,返回错误
5896046f775S裕依             if !socket.is_active() {
5906046f775S裕依                 // kdebug!("Tcp Socket Read Error, socket is closed");
5916046f775S裕依                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
5926046f775S裕依             }
5936046f775S裕依 
5946046f775S裕依             if socket.may_recv() {
595*881ff6f9Syuyi2439                 match socket.recv_slice(buf) {
596*881ff6f9Syuyi2439                     Ok(size) => {
5976046f775S裕依                         if size > 0 {
5986046f775S裕依                             let endpoint = if let Some(p) = socket.remote_endpoint() {
5996046f775S裕依                                 p
6006046f775S裕依                             } else {
6016046f775S裕依                                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6026046f775S裕依                             };
6036046f775S裕依 
6046046f775S裕依                             drop(socket_set_guard);
6056046f775S裕依                             poll_ifaces();
6066046f775S裕依                             return (Ok(size), Endpoint::Ip(Some(endpoint)));
6076046f775S裕依                         }
608*881ff6f9Syuyi2439                     }
609*881ff6f9Syuyi2439                     Err(tcp::RecvError::InvalidState) => {
6106046f775S裕依                         kwarn!("Tcp Socket Read Error, InvalidState");
6116046f775S裕依                         return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6126046f775S裕依                     }
613*881ff6f9Syuyi2439                     Err(tcp::RecvError::Finished) => {
6146046f775S裕依                         // 对端写端已关闭,我们应该关闭读端
6156046f775S裕依                         HANDLE_MAP
6166046f775S裕依                             .write_irqsave()
6176046f775S裕依                             .get_mut(&self.socket_handle())
6186046f775S裕依                             .unwrap()
6196046f775S裕依                             .shutdown_type_writer()
6206046f775S裕依                             .insert(ShutdownType::RCV_SHUTDOWN);
6216046f775S裕依                         return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6226046f775S裕依                     }
6236046f775S裕依                 }
6246046f775S裕依             } else {
6256046f775S裕依                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6266046f775S裕依             }
6276046f775S裕依             drop(socket_set_guard);
6286046f775S裕依             SocketHandleItem::sleep(
6296046f775S裕依                 self.socket_handle(),
6306046f775S裕依                 EPollEventType::EPOLLIN.bits() as u64,
6316046f775S裕依                 HANDLE_MAP.read_irqsave(),
6326046f775S裕依             );
6336046f775S裕依         }
6346046f775S裕依     }
6356046f775S裕依 
6366046f775S裕依     fn write(&self, buf: &[u8], _to: Option<Endpoint>) -> Result<usize, SystemError> {
6376046f775S裕依         if HANDLE_MAP
6386046f775S裕依             .read_irqsave()
6396046f775S裕依             .get(&self.socket_handle())
6406046f775S裕依             .unwrap()
6416046f775S裕依             .shutdown_type()
6426046f775S裕依             .contains(ShutdownType::RCV_SHUTDOWN)
6436046f775S裕依         {
6446046f775S裕依             return Err(SystemError::ENOTCONN);
6456046f775S裕依         }
646c719ddc6SSaga1718         // kdebug!("tcp socket:write, socket'len={}",self.handle.len());
647c719ddc6SSaga1718 
6486046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
649c719ddc6SSaga1718 
650d623e902SGnoCiYeH         let socket = socket_set_guard
651d623e902SGnoCiYeH             .get_mut::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
6526046f775S裕依 
6536046f775S裕依         if socket.is_open() {
6546046f775S裕依             if socket.can_send() {
6556046f775S裕依                 match socket.send_slice(buf) {
6566046f775S裕依                     Ok(size) => {
6576046f775S裕依                         drop(socket_set_guard);
6586046f775S裕依                         poll_ifaces();
6596046f775S裕依                         return Ok(size);
6606046f775S裕依                     }
6616046f775S裕依                     Err(e) => {
6626046f775S裕依                         kerror!("Tcp Socket Write Error {e:?}");
6636046f775S裕依                         return Err(SystemError::ENOBUFS);
6646046f775S裕依                     }
6656046f775S裕依                 }
6666046f775S裕依             } else {
6676046f775S裕依                 return Err(SystemError::ENOBUFS);
6686046f775S裕依             }
6696046f775S裕依         }
6706046f775S裕依 
6716046f775S裕依         return Err(SystemError::ENOTCONN);
6726046f775S裕依     }
6736046f775S裕依 
6746046f775S裕依     fn poll(&self) -> EPollEventType {
6756046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
676c719ddc6SSaga1718         // kdebug!("tcp socket:poll, socket'len={}",self.handle.len());
6776046f775S裕依 
678d623e902SGnoCiYeH         let socket = socket_set_guard
679d623e902SGnoCiYeH             .get_mut::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
6806046f775S裕依         return SocketPollMethod::tcp_poll(
6816046f775S裕依             socket,
6826046f775S裕依             HANDLE_MAP
6836046f775S裕依                 .read_irqsave()
6846046f775S裕依                 .get(&self.socket_handle())
6856046f775S裕依                 .unwrap()
6866046f775S裕依                 .shutdown_type(),
6876046f775S裕依         );
6886046f775S裕依     }
6896046f775S裕依 
6906046f775S裕依     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
6916046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
692c719ddc6SSaga1718         // kdebug!("tcp socket:connect, socket'len={}",self.handle.len());
693c719ddc6SSaga1718 
694d623e902SGnoCiYeH         let socket =
695d623e902SGnoCiYeH             sockets.get_mut::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
6966046f775S裕依 
6976046f775S裕依         if let Endpoint::Ip(Some(ip)) = endpoint {
6986046f775S裕依             let temp_port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
6996046f775S裕依             // 检测端口是否被占用
700c719ddc6SSaga1718             PORT_MANAGER.bind_port(self.metadata.socket_type, temp_port, self.clone())?;
7016046f775S裕依 
7026046f775S裕依             // kdebug!("temp_port: {}", temp_port);
7036046f775S裕依             let iface: Arc<dyn NetDriver> = NET_DRIVERS.write_irqsave().get(&0).unwrap().clone();
7046046f775S裕依             let mut inner_iface = iface.inner_iface().lock();
7056046f775S裕依             // kdebug!("to connect: {ip:?}");
7066046f775S裕依 
7076046f775S裕依             match socket.connect(inner_iface.context(), ip, temp_port) {
7086046f775S裕依                 Ok(()) => {
7096046f775S裕依                     // avoid deadlock
7106046f775S裕依                     drop(inner_iface);
7116046f775S裕依                     drop(iface);
7126046f775S裕依                     drop(sockets);
7136046f775S裕依                     loop {
7146046f775S裕依                         poll_ifaces();
7156046f775S裕依                         let mut sockets = SOCKET_SET.lock_irqsave();
716d623e902SGnoCiYeH                         let socket = sockets.get_mut::<tcp::Socket>(
717d623e902SGnoCiYeH                             self.handles.get(0).unwrap().smoltcp_handle().unwrap(),
718d623e902SGnoCiYeH                         );
7196046f775S裕依 
7206046f775S裕依                         match socket.state() {
7216046f775S裕依                             tcp::State::Established => {
7226046f775S裕依                                 return Ok(());
7236046f775S裕依                             }
7246046f775S裕依                             tcp::State::SynSent => {
7256046f775S裕依                                 drop(sockets);
7266046f775S裕依                                 SocketHandleItem::sleep(
7276046f775S裕依                                     self.socket_handle(),
7286046f775S裕依                                     Self::CAN_CONNECT,
7296046f775S裕依                                     HANDLE_MAP.read_irqsave(),
7306046f775S裕依                                 );
7316046f775S裕依                             }
7326046f775S裕依                             _ => {
7336046f775S裕依                                 return Err(SystemError::ECONNREFUSED);
7346046f775S裕依                             }
7356046f775S裕依                         }
7366046f775S裕依                     }
7376046f775S裕依                 }
7386046f775S裕依                 Err(e) => {
7396046f775S裕依                     // kerror!("Tcp Socket Connect Error {e:?}");
7406046f775S裕依                     match e {
7416046f775S裕依                         tcp::ConnectError::InvalidState => return Err(SystemError::EISCONN),
7426046f775S裕依                         tcp::ConnectError::Unaddressable => return Err(SystemError::EADDRNOTAVAIL),
7436046f775S裕依                     }
7446046f775S裕依                 }
7456046f775S裕依             }
7466046f775S裕依         } else {
7476046f775S裕依             return Err(SystemError::EINVAL);
7486046f775S裕依         }
7496046f775S裕依     }
7506046f775S裕依 
7516046f775S裕依     /// @brief tcp socket 监听 local_endpoint 端口
7526046f775S裕依     ///
7536046f775S裕依     /// @param backlog 未处理的连接队列的最大长度. 由于smoltcp不支持backlog,所以这个参数目前无效
754c719ddc6SSaga1718     fn listen(&mut self, backlog: usize) -> Result<(), SystemError> {
7556046f775S裕依         if self.is_listening {
7566046f775S裕依             return Ok(());
7576046f775S裕依         }
7586046f775S裕依 
7596046f775S裕依         let local_endpoint = self.local_endpoint.ok_or(SystemError::EINVAL)?;
7606046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
761c719ddc6SSaga1718         // 获取handle的数量
762c719ddc6SSaga1718         let handlen = self.handles.len();
763c719ddc6SSaga1718         let backlog = handlen.max(backlog);
7646046f775S裕依 
765c719ddc6SSaga1718         // 添加剩余需要构建的socket
766c719ddc6SSaga1718         // kdebug!("tcp socket:before listen, socket'len={}",self.handle.len());
767c719ddc6SSaga1718         let mut handle_guard = HANDLE_MAP.write_irqsave();
768c719ddc6SSaga1718         self.handles.extend((handlen..backlog).map(|_| {
769c719ddc6SSaga1718             let socket = Self::create_new_socket();
770d623e902SGnoCiYeH             let handle = GlobalSocketHandle::new_smoltcp_handle(sockets.add(socket));
771c719ddc6SSaga1718             let handle_item = SocketHandleItem::new();
772d623e902SGnoCiYeH             handle_guard.insert(handle, handle_item);
773c719ddc6SSaga1718             handle
774c719ddc6SSaga1718         }));
775c719ddc6SSaga1718         // kdebug!("tcp socket:listen, socket'len={}",self.handle.len());
776c719ddc6SSaga1718         // kdebug!("tcp socket:listen, backlog={backlog}");
777c719ddc6SSaga1718 
778c719ddc6SSaga1718         // 监听所有的socket
779c719ddc6SSaga1718         for i in 0..backlog {
780c719ddc6SSaga1718             let handle = self.handles.get(i).unwrap();
781c719ddc6SSaga1718 
782d623e902SGnoCiYeH             let socket = sockets.get_mut::<tcp::Socket>(handle.smoltcp_handle().unwrap());
783c719ddc6SSaga1718 
784c719ddc6SSaga1718             if !socket.is_listening() {
7856046f775S裕依                 // kdebug!("Tcp Socket is already listening on {local_endpoint}");
786c719ddc6SSaga1718                 self.do_listen(socket, local_endpoint)?;
7876046f775S裕依             }
7886046f775S裕依             // kdebug!("Tcp Socket  before listen, open={}", socket.is_open());
789c719ddc6SSaga1718         }
790c719ddc6SSaga1718         return Ok(());
7916046f775S裕依     }
7926046f775S裕依 
7936046f775S裕依     fn bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
7946046f775S裕依         if let Endpoint::Ip(Some(mut ip)) = endpoint {
7956046f775S裕依             if ip.port == 0 {
7966046f775S裕依                 ip.port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
7976046f775S裕依             }
7986046f775S裕依 
7996046f775S裕依             // 检测端口是否已被占用
800c719ddc6SSaga1718             PORT_MANAGER.bind_port(self.metadata.socket_type, ip.port, self.clone())?;
801c719ddc6SSaga1718             // kdebug!("tcp socket:bind, socket'len={}",self.handle.len());
8026046f775S裕依 
8036046f775S裕依             self.local_endpoint = Some(ip);
8046046f775S裕依             self.is_listening = false;
8056046f775S裕依             return Ok(());
8066046f775S裕依         }
8076046f775S裕依         return Err(SystemError::EINVAL);
8086046f775S裕依     }
8096046f775S裕依 
8106046f775S裕依     fn shutdown(&mut self, shutdown_type: super::ShutdownType) -> Result<(), SystemError> {
8116046f775S裕依         // TODO:目前只是在表层判断,对端不知晓,后续需使用tcp实现
8126046f775S裕依         HANDLE_MAP
8136046f775S裕依             .write_irqsave()
8146046f775S裕依             .get_mut(&self.socket_handle())
8156046f775S裕依             .unwrap()
8166046f775S裕依             .shutdown_type = RwLock::new(shutdown_type);
8176046f775S裕依         return Ok(());
8186046f775S裕依     }
8196046f775S裕依 
8206046f775S裕依     fn accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError> {
8216046f775S裕依         let endpoint = self.local_endpoint.ok_or(SystemError::EINVAL)?;
8226046f775S裕依         loop {
8236046f775S裕依             // kdebug!("tcp accept: poll_ifaces()");
8246046f775S裕依             poll_ifaces();
825c719ddc6SSaga1718             // kdebug!("tcp socket:accept, socket'len={}",self.handle.len());
8266046f775S裕依 
8276046f775S裕依             let mut sockets = SOCKET_SET.lock_irqsave();
8286046f775S裕依 
829c719ddc6SSaga1718             // 随机获取访问的socket的handle
830c719ddc6SSaga1718             let index: usize = rand() % self.handles.len();
831c719ddc6SSaga1718             let handle = self.handles.get(index).unwrap();
8326046f775S裕依 
833d623e902SGnoCiYeH             let socket = sockets
834d623e902SGnoCiYeH                 .iter_mut()
835d623e902SGnoCiYeH                 .find(|y| {
836d623e902SGnoCiYeH                     tcp::Socket::downcast(y.1)
837d623e902SGnoCiYeH                         .map(|y| y.is_active())
838d623e902SGnoCiYeH                         .unwrap_or(false)
839d623e902SGnoCiYeH                 })
840d623e902SGnoCiYeH                 .map(|y| tcp::Socket::downcast_mut(y.1).unwrap());
841d623e902SGnoCiYeH             if let Some(socket) = socket {
8426046f775S裕依                 if socket.is_active() {
8436046f775S裕依                     // kdebug!("tcp accept: socket.is_active()");
8446046f775S裕依                     let remote_ep = socket.remote_endpoint().ok_or(SystemError::ENOTCONN)?;
8456046f775S裕依 
8466046f775S裕依                     let new_socket = {
8476046f775S裕依                         // The new TCP socket used for sending and receiving data.
848c719ddc6SSaga1718                         let mut tcp_socket = Self::create_new_socket();
8496046f775S裕依                         self.do_listen(&mut tcp_socket, endpoint)
8506046f775S裕依                             .expect("do_listen failed");
8516046f775S裕依 
8526046f775S裕依                         // tcp_socket.listen(endpoint).unwrap();
8536046f775S裕依 
8546046f775S裕依                         // 之所以把old_handle存入new_socket, 是因为当前时刻,smoltcp已经把old_handle对应的socket与远程的endpoint关联起来了
8556046f775S裕依                         // 因此需要再为当前的socket分配一个新的handle
856d623e902SGnoCiYeH                         let new_handle =
857d623e902SGnoCiYeH                             GlobalSocketHandle::new_smoltcp_handle(sockets.add(tcp_socket));
858c719ddc6SSaga1718                         let old_handle = ::core::mem::replace(
859c719ddc6SSaga1718                             &mut *self.handles.get_mut(index).unwrap(),
860d623e902SGnoCiYeH                             new_handle,
861c719ddc6SSaga1718                         );
8626046f775S裕依 
8636046f775S裕依                         let metadata = SocketMetadata::new(
8646046f775S裕依                             SocketType::Tcp,
8656046f775S裕依                             Self::DEFAULT_TX_BUF_SIZE,
8666046f775S裕依                             Self::DEFAULT_RX_BUF_SIZE,
8676046f775S裕依                             Self::DEFAULT_METADATA_BUF_SIZE,
8686046f775S裕依                             self.metadata.options,
8696046f775S裕依                         );
8706046f775S裕依 
8716046f775S裕依                         let new_socket = Box::new(TcpSocket {
872d623e902SGnoCiYeH                             handles: vec![old_handle],
8736046f775S裕依                             local_endpoint: self.local_endpoint,
8746046f775S裕依                             is_listening: false,
8756046f775S裕依                             metadata,
8766046f775S裕依                         });
877c719ddc6SSaga1718                         // kdebug!("tcp socket:after accept, socket'len={}",new_socket.handle.len());
878c719ddc6SSaga1718 
879c719ddc6SSaga1718                         // 更新端口与 socket 的绑定
880c719ddc6SSaga1718                         if let Some(Endpoint::Ip(Some(ip))) = self.endpoint() {
881c719ddc6SSaga1718                             PORT_MANAGER.unbind_port(self.metadata.socket_type, ip.port)?;
882c719ddc6SSaga1718                             PORT_MANAGER.bind_port(
883c719ddc6SSaga1718                                 self.metadata.socket_type,
884c719ddc6SSaga1718                                 ip.port,
885c719ddc6SSaga1718                                 *new_socket.clone(),
886c719ddc6SSaga1718                             )?;
887c719ddc6SSaga1718                         }
8886046f775S裕依 
8896046f775S裕依                         // 更新handle表
8906046f775S裕依                         let mut handle_guard = HANDLE_MAP.write_irqsave();
8916046f775S裕依                         // 先删除原来的
892c719ddc6SSaga1718 
893d623e902SGnoCiYeH                         let item = handle_guard.remove(&old_handle).unwrap();
894c719ddc6SSaga1718 
8956046f775S裕依                         // 按照smoltcp行为,将新的handle绑定到原来的item
896d623e902SGnoCiYeH                         handle_guard.insert(new_handle, item);
8976046f775S裕依                         let new_item = SocketHandleItem::new();
898c719ddc6SSaga1718 
8996046f775S裕依                         // 插入新的item
900d623e902SGnoCiYeH                         handle_guard.insert(old_handle, new_item);
9016046f775S裕依 
9026046f775S裕依                         new_socket
9036046f775S裕依                     };
9046046f775S裕依                     // kdebug!("tcp accept: new socket: {:?}", new_socket);
9056046f775S裕依                     drop(sockets);
9066046f775S裕依                     poll_ifaces();
9076046f775S裕依 
9086046f775S裕依                     return Ok((new_socket, Endpoint::Ip(Some(remote_ep))));
9096046f775S裕依                 }
910d623e902SGnoCiYeH             }
911c719ddc6SSaga1718             // kdebug!("tcp socket:before sleep, handle_guard'len={}",HANDLE_MAP.write_irqsave().len());
9126046f775S裕依 
913c719ddc6SSaga1718             drop(sockets);
914d623e902SGnoCiYeH             SocketHandleItem::sleep(*handle, Self::CAN_ACCPET, HANDLE_MAP.read_irqsave());
915c719ddc6SSaga1718             // kdebug!("tcp socket:after sleep, handle_guard'len={}",HANDLE_MAP.write_irqsave().len());
9166046f775S裕依         }
9176046f775S裕依     }
9186046f775S裕依 
9196046f775S裕依     fn endpoint(&self) -> Option<Endpoint> {
9206046f775S裕依         let mut result: Option<Endpoint> = self.local_endpoint.map(|x| Endpoint::Ip(Some(x)));
9216046f775S裕依 
9226046f775S裕依         if result.is_none() {
9236046f775S裕依             let sockets = SOCKET_SET.lock_irqsave();
924c719ddc6SSaga1718             // kdebug!("tcp socket:endpoint, socket'len={}",self.handle.len());
925c719ddc6SSaga1718 
926d623e902SGnoCiYeH             let socket =
927d623e902SGnoCiYeH                 sockets.get::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
9286046f775S裕依             if let Some(ep) = socket.local_endpoint() {
9296046f775S裕依                 result = Some(Endpoint::Ip(Some(ep)));
9306046f775S裕依             }
9316046f775S裕依         }
9326046f775S裕依         return result;
9336046f775S裕依     }
9346046f775S裕依 
9356046f775S裕依     fn peer_endpoint(&self) -> Option<Endpoint> {
9366046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
937c719ddc6SSaga1718         // kdebug!("tcp socket:peer_endpoint, socket'len={}",self.handle.len());
938c719ddc6SSaga1718 
939d623e902SGnoCiYeH         let socket =
940d623e902SGnoCiYeH             sockets.get::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
9416046f775S裕依         return socket.remote_endpoint().map(|x| Endpoint::Ip(Some(x)));
9426046f775S裕依     }
9436046f775S裕依 
9446046f775S裕依     fn metadata(&self) -> SocketMetadata {
9456046f775S裕依         self.metadata.clone()
9466046f775S裕依     }
9476046f775S裕依 
9486046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
9496046f775S裕依         Box::new(self.clone())
9506046f775S裕依     }
9516046f775S裕依 
952d623e902SGnoCiYeH     fn socket_handle(&self) -> GlobalSocketHandle {
953c719ddc6SSaga1718         // kdebug!("tcp socket:socket_handle, socket'len={}",self.handle.len());
954c719ddc6SSaga1718 
955d623e902SGnoCiYeH         *self.handles.get(0).unwrap()
9566046f775S裕依     }
9576046f775S裕依 
9586046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
9596046f775S裕依         self
9606046f775S裕依     }
9616046f775S裕依 
9626046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
9636046f775S裕依         self
9646046f775S裕依     }
9656046f775S裕依 }
966