clock-bound 3.0.0-beta.1

A crate to provide error bounded timestamp intervals.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Parsing and emitting NTP packets
#![allow(
    clippy::missing_errors_doc,
    clippy::missing_panics_doc,
    reason = "TODO: Shamik please add documentation."
)]
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    reason = "TODO: Shamik please address various warning associated with casting."
)]
use std::fmt::Display;

use bon::Builder;
use nom::Parser;
use nom::number::{be_i8, be_u8};
use thiserror::Error;

mod extension;
mod header;
mod short;
mod timestamp;

pub use extension::{ExtensionField, Fec2V1Value};
pub use header::{LeapIndicator, Mode, Version};
pub use short::Short;
pub use timestamp::Timestamp;

use crate::daemon::event::{NtpData, Stratum, TryFromU8Error};
use crate::daemon::time::{Duration as ClockBoundDuration, Instant as ClockBoundInstant};

/// An NTP packet, as defined in RFC 5905
///
/// See each of the fields for more information
#[derive(Debug, Clone, PartialEq, Eq, Builder)]
pub struct Packet {
    /// warning of impending leap second
    #[builder(default = LeapIndicator::NoWarning)]
    pub leap_indicator: LeapIndicator,
    /// NTP version
    #[builder(default = Version::V4)]
    pub version: Version,
    /// Association mode
    #[builder(default = Mode::Client)]
    pub mode: Mode,
    /// Stratum
    #[builder(default = 0)]
    pub stratum: u8,
    /// Maximum interval between successive messages, in log2 seconds
    #[builder(default = 0)]
    pub poll: u8,
    /// Precision of system clock in log2 seconds
    #[builder(default = 0)]
    pub precision: i8,
    /// Total round trip delay to the reference clock
    #[builder(default = Short::new(0))]
    pub root_delay: Short,
    /// Total dispersion to the reference clock
    #[builder(default = Short::new(0))]
    pub root_dispersion: Short,
    /// 32 bit code identifying the particular server/reference clock
    #[builder(default = [0u8; 4])]
    pub reference_id: [u8; 4],
    /// Time when the system clock was last corrected
    #[builder(default = Timestamp::new(0))]
    pub reference_timestamp: Timestamp,
    /// Time at the client when the request departed for the server
    #[builder(default = Timestamp::new(0))]
    pub origin_timestamp: Timestamp,
    /// Time at the server when the request arrived from the client
    #[builder(default = Timestamp::new(0))]
    pub receive_timestamp: Timestamp,
    /// Time at the server when the response left for the client
    #[builder(default = Timestamp::new(0))]
    pub transmit_timestamp: Timestamp,
    /// Extension field(s), if any
    #[builder(default = Vec::new())]
    pub extensions: Vec<ExtensionField>,
}

impl Display for Packet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Packet")?;
        writeln!(f, "leap indicator: {:?}", self.leap_indicator)?;
        writeln!(f, "version: {:?}", self.version)?;
        writeln!(f, "mode: {:?}", self.mode)?;
        writeln!(f, "stratum: {}", self.stratum)?;
        writeln!(f, "poll: {}", self.poll)?;
        writeln!(f, "precision: {}", self.precision)?;
        writeln!(f, "root_delay: {}", self.root_delay.to_time_delta())?;
        writeln!(
            f,
            "root_dispersion: {}",
            self.root_dispersion.to_time_delta()
        )?;
        writeln!(f, "reference_id: {:?}", self.reference_id)?;
        writeln!(
            f,
            "reference_timestamp: {}",
            self.reference_timestamp.to_utc_datetime()
        )?;
        writeln!(
            f,
            "origin_timestamp: {}",
            self.origin_timestamp.to_utc_datetime()
        )?;
        writeln!(
            f,
            "receive_timestamp: {}",
            self.receive_timestamp.to_utc_datetime()
        )?;
        writeln!(
            f,
            "transmit_timestamp: {}",
            self.transmit_timestamp.to_utc_datetime()
        )?;
        Ok(())
    }
}

impl Packet {
    /// NTP packet size in bytes, without extensions
    pub const MIN_SIZE: usize = 48;

