xref: /DragonOS/kernel/src/net/socket/inet.rs (revision 6046f77591cf23dc9cc53b68b25c0d74f94fa493)
1*6046f775S裕依 use alloc::{boxed::Box, sync::Arc, vec::Vec};
2*6046f775S裕依 use smoltcp::{
3*6046f775S裕依     iface::SocketHandle,
4*6046f775S裕依     socket::{raw, tcp, udp},
5*6046f775S裕依     wire,
6*6046f775S裕依 };
7*6046f775S裕依 use system_error::SystemError;
8*6046f775S裕依 
9*6046f775S裕依 use crate::{
10*6046f775S裕依     driver::net::NetDriver,
11*6046f775S裕依     kerror, kwarn,
12*6046f775S裕依     libs::rwlock::RwLock,
13*6046f775S裕依     net::{
14*6046f775S裕依         event_poll::EPollEventType, net_core::poll_ifaces, Endpoint, Protocol, ShutdownType,
15*6046f775S裕依         NET_DRIVERS,
16*6046f775S裕依     },
17*6046f775S裕依 };
18*6046f775S裕依 
19*6046f775S裕依 use super::{
20*6046f775S裕依     GlobalSocketHandle, Socket, SocketHandleItem, SocketMetadata, SocketOptions, SocketPollMethod,
21*6046f775S裕依     SocketType, HANDLE_MAP, PORT_MANAGER, SOCKET_SET,
22*6046f775S裕依 };
23*6046f775S裕依 
24*6046f775S裕依 /// @brief 表示原始的socket。原始套接字绕过传输层协议(如 TCP 或 UDP)并提供对网络层协议(如 IP)的直接访问。
25*6046f775S裕依 ///
26*6046f775S裕依 /// ref: https://man7.org/linux/man-pages/man7/raw.7.html
27*6046f775S裕依 #[derive(Debug, Clone)]
28*6046f775S裕依 pub struct RawSocket {
29*6046f775S裕依     handle: Arc<GlobalSocketHandle>,
30*6046f775S裕依     /// 用户发送的数据包是否包含了IP头.
31*6046f775S裕依     /// 如果是true,用户发送的数据包,必须包含IP头。(即用户要自行设置IP头+数据)
32*6046f775S裕依     /// 如果是false,用户发送的数据包,不包含IP头。(即用户只要设置数据)
33*6046f775S裕依     header_included: bool,
34*6046f775S裕依     /// socket的metadata
35*6046f775S裕依     metadata: SocketMetadata,
36*6046f775S裕依 }
37*6046f775S裕依 
38*6046f775S裕依 impl RawSocket {
39*6046f775S裕依     /// 元数据的缓冲区的大小
40*6046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
41*6046f775S裕依     /// 默认的接收缓冲区的大小 receive
42*6046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 64 * 1024;
43*6046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
44*6046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 64 * 1024;
45*6046f775S裕依 
46*6046f775S裕依     /// @brief 创建一个原始的socket
47*6046f775S裕依     ///
48*6046f775S裕依     /// @param protocol 协议号
49*6046f775S裕依     /// @param options socket的选项
50*6046f775S裕依     ///
51*6046f775S裕依     /// @return 返回创建的原始的socket
52*6046f775S裕依     pub fn new(protocol: Protocol, options: SocketOptions) -> Self {
53*6046f775S裕依         let rx_buffer = raw::PacketBuffer::new(
54*6046f775S裕依             vec![raw::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
55*6046f775S裕依             vec![0; Self::DEFAULT_RX_BUF_SIZE],
56*6046f775S裕依         );
57*6046f775S裕依         let tx_buffer = raw::PacketBuffer::new(
58*6046f775S裕依             vec![raw::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
59*6046f775S裕依             vec![0; Self::DEFAULT_TX_BUF_SIZE],
60*6046f775S裕依         );
61*6046f775S裕依         let protocol: u8 = protocol.into();
62*6046f775S裕依         let socket = raw::Socket::new(
63*6046f775S裕依             wire::IpVersion::Ipv4,
64*6046f775S裕依             wire::IpProtocol::from(protocol),
65*6046f775S裕依             rx_buffer,
66*6046f775S裕依             tx_buffer,
67*6046f775S裕依         );
68*6046f775S裕依 
69*6046f775S裕依         // 把socket添加到socket集合中,并得到socket的句柄
70*6046f775S裕依         let handle: Arc<GlobalSocketHandle> =
71*6046f775S裕依             GlobalSocketHandle::new(SOCKET_SET.lock_irqsave().add(socket));
72*6046f775S裕依 
73*6046f775S裕依         let metadata = SocketMetadata::new(
74*6046f775S裕依             SocketType::Raw,
75*6046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
76*6046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
77*6046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
78*6046f775S裕依             options,
79*6046f775S裕依         );
80*6046f775S裕依 
81*6046f775S裕依         return Self {
82*6046f775S裕依             handle,
83*6046f775S裕依             header_included: false,
84*6046f775S裕依             metadata,
85*6046f775S裕依         };
86*6046f775S裕依     }
87*6046f775S裕依 }
88*6046f775S裕依 
89*6046f775S裕依 impl Socket for RawSocket {
90*6046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
91*6046f775S裕依         poll_ifaces();
92*6046f775S裕依         loop {
93*6046f775S裕依             // 如何优化这里?
94*6046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
95*6046f775S裕依             let socket = socket_set_guard.get_mut::<raw::Socket>(self.handle.0);
96*6046f775S裕依 
97*6046f775S裕依             match socket.recv_slice(buf) {
98*6046f775S裕依                 Ok(len) => {
99*6046f775S裕依                     let packet = wire::Ipv4Packet::new_unchecked(buf);
100*6046f775S裕依                     return (
101*6046f775S裕依                         Ok(len),
102*6046f775S裕依                         Endpoint::Ip(Some(wire::IpEndpoint {
103*6046f775S裕依                             addr: wire::IpAddress::Ipv4(packet.src_addr()),
104*6046f775S裕依                             port: 0,
105*6046f775S裕依                         })),
106*6046f775S裕依                     );
107*6046f775S裕依                 }
108*6046f775S裕依                 Err(raw::RecvError::Exhausted) => {
109*6046f775S裕依                     if !self.metadata.options.contains(SocketOptions::BLOCK) {
110*6046f775S裕依                         // 如果是非阻塞的socket,就返回错误
111*6046f775S裕依                         return (Err(SystemError::EAGAIN_OR_EWOULDBLOCK), Endpoint::Ip(None));
112*6046f775S裕依                     }
113*6046f775S裕依                 }
114*6046f775S裕依             }
115*6046f775S裕依             drop(socket_set_guard);
116*6046f775S裕依             SocketHandleItem::sleep(
117*6046f775S裕依                 self.socket_handle(),
118*6046f775S裕依                 EPollEventType::EPOLLIN.bits() as u64,
119*6046f775S裕依                 HANDLE_MAP.read_irqsave(),
120*6046f775S裕依             );
121*6046f775S裕依         }
122*6046f775S裕依     }
123*6046f775S裕依 
124*6046f775S裕依     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError> {
125*6046f775S裕依         // 如果用户发送的数据包,包含IP头,则直接发送
126*6046f775S裕依         if self.header_included {
127*6046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
128*6046f775S裕依             let socket = socket_set_guard.get_mut::<raw::Socket>(self.handle.0);
129*6046f775S裕依             match socket.send_slice(buf) {
130*6046f775S裕依                 Ok(_) => {
131*6046f775S裕依                     return Ok(buf.len());
132*6046f775S裕依                 }
133*6046f775S裕依                 Err(raw::SendError::BufferFull) => {
134*6046f775S裕依                     return Err(SystemError::ENOBUFS);
135*6046f775S裕依                 }
136*6046f775S裕依             }
137*6046f775S裕依         } else {
138*6046f775S裕依             // 如果用户发送的数据包,不包含IP头,则需要自己构造IP头
139*6046f775S裕依 
140*6046f775S裕依             if let Some(Endpoint::Ip(Some(endpoint))) = to {
141*6046f775S裕依                 let mut socket_set_guard = SOCKET_SET.lock_irqsave();
142*6046f775S裕依                 let socket: &mut raw::Socket =
143*6046f775S裕依                     socket_set_guard.get_mut::<raw::Socket>(self.handle.0);
144*6046f775S裕依 
145*6046f775S裕依                 // 暴力解决方案:只考虑0号网卡。 TODO:考虑多网卡的情况!!!
146*6046f775S裕依                 let iface = NET_DRIVERS.read_irqsave().get(&0).unwrap().clone();
147*6046f775S裕依 
148*6046f775S裕依                 // 构造IP头
149*6046f775S裕依                 let ipv4_src_addr: Option<wire::Ipv4Address> =
150*6046f775S裕依                     iface.inner_iface().lock().ipv4_addr();
151*6046f775S裕依                 if ipv4_src_addr.is_none() {
152*6046f775S裕依                     return Err(SystemError::ENETUNREACH);
153*6046f775S裕依                 }
154*6046f775S裕依                 let ipv4_src_addr = ipv4_src_addr.unwrap();
155*6046f775S裕依 
156*6046f775S裕依                 if let wire::IpAddress::Ipv4(ipv4_dst) = endpoint.addr {
157*6046f775S裕依                     let len = buf.len();
158*6046f775S裕依 
159*6046f775S裕依                     // 创建20字节的IPv4头部
160*6046f775S裕依                     let mut buffer: Vec<u8> = vec![0u8; len + 20];
161*6046f775S裕依                     let mut packet: wire::Ipv4Packet<&mut Vec<u8>> =
162*6046f775S裕依                         wire::Ipv4Packet::new_unchecked(&mut buffer);
163*6046f775S裕依 
164*6046f775S裕依                     // 封装ipv4 header
165*6046f775S裕依                     packet.set_version(4);
166*6046f775S裕依                     packet.set_header_len(20);
167*6046f775S裕依                     packet.set_total_len((20 + len) as u16);
168*6046f775S裕依                     packet.set_src_addr(ipv4_src_addr);
169*6046f775S裕依                     packet.set_dst_addr(ipv4_dst);
170*6046f775S裕依 
171*6046f775S裕依                     // 设置ipv4 header的protocol字段
172*6046f775S裕依                     packet.set_next_header(socket.ip_protocol());
173*6046f775S裕依 
174*6046f775S裕依                     // 获取IP数据包的负载字段
175*6046f775S裕依                     let payload: &mut [u8] = packet.payload_mut();
176*6046f775S裕依                     payload.copy_from_slice(buf);
177*6046f775S裕依 
178*6046f775S裕依                     // 填充checksum字段
179*6046f775S裕依                     packet.fill_checksum();
180*6046f775S裕依 
181*6046f775S裕依                     // 发送数据包
182*6046f775S裕依                     socket.send_slice(&buffer).unwrap();
183*6046f775S裕依 
184*6046f775S裕依                     iface.poll(&mut socket_set_guard).ok();
185*6046f775S裕依 
186*6046f775S裕依                     drop(socket_set_guard);
187*6046f775S裕依                     return Ok(len);
188*6046f775S裕依                 } else {
189*6046f775S裕依                     kwarn!("Unsupport Ip protocol type!");
190*6046f775S裕依                     return Err(SystemError::EINVAL);
191*6046f775S裕依                 }
192*6046f775S裕依             } else {
193*6046f775S裕依                 // 如果没有指定目的地址,则返回错误
194*6046f775S裕依                 return Err(SystemError::ENOTCONN);
195*6046f775S裕依             }
196*6046f775S裕依         }
197*6046f775S裕依     }
198*6046f775S裕依 
199*6046f775S裕依     fn connect(&mut self, _endpoint: Endpoint) -> Result<(), SystemError> {
200*6046f775S裕依         Ok(())
201*6046f775S裕依     }
202*6046f775S裕依 
203*6046f775S裕依     fn metadata(&self) -> SocketMetadata {
204*6046f775S裕依         self.metadata.clone()
205*6046f775S裕依     }
206*6046f775S裕依 
207*6046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
208*6046f775S裕依         Box::new(self.clone())
209*6046f775S裕依     }
210*6046f775S裕依 
211*6046f775S裕依     fn socket_handle(&self) -> SocketHandle {
212*6046f775S裕依         self.handle.0
213*6046f775S裕依     }
214*6046f775S裕依 
215*6046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
216*6046f775S裕依         self
217*6046f775S裕依     }
218*6046f775S裕依 
219*6046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
220*6046f775S裕依         self
221*6046f775S裕依     }
222*6046f775S裕依 }
223*6046f775S裕依 
224*6046f775S裕依 /// @brief 表示udp socket
225*6046f775S裕依 ///
226*6046f775S裕依 /// https://man7.org/linux/man-pages/man7/udp.7.html
227*6046f775S裕依 #[derive(Debug, Clone)]
228*6046f775S裕依 pub struct UdpSocket {
229*6046f775S裕依     pub handle: Arc<GlobalSocketHandle>,
230*6046f775S裕依     remote_endpoint: Option<Endpoint>, // 记录远程endpoint提供给connect(), 应该使用IP地址。
231*6046f775S裕依     metadata: SocketMetadata,
232*6046f775S裕依 }
233*6046f775S裕依 
234*6046f775S裕依 impl UdpSocket {
235*6046f775S裕依     /// 元数据的缓冲区的大小
236*6046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
237*6046f775S裕依     /// 默认的接收缓冲区的大小 receive
238*6046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 64 * 1024;
239*6046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
240*6046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 64 * 1024;
241*6046f775S裕依 
242*6046f775S裕依     /// @brief 创建一个udp的socket
243*6046f775S裕依     ///
244*6046f775S裕依     /// @param options socket的选项
245*6046f775S裕依     ///
246*6046f775S裕依     /// @return 返回创建的udp的socket
247*6046f775S裕依     pub fn new(options: SocketOptions) -> Self {
248*6046f775S裕依         let rx_buffer = udp::PacketBuffer::new(
249*6046f775S裕依             vec![udp::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
250*6046f775S裕依             vec![0; Self::DEFAULT_RX_BUF_SIZE],
251*6046f775S裕依         );
252*6046f775S裕依         let tx_buffer = udp::PacketBuffer::new(
253*6046f775S裕依             vec![udp::PacketMetadata::EMPTY; Self::DEFAULT_METADATA_BUF_SIZE],
254*6046f775S裕依             vec![0; Self::DEFAULT_TX_BUF_SIZE],
255*6046f775S裕依         );
256*6046f775S裕依         let socket = udp::Socket::new(rx_buffer, tx_buffer);
257*6046f775S裕依 
258*6046f775S裕依         // 把socket添加到socket集合中,并得到socket的句柄
259*6046f775S裕依         let handle: Arc<GlobalSocketHandle> =
260*6046f775S裕依             GlobalSocketHandle::new(SOCKET_SET.lock_irqsave().add(socket));
261*6046f775S裕依 
262*6046f775S裕依         let metadata = SocketMetadata::new(
263*6046f775S裕依             SocketType::Udp,
264*6046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
265*6046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
266*6046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
267*6046f775S裕依             options,
268*6046f775S裕依         );
269*6046f775S裕依 
270*6046f775S裕依         return Self {
271*6046f775S裕依             handle,
272*6046f775S裕依             remote_endpoint: None,
273*6046f775S裕依             metadata,
274*6046f775S裕依         };
275*6046f775S裕依     }
276*6046f775S裕依 
277*6046f775S裕依     fn do_bind(&self, socket: &mut udp::Socket, endpoint: Endpoint) -> Result<(), SystemError> {
278*6046f775S裕依         if let Endpoint::Ip(Some(ip)) = endpoint {
279*6046f775S裕依             // 检测端口是否已被占用
280*6046f775S裕依             PORT_MANAGER.bind_port(self.metadata.socket_type, ip.port, self.handle.clone())?;
281*6046f775S裕依 
282*6046f775S裕依             let bind_res = if ip.addr.is_unspecified() {
283*6046f775S裕依                 socket.bind(ip.port)
284*6046f775S裕依             } else {
285*6046f775S裕依                 socket.bind(ip)
286*6046f775S裕依             };
287*6046f775S裕依 
288*6046f775S裕依             match bind_res {
289*6046f775S裕依                 Ok(()) => return Ok(()),
290*6046f775S裕依                 Err(_) => return Err(SystemError::EINVAL),
291*6046f775S裕依             }
292*6046f775S裕依         } else {
293*6046f775S裕依             return Err(SystemError::EINVAL);
294*6046f775S裕依         }
295*6046f775S裕依     }
296*6046f775S裕依 }
297*6046f775S裕依 
298*6046f775S裕依 impl Socket for UdpSocket {
299*6046f775S裕依     /// @brief 在read函数执行之前,请先bind到本地的指定端口
300*6046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
301*6046f775S裕依         loop {
302*6046f775S裕依             // kdebug!("Wait22 to Read");
303*6046f775S裕依             poll_ifaces();
304*6046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
305*6046f775S裕依             let socket = socket_set_guard.get_mut::<udp::Socket>(self.handle.0);
306*6046f775S裕依 
307*6046f775S裕依             // kdebug!("Wait to Read");
308*6046f775S裕依 
309*6046f775S裕依             if socket.can_recv() {
310*6046f775S裕依                 if let Ok((size, remote_endpoint)) = socket.recv_slice(buf) {
311*6046f775S裕依                     drop(socket_set_guard);
312*6046f775S裕依                     poll_ifaces();
313*6046f775S裕依                     return (Ok(size), Endpoint::Ip(Some(remote_endpoint)));
314*6046f775S裕依                 }
315*6046f775S裕依             } else {
316*6046f775S裕依                 // 如果socket没有连接,则忙等
317*6046f775S裕依                 // return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
318*6046f775S裕依             }
319*6046f775S裕依             drop(socket_set_guard);
320*6046f775S裕依             SocketHandleItem::sleep(
321*6046f775S裕依                 self.socket_handle(),
322*6046f775S裕依                 EPollEventType::EPOLLIN.bits() as u64,
323*6046f775S裕依                 HANDLE_MAP.read_irqsave(),
324*6046f775S裕依             );
325*6046f775S裕依         }
326*6046f775S裕依     }
327*6046f775S裕依 
328*6046f775S裕依     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError> {
329*6046f775S裕依         // kdebug!("udp to send: {:?}, len={}", to, buf.len());
330*6046f775S裕依         let remote_endpoint: &wire::IpEndpoint = {
331*6046f775S裕依             if let Some(Endpoint::Ip(Some(ref endpoint))) = to {
332*6046f775S裕依                 endpoint
333*6046f775S裕依             } else if let Some(Endpoint::Ip(Some(ref endpoint))) = self.remote_endpoint {
334*6046f775S裕依                 endpoint
335*6046f775S裕依             } else {
336*6046f775S裕依                 return Err(SystemError::ENOTCONN);
337*6046f775S裕依             }
338*6046f775S裕依         };
339*6046f775S裕依         // kdebug!("udp write: remote = {:?}", remote_endpoint);
340*6046f775S裕依 
341*6046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
342*6046f775S裕依         let socket = socket_set_guard.get_mut::<udp::Socket>(self.handle.0);
343*6046f775S裕依         // kdebug!("is open()={}", socket.is_open());
344*6046f775S裕依         // kdebug!("socket endpoint={:?}", socket.endpoint());
345*6046f775S裕依         if socket.endpoint().port == 0 {
346*6046f775S裕依             let temp_port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
347*6046f775S裕依 
348*6046f775S裕依             let local_ep = match remote_endpoint.addr {
349*6046f775S裕依                 // 远程remote endpoint使用什么协议,发送的时候使用的协议是一样的吧
350*6046f775S裕依                 // 否则就用 self.endpoint().addr.unwrap()
351*6046f775S裕依                 wire::IpAddress::Ipv4(_) => Endpoint::Ip(Some(wire::IpEndpoint::new(
352*6046f775S裕依                     wire::IpAddress::Ipv4(wire::Ipv4Address::UNSPECIFIED),
353*6046f775S裕依                     temp_port,
354*6046f775S裕依                 ))),
355*6046f775S裕依                 wire::IpAddress::Ipv6(_) => Endpoint::Ip(Some(wire::IpEndpoint::new(
356*6046f775S裕依                     wire::IpAddress::Ipv6(wire::Ipv6Address::UNSPECIFIED),
357*6046f775S裕依                     temp_port,
358*6046f775S裕依                 ))),
359*6046f775S裕依             };
360*6046f775S裕依             // kdebug!("udp write: local_ep = {:?}", local_ep);
361*6046f775S裕依             self.do_bind(socket, local_ep)?;
362*6046f775S裕依         }
363*6046f775S裕依         // kdebug!("is open()={}", socket.is_open());
364*6046f775S裕依         if socket.can_send() {
365*6046f775S裕依             // kdebug!("udp write: can send");
366*6046f775S裕依             match socket.send_slice(buf, *remote_endpoint) {
367*6046f775S裕依                 Ok(()) => {
368*6046f775S裕依                     // kdebug!("udp write: send ok");
369*6046f775S裕依                     drop(socket_set_guard);
370*6046f775S裕依                     poll_ifaces();
371*6046f775S裕依                     return Ok(buf.len());
372*6046f775S裕依                 }
373*6046f775S裕依                 Err(_) => {
374*6046f775S裕依                     // kdebug!("udp write: send err");
375*6046f775S裕依                     return Err(SystemError::ENOBUFS);
376*6046f775S裕依                 }
377*6046f775S裕依             }
378*6046f775S裕依         } else {
379*6046f775S裕依             // kdebug!("udp write: can not send");
380*6046f775S裕依             return Err(SystemError::ENOBUFS);
381*6046f775S裕依         };
382*6046f775S裕依     }
383*6046f775S裕依 
384*6046f775S裕依     fn bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
385*6046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
386*6046f775S裕依         let socket = sockets.get_mut::<udp::Socket>(self.handle.0);
387*6046f775S裕依         // kdebug!("UDP Bind to {:?}", endpoint);
388*6046f775S裕依         return self.do_bind(socket, endpoint);
389*6046f775S裕依     }
390*6046f775S裕依 
391*6046f775S裕依     fn poll(&self) -> EPollEventType {
392*6046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
393*6046f775S裕依         let socket = sockets.get::<udp::Socket>(self.handle.0);
394*6046f775S裕依 
395*6046f775S裕依         return SocketPollMethod::udp_poll(
396*6046f775S裕依             socket,
397*6046f775S裕依             HANDLE_MAP
398*6046f775S裕依                 .read_irqsave()
399*6046f775S裕依                 .get(&self.socket_handle())
400*6046f775S裕依                 .unwrap()
401*6046f775S裕依                 .shutdown_type(),
402*6046f775S裕依         );
403*6046f775S裕依     }
404*6046f775S裕依 
405*6046f775S裕依     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
406*6046f775S裕依         if let Endpoint::Ip(_) = endpoint {
407*6046f775S裕依             self.remote_endpoint = Some(endpoint);
408*6046f775S裕依             Ok(())
409*6046f775S裕依         } else {
410*6046f775S裕依             Err(SystemError::EINVAL)
411*6046f775S裕依         }
412*6046f775S裕依     }
413*6046f775S裕依 
414*6046f775S裕依     fn ioctl(
415*6046f775S裕依         &self,
416*6046f775S裕依         _cmd: usize,
417*6046f775S裕依         _arg0: usize,
418*6046f775S裕依         _arg1: usize,
419*6046f775S裕依         _arg2: usize,
420*6046f775S裕依     ) -> Result<usize, SystemError> {
421*6046f775S裕依         todo!()
422*6046f775S裕依     }
423*6046f775S裕依 
424*6046f775S裕依     fn metadata(&self) -> SocketMetadata {
425*6046f775S裕依         self.metadata.clone()
426*6046f775S裕依     }
427*6046f775S裕依 
428*6046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
429*6046f775S裕依         return Box::new(self.clone());
430*6046f775S裕依     }
431*6046f775S裕依 
432*6046f775S裕依     fn endpoint(&self) -> Option<Endpoint> {
433*6046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
434*6046f775S裕依         let socket = sockets.get::<udp::Socket>(self.handle.0);
435*6046f775S裕依         let listen_endpoint = socket.endpoint();
436*6046f775S裕依 
437*6046f775S裕依         if listen_endpoint.port == 0 {
438*6046f775S裕依             return None;
439*6046f775S裕依         } else {
440*6046f775S裕依             // 如果listen_endpoint的address是None,意味着“监听所有的地址”。
441*6046f775S裕依             // 这里假设所有的地址都是ipv4
442*6046f775S裕依             // TODO: 支持ipv6
443*6046f775S裕依             let result = wire::IpEndpoint::new(
444*6046f775S裕依                 listen_endpoint
445*6046f775S裕依                     .addr
446*6046f775S裕依                     .unwrap_or(wire::IpAddress::v4(0, 0, 0, 0)),
447*6046f775S裕依                 listen_endpoint.port,
448*6046f775S裕依             );
449*6046f775S裕依             return Some(Endpoint::Ip(Some(result)));
450*6046f775S裕依         }
451*6046f775S裕依     }
452*6046f775S裕依 
453*6046f775S裕依     fn peer_endpoint(&self) -> Option<Endpoint> {
454*6046f775S裕依         return self.remote_endpoint.clone();
455*6046f775S裕依     }
456*6046f775S裕依 
457*6046f775S裕依     fn socket_handle(&self) -> SocketHandle {
458*6046f775S裕依         self.handle.0
459*6046f775S裕依     }
460*6046f775S裕依 
461*6046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
462*6046f775S裕依         self
463*6046f775S裕依     }
464*6046f775S裕依 
465*6046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
466*6046f775S裕依         self
467*6046f775S裕依     }
468*6046f775S裕依 }
469*6046f775S裕依 
470*6046f775S裕依 /// @brief 表示 tcp socket
471*6046f775S裕依 ///
472*6046f775S裕依 /// https://man7.org/linux/man-pages/man7/tcp.7.html
473*6046f775S裕依 #[derive(Debug, Clone)]
474*6046f775S裕依 pub struct TcpSocket {
475*6046f775S裕依     handle: Arc<GlobalSocketHandle>,
476*6046f775S裕依     local_endpoint: Option<wire::IpEndpoint>, // save local endpoint for bind()
477*6046f775S裕依     is_listening: bool,
478*6046f775S裕依     metadata: SocketMetadata,
479*6046f775S裕依 }
480*6046f775S裕依 
481*6046f775S裕依 impl TcpSocket {
482*6046f775S裕依     /// 元数据的缓冲区的大小
483*6046f775S裕依     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
484*6046f775S裕依     /// 默认的接收缓冲区的大小 receive
485*6046f775S裕依     pub const DEFAULT_RX_BUF_SIZE: usize = 512 * 1024;
486*6046f775S裕依     /// 默认的发送缓冲区的大小 transmiss
487*6046f775S裕依     pub const DEFAULT_TX_BUF_SIZE: usize = 512 * 1024;
488*6046f775S裕依 
489*6046f775S裕依     /// TcpSocket的特殊事件,用于在事件等待队列上sleep
490*6046f775S裕依     pub const CAN_CONNECT: u64 = 1u64 << 63;
491*6046f775S裕依     pub const CAN_ACCPET: u64 = 1u64 << 62;
492*6046f775S裕依 
493*6046f775S裕依     /// @brief 创建一个tcp的socket
494*6046f775S裕依     ///
495*6046f775S裕依     /// @param options socket的选项
496*6046f775S裕依     ///
497*6046f775S裕依     /// @return 返回创建的tcp的socket
498*6046f775S裕依     pub fn new(options: SocketOptions) -> Self {
499*6046f775S裕依         let rx_buffer = tcp::SocketBuffer::new(vec![0; Self::DEFAULT_RX_BUF_SIZE]);
500*6046f775S裕依         let tx_buffer = tcp::SocketBuffer::new(vec![0; Self::DEFAULT_TX_BUF_SIZE]);
501*6046f775S裕依         let socket = tcp::Socket::new(rx_buffer, tx_buffer);
502*6046f775S裕依 
503*6046f775S裕依         // 把socket添加到socket集合中,并得到socket的句柄
504*6046f775S裕依         let handle: Arc<GlobalSocketHandle> =
505*6046f775S裕依             GlobalSocketHandle::new(SOCKET_SET.lock_irqsave().add(socket));
506*6046f775S裕依 
507*6046f775S裕依         let metadata = SocketMetadata::new(
508*6046f775S裕依             SocketType::Tcp,
509*6046f775S裕依             Self::DEFAULT_RX_BUF_SIZE,
510*6046f775S裕依             Self::DEFAULT_TX_BUF_SIZE,
511*6046f775S裕依             Self::DEFAULT_METADATA_BUF_SIZE,
512*6046f775S裕依             options,
513*6046f775S裕依         );
514*6046f775S裕依 
515*6046f775S裕依         return Self {
516*6046f775S裕依             handle,
517*6046f775S裕依             local_endpoint: None,
518*6046f775S裕依             is_listening: false,
519*6046f775S裕依             metadata,
520*6046f775S裕依         };
521*6046f775S裕依     }
522*6046f775S裕依 
523*6046f775S裕依     fn do_listen(
524*6046f775S裕依         &mut self,
525*6046f775S裕依         socket: &mut tcp::Socket,
526*6046f775S裕依         local_endpoint: wire::IpEndpoint,
527*6046f775S裕依     ) -> Result<(), SystemError> {
528*6046f775S裕依         let listen_result = if local_endpoint.addr.is_unspecified() {
529*6046f775S裕依             // kdebug!("Tcp Socket Listen on port {}", local_endpoint.port);
530*6046f775S裕依             socket.listen(local_endpoint.port)
531*6046f775S裕依         } else {
532*6046f775S裕依             // kdebug!("Tcp Socket Listen on {local_endpoint}");
533*6046f775S裕依             socket.listen(local_endpoint)
534*6046f775S裕依         };
535*6046f775S裕依         // TODO: 增加端口占用检查
536*6046f775S裕依         return match listen_result {
537*6046f775S裕依             Ok(()) => {
538*6046f775S裕依                 // kdebug!(
539*6046f775S裕依                 //     "Tcp Socket Listen on {local_endpoint}, open?:{}",
540*6046f775S裕依                 //     socket.is_open()
541*6046f775S裕依                 // );
542*6046f775S裕依                 self.is_listening = true;
543*6046f775S裕依 
544*6046f775S裕依                 Ok(())
545*6046f775S裕依             }
546*6046f775S裕依             Err(_) => Err(SystemError::EINVAL),
547*6046f775S裕依         };
548*6046f775S裕依     }
549*6046f775S裕依 }
550*6046f775S裕依 
551*6046f775S裕依 impl Socket for TcpSocket {
552*6046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
553*6046f775S裕依         if HANDLE_MAP
554*6046f775S裕依             .read_irqsave()
555*6046f775S裕依             .get(&self.socket_handle())
556*6046f775S裕依             .unwrap()
557*6046f775S裕依             .shutdown_type()
558*6046f775S裕依             .contains(ShutdownType::RCV_SHUTDOWN)
559*6046f775S裕依         {
560*6046f775S裕依             return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
561*6046f775S裕依         }
562*6046f775S裕依         // kdebug!("tcp socket: read, buf len={}", buf.len());
563*6046f775S裕依 
564*6046f775S裕依         loop {
565*6046f775S裕依             poll_ifaces();
566*6046f775S裕依             let mut socket_set_guard = SOCKET_SET.lock_irqsave();
567*6046f775S裕依             let socket = socket_set_guard.get_mut::<tcp::Socket>(self.handle.0);
568*6046f775S裕依 
569*6046f775S裕依             // 如果socket已经关闭,返回错误
570*6046f775S裕依             if !socket.is_active() {
571*6046f775S裕依                 // kdebug!("Tcp Socket Read Error, socket is closed");
572*6046f775S裕依                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
573*6046f775S裕依             }
574*6046f775S裕依 
575*6046f775S裕依             if socket.may_recv() {
576*6046f775S裕依                 let recv_res = socket.recv_slice(buf);
577*6046f775S裕依 
578*6046f775S裕依                 if let Ok(size) = recv_res {
579*6046f775S裕依                     if size > 0 {
580*6046f775S裕依                         let endpoint = if let Some(p) = socket.remote_endpoint() {
581*6046f775S裕依                             p
582*6046f775S裕依                         } else {
583*6046f775S裕依                             return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
584*6046f775S裕依                         };
585*6046f775S裕依 
586*6046f775S裕依                         drop(socket_set_guard);
587*6046f775S裕依                         poll_ifaces();
588*6046f775S裕依                         return (Ok(size), Endpoint::Ip(Some(endpoint)));
589*6046f775S裕依                     }
590*6046f775S裕依                 } else {
591*6046f775S裕依                     let err = recv_res.unwrap_err();
592*6046f775S裕依                     match err {
593*6046f775S裕依                         tcp::RecvError::InvalidState => {
594*6046f775S裕依                             kwarn!("Tcp Socket Read Error, InvalidState");
595*6046f775S裕依                             return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
596*6046f775S裕依                         }
597*6046f775S裕依                         tcp::RecvError::Finished => {
598*6046f775S裕依                             // 对端写端已关闭,我们应该关闭读端
599*6046f775S裕依                             HANDLE_MAP
600*6046f775S裕依                                 .write_irqsave()
601*6046f775S裕依                                 .get_mut(&self.socket_handle())
602*6046f775S裕依                                 .unwrap()
603*6046f775S裕依                                 .shutdown_type_writer()
604*6046f775S裕依                                 .insert(ShutdownType::RCV_SHUTDOWN);
605*6046f775S裕依                             return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
606*6046f775S裕依                         }
607*6046f775S裕依                     }
608*6046f775S裕依                 }
609*6046f775S裕依             } else {
610*6046f775S裕依                 return (Err(SystemError::ENOTCONN), Endpoint::Ip(None));
611*6046f775S裕依             }
612*6046f775S裕依             drop(socket_set_guard);
613*6046f775S裕依             SocketHandleItem::sleep(
614*6046f775S裕依                 self.socket_handle(),
615*6046f775S裕依                 EPollEventType::EPOLLIN.bits() as u64,
616*6046f775S裕依                 HANDLE_MAP.read_irqsave(),
617*6046f775S裕依             );
618*6046f775S裕依         }
619*6046f775S裕依     }
620*6046f775S裕依 
621*6046f775S裕依     fn write(&self, buf: &[u8], _to: Option<Endpoint>) -> Result<usize, SystemError> {
622*6046f775S裕依         if HANDLE_MAP
623*6046f775S裕依             .read_irqsave()
624*6046f775S裕依             .get(&self.socket_handle())
625*6046f775S裕依             .unwrap()
626*6046f775S裕依             .shutdown_type()
627*6046f775S裕依             .contains(ShutdownType::RCV_SHUTDOWN)
628*6046f775S裕依         {
629*6046f775S裕依             return Err(SystemError::ENOTCONN);
630*6046f775S裕依         }
631*6046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
632*6046f775S裕依         let socket = socket_set_guard.get_mut::<tcp::Socket>(self.handle.0);
633*6046f775S裕依 
634*6046f775S裕依         if socket.is_open() {
635*6046f775S裕依             if socket.can_send() {
636*6046f775S裕依                 match socket.send_slice(buf) {
637*6046f775S裕依                     Ok(size) => {
638*6046f775S裕依                         drop(socket_set_guard);
639*6046f775S裕依                         poll_ifaces();
640*6046f775S裕依                         return Ok(size);
641*6046f775S裕依                     }
642*6046f775S裕依                     Err(e) => {
643*6046f775S裕依                         kerror!("Tcp Socket Write Error {e:?}");
644*6046f775S裕依                         return Err(SystemError::ENOBUFS);
645*6046f775S裕依                     }
646*6046f775S裕依                 }
647*6046f775S裕依             } else {
648*6046f775S裕依                 return Err(SystemError::ENOBUFS);
649*6046f775S裕依             }
650*6046f775S裕依         }
651*6046f775S裕依 
652*6046f775S裕依         return Err(SystemError::ENOTCONN);
653*6046f775S裕依     }
654*6046f775S裕依 
655*6046f775S裕依     fn poll(&self) -> EPollEventType {
656*6046f775S裕依         let mut socket_set_guard = SOCKET_SET.lock_irqsave();
657*6046f775S裕依         let socket = socket_set_guard.get_mut::<tcp::Socket>(self.handle.0);
658*6046f775S裕依 
659*6046f775S裕依         return SocketPollMethod::tcp_poll(
660*6046f775S裕依             socket,
661*6046f775S裕依             HANDLE_MAP
662*6046f775S裕依                 .read_irqsave()
663*6046f775S裕依                 .get(&self.socket_handle())
664*6046f775S裕依                 .unwrap()
665*6046f775S裕依                 .shutdown_type(),
666*6046f775S裕依         );
667*6046f775S裕依     }
668*6046f775S裕依 
669*6046f775S裕依     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
670*6046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
671*6046f775S裕依         let socket = sockets.get_mut::<tcp::Socket>(self.handle.0);
672*6046f775S裕依 
673*6046f775S裕依         if let Endpoint::Ip(Some(ip)) = endpoint {
674*6046f775S裕依             let temp_port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
675*6046f775S裕依             // 检测端口是否被占用
676*6046f775S裕依             PORT_MANAGER.bind_port(self.metadata.socket_type, temp_port, self.handle.clone())?;
677*6046f775S裕依 
678*6046f775S裕依             // kdebug!("temp_port: {}", temp_port);
679*6046f775S裕依             let iface: Arc<dyn NetDriver> = NET_DRIVERS.write_irqsave().get(&0).unwrap().clone();
680*6046f775S裕依             let mut inner_iface = iface.inner_iface().lock();
681*6046f775S裕依             // kdebug!("to connect: {ip:?}");
682*6046f775S裕依 
683*6046f775S裕依             match socket.connect(inner_iface.context(), ip, temp_port) {
684*6046f775S裕依                 Ok(()) => {
685*6046f775S裕依                     // avoid deadlock
686*6046f775S裕依                     drop(inner_iface);
687*6046f775S裕依                     drop(iface);
688*6046f775S裕依                     drop(sockets);
689*6046f775S裕依                     loop {
690*6046f775S裕依                         poll_ifaces();
691*6046f775S裕依                         let mut sockets = SOCKET_SET.lock_irqsave();
692*6046f775S裕依                         let socket = sockets.get_mut::<tcp::Socket>(self.handle.0);
693*6046f775S裕依 
694*6046f775S裕依                         match socket.state() {
695*6046f775S裕依                             tcp::State::Established => {
696*6046f775S裕依                                 return Ok(());
697*6046f775S裕依                             }
698*6046f775S裕依                             tcp::State::SynSent => {
699*6046f775S裕依                                 drop(sockets);
700*6046f775S裕依                                 SocketHandleItem::sleep(
701*6046f775S裕依                                     self.socket_handle(),
702*6046f775S裕依                                     Self::CAN_CONNECT,
703*6046f775S裕依                                     HANDLE_MAP.read_irqsave(),
704*6046f775S裕依                                 );
705*6046f775S裕依                             }
706*6046f775S裕依                             _ => {
707*6046f775S裕依                                 return Err(SystemError::ECONNREFUSED);
708*6046f775S裕依                             }
709*6046f775S裕依                         }
710*6046f775S裕依                     }
711*6046f775S裕依                 }
712*6046f775S裕依                 Err(e) => {
713*6046f775S裕依                     // kerror!("Tcp Socket Connect Error {e:?}");
714*6046f775S裕依                     match e {
715*6046f775S裕依                         tcp::ConnectError::InvalidState => return Err(SystemError::EISCONN),
716*6046f775S裕依                         tcp::ConnectError::Unaddressable => return Err(SystemError::EADDRNOTAVAIL),
717*6046f775S裕依                     }
718*6046f775S裕依                 }
719*6046f775S裕依             }
720*6046f775S裕依         } else {
721*6046f775S裕依             return Err(SystemError::EINVAL);
722*6046f775S裕依         }
723*6046f775S裕依     }
724*6046f775S裕依 
725*6046f775S裕依     /// @brief tcp socket 监听 local_endpoint 端口
726*6046f775S裕依     ///
727*6046f775S裕依     /// @param backlog 未处理的连接队列的最大长度. 由于smoltcp不支持backlog,所以这个参数目前无效
728*6046f775S裕依     fn listen(&mut self, _backlog: usize) -> Result<(), SystemError> {
729*6046f775S裕依         if self.is_listening {
730*6046f775S裕依             return Ok(());
731*6046f775S裕依         }
732*6046f775S裕依 
733*6046f775S裕依         let local_endpoint = self.local_endpoint.ok_or(SystemError::EINVAL)?;
734*6046f775S裕依         let mut sockets = SOCKET_SET.lock_irqsave();
735*6046f775S裕依         let socket = sockets.get_mut::<tcp::Socket>(self.handle.0);
736*6046f775S裕依 
737*6046f775S裕依         if socket.is_listening() {
738*6046f775S裕依             // kdebug!("Tcp Socket is already listening on {local_endpoint}");
739*6046f775S裕依             return Ok(());
740*6046f775S裕依         }
741*6046f775S裕依         // kdebug!("Tcp Socket  before listen, open={}", socket.is_open());
742*6046f775S裕依         return self.do_listen(socket, local_endpoint);
743*6046f775S裕依     }
744*6046f775S裕依 
745*6046f775S裕依     fn bind(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
746*6046f775S裕依         if let Endpoint::Ip(Some(mut ip)) = endpoint {
747*6046f775S裕依             if ip.port == 0 {
748*6046f775S裕依                 ip.port = PORT_MANAGER.get_ephemeral_port(self.metadata.socket_type)?;
749*6046f775S裕依             }
750*6046f775S裕依 
751*6046f775S裕依             // 检测端口是否已被占用
752*6046f775S裕依             PORT_MANAGER.bind_port(self.metadata.socket_type, ip.port, self.handle.clone())?;
753*6046f775S裕依 
754*6046f775S裕依             self.local_endpoint = Some(ip);
755*6046f775S裕依             self.is_listening = false;
756*6046f775S裕依             return Ok(());
757*6046f775S裕依         }
758*6046f775S裕依         return Err(SystemError::EINVAL);
759*6046f775S裕依     }
760*6046f775S裕依 
761*6046f775S裕依     fn shutdown(&mut self, shutdown_type: super::ShutdownType) -> Result<(), SystemError> {
762*6046f775S裕依         // TODO:目前只是在表层判断,对端不知晓,后续需使用tcp实现
763*6046f775S裕依         HANDLE_MAP
764*6046f775S裕依             .write_irqsave()
765*6046f775S裕依             .get_mut(&self.socket_handle())
766*6046f775S裕依             .unwrap()
767*6046f775S裕依             .shutdown_type = RwLock::new(shutdown_type);
768*6046f775S裕依         return Ok(());
769*6046f775S裕依     }
770*6046f775S裕依 
771*6046f775S裕依     fn accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError> {
772*6046f775S裕依         let endpoint = self.local_endpoint.ok_or(SystemError::EINVAL)?;
773*6046f775S裕依         loop {
774*6046f775S裕依             // kdebug!("tcp accept: poll_ifaces()");
775*6046f775S裕依             poll_ifaces();
776*6046f775S裕依 
777*6046f775S裕依             let mut sockets = SOCKET_SET.lock_irqsave();
778*6046f775S裕依 
779*6046f775S裕依             let socket = sockets.get_mut::<tcp::Socket>(self.handle.0);
780*6046f775S裕依 
781*6046f775S裕依             if socket.is_active() {
782*6046f775S裕依                 // kdebug!("tcp accept: socket.is_active()");
783*6046f775S裕依                 let remote_ep = socket.remote_endpoint().ok_or(SystemError::ENOTCONN)?;
784*6046f775S裕依 
785*6046f775S裕依                 let new_socket = {
786*6046f775S裕依                     // Initialize the TCP socket's buffers.
787*6046f775S裕依                     let rx_buffer = tcp::SocketBuffer::new(vec![0; Self::DEFAULT_RX_BUF_SIZE]);
788*6046f775S裕依                     let tx_buffer = tcp::SocketBuffer::new(vec![0; Self::DEFAULT_TX_BUF_SIZE]);
789*6046f775S裕依                     // The new TCP socket used for sending and receiving data.
790*6046f775S裕依                     let mut tcp_socket = tcp::Socket::new(rx_buffer, tx_buffer);
791*6046f775S裕依                     self.do_listen(&mut tcp_socket, endpoint)
792*6046f775S裕依                         .expect("do_listen failed");
793*6046f775S裕依 
794*6046f775S裕依                     // tcp_socket.listen(endpoint).unwrap();
795*6046f775S裕依 
796*6046f775S裕依                     // 之所以把old_handle存入new_socket, 是因为当前时刻,smoltcp已经把old_handle对应的socket与远程的endpoint关联起来了
797*6046f775S裕依                     // 因此需要再为当前的socket分配一个新的handle
798*6046f775S裕依                     let new_handle = GlobalSocketHandle::new(sockets.add(tcp_socket));
799*6046f775S裕依                     let old_handle = ::core::mem::replace(&mut self.handle, new_handle.clone());
800*6046f775S裕依 
801*6046f775S裕依                     // 更新端口与 handle 的绑定
802*6046f775S裕依                     if let Some(Endpoint::Ip(Some(ip))) = self.endpoint() {
803*6046f775S裕依                         PORT_MANAGER.unbind_port(self.metadata.socket_type, ip.port)?;
804*6046f775S裕依                         PORT_MANAGER.bind_port(
805*6046f775S裕依                             self.metadata.socket_type,
806*6046f775S裕依                             ip.port,
807*6046f775S裕依                             new_handle.clone(),
808*6046f775S裕依                         )?;
809*6046f775S裕依                     }
810*6046f775S裕依 
811*6046f775S裕依                     let metadata = SocketMetadata::new(
812*6046f775S裕依                         SocketType::Tcp,
813*6046f775S裕依                         Self::DEFAULT_TX_BUF_SIZE,
814*6046f775S裕依                         Self::DEFAULT_RX_BUF_SIZE,
815*6046f775S裕依                         Self::DEFAULT_METADATA_BUF_SIZE,
816*6046f775S裕依                         self.metadata.options,
817*6046f775S裕依                     );
818*6046f775S裕依 
819*6046f775S裕依                     let new_socket = Box::new(TcpSocket {
820*6046f775S裕依                         handle: old_handle.clone(),
821*6046f775S裕依                         local_endpoint: self.local_endpoint,
822*6046f775S裕依                         is_listening: false,
823*6046f775S裕依                         metadata,
824*6046f775S裕依                     });
825*6046f775S裕依 
826*6046f775S裕依                     // 更新handle表
827*6046f775S裕依                     let mut handle_guard = HANDLE_MAP.write_irqsave();
828*6046f775S裕依                     // 先删除原来的
829*6046f775S裕依                     let item = handle_guard.remove(&old_handle.0).unwrap();
830*6046f775S裕依                     // 按照smoltcp行为,将新的handle绑定到原来的item
831*6046f775S裕依                     handle_guard.insert(new_handle.0, item);
832*6046f775S裕依                     let new_item = SocketHandleItem::new();
833*6046f775S裕依                     // 插入新的item
834*6046f775S裕依                     handle_guard.insert(old_handle.0, new_item);
835*6046f775S裕依 
836*6046f775S裕依                     new_socket
837*6046f775S裕依                 };
838*6046f775S裕依                 // kdebug!("tcp accept: new socket: {:?}", new_socket);
839*6046f775S裕依                 drop(sockets);
840*6046f775S裕依                 poll_ifaces();
841*6046f775S裕依 
842*6046f775S裕依                 return Ok((new_socket, Endpoint::Ip(Some(remote_ep))));
843*6046f775S裕依             }
844*6046f775S裕依             drop(sockets);
845*6046f775S裕依 
846*6046f775S裕依             SocketHandleItem::sleep(
847*6046f775S裕依                 self.socket_handle(),
848*6046f775S裕依                 Self::CAN_ACCPET,
849*6046f775S裕依                 HANDLE_MAP.read_irqsave(),
850*6046f775S裕依             );
851*6046f775S裕依         }
852*6046f775S裕依     }
853*6046f775S裕依 
854*6046f775S裕依     fn endpoint(&self) -> Option<Endpoint> {
855*6046f775S裕依         let mut result: Option<Endpoint> = self.local_endpoint.map(|x| Endpoint::Ip(Some(x)));
856*6046f775S裕依 
857*6046f775S裕依         if result.is_none() {
858*6046f775S裕依             let sockets = SOCKET_SET.lock_irqsave();
859*6046f775S裕依             let socket = sockets.get::<tcp::Socket>(self.handle.0);
860*6046f775S裕依             if let Some(ep) = socket.local_endpoint() {
861*6046f775S裕依                 result = Some(Endpoint::Ip(Some(ep)));
862*6046f775S裕依             }
863*6046f775S裕依         }
864*6046f775S裕依         return result;
865*6046f775S裕依     }
866*6046f775S裕依 
867*6046f775S裕依     fn peer_endpoint(&self) -> Option<Endpoint> {
868*6046f775S裕依         let sockets = SOCKET_SET.lock_irqsave();
869*6046f775S裕依         let socket = sockets.get::<tcp::Socket>(self.handle.0);
870*6046f775S裕依         return socket.remote_endpoint().map(|x| Endpoint::Ip(Some(x)));
871*6046f775S裕依     }
872*6046f775S裕依 
873*6046f775S裕依     fn metadata(&self) -> SocketMetadata {
874*6046f775S裕依         self.metadata.clone()
875*6046f775S裕依     }
876*6046f775S裕依 
877*6046f775S裕依     fn box_clone(&self) -> Box<dyn Socket> {
878*6046f775S裕依         Box::new(self.clone())
879*6046f775S裕依     }
880*6046f775S裕依 
881*6046f775S裕依     fn socket_handle(&self) -> SocketHandle {
882*6046f775S裕依         self.handle.0
883*6046f775S裕依     }
884*6046f775S裕依 
885*6046f775S裕依     fn as_any_ref(&self) -> &dyn core::any::Any {
886*6046f775S裕依         self
887*6046f775S裕依     }
888*6046f775S裕依 
889*6046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
890*6046f775S裕依         self
891*6046f775S裕依     }
892*6046f775S裕依 }
893