1 | use std::cmp; |
2 | use std::fmt::{self, Display, Formatter}; |
3 | use std::str::FromStr; |
4 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
5 | |
6 | use crate::Error; |
7 | |
8 | /// HTTP timestamp type. |
9 | /// |
10 | /// Parse using `FromStr` impl. |
11 | /// Format using the `Display` trait. |
12 | /// Convert timestamp into/from `SytemTime` to use. |
13 | /// Supports comparsion and sorting. |
14 | #[derive (Copy, Clone, Debug, Eq, PartialEq, Hash)] |
15 | pub struct HttpDate { |
16 | /// 0...59 |
17 | sec: u8, |
18 | /// 0...59 |
19 | min: u8, |
20 | /// 0...23 |
21 | hour: u8, |
22 | /// 1...31 |
23 | day: u8, |
24 | /// 1...12 |
25 | mon: u8, |
26 | /// 1970...9999 |
27 | year: u16, |
28 | /// 1...7 |
29 | wday: u8, |
30 | } |
31 | |
32 | impl HttpDate { |
33 | fn is_valid(&self) -> bool { |
34 | self.sec < 60 |
35 | && self.min < 60 |
36 | && self.hour < 24 |
37 | && self.day > 0 |
38 | && self.day < 32 |
39 | && self.mon > 0 |
40 | && self.mon <= 12 |
41 | && self.year >= 1970 |
42 | && self.year <= 9999 |
43 | && &HttpDate::from(SystemTime::from(*self)) == self |
44 | } |
45 | } |
46 | |
47 | impl From<SystemTime> for HttpDate { |
48 | fn from(v: SystemTime) -> HttpDate { |
49 | let dur = v |
50 | .duration_since(UNIX_EPOCH) |
51 | .expect("all times should be after the epoch" ); |
52 | let secs_since_epoch = dur.as_secs(); |
53 | |
54 | if secs_since_epoch >= 253402300800 { |
55 | // year 9999 |
56 | panic!("date must be before year 9999" ); |
57 | } |
58 | |
59 | /* 2000-03-01 (mod 400 year, immediately after feb29 */ |
60 | const LEAPOCH: i64 = 11017; |
61 | const DAYS_PER_400Y: i64 = 365 * 400 + 97; |
62 | const DAYS_PER_100Y: i64 = 365 * 100 + 24; |
63 | const DAYS_PER_4Y: i64 = 365 * 4 + 1; |
64 | |
65 | let days = (secs_since_epoch / 86400) as i64 - LEAPOCH; |
66 | let secs_of_day = secs_since_epoch % 86400; |
67 | |
68 | let mut qc_cycles = days / DAYS_PER_400Y; |
69 | let mut remdays = days % DAYS_PER_400Y; |
70 | |
71 | if remdays < 0 { |
72 | remdays += DAYS_PER_400Y; |
73 | qc_cycles -= 1; |
74 | } |
75 | |
76 | let mut c_cycles = remdays / DAYS_PER_100Y; |
77 | if c_cycles == 4 { |
78 | c_cycles -= 1; |
79 | } |
80 | remdays -= c_cycles * DAYS_PER_100Y; |
81 | |
82 | let mut q_cycles = remdays / DAYS_PER_4Y; |
83 | if q_cycles == 25 { |
84 | q_cycles -= 1; |
85 | } |
86 | remdays -= q_cycles * DAYS_PER_4Y; |
87 | |
88 | let mut remyears = remdays / 365; |
89 | if remyears == 4 { |
90 | remyears -= 1; |
91 | } |
92 | remdays -= remyears * 365; |
93 | |
94 | let mut year = 2000 + remyears + 4 * q_cycles + 100 * c_cycles + 400 * qc_cycles; |
95 | |
96 | let months = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29]; |
97 | let mut mon = 0; |
98 | for mon_len in months.iter() { |
99 | mon += 1; |
100 | if remdays < *mon_len { |
101 | break; |
102 | } |
103 | remdays -= *mon_len; |
104 | } |
105 | let mday = remdays + 1; |
106 | let mon = if mon + 2 > 12 { |
107 | year += 1; |
108 | mon - 10 |
109 | } else { |
110 | mon + 2 |
111 | }; |
112 | |
113 | let mut wday = (3 + days) % 7; |
114 | if wday <= 0 { |
115 | wday += 7 |
116 | }; |
117 | |
118 | HttpDate { |
119 | sec: (secs_of_day % 60) as u8, |
120 | min: ((secs_of_day % 3600) / 60) as u8, |
121 | hour: (secs_of_day / 3600) as u8, |
122 | day: mday as u8, |
123 | mon: mon as u8, |
124 | year: year as u16, |
125 | wday: wday as u8, |
126 | } |
127 | } |
128 | } |
129 | |
130 | impl From<HttpDate> for SystemTime { |
131 | fn from(v: HttpDate) -> SystemTime { |
132 | let leap_years = |
133 | ((v.year - 1) - 1968) / 4 - ((v.year - 1) - 1900) / 100 + ((v.year - 1) - 1600) / 400; |
134 | let mut ydays = match v.mon { |
135 | 1 => 0, |
136 | 2 => 31, |
137 | 3 => 59, |
138 | 4 => 90, |
139 | 5 => 120, |
140 | 6 => 151, |
141 | 7 => 181, |
142 | 8 => 212, |
143 | 9 => 243, |
144 | 10 => 273, |
145 | 11 => 304, |
146 | 12 => 334, |
147 | _ => unreachable!(), |
148 | } + v.day as u64 |
149 | - 1; |
150 | if is_leap_year(v.year) && v.mon > 2 { |
151 | ydays += 1; |
152 | } |
153 | let days = (v.year as u64 - 1970) * 365 + leap_years as u64 + ydays; |
154 | UNIX_EPOCH |
155 | + Duration::from_secs( |
156 | v.sec as u64 + v.min as u64 * 60 + v.hour as u64 * 3600 + days * 86400, |
157 | ) |
158 | } |
159 | } |
160 | |
161 | impl FromStr for HttpDate { |
162 | type Err = Error; |
163 | |
164 | fn from_str(s: &str) -> Result<HttpDate, Error> { |
165 | if !s.is_ascii() { |
166 | return Err(Error(())); |
167 | } |
168 | let x: &[u8] = s.trim().as_bytes(); |
169 | let date: HttpDate = parse_imf_fixdate(x) |
170 | .or_else(|_| parse_rfc850_date(x)) |
171 | .or_else(|_| parse_asctime(x))?; |
172 | if !date.is_valid() { |
173 | return Err(Error(())); |
174 | } |
175 | Ok(date) |
176 | } |
177 | } |
178 | |
179 | impl Display for HttpDate { |
180 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
181 | let wday = match self.wday { |
182 | 1 => b"Mon" , |
183 | 2 => b"Tue" , |
184 | 3 => b"Wed" , |
185 | 4 => b"Thu" , |
186 | 5 => b"Fri" , |
187 | 6 => b"Sat" , |
188 | 7 => b"Sun" , |
189 | _ => unreachable!(), |
190 | }; |
191 | |
192 | let mon = match self.mon { |
193 | 1 => b"Jan" , |
194 | 2 => b"Feb" , |
195 | 3 => b"Mar" , |
196 | 4 => b"Apr" , |
197 | 5 => b"May" , |
198 | 6 => b"Jun" , |
199 | 7 => b"Jul" , |
200 | 8 => b"Aug" , |
201 | 9 => b"Sep" , |
202 | 10 => b"Oct" , |
203 | 11 => b"Nov" , |
204 | 12 => b"Dec" , |
205 | _ => unreachable!(), |
206 | }; |
207 | |
208 | let mut buf: [u8; 29] = *b" , 00 0000 00:00:00 GMT" ; |
209 | buf[0] = wday[0]; |
210 | buf[1] = wday[1]; |
211 | buf[2] = wday[2]; |
212 | buf[5] = b'0' + (self.day / 10); |
213 | buf[6] = b'0' + (self.day % 10); |
214 | buf[8] = mon[0]; |
215 | buf[9] = mon[1]; |
216 | buf[10] = mon[2]; |
217 | buf[12] = b'0' + (self.year / 1000) as u8; |
218 | buf[13] = b'0' + (self.year / 100 % 10) as u8; |
219 | buf[14] = b'0' + (self.year / 10 % 10) as u8; |
220 | buf[15] = b'0' + (self.year % 10) as u8; |
221 | buf[17] = b'0' + (self.hour / 10); |
222 | buf[18] = b'0' + (self.hour % 10); |
223 | buf[20] = b'0' + (self.min / 10); |
224 | buf[21] = b'0' + (self.min % 10); |
225 | buf[23] = b'0' + (self.sec / 10); |
226 | buf[24] = b'0' + (self.sec % 10); |
227 | f.write_str(std::str::from_utf8(&buf[..]).unwrap()) |
228 | } |
229 | } |
230 | |
231 | impl Ord for HttpDate { |
232 | fn cmp(&self, other: &HttpDate) -> cmp::Ordering { |
233 | SystemTime::from(*self).cmp(&SystemTime::from(*other)) |
234 | } |
235 | } |
236 | |
237 | impl PartialOrd for HttpDate { |
238 | fn partial_cmp(&self, other: &HttpDate) -> Option<cmp::Ordering> { |
239 | Some(self.cmp(other)) |
240 | } |
241 | } |
242 | |
243 | fn toint_1(x: u8) -> Result<u8, Error> { |
244 | let result: u8 = x.wrapping_sub(b'0' ); |
245 | if result < 10 { |
246 | Ok(result) |
247 | } else { |
248 | Err(Error(())) |
249 | } |
250 | } |
251 | |
252 | fn toint_2(s: &[u8]) -> Result<u8, Error> { |
253 | let high: u8 = s[0].wrapping_sub(b'0' ); |
254 | let low: u8 = s[1].wrapping_sub(b'0' ); |
255 | |
256 | if high < 10 && low < 10 { |
257 | Ok(high * 10 + low) |
258 | } else { |
259 | Err(Error(())) |
260 | } |
261 | } |
262 | |
263 | #[allow (clippy::many_single_char_names)] |
264 | fn toint_4(s: &[u8]) -> Result<u16, Error> { |
265 | let a: u16 = u16::from(s[0].wrapping_sub(b'0' )); |
266 | let b: u16 = u16::from(s[1].wrapping_sub(b'0' )); |
267 | let c: u16 = u16::from(s[2].wrapping_sub(b'0' )); |
268 | let d: u16 = u16::from(s[3].wrapping_sub(b'0' )); |
269 | |
270 | if a < 10 && b < 10 && c < 10 && d < 10 { |
271 | Ok(a * 1000 + b * 100 + c * 10 + d) |
272 | } else { |
273 | Err(Error(())) |
274 | } |
275 | } |
276 | |
277 | fn parse_imf_fixdate(s: &[u8]) -> Result<HttpDate, Error> { |
278 | // Example: `Sun, 06 Nov 1994 08:49:37 GMT` |
279 | if s.len() != 29 || &s[25..] != b" GMT" || s[16] != b' ' || s[19] != b':' || s[22] != b':' { |
280 | return Err(Error(())); |
281 | } |
282 | Ok(HttpDate { |
283 | sec: toint_2(&s[23..25])?, |
284 | min: toint_2(&s[20..22])?, |
285 | hour: toint_2(&s[17..19])?, |
286 | day: toint_2(&s[5..7])?, |
287 | mon: match &s[7..12] { |
288 | b" Jan " => 1, |
289 | b" Feb " => 2, |
290 | b" Mar " => 3, |
291 | b" Apr " => 4, |
292 | b" May " => 5, |
293 | b" Jun " => 6, |
294 | b" Jul " => 7, |
295 | b" Aug " => 8, |
296 | b" Sep " => 9, |
297 | b" Oct " => 10, |
298 | b" Nov " => 11, |
299 | b" Dec " => 12, |
300 | _ => return Err(Error(())), |
301 | }, |
302 | year: toint_4(&s[12..16])?, |
303 | wday: match &s[..5] { |
304 | b"Mon, " => 1, |
305 | b"Tue, " => 2, |
306 | b"Wed, " => 3, |
307 | b"Thu, " => 4, |
308 | b"Fri, " => 5, |
309 | b"Sat, " => 6, |
310 | b"Sun, " => 7, |
311 | _ => return Err(Error(())), |
312 | }, |
313 | }) |
314 | } |
315 | |
316 | fn parse_rfc850_date(s: &[u8]) -> Result<HttpDate, Error> { |
317 | // Example: `Sunday, 06-Nov-94 08:49:37 GMT` |
318 | if s.len() < 23 { |
319 | return Err(Error(())); |
320 | } |
321 | |
322 | fn wday<'a>(s: &'a [u8], wday: u8, name: &'static [u8]) -> Option<(u8, &'a [u8])> { |
323 | if &s[0..name.len()] == name { |
324 | return Some((wday, &s[name.len()..])); |
325 | } |
326 | None |
327 | } |
328 | let (wday, s) = wday(s, 1, b"Monday, " ) |
329 | .or_else(|| wday(s, 2, b"Tuesday, " )) |
330 | .or_else(|| wday(s, 3, b"Wednesday, " )) |
331 | .or_else(|| wday(s, 4, b"Thursday, " )) |
332 | .or_else(|| wday(s, 5, b"Friday, " )) |
333 | .or_else(|| wday(s, 6, b"Saturday, " )) |
334 | .or_else(|| wday(s, 7, b"Sunday, " )) |
335 | .ok_or(Error(()))?; |
336 | if s.len() != 22 || s[12] != b':' || s[15] != b':' || &s[18..22] != b" GMT" { |
337 | return Err(Error(())); |
338 | } |
339 | let mut year = u16::from(toint_2(&s[7..9])?); |
340 | if year < 70 { |
341 | year += 2000; |
342 | } else { |
343 | year += 1900; |
344 | } |
345 | Ok(HttpDate { |
346 | sec: toint_2(&s[16..18])?, |
347 | min: toint_2(&s[13..15])?, |
348 | hour: toint_2(&s[10..12])?, |
349 | day: toint_2(&s[0..2])?, |
350 | mon: match &s[2..7] { |
351 | b"-Jan-" => 1, |
352 | b"-Feb-" => 2, |
353 | b"-Mar-" => 3, |
354 | b"-Apr-" => 4, |
355 | b"-May-" => 5, |
356 | b"-Jun-" => 6, |
357 | b"-Jul-" => 7, |
358 | b"-Aug-" => 8, |
359 | b"-Sep-" => 9, |
360 | b"-Oct-" => 10, |
361 | b"-Nov-" => 11, |
362 | b"-Dec-" => 12, |
363 | _ => return Err(Error(())), |
364 | }, |
365 | year, |
366 | wday, |
367 | }) |
368 | } |
369 | |
370 | fn parse_asctime(s: &[u8]) -> Result<HttpDate, Error> { |
371 | // Example: `Sun Nov 6 08:49:37 1994` |
372 | if s.len() != 24 || s[10] != b' ' || s[13] != b':' || s[16] != b':' || s[19] != b' ' { |
373 | return Err(Error(())); |
374 | } |
375 | Ok(HttpDate { |
376 | sec: toint_2(&s[17..19])?, |
377 | min: toint_2(&s[14..16])?, |
378 | hour: toint_2(&s[11..13])?, |
379 | day: { |
380 | let x = &s[8..10]; |
381 | { |
382 | if x[0] == b' ' { |
383 | toint_1(x[1]) |
384 | } else { |
385 | toint_2(x) |
386 | } |
387 | }? |
388 | }, |
389 | mon: match &s[4..8] { |
390 | b"Jan " => 1, |
391 | b"Feb " => 2, |
392 | b"Mar " => 3, |
393 | b"Apr " => 4, |
394 | b"May " => 5, |
395 | b"Jun " => 6, |
396 | b"Jul " => 7, |
397 | b"Aug " => 8, |
398 | b"Sep " => 9, |
399 | b"Oct " => 10, |
400 | b"Nov " => 11, |
401 | b"Dec " => 12, |
402 | _ => return Err(Error(())), |
403 | }, |
404 | year: toint_4(&s[20..24])?, |
405 | wday: match &s[0..4] { |
406 | b"Mon " => 1, |
407 | b"Tue " => 2, |
408 | b"Wed " => 3, |
409 | b"Thu " => 4, |
410 | b"Fri " => 5, |
411 | b"Sat " => 6, |
412 | b"Sun " => 7, |
413 | _ => return Err(Error(())), |
414 | }, |
415 | }) |
416 | } |
417 | |
418 | fn is_leap_year(y: u16) -> bool { |
419 | y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) |
420 | } |
421 | |