Add __connman_timerserver_sync() to resolve a list of timeservers
[framework/connectivity/connman.git] / src / ntp.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2010  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 static guint channel_watch = 0;
73 static struct timeval transmit_timeval;
74 static int transmit_fd = 0;
75
76 static char *timeserver = NULL;
77 static gint poll_id = 0;
78
79 static void send_packet(int fd, const char *server)
80 {
81         struct ntp_msg msg;
82         struct sockaddr_in addr;
83         ssize_t len;
84
85         memset(&msg, 0, sizeof(msg));
86         msg.flags = 0x23;
87         msg.poll = 4;   // min
88         msg.poll = 10;  // max
89         msg.xmttime.seconds = random();
90         msg.xmttime.fraction = random();
91
92         memset(&addr, 0, sizeof(addr));
93         addr.sin_family = AF_INET;
94         addr.sin_port = htons(123);
95         addr.sin_addr.s_addr = inet_addr(server);
96
97         gettimeofday(&transmit_timeval, NULL);
98
99         len = sendto(fd, &msg, sizeof(msg), MSG_DONTWAIT,
100                                                 &addr, sizeof(addr));
101         if (len < 0) {
102                 connman_error("Time request for server %s failed", server);
103                 return;
104         }
105
106         if (len != sizeof(msg)) {
107                 connman_error("Broken time request for server %s", server);
108                 return;
109         }
110 }
111
112 static gboolean next_poll(gpointer user_data)
113 {
114         if (timeserver == NULL || transmit_fd == 0)
115                 return FALSE;
116
117         send_packet(transmit_fd, timeserver);
118
119         return FALSE;
120 }
121
122 static void decode_msg(void *base, size_t len, struct timeval *tv)
123 {
124         struct ntp_msg *msg = base;
125         double org, rec, xmt, dst;
126         double delay, offset;
127         static guint transmit_delay;
128
129         if (len < sizeof(*msg)) {
130                 connman_error("Invalid response from time server");
131                 return;
132         }
133
134         if (tv == NULL) {
135                 connman_error("Invalid packet timestamp from time server");
136                 return;
137         }
138
139         DBG("flags      : 0x%02x", msg->flags);
140         DBG("stratum    : %u", msg->stratum);
141         DBG("poll       : %f seconds (%d)",
142                                 LOGTOD(msg->poll), msg->poll);
143         DBG("precision  : %f seconds (%d)",
144                                 LOGTOD(msg->precision), msg->precision);
145         DBG("root delay : %u seconds (fraction %u)",
146                         msg->rootdelay.seconds, msg->rootdelay.fraction);
147         DBG("root disp. : %u seconds (fraction %u)",
148                         msg->rootdisp.seconds, msg->rootdisp.fraction);
149         DBG("reference  : 0x%04x", msg->refid);
150
151         transmit_delay = LOGTOD(msg->poll);
152
153         if (msg->flags != 0x24)
154                 return;
155
156         org = transmit_timeval.tv_sec +
157                         (1.0e-6 * transmit_timeval.tv_usec) + OFFSET_1900_1970;
158         rec = ntohl(msg->rectime.seconds) +
159                         ((double) ntohl(msg->rectime.fraction) / UINT_MAX);
160         xmt = ntohl(msg->xmttime.seconds) +
161                         ((double) ntohl(msg->xmttime.fraction) / UINT_MAX);
162         dst = tv->tv_sec + (1.0e-6 * tv->tv_usec) + OFFSET_1900_1970;
163
164         DBG("org=%f rec=%f xmt=%f dst=%f", org, rec, xmt, dst);
165
166         offset = ((rec - org) + (xmt - dst)) / 2;
167         delay = (dst - org) - (xmt - rec);
168
169         DBG("offset=%f delay=%f", offset, delay);
170
171         /* Timeserver has responded.
172          * Now poll the server every transmit_delay seconds
173          * for time correction.
174          */
175         if (poll_id > 0)
176                 g_source_remove(poll_id);
177
178         DBG("Timeserver %s, next sync in %d seconds", timeserver, transmit_delay);
179
180         poll_id = g_timeout_add_seconds(transmit_delay, next_poll, NULL);
181
182         if (offset < STEPTIME_MIN_OFFSET && offset > -STEPTIME_MIN_OFFSET) {
183                 struct timeval adj;
184
185                 adj.tv_sec = (long) offset;
186                 adj.tv_usec = (offset - adj.tv_sec) * 1000000;
187
188                 DBG("adjusting time");
189
190                 if (adjtime(&adj, &adj) < 0) {
191                         connman_error("Failed to adjust time");
192                         return;
193                 }
194
195                 DBG("%lu seconds, %lu msecs", adj.tv_sec, adj.tv_usec);
196         } else {
197                 struct timeval cur;
198                 double dtime;
199
200                 gettimeofday(&cur, NULL);
201                 dtime = offset + cur.tv_sec + 1.0e-6 * cur.tv_usec;
202                 cur.tv_sec = (long) dtime;
203                 cur.tv_usec = (dtime - cur.tv_sec) * 1000000;
204
205                 DBG("setting time");
206
207                 if (settimeofday(&cur, NULL) < 0) {
208                         connman_error("Failed to set time");
209                         return;
210                 }
211
212                 DBG("%lu seconds, %lu msecs", cur.tv_sec, cur.tv_usec);
213         }
214 }
215
216 static gboolean received_data(GIOChannel *channel, GIOCondition condition,
217                                                         gpointer user_data)
218 {
219         unsigned char buf[128];
220         struct msghdr msg;
221         struct iovec iov;
222         struct cmsghdr *cmsg;
223         struct timeval *tv;
224         char aux[128];
225         ssize_t len;
226         int fd;
227
228         if (condition & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
229                 connman_error("Problem with timer server channel");
230                 channel_watch = 0;
231                 return FALSE;
232         }
233
234         fd = g_io_channel_unix_get_fd(channel);
235
236         iov.iov_base = buf;
237         iov.iov_len = sizeof(buf);
238
239         memset(&msg, 0, sizeof(msg));
240         msg.msg_iov = &iov;
241         msg.msg_iovlen = 1;
242         msg.msg_control = aux;
243         msg.msg_controllen = sizeof(aux);
244
245         len = recvmsg(fd, &msg, MSG_DONTWAIT);
246         if (len < 0)
247                 return TRUE;
248
249         tv = NULL;
250
251         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
252                 if (cmsg->cmsg_level != SOL_SOCKET)
253                         continue;
254
255                 switch (cmsg->cmsg_type) {
256                 case SCM_TIMESTAMP:
257                         tv = (struct timeval *) CMSG_DATA(cmsg);
258                         break;
259                 }
260         }
261
262         decode_msg(iov.iov_base, iov.iov_len, tv);
263
264         return TRUE;
265 }
266
267 static void start_ntp(char *server)
268 {
269         GIOChannel *channel;
270         struct sockaddr_in addr;
271         int tos = IPTOS_LOWDELAY, timestamp = 1;
272
273         if (server == NULL)
274                 return;
275
276         DBG("server %s", server);
277
278         if (channel_watch > 0)
279                 goto send;
280
281         transmit_fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
282         if (transmit_fd < 0) {
283                 connman_error("Failed to open time server socket");
284                 return;
285         }
286
287         memset(&addr, 0, sizeof(addr));
288         addr.sin_family = AF_INET;
289
290         if (bind(transmit_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
291                 connman_error("Failed to bind time server socket");
292                 close(transmit_fd);
293                 return;
294         }
295
296         if (setsockopt(transmit_fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0) {
297                 connman_error("Failed to set type of service option");
298                 close(transmit_fd);
299                 return;
300         }
301
302         if (setsockopt(transmit_fd, SOL_SOCKET, SO_TIMESTAMP, &timestamp,
303                                                 sizeof(timestamp)) < 0) {
304                 connman_error("Failed to enable timestamp support");
305                 close(transmit_fd);
306                 return;
307         }
308
309         channel = g_io_channel_unix_new(transmit_fd);
310         if (channel == NULL) {
311                 close(transmit_fd);
312                 return;
313         }
314
315         g_io_channel_set_encoding(channel, NULL, NULL);
316         g_io_channel_set_buffered(channel, FALSE);
317
318         g_io_channel_set_close_on_unref(channel, TRUE);
319
320         channel_watch = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT,
321                                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
322                                 received_data, NULL, NULL);
323
324         g_io_channel_unref(channel);
325
326 send:
327         send_packet(transmit_fd, server);
328 }
329
330 int __connman_ntp_start(char *server)
331 {
332         DBG("%s", server);
333
334         if (server == NULL)
335                 return -EINVAL;
336
337         if (timeserver != NULL)
338                 g_free(timeserver);
339
340         timeserver = g_strdup(server);
341
342         start_ntp(timeserver);
343
344         return 0;
345 }
346
347 void __connman_ntp_stop()
348 {
349         DBG("");
350
351         if (poll_id > 0)
352                 g_source_remove(poll_id);
353
354         if (channel_watch > 0) {
355                 g_source_remove(channel_watch);
356                 channel_watch = 0;
357                 transmit_fd = 0;
358         }
359
360         if (timeserver != NULL) {
361                 g_free(timeserver);
362                 timeserver = NULL;
363         }
364 }