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