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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
use std::io::Cursor;

use crate::{
    cookiestash::CookieStash,
    packet::{Cipher, NtpAssociationMode, RequestIdentifier},
    time_types::NtpInstant,
    NtpDuration, NtpPacket, NtpTimestamp, PollInterval, ReferenceId, SystemConfig, SystemSnapshot,
};
use serde::{Deserialize, Serialize};
use tracing::{debug, info, instrument, trace, warn};

const MAX_STRATUM: u8 = 16;
const POLL_WINDOW: std::time::Duration = std::time::Duration::from_secs(5);
const STARTUP_TRIES_THRESHOLD: usize = 3;

#[derive(Debug, thiserror::Error)]
pub enum NtsError {
    #[error("Ran out of nts cookies")]
    OutOfCookies,
}

pub struct PeerNtsData {
    pub(crate) cookies: CookieStash,
    // Note: we use Box<dyn Cipher> to support the use
    // of multiple different ciphers, that might differ
    // in the key information they need to keep.
    pub(crate) c2s: Box<dyn Cipher>,
    pub(crate) s2c: Box<dyn Cipher>,
}

#[cfg(feature = "ext-test")]
impl PeerNtsData {
    pub fn get_cookie(&mut self) -> Option<Vec<u8>> {
        self.cookies.get()
    }

    pub fn get_keys(self) -> (Box<dyn Cipher>, Box<dyn Cipher>) {
        (self.c2s, self.s2c)
    }
}

impl std::fmt::Debug for PeerNtsData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PeerNtsData")
            .field("cookies", &self.cookies)
            .finish()
    }
}

#[derive(Debug)]
pub struct Peer {
    nts: Option<Box<PeerNtsData>>,

    // Poll interval dictated by unreachability backoff
    backoff_interval: PollInterval,
    // Poll interval used when sending last poll mesage.
    last_poll_interval: PollInterval,
    // The poll interval desired by the remove server.
    // Must be increased when the server sends the RATE kiss code.
    remote_min_poll_interval: PollInterval,

    // Identifier of the last request sent to the server. This is correlated
    // with any received response from the server to guard against replay
    // attacks and packet reordering.
    current_request_identifier: Option<(RequestIdentifier, NtpInstant)>,

    stratum: u8,
    reference_id: ReferenceId,

    peer_id: ReferenceId,
    our_id: ReferenceId,
    reach: Reach,
    tries: usize,

    system_config: SystemConfig,
}

#[derive(Debug, Copy, Clone)]
pub struct Measurement {
    pub delay: NtpDuration,
    pub offset: NtpDuration,
    pub localtime: NtpTimestamp,
    pub monotime: NtpInstant,
}

impl Measurement {
    fn from_packet(
        packet: &NtpPacket,
        send_timestamp: NtpTimestamp,
        recv_timestamp: NtpTimestamp,
        local_clock_time: NtpInstant,
        precision: NtpDuration,
    ) -> Self {
        Self {
            delay: ((recv_timestamp - send_timestamp)
                - (packet.transmit_timestamp() - packet.receive_timestamp()))
            .max(precision),
            offset: ((packet.receive_timestamp() - send_timestamp)
                + (packet.transmit_timestamp() - recv_timestamp))
                / 2,
            localtime: send_timestamp + (recv_timestamp - send_timestamp) / 2,
            monotime: local_clock_time,
        }
    }
}

/// Used to determine whether the server is reachable and the data are fresh
///
/// This value is represented as an 8-bit shift register. The register is shifted left
/// by one bit when a packet is sent and the rightmost bit is set to zero.
/// As valid packets arrive, the rightmost bit is set to one.
/// If the register contains any nonzero bits, the server is considered reachable;
/// otherwise, it is unreachable.
#[derive(Default, Clone, Copy, Serialize, Deserialize)]
pub struct Reach(u8);

impl std::fmt::Debug for Reach {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_reachable() {
            write!(
                f,
                "Reach(0b{:07b} ({} polls until unreachable))",
                self.0,
                7 - self.0.trailing_zeros()
            )
        } else {
            write!(f, "Reach(unreachable)",)
        }
    }
}

impl Reach {
    pub fn is_reachable(&self) -> bool {
        self.0 != 0
    }

    /// We have just received a packet, so the peer is definitely reachable
    pub(crate) fn received_packet(&mut self) {
        self.0 |= 1;
    }

