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