1 /**
2 * @file
3 * SNTP client module
4 */
5
6 /*
7 * Copyright (c) 2007-2009 Frédéric Bernon, Simon Goldschmidt
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without modification,
11 * are permitted provided that the following conditions are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright notice,
14 * this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
18 * 3. The name of the author may not be used to endorse or promote products
19 * derived from this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
22 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
24 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
26 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
29 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
30 * OF SUCH DAMAGE.
31 *
32 * This file is part of the lwIP TCP/IP stack.
33 *
34 * Author: Frédéric Bernon, Simon Goldschmidt
35 */
36
37
38 /**
39 * @defgroup sntp SNTP
40 * @ingroup apps
41 *
42 * This is simple "SNTP" client for the lwIP raw API.
43 * It is a minimal implementation of SNTPv4 as specified in RFC 4330.
44 *
45 * For a list of some public NTP servers, see this link:
46 * http://support.ntp.org/bin/view/Servers/NTPPoolServers
47 *
48 * @todo:
49 * - complete SNTP_CHECK_RESPONSE checks 3 and 4
50 */
51
52 #include "lwip/opt.h"
53
54 #include "lwip/sntp.h"
55 #include "lwip/sys.h"
56 #include "lwip/timeouts.h"
57 #include "lwip/udp.h"
58 #include "lwip/dns.h"
59 #include "lwip/ip_addr.h"
60 #include "lwip/pbuf.h"
61 #include "lwip/dhcp.h"
62 #include "lwip/tcpip.h"
63
64 #include <string.h>
65 #include <time.h>
66
67 #if LWIP_SNTP
68
69 #ifndef SNTP_SUPPRESS_DELAY_CHECK
70 #if SNTP_UPDATE_DELAY < 15000
71 #error "SNTPv4 RFC 4330 enforces a minimum update time of 15 seconds (define SNTP_SUPPRESS_DELAY_CHECK to disable this error)!"
72 #endif
73 #endif
74
75 /* the various debug levels for this file */
76 #define SNTP_DEBUG_TRACE (SNTP_DEBUG | LWIP_DBG_TRACE)
77 #define SNTP_DEBUG_STATE (SNTP_DEBUG | LWIP_DBG_STATE)
78 #define SNTP_DEBUG_WARN (SNTP_DEBUG | LWIP_DBG_LEVEL_WARNING)
79 #define SNTP_DEBUG_WARN_STATE (SNTP_DEBUG | LWIP_DBG_LEVEL_WARNING | LWIP_DBG_STATE)
80 #define SNTP_DEBUG_SERIOUS (SNTP_DEBUG | LWIP_DBG_LEVEL_SERIOUS)
81
82 #define SNTP_ERR_KOD 1
83
84 /* SNTP protocol defines */
85 #define SNTP_MSG_LEN 48
86
87 #define SNTP_OFFSET_LI_VN_MODE 0
88 #define SNTP_LI_MASK 0xC0
89 #define SNTP_LI_NO_WARNING (0x00 << 6)
90 #define SNTP_LI_LAST_MINUTE_61_SEC (0x01 << 6)
91 #define SNTP_LI_LAST_MINUTE_59_SEC (0x02 << 6)
92 #define SNTP_LI_ALARM_CONDITION (0x03 << 6) /* (clock not synchronized) */
93
94 #define SNTP_VERSION_MASK 0x38
95 #define SNTP_VERSION (4/* NTP Version 4*/<<3)
96
97 #define SNTP_MODE_MASK 0x07
98 #define SNTP_MODE_CLIENT 0x03
99 #define SNTP_MODE_SERVER 0x04
100 #define SNTP_MODE_BROADCAST 0x05
101
102 #define SNTP_OFFSET_STRATUM 1
103 #define SNTP_STRATUM_KOD 0x00
104
105 #define SNTP_OFFSET_ORIGINATE_TIME 24
106 #define SNTP_OFFSET_RECEIVE_TIME 32
107 #define SNTP_OFFSET_TRANSMIT_TIME 40
108
109 /* Number of seconds between 1970 and Feb 7, 2036 06:28:16 UTC (epoch 1) */
110 #define DIFF_SEC_1970_2036 ((u32_t)2085978496L)
111
112 /** Convert NTP timestamp fraction to microseconds.
113 */
114 #ifndef SNTP_FRAC_TO_US
115 # if LWIP_HAVE_INT64
116 # define SNTP_FRAC_TO_US(f) ((u32_t)(((u64_t)(f) * 1000000UL) >> 32))
117 # else
118 # define SNTP_FRAC_TO_US(f) ((u32_t)(f) / 4295)
119 # endif
120 #endif /* !SNTP_FRAC_TO_US */
121
122 /* Configure behaviour depending on native, microsecond or second precision.
123 * Treat NTP timestamps as signed two's-complement integers. This way,
124 * timestamps that have the MSB set simply become negative offsets from
125 * the epoch (Feb 7, 2036 06:28:16 UTC). Representable dates range from
126 * 1968 to 2104.
127 */
128 #ifndef SNTP_SET_SYSTEM_TIME_NTP
129 # ifdef SNTP_SET_SYSTEM_TIME_US
130 # define SNTP_SET_SYSTEM_TIME_NTP(s, f) \
131 SNTP_SET_SYSTEM_TIME_US((u32_t)((s) + DIFF_SEC_1970_2036), SNTP_FRAC_TO_US(f))
132 # else
133 # define SNTP_SET_SYSTEM_TIME_NTP(s, f) \
134 SNTP_SET_SYSTEM_TIME((u32_t)((s) + DIFF_SEC_1970_2036))
135 # endif
136 #endif /* !SNTP_SET_SYSTEM_TIME_NTP */
137
138 /* Get the system time either natively as NTP timestamp or convert from
139 * Unix time in seconds and microseconds. Take care to avoid overflow if the
140 * microsecond value is at the maximum of 999999. Also add 0.5 us fudge to
141 * avoid special values like 0, and to mask round-off errors that would
142 * otherwise break round-trip conversion identity.
143 */
144 #ifndef SNTP_GET_SYSTEM_TIME_NTP
145 # define SNTP_GET_SYSTEM_TIME_NTP(s, f) do { \
146 u32_t sec_, usec_; \
147 SNTP_GET_SYSTEM_TIME(sec_, usec_); \
148 (s) = (s32_t)(sec_ - DIFF_SEC_1970_2036); \
149 if (usec_ != 0) { \
150 (f) = usec_ * 4295 - ((usec_ * 2143) >> 16) + 2147; \
151 } else { \
152 (f) = 0; \
153 } \
154 } while (0)
155 #endif /* !SNTP_GET_SYSTEM_TIME_NTP */
156
157 /* Start offset of the timestamps to extract from the SNTP packet */
158 #define SNTP_OFFSET_TIMESTAMPS \
159 (SNTP_OFFSET_TRANSMIT_TIME + 8 - sizeof(struct sntp_timestamps))
160
161 /* Round-trip delay arithmetic helpers */
162 #if SNTP_COMP_ROUNDTRIP
163 # if !LWIP_HAVE_INT64
164 # error "SNTP round-trip delay compensation requires 64-bit arithmetic"
165 # endif
166 # define SNTP_SEC_FRAC_TO_S64(s, f) \
167 ((s64_t)(((u64_t)(s) << 32) | (u32_t)(f)))
168 # define SNTP_TIMESTAMP_TO_S64(t) \
169 SNTP_SEC_FRAC_TO_S64(lwip_ntohl((t).sec), lwip_ntohl((t).frac))
170 #endif /* SNTP_COMP_ROUNDTRIP */
171
172 /**
173 * 64-bit NTP timestamp, in network byte order.
174 */
175 struct sntp_time {
176 u32_t sec;
177 u32_t frac;
178 };
179
180 /**
181 * Timestamps to be extracted from the NTP header.
182 */
183 struct sntp_timestamps {
184 #if SNTP_COMP_ROUNDTRIP || SNTP_CHECK_RESPONSE >= 2
185 struct sntp_time orig;
186 struct sntp_time recv;
187 #endif
188 struct sntp_time xmit;
189 };
190
191 struct api_sntp_msg {
192 int server_num;
193 char **sntp_server;
194 struct timeval *sntp_time;
195 sys_sem_t cb_completed;
196 err_t err;
197 };
198
199 /**
200 * SNTP packet format (without optional fields)
201 * Timestamps are coded as 64 bits:
202 * - signed 32 bits seconds since Feb 07, 2036, 06:28:16 UTC (epoch 1)
203 * - unsigned 32 bits seconds fraction (2^32 = 1 second)
204 */
205 #ifdef PACK_STRUCT_USE_INCLUDES
206 # include "arch/bpstruct.h"
207 #endif
208 PACK_STRUCT_BEGIN
209 struct sntp_msg {
210 PACK_STRUCT_FLD_8(u8_t li_vn_mode);
211 PACK_STRUCT_FLD_8(u8_t stratum);
212 PACK_STRUCT_FLD_8(u8_t poll);
213 PACK_STRUCT_FLD_8(u8_t precision);
214 PACK_STRUCT_FIELD(u32_t root_delay);
215 PACK_STRUCT_FIELD(u32_t root_dispersion);
216 PACK_STRUCT_FIELD(u32_t reference_identifier);
217 PACK_STRUCT_FIELD(u32_t reference_timestamp[2]);
218 PACK_STRUCT_FIELD(u32_t originate_timestamp[2]);
219 PACK_STRUCT_FIELD(u32_t receive_timestamp[2]);
220 PACK_STRUCT_FIELD(u32_t transmit_timestamp[2]);
221 } PACK_STRUCT_STRUCT;
222 PACK_STRUCT_END
223 #ifdef PACK_STRUCT_USE_INCLUDES
224 # include "arch/epstruct.h"
225 #endif
226
227 /* function prototypes */
228 static void sntp_request(void *arg);
229
230 /** The operating mode */
231 static u8_t sntp_opmode;
232
233 /** The UDP pcb used by the SNTP client */
234 static struct udp_pcb *sntp_pcb;
235 /** Names/Addresses of servers */
236 struct sntp_server {
237 #if SNTP_SERVER_DNS
238 const char *name;
239 #endif /* SNTP_SERVER_DNS */
240 ip_addr_t addr;
241 #if SNTP_MONITOR_SERVER_REACHABILITY
242 /** Reachability shift register as described in RFC 5905 */
243 u8_t reachability;
244 #endif /* SNTP_MONITOR_SERVER_REACHABILITY */
245 };
246 static struct sntp_server sntp_servers[SNTP_MAX_SERVERS];
247
248 #if SNTP_GET_SERVERS_FROM_DHCP || SNTP_GET_SERVERS_FROM_DHCPV6
249 static u8_t sntp_set_servers_from_dhcp;
250 #endif /* SNTP_GET_SERVERS_FROM_DHCP || SNTP_GET_SERVERS_FROM_DHCPV6 */
251 /** The currently used server (initialized to 0) */
252 static u8_t sntp_current_server;
253 static u8_t sntp_kod_found;
254 static int sntp_num_servers;
255
256 static struct api_sntp_msg smsg;
257
258 #if SNTP_RETRY_TIMEOUT_EXP
259 #define SNTP_RESET_RETRY_TIMEOUT() sntp_retry_timeout = SNTP_RETRY_TIMEOUT
260
261 static u8_t sntp_retry_count;
262
263 /** Retry time, initialized with SNTP_RETRY_TIMEOUT and doubled with each retry. */
264 static u32_t sntp_retry_timeout;
265 #else /* SNTP_RETRY_TIMEOUT_EXP */
266 #define SNTP_RESET_RETRY_TIMEOUT()
267 #define sntp_retry_timeout SNTP_RETRY_TIMEOUT
268 #endif /* SNTP_RETRY_TIMEOUT_EXP */
269
270 #if SNTP_CHECK_RESPONSE >= 1
271 /** Saves the last server address to compare with response */
272 static ip_addr_t sntp_last_server_address;
273 #endif /* SNTP_CHECK_RESPONSE >= 1 */
274
275 #if SNTP_CHECK_RESPONSE >= 2
276 /** Saves the last timestamp sent (which is sent back by the server)
277 * to compare against in response. Stored in network byte order. */
278 static struct sntp_time sntp_last_timestamp_sent;
279 #endif /* SNTP_CHECK_RESPONSE >= 2 */
280
281 #if defined(LWIP_DEBUG) && !defined(sntp_format_time)
282 /* Debug print helper. */
283 static const char *
sntp_format_time(s32_t sec)284 sntp_format_time(s32_t sec)
285 {
286 time_t ut;
287 ut = (u32_t)((u32_t)sec + DIFF_SEC_1970_2036);
288 return ctime(&ut);
289 }
290 #endif /* LWIP_DEBUG && !sntp_format_time */
291
292 /**
293 * SNTP processing of received timestamp
294 */
295 static void
sntp_process(const struct sntp_timestamps * timestamps)296 sntp_process(const struct sntp_timestamps *timestamps)
297 {
298 s32_t sec;
299 u32_t frac;
300
301 sec = (s32_t)lwip_ntohl(timestamps->xmit.sec);
302 frac = lwip_ntohl(timestamps->xmit.frac);
303
304 #if SNTP_COMP_ROUNDTRIP
305 # if SNTP_CHECK_RESPONSE >= 2
306 if (timestamps->recv.sec != 0 || timestamps->recv.frac != 0)
307 # endif
308 {
309 s32_t dest_sec;
310 u32_t dest_frac;
311 u32_t step_sec;
312
313 /* Get the destination time stamp, i.e. the current system time */
314 SNTP_GET_SYSTEM_TIME_NTP(dest_sec, dest_frac);
315
316 step_sec = (dest_sec < sec) ? ((u32_t)sec - (u32_t)dest_sec)
317 : ((u32_t)dest_sec - (u32_t)sec);
318 /* In order to avoid overflows, skip the compensation if the clock step
319 * is larger than about 34 years. */
320 if ((step_sec >> 30) == 0) {
321 s64_t t1, t2, t3, t4;
322
323 t4 = SNTP_SEC_FRAC_TO_S64(dest_sec, dest_frac);
324 t3 = SNTP_SEC_FRAC_TO_S64(sec, frac);
325 t1 = SNTP_TIMESTAMP_TO_S64(timestamps->orig);
326 t2 = SNTP_TIMESTAMP_TO_S64(timestamps->recv);
327 /* Clock offset calculation according to RFC 4330 */
328 t4 += ((t2 - t1) + (t3 - t4)) / 2;
329
330 sec = (s32_t)((u64_t)t4 >> 32);
331 frac = (u32_t)((u64_t)t4);
332 }
333 }
334 #endif /* SNTP_COMP_ROUNDTRIP */
335
336 SNTP_SET_SYSTEM_TIME_NTP(sec, frac);
337 if (smsg.sntp_time != NULL) {
338 smsg.sntp_time->tv_sec = (long)sec;
339 smsg.sntp_time->tv_usec = (long)frac;
340 }
341 LWIP_UNUSED_ARG(frac); /* might be unused if only seconds are set */
342 LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_process: %s, %" U32_F " us\n",
343 sntp_format_time(sec), SNTP_FRAC_TO_US(frac)));
344 }
345
346 /**
347 * Initialize request struct to be sent to server.
348 */
349 static void
sntp_initialize_request(struct sntp_msg * req)350 sntp_initialize_request(struct sntp_msg *req)
351 {
352 memset(req, 0, SNTP_MSG_LEN);
353 req->li_vn_mode = SNTP_LI_NO_WARNING | SNTP_VERSION | SNTP_MODE_CLIENT;
354
355 #if SNTP_CHECK_RESPONSE >= 2 || SNTP_COMP_ROUNDTRIP
356 {
357 s32_t secs;
358 u32_t sec, frac;
359 /* Get the transmit timestamp */
360 SNTP_GET_SYSTEM_TIME_NTP(secs, frac);
361 sec = lwip_htonl((u32_t)secs);
362 frac = lwip_htonl(frac);
363
364 # if SNTP_CHECK_RESPONSE >= 2
365 sntp_last_timestamp_sent.sec = sec;
366 sntp_last_timestamp_sent.frac = frac;
367 # endif
368 req->transmit_timestamp[0] = sec;
369 req->transmit_timestamp[1] = frac;
370 }
371 #endif /* SNTP_CHECK_RESPONSE >= 2 || SNTP_COMP_ROUNDTRIP */
372 }
373
374 /**
375 * Retry: send a new request (and increase retry timeout).
376 *
377 * @param arg is unused (only necessary to conform to sys_timeout)
378 */
379 static void
sntp_retry(void * arg)380 sntp_retry(void *arg)
381 {
382 LWIP_UNUSED_ARG(arg);
383
384 LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_retry: Next request will be sent in %"U32_F" ms\n",
385 sntp_retry_timeout));
386
387 /* set up a timer to send a retry and increase the retry delay */
388 sys_untimeout(sntp_request, NULL);
389 if (sys_timeout(sntp_retry_timeout, sntp_request, NULL) != ERR_OK) {
390 smsg.err = ERR_MEM;
391 sys_sem_signal(&smsg.cb_completed);
392 return;
393 }
394
395 #if SNTP_RETRY_TIMEOUT_EXP
396 {
397 u32_t new_retry_timeout;
398 /* increase the timeout for next retry */
399 new_retry_timeout = sntp_retry_timeout << 1;
400 /* limit to maximum timeout and prevent overflow */
401 if ((new_retry_timeout <= SNTP_RETRY_TIMEOUT_MAX) &&
402 (new_retry_timeout > sntp_retry_timeout)) {
403 sntp_retry_timeout = new_retry_timeout;
404 } else {
405 sntp_retry_timeout = SNTP_RETRY_TIMEOUT_MAX;
406 }
407 }
408 #endif /* SNTP_RETRY_TIMEOUT_EXP */
409 }
410
411 /**
412 * If Kiss-of-Death is received (or another packet parsing error),
413 * try the next server or retry the current server and increase the retry
414 * timeout if only one server is available.
415 * (implicitly, SNTP_MAX_SERVERS > 1)
416 *
417 * @param arg is unused (only necessary to conform to sys_timeout)
418 */
419 static void
sntp_try_next_server(void * arg)420 sntp_try_next_server(void *arg)
421 {
422 LWIP_UNUSED_ARG(arg);
423
424 /* sntp_pcb has been released, that implies the response came too late... just ignore it */
425 if (sntp_pcb == NULL) {
426 return;
427 }
428
429 sntp_current_server++;
430 if (sntp_current_server >= sntp_num_servers) {
431 /* Stop sntp module */
432 sntp_stop();
433 if (sntp_kod_found) {
434 smsg.err = ERR_ACCESS;
435 } else {
436 smsg.err = ERR_TIMEOUT;
437 }
438 sys_sem_signal(&smsg.cb_completed);
439 return;
440 }
441
442 /* reset KoD found flag for another SNTP server */
443 sntp_kod_found = 0;
444
445 LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_try_next_server: Sending request to server %"U16_F"\n",
446 (u16_t)sntp_current_server));
447 /* new server: reset retry timeout */
448 SNTP_RESET_RETRY_TIMEOUT();
449 /* instantly send a request to the next server */
450 sntp_request(NULL);
451 }
452
453 /** UDP recv callback for the sntp pcb */
454 static void
sntp_recv(void * arg,struct udp_pcb * pcb,struct pbuf * p,const ip_addr_t * addr,u16_t port)455 sntp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
456 {
457 struct sntp_timestamps timestamps;
458 u8_t mode;
459 u8_t stratum;
460 err_t err;
461
462 LWIP_UNUSED_ARG(arg);
463 LWIP_UNUSED_ARG(pcb);
464
465 /* packet received: stop retry timeout */
466 sys_untimeout(sntp_try_next_server, NULL);
467 sys_untimeout(sntp_request, NULL);
468
469 err = ERR_ARG;
470 #if SNTP_CHECK_RESPONSE >= 1
471 /* check server address and port */
472 if (((sntp_opmode != SNTP_OPMODE_POLL) || ip_addr_cmp(addr, &sntp_last_server_address)) &&
473 (port == SNTP_PORT))
474 #else /* SNTP_CHECK_RESPONSE >= 1 */
475 LWIP_UNUSED_ARG(addr);
476 LWIP_UNUSED_ARG(port);
477 #endif /* SNTP_CHECK_RESPONSE >= 1 */
478 {
479 /* process the response */
480 if (p->tot_len == SNTP_MSG_LEN) {
481 mode = pbuf_get_at(p, SNTP_OFFSET_LI_VN_MODE) & SNTP_MODE_MASK;
482 /* if this is a SNTP response... */
483 if (((sntp_opmode == SNTP_OPMODE_POLL) && (mode == SNTP_MODE_SERVER)) ||
484 ((sntp_opmode == SNTP_OPMODE_LISTENONLY) && (mode == SNTP_MODE_BROADCAST))) {
485 stratum = pbuf_get_at(p, SNTP_OFFSET_STRATUM);
486
487 if (stratum == SNTP_STRATUM_KOD) {
488 /* Kiss-of-death packet. Use another server or increase UPDATE_DELAY. */
489 err = SNTP_ERR_KOD;
490 sntp_kod_found = 1;
491 LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_recv: Received Kiss-of-Death\n"));
492 } else {
493 pbuf_copy_partial(p, ×tamps, sizeof(timestamps), SNTP_OFFSET_TIMESTAMPS);
494 #if SNTP_CHECK_RESPONSE >= 2
495 /* check originate_timetamp against sntp_last_timestamp_sent */
496 if (timestamps.orig.sec != sntp_last_timestamp_sent.sec ||
497 timestamps.orig.frac != sntp_last_timestamp_sent.frac) {
498 LWIP_DEBUGF(SNTP_DEBUG_WARN,
499 ("sntp_recv: Invalid originate timestamp in response\n"));
500 } else
501 #endif /* SNTP_CHECK_RESPONSE >= 2 */
502 /* @todo: add code for SNTP_CHECK_RESPONSE >= 3 and >= 4 here */
503 {
504 /* correct answer */
505 err = ERR_OK;
506 }
507 }
508 } else {
509 LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid mode in response: %"U16_F"\n", (u16_t)mode));
510 /* wait for correct response */
511 err = ERR_TIMEOUT;
512 }
513 } else {
514 LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid packet length: %"U16_F"\n", p->tot_len));
515 }
516 }
517 #if SNTP_CHECK_RESPONSE >= 1
518 else {
519 /* packet from wrong remote address or port, wait for correct response */
520 err = ERR_TIMEOUT;
521 }
522 #endif /* SNTP_CHECK_RESPONSE >= 1 */
523
524 pbuf_free(p);
525
526 if (err == ERR_OK) {
527 /* correct packet received: process it it */
528 sntp_process(×tamps);
529
530 #if SNTP_MONITOR_SERVER_REACHABILITY
531 /* indicate that server responded */
532 sntp_servers[sntp_current_server].reachability |= 1;
533 #endif /* SNTP_MONITOR_SERVER_REACHABILITY */
534 /* Stop sntp module */
535 sntp_stop();
536
537 smsg.err = (err_t)sntp_current_server;
538
539 /* Return success */
540 sys_sem_signal(&smsg.cb_completed);
541
542 } else if (err == SNTP_ERR_KOD) {
543 /* KOD errors are only processed in case of an explicit poll response */
544 if (sntp_opmode == SNTP_OPMODE_POLL) {
545 /* Kiss-of-death packet. Use another server or increase UPDATE_DELAY. */
546 sntp_try_next_server(NULL);
547 }
548 } else {
549 /* broken packet: try the same server again, limit max retry count to avoid flooding */
550 sntp_retry(NULL);
551 }
552 }
553
554 /** Actually send an sntp request to a server.
555 *
556 * @param server_addr resolved IP address of the SNTP server
557 */
558 static void
sntp_send_request(const ip_addr_t * server_addr)559 sntp_send_request(const ip_addr_t *server_addr)
560 {
561 struct pbuf *p;
562
563 LWIP_ASSERT("server_addr != NULL", server_addr != NULL);
564
565 /* sntp_pcb has been released, that implies the response came too late... just ignore it */
566 if (sntp_pcb == NULL) {
567 return;
568 }
569
570 p = pbuf_alloc(PBUF_TRANSPORT, SNTP_MSG_LEN, PBUF_RAM);
571 if (p != NULL) {
572 struct sntp_msg *sntpmsg = (struct sntp_msg *)p->payload;
573 LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_send_request: Sending request to server\n"));
574 /* initialize request message */
575 sntp_initialize_request(sntpmsg);
576 /* send request */
577 udp_sendto(sntp_pcb, p, server_addr, SNTP_PORT);
578 /* free the pbuf after sending it */
579 pbuf_free(p);
580 #if SNTP_MONITOR_SERVER_REACHABILITY
581 /* indicate new packet has been sent */
582 sntp_servers[sntp_current_server].reachability <<= 1;
583 #endif /* SNTP_MONITOR_SERVER_REACHABILITY */
584 /* set up receive timeout: try next server or retry on timeout */
585 if (sntp_retry_count >= SNTP_MAX_REQUEST_RETRANSMIT) {
586 sntp_retry_count = 0;
587 LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_retry: Sending request to next server\n"));
588 sys_untimeout(sntp_try_next_server, NULL);
589 if (sys_timeout((u32_t)SNTP_RECV_TIMEOUT, sntp_try_next_server, NULL) != ERR_OK) {
590 smsg.err = ERR_MEM;
591 sys_sem_signal(&smsg.cb_completed);
592 return;
593 }
594 } else {
595 sntp_retry_count++;
596 LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_retry: Sending request to server\n"));
597 sntp_retry(NULL);
598 }
599 #if SNTP_CHECK_RESPONSE >= 1
600 /* save server address to verify it in sntp_recv */
601 ip_addr_copy(sntp_last_server_address, *server_addr);
602 #endif /* SNTP_CHECK_RESPONSE >= 1 */
603 } else {
604 LWIP_DEBUGF(SNTP_DEBUG_SERIOUS, ("sntp_send_request: Out of memory, trying again in %"U32_F" ms\n",
605 (u32_t)SNTP_RETRY_TIMEOUT));
606 /* out of memory: set up a timer to send a retry */
607 sys_untimeout(sntp_request, NULL);
608 if (sys_timeout((u32_t)SNTP_RETRY_TIMEOUT, sntp_request, NULL) != ERR_OK) {
609 smsg.err = ERR_MEM;
610 sys_sem_signal(&smsg.cb_completed);
611 }
612 }
613 }
614
615 #if SNTP_SERVER_DNS
616 /**
617 * DNS found callback when using DNS names as server address.
618 */
619 static void
sntp_dns_found(const char * hostname,const ip_addr_t * ipaddr,u32_t count,void * arg)620 sntp_dns_found(const char *hostname, const ip_addr_t *ipaddr, u32_t count, void *arg)
621 {
622 LWIP_UNUSED_ARG(hostname);
623 LWIP_UNUSED_ARG(arg);
624 LWIP_UNUSED_ARG(count);
625
626 /* sntp_pcb has been released, that implies the response came too late... just ignore it */
627 if (sntp_pcb == NULL) {
628 return;
629 }
630
631 if (ipaddr != NULL) {
632 /* Address resolved, send request */
633 LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_dns_found: Server address resolved, sending request\n"));
634 sntp_servers[sntp_current_server].addr = *ipaddr;
635 sntp_send_request(ipaddr);
636 } else {
637 /* DNS resolving failed -> try another server */
638 LWIP_DEBUGF(SNTP_DEBUG_WARN_STATE, ("sntp_dns_found: Failed to resolve server address resolved, trying next server\n"));
639 sntp_try_next_server(NULL);
640 }
641 }
642 #endif /* SNTP_SERVER_DNS */
643
644 /**
645 * Send out an sntp request.
646 *
647 * @param arg is unused (only necessary to conform to sys_timeout)
648 */
649 static void
sntp_request(void * arg)650 sntp_request(void *arg)
651 {
652 ip_addr_t sntp_server_address;
653 err_t err;
654
655 #if SNTP_SERVER_DNS
656 u32_t count = 1;
657 #endif /* SNTP_SERVER_DNS */
658
659 LWIP_UNUSED_ARG(arg);
660
661 /* initialize SNTP server address */
662 #if SNTP_SERVER_DNS
663 if (sntp_servers[sntp_current_server].name) {
664 /* always resolve the name and rely on dns-internal caching & timeout */
665 ip_addr_set_zero(&sntp_servers[sntp_current_server].addr);
666 err = dns_gethostbyname(sntp_servers[sntp_current_server].name, &sntp_server_address, &count,
667 sntp_dns_found, NULL);
668 if (err == ERR_INPROGRESS) {
669 /* DNS request sent, wait for sntp_dns_found being called */
670 LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_request: Waiting for server address to be resolved.\n"));
671 return;
672 } else if (err == ERR_OK) {
673 sntp_servers[sntp_current_server].addr = sntp_server_address;
674 }
675 } else
676 #endif /* SNTP_SERVER_DNS */
677 {
678 sntp_server_address = sntp_servers[sntp_current_server].addr;
679 err = (ip_addr_isany_val(sntp_server_address)) ? ERR_ARG : ERR_OK;
680 }
681
682 if (err == ERR_OK) {
683 #ifdef LWIP_DEBUG
684 char buf[IPADDR_STRLEN_MAX];
685 (void)ipaddr_ntoa_r(&sntp_server_address, buf, IPADDR_STRLEN_MAX);
686 #endif
687 LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_request: current server address is %s\n",
688 buf));
689 sntp_send_request(&sntp_server_address);
690 } else {
691 /* address conversion failed, try another server */
692 LWIP_DEBUGF(SNTP_DEBUG_WARN_STATE, ("sntp_request: Invalid server address, trying next server.\n"));
693 sys_untimeout(sntp_try_next_server, NULL);
694 if (sys_timeout((u32_t)SNTP_RETRY_TIMEOUT, sntp_try_next_server, NULL) != ERR_OK) {
695 smsg.err = ERR_MEM;
696 sys_sem_signal(&smsg.cb_completed);
697 }
698 }
699 }
700
701 /**
702 * @ingroup sntp
703 * Initialize this module.
704 * Send out request instantly or after SNTP_STARTUP_DELAY(_FUNC).
705 */
706 void
sntp_init(void * arg)707 sntp_init(void *arg)
708 {
709 LWIP_UNUSED_ARG(arg);
710 /* LWIP_ASSERT_CORE_LOCKED(); is checked by udp_new() */
711 LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_init: SNTP initialised\n"));
712
713 #ifdef SNTP_SERVER_ADDRESS
714 #if SNTP_SERVER_DNS
715 sntp_setservername(0, SNTP_SERVER_ADDRESS);
716 #else
717 #error SNTP_SERVER_ADDRESS string not supported SNTP_SERVER_DNS==0
718 #endif
719 #endif /* SNTP_SERVER_ADDRESS */
720
721 if (sntp_pcb == NULL) {
722 int server_num = 0;
723 int i;
724 sntp_pcb = udp_new_ip_type(IPADDR_TYPE_ANY);
725 LWIP_ASSERT("Failed to allocate udp pcb for sntp client", sntp_pcb != NULL);
726 if (sntp_pcb != NULL) {
727 for (i = 0; i < LWIP_MIN(smsg.server_num, SNTP_MAX_SERVERS); i++) {
728 #if SNTP_SERVER_DNS
729 sntp_setservername((u8_t)server_num, smsg.sntp_server[i]);
730 server_num++;
731 #else /* SNTP_SERVER_DNS */
732 ip_addr_t server_ip;
733 if (ipaddr_aton(smsg.sntp_server[i], &server_ip) == 1) {
734 sntp_setserver(server_num, &server_ip);
735 server_num++;
736 }
737 #endif /* SNTP_SERVER_DNS */
738 }
739
740 if (server_num <= 0) {
741 sntp_stop();
742 smsg.err = ERR_ARG;
743 sys_sem_signal(&smsg.cb_completed);
744 }
745 sntp_current_server = 0;
746 sntp_num_servers = server_num;
747 sntp_retry_count = 0;
748 sntp_kod_found = 0;
749 udp_recv(sntp_pcb, sntp_recv, NULL);
750
751 if (sntp_opmode == SNTP_OPMODE_POLL) {
752 SNTP_RESET_RETRY_TIMEOUT();
753 #if LWIP_SO_PRIORITY
754 sntp_pcb->priority = LWIP_PKT_PRIORITY_SNTP;
755 #endif /* LWIP_SO_PRIORITY */
756 #if SNTP_STARTUP_DELAY
757 if (sys_timeout((u32_t)SNTP_STARTUP_DELAY_FUNC, sntp_request, NULL) != ERR_OK) {
758 smsg.err = ERR_MEM;
759 sys_sem_signal(&smsg.cb_completed);
760 }
761 #else
762 sntp_request(NULL);
763 #endif
764 } else if (sntp_opmode == SNTP_OPMODE_LISTENONLY) {
765 ip_set_option(sntp_pcb, SOF_BROADCAST);
766 udp_bind(sntp_pcb, IP_ANY_TYPE, SNTP_PORT);
767 }
768 } else {
769 smsg.err = ERR_MEM;
770 sys_sem_signal(&smsg.cb_completed);
771 }
772 } else {
773 LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_init: In processing, please try later\n"));
774 smsg.err = ERR_INPROGRESS;
775 sys_sem_signal(&smsg.cb_completed);
776 }
777 }
778
779 int
lwip_sntp_start(int server_num,char ** sntp_server,struct timeval * time_local)780 lwip_sntp_start(int server_num, char **sntp_server, struct timeval *time_local)
781 {
782 err_t err;
783
784 if ((server_num == 0) || (sntp_server == NULL) || (server_num > DNS_MAX_SERVERS)) {
785 return ERR_ARG;
786 }
787
788 err = sys_sem_new(&smsg.cb_completed, 0);
789 if (err != ERR_OK) {
790 return ERR_MEM;
791 }
792
793 smsg.server_num = server_num;
794 smsg.sntp_server = sntp_server;
795 smsg.sntp_time = time_local;
796 smsg.err = ERR_OK;
797 err = tcpip_callback(sntp_init, NULL);
798 if (err != ERR_OK) {
799 sys_sem_free(&smsg.cb_completed);
800 return err;
801 }
802 err = (err_t)sys_arch_sem_wait(&smsg.cb_completed, 0);
803 if ((err == (err_t)SYS_ARCH_ERROR) || (err == (err_t)SYS_ARCH_TIMEOUT)) {
804 sys_sem_free(&smsg.cb_completed);
805 return err;
806 }
807 sys_sem_free(&smsg.cb_completed);
808 return smsg.err;
809 }
810
811 /**
812 * @ingroup sntp
813 * Stop this module.
814 */
815 void
sntp_stop(void)816 sntp_stop(void)
817 {
818 LWIP_ASSERT_CORE_LOCKED();
819 if (sntp_pcb != NULL) {
820 #if SNTP_MONITOR_SERVER_REACHABILITY
821 u8_t i;
822 for (i = 0; i < SNTP_MAX_SERVERS; i++) {
823 sntp_servers[i].reachability = 0;
824 }
825 #endif /* SNTP_MONITOR_SERVER_REACHABILITY */
826 sys_untimeout(sntp_request, NULL);
827 sys_untimeout(sntp_try_next_server, NULL);
828 udp_remove(sntp_pcb);
829 sntp_pcb = NULL;
830 }
831 }
832
833 /**
834 * @ingroup sntp
835 * Get enabled state.
836 */
sntp_enabled(void)837 u8_t sntp_enabled(void)
838 {
839 return (sntp_pcb != NULL) ? 1 : 0;
840 }
841
842 /**
843 * @ingroup sntp
844 * Sets the operating mode.
845 * @param operating_mode one of the available operating modes
846 */
847 void
sntp_setoperatingmode(u8_t operating_mode)848 sntp_setoperatingmode(u8_t operating_mode)
849 {
850 LWIP_ASSERT_CORE_LOCKED();
851 LWIP_ASSERT("Invalid operating mode", operating_mode <= SNTP_OPMODE_LISTENONLY);
852 LWIP_ASSERT("Operating mode must not be set while SNTP client is running", sntp_pcb == NULL);
853 sntp_opmode = operating_mode;
854 }
855
856 /**
857 * @ingroup sntp
858 * Gets the operating mode.
859 */
860 u8_t
sntp_getoperatingmode(void)861 sntp_getoperatingmode(void)
862 {
863 return sntp_opmode;
864 }
865
866 #if SNTP_MONITOR_SERVER_REACHABILITY
867 /**
868 * @ingroup sntp
869 * Gets the server reachability shift register as described in RFC 5905.
870 *
871 * @param idx the index of the NTP server
872 */
873 u8_t
sntp_getreachability(u8_t idx)874 sntp_getreachability(u8_t idx)
875 {
876 if (idx < SNTP_MAX_SERVERS) {
877 return sntp_servers[idx].reachability;
878 }
879 return 0;
880 }
881 #endif /* SNTP_MONITOR_SERVER_REACHABILITY */
882
883 #if SNTP_GET_SERVERS_FROM_DHCP || SNTP_GET_SERVERS_FROM_DHCPV6
884 /**
885 * Config SNTP server handling by IP address, name, or DHCP; clear table
886 * @param set_servers_from_dhcp enable or disable getting server addresses from dhcp
887 */
888 void
sntp_servermode_dhcp(int set_servers_from_dhcp)889 sntp_servermode_dhcp(int set_servers_from_dhcp)
890 {
891 u8_t new_mode = set_servers_from_dhcp ? 1 : 0;
892 LWIP_ASSERT_CORE_LOCKED();
893 if (sntp_set_servers_from_dhcp != new_mode) {
894 sntp_set_servers_from_dhcp = new_mode;
895 }
896 }
897 #endif /* SNTP_GET_SERVERS_FROM_DHCP || SNTP_GET_SERVERS_FROM_DHCPV6 */
898
899 /**
900 * @ingroup sntp
901 * Initialize one of the NTP servers by IP address
902 *
903 * @param idx the index of the NTP server to set must be < SNTP_MAX_SERVERS
904 * @param server IP address of the NTP server to set
905 */
906 void
sntp_setserver(u8_t idx,const ip_addr_t * server)907 sntp_setserver(u8_t idx, const ip_addr_t *server)
908 {
909 LWIP_ASSERT_CORE_LOCKED();
910 if (idx < SNTP_MAX_SERVERS) {
911 if (server != NULL) {
912 sntp_servers[idx].addr = (*server);
913 } else {
914 ip_addr_set_zero(&sntp_servers[idx].addr);
915 }
916 #if SNTP_SERVER_DNS
917 sntp_servers[idx].name = NULL;
918 #endif
919 }
920 }
921
922 #if LWIP_DHCP && SNTP_GET_SERVERS_FROM_DHCP
923 /**
924 * Initialize one of the NTP servers by IP address, required by DHCP
925 *
926 * @param num the index of the NTP server to set must be < SNTP_MAX_SERVERS
927 * @param server IP address of the NTP server to set
928 */
929 void
dhcp_set_ntp_servers(u8_t num,const ip4_addr_t * server)930 dhcp_set_ntp_servers(u8_t num, const ip4_addr_t *server)
931 {
932 LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp: %s %u.%u.%u.%u as NTP server #%u via DHCP\n",
933 (sntp_set_servers_from_dhcp ? "Got" : "Rejected"),
934 ip4_addr1(server), ip4_addr2(server), ip4_addr3(server), ip4_addr4(server), num));
935 if (sntp_set_servers_from_dhcp && num) {
936 u8_t i;
937 for (i = 0; (i < num) && (i < SNTP_MAX_SERVERS); i++) {
938 ip_addr_t addr;
939 ip_addr_copy_from_ip4(addr, server[i]);
940 sntp_setserver(i, &addr);
941 }
942 for (i = num; i < SNTP_MAX_SERVERS; i++) {
943 sntp_setserver(i, NULL);
944 }
945 }
946 }
947 #endif /* LWIP_DHCP && SNTP_GET_SERVERS_FROM_DHCP */
948
949 #if LWIP_IPV6_DHCP6 && SNTP_GET_SERVERS_FROM_DHCPV6
950 /**
951 * Initialize one of the NTP servers by IP address, required by DHCPV6
952 *
953 * @param num the number of NTP server addresses to set must be < SNTP_MAX_SERVERS
954 * @param server array of IP address of the NTP servers to set
955 */
956 void
dhcp6_set_ntp_servers(u8_t num_ntp_servers,ip_addr_t * ntp_server_addrs)957 dhcp6_set_ntp_servers(u8_t num_ntp_servers, ip_addr_t* ntp_server_addrs)
958 {
959 LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp: %s %u NTP server(s) via DHCPv6\n",
960 (sntp_set_servers_from_dhcp ? "Got" : "Rejected"),
961 num_ntp_servers));
962 if (sntp_set_servers_from_dhcp && num_ntp_servers) {
963 u8_t i;
964 for (i = 0; (i < num_ntp_servers) && (i < SNTP_MAX_SERVERS); i++) {
965 LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp: NTP server %u: %s\n",
966 i, ipaddr_ntoa(&ntp_server_addrs[i])));
967 sntp_setserver(i, &ntp_server_addrs[i]);
968 }
969 for (i = num_ntp_servers; i < SNTP_MAX_SERVERS; i++) {
970 sntp_setserver(i, NULL);
971 }
972 }
973 }
974 #endif /* LWIP_DHCPv6 && SNTP_GET_SERVERS_FROM_DHCPV6 */
975
976 /**
977 * @ingroup sntp
978 * Obtain one of the currently configured by IP address (or DHCP) NTP servers
979 *
980 * @param idx the index of the NTP server
981 * @return IP address of the indexed NTP server or "ip_addr_any" if the NTP
982 * server has not been configured by address (or at all).
983 */
984 const ip_addr_t *
sntp_getserver(u8_t idx)985 sntp_getserver(u8_t idx)
986 {
987 if (idx < SNTP_MAX_SERVERS) {
988 return &sntp_servers[idx].addr;
989 }
990 return IP_ADDR_ANY;
991 }
992
993 #if SNTP_SERVER_DNS
994 /**
995 * Initialize one of the NTP servers by name
996 *
997 * @param idx the index of the NTP server to set must be < SNTP_MAX_SERVERS
998 * @param server DNS name of the NTP server to set, to be resolved at contact time
999 */
1000 void
sntp_setservername(u8_t idx,const char * server)1001 sntp_setservername(u8_t idx, const char *server)
1002 {
1003 LWIP_ASSERT_CORE_LOCKED();
1004 if (idx < SNTP_MAX_SERVERS) {
1005 sntp_servers[idx].name = server;
1006 }
1007 }
1008
1009 /**
1010 * Obtain one of the currently configured by name NTP servers.
1011 *
1012 * @param idx the index of the NTP server
1013 * @return IP address of the indexed NTP server or NULL if the NTP
1014 * server has not been configured by name (or at all)
1015 */
1016 const char *
sntp_getservername(u8_t idx)1017 sntp_getservername(u8_t idx)
1018 {
1019 if (idx < SNTP_MAX_SERVERS) {
1020 return sntp_servers[idx].name;
1021 }
1022 return NULL;
1023 }
1024 #endif /* SNTP_SERVER_DNS */
1025
1026 #endif /* LWIP_SNTP */
1027