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