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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! A client library to communicate with ClockBoundD.
//! # Usage
//! ClockBoundC requires ClockBoundD to be running to work. See [ClockBoundD documentation](../clock-bound-d/README.md) for installation instructions.
//!
//! For Rust programs built with Cargo, add "clock-bound-c" as a dependency in your Cargo.toml.
//!
//! For example:
//! ```text
//! [dependencies]
//! clock-bound-c = "0.1.0"
//! ```
//!
//! ## Examples
//!
//! Runnable examples exist at [examples](examples) and can be run with Cargo.
//!
//! "/run/clockboundd/clockboundd.sock" is the expected default clockboundd.sock location, but the examples can be run with a
//! different socket location if desired:
//!
//! ```text
//! cargo run --example now /run/clockboundd/clockboundd.sock
//! cargo run --example before /run/clockboundd/clockboundd.sock
//! cargo run --example after /run/clockboundd/clockboundd.sock
//! ```
//!
//! # Updating README
//!
//! This README is generated via [cargo-readme](https://crates.io/crates/cargo-readme). Updating can be done by running:
//! ```text
//! cargo readme > README.md
//! ```
mod error;

use crate::error::ClockBoundCError;
use byteorder::{ByteOrder, NetworkEndian, WriteBytesExt};
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::net::UnixDatagram;
use std::path::PathBuf;

/// The default Unix Datagram Socket file that is generated by ClockBoundD.
pub const CLOCKBOUNDD_SOCKET_ADDRESS_PATH: &str = "/run/clockboundd/clockboundd.sock";
/// The prefix of a ClockBoundC socket name. It is appended with a randomized string
/// Ex: clockboundc-G0uv7ULMLNyeLIGKSejG.sock
pub const CLOCKBOUNDC_SOCKET_NAME_PREFIX: &str = "clockboundc";

/// A structure for containing the error bounds returned from ClockBoundD. The values represent
/// the time since the Unix Epoch in nanoseconds.
pub struct Bound {
    /// System time minus the error calculated from chrony in nanoseconds since the Unix Epoch
    pub earliest: u64,
    /// System time plus the error calculated from chrony in nanoseconds since the Unix Epoch
    pub latest: u64,
}

/// A structure for holding the header of the received response.
pub struct ResponseHeader {
    /// The version of the response received from ClockBoundD.
    pub response_version: u8,
    /// The type of the response received from ClockBoundD.
    pub response_type: u8,
    /// A flag representing if Chrony is reporting as unsynchronized.
    pub unsynchronized_flag: bool,
}

/// A structure for holding the response of a now request.
pub struct ResponseNow {
    pub header: ResponseHeader,
    pub bound: Bound,
    /// The timestamp, represented as nanoseconds since the Unix Epoch, bounded against.
    pub timestamp: u64,
}

/// A structure for holding the response of a before request.
pub struct ResponseBefore {
    pub header: ResponseHeader,
    /// A boolean indicating if the requested time is before the current error bounds or not.
    pub before: bool,
}

/// A structure for holding the response of an after request.
pub struct ResponseAfter {
    pub header: ResponseHeader,
    /// A boolean indicating if the requested time is after the current error bounds or not.
    pub after: bool,
}

/// A structure for holding a client to communicate with ClockBoundD.
pub struct ClockBoundClient {
    /// A ClockBoundClient must have a socket to communicate with ClockBoundD.
    socket: UnixDatagram,
}

