1 /*
2  * Copyright (c) 2017 Linaro Limited
3  * Copyright (c) 2019 Intel Corporation
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #ifndef ZEPHYR_INCLUDE_NET_SNTP_H_
9 #define ZEPHYR_INCLUDE_NET_SNTP_H_
10 
11 #include <zephyr/net/socket.h>
12 
13 #ifdef __cplusplus
14 extern "C" {
15 #endif
16 
17 /**
18  * @brief Simple Network Time Protocol API
19  * @defgroup sntp SNTP
20  * @ingroup networking
21  * @{
22  */
23 
24 /** SNTP context */
25 struct sntp_ctx {
26 	struct {
27 		struct zsock_pollfd fds[1];
28 		int nfds;
29 		int fd;
30 	} sock;
31 
32 	/** Timestamp when the request was sent from client to server.
33 	 *  This is used to check if the originated timestamp in the server
34 	 *  reply matches the one in client request.
35 	 */
36 	uint32_t expected_orig_ts;
37 };
38 
39 /** Time as returned by SNTP API, fractional seconds since 1 Jan 1970 */
40 struct sntp_time {
41 	uint64_t seconds;
42 	uint32_t fraction;
43 };
44 
45 /**
46  * @brief Initialize SNTP context
47  *
48  * @param ctx Address of sntp context.
49  * @param addr IP address of NTP/SNTP server.
50  * @param addr_len IP address length of NTP/SNTP server.
51  *
52  * @return 0 if ok, <0 if error.
53  */
54 int sntp_init(struct sntp_ctx *ctx, struct sockaddr *addr,
55 	      socklen_t addr_len);
56 
57 /**
58  * @brief Perform SNTP query
59  *
60  * @param ctx Address of sntp context.
61  * @param timeout Timeout of waiting for sntp response (in milliseconds).
62  * @param time Timestamp including integer and fractional seconds since
63  * 1 Jan 1970 (output).
64  *
65  * @return 0 if ok, <0 if error (-ETIMEDOUT if timeout).
66  */
67 int sntp_query(struct sntp_ctx *ctx, uint32_t timeout,
68 	       struct sntp_time *time);
69 
70 /**
71  * @brief Release SNTP context
72  *
73  * @param ctx Address of sntp context.
74  */
75 void sntp_close(struct sntp_ctx *ctx);
76 
77 /**
78  * @brief Convenience function to query SNTP in one-shot fashion
79  *
80  * Convenience wrapper which calls getaddrinfo(), sntp_init(),
81  * sntp_query(), and sntp_close().
82  *
83  * @param server Address of server in format addr[:port]
84  * @param timeout Query timeout
85  * @param time Timestamp including integer and fractional seconds since
86  * 1 Jan 1970 (output).
87  *
88  * @return 0 if ok, <0 if error (-ETIMEDOUT if timeout).
89  */
90 int sntp_simple(const char *server, uint32_t timeout,
91 		struct sntp_time *time);
92 
93 #ifdef __cplusplus
94 }
95 #endif
96 
97 /**
98  * @}
99  */
100 
101 #endif
102