xref: /DragonOS/kernel/src/net/socket/unix.rs (revision 4256da7fb6ad25a3caab6f656607aaf047cb6446)
1 use alloc::{boxed::Box, sync::Arc, vec::Vec};
2 use system_error::SystemError;
3 
4 use crate::{libs::spinlock::SpinLock, net::Endpoint};
5 
6 use super::{Socket, SocketInode, SocketMetadata, SocketOptions, SocketType};
7 
8 #[derive(Debug, Clone)]
9 pub struct StreamSocket {
10     metadata: SocketMetadata,
11     buffer: Arc<SpinLock<Vec<u8>>>,
12     peer_inode: Option<Arc<SocketInode>>,
13 }
14 
15 impl StreamSocket {
16     /// 默认的元数据缓冲区大小
17     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
18     /// 默认的缓冲区大小
19     pub const DEFAULT_BUF_SIZE: usize = 64 * 1024;
20 
21     /// # 创建一个 Stream Socket
22     ///
23     /// ## 参数
24     /// - `options`: socket选项
25     pub fn new(options: SocketOptions) -> Self {
26         let buffer = Arc::new(SpinLock::new(Vec::with_capacity(Self::DEFAULT_BUF_SIZE)));
27 
28         let metadata = SocketMetadata::new(
29             SocketType::Unix,
30             Self::DEFAULT_BUF_SIZE,
31             Self::DEFAULT_BUF_SIZE,
32             Self::DEFAULT_METADATA_BUF_SIZE,
33             options,
34         );
35 
36         Self {
37             metadata,
38             buffer,
39             peer_inode: None,
40         }
41     }
42 }
43 
44 impl Socket for StreamSocket {
45     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
46         let mut buffer = self.buffer.lock_irqsave();
47 
48         let len = core::cmp::min(buf.len(), buffer.len());
49         buf[..len].copy_from_slice(&buffer[..len]);
50 
51         let _ = buffer.split_off(len);
52 
53         (Ok(len), Endpoint::Inode(self.peer_inode.clone()))
54     }
55 
56     fn write(&self, buf: &[u8], _to: Option<Endpoint>) -> Result<usize, SystemError> {
57         if self.peer_inode.is_none() {
58             return Err(SystemError::ENOTCONN);
59         }
60 
61         let peer_inode = self.peer_inode.clone().unwrap();
62         let len = peer_inode.inner().write_buffer(buf)?;
63         Ok(len)
64     }
65 
66     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
67         if self.peer_inode.is_some() {
68             return Err(SystemError::EISCONN);
69         }
70 
71         if let Endpoint::Inode(inode) = endpoint {
72             self.peer_inode = inode;
73             Ok(())
74         } else {
75             Err(SystemError::EINVAL)
76         }
77     }
78 
79     fn write_buffer(&self, buf: &[u8]) -> Result<usize, SystemError> {
80         let mut buffer = self.buffer.lock_irqsave();
81 
82         let len = buf.len();
83         if buffer.capacity() - buffer.len() < len {
84             return Err(SystemError::ENOBUFS);
85         }
86         buffer.extend_from_slice(buf);
87 
88         Ok(len)
89     }
90 
91     fn metadata(&self) -> SocketMetadata {
92         self.metadata.clone()
93     }
94 
95     fn box_clone(&self) -> Box<dyn Socket> {
96         Box::new(self.clone())
97     }
98 
99     fn as_any_ref(&self) -> &dyn core::any::Any {
100         self
101     }
102 
103     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
104         self
105     }
106 }
107 
108 #[derive(Debug, Clone)]
109 pub struct SeqpacketSocket {
110     metadata: SocketMetadata,
111     buffer: Arc<SpinLock<Vec<u8>>>,
112     peer_inode: Option<Arc<SocketInode>>,
113 }
114 
115 impl SeqpacketSocket {
116     /// 默认的元数据缓冲区大小
117     pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
118     /// 默认的缓冲区大小
119     pub const DEFAULT_BUF_SIZE: usize = 64 * 1024;
120 
121     /// # 创建一个 Seqpacket Socket
122     ///
123     /// ## 参数
124     /// - `options`: socket选项
125     pub fn new(options: SocketOptions) -> Self {
126         let buffer = Arc::new(SpinLock::new(Vec::with_capacity(Self::DEFAULT_BUF_SIZE)));
127 
128         let metadata = SocketMetadata::new(
129             SocketType::Unix,
130             Self::DEFAULT_BUF_SIZE,
131             Self::DEFAULT_BUF_SIZE,
132             Self::DEFAULT_METADATA_BUF_SIZE,
133             options,
134         );
135 
136         Self {
137             metadata,
138             buffer,
139             peer_inode: None,
140         }
141     }
142 }
143 
144 impl Socket for SeqpacketSocket {
145     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint) {
146         let mut buffer = self.buffer.lock_irqsave();
147 
148         let len = core::cmp::min(buf.len(), buffer.len());
149         buf[..len].copy_from_slice(&buffer[..len]);
150 
151         let _ = buffer.split_off(len);
152 
153         (Ok(len), Endpoint::Inode(self.peer_inode.clone()))
154     }
155 
156     fn write(&self, buf: &[u8], _to: Option<Endpoint>) -> Result<usize, SystemError> {
157         if self.peer_inode.is_none() {
158             return Err(SystemError::ENOTCONN);
159         }
160 
161         let peer_inode = self.peer_inode.clone().unwrap();
162         let len = peer_inode.inner().write_buffer(buf)?;
163         Ok(len)
164     }
165 
166     fn connect(&mut self, endpoint: Endpoint) -> Result<(), SystemError> {
167         if self.peer_inode.is_some() {
168             return Err(SystemError::EISCONN);
169         }
170 
171         if let Endpoint::Inode(inode) = endpoint {
172             self.peer_inode = inode;
173             Ok(())
174         } else {
175             Err(SystemError::EINVAL)
176         }
177     }
178 
179     fn write_buffer(&self, buf: &[u8]) -> Result<usize, SystemError> {
180         let mut buffer = self.buffer.lock_irqsave();
181 
182         let len = buf.len();
183         if buffer.capacity() - buffer.len() < len {
184             return Err(SystemError::ENOBUFS);
185         }
186         buffer.extend_from_slice(buf);
187 
188         Ok(len)
189     }
190 
191     fn metadata(&self) -> SocketMetadata {
192         self.metadata.clone()
193     }
194 
195     fn box_clone(&self) -> Box<dyn Socket> {
196         Box::new(self.clone())
197     }
198 
199     fn as_any_ref(&self) -> &dyn core::any::Any {
200         self
201     }
202 
203     fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
204         self
205     }
206 }
207