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
#![cfg_attr(
    all(feature = "async", feature = "chrono", feature = "time"),
    doc = r##"
# rsntp

An [RFC 5905](https://www.rfc-editor.org/rfc/rfc5905.txt) compliant Simple Network Time Protocol (SNTP) client
library for Rust.

`rsntp` provides an API to synchronize time with SNTPv4 time servers with the following features:
* Provides both a synchronous (blocking) and an (optional) asynchronous, `tokio` based API
* Optional support for time and date crates `chrono` and `time` (`chrono` is enabled by
  default)
* IPv6 support

## Usage

Add this to your `Cargo.toml`:

```toml
[dependencies]
rsntp = "4.0.0"
```

Obtain the current local time with the blocking API:

```no_run
use rsntp::SntpClient;
use chrono::{DateTime, Local};

let client = SntpClient::new();
let result = client.synchronize("pool.ntp.org").unwrap();

let local_time: DateTime<Local> =
  DateTime::from(result.datetime().into_chrono_datetime().unwrap());

println!("Current time is: {}", local_time);
```

You can also use the asynchronous API to do the same:

```no_run
use rsntp::AsyncSntpClient;
use chrono::{DateTime, Local, Utc};

async fn local_time() -> DateTime<Local> {
  let client = AsyncSntpClient::new();
  let result = client.synchronize("pool.ntp.org").await.unwrap();
   
   DateTime::from(result.datetime().into_chrono_datetime().unwrap())
}
```

## API changes in version 3.0

Version 3.0 made core code independent of time and date crates and added support for the `time` crate.
This led to some breaking API changes, `SynchronizationResult` methods will return with wrappers
struct instead of `chrono` ones. Those wrapper structs has `TryInto` implementation and helper
methods to convert them to `chrono` format.

To convert old code, replace
```no_run
# use rsntp::SntpClient;
# let result = SntpClient::new().synchronize("pool.ntp.org").unwrap();
let datetime = result.datetime();
```
with
```no_run
# use rsntp::SntpClient;
# use chrono::{DateTime, Utc};
# let result = SntpClient::new().synchronize("pool.ntp.org").unwrap();
let datetime = result.datetime().into_chrono_datetime().unwrap();
```
or with
```no_run
# use rsntp::SntpClient;
# use chrono::{DateTime, Utc};
# let result = SntpClient::new().synchronize("pool.ntp.org").unwrap();
let datetime: chrono::DateTime<Utc> = result.datetime().try_into().unwrap();
```

The same applies to `Duration`s returned by `SynchronizationResult`.

## Support for time and date crates

`rsntp` supports returning time and date data in different formats. Currently the format of
the two most popular time and date handling crates supported: `chrono` and `time`.
By default, `chrono` is enabled, but you can add `time` support with a feature:

```no_run
use rsntp::SntpClient;

let client = SntpClient::new();
let result = client.synchronize("pool.ntp.org").unwrap();

let utc_time = result
  .datetime()
  .into_offset_date_time()
  .unwrap();

println!("UTC time is: {}", utc_time);
```

Support for both crates can be enabled independently; you can even enable both
at the same time.

## Disabling asynchronous API

The asynchronous API is enabled by default, but you can disable it. Disabling it 
has the advantage that it removes the dependency to `tokio`, which reduces 
the amount of dependencies significantly.

```toml
[dependencies]
rsntp = { version = "4.0.0", default-features = false, features = ["chrono"]  }
```

## System clock assumptions

`rsntp` assumes that system clock is monotonic and stable. This is especially important
with the `SynchronizationResult::datetime()` method, as `SynchronizationResult` stores just
an offset to the system clock. If the system clock is changed between synchronization
and the call to this method, then offset will not be valid anymore and some undefined result
might be returned.

## IPv6 support

`rsntp` supports IPv6, but for compatibility reasons, it binds its UDP socket to an
IPv4 address (0.0.0.0) by default. That might prevent synchronization with IPv6 servers.

To use IPv6, you need to set an IPv6 bind address:

```no_run
use rsntp::{Config, SntpClient};
use std::net::Ipv6Addr;

let config = Config::default().bind_address((Ipv6Addr::UNSPECIFIED, 0).into());
let client = SntpClient::with_config(config);

let result = client.synchronize("2.pool.ntp.org").unwrap();

let unix_timestamp_utc = result.datetime().unix_timestamp();
```
"##
)]

mod core_logic;
mod error;
mod packet;
mod result;
mod to_server_addrs;

pub use error::{ConversionError, KissCode, ProtocolError, SynchronizationError};
pub use packet::{LeapIndicator, ReferenceIdentifier};
pub use result::{SntpDateTime, SntpDuration, SynchronizationResult};
pub use to_server_addrs::ToServerAddrs;

