xref: /DragonOS/kernel/src/net/mod.rs (revision e7071df6a47c100381a8bc2000022e82d422361a)
113776c11Slogin use core::{
213776c11Slogin     fmt::{self, Debug},
313776c11Slogin     sync::atomic::AtomicUsize,
413776c11Slogin };
54454d1a2Slogin 
640609970SGnoCiYeH use alloc::{
740609970SGnoCiYeH     boxed::Box,
840609970SGnoCiYeH     collections::BTreeMap,
940609970SGnoCiYeH     sync::{Arc, Weak},
1040609970SGnoCiYeH };
1191e9d4abSLoGin use system_error::SystemError;
1213776c11Slogin 
1340609970SGnoCiYeH use crate::{
1440609970SGnoCiYeH     driver::net::NetDriver,
1540609970SGnoCiYeH     kwarn,
1640609970SGnoCiYeH     libs::{rwlock::RwLock, spinlock::SpinLock},
1740609970SGnoCiYeH     net::event_poll::EventPoll,
1840609970SGnoCiYeH };
1940609970SGnoCiYeH use smoltcp::{iface::SocketHandle, wire::IpEndpoint};
2013776c11Slogin 
2140609970SGnoCiYeH use self::{
2240609970SGnoCiYeH     event_poll::{EPollEventType, EPollItem},
2340609970SGnoCiYeH     socket::{SocketMetadata, HANDLE_MAP},
2440609970SGnoCiYeH };
2513776c11Slogin 
2613776c11Slogin pub mod endpoints;
2740609970SGnoCiYeH pub mod event_poll;
2813776c11Slogin pub mod net_core;
2913776c11Slogin pub mod socket;
30cde5492fSlogin pub mod syscall;
3113776c11Slogin 
3213776c11Slogin lazy_static! {
330d6cf65aSLoGin     /// 所有网络接口的列表
340d6cf65aSLoGin     ///
350d6cf65aSLoGin     /// 这个列表在中断上下文会使用到,因此需要irqsave
3613776c11Slogin     pub static ref NET_DRIVERS: RwLock<BTreeMap<usize, Arc<dyn NetDriver>>> = RwLock::new(BTreeMap::new());
3713776c11Slogin }
3813776c11Slogin 
390d6cf65aSLoGin /// 生成网络接口的id (全局自增)
4013776c11Slogin pub fn generate_iface_id() -> usize {
4113776c11Slogin     static IFACE_ID: AtomicUsize = AtomicUsize::new(0);
4213776c11Slogin     return IFACE_ID
4313776c11Slogin         .fetch_add(1, core::sync::atomic::Ordering::SeqCst)
4413776c11Slogin         .into();
4513776c11Slogin }
4613776c11Slogin 
4740609970SGnoCiYeH bitflags! {
4813776c11Slogin     /// @brief 用于指定socket的关闭类型
49*e7071df6SLoGin     /// 参考:https://code.dragonos.org.cn/xref/linux-6.1.9/include/net/sock.h?fi=SHUTDOWN_MASK#1573
5040609970SGnoCiYeH     pub struct ShutdownType: u8 {
5140609970SGnoCiYeH         const RCV_SHUTDOWN = 1;
5240609970SGnoCiYeH         const SEND_SHUTDOWN = 2;
5340609970SGnoCiYeH         const SHUTDOWN_MASK = 3;
54cde5492fSlogin     }
5513776c11Slogin }
5613776c11Slogin 
5713776c11Slogin #[derive(Debug, Clone)]
5813776c11Slogin pub enum Endpoint {
5913776c11Slogin     /// 链路层端点
6013776c11Slogin     LinkLayer(endpoints::LinkLayerEndpoint),
6113776c11Slogin     /// 网络层端点
62cde5492fSlogin     Ip(Option<IpEndpoint>),
6313776c11Slogin     // todo: 增加NetLink机制后,增加NetLink端点
6413776c11Slogin }
654454d1a2Slogin 
664454d1a2Slogin pub trait Socket: Sync + Send + Debug {
6713776c11Slogin     /// @brief 从socket中读取数据,如果socket是阻塞的,那么直到读取到数据才返回
6813776c11Slogin     ///
6913776c11Slogin     /// @param buf 读取到的数据存放的缓冲区
7013776c11Slogin     ///
7113776c11Slogin     /// @return - 成功:(返回读取的数据的长度,读取数据的端点).
7213776c11Slogin     ///         - 失败:错误码
7340609970SGnoCiYeH     fn read(&mut self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint);
744454d1a2Slogin 
7513776c11Slogin     /// @brief 向socket中写入数据。如果socket是阻塞的,那么直到写入的数据全部写入socket中才返回
7613776c11Slogin     ///
7713776c11Slogin     /// @param buf 要写入的数据
7813776c11Slogin     /// @param to 要写入的目的端点,如果是None,那么写入的数据将会被丢弃
7913776c11Slogin     ///
8013776c11Slogin     /// @return 返回写入的数据的长度
8113776c11Slogin     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError>;
8213776c11Slogin 
8313776c11Slogin     /// @brief 对应于POSIX的connect函数,用于连接到指定的远程服务器端点
8413776c11Slogin     ///
8513776c11Slogin     /// It is used to establish a connection to a remote server.
8613776c11Slogin     /// When a socket is connected to a remote server,
8713776c11Slogin     /// the operating system will establish a network connection with the server
8813776c11Slogin     /// and allow data to be sent and received between the local socket and the remote server.
8913776c11Slogin     ///
9013776c11Slogin     /// @param endpoint 要连接的端点
9113776c11Slogin     ///
9213776c11Slogin     /// @return 返回连接是否成功
9313776c11Slogin     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError>;
9413776c11Slogin 
9513776c11Slogin     /// @brief 对应于POSIX的bind函数,用于绑定到本机指定的端点
9613776c11Slogin     ///
9713776c11Slogin     /// The bind() function is used to associate a socket with a particular IP address and port number on the local machine.
9813776c11Slogin     ///
9913776c11Slogin     /// @param endpoint 要绑定的端点
10013776c11Slogin     ///
10113776c11Slogin     /// @return 返回绑定是否成功
102cde5492fSlogin     fn bind(&mut self, _endpoint: Endpoint) -> Result<(), SystemError> {
10313776c11Slogin         return Err(SystemError::ENOSYS);
10413776c11Slogin     }
10513776c11Slogin 
10613776c11Slogin     /// @brief 对应于 POSIX 的 shutdown 函数,用于关闭socket。
10713776c11Slogin     ///
10813776c11Slogin     /// shutdown() 函数用于启动网络连接的正常关闭。
10913776c11Slogin     /// 当在两个端点之间建立网络连接时,任一端点都可以通过调用其端点对象上的 shutdown() 函数来启动关闭序列。
11013776c11Slogin     /// 此函数向远程端点发送关闭消息以指示本地端点不再接受新数据。
11113776c11Slogin     ///
11213776c11Slogin     /// @return 返回是否成功关闭
11340609970SGnoCiYeH     fn shutdown(&mut self, _type: ShutdownType) -> Result<(), SystemError> {
11413776c11Slogin         return Err(SystemError::ENOSYS);
11513776c11Slogin     }
11613776c11Slogin 
11713776c11Slogin     /// @brief 对应于POSIX的listen函数,用于监听端点
11813776c11Slogin     ///
11913776c11Slogin     /// @param backlog 最大的等待连接数
12013776c11Slogin     ///
12113776c11Slogin     /// @return 返回监听是否成功
12213776c11Slogin     fn listen(&mut self, _backlog: usize) -> Result<(), SystemError> {
12313776c11Slogin         return Err(SystemError::ENOSYS);
12413776c11Slogin     }
12513776c11Slogin 
12613776c11Slogin     /// @brief 对应于POSIX的accept函数,用于接受连接
12713776c11Slogin     ///
128cde5492fSlogin     /// @param endpoint 对端的端点
12913776c11Slogin     ///
13013776c11Slogin     /// @return 返回接受连接是否成功
13113776c11Slogin     fn accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError> {
13213776c11Slogin         return Err(SystemError::ENOSYS);
13313776c11Slogin     }
13413776c11Slogin 
13513776c11Slogin     /// @brief 获取socket的端点
13613776c11Slogin     ///
13713776c11Slogin     /// @return 返回socket的端点
13813776c11Slogin     fn endpoint(&self) -> Option<Endpoint> {
13913776c11Slogin         return None;
14013776c11Slogin     }
14113776c11Slogin 
14213776c11Slogin     /// @brief 获取socket的对端端点
14313776c11Slogin     ///
14413776c11Slogin     /// @return 返回socket的对端端点
14513776c11Slogin     fn peer_endpoint(&self) -> Option<Endpoint> {
14613776c11Slogin         return None;
14713776c11Slogin     }
14813776c11Slogin 
14913776c11Slogin     /// @brief
15013776c11Slogin     ///     The purpose of the poll function is to provide
15113776c11Slogin     ///     a non-blocking way to check if a socket is ready for reading or writing,
15213776c11Slogin     ///     so that you can efficiently handle multiple sockets in a single thread or event loop.
15313776c11Slogin     ///
15413776c11Slogin     /// @return (in, out, err)
15513776c11Slogin     ///
15613776c11Slogin     ///     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.
15713776c11Slogin     ///     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.
15813776c11Slogin     ///     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
15913776c11Slogin     ///
16040609970SGnoCiYeH     fn poll(&self) -> EPollEventType {
16140609970SGnoCiYeH         return EPollEventType::empty();
16213776c11Slogin     }
16313776c11Slogin 
16413776c11Slogin     /// @brief socket的ioctl函数
16513776c11Slogin     ///
16613776c11Slogin     /// @param cmd ioctl命令
16713776c11Slogin     /// @param arg0 ioctl命令的第一个参数
16813776c11Slogin     /// @param arg1 ioctl命令的第二个参数
16913776c11Slogin     /// @param arg2 ioctl命令的第三个参数
17013776c11Slogin     ///
17113776c11Slogin     /// @return 返回ioctl命令的返回值
17213776c11Slogin     fn ioctl(
17313776c11Slogin         &self,
17413776c11Slogin         _cmd: usize,
17513776c11Slogin         _arg0: usize,
17613776c11Slogin         _arg1: usize,
17713776c11Slogin         _arg2: usize,
17813776c11Slogin     ) -> Result<usize, SystemError> {
17913776c11Slogin         return Ok(0);
18013776c11Slogin     }
18113776c11Slogin 
18213776c11Slogin     /// @brief 获取socket的元数据
18313776c11Slogin     fn metadata(&self) -> Result<SocketMetadata, SystemError>;
18413776c11Slogin 
18513776c11Slogin     fn box_clone(&self) -> Box<dyn Socket>;
186cde5492fSlogin 
187cde5492fSlogin     /// @brief 设置socket的选项
188cde5492fSlogin     ///
189cde5492fSlogin     /// @param level 选项的层次
190cde5492fSlogin     /// @param optname 选项的名称
191cde5492fSlogin     /// @param optval 选项的值
192cde5492fSlogin     ///
193cde5492fSlogin     /// @return 返回设置是否成功, 如果不支持该选项,返回ENOSYS
194cde5492fSlogin     fn setsockopt(
195cde5492fSlogin         &self,
196cde5492fSlogin         _level: usize,
197cde5492fSlogin         _optname: usize,
198cde5492fSlogin         _optval: &[u8],
199cde5492fSlogin     ) -> Result<(), SystemError> {
200cde5492fSlogin         kwarn!("setsockopt is not implemented");
201393f6915SLoGin         return Ok(());
202cde5492fSlogin     }
20340609970SGnoCiYeH 
20440609970SGnoCiYeH     fn socket_handle(&self) -> SocketHandle;
20540609970SGnoCiYeH 
20640609970SGnoCiYeH     fn add_epoll(&mut self, epitem: Arc<EPollItem>) -> Result<(), SystemError> {
20740609970SGnoCiYeH         HANDLE_MAP
20840609970SGnoCiYeH             .write_irqsave()
20940609970SGnoCiYeH             .get_mut(&self.socket_handle())
21040609970SGnoCiYeH             .unwrap()
21140609970SGnoCiYeH             .add_epoll(epitem);
21240609970SGnoCiYeH         Ok(())
21340609970SGnoCiYeH     }
21440609970SGnoCiYeH 
21540609970SGnoCiYeH     fn remove_epoll(
21640609970SGnoCiYeH         &mut self,
21740609970SGnoCiYeH         epoll: &Weak<SpinLock<event_poll::EventPoll>>,
21840609970SGnoCiYeH     ) -> Result<(), SystemError> {
21940609970SGnoCiYeH         HANDLE_MAP
22040609970SGnoCiYeH             .write_irqsave()
22140609970SGnoCiYeH             .get_mut(&self.socket_handle())
22240609970SGnoCiYeH             .unwrap()
22340609970SGnoCiYeH             .remove_epoll(epoll)?;
22440609970SGnoCiYeH 
22540609970SGnoCiYeH         Ok(())
22640609970SGnoCiYeH     }
22740609970SGnoCiYeH 
22840609970SGnoCiYeH     fn clear_epoll(&mut self) -> Result<(), SystemError> {
22940609970SGnoCiYeH         let mut handle_map_guard = HANDLE_MAP.write_irqsave();
23040609970SGnoCiYeH         let handle_item = handle_map_guard.get_mut(&self.socket_handle()).unwrap();
23140609970SGnoCiYeH 
23240609970SGnoCiYeH         for epitem in handle_item.epitems.lock_irqsave().iter() {
23340609970SGnoCiYeH             let epoll = epitem.epoll();
2345e948c56SGnoCiYeH             if epoll.upgrade().is_some() {
23540609970SGnoCiYeH                 let _ = EventPoll::ep_remove(
23640609970SGnoCiYeH                     &mut epoll.upgrade().unwrap().lock_irqsave(),
23740609970SGnoCiYeH                     epitem.fd(),
23840609970SGnoCiYeH                     None,
23940609970SGnoCiYeH                 );
24040609970SGnoCiYeH             }
2415e948c56SGnoCiYeH         }
24240609970SGnoCiYeH 
24340609970SGnoCiYeH         Ok(())
24440609970SGnoCiYeH     }
24513776c11Slogin }
24613776c11Slogin 
24713776c11Slogin impl Clone for Box<dyn Socket> {
24813776c11Slogin     fn clone(&self) -> Box<dyn Socket> {
24913776c11Slogin         self.box_clone()
25013776c11Slogin     }
25113776c11Slogin }
25213776c11Slogin 
25313776c11Slogin /// IP datagram encapsulated protocol.
25413776c11Slogin #[derive(Debug, PartialEq, Eq, Clone, Copy)]
25513776c11Slogin #[repr(u8)]
25613776c11Slogin pub enum Protocol {
25713776c11Slogin     HopByHop = 0x00,
25813776c11Slogin     Icmp = 0x01,
25913776c11Slogin     Igmp = 0x02,
26013776c11Slogin     Tcp = 0x06,
26113776c11Slogin     Udp = 0x11,
26213776c11Slogin     Ipv6Route = 0x2b,
26313776c11Slogin     Ipv6Frag = 0x2c,
26413776c11Slogin     Icmpv6 = 0x3a,
26513776c11Slogin     Ipv6NoNxt = 0x3b,
26613776c11Slogin     Ipv6Opts = 0x3c,
26713776c11Slogin     Unknown(u8),
26813776c11Slogin }
26913776c11Slogin 
27013776c11Slogin impl fmt::Display for Protocol {
27113776c11Slogin     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27213776c11Slogin         match *self {
27313776c11Slogin             Protocol::HopByHop => write!(f, "Hop-by-Hop"),
27413776c11Slogin             Protocol::Icmp => write!(f, "ICMP"),
27513776c11Slogin             Protocol::Igmp => write!(f, "IGMP"),
27613776c11Slogin             Protocol::Tcp => write!(f, "TCP"),
27713776c11Slogin             Protocol::Udp => write!(f, "UDP"),
27813776c11Slogin             Protocol::Ipv6Route => write!(f, "IPv6-Route"),
27913776c11Slogin             Protocol::Ipv6Frag => write!(f, "IPv6-Frag"),
28013776c11Slogin             Protocol::Icmpv6 => write!(f, "ICMPv6"),
28113776c11Slogin             Protocol::Ipv6NoNxt => write!(f, "IPv6-NoNxt"),
28213776c11Slogin             Protocol::Ipv6Opts => write!(f, "IPv6-Opts"),
28313776c11Slogin             Protocol::Unknown(id) => write!(f, "0x{id:02x}"),
28413776c11Slogin         }
28513776c11Slogin     }
28613776c11Slogin }
28713776c11Slogin 
28813776c11Slogin impl From<smoltcp::wire::IpProtocol> for Protocol {
28913776c11Slogin     fn from(value: smoltcp::wire::IpProtocol) -> Self {
29013776c11Slogin         let x: u8 = value.into();
29113776c11Slogin         Protocol::from(x)
29213776c11Slogin     }
29313776c11Slogin }
29413776c11Slogin 
29513776c11Slogin impl From<u8> for Protocol {
29613776c11Slogin     fn from(value: u8) -> Self {
29713776c11Slogin         match value {
29813776c11Slogin             0x00 => Protocol::HopByHop,
29913776c11Slogin             0x01 => Protocol::Icmp,
30013776c11Slogin             0x02 => Protocol::Igmp,
30113776c11Slogin             0x06 => Protocol::Tcp,
30213776c11Slogin             0x11 => Protocol::Udp,
30313776c11Slogin             0x2b => Protocol::Ipv6Route,
30413776c11Slogin             0x2c => Protocol::Ipv6Frag,
30513776c11Slogin             0x3a => Protocol::Icmpv6,
30613776c11Slogin             0x3b => Protocol::Ipv6NoNxt,
30713776c11Slogin             0x3c => Protocol::Ipv6Opts,
30813776c11Slogin             _ => Protocol::Unknown(value),
30913776c11Slogin         }
31013776c11Slogin     }
31113776c11Slogin }
31213776c11Slogin 
31313776c11Slogin impl Into<u8> for Protocol {
31413776c11Slogin     fn into(self) -> u8 {
31513776c11Slogin         match self {
31613776c11Slogin             Protocol::HopByHop => 0x00,
31713776c11Slogin             Protocol::Icmp => 0x01,
31813776c11Slogin             Protocol::Igmp => 0x02,
31913776c11Slogin             Protocol::Tcp => 0x06,
32013776c11Slogin             Protocol::Udp => 0x11,
32113776c11Slogin             Protocol::Ipv6Route => 0x2b,
32213776c11Slogin             Protocol::Ipv6Frag => 0x2c,
32313776c11Slogin             Protocol::Icmpv6 => 0x3a,
32413776c11Slogin             Protocol::Ipv6NoNxt => 0x3b,
32513776c11Slogin             Protocol::Ipv6Opts => 0x3c,
32613776c11Slogin             Protocol::Unknown(id) => id,
32713776c11Slogin         }
32813776c11Slogin     }
3294454d1a2Slogin }
330