xref: /DragonOS/kernel/src/net/mod.rs (revision 406099704eb939ae23b18f0cfb3ed36c534c1c84)
113776c11Slogin use core::{
213776c11Slogin     fmt::{self, Debug},
313776c11Slogin     sync::atomic::AtomicUsize,
413776c11Slogin };
54454d1a2Slogin 
6*40609970SGnoCiYeH use alloc::{
7*40609970SGnoCiYeH     boxed::Box,
8*40609970SGnoCiYeH     collections::BTreeMap,
9*40609970SGnoCiYeH     sync::{Arc, Weak},
10*40609970SGnoCiYeH };
1113776c11Slogin 
12*40609970SGnoCiYeH use crate::{
13*40609970SGnoCiYeH     driver::net::NetDriver,
14*40609970SGnoCiYeH     kwarn,
15*40609970SGnoCiYeH     libs::{rwlock::RwLock, spinlock::SpinLock},
16*40609970SGnoCiYeH     net::event_poll::EventPoll,
17*40609970SGnoCiYeH     syscall::SystemError,
18*40609970SGnoCiYeH };
19*40609970SGnoCiYeH use smoltcp::{iface::SocketHandle, wire::IpEndpoint};
2013776c11Slogin 
21*40609970SGnoCiYeH use self::{
22*40609970SGnoCiYeH     event_poll::{EPollEventType, EPollItem},
23*40609970SGnoCiYeH     socket::{SocketMetadata, HANDLE_MAP},
24*40609970SGnoCiYeH };
2513776c11Slogin 
2613776c11Slogin pub mod endpoints;
27*40609970SGnoCiYeH pub mod event_poll;
2813776c11Slogin pub mod net_core;
2913776c11Slogin pub mod socket;
30cde5492fSlogin pub mod syscall;
3113776c11Slogin 
3213776c11Slogin lazy_static! {
3313776c11Slogin     /// @brief 所有网络接口的列表
3413776c11Slogin     pub static ref NET_DRIVERS: RwLock<BTreeMap<usize, Arc<dyn NetDriver>>> = RwLock::new(BTreeMap::new());
3513776c11Slogin }
3613776c11Slogin 
3713776c11Slogin /// @brief 生成网络接口的id (全局自增)
3813776c11Slogin pub fn generate_iface_id() -> usize {
3913776c11Slogin     static IFACE_ID: AtomicUsize = AtomicUsize::new(0);
4013776c11Slogin     return IFACE_ID
4113776c11Slogin         .fetch_add(1, core::sync::atomic::Ordering::SeqCst)
4213776c11Slogin         .into();
4313776c11Slogin }
4413776c11Slogin 
45*40609970SGnoCiYeH bitflags! {
4613776c11Slogin     /// @brief 用于指定socket的关闭类型
47*40609970SGnoCiYeH     /// 参考:https://opengrok.ringotek.cn/xref/linux-6.1.9/include/net/sock.h?fi=SHUTDOWN_MASK#1573
48*40609970SGnoCiYeH     pub struct ShutdownType: u8 {
49*40609970SGnoCiYeH         const RCV_SHUTDOWN = 1;
50*40609970SGnoCiYeH         const SEND_SHUTDOWN = 2;
51*40609970SGnoCiYeH         const SHUTDOWN_MASK = 3;
52cde5492fSlogin     }
5313776c11Slogin }
5413776c11Slogin 
5513776c11Slogin #[derive(Debug, Clone)]
5613776c11Slogin pub enum Endpoint {
5713776c11Slogin     /// 链路层端点
5813776c11Slogin     LinkLayer(endpoints::LinkLayerEndpoint),
5913776c11Slogin     /// 网络层端点
60cde5492fSlogin     Ip(Option<IpEndpoint>),
6113776c11Slogin     // todo: 增加NetLink机制后,增加NetLink端点
6213776c11Slogin }
634454d1a2Slogin 
644454d1a2Slogin pub trait Socket: Sync + Send + Debug {
6513776c11Slogin     /// @brief 从socket中读取数据,如果socket是阻塞的,那么直到读取到数据才返回
6613776c11Slogin     ///
6713776c11Slogin     /// @param buf 读取到的数据存放的缓冲区
6813776c11Slogin     ///
6913776c11Slogin     /// @return - 成功:(返回读取的数据的长度,读取数据的端点).
7013776c11Slogin     ///         - 失败:错误码
71*40609970SGnoCiYeH     fn read(&mut self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint);
724454d1a2Slogin 
7313776c11Slogin     /// @brief 向socket中写入数据。如果socket是阻塞的,那么直到写入的数据全部写入socket中才返回
7413776c11Slogin     ///
7513776c11Slogin     /// @param buf 要写入的数据
7613776c11Slogin     /// @param to 要写入的目的端点,如果是None,那么写入的数据将会被丢弃
7713776c11Slogin     ///
7813776c11Slogin     /// @return 返回写入的数据的长度
7913776c11Slogin     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError>;
8013776c11Slogin 
8113776c11Slogin     /// @brief 对应于POSIX的connect函数,用于连接到指定的远程服务器端点
8213776c11Slogin     ///
8313776c11Slogin     /// It is used to establish a connection to a remote server.
8413776c11Slogin     /// When a socket is connected to a remote server,
8513776c11Slogin     /// the operating system will establish a network connection with the server
8613776c11Slogin     /// and allow data to be sent and received between the local socket and the remote server.
8713776c11Slogin     ///
8813776c11Slogin     /// @param endpoint 要连接的端点
8913776c11Slogin     ///
9013776c11Slogin     /// @return 返回连接是否成功
9113776c11Slogin     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError>;
9213776c11Slogin 
9313776c11Slogin     /// @brief 对应于POSIX的bind函数,用于绑定到本机指定的端点
9413776c11Slogin     ///
9513776c11Slogin     /// The bind() function is used to associate a socket with a particular IP address and port number on the local machine.
9613776c11Slogin     ///
9713776c11Slogin     /// @param endpoint 要绑定的端点
9813776c11Slogin     ///
9913776c11Slogin     /// @return 返回绑定是否成功
100cde5492fSlogin     fn bind(&mut self, _endpoint: Endpoint) -> Result<(), SystemError> {
10113776c11Slogin         return Err(SystemError::ENOSYS);
10213776c11Slogin     }
10313776c11Slogin 
10413776c11Slogin     /// @brief 对应于 POSIX 的 shutdown 函数,用于关闭socket。
10513776c11Slogin     ///
10613776c11Slogin     /// shutdown() 函数用于启动网络连接的正常关闭。
10713776c11Slogin     /// 当在两个端点之间建立网络连接时,任一端点都可以通过调用其端点对象上的 shutdown() 函数来启动关闭序列。
10813776c11Slogin     /// 此函数向远程端点发送关闭消息以指示本地端点不再接受新数据。
10913776c11Slogin     ///
11013776c11Slogin     /// @return 返回是否成功关闭
111*40609970SGnoCiYeH     fn shutdown(&mut self, _type: ShutdownType) -> Result<(), SystemError> {
11213776c11Slogin         return Err(SystemError::ENOSYS);
11313776c11Slogin     }
11413776c11Slogin 
11513776c11Slogin     /// @brief 对应于POSIX的listen函数,用于监听端点
11613776c11Slogin     ///
11713776c11Slogin     /// @param backlog 最大的等待连接数
11813776c11Slogin     ///
11913776c11Slogin     /// @return 返回监听是否成功
12013776c11Slogin     fn listen(&mut self, _backlog: usize) -> Result<(), SystemError> {
12113776c11Slogin         return Err(SystemError::ENOSYS);
12213776c11Slogin     }
12313776c11Slogin 
12413776c11Slogin     /// @brief 对应于POSIX的accept函数,用于接受连接
12513776c11Slogin     ///
126cde5492fSlogin     /// @param endpoint 对端的端点
12713776c11Slogin     ///
12813776c11Slogin     /// @return 返回接受连接是否成功
12913776c11Slogin     fn accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError> {
13013776c11Slogin         return Err(SystemError::ENOSYS);
13113776c11Slogin     }
13213776c11Slogin 
13313776c11Slogin     /// @brief 获取socket的端点
13413776c11Slogin     ///
13513776c11Slogin     /// @return 返回socket的端点
13613776c11Slogin     fn endpoint(&self) -> Option<Endpoint> {
13713776c11Slogin         return None;
13813776c11Slogin     }
13913776c11Slogin 
14013776c11Slogin     /// @brief 获取socket的对端端点
14113776c11Slogin     ///
14213776c11Slogin     /// @return 返回socket的对端端点
14313776c11Slogin     fn peer_endpoint(&self) -> Option<Endpoint> {
14413776c11Slogin         return None;
14513776c11Slogin     }
14613776c11Slogin 
14713776c11Slogin     /// @brief
14813776c11Slogin     ///     The purpose of the poll function is to provide
14913776c11Slogin     ///     a non-blocking way to check if a socket is ready for reading or writing,
15013776c11Slogin     ///     so that you can efficiently handle multiple sockets in a single thread or event loop.
15113776c11Slogin     ///
15213776c11Slogin     /// @return (in, out, err)
15313776c11Slogin     ///
15413776c11Slogin     ///     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.
15513776c11Slogin     ///     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.
15613776c11Slogin     ///     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
15713776c11Slogin     ///
158*40609970SGnoCiYeH     fn poll(&self) -> EPollEventType {
159*40609970SGnoCiYeH         return EPollEventType::empty();
16013776c11Slogin     }
16113776c11Slogin 
16213776c11Slogin     /// @brief socket的ioctl函数
16313776c11Slogin     ///
16413776c11Slogin     /// @param cmd ioctl命令
16513776c11Slogin     /// @param arg0 ioctl命令的第一个参数
16613776c11Slogin     /// @param arg1 ioctl命令的第二个参数
16713776c11Slogin     /// @param arg2 ioctl命令的第三个参数
16813776c11Slogin     ///
16913776c11Slogin     /// @return 返回ioctl命令的返回值
17013776c11Slogin     fn ioctl(
17113776c11Slogin         &self,
17213776c11Slogin         _cmd: usize,
17313776c11Slogin         _arg0: usize,
17413776c11Slogin         _arg1: usize,
17513776c11Slogin         _arg2: usize,
17613776c11Slogin     ) -> Result<usize, SystemError> {
17713776c11Slogin         return Ok(0);
17813776c11Slogin     }
17913776c11Slogin 
18013776c11Slogin     /// @brief 获取socket的元数据
18113776c11Slogin     fn metadata(&self) -> Result<SocketMetadata, SystemError>;
18213776c11Slogin 
18313776c11Slogin     fn box_clone(&self) -> Box<dyn Socket>;
184cde5492fSlogin 
185cde5492fSlogin     /// @brief 设置socket的选项
186cde5492fSlogin     ///
187cde5492fSlogin     /// @param level 选项的层次
188cde5492fSlogin     /// @param optname 选项的名称
189cde5492fSlogin     /// @param optval 选项的值
190cde5492fSlogin     ///
191cde5492fSlogin     /// @return 返回设置是否成功, 如果不支持该选项,返回ENOSYS
192cde5492fSlogin     fn setsockopt(
193cde5492fSlogin         &self,
194cde5492fSlogin         _level: usize,
195cde5492fSlogin         _optname: usize,
196cde5492fSlogin         _optval: &[u8],
197cde5492fSlogin     ) -> Result<(), SystemError> {
198cde5492fSlogin         kwarn!("setsockopt is not implemented");
199393f6915SLoGin         return Ok(());
200cde5492fSlogin     }
201*40609970SGnoCiYeH 
202*40609970SGnoCiYeH     fn socket_handle(&self) -> SocketHandle;
203*40609970SGnoCiYeH 
204*40609970SGnoCiYeH     fn add_epoll(&mut self, epitem: Arc<EPollItem>) -> Result<(), SystemError> {
205*40609970SGnoCiYeH         HANDLE_MAP
206*40609970SGnoCiYeH             .write_irqsave()
207*40609970SGnoCiYeH             .get_mut(&self.socket_handle())
208*40609970SGnoCiYeH             .unwrap()
209*40609970SGnoCiYeH             .add_epoll(epitem);
210*40609970SGnoCiYeH         Ok(())
211*40609970SGnoCiYeH     }
212*40609970SGnoCiYeH 
213*40609970SGnoCiYeH     fn remove_epoll(
214*40609970SGnoCiYeH         &mut self,
215*40609970SGnoCiYeH         epoll: &Weak<SpinLock<event_poll::EventPoll>>,
216*40609970SGnoCiYeH     ) -> Result<(), SystemError> {
217*40609970SGnoCiYeH         HANDLE_MAP
218*40609970SGnoCiYeH             .write_irqsave()
219*40609970SGnoCiYeH             .get_mut(&self.socket_handle())
220*40609970SGnoCiYeH             .unwrap()
221*40609970SGnoCiYeH             .remove_epoll(epoll)?;
222*40609970SGnoCiYeH 
223*40609970SGnoCiYeH         Ok(())
224*40609970SGnoCiYeH     }
225*40609970SGnoCiYeH 
226*40609970SGnoCiYeH     fn clear_epoll(&mut self) -> Result<(), SystemError> {
227*40609970SGnoCiYeH         let mut handle_map_guard = HANDLE_MAP.write_irqsave();
228*40609970SGnoCiYeH         let handle_item = handle_map_guard.get_mut(&self.socket_handle()).unwrap();
229*40609970SGnoCiYeH 
230*40609970SGnoCiYeH         for epitem in handle_item.epitems.lock_irqsave().iter() {
231*40609970SGnoCiYeH             let epoll = epitem.epoll();
232*40609970SGnoCiYeH             let _ = EventPoll::ep_remove(
233*40609970SGnoCiYeH                 &mut epoll.upgrade().unwrap().lock_irqsave(),
234*40609970SGnoCiYeH                 epitem.fd(),
235*40609970SGnoCiYeH                 None,
236*40609970SGnoCiYeH             );
237*40609970SGnoCiYeH         }
238*40609970SGnoCiYeH 
239*40609970SGnoCiYeH         Ok(())
240*40609970SGnoCiYeH     }
24113776c11Slogin }
24213776c11Slogin 
24313776c11Slogin impl Clone for Box<dyn Socket> {
24413776c11Slogin     fn clone(&self) -> Box<dyn Socket> {
24513776c11Slogin         self.box_clone()
24613776c11Slogin     }
24713776c11Slogin }
24813776c11Slogin 
24913776c11Slogin /// IP datagram encapsulated protocol.
25013776c11Slogin #[derive(Debug, PartialEq, Eq, Clone, Copy)]
25113776c11Slogin #[repr(u8)]
25213776c11Slogin pub enum Protocol {
25313776c11Slogin     HopByHop = 0x00,
25413776c11Slogin     Icmp = 0x01,
25513776c11Slogin     Igmp = 0x02,
25613776c11Slogin     Tcp = 0x06,
25713776c11Slogin     Udp = 0x11,
25813776c11Slogin     Ipv6Route = 0x2b,
25913776c11Slogin     Ipv6Frag = 0x2c,
26013776c11Slogin     Icmpv6 = 0x3a,
26113776c11Slogin     Ipv6NoNxt = 0x3b,
26213776c11Slogin     Ipv6Opts = 0x3c,
26313776c11Slogin     Unknown(u8),
26413776c11Slogin }
26513776c11Slogin 
26613776c11Slogin impl fmt::Display for Protocol {
26713776c11Slogin     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26813776c11Slogin         match *self {
26913776c11Slogin             Protocol::HopByHop => write!(f, "Hop-by-Hop"),
27013776c11Slogin             Protocol::Icmp => write!(f, "ICMP"),
27113776c11Slogin             Protocol::Igmp => write!(f, "IGMP"),
27213776c11Slogin             Protocol::Tcp => write!(f, "TCP"),
27313776c11Slogin             Protocol::Udp => write!(f, "UDP"),
27413776c11Slogin             Protocol::Ipv6Route => write!(f, "IPv6-Route"),
27513776c11Slogin             Protocol::Ipv6Frag => write!(f, "IPv6-Frag"),
27613776c11Slogin             Protocol::Icmpv6 => write!(f, "ICMPv6"),
27713776c11Slogin             Protocol::Ipv6NoNxt => write!(f, "IPv6-NoNxt"),
27813776c11Slogin             Protocol::Ipv6Opts => write!(f, "IPv6-Opts"),
27913776c11Slogin             Protocol::Unknown(id) => write!(f, "0x{id:02x}"),
28013776c11Slogin         }
28113776c11Slogin     }
28213776c11Slogin }
28313776c11Slogin 
28413776c11Slogin impl From<smoltcp::wire::IpProtocol> for Protocol {
28513776c11Slogin     fn from(value: smoltcp::wire::IpProtocol) -> Self {
28613776c11Slogin         let x: u8 = value.into();
28713776c11Slogin         Protocol::from(x)
28813776c11Slogin     }
28913776c11Slogin }
29013776c11Slogin 
29113776c11Slogin impl From<u8> for Protocol {
29213776c11Slogin     fn from(value: u8) -> Self {
29313776c11Slogin         match value {
29413776c11Slogin             0x00 => Protocol::HopByHop,
29513776c11Slogin             0x01 => Protocol::Icmp,
29613776c11Slogin             0x02 => Protocol::Igmp,
29713776c11Slogin             0x06 => Protocol::Tcp,
29813776c11Slogin             0x11 => Protocol::Udp,
29913776c11Slogin             0x2b => Protocol::Ipv6Route,
30013776c11Slogin             0x2c => Protocol::Ipv6Frag,
30113776c11Slogin             0x3a => Protocol::Icmpv6,
30213776c11Slogin             0x3b => Protocol::Ipv6NoNxt,
30313776c11Slogin             0x3c => Protocol::Ipv6Opts,
30413776c11Slogin             _ => Protocol::Unknown(value),
30513776c11Slogin         }
30613776c11Slogin     }
30713776c11Slogin }
30813776c11Slogin 
30913776c11Slogin impl Into<u8> for Protocol {
31013776c11Slogin     fn into(self) -> u8 {
31113776c11Slogin         match self {
31213776c11Slogin             Protocol::HopByHop => 0x00,
31313776c11Slogin             Protocol::Icmp => 0x01,
31413776c11Slogin             Protocol::Igmp => 0x02,
31513776c11Slogin             Protocol::Tcp => 0x06,
31613776c11Slogin             Protocol::Udp => 0x11,
31713776c11Slogin             Protocol::Ipv6Route => 0x2b,
31813776c11Slogin             Protocol::Ipv6Frag => 0x2c,
31913776c11Slogin             Protocol::Icmpv6 => 0x3a,
32013776c11Slogin             Protocol::Ipv6NoNxt => 0x3b,
32113776c11Slogin             Protocol::Ipv6Opts => 0x3c,
32213776c11Slogin             Protocol::Unknown(id) => id,
32313776c11Slogin         }
32413776c11Slogin     }
3254454d1a2Slogin }
326