sntp_client_misc.c
Go to the documentation of this file.
1 /**
2  * @file sntp_client_misc.c
3  * @brief Helper functions for SNTP client
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2025 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneTCP Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.5.4
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL SNTP_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/net.h"
36 #include "sntp/sntp_client.h"
37 #include "sntp/sntp_client_misc.h"
38 #include "ntp/ntp_debug.h"
39 #include "debug.h"
40 
41 //Check TCP/IP stack configuration
42 #if (SNTP_CLIENT_SUPPORT == ENABLED)
43 
44 
45 /**
46  * @brief Open UDP connection
47  * @param[in] context Pointer to the SNTP client context
48  * @return Error code
49  **/
50 
52 {
53  error_t error;
54 
55  //Open a UDP socket
57 
58  //Valid socket?
59  if(context->socket != NULL)
60  {
61  //Associate the socket with the relevant interface
62  error = socketBindToInterface(context->socket, context->interface);
63  }
64  else
65  {
66  //Report an error
67  error = ERROR_OPEN_FAILED;
68  }
69 
70 #if (SNTP_CLIENT_SRC_PORT != 0)
71  //Check status code
72  if(!error)
73  {
74  //Set client's source port
76  }
77 #endif
78 
79  //Return status code
80  return error;
81 }
82 
83 
84 /**
85  * @brief Close UDP connection
86  * @param[in] context Pointer to the SNTP client context
87  **/
88 
90 {
91  //Valid socket?
92  if(context->socket != NULL)
93  {
94  //Close UDP socket
95  socketClose(context->socket);
96  context->socket = NULL;
97  }
98 }
99 
100 
101 /**
102  * @brief Send request to the NTP server
103  * @param[in] context Pointer to the SNTP client context
104  * @return Error code
105  **/
106 
108 {
109  error_t error;
110  NtpHeader *header;
111 
112  //Point to the buffer where to format the NTP message
113  header = (NtpHeader *) context->message;
114 
115  //The client initializes the NTP message header. For this purpose, all
116  //the NTP header fields are set to 0, except the Mode, VN, and optional
117  //Transmit Timestamp fields
118  osMemset(header, 0, sizeof(NtpHeader));
119 
120  //Format NTP request
121  header->vn = context->version;
122  header->mode = NTP_MODE_CLIENT;
123 
124  //Time at which the NTP request was sent
126 
127  //The Transmit Timestamp allows a simple calculation to determine the
128  //propagation delay between the server and client and to align the system
129  //clock generally within a few tens of milliseconds relative to the server
130  header->transmitTimestamp.seconds = 0;
131  header->transmitTimestamp.fraction = htonl(context->retransmitStartTime);
132 
133  //Length of the NTP request
134  context->messageLen = sizeof(NtpHeader);
135 
136  //Debug message
137  TRACE_INFO("Sending NTP request message (%" PRIuSIZE " bytes)...\r\n",
138  context->messageLen);
139 
140  //Dump the contents of the NTP packet for debugging purpose
141  ntpDumpPacket(header, context->messageLen);
142 
143  //Send the request to the designated NTP server
144  error = socketSendTo(context->socket, &context->serverIpAddr,
145  context->serverPort, context->message, context->messageLen,
146  NULL, 0);
147 
148  //Check status code
149  if(!error)
150  {
151  //Wait for server's response
153  }
154 
155  //Return status code
156  return error;
157 }
158 
159 
160 /**
161  * @brief Wait for NTP server's response
162  * @param[in] context Pointer to the SNTP client context
163  * @return Error code
164  **/
165 
167 {
168  error_t error;
169  systime_t t1;
170  systime_t t2;
171  systime_t time;
172  IpAddr ipAddr;
173  uint16_t port;
174 
175  //Get current time
176  time = osGetSystemTime();
177 
178  //Compute request timeout
179  if(timeCompare(context->startTime + context->timeout, time) > 0)
180  {
181  t1 = context->startTime + context->timeout - time;
182  }
183  else
184  {
185  t1 = 0;
186  }
187 
188  //Compute retransmission timeout
189  if(timeCompare(context->retransmitStartTime + context->retransmitTimeout, time) > 0)
190  {
191  t2 = context->retransmitStartTime + context->retransmitTimeout - time;
192  }
193  else
194  {
195  t2 = 0;
196  }
197 
198  //Adjust receive timeout
199  error = socketSetTimeout(context->socket, MIN(t1, t2));
200 
201  //Check status code
202  if(!error)
203  {
204  //Wait for server's response
205  error = socketReceiveFrom(context->socket, &ipAddr, &port,
206  context->message, NTP_MAX_MSG_SIZE, &context->messageLen, 0);
207  }
208 
209  //Any datagram received?
210  if(error == NO_ERROR)
211  {
212  //Check NTP response
213  error = sntpClientCheckResponse(context, &ipAddr, port,
214  context->message, context->messageLen);
215 
216  //Check status code
217  if(!error)
218  {
219  //A valid NTP response has been received
221  }
222  else
223  {
224  //Silently discard invalid NTP packets
225  error = sntpClientCheckTimeout(context);
226  }
227  }
228  else if(error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
229  {
230  //Check whether the timeout has elapsed
231  error = sntpClientCheckTimeout(context);
232  }
233  else
234  {
235  //A communication error has occurred
236  }
237 
238  //Return status code
239  return error;
240 }
241 
242 
243 /**
244  * @brief Check whether the NTP response is valid
245  * @param[in] context Pointer to the SNTP client context
246  * @param[in] ipAddr Remote IP address
247  * @param[in] port Remote port number
248  * @param[in] message Pointer to the NTP message
249  * @param[in] length Length of the NTP message, in bytes
250  * @return Error code
251  **/
252 
254  const IpAddr *ipAddr, uint16_t port, const uint8_t *message,
255  size_t length)
256 {
257  NtpHeader *header;
258 
259  //Ensure the NTP packet is valid
260  if(length < sizeof(NtpHeader))
261  return ERROR_INVALID_MESSAGE;
262 
263  //Point to the NTP response
264  header = (NtpHeader *) context->message;
265 
266  //Debug message
267  TRACE_INFO("NTP response message received (%" PRIuSIZE " bytes)...\r\n",
268  length);
269 
270  //Dump the contents of the NTP packet for debugging purpose
271  ntpDumpPacket(header, length);
272 
273  //The server reply should be discarded if the VN field is 0
274  if(header->vn == 0)
275  return ERROR_INVALID_MESSAGE;
276 
277  //The server reply should be discarded if the Transmit Timestamp fields is 0
278  if(header->transmitTimestamp.seconds == 0 &&
279  header->transmitTimestamp.fraction == 0)
280  {
281  return ERROR_INVALID_MESSAGE;
282  }
283 
284  //The server reply should be discarded if the Mode field is not 4 (unicast)
285  //or 5 (broadcast)
286  if(header->mode != NTP_MODE_SERVER && header->mode != NTP_MODE_BROADCAST)
287  return ERROR_INVALID_MESSAGE;
288 
289  //The Originate Timestamp in the server reply should match the Transmit
290  //Timestamp used in the client request
291  if(header->originateTimestamp.seconds != 0)
292  return ERROR_INVALID_MESSAGE;
293 
294  if(header->originateTimestamp.fraction != htonl(context->retransmitStartTime))
295  return ERROR_INVALID_MESSAGE;
296 
297  //The NTP response message is acceptable
298  return NO_ERROR;
299 }
300 
301 
302 /**
303  * @brief Parse NTP server's response
304  * @param[in] context Pointer to the SNTP client context
305  * @param[out] timestamp Pointer to the NTP timestamp
306  * @return Error code
307  **/
308 
310  NtpTimestamp *timestamp)
311 {
312  NtpHeader *header;
313 
314  //Ensure the NTP packet is valid
315  if(context->messageLen < sizeof(NtpHeader))
316  return ERROR_INVALID_LENGTH;
317 
318  //Point to the NTP response
319  header = (NtpHeader *) context->message;
320 
321  //Clear kiss code
322  context->kissCode = 0;
323 
324  //Kiss-of-Death packet received?
325  if(header->stratum == 0)
326  {
327  //The kiss code is encoded in four-character ASCII strings left
328  //justified and zero filled
329  context->kissCode = htonl(header->referenceId);
330 
331  //An SNTP client should stop sending to a particular server if that
332  //server returns a reply with a Stratum field of 0
333  return ERROR_REQUEST_REJECTED;
334  }
335 
336  //Extract NTP timestamp from server's response
337  timestamp->seconds = ntohl(header->transmitTimestamp.seconds);
338  timestamp->fraction = ntohl(header->transmitTimestamp.fraction);
339 
340  //Successful processing
341  return NO_ERROR;
342 }
343 
344 
345 /**
346  * @brief Determine whether a timeout error has occurred
347  * @param[in] context Pointer to the SNTP client context
348  * @return Error code
349  **/
350 
352 {
353  error_t error;
354  systime_t time;
355 
356  //Get current time
357  time = osGetSystemTime();
358 
359  //Check whether the timeout has elapsed
360  if(timeCompare(time, context->startTime + context->timeout) >= 0)
361  {
362  //Report a timeout error
363  error = ERROR_TIMEOUT;
364  }
365  else if(timeCompare(time, context->retransmitStartTime + context->retransmitTimeout) >= 0)
366  {
367  //The timeout value is doubled for each subsequent retransmission
368  context->retransmitTimeout = MIN(context->retransmitTimeout * 2,
370 
371  //Retransmit NTP request
372  context->state = SNTP_CLIENT_STATE_SENDING;
373 
374  //Continue processing
375  error = NO_ERROR;
376  }
377  else
378  {
379 #if (NET_RTOS_SUPPORT == ENABLED)
380  //Report a timeout error
381  error = ERROR_TIMEOUT;
382 #else
383  //The operation would block
384  error = ERROR_WOULD_BLOCK;
385 #endif
386  }
387 
388  //Return status code
389  return error;
390 }
391 
392 #endif
uint8_t message[NTP_MAX_MSG_SIZE]
Buffer that holds the NTP request/response.
Definition: sntp_client.h:113
size_t messageLen
Length of the NTP message, in bytes.
Definition: sntp_client.h:114
@ SOCKET_IP_PROTO_UDP
Definition: socket.h:108
void ntpDumpPacket(const NtpHeader *packet, size_t length)
Dump NTP packet for debugging purpose.
Definition: ntp_debug.c:108
error_t socketBind(Socket *socket, const IpAddr *localIpAddr, uint16_t localPort)
Associate a local address with a socket.
Definition: socket.c:1321
@ SNTP_CLIENT_STATE_COMPLETE
Definition: sntp_client.h:93
@ ERROR_WOULD_BLOCK
Definition: error.h:96
IP network address.
Definition: ip.h:90
#define SNTP_CLIENT_SRC_PORT
Definition: sntp_client.h:68
NtpTimestamp
Definition: ntp_common.h:185
uint8_t message[]
Definition: chap.h:154
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:2071
@ SOCKET_TYPE_DGRAM
Definition: socket.h:93
void sntpClientCloseConnection(SntpClientContext *context)
Close UDP connection.
@ NTP_MODE_SERVER
Definition: ntp_common.h:94
@ ERROR_INVALID_MESSAGE
Definition: error.h:105
systime_t retransmitStartTime
Time at which the last request was sent.
Definition: sntp_client.h:111
#define timeCompare(t1, t2)
Definition: os_port.h:40
error_t sntpClientOpenConnection(SntpClientContext *context)
Open UDP connection.
Socket * socket
Underlying socket.
Definition: sntp_client.h:109
IpAddr serverIpAddr
NTP server address.
Definition: sntp_client.h:106
@ NTP_MODE_BROADCAST
Definition: ntp_common.h:95
@ ERROR_OPEN_FAILED
Definition: error.h:75
systime_t startTime
Request start time.
Definition: sntp_client.h:110
SNTP client context.
Definition: sntp_client.h:102
const IpAddr IP_ADDR_ANY
Definition: ip.c:53
#define htonl(value)
Definition: cpu_endian.h:414
SntpClientState state
SNTP client state.
Definition: sntp_client.h:103
error_t
Error codes.
Definition: error.h:43
Data logging functions for debugging purpose (NTP)
error_t sntpClientCheckResponse(SntpClientContext *context, const IpAddr *ipAddr, uint16_t port, const uint8_t *message, size_t length)
Check whether the NTP response is valid.
@ SNTP_CLIENT_STATE_RECEIVING
Definition: sntp_client.h:92
@ ERROR_INVALID_LENGTH
Definition: error.h:111
error_t socketReceiveFrom(Socket *socket, IpAddr *srcIpAddr, uint16_t *srcPort, void *data, size_t size, size_t *received, uint_t flags)
Receive a datagram from a connectionless socket.
Definition: socket.c:1723
uint32_t t2
#define TRACE_INFO(...)
Definition: debug.h:105
uint8_t length
Definition: tcp.h:375
Socket * socketOpen(uint_t type, uint_t protocol)
Create a socket (UDP or TCP)
Definition: socket.c:125
#define MIN(a, b)
Definition: os_port.h:63
#define NTP_MAX_MSG_SIZE
Definition: ntp_common.h:40
error_t sntpClientReceiveResponse(SntpClientContext *context)
Wait for NTP server's response.
systime_t timeout
Timeout value.
Definition: sntp_client.h:108
#define socketBindToInterface
Definition: net_legacy.h:193
error_t sntpClientParseResponse(SntpClientContext *context, NtpTimestamp *timestamp)
Parse NTP server's response.
uint32_t systime_t
System time.
uint16_t port
Definition: dns_common.h:270
error_t sntpClientCheckTimeout(SntpClientContext *context)
Determine whether a timeout error has occurred.
@ ERROR_TIMEOUT
Definition: error.h:95
@ NTP_MODE_CLIENT
Definition: ntp_common.h:93
uint32_t time
uint32_t t1
NtpHeader
Definition: ntp_common.h:214
error_t sntpClientSendRequest(SntpClientContext *context)
Send request to the NTP server.
uint32_t kissCode
Kiss code.
Definition: sntp_client.h:115
@ SNTP_CLIENT_STATE_SENDING
Definition: sntp_client.h:91
error_t socketSendTo(Socket *socket, const IpAddr *destIpAddr, uint16_t destPort, const void *data, size_t length, size_t *written, uint_t flags)
Send a datagram to a specific destination.
Definition: socket.c:1512
Ipv4Addr ipAddr
Definition: ipcp.h:105
NtpVersion version
NTP protocol version.
Definition: sntp_client.h:104
systime_t retransmitTimeout
Retransmission timeout.
Definition: sntp_client.h:112
NetInterface * interface
Underlying network interface.
Definition: sntp_client.h:105
@ ERROR_REQUEST_REJECTED
Definition: error.h:273
#define PRIuSIZE
#define osMemset(p, value, length)
Definition: os_port.h:138
TCP/IP stack core.
SNTP client (Simple Network Time Protocol)
error_t socketSetTimeout(Socket *socket, systime_t timeout)
Set timeout value for blocking operations.
Definition: socket.c:148
#define ntohl(value)
Definition: cpu_endian.h:422
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
#define SNTP_CLIENT_MAX_RETRANSMIT_TIMEOUT
Definition: sntp_client.h:61
uint16_t serverPort
NTP server port.
Definition: sntp_client.h:107
systime_t osGetSystemTime(void)
Retrieve system time.
Helper functions for SNTP client.