    /// A packet received some number of poll intervals ago is decreasingly relevant for
    /// determining that a peer is still reachable. We discount the packets received so far.
    fn poll(&mut self) {
        self.0 <<= 1
    }

    /// Number of polls since the last message we received
    pub fn unanswered_polls(&self) -> u32 {
        self.0.leading_zeros()
    }

    /// Number of polls remaining until unreachable
    pub fn reachability_score(&self) -> u32 {
        8 - self.0.trailing_zeros()
    }
}

#[derive(Debug)]
pub enum IgnoreReason {
    /// The packet doesn't parse
    InvalidPacket,
    /// The association mode is not one that this peer supports
    InvalidMode,
    /// The NTP version is not one that this implementation supports
    InvalidVersion,
    /// The stratum of the server is too high
    InvalidStratum,
    /// The send time on the received packet is not the time we sent it at
    InvalidPacketTime,
    /// Received a Kiss-o'-Death https://datatracker.ietf.org/doc/html/rfc5905#section-7.4
    KissIgnore,
    /// Received a DENY or RSTR Kiss-o'-Death, and must demobilize the association
    KissDemobilize,
    /// Received a matching NTS-Nack, no further action needed.
    KissNtsNack,
    /// The best packet is older than the peer's current time
    TooOld,
}

#[derive(Debug, Clone, Copy)]
pub struct PeerSnapshot {
    pub peer_id: ReferenceId,
    pub our_id: ReferenceId,

    pub poll_interval: PollInterval,
    pub reach: Reach,

    pub stratum: u8,
    pub reference_id: ReferenceId,
}

impl PeerSnapshot {
    pub fn accept_synchronization(
        &self,
        local_stratum: u8,
    ) -> Result<(), AcceptSynchronizationError> {
        use AcceptSynchronizationError::*;

        if self.stratum >= local_stratum {
            warn!(
                stratum = debug(self.stratum),
                "Peer rejected due to invalid stratum"
            );
            return Err(Stratum);
        }

        // Detect whether the remote uses us as their main time reference.
        // if so, we shouldn't sync to them as that would create a loop.
        // Note, this can only ever be an issue if the peer is not using
        // hardware as its source, so ignore reference_id if stratum is 1.
        if self.stratum != 1 && self.reference_id == self.our_id {
            debug!("Peer rejected because of detected synchornization loop");
            return Err(Loop);
        }

        // An unreachable error occurs if the server is unreachable.
        if !self.reach.is_reachable() {
            warn!("Peer unreachable");
            return Err(ServerUnreachable);
        }

        Ok(())
    }

    pub fn from_peer(peer: &Peer) -> Self {
        Self {
            peer_id: peer.peer_id,
            our_id: peer.our_id,
            stratum: peer.stratum,
            reference_id: peer.reference_id,
            reach: peer.reach,
            poll_interval: peer.last_poll_interval,
        }
    }
}

#[cfg(feature = "ext-test")]
pub fn peer_snapshot() -> crate::PeerSnapshot {
    let mut reach = crate::peer::Reach::default();
    reach.received_packet();

    crate::PeerSnapshot {
        peer_id: ReferenceId::from_int(0),
        stratum: 0,
        reference_id: ReferenceId::from_int(0),

        our_id: ReferenceId::from_int(1),
        reach,
        poll_interval: crate::time_types::PollIntervalLimits::default().min,
    }
}

#[derive(Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum AcceptSynchronizationError {
    ServerUnreachable,
    Loop,
    Distance,
    Stratum,
}

#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum Update {
    BareUpdate(PeerSnapshot),
    NewMeasurement(PeerSnapshot, Measurement, NtpPacket<'static>),
}

#[derive(Debug, thiserror::Error)]
pub enum PollError {
    #[error("{0}")]
    Io(#[from] std::io::Error),
    #[error("peer unreachable")]
    Unreachable,
}

impl Peer {
    #[instrument]
    pub fn new(
        our_id: ReferenceId,
        peer_id: ReferenceId,
        local_clock_time: NtpInstant,
        system_config: SystemConfig,
    ) -> Self {
        Self {
            nts: None,

            last_poll_interval: system_config.poll_limits.min,
            backoff_interval: system_config.poll_limits.min,
            remote_min_poll_interval: system_config.poll_limits.min,

            current_request_identifier: None,
            our_id,
            peer_id,
            reach: Default::default(),
            tries: 0,

            stratum: 16,
            reference_id: ReferenceId::NONE,

            system_config,
        }
    }

