1 /*
2 * libwebsockets - small server side websockets and web server implementation
3 *
4 * Copyright (C) 2010 - 2019 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
31 struct 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 lws_state_notify_link_t notify_link;
38 const char *ntp_server_ads;
39 struct lws *wsi_udp;
40 uint16_t retry_count_conn;
41 uint16_t retry_count_write;
42
43 char set_time;
44 };
45
46 /*
47 * Without a valid ntp we won't be able to do anything requiring client tls.
48 *
49 * We have our own outer backoff scheme that just keeps retrying dns lookup
50 * and the transaction forever.
51 */
52
53 static const uint32_t botable[] = { 1000, 1250, 1500, 2000, 3000 };
54 static 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
64 static const uint32_t botable2[] = { 1000, 1250, 5000 /* in case dog slow */ };
65 static 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
69 static void
lws_ntpc_retry_conn(struct lws_sorted_usec_list * sul)70 lws_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: %p\n", __func__, 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_debug("%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);
87 lwsl_debug("%s: created wsi_udp: %p\n", __func__, 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
96 static void
lws_ntpc_retry_write(struct lws_sorted_usec_list * sul)97 lws_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
107 static int
lws_sys_ntpc_notify_cb(lws_state_manager_t * mgr,lws_state_notify_link_t * l,int current,int target)108 lws_sys_ntpc_notify_cb(lws_state_manager_t *mgr, lws_state_notify_link_t *l,
109 int current, int target)
110 {
111 struct vhd_ntpc *v = lws_container_of(l, struct vhd_ntpc, notify_link);
112
113 if (target != LWS_SYSTATE_TIME_VALID || v->set_time)
114 return 0;
115
116 /* it's trying to do it ever since the protocol / vhost was set up */
117
118 return 1;
119 }
120
121 static int
callback_ntpc(struct lws * wsi,enum lws_callback_reasons reason,void * user,void * in,size_t len)122 callback_ntpc(struct lws *wsi, enum lws_callback_reasons reason, void *user,
123 void *in, size_t len)
124 {
125 struct vhd_ntpc *v = (struct vhd_ntpc *)
126 lws_protocol_vh_priv_get(lws_get_vhost(wsi),
127 lws_get_protocol(wsi));
128 uint8_t pkt[LWS_PRE + 48];
129 uint64_t ns;
130
131 switch (reason) {
132
133 case LWS_CALLBACK_PROTOCOL_INIT: /* per vhost */
134 if (v)
135 break;
136
137 lwsl_debug("%s: LWS_CALLBACK_PROTOCOL_INIT:\n", __func__);
138 lws_protocol_vh_priv_zalloc(wsi->vhost, wsi->protocol,
139 sizeof(*v));
140 v = (struct vhd_ntpc *)lws_protocol_vh_priv_get(wsi->vhost,
141 wsi->protocol);
142 v->context = lws_get_context(wsi);
143 v->vhost = lws_get_vhost(wsi);
144 v->protocol = lws_get_protocol(wsi);
145
146 if (!lws_system_get_ops(wsi->context) ||
147 !lws_system_get_ops(wsi->context)->set_clock) {
148 lwsl_err("%s: set up system ops for set_clock\n",
149 __func__);
150
151 // return -1;
152 }
153
154 /* register our lws_system notifier */
155
156 v->notify_link.notify_cb = lws_sys_ntpc_notify_cb;
157 v->notify_link.name = "ntpclient";
158 lws_state_reg_notifier(&wsi->context->mgr_system, &v->notify_link);
159
160 v->ntp_server_ads = "pool.ntp.org";
161 lws_system_blob_get_single_ptr(lws_system_get_blob(
162 v->context, LWS_SYSBLOB_TYPE_NTP_SERVER, 0),
163 (const uint8_t **)&v->ntp_server_ads);
164
165 lws_ntpc_retry_conn(&v->sul_conn);
166 break;
167
168 case LWS_CALLBACK_PROTOCOL_DESTROY: /* per vhost */
169 if (!v)
170 break;
171 if (v->wsi_udp)
172 lws_set_timeout(v->wsi_udp, 1, LWS_TO_KILL_ASYNC);
173 lws_state_reg_deregister(&v->notify_link);
174 v->wsi_udp = NULL;
175 goto cancel_conn_timer;
176
177 /* callbacks related to raw socket descriptor */
178
179 case LWS_CALLBACK_RAW_ADOPT:
180 lwsl_debug("%s: LWS_CALLBACK_RAW_ADOPT\n", __func__);
181 lws_callback_on_writable(wsi);
182 break;
183
184 case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
185 lwsl_info("%s: CONNECTION_ERROR\n", __func__);
186 goto do_close;
187
188 case LWS_CALLBACK_RAW_CLOSE:
189 lwsl_debug("%s: LWS_CALLBACK_RAW_CLOSE\n", __func__);
190 do_close:
191 v->wsi_udp = NULL;
192
193 /* cancel any pending write retry */
194 lws_sul_schedule(v->context, 0, &v->sul_write, NULL,
195 LWS_SET_TIMER_USEC_CANCEL);
196
197 if (v->set_time)
198 goto cancel_conn_timer;
199
200 lws_retry_sul_schedule(v->context, 0, &v->sul_conn, &bo,
201 lws_ntpc_retry_conn,
202 &v->retry_count_conn);
203 break;
204
205 case LWS_CALLBACK_RAW_RX:
206
207 if (len != 48)
208 return 0; /* ignore it */
209
210 /*
211 * First get the seconds, corrected for the ntp epoch of 1900
212 * vs the unix epoch of 1970. Then shift the seconds up by 1bn
213 * and add in the ns
214 */
215
216 ns = lws_ser_ru32be(((uint8_t *)in) + 40) - 2208988800;
217 ns = (ns * 1000000000) + lws_ser_ru32be(((uint8_t *)in) + 44);
218
219 lwsl_notice("%s: Unix time: %llu\n", __func__,
220 (unsigned long long)ns / 1000000000);
221
222 // lws_system_get_ops(wsi->context)->set_clock(ns / 1000);
223
224 v->set_time = 1;
225 lws_state_transition_steps(&wsi->context->mgr_system,
226 LWS_SYSTATE_OPERATIONAL);
227
228 /* close the wsi */
229 return -1;
230
231 case LWS_CALLBACK_RAW_WRITEABLE:
232
233 /*
234 * UDP is not reliable, it can be locally dropped, or dropped
235 * by any intermediary or the remote peer. So even though we
236 * will do the write in a moment, we schedule another request
237 * for rewrite according to the wsi retry policy.
238 *
239 * If the result came before, we'll cancel it in the close flow.
240 *
241 * If we have already reached the end of our concealed retries
242 * in the policy, just close without another write.
243 */
244 if (lws_dll2_is_detached(&v->sul_write.list) &&
245 lws_retry_sul_schedule_retry_wsi(wsi, &v->sul_write,
246 lws_ntpc_retry_write,
247 &v->retry_count_write)) {
248 /* we have reached the end of our concealed retries */
249 lwsl_warn("%s: concealed retries done, failing\n", __func__);
250 goto retry_conn;
251 }
252
253 memset(pkt + LWS_PRE, 0, sizeof(pkt) - LWS_PRE);
254 pkt[LWS_PRE] = (LWSNTPC_LI_NONE << 6) |
255 (LWSNTPC_VN_3 << 3) |
256 (LWSNTPC_MODE_CLIENT << 0);
257
258 if (lws_write(wsi, pkt + LWS_PRE, sizeof(pkt) - LWS_PRE, 0) ==
259 sizeof(pkt) - LWS_PRE)
260 break;
261
262 lwsl_err("%s: Failed to write ntp client req\n", __func__);
263
264 retry_conn:
265 lws_retry_sul_schedule(wsi->context, 0, &v->sul_conn, &bo,
266 lws_ntpc_retry_conn,
267 &v->retry_count_conn);
268
269 return -1;
270
271 default:
272 break;
273 }
274
275 return 0;
276
277
278 cancel_conn_timer:
279 lws_sul_schedule(v->context, 0, &v->sul_conn, NULL,
280 LWS_SET_TIMER_USEC_CANCEL);
281
282 return 0;
283 }
284
285 struct lws_protocols lws_system_protocol_ntpc =
286 { "lws-ntpclient", callback_ntpc, 0, 128, };
287
288