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