xref: /DragonOS/kernel/src/net/socket/inet.rs (revision bd70d2d1f490aabd570a5301b858bd5eb04149fa)
16046f775S裕依 use alloc::{boxed::Box, sync::Arc, vec::Vec};
22eab6dd7S曾俊 use log::{error, warn};
36046f775S裕依 use smoltcp::{
437cef00bSSamuel Dai     socket::{raw, tcp, udp},
56046f775S裕依     wire,
66046f775S裕依 };
76046f775S裕依 use system_error::SystemError;
86046f775S裕依 
96046f775S裕依 use crate::{
10e32effb1SLoGin     driver::net::NetDevice,
116046f775S裕依     libs::rwlock::RwLock,
126046f775S裕依     net::{
136046f775S裕依         event_poll::EPollEventType, net_core::poll_ifaces, Endpoint, Protocol, ShutdownType,
14e32effb1SLoGin         NET_DEVICES,
156046f775S裕依     },
166046f775S裕依 };
176046f775S裕依 
186046f775S裕依 use super::{
19634349e0SLoGin     handle::GlobalSocketHandle, PosixSocketHandleItem, Socket, SocketHandleItem, SocketMetadata,
20634349e0SLoGin     SocketOptions, SocketPollMethod, SocketType, HANDLE_MAP, PORT_MANAGER, SOCKET_SET,
216046f775S裕依 };
226046f775S裕依 
236046f775S裕依 /// @brief 表示原始的socket。原始套接字绕过传输层协议(如 TCP 或 UDP)并提供对网络层协议(如 IP)的直接访问。
246046f775S裕依 ///
256046f775S裕依 /// ref: https://man7.org/linux/man-pages/man7/raw.7.html
266046f775S裕依 #[derive(Debug, Clone)]
276046f775S裕依 pub struct RawSocket {
28d623e902SGnoCiYeH     handle: GlobalSocketHandle,
296046f775S裕依     /// 用户发送的数据包是否包含了IP头.
306046f775S裕依     /// 如果是true,用户发送的数据包,必须包含IP头。(即用户要自行设置IP头+数据)
316046f775S裕依     /// 如果是false,用户发送的数据包,不包含IP头。(即用户只要设置数据)
326046f775S裕依     header_included: bool,
336046f775S裕依     /// socket的metadata
346046f775S裕依     metadata: SocketMetadata,
35634349e0SLoGin     posix_item: Arc<PosixSocketHandleItem>,
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
new(protocol: Protocol, options: SocketOptions) -> Self526046f775S裕依     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裕依 
80634349e0SLoGin         let posix_item = Arc::new(PosixSocketHandleItem::new(None));
81634349e0SLoGin 
826046f775S裕依         return Self {
836046f775S裕依             handle,
846046f775S裕依             header_included: false,
856046f775S裕依             metadata,
86634349e0SLoGin             posix_item,
876046f775S裕依         };
886046f775S裕依     }
896046f775S裕依 }
906046f775S裕依 
916046f775S裕依 impl Socket for RawSocket {
posix_item(&self) -> Arc<PosixSocketHandleItem>92634349e0SLoGin     fn posix_item(&self) -> Arc<PosixSocketHandleItem> {
93634349e0SLoGin         self.posix_item.clone()
94634349e0SLoGin     }
95634349e0SLoGin 
close(&mut self)96d623e902SGnoCiYeH     fn close(&mut self) {
97d623e902SGnoCiYeH         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
9837cef00bSSamuel Dai         if let smoltcp::socket::Socket::Udp(mut sock) =
9937cef00bSSamuel Dai             socket_set_guard.remove(self.handle.smoltcp_handle().unwrap())
10037cef00bSSamuel Dai         {
10137cef00bSSamuel Dai             sock.close();
10237cef00bSSamuel Dai         }
103d623e902SGnoCiYeH         drop(socket_set_guard);
104d623e902SGnoCiYeH         poll_ifaces();
105d623e902SGnoCiYeH     }
106d623e902SGnoCiYeH 
read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint)1076046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
1086046f775S裕依         poll_ifaces();
1096046f775S裕依         loop {
1106046f775S裕依             // 如何优化这里?
1116046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
112d623e902SGnoCiYeH             let socket =
113d623e902SGnoCiYeH                 socket_set_guard.get_mut::<raw::Socket>(self.handle.smoltcp_handle().unwrap());
1146046f775S裕依 
1156046f775S裕依             match socket.recv_slice(buf) {
1166046f775S裕依                 Ok(len) => {
1176046f775S裕依                     let packet = wire::Ipv4Packet::new_unchecked(buf);
1186046f775S裕依                     return (
1196046f775S裕依                         Ok(len),
1206046f775S裕依                         Endpoint::Ip(Some(wire::IpEndpoint {
1216046f775S裕依                             addr: wire::IpAddress::Ipv4(packet.src_addr()),
1226046f775S裕依                             port: 0,
1236046f775S裕依                         })),
1246046f775S裕依                     );
1256046f775S裕依                 }
126881ff6f9Syuyi2439                 Err(_) => {
1276046f775S裕依                     if !self.metadata.options.contains(SocketOptions::BLOCK) {
1286046f775S裕依                         // 如果是非阻塞的socket,就返回错误
1296046f775S裕依                         return (Err(SystemError::EAGAIN_OR_EWOULDBLOCK), Endpoint::Ip(None));
1306046f775S裕依                     }
1316046f775S裕依                 }
1326046f775S裕依             }
1336046f775S裕依             drop(socket_set_guard);
134634349e0SLoGin             self.posix_item.sleep(EPollEventType::EPOLLIN.bits() as u64);
1356046f775S裕依         }
1366046f775S裕依     }
1376046f775S裕依 
write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError>1386046f775S裕依     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError> {
1396046f775S裕依         // 如果用户发送的数据包,包含IP头,则直接发送
1406046f775S裕依         if self.header_included {
1416046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
142d623e902SGnoCiYeH             let socket =
143d623e902SGnoCiYeH                 socket_set_guard.get_mut::<raw::Socket>(self.handle.smoltcp_handle().unwrap());
1446046f775S裕依             match socket.send_slice(buf) {
1456046f775S裕依                 Ok(_) => {
1466046f775S裕依                     return Ok(buf.len());
1476046f775S裕依                 }
1486046f775S裕依                 Err(raw::SendError::BufferFull) => {
1496046f775S裕依                     return Err(SystemError::ENOBUFS);
1506046f775S裕依                 }
1516046f775S裕依             }
1526046f775S裕依         } else {
1536046f775S裕依             // 如果用户发送的数据包,不包含IP头,则需要自己构造IP头
1546046f775S裕依 
1556046f775S裕依             if let Some(Endpoint::Ip(Some(endpoint))) = to {
1566046f775S裕依                 let mut socket_set_guard = SOCKET_SET.lock_irqsave();
1576046f775S裕依                 let socket: &mut raw::Socket =
158d623e902SGnoCiYeH                     socket_set_guard.get_mut::<raw::Socket>(self.handle.smoltcp_handle().unwrap());
1596046f775S裕依 
1606046f775S裕依                 // 暴力解决方案:只考虑0号网卡。 TODO:考虑多网卡的情况!!!
161e32effb1SLoGin                 let iface = NET_DEVICES.read_irqsave().get(&0).unwrap().clone();
1626046f775S裕依 
1636046f775S裕依                 // 构造IP头
1646046f775S裕依                 let ipv4_src_addr: Option<wire::Ipv4Address> =
1656046f775S裕依                     iface.inner_iface().lock().ipv4_addr();
1666046f775S裕依                 if ipv4_src_addr.is_none() {
1676046f775S裕依                     return Err(SystemError::ENETUNREACH);
1686046f775S裕依                 }
1696046f775S裕依                 let ipv4_src_addr = ipv4_src_addr.unwrap();
1706046f775S裕依 
1716046f775S裕依                 if let wire::IpAddress::Ipv4(ipv4_dst) = endpoint.addr {
1726046f775S裕依                     let len = buf.len();
1736046f775S裕依 
1746046f775S裕依                     // 创建20字节的IPv4头部
1756046f775S裕依                     let mut buffer: Vec<u8> = vec![0u8; len + 20];
1766046f775S裕依                     let mut packet: wire::Ipv4Packet<&mut Vec<u8>> =
1776046f775S裕依                         wire::Ipv4Packet::new_unchecked(&mut buffer);
1786046f775S裕依 
1796046f775S裕依                     // 封装ipv4 header
1806046f775S裕依                     packet.set_version(4);
1816046f775S裕依                     packet.set_header_len(20);
1826046f775S裕依                     packet.set_total_len((20 + len) as u16);
1836046f775S裕依                     packet.set_src_addr(ipv4_src_addr);
1846046f775S裕依                     packet.set_dst_addr(ipv4_dst);
1856046f775S裕依 
1866046f775S裕依                     // 设置ipv4 header的protocol字段
1876046f775S裕依                     packet.set_next_header(socket.ip_protocol());
1886046f775S裕依 
1896046f775S裕依                     // 获取IP数据包的负载字段
1906046f775S裕依                     let payload: &mut [u8] = packet.payload_mut();
1916046f775S裕依                     payload.copy_from_slice(buf);
1926046f775S裕依 
1936046f775S裕依                     // 填充checksum字段
1946046f775S裕依                     packet.fill_checksum();
1956046f775S裕依 
1966046f775S裕依                     // 发送数据包
1976046f775S裕依                     socket.send_slice(&buffer).unwrap();
1986046f775S裕依 
1996046f775S裕依                     iface.poll(&mut socket_set_guard).ok();
2006046f775S裕依 
2016046f775S裕依                     drop(socket_set_guard);
2026046f775S裕依                     return Ok(len);
2036046f775S裕依                 } else {
2042eab6dd7S曾俊                     warn!("Unsupport Ip protocol type!");
2056046f775S裕依                     return Err(SystemError::EINVAL);
2066046f775S裕依                 }
2076046f775S裕依             } else {
2086046f775S裕依                 // 如果没有指定目的地址,则返回错误
2096046f775S裕依                 return Err(SystemError::ENOTCONN);
2106046f775S裕依             }
2116046f775S裕依         }
2126046f775S裕依     }
2136046f775S裕依 
connect(&mut self, _endpoint: Endpoint) -> Result<(), SystemError>2146046f775S裕依     fn connect(&mut self, _endpoint: Endpoint) -> Result<(), SystemError> {
2156046f775S裕依         Ok(())
2166046f775S裕依     }
2176046f775S裕依 
metadata(&self) -> SocketMetadata2186046f775S裕依     fn metadata(&self) -> SocketMetadata {
2196046f775S裕依         self.metadata.clone()
2206046f775S裕依     }
2216046f775S裕依 
box_clone(&self) -> Box<dyn Socket>2226046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
2236046f775S裕依         Box::new(self.clone())
2246046f775S裕依     }
2256046f775S裕依 
socket_handle(&self) -> GlobalSocketHandle226d623e902SGnoCiYeH     fn socket_handle(&self) -> GlobalSocketHandle {
227d623e902SGnoCiYeH         self.handle
2286046f775S裕依     }
2296046f775S裕依 
as_any_ref(&self) -> &dyn core::any::Any2306046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
2316046f775S裕依         self
2326046f775S裕依     }
2336046f775S裕依 
as_any_mut(&mut self) -> &mut dyn core::any::Any2346046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
2356046f775S裕依         self
2366046f775S裕依     }
2376046f775S裕依 }
2386046f775S裕依 
2396046f775S裕依 /// @brief 表示udp socket
2406046f775S裕依 ///
2416046f775S裕依 /// https://man7.org/linux/man-pages/man7/udp.7.html
2426046f775S裕依 #[derive(Debug, Clone)]
2436046f775S裕依 pub struct UdpSocket {
244d623e902SGnoCiYeH     pub handle: GlobalSocketHandle,
2456046f775S裕依     remote_endpoint: Option<Endpoint>, // 记录远程endpoint提供给connect(), 应该使用IP地址。
2466046f775S裕依     metadata: SocketMetadata,
247634349e0SLoGin     posix_item: Arc<PosixSocketHandleItem>,
2486046f775S裕依 }
2496046f775S裕依 
2506046f775S裕依 impl UdpSocket {
2516046f775S裕依     /// 元数据的缓冲区的大小
2526046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
2536046f775S裕依     /// 默认的接收缓冲区的大小 receive
2546046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 64 * 1024;
2556046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
2566046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 64 * 1024;
2576046f775S裕依 
2586046f775S裕依     /// @brief 创建一个udp的socket
2596046f775S裕依     ///
2606046f775S裕依     /// @param options socket的选项
2616046f775S裕依     ///
2626046f775S裕依     /// @return 返回创建的udp的socket
new(options: SocketOptions) -> Self2636046f775S裕依     pub fn new(options: SocketOptions) -> Self {
2646046f775S裕依         let rx_buffer = udp::PacketBuffer::new(
2656046f775S裕依             vec![udp::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
2666046f775S裕依             vec![0; Self::DEFAULT_RX_BUF_SIZE],
2676046f775S裕依         );
2686046f775S裕依         let tx_buffer = udp::PacketBuffer::new(
2696046f775S裕依             vec![udp::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
2706046f775S裕依             vec![0; Self::DEFAULT_TX_BUF_SIZE],
2716046f775S裕依         );
2726046f775S裕依         let socket = udp::Socket::new(rx_buffer, tx_buffer);
2736046f775S裕依 
2746046f775S裕依         // 把socket添加到socket集合中,并得到socket的句柄
275d623e902SGnoCiYeH         let handle: GlobalSocketHandle =
276d623e902SGnoCiYeH             GlobalSocketHandle::new_smoltcp_handle(SOCKET_SET.lock_irqsave().add(socket));
2776046f775S裕依 
2786046f775S裕依         let metadata = SocketMetadata::new(
2796046f775S裕依             SocketType::Udp,
2806046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
2816046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
2826046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
2836046f775S裕依             options,
2846046f775S裕依         );
2856046f775S裕依 
286634349e0SLoGin         let posix_item = Arc::new(PosixSocketHandleItem::new(None));
287634349e0SLoGin 
2886046f775S裕依         return Self {
2896046f775S裕依             handle,
2906046f775S裕依             remote_endpoint: None,
2916046f775S裕依             metadata,
292634349e0SLoGin             posix_item,
2936046f775S裕依         };
2946046f775S裕依     }
2956046f775S裕依 
do_bind(&self, socket: &mut udp::Socket, endpoint: Endpoint) -> Result<(), SystemError>2966046f775S裕依     fn do_bind(&self, socket: &mut udp::Socket, endpoint: Endpoint) -> Result<(), SystemError> {
2979d9a0984Ssun5etop         if let Endpoint::Ip(Some(mut ip)) = endpoint {
2989d9a0984Ssun5etop             // 端口为0则分配随机端口
2999d9a0984Ssun5etop             if ip.port == 0 {
3009d9a0984Ssun5etop                 ip.port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
3019d9a0984Ssun5etop             }
3026046f775S裕依             // 检测端口是否已被占用
30337cef00bSSamuel Dai             PORT_MANAGER.bind_port(self.metadata.socket_type, ip.port)?;
3046046f775S裕依 
3056046f775S裕依             let bind_res = if ip.addr.is_unspecified() {
3066046f775S裕依                 socket.bind(ip.port)
3076046f775S裕依             } else {
3086046f775S裕依                 socket.bind(ip)
3096046f775S裕依             };
3106046f775S裕依 
3116046f775S裕依             match bind_res {
3126046f775S裕依                 Ok(()) => return Ok(()),
3136046f775S裕依                 Err(_) => return Err(SystemError::EINVAL),
3146046f775S裕依             }
3156046f775S裕依         } else {
3166046f775S裕依             return Err(SystemError::EINVAL);
3176046f775S裕依         }
3186046f775S裕依     }
3196046f775S裕依 }
3206046f775S裕依 
3216046f775S裕依 impl Socket for UdpSocket {
posix_item(&self) -> Arc<PosixSocketHandleItem>322634349e0SLoGin     fn posix_item(&self) -> Arc<PosixSocketHandleItem> {
323634349e0SLoGin         self.posix_item.clone()
324634349e0SLoGin     }
325634349e0SLoGin 
close(&mut self)326d623e902SGnoCiYeH     fn close(&mut self) {
327d623e902SGnoCiYeH         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
32837cef00bSSamuel Dai         if let smoltcp::socket::Socket::Udp(mut sock) =
32937cef00bSSamuel Dai             socket_set_guard.remove(self.handle.smoltcp_handle().unwrap())
33037cef00bSSamuel Dai         {
33137cef00bSSamuel Dai             sock.close();
33237cef00bSSamuel Dai         }
333d623e902SGnoCiYeH         drop(socket_set_guard);
334d623e902SGnoCiYeH         poll_ifaces();
335d623e902SGnoCiYeH     }
336d623e902SGnoCiYeH 
3376046f775S裕依     /// @brief 在read函数执行之前,请先bind到本地的指定端口
read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint)3386046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
3396046f775S裕依         loop {
3402eab6dd7S曾俊             // debug!("Wait22 to Read");
3416046f775S裕依             poll_ifaces();
3426046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
343d623e902SGnoCiYeH             let socket =
344d623e902SGnoCiYeH                 socket_set_guard.get_mut::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
3456046f775S裕依 
3462eab6dd7S曾俊             // debug!("Wait to Read");
3476046f775S裕依 
3486046f775S裕依             if socket.can_recv() {
349881ff6f9Syuyi2439                 if let Ok((size, metadata)) = socket.recv_slice(buf) {
3506046f775S裕依                     drop(socket_set_guard);
3516046f775S裕依                     poll_ifaces();
352881ff6f9Syuyi2439                     return (Ok(size), Endpoint::Ip(Some(metadata.endpoint)));
3536046f775S裕依                 }
3546046f775S裕依             } else {
3556046f775S裕依                 // 如果socket没有连接,则忙等
3566046f775S裕依                 // return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
3576046f775S裕依             }
3586046f775S裕依             drop(socket_set_guard);
359634349e0SLoGin             self.posix_item.sleep(EPollEventType::EPOLLIN.bits() as u64);
3606046f775S裕依         }
3616046f775S裕依     }
3626046f775S裕依 
write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError>3636046f775S裕依     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError> {
3642eab6dd7S曾俊         // debug!("udp to send: {:?}, len={}", to, buf.len());
3656046f775S裕依         let remote_endpoint: &wire::IpEndpoint = {
3666046f775S裕依             if let Some(Endpoint::Ip(Some(ref endpoint))) = to {
3676046f775S裕依                 endpoint
3686046f775S裕依             } else if let Some(Endpoint::Ip(Some(ref endpoint))) = self.remote_endpoint {
3696046f775S裕依                 endpoint
3706046f775S裕依             } else {
3716046f775S裕依                 return Err(SystemError::ENOTCONN);
3726046f775S裕依             }
3736046f775S裕依         };
3742eab6dd7S曾俊         // debug!("udp write: remote = {:?}", remote_endpoint);
3756046f775S裕依 
3766046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
377d623e902SGnoCiYeH         let socket = socket_set_guard.get_mut::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
3782eab6dd7S曾俊         // debug!("is open()={}", socket.is_open());
3792eab6dd7S曾俊         // debug!("socket endpoint={:?}", socket.endpoint());
3806046f775S裕依         if socket.can_send() {
3812eab6dd7S曾俊             // debug!("udp write: can send");
3826046f775S裕依             match socket.send_slice(buf, *remote_endpoint) {
3836046f775S裕依                 Ok(()) => {
3842eab6dd7S曾俊                     // debug!("udp write: send ok");
3856046f775S裕依                     drop(socket_set_guard);
3866046f775S裕依                     poll_ifaces();
3876046f775S裕依                     return Ok(buf.len());
3886046f775S裕依                 }
3896046f775S裕依                 Err(_) => {
3902eab6dd7S曾俊                     // debug!("udp write: send err");
3916046f775S裕依                     return Err(SystemError::ENOBUFS);
3926046f775S裕依                 }
3936046f775S裕依             }
3946046f775S裕依         } else {
3952eab6dd7S曾俊             // debug!("udp write: can not send");
3966046f775S裕依             return Err(SystemError::ENOBUFS);
3976046f775S裕依         };
3986046f775S裕依     }
3996046f775S裕依 
bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError>4006046f775S裕依     fn bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
4016046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
402d623e902SGnoCiYeH         let socket = sockets.get_mut::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
4032eab6dd7S曾俊         // debug!("UDP Bind to {:?}", endpoint);
4046046f775S裕依         return self.do_bind(socket, endpoint);
4056046f775S裕依     }
4066046f775S裕依 
poll(&self) -> EPollEventType4076046f775S裕依     fn poll(&self) -> EPollEventType {
4086046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
409d623e902SGnoCiYeH         let socket = sockets.get::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
4106046f775S裕依 
4116046f775S裕依         return SocketPollMethod::udp_poll(
4126046f775S裕依             socket,
4136046f775S裕依             HANDLE_MAP
4146046f775S裕依                 .read_irqsave()
4156046f775S裕依                 .get(&self.socket_handle())
4166046f775S裕依                 .unwrap()
4176046f775S裕依                 .shutdown_type(),
4186046f775S裕依         );
4196046f775S裕依     }
4206046f775S裕依 
connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError>4216046f775S裕依     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
4226046f775S裕依         if let Endpoint::Ip(_) = endpoint {
4236046f775S裕依             self.remote_endpoint = Some(endpoint);
4246046f775S裕依             Ok(())
4256046f775S裕依         } else {
4266046f775S裕依             Err(SystemError::EINVAL)
4276046f775S裕依         }
4286046f775S裕依     }
4296046f775S裕依 
ioctl( &self, _cmd: usize, _arg0: usize, _arg1: usize, _arg2: usize, ) -> Result<usize, SystemError>4306046f775S裕依     fn ioctl(
4316046f775S裕依         &self,
4326046f775S裕依         _cmd: usize,
4336046f775S裕依         _arg0: usize,
4346046f775S裕依         _arg1: usize,
4356046f775S裕依         _arg2: usize,
4366046f775S裕依     ) -> Result<usize, SystemError> {
4376046f775S裕依         todo!()
4386046f775S裕依     }
4396046f775S裕依 
metadata(&self) -> SocketMetadata4406046f775S裕依     fn metadata(&self) -> SocketMetadata {
4416046f775S裕依         self.metadata.clone()
4426046f775S裕依     }
4436046f775S裕依 
box_clone(&self) -> Box<dyn Socket>4446046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
4456046f775S裕依         return Box::new(self.clone());
4466046f775S裕依     }
4476046f775S裕依 
endpoint(&self) -> Option<Endpoint>4486046f775S裕依     fn endpoint(&self) -> Option<Endpoint> {
4496046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
450d623e902SGnoCiYeH         let socket = sockets.get::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
4516046f775S裕依         let listen_endpoint = socket.endpoint();
4526046f775S裕依 
4536046f775S裕依         if listen_endpoint.port == 0 {
4546046f775S裕依             return None;
4556046f775S裕依         } else {
4566046f775S裕依             // 如果listen_endpoint的address是None,意味着“监听所有的地址”。
4576046f775S裕依             // 这里假设所有的地址都是ipv4
4586046f775S裕依             // TODO: 支持ipv6
4596046f775S裕依             let result = wire::IpEndpoint::new(
4606046f775S裕依                 listen_endpoint
4616046f775S裕依                     .addr
4626046f775S裕依                     .unwrap_or(wire::IpAddress::v4(0, 0, 0, 0)),
4636046f775S裕依                 listen_endpoint.port,
4646046f775S裕依             );
4656046f775S裕依             return Some(Endpoint::Ip(Some(result)));
4666046f775S裕依         }
4676046f775S裕依     }
4686046f775S裕依 
peer_endpoint(&self) -> Option<Endpoint>4696046f775S裕依     fn peer_endpoint(&self) -> Option<Endpoint> {
4706046f775S裕依         return self.remote_endpoint.clone();
4716046f775S裕依     }
4726046f775S裕依 
socket_handle(&self) -> GlobalSocketHandle473d623e902SGnoCiYeH     fn socket_handle(&self) -> GlobalSocketHandle {
474d623e902SGnoCiYeH         self.handle
4756046f775S裕依     }
4766046f775S裕依 
as_any_ref(&self) -> &dyn core::any::Any4776046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
4786046f775S裕依         self
4796046f775S裕依     }
4806046f775S裕依 
as_any_mut(&mut self) -> &mut dyn core::any::Any4816046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
4826046f775S裕依         self
4836046f775S裕依     }
4846046f775S裕依 }
4856046f775S裕依 
4866046f775S裕依 /// @brief 表示 tcp socket
4876046f775S裕依 ///
4886046f775S裕依 /// https://man7.org/linux/man-pages/man7/tcp.7.html
4896046f775S裕依 #[derive(Debug, Clone)]
4906046f775S裕依 pub struct TcpSocket {
491d623e902SGnoCiYeH     handles: Vec<GlobalSocketHandle>,
4926046f775S裕依     local_endpoint: Option<wire::IpEndpoint>, // save local endpoint for bind()
4936046f775S裕依     is_listening: bool,
4946046f775S裕依     metadata: SocketMetadata,
495634349e0SLoGin     posix_item: Arc<PosixSocketHandleItem>,
4966046f775S裕依 }
4976046f775S裕依 
4986046f775S裕依 impl TcpSocket {
4996046f775S裕依     /// 元数据的缓冲区的大小
5006046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
5016046f775S裕依     /// 默认的接收缓冲区的大小 receive
5026046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 512 * 1024;
5036046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
5046046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 512 * 1024;
5056046f775S裕依 
5066046f775S裕依     /// TcpSocket的特殊事件,用于在事件等待队列上sleep
5076046f775S裕依     pub const CAN_CONNECT: u64 = 1u64 << 63;
5086046f775S裕依     pub const CAN_ACCPET: u64 = 1u64 << 62;
5096046f775S裕依 
5106046f775S裕依     /// @brief 创建一个tcp的socket
5116046f775S裕依     ///
5126046f775S裕依     /// @param options socket的选项
5136046f775S裕依     ///
5146046f775S裕依     /// @return 返回创建的tcp的socket
new(options: SocketOptions) -> Self5156046f775S裕依     pub fn new(options: SocketOptions) -> Self {
516c719ddc6SSaga1718         // 创建handles数组并把socket添加到socket集合中,并得到socket的句柄
517d623e902SGnoCiYeH         let handles: Vec<GlobalSocketHandle> = vec![GlobalSocketHandle::new_smoltcp_handle(
518c719ddc6SSaga1718             SOCKET_SET.lock_irqsave().add(Self::create_new_socket()),
519c719ddc6SSaga1718         )];
5206046f775S裕依 
5216046f775S裕依         let metadata = SocketMetadata::new(
5226046f775S裕依             SocketType::Tcp,
5236046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
5246046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
5256046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
5266046f775S裕依             options,
5276046f775S裕依         );
528634349e0SLoGin         let posix_item = Arc::new(PosixSocketHandleItem::new(None));
5292eab6dd7S曾俊         // debug!("when there's a new tcp socket,its'len: {}",handles.len());
5306046f775S裕依 
5316046f775S裕依         return Self {
532c719ddc6SSaga1718             handles,
5336046f775S裕依             local_endpoint: None,
5346046f775S裕依             is_listening: false,
5356046f775S裕依             metadata,
536634349e0SLoGin             posix_item,
5376046f775S裕依         };
5386046f775S裕依     }
5396046f775S裕依 
do_listen( &mut self, socket: &mut tcp::Socket, local_endpoint: wire::IpEndpoint, ) -> Result<(), SystemError>5406046f775S裕依     fn do_listen(
5416046f775S裕依         &mut self,
5426046f775S裕依         socket: &mut tcp::Socket,
5436046f775S裕依         local_endpoint: wire::IpEndpoint,
5446046f775S裕依     ) -> Result<(), SystemError> {
5456046f775S裕依         let listen_result = if local_endpoint.addr.is_unspecified() {
5466046f775S裕依             socket.listen(local_endpoint.port)
5476046f775S裕依         } else {
5486046f775S裕依             socket.listen(local_endpoint)
5496046f775S裕依         };
5506046f775S裕依         return match listen_result {
5516046f775S裕依             Ok(()) => {
5522eab6dd7S曾俊                 // debug!(
5536046f775S裕依                 //     "Tcp Socket Listen on {local_endpoint}, open?:{}",
5546046f775S裕依                 //     socket.is_open()
5556046f775S裕依                 // );
5566046f775S裕依                 self.is_listening = true;
5576046f775S裕依 
5586046f775S裕依                 Ok(())
5596046f775S裕依             }
5606046f775S裕依             Err(_) => Err(SystemError::EINVAL),
5616046f775S裕依         };
5626046f775S裕依     }
563c719ddc6SSaga1718 
564c719ddc6SSaga1718     /// # create_new_socket - 创建新的TCP套接字
565c719ddc6SSaga1718     ///
566c719ddc6SSaga1718     /// 该函数用于创建一个新的TCP套接字,并返回该套接字的引用。
create_new_socket() -> tcp::Socket<'static>567c719ddc6SSaga1718     fn create_new_socket() -> tcp::Socket<'static> {
568c719ddc6SSaga1718         // 初始化tcp的buffer
569c719ddc6SSaga1718         let rx_buffer = tcp::SocketBuffer::new(vec![0; Self::DEFAULT_RX_BUF_SIZE]);
570c719ddc6SSaga1718         let tx_buffer = tcp::SocketBuffer::new(vec![0; Self::DEFAULT_TX_BUF_SIZE]);
571c719ddc6SSaga1718         tcp::Socket::new(rx_buffer, tx_buffer)
572c719ddc6SSaga1718     }
573634349e0SLoGin 
574634349e0SLoGin     /// listening状态的posix socket是需要特殊处理的
tcp_poll_listening(&self) -> EPollEventType575634349e0SLoGin     fn tcp_poll_listening(&self) -> EPollEventType {
576634349e0SLoGin         let socketset_guard = SOCKET_SET.lock_irqsave();
577634349e0SLoGin 
578634349e0SLoGin         let can_accept = self.handles.iter().any(|h| {
579634349e0SLoGin             if let Some(sh) = h.smoltcp_handle() {
580634349e0SLoGin                 let socket = socketset_guard.get::<tcp::Socket>(sh);
581634349e0SLoGin                 socket.is_active()
582634349e0SLoGin             } else {
583634349e0SLoGin                 false
584634349e0SLoGin             }
585634349e0SLoGin         });
586634349e0SLoGin 
587634349e0SLoGin         if can_accept {
588634349e0SLoGin             return EPollEventType::EPOLL_LISTEN_CAN_ACCEPT;
589634349e0SLoGin         } else {
590634349e0SLoGin             return EPollEventType::empty();
591634349e0SLoGin         }
592634349e0SLoGin     }
5936046f775S裕依 }
5946046f775S裕依 
5956046f775S裕依 impl Socket for TcpSocket {
posix_item(&self) -> Arc<PosixSocketHandleItem>596634349e0SLoGin     fn posix_item(&self) -> Arc<PosixSocketHandleItem> {
597634349e0SLoGin         self.posix_item.clone()
598634349e0SLoGin     }
599634349e0SLoGin 
close(&mut self)600d623e902SGnoCiYeH     fn close(&mut self) {
601d623e902SGnoCiYeH         for handle in self.handles.iter() {
60237cef00bSSamuel Dai             {
603d623e902SGnoCiYeH                 let mut socket_set_guard = SOCKET_SET.lock_irqsave();
60437cef00bSSamuel Dai                 let smoltcp_handle = handle.smoltcp_handle().unwrap();
60537cef00bSSamuel Dai                 socket_set_guard
60637cef00bSSamuel Dai                     .get_mut::<smoltcp::socket::tcp::Socket>(smoltcp_handle)
60737cef00bSSamuel Dai                     .close();
608d623e902SGnoCiYeH                 drop(socket_set_guard);
609d623e902SGnoCiYeH             }
610d623e902SGnoCiYeH             poll_ifaces();
61137cef00bSSamuel Dai             SOCKET_SET
61237cef00bSSamuel Dai                 .lock_irqsave()
61337cef00bSSamuel Dai                 .remove(handle.smoltcp_handle().unwrap());
6142eab6dd7S曾俊             // debug!("[Socket] [TCP] Close: {:?}", handle);
61537cef00bSSamuel Dai         }
616d623e902SGnoCiYeH     }
617d623e902SGnoCiYeH 
read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint)6186046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
6196046f775S裕依         if HANDLE_MAP
6206046f775S裕依             .read_irqsave()
6216046f775S裕依             .get(&self.socket_handle())
6226046f775S裕依             .unwrap()
6236046f775S裕依             .shutdown_type()
6246046f775S裕依             .contains(ShutdownType::RCV_SHUTDOWN)
6256046f775S裕依         {
6266046f775S裕依             return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6276046f775S裕依         }
6282eab6dd7S曾俊         // debug!("tcp socket: read, buf len={}", buf.len());
6292eab6dd7S曾俊         // debug!("tcp socket:read, socket'len={}",self.handle.len());
6306046f775S裕依         loop {
6316046f775S裕依             poll_ifaces();
6326046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
633c719ddc6SSaga1718 
634d623e902SGnoCiYeH             let socket = socket_set_guard
635*bd70d2d1SLoGin                 .get_mut::<tcp::Socket>(self.handles.first().unwrap().smoltcp_handle().unwrap());
6366046f775S裕依 
6376046f775S裕依             // 如果socket已经关闭,返回错误
6386046f775S裕依             if !socket.is_active() {
6392eab6dd7S曾俊                 // debug!("Tcp Socket Read Error, socket is closed");
6406046f775S裕依                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6416046f775S裕依             }
6426046f775S裕依 
6436046f775S裕依             if socket.may_recv() {
644881ff6f9Syuyi2439                 match socket.recv_slice(buf) {
645881ff6f9Syuyi2439                     Ok(size) => {
6466046f775S裕依                         if size > 0 {
6476046f775S裕依                             let endpoint = if let Some(p) = socket.remote_endpoint() {
6486046f775S裕依                                 p
6496046f775S裕依                             } else {
6506046f775S裕依                                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6516046f775S裕依                             };
6526046f775S裕依 
6536046f775S裕依                             drop(socket_set_guard);
6546046f775S裕依                             poll_ifaces();
6556046f775S裕依                             return (Ok(size), Endpoint::Ip(Some(endpoint)));
6566046f775S裕依                         }
657881ff6f9Syuyi2439                     }
658881ff6f9Syuyi2439                     Err(tcp::RecvError::InvalidState) => {
6592eab6dd7S曾俊                         warn!("Tcp Socket Read Error, InvalidState");
6606046f775S裕依                         return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6616046f775S裕依                     }
662881ff6f9Syuyi2439                     Err(tcp::RecvError::Finished) => {
6636046f775S裕依                         // 对端写端已关闭,我们应该关闭读端
6646046f775S裕依                         HANDLE_MAP
6656046f775S裕依                             .write_irqsave()
6666046f775S裕依                             .get_mut(&self.socket_handle())
6676046f775S裕依                             .unwrap()
6686046f775S裕依                             .shutdown_type_writer()
6696046f775S裕依                             .insert(ShutdownType::RCV_SHUTDOWN);
6706046f775S裕依                         return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6716046f775S裕依                     }
6726046f775S裕依                 }
6736046f775S裕依             } else {
6746046f775S裕依                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6756046f775S裕依             }
6766046f775S裕依             drop(socket_set_guard);
677634349e0SLoGin             self.posix_item
678634349e0SLoGin                 .sleep((EPollEventType::EPOLLIN | EPollEventType::EPOLLHUP).bits() as u64);
6796046f775S裕依         }
6806046f775S裕依     }
6816046f775S裕依 
write(&self, buf: &[u8], _to: Option<Endpoint>) -> Result<usize, SystemError>6826046f775S裕依     fn write(&self, buf: &[u8], _to: Option<Endpoint>) -> Result<usize, SystemError> {
6836046f775S裕依         if HANDLE_MAP
6846046f775S裕依             .read_irqsave()
6856046f775S裕依             .get(&self.socket_handle())
6866046f775S裕依             .unwrap()
6876046f775S裕依             .shutdown_type()
6886046f775S裕依             .contains(ShutdownType::RCV_SHUTDOWN)
6896046f775S裕依         {
6906046f775S裕依             return Err(SystemError::ENOTCONN);
6916046f775S裕依         }
6922eab6dd7S曾俊         // debug!("tcp socket:write, socket'len={}",self.handle.len());
693c719ddc6SSaga1718 
6946046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
695c719ddc6SSaga1718 
696d623e902SGnoCiYeH         let socket = socket_set_guard
697*bd70d2d1SLoGin             .get_mut::<tcp::Socket>(self.handles.first().unwrap().smoltcp_handle().unwrap());
6986046f775S裕依 
6996046f775S裕依         if socket.is_open() {
7006046f775S裕依             if socket.can_send() {
7016046f775S裕依                 match socket.send_slice(buf) {
7026046f775S裕依                     Ok(size) => {
7036046f775S裕依                         drop(socket_set_guard);
7046046f775S裕依                         poll_ifaces();
7056046f775S裕依                         return Ok(size);
7066046f775S裕依                     }
7076046f775S裕依                     Err(e) => {
7082eab6dd7S曾俊                         error!("Tcp Socket Write Error {e:?}");
7096046f775S裕依                         return Err(SystemError::ENOBUFS);
7106046f775S裕依                     }
7116046f775S裕依                 }
7126046f775S裕依             } else {
7136046f775S裕依                 return Err(SystemError::ENOBUFS);
7146046f775S裕依             }
7156046f775S裕依         }
7166046f775S裕依 
7176046f775S裕依         return Err(SystemError::ENOTCONN);
7186046f775S裕依     }
7196046f775S裕依 
poll(&self) -> EPollEventType7206046f775S裕依     fn poll(&self) -> EPollEventType {
721634349e0SLoGin         // 处理listen的快速路径
722634349e0SLoGin         if self.is_listening {
723634349e0SLoGin             return self.tcp_poll_listening();
724634349e0SLoGin         }
725634349e0SLoGin         // 由于上面处理了listening状态,所以这里只处理非listening状态,这种情况下只有一个handle
726634349e0SLoGin 
727634349e0SLoGin         assert!(self.handles.len() == 1);
728634349e0SLoGin 
7296046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
7302eab6dd7S曾俊         // debug!("tcp socket:poll, socket'len={}",self.handle.len());
7316046f775S裕依 
732d623e902SGnoCiYeH         let socket = socket_set_guard
733*bd70d2d1SLoGin             .get_mut::<tcp::Socket>(self.handles.first().unwrap().smoltcp_handle().unwrap());
734634349e0SLoGin         let handle_map_guard = HANDLE_MAP.read_irqsave();
735634349e0SLoGin         let handle_item = handle_map_guard.get(&self.socket_handle()).unwrap();
736634349e0SLoGin         let shutdown_type = handle_item.shutdown_type();
737634349e0SLoGin         let is_posix_listen = handle_item.is_posix_listen;
738634349e0SLoGin         drop(handle_map_guard);
739634349e0SLoGin 
740634349e0SLoGin         return SocketPollMethod::tcp_poll(socket, shutdown_type, is_posix_listen);
7416046f775S裕依     }
7426046f775S裕依 
connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError>7436046f775S裕依     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
7446046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
745634349e0SLoGin         // debug!("tcp socket:connect, socket'len={}", self.handles.len());
746c719ddc6SSaga1718 
747d623e902SGnoCiYeH         let socket =
748*bd70d2d1SLoGin             sockets.get_mut::<tcp::Socket>(self.handles.first().unwrap().smoltcp_handle().unwrap());
7496046f775S裕依 
7506046f775S裕依         if let Endpoint::Ip(Some(ip)) = endpoint {
7516046f775S裕依             let temp_port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
7526046f775S裕依             // 检测端口是否被占用
75337cef00bSSamuel Dai             PORT_MANAGER.bind_port(self.metadata.socket_type, temp_port)?;
7546046f775S裕依 
7552eab6dd7S曾俊             // debug!("temp_port: {}", temp_port);
756e32effb1SLoGin             let iface: Arc<dyn NetDevice> = NET_DEVICES.write_irqsave().get(&0).unwrap().clone();
7576046f775S裕依             let mut inner_iface = iface.inner_iface().lock();
7582eab6dd7S曾俊             // debug!("to connect: {ip:?}");
7596046f775S裕依 
7606046f775S裕依             match socket.connect(inner_iface.context(), ip, temp_port) {
7616046f775S裕依                 Ok(()) => {
7626046f775S裕依                     // avoid deadlock
7636046f775S裕依                     drop(inner_iface);
7646046f775S裕依                     drop(iface);
7656046f775S裕依                     drop(sockets);
7666046f775S裕依                     loop {
7676046f775S裕依                         poll_ifaces();
7686046f775S裕依                         let mut sockets = SOCKET_SET.lock_irqsave();
769d623e902SGnoCiYeH                         let socket = sockets.get_mut::<tcp::Socket>(
770*bd70d2d1SLoGin                             self.handles.first().unwrap().smoltcp_handle().unwrap(),
771d623e902SGnoCiYeH                         );
7726046f775S裕依 
7736046f775S裕依                         match socket.state() {
7746046f775S裕依                             tcp::State::Established => {
7756046f775S裕依                                 return Ok(());
7766046f775S裕依                             }
7776046f775S裕依                             tcp::State::SynSent => {
7786046f775S裕依                                 drop(sockets);
779634349e0SLoGin                                 self.posix_item.sleep(Self::CAN_CONNECT);
7806046f775S裕依                             }
7816046f775S裕依                             _ => {
7826046f775S裕依                                 return Err(SystemError::ECONNREFUSED);
7836046f775S裕依                             }
7846046f775S裕依                         }
7856046f775S裕依                     }
7866046f775S裕依                 }
7876046f775S裕依                 Err(e) => {
7882eab6dd7S曾俊                     // error!("Tcp Socket Connect Error {e:?}");
7896046f775S裕依                     match e {
7906046f775S裕依                         tcp::ConnectError::InvalidState => return Err(SystemError::EISCONN),
7916046f775S裕依                         tcp::ConnectError::Unaddressable => return Err(SystemError::EADDRNOTAVAIL),
7926046f775S裕依                     }
7936046f775S裕依                 }
7946046f775S裕依             }
7956046f775S裕依         } else {
7966046f775S裕依             return Err(SystemError::EINVAL);
7976046f775S裕依         }
7986046f775S裕依     }
7996046f775S裕依 
8006046f775S裕依     /// @brief tcp socket 监听 local_endpoint 端口
8016046f775S裕依     ///
80237cef00bSSamuel Dai     /// @param backlog 未处理的连接队列的最大长度
listen(&mut self, backlog: usize) -> Result<(), SystemError>803c719ddc6SSaga1718     fn listen(&mut self, backlog: usize) -> Result<(), SystemError> {
8046046f775S裕依         if self.is_listening {
8056046f775S裕依             return Ok(());
8066046f775S裕依         }
8076046f775S裕依 
808634349e0SLoGin         // debug!(
809634349e0SLoGin         //     "tcp socket:listen, socket'len={}, backlog = {backlog}",
810634349e0SLoGin         //     self.handles.len()
811634349e0SLoGin         // );
812634349e0SLoGin 
8136046f775S裕依         let local_endpoint = self.local_endpoint.ok_or(SystemError::EINVAL)?;
8146046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
815c719ddc6SSaga1718         // 获取handle的数量
816c719ddc6SSaga1718         let handlen = self.handles.len();
817c719ddc6SSaga1718         let backlog = handlen.max(backlog);
8186046f775S裕依 
819c719ddc6SSaga1718         // 添加剩余需要构建的socket
8202eab6dd7S曾俊         // debug!("tcp socket:before listen, socket'len={}", self.handle_list.len());
821c719ddc6SSaga1718         let mut handle_guard = HANDLE_MAP.write_irqsave();
822634349e0SLoGin         let socket_handle_item_0 = handle_guard.get_mut(&self.socket_handle()).unwrap();
823634349e0SLoGin         socket_handle_item_0.is_posix_listen = true;
82437cef00bSSamuel Dai 
825c719ddc6SSaga1718         self.handles.extend((handlen..backlog).map(|_| {
826c719ddc6SSaga1718             let socket = Self::create_new_socket();
827d623e902SGnoCiYeH             let handle = GlobalSocketHandle::new_smoltcp_handle(sockets.add(socket));
828634349e0SLoGin             let mut handle_item = SocketHandleItem::new(Arc::downgrade(&self.posix_item));
829634349e0SLoGin             handle_item.is_posix_listen = true;
830d623e902SGnoCiYeH             handle_guard.insert(handle, handle_item);
831c719ddc6SSaga1718             handle
832c719ddc6SSaga1718         }));
833634349e0SLoGin 
834634349e0SLoGin         // debug!("tcp socket:listen, socket'len={}", self.handles.len());
8352eab6dd7S曾俊         // debug!("tcp socket:listen, backlog={backlog}");
836c719ddc6SSaga1718 
837c719ddc6SSaga1718         // 监听所有的socket
838c719ddc6SSaga1718         for i in 0..backlog {
839c719ddc6SSaga1718             let handle = self.handles.get(i).unwrap();
840c719ddc6SSaga1718 
841d623e902SGnoCiYeH             let socket = sockets.get_mut::<tcp::Socket>(handle.smoltcp_handle().unwrap());
842c719ddc6SSaga1718 
843c719ddc6SSaga1718             if !socket.is_listening() {
8442eab6dd7S曾俊                 // debug!("Tcp Socket is already listening on {local_endpoint}");
845c719ddc6SSaga1718                 self.do_listen(socket, local_endpoint)?;
8466046f775S裕依             }
8472eab6dd7S曾俊             // debug!("Tcp Socket  before listen, open={}", socket.is_open());
848c719ddc6SSaga1718         }
849634349e0SLoGin 
850c719ddc6SSaga1718         return Ok(());
8516046f775S裕依     }
8526046f775S裕依 
bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError>8536046f775S裕依     fn bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
8546046f775S裕依         if let Endpoint::Ip(Some(mut ip)) = endpoint {
8556046f775S裕依             if ip.port == 0 {
8566046f775S裕依                 ip.port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
8576046f775S裕依             }
8586046f775S裕依 
8596046f775S裕依             // 检测端口是否已被占用
86037cef00bSSamuel Dai             PORT_MANAGER.bind_port(self.metadata.socket_type, ip.port)?;
8612eab6dd7S曾俊             // debug!("tcp socket:bind, socket'len={}",self.handle.len());
8626046f775S裕依 
8636046f775S裕依             self.local_endpoint = Some(ip);
8646046f775S裕依             self.is_listening = false;
865634349e0SLoGin 
8666046f775S裕依             return Ok(());
8676046f775S裕依         }
8686046f775S裕依         return Err(SystemError::EINVAL);
8696046f775S裕依     }
8706046f775S裕依 
shutdown(&mut self, shutdown_type: super::ShutdownType) -> Result<(), SystemError>8716046f775S裕依     fn shutdown(&mut self, shutdown_type: super::ShutdownType) -> Result<(), SystemError> {
8726046f775S裕依         // TODO:目前只是在表层判断,对端不知晓,后续需使用tcp实现
8736046f775S裕依         HANDLE_MAP
8746046f775S裕依             .write_irqsave()
8756046f775S裕依             .get_mut(&self.socket_handle())
8766046f775S裕依             .unwrap()
8776046f775S裕依             .shutdown_type = RwLock::new(shutdown_type);
8786046f775S裕依         return Ok(());
8796046f775S裕依     }
8806046f775S裕依 
accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError>8816046f775S裕依     fn accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError> {
88237cef00bSSamuel Dai         if !self.is_listening {
88337cef00bSSamuel Dai             return Err(SystemError::EINVAL);
88437cef00bSSamuel Dai         }
8856046f775S裕依         let endpoint = self.local_endpoint.ok_or(SystemError::EINVAL)?;
8866046f775S裕依         loop {
8872eab6dd7S曾俊             // debug!("tcp accept: poll_ifaces()");
8886046f775S裕依             poll_ifaces();
8892eab6dd7S曾俊             // debug!("tcp socket:accept, socket'len={}", self.handle_list.len());
8906046f775S裕依 
89137cef00bSSamuel Dai             let mut sockset = SOCKET_SET.lock_irqsave();
89237cef00bSSamuel Dai             // Get the corresponding activated handler
89337cef00bSSamuel Dai             let global_handle_index = self.handles.iter().position(|handle| {
89437cef00bSSamuel Dai                 let con_smol_sock = sockset.get::<tcp::Socket>(handle.smoltcp_handle().unwrap());
89537cef00bSSamuel Dai                 con_smol_sock.is_active()
89637cef00bSSamuel Dai             });
8976046f775S裕依 
89837cef00bSSamuel Dai             if let Some(handle_index) = global_handle_index {
89937cef00bSSamuel Dai                 let con_smol_sock = sockset
90037cef00bSSamuel Dai                     .get::<tcp::Socket>(self.handles[handle_index].smoltcp_handle().unwrap());
9016046f775S裕依 
9022eab6dd7S曾俊                 // debug!("[Socket] [TCP] Accept: {:?}", handle);
90337cef00bSSamuel Dai                 // handle is connected socket's handle
90437cef00bSSamuel Dai                 let remote_ep = con_smol_sock
90537cef00bSSamuel Dai                     .remote_endpoint()
90637cef00bSSamuel Dai                     .ok_or(SystemError::ENOTCONN)?;
9076046f775S裕依 
908634349e0SLoGin                 let tcp_socket = Self::create_new_socket();
9096046f775S裕依 
91037cef00bSSamuel Dai                 let new_handle = GlobalSocketHandle::new_smoltcp_handle(sockset.add(tcp_socket));
9116046f775S裕依 
91237cef00bSSamuel Dai                 // let handle in TcpSock be the new empty handle, and return the old connected handle
91337cef00bSSamuel Dai                 let old_handle = core::mem::replace(&mut self.handles[handle_index], new_handle);
9146046f775S裕依 
9156046f775S裕依                 let metadata = SocketMetadata::new(
9166046f775S裕依                     SocketType::Tcp,
9176046f775S裕依                     Self::DEFAULT_TX_BUF_SIZE,
9186046f775S裕依                     Self::DEFAULT_RX_BUF_SIZE,
9196046f775S裕依                     Self::DEFAULT_METADATA_BUF_SIZE,
9206046f775S裕依                     self.metadata.options,
9216046f775S裕依                 );
9226046f775S裕依 
92337cef00bSSamuel Dai                 let sock_ret = Box::new(TcpSocket {
924d623e902SGnoCiYeH                     handles: vec![old_handle],
9256046f775S裕依                     local_endpoint: self.local_endpoint,
9266046f775S裕依                     is_listening: false,
9276046f775S裕依                     metadata,
928634349e0SLoGin                     posix_item: Arc::new(PosixSocketHandleItem::new(None)),
9296046f775S裕依                 });
930c719ddc6SSaga1718 
93137cef00bSSamuel Dai                 {
9326046f775S裕依                     let mut handle_guard = HANDLE_MAP.write_irqsave();
9336046f775S裕依                     // 先删除原来的
934d623e902SGnoCiYeH                     let item = handle_guard.remove(&old_handle).unwrap();
935634349e0SLoGin                     item.reset_shutdown_type();
936634349e0SLoGin                     assert!(item.is_posix_listen);
937c719ddc6SSaga1718 
9386046f775S裕依                     // 按照smoltcp行为,将新的handle绑定到原来的item
939634349e0SLoGin                     let new_item = SocketHandleItem::new(Arc::downgrade(&sock_ret.posix_item));
940d623e902SGnoCiYeH                     handle_guard.insert(old_handle, new_item);
94137cef00bSSamuel Dai                     // 插入新的item
94237cef00bSSamuel Dai                     handle_guard.insert(new_handle, item);
943634349e0SLoGin 
944634349e0SLoGin                     let socket = sockset.get_mut::<tcp::Socket>(
945634349e0SLoGin                         self.handles[handle_index].smoltcp_handle().unwrap(),
946634349e0SLoGin                     );
947634349e0SLoGin 
948634349e0SLoGin                     if !socket.is_listening() {
949634349e0SLoGin                         self.do_listen(socket, endpoint)?;
950634349e0SLoGin                     }
951634349e0SLoGin 
95237cef00bSSamuel Dai                     drop(handle_guard);
9536046f775S裕依                 }
954634349e0SLoGin 
95537cef00bSSamuel Dai                 return Ok((sock_ret, Endpoint::Ip(Some(remote_ep))));
956d623e902SGnoCiYeH             }
9576046f775S裕依 
95837cef00bSSamuel Dai             drop(sockset);
95937cef00bSSamuel Dai 
960*bd70d2d1SLoGin             // debug!("[TCP] [Accept] sleeping socket with handle: {:?}", self.handles.first().unwrap().smoltcp_handle().unwrap());
961634349e0SLoGin             self.posix_item.sleep(Self::CAN_ACCPET);
9622eab6dd7S曾俊             // debug!("tcp socket:after sleep, handle_guard'len={}",HANDLE_MAP.write_irqsave().len());
9636046f775S裕依         }
9646046f775S裕依     }
9656046f775S裕依 
endpoint(&self) -> Option<Endpoint>9666046f775S裕依     fn endpoint(&self) -> Option<Endpoint> {
9676046f775S裕依         let mut result: Option<Endpoint> = self.local_endpoint.map(|x| Endpoint::Ip(Some(x)));
9686046f775S裕依 
9696046f775S裕依         if result.is_none() {
9706046f775S裕依             let sockets = SOCKET_SET.lock_irqsave();
9712eab6dd7S曾俊             // debug!("tcp socket:endpoint, socket'len={}",self.handle.len());
972c719ddc6SSaga1718 
973d623e902SGnoCiYeH             let socket =
974*bd70d2d1SLoGin                 sockets.get::<tcp::Socket>(self.handles.first().unwrap().smoltcp_handle().unwrap());
9756046f775S裕依             if let Some(ep) = socket.local_endpoint() {
9766046f775S裕依                 result = Some(Endpoint::Ip(Some(ep)));
9776046f775S裕依             }
9786046f775S裕依         }
9796046f775S裕依         return result;
9806046f775S裕依     }
9816046f775S裕依 
peer_endpoint(&self) -> Option<Endpoint>9826046f775S裕依     fn peer_endpoint(&self) -> Option<Endpoint> {
9836046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
9842eab6dd7S曾俊         // debug!("tcp socket:peer_endpoint, socket'len={}",self.handle.len());
985c719ddc6SSaga1718 
986d623e902SGnoCiYeH         let socket =
987*bd70d2d1SLoGin             sockets.get::<tcp::Socket>(self.handles.first().unwrap().smoltcp_handle().unwrap());
9886046f775S裕依         return socket.remote_endpoint().map(|x| Endpoint::Ip(Some(x)));
9896046f775S裕依     }
9906046f775S裕依 
metadata(&self) -> SocketMetadata9916046f775S裕依     fn metadata(&self) -> SocketMetadata {
9926046f775S裕依         self.metadata.clone()
9936046f775S裕依     }
9946046f775S裕依 
box_clone(&self) -> Box<dyn Socket>9956046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
9966046f775S裕依         Box::new(self.clone())
9976046f775S裕依     }
9986046f775S裕依 
socket_handle(&self) -> GlobalSocketHandle999d623e902SGnoCiYeH     fn socket_handle(&self) -> GlobalSocketHandle {
10002eab6dd7S曾俊         // debug!("tcp socket:socket_handle, socket'len={}",self.handle.len());
1001c719ddc6SSaga1718 
1002*bd70d2d1SLoGin         *self.handles.first().unwrap()
10036046f775S裕依     }
10046046f775S裕依 
as_any_ref(&self) -> &dyn core::any::Any10056046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
10066046f775S裕依         self
10076046f775S裕依     }
10086046f775S裕依 
as_any_mut(&mut self) -> &mut dyn core::any::Any10096046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
10106046f775S裕依         self
10116046f775S裕依     }
10126046f775S裕依 }
1013