Debian Codegraph @

third_party/rust/neqo-crypto/src/time.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 ops::Deref,
14 os::raw::c_void,
15 pin::Pin,
16 sync::OnceLock,
17 time::{Duration, Instant},
18 };
19
20 use crate::{
21 agentio::as_c_void,
22 err::{Error, Res},
23 ssl::{PRFileDesc, SSLTimeFunc},
24 };
25
26 include!(concat!(env!("OUT_DIR"), "/nspr_time.rs"));
27
28 experimental_api!(SSL_SetTimeFunc(
29 fd: *mut PRFileDesc,
30 cb: SSLTimeFunc,
31 arg: *mut c_void,
32 ));
33
34 /// This struct holds the zero time used for converting between `Instant` and `PRTime`.
35 #[derive(Debug)]
36 struct TimeZero {
37 instant: Instant,
38 prtime: PRTime,
39 }
40
41 impl TimeZero {
42 /// This function sets a baseline from an instance of `Instant`.
43 /// This allows for the possibility that code that uses these APIs will create
44 /// instances of `Instant` before any of this code is run. If `Instant`s older than
45 /// `BASE_TIME` are used with these conversion functions, they will fail.
46 /// To avoid that, we make sure that this sets the base time using the first value
47 /// it sees if it is in the past. If it is not, then use `Instant::now()` instead.
48 pub fn baseline(t: Instant) -> Self {
49 let now = Instant::now();
50 let prnow = unsafe { PR_Now() };
51
52 if now <= t {
53 // `t` is in the future, just use `now`.
54 Self {
55 instant: now,
56 prtime: prnow,
57 }
58 } else {
59 let elapsed = Interval::from(now.duration_since(now));
60 // An error from these unwrap functions would require
61 // ridiculously long application running time.
62 let prelapsed: PRTime = elapsed.try_into().unwrap();
63 Self {
64 instant: t,
65 prtime: prnow.checked_sub(prelapsed).unwrap(),
66 }
67 }
68 }
69 }
70
71 static BASE_TIME: OnceLock<TimeZero> = OnceLock::new();
72
73 fn get_base() -> &'static TimeZero {
74 BASE_TIME.get_or_init(|| TimeZero {
75 instant: Instant::now(),
76 prtime: unsafe { PR_Now() },
77 })
78 }
79
80 pub fn init() {
81 _ = get_base();
82 }
83
84 /// Time wraps Instant and provides conversion functions into `PRTime`.
85 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
86 pub struct Time {
87 t: Instant,
88 }
89
90 impl Deref for Time {
91 type Target = Instant;
92 fn deref(&self) -> &Self::Target {
93 &self.t
94 }
95 }
96
97 impl From<Instant> for Time {
98 /// Convert from an Instant into a Time.
99 fn from(t: Instant) -> Self {
100 // Initialize `BASE_TIME` using `TimeZero::baseline(t)`.
101 BASE_TIME.get_or_init(|| TimeZero::baseline(t));
102 Self { t }
103 }
104 }
105
106 impl TryFrom<PRTime> for Time {
107 type Error = Error;
108 fn try_from(prtime: PRTime) -> Res<Self> {
109 let base = get_base();
110 let delta = prtime
111 .checked_sub(base.prtime)
112 .ok_or(Error::TimeTravelError)?;
113 let d = Duration::from_micros(u64::try_from(delta.abs())?);
114 let t = if delta >= 0 {
115 base.instant.checked_add(d)
116 } else {
117 base.instant.checked_sub(d)
118 };
119 let t = t.ok_or(Error::TimeTravelError)?;
120 Ok(Self { t })
121 }
122 }
123
124 impl TryInto<PRTime> for Time {
125 type Error = Error;
126 fn try_into(self) -> Res<PRTime> {
127 let base = get_base();
128
129 self.t.checked_duration_since(base.instant).map_or_else(
130 || {
131 // Try to go backwards from the base time.
132 let backwards = base.instant - self.t; // infallible
133 PRTime::try_from(backwards.as_micros()).map_or(Err(Error::TimeTravelError), |d| {
134 base.prtime.checked_sub(d).ok_or(Error::TimeTravelError)
135 })
136 },
137 |delta| {
138 PRTime::try_from(delta.as_micros()).map_or(Err(Error::TimeTravelError), |d| {
139 d.checked_add(base.prtime).ok_or(Error::TimeTravelError)
140 })
141 },
142 )
143 }
144 }
145
146 impl From<Time> for Instant {
147 fn from(t: Time) -> Self {
148 t.t
149 }
150 }
151
152 /// Interval wraps Duration and provides conversion functions into `PRTime`.
153 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
154 pub struct Interval {
155 d: Duration,
156 }
157
158 impl Deref for Interval {
159 type Target = Duration;
160 fn deref(&self) -> &Self::Target {
161 &self.d
162 }
163 }
164
165 impl TryFrom<PRTime> for Interval {
166 type Error = Error;
167 fn try_from(prtime: PRTime) -> Res<Self> {
168 Ok(Self {
169 d: Duration::from_micros(u64::try_from(prtime)?),
170 })
171 }
172 }
173
174 impl From<Duration> for Interval {
175 fn from(d: Duration) -> Self {
176 Self { d }
177 }
178 }
179
180 impl TryInto<PRTime> for Interval {
181 type Error = Error;
182 fn try_into(self) -> Res<PRTime> {
183 Ok(PRTime::try_from(self.d.as_micros())?)
184 }
185 }
186
187 /// `TimeHolder` maintains a `PRTime` value in a form that is accessible to the TLS stack.
188 #[derive(Debug)]
189 pub struct TimeHolder {
190 t: Pin<Box<PRTime>>,
191 }
192
193 impl TimeHolder {
194 unsafe extern "C" fn time_func(arg: *mut c_void) -> PRTime {
195 let p = arg as *const PRTime;
196 *p.as_ref().unwrap()
197 }
198
199 pub fn bind(&mut self, fd: *mut PRFileDesc) -> Res<()> {
200 unsafe { SSL_SetTimeFunc(fd, Some(Self::time_func), as_c_void(&mut self.t)) }
201 }
202
203 pub fn set(&mut self, t: Instant) -> Res<()> {
204 *self.t = Time::from(t).try_into()?;
205 Ok(())
206 }
207 }
208
209 impl Default for TimeHolder {
210 fn default() -> Self {
211 Self { t: Box::pin(0) }
212 }
213 }
214
215 #[cfg(test)]
216 mod test {
217 use std::time::{Duration, Instant};
218
219 use super::{get_base, init, Interval, PRTime, Time};
220 use crate::err::Res;
221
222 #[test]
223 fn convert_stable() {
224 init();
225 let now = Time::from(Instant::now());
226 let pr: PRTime = now.try_into().expect("convert to PRTime with truncation");
227 let t2 = Time::try_from(pr).expect("convert to Instant");
228 let pr2: PRTime = t2.try_into().expect("convert to PRTime again");
229 assert_eq!(pr, pr2);
230 let t3 = Time::try_from(pr2).expect("convert to Instant again");
231 assert_eq!(t2, t3);
232 }
233
234 #[test]
235 fn past_prtime() {
236 const DELTA: Duration = Duration::from_secs(1);
237 init();
238 let base = get_base();
239 let delta_micros = PRTime::try_from(DELTA.as_micros()).unwrap();
240 println!("{} - {delta_micros}", base.prtime);
241 let t = Time::try_from(base.prtime - delta_micros).unwrap();
242 assert_eq!(Instant::from(t) + DELTA, base.instant);
243 }
244
245 #[test]
246 fn past_instant() {
247 const DELTA: Duration = Duration::from_secs(1);
248 init();
249 let base = get_base();
250 let t = Time::from(base.instant.checked_sub(DELTA).unwrap());
251 assert_eq!(Instant::from(t) + DELTA, base.instant);
252 }
253
254 #[test]
255 fn negative_interval() {
256 init();
257 assert!(Interval::try_from(-1).is_err());
258 }
259
260 #[test]
261 // We allow replace_consts here because
262 // std::u64::MAX isn't available
263 // in all of our targets
264 fn overflow_interval() {
265 init();
266 let interval = Interval::from(Duration::from_micros(u64::MAX));
267 let res: Res<PRTime> = interval.try_into();
268 assert!(res.is_err());
269 }
270 }