Debian Codegraph @

third_party/rust/neqo-crypto/src/agentio.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 #![expect(
8 clippy::unwrap_used,
9 reason = "Let's assume the use of `unwrap` was checked when the use of `unsafe` was reviewed."
10 )]
11
12 use std::{
13 cmp::min,
14 fmt::{self, Display, Formatter},
15 mem,
16 ops::Deref,
17 os::raw::{c_uint, c_void},
18 pin::Pin,
19 ptr::{null, null_mut},
20 };
21
22 use neqo_common::{hex, hex_with_len, qtrace};
23
24 use crate::{
25 constants::{ContentType, Epoch},
26 err::{nspr, Error, PR_SetError, Res},
27 null_safe_slice, prio, ssl,
28 };
29
30 // Alias common types.
31 type PrFd = *mut prio::PRFileDesc;
32 type PrStatus = prio::PRStatus::Type;
33 const PR_SUCCESS: PrStatus = prio::PRStatus::PR_SUCCESS;
34 const PR_FAILURE: PrStatus = prio::PRStatus::PR_FAILURE;
35
36 /// Convert a pinned, boxed object into a void pointer.
37 pub fn as_c_void<T: Unpin>(pin: &mut Pin<Box<T>>) -> *mut c_void {
38 (std::ptr::from_mut::<T>(Pin::into_inner(pin.as_mut()))).cast()
39 }
40
41 /// A slice of the output.
42 #[derive(Default)]
43 pub struct Record {
44 pub epoch: Epoch,
45 pub ct: ContentType,
46 pub data: Vec<u8>,
47 }
48
49 impl Record {
50 #[must_use]
51 pub fn new(epoch: Epoch, ct: ContentType, data: &[u8]) -> Self {
52 Self {
53 epoch,
54 ct,
55 data: data.to_vec(),
56 }
57 }
58
59 // Shoves this record into the socket, returns true if blocked.
60 pub(crate) fn write(self, fd: *mut ssl::PRFileDesc) -> Res<()> {
61 qtrace!("write {self:?}");
62 unsafe {
63 ssl::SSL_RecordLayerData(
64 fd,
65 self.epoch,
66 ssl::SSLContentType::Type::from(self.ct),
67 self.data.as_ptr(),
68 c_uint::try_from(self.data.len())?,
69 )
70 }
71 }
72 }
73
74 impl fmt::Debug for Record {
75 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
76 write!(
77 f,
78 "Record {:?}:{:?} {}",
79 self.epoch,
80 self.ct,
81 hex_with_len(&self.data[..])
82 )
83 }
84 }
85
86 #[derive(Debug, Default)]
87 pub struct RecordList {
88 records: Vec<Record>,
89 }
90
91 impl RecordList {
92 fn append(&mut self, epoch: Epoch, ct: ContentType, data: &[u8]) {
93 self.records.push(Record::new(epoch, ct, data));
94 }
95
96 unsafe extern "C" fn ingest(
97 _fd: *mut ssl::PRFileDesc,
98 epoch: ssl::PRUint16,
99 ct: ssl::SSLContentType::Type,
100 data: *const ssl::PRUint8,
101 len: c_uint,
102 arg: *mut c_void,
103 ) -> ssl::SECStatus {
104 let Ok(epoch) = Epoch::try_from(epoch) else {
105 return ssl::SECFailure;
106 };
107 let Ok(ct) = ContentType::try_from(ct) else {
108 return ssl::SECFailure;
109 };
110 let Some(records) = arg.cast::<Self>().as_mut() else {
111 return ssl::SECFailure;
112 };
113 let slice = null_safe_slice(data, len);
114 records.append(epoch, ct, slice);
115 ssl::SECSuccess
116 }
117
118 /// Create a new record list.
119 pub(crate) fn setup(fd: *mut ssl::PRFileDesc) -> Res<Pin<Box<Self>>> {
120 let mut records = Box::pin(Self::default());
121 unsafe {
122 ssl::SSL_RecordLayerWriteCallback(fd, Some(Self::ingest), as_c_void(&mut records))
123 }?;
124 Ok(records)
125 }
126 }
127
128 impl Deref for RecordList {
129 type Target = Vec<Record>;
130 fn deref(&self) -> &Vec<Record> {
131 &self.records
132 }
133 }
134
135 pub struct RecordListIter(std::vec::IntoIter<Record>);
136
137 impl Iterator for RecordListIter {
138 type Item = Record;
139 fn next(&mut self) -> Option<Self::Item> {
140 self.0.next()
141 }
142 }
143
144 impl IntoIterator for RecordList {
145 type Item = Record;
146 type IntoIter = RecordListIter;
147 fn into_iter(self) -> Self::IntoIter {
148 RecordListIter(self.records.into_iter())
149 }
150 }
151
152 pub struct AgentIoInputContext<'a> {
153 input: &'a mut AgentIoInput,
154 }
155
156 impl Drop for AgentIoInputContext<'_> {
157 fn drop(&mut self) {
158 self.input.reset();
159 }
160 }
161
162 #[derive(Debug)]
163 struct AgentIoInput {
164 // input is data that is read by TLS.
165 input: *const u8,
166 // input_available is how much data is left for reading.
167 available: usize,
168 }
169
170 impl AgentIoInput {
171 fn wrap<'a: 'c, 'b: 'c, 'c>(&'a mut self, input: &'b [u8]) -> AgentIoInputContext<'c> {
172 assert!(self.input.is_null());
173 self.input = input.as_ptr();
174 self.available = input.len();
175 qtrace!("AgentIoInput wrap {:p}", self.input);
176 AgentIoInputContext { input: self }
177 }
178
179 // Take the data provided as input and provide it to the TLS stack.
180 fn read_input(&mut self, buf: *mut u8, count: usize) -> Res<usize> {
181 let amount = min(self.available, count);
182 if amount == 0 {
183 unsafe {
184 PR_SetError(nspr::PR_WOULD_BLOCK_ERROR, 0);
185 }
186 return Err(Error::NoDataAvailable);
187 }
188
189 #[expect(
190 clippy::disallowed_methods,
191 reason = "We just checked if this was empty."
192 )]
193 let src = unsafe { std::slice::from_raw_parts(self.input, amount) };
194 qtrace!("[{self}] read {}", hex(src));
195 let dst = unsafe { std::slice::from_raw_parts_mut(buf, amount) };
196 dst.copy_from_slice(src);
197 self.input = self.input.wrapping_add(amount);
198 self.available -= amount;
199 Ok(amount)
200 }
201
202 fn reset(&mut self) {
203 qtrace!("[{self}] reset");
204 self.input = null();
205 self.available = 0;
206 }
207 }
208
209 impl Display for AgentIoInput {
210 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
211 write!(f, "AgentIoInput {:p}", self.input)
212 }
213 }
214
215 #[derive(Debug)]
216 pub struct AgentIo {
217 // input collects the input we might provide to TLS.
218 input: AgentIoInput,
219
220 // output contains data that is written by TLS.
221 output: Vec<u8>,
222 }
223
224 impl AgentIo {
225 pub const fn new() -> Self {
226 Self {
227 input: AgentIoInput {
228 input: null(),
229 available: 0,
230 },
231 output: Vec::new(),
232 }
233 }
234
235 unsafe fn borrow(fd: &mut PrFd) -> &mut Self {
236 (**fd).secret.cast::<Self>().as_mut().unwrap()
237 }
238
239 pub fn wrap<'a: 'c, 'b: 'c, 'c>(&'a mut self, input: &'b [u8]) -> AgentIoInputContext<'c> {
240 assert_eq!(self.output.len(), 0);
241 self.input.wrap(input)
242 }
243
244 // Stage output from TLS into the output buffer.
245 fn save_output(&mut self, buf: *const u8, count: usize) {
246 let slice = unsafe { null_safe_slice(buf, count) };
247 qtrace!("[{self}] save output {}", hex(slice));
248 self.output.extend_from_slice(slice);
249 }
250
251 pub fn take_output(&mut self) -> Vec<u8> {
252 qtrace!("[{self}] take output");
253 mem::take(&mut self.output)
254 }
255 }
256
257 impl Display for AgentIo {
258 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
259 write!(f, "AgentIo")
260 }
261 }
262
263 unsafe extern "C" fn agent_close(fd: PrFd) -> PrStatus {
264 (*fd).secret = null_mut();
265 if let Some(dtor) = (*fd).dtor {
266 dtor(fd);
267 }
268 PR_SUCCESS
269 }
270
271 unsafe extern "C" fn agent_read(mut fd: PrFd, buf: *mut c_void, amount: prio::PRInt32) -> PrStatus {
272 let io = AgentIo::borrow(&mut fd);
273 if let Ok(a) = usize::try_from(amount) {
274 match io.input.read_input(buf.cast(), a) {
275 Ok(_) => PR_SUCCESS,
276 Err(_) => PR_FAILURE,
277 }
278 } else {
279 PR_FAILURE
280 }
281 }
282
283 unsafe extern "C" fn agent_recv(
284 mut fd: PrFd,
285 buf: *mut c_void,
286 amount: prio::PRInt32,
287 flags: prio::PRIntn,
288 _timeout: prio::PRIntervalTime,
289 ) -> prio::PRInt32 {
290 let io = AgentIo::borrow(&mut fd);
291 if flags != 0 {
292 return PR_FAILURE;
293 }
294 if let Ok(a) = usize::try_from(amount) {
295 io.input.read_input(buf.cast(), a).map_or(PR_FAILURE, |v| {
296 prio::PRInt32::try_from(v).unwrap_or(PR_FAILURE)
297 })
298 } else {
299 PR_FAILURE
300 }
301 }
302
303 unsafe extern "C" fn agent_write(
304 mut fd: PrFd,
305 buf: *const c_void,
306 amount: prio::PRInt32,
307 ) -> PrStatus {
308 let io = AgentIo::borrow(&mut fd);
309 usize::try_from(amount).map_or(PR_FAILURE, |a| {
310 io.save_output(buf.cast(), a);
311 amount
312 })
313 }
314
315 unsafe extern "C" fn agent_send(
316 mut fd: PrFd,
317 buf: *const c_void,
318 amount: prio::PRInt32,
319 flags: prio::PRIntn,
320 _timeout: prio::PRIntervalTime,
321 ) -> prio::PRInt32 {
322 let io = AgentIo::borrow(&mut fd);
323
324 if flags != 0 {
325 return PR_FAILURE;
326 }
327 usize::try_from(amount).map_or(PR_FAILURE, |a| {
328 io.save_output(buf.cast(), a);
329 amount
330 })
331 }
332
333 unsafe extern "C" fn agent_available(mut fd: PrFd) -> prio::PRInt32 {
334 let io = AgentIo::borrow(&mut fd);
335 io.input.available.try_into().unwrap_or(PR_FAILURE)
336 }
337
338 unsafe extern "C" fn agent_available64(mut fd: PrFd) -> prio::PRInt64 {
339 let io = AgentIo::borrow(&mut fd);
340 io.input
341 .available
342 .try_into()
343 .unwrap_or_else(|_| PR_FAILURE.into())
344 }
345
346 #[expect(
347 clippy::cast_possible_truncation,
348 reason = "Cast is safe because prio::PR_AF_INET is 2."
349 )]
350 unsafe extern "C" fn agent_getname(_fd: PrFd, addr: *mut prio::PRNetAddr) -> PrStatus {
351 let Some(a) = addr.as_mut() else {
352 return PR_FAILURE;
353 };
354 a.inet.family = prio::PR_AF_INET as prio::PRUint16;
355 a.inet.port = 0;
356 a.inet.ip = 0;
357 PR_SUCCESS
358 }
359
360 unsafe extern "C" fn agent_getsockopt(_fd: PrFd, opt: *mut prio::PRSocketOptionData) -> PrStatus {
361 if let Some(o) = opt.as_mut() {
362 if o.option == prio::PRSockOption::PR_SockOpt_Nonblocking {
363 o.value.non_blocking = 1;
364 return PR_SUCCESS;
365 }
366 }
367 PR_FAILURE
368 }
369
370 pub const METHODS: &prio::PRIOMethods = &prio::PRIOMethods {
371 file_type: prio::PRDescType::PR_DESC_LAYERED,
372 close: Some(agent_close),
373 read: Some(agent_read),
374 write: Some(agent_write),
375 available: Some(agent_available),
376 available64: Some(agent_available64),
377 fsync: None,
378 seek: None,
379 seek64: None,
380 fileInfo: None,
381 fileInfo64: None,
382 writev: None,
383 connect: None,
384 accept: None,
385 bind: None,
386 listen: None,
387 shutdown: None,
388 recv: Some(agent_recv),
389 send: Some(agent_send),
390 recvfrom: None,
391 sendto: None,
392 poll: None,
393 acceptread: None,
394 transmitfile: None,
395 getsockname: Some(agent_getname),
396 getpeername: Some(agent_getname),
397 reserved_fn_6: None,
398 reserved_fn_5: None,
399 getsocketoption: Some(agent_getsockopt),
400 setsocketoption: None,
401 sendfile: None,
402 connectcontinue: None,
403 reserved_fn_3: None,
404 reserved_fn_2: None,
405 reserved_fn_1: None,
406 reserved_fn_0: None,
407 };