ntpclient.c 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. * libwebsockets - small server side websockets and web server implementation
  3. *
  4. * Copyright (C) 2010 - 2020 Andy Green <[email protected]>
  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. #include "private-lib-core.h"
  25. #define LWSNTPC_LI_NONE 0
  26. #define LWSNTPC_VN_3 3
  27. #define LWSNTPC_MODE_CLIENT 3
  28. struct vhd_ntpc {
  29. struct lws_context *context;
  30. struct lws_vhost *vhost;
  31. const struct lws_protocols *protocol;
  32. lws_sorted_usec_list_t sul_conn;
  33. lws_sorted_usec_list_t sul_write; /* track write retries */
  34. const char *ntp_server_ads;
  35. struct lws *wsi_udp;
  36. uint16_t retry_count_conn;
  37. uint16_t retry_count_write;
  38. char set_time;
  39. };
  40. /*
  41. * Without a valid ntp we won't be able to do anything requiring client tls.
  42. *
  43. * We have our own outer backoff scheme that just keeps retrying dns lookup
  44. * and the transaction forever.
  45. */
  46. static const uint32_t botable[] =
  47. { 300, 500, 650, 800, 800, 900, 1000, 1100, 1500 };
  48. static const lws_retry_bo_t bo = {
  49. botable, LWS_ARRAY_SIZE(botable), LWS_RETRY_CONCEAL_ALWAYS, 0, 0, 20 };
  50. /*
  51. * Once we resolved the remote server (implying we should have network),
  52. * we use a different policy on the wsi itself that gives it a few tries before
  53. * failing the wsi and using to outer retry policy to get dns to a different
  54. * server in the pool and try fresh
  55. */
  56. static const uint32_t botable2[] = { 1000, 1250, 5000 /* in case dog slow */ };
  57. static const lws_retry_bo_t bo2 = {
  58. botable2, LWS_ARRAY_SIZE(botable2), LWS_ARRAY_SIZE(botable2),
  59. /* don't conceal after the last table entry */ 0, 0, 20 };
  60. static void
  61. lws_ntpc_retry_conn(struct lws_sorted_usec_list *sul)
  62. {
  63. struct vhd_ntpc *v = lws_container_of(sul, struct vhd_ntpc, sul_conn);
  64. lwsl_debug("%s: wsi_udp: %p\n", __func__, v->wsi_udp);
  65. if (v->wsi_udp || !lws_dll2_is_detached(&v->sul_conn.list))
  66. return;
  67. /* create the UDP socket aimed at the server */
  68. lwsl_debug("%s: server %s\n", __func__, v->ntp_server_ads);
  69. v->retry_count_write = 0;
  70. v->wsi_udp = lws_create_adopt_udp(v->vhost, v->ntp_server_ads, 123, 0,
  71. v->protocol->name, NULL, NULL, NULL,
  72. &bo2);
  73. lwsl_debug("%s: created wsi_udp: %p\n", __func__, v->wsi_udp);
  74. if (!v->wsi_udp) {
  75. lwsl_err("%s: unable to create udp skt\n", __func__);
  76. lws_retry_sul_schedule(v->context, 0, &v->sul_conn, &bo,
  77. lws_ntpc_retry_conn, &v->retry_count_conn);
  78. }
  79. }
  80. static void
  81. lws_ntpc_retry_write(struct lws_sorted_usec_list *sul)
  82. {
  83. struct vhd_ntpc *v = lws_container_of(sul, struct vhd_ntpc, sul_write);
  84. lwsl_debug("%s\n", __func__);
  85. if (v && v->wsi_udp)
  86. lws_callback_on_writable(v->wsi_udp);
  87. }
  88. static int
  89. callback_ntpc(struct lws *wsi, enum lws_callback_reasons reason, void *user,
  90. void *in, size_t len)
  91. {
  92. struct vhd_ntpc *v = (struct vhd_ntpc *)
  93. lws_protocol_vh_priv_get(lws_get_vhost(wsi),
  94. lws_get_protocol(wsi));
  95. uint8_t pkt[LWS_PRE + 48];
  96. struct timeval t1;
  97. int64_t delta_us;
  98. uint64_t ns;
  99. switch (reason) {
  100. case LWS_CALLBACK_PROTOCOL_INIT: /* per vhost */
  101. if (v)
  102. break;
  103. lwsl_debug("%s: LWS_CALLBACK_PROTOCOL_INIT:\n", __func__);
  104. lws_protocol_vh_priv_zalloc(wsi->a.vhost, wsi->a.protocol,
  105. sizeof(*v));
  106. v = (struct vhd_ntpc *)lws_protocol_vh_priv_get(wsi->a.vhost,
  107. wsi->a.protocol);
  108. v->context = lws_get_context(wsi);
  109. v->vhost = lws_get_vhost(wsi);
  110. v->protocol = lws_get_protocol(wsi);
  111. v->context->ntpclient_priv = v;
  112. if (!lws_system_get_ops(wsi->a.context) ||
  113. !lws_system_get_ops(wsi->a.context)->set_clock) {
  114. #if !defined(LWS_ESP_PLATFORM)
  115. lwsl_err("%s: set up system ops for set_clock\n",
  116. __func__);
  117. #endif
  118. // return -1;
  119. }
  120. /* register our lws_system notifier */
  121. v->ntp_server_ads = "pool.ntp.org";
  122. lws_plat_ntpclient_config(v->context);
  123. lws_system_blob_get_single_ptr(lws_system_get_blob(
  124. v->context, LWS_SYSBLOB_TYPE_NTP_SERVER, 0),
  125. (const uint8_t **)&v->ntp_server_ads);
  126. if (!v->ntp_server_ads || v->ntp_server_ads[0] == '\0')
  127. v->ntp_server_ads = "pool.ntp.org";
  128. lwsl_info("%s: using ntp server %s\n", __func__,
  129. v->ntp_server_ads);
  130. break;
  131. case LWS_CALLBACK_PROTOCOL_DESTROY: /* per vhost */
  132. if (!v)
  133. break;
  134. if (v->wsi_udp)
  135. lws_set_timeout(v->wsi_udp, 1, LWS_TO_KILL_ASYNC);
  136. v->wsi_udp = NULL;
  137. goto cancel_conn_timer;
  138. /* callbacks related to raw socket descriptor */
  139. case LWS_CALLBACK_RAW_ADOPT:
  140. lwsl_debug("%s: LWS_CALLBACK_RAW_ADOPT\n", __func__);
  141. lws_callback_on_writable(wsi);
  142. break;
  143. case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
  144. lwsl_info("%s: CONNECTION_ERROR\n", __func__);
  145. goto do_close;
  146. case LWS_CALLBACK_RAW_CLOSE:
  147. lwsl_debug("%s: LWS_CALLBACK_RAW_CLOSE\n", __func__);
  148. do_close:
  149. v->wsi_udp = NULL;
  150. /* cancel any pending write retry */
  151. lws_sul_cancel(&v->sul_write);
  152. if (v->set_time)
  153. goto cancel_conn_timer;
  154. lws_retry_sul_schedule(v->context, 0, &v->sul_conn, &bo,
  155. lws_ntpc_retry_conn,
  156. &v->retry_count_conn);
  157. break;
  158. case LWS_CALLBACK_RAW_RX:
  159. if (len != 48)
  160. return 0; /* ignore it */
  161. /*
  162. * First get the seconds, corrected for the ntp epoch of 1900
  163. * vs the unix epoch of 1970. Then shift the seconds up by 1bn
  164. * and add in the ns
  165. */
  166. ns = lws_ser_ru32be(((uint8_t *)in) + 40) - 2208988800;
  167. ns = (ns * 1000000000) + lws_ser_ru32be(((uint8_t *)in) + 44);
  168. /*
  169. * Compute the step
  170. */
  171. gettimeofday(&t1, NULL);
  172. delta_us = (ns / 1000) -
  173. ((t1.tv_sec * LWS_US_PER_SEC) + t1.tv_usec);
  174. lwsl_notice("%s: Unix time: %llu, step: %lldus\n", __func__,
  175. (unsigned long long)ns / 1000000000,
  176. (long long)delta_us);
  177. #if defined(LWS_PLAT_FREERTOS)
  178. {
  179. struct timeval t;
  180. t.tv_sec = (unsigned long long)ns / 1000000000;
  181. t.tv_usec = (ns % 1000000000) / 1000;
  182. lws_sul_nonmonotonic_adjust(wsi->a.context, delta_us);
  183. settimeofday(&t, NULL);
  184. }
  185. #endif
  186. if (lws_system_get_ops(wsi->a.context) &&
  187. lws_system_get_ops(wsi->a.context)->set_clock)
  188. lws_system_get_ops(wsi->a.context)->set_clock(ns / 1000);
  189. v->set_time = 1;
  190. lws_state_transition_steps(&wsi->a.context->mgr_system,
  191. LWS_SYSTATE_OPERATIONAL);
  192. /* close the wsi */
  193. return -1;
  194. case LWS_CALLBACK_RAW_WRITEABLE:
  195. /*
  196. * UDP is not reliable, it can be locally dropped, or dropped
  197. * by any intermediary or the remote peer. So even though we
  198. * will do the write in a moment, we schedule another request
  199. * for rewrite according to the wsi retry policy.
  200. *
  201. * If the result came before, we'll cancel it in the close flow.
  202. *
  203. * If we have already reached the end of our concealed retries
  204. * in the policy, just close without another write.
  205. */
  206. if (lws_dll2_is_detached(&v->sul_write.list) &&
  207. lws_retry_sul_schedule_retry_wsi(wsi, &v->sul_write,
  208. lws_ntpc_retry_write,
  209. &v->retry_count_write)) {
  210. /* we have reached the end of our concealed retries */
  211. lwsl_warn("%s: concealed retries done, failing\n", __func__);
  212. goto retry_conn;
  213. }
  214. memset(pkt + LWS_PRE, 0, sizeof(pkt) - LWS_PRE);
  215. pkt[LWS_PRE] = (LWSNTPC_LI_NONE << 6) |
  216. (LWSNTPC_VN_3 << 3) |
  217. (LWSNTPC_MODE_CLIENT << 0);
  218. if (lws_write(wsi, pkt + LWS_PRE, sizeof(pkt) - LWS_PRE, 0) ==
  219. sizeof(pkt) - LWS_PRE)
  220. break;
  221. lwsl_err("%s: Failed to write ntp client req\n", __func__);
  222. retry_conn:
  223. lws_retry_sul_schedule(wsi->a.context, 0, &v->sul_conn, &bo,
  224. lws_ntpc_retry_conn,
  225. &v->retry_count_conn);
  226. return -1;
  227. default:
  228. break;
  229. }
  230. return 0;
  231. cancel_conn_timer:
  232. lws_sul_cancel(&v->sul_conn);
  233. return 0;
  234. }
  235. void
  236. lws_ntpc_trigger(struct lws_context *ctx)
  237. {
  238. struct vhd_ntpc *v = (struct vhd_ntpc *)ctx->ntpclient_priv;
  239. lwsl_notice("%s\n", __func__);
  240. v->retry_count_conn = 0;
  241. lws_ntpc_retry_conn(&v->sul_conn);
  242. }
  243. struct lws_protocols lws_system_protocol_ntpc =
  244. { "lws-ntpclient", callback_ntpc, 0, 128, };