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