libwebsockets.c 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671
  1. /*
  2. * libwebsockets - small server side websockets and web server implementation
  3. *
  4. * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation:
  9. * version 2.1 of the License.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. * MA 02110-1301 USA
  20. */
  21. #include "private-libwebsockets.h"
  22. #ifdef LWS_HAVE_SYS_TYPES_H
  23. #include <sys/types.h>
  24. #endif
  25. #if defined(WIN32) || defined(_WIN32)
  26. #else
  27. #include <sys/wait.h>
  28. #endif
  29. int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
  30. static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
  31. static const char * const log_level_names[] = {
  32. "ERR",
  33. "WARN",
  34. "NOTICE",
  35. "INFO",
  36. "DEBUG",
  37. "PARSER",
  38. "HEADER",
  39. "EXTENSION",
  40. "CLIENT",
  41. "LATENCY",
  42. };
  43. void
  44. lws_free_wsi(struct lws *wsi)
  45. {
  46. if (!wsi)
  47. return;
  48. /* Protocol user data may be allocated either internally by lws
  49. * or by specified the user.
  50. * We should only free what we allocated. */
  51. if (wsi->protocol && wsi->protocol->per_session_data_size &&
  52. wsi->user_space && !wsi->user_space_externally_allocated)
  53. lws_free(wsi->user_space);
  54. lws_free_set_NULL(wsi->rxflow_buffer);
  55. lws_free_set_NULL(wsi->trunc_alloc);
  56. /* we may not have an ah, but may be on the waiting list... */
  57. lwsl_info("ah det due to close\n");
  58. lws_header_table_detach(wsi, 0);
  59. wsi->context->count_wsi_allocated--;
  60. lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
  61. wsi->context->count_wsi_allocated);
  62. lws_free(wsi);
  63. }
  64. static void
  65. lws_remove_from_timeout_list(struct lws *wsi)
  66. {
  67. struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
  68. if (!wsi->timeout_list_prev) /* ie, not part of the list */
  69. return;
  70. lws_pt_lock(pt);
  71. /* if we have a next guy, set his prev to our prev */
  72. if (wsi->timeout_list)
  73. wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
  74. /* set our prev guy to our next guy instead of us */
  75. *wsi->timeout_list_prev = wsi->timeout_list;
  76. /* we're out of the list, we should not point anywhere any more */
  77. wsi->timeout_list_prev = NULL;
  78. wsi->timeout_list = NULL;
  79. lws_pt_unlock(pt);
  80. }
  81. LWS_VISIBLE void
  82. lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
  83. {
  84. struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
  85. time_t now;
  86. lws_pt_lock(pt);
  87. time(&now);
  88. if (reason && !wsi->timeout_list_prev) {
  89. /* our next guy is current first guy */
  90. wsi->timeout_list = pt->timeout_list;
  91. /* if there is a next guy, set his prev ptr to our next ptr */
  92. if (wsi->timeout_list)
  93. wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
  94. /* our prev ptr is first ptr */
  95. wsi->timeout_list_prev = &pt->timeout_list;
  96. /* set the first guy to be us */
  97. *wsi->timeout_list_prev = wsi;
  98. }
  99. lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
  100. wsi->pending_timeout_limit = now + secs;
  101. wsi->pending_timeout = reason;
  102. lws_pt_unlock(pt);
  103. if (!reason)
  104. lws_remove_from_timeout_list(wsi);
  105. }
  106. void
  107. lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
  108. {
  109. struct lws_context_per_thread *pt;
  110. struct lws **pwsi, *wsi1, *wsi2;
  111. struct lws_context *context;
  112. struct lws_tokens eff_buf;
  113. int n, m, ret;
  114. if (!wsi)
  115. return;
  116. lws_access_log(wsi);
  117. #if defined(LWS_WITH_ESP8266)
  118. if (wsi->premature_rx)
  119. lws_free(wsi->premature_rx);
  120. if (wsi->pending_send_completion && !wsi->close_is_pending_send_completion) {
  121. lwsl_notice("delaying close\n");
  122. wsi->close_is_pending_send_completion = 1;
  123. return;
  124. }
  125. #endif
  126. if (wsi->u.hdr.ah)
  127. /* we're closing, losing some rx is OK */
  128. wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
  129. context = wsi->context;
  130. pt = &context->pt[(int)wsi->tsi];
  131. /* if we have children, close them first */
  132. if (wsi->child_list) {
  133. wsi2 = wsi->child_list;
  134. while (wsi2) {
  135. //lwsl_notice("%s: closing %p: close child %p\n",
  136. // __func__, wsi, wsi2);
  137. wsi1 = wsi2->sibling_list;
  138. //lwsl_notice("%s: closing %p: next sibling %p\n",
  139. // __func__, wsi2, wsi1);
  140. wsi2->parent = NULL;
  141. /* stop it doing shutdown processing */
  142. wsi2->socket_is_permanently_unusable = 1;
  143. lws_close_free_wsi(wsi2, reason);
  144. wsi2 = wsi1;
  145. }
  146. wsi->child_list = NULL;
  147. }
  148. #ifdef LWS_WITH_CGI
  149. if (wsi->mode == LWSCM_CGI) {
  150. /* we are not a network connection, but a handler for CGI io */
  151. if (wsi->parent && wsi->parent->cgi)
  152. /* end the binding between us and master */
  153. wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
  154. wsi->socket_is_permanently_unusable = 1;
  155. lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
  156. goto just_kill_connection;
  157. }
  158. if (wsi->cgi) {
  159. struct lws_cgi **pcgi = &pt->cgi_list;
  160. /* remove us from the cgi list */
  161. lwsl_debug("%s: remove cgi %p from list\n", __func__, wsi->cgi);
  162. while (*pcgi) {
  163. if (*pcgi == wsi->cgi) {
  164. /* drop us from the pt cgi list */
  165. *pcgi = (*pcgi)->cgi_list;
  166. break;
  167. }
  168. pcgi = &(*pcgi)->cgi_list;
  169. }
  170. /* we have a cgi going, we must kill it */
  171. wsi->cgi->being_closed = 1;
  172. lws_cgi_kill(wsi);
  173. }
  174. #endif
  175. if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
  176. wsi->u.http.fd != LWS_INVALID_FILE) {
  177. lws_plat_file_close(wsi, wsi->u.http.fd);
  178. wsi->u.http.fd = LWS_INVALID_FILE;
  179. wsi->vhost->protocols->callback(wsi,
  180. LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
  181. wsi->told_user_closed = 1;
  182. }
  183. if (wsi->socket_is_permanently_unusable ||
  184. reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
  185. wsi->state == LWSS_SHUTDOWN)
  186. goto just_kill_connection;
  187. wsi->state_pre_close = wsi->state;
  188. switch (wsi->state_pre_close) {
  189. case LWSS_DEAD_SOCKET:
  190. return;
  191. /* we tried the polite way... */
  192. case LWSS_AWAITING_CLOSE_ACK:
  193. goto just_kill_connection;
  194. case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
  195. if (wsi->trunc_len) {
  196. lws_callback_on_writable(wsi);
  197. return;
  198. }
  199. lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
  200. goto just_kill_connection;
  201. default:
  202. if (wsi->trunc_len) {
  203. lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
  204. wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
  205. lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
  206. return;
  207. }
  208. break;
  209. }
  210. if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
  211. wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
  212. goto just_kill_connection;
  213. if (wsi->mode == LWSCM_HTTP_SERVING) {
  214. if (wsi->user_space)
  215. wsi->vhost->protocols->callback(wsi,
  216. LWS_CALLBACK_HTTP_DROP_PROTOCOL,
  217. wsi->user_space, NULL, 0);
  218. wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
  219. wsi->user_space, NULL, 0);
  220. wsi->told_user_closed = 1;
  221. }
  222. if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
  223. wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
  224. wsi->user_space, NULL, 0);
  225. wsi->told_user_closed = 1;
  226. }
  227. /*
  228. * are his extensions okay with him closing? Eg he might be a mux
  229. * parent and just his ch1 aspect is closing?
  230. */
  231. if (lws_ext_cb_active(wsi,
  232. LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
  233. lwsl_ext("extension vetoed close\n");
  234. return;
  235. }
  236. /*
  237. * flush any tx pending from extensions, since we may send close packet
  238. * if there are problems with send, just nuke the connection
  239. */
  240. do {
  241. ret = 0;
  242. eff_buf.token = NULL;
  243. eff_buf.token_len = 0;
  244. /* show every extension the new incoming data */
  245. m = lws_ext_cb_active(wsi,
  246. LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
  247. if (m < 0) {
  248. lwsl_ext("Extension reports fatal error\n");
  249. goto just_kill_connection;
  250. }
  251. if (m)
  252. /*
  253. * at least one extension told us he has more
  254. * to spill, so we will go around again after
  255. */
  256. ret = 1;
  257. /* assuming they left us something to send, send it */
  258. if (eff_buf.token_len)
  259. if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
  260. eff_buf.token_len) !=
  261. eff_buf.token_len) {
  262. lwsl_debug("close: ext spill failed\n");
  263. goto just_kill_connection;
  264. }
  265. } while (ret);
  266. /*
  267. * signal we are closing, lws_write will
  268. * add any necessary version-specific stuff. If the write fails,
  269. * no worries we are closing anyway. If we didn't initiate this
  270. * close, then our state has been changed to
  271. * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
  272. *
  273. * Likewise if it's a second call to close this connection after we
  274. * sent the close indication to the peer already, we are in state
  275. * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
  276. */
  277. if (wsi->state_pre_close == LWSS_ESTABLISHED &&
  278. (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
  279. (reason != LWS_CLOSE_STATUS_NOSTATUS &&
  280. (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
  281. lwsl_debug("sending close indication...\n");
  282. /* if no prepared close reason, use 1000 and no aux data */
  283. if (!wsi->u.ws.close_in_ping_buffer_len) {
  284. wsi->u.ws.close_in_ping_buffer_len = 2;
  285. wsi->u.ws.ping_payload_buf[LWS_PRE] =
  286. (reason >> 16) & 0xff;
  287. wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
  288. reason & 0xff;
  289. }
  290. #if defined (LWS_WITH_ESP8266)
  291. wsi->close_is_pending_send_completion = 1;
  292. #endif
  293. n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
  294. wsi->u.ws.close_in_ping_buffer_len,
  295. LWS_WRITE_CLOSE);
  296. if (n >= 0) {
  297. /*
  298. * we have sent a nice protocol level indication we
  299. * now wish to close, we should not send anything more
  300. */
  301. wsi->state = LWSS_AWAITING_CLOSE_ACK;
  302. /*
  303. * ...and we should wait for a reply for a bit
  304. * out of politeness
  305. */
  306. lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
  307. lwsl_debug("sent close indication, awaiting ack\n");
  308. return;
  309. }
  310. lwsl_info("close: sending close packet failed, hanging up\n");
  311. /* else, the send failed and we should just hang up */
  312. }
  313. just_kill_connection:
  314. if (wsi->parent) {
  315. /* detach ourselves from parent's child list */
  316. pwsi = &wsi->parent->child_list;
  317. while (*pwsi) {
  318. if (*pwsi == wsi) {
  319. //lwsl_notice("%s: detach %p from parent %p\n",
  320. // __func__, wsi, wsi->parent);
  321. *pwsi = wsi->sibling_list;
  322. break;
  323. }
  324. pwsi = &(*pwsi)->sibling_list;
  325. }
  326. if (*pwsi)
  327. lwsl_err("%s: failed to detach from parent\n",
  328. __func__);
  329. }
  330. #if LWS_POSIX
  331. /*
  332. * Testing with ab shows that we have to stage the socket close when
  333. * the system is under stress... shutdown any further TX, change the
  334. * state to one that won't emit anything more, and wait with a timeout
  335. * for the POLLIN to show a zero-size rx before coming back and doing
  336. * the actual close.
  337. */
  338. if (wsi->state != LWSS_SHUTDOWN &&
  339. wsi->state != LWSS_CLIENT_UNCONNECTED &&
  340. reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
  341. !wsi->socket_is_permanently_unusable) {
  342. lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, wsi->sock, wsi->state);
  343. n = shutdown(wsi->sock, SHUT_WR);
  344. if (n)
  345. lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
  346. // This causes problems with disconnection when the events are half closing connection
  347. // FD_READ | FD_CLOSE (33)
  348. #ifndef _WIN32_WCE
  349. /* libuv: no event available to guarantee completion */
  350. if (!LWS_LIBUV_ENABLED(context)) {
  351. lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
  352. wsi->state = LWSS_SHUTDOWN;
  353. lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
  354. context->timeout_secs);
  355. return;
  356. }
  357. #endif
  358. }
  359. #endif
  360. lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
  361. wsi, wsi->sock);
  362. #ifdef LWS_WITH_HTTP_PROXY
  363. if (wsi->rw) {
  364. lws_rewrite_destroy(wsi->rw);
  365. wsi->rw = NULL;
  366. }
  367. #endif
  368. /*
  369. * we won't be servicing or receiving anything further from this guy
  370. * delete socket from the internal poll list if still present
  371. */
  372. lws_ssl_remove_wsi_from_buffered_list(wsi);
  373. lws_remove_from_timeout_list(wsi);
  374. /* checking return redundant since we anyway close */
  375. if (wsi->sock != LWS_SOCK_INVALID)
  376. remove_wsi_socket_from_fds(wsi);
  377. #if defined(LWS_WITH_ESP8266)
  378. espconn_disconnect(wsi->sock);
  379. #endif
  380. wsi->state = LWSS_DEAD_SOCKET;
  381. lws_free_set_NULL(wsi->rxflow_buffer);
  382. if (wsi->state_pre_close == LWSS_ESTABLISHED ||
  383. wsi->mode == LWSCM_WS_SERVING ||
  384. wsi->mode == LWSCM_WS_CLIENT) {
  385. if (wsi->u.ws.rx_draining_ext) {
  386. struct lws **w = &pt->rx_draining_ext_list;
  387. wsi->u.ws.rx_draining_ext = 0;
  388. /* remove us from context draining ext list */
  389. while (*w) {
  390. if (*w == wsi) {
  391. *w = wsi->u.ws.rx_draining_ext_list;
  392. break;
  393. }
  394. w = &((*w)->u.ws.rx_draining_ext_list);
  395. }
  396. wsi->u.ws.rx_draining_ext_list = NULL;
  397. }
  398. if (wsi->u.ws.tx_draining_ext) {
  399. struct lws **w = &pt->tx_draining_ext_list;
  400. wsi->u.ws.tx_draining_ext = 0;
  401. /* remove us from context draining ext list */
  402. while (*w) {
  403. if (*w == wsi) {
  404. *w = wsi->u.ws.tx_draining_ext_list;
  405. break;
  406. }
  407. w = &((*w)->u.ws.tx_draining_ext_list);
  408. }
  409. wsi->u.ws.tx_draining_ext_list = NULL;
  410. }
  411. lws_free_set_NULL(wsi->u.ws.rx_ubuf);
  412. if (wsi->trunc_alloc)
  413. /* not going to be completed... nuke it */
  414. lws_free_set_NULL(wsi->trunc_alloc);
  415. wsi->u.ws.ping_payload_len = 0;
  416. wsi->u.ws.ping_pending_flag = 0;
  417. }
  418. /* tell the user it's all over for this guy */
  419. if (wsi->protocol && wsi->protocol->callback &&
  420. ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
  421. (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
  422. (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
  423. (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
  424. (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
  425. (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
  426. if (wsi->user_space) {
  427. lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s", __func__, wsi, wsi->protocol->name);
  428. wsi->protocol->callback(wsi,
  429. LWS_CALLBACK_HTTP_DROP_PROTOCOL,
  430. wsi->user_space, NULL, 0);
  431. }
  432. lwsl_debug("calling back CLOSED\n");
  433. wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
  434. wsi->user_space, NULL, 0);
  435. } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
  436. lwsl_debug("calling back CLOSED_HTTP\n");
  437. wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
  438. wsi->user_space, NULL, 0 );
  439. } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
  440. wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
  441. !wsi->already_did_cce) {
  442. wsi->vhost->protocols[0].callback(wsi,
  443. LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
  444. wsi->user_space, NULL, 0);
  445. } else
  446. lwsl_debug("not calling back closed mode=%d state=%d\n",
  447. wsi->mode, wsi->state_pre_close);
  448. /* deallocate any active extension contexts */
  449. if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
  450. lwsl_warn("extension destruction failed\n");
  451. /*
  452. * inform all extensions in case they tracked this guy out of band
  453. * even though not active on him specifically
  454. */
  455. if (lws_ext_cb_all_exts(context, wsi,
  456. LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
  457. lwsl_warn("ext destroy wsi failed\n");
  458. wsi->socket_is_permanently_unusable = 1;
  459. #ifdef LWS_USE_LIBUV
  460. if (LWS_LIBUV_ENABLED(context)) {
  461. lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
  462. /* libuv has to do his own close handle processing asynchronously */
  463. lws_libuv_closehandle(wsi);
  464. return;
  465. }
  466. #endif
  467. lws_close_free_wsi_final(wsi);
  468. }
  469. void
  470. lws_close_free_wsi_final(struct lws *wsi)
  471. {
  472. int n;
  473. if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
  474. #if LWS_POSIX
  475. //lwsl_err("*** closing sockfd %d\n", wsi->sock);
  476. n = compatible_close(wsi->sock);
  477. if (n)
  478. lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
  479. #else
  480. compatible_close(wsi->sock);
  481. (void)n;
  482. #endif
  483. wsi->sock = LWS_SOCK_INVALID;
  484. }
  485. /* outermost destroy notification for wsi (user_space still intact) */
  486. wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
  487. wsi->user_space, NULL, 0);
  488. #ifdef LWS_WITH_CGI
  489. if (wsi->cgi) {
  490. for (n = 0; n < 6; n++)
  491. if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
  492. close(wsi->cgi->pipe_fds[n / 2][n & 1]);
  493. lws_free(wsi->cgi);
  494. }
  495. #endif
  496. lws_free_wsi(wsi);
  497. }
  498. LWS_VISIBLE LWS_EXTERN const char *
  499. lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
  500. {
  501. int n = 0, sl = strlen(name);
  502. while (lws_hdr_copy_fragment(wsi, buf, len,
  503. WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
  504. if (!strncmp(buf, name, sl))
  505. return buf + sl;
  506. n++;
  507. }
  508. return NULL;
  509. }
  510. #if LWS_POSIX
  511. LWS_VISIBLE int
  512. interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
  513. {
  514. int ipv6 = 0;
  515. #ifdef LWS_USE_IPV6
  516. ipv6 = LWS_IPV6_ENABLED(vh);
  517. #endif
  518. (void)vh;
  519. return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
  520. }
  521. #endif
  522. #if LWS_POSIX
  523. static int
  524. lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
  525. int name_len, char *rip, int rip_len)
  526. {
  527. #if LWS_POSIX
  528. struct addrinfo ai, *res;
  529. struct sockaddr_in addr4;
  530. if (rip)
  531. rip[0] = '\0';
  532. name[0] = '\0';
  533. addr4.sin_family = AF_UNSPEC;
  534. #ifdef LWS_USE_IPV6
  535. if (LWS_IPV6_ENABLED(vh)) {
  536. if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
  537. lwsl_err("inet_ntop", strerror(LWS_ERRNO));
  538. return -1;
  539. }
  540. // Strip off the IPv4 to IPv6 header if one exists
  541. if (strncmp(rip, "::ffff:", 7) == 0)
  542. memmove(rip, rip + 7, strlen(rip) - 6);
  543. getnameinfo((struct sockaddr *)ads,
  544. sizeof(struct sockaddr_in6), name,
  545. name_len, NULL, 0, 0);
  546. return 0;
  547. } else
  548. #endif
  549. {
  550. struct addrinfo *result;
  551. memset(&ai, 0, sizeof ai);
  552. ai.ai_family = PF_UNSPEC;
  553. ai.ai_socktype = SOCK_STREAM;
  554. ai.ai_flags = AI_CANONNAME;
  555. if (getnameinfo((struct sockaddr *)ads,
  556. sizeof(struct sockaddr_in),
  557. name, name_len, NULL, 0, 0))
  558. return -1;
  559. if (!rip)
  560. return 0;
  561. if (getaddrinfo(name, NULL, &ai, &result))
  562. return -1;
  563. res = result;
  564. while (addr4.sin_family == AF_UNSPEC && res) {
  565. switch (res->ai_family) {
  566. case AF_INET:
  567. addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
  568. addr4.sin_family = AF_INET;
  569. break;
  570. }
  571. res = res->ai_next;
  572. }
  573. freeaddrinfo(result);
  574. }
  575. if (addr4.sin_family == AF_UNSPEC)
  576. return -1;
  577. if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
  578. return -1;
  579. return 0;
  580. #else
  581. (void)vh;
  582. (void)ads;
  583. (void)name;
  584. (void)name_len;
  585. (void)rip;
  586. (void)rip_len;
  587. return -1;
  588. #endif
  589. }
  590. #endif
  591. LWS_VISIBLE const char *
  592. lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
  593. {
  594. #if LWS_POSIX
  595. socklen_t len, olen;
  596. #ifdef LWS_USE_IPV6
  597. struct sockaddr_in6 sin6;
  598. #endif
  599. struct sockaddr_in sin4;
  600. int af = AF_INET;
  601. void *p, *q;
  602. #ifdef LWS_USE_IPV6
  603. if (LWS_IPV6_ENABLED(wsi->vhost)) {
  604. len = sizeof(sin6);
  605. p = &sin6;
  606. af = AF_INET6;
  607. q = &sin6.sin6_addr;
  608. } else
  609. #endif
  610. {
  611. len = sizeof(sin4);
  612. p = &sin4;
  613. q = &sin4.sin_addr;
  614. }
  615. olen = len;
  616. if (getpeername(wsi->sock, p, &len) < 0 || len > olen) {
  617. lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
  618. return NULL;
  619. }
  620. return lws_plat_inet_ntop(af, q, name, namelen);
  621. #else
  622. #if defined(LWS_WITH_ESP8266)
  623. return lws_plat_get_peer_simple(wsi, name, namelen);
  624. #else
  625. return NULL;
  626. #endif
  627. #endif
  628. }
  629. LWS_VISIBLE void
  630. lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
  631. int name_len, char *rip, int rip_len)
  632. {
  633. #if LWS_POSIX
  634. socklen_t len;
  635. #ifdef LWS_USE_IPV6
  636. struct sockaddr_in6 sin6;
  637. #endif
  638. struct sockaddr_in sin4;
  639. struct lws_context *context = wsi->context;
  640. int ret = -1;
  641. void *p;
  642. rip[0] = '\0';
  643. name[0] = '\0';
  644. lws_latency_pre(context, wsi);
  645. #ifdef LWS_USE_IPV6
  646. if (LWS_IPV6_ENABLED(wsi->vhost)) {
  647. len = sizeof(sin6);
  648. p = &sin6;
  649. } else
  650. #endif
  651. {
  652. len = sizeof(sin4);
  653. p = &sin4;
  654. }
  655. if (getpeername(fd, p, &len) < 0) {
  656. lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
  657. goto bail;
  658. }
  659. ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
  660. bail:
  661. lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
  662. #else
  663. (void)wsi;
  664. (void)fd;
  665. (void)name;
  666. (void)name_len;
  667. (void)rip;
  668. (void)rip_len;
  669. #endif
  670. }
  671. LWS_EXTERN void *
  672. lws_context_user(struct lws_context *context)
  673. {
  674. return context->user_space;
  675. }
  676. LWS_VISIBLE struct lws_vhost *
  677. lws_vhost_get(struct lws *wsi)
  678. {
  679. return wsi->vhost;
  680. }
  681. LWS_VISIBLE struct lws_vhost *
  682. lws_get_vhost(struct lws *wsi)
  683. {
  684. return wsi->vhost;
  685. }
  686. LWS_VISIBLE const struct lws_protocols *
  687. lws_protocol_get(struct lws *wsi)
  688. {
  689. return wsi->protocol;
  690. }
  691. LWS_VISIBLE int
  692. lws_callback_all_protocol(struct lws_context *context,
  693. const struct lws_protocols *protocol, int reason)
  694. {
  695. struct lws_context_per_thread *pt = &context->pt[0];
  696. unsigned int n, m = context->count_threads;
  697. struct lws *wsi;
  698. while (m--) {
  699. for (n = 0; n < pt->fds_count; n++) {
  700. wsi = wsi_from_fd(context, pt->fds[n].fd);
  701. if (!wsi)
  702. continue;
  703. if (wsi->protocol == protocol)
  704. protocol->callback(wsi, reason, wsi->user_space,
  705. NULL, 0);
  706. }
  707. pt++;
  708. }
  709. return 0;
  710. }
  711. LWS_VISIBLE int
  712. lws_callback_all_protocol_vhost(struct lws_vhost *vh,
  713. const struct lws_protocols *protocol, int reason)
  714. {
  715. struct lws_context *context = vh->context;
  716. struct lws_context_per_thread *pt = &context->pt[0];
  717. unsigned int n, m = context->count_threads;
  718. struct lws *wsi;
  719. while (m--) {
  720. for (n = 0; n < pt->fds_count; n++) {
  721. wsi = wsi_from_fd(context, pt->fds[n].fd);
  722. if (!wsi)
  723. continue;
  724. if (wsi->vhost == vh && wsi->protocol == protocol)
  725. protocol->callback(wsi, reason, wsi->user_space,
  726. NULL, 0);
  727. }
  728. pt++;
  729. }
  730. return 0;
  731. }
  732. LWS_VISIBLE LWS_EXTERN int
  733. lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
  734. {
  735. int n;
  736. for (n = 0; n < wsi->vhost->count_protocols; n++)
  737. if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
  738. return 1;
  739. return 0;
  740. }
  741. /**
  742. * lws_now_secs() - seconds since 1970-1-1
  743. *
  744. */
  745. LWS_VISIBLE LWS_EXTERN unsigned long
  746. lws_now_secs(void)
  747. {
  748. struct timeval tv;
  749. gettimeofday(&tv, NULL);
  750. return tv.tv_sec;
  751. }
  752. #if LWS_POSIX
  753. LWS_VISIBLE int
  754. lws_get_socket_fd(struct lws *wsi)
  755. {
  756. return wsi->sock;
  757. }
  758. #endif
  759. #ifdef LWS_LATENCY
  760. void
  761. lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
  762. int ret, int completed)
  763. {
  764. unsigned long long u;
  765. char buf[256];
  766. u = time_in_microseconds();
  767. if (!action) {
  768. wsi->latency_start = u;
  769. if (!wsi->action_start)
  770. wsi->action_start = u;
  771. return;
  772. }
  773. if (completed) {
  774. if (wsi->action_start == wsi->latency_start)
  775. sprintf(buf,
  776. "Completion first try lat %lluus: %p: ret %d: %s\n",
  777. u - wsi->latency_start,
  778. (void *)wsi, ret, action);
  779. else
  780. sprintf(buf,
  781. "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
  782. u - wsi->action_start,
  783. u - wsi->latency_start,
  784. (void *)wsi, ret, action);
  785. wsi->action_start = 0;
  786. } else
  787. sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
  788. u - wsi->latency_start, (void *)wsi, ret, action);
  789. if (u - wsi->latency_start > context->worst_latency) {
  790. context->worst_latency = u - wsi->latency_start;
  791. strcpy(context->worst_latency_info, buf);
  792. }
  793. lwsl_latency("%s", buf);
  794. }
  795. #endif
  796. LWS_VISIBLE int
  797. lws_rx_flow_control(struct lws *wsi, int enable)
  798. {
  799. if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
  800. return 0;
  801. lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
  802. wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
  803. return 0;
  804. }
  805. LWS_VISIBLE void
  806. lws_rx_flow_allow_all_protocol(const struct lws_context *context,
  807. const struct lws_protocols *protocol)
  808. {
  809. const struct lws_context_per_thread *pt = &context->pt[0];
  810. struct lws *wsi;
  811. unsigned int n, m = context->count_threads;
  812. while (m--) {
  813. for (n = 0; n < pt->fds_count; n++) {
  814. wsi = wsi_from_fd(context, pt->fds[n].fd);
  815. if (!wsi)
  816. continue;
  817. if (wsi->protocol == protocol)
  818. lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
  819. }
  820. pt++;
  821. }
  822. }
  823. LWS_VISIBLE extern const char *
  824. lws_canonical_hostname(struct lws_context *context)
  825. {
  826. return (const char *)context->canonical_hostname;
  827. }
  828. int user_callback_handle_rxflow(lws_callback_function callback_function,
  829. struct lws *wsi,
  830. enum lws_callback_reasons reason, void *user,
  831. void *in, size_t len)
  832. {
  833. int n;
  834. n = callback_function(wsi, reason, user, in, len);
  835. if (!n)
  836. n = _lws_rx_flow_control(wsi);
  837. return n;
  838. }
  839. #if defined(LWS_WITH_ESP8266)
  840. #undef strchr
  841. #define strchr ets_strchr
  842. #endif
  843. LWS_VISIBLE int
  844. lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
  845. {
  846. #if !defined(LWS_WITH_ESP8266)
  847. char *p;
  848. char authstring[96];
  849. if (!proxy)
  850. return -1;
  851. p = strchr(proxy, '@');
  852. if (p) { /* auth is around */
  853. if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
  854. goto auth_too_long;
  855. strncpy(authstring, proxy, p - proxy);
  856. // null termination not needed on input
  857. if (lws_b64_encode_string(authstring, (p - proxy),
  858. vhost->proxy_basic_auth_token,
  859. sizeof vhost->proxy_basic_auth_token) < 0)
  860. goto auth_too_long;
  861. lwsl_info(" Proxy auth in use\n");
  862. proxy = p + 1;
  863. } else
  864. vhost->proxy_basic_auth_token[0] = '\0';
  865. strncpy(vhost->http_proxy_address, proxy,
  866. sizeof(vhost->http_proxy_address) - 1);
  867. vhost->http_proxy_address[
  868. sizeof(vhost->http_proxy_address) - 1] = '\0';
  869. p = strchr(vhost->http_proxy_address, ':');
  870. if (!p && !vhost->http_proxy_port) {
  871. lwsl_err("http_proxy needs to be ads:port\n");
  872. return -1;
  873. } else {
  874. if (p) {
  875. *p = '\0';
  876. vhost->http_proxy_port = atoi(p + 1);
  877. }
  878. }
  879. lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
  880. vhost->http_proxy_port);
  881. return 0;
  882. auth_too_long:
  883. lwsl_err("proxy auth too long\n");
  884. #endif
  885. return -1;
  886. }
  887. LWS_VISIBLE const struct lws_protocols *
  888. lws_get_protocol(struct lws *wsi)
  889. {
  890. return wsi->protocol;
  891. }
  892. LWS_VISIBLE int
  893. lws_is_final_fragment(struct lws *wsi)
  894. {
  895. lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
  896. wsi->u.ws.final, wsi->u.ws.rx_packet_length,
  897. wsi->u.ws.rx_draining_ext);
  898. return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
  899. }
  900. LWS_VISIBLE unsigned char
  901. lws_get_reserved_bits(struct lws *wsi)
  902. {
  903. return wsi->u.ws.rsv;
  904. }
  905. int
  906. lws_ensure_user_space(struct lws *wsi)
  907. {
  908. lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
  909. if (!wsi->protocol)
  910. return 1;
  911. /* allocate the per-connection user memory (if any) */
  912. if (wsi->protocol->per_session_data_size && !wsi->user_space) {
  913. wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
  914. if (wsi->user_space == NULL) {
  915. lwsl_err("Out of memory for conn user space\n");
  916. return 1;
  917. }
  918. } else
  919. lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
  920. __func__, wsi, wsi->protocol->per_session_data_size,
  921. wsi->user_space);
  922. return 0;
  923. }
  924. LWS_VISIBLE int
  925. lwsl_timestamp(int level, char *p, int len)
  926. {
  927. time_t o_now = time(NULL);
  928. unsigned long long now;
  929. struct tm *ptm = NULL;
  930. #ifndef WIN32
  931. struct tm tm;
  932. #endif
  933. int n;
  934. #ifndef _WIN32_WCE
  935. #ifdef WIN32
  936. ptm = localtime(&o_now);
  937. #else
  938. if (localtime_r(&o_now, &tm))
  939. ptm = &tm;
  940. #endif
  941. #endif
  942. p[0] = '\0';
  943. for (n = 0; n < LLL_COUNT; n++) {
  944. if (level != (1 << n))
  945. continue;
  946. now = time_in_microseconds() / 100;
  947. if (ptm)
  948. n = lws_snprintf(p, len,
  949. "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
  950. ptm->tm_year + 1900,
  951. ptm->tm_mon + 1,
  952. ptm->tm_mday,
  953. ptm->tm_hour,
  954. ptm->tm_min,
  955. ptm->tm_sec,
  956. (int)(now % 10000), log_level_names[n]);
  957. else
  958. n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
  959. (unsigned long long) now / 10000,
  960. (int)(now % 10000), log_level_names[n]);
  961. return n;
  962. }
  963. return 0;
  964. }
  965. LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
  966. {
  967. #if !defined(LWS_WITH_ESP8266)
  968. char buf[50];
  969. lwsl_timestamp(level, buf, sizeof(buf));
  970. fprintf(stderr, "%s%s", buf, line);
  971. #endif
  972. }
  973. LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
  974. {
  975. #if defined(LWS_WITH_ESP8266)
  976. char buf[128];
  977. #else
  978. char buf[256];
  979. #endif
  980. int n;
  981. if (!(log_level & filter))
  982. return;
  983. n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
  984. (void)n;
  985. #if defined(LWS_WITH_ESP8266)
  986. buf[sizeof(buf) - 1] = '\0';
  987. #else
  988. /* vnsprintf returns what it would have written, even if truncated */
  989. if (n > sizeof(buf) - 1)
  990. n = sizeof(buf) - 1;
  991. if (n > 0)
  992. buf[n] = '\0';
  993. #endif
  994. lwsl_emit(filter, buf);
  995. }
  996. LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
  997. {
  998. va_list ap;
  999. va_start(ap, format);
  1000. _lws_logv(filter, format, ap);
  1001. va_end(ap);
  1002. }
  1003. LWS_VISIBLE void lws_set_log_level(int level,
  1004. void (*func)(int level, const char *line))
  1005. {
  1006. log_level = level;
  1007. if (func)
  1008. lwsl_emit = func;
  1009. }
  1010. LWS_VISIBLE int
  1011. lws_is_ssl(struct lws *wsi)
  1012. {
  1013. #ifdef LWS_OPENSSL_SUPPORT
  1014. return wsi->use_ssl;
  1015. #else
  1016. (void)wsi;
  1017. return 0;
  1018. #endif
  1019. }
  1020. LWS_VISIBLE int
  1021. lws_partial_buffered(struct lws *wsi)
  1022. {
  1023. return !!wsi->trunc_len;
  1024. }
  1025. void lws_set_protocol_write_pending(struct lws *wsi,
  1026. enum lws_pending_protocol_send pend)
  1027. {
  1028. lwsl_info("setting pps %d\n", pend);
  1029. if (wsi->pps)
  1030. lwsl_err("pps overwrite\n");
  1031. wsi->pps = pend;
  1032. lws_rx_flow_control(wsi, 0);
  1033. lws_callback_on_writable(wsi);
  1034. }
  1035. LWS_VISIBLE size_t
  1036. lws_get_peer_write_allowance(struct lws *wsi)
  1037. {
  1038. #ifdef LWS_USE_HTTP2
  1039. /* only if we are using HTTP2 on this connection */
  1040. if (wsi->mode != LWSCM_HTTP2_SERVING)
  1041. return -1;
  1042. /* user is only interested in how much he can send, or that he can't */
  1043. if (wsi->u.http2.tx_credit <= 0)
  1044. return 0;
  1045. return wsi->u.http2.tx_credit;
  1046. #else
  1047. (void)wsi;
  1048. return -1;
  1049. #endif
  1050. }
  1051. LWS_VISIBLE void
  1052. lws_union_transition(struct lws *wsi, enum connection_mode mode)
  1053. {
  1054. lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
  1055. memset(&wsi->u, 0, sizeof(wsi->u));
  1056. wsi->mode = mode;
  1057. }
  1058. LWS_VISIBLE struct lws_plat_file_ops *
  1059. lws_get_fops(struct lws_context *context)
  1060. {
  1061. return &context->fops;
  1062. }
  1063. LWS_VISIBLE LWS_EXTERN struct lws_context *
  1064. lws_get_context(const struct lws *wsi)
  1065. {
  1066. return wsi->context;
  1067. }
  1068. LWS_VISIBLE LWS_EXTERN int
  1069. lws_get_count_threads(struct lws_context *context)
  1070. {
  1071. return context->count_threads;
  1072. }
  1073. LWS_VISIBLE LWS_EXTERN void *
  1074. lws_wsi_user(struct lws *wsi)
  1075. {
  1076. return wsi->user_space;
  1077. }
  1078. LWS_VISIBLE LWS_EXTERN struct lws *
  1079. lws_get_parent(const struct lws *wsi)
  1080. {
  1081. return wsi->parent;
  1082. }
  1083. LWS_VISIBLE LWS_EXTERN struct lws *
  1084. lws_get_child(const struct lws *wsi)
  1085. {
  1086. return wsi->child_list;
  1087. }
  1088. LWS_VISIBLE LWS_EXTERN void
  1089. lws_close_reason(struct lws *wsi, enum lws_close_status status,
  1090. unsigned char *buf, size_t len)
  1091. {
  1092. unsigned char *p, *start;
  1093. int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
  1094. assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
  1095. start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
  1096. *p++ = (((int)status) >> 8) & 0xff;
  1097. *p++ = ((int)status) & 0xff;
  1098. if (buf)
  1099. while (len-- && p < start + budget)
  1100. *p++ = *buf++;
  1101. wsi->u.ws.close_in_ping_buffer_len = p - start;
  1102. }
  1103. LWS_EXTERN int
  1104. _lws_rx_flow_control(struct lws *wsi)
  1105. {
  1106. /* there is no pending change */
  1107. if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
  1108. lwsl_debug("%s: no pending change\n", __func__);
  1109. return 0;
  1110. }
  1111. /* stuff is still buffered, not ready to really accept new input */
  1112. if (wsi->rxflow_buffer) {
  1113. /* get ourselves called back to deal with stashed buffer */
  1114. lws_callback_on_writable(wsi);
  1115. return 0;
  1116. }
  1117. /* pending is cleared, we can change rxflow state */
  1118. wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
  1119. lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
  1120. wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
  1121. /* adjust the pollfd for this wsi */
  1122. if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
  1123. if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
  1124. lwsl_info("%s: fail\n", __func__);
  1125. return -1;
  1126. }
  1127. } else
  1128. if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
  1129. return -1;
  1130. return 0;
  1131. }
  1132. LWS_EXTERN int
  1133. lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
  1134. {
  1135. static const unsigned char e0f4[] = {
  1136. 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
  1137. 0x80 | ((4 - 1) << 2) | 1, /* e1 */
  1138. 0x80 | ((4 - 1) << 2) | 1, /* e2 */
  1139. 0x80 | ((4 - 1) << 2) | 1, /* e3 */
  1140. 0x80 | ((4 - 1) << 2) | 1, /* e4 */
  1141. 0x80 | ((4 - 1) << 2) | 1, /* e5 */
  1142. 0x80 | ((4 - 1) << 2) | 1, /* e6 */
  1143. 0x80 | ((4 - 1) << 2) | 1, /* e7 */
  1144. 0x80 | ((4 - 1) << 2) | 1, /* e8 */
  1145. 0x80 | ((4 - 1) << 2) | 1, /* e9 */
  1146. 0x80 | ((4 - 1) << 2) | 1, /* ea */
  1147. 0x80 | ((4 - 1) << 2) | 1, /* eb */
  1148. 0x80 | ((4 - 1) << 2) | 1, /* ec */
  1149. 0x80 | ((2 - 1) << 2) | 1, /* ed */
  1150. 0x80 | ((4 - 1) << 2) | 1, /* ee */
  1151. 0x80 | ((4 - 1) << 2) | 1, /* ef */
  1152. 0x90 | ((3 - 1) << 2) | 2, /* f0 */
  1153. 0x80 | ((4 - 1) << 2) | 2, /* f1 */
  1154. 0x80 | ((4 - 1) << 2) | 2, /* f2 */
  1155. 0x80 | ((4 - 1) << 2) | 2, /* f3 */
  1156. 0x80 | ((1 - 1) << 2) | 2, /* f4 */
  1157. 0, /* s0 */
  1158. 0x80 | ((4 - 1) << 2) | 0, /* s2 */
  1159. 0x80 | ((4 - 1) << 2) | 1, /* s3 */
  1160. };
  1161. unsigned char s = *state;
  1162. while (len--) {
  1163. unsigned char c = *buf++;
  1164. if (!s) {
  1165. if (c >= 0x80) {
  1166. if (c < 0xc2 || c > 0xf4)
  1167. return 1;
  1168. if (c < 0xe0)
  1169. s = 0x80 | ((4 - 1) << 2);
  1170. else
  1171. s = e0f4[c - 0xe0];
  1172. }
  1173. } else {
  1174. if (c < (s & 0xf0) ||
  1175. c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
  1176. return 1;
  1177. s = e0f4[21 + (s & 3)];
  1178. }
  1179. }
  1180. *state = s;
  1181. return 0;
  1182. }
  1183. LWS_VISIBLE LWS_EXTERN int
  1184. lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
  1185. const char **path)
  1186. {
  1187. const char *end;
  1188. static const char *slash = "/";
  1189. /* cut up the location into address, port and path */
  1190. *prot = p;
  1191. while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
  1192. p++;
  1193. if (!*p) {
  1194. end = p;
  1195. p = (char *)*prot;
  1196. *prot = end;
  1197. } else {
  1198. *p = '\0';
  1199. p += 3;
  1200. }
  1201. *ads = p;
  1202. if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
  1203. *port = 80;
  1204. else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
  1205. *port = 443;
  1206. while (*p && *p != ':' && *p != '/')
  1207. p++;
  1208. if (*p == ':') {
  1209. *p++ = '\0';
  1210. *port = atoi(p);
  1211. while (*p && *p != '/')
  1212. p++;
  1213. }
  1214. *path = slash;
  1215. if (*p) {
  1216. *p++ = '\0';
  1217. if (*p)
  1218. *path = p;
  1219. }
  1220. return 0;
  1221. }
  1222. #ifdef LWS_NO_EXTENSIONS
  1223. /* we need to provide dummy callbacks for internal exts
  1224. * so user code runs when faced with a lib compiled with
  1225. * extensions disabled.
  1226. */
  1227. int
  1228. lws_extension_callback_pm_deflate(struct lws_context *context,
  1229. const struct lws_extension *ext,
  1230. struct lws *wsi,
  1231. enum lws_extension_callback_reasons reason,
  1232. void *user, void *in, size_t len)
  1233. {
  1234. (void)context;
  1235. (void)ext;
  1236. (void)wsi;
  1237. (void)reason;
  1238. (void)user;
  1239. (void)in;
  1240. (void)len;
  1241. return 0;
  1242. }
  1243. #endif
  1244. LWS_EXTERN int
  1245. lws_socket_bind(struct lws_vhost *vhost, int sockfd, int port,
  1246. const char *iface)
  1247. {
  1248. #if LWS_POSIX
  1249. #ifdef LWS_USE_UNIX_SOCK
  1250. struct sockaddr_un serv_unix;
  1251. #endif
  1252. #ifdef LWS_USE_IPV6
  1253. struct sockaddr_in6 serv_addr6;
  1254. #endif
  1255. struct sockaddr_in serv_addr4;
  1256. socklen_t len = sizeof(struct sockaddr);
  1257. int n;
  1258. struct sockaddr_in sin;
  1259. struct sockaddr *v;
  1260. #ifdef LWS_USE_UNIX_SOCK
  1261. if (LWS_UNIX_SOCK_ENABLED(vhost)) {
  1262. v = (struct sockaddr *)&serv_unix;
  1263. n = sizeof(struct sockaddr_un);
  1264. bzero((char *) &serv_unix, sizeof(serv_unix));
  1265. serv_unix.sun_family = AF_UNIX;
  1266. if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
  1267. lwsl_err("\"%s\" too long for UNIX domain socket\n",
  1268. iface);
  1269. return -1;
  1270. }
  1271. strcpy(serv_unix.sun_path, iface);
  1272. if (serv_unix.sun_path[0] == '@')
  1273. serv_unix.sun_path[0] = '\0';
  1274. } else
  1275. #endif
  1276. #ifdef LWS_USE_IPV6
  1277. if (LWS_IPV6_ENABLED(vhost)) {
  1278. v = (struct sockaddr *)&serv_addr6;
  1279. n = sizeof(struct sockaddr_in6);
  1280. bzero((char *) &serv_addr6, sizeof(serv_addr6));
  1281. if (iface &&
  1282. interface_to_sa(vhost, iface,
  1283. (struct sockaddr_in *)v, n) < 0) {
  1284. lwsl_err("Unable to find interface %s\n", iface);
  1285. return -1;
  1286. }
  1287. serv_addr6.sin6_family = AF_INET6;
  1288. serv_addr6.sin6_port = htons(port);
  1289. } else
  1290. #endif
  1291. {
  1292. v = (struct sockaddr *)&serv_addr4;
  1293. n = sizeof(serv_addr4);
  1294. bzero((char *) &serv_addr4, sizeof(serv_addr4));
  1295. serv_addr4.sin_addr.s_addr = INADDR_ANY;
  1296. serv_addr4.sin_family = AF_INET;
  1297. if (iface &&
  1298. interface_to_sa(vhost, iface,
  1299. (struct sockaddr_in *)v, n) < 0) {
  1300. lwsl_err("Unable to find interface %s\n", iface);
  1301. return -1;
  1302. }
  1303. serv_addr4.sin_port = htons(port);
  1304. } /* ipv4 */
  1305. n = bind(sockfd, v, n);
  1306. #ifdef LWS_USE_UNIX_SOCK
  1307. if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
  1308. lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
  1309. sockfd, iface, n, LWS_ERRNO);
  1310. return -1;
  1311. } else
  1312. #endif
  1313. if (n < 0) {
  1314. lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
  1315. sockfd, port, n, LWS_ERRNO);
  1316. return -1;
  1317. }
  1318. if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
  1319. lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
  1320. else
  1321. port = ntohs(sin.sin_port);
  1322. #endif
  1323. return port;
  1324. }
  1325. LWS_EXTERN void
  1326. lws_restart_ws_ping_pong_timer(struct lws *wsi)
  1327. {
  1328. if (!wsi->context->ws_ping_pong_interval)
  1329. return;
  1330. if (wsi->state != LWSS_ESTABLISHED)
  1331. return;
  1332. wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
  1333. wsi->context->ws_ping_pong_interval;
  1334. }
  1335. static const char *hex = "0123456789ABCDEF";
  1336. LWS_VISIBLE LWS_EXTERN const char *
  1337. lws_sql_purify(char *escaped, const char *string, int len)
  1338. {
  1339. const char *p = string;
  1340. char *q = escaped;
  1341. while (*p && len-- > 2) {
  1342. if (*p == '\'') {
  1343. *q++ = '\'';
  1344. *q++ = '\'';
  1345. len --;
  1346. p++;
  1347. } else
  1348. *q++ = *p++;
  1349. }
  1350. *q = '\0';
  1351. return escaped;
  1352. }
  1353. LWS_VISIBLE LWS_EXTERN const char *
  1354. lws_json_purify(char *escaped, const char *string, int len)
  1355. {
  1356. const char *p = string;
  1357. char *q = escaped;
  1358. if (!p) {
  1359. escaped[0] = '\0';
  1360. return escaped;
  1361. }
  1362. while (*p && len-- > 6) {
  1363. if (*p == '\"' || *p == '\\' || *p < 0x20) {
  1364. *q++ = '\\';
  1365. *q++ = 'u';
  1366. *q++ = '0';
  1367. *q++ = '0';
  1368. *q++ = hex[((*p) >> 4) & 15];
  1369. *q++ = hex[(*p) & 15];
  1370. len -= 5;
  1371. p++;
  1372. } else
  1373. *q++ = *p++;
  1374. }
  1375. *q = '\0';
  1376. return escaped;
  1377. }
  1378. LWS_VISIBLE LWS_EXTERN const char *
  1379. lws_urlencode(char *escaped, const char *string, int len)
  1380. {
  1381. const char *p = string;
  1382. char *q = escaped;
  1383. while (*p && len-- > 3) {
  1384. if (*p == ' ') {
  1385. *q++ = '+';
  1386. p++;
  1387. continue;
  1388. }
  1389. if ((*p >= '0' && *p <= '9') ||
  1390. (*p >= 'A' && *p <= 'Z') ||
  1391. (*p >= 'a' && *p <= 'z')) {
  1392. *q++ = *p++;
  1393. continue;
  1394. }
  1395. *q++ = '%';
  1396. *q++ = hex[(*p >> 4) & 0xf];
  1397. *q++ = hex[*p & 0xf];
  1398. len -= 2;
  1399. p++;
  1400. }
  1401. *q = '\0';
  1402. return escaped;
  1403. }
  1404. LWS_VISIBLE LWS_EXTERN int
  1405. lws_urldecode(char *string, const char *escaped, int len)
  1406. {
  1407. int state = 0, n;
  1408. char sum = 0;
  1409. while (*escaped && len) {
  1410. switch (state) {
  1411. case 0:
  1412. if (*escaped == '%') {
  1413. state++;
  1414. escaped++;
  1415. continue;
  1416. }
  1417. if (*escaped == '+') {
  1418. escaped++;
  1419. *string++ = ' ';
  1420. len--;
  1421. continue;
  1422. }
  1423. *string++ = *escaped++;
  1424. len--;
  1425. break;
  1426. case 1:
  1427. n = char_to_hex(*escaped);
  1428. if (n < 0)
  1429. return -1;
  1430. escaped++;
  1431. sum = n << 4;
  1432. state++;
  1433. break;
  1434. case 2:
  1435. n = char_to_hex(*escaped);
  1436. if (n < 0)
  1437. return -1;
  1438. escaped++;
  1439. *string++ = sum | n;
  1440. len--;
  1441. state = 0;
  1442. break;
  1443. }
  1444. }
  1445. *string = '\0';
  1446. return 0;
  1447. }
  1448. LWS_VISIBLE LWS_EXTERN int
  1449. lws_finalize_startup(struct lws_context *context)
  1450. {
  1451. struct lws_context_creation_info info;
  1452. info.uid = context->uid;
  1453. info.gid = context->gid;
  1454. if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
  1455. lws_plat_drop_app_privileges(&info);
  1456. return 0;
  1457. }
  1458. int
  1459. lws_snprintf(char *str, size_t size, const char *format, ...)
  1460. {
  1461. va_list ap;
  1462. int n;
  1463. if (!size)
  1464. return 0;
  1465. va_start(ap, format);
  1466. n = vsnprintf(str, size, format, ap);
  1467. va_end(ap);
  1468. if (n >= size)
  1469. return size;
  1470. return n;
  1471. }
  1472. LWS_VISIBLE LWS_EXTERN int
  1473. lws_is_cgi(struct lws *wsi) {
  1474. #ifdef LWS_WITH_CGI
  1475. return !!wsi->cgi;
  1476. #else
  1477. return 0;
  1478. #endif
  1479. }
  1480. #ifdef LWS_WITH_CGI
  1481. static int
  1482. urlencode(const char *in, int inlen, char *out, int outlen)
  1483. {
  1484. char *start = out, *end = out + outlen;
  1485. while (inlen-- && out < end - 4) {
  1486. if ((*in >= 'A' && *in <= 'Z') ||
  1487. (*in >= 'a' && *in <= 'z') ||
  1488. (*in >= '0' && *in <= '9') ||
  1489. *in == '-' ||
  1490. *in == '_' ||
  1491. *in == '.' ||
  1492. *in == '~') {
  1493. *out++ = *in++;
  1494. continue;
  1495. }
  1496. if (*in == ' ') {
  1497. *out++ = '+';
  1498. in++;
  1499. continue;
  1500. }
  1501. *out++ = '%';
  1502. *out++ = hex[(*in) >> 4];
  1503. *out++ = hex[(*in++) & 15];
  1504. }
  1505. *out = '\0';
  1506. if (out >= end - 4)
  1507. return -1;
  1508. return out - start;
  1509. }
  1510. static struct lws *
  1511. lws_create_basic_wsi(struct lws_context *context, int tsi)
  1512. {
  1513. struct lws *new_wsi;
  1514. if ((unsigned int)context->pt[tsi].fds_count ==
  1515. context->fd_limit_per_thread - 1) {
  1516. lwsl_err("no space for new conn\n");
  1517. return NULL;
  1518. }
  1519. new_wsi = lws_zalloc(sizeof(struct lws));
  1520. if (new_wsi == NULL) {
  1521. lwsl_err("Out of memory for new connection\n");
  1522. return NULL;
  1523. }
  1524. new_wsi->tsi = tsi;
  1525. new_wsi->context = context;
  1526. new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
  1527. new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
  1528. /* initialize the instance struct */
  1529. new_wsi->state = LWSS_CGI;
  1530. new_wsi->mode = LWSCM_CGI;
  1531. new_wsi->hdr_parsing_completed = 0;
  1532. new_wsi->position_in_fds_table = -1;
  1533. /*
  1534. * these can only be set once the protocol is known
  1535. * we set an unestablished connection's protocol pointer
  1536. * to the start of the defauly vhost supported list, so it can look
  1537. * for matching ones during the handshake
  1538. */
  1539. new_wsi->protocol = context->vhost_list->protocols;
  1540. new_wsi->user_space = NULL;
  1541. new_wsi->ietf_spec_revision = 0;
  1542. new_wsi->sock = LWS_SOCK_INVALID;
  1543. context->count_wsi_allocated++;
  1544. return new_wsi;
  1545. }
  1546. LWS_VISIBLE LWS_EXTERN int
  1547. lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
  1548. int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
  1549. {
  1550. struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
  1551. char *env_array[30], cgi_path[400], e[1024], *p = e,
  1552. *end = p + sizeof(e) - 1, tok[256], *t;
  1553. struct lws_cgi *cgi;
  1554. int n, m, i, uritok = -1;
  1555. /*
  1556. * give the master wsi a cgi struct
  1557. */
  1558. wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
  1559. if (!wsi->cgi) {
  1560. lwsl_err("%s: OOM\n", __func__);
  1561. return -1;
  1562. }
  1563. cgi = wsi->cgi;
  1564. cgi->wsi = wsi; /* set cgi's owning wsi */
  1565. /* create pipes for [stdin|stdout] and [stderr] */
  1566. for (n = 0; n < 3; n++)
  1567. if (pipe(cgi->pipe_fds[n]) == -1)
  1568. goto bail1;
  1569. /* create cgi wsis for each stdin/out/err fd */
  1570. for (n = 0; n < 3; n++) {
  1571. cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
  1572. if (!cgi->stdwsi[n])
  1573. goto bail2;
  1574. cgi->stdwsi[n]->cgi_channel = n;
  1575. cgi->stdwsi[n]->vhost = wsi->vhost;
  1576. // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
  1577. // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
  1578. /* read side is 0, stdin we want the write side, others read */
  1579. cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
  1580. if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
  1581. lwsl_err("%s: setting NONBLOCK failed\n", __func__);
  1582. goto bail2;
  1583. }
  1584. }
  1585. for (n = 0; n < 3; n++) {
  1586. lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->sock);
  1587. if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
  1588. goto bail3;
  1589. cgi->stdwsi[n]->parent = wsi;
  1590. cgi->stdwsi[n]->sibling_list = wsi->child_list;
  1591. wsi->child_list = cgi->stdwsi[n];
  1592. }
  1593. lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
  1594. lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
  1595. lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
  1596. lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
  1597. cgi->stdwsi[LWS_STDIN]->sock, cgi->stdwsi[LWS_STDOUT]->sock,
  1598. cgi->stdwsi[LWS_STDERR]->sock);
  1599. lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
  1600. /* the cgi stdout is always sending us http1.x header data first */
  1601. wsi->hdr_state = LCHS_HEADER;
  1602. /* add us to the pt list of active cgis */
  1603. lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
  1604. cgi->cgi_list = pt->cgi_list;
  1605. pt->cgi_list = cgi;
  1606. /* prepare his CGI env */
  1607. n = 0;
  1608. if (lws_is_ssl(wsi))
  1609. env_array[n++] = "HTTPS=ON";
  1610. if (wsi->u.hdr.ah) {
  1611. static const unsigned char meths[] = {
  1612. WSI_TOKEN_GET_URI,
  1613. WSI_TOKEN_POST_URI,
  1614. WSI_TOKEN_OPTIONS_URI,
  1615. WSI_TOKEN_PUT_URI,
  1616. WSI_TOKEN_PATCH_URI,
  1617. WSI_TOKEN_DELETE_URI,
  1618. };
  1619. static const char * const meth_names[] = {
  1620. "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
  1621. };
  1622. for (m = 0; m < ARRAY_SIZE(meths); m++)
  1623. if (lws_hdr_total_length(wsi, meths[m]) >=
  1624. script_uri_path_len) {
  1625. uritok = meths[m];
  1626. break;
  1627. }
  1628. if (uritok < 0)
  1629. goto bail3;
  1630. lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
  1631. lws_hdr_simple_ptr(wsi, uritok));
  1632. cgi_path[sizeof(cgi_path) - 1] = '\0';
  1633. env_array[n++] = cgi_path;
  1634. env_array[n++] = p;
  1635. p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
  1636. meth_names[m]);
  1637. p++;
  1638. env_array[n++] = p;
  1639. p += lws_snprintf(p, end - p, "QUERY_STRING=");
  1640. /* dump the individual URI Arg parameters */
  1641. m = 0;
  1642. while (1) {
  1643. i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
  1644. WSI_TOKEN_HTTP_URI_ARGS, m);
  1645. if (i < 0)
  1646. break;
  1647. t = tok;
  1648. while (*t && *t != '=' && p < end - 4)
  1649. *p++ = *t++;
  1650. if (*t == '=')
  1651. *p++ = *t++;
  1652. i = urlencode(t, i- (t - tok), p, end - p);
  1653. if (i > 0) {
  1654. p += i;
  1655. *p++ = '&';
  1656. }
  1657. m++;
  1658. }
  1659. if (m)
  1660. p--;
  1661. *p++ = '\0';
  1662. env_array[n++] = p;
  1663. p += lws_snprintf(p, end - p, "PATH_INFO=%s",
  1664. lws_hdr_simple_ptr(wsi, uritok) +
  1665. script_uri_path_len);
  1666. p++;
  1667. }
  1668. if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
  1669. env_array[n++] = p;
  1670. p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
  1671. lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
  1672. p++;
  1673. }
  1674. if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
  1675. env_array[n++] = p;
  1676. p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
  1677. lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
  1678. p++;
  1679. }
  1680. if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
  1681. env_array[n++] = p;
  1682. p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
  1683. lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
  1684. p++;
  1685. }
  1686. if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
  1687. env_array[n++] = p;
  1688. p += lws_snprintf(p, end - p, "USER_AGENT=%s",
  1689. lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
  1690. p++;
  1691. }
  1692. if (uritok == WSI_TOKEN_POST_URI) {
  1693. if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
  1694. env_array[n++] = p;
  1695. p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
  1696. lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
  1697. p++;
  1698. }
  1699. if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
  1700. env_array[n++] = p;
  1701. p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
  1702. lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
  1703. p++;
  1704. }
  1705. }
  1706. env_array[n++] = p;
  1707. p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
  1708. while (mp_cgienv) {
  1709. env_array[n++] = p;
  1710. p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
  1711. mp_cgienv->value);
  1712. lwsl_debug(" Applying mount-specific cgi env '%s'\n",
  1713. env_array[n - 1]);
  1714. p++;
  1715. mp_cgienv = mp_cgienv->next;
  1716. }
  1717. env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
  1718. env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
  1719. env_array[n] = NULL;
  1720. #if 0
  1721. for (m = 0; m < n; m++)
  1722. lwsl_err(" %s\n", env_array[m]);
  1723. #endif
  1724. /*
  1725. * Actually having made the env, as a cgi we don't need the ah
  1726. * any more
  1727. */
  1728. if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
  1729. lws_header_table_detach(wsi, 0);
  1730. /* we are ready with the redirection pipes... run the thing */
  1731. #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
  1732. cgi->pid = fork();
  1733. #else
  1734. cgi->pid = vfork();
  1735. #endif
  1736. if (cgi->pid < 0) {
  1737. lwsl_err("fork failed, errno %d", errno);
  1738. goto bail3;
  1739. }
  1740. #if defined(__linux__)
  1741. prctl(PR_SET_PDEATHSIG, SIGTERM);
  1742. #endif
  1743. setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
  1744. if (cgi->pid) {
  1745. /* we are the parent process */
  1746. wsi->context->count_cgi_spawned++;
  1747. lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
  1748. return 0;
  1749. }
  1750. /* somewhere we can at least read things and enter it */
  1751. if (chdir("/tmp"))
  1752. lwsl_notice("%s: Failed to chdir\n", __func__);
  1753. /* We are the forked process, redirect and kill inherited things.
  1754. *
  1755. * Because of vfork(), we cannot do anything that changes pages in
  1756. * the parent environment. Stuff that changes kernel state for the
  1757. * process is OK. Stuff that happens after the execvpe() is OK.
  1758. */
  1759. for (n = 0; n < 3; n++)
  1760. if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
  1761. lwsl_err("%s: stdin dup2 failed\n", __func__);
  1762. goto bail3;
  1763. }
  1764. #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
  1765. for (m = 0; m < n; m++) {
  1766. p = strchr(env_array[m], '=');
  1767. *p++ = '\0';
  1768. setenv(env_array[m], p, 1);
  1769. }
  1770. execvp(exec_array[0], (char * const *)&exec_array[0]);
  1771. #else
  1772. execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
  1773. #endif
  1774. exit(1);
  1775. bail3:
  1776. /* drop us from the pt cgi list */
  1777. pt->cgi_list = cgi->cgi_list;
  1778. while (--n >= 0)
  1779. remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
  1780. bail2:
  1781. for (n = 0; n < 3; n++)
  1782. if (wsi->cgi->stdwsi[n])
  1783. lws_free_wsi(cgi->stdwsi[n]);
  1784. bail1:
  1785. for (n = 0; n < 3; n++) {
  1786. if (cgi->pipe_fds[n][0])
  1787. close(cgi->pipe_fds[n][0]);
  1788. if (cgi->pipe_fds[n][1])
  1789. close(cgi->pipe_fds[n][1]);
  1790. }
  1791. lws_free_set_NULL(wsi->cgi);
  1792. lwsl_err("%s: failed\n", __func__);
  1793. return -1;
  1794. }
  1795. LWS_VISIBLE LWS_EXTERN int
  1796. lws_cgi_write_split_stdout_headers(struct lws *wsi)
  1797. {
  1798. int n, m, match = 0, lp = 0;
  1799. static const char * const content_length = "content-length: ";
  1800. char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
  1801. *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
  1802. if (!wsi->cgi)
  1803. return -1;
  1804. while (wsi->hdr_state != LHCS_PAYLOAD) {
  1805. /* we have to separate header / finalize and
  1806. * payload chunks, since they need to be
  1807. * handled separately
  1808. */
  1809. n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
  1810. if (n < 0) {
  1811. if (errno != EAGAIN) {
  1812. lwsl_debug("%s: read says %d\n", __func__, n);
  1813. return -1;
  1814. }
  1815. else
  1816. n = 0;
  1817. }
  1818. if (n) {
  1819. lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
  1820. switch (wsi->hdr_state) {
  1821. case LCHS_HEADER:
  1822. if (!content_length[match] &&
  1823. (c >= '0' && c <= '9') &&
  1824. lp < sizeof(l) - 1) {
  1825. l[lp++] = c;
  1826. l[lp] = '\0';
  1827. wsi->cgi->content_length = atol(l);
  1828. }
  1829. if (tolower(c) == content_length[match])
  1830. match++;
  1831. else
  1832. match = 0;
  1833. /* some cgi only send us \x0a for EOL */
  1834. if (c == '\x0a') {
  1835. wsi->hdr_state = LCHS_SINGLE_0A;
  1836. *p++ = '\x0d';
  1837. }
  1838. *p++ = c;
  1839. if (c == '\x0d') {
  1840. wsi->hdr_state = LCHS_LF1;
  1841. break;
  1842. }
  1843. break;
  1844. case LCHS_LF1:
  1845. *p++ = c;
  1846. if (c == '\x0a') {
  1847. wsi->hdr_state = LCHS_CR2;
  1848. break;
  1849. }
  1850. /* we got \r[^\n]... it's unreasonable */
  1851. lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
  1852. return -1;
  1853. case LCHS_CR2:
  1854. if (c == '\x0d') {
  1855. /* drop the \x0d */
  1856. wsi->hdr_state = LCHS_LF2;
  1857. break;
  1858. }
  1859. wsi->hdr_state = LCHS_HEADER;
  1860. match = 0;
  1861. *p++ = c;
  1862. break;
  1863. case LCHS_LF2:
  1864. case LCHS_SINGLE_0A:
  1865. m = wsi->hdr_state;
  1866. if (c == '\x0a') {
  1867. lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
  1868. wsi->hdr_state = LHCS_PAYLOAD;
  1869. /* drop the \0xa ... finalize will add it if needed */
  1870. if (lws_finalize_http_header(wsi,
  1871. (unsigned char **)&p,
  1872. (unsigned char *)end))
  1873. return -1;
  1874. break;
  1875. }
  1876. if (m == LCHS_LF2)
  1877. /* we got \r\n\r[^\n]... it's unreasonable */
  1878. return -1;
  1879. /* we got \x0anext header, it's reasonable */
  1880. *p++ = c;
  1881. wsi->hdr_state = LCHS_HEADER;
  1882. break;
  1883. case LHCS_PAYLOAD:
  1884. break;
  1885. }
  1886. }
  1887. /* ran out of input, ended the headers, or filled up the headers buf */
  1888. if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
  1889. m = lws_write(wsi, (unsigned char *)start,
  1890. p - start, LWS_WRITE_HTTP_HEADERS);
  1891. if (m < 0) {
  1892. lwsl_debug("%s: write says %d\n", __func__, m);
  1893. return -1;
  1894. }
  1895. /* writeability becomes uncertain now we wrote
  1896. * something, we must return to the event loop
  1897. */
  1898. return 0;
  1899. }
  1900. }
  1901. n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
  1902. start, sizeof(buf) - LWS_PRE);
  1903. if (n < 0 && errno != EAGAIN) {
  1904. lwsl_debug("%s: stdout read says %d\n", __func__, n);
  1905. return -1;
  1906. }
  1907. if (n > 0) {
  1908. m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
  1909. //lwsl_notice("write %d\n", m);
  1910. if (m < 0) {
  1911. lwsl_debug("%s: stdout write says %d\n", __func__, m);
  1912. return -1;
  1913. }
  1914. wsi->cgi->content_length_seen += m;
  1915. }
  1916. return 0;
  1917. }
  1918. LWS_VISIBLE LWS_EXTERN int
  1919. lws_cgi_kill(struct lws *wsi)
  1920. {
  1921. struct lws_cgi_args args;
  1922. int status, n;
  1923. lwsl_debug("%s: %p\n", __func__, wsi);
  1924. if (!wsi->cgi)
  1925. return 0;
  1926. if (wsi->cgi->pid > 0) {
  1927. n = waitpid(wsi->cgi->pid, &status, WNOHANG);
  1928. if (n > 0) {
  1929. lwsl_debug("%s: PID %d reaped\n", __func__,
  1930. wsi->cgi->pid);
  1931. goto handled;
  1932. }
  1933. /* kill the process group */
  1934. n = kill(-wsi->cgi->pid, SIGTERM);
  1935. lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
  1936. wsi->cgi->pid, n, errno);
  1937. if (n < 0) {
  1938. /*
  1939. * hum seen errno=3 when process is listed in ps,
  1940. * it seems we don't always retain process grouping
  1941. *
  1942. * Direct these fallback attempt to the exact child
  1943. */
  1944. n = kill(wsi->cgi->pid, SIGTERM);
  1945. if (n < 0) {
  1946. n = kill(wsi->cgi->pid, SIGPIPE);
  1947. if (n < 0) {
  1948. n = kill(wsi->cgi->pid, SIGKILL);
  1949. if (n < 0)
  1950. lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
  1951. __func__, wsi->cgi->pid, errno);
  1952. }
  1953. }
  1954. }
  1955. /* He could be unkillable because he's a zombie */
  1956. n = 1;
  1957. while (n > 0) {
  1958. n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
  1959. if (n > 0)
  1960. lwsl_debug("%s: reaped PID %d\n", __func__, n);
  1961. if (n <= 0) {
  1962. n = waitpid(wsi->cgi->pid, &status, WNOHANG);
  1963. if (n > 0)
  1964. lwsl_debug("%s: reaped PID %d\n", __func__, n);
  1965. }
  1966. }
  1967. }
  1968. handled:
  1969. args.stdwsi = &wsi->cgi->stdwsi[0];
  1970. if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
  1971. wsi->protocol->callback,
  1972. wsi, LWS_CALLBACK_CGI_TERMINATED,
  1973. wsi->user_space,
  1974. (void *)&args, 0)) {
  1975. wsi->cgi->pid = -1;
  1976. if (!wsi->cgi->being_closed)
  1977. lws_close_free_wsi(wsi, 0);
  1978. }
  1979. return 0;
  1980. }
  1981. LWS_EXTERN int
  1982. lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
  1983. {
  1984. struct lws_cgi **pcgi, *cgi = NULL;
  1985. int status, n = 1;
  1986. while (n > 0) {
  1987. /* find finished guys but don't reap yet */
  1988. n = waitpid(-1, &status, WNOHANG | WNOWAIT);
  1989. if (n <= 0)
  1990. continue;
  1991. lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
  1992. pcgi = &pt->cgi_list;
  1993. /* check all the subprocesses on the cgi list */
  1994. while (*pcgi) {
  1995. /* get the next one first as list may change */
  1996. cgi = *pcgi;
  1997. pcgi = &(*pcgi)->cgi_list;
  1998. if (cgi->pid <= 0)
  1999. continue;
  2000. /* wait for stdout to be drained */
  2001. if (cgi->content_length > cgi->content_length_seen)
  2002. continue;
  2003. if (cgi->content_length) {
  2004. lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
  2005. __func__, cgi->wsi, cgi->content_length_seen);
  2006. }
  2007. /* reap it */
  2008. waitpid(n, &status, WNOHANG);
  2009. /*
  2010. * he's already terminated so no need for kill()
  2011. * but we should do the terminated cgi callback
  2012. * and close him if he's not already closing
  2013. */
  2014. if (n == cgi->pid) {
  2015. lwsl_debug("%s: found PID %d on cgi list\n",
  2016. __func__, n);
  2017. /* defeat kill() */
  2018. cgi->pid = 0;
  2019. lws_cgi_kill(cgi->wsi);
  2020. break;
  2021. }
  2022. cgi = NULL;
  2023. }
  2024. /* if not found on the cgi list, as he's one of ours, reap */
  2025. if (!cgi) {
  2026. lwsl_debug("%s: reading PID %d although no cgi match\n",
  2027. __func__, n);
  2028. waitpid(n, &status, WNOHANG);
  2029. }
  2030. }
  2031. /* disable this to confirm timeout cgi cleanup flow */
  2032. #if 1
  2033. pcgi = &pt->cgi_list;
  2034. /* check all the subprocesses on the cgi list */
  2035. while (*pcgi) {
  2036. /* get the next one first as list may change */
  2037. cgi = *pcgi;
  2038. pcgi = &(*pcgi)->cgi_list;
  2039. if (cgi->pid <= 0)
  2040. continue;
  2041. /* wait for stdout to be drained */
  2042. if (cgi->content_length > cgi->content_length_seen)
  2043. continue;
  2044. if (cgi->content_length) {
  2045. lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
  2046. __func__, cgi->wsi, cgi->content_length_seen);
  2047. }
  2048. /* reap it */
  2049. if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
  2050. lwsl_debug("%s: found PID %d on cgi list\n",
  2051. __func__, cgi->pid);
  2052. /* defeat kill() */
  2053. cgi->pid = 0;
  2054. lws_cgi_kill(cgi->wsi);
  2055. break;
  2056. }
  2057. }
  2058. #endif
  2059. /* general anti zombie defence */
  2060. n = waitpid(-1, &status, WNOHANG);
  2061. //if (n > 0)
  2062. // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
  2063. return 0;
  2064. }
  2065. #endif
  2066. #ifdef LWS_NO_EXTENSIONS
  2067. LWS_EXTERN int
  2068. lws_set_extension_option(struct lws *wsi, const char *ext_name,
  2069. const char *opt_name, const char *opt_val)
  2070. {
  2071. return -1;
  2072. }
  2073. #endif
  2074. #ifdef LWS_WITH_ACCESS_LOG
  2075. int
  2076. lws_access_log(struct lws *wsi)
  2077. {
  2078. char *p = wsi->access_log.user_agent, ass[512];
  2079. int l;
  2080. if (!wsi->access_log_pending)
  2081. return 0;
  2082. if (!wsi->access_log.header_log)
  2083. return 0;
  2084. if (!p)
  2085. p = "";
  2086. l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
  2087. wsi->access_log.header_log,
  2088. wsi->access_log.response, wsi->access_log.sent, p);
  2089. if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
  2090. if (write(wsi->vhost->log_fd, ass, l) != l)
  2091. lwsl_err("Failed to write log\n");
  2092. } else
  2093. lwsl_err("%s", ass);
  2094. if (wsi->access_log.header_log) {
  2095. lws_free(wsi->access_log.header_log);
  2096. wsi->access_log.header_log = NULL;
  2097. }
  2098. if (wsi->access_log.user_agent) {
  2099. lws_free(wsi->access_log.user_agent);
  2100. wsi->access_log.user_agent = NULL;
  2101. }
  2102. wsi->access_log_pending = 0;
  2103. return 0;
  2104. }
  2105. #endif
  2106. #ifdef LWS_WITH_SERVER_STATUS
  2107. LWS_EXTERN int
  2108. lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
  2109. {
  2110. static const char * const prots[] = {
  2111. "http://",
  2112. "https://",
  2113. "file://",
  2114. "cgi://",
  2115. ">http://",
  2116. ">https://",
  2117. "callback://"
  2118. };
  2119. char *orig = buf, *end = buf + len - 1, first = 1;
  2120. int n = 0;
  2121. if (len < 100)
  2122. return 0;
  2123. buf += lws_snprintf(buf, end - buf,
  2124. "{\n \"name\":\"%s\",\n"
  2125. " \"port\":\"%d\",\n"
  2126. " \"use_ssl\":\"%d\",\n"
  2127. " \"sts\":\"%d\",\n"
  2128. " \"rx\":\"%llu\",\n"
  2129. " \"tx\":\"%llu\",\n"
  2130. " \"conn\":\"%lu\",\n"
  2131. " \"trans\":\"%lu\",\n"
  2132. " \"ws_upg\":\"%lu\",\n"
  2133. " \"http2_upg\":\"%lu\""
  2134. ,
  2135. vh->name, vh->listen_port,
  2136. #ifdef LWS_OPENSSL_SUPPORT
  2137. vh->use_ssl,
  2138. #else
  2139. 0,
  2140. #endif
  2141. !!(vh->options & LWS_SERVER_OPTION_STS),
  2142. vh->rx, vh->tx, vh->conn, vh->trans, vh->ws_upgrades,
  2143. vh->http2_upgrades
  2144. );
  2145. if (vh->mount_list) {
  2146. const struct lws_http_mount *m = vh->mount_list;
  2147. buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
  2148. while (m) {
  2149. if (!first)
  2150. buf += lws_snprintf(buf, end - buf, ",");
  2151. buf += lws_snprintf(buf, end - buf,
  2152. "\n {\n \"mountpoint\":\"%s\",\n"
  2153. " \"origin\":\"%s%s\",\n"
  2154. " \"cache_max_age\":\"%d\",\n"
  2155. " \"cache_reuse\":\"%d\",\n"
  2156. " \"cache_revalidate\":\"%d\",\n"
  2157. " \"cache_intermediaries\":\"%d\"\n"
  2158. ,
  2159. m->mountpoint,
  2160. prots[m->origin_protocol],
  2161. m->origin,
  2162. m->cache_max_age,
  2163. m->cache_reusable,
  2164. m->cache_revalidate,
  2165. m->cache_intermediaries);
  2166. if (m->def)
  2167. buf += lws_snprintf(buf, end - buf,
  2168. ",\n \"default\":\"%s\"",
  2169. m->def);
  2170. buf += lws_snprintf(buf, end - buf, "\n }");
  2171. first = 0;
  2172. m = m->mount_next;
  2173. }
  2174. buf += lws_snprintf(buf, end - buf, "\n ]");
  2175. }
  2176. if (vh->protocols) {
  2177. n = 0;
  2178. first = 1;
  2179. buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
  2180. while (n < vh->count_protocols) {
  2181. if (!first)
  2182. buf += lws_snprintf(buf, end - buf, ",");
  2183. buf += lws_snprintf(buf, end - buf,
  2184. "\n {\n \"%s\":{\n"
  2185. " \"status\":\"ok\"\n }\n }"
  2186. ,
  2187. vh->protocols[n].name);
  2188. first = 0;
  2189. n++;
  2190. }
  2191. buf += lws_snprintf(buf, end - buf, "\n ]");
  2192. }
  2193. buf += lws_snprintf(buf, end - buf, "\n}");
  2194. return buf - orig;
  2195. }
  2196. LWS_EXTERN LWS_VISIBLE int
  2197. lws_json_dump_context(const struct lws_context *context, char *buf, int len)
  2198. {
  2199. char *orig = buf, *end = buf + len - 1, first = 1;
  2200. const struct lws_vhost *vh = context->vhost_list;
  2201. #ifdef LWS_WITH_CGI
  2202. struct lws_cgi * const *pcgi;
  2203. #endif
  2204. const struct lws_context_per_thread *pt;
  2205. time_t t = time(NULL);
  2206. int listening = 0, cgi_count = 0, n;
  2207. buf += lws_snprintf(buf, end - buf, "{ "
  2208. "\"version\":\"%s\",\n"
  2209. "\"uptime\":\"%ld\",\n"
  2210. "\"cgi_spawned\":\"%d\",\n"
  2211. "\"pt_fd_max\":\"%d\",\n"
  2212. "\"ah_pool_max\":\"%d\",\n"
  2213. "\"wsi_alive\":\"%d\",\n",
  2214. lws_get_library_version(),
  2215. (unsigned long)(t - context->time_up),
  2216. context->count_cgi_spawned,
  2217. context->fd_limit_per_thread,
  2218. context->max_http_header_pool,
  2219. context->count_wsi_allocated);
  2220. #ifdef LWS_HAVE_GETLOADAVG
  2221. {
  2222. double d[3];
  2223. int m;
  2224. m = getloadavg(d, 3);
  2225. for (n = 0; n < m; n++) {
  2226. buf += lws_snprintf(buf, end - buf,
  2227. "\"l%d\":\"%.2f\",\n",
  2228. n + 1, d[n]);
  2229. }
  2230. }
  2231. #endif
  2232. buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
  2233. for (n = 0; n < context->count_threads; n++) {
  2234. pt = &context->pt[n];
  2235. if (n)
  2236. buf += lws_snprintf(buf, end - buf, ",");
  2237. buf += lws_snprintf(buf, end - buf,
  2238. "\n {\n"
  2239. " \"fds_count\":\"%d\",\n"
  2240. " \"ah_pool_inuse\":\"%d\",\n"
  2241. " \"ah_wait_list\":\"%d\"\n"
  2242. " }",
  2243. pt->fds_count,
  2244. pt->ah_count_in_use,
  2245. pt->ah_wait_list_length);
  2246. }
  2247. buf += lws_snprintf(buf, end - buf, "], \"vhosts\":[\n ");
  2248. while (vh) {
  2249. if (!first)
  2250. if(buf != end)
  2251. *buf++ = ',';
  2252. buf += lws_json_dump_vhost(vh, buf, end - buf);
  2253. first = 0;
  2254. if (vh->lserv_wsi)
  2255. listening++;
  2256. vh = vh->vhost_next;
  2257. }
  2258. buf += lws_snprintf(buf, end - buf, "],\n\"listen_wsi\":\"%d\"",
  2259. listening);
  2260. #ifdef LWS_WITH_CGI
  2261. for (n = 0; n < context->count_threads; n++) {
  2262. pt = &context->pt[n];
  2263. pcgi = &pt->cgi_list;
  2264. while (*pcgi) {
  2265. pcgi = &(*pcgi)->cgi_list;
  2266. cgi_count++;
  2267. }
  2268. }
  2269. #endif
  2270. buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
  2271. cgi_count);
  2272. buf += lws_snprintf(buf, end - buf, "}\n ");
  2273. return buf - orig;
  2274. }
  2275. #endif