5 * Copyright (C) 2007-2012 Intel Corporation. All rights reserved.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <netinet/ip.h>
36 #include <arpa/inet.h>
45 } __attribute__ ((packed));
50 } __attribute__ ((packed));
53 uint8_t flags; /* Mode, version and leap indicator */
54 uint8_t stratum; /* Stratum details */
55 int8_t poll; /* Maximum interval in log2 seconds */
56 int8_t precision; /* Clock precision in log2 seconds */
57 struct ntp_short rootdelay; /* Root delay */
58 struct ntp_short rootdisp; /* Root dispersion */
59 uint32_t refid; /* Reference ID */
60 struct ntp_time reftime; /* Reference timestamp */
61 struct ntp_time orgtime; /* Origin timestamp */
62 struct ntp_time rectime; /* Receive timestamp */
63 struct ntp_time xmttime; /* Transmit timestamp */
64 } __attribute__ ((packed));
66 #define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
68 #define STEPTIME_MIN_OFFSET 0.128
70 #define LOGTOD(a) ((a) < 0 ? 1. / (1L << -(a)) : 1L << (int)(a))
72 #define NTP_SEND_TIMEOUT 2
73 #define NTP_SEND_RETRIES 3
75 #define NTP_FLAG_LI_SHIFT 6
76 #define NTP_FLAG_LI_MASK 0x3
77 #define NTP_FLAG_LI_NOWARNING 0x0
78 #define NTP_FLAG_LI_ADDSECOND 0x1
79 #define NTP_FLAG_LI_DELSECOND 0x2
80 #define NTP_FLAG_LI_NOTINSYNC 0x3
82 #define NTP_FLAG_VN_SHIFT 3
83 #define NTP_FLAG_VN_MASK 0x7
85 #define NTP_FLAG_MD_SHIFT 0
86 #define NTP_FLAG_MD_MASK 0x7
87 #define NTP_FLAG_MD_UNSPEC 0
88 #define NTP_FLAG_MD_ACTIVE 1
89 #define NTP_FLAG_MD_PASSIVE 2
90 #define NTP_FLAG_MD_CLIENT 3
91 #define NTP_FLAG_MD_SERVER 4
92 #define NTP_FLAG_MD_BROADCAST 5
93 #define NTP_FLAG_MD_CONTROL 6
94 #define NTP_FLAG_MD_PRIVATE 7
96 #define NTP_FLAGS_ENCODE(li, vn, md) ((uint8_t)( \
97 (((li) & NTP_FLAG_LI_MASK) << NTP_FLAG_LI_SHIFT) | \
98 (((vn) & NTP_FLAG_VN_MASK) << NTP_FLAG_VN_SHIFT) | \
99 (((md) & NTP_FLAG_MD_MASK) << NTP_FLAG_MD_SHIFT)))
101 #define NTP_FLAGS_LI_DECODE(flags) ((uint8_t)(((flags) >> NTP_FLAG_LI_SHIFT) & NTP_FLAG_LI_MASK))
102 #define NTP_FLAGS_VN_DECODE(flags) ((uint8_t)(((flags) >> NTP_FLAG_VN_SHIFT) & NTP_FLAG_VN_MASK))
103 #define NTP_FLAGS_MD_DECODE(flags) ((uint8_t)(((flags) >> NTP_FLAG_MD_SHIFT) & NTP_FLAG_MD_MASK))
105 #define NTP_PRECISION_S 0
106 #define NTP_PRECISION_DS -3
107 #define NTP_PRECISION_CS -6
108 #define NTP_PRECISION_MS -9
109 #define NTP_PRECISION_US -19
110 #define NTP_PRECISION_NS -29
112 static guint channel_watch = 0;
113 static struct timeval transmit_timeval;
114 static int transmit_fd = 0;
116 static char *timeserver = NULL;
117 static gint poll_id = 0;
118 static gint timeout_id = 0;
119 static guint retries = 0;
121 static void send_packet(int fd, const char *server);
123 static void next_server(void)
125 if (timeserver != NULL) {
130 __connman_timeserver_sync_next();
133 static gboolean send_timeout(gpointer user_data)
135 DBG("send timeout (retries %d)", retries);
137 if (retries++ == NTP_SEND_RETRIES)
140 send_packet(transmit_fd, timeserver);
145 static void send_packet(int fd, const char *server)
148 struct sockaddr_in addr;
152 * At some point, we could specify the actual system precision with:
154 * clock_getres(CLOCK_REALTIME, &ts);
155 * msg.precision = (int)log2(ts.tv_sec + (ts.tv_nsec * 1.0e-9));
157 memset(&msg, 0, sizeof(msg));
158 msg.flags = NTP_FLAGS_ENCODE(NTP_FLAG_LI_NOTINSYNC, 4, NTP_FLAG_MD_CLIENT);
160 msg.poll = 10; // max
161 msg.precision = NTP_PRECISION_S;
163 memset(&addr, 0, sizeof(addr));
164 addr.sin_family = AF_INET;
165 addr.sin_port = htons(123);
166 addr.sin_addr.s_addr = inet_addr(server);
168 gettimeofday(&transmit_timeval, NULL);
170 msg.xmttime.seconds = htonl(transmit_timeval.tv_sec + OFFSET_1900_1970);
171 msg.xmttime.fraction = htonl(transmit_timeval.tv_usec * 1000);
173 len = sendto(fd, &msg, sizeof(msg), MSG_DONTWAIT,
174 &addr, sizeof(addr));
176 connman_error("Time request for server %s failed (%d/%s)",
177 server, errno, strerror(errno));
179 if (errno == ENETUNREACH)
180 __connman_timeserver_sync_next();
185 if (len != sizeof(msg)) {
186 connman_error("Broken time request for server %s", server);
191 * Add a retry timeout of two seconds to retry the existing
192 * request. After a set number of retries, we'll fallback to
193 * trying another server.
196 timeout_id = g_timeout_add_seconds(NTP_SEND_TIMEOUT, send_timeout, NULL);
199 static gboolean next_poll(gpointer user_data)
201 if (timeserver == NULL || transmit_fd == 0)
204 send_packet(transmit_fd, timeserver);
209 static void reset_timeout(void)
212 g_source_remove(timeout_id);
217 static void decode_msg(void *base, size_t len, struct timeval *tv)
219 struct ntp_msg *msg = base;
220 double org, rec, xmt, dst;
221 double delay, offset;
222 static guint transmit_delay;
224 if (len < sizeof(*msg)) {
225 connman_error("Invalid response from time server");
230 connman_error("Invalid packet timestamp from time server");
234 DBG("flags : 0x%02x", msg->flags);
235 DBG("stratum : %u", msg->stratum);
236 DBG("poll : %f seconds (%d)",
237 LOGTOD(msg->poll), msg->poll);
238 DBG("precision : %f seconds (%d)",
239 LOGTOD(msg->precision), msg->precision);
240 DBG("root delay : %u seconds (fraction %u)",
241 msg->rootdelay.seconds, msg->rootdelay.fraction);
242 DBG("root disp. : %u seconds (fraction %u)",
243 msg->rootdisp.seconds, msg->rootdisp.fraction);
244 DBG("reference : 0x%04x", msg->refid);
246 transmit_delay = LOGTOD(msg->poll);
248 if (NTP_FLAGS_LI_DECODE(msg->flags) == NTP_FLAG_LI_NOTINSYNC) {
249 DBG("ignoring unsynchronized peer");
253 if (NTP_FLAGS_VN_DECODE(msg->flags) != 4) {
254 DBG("unsupported version %d", NTP_FLAGS_VN_DECODE(msg->flags));
258 if (NTP_FLAGS_MD_DECODE(msg->flags) != NTP_FLAG_MD_SERVER) {
259 DBG("unsupported mode %d", NTP_FLAGS_MD_DECODE(msg->flags));
263 org = transmit_timeval.tv_sec +
264 (1.0e-6 * transmit_timeval.tv_usec) + OFFSET_1900_1970;
265 rec = ntohl(msg->rectime.seconds) +
266 ((double) ntohl(msg->rectime.fraction) / UINT_MAX);
267 xmt = ntohl(msg->xmttime.seconds) +
268 ((double) ntohl(msg->xmttime.fraction) / UINT_MAX);
269 dst = tv->tv_sec + (1.0e-6 * tv->tv_usec) + OFFSET_1900_1970;
271 DBG("org=%f rec=%f xmt=%f dst=%f", org, rec, xmt, dst);
273 offset = ((rec - org) + (xmt - dst)) / 2;
274 delay = (dst - org) - (xmt - rec);
276 DBG("offset=%f delay=%f", offset, delay);
278 /* Remove the timeout, as timeserver has responded */
283 * Now poll the server every transmit_delay seconds
284 * for time correction.
287 g_source_remove(poll_id);
289 DBG("Timeserver %s, next sync in %d seconds", timeserver, transmit_delay);
291 poll_id = g_timeout_add_seconds(transmit_delay, next_poll, NULL);
293 connman_info("ntp: time slew %+.6f s", offset);
295 if (offset < STEPTIME_MIN_OFFSET && offset > -STEPTIME_MIN_OFFSET) {
298 adj.tv_sec = (long) offset;
299 adj.tv_usec = (offset - adj.tv_sec) * 1000000;
301 DBG("adjusting time");
303 if (adjtime(&adj, &adj) < 0) {
304 connman_error("Failed to adjust time");
308 DBG("%lu seconds, %lu msecs", adj.tv_sec, adj.tv_usec);
313 gettimeofday(&cur, NULL);
314 dtime = offset + cur.tv_sec + 1.0e-6 * cur.tv_usec;
315 cur.tv_sec = (long) dtime;
316 cur.tv_usec = (dtime - cur.tv_sec) * 1000000;
320 if (settimeofday(&cur, NULL) < 0) {
321 connman_error("Failed to set time");
325 DBG("%lu seconds, %lu msecs", cur.tv_sec, cur.tv_usec);
329 static gboolean received_data(GIOChannel *channel, GIOCondition condition,
332 unsigned char buf[128];
335 struct cmsghdr *cmsg;
341 if (condition & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
342 connman_error("Problem with timer server channel");
347 fd = g_io_channel_unix_get_fd(channel);
350 iov.iov_len = sizeof(buf);
352 memset(&msg, 0, sizeof(msg));
355 msg.msg_control = aux;
356 msg.msg_controllen = sizeof(aux);
358 len = recvmsg(fd, &msg, MSG_DONTWAIT);
364 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
365 if (cmsg->cmsg_level != SOL_SOCKET)
368 switch (cmsg->cmsg_type) {
370 tv = (struct timeval *) CMSG_DATA(cmsg);
375 decode_msg(iov.iov_base, iov.iov_len, tv);
380 static void start_ntp(char *server)
383 struct sockaddr_in addr;
384 int tos = IPTOS_LOWDELAY, timestamp = 1;
389 DBG("server %s", server);
391 if (channel_watch > 0)
394 transmit_fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
395 if (transmit_fd < 0) {
396 connman_error("Failed to open time server socket");
400 memset(&addr, 0, sizeof(addr));
401 addr.sin_family = AF_INET;
403 if (bind(transmit_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
404 connman_error("Failed to bind time server socket");
409 if (setsockopt(transmit_fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0) {
410 connman_error("Failed to set type of service option");
415 if (setsockopt(transmit_fd, SOL_SOCKET, SO_TIMESTAMP, ×tamp,
416 sizeof(timestamp)) < 0) {
417 connman_error("Failed to enable timestamp support");
422 channel = g_io_channel_unix_new(transmit_fd);
423 if (channel == NULL) {
428 g_io_channel_set_encoding(channel, NULL, NULL);
429 g_io_channel_set_buffered(channel, FALSE);
431 g_io_channel_set_close_on_unref(channel, TRUE);
433 channel_watch = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT,
434 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
435 received_data, NULL, NULL);
437 g_io_channel_unref(channel);
440 send_packet(transmit_fd, server);
443 int __connman_ntp_start(char *server)
450 if (timeserver != NULL)
453 timeserver = g_strdup(server);
455 start_ntp(timeserver);
460 void __connman_ntp_stop()
465 g_source_remove(poll_id);
469 if (channel_watch > 0) {
470 g_source_remove(channel_watch);
475 if (timeserver != NULL) {