timesyncd.c revision 609e002e78e79ef2bf9d6a6ea22bda215abbbb14
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2014 Kay Sievers, Lennart Poettering
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/>.
***/
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <resolv.h>
#include <grp.h>
#include "missing.h"
#include "util.h"
#include "sparse-endian.h"
#include "log.h"
#include "socket-util.h"
#include "list.h"
#include "ratelimit.h"
#include "strv.h"
#include "conf-parser.h"
#include "sd-event.h"
#include "sd-resolve.h"
#include "sd-daemon.h"
#include "sd-network.h"
#include "event-util.h"
#include "network-util.h"
#include "capability.h"
#include "mkdir.h"
#include "timesyncd.h"
#ifndef ADJ_SETOFFSET
#endif
/* expected accuracy of time synchronization; used to adjust the poll interval */
#define NTP_ACCURACY_SEC 0.2
/*
* "A client MUST NOT under any conditions use a poll interval less
* than 15 seconds."
*/
#define NTP_POLL_INTERVAL_MIN_SEC 32
#define NTP_POLL_INTERVAL_MAX_SEC 2048
/*
* Maximum delta in seconds which the system clock is gradually adjusted
* (slew) to approach the network time. Deltas larger that this are set by
* letting the system time jump. The kernel's limit for adjtime is 0.5s.
*/
#define NTP_MAX_ADJUST 0.4
/* NTP protocol, packet header */
#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
#define RATELIMIT_BURST 10
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_;
static void manager_free(Manager *m);
static int manager_clock_watch_setup(Manager *m);
static int manager_connect(Manager *m);
static void manager_disconnect(Manager *m);
/* Let's try to make sure that the clock is always
* monotonically increasing, by saving the clock whenever we
* have a new NTP time, or when we shut down, and restoring it
* when we start again. This is particularly helpful on
* systems lacking a battery backed RTC. We also will adjust
* the time to at least the build time of systemd. */
/* First, we try to create the clock file if it doesn't exist yet */
if (fd < 0) {
if (fd < 0) {
return -errno;
}
} else {
log_error("fstat() failed: %m");
return -errno;
}
}
log_info("System clock time unset or jumped backwards, restoring.");
log_error("Failed to restore system clock: %m");
}
/* Try to fix the access mode, so that we can still
touch the file after dropping priviliges */
return 0;
}
static int save_clock(void) {
};
int r;
if (r < 0) {
log_warning("Failed to touch /var/lib/systemd/clock: %m");
return -errno;
}
return 0;
}
}
}
}
static double square(double d) {
return d * d;
}
assert(m);
sockaddr_pretty(&m->current_server_address->sockaddr.sa, m->current_server_address->socklen, true, &pretty);
log_info("Timed out waiting for reply from %s (%s).", strna(pretty), m->current_server_name->string);
return manager_connect(m);
}
static int manager_send_request(Manager *m) {
/*
* "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."
*/
};
int r;
assert(m);
/*
* 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.
*/
sockaddr_pretty(&m->current_server_address->sockaddr.sa, m->current_server_address->socklen, true, &pretty);
len = sendto(m->server_socket, &ntpmsg, sizeof(ntpmsg), MSG_DONTWAIT, &m->current_server_address->sockaddr.sa, m->current_server_address->socklen);
m->pending = true;
} else {
log_debug("Sending NTP request to %s (%s) failed: %m", strna(pretty), m->current_server_name->string);
return manager_connect(m);
}
/* re-arm timer with increasing timeout, in case the packets never arrive back */
if (m->retry_interval > 0) {
m->retry_interval *= 2;
} else
r = manager_arm_timer(m, m->retry_interval);
if (r < 0) {
return r;
}
r = sd_event_add_time(
m->event,
&m->event_timeout,
manager_timeout, m);
if (r < 0) {
return r;
}
return 0;
}
assert(m);
return manager_send_request(m);
}
int r;
assert(m);
assert(m->event_receive);
if (next == 0) {
return 0;
}
if (m->event_timer) {
if (r < 0)
return r;
}
return sd_event_add_time(
m->event,
&m->event_timer,
manager_timer, m);
}
assert(m);
/* rearm timer */
/* skip our own jumps */
if (m->jumped) {
m->jumped = false;
return 0;
}
/* resync */
log_info("System time changed. Resyncing.");
m->poll_resync = true;
return manager_send_request(m);
}
/* wake up when the system time changes underneath us */
static int manager_clock_watch_setup(Manager *m) {
struct itimerspec its = {
};
int r;
assert(m);
safe_close(m->clock_watch_fd);
if (m->clock_watch_fd < 0) {
log_error("Failed to create timerfd: %m");
return -errno;
}
if (timerfd_settime(m->clock_watch_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
log_error("Failed to set up timerfd: %m");
return -errno;
}
r = sd_event_add_io(m->event, &m->event_clock_watch, m->clock_watch_fd, EPOLLIN, manager_clock_watch, m);
if (r < 0) {
return r;
}
return 0;
}
int r;
assert(m);
/*
* 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.
*/
} else {
/* ADJ_NANO uses nanoseconds in the microseconds field */
/* the kernel expects -0.3s as {-1, 7000.000.000} */
}
m->jumped = true;
}
switch (leap_sec) {
case 1:
break;
case -1:
break;
}
save_clock();
if (r < 0)
return r;
log_debug(" status : %04i %s\n"
" time now : %li.%03llu\n"
" constant : %li\n"
" offset : %+.3f sec\n"
" freq offset : %+li (%i ppm)\n",
return 0;
}
double jitter;
double j;
assert(m);
m->packet_count++;
/* ignore initial sample */
if (m->packet_count == 1)
return false;
/* store the current data in our samples array */
idx_cur = m->samples_idx;
m->samples_idx = idx_new;
/* calculate new jitter value from the RMS differences relative to the lowest delay sample */
jitter = m->samples_jitter;
idx_min = i;
j = 0;
for (i = 0; i < ELEMENTSOF(m->samples); i++)
/* ignore samples when resyncing */
if (m->poll_resync)
return false;
/* always accept offset if we are farther off than the round-trip delay */
return false;
/* we need a few samples before looking at them */
if (m->packet_count < 4)
return false;
/* do not accept anything worse than the maximum possible error of the best sample */
return true;
/* compare the difference between the current offset to the previous offset and jitter */
}
assert(m);
if (m->poll_resync) {
m->poll_resync = false;
return;
}
/* set to minimal poll interval */
return;
}
/* increase polling interval */
m->poll_interval_usec *= 2;
return;
}
/* decrease polling interval */
m->poll_interval_usec /= 2;
return;
}
}
assert(a);
assert(b);
return false;
return false;
}
static int manager_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
};
union {
} control;
union sockaddr_union 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;
assert(m);
log_warning("Server connection returned error.");
return manager_connect(m);
}
if (len < 0) {
return 0;
log_warning("Error receiving message. Disconnecting.");
return manager_connect(m);
}
log_warning("Invalid response from server. Disconnecting.");
return manager_connect(m);
}
if (!m->current_server_name ||
!m->current_server_address ||
log_debug("Response from unknown server.");
return 0;
}
continue;
case SCM_TIMESTAMP:
break;
}
}
if (!recv_time) {
log_error("Invalid packet timestamp.");
return -EINVAL;
}
if (!m->pending) {
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("Invalid reply, returned times before epoch. Ignoring.");
return manager_connect(m);
}
log_debug("Server is not synchronized. Disconnecting.");
return manager_connect(m);
}
return manager_connect(m);
}
return manager_connect(m);
}
/* valid packet */
m->pending = false;
m->retry_interval = 0;
/* 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 round-trip 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 : %.6f sec (%d)\n"
" reference : %.4s\n"
" origin : %.3f\n"
" receive : %.3f\n"
" transmit : %.3f\n"
" dest : %.3f\n"
" offset : %+.3f sec\n"
" delay : %+.3f sec\n"
" jitter : %.3f%s\n"
m->packet_count,
m->poll_interval_usec / USEC_PER_SEC);
if (!spike) {
if (r < 0)
log_error("Failed to call clock_adjtime(): %m");
}
r = manager_arm_timer(m, m->poll_interval_usec);
if (r < 0) {
return r;
}
return 0;
}
static int manager_listen_setup(Manager *m) {
union sockaddr_union addr = {};
static const int tos = IPTOS_LOWDELAY;
static const int on = 1;
int r;
assert(m);
assert(m->server_socket < 0);
assert(!m->event_receive);
if (m->server_socket < 0)
return -errno;
if (r < 0)
return -errno;
if (r < 0)
return -errno;
return sd_event_add_io(m->event, &m->event_receive, m->server_socket, EPOLLIN, manager_receive_response, m);
}
static int manager_begin(Manager *m) {
int r;
assert(m);
sockaddr_pretty(&m->current_server_address->sockaddr.sa, m->current_server_address->socklen, true, &pretty);
sd_notifyf(false, "STATUS=Using Time Server %s (%s).", strna(pretty), m->current_server_name->string);
r = manager_listen_setup(m);
if (r < 0) {
return r;
}
r = manager_clock_watch_setup(m);
if (r < 0)
return r;
return manager_send_request(m);
}
static void server_name_flush_addresses(ServerName *n) {
ServerAddress *a;
assert(n);
while ((a = n->addresses)) {
free(a);
}
}
static void manager_flush_names(Manager *m) {
ServerName *n;
assert(m);
while ((n = m->servers)) {
free(n);
}
}
static int manager_resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) {
assert(q);
assert(m);
if (ret != 0) {
/* Try next host */
return manager_connect(m);
}
continue;
}
if (!a)
return log_oom();
last = a;
}
if (!m->current_server_name->addresses) {
/* Try next host */
return manager_connect(m);
}
return manager_begin(m);
}
assert(m);
return manager_connect(m);
}
static int manager_connect(Manager *m) {
};
int r;
assert(m);
if (!ratelimit_test(&m->ratelimit)) {
log_debug("Slowing down attempts to contact servers.");
r = sd_event_add_time(m->event, &m->event_retry, CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + RETRY_USEC, 0, manager_retry, m);
if (r < 0) {
return r;
}
return 0;
}
/* If we already are operating on some address, switch to the
* next one. */
else {
/* Hmm, we are through all addresses, let's look for the next host instead */
m->current_server_address = NULL;
else {
if (!m->servers) {
m->current_server_name = NULL;
log_debug("No server found.");
return 0;
}
m->current_server_name = m->servers;
}
/* Tell the resolver to reread /etc/resolv.conf, in
* case it changed. */
res_init();
r = sd_resolve_getaddrinfo(m->resolve, &m->resolve_query, m->current_server_name->string, "123", &hints, manager_resolve_handler, m);
if (r < 0) {
return r;
}
return 1;
}
r = manager_begin(m);
if (r < 0)
return r;
return 1;
}
ServerName *n, *tail;
assert(m);
if (!n)
return -ENOMEM;
if (!n->string) {
free(n);
return -ENOMEM;
}
return 0;
}
char *w, *state;
size_t l;
int r;
assert(m);
char t[l+1];
memcpy(t, w, l);
t[l] = 0;
r = manager_add_server(m, t);
if (r < 0)
}
return 0;
}
static void manager_disconnect(Manager *m) {
assert(m);
sd_notifyf(false, "STATUS=Idle.");
}
int r;
if (!m)
return -ENOMEM;
r = sd_event_default(&m->event);
if (r < 0)
return r;
sd_event_set_watchdog(m->event, true);
r = sd_resolve_default(&m->resolve);
if (r < 0)
return r;
if (r < 0)
return r;
r = manager_clock_watch_setup(m);
if (r < 0)
return r;
*ret = m;
m = NULL;
return 0;
}
static void manager_free(Manager *m) {
if (!m)
return;
sd_resolve_unref(m->resolve);
sd_event_unref(m->event);
free(m);
}
int config_parse_servers(
const char *unit,
const char *filename,
unsigned line,
const char *section,
unsigned section_line,
const char *lvalue,
int ltype,
const char *rvalue,
void *data,
void *userdata) {
return 0;
}
static int manager_parse_config_file(Manager *m) {
static const char fn[] = "/etc/systemd/timesyncd.conf";
int r;
assert(m);
if (!f) {
return 0;
return -errno;
}
(void*) timesyncd_gperf_lookup, false, false, m);
if (r < 0)
return r;
}
static bool network_is_online(void) {
int r;
return true;
return false;
}
void *userdata) {
int r;
assert(m);
/* check if the machine is online */
online = network_is_online();
/* check if the client is currently connected */
log_info("No network connectivity. Suspending.");
log_info("Network connectivity detected. Resuming.");
if (m->current_server_address) {
r = manager_begin(m);
if (r < 0)
return r;
} else {
r = manager_connect(m);
if (r < 0)
return r;
}
}
return 0;
}
static int manager_network_monitor_listen(Manager *m) {
if (r < 0)
return r;
if (fd < 0)
return fd;
if (events < 0)
return events;
if (r < 0)
return r;
m->network_monitor = monitor;
event_source = NULL;
return 0;
}
static const cap_value_t bits[] = {
};
int r;
/* Unfortunately we cannot leave privilege dropping to PID 1
* here, since we want to run as user but want to keep te
* CAP_SYS_TIME capability. Since file capabilities have been
* introduced this cannot be done across exec() anymore,
* unless our binary has the capability configured in the file
* system, which we want to avoid. */
log_error("Failed change group ID: %m");
return -errno;
}
log_error("Failed to drop auxiliary groups list: %m");
return -errno;
}
log_error("Failed to enable keep capabilities flag: %m");
return -errno;
}
if (r < 0) {
log_error("Failed change user ID: %m");
return -errno;
}
if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
log_error("Failed to disable keep capabilities flag: %m");
return -errno;
}
if (r < 0) {
return r;
}
d = cap_init();
if (!d)
return log_oom();
log_error("Failed to enable capabilities bits: %m");
return -errno;
}
if (cap_set_proc(d) < 0) {
log_error("Failed to increase capabilities: %m");
return -errno;
}
return 0;
}
const char *user = "systemd-timesync";
int r;
if (argc > 1) {
log_error("This program does not take arguments.");
return EXIT_FAILURE;
}
log_open();
umask(0022);
if (r < 0) {
return r;
}
if (r < 0)
goto out;
if (r < 0)
goto out;
r = manager_new(&m);
if (r < 0) {
goto out;
}
r = manager_network_monitor_listen(m);
if (r < 0) {
goto out;
}
sd_notify(false, "READY=1");
if (network_is_online()) {
r = manager_connect(m);
if (r < 0)
goto out;
}
r = sd_event_loop(m->event);
if (r < 0) {
goto out;
}
sd_event_get_exit_code(m->event, &r);
save_clock();
out:
sd_notify(false, "STATUS=Shutting down...");
return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}