coreSNTP v1.1.0
Client library for synchronizing device time with internet time using Simple Network Time Protocol (SNTP)
core_sntp_client.h File Reference

API of an SNTPv4 client library that can send time requests and receive time response to/from SNTP/NTP servers. The library follows the Best Practices suggested in the the SNTPv4 specification, RFC 4330. The library can be used to run an SNTP client in a dedicated deamon task to periodically synchronize time from the Internet. More...

#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include "core_sntp_serializer.h"
#include "core_sntp_config.h"
#include "core_sntp_config_defaults.h"

Go to the source code of this file.

Data Structures

struct  SntpServerInfo_t
 Structure representing information for a time server. More...
 
struct  UdpTransportInterface_t
 Struct representing the UDP transport interface for user-defined functions that coreSNTP library depends on for performing read/write network operations. More...
 
struct  SntpAuthenticationInterface_t
 Struct representing the authentication interface for securely communicating with time servers. More...
 
struct  SntpContext_t
 Structure for a context that stores state for managing a long-running SNTP client that periodically polls time and synchronizes system clock. More...
 

Macros

#define SNTP_DEFAULT_SERVER_PORT   ( 123U )
 The default UDP port supported by SNTP/NTP servers for client-server communication. More...
 

Typedefs

typedef bool(* SntpResolveDns_t) (const SntpServerInfo_t *pServerAddr, uint32_t *pIpV4Addr)
 Interface for user-defined function to resolve time server domain-name to an IPv4 address. The SNTP client library attempts to resolve the DNS of the time-server being used every time the Sntp_SendTimeRequest API is called. More...
 
typedef void(* SntpGetTime_t) (SntpTimestamp_t *pCurrentTime)
 Interface for user-defined function to obtain the current system time in SNTP timestamp format. More...
 
typedef void(* SntpSetTime_t) (const SntpServerInfo_t *pTimeServer, const SntpTimestamp_t *pServerTime, int64_t clockOffsetMs, SntpLeapSecondInfo_t leapSecondInfo)
 Interface for user-defined function to update the system clock time so that it is synchronized the time server used for getting current time. More...
 
typedef struct NetworkContext NetworkContext_t
 A user-defined type for context that is passed to the transport interface functions. It MUST be defined by the user to use the library. It is of incomplete type to allow user to define to the needs of their transport interface implementation.
 
typedef int32_t(* UdpTransportSendTo_t) (NetworkContext_t *pNetworkContext, uint32_t serverAddr, uint16_t serverPort, const void *pBuffer, uint16_t bytesToSend)
 Interface for user-defined function to send time request as a single datagram to server on the network over User Datagram Protocol (UDP). More...
 
typedef int32_t(* UdpTransportRecvFrom_t) (NetworkContext_t *pNetworkContext, uint32_t serverAddr, uint16_t serverPort, void *pBuffer, uint16_t bytesToRecv)
 Interface for user-defined function to receive the server response, to a time request (sent through the UdpTransportSendTo_t function), from the network over User Datagram Protocol (UDP). More...
 
typedef struct SntpAuthContext SntpAuthContext_t
 A user-defined type for context that is passed to the authentication interface functions. It MUST be defined by the user to use the library. It is of incomplete type to allow user to defined to the the needs of their authentication interface implementation.
 
typedef SntpStatus_t(* SntpGenerateAuthCode_t) (SntpAuthContext_t *pContext, const SntpServerInfo_t *pTimeServer, void *pBuffer, size_t bufferSize, uint16_t *pAuthCodeSize)
 Interface for user-defined function to generate and append authentication code in an SNTP request buffer for the SNTP client to be authenticated by the time server, if a security mechanism is used. More...
 
typedef SntpStatus_t(* SntpValidateServerAuth_t) (SntpAuthContext_t *pContext, const SntpServerInfo_t *pTimeServer, const void *pResponseData, uint16_t responseSize)
 Interface for user-defined function to authenticate server by validating the authentication code present in its SNTP response to a time request, if a security mechanism is supported by the server. More...
 

