1 use core::{
2     fmt::{self, Debug},
3     sync::atomic::AtomicUsize,
4 };
5 
6 use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
7 
8 use crate::{driver::net::NetDriver, kwarn, libs::rwlock::RwLock, syscall::SystemError};
9 use smoltcp::wire::IpEndpoint;
10 
11 use self::socket::SocketMetadata;
12 
13 pub mod endpoints;
14 pub mod net_core;
15 pub mod socket;
16 pub mod syscall;
17 
18 lazy_static! {
19     /// @brief 所有网络接口的列表
20     pub static ref NET_DRIVERS: RwLock<BTreeMap<usize, Arc<dyn NetDriver>>> = RwLock::new(BTreeMap::new());
21 }
22 
23 /// @brief 生成网络接口的id (全局自增)
generate_iface_id() -> usize24 pub fn generate_iface_id() -> usize {
25     static IFACE_ID: AtomicUsize = AtomicUsize::new(0);
26     return IFACE_ID
27         .fetch_add(1, core::sync::atomic::Ordering::SeqCst)
28         .into();
29 }
30 
31 /// @brief 用于指定socket的关闭类型
32 /// 参考:https://pubs.opengroup.org/onlinepubs/9699919799/functions/shutdown.html
33 #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
34 pub enum ShutdownType {
35     ShutRd = 0,   // Disables further receive operations.
36     ShutWr = 1,   // Disables further send operations.
37     ShutRdwr = 2, // Disables further send and receive operations.
38 }
39 
40 impl TryFrom<i32> for ShutdownType {
41     type Error = SystemError;
42 
try_from(value: i32) -> Result<Self, Self::Error>43     fn try_from(value: i32) -> Result<Self, Self::Error> {
44         use num_traits::FromPrimitive;
45         <Self as FromPrimitive>::from_i32(value).ok_or(SystemError::EINVAL)
46     }
47 }
48 
49 impl Into<i32> for ShutdownType {
into(self) -> i3250     fn into(self) -> i32 {
51         use num_traits::ToPrimitive;
52         <Self as ToPrimitive>::to_i32(&self).unwrap()
53     }
54 }
55 
56 #[derive(Debug, Clone)]
57 pub enum Endpoint {
58     /// 链路层端点
59     LinkLayer(endpoints::LinkLayerEndpoint),
60     /// 网络层端点
61     Ip(Option<IpEndpoint>),
62     // todo: 增加NetLink机制后,增加NetLink端点
63 }
64 
65 pub trait Socket: Sync + Send + Debug {
66     /// @brief 从socket中读取数据,如果socket是阻塞的,那么直到读取到数据才返回
67     ///
68     /// @param buf 读取到的数据存放的缓冲区
69     ///
70     /// @return - 成功:(返回读取的数据的长度,读取数据的端点).
71     ///         - 失败:错误码
read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint)72     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint);
73 
74     /// @brief 向socket中写入数据。如果socket是阻塞的,那么直到写入的数据全部写入socket中才返回
75     ///
76     /// @param buf 要写入的数据
77     /// @param to 要写入的目的端点,如果是None,那么写入的数据将会被丢弃
78     ///
79     /// @return 返回写入的数据的长度
write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError>80     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError>;
81 
82     /// @brief 对应于POSIX的connect函数,用于连接到指定的远程服务器端点
83     ///
84     /// It is used to establish a connection to a remote server.
85     /// When a socket is connected to a remote server,
86     /// the operating system will establish a network connection with the server
87     /// and allow data to be sent and received between the local socket and the remote server.
88     ///
89     /// @param endpoint 要连接的端点
90     ///
91     /// @return 返回连接是否成功
connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError>92     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError>;
93 
94     /// @brief 对应于POSIX的bind函数,用于绑定到本机指定的端点
95     ///
96     /// The bind() function is used to associate a socket with a particular IP address and port number on the local machine.
97     ///
98     /// @param endpoint 要绑定的端点
99     ///
100     /// @return 返回绑定是否成功
bind(&mut self, _endpoint: Endpoint) -> Result<(), SystemError>101     fn bind(&mut self, _endpoint: Endpoint) -> Result<(), SystemError> {
102         return Err(SystemError::ENOSYS);
103     }
104 
105     /// @brief 对应于 POSIX 的 shutdown 函数,用于关闭socket。
106     ///
107     /// shutdown() 函数用于启动网络连接的正常关闭。
108     /// 当在两个端点之间建立网络连接时,任一端点都可以通过调用其端点对象上的 shutdown() 函数来启动关闭序列。
109     /// 此函数向远程端点发送关闭消息以指示本地端点不再接受新数据。
110     ///
111     /// @return 返回是否成功关闭
shutdown(&self, _type: ShutdownType) -> Result<(), SystemError>112     fn shutdown(&self, _type: ShutdownType) -> Result<(), SystemError> {
113         return Err(SystemError::ENOSYS);
114     }
115 
116     /// @brief 对应于POSIX的listen函数,用于监听端点
117     ///
118     /// @param backlog 最大的等待连接数
119     ///
120     /// @return 返回监听是否成功
listen(&mut self, _backlog: usize) -> Result<(), SystemError>121     fn listen(&mut self, _backlog: usize) -> Result<(), SystemError> {
122         return Err(SystemError::ENOSYS);
123     }
124 
125     /// @brief 对应于POSIX的accept函数,用于接受连接
126     ///
127     /// @param endpoint 对端的端点
128     ///
129     /// @return 返回接受连接是否成功
accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError>130     fn accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError> {
131         return Err(SystemError::ENOSYS);
132     }
133 
134     /// @brief 获取socket的端点
135     ///
136     /// @return 返回socket的端点
endpoint(&self) -> Option<Endpoint>137     fn endpoint(&self) -> Option<Endpoint> {
138         return None;
139     }
140 
141     /// @brief 获取socket的对端端点
142     ///
143     /// @return 返回socket的对端端点
peer_endpoint(&self) -> Option<Endpoint>144     fn peer_endpoint(&self) -> Option<Endpoint> {
145         return None;
146     }
147 
148     /// @brief
149     ///     The purpose of the poll function is to provide
150     ///     a non-blocking way to check if a socket is ready for reading or writing,
151     ///     so that you can efficiently handle multiple sockets in a single thread or event loop.
152     ///
153     /// @return (in, out, err)
154     ///
155     ///     The first boolean value indicates whether the socket is ready for reading. If it is true, then there is data available to be read from the socket without blocking.
156     ///     The second boolean value indicates whether the socket is ready for writing. If it is true, then data can be written to the socket without blocking.
157     ///     The third boolean value indicates whether the socket has encountered an error condition. If it is true, then the socket is in an error state and should be closed or reset
158     ///
poll(&self) -> (bool, bool, bool)159     fn poll(&self) -> (bool, bool, bool) {
160         return (false, false, false);
161     }
162 
163     /// @brief socket的ioctl函数
164     ///
165     /// @param cmd ioctl命令
166     /// @param arg0 ioctl命令的第一个参数
167     /// @param arg1 ioctl命令的第二个参数
168     /// @param arg2 ioctl命令的第三个参数
169     ///
170     /// @return 返回ioctl命令的返回值
ioctl( &self, _cmd: usize, _arg0: usize, _arg1: usize, _arg2: usize, ) -> Result<usize, SystemError>171     fn ioctl(
172         &self,
173         _cmd: usize,
174         _arg0: usize,
175         _arg1: usize,
176         _arg2: usize,
177     ) -> Result<usize, SystemError> {
178         return Ok(0);
179     }
180 
181     /// @brief 获取socket的元数据
metadata(&self) -> Result<SocketMetadata, SystemError>182     fn metadata(&self) -> Result<SocketMetadata, SystemError>;
183 
box_clone(&self) -> Box<dyn Socket>184     fn box_clone(&self) -> Box<dyn Socket>;
185 
186     /// @brief 设置socket的选项
187     ///
188     /// @param level 选项的层次
189     /// @param optname 选项的名称
190     /// @param optval 选项的值
191     ///
192     /// @return 返回设置是否成功, 如果不支持该选项,返回ENOSYS
setsockopt( &self, _level: usize, _optname: usize, _optval: &[u8], ) -> Result<(), SystemError>193     fn setsockopt(
194         &self,
195         _level: usize,
196         _optname: usize,
197         _optval: &[u8],
198     ) -> Result<(), SystemError> {
199         kwarn!("setsockopt is not implemented");
200         return Err(SystemError::ENOSYS);
201     }
202 }
203 
204 impl Clone for Box<dyn Socket> {
clone(&self) -> Box<dyn Socket>205     fn clone(&self) -> Box<dyn Socket> {
206         self.box_clone()
207     }
208 }
209 
210 /// IP datagram encapsulated protocol.
211 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
212 #[repr(u8)]
213 pub enum Protocol {
214     HopByHop = 0x00,
215     Icmp = 0x01,
216     Igmp = 0x02,
217     Tcp = 0x06,
218     Udp = 0x11,
219     Ipv6Route = 0x2b,
220     Ipv6Frag = 0x2c,
221     Icmpv6 = 0x3a,
222     Ipv6NoNxt = 0x3b,
223     Ipv6Opts = 0x3c,
224     Unknown(u8),
225 }
226 
227 impl fmt::Display for Protocol {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result228     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
229         match *self {
230             Protocol::HopByHop => write!(f, "Hop-by-Hop"),
231             Protocol::Icmp => write!(f, "ICMP"),
232             Protocol::Igmp => write!(f, "IGMP"),
233             Protocol::Tcp => write!(f, "TCP"),
234             Protocol::Udp => write!(f, "UDP"),
235             Protocol::Ipv6Route => write!(f, "IPv6-Route"),
236             Protocol::Ipv6Frag => write!(f, "IPv6-Frag"),
237             Protocol::Icmpv6 => write!(f, "ICMPv6"),
238             Protocol::Ipv6NoNxt => write!(f, "IPv6-NoNxt"),
239             Protocol::Ipv6Opts => write!(f, "IPv6-Opts"),
240             Protocol::Unknown(id) => write!(f, "0x{id:02x}"),
241         }
242     }
243 }
244 
245 impl From<smoltcp::wire::IpProtocol> for Protocol {
from(value: smoltcp::wire::IpProtocol) -> Self246     fn from(value: smoltcp::wire::IpProtocol) -> Self {
247         let x: u8 = value.into();
248         Protocol::from(x)
249     }
250 }
251 
252 impl From<u8> for Protocol {
from(value: u8) -> Self253     fn from(value: u8) -> Self {
254         match value {
255             0x00 => Protocol::HopByHop,
256             0x01 => Protocol::Icmp,
257             0x02 => Protocol::Igmp,
258             0x06 => Protocol::Tcp,
259             0x11 => Protocol::Udp,
260             0x2b => Protocol::Ipv6Route,
261             0x2c => Protocol::Ipv6Frag,
262             0x3a => Protocol::Icmpv6,
263             0x3b => Protocol::Ipv6NoNxt,
264             0x3c => Protocol::Ipv6Opts,
265             _ => Protocol::Unknown(value),
266         }
267     }
268 }
269 
270 impl Into<u8> for Protocol {
into(self) -> u8271     fn into(self) -> u8 {
272         match self {
273             Protocol::HopByHop => 0x00,
274             Protocol::Icmp => 0x01,
275             Protocol::Igmp => 0x02,
276             Protocol::Tcp => 0x06,
277             Protocol::Udp => 0x11,
278             Protocol::Ipv6Route => 0x2b,
279             Protocol::Ipv6Frag => 0x2c,
280             Protocol::Icmpv6 => 0x3a,
281             Protocol::Ipv6NoNxt => 0x3b,
282             Protocol::Ipv6Opts => 0x3c,
283             Protocol::Unknown(id) => id,
284         }
285     }
286 }
287