/***
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 <errno.h>
#include <math.h>
#include <resolv.h>
#include <stdlib.h>
#include <time.h>
#include "sd-daemon.h"
#include "alloc-util.h"
#include "fd-util.h"
#include "fs-util.h"
#include "list.h"
#include "log.h"
#include "missing.h"
#include "network-util.h"
#include "ratelimit.h"
#include "socket-util.h"
#include "sparse-endian.h"
#include "string-util.h"
#include "strv.h"
#include "time-util.h"
#include "timesyncd-conf.h"
#include "timesyncd-manager.h"
#include "util.h"
#ifndef ADJ_SETOFFSET
#endif
/* expected accuracy of time synchronization; used to adjust the poll interval */
/*
* "A client MUST NOT under any conditions use a poll interval less
* than 15 seconds."
*/
/*
* 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.
*/
/* NTP protocol, packet header */
/* Maximum acceptable root distance in seconds. */
/* Maximum number of missed replies before selecting another source. */
/*
* "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
* in seconds relative to 0h on 1 January 1900."
*/
struct ntp_ts {
} _packed_;
struct ntp_ts_short {
} _packed_;
struct ntp_msg {
} _packed_;
static int manager_clock_watch_setup(Manager *m);
static int manager_listen_setup(Manager *m);
static void manager_listen_stop(Manager *m);
}
}
}
assert(m);
log_info("Timed out waiting for reply from %s (%s).", strna(pretty), m->current_server_name->string);
return manager_connect(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);
r = manager_listen_setup(m);
if (r < 0)
return log_warning_errno(r, "Failed to setup connection socket: %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.
*/
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_errno(errno, "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 log_error_errno(r, "Failed to rearm timer: %m");
m->missed_replies++;
if (m->missed_replies > NTP_MAX_MISSED_REPLIES) {
r = sd_event_add_time(
m->event,
&m->event_timeout,
manager_timeout, m);
if (r < 0)
return log_error_errno(r, "Failed to arm timeout timer: %m");
}
return 0;
}
assert(m);
return manager_send_request(m);
}
int r;
assert(m);
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_debug("System time changed. Resyncing.");
m->poll_resync = true;
return manager_send_request(m);
}
/* wake up when the system time changes underneath us */
};
int r;
assert(m);
safe_close(m->clock_watch_fd);
if (m->clock_watch_fd < 0)
r = sd_event_add_io(m->event, &m->event_clock_watch, m->clock_watch_fd, EPOLLIN, manager_clock_watch, m);
if (r < 0)
return log_error_errno(r, "Failed to create clock watch event source: %m");
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.
*/
} else {
/* ADJ_NANO uses nanoseconds in the microseconds field */
/* the kernel expects -0.3s as {-1, 7000.000.000} */
}
m->jumped = true;
}
/*
* An unset STA_UNSYNC will enable the kernel's 11-minute mode,
* which syncs the system time periodically to the RTC.
*
* In case the RTC runs in local time, never touch the RTC,
* we have no way to properly handle daylight saving changes and
* mobile devices moving between time zones.
*/
if (m->rtc_local_time)
switch (leap_sec) {
case 1:
break;
case -1:
break;
}
if (r < 0)
return -errno;
/* If touch fails, there isn't much we can do. Maybe it'll work next time. */
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;
}
}
static int manager_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
};
union {
} control;
.msg_iovlen = 1,
.msg_control = &control,
.msg_controllen = sizeof(control),
.msg_name = &server_addr,
.msg_namelen = sizeof(server_addr),
};
double root_distance;
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);
}
/* Too short or too long packet? */
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_TIMESTAMPNS:
break;
}
}
if (!recv_time) {
log_error("Invalid packet timestamp.");
return -EINVAL;
}
if (!m->pending) {
log_debug("Unexpected reply. Ignoring.");
return 0;
}
m->missed_replies = 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);
}
root_distance = ntp_ts_short_to_d(&ntpmsg.root_delay) / 2 + ntp_ts_short_to_d(&ntpmsg.root_dispersion);
if (root_distance > NTP_MAX_ROOT_DISTANCE) {
log_debug("Server has too large root distance. Disconnecting.");
return manager_connect(m);
}
/* valid packet */
m->pending = false;
m->retry_interval = 0;
/* Stop listening */
/* 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"
" root distance: %.6f sec\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) {
m->sync = true;
if (r < 0)
log_error_errno(r, "Failed to call clock_adjtime(): %m");
}
if (!m->good) {
m->good = true;
sd_notifyf(false, "STATUS=Synchronized to time server %s (%s).", strna(pretty), m->current_server_name->string);
}
r = manager_arm_timer(m, m->poll_interval_usec);
if (r < 0)
return log_error_errno(r, "Failed to rearm timer: %m");
return 0;
}
int r;
assert(m);
if (m->server_socket >= 0)
return 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);
}
assert(m);
}
int r;
assert(m);
m->good = false;
if (m->poll_interval_usec == 0)
sd_notifyf(false, "STATUS=Connecting to time server %s (%s).", strna(pretty), m->current_server_name->string);
r = manager_clock_watch_setup(m);
if (r < 0)
return r;
return manager_send_request(m);
}
assert(m);
if (m->current_server_name == n)
return;
m->current_server_name = n;
m->current_server_address = NULL;
if (n)
}
assert(m);
if (m->current_server_address == a)
return;
m->current_server_address = a;
/* If a is NULL, we are just clearing the address, without
* changing the name. Keep the existing name in that case. */
if (a)
m->current_server_name = a->name;
if (a) {
server_address_pretty(a, &pretty);
}
}
static int manager_resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) {
int r;
assert(q);
assert(m);
if (ret != 0) {
/* Try next host */
return manager_connect(m);
}
ServerAddress *a;
continue;
}
r = server_address_new(m->current_server_name, &a, (const union sockaddr_union*) ai->ai_addr, ai->ai_addrlen);
if (r < 0)
return log_error_errno(r, "Failed to add server address: %m");
server_address_pretty(a, &pretty);
}
if (!m->current_server_name->addresses) {
/* Try next host */
return manager_connect(m);
}
return manager_begin(m);
}
assert(m);
return manager_connect(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_boottime_or_monotonic(), now(clock_boottime_or_monotonic()) + RETRY_USEC, 0, manager_retry_connect, m);
if (r < 0)
return log_error_errno(r, "Failed to create retry timer: %m");
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 */
else {
ServerName *f;
bool restart = true;
/* Our current server name list is exhausted,
* let's find the next one to iterate. First
* we try the system list, then the link list.
* After having processed the link list we
* jump back to the system list. However, if
* both lists are empty, we change to the
* fallback list. */
f = m->system_servers;
if (!f)
f = m->link_servers;
} else {
f = m->link_servers;
if (!f)
f = m->system_servers;
else
restart = false;
}
if (!f)
f = m->fallback_servers;
if (!f) {
log_debug("No server found.");
return 0;
}
log_debug("Waiting after exhausting servers.");
r = sd_event_add_time(m->event, &m->event_retry, clock_boottime_or_monotonic(), now(clock_boottime_or_monotonic()) + m->poll_interval_usec, 0, manager_retry_connect, m);
if (r < 0)
return log_error_errno(r, "Failed to create retry timer: %m");
m->exhausted_servers = true;
/* Increase the polling interval */
m->poll_interval_usec *= 2;
return 0;
}
m->exhausted_servers = false;
manager_set_server_name(m, f);
}
/* Tell the resolver to reread /etc/resolv.conf, in
* case it changed. */
res_init();
/* Flush out any previously resolved addresses */
r = sd_resolve_getaddrinfo(m->resolve, &m->resolve_query, m->current_server_name->string, "123", &hints, manager_resolve_handler, m);
if (r < 0)
return log_error_errno(r, "Failed to create resolver: %m");
return 1;
}
r = manager_begin(m);
if (r < 0)
return r;
return 1;
}
assert(m);
sd_notifyf(false, "STATUS=Idle.");
}
assert(m);
if (t == SERVER_SYSTEM)
while (m->system_servers)
if (t == SERVER_LINK)
while (m->link_servers)
if (t == SERVER_FALLBACK)
while (m->fallback_servers)
}
if (!m)
return;
sd_resolve_unref(m->resolve);
sd_event_unref(m->event);
free(m);
}
char **i;
int r;
assert(m);
r = sd_network_get_ntp(&ntp);
if (r < 0)
goto clear;
n->marked = true;
bool found = false;
n->marked = false;
found = true;
break;
}
if (!found) {
if (r < 0)
goto clear;
}
}
if (n->marked)
server_name_free(n);
return 0;
return r;
}
static int manager_network_event_handler(sd_event_source *s, int fd, uint32_t revents, 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, watching for changes.");
log_info("Network configuration changed, trying to establish connection.");
if (m->current_server_address)
r = manager_begin(m);
else
r = manager_connect(m);
if (r < 0)
return r;
}
return 0;
}
assert(m);
if (r < 0)
return r;
if (fd < 0)
return fd;
if (events < 0)
return events;
r = sd_event_add_io(m->event, &m->network_event_source, fd, events, manager_network_event_handler, m);
if (r < 0)
return r;
return 0;
}
int r;
if (!m)
return -ENOMEM;
if (r < 0)
return r;
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_network_monitor_listen(m);
if (r < 0)
return r;
*ret = m;
m = NULL;
return 0;
}