    /// Construct an NTP request packet using an arbitrary u32 as the transmit timestamp
    ///
    /// Convention is that the transmit timestamp does not need to correlate with any real timestamp
    /// in the NTP request. Hence, the `u64` input.
    ///
    /// If one wants to modify this constructor, they can simply do so via
    /// ```
    /// use clock_bound::daemon::io::ntp::packet::Packet;
    ///
    /// let modified_request = Packet {
    ///     poll: 4,
    ///     ..Packet::new_request(0xd00f)
    /// };
    /// ```
    pub const fn new_request(transmit_timestamp: u64) -> Self {
        let transmit_timestamp = Timestamp::new(transmit_timestamp);
        // These values don't HAVE to be zero, but keeping it simple for now.
        Self {
            leap_indicator: LeapIndicator::NoWarning,
            version: Version::V4,
            mode: Mode::Client,
            stratum: 0,
            poll: 0,
            precision: 0,
            root_delay: Short::new(0),
            root_dispersion: Short::new(0),
            reference_id: [0u8; 4],
            reference_timestamp: Timestamp::new(0),
            origin_timestamp: Timestamp::new(0),
            receive_timestamp: Timestamp::new(0),
            transmit_timestamp,
            extensions: Vec::new(),
        }
    }

    /// Emit packet into bytes
    ///
    /// ## Panics
    /// Panics if buffer is smaller than total packet size
    pub fn emit_bytes(&self, mut buffer: &mut [u8]) {
        use bytes::BufMut;

        let total_size = self.total_size();
        assert!(
            buffer.len() >= total_size,
            "Buffer too small: {} < {}",
            buffer.len(),
            total_size
        );

        let header: u8 =
            self.mode.to_bits() | self.version.get() << 3 | self.leap_indicator.to_bits() << 6;
        buffer.put_u8(header);
        buffer.put_u8(self.stratum);
        buffer.put_u8(self.poll);
        buffer.put_i8(self.precision);
        buffer.put_u32_ne(self.root_delay.into_network_endian());
        buffer.put_u32_ne(self.root_dispersion.into_network_endian());
        buffer.put(self.reference_id.as_slice());
        buffer.put_u64_ne(self.reference_timestamp.into_network_endian());
        buffer.put_u64_ne(self.origin_timestamp.into_network_endian());
        buffer.put_u64_ne(self.receive_timestamp.into_network_endian());
        buffer.put_u64_ne(self.transmit_timestamp.into_network_endian());

        for extension in &self.extensions {
            extension.emit_bytes(buffer);
        }
    }

    /// Calculate total packet size including extensions
    pub fn total_size(&self) -> usize {
        Self::MIN_SIZE
            + self
                .extensions
                .iter()
                .map(|ext| ext.length() as usize)
                .sum::<usize>()
    }

    /// Parse from packet payload
    pub fn parse_from_bytes(input: &[u8]) -> nom::IResult<&[u8], Packet> {
        let (input, (leap_indicator, version, mode)) =
            nom::bits::bits((LeapIndicator::parse, Version::parse, Mode::parse)).parse(input)?;

        let (input, (stratum, poll, precision)) = (be_u8(), be_u8(), be_i8()).parse(input)?;

        let (input, (root_delay, root_dispersion)) = (Short::parse, Short::parse).parse(input)?;

        let (input, reference_id) = nom::bytes::take(4usize).parse(input)?;
        let reference_id: [u8; 4] = reference_id.try_into().unwrap();

        let (input, (reference_timestamp, origin_timestamp)) =
            (Timestamp::parse, Timestamp::parse).parse(input)?;
        let (input, (receive_timestamp, transmit_timestamp)) =
            (Timestamp::parse, Timestamp::parse).parse(input)?;

        let rv = Self {
            leap_indicator,
            version,
            mode,
            stratum,
            poll,
            precision,
            root_delay,
            root_dispersion,
            reference_id,
            reference_timestamp,
            origin_timestamp,
            receive_timestamp,
            transmit_timestamp,
            extensions: Vec::new(),
        };
        Ok((input, rv))
    }
}

impl TryFrom<Packet> for NtpData {
    type Error = TryFromPacketError;