impl ClockBoundClient {
    /// Create a new ClockBoundClient using the default clockboundd.sock path at
    /// "/run/clockboundd/clockboundd.sock".
    ///
    /// # Examples
    ///
    /// ```
    /// use clock_bound_c::ClockBoundClient;
    /// let client = match ClockBoundClient::new(){
    ///     Ok(client) => client,
    ///     Err(e) => {
    ///         println!("Couldn't create client: {}", e);
    ///         return
    ///     }
    /// };
    pub fn new() -> Result<ClockBoundClient, ClockBoundCError> {
        ClockBoundClient::new_with_path(std::path::PathBuf::from(CLOCKBOUNDD_SOCKET_ADDRESS_PATH))
    }
    /// Create a new ClockBoundClient using a defined clockboundd.sock path.
    ///
    /// The expected default socket path is at "/run/clockboundd/clockboundd.sock", but if a
    /// different desired location has been set up this allows its usage.
    ///
    /// If using the default location at "/run/clockboundd/clockboundd.sock", use new() instead.
    ///
    /// # Arguments
    ///
    /// * `clock_bound_d_socket` - The path at which the clockboundd.sock lives.
    ///
    /// # Examples
    ///
    /// ```
    /// use clock_bound_c::ClockBoundClient;
    /// let client = match ClockBoundClient::new_with_path(std::path::PathBuf::from("/run/clockboundd/clockboundd.sock")){
    ///     Ok(client) => client,
    ///     Err(e) => {
    ///         println!("Couldn't create client: {}", e);
    ///         return
    ///     }
    /// };
    /// ```
    pub fn new_with_path(
        clock_bound_d_socket: PathBuf,
    ) -> Result<ClockBoundClient, ClockBoundCError> {
        let client_path = get_socket_path();

        // Binding will fail if the socket file already exists. However, since the socket file is
        // uniquely created based on the current time this should not fail.
        let sock = match UnixDatagram::bind(client_path.as_path()) {
            Ok(sock) => sock,
            Err(e) => return Err(ClockBoundCError::BindError(e)),
        };

        let mode = 0o666;
        let permissions = fs::Permissions::from_mode(mode);
        match fs::set_permissions(client_path, permissions) {
            Err(e) => return Err(ClockBoundCError::SetPermissionsError(e)),
            _ => {}
        }

        match sock.connect(clock_bound_d_socket.as_path()) {
            Err(e) => return Err(ClockBoundCError::ConnectError(e)),
            _ => {}
        }

        Ok(ClockBoundClient { socket: sock })
    }

    /// Returns the bounds of the current system time +/- the error calculated from chrony.
    ///
    /// # Examples
    ///
    /// ```
    /// use clock_bound_c::ClockBoundClient;
    /// let client = match ClockBoundClient::new(){
    ///     Ok(client) => client,
    ///     Err(e) => {
    ///         println!("Couldn't create client: {}", e);
    ///         return
    ///     }
    /// };
    /// let response = match client.now(){
    ///     Ok(response) => response,
    ///     Err(e) => {
    ///         println!("Couldn't complete now request: {}", e);
    ///         return
    ///     }
    /// };
    /// ```
    pub fn now(&self) -> Result<ResponseNow, ClockBoundCError> {
        let mut request: Vec<u8> = Vec::new();

        // Header
        // Version
        request.push(1);
        // Command Type
        request.push(1);
        request.push(0);
        request.push(0);

        match self.socket.send(&mut request) {
            Err(e) => return Err(ClockBoundCError::SendMessageError(e)),
            _ => {}
        }
        let mut response: [u8; 20] = [0; 20];
        match self.socket.recv(&mut response) {
            Err(e) => return Err(ClockBoundCError::ReceiveMessageError(e)),
            _ => {}
        }
        let response_version = response[0];
        let response_type = response[1];
        let unsynchronized_flag = response[2] != 0;
        let earliest = NetworkEndian::read_u64(&response[4..12]);
        let latest = NetworkEndian::read_u64(&response[12..20]);
        Ok(ResponseNow {
            header: ResponseHeader {
                response_version,
                response_type,
                unsynchronized_flag,
            },
            bound: Bound { earliest, latest },
            // Since the bounds are the system time +/- the Clock Error Bound, the system time
            // timestamp can be calculated with the below formula.
            timestamp: (latest - ((latest - earliest) / 2)),
        })
    }