Functions

SntpStatus_t Sntp_Init (SntpContext_t *pContext, const SntpServerInfo_t *pTimeServers, size_t numOfServers, uint32_t serverResponseTimeoutMs, uint8_t *pNetworkBuffer, size_t bufferSize, SntpResolveDns_t resolveDnsFunc, SntpGetTime_t getSystemTimeFunc, SntpSetTime_t setSystemTimeFunc, const UdpTransportInterface_t *pTransportIntf, const SntpAuthenticationInterface_t *pAuthIntf)
 Initializes a context for SNTP client communication with SNTP/NTP servers. More...
 
SntpStatus_t Sntp_SendTimeRequest (SntpContext_t *pContext, uint32_t randomNumber, uint32_t blockTimeMs)
 Sends a request for time from the currently configured server (in the context). If the user has provided an authentication interface, the client authentication code is appended to the request before sending over the network by calling the SntpGenerateAuthCode_t function of the SntpAuthenticationInterface_t. More...
 
SntpStatus_t Sntp_ReceiveTimeResponse (SntpContext_t *pContext, uint32_t blockTimeMs)
 Receives a time response from the server that has been requested for time with the Sntp_SendTimeRequest API function. Once an accepted response containing time from server is received, this function calls the user-defined SntpSetTime_t function to update the system time. More...
 
const char * Sntp_StatusToStr (SntpStatus_t status)
 Converts SntpStatus_t to its equivalent string. More...
 

Detailed Description

API of an SNTPv4 client library that can send time requests and receive time response to/from SNTP/NTP servers. The library follows the Best Practices suggested in the the SNTPv4 specification, RFC 4330. The library can be used to run an SNTP client in a dedicated deamon task to periodically synchronize time from the Internet.

Function Documentation

◆ Sntp_Init()

SntpStatus_t Sntp_Init ( SntpContext_t pContext,
const SntpServerInfo_t pTimeServers,
size_t  numOfServers,
uint32_t  serverResponseTimeoutMs,
uint8_t *  pNetworkBuffer,
size_t  bufferSize,
SntpResolveDns_t  resolveDnsFunc,
SntpGetTime_t  getSystemTimeFunc,
SntpSetTime_t  setSystemTimeFunc,
const UdpTransportInterface_t pTransportIntf,
const SntpAuthenticationInterface_t pAuthIntf 
)

Initializes a context for SNTP client communication with SNTP/NTP servers.

Parameters
[out]pContextThe user-supplied memory for the context that will be initialized to represent an SNTP client.
[in]pTimeServersThe list of decreasing order of priority of time servers that should be used by the SNTP client. This list MUST stay in scope for all the time of use of the context.
[in]numOfServersThe number of servers in the list, pTimeServers.
[in]serverResponseTimeoutMsThe timeout duration (in milliseconds) for receiving server response for time requests. The same timeout value is used for each server in the pTimeServers list.
[in]pNetworkBufferThe user-supplied memory that will be used for storing network data for SNTP client-server communication. The buffer MUST stay in scope for all the time of use of the context.
[in]bufferSizeThe size of the passed buffer pNetworkBuffer. The buffer SHOULD be appropriately sized for storing an entire SNTP packet which includes both SNTP_PACKET_BASE_SIZE bytes of standard SNTP packet size, and space for authentication data, if security mechanism is used to communicate with any of the time servers configured for use.
[in]resolveDnsFuncThe user-defined function for DNS resolution of time server.
[in]getSystemTimeFuncThe user-defined function for querying system time.
[in]setSystemTimeFuncThe user-defined function for correcting system time for every successful time response received from a server.
[in]pTransportIntfThe user-defined function for performing network send/recv operations over UDP.
[in]pAuthIntfThe user-defined interface for generating client authentication in SNTP requests and authenticating servers in SNTP responses, if security mechanism is used in SNTP communication with server(s). If security mechanism is not used in communication with any of the configured servers (in pTimeServers), then the SntpAuthenticationInterface_t does not need to be defined and this parameter can be NULL.
Returns
This function returns one of the following:

