forked from apache/nuttx-apps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathntpclient.c
1611 lines (1283 loc) · 41.2 KB
/
ntpclient.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
* apps/netutils/ntpclient/ntpclient.c
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sched.h>
#include <assert.h>
#include <errno.h>
#include <debug.h>
#include <unistd.h>
#include <netinet/in.h>
#ifdef CONFIG_LIBC_NETDB
# include <netdb.h>
# include <arpa/inet.h>
#endif
#include <nuttx/clock.h>
#include "netutils/ntpclient.h"
#include "ntpv3.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Configuration ************************************************************/
#ifndef CONFIG_HAVE_LONG_LONG
# error "64-bit integer support required for NTP client"
#endif
#if defined(CONFIG_LIBC_NETDB) && !defined(CONFIG_NETUTILS_NTPCLIENT_SERVER)
# error "CONFIG_NETUTILS_NTPCLIENT_SERVER must be provided"
#endif
#if !defined(CONFIG_LIBC_NETDB) && !defined(CONFIG_NETUTILS_NTPCLIENT_SERVERIP)
# error "CONFIG_NETUTILS_NTPCLIENT_SERVERIP must be provided"
#endif
#ifndef CONFIG_NETUTILS_NTPCLIENT_NUM_SAMPLES
# define CONFIG_NETUTILS_NTPCLIENT_NUM_SAMPLES 5
#elif CONFIG_NETUTILS_NTPCLIENT_NUM_SAMPLES < 1
# error "NTP sample number below 1, invalid configuration"
#endif
#ifndef CONFIG_NETUTILS_NTPCLIENT_SERVER
# ifdef CONFIG_NETUTILS_NTPCLIENT_SERVERIP
/* Old config support */
# warning "NTP server hostname not defined, using deprecated server IP address setting"
# define CONFIG_NETUTILS_NTPCLIENT_SERVER \
inet_ntoa(CONFIG_NETUTILS_NTPCLIENT_SERVERIP)
# else
# error "NTP server hostname not defined"
# endif
#endif
/* NTP Time is seconds since 1900. Convert to Unix time which is seconds
* since 1970
*/
#define NTP2UNIX_TRANSLATION 2208988800u
#define NTP_VERSION_V3 3
#define NTP_VERSION_V4 4
#define NTP_VERSION NTP_VERSION_V4
#define MAX_SERVER_SELECTION_RETRIES 3
#ifndef STR
# define STR2(x) #x
# define STR(x) STR2(x)
#endif
/****************************************************************************
* Private Types
****************************************************************************/
/* This enumeration describes the state of the NTP daemon */
enum ntpc_daemon_e
{
NTP_NOT_RUNNING = 0,
NTP_STARTED,
NTP_RUNNING,
NTP_STOP_REQUESTED,
NTP_STOPPED
};
/* This type describes the state of the NTP client daemon. Only one
* instance of the NTP daemon is permitted in this implementation.
*/
struct ntpc_daemon_s
{
uint8_t state; /* See enum ntpc_daemon_e */
sem_t lock; /* Used to protect the whole structure */
sem_t sync; /* Used to synchronize start and stop events */
pid_t pid; /* Task ID of the NTP daemon */
sq_queue_t kod_list; /* KoD excluded server addresses */
int family; /* Allowed address family */
};
union ntp_addr_u
{
struct sockaddr sa;
#ifdef CONFIG_NET_IPv4
struct sockaddr_in in4;
#endif
#ifdef CONFIG_NET_IPv6
struct sockaddr_in6 in6;
#endif
struct sockaddr_storage ss;
};
/* NTP offset. */
struct ntp_sample_s
{
int64_t offset;
int64_t delay;
union ntp_addr_u srv_addr;
} packet_struct;
/* Server address list. */
struct ntp_servers_s
{
union ntp_addr_u list[CONFIG_NETUTILS_NTPCLIENT_NUM_SAMPLES];
size_t num;
size_t pos;
FAR char *hostlist_str;
FAR char *hostlist_saveptr;
FAR char *hostnext;
FAR const char *ntp_servers;
};
/* KoD exclusion list. */
struct ntp_kod_exclude_s
{
sq_entry_t node;
union ntp_addr_u addr;
};
/****************************************************************************
* Private Data
****************************************************************************/
/* This type describes the state of the NTP client daemon. Only one
* instance of the NTP daemon is permitted in this implementation. This
* limitation is due only to this global data structure.
*/
static struct ntpc_daemon_s g_ntpc_daemon =
{
NTP_NOT_RUNNING,
SEM_INITIALIZER(1),
SEM_INITIALIZER(0),
-1,
{ NULL, NULL },
AF_UNSPEC, /* Default is both IPv4 and IPv6 */
};
static struct ntp_sample_s g_last_samples
[CONFIG_NETUTILS_NTPCLIENT_NUM_SAMPLES];
unsigned int g_last_nsamples = 0;
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: sample_cmp
****************************************************************************/
static int sample_cmp(FAR const void *_a, FAR const void *_b)
{
FAR const struct ntp_sample_s *a = _a;
FAR const struct ntp_sample_s *b = _b;
int64_t diff = a->offset - b->offset;
if (diff < 0)
{
return -1;
}
else if (diff > 0)
{
return 1;
}
else
{
return 0;
}
}
/****************************************************************************
* Name: int64abs
****************************************************************************/
static inline int64_t int64abs(int64_t value)
{
return value >= 0 ? value : -value;
}
/****************************************************************************
* Name: ntpc_get_compile_timestamp
****************************************************************************/
static time_t ntpc_get_compile_timestamp(void)
{
struct tm tm;
int year;
int day;
int month;
bool unknown = true;
time_t tim;
#ifdef __DATE__
const char *pmonth;
const char *pyear;
const char *pday;
/* Compile date. Format: "MMM DD YYYY", where MMM is month in three letter
* format, DD is day of month (left padded with space if less than ten) and
* YYYY is year. "??? ?? ????" if unknown.
*/
pmonth = __DATE__;
pday = pmonth + 4;
pyear = pmonth + 7;
year = (pyear[0] - '0') * 1000
+ (pyear[1] - '0') * 100
+ (pyear[2] - '0') * 10
+ (pyear[3] - '0') * 1;
day = (pday[1] - '0');
if (pday[0] != ' ')
{
day += (pday[0] - '0') * 10;
}
unknown = false;
switch (pmonth[0])
{
default:
unknown = true;
break;
case 'J':
if (pmonth[1] == 'a') /* Jan */
month = 1;
else if (pmonth[2] == 'n') /* Jun */
month = 6;
else /* Jul */
month = 7;
break;
case 'F': /* Feb */
month = 2;
break;
case 'M':
if (pmonth[2] == 'r') /* Mar */
month = 3;
else /* May */
month = 5;
break;
case 'A':
if (pmonth[1] == 'p') /* Apr */
month = 4;
else /* Aug */
month = 8;
break;
case 'S': /* Sep */
month = 9;
break;
case 'O': /* Oct */
month = 10;
break;
case 'N': /* Nov */
month = 11;
break;
case 'D': /* Dec */
month = 12;
break;
}
#endif
if (unknown)
{
month = 8;
day = 18;
year = 2015;
}
/* Convert date to timestamp. */
memset(&tm, 0, sizeof(tm));
tm.tm_hour = 0;
tm.tm_min = 0;
tm.tm_sec = 0;
tm.tm_mday = day;
tm.tm_mon = month - 1;
tm.tm_year = year - 1900;
tim = mktime(&tm);
/* Reduce by one day to discount timezones. */
tim -= 24 * 60 * 60;
return tim;
}
/****************************************************************************
* Name: ntpc_getuint32
*
* Description:
* Return the big-endian, 4-byte value in network (big-endian) order.
*
****************************************************************************/
static inline uint32_t ntpc_getuint32(FAR const uint8_t *ptr)
{
/* Network order is big-endian; host order is irrelevant */
return (uint32_t)ptr[3] | /* MS byte appears first in data stream */
((uint32_t)ptr[2] << 8) |
((uint32_t)ptr[1] << 16) |
((uint32_t)ptr[0] << 24);
}
/****************************************************************************
* Name: ntpc_getuint64
*
* Description:
* Return the big-endian, 8-byte value in network (big-endian) order.
*
****************************************************************************/
static inline uint64_t ntpc_getuint64(FAR const uint8_t *ptr)
{
return ((uint64_t)ntpc_getuint32(ptr) << 32) | ntpc_getuint32(&ptr[4]);
}
/****************************************************************************
* Name: ntpc_setuint32
*
* Description:
* Write 4-byte value to buffer in network (big-endian) order.
*
****************************************************************************/
static inline void ntpc_setuint32(FAR uint8_t *ptr, uint32_t value)
{
ptr[3] = (uint8_t)value;
ptr[2] = (uint8_t)(value >> 8);
ptr[1] = (uint8_t)(value >> 16);
ptr[0] = (uint8_t)(value >> 24);
}
/****************************************************************************
* Name: ntpc_setuint64
*
* Description:
* Write 8-byte value to buffer in network (big-endian) order.
*
****************************************************************************/
static inline void ntpc_setuint64(FAR uint8_t *ptr, uint64_t value)
{
ntpc_setuint32(ptr + 0, (uint32_t)(value >> 32));
ntpc_setuint32(ptr + 4, (uint32_t)value);
}
/****************************************************************************
* Name: ntp_secpart
****************************************************************************/
static int32_t ntp_secpart(int64_t time)
{
/* NTP timestamps are represented as a 64-bit fixed-point number, in
* seconds relative to 0000 UT on 1 January 1900. The integer part is
* in the first 32 bits and the fraction part in the last 32 bits, as
* shown in the following diagram.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Integer Part |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Fraction Part |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
/* Get seconds part. */
return time >> 32;
}
/****************************************************************************
* Name: ntp_nsecpart
****************************************************************************/
static int32_t ntp_nsecpart(int64_t time)
{
/* Get fraction part converted to nanoseconds. */
return (((int64_t)((uint64_t)time << 32) >> 32) * NSEC_PER_SEC) >> 32;
}
/****************************************************************************
* Name: timespec2ntp
*
* Convert UNIX timespec timestamp to NTP 64-bit fixed point timestamp.
*
****************************************************************************/
static uint64_t timespec2ntp(FAR const struct timespec *ts)
{
uint64_t ntp_time;
/* Set fraction part. */
ntp_time = ((uint64_t)(ts->tv_nsec) << 32) / NSEC_PER_SEC;
DEBUGASSERT((ntp_time >> 32) == 0);
/* Set seconds part. */
ntp_time += (uint64_t)(ts->tv_sec) << 32;
return ntp_time;
}
/****************************************************************************
* Name: ntp_gettime
*
* Get time in NTP epoch, stored in fixed point uint64_t format (upper 32-bit
* seconds, lower 32-bit fraction)
****************************************************************************/
static uint64_t ntp_localtime(void)
{
int err = errno;
struct timespec currts;
/* Get current clock in NTP epoch. */
clock_gettime(CLOCK_REALTIME, &currts);
currts.tv_sec += NTP2UNIX_TRANSLATION;
/* Restore errno. */
errno = err;
return timespec2ntp(&currts);
}
/****************************************************************************
* Name: ntpc_calculate_offset
*
* Description:
* Calculate NTP time offset and round-trip delay
*
****************************************************************************/
static void ntpc_calculate_offset(FAR int64_t *offset, FAR int64_t *delay,
uint64_t local_xmittime,
uint64_t local_recvtime,
FAR const uint8_t *remote_recv,
FAR const uint8_t *remote_xmit)
{
uint64_t remote_recvtime;
uint64_t remote_xmittime;
/* Two timestamps from server, when request was received, and response
* send.
*/
remote_recvtime = ntpc_getuint64(remote_recv);
remote_xmittime = ntpc_getuint64(remote_xmit);
/* Calculate offset of local time compared to remote time.
* See: https://www.eecis.udel.edu/~mills/time.html
* http://nicolas.aimon.fr/2014/12/05/timesync/
*/
*offset = (int64_t)((remote_recvtime / 2 - local_xmittime / 2) +
(remote_xmittime / 2 - local_recvtime / 2));
/* Calculate roundtrip delay. */
*delay = (local_recvtime - local_xmittime) -
(remote_xmittime - remote_recvtime);
}
/****************************************************************************
* Name: ntpc_apply_offset
****************************************************************************/
static void ntpc_apply_offset(FAR struct timespec *tp,
FAR struct timespec *src,
int64_t offset)
{
tp->tv_sec = src->tv_sec + ntp_secpart(offset);
tp->tv_nsec = src->tv_nsec + ntp_nsecpart(offset);
while (tp->tv_nsec < 0)
{
tp->tv_nsec += NSEC_PER_SEC;
tp->tv_sec--;
}
while (tp->tv_nsec >= NSEC_PER_SEC)
{
tp->tv_nsec -= NSEC_PER_SEC;
tp->tv_sec++;
}
}
/****************************************************************************
* Name: ntpc_settime
*
* Description:
* Given the NTP time offset, adjust the system time
*
****************************************************************************/
static void ntpc_settime(int64_t offset, FAR struct timespec *start_realtime,
FAR struct timespec *start_monotonic)
{
struct timespec tp;
struct timespec curr_realtime;
struct timespec curr_monotonic;
int64_t diffms_real;
int64_t diffms_mono;
int64_t diff_diff_ms;
/* Get the system times */
clock_gettime(CLOCK_REALTIME, &curr_realtime);
clock_gettime(CLOCK_MONOTONIC, &curr_monotonic);
/* Check differences between monotonic and realtime. */
diffms_real = curr_realtime.tv_sec - start_realtime->tv_sec;
diffms_real *= 1000;
diffms_real += (int64_t)(curr_realtime.tv_nsec -
start_realtime->tv_nsec) / (1000 * 1000);
diffms_mono = curr_monotonic.tv_sec - start_monotonic->tv_sec;
diffms_mono *= 1000;
diffms_mono += (int64_t)(curr_monotonic.tv_nsec -
start_monotonic->tv_nsec) / (1000 * 1000);
/* Detect if real-time has been altered by other task. */
diff_diff_ms = diffms_real - diffms_mono;
if (diff_diff_ms < 0)
{
diff_diff_ms = -diff_diff_ms;
}
if (diff_diff_ms >= 1000)
{
nwarn("System time altered by other task by %ju msecs, "
"do not apply offset.\n", (intmax_t)diff_diff_ms);
return;
}
/* Apply offset */
ntpc_apply_offset(&tp, &curr_realtime, offset);
/* Set the system time */
clock_settime(CLOCK_REALTIME, &tp);
ninfo("Set time to %ju.%03ld seconds (offset: %s%lu.%03lu).\n",
(intmax_t)tp.tv_sec, tp.tv_nsec / NSEC_PER_MSEC,
offset < 0 ? "-" : "",
(unsigned long)ntp_secpart(int64abs(offset)),
ntp_nsecpart(int64abs(offset)) / NSEC_PER_MSEC);
}
/****************************************************************************
* Name: ntp_address_in_kod_list
*
* Description: Check if address is in KoD KoD exclusion list.
*
****************************************************************************/
static bool ntp_address_in_kod_list(FAR const union ntp_addr_u *server_addr)
{
FAR struct ntp_kod_exclude_s *entry;
entry = (FAR void *)sq_peek(&g_ntpc_daemon.kod_list);
while (entry)
{
if (memcmp(&entry->addr, server_addr, sizeof(*server_addr)) == 0)
{
return true;
}
entry = (FAR void *)sq_next(&entry->node);
}
return false;
}
/****************************************************************************
* Name: ntp_is_kiss_of_death
*
* Description: Check if this is KoD response from the server. If it is,
* add server to KoD exclusion list and return 'true'.
*
****************************************************************************/
static bool ntp_is_kiss_of_death(FAR const struct ntp_datagram_s *recv,
FAR const union ntp_addr_u *server_addr)
{
/* KoD only specified for v4. */
if (GETVN(recv->lvm) != NTP_VERSION_V4)
{
if (recv->stratum == 0)
{
/* Stratum 0 is unspecified on v3, so ignore packet. */
return true;
}
else
{
return false;
}
}
/* KoD message if stratum == 0. */
if (recv->stratum != 0)
{
return false;
}
/* KoD message received. */
/* Check if we need to add server to access exclusion list. */
if (strncmp((char *)recv->refid, "DENY", 4) == 0 ||
strncmp((char *)recv->refid, "RSTR", 4) == 0 ||
strncmp((char *)recv->refid, "RATE", 4) == 0)
{
struct ntp_kod_exclude_s *entry;
entry = calloc(1, sizeof(*entry));
if (entry)
{
entry->addr = *server_addr;
sq_addlast(&entry->node, &g_ntpc_daemon.kod_list);
}
}
return true;
}
/****************************************************************************
* Name: ntpc_verify_recvd_ntp_datagram
****************************************************************************/
static bool ntpc_verify_recvd_ntp_datagram(
FAR const struct ntp_datagram_s *xmit,
FAR const struct ntp_datagram_s *recv,
size_t nbytes,
FAR const union ntp_addr_u *xmitaddr,
FAR const union ntp_addr_u *recvaddr,
size_t recvaddrlen)
{
time_t buildtime;
time_t seconds;
if (recvaddr->sa.sa_family != xmitaddr->sa.sa_family)
{
ninfo("wrong address family\n");
return false;
}
#ifdef CONFIG_NET_IPv4
if (recvaddr->sa.sa_family == AF_INET)
{
if (recvaddrlen != sizeof(struct sockaddr_in) ||
xmitaddr->in4.sin_addr.s_addr != recvaddr->in4.sin_addr.s_addr ||
xmitaddr->in4.sin_port != recvaddr->in4.sin_port)
{
ninfo("response from wrong peer\n");
return false;
}
}
#endif
#ifdef CONFIG_NET_IPv6
if (recvaddr->sa.sa_family == AF_INET6)
{
if (recvaddrlen != sizeof(struct sockaddr_in6) ||
memcmp(&xmitaddr->in6.sin6_addr,
&recvaddr->in6.sin6_addr, sizeof(struct in6_addr)) != 0 ||
xmitaddr->in6.sin6_port != recvaddr->in6.sin6_port)
{
ninfo("response from wrong peer\n");
return false;
}
}
#endif /* CONFIG_NET_IPv6 */
if (nbytes < NTP_DATAGRAM_MINSIZE)
{
/* Too short. */
ninfo("too short response\n");
return false;
}
if (GETVN(recv->lvm) != NTP_VERSION_V3 &&
GETVN(recv->lvm) != NTP_VERSION_V4)
{
/* Wrong version. */
ninfo("wrong version: %d\n", GETVN(recv->lvm));
return false;
}
if (GETMODE(recv->lvm) != 4)
{
/* Response not in server mode. */
ninfo("wrong mode: %d\n", GETMODE(recv->lvm));
return false;
}
if (ntp_is_kiss_of_death(recv, xmitaddr))
{
/* KoD, Kiss-o'-Death. Ignore response. */
ninfo("kiss-of-death response\n");
return false;
}
if (GETLI(recv->lvm) == 3)
{
/* Clock not synchronized. */
ninfo("LI: not synchronized\n");
return false;
}
if (memcmp(recv->origtimestamp, xmit->xmittimestamp, 8) != 0)
{
/* "The Originate Timestamp in the server reply should match the
* Transmit Timestamp used in the client request."
*/
ninfo("xmittimestamp mismatch\n");
return false;
}
if (ntpc_getuint32(recv->reftimestamp) == 0)
{
/* Invalid timestamp. */
ninfo("invalid reftimestamp, 0x%08lx\n",
(unsigned long)ntpc_getuint32(recv->reftimestamp));
return false;
}
if (ntpc_getuint32(recv->recvtimestamp) == 0)
{
/* Invalid timestamp. */
ninfo("invalid recvtimestamp, 0x%08lx\n",
(unsigned long)ntpc_getuint32(recv->recvtimestamp));
return false;
}
if (ntpc_getuint32(recv->xmittimestamp) == 0)
{
/* Invalid timestamp. */
ninfo("invalid xmittimestamp, 0x%08lx\n",
(unsigned long)ntpc_getuint32(recv->xmittimestamp));
return false;
}
if ((int64_t)(ntpc_getuint64(recv->xmittimestamp) -
ntpc_getuint64(recv->recvtimestamp)) < 0)
{
/* Remote received our request after sending response? */
ninfo("invalid xmittimestamp & recvtimestamp pair\n");
return false;
}
buildtime = ntpc_get_compile_timestamp();
seconds = ntpc_getuint32(recv->recvtimestamp);
if (seconds > NTP2UNIX_TRANSLATION)
{
seconds -= NTP2UNIX_TRANSLATION;
}
if (seconds < buildtime)
{
/* Invalid timestamp. */
ninfo("invalid recvtimestamp, 0x%08lx\n",
(unsigned long)ntpc_getuint32(recv->recvtimestamp));
return false;
}
return true;
}
/****************************************************************************
* Name: ntpc_create_dgram_socket
****************************************************************************/
static int ntpc_create_dgram_socket(int domain)
{
struct timeval tv;
int ret;
int sd;
int err;
/* Create a datagram socket */
sd = socket(domain, SOCK_DGRAM, 0);
if (sd < 0)
{
err = errno;
nerr("ERROR: socket failed: %d\n", err);
errno = err;
return sd;
}
/* Setup a send timeout on the socket */
tv.tv_sec = CONFIG_NETUTILS_NTPCLIENT_TIMEOUT_MS / 1000;
tv.tv_usec = CONFIG_NETUTILS_NTPCLIENT_TIMEOUT_MS % 1000;
ret = setsockopt(sd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval));
if (ret < 0)
{
err = errno;
nerr("ERROR: setsockopt(SO_SNDTIMEO) failed: %d\n", errno);
goto err_close;
}
/* Setup a receive timeout on the socket */
ret = setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval));
if (ret < 0)
{
err = errno;
nerr("ERROR: setsockopt(SO_RCVTIMEO) failed: %d\n", errno);
goto err_close;
}
return sd;
err_close:
close(sd);
errno = err;
return ret;
}
/****************************************************************************
* Name: ntp_gethostip_multi
****************************************************************************/
static int ntp_gethostip_multi(FAR const char *hostname,
FAR union ntp_addr_u *ipaddr, size_t nipaddr)
{
struct addrinfo hints;
FAR struct addrinfo *info;
FAR struct addrinfo *next;
int ret;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = g_ntpc_daemon.family;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_NUMERICSERV;
ret = getaddrinfo(hostname, STR(CONFIG_NETUTILS_NTPCLIENT_PORTNO),
&hints, &info);
if (ret != OK)
{
nerr("ERROR: getaddrinfo(%s): %d: %s\n", hostname,
ret, gai_strerror(ret));
return ERROR;
}
ret = 0;
for (next = info; next != NULL; next = next->ai_next)
{
if (ret >= nipaddr)
{
break;
}
memcpy(ipaddr, next->ai_addr, next->ai_addrlen);
ret++;
ipaddr++;
}
freeaddrinfo(info);
return ret;
}
/****************************************************************************
* Name: ntp_get_next_hostip
****************************************************************************/
static int ntp_get_next_hostip(FAR struct ntp_servers_s *srvs,
FAR union ntp_addr_u *addr)
{
int ret;
if (srvs->pos >= srvs->num)
{
FAR char *hostname;
srvs->pos = 0;
srvs->num = 0;
/* Get next hostname. */
if (srvs->hostnext == NULL)
{
if (srvs->hostlist_str)
{
free(srvs->hostlist_str);
srvs->hostlist_str = NULL;
}
/* Allocate hostname list buffer */
srvs->hostlist_str = strdup(srvs->ntp_servers);
if (!srvs->hostlist_str)
{
return ERROR;
}