    /// Returns true if the provided timestamp is before the earliest error bound.
    /// Otherwise, returns false.
    ///
    /// # Arguments
    ///
    /// * `before_time` - A timestamp, represented as nanoseconds since the Unix Epoch, that is
    /// tested against the earliest error bound.
    ///
    /// # Examples
    ///
    /// ```
    /// use clock_bound_c::ClockBoundClient;
    /// let client = match ClockBoundClient::new(){
    ///     Ok(client) => client,
    ///     Err(e) => {
    ///         println!("Couldn't create client: {}", e);
    ///         return
    ///     }
    /// };
    /// // Using 0 which equates to the Unix Epoch
    /// let response = match client.before(0){
    ///     Ok(response) => response,
    ///     Err(e) => {
    ///         println!("Couldn't complete before request: {}", e);
    ///         return
    ///     }
    /// };
    /// ```
    pub fn before(&self, before_time: u64) -> Result<ResponseBefore, ClockBoundCError> {
        let mut request: Vec<u8> = Vec::new();

        // Header
        // Version
        request.push(1);
        // Command Type
        request.push(2);
        request.push(0);
        request.push(0);
        // Body
        match request.write_u64::<NetworkEndian>(before_time) {
            Err(e) => return Err(ClockBoundCError::WriteRequestError(e)),
            _ => {}
        }
        match self.socket.send(&mut request) {
            Err(e) => return Err(ClockBoundCError::SendMessageError(e)),
            _ => {}
        }
        let mut response: [u8; 5] = [0; 5];
        match self.socket.recv(&mut response) {
            Err(e) => return Err(ClockBoundCError::ReceiveMessageError(e)),
            _ => {}
        }
        let response_version = response[0];
        let response_type = response[1];
        let unsynchronized_flag = response[2] != 0;
        let before = response[4] != 0;
        Ok(ResponseBefore {
            header: ResponseHeader {
                response_version,
                response_type,
                unsynchronized_flag,
            },
            before,
        })
    }

    /// Returns true if the provided timestamp is after the latest error bound.
    /// Otherwise, returns false.
    ///
    /// # Arguments
    ///
    /// * `after_time` - A timestamp, represented as nanoseconds since the Unix Epoch, that is
    /// tested against the latest error bound.
    ///
    /// # Examples
    ///
    /// ```
    /// use clock_bound_c::ClockBoundClient;
    /// let client = match ClockBoundClient::new(){
    ///     Ok(client) => client,
    ///     Err(e) => {
    ///         println!("Couldn't create client: {}", e);
    ///         return
    ///     }
    /// };
    /// // Using 0 which equates to the Unix Epoch
    /// let response = match client.after(0){
    ///     Ok(response) => response,
    ///     Err(e) => {
    ///         println!("Couldn't complete after request: {}", e);
    ///         return
    ///     }
    /// };
    /// ```
    pub fn after(&self, after_time: u64) -> Result<ResponseAfter, ClockBoundCError> {
        let mut request: Vec<u8> = Vec::new();
        // Header
        // Version
        request.push(1);
        // Command Type
        request.push(3);
        // Reserved
        request.push(0);
        request.push(0);

        // Body
        match request.write_u64::<NetworkEndian>(after_time) {
            Err(e) => return Err(ClockBoundCError::WriteRequestError(e)),
            _ => {}
        }
        match self.socket.send(&mut request) {
            Err(e) => return Err(ClockBoundCError::SendMessageError(e)),
            _ => {}
        }
        let mut response: [u8; 5] = [0; 5];
        match self.socket.recv(&mut response) {
            Err(e) => return Err(ClockBoundCError::ReceiveMessageError(e)),
            _ => {}
        }
        let response_version = response[0];
        let response_type = response[1];
        let unsynchronized_flag = response[2] != 0;
        let after = response[4] != 0;
        Ok(ResponseAfter {
            header: ResponseHeader {
                response_version,
                response_type,
                unsynchronized_flag,
            },
            after,
        })
    }
}

impl Drop for ClockBoundClient {
    /// Remove the client socket file when a ClockBoundClient is dropped.
    fn drop(&mut self) {
        if let Ok(addr) = self.socket.local_addr() {
            if let Some(path) = addr.as_pathname() {
                let _ = self.socket.shutdown(std::net::Shutdown::Both);
                let _ = std::fs::remove_file(path);
            }
        }
    }
}

/// Create a unique client socket file in the system's temp directory
///
/// The socket name will have clockboundc as a prefix, followed by a random string of 20
/// alphanumeric characters.
/// Ex: clockboundc-G0uv7ULMLNyeLIGKSejG.sock
fn get_socket_path() -> PathBuf {
    let dir = std::env::temp_dir();
    let mut rng = thread_rng();
    let random_str: String = (&mut rng)
        .sample_iter(Alphanumeric)
        .take(20)
        .map(char::from)
        .collect();

    let client_path_buf =
        dir.join(CLOCKBOUNDC_SOCKET_NAME_PREFIX.to_owned() + "-" + &*random_str + ".sock");
    return client_path_buf;
}