◆ Sntp_SendTimeRequest()

SntpStatus_t Sntp_SendTimeRequest ( SntpContext_t pContext,
uint32_t  randomNumber,
uint32_t  blockTimeMs 
)

Sends a request for time from the currently configured server (in the context). If the user has provided an authentication interface, the client authentication code is appended to the request before sending over the network by calling the SntpGenerateAuthCode_t function of the SntpAuthenticationInterface_t.

Note
This function will ONLY send a request if there is a server available in the configured list that has not rejected an earlier request for time. This adheres to the Best Practice functionality specified in Section 10 Point 8 of SNTPv4 specification.
Parameters
[in]pContextThe context representing an SNTPv4 client.
[in]randomNumberA random number serializing the SNTP request packet to protect against spoofing attacks by attackers that are off the network path of the SNTP client-server communication. This mechanism is suggested by SNTPv4 specification in RFC 4330 Section 3.
[in]blockTimeMsThe maximum duration of time (in milliseconds) the function will block on attempting to send time request to the server over the network. If a zero block time value is provided, then the function will attempt to send the packet ONLY once.
Note
It is RECOMMENDED that a True Random Number Generator is used to generate the random number by using a hardware module, like Hardware Security Module (HSM), Secure Element, etc, as the entropy source.
Returns
The API function returns one of the following:
  • SntpSuccess if a time request is successfully sent to the currently configured time server in the context.
  • SntpErrorBadParameter if an invalid context is passed to the function.
  • SntpErrorContextNotInitialized if an uninitialized or invalid context is passed to the function.
  • SntpErrorDnsFailure if there is failure in the user-defined function for DNS resolution of the time server.
  • SntpErrorNetworkFailure if the SNTP request could not be sent over the network through the user-defined transport interface.
  • SntpErrorAuthFailure if there was a failure in generating the client authentication code in the user-defined authentication interface.
  • SntpErrorSendTimeout if the time request packet could not be sent over the network for the entire blockTimeMs duration.

◆ Sntp_ReceiveTimeResponse()

SntpStatus_t Sntp_ReceiveTimeResponse ( SntpContext_t pContext,
uint32_t  blockTimeMs 
)

Receives a time response from the server that has been requested for time with the Sntp_SendTimeRequest API function. Once an accepted response containing time from server is received, this function calls the user-defined SntpSetTime_t function to update the system time.

Note
If the user has provided an authentication interface to the client (through Sntp_Init), the server response is authenticated by calling the SntpValidateServerAuth_t function of the SntpAuthenticationInterface_t interface.
On receiving a successful server response containing server time, this API calculates the clock offset value of the system clock relative to the server before calling the user-defined SntpSetTime_t function for updating the system time.
For correct calculation of clock-offset, the server and client times MUST be within ~68 years (or 2^31 seconds) of each other. In the special case when the server and client times are exactly 2^31 seconds apart, the library ASSUMES that the server time is ahead of the client time, and returns the positive clock-offset value of INT32_MAX seconds.
This API will rotate the server of use in the library for the next time request (through the Sntp_SendTimeRequest) if either of following events occur:
  • The server has responded with a rejection for the time request. OR
  • The server response wait has timed out. If all the servers configured in the context have been used, the API will rotate server for time query back to the first server in the list which will be used in next time request.
Parameters
[in]pContextThe context representing an SNTPv4 client.
[in]blockTimeMsThe maximum duration of time (in milliseconds) the function will block on receiving a response from the server unless either the response is received OR a response timeout occurs.
Note
This function can be called multiple times with zero or small blocking times to poll whether server response is received until either the response response is received from the server OR a response timeout has occurred.
Returns
This API functions returns one of the following:

◆ Sntp_StatusToStr()

const char * Sntp_StatusToStr ( SntpStatus_t  status)

Converts SntpStatus_t to its equivalent string.

Note
The returned string MUST NOT be modified.
Parameters
[in]statusThe status to convert to a string.
Returns
The string representation of the status code.