ntp: Use mnemonic when specifying the request precision
[platform/upstream/connman.git] / src / ntp.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2012  Intel Corporation. All rights reserved.
6  *
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.
10  *
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.
15  *
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
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #define _GNU_SOURCE
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/time.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <netinet/ip.h>
36 #include <arpa/inet.h>
37
38 #include <glib.h>
39
40 #include "connman.h"
41
42 struct ntp_short {
43         uint16_t seconds;
44         uint16_t fraction;
45 } __attribute__ ((packed));
46
47 struct ntp_time {
48         uint32_t seconds;
49         uint32_t fraction;
50 } __attribute__ ((packed));
51
52 struct ntp_msg {
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));
65
66 #define OFFSET_1900_1970  2208988800UL  /* 1970 - 1900 in seconds */
67
68 #define STEPTIME_MIN_OFFSET  0.128
69
70 #define LOGTOD(a)  ((a) < 0 ? 1. / (1L << -(a)) : 1L << (int)(a))
71
72 #define NTP_FLAG_LI_SHIFT      6
73 #define NTP_FLAG_LI_MASK       0x3
74 #define NTP_FLAG_LI_NOWARNING  0x0
75 #define NTP_FLAG_LI_ADDSECOND  0x1
76 #define NTP_FLAG_LI_DELSECOND  0x2
77 #define NTP_FLAG_LI_NOTINSYNC  0x3
78
79 #define NTP_FLAG_VN_SHIFT      3
80 #define NTP_FLAG_VN_MASK       0x7
81
82 #define NTP_FLAG_MD_SHIFT      0
83 #define NTP_FLAG_MD_MASK       0x7
84 #define NTP_FLAG_MD_UNSPEC     0
85 #define NTP_FLAG_MD_ACTIVE     1
86 #define NTP_FLAG_MD_PASSIVE    2
87 #define NTP_FLAG_MD_CLIENT     3
88 #define NTP_FLAG_MD_SERVER     4
89 #define NTP_FLAG_MD_BROADCAST  5
90 #define NTP_FLAG_MD_CONTROL    6
91 #define NTP_FLAG_MD_PRIVATE    7
92
93 #define NTP_FLAGS_ENCODE(li, vn, md)  ((uint8_t)( \
94                       (((li) & NTP_FLAG_LI_MASK) << NTP_FLAG_LI_SHIFT) | \
95                       (((vn) & NTP_FLAG_VN_MASK) << NTP_FLAG_VN_SHIFT) | \
96                       (((md) & NTP_FLAG_MD_MASK) << NTP_FLAG_MD_SHIFT)))
97
98 #define NTP_FLAGS_LI_DECODE(flags)    ((uint8_t)(((flags) >> NTP_FLAG_LI_SHIFT) & NTP_FLAG_LI_MASK))
99 #define NTP_FLAGS_VN_DECODE(flags)    ((uint8_t)(((flags) >> NTP_FLAG_VN_SHIFT) & NTP_FLAG_VN_MASK))
100 #define NTP_FLAGS_MD_DECODE(flags)    ((uint8_t)(((flags) >> NTP_FLAG_MD_SHIFT) & NTP_FLAG_MD_MASK))
101
102 #define NTP_PRECISION_S    0
103 #define NTP_PRECISION_DS   -3
104 #define NTP_PRECISION_CS   -6
105 #define NTP_PRECISION_MS   -9
106 #define NTP_PRECISION_US   -19
107 #define NTP_PRECISION_NS   -29
108
109 static guint channel_watch = 0;
110 static struct timeval transmit_timeval;
111 static int transmit_fd = 0;
112
113 static char *timeserver = NULL;
114 static gint poll_id = 0;
115 static gint timeout_id = 0;
116
117 static void send_packet(int fd, const char *server)
118 {
119         struct ntp_msg msg;
120         struct sockaddr_in addr;
121         ssize_t len;
122
123         /*
124          * At some point, we could specify the actual system precision with:
125          *
126          *   clock_getres(CLOCK_REALTIME, &ts);
127          *   msg.precision = (int)log2(ts.tv_sec + (ts.tv_nsec * 1.0e-9));
128          */
129         memset(&msg, 0, sizeof(msg));
130         msg.flags = NTP_FLAGS_ENCODE(NTP_FLAG_LI_NOTINSYNC, 4, NTP_FLAG_MD_CLIENT);
131         msg.poll = 4;   // min
132         msg.poll = 10;  // max
133         msg.precision = NTP_PRECISION_S;
134
135         memset(&addr, 0, sizeof(addr));
136         addr.sin_family = AF_INET;
137         addr.sin_port = htons(123);
138         addr.sin_addr.s_addr = inet_addr(server);
139
140         gettimeofday(&transmit_timeval, NULL);
141
142         msg.xmttime.seconds = htonl(transmit_timeval.tv_sec + OFFSET_1900_1970);
143         msg.xmttime.fraction = htonl(transmit_timeval.tv_usec * 1000);
144
145         len = sendto(fd, &msg, sizeof(msg), MSG_DONTWAIT,
146                                                 &addr, sizeof(addr));
147         if (len < 0) {
148                 connman_error("Time request for server %s failed (%d/%s)",
149                         server, errno, strerror(errno));
150
151                 if (errno == ENETUNREACH)
152                         __connman_timeserver_sync_next();
153
154                 return;
155         }
156
157         if (len != sizeof(msg)) {
158                 connman_error("Broken time request for server %s", server);
159                 return;
160         }
161 }
162
163 static gboolean next_server(gpointer user_data)
164 {
165         if (timeserver != NULL) {
166                 g_free(timeserver);
167                 timeserver = NULL;
168         }
169
170         __connman_timeserver_sync_next();
171
172         return FALSE;
173 }
174
175 static gboolean next_poll(gpointer user_data)
176 {
177         if (timeserver == NULL || transmit_fd == 0)
178                 return FALSE;
179
180         send_packet(transmit_fd, timeserver);
181
182         return FALSE;
183 }
184
185 static void decode_msg(void *base, size_t len, struct timeval *tv)
186 {
187         struct ntp_msg *msg = base;
188         double org, rec, xmt, dst;
189         double delay, offset;
190         static guint transmit_delay;
191
192         if (len < sizeof(*msg)) {
193                 connman_error("Invalid response from time server");
194                 return;
195         }
196
197         if (tv == NULL) {
198                 connman_error("Invalid packet timestamp from time server");
199                 return;
200         }
201
202         DBG("flags      : 0x%02x", msg->flags);
203         DBG("stratum    : %u", msg->stratum);
204         DBG("poll       : %f seconds (%d)",
205                                 LOGTOD(msg->poll), msg->poll);
206         DBG("precision  : %f seconds (%d)",
207                                 LOGTOD(msg->precision), msg->precision);
208         DBG("root delay : %u seconds (fraction %u)",
209                         msg->rootdelay.seconds, msg->rootdelay.fraction);
210         DBG("root disp. : %u seconds (fraction %u)",
211                         msg->rootdisp.seconds, msg->rootdisp.fraction);
212         DBG("reference  : 0x%04x", msg->refid);
213
214         transmit_delay = LOGTOD(msg->poll);
215
216         if (NTP_FLAGS_LI_DECODE(msg->flags) == NTP_FLAG_LI_NOTINSYNC) {
217                 DBG("ignoring unsynchronized peer");
218                 return;
219         }
220
221         if (NTP_FLAGS_VN_DECODE(msg->flags) != 4) {
222                 DBG("unsupported version %d", NTP_FLAGS_VN_DECODE(msg->flags));
223                 return;
224         }
225
226         if (NTP_FLAGS_MD_DECODE(msg->flags) != NTP_FLAG_MD_SERVER) {
227                 DBG("unsupported mode %d", NTP_FLAGS_MD_DECODE(msg->flags));
228                 return;
229         }
230
231         org = transmit_timeval.tv_sec +
232                         (1.0e-6 * transmit_timeval.tv_usec) + OFFSET_1900_1970;
233         rec = ntohl(msg->rectime.seconds) +
234                         ((double) ntohl(msg->rectime.fraction) / UINT_MAX);
235         xmt = ntohl(msg->xmttime.seconds) +
236                         ((double) ntohl(msg->xmttime.fraction) / UINT_MAX);
237         dst = tv->tv_sec + (1.0e-6 * tv->tv_usec) + OFFSET_1900_1970;
238
239         DBG("org=%f rec=%f xmt=%f dst=%f", org, rec, xmt, dst);
240
241         offset = ((rec - org) + (xmt - dst)) / 2;
242         delay = (dst - org) - (xmt - rec);
243
244         DBG("offset=%f delay=%f", offset, delay);
245
246         /* Remove the timeout, as timeserver has responded */
247         if (timeout_id > 0)
248                 g_source_remove(timeout_id);
249
250         /*
251          * Now poll the server every transmit_delay seconds
252          * for time correction.
253          */
254         if (poll_id > 0)
255                 g_source_remove(poll_id);
256
257         DBG("Timeserver %s, next sync in %d seconds", timeserver, transmit_delay);
258
259         poll_id = g_timeout_add_seconds(transmit_delay, next_poll, NULL);
260
261         connman_info("ntp: time slew %+.6f s", offset);
262
263         if (offset < STEPTIME_MIN_OFFSET && offset > -STEPTIME_MIN_OFFSET) {
264                 struct timeval adj;
265
266                 adj.tv_sec = (long) offset;
267                 adj.tv_usec = (offset - adj.tv_sec) * 1000000;
268
269                 DBG("adjusting time");
270
271                 if (adjtime(&adj, &adj) < 0) {
272                         connman_error("Failed to adjust time");
273                         return;
274                 }
275
276                 DBG("%lu seconds, %lu msecs", adj.tv_sec, adj.tv_usec);
277         } else {
278                 struct timeval cur;
279                 double dtime;
280
281                 gettimeofday(&cur, NULL);
282                 dtime = offset + cur.tv_sec + 1.0e-6 * cur.tv_usec;
283                 cur.tv_sec = (long) dtime;
284                 cur.tv_usec = (dtime - cur.tv_sec) * 1000000;
285
286                 DBG("setting time");
287
288                 if (settimeofday(&cur, NULL) < 0) {
289                         connman_error("Failed to set time");
290                         return;
291                 }
292
293                 DBG("%lu seconds, %lu msecs", cur.tv_sec, cur.tv_usec);
294         }
295 }
296
297 static gboolean received_data(GIOChannel *channel, GIOCondition condition,
298                                                         gpointer user_data)
299 {
300         unsigned char buf[128];
301         struct msghdr msg;
302         struct iovec iov;
303         struct cmsghdr *cmsg;
304         struct timeval *tv;
305         char aux[128];
306         ssize_t len;
307         int fd;
308
309         if (condition & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
310                 connman_error("Problem with timer server channel");
311                 channel_watch = 0;
312                 return FALSE;
313         }
314
315         fd = g_io_channel_unix_get_fd(channel);
316
317         iov.iov_base = buf;
318         iov.iov_len = sizeof(buf);
319
320         memset(&msg, 0, sizeof(msg));
321         msg.msg_iov = &iov;
322         msg.msg_iovlen = 1;
323         msg.msg_control = aux;
324         msg.msg_controllen = sizeof(aux);
325
326         len = recvmsg(fd, &msg, MSG_DONTWAIT);
327         if (len < 0)
328                 return TRUE;
329
330         tv = NULL;
331
332         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
333                 if (cmsg->cmsg_level != SOL_SOCKET)
334                         continue;
335
336                 switch (cmsg->cmsg_type) {
337                 case SCM_TIMESTAMP:
338                         tv = (struct timeval *) CMSG_DATA(cmsg);
339                         break;
340                 }
341         }
342
343         decode_msg(iov.iov_base, iov.iov_len, tv);
344
345         return TRUE;
346 }
347
348 static void start_ntp(char *server)
349 {
350         GIOChannel *channel;
351         struct sockaddr_in addr;
352         int tos = IPTOS_LOWDELAY, timestamp = 1;
353
354         if (server == NULL)
355                 return;
356
357         DBG("server %s", server);
358
359         if (channel_watch > 0)
360                 goto send;
361
362         transmit_fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
363         if (transmit_fd < 0) {
364                 connman_error("Failed to open time server socket");
365                 return;
366         }
367
368         memset(&addr, 0, sizeof(addr));
369         addr.sin_family = AF_INET;
370
371         if (bind(transmit_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
372                 connman_error("Failed to bind time server socket");
373                 close(transmit_fd);
374                 return;
375         }
376
377         if (setsockopt(transmit_fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0) {
378                 connman_error("Failed to set type of service option");
379                 close(transmit_fd);
380                 return;
381         }
382
383         if (setsockopt(transmit_fd, SOL_SOCKET, SO_TIMESTAMP, &timestamp,
384                                                 sizeof(timestamp)) < 0) {
385                 connman_error("Failed to enable timestamp support");
386                 close(transmit_fd);
387                 return;
388         }
389
390         channel = g_io_channel_unix_new(transmit_fd);
391         if (channel == NULL) {
392                 close(transmit_fd);
393                 return;
394         }
395
396         g_io_channel_set_encoding(channel, NULL, NULL);
397         g_io_channel_set_buffered(channel, FALSE);
398
399         g_io_channel_set_close_on_unref(channel, TRUE);
400
401         channel_watch = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT,
402                                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
403                                 received_data, NULL, NULL);
404
405         g_io_channel_unref(channel);
406
407 send:
408         send_packet(transmit_fd, server);
409 }
410
411 int __connman_ntp_start(char *server)
412 {
413         DBG("%s", server);
414
415         if (server == NULL)
416                 return -EINVAL;
417
418         if (timeserver != NULL)
419                 g_free(timeserver);
420
421         timeserver = g_strdup(server);
422
423         start_ntp(timeserver);
424
425         /*
426          * Add a fallback timeout , preferably short, 5 sec here,
427          * to fallback on the next server.
428          */
429
430         timeout_id = g_timeout_add_seconds(5, next_server, NULL);
431
432         return 0;
433 }
434
435 void __connman_ntp_stop()
436 {
437         DBG("");
438
439         if (poll_id > 0)
440                 g_source_remove(poll_id);
441
442         if (timeout_id > 0)
443                 g_source_remove(timeout_id);
444
445         if (channel_watch > 0) {
446                 g_source_remove(channel_watch);
447                 channel_watch = 0;
448                 transmit_fd = 0;
449         }
450
451         if (timeserver != NULL) {
452                 g_free(timeserver);
453                 timeserver = NULL;
454         }
455 }