xref: /DragonOS/kernel/src/net/socket/inet.rs (revision 2eab6dd743e94a86a685f1f3c01e599adf86610a)
16046f775S裕依 use alloc::{boxed::Box, sync::Arc, vec::Vec};
2*2eab6dd7S曾俊 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::{
19d623e902SGnoCiYeH     handle::GlobalSocketHandle, Socket, SocketHandleItem, SocketMetadata, SocketOptions,
20d623e902SGnoCiYeH     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,
356046f775S裕依 }
366046f775S裕依 
376046f775S裕依 impl RawSocket {
386046f775S裕依     /// 元数据的缓冲区的大小
396046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
406046f775S裕依     /// 默认的接收缓冲区的大小 receive
416046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 64 * 1024;
426046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
436046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 64 * 1024;
446046f775S裕依 
456046f775S裕依     /// @brief 创建一个原始的socket
466046f775S裕依     ///
476046f775S裕依     /// @param protocol 协议号
486046f775S裕依     /// @param options socket的选项
496046f775S裕依     ///
506046f775S裕依     /// @return 返回创建的原始的socket
516046f775S裕依     pub fn new(protocol: Protocol, options: SocketOptions) -> Self {
526046f775S裕依         let rx_buffer = raw::PacketBuffer::new(
536046f775S裕依             vec![raw::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
546046f775S裕依             vec![0; Self::DEFAULT_RX_BUF_SIZE],
556046f775S裕依         );
566046f775S裕依         let tx_buffer = raw::PacketBuffer::new(
576046f775S裕依             vec![raw::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
586046f775S裕依             vec![0; Self::DEFAULT_TX_BUF_SIZE],
596046f775S裕依         );
606046f775S裕依         let protocol: u8 = protocol.into();
616046f775S裕依         let socket = raw::Socket::new(
626046f775S裕依             wire::IpVersion::Ipv4,
636046f775S裕依             wire::IpProtocol::from(protocol),
646046f775S裕依             rx_buffer,
656046f775S裕依             tx_buffer,
666046f775S裕依         );
676046f775S裕依 
686046f775S裕依         // 把socket添加到socket集合中,并得到socket的句柄
69d623e902SGnoCiYeH         let handle = GlobalSocketHandle::new_smoltcp_handle(SOCKET_SET.lock_irqsave().add(socket));
706046f775S裕依 
716046f775S裕依         let metadata = SocketMetadata::new(
726046f775S裕依             SocketType::Raw,
736046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
746046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
756046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
766046f775S裕依             options,
776046f775S裕依         );
786046f775S裕依 
796046f775S裕依         return Self {
806046f775S裕依             handle,
816046f775S裕依             header_included: false,
826046f775S裕依             metadata,
836046f775S裕依         };
846046f775S裕依     }
856046f775S裕依 }
866046f775S裕依 
876046f775S裕依 impl Socket for RawSocket {
88d623e902SGnoCiYeH     fn close(&mut self) {
89d623e902SGnoCiYeH         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
9037cef00bSSamuel Dai         if let smoltcp::socket::Socket::Udp(mut sock) =
9137cef00bSSamuel Dai             socket_set_guard.remove(self.handle.smoltcp_handle().unwrap())
9237cef00bSSamuel Dai         {
9337cef00bSSamuel Dai             sock.close();
9437cef00bSSamuel Dai         }
95d623e902SGnoCiYeH         drop(socket_set_guard);
96d623e902SGnoCiYeH         poll_ifaces();
97d623e902SGnoCiYeH     }
98d623e902SGnoCiYeH 
996046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
1006046f775S裕依         poll_ifaces();
1016046f775S裕依         loop {
1026046f775S裕依             // 如何优化这里?
1036046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
104d623e902SGnoCiYeH             let socket =
105d623e902SGnoCiYeH                 socket_set_guard.get_mut::<raw::Socket>(self.handle.smoltcp_handle().unwrap());
1066046f775S裕依 
1076046f775S裕依             match socket.recv_slice(buf) {
1086046f775S裕依                 Ok(len) => {
1096046f775S裕依                     let packet = wire::Ipv4Packet::new_unchecked(buf);
1106046f775S裕依                     return (
1116046f775S裕依                         Ok(len),
1126046f775S裕依                         Endpoint::Ip(Some(wire::IpEndpoint {
1136046f775S裕依                             addr: wire::IpAddress::Ipv4(packet.src_addr()),
1146046f775S裕依                             port: 0,
1156046f775S裕依                         })),
1166046f775S裕依                     );
1176046f775S裕依                 }
118881ff6f9Syuyi2439                 Err(_) => {
1196046f775S裕依                     if !self.metadata.options.contains(SocketOptions::BLOCK) {
1206046f775S裕依                         // 如果是非阻塞的socket,就返回错误
1216046f775S裕依                         return (Err(SystemError::EAGAIN_OR_EWOULDBLOCK), Endpoint::Ip(None));
1226046f775S裕依                     }
1236046f775S裕依                 }
1246046f775S裕依             }
1256046f775S裕依             drop(socket_set_guard);
1266046f775S裕依             SocketHandleItem::sleep(
1276046f775S裕依                 self.socket_handle(),
1286046f775S裕依                 EPollEventType::EPOLLIN.bits() as u64,
1296046f775S裕依                 HANDLE_MAP.read_irqsave(),
1306046f775S裕依             );
1316046f775S裕依         }
1326046f775S裕依     }
1336046f775S裕依 
1346046f775S裕依     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError> {
1356046f775S裕依         // 如果用户发送的数据包,包含IP头,则直接发送
1366046f775S裕依         if self.header_included {
1376046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
138d623e902SGnoCiYeH             let socket =
139d623e902SGnoCiYeH                 socket_set_guard.get_mut::<raw::Socket>(self.handle.smoltcp_handle().unwrap());
1406046f775S裕依             match socket.send_slice(buf) {
1416046f775S裕依                 Ok(_) => {
1426046f775S裕依                     return Ok(buf.len());
1436046f775S裕依                 }
1446046f775S裕依                 Err(raw::SendError::BufferFull) => {
1456046f775S裕依                     return Err(SystemError::ENOBUFS);
1466046f775S裕依                 }
1476046f775S裕依             }
1486046f775S裕依         } else {
1496046f775S裕依             // 如果用户发送的数据包,不包含IP头,则需要自己构造IP头
1506046f775S裕依 
1516046f775S裕依             if let Some(Endpoint::Ip(Some(endpoint))) = to {
1526046f775S裕依                 let mut socket_set_guard = SOCKET_SET.lock_irqsave();
1536046f775S裕依                 let socket: &mut raw::Socket =
154d623e902SGnoCiYeH                     socket_set_guard.get_mut::<raw::Socket>(self.handle.smoltcp_handle().unwrap());
1556046f775S裕依 
1566046f775S裕依                 // 暴力解决方案:只考虑0号网卡。 TODO:考虑多网卡的情况!!!
157e32effb1SLoGin                 let iface = NET_DEVICES.read_irqsave().get(&0).unwrap().clone();
1586046f775S裕依 
1596046f775S裕依                 // 构造IP头
1606046f775S裕依                 let ipv4_src_addr: Option<wire::Ipv4Address> =
1616046f775S裕依                     iface.inner_iface().lock().ipv4_addr();
1626046f775S裕依                 if ipv4_src_addr.is_none() {
1636046f775S裕依                     return Err(SystemError::ENETUNREACH);
1646046f775S裕依                 }
1656046f775S裕依                 let ipv4_src_addr = ipv4_src_addr.unwrap();
1666046f775S裕依 
1676046f775S裕依                 if let wire::IpAddress::Ipv4(ipv4_dst) = endpoint.addr {
1686046f775S裕依                     let len = buf.len();
1696046f775S裕依 
1706046f775S裕依                     // 创建20字节的IPv4头部
1716046f775S裕依                     let mut buffer: Vec<u8> = vec![0u8; len + 20];
1726046f775S裕依                     let mut packet: wire::Ipv4Packet<&mut Vec<u8>> =
1736046f775S裕依                         wire::Ipv4Packet::new_unchecked(&mut buffer);
1746046f775S裕依 
1756046f775S裕依                     // 封装ipv4 header
1766046f775S裕依                     packet.set_version(4);
1776046f775S裕依                     packet.set_header_len(20);
1786046f775S裕依                     packet.set_total_len((20 + len) as u16);
1796046f775S裕依                     packet.set_src_addr(ipv4_src_addr);
1806046f775S裕依                     packet.set_dst_addr(ipv4_dst);
1816046f775S裕依 
1826046f775S裕依                     // 设置ipv4 header的protocol字段
1836046f775S裕依                     packet.set_next_header(socket.ip_protocol());
1846046f775S裕依 
1856046f775S裕依                     // 获取IP数据包的负载字段
1866046f775S裕依                     let payload: &mut [u8] = packet.payload_mut();
1876046f775S裕依                     payload.copy_from_slice(buf);
1886046f775S裕依 
1896046f775S裕依                     // 填充checksum字段
1906046f775S裕依                     packet.fill_checksum();
1916046f775S裕依 
1926046f775S裕依                     // 发送数据包
1936046f775S裕依                     socket.send_slice(&buffer).unwrap();
1946046f775S裕依 
1956046f775S裕依                     iface.poll(&mut socket_set_guard).ok();
1966046f775S裕依 
1976046f775S裕依                     drop(socket_set_guard);
1986046f775S裕依                     return Ok(len);
1996046f775S裕依                 } else {
200*2eab6dd7S曾俊                     warn!("Unsupport Ip protocol type!");
2016046f775S裕依                     return Err(SystemError::EINVAL);
2026046f775S裕依                 }
2036046f775S裕依             } else {
2046046f775S裕依                 // 如果没有指定目的地址,则返回错误
2056046f775S裕依                 return Err(SystemError::ENOTCONN);
2066046f775S裕依             }
2076046f775S裕依         }
2086046f775S裕依     }
2096046f775S裕依 
2106046f775S裕依     fn connect(&mut self, _endpoint: Endpoint) -> Result<(), SystemError> {
2116046f775S裕依         Ok(())
2126046f775S裕依     }
2136046f775S裕依 
2146046f775S裕依     fn metadata(&self) -> SocketMetadata {
2156046f775S裕依         self.metadata.clone()
2166046f775S裕依     }
2176046f775S裕依 
2186046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
2196046f775S裕依         Box::new(self.clone())
2206046f775S裕依     }
2216046f775S裕依 
222d623e902SGnoCiYeH     fn socket_handle(&self) -> GlobalSocketHandle {
223d623e902SGnoCiYeH         self.handle
2246046f775S裕依     }
2256046f775S裕依 
2266046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
2276046f775S裕依         self
2286046f775S裕依     }
2296046f775S裕依 
2306046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
2316046f775S裕依         self
2326046f775S裕依     }
2336046f775S裕依 }
2346046f775S裕依 
2356046f775S裕依 /// @brief 表示udp socket
2366046f775S裕依 ///
2376046f775S裕依 /// https://man7.org/linux/man-pages/man7/udp.7.html
2386046f775S裕依 #[derive(Debug, Clone)]
2396046f775S裕依 pub struct UdpSocket {
240d623e902SGnoCiYeH     pub handle: GlobalSocketHandle,
2416046f775S裕依     remote_endpoint: Option<Endpoint>, // 记录远程endpoint提供给connect(), 应该使用IP地址。
2426046f775S裕依     metadata: SocketMetadata,
2436046f775S裕依 }
2446046f775S裕依 
2456046f775S裕依 impl UdpSocket {
2466046f775S裕依     /// 元数据的缓冲区的大小
2476046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
2486046f775S裕依     /// 默认的接收缓冲区的大小 receive
2496046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 64 * 1024;
2506046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
2516046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 64 * 1024;
2526046f775S裕依 
2536046f775S裕依     /// @brief 创建一个udp的socket
2546046f775S裕依     ///
2556046f775S裕依     /// @param options socket的选项
2566046f775S裕依     ///
2576046f775S裕依     /// @return 返回创建的udp的socket
2586046f775S裕依     pub fn new(options: SocketOptions) -> Self {
2596046f775S裕依         let rx_buffer = udp::PacketBuffer::new(
2606046f775S裕依             vec![udp::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
2616046f775S裕依             vec![0; Self::DEFAULT_RX_BUF_SIZE],
2626046f775S裕依         );
2636046f775S裕依         let tx_buffer = udp::PacketBuffer::new(
2646046f775S裕依             vec![udp::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
2656046f775S裕依             vec![0; Self::DEFAULT_TX_BUF_SIZE],
2666046f775S裕依         );
2676046f775S裕依         let socket = udp::Socket::new(rx_buffer, tx_buffer);
2686046f775S裕依 
2696046f775S裕依         // 把socket添加到socket集合中,并得到socket的句柄
270d623e902SGnoCiYeH         let handle: GlobalSocketHandle =
271d623e902SGnoCiYeH             GlobalSocketHandle::new_smoltcp_handle(SOCKET_SET.lock_irqsave().add(socket));
2726046f775S裕依 
2736046f775S裕依         let metadata = SocketMetadata::new(
2746046f775S裕依             SocketType::Udp,
2756046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
2766046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
2776046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
2786046f775S裕依             options,
2796046f775S裕依         );
2806046f775S裕依 
2816046f775S裕依         return Self {
2826046f775S裕依             handle,
2836046f775S裕依             remote_endpoint: None,
2846046f775S裕依             metadata,
2856046f775S裕依         };
2866046f775S裕依     }
2876046f775S裕依 
2886046f775S裕依     fn do_bind(&self, socket: &mut udp::Socket, endpoint: Endpoint) -> Result<(), SystemError> {
2899d9a0984Ssun5etop         if let Endpoint::Ip(Some(mut ip)) = endpoint {
2909d9a0984Ssun5etop             // 端口为0则分配随机端口
2919d9a0984Ssun5etop             if ip.port == 0 {
2929d9a0984Ssun5etop                 ip.port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
2939d9a0984Ssun5etop             }
2946046f775S裕依             // 检测端口是否已被占用
29537cef00bSSamuel Dai             PORT_MANAGER.bind_port(self.metadata.socket_type, ip.port)?;
2966046f775S裕依 
2976046f775S裕依             let bind_res = if ip.addr.is_unspecified() {
2986046f775S裕依                 socket.bind(ip.port)
2996046f775S裕依             } else {
3006046f775S裕依                 socket.bind(ip)
3016046f775S裕依             };
3026046f775S裕依 
3036046f775S裕依             match bind_res {
3046046f775S裕依                 Ok(()) => return Ok(()),
3056046f775S裕依                 Err(_) => return Err(SystemError::EINVAL),
3066046f775S裕依             }
3076046f775S裕依         } else {
3086046f775S裕依             return Err(SystemError::EINVAL);
3096046f775S裕依         }
3106046f775S裕依     }
3116046f775S裕依 }
3126046f775S裕依 
3136046f775S裕依 impl Socket for UdpSocket {
314d623e902SGnoCiYeH     fn close(&mut self) {
315d623e902SGnoCiYeH         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
31637cef00bSSamuel Dai         if let smoltcp::socket::Socket::Udp(mut sock) =
31737cef00bSSamuel Dai             socket_set_guard.remove(self.handle.smoltcp_handle().unwrap())
31837cef00bSSamuel Dai         {
31937cef00bSSamuel Dai             sock.close();
32037cef00bSSamuel Dai         }
321d623e902SGnoCiYeH         drop(socket_set_guard);
322d623e902SGnoCiYeH         poll_ifaces();
323d623e902SGnoCiYeH     }
324d623e902SGnoCiYeH 
3256046f775S裕依     /// @brief 在read函数执行之前,请先bind到本地的指定端口
3266046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
3276046f775S裕依         loop {
328*2eab6dd7S曾俊             // debug!("Wait22 to Read");
3296046f775S裕依             poll_ifaces();
3306046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
331d623e902SGnoCiYeH             let socket =
332d623e902SGnoCiYeH                 socket_set_guard.get_mut::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
3336046f775S裕依 
334*2eab6dd7S曾俊             // debug!("Wait to Read");
3356046f775S裕依 
3366046f775S裕依             if socket.can_recv() {
337881ff6f9Syuyi2439                 if let Ok((size, metadata)) = socket.recv_slice(buf) {
3386046f775S裕依                     drop(socket_set_guard);
3396046f775S裕依                     poll_ifaces();
340881ff6f9Syuyi2439                     return (Ok(size), Endpoint::Ip(Some(metadata.endpoint)));
3416046f775S裕依                 }
3426046f775S裕依             } else {
3436046f775S裕依                 // 如果socket没有连接,则忙等
3446046f775S裕依                 // return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
3456046f775S裕依             }
3466046f775S裕依             drop(socket_set_guard);
3476046f775S裕依             SocketHandleItem::sleep(
3486046f775S裕依                 self.socket_handle(),
3496046f775S裕依                 EPollEventType::EPOLLIN.bits() as u64,
3506046f775S裕依                 HANDLE_MAP.read_irqsave(),
3516046f775S裕依             );
3526046f775S裕依         }
3536046f775S裕依     }
3546046f775S裕依 
3556046f775S裕依     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError> {
356*2eab6dd7S曾俊         // debug!("udp to send: {:?}, len={}", to, buf.len());
3576046f775S裕依         let remote_endpoint: &wire::IpEndpoint = {
3586046f775S裕依             if let Some(Endpoint::Ip(Some(ref endpoint))) = to {
3596046f775S裕依                 endpoint
3606046f775S裕依             } else if let Some(Endpoint::Ip(Some(ref endpoint))) = self.remote_endpoint {
3616046f775S裕依                 endpoint
3626046f775S裕依             } else {
3636046f775S裕依                 return Err(SystemError::ENOTCONN);
3646046f775S裕依             }
3656046f775S裕依         };
366*2eab6dd7S曾俊         // debug!("udp write: remote = {:?}", remote_endpoint);
3676046f775S裕依 
3686046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
369d623e902SGnoCiYeH         let socket = socket_set_guard.get_mut::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
370*2eab6dd7S曾俊         // debug!("is open()={}", socket.is_open());
371*2eab6dd7S曾俊         // debug!("socket endpoint={:?}", socket.endpoint());
3726046f775S裕依         if socket.can_send() {
373*2eab6dd7S曾俊             // debug!("udp write: can send");
3746046f775S裕依             match socket.send_slice(buf, *remote_endpoint) {
3756046f775S裕依                 Ok(()) => {
376*2eab6dd7S曾俊                     // debug!("udp write: send ok");
3776046f775S裕依                     drop(socket_set_guard);
3786046f775S裕依                     poll_ifaces();
3796046f775S裕依                     return Ok(buf.len());
3806046f775S裕依                 }
3816046f775S裕依                 Err(_) => {
382*2eab6dd7S曾俊                     // debug!("udp write: send err");
3836046f775S裕依                     return Err(SystemError::ENOBUFS);
3846046f775S裕依                 }
3856046f775S裕依             }
3866046f775S裕依         } else {
387*2eab6dd7S曾俊             // debug!("udp write: can not send");
3886046f775S裕依             return Err(SystemError::ENOBUFS);
3896046f775S裕依         };
3906046f775S裕依     }
3916046f775S裕依 
3926046f775S裕依     fn bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
3936046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
394d623e902SGnoCiYeH         let socket = sockets.get_mut::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
395*2eab6dd7S曾俊         // debug!("UDP Bind to {:?}", endpoint);
3966046f775S裕依         return self.do_bind(socket, endpoint);
3976046f775S裕依     }
3986046f775S裕依 
3996046f775S裕依     fn poll(&self) -> EPollEventType {
4006046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
401d623e902SGnoCiYeH         let socket = sockets.get::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
4026046f775S裕依 
4036046f775S裕依         return SocketPollMethod::udp_poll(
4046046f775S裕依             socket,
4056046f775S裕依             HANDLE_MAP
4066046f775S裕依                 .read_irqsave()
4076046f775S裕依                 .get(&self.socket_handle())
4086046f775S裕依                 .unwrap()
4096046f775S裕依                 .shutdown_type(),
4106046f775S裕依         );
4116046f775S裕依     }
4126046f775S裕依 
4136046f775S裕依     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
4146046f775S裕依         if let Endpoint::Ip(_) = endpoint {
4156046f775S裕依             self.remote_endpoint = Some(endpoint);
4166046f775S裕依             Ok(())
4176046f775S裕依         } else {
4186046f775S裕依             Err(SystemError::EINVAL)
4196046f775S裕依         }
4206046f775S裕依     }
4216046f775S裕依 
4226046f775S裕依     fn ioctl(
4236046f775S裕依         &self,
4246046f775S裕依         _cmd: usize,
4256046f775S裕依         _arg0: usize,
4266046f775S裕依         _arg1: usize,
4276046f775S裕依         _arg2: usize,
4286046f775S裕依     ) -> Result<usize, SystemError> {
4296046f775S裕依         todo!()
4306046f775S裕依     }
4316046f775S裕依 
4326046f775S裕依     fn metadata(&self) -> SocketMetadata {
4336046f775S裕依         self.metadata.clone()
4346046f775S裕依     }
4356046f775S裕依 
4366046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
4376046f775S裕依         return Box::new(self.clone());
4386046f775S裕依     }
4396046f775S裕依 
4406046f775S裕依     fn endpoint(&self) -> Option<Endpoint> {
4416046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
442d623e902SGnoCiYeH         let socket = sockets.get::<udp::Socket>(self.handle.smoltcp_handle().unwrap());
4436046f775S裕依         let listen_endpoint = socket.endpoint();
4446046f775S裕依 
4456046f775S裕依         if listen_endpoint.port == 0 {
4466046f775S裕依             return None;
4476046f775S裕依         } else {
4486046f775S裕依             // 如果listen_endpoint的address是None,意味着“监听所有的地址”。
4496046f775S裕依             // 这里假设所有的地址都是ipv4
4506046f775S裕依             // TODO: 支持ipv6
4516046f775S裕依             let result = wire::IpEndpoint::new(
4526046f775S裕依                 listen_endpoint
4536046f775S裕依                     .addr
4546046f775S裕依                     .unwrap_or(wire::IpAddress::v4(0, 0, 0, 0)),
4556046f775S裕依                 listen_endpoint.port,
4566046f775S裕依             );
4576046f775S裕依             return Some(Endpoint::Ip(Some(result)));
4586046f775S裕依         }
4596046f775S裕依     }
4606046f775S裕依 
4616046f775S裕依     fn peer_endpoint(&self) -> Option<Endpoint> {
4626046f775S裕依         return self.remote_endpoint.clone();
4636046f775S裕依     }
4646046f775S裕依 
465d623e902SGnoCiYeH     fn socket_handle(&self) -> GlobalSocketHandle {
466d623e902SGnoCiYeH         self.handle
4676046f775S裕依     }
4686046f775S裕依 
4696046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
4706046f775S裕依         self
4716046f775S裕依     }
4726046f775S裕依 
4736046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
4746046f775S裕依         self
4756046f775S裕依     }
4766046f775S裕依 }
4776046f775S裕依 
4786046f775S裕依 /// @brief 表示 tcp socket
4796046f775S裕依 ///
4806046f775S裕依 /// https://man7.org/linux/man-pages/man7/tcp.7.html
4816046f775S裕依 #[derive(Debug, Clone)]
4826046f775S裕依 pub struct TcpSocket {
483d623e902SGnoCiYeH     handles: Vec<GlobalSocketHandle>,
4846046f775S裕依     local_endpoint: Option<wire::IpEndpoint>, // save local endpoint for bind()
4856046f775S裕依     is_listening: bool,
4866046f775S裕依     metadata: SocketMetadata,
4876046f775S裕依 }
4886046f775S裕依 
4896046f775S裕依 impl TcpSocket {
4906046f775S裕依     /// 元数据的缓冲区的大小
4916046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
4926046f775S裕依     /// 默认的接收缓冲区的大小 receive
4936046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 512 * 1024;
4946046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
4956046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 512 * 1024;
4966046f775S裕依 
4976046f775S裕依     /// TcpSocket的特殊事件,用于在事件等待队列上sleep
4986046f775S裕依     pub const CAN_CONNECT: u64 = 1u64 << 63;
4996046f775S裕依     pub const CAN_ACCPET: u64 = 1u64 << 62;
5006046f775S裕依 
5016046f775S裕依     /// @brief 创建一个tcp的socket
5026046f775S裕依     ///
5036046f775S裕依     /// @param options socket的选项
5046046f775S裕依     ///
5056046f775S裕依     /// @return 返回创建的tcp的socket
5066046f775S裕依     pub fn new(options: SocketOptions) -> Self {
507c719ddc6SSaga1718         // 创建handles数组并把socket添加到socket集合中,并得到socket的句柄
508d623e902SGnoCiYeH         let handles: Vec<GlobalSocketHandle> = vec![GlobalSocketHandle::new_smoltcp_handle(
509c719ddc6SSaga1718             SOCKET_SET.lock_irqsave().add(Self::create_new_socket()),
510c719ddc6SSaga1718         )];
5116046f775S裕依 
5126046f775S裕依         let metadata = SocketMetadata::new(
5136046f775S裕依             SocketType::Tcp,
5146046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
5156046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
5166046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
5176046f775S裕依             options,
5186046f775S裕依         );
519*2eab6dd7S曾俊         // debug!("when there's a new tcp socket,its'len: {}",handles.len());
5206046f775S裕依 
5216046f775S裕依         return Self {
522c719ddc6SSaga1718             handles,
5236046f775S裕依             local_endpoint: None,
5246046f775S裕依             is_listening: false,
5256046f775S裕依             metadata,
5266046f775S裕依         };
5276046f775S裕依     }
5286046f775S裕依 
5296046f775S裕依     fn do_listen(
5306046f775S裕依         &mut self,
5316046f775S裕依         socket: &mut tcp::Socket,
5326046f775S裕依         local_endpoint: wire::IpEndpoint,
5336046f775S裕依     ) -> Result<(), SystemError> {
5346046f775S裕依         let listen_result = if local_endpoint.addr.is_unspecified() {
535*2eab6dd7S曾俊             // debug!("Tcp Socket Listen on port {}", local_endpoint.port);
5366046f775S裕依             socket.listen(local_endpoint.port)
5376046f775S裕依         } else {
538*2eab6dd7S曾俊             // debug!("Tcp Socket Listen on {local_endpoint}");
5396046f775S裕依             socket.listen(local_endpoint)
5406046f775S裕依         };
5416046f775S裕依         return match listen_result {
5426046f775S裕依             Ok(()) => {
543*2eab6dd7S曾俊                 // debug!(
5446046f775S裕依                 //     "Tcp Socket Listen on {local_endpoint}, open?:{}",
5456046f775S裕依                 //     socket.is_open()
5466046f775S裕依                 // );
5476046f775S裕依                 self.is_listening = true;
5486046f775S裕依 
5496046f775S裕依                 Ok(())
5506046f775S裕依             }
5516046f775S裕依             Err(_) => Err(SystemError::EINVAL),
5526046f775S裕依         };
5536046f775S裕依     }
554c719ddc6SSaga1718 
555c719ddc6SSaga1718     /// # create_new_socket - 创建新的TCP套接字
556c719ddc6SSaga1718     ///
557c719ddc6SSaga1718     /// 该函数用于创建一个新的TCP套接字,并返回该套接字的引用。
558c719ddc6SSaga1718     fn create_new_socket() -> tcp::Socket<'static> {
559c719ddc6SSaga1718         // 初始化tcp的buffer
560c719ddc6SSaga1718         let rx_buffer = tcp::SocketBuffer::new(vec![0; Self::DEFAULT_RX_BUF_SIZE]);
561c719ddc6SSaga1718         let tx_buffer = tcp::SocketBuffer::new(vec![0; Self::DEFAULT_TX_BUF_SIZE]);
562c719ddc6SSaga1718         tcp::Socket::new(rx_buffer, tx_buffer)
563c719ddc6SSaga1718     }
5646046f775S裕依 }
5656046f775S裕依 
5666046f775S裕依 impl Socket for TcpSocket {
567d623e902SGnoCiYeH     fn close(&mut self) {
568d623e902SGnoCiYeH         for handle in self.handles.iter() {
56937cef00bSSamuel Dai             {
570d623e902SGnoCiYeH                 let mut socket_set_guard = SOCKET_SET.lock_irqsave();
57137cef00bSSamuel Dai                 let smoltcp_handle = handle.smoltcp_handle().unwrap();
57237cef00bSSamuel Dai                 socket_set_guard
57337cef00bSSamuel Dai                     .get_mut::<smoltcp::socket::tcp::Socket>(smoltcp_handle)
57437cef00bSSamuel Dai                     .close();
575d623e902SGnoCiYeH                 drop(socket_set_guard);
576d623e902SGnoCiYeH             }
577d623e902SGnoCiYeH             poll_ifaces();
57837cef00bSSamuel Dai             SOCKET_SET
57937cef00bSSamuel Dai                 .lock_irqsave()
58037cef00bSSamuel Dai                 .remove(handle.smoltcp_handle().unwrap());
581*2eab6dd7S曾俊             // debug!("[Socket] [TCP] Close: {:?}", handle);
58237cef00bSSamuel Dai         }
583d623e902SGnoCiYeH     }
584d623e902SGnoCiYeH 
5856046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
5866046f775S裕依         if HANDLE_MAP
5876046f775S裕依             .read_irqsave()
5886046f775S裕依             .get(&self.socket_handle())
5896046f775S裕依             .unwrap()
5906046f775S裕依             .shutdown_type()
5916046f775S裕依             .contains(ShutdownType::RCV_SHUTDOWN)
5926046f775S裕依         {
5936046f775S裕依             return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
5946046f775S裕依         }
595*2eab6dd7S曾俊         // debug!("tcp socket: read, buf len={}", buf.len());
596*2eab6dd7S曾俊         // debug!("tcp socket:read, socket'len={}",self.handle.len());
5976046f775S裕依         loop {
5986046f775S裕依             poll_ifaces();
5996046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
600c719ddc6SSaga1718 
601d623e902SGnoCiYeH             let socket = socket_set_guard
602d623e902SGnoCiYeH                 .get_mut::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
6036046f775S裕依 
6046046f775S裕依             // 如果socket已经关闭,返回错误
6056046f775S裕依             if !socket.is_active() {
606*2eab6dd7S曾俊                 // debug!("Tcp Socket Read Error, socket is closed");
6076046f775S裕依                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6086046f775S裕依             }
6096046f775S裕依 
6106046f775S裕依             if socket.may_recv() {
611881ff6f9Syuyi2439                 match socket.recv_slice(buf) {
612881ff6f9Syuyi2439                     Ok(size) => {
6136046f775S裕依                         if size > 0 {
6146046f775S裕依                             let endpoint = if let Some(p) = socket.remote_endpoint() {
6156046f775S裕依                                 p
6166046f775S裕依                             } else {
6176046f775S裕依                                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6186046f775S裕依                             };
6196046f775S裕依 
6206046f775S裕依                             drop(socket_set_guard);
6216046f775S裕依                             poll_ifaces();
6226046f775S裕依                             return (Ok(size), Endpoint::Ip(Some(endpoint)));
6236046f775S裕依                         }
624881ff6f9Syuyi2439                     }
625881ff6f9Syuyi2439                     Err(tcp::RecvError::InvalidState) => {
626*2eab6dd7S曾俊                         warn!("Tcp Socket Read Error, InvalidState");
6276046f775S裕依                         return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6286046f775S裕依                     }
629881ff6f9Syuyi2439                     Err(tcp::RecvError::Finished) => {
6306046f775S裕依                         // 对端写端已关闭,我们应该关闭读端
6316046f775S裕依                         HANDLE_MAP
6326046f775S裕依                             .write_irqsave()
6336046f775S裕依                             .get_mut(&self.socket_handle())
6346046f775S裕依                             .unwrap()
6356046f775S裕依                             .shutdown_type_writer()
6366046f775S裕依                             .insert(ShutdownType::RCV_SHUTDOWN);
6376046f775S裕依                         return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6386046f775S裕依                     }
6396046f775S裕依                 }
6406046f775S裕依             } else {
6416046f775S裕依                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
6426046f775S裕依             }
6436046f775S裕依             drop(socket_set_guard);
6446046f775S裕依             SocketHandleItem::sleep(
6456046f775S裕依                 self.socket_handle(),
64637cef00bSSamuel Dai                 (EPollEventType::EPOLLIN.bits() | EPollEventType::EPOLLHUP.bits()) as u64,
6476046f775S裕依                 HANDLE_MAP.read_irqsave(),
6486046f775S裕依             );
6496046f775S裕依         }
6506046f775S裕依     }
6516046f775S裕依 
6526046f775S裕依     fn write(&self, buf: &[u8], _to: Option<Endpoint>) -> Result<usize, SystemError> {
6536046f775S裕依         if HANDLE_MAP
6546046f775S裕依             .read_irqsave()
6556046f775S裕依             .get(&self.socket_handle())
6566046f775S裕依             .unwrap()
6576046f775S裕依             .shutdown_type()
6586046f775S裕依             .contains(ShutdownType::RCV_SHUTDOWN)
6596046f775S裕依         {
6606046f775S裕依             return Err(SystemError::ENOTCONN);
6616046f775S裕依         }
662*2eab6dd7S曾俊         // debug!("tcp socket:write, socket'len={}",self.handle.len());
663c719ddc6SSaga1718 
6646046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
665c719ddc6SSaga1718 
666d623e902SGnoCiYeH         let socket = socket_set_guard
667d623e902SGnoCiYeH             .get_mut::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
6686046f775S裕依 
6696046f775S裕依         if socket.is_open() {
6706046f775S裕依             if socket.can_send() {
6716046f775S裕依                 match socket.send_slice(buf) {
6726046f775S裕依                     Ok(size) => {
6736046f775S裕依                         drop(socket_set_guard);
6746046f775S裕依                         poll_ifaces();
6756046f775S裕依                         return Ok(size);
6766046f775S裕依                     }
6776046f775S裕依                     Err(e) => {
678*2eab6dd7S曾俊                         error!("Tcp Socket Write Error {e:?}");
6796046f775S裕依                         return Err(SystemError::ENOBUFS);
6806046f775S裕依                     }
6816046f775S裕依                 }
6826046f775S裕依             } else {
6836046f775S裕依                 return Err(SystemError::ENOBUFS);
6846046f775S裕依             }
6856046f775S裕依         }
6866046f775S裕依 
6876046f775S裕依         return Err(SystemError::ENOTCONN);
6886046f775S裕依     }
6896046f775S裕依 
6906046f775S裕依     fn poll(&self) -> EPollEventType {
6916046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
692*2eab6dd7S曾俊         // debug!("tcp socket:poll, socket'len={}",self.handle.len());
6936046f775S裕依 
694d623e902SGnoCiYeH         let socket = socket_set_guard
695d623e902SGnoCiYeH             .get_mut::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
6966046f775S裕依         return SocketPollMethod::tcp_poll(
6976046f775S裕依             socket,
6986046f775S裕依             HANDLE_MAP
6996046f775S裕依                 .read_irqsave()
7006046f775S裕依                 .get(&self.socket_handle())
7016046f775S裕依                 .unwrap()
7026046f775S裕依                 .shutdown_type(),
7036046f775S裕依         );
7046046f775S裕依     }
7056046f775S裕依 
7066046f775S裕依     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
7076046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
708*2eab6dd7S曾俊         // debug!("tcp socket:connect, socket'len={}",self.handle.len());
709c719ddc6SSaga1718 
710d623e902SGnoCiYeH         let socket =
711d623e902SGnoCiYeH             sockets.get_mut::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
7126046f775S裕依 
7136046f775S裕依         if let Endpoint::Ip(Some(ip)) = endpoint {
7146046f775S裕依             let temp_port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
7156046f775S裕依             // 检测端口是否被占用
71637cef00bSSamuel Dai             PORT_MANAGER.bind_port(self.metadata.socket_type, temp_port)?;
7176046f775S裕依 
718*2eab6dd7S曾俊             // debug!("temp_port: {}", temp_port);
719e32effb1SLoGin             let iface: Arc<dyn NetDevice> = NET_DEVICES.write_irqsave().get(&0).unwrap().clone();
7206046f775S裕依             let mut inner_iface = iface.inner_iface().lock();
721*2eab6dd7S曾俊             // debug!("to connect: {ip:?}");
7226046f775S裕依 
7236046f775S裕依             match socket.connect(inner_iface.context(), ip, temp_port) {
7246046f775S裕依                 Ok(()) => {
7256046f775S裕依                     // avoid deadlock
7266046f775S裕依                     drop(inner_iface);
7276046f775S裕依                     drop(iface);
7286046f775S裕依                     drop(sockets);
7296046f775S裕依                     loop {
7306046f775S裕依                         poll_ifaces();
7316046f775S裕依                         let mut sockets = SOCKET_SET.lock_irqsave();
732d623e902SGnoCiYeH                         let socket = sockets.get_mut::<tcp::Socket>(
733d623e902SGnoCiYeH                             self.handles.get(0).unwrap().smoltcp_handle().unwrap(),
734d623e902SGnoCiYeH                         );
7356046f775S裕依 
7366046f775S裕依                         match socket.state() {
7376046f775S裕依                             tcp::State::Established => {
7386046f775S裕依                                 return Ok(());
7396046f775S裕依                             }
7406046f775S裕依                             tcp::State::SynSent => {
7416046f775S裕依                                 drop(sockets);
7426046f775S裕依                                 SocketHandleItem::sleep(
7436046f775S裕依                                     self.socket_handle(),
7446046f775S裕依                                     Self::CAN_CONNECT,
7456046f775S裕依                                     HANDLE_MAP.read_irqsave(),
7466046f775S裕依                                 );
7476046f775S裕依                             }
7486046f775S裕依                             _ => {
7496046f775S裕依                                 return Err(SystemError::ECONNREFUSED);
7506046f775S裕依                             }
7516046f775S裕依                         }
7526046f775S裕依                     }
7536046f775S裕依                 }
7546046f775S裕依                 Err(e) => {
755*2eab6dd7S曾俊                     // error!("Tcp Socket Connect Error {e:?}");
7566046f775S裕依                     match e {
7576046f775S裕依                         tcp::ConnectError::InvalidState => return Err(SystemError::EISCONN),
7586046f775S裕依                         tcp::ConnectError::Unaddressable => return Err(SystemError::EADDRNOTAVAIL),
7596046f775S裕依                     }
7606046f775S裕依                 }
7616046f775S裕依             }
7626046f775S裕依         } else {
7636046f775S裕依             return Err(SystemError::EINVAL);
7646046f775S裕依         }
7656046f775S裕依     }
7666046f775S裕依 
7676046f775S裕依     /// @brief tcp socket 监听 local_endpoint 端口
7686046f775S裕依     ///
76937cef00bSSamuel Dai     /// @param backlog 未处理的连接队列的最大长度
770c719ddc6SSaga1718     fn listen(&mut self, backlog: usize) -> Result<(), SystemError> {
7716046f775S裕依         if self.is_listening {
7726046f775S裕依             return Ok(());
7736046f775S裕依         }
7746046f775S裕依 
7756046f775S裕依         let local_endpoint = self.local_endpoint.ok_or(SystemError::EINVAL)?;
7766046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
777c719ddc6SSaga1718         // 获取handle的数量
778c719ddc6SSaga1718         let handlen = self.handles.len();
779c719ddc6SSaga1718         let backlog = handlen.max(backlog);
7806046f775S裕依 
781c719ddc6SSaga1718         // 添加剩余需要构建的socket
782*2eab6dd7S曾俊         // debug!("tcp socket:before listen, socket'len={}", self.handle_list.len());
783c719ddc6SSaga1718         let mut handle_guard = HANDLE_MAP.write_irqsave();
78437cef00bSSamuel Dai         let wait_queue = Arc::clone(&handle_guard.get(&self.socket_handle()).unwrap().wait_queue);
78537cef00bSSamuel Dai 
786c719ddc6SSaga1718         self.handles.extend((handlen..backlog).map(|_| {
787c719ddc6SSaga1718             let socket = Self::create_new_socket();
788d623e902SGnoCiYeH             let handle = GlobalSocketHandle::new_smoltcp_handle(sockets.add(socket));
78937cef00bSSamuel Dai             let handle_item = SocketHandleItem::new(Some(wait_queue.clone()));
790d623e902SGnoCiYeH             handle_guard.insert(handle, handle_item);
791c719ddc6SSaga1718             handle
792c719ddc6SSaga1718         }));
793*2eab6dd7S曾俊         // debug!("tcp socket:listen, socket'len={}",self.handle.len());
794*2eab6dd7S曾俊         // debug!("tcp socket:listen, backlog={backlog}");
795c719ddc6SSaga1718 
796c719ddc6SSaga1718         // 监听所有的socket
797c719ddc6SSaga1718         for i in 0..backlog {
798c719ddc6SSaga1718             let handle = self.handles.get(i).unwrap();
799c719ddc6SSaga1718 
800d623e902SGnoCiYeH             let socket = sockets.get_mut::<tcp::Socket>(handle.smoltcp_handle().unwrap());
801c719ddc6SSaga1718 
802c719ddc6SSaga1718             if !socket.is_listening() {
803*2eab6dd7S曾俊                 // debug!("Tcp Socket is already listening on {local_endpoint}");
804c719ddc6SSaga1718                 self.do_listen(socket, local_endpoint)?;
8056046f775S裕依             }
806*2eab6dd7S曾俊             // debug!("Tcp Socket  before listen, open={}", socket.is_open());
807c719ddc6SSaga1718         }
808c719ddc6SSaga1718         return Ok(());
8096046f775S裕依     }
8106046f775S裕依 
8116046f775S裕依     fn bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
8126046f775S裕依         if let Endpoint::Ip(Some(mut ip)) = endpoint {
8136046f775S裕依             if ip.port == 0 {
8146046f775S裕依                 ip.port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
8156046f775S裕依             }
8166046f775S裕依 
8176046f775S裕依             // 检测端口是否已被占用
81837cef00bSSamuel Dai             PORT_MANAGER.bind_port(self.metadata.socket_type, ip.port)?;
819*2eab6dd7S曾俊             // debug!("tcp socket:bind, socket'len={}",self.handle.len());
8206046f775S裕依 
8216046f775S裕依             self.local_endpoint = Some(ip);
8226046f775S裕依             self.is_listening = false;
8236046f775S裕依             return Ok(());
8246046f775S裕依         }
8256046f775S裕依         return Err(SystemError::EINVAL);
8266046f775S裕依     }
8276046f775S裕依 
8286046f775S裕依     fn shutdown(&mut self, shutdown_type: super::ShutdownType) -> Result<(), SystemError> {
8296046f775S裕依         // TODO:目前只是在表层判断,对端不知晓,后续需使用tcp实现
8306046f775S裕依         HANDLE_MAP
8316046f775S裕依             .write_irqsave()
8326046f775S裕依             .get_mut(&self.socket_handle())
8336046f775S裕依             .unwrap()
8346046f775S裕依             .shutdown_type = RwLock::new(shutdown_type);
8356046f775S裕依         return Ok(());
8366046f775S裕依     }
8376046f775S裕依 
8386046f775S裕依     fn accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError> {
83937cef00bSSamuel Dai         if !self.is_listening {
84037cef00bSSamuel Dai             return Err(SystemError::EINVAL);
84137cef00bSSamuel Dai         }
8426046f775S裕依         let endpoint = self.local_endpoint.ok_or(SystemError::EINVAL)?;
8436046f775S裕依         loop {
844*2eab6dd7S曾俊             // debug!("tcp accept: poll_ifaces()");
8456046f775S裕依             poll_ifaces();
846*2eab6dd7S曾俊             // debug!("tcp socket:accept, socket'len={}", self.handle_list.len());
8476046f775S裕依 
84837cef00bSSamuel Dai             let mut sockset = SOCKET_SET.lock_irqsave();
84937cef00bSSamuel Dai             // Get the corresponding activated handler
85037cef00bSSamuel Dai             let global_handle_index = self.handles.iter().position(|handle| {
85137cef00bSSamuel Dai                 let con_smol_sock = sockset.get::<tcp::Socket>(handle.smoltcp_handle().unwrap());
85237cef00bSSamuel Dai                 con_smol_sock.is_active()
85337cef00bSSamuel Dai             });
8546046f775S裕依 
85537cef00bSSamuel Dai             if let Some(handle_index) = global_handle_index {
85637cef00bSSamuel Dai                 let con_smol_sock = sockset
85737cef00bSSamuel Dai                     .get::<tcp::Socket>(self.handles[handle_index].smoltcp_handle().unwrap());
8586046f775S裕依 
859*2eab6dd7S曾俊                 // debug!("[Socket] [TCP] Accept: {:?}", handle);
86037cef00bSSamuel Dai                 // handle is connected socket's handle
86137cef00bSSamuel Dai                 let remote_ep = con_smol_sock
86237cef00bSSamuel Dai                     .remote_endpoint()
86337cef00bSSamuel Dai                     .ok_or(SystemError::ENOTCONN)?;
8646046f775S裕依 
865c719ddc6SSaga1718                 let mut tcp_socket = Self::create_new_socket();
86637cef00bSSamuel Dai                 self.do_listen(&mut tcp_socket, endpoint)?;
8676046f775S裕依 
86837cef00bSSamuel Dai                 let new_handle = GlobalSocketHandle::new_smoltcp_handle(sockset.add(tcp_socket));
8696046f775S裕依 
87037cef00bSSamuel Dai                 // let handle in TcpSock be the new empty handle, and return the old connected handle
87137cef00bSSamuel Dai                 let old_handle = core::mem::replace(&mut self.handles[handle_index], new_handle);
8726046f775S裕依 
8736046f775S裕依                 let metadata = SocketMetadata::new(
8746046f775S裕依                     SocketType::Tcp,
8756046f775S裕依                     Self::DEFAULT_TX_BUF_SIZE,
8766046f775S裕依                     Self::DEFAULT_RX_BUF_SIZE,
8776046f775S裕依                     Self::DEFAULT_METADATA_BUF_SIZE,
8786046f775S裕依                     self.metadata.options,
8796046f775S裕依                 );
8806046f775S裕依 
88137cef00bSSamuel Dai                 let sock_ret = Box::new(TcpSocket {
882d623e902SGnoCiYeH                     handles: vec![old_handle],
8836046f775S裕依                     local_endpoint: self.local_endpoint,
8846046f775S裕依                     is_listening: false,
8856046f775S裕依                     metadata,
8866046f775S裕依                 });
887c719ddc6SSaga1718 
88837cef00bSSamuel Dai                 {
8896046f775S裕依                     let mut handle_guard = HANDLE_MAP.write_irqsave();
8906046f775S裕依                     // 先删除原来的
891d623e902SGnoCiYeH                     let item = handle_guard.remove(&old_handle).unwrap();
892c719ddc6SSaga1718 
8936046f775S裕依                     // 按照smoltcp行为,将新的handle绑定到原来的item
89437cef00bSSamuel Dai                     let new_item = SocketHandleItem::new(None);
895d623e902SGnoCiYeH                     handle_guard.insert(old_handle, new_item);
89637cef00bSSamuel Dai                     // 插入新的item
89737cef00bSSamuel Dai                     handle_guard.insert(new_handle, item);
89837cef00bSSamuel Dai                     drop(handle_guard);
8996046f775S裕依                 }
90037cef00bSSamuel Dai                 return Ok((sock_ret, Endpoint::Ip(Some(remote_ep))));
901d623e902SGnoCiYeH             }
9026046f775S裕依 
90337cef00bSSamuel Dai             drop(sockset);
90437cef00bSSamuel Dai 
905*2eab6dd7S曾俊             // debug!("[TCP] [Accept] sleeping socket with handle: {:?}", self.handles.get(0).unwrap().smoltcp_handle().unwrap());
90637cef00bSSamuel Dai             SocketHandleItem::sleep(
90737cef00bSSamuel Dai                 self.socket_handle(), // NOTICE
90837cef00bSSamuel Dai                 Self::CAN_ACCPET,
90937cef00bSSamuel Dai                 HANDLE_MAP.read_irqsave(),
91037cef00bSSamuel Dai             );
911*2eab6dd7S曾俊             // debug!("tcp socket:after sleep, handle_guard'len={}",HANDLE_MAP.write_irqsave().len());
9126046f775S裕依         }
9136046f775S裕依     }
9146046f775S裕依 
9156046f775S裕依     fn endpoint(&self) -> Option<Endpoint> {
9166046f775S裕依         let mut result: Option<Endpoint> = self.local_endpoint.map(|x| Endpoint::Ip(Some(x)));
9176046f775S裕依 
9186046f775S裕依         if result.is_none() {
9196046f775S裕依             let sockets = SOCKET_SET.lock_irqsave();
920*2eab6dd7S曾俊             // debug!("tcp socket:endpoint, socket'len={}",self.handle.len());
921c719ddc6SSaga1718 
922d623e902SGnoCiYeH             let socket =
923d623e902SGnoCiYeH                 sockets.get::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
9246046f775S裕依             if let Some(ep) = socket.local_endpoint() {
9256046f775S裕依                 result = Some(Endpoint::Ip(Some(ep)));
9266046f775S裕依             }
9276046f775S裕依         }
9286046f775S裕依         return result;
9296046f775S裕依     }
9306046f775S裕依 
9316046f775S裕依     fn peer_endpoint(&self) -> Option<Endpoint> {
9326046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
933*2eab6dd7S曾俊         // debug!("tcp socket:peer_endpoint, socket'len={}",self.handle.len());
934c719ddc6SSaga1718 
935d623e902SGnoCiYeH         let socket =
936d623e902SGnoCiYeH             sockets.get::<tcp::Socket>(self.handles.get(0).unwrap().smoltcp_handle().unwrap());
9376046f775S裕依         return socket.remote_endpoint().map(|x| Endpoint::Ip(Some(x)));
9386046f775S裕依     }
9396046f775S裕依 
9406046f775S裕依     fn metadata(&self) -> SocketMetadata {
9416046f775S裕依         self.metadata.clone()
9426046f775S裕依     }
9436046f775S裕依 
9446046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
9456046f775S裕依         Box::new(self.clone())
9466046f775S裕依     }
9476046f775S裕依 
948d623e902SGnoCiYeH     fn socket_handle(&self) -> GlobalSocketHandle {
949*2eab6dd7S曾俊         // debug!("tcp socket:socket_handle, socket'len={}",self.handle.len());
950c719ddc6SSaga1718 
951d623e902SGnoCiYeH         *self.handles.get(0).unwrap()
9526046f775S裕依     }
9536046f775S裕依 
9546046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
9556046f775S裕依         self
9566046f775S裕依     }
9576046f775S裕依 
9586046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
9596046f775S裕依         self
9606046f775S裕依     }
9616046f775S裕依 }
962