    fn try_from(value: Packet) -> Result<Self, Self::Error> {
        match value {
            // kiss-o'-death packet
            //
            // [rfc5905 7.4](https://datatracker.ietf.org/doc/html/rfc5905#section-7.4)
            // When a packets stratum is set to "0" it implies that the packet is either invalid or
            // unspecified. In either case the Reference ID field will contain a four letter ascii
            // code specified the nature of the error.
            Packet {
                stratum: 0,
                reference_id,
                ..
            } => Err(Self::Error::KissoDeath(reference_id)),
            // Unsynchronized host
            //
            // Generally NTP servers identify themselves as unsynchronized by their stratum level
            // and leap indicator value. A stratum of "16" and a leap indicator of "0x3" (Unknown)
            // are the most widely used indicators.
            Packet {
                stratum: 16,
                leap_indicator: LeapIndicator::Unknown,
                ..
            } => Err(Self::Error::Unsynchronized),
            // Bad time stamp
            //
            // If the packet was received after it was sent, something has gone wrong and the
            // packet's time stamps should not be used when synchronizing the clock.
            Packet {
                transmit_timestamp,
                receive_timestamp,
                ..
            } if receive_timestamp > transmit_timestamp => Err(Self::Error::BadTimestamps),
            // Useable packet
            Packet {
                root_delay,
                root_dispersion,
                receive_timestamp,
                transmit_timestamp,
                stratum,
                ..
            } => {
                let root_delay = ClockBoundDuration::from(root_delay);
                let root_dispersion = ClockBoundDuration::from(root_dispersion);
                let server_recv_time = ClockBoundInstant::from(receive_timestamp);
                let server_send_time = ClockBoundInstant::from(transmit_timestamp);
                let stratum = Stratum::try_from(stratum)?;
                Ok(NtpData {
                    server_recv_time,
                    server_send_time,

                    root_delay,
                    root_dispersion,

                    stratum,
                })
            }
        }
    }
}

#[derive(Debug, Error, PartialEq)]
pub enum TryFromPacketError {
    #[error("Could not parse stratum value.")]
    ParsingStratum(#[from] TryFromU8Error),
    #[error("Unspecified or invalid packet.")]
    KissoDeath([u8; 4]),
    #[error("The packet's timestamp indicates that it was received after it was transmitted.")]
    BadTimestamps,
    #[error("Server indicates that it is unsynchronized.")]
    Unsynchronized,
}

#[cfg(test)]
mod test {
    use chrono::{DateTime, TimeDelta};
    use hex_literal::hex;
    use rstest::rstest;

    use crate::daemon::io::ntp::packet::extension::Fec2V1Value;

    use super::*;

    // test packet grabbed from wireshark
    // Network Time Protocol (NTP Version 4, server)
    // Flags: 0x24, Leap Indicator: no warning, Version number: NTP Version 4, Mode: server
    // [Request In: 5]
    // [Delta Time: 0.002007000 seconds]
    // Peer Clock Stratum: primary reference (1)
    // Peer Polling Interval: 3 (8 seconds)
    // Peer Clock Precision: -18 (0.000003815 seconds)
    // Root Delay: 0.000031 seconds
    // Root Dispersion: 0.000015 seconds
    // Reference ID: Unidentified reference source '���z'
    // Reference Timestamp: Jan 29, 2025 22:28:14.000004228 UTC // 1738189694 seconds
    // Origin Timestamp: Jan 29, 2025 22:28:14.687415882 UTC // 1738189694 seconds
    // Receive Timestamp: Jan 29, 2025 22:28:14.689357564 UTC // 1738189694 seconds
    // Transmit Timestamp: Jan 29, 2025 22:28:14.689379474 UTC // 1738189694 seconds
    const NTP_PACKET: &[u8] = &hex!(
        "
        240103ee0000000200000001a9fea97aeb4529fe
        000046f3eb4529feaffa7cbceb4529feb079bcc4
        eb4529feb07b2c5b
    "
    );

    #[test]
    fn parse() {
        let (leftover, packet) = Packet::parse_from_bytes(NTP_PACKET).unwrap();
        assert!(leftover.is_empty());
        assert_eq!(packet.leap_indicator, LeapIndicator::NoWarning);
        assert_eq!(packet.version.get(), 4);
        assert_eq!(packet.mode, Mode::Server);
        assert_eq!(packet.stratum, 1);
        assert_eq!(packet.poll, 3);
        assert_eq!(packet.precision, -18); // todo, create type which represents this better
        packet.root_delay.assert_within_error_bound(
            TimeDelta::from_std(std::time::Duration::from_secs_f64(0.000031)).unwrap(),
        );
        packet.root_dispersion.assert_within_error_bound(
            TimeDelta::from_std(std::time::Duration::from_secs_f64(0.000015)).unwrap(),
        );
        assert_eq!(packet.reference_id, [169, 254, 169, 122]);
        packet
            .reference_timestamp
            .assert_within_error_bound(DateTime::from_timestamp(1738189694, 000004228).unwrap());
        packet
            .origin_timestamp
            .assert_within_error_bound(DateTime::from_timestamp(1738189694, 687415882).unwrap());
        packet
            .receive_timestamp
            .assert_within_error_bound(DateTime::from_timestamp(1738189694, 689357564).unwrap());
        packet
            .transmit_timestamp
            .assert_within_error_bound(DateTime::from_timestamp(1738189694, 689379474).unwrap());
    }

