1 /*
2 * libwebsockets - small server side websockets and web server implementation
3 *
4 * Copyright (C) 2010 - 2020 Andy Green <andy@warmcat.com>
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 * IN THE SOFTWARE.
23 */
24
25#include "private-lib-core.h"
26
27#define LWSNTPC_LI_NONE			0
28#define LWSNTPC_VN_3			3
29#define LWSNTPC_MODE_CLIENT		3
30
31struct vhd_ntpc {
32	struct lws_context		*context;
33	struct lws_vhost		*vhost;
34	const struct lws_protocols	*protocol;
35	lws_sorted_usec_list_t		sul_conn;
36	lws_sorted_usec_list_t		sul_write; /* track write retries */
37	const char			*ntp_server_ads;
38	struct lws			*wsi_udp;
39	uint16_t			retry_count_conn;
40	uint16_t			retry_count_write;
41
42	char				set_time;
43};
44
45/*
46 * Without a valid ntp we won't be able to do anything requiring client tls.
47 *
48 * We have our own outer backoff scheme that just keeps retrying dns lookup
49 * and the transaction forever.
50 */
51
52static const uint32_t botable[] =
53		{ 300, 500, 650, 800, 800, 900, 1000, 1100, 1500 };
54static const lws_retry_bo_t bo = {
55	botable, LWS_ARRAY_SIZE(botable), LWS_RETRY_CONCEAL_ALWAYS, 0, 0, 20 };
56
57/*
58 * Once we resolved the remote server (implying we should have network),
59 * we use a different policy on the wsi itself that gives it a few tries before
60 * failing the wsi and using to outer retry policy to get dns to a different
61 * server in the pool and try fresh
62 */
63
64static const uint32_t botable2[] = { 1000, 1250, 5000 /* in case dog slow */ };
65static const lws_retry_bo_t bo2 = {
66	botable2, LWS_ARRAY_SIZE(botable2), LWS_ARRAY_SIZE(botable2),
67	/* don't conceal after the last table entry */ 0, 0, 20 };
68
69static void
70lws_ntpc_retry_conn(struct lws_sorted_usec_list *sul)
71{
72	struct vhd_ntpc *v = lws_container_of(sul, struct vhd_ntpc, sul_conn);
73
74	lwsl_debug("%s: wsi_udp: %s\n", __func__, lws_wsi_tag(v->wsi_udp));
75
76	if (v->wsi_udp || !lws_dll2_is_detached(&v->sul_conn.list))
77		return;
78
79	/* create the UDP socket aimed at the server */
80
81	lwsl_notice("%s: server %s\n", __func__, v->ntp_server_ads);
82
83	v->retry_count_write = 0;
84	v->wsi_udp = lws_create_adopt_udp(v->vhost, v->ntp_server_ads, 123, 0,
85					  v->protocol->name, NULL, NULL, NULL,
86					  &bo2, "ntpclient");
87	lwsl_debug("%s: created wsi_udp: %s\n", __func__, lws_wsi_tag(v->wsi_udp));
88	if (!v->wsi_udp) {
89		lwsl_err("%s: unable to create udp skt\n", __func__);
90
91		lws_retry_sul_schedule(v->context, 0, &v->sul_conn, &bo,
92				       lws_ntpc_retry_conn, &v->retry_count_conn);
93	}
94}
95
96static void
97lws_ntpc_retry_write(struct lws_sorted_usec_list *sul)
98{
99	struct vhd_ntpc *v = lws_container_of(sul, struct vhd_ntpc, sul_write);
100
101	lwsl_debug("%s\n", __func__);
102
103	if (v && v->wsi_udp)
104		lws_callback_on_writable(v->wsi_udp);
105}
106
107static int
108callback_ntpc(struct lws *wsi, enum lws_callback_reasons reason, void *user,
109	      void *in, size_t len)
110{
111	struct vhd_ntpc *v = (struct vhd_ntpc *)
112			lws_protocol_vh_priv_get(lws_get_vhost(wsi),
113						 lws_get_protocol(wsi));
114	uint8_t pkt[LWS_PRE + 48];
115	struct timeval t1;
116	int64_t delta_us;
117	uint64_t ns;
118
119	switch (reason) {
120
121	case LWS_CALLBACK_PROTOCOL_INIT: /* per vhost */
122		if (v)
123			break;
124
125		lwsl_debug("%s: LWS_CALLBACK_PROTOCOL_INIT:\n", __func__);
126		lws_protocol_vh_priv_zalloc(wsi->a.vhost, wsi->a.protocol,
127					    sizeof(*v));
128		v = (struct vhd_ntpc *)lws_protocol_vh_priv_get(wsi->a.vhost,
129								wsi->a.protocol);
130		v->context = lws_get_context(wsi);
131		v->vhost = lws_get_vhost(wsi);
132		v->protocol = lws_get_protocol(wsi);
133
134		v->context->ntpclient_priv = v;
135
136		if (!lws_system_get_ops(wsi->a.context) ||
137		    !lws_system_get_ops(wsi->a.context)->set_clock) {
138#if !defined(LWS_ESP_PLATFORM)
139			lwsl_err("%s: set up system ops for set_clock\n",
140					__func__);
141#endif
142
143		//	return -1;
144		}
145
146		/* register our lws_system notifier */
147
148		v->ntp_server_ads = "pool.ntp.org";
149		lws_plat_ntpclient_config(v->context);
150		lws_system_blob_get_single_ptr(lws_system_get_blob(
151				v->context, LWS_SYSBLOB_TYPE_NTP_SERVER, 0),
152				(const uint8_t **)&v->ntp_server_ads);
153		if (!v->ntp_server_ads || v->ntp_server_ads[0] == '\0')
154			v->ntp_server_ads = "pool.ntp.org";
155
156		lwsl_notice("%s: using ntp server %s\n", __func__,
157			  v->ntp_server_ads);
158		break;
159
160	case LWS_CALLBACK_PROTOCOL_DESTROY: /* per vhost */
161		if (!v)
162			break;
163		if (v->wsi_udp)
164			lws_set_timeout(v->wsi_udp, 1, LWS_TO_KILL_ASYNC);
165		v->wsi_udp = NULL;
166		goto cancel_conn_timer;
167
168	/* callbacks related to raw socket descriptor */
169
170        case LWS_CALLBACK_RAW_ADOPT:
171		lwsl_debug("%s: LWS_CALLBACK_RAW_ADOPT\n", __func__);
172		lws_callback_on_writable(wsi);
173		break;
174
175        case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
176		lwsl_info("%s: CONNECTION_ERROR\n", __func__);
177		goto do_close;
178
179	case LWS_CALLBACK_RAW_CLOSE:
180		lwsl_debug("%s: LWS_CALLBACK_RAW_CLOSE\n", __func__);
181do_close:
182		v->wsi_udp = NULL;
183
184		/* cancel any pending write retry */
185		lws_sul_cancel(&v->sul_write);
186
187		if (v->set_time)
188			goto cancel_conn_timer;
189
190		lws_retry_sul_schedule(v->context, 0, &v->sul_conn, &bo,
191				       lws_ntpc_retry_conn,
192				       &v->retry_count_conn);
193		break;
194
195	case LWS_CALLBACK_RAW_RX:
196
197		if (len != 48)
198			return 0; /* ignore it */
199
200		/*
201		 * First get the seconds, corrected for the ntp epoch of 1900
202		 * vs the unix epoch of 1970.  Then shift the seconds up by 1bn
203		 * and add in the ns
204		 */
205
206		ns = (uint64_t)lws_ser_ru32be(((uint8_t *)in) + 40) - (uint64_t)2208988800;
207		ns = (ns * 1000000000) + lws_ser_ru32be(((uint8_t *)in) + 44);
208
209		/*
210		 * Compute the step
211		 */
212
213		gettimeofday(&t1, NULL);
214
215		delta_us = ((int64_t)ns / 1000) -
216				((t1.tv_sec * LWS_US_PER_SEC) + t1.tv_usec);
217
218		lwsl_notice("%s: Unix time: %llu, step: %lldus\n", __func__,
219				(unsigned long long)ns / 1000000000,
220				(long long)delta_us);
221
222#if defined(LWS_PLAT_FREERTOS)
223		{
224			struct timeval t;
225
226			t.tv_sec = (unsigned long long)ns / 1000000000;
227			t.tv_usec = (ns % 1000000000) / 1000;
228
229			lws_sul_nonmonotonic_adjust(wsi->a.context, delta_us);
230
231			settimeofday(&t, NULL);
232		}
233#endif
234		if (lws_system_get_ops(wsi->a.context) &&
235		    lws_system_get_ops(wsi->a.context)->set_clock)
236			lws_system_get_ops(wsi->a.context)->set_clock((int64_t)ns / 1000);
237
238		v->set_time = 1;
239		lws_state_transition_steps(&wsi->a.context->mgr_system,
240					   LWS_SYSTATE_OPERATIONAL);
241
242		/* close the wsi */
243		return -1;
244
245	case LWS_CALLBACK_RAW_WRITEABLE:
246
247		/*
248		 * UDP is not reliable, it can be locally dropped, or dropped
249		 * by any intermediary or the remote peer.  So even though we
250		 * will do the write in a moment, we schedule another request
251		 * for rewrite according to the wsi retry policy.
252		 *
253		 * If the result came before, we'll cancel it in the close flow.
254		 *
255		 * If we have already reached the end of our concealed retries
256		 * in the policy, just close without another write.
257		 */
258		if (lws_dll2_is_detached(&v->sul_write.list) &&
259		    lws_retry_sul_schedule_retry_wsi(wsi, &v->sul_write,
260						     lws_ntpc_retry_write,
261						     &v->retry_count_write)) {
262			/* we have reached the end of our concealed retries */
263			lwsl_warn("%s: concealed retries done, failing\n", __func__);
264			goto retry_conn;
265		}
266
267		memset(pkt + LWS_PRE, 0, sizeof(pkt) - LWS_PRE);
268		pkt[LWS_PRE] = (LWSNTPC_LI_NONE << 6) |
269			       (LWSNTPC_VN_3 << 3) |
270			       (LWSNTPC_MODE_CLIENT << 0);
271
272		if (lws_write(wsi, pkt + LWS_PRE, sizeof(pkt) - LWS_PRE, 0) ==
273						  sizeof(pkt) - LWS_PRE)
274			break;
275
276		lwsl_err("%s: Failed to write ntp client req\n", __func__);
277
278retry_conn:
279		lws_retry_sul_schedule(wsi->a.context, 0, &v->sul_conn, &bo,
280				       lws_ntpc_retry_conn,
281				       &v->retry_count_conn);
282
283		return -1;
284
285	default:
286		break;
287	}
288
289	return 0;
290
291
292cancel_conn_timer:
293	lws_sul_cancel(&v->sul_conn);
294
295	return 0;
296}
297
298void
299lws_ntpc_trigger(struct lws_context *ctx)
300{
301	struct vhd_ntpc *v = (struct vhd_ntpc *)ctx->ntpclient_priv;
302
303	lwsl_notice("%s\n", __func__);
304	v->retry_count_conn = 0;
305	lws_ntpc_retry_conn(&v->sul_conn);
306}
307
308struct lws_protocols lws_system_protocol_ntpc =
309	{ "lws-ntpclient", callback_ntpc, 0, 128, 0, NULL, 0 };
310
311