timedate-sntp.c revision bcdbbd7ee1b7dc6ec19261c957ed11e5e1ed1aaf
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2014 Kay Sievers
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
/*
* "Simple Network Time Protocol Version 4 (SNTPv4) is a subset of the
* Network Time Protocol (NTP) used to synchronize computer clocks in
* the Internet. SNTPv4 can be used when the ultimate performance of
* a full NTP implementation based on RFC 1305 is neither needed nor
* justified."
*
* "Unlike most NTP clients, SNTP clients normally operate with only a
* single server at a time."
*
*/
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include "util.h"
#include "sparse-endian.h"
#include "log.h"
#include "sd-event.h"
#include "timedate-sntp.h"
#ifndef ADJ_SETOFFSET
#endif
/* Maximum delta in seconds which the system clock is gradually adjusted
* to approach the network time. Deltas larger that this are set by letting
* the system time jump. The maximum for adjtime is 500ms.
*/
#define NTP_MAX_ADJUST 0.2
/*
* "Define the required accuracy of the system clock, then calculate the
* maximum timeout. Use the longest maximum timeout possible given the system
* constraints to minimize time server aggregate load."
*
* "A client MUST NOT under any conditions use a poll interval less
* than 15 seconds."
*/
#define NTP_POLL_INTERVAL_MIN_SEC 16
#define NTP_POLL_INTERVAL_MAX_SEC 2048
#define NTP_POLL_ACCURACY_SEC 0.1
#define NTP_LEAP_PLUSSEC 1
#define NTP_LEAP_MINUSSEC 2
#define NTP_LEAP_NOTINSYNC 3
#define NTP_MODE_CLIENT 3
#define NTP_MODE_SERVER 4
#define NTP_FIELD_MODE(f) ((f) & 7)
/*
* "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
* in seconds relative to 0h on 1 January 1900."
*/
#define OFFSET_1900_1970 2208988800UL
struct ntp_ts {
} _packed_;
struct ntp_ts_short {
} _packed_;
struct ntp_msg {
struct ntp_ts_short root_delay;
struct ntp_ts_short root_dispersion;
char refid[4];
struct ntp_ts reference_time;
struct ntp_ts origin_time;
struct ntp_ts trans_time;
} _packed_;
struct SNTPContext {
char *server;
struct sockaddr_in server_addr;
int server_socket;
struct timespec trans_time_mon;
struct timespec trans_time;
bool pending;
struct {
double offset;
double delay;
} samples[8];
unsigned int samples_idx;
double samples_jitter;
};
static int log2i(int a) {
int exp = 0;
assert(a > 0);
while (a > 0) {
a >>= 1;
exp++;
}
return exp;
}
static double log2d(int a) {
if (a < 0)
return 1.0 / (1UL << - a);
return 1UL << a;
}
}
}
}
/* the kernel expects -0.3s as {-1, 7000.000} */
}
}
static double square(double d) {
return d * d;
}
struct sockaddr_in addr = {};
int r;
/*
* "The client initializes the NTP message header, sends the request
* to the server, and strips the time of day from the Transmit
* Timestamp field of the reply. For this purpose, all the NTP
* header fields are set to 0, except the Mode, VN, and optional
* Transmit Timestamp fields."
*/
/*
* Set transmit timestamp, remember it; the server will send that back
* as the origin timestamp and we have an indication that this is the
* matching answer to our request.
*
* The actual value does not matter, We do not care about the correct
* NTP UINT_MAX fraction, we just pass the plain nanosecond value.
*/
if (len < 0) {
return -errno;
}
/* re-arm timer for next poll interval, in case the packet never arrives back */
r = sntp_arm_timer(sntp);
if (r < 0)
return r;
return 0;
}
return 0;
}
sd_event *e;
int r;
if (sntp->poll_interval <= 0) {
return 0;
}
if (sntp->event_timer) {
if (r < 0)
return r;
}
r = sd_event_add_monotonic(e, &sntp->event_timer, now(CLOCK_MONOTONIC) + sntp->poll_interval, 0, sntp_timer, sntp);
if (r < 0)
return r;
return 0;
}
int r;
/*
* For small deltas, tell the kernel to gradually adjust the system
* clock to the NTP time, larger deltas are just directly set.
*
* Clear STA_UNSYNC, it will enable the kernel's 11-minute mode, which
* syncs the system time periodically to the hardware clock.
*/
int constant;
} else {
}
switch (leap_sec) {
case 1:
break;
case -1:
break;
}
if (r < 0)
return r;
log_debug(" status : %04i %s\n"
" time now : %li.%06li\n"
" constant : %li\n"
" offset : %+f sec\n"
" freq offset : %+li (%+.3f ppm)\n",
return 0;
}
double jitter;
bool spike;
/* store the current data in our samples array */
sntp->packet_count++;
/*
* Spike detection; compare the difference between the
* current offset to the previous offset and jitter.
*/
spike = sntp->packet_count > 2 && fabs(offset - sntp->samples[idx_cur].offset) > sntp->samples_jitter * 3;
/* calculate new jitter value from the RMS differences relative to the lowest delay sample */
idx_min = i;
return spike;
}
double delta;
if (spike) {
return;
}
/* set to minimal poll interval */
if (delta > NTP_POLL_ACCURACY_SEC) {
return;
}
/* increase polling interval */
return;
}
/* decrease polling interval */
return;
}
}
static int sntp_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
};
union {
} control;
struct sockaddr_in server_addr;
.msg_iovlen = 1,
.msg_control = &control,
.msg_controllen = sizeof(control),
.msg_name = &server_addr,
.msg_namelen = sizeof(server_addr),
};
bool spike;
int leap_sec;
int r;
log_debug("Server connection returned error, closing.");
return -ENOTCONN;
}
if (len < 0) {
log_debug("Error receiving message, disconnecting");
return -EINVAL;
}
log_debug("Invalid response from server, disconnecting");
return -EINVAL;
}
log_debug("Response from unknown server, disconnecting");
return -EINVAL;
}
continue;
case SCM_TIMESTAMP:
break;
}
}
if (!recv_time) {
log_debug("Invalid packet timestamp, disconnecting");
return -EINVAL;
}
log_debug("Unexpected reply, ignoring");
return 0;
}
/* check our "time cookie" (we just stored nanoseconds in the fraction field) */
log_debug("Invalid reply, not our transmit time, ignoring");
return 0;
}
log_debug("Server is not synchronized, disconnecting");
return -EINVAL;
}
return -EINVAL;
}
return -EINVAL;
}
/* announce leap seconds */
leap_sec = 1;
leap_sec = -1;
else
leap_sec = 0;
/*
* "Timestamp Name ID When Generated
* ------------------------------------------------------------
* Originate Timestamp T1 time request sent by client
* Receive Timestamp T2 time request received by server
* Transmit Timestamp T3 time reply sent by server
* Destination Timestamp T4 time reply received by client
*
* The roundtrip delay d and system clock offset t are defined as:
* d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
*/
log_debug("NTP response:\n"
" leap : %u\n"
" version : %u\n"
" mode : %u\n"
" stratum : %u\n"
" precision : %f sec (%d)\n"
" reference : %.4s\n"
" origin : %f\n"
" recv : %f\n"
" transmit : %f\n"
" dest : %f\n"
" offset : %+f sec\n"
" delay : %+f sec\n"
" packet count : %llu\n"
" poll interval: %llu\n",
(unsigned long long)sntp->packet_count,
if (!spike) {
if (r < 0)
log_error("Failed to call clock_adjtime(): %m");
}
r = sntp_arm_timer(sntp);
if (r < 0)
return r;
return 0;
}
_cleanup_free_ char *s = NULL;
if (!s)
return -ENOMEM;
s = NULL;
return sntp_send_request(sntp);
}
return;
if (sntp->server_socket > 0)
}
struct sockaddr_in addr;
const int on = 1;
const int tos = IPTOS_LOWDELAY;
int r;
if (!c)
return -ENOMEM;
if (fd < 0)
return -errno;
if (r < 0)
return -errno;
if (r < 0)
return -errno;
if (r < 0)
return -errno;
if (r < 0)
return r;
c->server_socket = fd;
fd = -1;
*sntp = c;
c = NULL;
return 0;
}
return NULL;
}