    #[rstest]
    #[case::no_extensions(Packet::builder().build(), 48)]
    #[case::with_fec2v1(
        Packet::builder()
            .extensions(vec![ExtensionField::Fec2V1(Fec2V1Value {
                major_version: 2,
                minor_version: 100,
                startup_id: 0xdeadbeef,
            })])
            .build(),
        64
    )]
    fn packet_total_size(#[case] packet: Packet, #[case] expected_size: usize) {
        assert_eq!(packet.total_size(), expected_size);
    }

    #[rstest]
    #[case::no_extensions({
        let (_, packet) = Packet::parse_from_bytes(NTP_PACKET).unwrap();
        (packet, NTP_PACKET.to_vec())
    })]
    #[case::with_extension({
        let (_, mut packet) = Packet::parse_from_bytes(NTP_PACKET).unwrap();
        packet.extensions.push(ExtensionField::Fec2V1(Fec2V1Value {
            major_version: 2,
            minor_version: 100,
            startup_id: 0xdeadbeef,
        }));
        let mut expected = NTP_PACKET.to_vec();
        expected.extend_from_slice(&[0xFE, 0xC2, 0x00, 0x10]); // Extension header
        expected.extend_from_slice(&[1, 2, 100, 0]); // FEC2V1 data
        expected.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF]);
        (packet, expected)
    })]
    fn emit(#[case] (packet, expected): (Packet, Vec<u8>)) {
        let mut output = vec![0u8; packet.total_size()];
        packet.emit_bytes(&mut output);
        assert_eq!(output, expected);
    }

    #[test]
    fn display_does_not_panic() {
        let packet = Packet::new_request(0xd00f_d00f);
        let _ = packet.to_string();
    }

    #[test]
    fn conversion_packet_to_ntp_data() {
        let (_, packet) = Packet::parse_from_bytes(NTP_PACKET).unwrap();
        let ntp_data = NtpData::try_from(packet).unwrap();

        assert!((ntp_data.root_delay.as_seconds_f64() - 0.000031).abs() < 1.0 / 65536.0);
        assert!((ntp_data.root_dispersion.as_seconds_f64() - 0.000015).abs() < 1.0 / 65536.0);
        assert_eq!(
            ntp_data.server_recv_time,
            ClockBoundInstant::from_time(1738189694, 689357564)
        );
        assert_eq!(
            ntp_data.server_send_time,
            ClockBoundInstant::from_time(1738189694, 689379474)
        );
        assert_eq!(ntp_data.stratum, Stratum::ONE);
    }

    #[test]
    fn packet_builder() {
        // Test with defaults
        let default_packet = Packet::builder().build();
        assert_eq!(default_packet.leap_indicator, LeapIndicator::NoWarning);
        assert_eq!(default_packet.version, Version::V4);
        assert_eq!(default_packet.mode, Mode::Client);
        assert_eq!(default_packet.stratum, 0);
        assert_eq!(default_packet.reference_id, [0u8; 4]);
        assert!(default_packet.extensions.is_empty());

        // Test with specified values
        let custom_packet = Packet::builder()
            .mode(Mode::Server)
            .stratum(1)
            .reference_id([0xa9, 0xfe, 0xa9, 0x7a])
            .extensions(vec![ExtensionField::Fec2V1(Fec2V1Value {
                major_version: 1,
                minor_version: 0,
                startup_id: 0xdeadbeef,
            })])
            .build();

        assert_eq!(custom_packet.mode, Mode::Server);
        assert_eq!(custom_packet.stratum, 1);
        assert_eq!(custom_packet.reference_id, [0xa9, 0xfe, 0xa9, 0x7a]);
        assert_eq!(custom_packet.extensions.len(), 1);
    }

    #[rstest]
    #[case::kiss_o_death(
        Packet::builder().build(),
        Err(TryFromPacketError::KissoDeath([0, 0, 0,0]))
    )]
    #[case::healthy(
       Packet::builder()
        .stratum(16)
        .leap_indicator(LeapIndicator::Unknown)
        .build(),
        Err(TryFromPacketError::Unsynchronized)
    )]
    #[case::healthy(
       Packet::builder()
        .stratum(1)
        .receive_timestamp(Timestamp::new(10))
        .transmit_timestamp(Timestamp::new(9))
        .build(),
        Err(TryFromPacketError::BadTimestamps)
    )]
    fn packet_is_unuseable(
        #[case] packet: Packet,
        #[case] ntp_data: Result<NtpData, TryFromPacketError>,
    ) {
        // This unit tests only tests for failures.
        // The happy path is tested in `conversion_packet_to_ntp_data`.
        assert_eq!(packet.try_into(), ntp_data);
    }
}