    #[instrument]
    pub fn new_nts(
        our_id: ReferenceId,
        peer_id: ReferenceId,
        local_clock_time: NtpInstant,
        system_config: SystemConfig,
        nts: Box<PeerNtsData>,
    ) -> Self {
        Self {
            nts: Some(nts),
            ..Self::new(our_id, peer_id, local_clock_time, system_config)
        }
    }

    pub fn update_config(&mut self, system_config: SystemConfig) {
        self.system_config = system_config;
    }

    pub fn current_poll_interval(&self, system: SystemSnapshot) -> PollInterval {
        system
            .time_snapshot
            .poll_interval
            .max(self.backoff_interval)
            .max(self.remote_min_poll_interval)
    }

    pub fn generate_poll_message<'a>(
        &mut self,
        buf: &'a mut [u8],
        system: SystemSnapshot,
        system_config: &SystemConfig,
    ) -> Result<&'a [u8], PollError> {
        if !self.reach.is_reachable() && self.tries >= STARTUP_TRIES_THRESHOLD {
            return Err(PollError::Unreachable);
        }

        self.reach.poll();
        self.tries = self.tries.saturating_add(1);

        let poll_interval = self.current_poll_interval(system);
        let (packet, identifier) = match &mut self.nts {
            Some(nts) => {
                let cookie = nts.cookies.get().ok_or_else(|| {
                    std::io::Error::new(std::io::ErrorKind::Other, NtsError::OutOfCookies)
                })?;
                NtpPacket::nts_poll_message(&cookie, nts.cookies.gap(), poll_interval)
            }
            None => NtpPacket::poll_message(poll_interval),
        };
        self.current_request_identifier = Some((identifier, NtpInstant::now() + POLL_WINDOW));

        // Ensure we don't spam the remote with polls if it is not reachable
        self.backoff_interval = poll_interval.inc(system_config.poll_limits);

        // Write packet to buffer
        let mut cursor = Cursor::new(buf);
        packet.serialize(&mut cursor, &self.nts.as_ref().map(|nts| nts.c2s.as_ref()))?;
        let used = cursor.position();
        let result = &cursor.into_inner()[..used as usize];