use core_logic::{Reply, Request};
use packet::Packet;
use std::default::Default;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::time::Duration;

#[cfg(feature = "async")]
use tokio::time::timeout;

const SNTP_PORT: u16 = 123;

/// Client configuration
///
/// This is a struct that contains the configuration of a client. It uses a builder-like pattern
/// to set parameters. Its main aim is to be able to create client instances with non-default
/// configuration without making them mutable.
///
/// # Example
///
/// ```no_run
/// use rsntp::{Config, SntpClient};
/// use std::time::Duration;
///
/// let config = Config::default().bind_address("192.168.0.1:0".parse().unwrap()).timeout(Duration::from_secs(10));
/// let client = SntpClient::with_config(config);
/// ```
#[derive(Clone, Debug, Hash)]
pub struct Config {
    bind_address: SocketAddr,
    timeout: Duration,
}

impl Config {
    /// Set UDP bind address
    ///
    /// Sets the local address which is used to send/receive UDP packets. By default, it is
    /// "0.0.0.0:0" which means that IPv4 address and port are chosen automatically.
    ///
    /// To synchronize with IPv6 servers, you might need to set it to an IPv6 address.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::{Config, SntpClient};
    ///
    /// let config = Config::default().bind_address("192.168.0.1:0".parse().unwrap());
    /// let client = SntpClient::with_config(config);
    /// ```
    pub fn bind_address(self, address: SocketAddr) -> Config {
        Config {
            bind_address: address,
            timeout: self.timeout,
        }
    }

    /// Sets synchronization timeout
    ///
    /// Sets the time the client waits for a reply after the request has been sent.
    /// Default is 3 seconds.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::{Config, SntpClient};
    /// use std::time::Duration;
    ///
    /// let config = Config::default().timeout(Duration::from_secs(10));
    /// let client = SntpClient::with_config(config);
    /// ```
    pub fn timeout(self, timeout: Duration) -> Config {
        Config {
            bind_address: self.bind_address,
            timeout,
        }
    }
}

impl Default for Config {
    /// Creates an instance with default configuration
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::Config;
    ///
    /// let config = Config::default();
    /// ```
    fn default() -> Config {
        Config {
            bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0),
            timeout: Duration::from_secs(3),
        }
    }
}

/// Blocking client instance
///
/// This is the main entry point of the blocking API.
#[derive(Clone, Debug, Hash)]
pub struct SntpClient {
    config: Config,
}

impl SntpClient {
    /// Creates a new instance with default configuration
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::SntpClient;
    ///
    /// let client = SntpClient::new();
    /// ```
    pub fn new() -> SntpClient {
        SntpClient {
            config: Config::default(),
        }
    }

    /// Creates a new instance with the specified configuration
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::{Config, SntpClient};
    ///
    /// let client = SntpClient::with_config(Config::default());
    /// ```
    pub fn with_config(config: Config) -> SntpClient {
        SntpClient { config }
    }

    /// Synchronize with the server
    ///
    /// Sends a request to the server, waits for the reply, and processes it. This is a blocking call
    /// and can block for a long time. After sending the request, it waits for a timeout; if no
    /// reply is received, an error is returned.
    ///
    /// If the supplied server address resolves to multiple addresses, only the first one is used.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::SntpClient;
    ///
    /// let client = SntpClient::new();
    /// let result = client.synchronize("pool.ntp.org");
    /// ```
    pub fn synchronize<A: ToServerAddrs>(
        &self,
        server_address: A,
    ) -> Result<SynchronizationResult, SynchronizationError> {
        let socket = std::net::UdpSocket::bind(self.config.bind_address)?;

        socket.set_read_timeout(Some(self.config.timeout))?;
        socket.connect(server_address.to_server_addrs(SNTP_PORT))?;

        let request = Request::new();
        let mut receive_buffer = [0; Packet::ENCODED_LEN];

        socket.send(&request.as_bytes())?;
        let (bytes_received, server_address) = socket.recv_from(&mut receive_buffer)?;

        let reply = Reply::new(
            request,
            Packet::from_bytes(&receive_buffer[..bytes_received], server_address)?,
        );

        reply.process()
    }

