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