context.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  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. #ifndef LWS_BUILD_HASH
  26. #define LWS_BUILD_HASH "unknown-build-hash"
  27. #endif
  28. static const char *library_version = LWS_LIBRARY_VERSION;
  29. #if defined(__linux__) || defined(__FreeBSD__) || defined(__illumos__)
  30. /* for setrlimit */
  31. #include <sys/resource.h>
  32. #endif
  33. #if defined(LWS_WITH_NETWORK)
  34. /* in ms */
  35. static uint32_t default_backoff_table[] = { 1000, 3000, 9000, 17000 };
  36. #endif
  37. /**
  38. * lws_get_library_version: get version and git hash library built from
  39. *
  40. * returns a const char * to a string like "1.1 178d78c"
  41. * representing the library version followed by the git head hash it
  42. * was built from
  43. */
  44. const char *
  45. lws_get_library_version(void)
  46. {
  47. return library_version;
  48. }
  49. #if defined(LWS_WITH_STATS)
  50. static void
  51. lws_sul_stats_cb(lws_sorted_usec_list_t *sul)
  52. {
  53. struct lws_context_per_thread *pt = lws_container_of(sul,
  54. struct lws_context_per_thread, sul_stats);
  55. lws_stats_log_dump(pt->context);
  56. __lws_sul_insert_us(&pt->pt_sul_owner[LWSSULLI_MISS_IF_SUSPENDED],
  57. &pt->sul_stats, 10 * LWS_US_PER_SEC);
  58. }
  59. #endif
  60. #if defined(LWS_WITH_PEER_LIMITS)
  61. static void
  62. lws_sul_peer_limits_cb(lws_sorted_usec_list_t *sul)
  63. {
  64. struct lws_context_per_thread *pt = lws_container_of(sul,
  65. struct lws_context_per_thread, sul_peer_limits);
  66. lws_peer_cull_peer_wait_list(pt->context);
  67. __lws_sul_insert_us(&pt->pt_sul_owner[LWSSULLI_MISS_IF_SUSPENDED],
  68. &pt->sul_peer_limits, 10 * LWS_US_PER_SEC);
  69. }
  70. #endif
  71. #if defined(LWS_WITH_NETWORK)
  72. #if defined(LWS_WITH_SYS_STATE)
  73. static const char * system_state_names[] = {
  74. "undef",
  75. "CONTEXT_CREATED",
  76. "INITIALIZED",
  77. "IFACE_COLDPLUG",
  78. "DHCP",
  79. "CPD_PRE_TIME",
  80. "TIME_VALID",
  81. "CPD_POST_TIME",
  82. "POLICY_VALID",
  83. "REGISTERED",
  84. "AUTH1",
  85. "AUTH2",
  86. "OPERATIONAL",
  87. "POLICY_INVALID"
  88. };
  89. /*
  90. * Handle provoking protocol init when we pass through the right system state
  91. */
  92. static int
  93. lws_state_notify_protocol_init(struct lws_state_manager *mgr,
  94. struct lws_state_notify_link *link, int current,
  95. int target)
  96. {
  97. struct lws_context *context = lws_container_of(mgr, struct lws_context,
  98. mgr_system);
  99. #if defined(LWS_WITH_SECURE_STREAMS) && defined(LWS_WITH_SECURE_STREAMS_SYS_AUTH_API_AMAZON_COM)
  100. lws_system_blob_t *ab0, *ab1;
  101. #endif
  102. int n;
  103. /*
  104. * Deal with any attachments that were waiting for the right state
  105. * to come along
  106. */
  107. for (n = 0; n < context->count_threads; n++)
  108. lws_system_do_attach(&context->pt[n]);
  109. #if defined(LWS_WITH_SYS_DHCP_CLIENT)
  110. if (target == LWS_SYSTATE_DHCP) {
  111. /*
  112. * Don't let it past here until at least one iface has been
  113. * configured for operation with DHCP
  114. */
  115. if (!lws_dhcpc_status(context, NULL))
  116. return 1;
  117. }
  118. #endif
  119. #if defined(LWS_WITH_SYS_NTPCLIENT)
  120. if (target == LWS_SYSTATE_TIME_VALID &&
  121. lws_now_secs() < 1594017754) /* 06:42 Mon Jul 6 2020 UTC */ {
  122. lws_ntpc_trigger(context);
  123. return 1;
  124. }
  125. #endif
  126. #if defined(LWS_WITH_SECURE_STREAMS) && defined(LWS_WITH_SECURE_STREAMS_SYS_AUTH_API_AMAZON_COM)
  127. /*
  128. * Skip this if we are running something without the policy for it
  129. *
  130. * If root token is empty, skip too.
  131. */
  132. ab0 = lws_system_get_blob(context, LWS_SYSBLOB_TYPE_AUTH, 0);
  133. ab1 = lws_system_get_blob(context, LWS_SYSBLOB_TYPE_AUTH, 1);
  134. if (target == LWS_SYSTATE_AUTH1 &&
  135. context->pss_policies && ab0 && ab1 &&
  136. !lws_system_blob_get_size(ab0) &&
  137. lws_system_blob_get_size(ab1)) {
  138. lwsl_info("%s: AUTH1 state triggering api.amazon.com auth\n", __func__);
  139. /*
  140. * Start trying to acquire it if it's not already in progress
  141. * returns nonzero if we determine it's not needed
  142. */
  143. if (!lws_ss_sys_auth_api_amazon_com(context))
  144. return 1;
  145. }
  146. #endif
  147. #if defined(LWS_WITH_SECURE_STREAMS)
  148. #if defined(LWS_WITH_DRIVERS)
  149. /*
  150. * See if we should do the SS Captive Portal Detection
  151. */
  152. if (target == LWS_SYSTATE_CPD_PRE_TIME) {
  153. if (lws_system_cpd_state_get(context) == LWS_CPD_INTERNET_OK)
  154. return 0; /* allow it */
  155. /*
  156. * Don't allow it to move past here until we get an IP and
  157. * CPD passes, driven by SMD
  158. */
  159. return 1;
  160. }
  161. #endif
  162. #if !defined(LWS_WITH_SECURE_STREAMS_STATIC_POLICY_ONLY)
  163. /*
  164. * Skip this if we are running something without the policy for it
  165. */
  166. if (target == LWS_SYSTATE_POLICY_VALID &&
  167. context->pss_policies && !context->policy_updated) {
  168. /*
  169. * Start trying to acquire it if it's not already in progress
  170. * returns nonzero if we determine it's not needed
  171. */
  172. if (!lws_ss_sys_fetch_policy(context))
  173. return 1;
  174. }
  175. #endif
  176. #endif
  177. /* protocol part */
  178. if (context->protocol_init_done)
  179. return 0;
  180. if (target != LWS_SYSTATE_POLICY_VALID)
  181. return 0;
  182. lwsl_info("%s: doing protocol init on POLICY_VALID\n", __func__);
  183. return lws_protocol_init(context);
  184. }
  185. static void
  186. lws_context_creation_completion_cb(lws_sorted_usec_list_t *sul)
  187. {
  188. struct lws_context *context = lws_container_of(sul, struct lws_context,
  189. sul_system_state);
  190. /* if nothing is there to intercept anything, go all the way */
  191. lws_state_transition_steps(&context->mgr_system,
  192. LWS_SYSTATE_OPERATIONAL);
  193. }
  194. #endif /* WITH_SYS_STATE */
  195. #if defined(LWS_WITH_SYS_SMD)
  196. static int
  197. lws_system_smd_cb(void *opaque, lws_smd_class_t _class, lws_usec_t timestamp,
  198. void *buf, size_t len)
  199. {
  200. struct lws_context *cx = (struct lws_context *)opaque;
  201. if (_class != LWSSMDCL_NETWORK)
  202. return 0;
  203. /* something external requested CPD check */
  204. if (!lws_json_simple_strcmp(buf, len, "\"trigger\":", "cpdcheck"))
  205. lws_system_cpd_start(cx);
  206. else
  207. /*
  208. * IP acquisition on any interface triggers captive portal
  209. * check on default route
  210. */
  211. if (!lws_json_simple_strcmp(buf, len, "\"type\":", "ipacq"))
  212. lws_system_cpd_start(cx);
  213. #if defined(LWS_WITH_SYS_NTPCLIENT)
  214. /*
  215. * Captive portal detect showing internet workable triggers NTP Client
  216. */
  217. if (!lws_json_simple_strcmp(buf, len, "\"type\":", "cps") &&
  218. !lws_json_simple_strcmp(buf, len, "\"result\":", "OK") &&
  219. lws_now_secs() < 1594017754) /* 06:42 Mon Jul 6 2020 UTC */
  220. lws_ntpc_trigger(cx);
  221. #endif
  222. #if defined(LWS_WITH_SYS_DHCP_CLIENT)
  223. /*
  224. * Any network interface linkup triggers DHCP
  225. */
  226. if (!lws_json_simple_strcmp(buf, len, "\"type\":", "linkup"))
  227. lws_ntpc_trigger(cx);
  228. #endif
  229. #if defined(LWS_WITH_DRIVERS) && defined(LWS_WITH_NETWORK)
  230. lws_netdev_smd_cb(opaque, _class, timestamp, buf, len);
  231. #endif
  232. return 0;
  233. }
  234. #endif
  235. #endif /* NETWORK */
  236. #if !defined(LWS_WITH_NO_LOGS)
  237. static const char * const opts_str =
  238. #if defined(LWS_WITH_NETWORK)
  239. "NET "
  240. #else
  241. "NoNET "
  242. #endif
  243. #if defined(LWS_WITH_CLIENT)
  244. "CLI "
  245. #endif
  246. #if defined(LWS_WITH_SERVER)
  247. "SRV "
  248. #endif
  249. #if defined(LWS_ROLE_H1)
  250. "H1 "
  251. #endif
  252. #if defined(LWS_ROLE_H2)
  253. "H2 "
  254. #endif
  255. #if defined(LWS_ROLE_WS)
  256. "WS "
  257. #endif
  258. #if defined(LWS_ROLE_MQTT)
  259. "MQTT "
  260. #endif
  261. #if defined(LWS_WITH_SECURE_STREAMS) && !defined(LWS_WITH_SECURE_STREAMS_STATIC_POLICY_ONLY)
  262. "SS-JSON-POL "
  263. #endif
  264. #if defined(LWS_WITH_SECURE_STREAMS) && defined(LWS_WITH_SECURE_STREAMS_STATIC_POLICY_ONLY)
  265. "SS-STATIC-POL "
  266. #endif
  267. #if defined(LWS_WITH_SECURE_STREAMS_PROXY_API)
  268. "SSPROX "
  269. #endif
  270. #if defined(LWS_WITH_SYS_ASYNC_DNS)
  271. "ASYNC_DNS "
  272. #endif
  273. #if defined(LWS_WITH_SYS_NTPCLIENT)
  274. "NTPCLIENT "
  275. #endif
  276. #if defined(LWS_WITH_SYS_DHCP_CLIENT)
  277. "DHCP_CLIENT "
  278. #endif
  279. ;
  280. #endif
  281. #if defined(LWS_WITH_EVLIB_PLUGINS) && defined(LWS_WITH_EVENT_LIBS)
  282. static const struct lws_evlib_map {
  283. uint64_t flag;
  284. const char *name;
  285. } map[] = {
  286. { LWS_SERVER_OPTION_LIBUV, "evlib_uv" },
  287. { LWS_SERVER_OPTION_LIBEVENT, "evlib_event" },
  288. { LWS_SERVER_OPTION_GLIB, "evlib_glib" },
  289. { LWS_SERVER_OPTION_LIBEV, "evlib_ev" },
  290. };
  291. static const char * const dlist[] = {
  292. LWS_INSTALL_LIBDIR,
  293. NULL
  294. };
  295. #endif
  296. struct lws_context *
  297. lws_create_context(const struct lws_context_creation_info *info)
  298. {
  299. struct lws_context *context = NULL;
  300. #if !defined(LWS_WITH_NO_LOGS)
  301. const char *s = "IPv6-absent";
  302. #endif
  303. #if defined(LWS_WITH_FILE_OPS)
  304. struct lws_plat_file_ops *prev;
  305. #endif
  306. #ifndef LWS_NO_DAEMONIZE
  307. pid_t pid_daemon = get_daemonize_pid();
  308. #endif
  309. #if defined(LWS_WITH_NETWORK)
  310. int count_threads = 1;
  311. uint8_t *u;
  312. #endif
  313. #if defined(__ANDROID__)
  314. struct rlimit rt;
  315. #endif
  316. size_t
  317. #if defined(LWS_PLAT_FREERTOS)
  318. /* smaller default, can set in info->pt_serv_buf_size */
  319. s1 = 2048,
  320. #else
  321. s1 = 4096,
  322. #endif
  323. size = sizeof(struct lws_context);
  324. int n, lpf = info->fd_limit_per_thread;
  325. const lws_plugin_evlib_t *plev = NULL;
  326. #if defined(LWS_WITH_EVLIB_PLUGINS) && defined(LWS_WITH_EVENT_LIBS)
  327. struct lws_plugin *evlib_plugin_list = NULL;
  328. #endif
  329. if (lpf) {
  330. lpf+= 2;
  331. #if defined(LWS_WITH_SYS_ASYNC_DNS)
  332. lpf++;
  333. #endif
  334. #if defined(LWS_WITH_SYS_NTPCLIENT)
  335. lpf++;
  336. #endif
  337. #if defined(LWS_WITH_SYS_DHCP_CLIENT)
  338. lpf++;
  339. #endif
  340. }
  341. lwsl_notice("LWS: %s, loglevel %d\n", library_version, log_level);
  342. #if defined(LWS_WITH_IPV6) && !defined(LWS_WITH_NO_LOGS)
  343. if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))
  344. s = "IPV6-on";
  345. else
  346. s = "IPV6-off";
  347. #endif
  348. #if defined(LWS_WITH_STATS)
  349. lwsl_info(" LWS_WITH_STATS : on\n");
  350. #endif
  351. lwsl_notice("%s%s\n", opts_str, s);
  352. if (lws_plat_context_early_init())
  353. return NULL;
  354. #if defined(LWS_WITH_NETWORK)
  355. if (info->count_threads)
  356. count_threads = info->count_threads;
  357. if (count_threads > LWS_MAX_SMP)
  358. count_threads = LWS_MAX_SMP;
  359. if (info->pt_serv_buf_size)
  360. s1 = info->pt_serv_buf_size;
  361. /* pt fakewsi and the pt serv buf allocations ride after the context */
  362. size += count_threads * s1;
  363. #if !defined(LWS_PLAT_FREERTOS)
  364. size += (count_threads * sizeof(struct lws));
  365. #endif
  366. #endif /* network */
  367. #if defined(LWS_WITH_POLL)
  368. {
  369. extern const lws_plugin_evlib_t evlib_poll;
  370. plev = &evlib_poll;
  371. }
  372. #endif
  373. #if defined(LWS_WITH_EVLIB_PLUGINS) && defined(LWS_WITH_EVENT_LIBS)
  374. /*
  375. * New style dynamically loaded event lib support
  376. *
  377. * We have to pick and load the event lib plugin before we allocate
  378. * the context object, so we can overallocate it correctly
  379. */
  380. lwsl_info("%s: ev lib path %s\n", __func__, LWS_INSTALL_LIBDIR);
  381. for (n = 0; n < (int)LWS_ARRAY_SIZE(map); n++) {
  382. if (!lws_check_opt(info->options, map[n].flag))
  383. continue;
  384. if (lws_plugins_init(&evlib_plugin_list,
  385. dlist, "lws_evlib_plugin",
  386. map[n].name, NULL, NULL)) {
  387. lwsl_err("%s: failed to load %s\n", __func__,
  388. map[n].name);
  389. goto bail;
  390. }
  391. if (!evlib_plugin_list) {
  392. lwsl_err("%s: unable to load evlib plugin %s\n",
  393. __func__, map[n].name);
  394. goto bail;
  395. }
  396. plev = (const lws_plugin_evlib_t *)evlib_plugin_list->hdr;
  397. break;
  398. }
  399. #else
  400. #if defined(LWS_WITH_EVENT_LIBS)
  401. /*
  402. * set the context event loops ops struct
  403. *
  404. * after this, all event_loop actions use the generic ops
  405. */
  406. /*
  407. * oldstyle built-in event lib support
  408. *
  409. * We have composed them into the libwebsockets lib itself, we can
  410. * just pick the ops we want and done
  411. */
  412. #if defined(LWS_WITH_LIBUV)
  413. if (lws_check_opt(info->options, LWS_SERVER_OPTION_LIBUV)) {
  414. extern const lws_plugin_evlib_t evlib_uv;
  415. plev = &evlib_uv;
  416. }
  417. #endif
  418. #if defined(LWS_WITH_LIBEVENT)
  419. if (lws_check_opt(info->options, LWS_SERVER_OPTION_LIBEVENT)) {
  420. extern const lws_plugin_evlib_t evlib_event;
  421. plev = &evlib_event;
  422. }
  423. #endif
  424. #if defined(LWS_WITH_GLIB)
  425. if (lws_check_opt(info->options, LWS_SERVER_OPTION_GLIB)) {
  426. extern const lws_plugin_evlib_t evlib_glib;
  427. plev = &evlib_glib;
  428. }
  429. #endif
  430. #if defined(LWS_WITH_LIBEV)
  431. if (lws_check_opt(info->options, LWS_SERVER_OPTION_LIBEV)) {
  432. extern const lws_plugin_evlib_t evlib_ev;
  433. plev = &evlib_ev;
  434. }
  435. #endif
  436. #endif /* with event libs */
  437. #endif /* not with ev plugins */
  438. if (!plev)
  439. goto fail_event_libs;
  440. #if defined(LWS_WITH_NETWORK)
  441. size += (size_t)plev->ops->evlib_size_ctx /* the ctx evlib priv */ +
  442. (count_threads * (size_t)plev->ops->evlib_size_pt) /* the pt evlib priv */;
  443. lwsl_info("Event loop: %s\n", plev->ops->name);
  444. #endif
  445. context = lws_zalloc(size, "context");
  446. if (!context) {
  447. lwsl_err("No memory for websocket context\n");
  448. return NULL;
  449. }
  450. #if defined(LWS_WITH_NETWORK)
  451. context->event_loop_ops = plev->ops;
  452. #endif
  453. #if defined(LWS_WITH_EVENT_LIBS)
  454. /* at the very end */
  455. context->evlib_ctx = (uint8_t *)context + size -
  456. plev->ops->evlib_size_ctx;
  457. #endif
  458. #if defined(LWS_WITH_EVLIB_PLUGINS) && defined(LWS_WITH_EVENT_LIBS)
  459. context->evlib_plugin_list = evlib_plugin_list;
  460. #endif
  461. #if !defined(LWS_PLAT_FREERTOS)
  462. context->uid = info->uid;
  463. context->gid = info->gid;
  464. context->username = info->username;
  465. context->groupname = info->groupname;
  466. #endif
  467. context->system_ops = info->system_ops;
  468. context->pt_serv_buf_size = (unsigned int)s1;
  469. #if defined(LWS_WITH_UDP)
  470. context->udp_loss_sim_tx_pc = info->udp_loss_sim_tx_pc;
  471. context->udp_loss_sim_rx_pc = info->udp_loss_sim_rx_pc;
  472. if (context->udp_loss_sim_tx_pc || context->udp_loss_sim_rx_pc)
  473. lwsl_warn("%s: simulating udp loss tx: %d%%, rx: %d%%\n",
  474. __func__, context->udp_loss_sim_tx_pc,
  475. context->udp_loss_sim_rx_pc);
  476. #endif
  477. #if defined(LWS_WITH_SECURE_STREAMS_STATIC_POLICY_ONLY)
  478. /* directly use the user-provided policy object list */
  479. context->pss_policies = info->pss_policies;
  480. #endif
  481. #if defined(LWS_WITH_SECURE_STREAMS_PROXY_API)
  482. context->ss_proxy_bind = info->ss_proxy_bind;
  483. context->ss_proxy_port = info->ss_proxy_port;
  484. context->ss_proxy_address = info->ss_proxy_address;
  485. if (context->ss_proxy_bind && context->ss_proxy_address)
  486. lwsl_notice("%s: using ss proxy bind '%s', port %d, ads '%s'\n",
  487. __func__, context->ss_proxy_bind, context->ss_proxy_port,
  488. context->ss_proxy_address);
  489. #endif
  490. #if defined(LWS_WITH_NETWORK)
  491. context->count_threads = count_threads;
  492. #if defined(LWS_WITH_DETAILED_LATENCY)
  493. context->detailed_latency_cb = info->detailed_latency_cb;
  494. context->detailed_latency_filepath = info->detailed_latency_filepath;
  495. context->latencies_fd = -1;
  496. #endif
  497. #if defined(LWS_ROLE_WS) && defined(LWS_WITHOUT_EXTENSIONS)
  498. if (info->extensions)
  499. lwsl_warn("%s: LWS_WITHOUT_EXTENSIONS but extensions ptr set\n", __func__);
  500. #endif
  501. #endif /* network */
  502. #if defined(LWS_WITH_SECURE_STREAMS)
  503. #if !defined(LWS_WITH_SECURE_STREAMS_STATIC_POLICY_ONLY)
  504. context->pss_policies_json = info->pss_policies_json;
  505. #endif
  506. #if defined(LWS_WITH_SSPLUGINS)
  507. context->pss_plugins = info->pss_plugins;
  508. #endif
  509. #endif
  510. /* if he gave us names, set the uid / gid */
  511. if (lws_plat_drop_app_privileges(context, 0))
  512. goto bail;
  513. #if defined(LWS_WITH_TLS) && defined(LWS_WITH_NETWORK)
  514. #if defined(LWS_WITH_MBEDTLS)
  515. context->tls_ops = &tls_ops_mbedtls;
  516. #else
  517. context->tls_ops = &tls_ops_openssl;
  518. #endif
  519. #endif
  520. #if LWS_MAX_SMP > 1
  521. lws_mutex_refcount_init(&context->mr);
  522. #endif
  523. #if defined(LWS_PLAT_FREERTOS)
  524. #if defined(LWS_AMAZON_RTOS)
  525. context->last_free_heap = xPortGetFreeHeapSize();
  526. #else
  527. context->last_free_heap = esp_get_free_heap_size();
  528. #endif
  529. #endif
  530. #if defined(LWS_WITH_FILE_OPS)
  531. /* default to just the platform fops implementation */
  532. context->fops_platform.LWS_FOP_OPEN = _lws_plat_file_open;
  533. context->fops_platform.LWS_FOP_CLOSE = _lws_plat_file_close;
  534. context->fops_platform.LWS_FOP_SEEK_CUR = _lws_plat_file_seek_cur;
  535. context->fops_platform.LWS_FOP_READ = _lws_plat_file_read;
  536. context->fops_platform.LWS_FOP_WRITE = _lws_plat_file_write;
  537. context->fops_platform.fi[0].sig = NULL;
  538. /*
  539. * arrange a linear linked-list of fops starting from context->fops
  540. *
  541. * platform fops
  542. * [ -> fops_zip (copied into context so .next settable) ]
  543. * [ -> info->fops ]
  544. */
  545. context->fops = &context->fops_platform;
  546. prev = (struct lws_plat_file_ops *)context->fops;
  547. #if defined(LWS_WITH_ZIP_FOPS)
  548. /* make a soft copy so we can set .next */
  549. context->fops_zip = fops_zip;
  550. prev->next = &context->fops_zip;
  551. prev = (struct lws_plat_file_ops *)prev->next;
  552. #endif
  553. /* if user provided fops, tack them on the end of the list */
  554. if (info->fops)
  555. prev->next = info->fops;
  556. #endif
  557. #if defined(LWS_WITH_SERVER)
  558. context->reject_service_keywords = info->reject_service_keywords;
  559. #endif
  560. if (info->external_baggage_free_on_destroy)
  561. context->external_baggage_free_on_destroy =
  562. info->external_baggage_free_on_destroy;
  563. #if defined(LWS_WITH_NETWORK)
  564. context->time_up = lws_now_usecs();
  565. #endif
  566. context->pcontext_finalize = info->pcontext;
  567. #if defined(LWS_WITH_TLS) && defined(LWS_WITH_NETWORK)
  568. context->simultaneous_ssl_restriction =
  569. info->simultaneous_ssl_restriction;
  570. #endif
  571. context->options = info->options;
  572. #if !defined(LWS_PLAT_FREERTOS) && !defined(LWS_PLAT_OPTEE) && !defined(WIN32)
  573. /*
  574. * If asked, try to set the rlimit / ulimit for process sockets / files.
  575. * We read the effective limit in a moment, so we will find out the
  576. * real limit according to system constraints then.
  577. */
  578. if (info->rlimit_nofile) {
  579. struct rlimit rl;
  580. rl.rlim_cur = rl.rlim_max = info->rlimit_nofile;
  581. setrlimit(RLIMIT_NOFILE, &rl);
  582. }
  583. #endif
  584. #ifndef LWS_NO_DAEMONIZE
  585. if (pid_daemon) {
  586. context->started_with_parent = pid_daemon;
  587. lwsl_info(" Started with daemon pid %u\n", (unsigned int)pid_daemon);
  588. }
  589. #endif
  590. #if defined(__ANDROID__)
  591. n = getrlimit(RLIMIT_NOFILE, &rt);
  592. if (n == -1) {
  593. lwsl_err("Get RLIMIT_NOFILE failed!\n");
  594. return NULL;
  595. }
  596. context->max_fds = rt.rlim_cur;
  597. #else
  598. #if defined(WIN32) || defined(_WIN32) || defined(LWS_AMAZON_RTOS) || defined(LWS_ESP_PLATFORM)
  599. context->max_fds = getdtablesize();
  600. #else
  601. context->max_fds = sysconf(_SC_OPEN_MAX);
  602. #endif
  603. if (context->max_fds < 0) {
  604. lwsl_err("%s: problem getting process max files\n",
  605. __func__);
  606. return NULL;
  607. }
  608. #endif
  609. /*
  610. * deal with any max_fds override, if it's reducing (setting it to
  611. * more than ulimit -n is meaningless). The platform init will
  612. * figure out what if this is something it can deal with.
  613. */
  614. if (info->fd_limit_per_thread) {
  615. int mf = lpf * context->count_threads;
  616. if (mf < context->max_fds) {
  617. context->max_fds_unrelated_to_ulimit = 1;
  618. context->max_fds = mf;
  619. }
  620. }
  621. #if defined(LWS_WITH_NETWORK)
  622. context->token_limits = info->token_limits;
  623. #endif
  624. #if defined(LWS_WITH_TLS) && defined(LWS_WITH_NETWORK)
  625. time(&context->tls.last_cert_check_s);
  626. if (info->alpn)
  627. context->tls.alpn_default = info->alpn;
  628. else {
  629. char *p = context->tls.alpn_discovered, first = 1;
  630. LWS_FOR_EVERY_AVAILABLE_ROLE_START(ar) {
  631. if (ar->alpn) {
  632. if (!first)
  633. *p++ = ',';
  634. p += lws_snprintf(p,
  635. context->tls.alpn_discovered +
  636. sizeof(context->tls.alpn_discovered) -
  637. 2 - p, "%s", ar->alpn);
  638. first = 0;
  639. }
  640. } LWS_FOR_EVERY_AVAILABLE_ROLE_END;
  641. context->tls.alpn_default = context->tls.alpn_discovered;
  642. }
  643. #endif
  644. #if defined(LWS_WITH_NETWORK)
  645. if (info->timeout_secs)
  646. context->timeout_secs = info->timeout_secs;
  647. else
  648. #endif
  649. context->timeout_secs = 5;
  650. #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
  651. if (info->max_http_header_data)
  652. context->max_http_header_data = info->max_http_header_data;
  653. else
  654. if (info->max_http_header_data2)
  655. context->max_http_header_data =
  656. info->max_http_header_data2;
  657. else
  658. context->max_http_header_data = LWS_DEF_HEADER_LEN;
  659. if (info->max_http_header_pool)
  660. context->max_http_header_pool = info->max_http_header_pool;
  661. else
  662. if (info->max_http_header_pool2)
  663. context->max_http_header_pool =
  664. info->max_http_header_pool2;
  665. else
  666. context->max_http_header_pool = context->max_fds;
  667. #endif
  668. if (info->fd_limit_per_thread)
  669. context->fd_limit_per_thread = lpf;
  670. else
  671. if (context->count_threads)
  672. context->fd_limit_per_thread = context->max_fds /
  673. context->count_threads;
  674. #if defined(LWS_WITH_SYS_SMD)
  675. lws_mutex_init(context->smd.lock_messages);
  676. lws_mutex_init(context->smd.lock_peers);
  677. /* lws_system smd participant */
  678. if (!lws_smd_register(context, context, 0, LWSSMDCL_NETWORK,
  679. lws_system_smd_cb)) {
  680. lwsl_err("%s: early smd register failed\n", __func__);
  681. }
  682. /* user smd participant */
  683. if (info->early_smd_cb &&
  684. !lws_smd_register(context, info->early_smd_opaque, 0,
  685. info->early_smd_class_filter,
  686. info->early_smd_cb)) {
  687. lwsl_err("%s: early smd register failed\n", __func__);
  688. }
  689. #endif
  690. n = 0;
  691. #if defined(LWS_WITH_NETWORK)
  692. context->default_retry.retry_ms_table = default_backoff_table;
  693. context->default_retry.conceal_count =
  694. context->default_retry.retry_ms_table_count =
  695. LWS_ARRAY_SIZE(default_backoff_table);
  696. context->default_retry.jitter_percent = 20;
  697. context->default_retry.secs_since_valid_ping = 300;
  698. context->default_retry.secs_since_valid_hangup = 310;
  699. if (info->retry_and_idle_policy &&
  700. info->retry_and_idle_policy->secs_since_valid_ping) {
  701. context->default_retry.secs_since_valid_ping =
  702. info->retry_and_idle_policy->secs_since_valid_ping;
  703. context->default_retry.secs_since_valid_hangup =
  704. info->retry_and_idle_policy->secs_since_valid_hangup;
  705. }
  706. /*
  707. * Allocate the per-thread storage for scratchpad buffers,
  708. * and header data pool
  709. */
  710. u = (uint8_t *)&context[1];
  711. for (n = 0; n < context->count_threads; n++) {
  712. context->pt[n].serv_buf = u;
  713. u += context->pt_serv_buf_size;
  714. context->pt[n].context = context;
  715. context->pt[n].tid = n;
  716. #if !defined(LWS_PLAT_FREERTOS)
  717. /*
  718. * We overallocated for a fakewsi (can't compose it in the
  719. * pt because size isn't known at that time). point to it
  720. * and zero it down. Fakewsis are needed to make callbacks work
  721. * when the source of the callback is not actually from a wsi
  722. * context.
  723. */
  724. context->pt[n].fake_wsi = (struct lws *)u;
  725. u += sizeof(struct lws);
  726. memset(context->pt[n].fake_wsi, 0, sizeof(struct lws));
  727. #endif
  728. #if defined(LWS_WITH_EVENT_LIBS)
  729. context->pt[n].evlib_pt = u;
  730. u += plev->ops->evlib_size_pt;
  731. #endif
  732. #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
  733. context->pt[n].http.ah_list = NULL;
  734. context->pt[n].http.ah_pool_length = 0;
  735. #endif
  736. lws_pt_mutex_init(&context->pt[n]);
  737. #if defined(LWS_WITH_SEQUENCER)
  738. lws_seq_pt_init(&context->pt[n]);
  739. #endif
  740. LWS_FOR_EVERY_AVAILABLE_ROLE_START(ar) {
  741. if (ar->pt_init_destroy)
  742. ar->pt_init_destroy(context, info,
  743. &context->pt[n], 0);
  744. } LWS_FOR_EVERY_AVAILABLE_ROLE_END;
  745. #if defined(LWS_WITH_CGI)
  746. role_ops_cgi.pt_init_destroy(context, info, &context->pt[n], 0);
  747. #endif
  748. }
  749. if (!info->ka_interval && info->ka_time > 0) {
  750. lwsl_err("info->ka_interval can't be 0 if ka_time used\n");
  751. return NULL;
  752. }
  753. #if defined(LWS_WITH_PEER_LIMITS)
  754. /* scale the peer hash table according to the max fds for the process,
  755. * so that the max list depth averages 16. Eg, 1024 fd -> 64,
  756. * 102400 fd -> 6400
  757. */
  758. context->pl_hash_elements =
  759. (context->count_threads * context->fd_limit_per_thread) / 16;
  760. context->pl_hash_table = lws_zalloc(sizeof(struct lws_peer *) *
  761. context->pl_hash_elements, "peer limits hash table");
  762. context->ip_limit_ah = info->ip_limit_ah;
  763. context->ip_limit_wsi = info->ip_limit_wsi;
  764. context->pl_notify_cb = info->pl_notify_cb;
  765. #endif
  766. /*
  767. * fds table contains pollfd structs for as many pollfds as we can
  768. * handle... spread across as many service threads as we have going
  769. */
  770. n = sizeof(struct lws_pollfd) * context->count_threads *
  771. context->fd_limit_per_thread;
  772. context->pt[0].fds = lws_zalloc(n, "fds table");
  773. if (context->pt[0].fds == NULL) {
  774. lwsl_err("OOM allocating %d fds\n", context->max_fds);
  775. goto bail;
  776. }
  777. #endif
  778. lwsl_info(" ctx: %5luB (%ld ctx + pt(%ld thr x %d)), "
  779. "pt-fds: %d, fdmap: %d\n",
  780. (long)sizeof(struct lws_context) +
  781. (context->count_threads * context->pt_serv_buf_size),
  782. (long)sizeof(struct lws_context),
  783. (long)context->count_threads,
  784. context->pt_serv_buf_size,
  785. context->fd_limit_per_thread, n);
  786. #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
  787. lwsl_info(" http: ah_data: %u, ah: %lu, max count %u\n",
  788. context->max_http_header_data,
  789. (long)sizeof(struct allocated_headers),
  790. context->max_http_header_pool);
  791. #endif
  792. #if defined(LWS_WITH_SERVER)
  793. if (info->server_string) {
  794. context->server_string = info->server_string;
  795. context->server_string_len = (short)
  796. strlen(context->server_string);
  797. }
  798. #endif
  799. #if LWS_MAX_SMP > 1
  800. /* each thread serves his own chunk of fds */
  801. for (n = 1; n < (int)context->count_threads; n++)
  802. context->pt[n].fds = context->pt[n - 1].fds +
  803. context->fd_limit_per_thread;
  804. #endif
  805. if (lws_plat_init(context, info))
  806. goto bail;
  807. #if defined(LWS_WITH_NETWORK)
  808. if (context->event_loop_ops->init_context)
  809. if (context->event_loop_ops->init_context(context, info))
  810. goto bail;
  811. if (context->event_loop_ops->init_pt)
  812. for (n = 0; n < context->count_threads; n++) {
  813. void *lp = NULL;
  814. if (info->foreign_loops)
  815. lp = info->foreign_loops[n];
  816. if (context->event_loop_ops->init_pt(context, lp, n))
  817. goto bail;
  818. }
  819. if (lws_create_event_pipes(context))
  820. goto bail;
  821. #endif
  822. lws_context_init_ssl_library(info);
  823. context->user_space = info->user;
  824. #if defined(LWS_WITH_SERVER)
  825. strcpy(context->canonical_hostname, "unknown");
  826. #if defined(LWS_WITH_NETWORK)
  827. lws_server_get_canonical_hostname(context, info);
  828. #endif
  829. #endif
  830. #if defined(LWS_WITH_STATS)
  831. context->pt[0].sul_stats.cb = lws_sul_stats_cb;
  832. __lws_sul_insert_us(&context->pt[0].pt_sul_owner[LWSSULLI_MISS_IF_SUSPENDED],
  833. &context->pt[0].sul_stats, 10 * LWS_US_PER_SEC);
  834. #endif
  835. #if defined(LWS_WITH_PEER_LIMITS)
  836. context->pt[0].sul_peer_limits.cb = lws_sul_peer_limits_cb;
  837. __lws_sul_insert_us(&context->pt[0].pt_sul_owner[LWSSULLI_MISS_IF_SUSPENDED],
  838. &context->pt[0].sul_peer_limits, 10 * LWS_US_PER_SEC);
  839. #endif
  840. #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
  841. memcpy(context->caps, info->caps, sizeof(context->caps));
  842. context->count_caps = info->count_caps;
  843. #endif
  844. #if defined(LWS_WITH_NETWORK)
  845. #if defined(LWS_WITH_SYS_ASYNC_DNS) || defined(LWS_WITH_SYS_NTPCLIENT) || \
  846. defined(LWS_WITH_SYS_DHCP_CLIENT)
  847. {
  848. /*
  849. * system vhost
  850. */
  851. struct lws_context_creation_info ii;
  852. const struct lws_protocols *pp[4];
  853. struct lws_vhost *vh;
  854. #if defined(LWS_WITH_SYS_ASYNC_DNS)
  855. extern const struct lws_protocols lws_async_dns_protocol;
  856. #endif
  857. #if defined(LWS_WITH_SYS_NTPCLIENT)
  858. extern const struct lws_protocols lws_system_protocol_ntpc;
  859. #endif
  860. #if defined(LWS_WITH_SYS_DHCP_CLIENT)
  861. extern const struct lws_protocols lws_system_protocol_dhcpc;
  862. #endif
  863. n = 0;
  864. #if defined(LWS_WITH_SYS_ASYNC_DNS)
  865. pp[n++] = &lws_async_dns_protocol;
  866. #endif
  867. #if defined(LWS_WITH_SYS_NTPCLIENT)
  868. pp[n++] = &lws_system_protocol_ntpc;
  869. #endif
  870. #if defined(LWS_WITH_SYS_DHCP_CLIENT)
  871. pp[n++] = &lws_system_protocol_dhcpc;
  872. #endif
  873. pp[n] = NULL;
  874. memset(&ii, 0, sizeof(ii));
  875. ii.vhost_name = "system";
  876. ii.pprotocols = pp;
  877. vh = lws_create_vhost(context, &ii);
  878. if (!vh) {
  879. lwsl_err("%s: failed to create system vhost\n",
  880. __func__);
  881. goto bail;
  882. }
  883. context->vhost_system = vh;
  884. if (lws_protocol_init_vhost(vh, NULL)) {
  885. lwsl_err("%s: failed to init system vhost\n", __func__);
  886. goto bail;
  887. }
  888. #if defined(LWS_WITH_SYS_ASYNC_DNS)
  889. if (lws_async_dns_init(context))
  890. goto bail;
  891. #endif
  892. }
  893. #endif
  894. #if defined(LWS_WITH_SYS_STATE)
  895. /*
  896. * init the lws_state mgr for the system state
  897. */
  898. context->mgr_system.state_names = system_state_names;
  899. context->mgr_system.name = "system";
  900. context->mgr_system.state = LWS_SYSTATE_CONTEXT_CREATED;
  901. context->mgr_system.parent = context;
  902. context->mgr_system.context = context;
  903. #if defined(LWS_WITH_SYS_SMD)
  904. context->mgr_system.smd_class = LWSSMDCL_SYSTEM_STATE;
  905. #endif
  906. context->protocols_notify.name = "prot_init";
  907. context->protocols_notify.notify_cb = lws_state_notify_protocol_init;
  908. lws_state_reg_notifier(&context->mgr_system, &context->protocols_notify);
  909. /*
  910. * insert user notifiers here so they can participate with vetoing us
  911. * trying to jump straight to operational, or at least observe us
  912. * reaching 'operational', before we returned from context creation.
  913. */
  914. lws_state_reg_notifier_list(&context->mgr_system,
  915. info->register_notifier_list);
  916. #endif
  917. /*
  918. * if he's not saying he'll make his own vhosts later then act
  919. * compatibly and make a default vhost using the data in the info
  920. */
  921. if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
  922. if (!lws_create_vhost(context, info)) {
  923. lwsl_err("Failed to create default vhost\n");
  924. #if defined(LWS_WITH_PEER_LIMITS)
  925. lws_free_set_NULL(context->pl_hash_table);
  926. #endif
  927. goto fail_clean_pipes;
  928. }
  929. #if defined(LWS_WITH_SECURE_STREAMS)
  930. #if !defined(LWS_WITH_SECURE_STREAMS_STATIC_POLICY_ONLY)
  931. if (context->pss_policies_json) {
  932. /*
  933. * You must create your context with the explicit vhosts flag
  934. * in order to use secure streams
  935. */
  936. assert(lws_check_opt(info->options,
  937. LWS_SERVER_OPTION_EXPLICIT_VHOSTS));
  938. if (lws_ss_policy_parse_begin(context, 0))
  939. goto bail;
  940. n = lws_ss_policy_parse(context,
  941. (uint8_t *)context->pss_policies_json,
  942. strlen(context->pss_policies_json));
  943. if (n != LEJP_CONTINUE && n < 0)
  944. goto bail;
  945. if (lws_ss_policy_set(context, "hardcoded")) {
  946. lwsl_err("%s: policy set failed\n", __func__);
  947. goto bail;
  948. }
  949. } else
  950. #else
  951. if (context->pss_policies) {
  952. /* user code set the policy objects directly, no parsing step */
  953. if (lws_ss_policy_set(context, "hardcoded")) {
  954. lwsl_err("%s: policy set failed\n", __func__);
  955. goto bail;
  956. }
  957. } //else
  958. #endif
  959. // lws_create_vhost(context, info);
  960. #endif
  961. lws_context_init_extensions(info, context);
  962. lwsl_info(" mem: per-conn: %5lu bytes + protocol rx buf\n",
  963. (unsigned long)sizeof(struct lws));
  964. /*
  965. * drop any root privs for this process
  966. * to listen on port < 1023 we would have needed root, but now we are
  967. * listening, we don't want the power for anything else
  968. */
  969. if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
  970. if (lws_plat_drop_app_privileges(context, 1))
  971. goto bail;
  972. #if defined(LWS_WITH_SYS_STATE)
  973. /*
  974. * We want to move on the syste, state as far as it can go towards
  975. * OPERATIONAL now. But we have to return from here first so the user
  976. * code that called us can set its copy of context, which it may be
  977. * relying on to perform operations triggered by the state change.
  978. *
  979. * We set up a sul to come back immediately and do the state change.
  980. */
  981. lws_sul_schedule(context, 0, &context->sul_system_state,
  982. lws_context_creation_completion_cb, 1);
  983. #endif
  984. /* expedite post-context init (eg, protocols) */
  985. lws_cancel_service(context);
  986. #endif
  987. return context;
  988. #if defined(LWS_WITH_NETWORK)
  989. fail_clean_pipes:
  990. for (n = 0; n < context->count_threads; n++)
  991. lws_destroy_event_pipe(context->pt[n].pipe_wsi);
  992. lws_free_set_NULL(context->pt[0].fds);
  993. lws_plat_context_late_destroy(context);
  994. lws_free_set_NULL(context);
  995. return NULL;
  996. #endif
  997. bail:
  998. lws_context_destroy(context);
  999. return NULL;
  1000. fail_event_libs:
  1001. lwsl_err("Requested event library support not configured\n");
  1002. lws_free(context);
  1003. return NULL;
  1004. }
  1005. #if defined(LWS_WITH_NETWORK)
  1006. int
  1007. lws_system_cpd_start(struct lws_context *cx)
  1008. {
  1009. cx->captive_portal_detect = LWS_CPD_UNKNOWN;
  1010. /* if there's a platform implementation, use it */
  1011. if (lws_system_get_ops(cx) &&
  1012. lws_system_get_ops(cx)->captive_portal_detect_request)
  1013. return lws_system_get_ops(cx)->captive_portal_detect_request(cx);
  1014. #if defined(LWS_WITH_SECURE_STREAMS)
  1015. /*
  1016. * Otherwise try to use SS "captive_portal_detect" if that's enabled
  1017. */
  1018. return lws_ss_sys_cpd(cx);
  1019. #else
  1020. return 0;
  1021. #endif
  1022. }
  1023. static const char *cname[] = { "Unknown", "OK", "Captive", "No internet" };
  1024. void
  1025. lws_system_cpd_set(struct lws_context *cx, lws_cpd_result_t result)
  1026. {
  1027. if (cx->captive_portal_detect != LWS_CPD_UNKNOWN)
  1028. return;
  1029. lwsl_notice("%s: setting CPD result %s\n", __func__, cname[result]);
  1030. cx->captive_portal_detect = (uint8_t)result;
  1031. #if defined(LWS_WITH_SYS_STATE)
  1032. #if defined(LWS_WITH_SYS_SMD)
  1033. lws_smd_msg_printf(cx, LWSSMDCL_NETWORK,
  1034. "{\"type\":\"cpd\",\"result\":\"%s\"}",
  1035. cname[cx->captive_portal_detect]);
  1036. #endif
  1037. /* if nothing is there to intercept anything, go all the way */
  1038. if (cx->mgr_system.state != LWS_SYSTATE_POLICY_INVALID)
  1039. lws_state_transition_steps(&cx->mgr_system,
  1040. LWS_SYSTATE_OPERATIONAL);
  1041. #endif
  1042. }
  1043. lws_cpd_result_t
  1044. lws_system_cpd_state_get(struct lws_context *cx)
  1045. {
  1046. return (lws_cpd_result_t)cx->captive_portal_detect;
  1047. }
  1048. #endif
  1049. int
  1050. lws_context_is_deprecated(struct lws_context *cx)
  1051. {
  1052. return cx->deprecated;
  1053. }
  1054. /*
  1055. * When using an event loop, the context destruction is in three separate
  1056. * parts. This is to cover both internal and foreign event loops cleanly.
  1057. *
  1058. * - lws_context_destroy() simply starts a soft close of all wsi and
  1059. * related allocations. The event loop continues.
  1060. *
  1061. * As the closes complete in the event loop, reference counting is used
  1062. * to determine when everything is closed. It then calls
  1063. * lws_context_destroy2().
  1064. *
  1065. * - lws_context_destroy2() cleans up the rest of the higher-level logical
  1066. * lws pieces like vhosts. If the loop was foreign, it then proceeds to
  1067. * lws_context_destroy3(). If it the loop is internal, it stops the
  1068. * internal loops and waits for lws_context_destroy() to be called again
  1069. * outside the event loop (since we cannot destroy the loop from
  1070. * within the loop). That will cause lws_context_destroy3() to run
  1071. * directly.
  1072. *
  1073. * - lws_context_destroy3() destroys any internal event loops and then
  1074. * destroys the context itself, setting what was info.pcontext to NULL.
  1075. */
  1076. /*
  1077. * destroy the actual context itself
  1078. */
  1079. static void
  1080. lws_context_destroy3(struct lws_context *context)
  1081. {
  1082. struct lws_context **pcontext_finalize = context->pcontext_finalize;
  1083. int n;
  1084. #if defined(LWS_WITH_NETWORK)
  1085. context->finalize_destroy_after_internal_loops_stopped = 1;
  1086. if (context->event_loop_ops->destroy_context2)
  1087. context->event_loop_ops->destroy_context2(context);
  1088. for (n = 0; n < context->count_threads; n++) {
  1089. struct lws_context_per_thread *pt = &context->pt[n];
  1090. (void)pt;
  1091. #if defined(LWS_WITH_SEQUENCER)
  1092. lws_seq_destroy_all_on_pt(pt);
  1093. #endif
  1094. LWS_FOR_EVERY_AVAILABLE_ROLE_START(ar) {
  1095. if (ar->pt_init_destroy)
  1096. ar->pt_init_destroy(context, NULL, pt, 1);
  1097. } LWS_FOR_EVERY_AVAILABLE_ROLE_END;
  1098. #if defined(LWS_WITH_CGI)
  1099. role_ops_cgi.pt_init_destroy(context, NULL, pt, 1);
  1100. #endif
  1101. #if 0
  1102. if (context->event_loop_ops->destroy_pt)
  1103. context->event_loop_ops->destroy_pt(context, n);
  1104. #endif
  1105. #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
  1106. while (pt->http.ah_list)
  1107. _lws_destroy_ah(pt, pt->http.ah_list);
  1108. #endif
  1109. }
  1110. #if defined(LWS_WITH_SYS_SMD)
  1111. _lws_smd_destroy(context);
  1112. #endif
  1113. #if defined(LWS_WITH_SYS_ASYNC_DNS)
  1114. lws_async_dns_deinit(&context->async_dns);
  1115. #endif
  1116. #if defined(LWS_WITH_SYS_DHCP_CLIENT)
  1117. lws_dhcpc_remove(context, NULL);
  1118. #endif
  1119. if (context->pt[0].fds)
  1120. lws_free_set_NULL(context->pt[0].fds);
  1121. #endif
  1122. lws_context_deinit_ssl_library(context);
  1123. #if defined(LWS_WITH_DETAILED_LATENCIES)
  1124. if (context->latencies_fd != -1)
  1125. compatible_close(context->latencies_fd);
  1126. #endif
  1127. for (n = 0; n < LWS_SYSBLOB_TYPE_COUNT; n++)
  1128. lws_system_blob_destroy(
  1129. lws_system_get_blob(context, n, 0));
  1130. #if LWS_MAX_SMP > 1
  1131. lws_mutex_refcount_destroy(&context->mr);
  1132. #endif
  1133. /* drop any lingering deferred vhost frees */
  1134. while (context->deferred_free_list) {
  1135. struct lws_deferred_free *df = context->deferred_free_list;
  1136. context->deferred_free_list = df->next;
  1137. lws_free(df);
  1138. };
  1139. #if defined(LWS_WITH_EVLIB_PLUGINS) && defined(LWS_WITH_EVENT_LIBS)
  1140. if (context->evlib_plugin_list)
  1141. lws_plugins_destroy(&context->evlib_plugin_list, NULL, NULL);
  1142. #endif
  1143. lws_free(context);
  1144. lwsl_debug("%s: ctx %p freed\n", __func__, context);
  1145. if (pcontext_finalize)
  1146. *pcontext_finalize = NULL;
  1147. }
  1148. /*
  1149. * really start destroying things
  1150. */
  1151. void
  1152. lws_context_destroy2(struct lws_context *context)
  1153. {
  1154. #if defined(LWS_WITH_NETWORK)
  1155. struct lws_vhost *vh = NULL, *vh1;
  1156. int n;
  1157. #endif
  1158. #if defined(LWS_WITH_PEER_LIMITS)
  1159. uint32_t nu;
  1160. #endif
  1161. lwsl_info("%s: ctx %p\n", __func__, context);
  1162. lws_context_lock(context, "context destroy 2"); /* ------ context { */
  1163. context->being_destroyed2 = 1;
  1164. #if defined(LWS_WITH_NETWORK)
  1165. /*
  1166. * We're going to trash things like vhost-protocols
  1167. * So we need to finish dealing with wsi close that
  1168. * might make callbacks first
  1169. */
  1170. for (n = 0; n < context->count_threads; n++) {
  1171. struct lws_context_per_thread *pt = &context->pt[n];
  1172. (void)pt;
  1173. #if defined(LWS_WITH_SECURE_STREAMS)
  1174. lws_dll2_foreach_safe(&pt->ss_owner, NULL, lws_ss_destroy_dll);
  1175. #if !defined(LWS_WITH_SECURE_STREAMS_STATIC_POLICY_ONLY)
  1176. while (context->server_der_list) {
  1177. struct lws_ss_x509 *x = context->server_der_list;
  1178. context->server_der_list = x->next;
  1179. lws_free((void *)x->ca_der);
  1180. }
  1181. if (context->ac_policy)
  1182. lwsac_free(&context->ac_policy);
  1183. #endif
  1184. #endif
  1185. #if defined(LWS_WITH_SECURE_STREAMS_PROXY_API)
  1186. lws_dll2_foreach_safe(&pt->ss_client_owner, NULL, lws_sspc_destroy_dll);
  1187. #endif
  1188. #if defined(LWS_WITH_SEQUENCER)
  1189. lws_seq_destroy_all_on_pt(pt);
  1190. #endif
  1191. LWS_FOR_EVERY_AVAILABLE_ROLE_START(ar) {
  1192. if (ar->pt_init_destroy)
  1193. ar->pt_init_destroy(context, NULL, pt, 1);
  1194. } LWS_FOR_EVERY_AVAILABLE_ROLE_END;
  1195. #if defined(LWS_WITH_CGI)
  1196. role_ops_cgi.pt_init_destroy(context, NULL, pt, 1);
  1197. #endif
  1198. if (context->event_loop_ops->destroy_pt)
  1199. context->event_loop_ops->destroy_pt(context, n);
  1200. #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
  1201. while (pt->http.ah_list)
  1202. _lws_destroy_ah(pt, pt->http.ah_list);
  1203. #endif
  1204. }
  1205. /*
  1206. * free all the per-vhost allocations
  1207. */
  1208. vh = context->vhost_list;
  1209. while (vh) {
  1210. vh1 = vh->vhost_next;
  1211. __lws_vhost_destroy2(vh);
  1212. vh = vh1;
  1213. }
  1214. lwsl_debug("%p: post vh listl\n", __func__);
  1215. /* remove ourselves from the pending destruction list */
  1216. while (context->vhost_pending_destruction_list)
  1217. /* removes itself from list */
  1218. __lws_vhost_destroy2(context->vhost_pending_destruction_list);
  1219. #endif
  1220. lwsl_debug("%p: post pdl\n", __func__);
  1221. lws_stats_log_dump(context);
  1222. #if defined(LWS_WITH_NETWORK)
  1223. lws_ssl_context_destroy(context);
  1224. #endif
  1225. lws_plat_context_late_destroy(context);
  1226. #if defined(LWS_WITH_PEER_LIMITS)
  1227. for (nu = 0; nu < context->pl_hash_elements; nu++) {
  1228. lws_start_foreach_llp(struct lws_peer **, peer,
  1229. context->pl_hash_table[nu]) {
  1230. struct lws_peer *df = *peer;
  1231. *peer = df->next;
  1232. lws_free(df);
  1233. continue;
  1234. } lws_end_foreach_llp(peer, next);
  1235. }
  1236. lws_free(context->pl_hash_table);
  1237. #endif
  1238. lwsl_debug("%p: baggage\n", __func__);
  1239. if (context->external_baggage_free_on_destroy)
  1240. free(context->external_baggage_free_on_destroy);
  1241. #if defined(LWS_WITH_NETWORK)
  1242. lws_check_deferred_free(context, 0, 1);
  1243. #endif
  1244. lws_context_unlock(context); /* } context ------ */
  1245. #if defined(LWS_WITH_NETWORK)
  1246. if (context->event_loop_ops->destroy_context2)
  1247. if (context->event_loop_ops->destroy_context2(context)) {
  1248. context->finalize_destroy_after_internal_loops_stopped = 1;
  1249. return;
  1250. }
  1251. lwsl_debug("%p: post dc2\n", __func__);
  1252. // if (!context->pt[0].event_loop_foreign) {
  1253. // int n;
  1254. for (n = 0; n < context->count_threads; n++)
  1255. if (context->pt[n].inside_service) {
  1256. lwsl_debug("%p: bailing as inside service\n", __func__);
  1257. return;
  1258. }
  1259. // }
  1260. #endif
  1261. lws_context_destroy3(context);
  1262. }
  1263. #if defined(LWS_WITH_NETWORK)
  1264. static void
  1265. lws_pt_destroy(struct lws_context_per_thread *pt)
  1266. {
  1267. volatile struct lws_foreign_thread_pollfd *ftp, *next;
  1268. volatile struct lws_context_per_thread *vpt;
  1269. assert(!pt->is_destroyed);
  1270. pt->destroy_self = 0;
  1271. vpt = (volatile struct lws_context_per_thread *)pt;
  1272. ftp = vpt->foreign_pfd_list;
  1273. while (ftp) {
  1274. next = ftp->next;
  1275. lws_free((void *)ftp);
  1276. ftp = next;
  1277. }
  1278. vpt->foreign_pfd_list = NULL;
  1279. lws_pt_lock(pt, __func__);
  1280. if (pt->pipe_wsi)
  1281. lws_destroy_event_pipe(pt->pipe_wsi);
  1282. lws_pt_unlock(pt);
  1283. pt->pipe_wsi = NULL;
  1284. while (pt->fds_count) {
  1285. struct lws *wsi = wsi_from_fd(pt->context, pt->fds[0].fd);
  1286. if (!wsi)
  1287. break;
  1288. lws_close_free_wsi(wsi,
  1289. LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY,
  1290. "ctx destroy"
  1291. /* no protocol close */);
  1292. }
  1293. lws_pt_mutex_destroy(pt);
  1294. pt->is_destroyed = 1;
  1295. lwsl_info("%s: pt destroyed\n", __func__);
  1296. }
  1297. #endif
  1298. /*
  1299. * Begin the context takedown
  1300. */
  1301. void
  1302. lws_context_destroy(struct lws_context *context)
  1303. {
  1304. #if defined(LWS_WITH_NETWORK)
  1305. struct lws_vhost *vh = NULL;
  1306. int m, deferred_pt = 0;
  1307. #endif
  1308. if (!context || context->inside_context_destroy)
  1309. return;
  1310. context->inside_context_destroy = 1;
  1311. #if defined(LWS_WITH_NETWORK)
  1312. if (context->finalize_destroy_after_internal_loops_stopped) {
  1313. if (context->event_loop_ops->destroy_context2)
  1314. context->event_loop_ops->destroy_context2(context);
  1315. lws_context_destroy3(context);
  1316. /* context is invalid, no need to reset inside flag */
  1317. return;
  1318. }
  1319. #endif
  1320. if (context->being_destroyed1) {
  1321. if (!context->being_destroyed2) {
  1322. lws_context_destroy2(context);
  1323. return;
  1324. }
  1325. lwsl_info("%s: ctx %p: already being destroyed\n",
  1326. __func__, context);
  1327. lws_context_destroy3(context);
  1328. /* context is invalid, no need to reset inside flag */
  1329. return;
  1330. }
  1331. lwsl_info("%s: ctx %p\n", __func__, context);
  1332. context->being_destroyed = 1;
  1333. #if defined(LWS_WITH_NETWORK)
  1334. #if defined(LWS_WITH_SYS_STATE)
  1335. lws_state_transition(&context->mgr_system, LWS_SYSTATE_POLICY_INVALID);
  1336. #endif
  1337. m = context->count_threads;
  1338. while (m--) {
  1339. struct lws_context_per_thread *pt = &context->pt[m];
  1340. if (pt->is_destroyed)
  1341. continue;
  1342. if (pt->inside_lws_service) {
  1343. pt->destroy_self = 1;
  1344. deferred_pt = 1;
  1345. continue;
  1346. }
  1347. lws_pt_destroy(pt);
  1348. }
  1349. if (deferred_pt) {
  1350. lwsl_info("%s: waiting for deferred pt close\n", __func__);
  1351. lws_cancel_service(context);
  1352. goto out;
  1353. }
  1354. context->being_destroyed1 = 1;
  1355. context->requested_kill = 1;
  1356. /*
  1357. * inform all the protocols that they are done and will have no more
  1358. * callbacks.
  1359. *
  1360. * We can't free things until after the event loop shuts down.
  1361. */
  1362. if (context->protocol_init_done)
  1363. vh = context->vhost_list;
  1364. while (vh) {
  1365. struct lws_vhost *vhn = vh->vhost_next;
  1366. lws_vhost_destroy1(vh);
  1367. vh = vhn;
  1368. }
  1369. #endif
  1370. lws_plat_context_early_destroy(context);
  1371. #if defined(LWS_WITH_NETWORK)
  1372. /*
  1373. * We face two different needs depending if foreign loop or not.
  1374. *
  1375. * 1) If foreign loop, we really want to advance the destroy_context()
  1376. * past here, and block only for libuv-style async close completion.
  1377. *
  1378. * 2a) If poll, and we exited by ourselves and are calling a final
  1379. * destroy_context() outside of any service already, we want to
  1380. * advance all the way in one step.
  1381. *
  1382. * 2b) If poll, and we are reacting to a SIGINT, service thread(s) may
  1383. * be in poll wait or servicing. We can't advance the
  1384. * destroy_context() to the point it's freeing things; we have to
  1385. * leave that for the final destroy_context() after the service
  1386. * thread(s) are finished calling for service.
  1387. */
  1388. if (context->event_loop_ops->destroy_context1) {
  1389. context->event_loop_ops->destroy_context1(context);
  1390. goto out;
  1391. }
  1392. #endif
  1393. #if defined(LWS_PLAT_FREERTOS)
  1394. #if defined(LWS_AMAZON_RTOS)
  1395. context->last_free_heap = xPortGetFreeHeapSize();
  1396. #else
  1397. context->last_free_heap = esp_get_free_heap_size();
  1398. #endif
  1399. #endif
  1400. context->inside_context_destroy = 0;
  1401. lws_context_destroy2(context);
  1402. return;
  1403. #if defined(LWS_WITH_NETWORK)
  1404. out:
  1405. context->inside_context_destroy = 0;
  1406. #endif
  1407. }
  1408. #if defined(LWS_WITH_SYS_STATE)
  1409. struct lws_context *
  1410. lws_system_context_from_system_mgr(lws_state_manager_t *mgr)
  1411. {
  1412. #if defined(LWS_WITH_NETWORK)
  1413. return mgr->context;
  1414. #else
  1415. return NULL;
  1416. #endif
  1417. }
  1418. #endif