2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
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.
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.
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,
22 #include "private-libwebsockets.h"
24 #ifdef LWS_HAVE_SYS_TYPES_H
25 #include <sys/types.h>
28 #if defined(WIN32) || defined(_WIN32)
33 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
34 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
36 static const char * const log_level_names[] = {
50 lws_free_wsi(struct lws *wsi)
55 /* Protocol user data may be allocated either internally by lws
56 * or by specified the user.
57 * We should only free what we allocated. */
58 if (wsi->protocol && wsi->protocol->per_session_data_size &&
59 wsi->user_space && !wsi->user_space_externally_allocated)
60 lws_free(wsi->user_space);
62 lws_free_set_NULL(wsi->rxflow_buffer);
63 lws_free_set_NULL(wsi->trunc_alloc);
66 /* we're closing, losing some rx is OK */
67 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
69 /* we may not have an ah, but may be on the waiting list... */
70 lws_header_table_detach(wsi, 0);
72 wsi->context->count_wsi_allocated--;
73 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
74 wsi->context->count_wsi_allocated);
80 lws_remove_from_timeout_list(struct lws *wsi)
82 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
84 if (!wsi->timeout_list_prev) /* ie, not part of the list */
88 /* if we have a next guy, set his prev to our prev */
89 if (wsi->timeout_list)
90 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
91 /* set our prev guy to our next guy instead of us */
92 *wsi->timeout_list_prev = wsi->timeout_list;
94 /* we're out of the list, we should not point anywhere any more */
95 wsi->timeout_list_prev = NULL;
96 wsi->timeout_list = NULL;
101 * lws_set_timeout() - marks the wsi as subject to a timeout
103 * You will not need this unless you are doing something special
105 * @wsi: Websocket connection instance
106 * @reason: timeout reason
107 * @secs: how many seconds
111 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
113 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
120 if (reason && !wsi->timeout_list_prev) {
121 /* our next guy is current first guy */
122 wsi->timeout_list = pt->timeout_list;
123 /* if there is a next guy, set his prev ptr to our next ptr */
124 if (wsi->timeout_list)
125 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
126 /* our prev ptr is first ptr */
127 wsi->timeout_list_prev = &pt->timeout_list;
128 /* set the first guy to be us */
129 *wsi->timeout_list_prev = wsi;
132 lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
133 wsi->pending_timeout_limit = now + secs;
134 wsi->pending_timeout = reason;
139 lws_remove_from_timeout_list(wsi);
143 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
145 struct lws_context_per_thread *pt;
146 struct lws **pwsi, *wsi1, *wsi2;
147 struct lws_context *context;
148 struct lws_tokens eff_buf;
156 context = wsi->context;
157 pt = &context->pt[(int)wsi->tsi];
159 /* if we have children, close them first */
160 if (wsi->child_list) {
161 wsi2 = wsi->child_list;
163 //lwsl_notice("%s: closing %p: close child %p\n",
164 // __func__, wsi, wsi2);
165 wsi1 = wsi2->sibling_list;
166 //lwsl_notice("%s: closing %p: next sibling %p\n",
167 // __func__, wsi2, wsi1);
169 /* stop it doing shutdown processing */
170 wsi2->socket_is_permanently_unusable = 1;
171 lws_close_free_wsi(wsi2, reason);
174 wsi->child_list = NULL;
178 if (wsi->mode == LWSCM_CGI) {
179 /* we are not a network connection, but a handler for CGI io */
180 if (wsi->parent && wsi->parent->cgi)
181 /* end the binding between us and master */
182 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
183 wsi->socket_is_permanently_unusable = 1;
185 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
186 goto just_kill_connection;
190 struct lws_cgi **pcgi = &pt->cgi_list;
191 /* remove us from the cgi list */
192 lwsl_notice("%s: remove cgi %p from list\n", __func__, wsi->cgi);
194 if (*pcgi == wsi->cgi) {
195 /* drop us from the pt cgi list */
196 *pcgi = (*pcgi)->cgi_list;
199 pcgi = &(*pcgi)->cgi_list;
201 /* we have a cgi going, we must kill it */
202 wsi->cgi->being_closed = 1;
207 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
208 wsi->u.http.fd != LWS_INVALID_FILE) {
209 lws_plat_file_close(wsi, wsi->u.http.fd);
210 wsi->u.http.fd = LWS_INVALID_FILE;
211 wsi->vhost->protocols->callback(wsi,
212 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
214 if (wsi->socket_is_permanently_unusable ||
215 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
216 wsi->state == LWSS_SHUTDOWN)
217 goto just_kill_connection;
219 wsi->state_pre_close = wsi->state;
221 switch (wsi->state_pre_close) {
222 case LWSS_DEAD_SOCKET:
225 /* we tried the polite way... */
226 case LWSS_AWAITING_CLOSE_ACK:
227 goto just_kill_connection;
229 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
230 if (wsi->trunc_len) {
231 lws_callback_on_writable(wsi);
234 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
235 goto just_kill_connection;
237 if (wsi->trunc_len) {
238 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
239 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
240 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
246 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
247 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
248 goto just_kill_connection;
250 if (wsi->mode == LWSCM_HTTP_SERVING) {
252 wsi->vhost->protocols->callback(wsi,
253 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
254 wsi->user_space, NULL, 0);
255 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
256 wsi->user_space, NULL, 0);
258 if (wsi->mode == LWSCM_HTTP_CLIENT)
259 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
260 wsi->user_space, NULL, 0);
263 * are his extensions okay with him closing? Eg he might be a mux
264 * parent and just his ch1 aspect is closing?
267 if (lws_ext_cb_active(wsi,
268 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
269 lwsl_ext("extension vetoed close\n");
274 * flush any tx pending from extensions, since we may send close packet
275 * if there are problems with send, just nuke the connection
280 eff_buf.token = NULL;
281 eff_buf.token_len = 0;
283 /* show every extension the new incoming data */
285 m = lws_ext_cb_active(wsi,
286 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
288 lwsl_ext("Extension reports fatal error\n");
289 goto just_kill_connection;
293 * at least one extension told us he has more
294 * to spill, so we will go around again after
298 /* assuming they left us something to send, send it */
300 if (eff_buf.token_len)
301 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
302 eff_buf.token_len) !=
304 lwsl_debug("close: ext spill failed\n");
305 goto just_kill_connection;
310 * signal we are closing, lws_write will
311 * add any necessary version-specific stuff. If the write fails,
312 * no worries we are closing anyway. If we didn't initiate this
313 * close, then our state has been changed to
314 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
316 * Likewise if it's a second call to close this connection after we
317 * sent the close indication to the peer already, we are in state
318 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
321 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
322 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
323 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
324 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
325 lwsl_debug("sending close indication...\n");
327 /* if no prepared close reason, use 1000 and no aux data */
328 if (!wsi->u.ws.close_in_ping_buffer_len) {
329 wsi->u.ws.close_in_ping_buffer_len = 2;
330 wsi->u.ws.ping_payload_buf[LWS_PRE] =
331 (reason >> 16) & 0xff;
332 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
336 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
337 wsi->u.ws.close_in_ping_buffer_len,
341 * we have sent a nice protocol level indication we
342 * now wish to close, we should not send anything more
344 wsi->state = LWSS_AWAITING_CLOSE_ACK;
347 * ...and we should wait for a reply for a bit
350 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
351 lwsl_debug("sent close indication, awaiting ack\n");
356 lwsl_info("close: sending close packet failed, hanging up\n");
358 /* else, the send failed and we should just hang up */
361 just_kill_connection:
363 /* detach ourselves from parent's child list */
364 pwsi = &wsi->parent->child_list;
367 lwsl_notice("%s: detach %p from parent %p\n",
368 __func__, wsi, wsi->parent);
369 *pwsi = wsi->sibling_list;
372 pwsi = &(*pwsi)->sibling_list;
375 lwsl_err("%s: failed to detach from parent\n",
381 * Testing with ab shows that we have to stage the socket close when
382 * the system is under stress... shutdown any further TX, change the
383 * state to one that won't emit anything more, and wait with a timeout
384 * for the POLLIN to show a zero-size rx before coming back and doing
387 if (wsi->state != LWSS_SHUTDOWN &&
388 wsi->state != LWSS_CLIENT_UNCONNECTED &&
389 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
390 !wsi->socket_is_permanently_unusable) {
391 lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, wsi->sock, wsi->state);
392 n = shutdown(wsi->sock, SHUT_WR);
394 lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
396 // This causes problems with disconnection when the events are half closing connection
397 // FD_READ | FD_CLOSE (33)
399 /* libuv: no event available to guarantee completion */
400 if (!LWS_LIBUV_ENABLED(context)) {
402 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
403 wsi->state = LWSS_SHUTDOWN;
404 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
405 context->timeout_secs);
412 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
414 #ifdef LWS_WITH_HTTP_PROXY
416 lws_rewrite_destroy(wsi->rw);
421 * we won't be servicing or receiving anything further from this guy
422 * delete socket from the internal poll list if still present
424 lws_ssl_remove_wsi_from_buffered_list(wsi);
425 lws_remove_from_timeout_list(wsi);
427 /* checking return redundant since we anyway close */
428 remove_wsi_socket_from_fds(wsi);
430 wsi->state = LWSS_DEAD_SOCKET;
432 lws_free_set_NULL(wsi->rxflow_buffer);
434 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
435 wsi->mode == LWSCM_WS_SERVING ||
436 wsi->mode == LWSCM_WS_CLIENT) {
438 if (wsi->u.ws.rx_draining_ext) {
439 struct lws **w = &pt->rx_draining_ext_list;
441 wsi->u.ws.rx_draining_ext = 0;
442 /* remove us from context draining ext list */
445 *w = wsi->u.ws.rx_draining_ext_list;
448 w = &((*w)->u.ws.rx_draining_ext_list);
450 wsi->u.ws.rx_draining_ext_list = NULL;
453 if (wsi->u.ws.tx_draining_ext) {
454 struct lws **w = &pt->tx_draining_ext_list;
456 wsi->u.ws.tx_draining_ext = 0;
457 /* remove us from context draining ext list */
460 *w = wsi->u.ws.tx_draining_ext_list;
463 w = &((*w)->u.ws.tx_draining_ext_list);
465 wsi->u.ws.tx_draining_ext_list = NULL;
467 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
469 if (wsi->trunc_alloc)
470 /* not going to be completed... nuke it */
471 lws_free_set_NULL(wsi->trunc_alloc);
473 wsi->u.ws.ping_payload_len = 0;
474 wsi->u.ws.ping_pending_flag = 0;
477 /* tell the user it's all over for this guy */
479 if (wsi->protocol && wsi->protocol->callback &&
480 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
481 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
482 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
483 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
484 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
485 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
486 lwsl_debug("calling back CLOSED\n");
487 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
488 wsi->user_space, NULL, 0);
489 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
490 lwsl_debug("calling back CLOSED_HTTP\n");
491 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
492 wsi->user_space, NULL, 0 );
493 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
494 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
497 lwsl_debug("Connection closed before server reply\n");
498 errorString = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
500 wsi->vhost->protocols[0].callback(wsi,
501 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
502 wsi->user_space, errorString,
503 (unsigned int)strlen(errorString));
505 wsi->vhost->protocols[0].callback(wsi,
506 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
507 wsi->user_space, NULL, 0);
510 lwsl_debug("not calling back closed mode=%d state=%d\n",
511 wsi->mode, wsi->state_pre_close);
513 /* deallocate any active extension contexts */
515 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
516 lwsl_warn("extension destruction failed\n");
518 * inform all extensions in case they tracked this guy out of band
519 * even though not active on him specifically
521 if (lws_ext_cb_all_exts(context, wsi,
522 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
523 lwsl_warn("ext destroy wsi failed\n");
525 wsi->socket_is_permanently_unusable = 1;
528 if (LWS_LIBUV_ENABLED(context)) {
529 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
530 /* libuv has to do his own close handle processing asynchronously */
531 lws_libuv_closehandle(wsi);
537 lws_close_free_wsi_final(wsi);
541 lws_close_free_wsi_final(struct lws *wsi)
545 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
547 //lwsl_err("*** closing sockfd %d\n", wsi->sock);
548 n = compatible_close(wsi->sock);
550 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
553 compatible_close(wsi->sock);
555 wsi->sock = LWS_SOCK_INVALID;
558 /* outermost destroy notification for wsi (user_space still intact) */
559 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
560 wsi->user_space, NULL, 0);
564 for (n = 0; n < 6; n++)
565 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
566 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
576 * lws_get_urlarg_by_name() - return pointer to arg value if present
577 * @wsi: the connection to check
578 * @name: the arg name, like "token="
579 * @buf: the buffer to receive the urlarg (including the name= part)
580 * @len: the length of the buffer to receive the urlarg
582 * Returns NULL if not found or a pointer inside @buf to just after the
586 LWS_VISIBLE LWS_EXTERN const char *
587 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
589 int n = 0, sl = strlen(name);
591 while (lws_hdr_copy_fragment(wsi, buf, len,
592 WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
594 if (!strncmp(buf, name, sl))
605 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
609 ipv6 = LWS_IPV6_ENABLED(vh);
613 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
618 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
619 int name_len, char *rip, int rip_len)
622 struct addrinfo ai, *res;
623 struct sockaddr_in addr4;
628 addr4.sin_family = AF_UNSPEC;
631 if (LWS_IPV6_ENABLED(vh)) {
632 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
633 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
637 // Strip off the IPv4 to IPv6 header if one exists
638 if (strncmp(rip, "::ffff:", 7) == 0)
639 memmove(rip, rip + 7, strlen(rip) - 6);
641 getnameinfo((struct sockaddr *)ads,
642 sizeof(struct sockaddr_in6), name,
643 name_len, NULL, 0, 0);
649 struct addrinfo *result;
651 memset(&ai, 0, sizeof ai);
652 ai.ai_family = PF_UNSPEC;
653 ai.ai_socktype = SOCK_STREAM;
654 ai.ai_flags = AI_CANONNAME;
656 if (getnameinfo((struct sockaddr *)ads,
657 sizeof(struct sockaddr_in),
658 name, name_len, NULL, 0, 0))
664 if (getaddrinfo(name, NULL, &ai, &result))
668 while (addr4.sin_family == AF_UNSPEC && res) {
669 switch (res->ai_family) {
671 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
672 addr4.sin_family = AF_INET;
678 freeaddrinfo(result);
681 if (addr4.sin_family == AF_UNSPEC)
684 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
701 * lws_get_peer_simple() - Get client address information without RDNS
702 * @wsi: Local struct lws associated with
703 * @name: Buffer to take client address name
704 * @name_len: Length of client address name buffer
706 * This provides a 123.123.123.123 type IP address in @name from the
707 * peer that has connected to @wsi
710 LWS_VISIBLE const char *
711 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
716 struct sockaddr_in6 sin6;
718 struct sockaddr_in sin4;
723 if (LWS_IPV6_ENABLED(wsi->vhost)) {
737 if (getpeername(wsi->sock, p, &len) < 0 || len > olen) {
738 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
742 return lws_plat_inet_ntop(af, q, name, namelen);
749 * lws_get_peer_addresses() - Get client address information
750 * @wsi: Local struct lws associated with
751 * @fd: Connection socket descriptor
752 * @name: Buffer to take client address name
753 * @name_len: Length of client address name buffer
754 * @rip: Buffer to take client address IP dotted quad
755 * @rip_len: Length of client address IP buffer
757 * This function fills in @name and @rip with the name and IP of
758 * the client connected with socket descriptor @fd. Names may be
759 * truncated if there is not enough room. If either cannot be
760 * determined, they will be returned as valid zero-length strings.
764 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
765 int name_len, char *rip, int rip_len)
770 struct sockaddr_in6 sin6;
772 struct sockaddr_in sin4;
773 struct lws_context *context = wsi->context;
780 lws_latency_pre(context, wsi);
783 if (LWS_IPV6_ENABLED(wsi->vhost)) {
793 if (getpeername(fd, p, &len) < 0) {
794 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
798 ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
801 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
813 * lws_context_user() - get the user data associated with the context
814 * @context: Websocket context
816 * This returns the optional user allocation that can be attached to
817 * the context the sockets live in at context_create time. It's a way
818 * to let all sockets serviced in the same context share data without
819 * using globals statics in the user code.
822 lws_context_user(struct lws_context *context)
824 return context->user_space;
827 LWS_VISIBLE struct lws_vhost *
828 lws_vhost_get(struct lws *wsi)
833 LWS_VISIBLE struct lws_vhost *
834 lws_get_vhost(struct lws *wsi)
839 LWS_VISIBLE const struct lws_protocols *
840 lws_protocol_get(struct lws *wsi)
842 return wsi->protocol;
847 * lws_callback_all_protocol() - Callback all connections using
848 * the given protocol with the given reason
850 * @protocol: Protocol whose connections will get callbacks
851 * @reason: Callback reason index
855 lws_callback_all_protocol(struct lws_context *context,
856 const struct lws_protocols *protocol, int reason)
858 struct lws_context_per_thread *pt = &context->pt[0];
859 unsigned int n, m = context->count_threads;
863 for (n = 0; n < pt->fds_count; n++) {
864 wsi = wsi_from_fd(context, pt->fds[n].fd);
867 if (wsi->protocol == protocol)
868 protocol->callback(wsi, reason, wsi->user_space,
878 * lws_callback_all_protocol_vhost() - Callback all connections using
879 * the given protocol with the given reason
881 * @vh: Vhost whose connections will get callbacks
882 * @protocol: Which protocol to match
883 * @reason: Callback reason index
887 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
888 const struct lws_protocols *protocol, int reason)
890 struct lws_context *context = vh->context;
891 struct lws_context_per_thread *pt = &context->pt[0];
892 unsigned int n, m = context->count_threads;
896 for (n = 0; n < pt->fds_count; n++) {
897 wsi = wsi_from_fd(context, pt->fds[n].fd);
900 if (wsi->vhost == vh && wsi->protocol == protocol)
901 protocol->callback(wsi, reason, wsi->user_space,
911 * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost
912 * with the given reason
914 * @wsi: wsi whose vhost will get callbacks
915 * @reason: Callback reason index
916 * @in: in argument to callback
917 * @len: len argument to callback
919 * This is useful when informing all fellow enabled protocols on a vhost about
920 * a vhost-wide event, eg, creation or deletion of an account
923 LWS_VISIBLE LWS_EXTERN int
924 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
928 for (n = 0; n < wsi->vhost->count_protocols; n++)
929 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
936 * lws_now_secs() - seconds since 1970-1-1
939 LWS_VISIBLE LWS_EXTERN unsigned long
944 gettimeofday(&tv, NULL);
953 * lws_get_socket_fd() - returns the socket file descriptor
955 * You will not need this unless you are doing something special
957 * @wsi: Websocket connection instance
961 lws_get_socket_fd(struct lws *wsi)
970 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
971 int ret, int completed)
973 unsigned long long u;
976 u = time_in_microseconds();
979 wsi->latency_start = u;
980 if (!wsi->action_start)
981 wsi->action_start = u;
985 if (wsi->action_start == wsi->latency_start)
987 "Completion first try lat %lluus: %p: ret %d: %s\n",
988 u - wsi->latency_start,
989 (void *)wsi, ret, action);
992 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
993 u - wsi->action_start,
994 u - wsi->latency_start,
995 (void *)wsi, ret, action);
996 wsi->action_start = 0;
998 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
999 u - wsi->latency_start, (void *)wsi, ret, action);
1001 if (u - wsi->latency_start > context->worst_latency) {
1002 context->worst_latency = u - wsi->latency_start;
1003 strcpy(context->worst_latency_info, buf);
1005 lwsl_latency("%s", buf);
1012 * lws_rx_flow_control() - Enable and disable socket servicing for
1015 * If the output side of a server process becomes choked, this allows flow
1016 * control for the input side.
1018 * @wsi: Websocket connection instance to get callback for
1019 * @enable: 0 = disable read servicing for this connection, 1 = enable
1023 lws_rx_flow_control(struct lws *wsi, int enable)
1025 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1028 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1029 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1035 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
1037 * When the user server code realizes it can accept more input, it can
1038 * call this to have the RX flow restriction removed from all connections using
1039 * the given protocol.
1041 * @protocol: all connections using this protocol will be allowed to receive
1045 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1046 const struct lws_protocols *protocol)
1048 const struct lws_context_per_thread *pt = &context->pt[0];
1050 unsigned int n, m = context->count_threads;
1053 for (n = 0; n < pt->fds_count; n++) {
1054 wsi = wsi_from_fd(context, pt->fds[n].fd);
1057 if (wsi->protocol == protocol)
1058 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1066 * lws_canonical_hostname() - returns this host's hostname
1068 * This is typically used by client code to fill in the host parameter
1069 * when making a client connection. You can only call it after the context
1072 * @context: Websocket context
1074 LWS_VISIBLE extern const char *
1075 lws_canonical_hostname(struct lws_context *context)
1077 return (const char *)context->canonical_hostname;
1080 int user_callback_handle_rxflow(lws_callback_function callback_function,
1082 enum lws_callback_reasons reason, void *user,
1083 void *in, size_t len)
1087 n = callback_function(wsi, reason, user, in, len);
1089 n = _lws_rx_flow_control(wsi);
1096 * lws_set_proxy() - Setups proxy to lws_context.
1097 * @context: pointer to struct lws_context you want set proxy to
1098 * @proxy: pointer to c string containing proxy in format address:port
1100 * Returns 0 if proxy string was parsed and proxy was setup.
1101 * Returns -1 if @proxy is NULL or has incorrect format.
1103 * This is only required if your OS does not provide the http_proxy
1104 * environment variable (eg, OSX)
1106 * IMPORTANT! You should call this function right after creation of the
1107 * lws_context and before call to connect. If you call this
1108 * function after connect behavior is undefined.
1109 * This function will override proxy settings made on lws_context
1110 * creation with genenv() call.
1114 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1117 char authstring[96];
1122 p = strchr(proxy, '@');
1123 if (p) { /* auth is around */
1125 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1128 strncpy(authstring, proxy, p - proxy);
1129 // null termination not needed on input
1130 if (lws_b64_encode_string(authstring, (p - proxy),
1131 vhost->proxy_basic_auth_token,
1132 sizeof vhost->proxy_basic_auth_token) < 0)
1135 lwsl_notice(" Proxy auth in use\n");
1139 vhost->proxy_basic_auth_token[0] = '\0';
1141 strncpy(vhost->http_proxy_address, proxy,
1142 sizeof(vhost->http_proxy_address) - 1);
1143 vhost->http_proxy_address[
1144 sizeof(vhost->http_proxy_address) - 1] = '\0';
1146 p = strchr(vhost->http_proxy_address, ':');
1147 if (!p && !vhost->http_proxy_port) {
1148 lwsl_err("http_proxy needs to be ads:port\n");
1154 vhost->http_proxy_port = atoi(p + 1);
1158 lwsl_notice(" Proxy %s:%u\n", vhost->http_proxy_address,
1159 vhost->http_proxy_port);
1164 lwsl_err("proxy auth too long\n");
1170 * lws_get_protocol() - Returns a protocol pointer from a websocket
1172 * @wsi: pointer to struct websocket you want to know the protocol of
1175 * Some apis can act on all live connections of a given protocol,
1176 * this is how you can get a pointer to the active protocol if needed.
1179 LWS_VISIBLE const struct lws_protocols *
1180 lws_get_protocol(struct lws *wsi)
1182 return wsi->protocol;
1186 lws_is_final_fragment(struct lws *wsi)
1188 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
1189 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
1190 wsi->u.ws.rx_draining_ext);
1191 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1194 LWS_VISIBLE unsigned char
1195 lws_get_reserved_bits(struct lws *wsi)
1197 return wsi->u.ws.rsv;
1201 lws_ensure_user_space(struct lws *wsi)
1203 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1207 /* allocate the per-connection user memory (if any) */
1209 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1210 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1211 if (wsi->user_space == NULL) {
1212 lwsl_err("Out of memory for conn user space\n");
1216 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
1217 __func__, wsi, wsi->protocol->per_session_data_size,
1223 * lwsl_timestamp: generate logging timestamp string
1225 * @level: logging level
1226 * @p: char * buffer to take timestamp
1229 * returns length written in p
1232 lwsl_timestamp(int level, char *p, int len)
1234 time_t o_now = time(NULL);
1235 unsigned long long now;
1236 struct tm *ptm = NULL;
1244 ptm = localtime(&o_now);
1246 if (localtime_r(&o_now, &tm))
1251 for (n = 0; n < LLL_COUNT; n++) {
1252 if (level != (1 << n))
1254 now = time_in_microseconds() / 100;
1256 n = snprintf(p, len,
1257 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1258 ptm->tm_year + 1900,
1264 (int)(now % 10000), log_level_names[n]);
1266 n = snprintf(p, len, "[%llu:%04d] %s: ",
1267 (unsigned long long) now / 10000,
1268 (int)(now % 10000), log_level_names[n]);
1275 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1279 lwsl_timestamp(level, buf, sizeof(buf));
1281 fprintf(stderr, "%s%s", buf, line);
1284 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1288 if (!(log_level & filter))
1291 vsnprintf(buf, sizeof(buf), format, vl);
1292 buf[sizeof(buf) - 1] = '\0';
1294 lwsl_emit(filter, buf);
1297 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1301 va_start(ap, format);
1302 _lws_logv(filter, format, ap);
1307 * lws_set_log_level() - Set the logging bitfield
1308 * @level: OR together the LLL_ debug contexts you want output from
1309 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1310 * function to perform log string emission instead of
1311 * the default stderr one.
1313 * log level defaults to "err", "warn" and "notice" contexts enabled and
1314 * emission on stderr.
1317 LWS_VISIBLE void lws_set_log_level(int level,
1318 void (*func)(int level, const char *line))
1326 * lws_use_ssl() - Find out if connection is using SSL
1327 * @wsi: websocket connection to check
1329 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1330 * using verified cert, and 2 if using SSL but the cert was not
1331 * checked (appears for client wsi told to skip check on connection)
1334 lws_is_ssl(struct lws *wsi)
1336 #ifdef LWS_OPENSSL_SUPPORT
1337 return wsi->use_ssl;
1345 * lws_partial_buffered() - find out if lws buffered the last write
1346 * @wsi: websocket connection to check
1348 * Returns 1 if you cannot use lws_write because the last
1349 * write on this connection is still buffered, and can't be cleared without
1350 * returning to the service loop and waiting for the connection to be
1353 * If you will try to do >1 lws_write call inside a single
1354 * WRITEABLE callback, you must check this after every write and bail if
1355 * set, ask for a new writeable callback and continue writing from there.
1357 * This is never set at the start of a writeable callback, but any write
1362 lws_partial_buffered(struct lws *wsi)
1364 return !!wsi->trunc_len;
1367 void lws_set_protocol_write_pending(struct lws *wsi,
1368 enum lws_pending_protocol_send pend)
1370 lwsl_info("setting pps %d\n", pend);
1373 lwsl_err("pps overwrite\n");
1375 lws_rx_flow_control(wsi, 0);
1376 lws_callback_on_writable(wsi);
1380 lws_get_peer_write_allowance(struct lws *wsi)
1382 #ifdef LWS_USE_HTTP2
1383 /* only if we are using HTTP2 on this connection */
1384 if (wsi->mode != LWSCM_HTTP2_SERVING)
1386 /* user is only interested in how much he can send, or that he can't */
1387 if (wsi->u.http2.tx_credit <= 0)
1390 return wsi->u.http2.tx_credit;
1398 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1400 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1401 memset(&wsi->u, 0, sizeof(wsi->u));
1405 LWS_VISIBLE struct lws_plat_file_ops *
1406 lws_get_fops(struct lws_context *context)
1408 return &context->fops;
1412 * lws_get_context - Allow geting lws_context from a Websocket connection
1415 * With this function, users can access context in the callback function.
1416 * Otherwise users may have to declare context as a global variable.
1418 * @wsi: Websocket connection instance
1421 LWS_VISIBLE LWS_EXTERN struct lws_context *
1422 lws_get_context(const struct lws *wsi)
1424 return wsi->context;
1427 LWS_VISIBLE LWS_EXTERN int
1428 lws_get_count_threads(struct lws_context *context)
1430 return context->count_threads;
1433 LWS_VISIBLE LWS_EXTERN void *
1434 lws_wsi_user(struct lws *wsi)
1436 return wsi->user_space;
1439 LWS_VISIBLE LWS_EXTERN struct lws *
1440 lws_get_parent(const struct lws *wsi)
1445 LWS_VISIBLE LWS_EXTERN struct lws *
1446 lws_get_child(const struct lws *wsi)
1448 return wsi->child_list;
1451 LWS_VISIBLE LWS_EXTERN void
1452 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1453 unsigned char *buf, size_t len)
1455 unsigned char *p, *start;
1456 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1458 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1460 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1462 *p++ = (((int)status) >> 8) & 0xff;
1463 *p++ = ((int)status) & 0xff;
1466 while (len-- && p < start + budget)
1469 wsi->u.ws.close_in_ping_buffer_len = p - start;
1473 _lws_rx_flow_control(struct lws *wsi)
1475 /* there is no pending change */
1476 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1477 lwsl_debug("%s: no pending change\n", __func__);
1481 /* stuff is still buffered, not ready to really accept new input */
1482 if (wsi->rxflow_buffer) {
1483 /* get ourselves called back to deal with stashed buffer */
1484 lws_callback_on_writable(wsi);
1488 /* pending is cleared, we can change rxflow state */
1490 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1492 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1493 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1495 /* adjust the pollfd for this wsi */
1497 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1498 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1499 lwsl_info("%s: fail\n", __func__);
1503 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1510 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1512 static const unsigned char e0f4[] = {
1513 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1514 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1515 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1516 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1517 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1518 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1519 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1520 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1521 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1522 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1523 0x80 | ((4 - 1) << 2) | 1, /* ea */
1524 0x80 | ((4 - 1) << 2) | 1, /* eb */
1525 0x80 | ((4 - 1) << 2) | 1, /* ec */
1526 0x80 | ((2 - 1) << 2) | 1, /* ed */
1527 0x80 | ((4 - 1) << 2) | 1, /* ee */
1528 0x80 | ((4 - 1) << 2) | 1, /* ef */
1529 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1530 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1531 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1532 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1533 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1536 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1537 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1539 unsigned char s = *state;
1542 unsigned char c = *buf++;
1546 if (c < 0xc2 || c > 0xf4)
1549 s = 0x80 | ((4 - 1) << 2);
1554 if (c < (s & 0xf0) ||
1555 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1557 s = e0f4[21 + (s & 3)];
1567 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1568 * Notice it does so by dropping '\0' into input string
1569 * and the leading / on the path is consequently lost
1571 * @p: incoming uri string.. will get written to
1572 * @prot: result pointer for protocol part (https://)
1573 * @ads: result pointer for address part
1574 * @port: result pointer for port part
1575 * @path: result pointer for path part
1578 LWS_VISIBLE LWS_EXTERN int
1579 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1583 static const char *slash = "/";
1585 /* cut up the location into address, port and path */
1587 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1598 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1600 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1603 while (*p && *p != ':' && *p != '/')
1608 while (*p && *p != '/')
1621 #ifdef LWS_NO_EXTENSIONS
1623 /* we need to provide dummy callbacks for internal exts
1624 * so user code runs when faced with a lib compiled with
1625 * extensions disabled.
1629 lws_extension_callback_pm_deflate(struct lws_context *context,
1630 const struct lws_extension *ext,
1632 enum lws_extension_callback_reasons reason,
1633 void *user, void *in, size_t len)
1648 lws_socket_bind(struct lws_vhost *vhost, int sockfd, int port,
1652 #ifdef LWS_USE_UNIX_SOCK
1653 struct sockaddr_un serv_unix;
1656 struct sockaddr_in6 serv_addr6;
1658 struct sockaddr_in serv_addr4;
1659 socklen_t len = sizeof(struct sockaddr);
1661 struct sockaddr_in sin;
1664 #ifdef LWS_USE_UNIX_SOCK
1665 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1666 v = (struct sockaddr *)&serv_unix;
1667 n = sizeof(struct sockaddr_un);
1668 bzero((char *) &serv_unix, sizeof(serv_unix));
1669 serv_unix.sun_family = AF_UNIX;
1670 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1671 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1675 strcpy(serv_unix.sun_path, iface);
1676 if (serv_unix.sun_path[0] == '@')
1677 serv_unix.sun_path[0] = '\0';
1682 if (LWS_IPV6_ENABLED(vhost)) {
1683 v = (struct sockaddr *)&serv_addr6;
1684 n = sizeof(struct sockaddr_in6);
1685 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1687 interface_to_sa(vhost, iface,
1688 (struct sockaddr_in *)v, n) < 0) {
1689 lwsl_err("Unable to find interface %s\n", iface);
1692 serv_addr6.sin6_family = AF_INET6;
1693 serv_addr6.sin6_port = htons(port);
1697 v = (struct sockaddr *)&serv_addr4;
1698 n = sizeof(serv_addr4);
1699 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1700 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1701 serv_addr4.sin_family = AF_INET;
1704 interface_to_sa(vhost, iface,
1705 (struct sockaddr_in *)v, n) < 0) {
1706 lwsl_err("Unable to find interface %s\n", iface);
1710 serv_addr4.sin_port = htons(port);
1713 n = bind(sockfd, v, n);
1714 #ifdef LWS_USE_UNIX_SOCK
1715 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
1716 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1717 sockfd, iface, n, LWS_ERRNO);
1722 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1723 sockfd, port, n, LWS_ERRNO);
1727 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1728 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1730 port = ntohs(sin.sin_port);
1736 static const char *hex = "0123456789ABCDEF";
1739 urlencode(const char *in, int inlen, char *out, int outlen)
1741 char *start = out, *end = out + outlen;
1743 while (inlen-- && out < end - 4) {
1744 if ((*in >= 'A' && *in <= 'Z') ||
1745 (*in >= 'a' && *in <= 'z') ||
1746 (*in >= '0' && *in <= '9') ||
1760 *out++ = hex[(*in) >> 4];
1761 *out++ = hex[(*in++) & 15];
1772 * lws_sql_purify() - like strncpy but with escaping for sql quotes
1774 * @escaped: output buffer
1775 * @string: input buffer ('/0' terminated)
1776 * @len: output buffer max length
1778 * Because escaping expands the output string, it's not
1779 * possible to do it in-place, ie, with escaped == string
1782 LWS_VISIBLE LWS_EXTERN const char *
1783 lws_sql_purify(char *escaped, const char *string, int len)
1785 const char *p = string;
1788 while (*p && len-- > 2) {
1803 * lws_json_purify() - like strncpy but with escaping for json chars
1805 * @escaped: output buffer
1806 * @string: input buffer ('/0' terminated)
1807 * @len: output buffer max length
1809 * Because escaping expands the output string, it's not
1810 * possible to do it in-place, ie, with escaped == string
1813 LWS_VISIBLE LWS_EXTERN const char *
1814 lws_json_purify(char *escaped, const char *string, int len)
1816 const char *p = string;
1819 while (*p && len-- > 6) {
1820 if (*p == '\"' || *p == '\\' || *p < 0x20) {
1825 *q++ = hex[((*p) >> 4) & 15];
1826 *q++ = hex[(*p) & 15];
1839 * lws_urlencode() - like strncpy but with urlencoding
1841 * @escaped: output buffer
1842 * @string: input buffer ('/0' terminated)
1843 * @len: output buffer max length
1845 * Because urlencoding expands the output string, it's not
1846 * possible to do it in-place, ie, with escaped == string
1849 LWS_VISIBLE LWS_EXTERN const char *
1850 lws_urlencode(char *escaped, const char *string, int len)
1852 const char *p = string;
1855 while (*p && len-- > 3) {
1861 if ((*p >= '0' && *p <= '9') ||
1862 (*p >= 'A' && *p <= 'Z') ||
1863 (*p >= 'a' && *p <= 'z')) {
1868 *q++ = hex[(*p >> 4) & 0xf];
1869 *q++ = hex[*p & 0xf];
1880 * lws_urldecode() - like strncpy but with urldecoding
1882 * @string: output buffer
1883 * @escaped: input buffer ('\0' terminated)
1884 * @len: output buffer max length
1886 * This is only useful for '\0' terminated strings
1888 * Since urldecoding only shrinks the output string, it is possible to
1889 * do it in-place, ie, string == escaped
1892 LWS_VISIBLE LWS_EXTERN int
1893 lws_urldecode(char *string, const char *escaped, int len)
1898 while (*escaped && len) {
1901 if (*escaped == '%') {
1906 if (*escaped == '+') {
1912 *string++ = *escaped++;
1916 n = char_to_hex(*escaped);
1925 n = char_to_hex(*escaped);
1929 *string++ = sum | n;
1941 LWS_VISIBLE LWS_EXTERN int
1942 lws_finalize_startup(struct lws_context *context)
1944 struct lws_context_creation_info info;
1946 info.uid = context->uid;
1947 info.gid = context->gid;
1949 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1950 lws_plat_drop_app_privileges(&info);
1956 LWS_VISIBLE LWS_EXTERN int
1957 lws_is_cgi(struct lws *wsi) {
1968 lws_create_basic_wsi(struct lws_context *context, int tsi)
1970 struct lws *new_wsi;
1972 if ((unsigned int)context->pt[tsi].fds_count ==
1973 context->fd_limit_per_thread - 1) {
1974 lwsl_err("no space for new conn\n");
1978 new_wsi = lws_zalloc(sizeof(struct lws));
1979 if (new_wsi == NULL) {
1980 lwsl_err("Out of memory for new connection\n");
1985 new_wsi->context = context;
1986 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1987 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1989 /* intialize the instance struct */
1991 new_wsi->state = LWSS_CGI;
1992 new_wsi->mode = LWSCM_CGI;
1993 new_wsi->hdr_parsing_completed = 0;
1994 new_wsi->position_in_fds_table = -1;
1997 * these can only be set once the protocol is known
1998 * we set an unestablished connection's protocol pointer
1999 * to the start of the defauly vhost supported list, so it can look
2000 * for matching ones during the handshake
2002 new_wsi->protocol = context->vhost_list->protocols;
2003 new_wsi->user_space = NULL;
2004 new_wsi->ietf_spec_revision = 0;
2005 new_wsi->sock = LWS_SOCK_INVALID;
2006 context->count_wsi_allocated++;
2012 * lws_cgi: spawn network-connected cgi process
2014 * @wsi: connection to own the process
2015 * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
2018 LWS_VISIBLE LWS_EXTERN int
2019 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2020 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2022 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2023 char *env_array[30], cgi_path[400], e[1024], *p = e,
2024 *end = p + sizeof(e) - 1, tok[256], *t;
2025 struct lws_cgi *cgi;
2026 int n, m, i, uritok = WSI_TOKEN_GET_URI;
2029 * give the master wsi a cgi struct
2032 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2034 lwsl_err("%s: OOM\n", __func__);
2039 cgi->wsi = wsi; /* set cgi's owning wsi */
2041 /* create pipes for [stdin|stdout] and [stderr] */
2043 for (n = 0; n < 3; n++)
2044 if (pipe(cgi->pipe_fds[n]) == -1)
2047 /* create cgi wsis for each stdin/out/err fd */
2049 for (n = 0; n < 3; n++) {
2050 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2051 if (!cgi->stdwsi[n])
2053 cgi->stdwsi[n]->cgi_channel = n;
2054 cgi->stdwsi[n]->vhost = wsi->vhost;
2056 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2057 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2059 /* read side is 0, stdin we want the write side, others read */
2060 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
2061 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2062 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2067 for (n = 0; n < 3; n++) {
2068 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->sock);
2069 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2071 cgi->stdwsi[n]->parent = wsi;
2072 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2073 wsi->child_list = cgi->stdwsi[n];
2076 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2077 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2078 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2080 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2081 cgi->stdwsi[LWS_STDIN]->sock, cgi->stdwsi[LWS_STDOUT]->sock,
2082 cgi->stdwsi[LWS_STDERR]->sock);
2084 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2086 /* the cgi stdout is always sending us http1.x header data first */
2087 wsi->hdr_state = LCHS_HEADER;
2089 /* add us to the pt list of active cgis */
2090 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2091 cgi->cgi_list = pt->cgi_list;
2094 /* prepare his CGI env */
2098 if (lws_is_ssl(wsi))
2099 env_array[n++] = "HTTPS=ON";
2100 if (wsi->u.hdr.ah) {
2101 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
2102 uritok = WSI_TOKEN_POST_URI;
2103 snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2104 lws_hdr_simple_ptr(wsi, uritok));
2105 cgi_path[sizeof(cgi_path) - 1] = '\0';
2106 env_array[n++] = cgi_path;
2107 if (uritok == WSI_TOKEN_POST_URI)
2108 env_array[n++] = "REQUEST_METHOD=POST";
2110 env_array[n++] = "REQUEST_METHOD=GET";
2113 p += snprintf(p, end - p, "QUERY_STRING=");
2114 /* dump the individual URI Arg parameters */
2117 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2118 WSI_TOKEN_HTTP_URI_ARGS, m);
2122 while (*t && *t != '=' && p < end - 4)
2126 i = urlencode(t, i- (t - tok), p, end - p);
2138 p += snprintf(p, end - p, "PATH_INFO=%s",
2139 lws_hdr_simple_ptr(wsi, uritok) +
2140 script_uri_path_len);
2143 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2145 p += snprintf(p, end - p, "HTTP_REFERER=%s",
2146 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2149 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2151 p += snprintf(p, end - p, "HTTP_HOST=%s",
2152 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2155 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2157 p += snprintf(p, end - p, "HTTP_COOKIE=%s",
2158 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2161 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2163 p += snprintf(p, end - p, "USER_AGENT=%s",
2164 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2167 if (uritok == WSI_TOKEN_POST_URI) {
2168 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2170 p += snprintf(p, end - p, "CONTENT_TYPE=%s",
2171 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2174 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2176 p += snprintf(p, end - p, "CONTENT_LENGTH=%s",
2177 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2182 p += snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2186 p += snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2188 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2191 mp_cgienv = mp_cgienv->next;
2194 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2195 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2196 env_array[n] = NULL;
2199 for (m = 0; m < n; m++)
2200 lwsl_err(" %s\n", env_array[m]);
2204 * Actually having made the env, as a cgi we don't need the ah
2207 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
2208 lws_header_table_detach(wsi, 0);
2210 /* we are ready with the redirection pipes... run the thing */
2211 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2217 lwsl_err("fork failed, errno %d", errno);
2221 #if defined(__linux__)
2222 prctl(PR_SET_PDEATHSIG, SIGTERM);
2224 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2227 /* we are the parent process */
2228 wsi->context->count_cgi_spawned++;
2229 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2233 /* somewhere we can at least read things and enter it */
2235 lwsl_notice("%s: Failed to chdir\n", __func__);
2237 /* We are the forked process, redirect and kill inherited things.
2239 * Because of vfork(), we cannot do anything that changes pages in
2240 * the parent environment. Stuff that changes kernel state for the
2241 * process is OK. Stuff that happens after the execvpe() is OK.
2244 for (n = 0; n < 3; n++)
2245 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2246 lwsl_err("%s: stdin dup2 failed\n", __func__);
2250 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2251 for (m = 0; m < n; m++) {
2252 p = strchr(env_array[m], '=');
2254 setenv(env_array[m], p, 1);
2256 execvp(exec_array[0], (char * const *)&exec_array[0]);
2258 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2264 /* drop us from the pt cgi list */
2265 pt->cgi_list = cgi->cgi_list;
2268 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2270 for (n = 0; n < 3; n++)
2271 if (wsi->cgi->stdwsi[n])
2272 lws_free_wsi(cgi->stdwsi[n]);
2275 for (n = 0; n < 3; n++) {
2276 if (cgi->pipe_fds[n][0])
2277 close(cgi->pipe_fds[n][0]);
2278 if (cgi->pipe_fds[n][1])
2279 close(cgi->pipe_fds[n][1]);
2282 lws_free_set_NULL(wsi->cgi);
2284 lwsl_err("%s: failed\n", __func__);
2289 * lws_cgi_write_split_headers: write cgi output accounting for header part
2291 * @wsi: connection to own the process
2293 LWS_VISIBLE LWS_EXTERN int
2294 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2296 int n, m, match = 0, lp = 0;
2297 static const char * const content_length = "content-length: ";
2298 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2299 *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
2304 while (wsi->hdr_state != LHCS_PAYLOAD) {
2305 /* we have to separate header / finalize and
2306 * payload chunks, since they need to be
2307 * handled separately
2309 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2311 if (errno != EAGAIN) {
2312 lwsl_debug("%s: read says %d\n", __func__, n);
2319 lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
2320 switch (wsi->hdr_state) {
2322 if (!content_length[match] &&
2323 (c >= '0' && c <= '9') &&
2324 lp < sizeof(l) - 1) {
2327 wsi->cgi->content_length = atol(l);
2329 if (tolower(c) == content_length[match])
2334 /* some cgi only send us \x0a for EOL */
2336 wsi->hdr_state = LCHS_SINGLE_0A;
2341 wsi->hdr_state = LCHS_LF1;
2349 wsi->hdr_state = LCHS_CR2;
2352 /* we got \r[^\n]... it's unreasonable */
2353 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2359 wsi->hdr_state = LCHS_LF2;
2362 wsi->hdr_state = LCHS_HEADER;
2367 case LCHS_SINGLE_0A:
2370 lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
2371 wsi->hdr_state = LHCS_PAYLOAD;
2372 /* drop the \0xa ... finalize will add it if needed */
2373 if (lws_finalize_http_header(wsi,
2374 (unsigned char **)&p,
2375 (unsigned char *)end))
2380 /* we got \r\n\r[^\n]... it's unreasonable */
2382 /* we got \x0anext header, it's reasonable */
2384 wsi->hdr_state = LCHS_HEADER;
2391 /* ran out of input, ended the headers, or filled up the headers buf */
2392 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2394 m = lws_write(wsi, (unsigned char *)start,
2395 p - start, LWS_WRITE_HTTP_HEADERS);
2397 lwsl_debug("%s: write says %d\n", __func__, m);
2400 /* writeability becomes uncertain now we wrote
2401 * something, we must return to the event loop
2408 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2409 start, sizeof(buf) - LWS_PRE);
2411 if (n < 0 && errno != EAGAIN) {
2412 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2416 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2417 //lwsl_notice("write %d\n", m);
2419 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2422 wsi->cgi->content_length_seen += m;
2429 * lws_cgi_kill: terminate cgi process associated with wsi
2431 * @wsi: connection to own the process
2433 LWS_VISIBLE LWS_EXTERN int
2434 lws_cgi_kill(struct lws *wsi)
2436 struct lws_cgi_args args;
2439 lwsl_debug("%s: %p\n", __func__, wsi);
2444 if (wsi->cgi->pid > 0) {
2445 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2447 lwsl_debug("%s: PID %d reaped\n", __func__,
2451 /* kill the process group */
2452 n = kill(-wsi->cgi->pid, SIGTERM);
2453 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2454 wsi->cgi->pid, n, errno);
2457 * hum seen errno=3 when process is listed in ps,
2458 * it seems we don't always retain process grouping
2460 * Direct these fallback attempt to the exact child
2462 n = kill(wsi->cgi->pid, SIGTERM);
2464 n = kill(wsi->cgi->pid, SIGPIPE);
2466 n = kill(wsi->cgi->pid, SIGKILL);
2468 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2469 __func__, wsi->cgi->pid, errno);
2473 /* He could be unkillable because he's a zombie */
2476 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2478 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2480 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2482 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2488 args.stdwsi = &wsi->cgi->stdwsi[0];
2490 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2491 wsi->protocol->callback,
2492 wsi, LWS_CALLBACK_CGI_TERMINATED,
2494 (void *)&args, 0)) {
2496 if (!wsi->cgi->being_closed)
2497 lws_close_free_wsi(wsi, 0);
2504 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2506 struct lws_cgi **pcgi, *cgi = NULL;
2510 /* find finished guys but don't reap yet */
2511 n = waitpid(-1, &status, WNOHANG | WNOWAIT);
2514 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
2516 pcgi = &pt->cgi_list;
2518 /* check all the subprocesses on the cgi list */
2520 /* get the next one first as list may change */
2522 pcgi = &(*pcgi)->cgi_list;
2527 /* wait for stdout to be drained */
2528 if (cgi->content_length > cgi->content_length_seen)
2531 if (cgi->content_length) {
2532 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2533 __func__, cgi->wsi, cgi->content_length_seen);
2537 waitpid(n, &status, WNOHANG);
2539 * he's already terminated so no need for kill()
2540 * but we should do the terminated cgi callback
2541 * and close him if he's not already closing
2543 if (n == cgi->pid) {
2544 lwsl_debug("%s: found PID %d on cgi list\n",
2548 lws_cgi_kill(cgi->wsi);
2554 /* if not found on the cgi list, as he's one of ours, reap */
2556 lwsl_debug("%s: reading PID %d although no cgi match\n",
2558 waitpid(n, &status, WNOHANG);
2562 /* disable this to confirm timeout cgi cleanup flow */
2564 pcgi = &pt->cgi_list;
2566 /* check all the subprocesses on the cgi list */
2568 /* get the next one first as list may change */
2570 pcgi = &(*pcgi)->cgi_list;
2575 /* wait for stdout to be drained */
2576 if (cgi->content_length > cgi->content_length_seen)
2579 if (cgi->content_length) {
2580 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2581 __func__, cgi->wsi, cgi->content_length_seen);
2585 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2587 lwsl_debug("%s: found PID %d on cgi list\n",
2588 __func__, cgi->pid);
2591 lws_cgi_kill(cgi->wsi);
2598 /* general anti zombie defence */
2599 n = waitpid(-1, &status, WNOHANG);
2601 lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
2607 #ifdef LWS_NO_EXTENSIONS
2609 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2610 const char *opt_name, const char *opt_val)
2616 #ifdef LWS_WITH_ACCESS_LOG
2618 lws_access_log(struct lws *wsi)
2620 char *p = wsi->access_log.user_agent, ass[512];
2623 if (!wsi->access_log_pending)
2626 if (!wsi->access_log.header_log)
2632 l = snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
2633 wsi->access_log.header_log,
2634 wsi->access_log.response, wsi->access_log.sent, p);
2636 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
2637 if (write(wsi->vhost->log_fd, ass, l) != l)
2638 lwsl_err("Failed to write log\n");
2640 lwsl_err("%s", ass);
2642 if (wsi->access_log.header_log) {
2643 lws_free(wsi->access_log.header_log);
2644 wsi->access_log.header_log = NULL;
2646 if (wsi->access_log.user_agent) {
2647 lws_free(wsi->access_log.user_agent);
2648 wsi->access_log.user_agent = NULL;
2650 wsi->access_log_pending = 0;
2656 #ifdef LWS_WITH_SERVER_STATUS
2659 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
2661 static const char * const prots[] = {
2670 char *orig = buf, *end = buf + len - 1, first = 1;
2676 buf += snprintf(buf, end - buf,
2677 "{\n \"name\":\"%s\",\n"
2678 " \"port\":\"%d\",\n"
2679 " \"use_ssl\":\"%d\",\n"
2680 " \"sts\":\"%d\",\n"
2681 " \"rx\":\"%llu\",\n"
2682 " \"tx\":\"%llu\",\n"
2683 " \"conn\":\"%lu\",\n"
2684 " \"trans\":\"%lu\",\n"
2685 " \"ws_upg\":\"%lu\",\n"
2686 " \"http2_upg\":\"%lu\""
2688 vh->name, vh->listen_port,
2689 #ifdef LWS_OPENSSL_SUPPORT
2694 !!(vh->options & LWS_SERVER_OPTION_STS),
2695 vh->rx, vh->tx, vh->conn, vh->trans, vh->ws_upgrades,
2699 if (vh->mount_list) {
2700 const struct lws_http_mount *m = vh->mount_list;
2702 buf += snprintf(buf, end - buf, ",\n \"mounts\":[");
2705 buf += snprintf(buf, end - buf, ",");
2706 buf += snprintf(buf, end - buf,
2707 "\n {\n \"mountpoint\":\"%s\",\n"
2708 " \"origin\":\"%s%s\",\n"
2709 " \"cache_max_age\":\"%d\",\n"
2710 " \"cache_reuse\":\"%d\",\n"
2711 " \"cache_revalidate\":\"%d\",\n"
2712 " \"cache_intermediaries\":\"%d\"\n"
2715 prots[m->origin_protocol],
2719 m->cache_revalidate,
2720 m->cache_intermediaries);
2722 buf += snprintf(buf, end - buf,
2723 ",\n \"default\":\"%s\"",
2725 buf += snprintf(buf, end - buf, "\n }");
2729 buf += snprintf(buf, end - buf, "\n ]");
2732 if (vh->protocols) {
2736 buf += snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
2737 while (n < vh->count_protocols) {
2739 buf += snprintf(buf, end - buf, ",");
2740 buf += snprintf(buf, end - buf,
2742 " \"status\":\"ok\"\n }\n }"
2744 vh->protocols[n].name);
2748 buf += snprintf(buf, end - buf, "\n ]");
2751 buf += snprintf(buf, end - buf, "\n}");
2757 LWS_EXTERN LWS_VISIBLE int
2758 lws_json_dump_context(const struct lws_context *context, char *buf, int len)
2760 char *orig = buf, *end = buf + len - 1, first = 1;
2761 const struct lws_vhost *vh = context->vhost_list;
2764 struct lws_cgi * const *pcgi;
2766 const struct lws_context_per_thread *pt;
2767 time_t t = time(NULL);
2768 int listening = 0, cgi_count = 0, n;
2770 buf += snprintf(buf, end - buf, "{ "
2771 "\"version\":\"%s\",\n"
2772 "\"uptime\":\"%ld\",\n"
2773 "\"cgi_spawned\":\"%d\",\n"
2774 "\"pt_fd_max\":\"%d\",\n"
2775 "\"ah_pool_max\":\"%d\",\n"
2776 "\"wsi_alive\":\"%d\",\n",
2777 lws_get_library_version(),
2778 (unsigned long)(t - context->time_up),
2779 context->count_cgi_spawned,
2780 context->fd_limit_per_thread,
2781 context->max_http_header_pool,
2782 context->count_wsi_allocated);
2783 #ifdef LWS_HAVE_GETLOADAVG
2788 m = getloadavg(d, 3);
2789 for (n = 0; n < m; n++) {
2790 buf += snprintf(buf, end - buf,
2791 "\"l%d\":\"%.2f\",\n",
2797 buf += snprintf(buf, end - buf, "\"pt\":[\n ");
2798 for (n = 0; n < context->count_threads; n++) {
2799 pt = &context->pt[n];
2801 buf += snprintf(buf, end - buf, ",");
2802 buf += snprintf(buf, end - buf,
2804 " \"fds_count\":\"%d\",\n"
2805 " \"ah_pool_inuse\":\"%d\",\n"
2806 " \"ah_wait_list\":\"%d\"\n"
2809 pt->ah_count_in_use,
2810 pt->ah_wait_list_length);
2813 buf += snprintf(buf, end - buf, "], \"vhosts\":[\n ");
2819 buf += lws_json_dump_vhost(vh, buf, end - buf);
2823 vh = vh->vhost_next;
2826 buf += snprintf(buf, end - buf, "],\n\"listen_wsi\":\"%d\"",
2830 for (n = 0; n < context->count_threads; n++) {
2831 pt = &context->pt[n];
2832 pcgi = &pt->cgi_list;
2835 pcgi = &(*pcgi)->cgi_list;
2841 buf += snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
2844 buf += snprintf(buf, end - buf, "}\n ");