        Ok(result)
    }

    #[instrument(skip(self, system), fields(peer = debug(self.peer_id)))]
    pub fn handle_incoming(
        &mut self,
        system: SystemSnapshot,
        message: &[u8],
        local_clock_time: NtpInstant,
        send_time: NtpTimestamp,
        recv_time: NtpTimestamp,
    ) -> Result<Update, IgnoreReason> {
        let message =
            match NtpPacket::deserialize(message, &self.nts.as_ref().map(|nts| nts.s2c.as_ref())) {
                Ok((packet, _)) => packet,
                Err(e) => {
                    warn!("received invalid packet: {}", e);
                    return Err(IgnoreReason::InvalidPacket);
                }
            };

        let request_identifier = match self.current_request_identifier {
            Some((next_expected_origin, validity)) if validity >= NtpInstant::now() => {
                next_expected_origin
            }
            _ => {
                debug!("Received old/unexpected packet from peer");
                return Err(IgnoreReason::InvalidPacketTime);
            }
        };

        if !message.valid_server_response(request_identifier, self.nts.is_some()) {
            // Packets should be a response to a previous request from us,
            // if not just ignore. Note that this might also happen when
            // we reset between sending the request and receiving the response.
            // We do this as the first check since accepting even a KISS
            // packet that is not a response will leave us vulnerable
            // to denial of service attacks.
            debug!("Received old/unexpected packet from peer");
            Err(IgnoreReason::InvalidPacketTime)
        } else if message.is_kiss_rate() {
            // KISS packets may not have correct timestamps at all, handle them anyway
            self.remote_min_poll_interval = Ord::max(
                self.remote_min_poll_interval
                    .inc(self.system_config.poll_limits),
                self.last_poll_interval,
            );
            warn!(?self.remote_min_poll_interval, "Peer requested rate limit");
            Err(IgnoreReason::KissIgnore)
        } else if message.is_kiss_rstr() || message.is_kiss_deny() {
            warn!("Peer denied service");
            // KISS packets may not have correct timestamps at all, handle them anyway
            Err(IgnoreReason::KissDemobilize)
        } else if message.is_kiss_ntsn() {
            warn!("Received nts not-acknowledge");
            // as these can be easily faked, we dont immediately give up on receiving
            // a response, however, for the purpose of backoff we do count it as a response.
            // This ensures that if we have expired cookies, we get through them
            // fairly quickly.
            self.backoff_interval = self.system_config.poll_limits.min;
            Err(IgnoreReason::KissNtsNack)
        } else if message.is_kiss() {
            warn!("Unrecognized KISS Message from peer");
            // Ignore unrecognized control messages
            Err(IgnoreReason::KissIgnore)
        } else if message.stratum() > MAX_STRATUM {
            // A servers stratum should be between 1 and MAX_STRATUM (16) inclusive.
            warn!(
                "Received message from server with excessive stratum {}",
                message.stratum()
            );
            Err(IgnoreReason::InvalidStratum)
        } else if message.mode() != NtpAssociationMode::Server {
            // we currently only support a client <-> server association
            warn!("Received packet with invalid mode");
            Err(IgnoreReason::InvalidMode)
        } else {
            Ok(self.process_message(system, message, local_clock_time, send_time, recv_time))
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn process_message(
        &mut self,
        system: SystemSnapshot,
        message: NtpPacket,
        local_clock_time: NtpInstant,
        send_time: NtpTimestamp,
        recv_time: NtpTimestamp,
    ) -> Update {
        trace!("Packet accepted for processing");
        // For reachability, mark that we have had a response
        self.reach.received_packet();

        // Got a response, so no need for unreachability backoff
        self.backoff_interval = self.system_config.poll_limits.min;

        // we received this packet, and don't want to accept future ones with this next_expected_origin
        self.current_request_identifier = None;

        // Update stratum and reference id
        self.stratum = message.stratum();
        self.reference_id = message.reference_id();

        // generate a measurement
        let measurement = Measurement::from_packet(
            &message,
            send_time,
            recv_time,
            local_clock_time,
            system.time_snapshot.precision,
        );

        // Process new cookies
        if let Some(nts) = self.nts.as_mut() {
            for cookie in message.new_cookies() {
                nts.cookies.store(cookie);
            }
        }

        Update::NewMeasurement(
            PeerSnapshot::from_peer(self),
            measurement,
            message.into_owned(),
        )
    }

    #[instrument(level="trace", skip(self), fields(peer = debug(self.peer_id)))]
    pub fn reset(&mut self) {
        // make sure in-flight messages are ignored
        self.current_request_identifier = None;

        info!(our_id = ?self.our_id, peer_id = ?self.peer_id, "Peer reset");
    }

    #[cfg(test)]
    pub(crate) fn test_peer() -> Self {
        Peer {
            nts: None,

            last_poll_interval: PollInterval::default(),
            backoff_interval: PollInterval::default(),
            remote_min_poll_interval: PollInterval::default(),

            current_request_identifier: None,

            peer_id: ReferenceId::from_int(0),
            our_id: ReferenceId::from_int(0),
            reach: Reach::default(),
            tries: 0,

            stratum: 0,
            reference_id: ReferenceId::from_int(0),

            system_config: SystemConfig::default(),
        }
    }
}

#[cfg(feature = "fuzz")]
pub fn fuzz_measurement_from_packet(
    client: u64,
    client_interval: u32,
    server: u64,
    server_interval: u32,
    client_precision: i8,
    server_precision: i8,
) {
    let mut packet = NtpPacket::test();
    packet.set_origin_timestamp(NtpTimestamp::from_fixed_int(client));
    packet.set_receive_timestamp(NtpTimestamp::from_fixed_int(server));
    packet.set_transmit_timestamp(NtpTimestamp::from_fixed_int(
        server.wrapping_add(server_interval as u64),
    ));
    packet.set_precision(server_precision);

    let result = Measurement::from_packet(
        &packet,
        NtpTimestamp::from_fixed_int(client),
        NtpTimestamp::from_fixed_int(client.wrapping_add(client_interval as u64)),
        NtpInstant::now(),
        NtpDuration::from_exponent(client_precision),
    );

    assert!(result.delay >= NtpDuration::ZERO);
}

#[cfg(test)]
mod test {
    use crate::{packet::NoCipher, time_types::PollIntervalLimits};

    use super::*;
    use std::time::Duration;

    #[test]
    fn test_measurement_from_packet() {
        let instant = NtpInstant::now();

        let mut packet = NtpPacket::test();
        packet.set_receive_timestamp(NtpTimestamp::from_fixed_int(1));
        packet.set_transmit_timestamp(NtpTimestamp::from_fixed_int(2));
        let result = Measurement::from_packet(
            &packet,
            NtpTimestamp::from_fixed_int(0),
            NtpTimestamp::from_fixed_int(3),
            instant,
            NtpDuration::from_exponent(-32),
        );
        assert_eq!(result.offset, NtpDuration::from_fixed_int(0));
        assert_eq!(result.delay, NtpDuration::from_fixed_int(2));

        packet.set_receive_timestamp(NtpTimestamp::from_fixed_int(2));
        packet.set_transmit_timestamp(NtpTimestamp::from_fixed_int(3));
        let result = Measurement::from_packet(
            &packet,
            NtpTimestamp::from_fixed_int(0),
            NtpTimestamp::from_fixed_int(3),
            instant,
            NtpDuration::from_exponent(-32),
        );
        assert_eq!(result.offset, NtpDuration::from_fixed_int(1));
        assert_eq!(result.delay, NtpDuration::from_fixed_int(2));

        packet.set_receive_timestamp(NtpTimestamp::from_fixed_int(0));
        packet.set_transmit_timestamp(NtpTimestamp::from_fixed_int(5));
        let result = Measurement::from_packet(
            &packet,
            NtpTimestamp::from_fixed_int(0),
            NtpTimestamp::from_fixed_int(3),
            instant,
            NtpDuration::from_exponent(-32),
        );
        assert_eq!(result.offset, NtpDuration::from_fixed_int(1));
        assert_eq!(result.delay, NtpDuration::from_fixed_int(1));
    }

    #[test]
    fn reachability() {
        let mut reach = Reach::default();

        // the default reach register value is 0, and hence not reachable
        assert!(!reach.is_reachable());

        // when we receive a packet, we set the right-most bit;
        // we just received a packet from the peer, so it is reachable
        reach.received_packet();
        assert!(reach.is_reachable());

        // on every poll, the register is shifted to the left, and there are
        // 8 bits. So we can poll 7 times and the peer is still considered reachable
        for _ in 0..7 {
            reach.poll();
        }

        assert!(reach.is_reachable());

        // but one more poll and all 1 bits have been shifted out;
        // the peer is no longer reachable
        reach.poll();
        assert!(!reach.is_reachable());

        // until we receive a packet from it again
        reach.received_packet();
        assert!(reach.is_reachable());
    }

    #[test]
    fn test_accept_synchronization() {
        use AcceptSynchronizationError::*;

        let mut peer = Peer::test_peer();

        macro_rules! accept {
            () => {{
                let snapshot = PeerSnapshot::from_peer(&peer);
                snapshot.accept_synchronization(16)
            }};
        }

        // by default, the packet id and the peer's id are the same, indicating a loop
        assert_eq!(accept!(), Err(Loop));

        peer.our_id = ReferenceId::from_int(42);

        assert_eq!(accept!(), Err(ServerUnreachable));

        peer.reach.received_packet();

        assert_eq!(accept!(), Ok(()));

        peer.stratum = 42;
        assert_eq!(accept!(), Err(Stratum));
    }

    #[test]
    fn test_poll_interval() {
        let base = NtpInstant::now();
        let mut peer = Peer::test_peer();
        let mut system = SystemSnapshot::default();

        assert!(peer.current_poll_interval(system) >= peer.remote_min_poll_interval);
        assert!(peer.current_poll_interval(system) >= system.time_snapshot.poll_interval);

        system.time_snapshot.poll_interval = PollIntervalLimits::default().max;

        assert!(peer.current_poll_interval(system) >= peer.remote_min_poll_interval);
        assert!(peer.current_poll_interval(system) >= system.time_snapshot.poll_interval);

        system.time_snapshot.poll_interval = PollIntervalLimits::default().min;
        peer.remote_min_poll_interval = PollIntervalLimits::default().max;

        assert!(peer.current_poll_interval(system) >= peer.remote_min_poll_interval);
        assert!(peer.current_poll_interval(system) >= system.time_snapshot.poll_interval);

        peer.remote_min_poll_interval = PollIntervalLimits::default().min;

        let prev = peer.current_poll_interval(system);
        let mut buf = [0; 1024];
        let packetbuf = peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .unwrap();
        let packet = NtpPacket::deserialize(packetbuf, &NoCipher).unwrap().0;
        assert!(peer.current_poll_interval(system) > prev);
        let mut response = NtpPacket::test();
        response.set_mode(NtpAssociationMode::Server);
        response.set_stratum(1);
        response.set_origin_timestamp(packet.transmit_timestamp());
        assert!(peer
            .handle_incoming(
                system,
                &response.serialize_without_encryption_vec().unwrap(),
                base,
                NtpTimestamp::default(),
                NtpTimestamp::default()
            )
            .is_ok());
        assert_eq!(peer.current_poll_interval(system), prev);

        let prev = peer.current_poll_interval(system);
        let mut buf = [0; 1024];
        let packetbuf = peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .unwrap();
        let packet = NtpPacket::deserialize(packetbuf, &NoCipher).unwrap().0;
        assert!(peer.current_poll_interval(system) > prev);
        let mut response = NtpPacket::test();
        response.set_mode(NtpAssociationMode::Server);
        response.set_stratum(0);
        response.set_origin_timestamp(packet.transmit_timestamp());
        response.set_reference_id(ReferenceId::KISS_RATE);
        assert!(peer
            .handle_incoming(
                system,
                &response.serialize_without_encryption_vec().unwrap(),
                base,
                NtpTimestamp::default(),
                NtpTimestamp::default()
            )
            .is_err());
        assert!(peer.current_poll_interval(system) > prev);
        assert!(peer.remote_min_poll_interval > prev);
    }

    #[test]
    fn test_handle_incoming() {
        let base = NtpInstant::now();
        let mut peer = Peer::test_peer();

        let system = SystemSnapshot::default();
        let mut buf = [0; 1024];
        let outgoingbuf = peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .unwrap();
        let outgoing = NtpPacket::deserialize(outgoingbuf, &NoCipher).unwrap().0;
        let mut packet = NtpPacket::test();
        let system = SystemSnapshot::default();
        packet.set_stratum(1);
        packet.set_mode(NtpAssociationMode::Server);
        packet.set_origin_timestamp(outgoing.transmit_timestamp());
        packet.set_receive_timestamp(NtpTimestamp::from_fixed_int(100));
        packet.set_transmit_timestamp(NtpTimestamp::from_fixed_int(200));

        assert!(peer
            .handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(400)
            )
            .is_ok());
        //assert_eq!(peer.timestate.last_packet, packet);
        assert!(peer
            .handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(500)
            )
            .is_err());
    }

    #[test]
    fn test_startup_unreachable() {
        let mut peer = Peer::test_peer();
        let system = SystemSnapshot::default();
        let mut buf = [0; 1024];
        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(matches!(
            peer.generate_poll_message(&mut buf, system, &SystemConfig::default()),
            Err(PollError::Unreachable)
        ));
    }

    #[test]
    fn test_running_unreachable() {
        let base = NtpInstant::now();
        let mut peer = Peer::test_peer();

        let system = SystemSnapshot::default();
        let mut buf = [0; 1024];
        let outgoingbuf = peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .unwrap();
        let outgoing = NtpPacket::deserialize(outgoingbuf, &NoCipher).unwrap().0;
        let mut packet = NtpPacket::test();
        let system = SystemSnapshot::default();
        packet.set_stratum(1);
        packet.set_mode(NtpAssociationMode::Server);
        packet.set_origin_timestamp(outgoing.transmit_timestamp());
        packet.set_receive_timestamp(NtpTimestamp::from_fixed_int(100));
        packet.set_transmit_timestamp(NtpTimestamp::from_fixed_int(200));
        assert!(peer
            .handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(400)
            )
            .is_ok());

        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .is_ok());
        assert!(matches!(
            peer.generate_poll_message(&mut buf, system, &SystemConfig::default()),
            Err(PollError::Unreachable)
        ));
    }

    #[test]
    fn test_stratum_checks() {
        let base = NtpInstant::now();
        let mut peer = Peer::test_peer();

        let system = SystemSnapshot::default();
        let mut buf = [0; 1024];
        let outgoingbuf = peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .unwrap();
        let outgoing = NtpPacket::deserialize(outgoingbuf, &NoCipher).unwrap().0;
        let mut packet = NtpPacket::test();
        let system = SystemSnapshot::default();
        packet.set_stratum(MAX_STRATUM + 1);
        packet.set_mode(NtpAssociationMode::Server);
        packet.set_origin_timestamp(outgoing.transmit_timestamp());
        packet.set_receive_timestamp(NtpTimestamp::from_fixed_int(100));
        packet.set_transmit_timestamp(NtpTimestamp::from_fixed_int(200));
        assert!(peer
            .handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(500)
            )
            .is_err());

        packet.set_stratum(0);
        assert!(peer
            .handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(500)
            )
            .is_err());
    }

    #[test]
    fn test_handle_kod() {
        let base = NtpInstant::now();
        let mut peer = Peer::test_peer();

        let mut packet = NtpPacket::test();
        let system = SystemSnapshot::default();
        packet.set_reference_id(ReferenceId::KISS_RSTR);
        packet.set_mode(NtpAssociationMode::Server);
        assert!(!matches!(
            peer.handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(100)
            ),
            Err(IgnoreReason::KissDemobilize)
        ));

        let mut packet = NtpPacket::test();
        let system = SystemSnapshot::default();
        let mut buf = [0; 1024];
        let outgoingbuf = peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .unwrap();
        let outgoing = NtpPacket::deserialize(outgoingbuf, &NoCipher).unwrap().0;
        packet.set_reference_id(ReferenceId::KISS_RSTR);
        packet.set_origin_timestamp(outgoing.transmit_timestamp());
        packet.set_mode(NtpAssociationMode::Server);
        assert!(matches!(
            peer.handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(100)
            ),
            Err(IgnoreReason::KissDemobilize)
        ));

        let mut packet = NtpPacket::test();
        let system = SystemSnapshot::default();
        packet.set_reference_id(ReferenceId::KISS_DENY);
        packet.set_mode(NtpAssociationMode::Server);
        assert!(!matches!(
            peer.handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(100)
            ),
            Err(IgnoreReason::KissDemobilize)
        ));

        let mut packet = NtpPacket::test();
        let system = SystemSnapshot::default();
        let outgoingbuf = peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .unwrap();
        let outgoing = NtpPacket::deserialize(outgoingbuf, &NoCipher).unwrap().0;
        packet.set_reference_id(ReferenceId::KISS_DENY);
        packet.set_origin_timestamp(outgoing.transmit_timestamp());
        packet.set_mode(NtpAssociationMode::Server);
        assert!(matches!(
            peer.handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(100)
            ),
            Err(IgnoreReason::KissDemobilize)
        ));

        let old_poll_interval = peer.last_poll_interval;
        let old_remote_interval = peer.remote_min_poll_interval;
        let mut packet = NtpPacket::test();
        let system = SystemSnapshot::default();
        packet.set_reference_id(ReferenceId::KISS_RATE);
        packet.set_mode(NtpAssociationMode::Server);
        assert!(peer
            .handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(100)
            )
            .is_err());
        assert_eq!(peer.remote_min_poll_interval, old_poll_interval);
        assert_eq!(peer.remote_min_poll_interval, old_remote_interval);

        let old_poll_interval = peer.last_poll_interval;
        let old_remote_interval = peer.remote_min_poll_interval;
        let mut packet = NtpPacket::test();
        let system = SystemSnapshot::default();
        let mut buf = [0; 1024];
        let outgoingbuf = peer
            .generate_poll_message(&mut buf, system, &SystemConfig::default())
            .unwrap();
        let outgoing = NtpPacket::deserialize(outgoingbuf, &NoCipher).unwrap().0;
        packet.set_reference_id(ReferenceId::KISS_RATE);
        packet.set_origin_timestamp(outgoing.transmit_timestamp());
        packet.set_mode(NtpAssociationMode::Server);
        assert!(peer
            .handle_incoming(
                system,
                &packet.serialize_without_encryption_vec().unwrap(),
                base + Duration::from_secs(1),
                NtpTimestamp::from_fixed_int(0),
                NtpTimestamp::from_fixed_int(100)
            )
            .is_err());
        assert!(peer.remote_min_poll_interval > old_poll_interval);
        assert!(peer.remote_min_poll_interval >= old_remote_interval);
    }
}