    /// Sets synchronization timeout
    ///
    /// Sets the time the client waits for a reply after the request has been sent.
    /// Default is 3 seconds.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::SntpClient;
    /// use std::time::Duration;
    ///
    /// let mut client = SntpClient::new();
    /// client.set_timeout(Duration::from_secs(10));
    /// ```
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.config.timeout = timeout;
    }

    /// Set UDP bind address
    ///
    /// Sets the local address which is used to send/receive UDP packets. By default, it is
    /// "0.0.0.0:0" which means that IPv4 address and port are chosen automatically.
    ///
    /// To synchronize with IPv6 servers, you might need to set it to an IPv6 address.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::SntpClient;
    ///
    /// let mut client = SntpClient::new();
    /// client.set_bind_address("192.168.0.1:0".parse().unwrap());
    /// ```
    pub fn set_bind_address(&mut self, address: SocketAddr) {
        self.config.bind_address = address;
    }

    /// Set the configuration
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::{Config, SntpClient};
    ///
    /// let client = SntpClient::new();
    /// let config = Config::default().bind_address("192.168.0.1:0".parse().unwrap());
    /// ```
    pub fn set_config(&mut self, config: Config) {
        self.config = config
    }
}

impl Default for SntpClient {
    fn default() -> Self {
        SntpClient::new()
    }
}

/// Asynchronous client instance
///
/// Only available when async feature is enabled (which is the default)
///
/// This is the main entry point of the asynchronous API.
#[cfg(feature = "async")]
pub struct AsyncSntpClient {
    config: Config,
}

#[cfg(feature = "async")]
impl AsyncSntpClient {
    /// Creates a new instance with default configuration
    ///
    /// Only available when async feature is enabled (which is the default)
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::AsyncSntpClient;
    ///
    /// let client = AsyncSntpClient::new();
    /// ```
    pub fn new() -> AsyncSntpClient {
        AsyncSntpClient {
            config: Config::default(),
        }
    }

    /// Creates a new instance with the specified configuration
    ///
    /// Only available when async feature is enabled (which is the default)
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::{Config, AsyncSntpClient};
    ///
    /// let client = AsyncSntpClient::with_config(Config::default());
    /// ```
    pub fn with_config(config: Config) -> AsyncSntpClient {
        AsyncSntpClient { config }
    }

    /// Synchronize with the server
    ///
    /// Only available when async feature is enabled (which is the default)
    ///
    /// Sends a request to the server and processes the reply. If no reply is received within timeout,
    /// then an error is returned. If the supplied server address resolves to multiple addresses,
    /// only the first one is used.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::{AsyncSntpClient, SynchronizationResult, SynchronizationError};
    ///
    /// async fn local_time() -> Result<SynchronizationResult, SynchronizationError> {
    ///   let client = AsyncSntpClient::new();
    ///   
    ///   client.synchronize("pool.ntp.org").await
    /// }
    /// ```
    pub async fn synchronize<A: ToServerAddrs>(
        &self,
        server_address: A,
    ) -> Result<SynchronizationResult, SynchronizationError> {
        let mut receive_buffer = [0; Packet::ENCODED_LEN];

        let socket = tokio::net::UdpSocket::bind(self.config.bind_address).await?;
        socket
            .connect(server_address.to_server_addrs(SNTP_PORT))
            .await?;
        let request = Request::new();

        socket.send(&request.as_bytes()).await?;

        let result_future = timeout(self.config.timeout, socket.recv_from(&mut receive_buffer));

        let (bytes_received, server_address) = result_future.await.map_err(|_| {
            std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "Timeout while waiting for server reply",
            )
        })??;

        let reply = Reply::new(
            request,
            Packet::from_bytes(&receive_buffer[..bytes_received], server_address)?,
        );

        reply.process()
    }

    /// Sets synchronization timeout
    ///
    /// Sets the time which the client waits for a reply after the request has been sent.
    /// Default is 3 seconds.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::AsyncSntpClient;
    /// use std::time::Duration;
    ///
    /// let mut client = AsyncSntpClient::new();
    /// client.set_timeout(Duration::from_secs(10));
    /// ```
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.config.timeout = timeout;
    }

    /// Set UDP bind address
    ///
    /// Sets the local address which is used to send/receive UDP packets. By default, it is
    /// "0.0.0.0:0" which means that IPv4 address and port are chosen automatically.
    ///
    /// To synchronize with IPv6 servers, you might need to set it to an IPv6 address.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::AsyncSntpClient;
    ///
    /// let mut client = AsyncSntpClient::new();
    /// client.set_bind_address("192.168.0.1:0".parse().unwrap());
    /// ```
    pub fn set_bind_address(&mut self, address: SocketAddr) {
        self.config.bind_address = address;
    }

    /// Set the configuration
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsntp::{Config, AsyncSntpClient};
    ///
    /// let client = AsyncSntpClient::new();
    /// let config = Config::default().bind_address("192.168.0.1:0".parse().unwrap());
    /// ```
    pub fn set_config(&mut self, config: Config) {
        self.config = config
    }
}

#[cfg(feature = "async")]
impl Default for AsyncSntpClient {
    fn default() -> Self {
        AsyncSntpClient::new()
    }
}