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