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)
34 #if defined(WIN32) || defined(_WIN32)
41 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
42 static void (*lwsl_emit)(int level, const char *line)
43 #ifndef LWS_PLAT_OPTEE
47 #ifndef LWS_PLAT_OPTEE
48 static const char * const log_level_names[] = {
66 lws_free_wsi(struct lws *wsi)
71 /* Protocol user data may be allocated either internally by lws
72 * or by specified the user.
73 * We should only free what we allocated. */
74 if (wsi->protocol && wsi->protocol->per_session_data_size &&
75 wsi->user_space && !wsi->user_space_externally_allocated)
76 lws_free(wsi->user_space);
78 lws_free_set_NULL(wsi->rxflow_buffer);
79 lws_free_set_NULL(wsi->trunc_alloc);
81 /* we may not have an ah, but may be on the waiting list... */
82 lwsl_info("ah det due to close\n");
83 lws_header_table_detach(wsi, 0);
85 wsi->context->count_wsi_allocated--;
86 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
87 wsi->context->count_wsi_allocated);
93 lws_remove_from_timeout_list(struct lws *wsi)
95 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
97 if (!wsi->timeout_list_prev) /* ie, not part of the list */
101 /* if we have a next guy, set his prev to our prev */
102 if (wsi->timeout_list)
103 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
104 /* set our prev guy to our next guy instead of us */
105 *wsi->timeout_list_prev = wsi->timeout_list;
107 /* we're out of the list, we should not point anywhere any more */
108 wsi->timeout_list_prev = NULL;
109 wsi->timeout_list = NULL;
114 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
116 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
119 if (secs == LWS_TO_KILL_SYNC) {
120 lws_remove_from_timeout_list(wsi);
121 lwsl_debug("synchronously killing %p\n", wsi);
122 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
130 if (reason && !wsi->timeout_list_prev) {
131 /* our next guy is current first guy */
132 wsi->timeout_list = pt->timeout_list;
133 /* if there is a next guy, set his prev ptr to our next ptr */
134 if (wsi->timeout_list)
135 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
136 /* our prev ptr is first ptr */
137 wsi->timeout_list_prev = &pt->timeout_list;
138 /* set the first guy to be us */
139 *wsi->timeout_list_prev = wsi;
142 lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
143 wsi->pending_timeout_limit = now + secs;
144 wsi->pending_timeout = reason;
149 lws_remove_from_timeout_list(wsi);
153 lws_remove_child_from_any_parent(struct lws *wsi)
161 /* detach ourselves from parent's child list */
162 pwsi = &wsi->parent->child_list;
165 lwsl_info("%s: detach %p from parent %p\n",
166 __func__, wsi, wsi->parent);
168 if (wsi->parent->protocol)
169 wsi->parent->protocol->callback(wsi,
170 LWS_CALLBACK_CHILD_CLOSING,
171 wsi->parent->user_space, wsi, 0);
173 *pwsi = wsi->sibling_list;
177 pwsi = &(*pwsi)->sibling_list;
180 lwsl_err("%s: failed to detach from parent\n", __func__);
186 lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)
188 // if (wsi->protocol == p)
190 const struct lws_protocols *vp = wsi->vhost->protocols, *vpo;
193 wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,
194 wsi->user_space, NULL, 0);
195 if (!wsi->user_space_externally_allocated)
196 lws_free_set_NULL(wsi->user_space);
198 lws_same_vh_protocol_remove(wsi);
204 if (lws_ensure_user_space(wsi))
207 if (p > vp && p < &vp[wsi->vhost->count_protocols])
208 lws_same_vh_protocol_insert(wsi, p - vp);
210 int n = wsi->vhost->count_protocols;
216 if (p->name && vp->name && !strcmp(p->name, vp->name)) {
218 lws_same_vh_protocol_insert(wsi, vp - vpo);
224 lwsl_err("%s: protocol %p is not in vhost %s protocols list\n",
225 __func__, p, wsi->vhost->name);
228 if (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,
229 wsi->user_space, NULL, 0))
236 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
238 struct lws_context_per_thread *pt;
239 struct lws *wsi1, *wsi2;
240 struct lws_context *context;
241 struct lws_tokens eff_buf;
244 lwsl_debug("%s: %p\n", __func__, wsi);
250 #if defined(LWS_WITH_ESP8266)
251 if (wsi->premature_rx)
252 lws_free(wsi->premature_rx);
254 if (wsi->pending_send_completion && !wsi->close_is_pending_send_completion) {
255 lwsl_notice("delaying close\n");
256 wsi->close_is_pending_send_completion = 1;
261 /* we're closing, losing some rx is OK */
262 lws_header_table_force_to_detachable_state(wsi);
264 context = wsi->context;
265 pt = &context->pt[(int)wsi->tsi];
266 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_CLOSE, 1);
268 /* if we have children, close them first */
269 if (wsi->child_list) {
270 wsi2 = wsi->child_list;
272 //lwsl_notice("%s: closing %p: close child %p\n",
273 // __func__, wsi, wsi2);
274 wsi1 = wsi2->sibling_list;
275 //lwsl_notice("%s: closing %p: next sibling %p\n",
276 // __func__, wsi2, wsi1);
278 /* stop it doing shutdown processing */
279 wsi2->socket_is_permanently_unusable = 1;
280 lws_close_free_wsi(wsi2, reason);
283 wsi->child_list = NULL;
286 if (wsi->mode == LWSCM_RAW_FILEDESC) {
287 lws_remove_child_from_any_parent(wsi);
288 remove_wsi_socket_from_fds(wsi);
289 wsi->protocol->callback(wsi,
290 LWS_CALLBACK_RAW_CLOSE_FILE,
291 wsi->user_space, NULL, 0);
296 if (wsi->mode == LWSCM_CGI) {
297 /* we are not a network connection, but a handler for CGI io */
298 if (wsi->parent && wsi->parent->cgi)
299 /* end the binding between us and master */
300 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
301 wsi->socket_is_permanently_unusable = 1;
303 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
304 goto just_kill_connection;
308 struct lws_cgi **pcgi = &pt->cgi_list;
309 /* remove us from the cgi list */
310 lwsl_debug("%s: remove cgi %p from list\n", __func__, wsi->cgi);
312 if (*pcgi == wsi->cgi) {
313 /* drop us from the pt cgi list */
314 *pcgi = (*pcgi)->cgi_list;
317 pcgi = &(*pcgi)->cgi_list;
319 if (wsi->cgi->headers_buf) {
320 lwsl_debug("close: freed cgi headers\n");
321 lws_free_set_NULL(wsi->cgi->headers_buf);
323 /* we have a cgi going, we must kill it */
324 wsi->cgi->being_closed = 1;
329 if (wsi->mode == LWSCM_RAW) {
330 wsi->protocol->callback(wsi,
331 LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0);
332 wsi->socket_is_permanently_unusable = 1;
333 goto just_kill_connection;
336 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
337 wsi->u.http.fop_fd != NULL) {
338 lws_vfs_file_close(&wsi->u.http.fop_fd);
339 wsi->vhost->protocols->callback(wsi,
340 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
341 wsi->told_user_closed = 1;
343 if (wsi->socket_is_permanently_unusable ||
344 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
345 wsi->state == LWSS_SHUTDOWN)
346 goto just_kill_connection;
348 wsi->state_pre_close = wsi->state;
350 switch (wsi->state_pre_close) {
351 case LWSS_DEAD_SOCKET:
354 /* we tried the polite way... */
355 case LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION:
356 case LWSS_AWAITING_CLOSE_ACK:
357 goto just_kill_connection;
359 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
360 if (wsi->trunc_len) {
361 lws_callback_on_writable(wsi);
364 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
365 goto just_kill_connection;
367 if (wsi->trunc_len) {
368 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
369 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
370 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
376 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
377 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
378 goto just_kill_connection;
380 if (wsi->mode == LWSCM_HTTP_SERVING) {
382 wsi->vhost->protocols->callback(wsi,
383 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
384 wsi->user_space, NULL, 0);
385 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
386 wsi->user_space, NULL, 0);
387 wsi->told_user_closed = 1;
389 if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
390 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
391 wsi->user_space, NULL, 0);
392 wsi->told_user_closed = 1;
396 * are his extensions okay with him closing? Eg he might be a mux
397 * parent and just his ch1 aspect is closing?
400 if (lws_ext_cb_active(wsi,
401 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
402 lwsl_ext("extension vetoed close\n");
407 * flush any tx pending from extensions, since we may send close packet
408 * if there are problems with send, just nuke the connection
413 eff_buf.token = NULL;
414 eff_buf.token_len = 0;
416 /* show every extension the new incoming data */
418 m = lws_ext_cb_active(wsi,
419 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
421 lwsl_ext("Extension reports fatal error\n");
422 goto just_kill_connection;
426 * at least one extension told us he has more
427 * to spill, so we will go around again after
431 /* assuming they left us something to send, send it */
433 if (eff_buf.token_len)
434 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
435 eff_buf.token_len) !=
437 lwsl_debug("close: ext spill failed\n");
438 goto just_kill_connection;
443 * signal we are closing, lws_write will
444 * add any necessary version-specific stuff. If the write fails,
445 * no worries we are closing anyway. If we didn't initiate this
446 * close, then our state has been changed to
447 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
449 * Likewise if it's a second call to close this connection after we
450 * sent the close indication to the peer already, we are in state
451 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
454 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
455 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
456 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
457 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
458 lwsl_debug("sending close indication...\n");
460 /* if no prepared close reason, use 1000 and no aux data */
461 if (!wsi->u.ws.close_in_ping_buffer_len) {
462 wsi->u.ws.close_in_ping_buffer_len = 2;
463 wsi->u.ws.ping_payload_buf[LWS_PRE] =
464 (reason >> 8) & 0xff;
465 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
469 #if defined (LWS_WITH_ESP8266)
470 wsi->close_is_pending_send_completion = 1;
473 lwsl_debug("waiting for chance to send close\n");
474 wsi->waiting_to_send_close_frame = 1;
475 wsi->state = LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION;
476 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 2);
477 lws_callback_on_writable(wsi);
482 just_kill_connection:
484 lws_remove_child_from_any_parent(wsi);
487 /* manage the vhost same protocol list entry */
489 if (wsi->same_vh_protocol_prev) { // we are on the vh list
491 // make guy who pointed to us, point to what our next was pointing to
492 *wsi->same_vh_protocol_prev = wsi->same_vh_protocol_next;
494 // if we had a next guy...
495 if (wsi->same_vh_protocol_next)
496 // have him point back to our prev
497 wsi->same_vh_protocol_next->same_vh_protocol_prev =
498 wsi->same_vh_protocol_prev;
504 * Testing with ab shows that we have to stage the socket close when
505 * the system is under stress... shutdown any further TX, change the
506 * state to one that won't emit anything more, and wait with a timeout
507 * for the POLLIN to show a zero-size rx before coming back and doing
510 if (wsi->mode != LWSCM_RAW &&
511 !(wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) &&
512 wsi->state != LWSS_SHUTDOWN &&
513 wsi->state != LWSS_CLIENT_UNCONNECTED &&
514 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
515 !wsi->socket_is_permanently_unusable) {
516 #ifdef LWS_OPENSSL_SUPPORT
517 if (lws_is_ssl(wsi) && wsi->ssl)
519 lwsl_info("%s: shutting down SSL connection: %p (ssl %p, sock %d, state %d)\n", __func__, wsi, wsi->ssl, (int)(long)wsi->desc.sockfd, wsi->state);
520 n = SSL_shutdown(wsi->ssl);
521 if (n == 1) /* If finished the SSL shutdown, then do socket shutdown, else need to retry SSL shutdown */
522 n = shutdown(wsi->desc.sockfd, SHUT_WR);
524 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
527 int shutdown_error = SSL_get_error(wsi->ssl, n);
528 lwsl_debug("SSL_shutdown returned %d, SSL_get_error: %d\n", n, shutdown_error);
529 if (shutdown_error == SSL_ERROR_WANT_READ) {
530 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
532 } else if (shutdown_error == SSL_ERROR_WANT_WRITE) {
533 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLOUT);
535 } else { // actual error occurred, just close the connection
536 n = shutdown(wsi->desc.sockfd, SHUT_WR);
543 lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, (int)(long)wsi->desc.sockfd, wsi->state);
544 n = shutdown(wsi->desc.sockfd, SHUT_WR);
547 lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
549 // This causes problems with disconnection when the events are half closing connection
550 // FD_READ | FD_CLOSE (33)
551 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP32)
552 /* libuv: no event available to guarantee completion */
553 if (!LWS_LIBUV_ENABLED(context)) {
555 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
556 wsi->state = LWSS_SHUTDOWN;
557 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
558 context->timeout_secs);
566 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
567 wsi, wsi->desc.sockfd);
569 #ifdef LWS_WITH_HTTP_PROXY
571 lws_rewrite_destroy(wsi->rw);
576 * we won't be servicing or receiving anything further from this guy
577 * delete socket from the internal poll list if still present
579 lws_ssl_remove_wsi_from_buffered_list(wsi);
581 lws_remove_from_timeout_list(wsi);
583 /* checking return redundant since we anyway close */
584 if (wsi->desc.sockfd != LWS_SOCK_INVALID)
585 remove_wsi_socket_from_fds(wsi);
587 lws_same_vh_protocol_remove(wsi);
589 #if defined(LWS_WITH_ESP8266)
590 espconn_disconnect(wsi->desc.sockfd);
593 wsi->state = LWSS_DEAD_SOCKET;
595 lws_free_set_NULL(wsi->rxflow_buffer);
596 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
597 wsi->mode == LWSCM_WS_SERVING ||
598 wsi->mode == LWSCM_WS_CLIENT) {
600 if (wsi->u.ws.rx_draining_ext) {
601 struct lws **w = &pt->rx_draining_ext_list;
603 wsi->u.ws.rx_draining_ext = 0;
604 /* remove us from context draining ext list */
607 *w = wsi->u.ws.rx_draining_ext_list;
610 w = &((*w)->u.ws.rx_draining_ext_list);
612 wsi->u.ws.rx_draining_ext_list = NULL;
615 if (wsi->u.ws.tx_draining_ext) {
616 struct lws **w = &pt->tx_draining_ext_list;
618 wsi->u.ws.tx_draining_ext = 0;
619 /* remove us from context draining ext list */
622 *w = wsi->u.ws.tx_draining_ext_list;
625 w = &((*w)->u.ws.tx_draining_ext_list);
627 wsi->u.ws.tx_draining_ext_list = NULL;
629 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
631 if (wsi->trunc_alloc)
632 /* not going to be completed... nuke it */
633 lws_free_set_NULL(wsi->trunc_alloc);
635 wsi->u.ws.ping_payload_len = 0;
636 wsi->u.ws.ping_pending_flag = 0;
639 /* tell the user it's all over for this guy */
641 if (wsi->mode != LWSCM_RAW && wsi->protocol && wsi->protocol->callback &&
642 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
643 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
644 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
645 (wsi->state_pre_close == LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION) ||
646 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
647 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
648 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
650 if (wsi->user_space) {
651 lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s\n", __func__, wsi, wsi->protocol->name);
652 wsi->protocol->callback(wsi,
653 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
654 wsi->user_space, NULL, 0);
656 lwsl_debug("calling back CLOSED\n");
657 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
658 wsi->user_space, NULL, 0);
659 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
660 lwsl_debug("calling back CLOSED_HTTP\n");
661 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
662 wsi->user_space, NULL, 0 );
663 } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
664 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
665 !wsi->already_did_cce) {
666 wsi->vhost->protocols[0].callback(wsi,
667 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
668 wsi->user_space, NULL, 0);
670 lwsl_debug("not calling back closed mode=%d state=%d\n",
671 wsi->mode, wsi->state_pre_close);
673 /* deallocate any active extension contexts */
675 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
676 lwsl_warn("extension destruction failed\n");
678 * inform all extensions in case they tracked this guy out of band
679 * even though not active on him specifically
681 if (lws_ext_cb_all_exts(context, wsi,
682 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
683 lwsl_warn("ext destroy wsi failed\n");
687 wsi->socket_is_permanently_unusable = 1;
690 if (!wsi->parent_carries_io)
691 if (LWS_LIBUV_ENABLED(context)) {
693 lwsl_debug("%s: stopping listner libuv poll\n", __func__);
694 uv_poll_stop(&wsi->w_read.uv_watcher);
696 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
697 /* libuv has to do his own close handle processing asynchronously */
698 lws_libuv_closehandle(wsi);
704 lws_close_free_wsi_final(wsi);
708 lws_close_free_wsi_final(struct lws *wsi)
712 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->desc.sockfd)) {
714 //lwsl_err("*** closing sockfd %d\n", wsi->desc.sockfd);
715 n = compatible_close(wsi->desc.sockfd);
717 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
720 compatible_close(wsi->desc.sockfd);
723 wsi->desc.sockfd = LWS_SOCK_INVALID;
726 /* outermost destroy notification for wsi (user_space still intact) */
727 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
728 wsi->user_space, NULL, 0);
732 for (n = 0; n < 6; n++) {
733 if (wsi->cgi->pipe_fds[n / 2][n & 1] == 0)
734 lwsl_err("ZERO FD IN CGI CLOSE");
736 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
737 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
747 LWS_VISIBLE LWS_EXTERN const char *
748 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
750 int n = 0, sl = strlen(name);
752 while (lws_hdr_copy_fragment(wsi, buf, len,
753 WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
755 if (!strncmp(buf, name, sl))
764 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
766 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
770 ipv6 = LWS_IPV6_ENABLED(vh);
774 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
778 #ifndef LWS_PLAT_OPTEE
781 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
782 int name_len, char *rip, int rip_len)
785 struct addrinfo ai, *res;
786 struct sockaddr_in addr4;
791 addr4.sin_family = AF_UNSPEC;
794 if (LWS_IPV6_ENABLED(vh)) {
795 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
796 lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
800 // Strip off the IPv4 to IPv6 header if one exists
801 if (strncmp(rip, "::ffff:", 7) == 0)
802 memmove(rip, rip + 7, strlen(rip) - 6);
804 getnameinfo((struct sockaddr *)ads,
805 sizeof(struct sockaddr_in6), name,
806 name_len, NULL, 0, 0);
812 struct addrinfo *result;
814 memset(&ai, 0, sizeof ai);
815 ai.ai_family = PF_UNSPEC;
816 ai.ai_socktype = SOCK_STREAM;
817 ai.ai_flags = AI_CANONNAME;
818 #if !defined(LWS_WITH_ESP32)
819 if (getnameinfo((struct sockaddr *)ads,
820 sizeof(struct sockaddr_in),
821 name, name_len, NULL, 0, 0))
827 if (getaddrinfo(name, NULL, &ai, &result))
831 while (addr4.sin_family == AF_UNSPEC && res) {
832 switch (res->ai_family) {
834 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
835 addr4.sin_family = AF_INET;
841 freeaddrinfo(result);
844 if (addr4.sin_family == AF_UNSPEC)
847 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
865 LWS_VISIBLE const char *
866 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
871 struct sockaddr_in6 sin6;
873 struct sockaddr_in sin4;
877 if (wsi->parent_carries_io)
881 if (LWS_IPV6_ENABLED(wsi->vhost)) {
895 if (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {
896 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
900 return lws_plat_inet_ntop(af, q, name, namelen);
902 #if defined(LWS_WITH_ESP8266)
903 return lws_plat_get_peer_simple(wsi, name, namelen);
912 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
913 int name_len, char *rip, int rip_len)
915 #ifndef LWS_PLAT_OPTEE
919 struct sockaddr_in6 sin6;
921 struct sockaddr_in sin4;
922 struct lws_context *context = wsi->context;
929 lws_latency_pre(context, wsi);
932 if (LWS_IPV6_ENABLED(wsi->vhost)) {
942 if (getpeername(fd, p, &len) < 0) {
943 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
947 ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
950 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
963 lws_context_user(struct lws_context *context)
965 return context->user_space;
968 LWS_VISIBLE struct lws_vhost *
969 lws_vhost_get(struct lws *wsi)
974 LWS_VISIBLE struct lws_vhost *
975 lws_get_vhost(struct lws *wsi)
980 LWS_VISIBLE const struct lws_protocols *
981 lws_protocol_get(struct lws *wsi)
983 return wsi->protocol;
986 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
987 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
991 for (n = 0; n < vh->count_protocols; n++)
992 if (!strcmp(name, vh->protocols[n].name))
993 return &vh->protocols[n];
999 lws_callback_all_protocol(struct lws_context *context,
1000 const struct lws_protocols *protocol, int reason)
1002 struct lws_context_per_thread *pt = &context->pt[0];
1003 unsigned int n, m = context->count_threads;
1007 for (n = 0; n < pt->fds_count; n++) {
1008 wsi = wsi_from_fd(context, pt->fds[n].fd);
1011 if (wsi->protocol == protocol)
1012 protocol->callback(wsi, reason, wsi->user_space,
1022 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
1023 const struct lws_protocols *protocol, int reason)
1025 struct lws_context *context = vh->context;
1026 struct lws_context_per_thread *pt = &context->pt[0];
1027 unsigned int n, m = context->count_threads;
1031 for (n = 0; n < pt->fds_count; n++) {
1032 wsi = wsi_from_fd(context, pt->fds[n].fd);
1035 if (wsi->vhost == vh && wsi->protocol == protocol)
1036 protocol->callback(wsi, reason, wsi->user_space,
1045 LWS_VISIBLE LWS_EXTERN int
1046 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
1050 for (n = 0; n < wsi->vhost->count_protocols; n++)
1051 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
1057 LWS_VISIBLE LWS_EXTERN void
1058 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)
1060 context->fops = fops;
1063 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1064 lws_vfs_tell(lws_fop_fd_t fop_fd)
1069 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1070 lws_vfs_get_length(lws_fop_fd_t fop_fd)
1075 LWS_VISIBLE LWS_EXTERN uint32_t
1076 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd)
1078 return fop_fd->mod_time;
1081 LWS_VISIBLE lws_fileofs_t
1082 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1085 lwsl_debug("%s: seeking to %ld, len %ld\n", __func__, (long)offset, (long)fop_fd->len);
1086 ofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);
1087 lwsl_debug("%s: result %ld, fop_fd pos %ld\n", __func__, (long)ofs, (long)fop_fd->pos);
1092 LWS_VISIBLE lws_fileofs_t
1093 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1095 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len + fop_fd->pos + offset);
1099 const struct lws_plat_file_ops *
1100 lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,
1103 const struct lws_plat_file_ops *pf;
1104 const char *p = vfs_path;
1109 /* no non-platform fops, just use that */
1115 * scan the vfs path looking for indications we are to be
1116 * handled by a specific fops
1124 /* the first one is always platform fops, so skip */
1128 while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {
1129 if (p >= vfs_path + pf->fi[n].len)
1130 if (!strncmp(p - (pf->fi[n].len - 1),
1132 pf->fi[n].len - 1)) {
1147 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
1148 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
1149 lws_fop_flags_t *flags)
1151 const char *vpath = "";
1152 const struct lws_plat_file_ops *selected = lws_vfs_select_fops(
1153 fops, vfs_path, &vpath);
1155 return selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);
1160 * lws_now_secs() - seconds since 1970-1-1
1163 LWS_VISIBLE LWS_EXTERN unsigned long
1168 gettimeofday(&tv, NULL);
1177 lws_get_socket_fd(struct lws *wsi)
1179 return wsi->desc.sockfd;
1186 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
1187 int ret, int completed)
1189 unsigned long long u;
1192 u = time_in_microseconds();
1195 wsi->latency_start = u;
1196 if (!wsi->action_start)
1197 wsi->action_start = u;
1201 if (wsi->action_start == wsi->latency_start)
1203 "Completion first try lat %lluus: %p: ret %d: %s\n",
1204 u - wsi->latency_start,
1205 (void *)wsi, ret, action);
1208 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1209 u - wsi->action_start,
1210 u - wsi->latency_start,
1211 (void *)wsi, ret, action);
1212 wsi->action_start = 0;
1214 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1215 u - wsi->latency_start, (void *)wsi, ret, action);
1217 if (u - wsi->latency_start > context->worst_latency) {
1218 context->worst_latency = u - wsi->latency_start;
1219 strcpy(context->worst_latency_info, buf);
1221 lwsl_latency("%s", buf);
1226 lws_rx_flow_control(struct lws *wsi, int enable)
1228 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1231 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1232 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1238 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1239 const struct lws_protocols *protocol)
1241 const struct lws_context_per_thread *pt = &context->pt[0];
1243 unsigned int n, m = context->count_threads;
1246 for (n = 0; n < pt->fds_count; n++) {
1247 wsi = wsi_from_fd(context, pt->fds[n].fd);
1250 if (wsi->protocol == protocol)
1251 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1257 LWS_VISIBLE extern const char *
1258 lws_canonical_hostname(struct lws_context *context)
1260 return (const char *)context->canonical_hostname;
1263 int user_callback_handle_rxflow(lws_callback_function callback_function,
1265 enum lws_callback_reasons reason, void *user,
1266 void *in, size_t len)
1270 n = callback_function(wsi, reason, user, in, len);
1272 n = _lws_rx_flow_control(wsi);
1277 #if defined(LWS_WITH_ESP8266)
1279 #define strchr ets_strchr
1283 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1285 #if !defined(LWS_WITH_ESP8266)
1287 char authstring[96];
1292 /* we have to deal with a possible redundant leading http:// */
1293 if (!strncmp(proxy, "http://", 7))
1296 p = strchr(proxy, '@');
1297 if (p) { /* auth is around */
1299 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1302 strncpy(authstring, proxy, p - proxy);
1303 // null termination not needed on input
1304 if (lws_b64_encode_string(authstring, (p - proxy),
1305 vhost->proxy_basic_auth_token,
1306 sizeof vhost->proxy_basic_auth_token) < 0)
1309 lwsl_info(" Proxy auth in use\n");
1313 vhost->proxy_basic_auth_token[0] = '\0';
1315 strncpy(vhost->http_proxy_address, proxy,
1316 sizeof(vhost->http_proxy_address) - 1);
1317 vhost->http_proxy_address[
1318 sizeof(vhost->http_proxy_address) - 1] = '\0';
1320 p = strchr(vhost->http_proxy_address, ':');
1321 if (!p && !vhost->http_proxy_port) {
1322 lwsl_err("http_proxy needs to be ads:port\n");
1328 vhost->http_proxy_port = atoi(p + 1);
1332 lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1333 vhost->http_proxy_port);
1338 lwsl_err("proxy auth too long\n");
1343 #if defined(LWS_WITH_SOCKS5)
1345 lws_set_socks(struct lws_vhost *vhost, const char *socks)
1347 #if !defined(LWS_WITH_ESP8266)
1348 char *p_at, *p_colon;
1355 vhost->socks_user[0] = '\0';
1356 vhost->socks_password[0] = '\0';
1358 p_at = strchr(socks, '@');
1359 if (p_at) { /* auth is around */
1360 if ((unsigned int)(p_at - socks) > (sizeof(user)
1361 + sizeof(password) - 2)) {
1362 lwsl_err("Socks auth too long\n");
1366 p_colon = strchr(socks, ':');
1368 if ((unsigned int)(p_colon - socks) > (sizeof(user)
1370 lwsl_err("Socks user too long\n");
1373 if ((unsigned int)(p_at - p_colon) > (sizeof(password)
1375 lwsl_err("Socks password too long\n");
1379 strncpy(vhost->socks_user, socks, p_colon - socks);
1380 strncpy(vhost->socks_password, p_colon + 1,
1381 p_at - (p_colon + 1));
1383 lwsl_info(" Socks auth, user: %s, password: %s\n",
1384 vhost->socks_user, vhost->socks_password );
1389 strncpy(vhost->socks_proxy_address, socks,
1390 sizeof(vhost->socks_proxy_address) - 1);
1391 vhost->socks_proxy_address[sizeof(vhost->socks_proxy_address) - 1]
1394 p_colon = strchr(vhost->socks_proxy_address, ':');
1395 if (!p_colon && !vhost->socks_proxy_port) {
1396 lwsl_err("socks_proxy needs to be address:port\n");
1401 vhost->socks_proxy_port = atoi(p_colon + 1);
1405 lwsl_info(" Socks %s:%u\n", vhost->socks_proxy_address,
1406 vhost->socks_proxy_port);
1416 LWS_VISIBLE const struct lws_protocols *
1417 lws_get_protocol(struct lws *wsi)
1419 return wsi->protocol;
1423 lws_is_final_fragment(struct lws *wsi)
1425 lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1426 wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1427 (long)wsi->u.ws.rx_draining_ext);
1428 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1432 lws_is_first_fragment(struct lws *wsi)
1434 return wsi->u.ws.first_fragment;
1437 LWS_VISIBLE unsigned char
1438 lws_get_reserved_bits(struct lws *wsi)
1440 return wsi->u.ws.rsv;
1444 lws_ensure_user_space(struct lws *wsi)
1446 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1450 /* allocate the per-connection user memory (if any) */
1452 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1453 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1454 if (wsi->user_space == NULL) {
1455 lwsl_err("Out of memory for conn user space\n");
1459 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1460 __func__, wsi, (long)wsi->protocol->per_session_data_size,
1466 lwsl_timestamp(int level, char *p, int len)
1468 #ifndef LWS_PLAT_OPTEE
1469 time_t o_now = time(NULL);
1470 unsigned long long now;
1471 struct tm *ptm = NULL;
1479 ptm = localtime(&o_now);
1481 if (localtime_r(&o_now, &tm))
1486 for (n = 0; n < LLL_COUNT; n++) {
1487 if (level != (1 << n))
1489 now = time_in_microseconds() / 100;
1491 n = lws_snprintf(p, len,
1492 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1493 ptm->tm_year + 1900,
1499 (int)(now % 10000), log_level_names[n]);
1501 n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1502 (unsigned long long) now / 10000,
1503 (int)(now % 10000), log_level_names[n]);
1510 #ifndef LWS_PLAT_OPTEE
1511 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1513 #if !defined(LWS_WITH_ESP8266)
1516 lwsl_timestamp(level, buf, sizeof(buf));
1517 fprintf(stderr, "%s%s", buf, line);
1522 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1524 #if defined(LWS_WITH_ESP8266)
1531 if (!(log_level & filter))
1534 n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1536 #if defined(LWS_WITH_ESP8266)
1537 buf[sizeof(buf) - 1] = '\0';
1539 /* vnsprintf returns what it would have written, even if truncated */
1540 if (n > sizeof(buf) - 1)
1541 n = sizeof(buf) - 1;
1546 lwsl_emit(filter, buf);
1549 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1553 va_start(ap, format);
1554 _lws_logv(filter, format, ap);
1558 LWS_VISIBLE void lws_set_log_level(int level,
1559 void (*func)(int level, const char *line))
1566 LWS_VISIBLE int lwsl_visible(int level)
1568 return log_level & level;
1572 lws_is_ssl(struct lws *wsi)
1574 #ifdef LWS_OPENSSL_SUPPORT
1575 return wsi->use_ssl;
1582 #ifdef LWS_OPENSSL_SUPPORT
1584 lws_get_ssl(struct lws *wsi)
1591 lws_partial_buffered(struct lws *wsi)
1593 return !!wsi->trunc_len;
1596 void lws_set_protocol_write_pending(struct lws *wsi,
1597 enum lws_pending_protocol_send pend)
1599 lwsl_info("setting pps %d\n", pend);
1602 lwsl_err("pps overwrite\n");
1604 lws_rx_flow_control(wsi, 0);
1605 lws_callback_on_writable(wsi);
1609 lws_get_peer_write_allowance(struct lws *wsi)
1611 #ifdef LWS_USE_HTTP2
1612 /* only if we are using HTTP2 on this connection */
1613 if (wsi->mode != LWSCM_HTTP2_SERVING)
1615 /* user is only interested in how much he can send, or that he can't */
1616 if (wsi->u.http2.tx_credit <= 0)
1619 return wsi->u.http2.tx_credit;
1627 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1629 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1630 memset(&wsi->u, 0, sizeof(wsi->u));
1634 LWS_VISIBLE struct lws_plat_file_ops *
1635 lws_get_fops(struct lws_context *context)
1637 return (struct lws_plat_file_ops *)context->fops;
1640 LWS_VISIBLE LWS_EXTERN struct lws_context *
1641 lws_get_context(const struct lws *wsi)
1643 return wsi->context;
1646 LWS_VISIBLE LWS_EXTERN int
1647 lws_get_count_threads(struct lws_context *context)
1649 return context->count_threads;
1652 LWS_VISIBLE LWS_EXTERN void *
1653 lws_wsi_user(struct lws *wsi)
1655 return wsi->user_space;
1658 LWS_VISIBLE LWS_EXTERN void
1659 lws_set_wsi_user(struct lws *wsi, void *data)
1661 if (wsi->user_space_externally_allocated)
1662 wsi->user_space = data;
1664 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1668 LWS_VISIBLE LWS_EXTERN struct lws *
1669 lws_get_parent(const struct lws *wsi)
1674 LWS_VISIBLE LWS_EXTERN struct lws *
1675 lws_get_child(const struct lws *wsi)
1677 return wsi->child_list;
1680 LWS_VISIBLE LWS_EXTERN void
1681 lws_set_parent_carries_io(struct lws *wsi)
1683 wsi->parent_carries_io = 1;
1686 LWS_VISIBLE LWS_EXTERN void *
1687 lws_get_opaque_parent_data(const struct lws *wsi)
1689 return wsi->opaque_parent_data;
1692 LWS_VISIBLE LWS_EXTERN void
1693 lws_set_opaque_parent_data(struct lws *wsi, void *data)
1695 wsi->opaque_parent_data = data;
1698 LWS_VISIBLE LWS_EXTERN int
1699 lws_get_child_pending_on_writable(const struct lws *wsi)
1701 return wsi->parent_pending_cb_on_writable;
1704 LWS_VISIBLE LWS_EXTERN void
1705 lws_clear_child_pending_on_writable(struct lws *wsi)
1707 wsi->parent_pending_cb_on_writable = 0;
1710 LWS_VISIBLE LWS_EXTERN int
1711 lws_get_close_length(struct lws *wsi)
1713 return wsi->u.ws.close_in_ping_buffer_len;
1716 LWS_VISIBLE LWS_EXTERN unsigned char *
1717 lws_get_close_payload(struct lws *wsi)
1719 return &wsi->u.ws.ping_payload_buf[LWS_PRE];
1722 LWS_VISIBLE LWS_EXTERN void
1723 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1724 unsigned char *buf, size_t len)
1726 unsigned char *p, *start;
1727 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1729 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1731 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1733 *p++ = (((int)status) >> 8) & 0xff;
1734 *p++ = ((int)status) & 0xff;
1737 while (len-- && p < start + budget)
1740 wsi->u.ws.close_in_ping_buffer_len = p - start;
1744 _lws_rx_flow_control(struct lws *wsi)
1746 struct lws *wsic = wsi->child_list;
1748 /* if he has children, do those if they were changed */
1750 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1751 _lws_rx_flow_control(wsic);
1753 wsic = wsic->sibling_list;
1756 /* there is no pending change */
1757 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1758 // lwsl_debug("%s: no pending change\n", __func__);
1762 /* stuff is still buffered, not ready to really accept new input */
1763 if (wsi->rxflow_buffer) {
1764 /* get ourselves called back to deal with stashed buffer */
1765 lws_callback_on_writable(wsi);
1769 /* pending is cleared, we can change rxflow state */
1771 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1773 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1774 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1776 /* adjust the pollfd for this wsi */
1778 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1779 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1780 lwsl_info("%s: fail\n", __func__);
1784 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1791 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1793 static const unsigned char e0f4[] = {
1794 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1795 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1796 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1797 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1798 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1799 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1800 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1801 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1802 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1803 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1804 0x80 | ((4 - 1) << 2) | 1, /* ea */
1805 0x80 | ((4 - 1) << 2) | 1, /* eb */
1806 0x80 | ((4 - 1) << 2) | 1, /* ec */
1807 0x80 | ((2 - 1) << 2) | 1, /* ed */
1808 0x80 | ((4 - 1) << 2) | 1, /* ee */
1809 0x80 | ((4 - 1) << 2) | 1, /* ef */
1810 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1811 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1812 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1813 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1814 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1817 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1818 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1820 unsigned char s = *state;
1823 unsigned char c = *buf++;
1827 if (c < 0xc2 || c > 0xf4)
1830 s = 0x80 | ((4 - 1) << 2);
1835 if (c < (s & 0xf0) ||
1836 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1838 s = e0f4[21 + (s & 3)];
1847 LWS_VISIBLE LWS_EXTERN int
1848 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1852 static const char *slash = "/";
1854 /* cut up the location into address, port and path */
1856 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1867 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1869 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1875 while (*p && *p != ']')
1882 while (*p && *p != ':' && *p != '/')
1888 while (*p && *p != '/')
1901 #ifdef LWS_NO_EXTENSIONS
1903 /* we need to provide dummy callbacks for internal exts
1904 * so user code runs when faced with a lib compiled with
1905 * extensions disabled.
1909 lws_extension_callback_pm_deflate(struct lws_context *context,
1910 const struct lws_extension *ext,
1912 enum lws_extension_callback_reasons reason,
1913 void *user, void *in, size_t len)
1928 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1932 #ifdef LWS_USE_UNIX_SOCK
1933 struct sockaddr_un serv_unix;
1936 struct sockaddr_in6 serv_addr6;
1938 struct sockaddr_in serv_addr4;
1939 #ifndef LWS_PLAT_OPTEE
1940 socklen_t len = sizeof(struct sockaddr_storage);
1943 struct sockaddr_storage sin;
1946 #ifdef LWS_USE_UNIX_SOCK
1947 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1948 v = (struct sockaddr *)&serv_unix;
1949 n = sizeof(struct sockaddr_un);
1950 bzero((char *) &serv_unix, sizeof(serv_unix));
1951 serv_unix.sun_family = AF_UNIX;
1952 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1953 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1957 strcpy(serv_unix.sun_path, iface);
1958 if (serv_unix.sun_path[0] == '@')
1959 serv_unix.sun_path[0] = '\0';
1963 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1964 if (LWS_IPV6_ENABLED(vhost)) {
1965 v = (struct sockaddr *)&serv_addr6;
1966 n = sizeof(struct sockaddr_in6);
1967 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1969 if (interface_to_sa(vhost, iface,
1970 (struct sockaddr_in *)v, n) < 0) {
1971 lwsl_err("Unable to find interface %s\n", iface);
1974 serv_addr6.sin6_scope_id = lws_get_addr_scope(iface);
1977 serv_addr6.sin6_family = AF_INET6;
1978 serv_addr6.sin6_port = htons(port);
1982 v = (struct sockaddr *)&serv_addr4;
1983 n = sizeof(serv_addr4);
1984 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1985 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1986 serv_addr4.sin_family = AF_INET;
1987 #if !defined(LWS_WITH_ESP32)
1990 interface_to_sa(vhost, iface,
1991 (struct sockaddr_in *)v, n) < 0) {
1992 lwsl_err("Unable to find interface %s\n", iface);
1996 serv_addr4.sin_port = htons(port);
1999 n = bind(sockfd, v, n);
2000 #ifdef LWS_USE_UNIX_SOCK
2001 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
2002 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
2003 sockfd, iface, n, LWS_ERRNO);
2008 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
2009 sockfd, port, n, LWS_ERRNO);
2013 #ifndef LWS_PLAT_OPTEE
2014 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
2015 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
2018 #if defined(LWS_USE_IPV6)
2019 port = (sin.ss_family == AF_INET6) ?
2020 ntohs(((struct sockaddr_in6 *) &sin)->sin6_port) :
2021 ntohs(((struct sockaddr_in *) &sin)->sin_port);
2023 port = ntohs(((struct sockaddr_in *) &sin)->sin_port);
2030 #if defined(LWS_USE_IPV6)
2031 LWS_EXTERN unsigned long
2032 lws_get_addr_scope(const char *ipaddr)
2034 unsigned long scope = 0;
2037 struct ifaddrs *addrs, *addr;
2038 char ip[NI_MAXHOST];
2042 for (addr = addrs; addr; addr = addr->ifa_next) {
2043 if (!addr->ifa_addr ||
2044 addr->ifa_addr->sa_family != AF_INET6)
2047 getnameinfo(addr->ifa_addr,
2048 sizeof(struct sockaddr_in6),
2050 NULL, 0, NI_NUMERICHOST);
2054 if (ip[i++] == '%') {
2059 if (!strcmp(ip, ipaddr)) {
2060 scope = if_nametoindex(addr->ifa_name);
2066 PIP_ADAPTER_ADDRESSES adapter, addrs = NULL;
2067 PIP_ADAPTER_UNICAST_ADDRESS addr;
2070 struct sockaddr_in6 *sockaddr;
2071 char ip[NI_MAXHOST];
2075 for (i = 0; i < 5; i++)
2077 ret = GetAdaptersAddresses(AF_INET6, GAA_FLAG_INCLUDE_PREFIX,
2078 NULL, addrs, &size);
2079 if ((ret == NO_ERROR) || (ret == ERROR_NO_DATA)) {
2081 } else if (ret == ERROR_BUFFER_OVERFLOW)
2085 addrs = (IP_ADAPTER_ADDRESSES *) malloc(size);
2093 lwsl_err("Failed to get IPv6 address table (%d)", ret);
2098 if ((ret == NO_ERROR) && (addrs))
2101 while ((adapter) && (!found))
2103 addr = adapter->FirstUnicastAddress;
2104 while ((addr) && (!found))
2106 if (addr->Address.lpSockaddr->sa_family == AF_INET6)
2108 sockaddr = (struct sockaddr_in6 *) (addr->Address.lpSockaddr);
2110 lws_plat_inet_ntop(sockaddr->sin6_family, &sockaddr->sin6_addr,
2113 if (!strcmp(ip, ipaddr)) {
2114 scope = sockaddr->sin6_scope_id;
2121 adapter = adapter->Next;
2133 lws_restart_ws_ping_pong_timer(struct lws *wsi)
2135 if (!wsi->context->ws_ping_pong_interval)
2137 if (wsi->state != LWSS_ESTABLISHED)
2140 wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
2141 wsi->context->ws_ping_pong_interval;
2144 static const char *hex = "0123456789ABCDEF";
2146 LWS_VISIBLE LWS_EXTERN const char *
2147 lws_sql_purify(char *escaped, const char *string, int len)
2149 const char *p = string;
2152 while (*p && len-- > 2) {
2166 LWS_VISIBLE LWS_EXTERN const char *
2167 lws_json_purify(char *escaped, const char *string, int len)
2169 const char *p = string;
2177 while (*p && len-- > 6) {
2178 if (*p == '\"' || *p == '\\' || *p < 0x20) {
2183 *q++ = hex[((*p) >> 4) & 15];
2184 *q++ = hex[(*p) & 15];
2195 LWS_VISIBLE LWS_EXTERN const char *
2196 lws_urlencode(char *escaped, const char *string, int len)
2198 const char *p = string;
2201 while (*p && len-- > 3) {
2207 if ((*p >= '0' && *p <= '9') ||
2208 (*p >= 'A' && *p <= 'Z') ||
2209 (*p >= 'a' && *p <= 'z')) {
2214 *q++ = hex[(*p >> 4) & 0xf];
2215 *q++ = hex[*p & 0xf];
2225 LWS_VISIBLE LWS_EXTERN int
2226 lws_urldecode(char *string, const char *escaped, int len)
2231 while (*escaped && len) {
2234 if (*escaped == '%') {
2239 if (*escaped == '+') {
2245 *string++ = *escaped++;
2249 n = char_to_hex(*escaped);
2258 n = char_to_hex(*escaped);
2262 *string++ = sum | n;
2274 LWS_VISIBLE LWS_EXTERN int
2275 lws_finalize_startup(struct lws_context *context)
2277 struct lws_context_creation_info info;
2279 info.uid = context->uid;
2280 info.gid = context->gid;
2282 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
2283 memcpy(info.caps, context->caps, sizeof(info.caps));
2284 info.count_caps = context->count_caps;
2287 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2288 lws_plat_drop_app_privileges(&info);
2294 lws_snprintf(char *str, size_t size, const char *format, ...)
2302 va_start(ap, format);
2303 n = vsnprintf(str, size, format, ap);
2313 LWS_VISIBLE LWS_EXTERN int
2314 lws_is_cgi(struct lws *wsi) {
2325 urlencode(const char *in, int inlen, char *out, int outlen)
2327 char *start = out, *end = out + outlen;
2329 while (inlen-- && out < end - 4) {
2330 if ((*in >= 'A' && *in <= 'Z') ||
2331 (*in >= 'a' && *in <= 'z') ||
2332 (*in >= '0' && *in <= '9') ||
2346 *out++ = hex[(*in) >> 4];
2347 *out++ = hex[(*in++) & 15];
2358 lws_create_basic_wsi(struct lws_context *context, int tsi)
2360 struct lws *new_wsi;
2362 if ((unsigned int)context->pt[tsi].fds_count ==
2363 context->fd_limit_per_thread - 1) {
2364 lwsl_err("no space for new conn\n");
2368 new_wsi = lws_zalloc(sizeof(struct lws));
2369 if (new_wsi == NULL) {
2370 lwsl_err("Out of memory for new connection\n");
2375 new_wsi->context = context;
2376 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2377 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2379 /* initialize the instance struct */
2381 new_wsi->state = LWSS_CGI;
2382 new_wsi->mode = LWSCM_CGI;
2383 new_wsi->hdr_parsing_completed = 0;
2384 new_wsi->position_in_fds_table = -1;
2387 * these can only be set once the protocol is known
2388 * we set an unestablished connection's protocol pointer
2389 * to the start of the defauly vhost supported list, so it can look
2390 * for matching ones during the handshake
2392 new_wsi->protocol = context->vhost_list->protocols;
2393 new_wsi->user_space = NULL;
2394 new_wsi->ietf_spec_revision = 0;
2395 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2396 context->count_wsi_allocated++;
2401 LWS_VISIBLE LWS_EXTERN int
2402 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2403 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2405 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2406 char *env_array[30], cgi_path[400], e[1024], *p = e,
2407 *end = p + sizeof(e) - 1, tok[256], *t;
2408 struct lws_cgi *cgi;
2409 int n, m, i, uritok = -1;
2412 * give the master wsi a cgi struct
2415 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2417 lwsl_err("%s: OOM\n", __func__);
2421 wsi->cgi->response_code = HTTP_STATUS_OK;
2424 cgi->wsi = wsi; /* set cgi's owning wsi */
2426 /* create pipes for [stdin|stdout] and [stderr] */
2428 for (n = 0; n < 3; n++)
2429 if (pipe(cgi->pipe_fds[n]) == -1)
2432 /* create cgi wsis for each stdin/out/err fd */
2434 for (n = 0; n < 3; n++) {
2435 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2436 if (!cgi->stdwsi[n])
2438 cgi->stdwsi[n]->cgi_channel = n;
2439 cgi->stdwsi[n]->vhost = wsi->vhost;
2441 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2442 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2444 /* read side is 0, stdin we want the write side, others read */
2445 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2446 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2447 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2452 for (n = 0; n < 3; n++) {
2453 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2454 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2456 cgi->stdwsi[n]->parent = wsi;
2457 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2458 wsi->child_list = cgi->stdwsi[n];
2461 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2462 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2463 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2465 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2466 cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2467 cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2468 cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2470 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2472 /* the cgi stdout is always sending us http1.x header data first */
2473 wsi->hdr_state = LCHS_HEADER;
2475 /* add us to the pt list of active cgis */
2476 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2477 cgi->cgi_list = pt->cgi_list;
2480 /* prepare his CGI env */
2484 if (lws_is_ssl(wsi))
2485 env_array[n++] = "HTTPS=ON";
2486 if (wsi->u.hdr.ah) {
2487 static const unsigned char meths[] = {
2490 WSI_TOKEN_OPTIONS_URI,
2492 WSI_TOKEN_PATCH_URI,
2493 WSI_TOKEN_DELETE_URI,
2495 static const char * const meth_names[] = {
2496 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2499 for (m = 0; m < ARRAY_SIZE(meths); m++)
2500 if (lws_hdr_total_length(wsi, meths[m]) >=
2501 script_uri_path_len) {
2509 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2510 lws_hdr_simple_ptr(wsi, uritok));
2511 cgi_path[sizeof(cgi_path) - 1] = '\0';
2512 env_array[n++] = cgi_path;
2515 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2520 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2521 /* dump the individual URI Arg parameters */
2524 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2525 WSI_TOKEN_HTTP_URI_ARGS, m);
2529 while (*t && *t != '=' && p < end - 4)
2533 i = urlencode(t, i- (t - tok), p, end - p);
2545 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2546 lws_hdr_simple_ptr(wsi, uritok) +
2547 script_uri_path_len);
2550 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2552 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2553 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2556 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2558 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2559 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2562 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2564 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2565 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2568 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2570 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2571 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2574 if (uritok == WSI_TOKEN_POST_URI) {
2575 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2577 p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2578 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2581 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2583 p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2584 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2589 p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2593 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2595 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2598 mp_cgienv = mp_cgienv->next;
2601 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2602 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2603 env_array[n] = NULL;
2606 for (m = 0; m < n; m++)
2607 lwsl_err(" %s\n", env_array[m]);
2611 * Actually having made the env, as a cgi we don't need the ah
2614 if (lws_header_table_is_in_detachable_state(wsi))
2615 lws_header_table_detach(wsi, 0);
2617 /* we are ready with the redirection pipes... run the thing */
2618 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2624 lwsl_err("fork failed, errno %d", errno);
2628 #if defined(__linux__)
2629 prctl(PR_SET_PDEATHSIG, SIGTERM);
2631 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2634 /* we are the parent process */
2635 wsi->context->count_cgi_spawned++;
2636 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2640 /* somewhere we can at least read things and enter it */
2642 lwsl_notice("%s: Failed to chdir\n", __func__);
2644 /* We are the forked process, redirect and kill inherited things.
2646 * Because of vfork(), we cannot do anything that changes pages in
2647 * the parent environment. Stuff that changes kernel state for the
2648 * process is OK. Stuff that happens after the execvpe() is OK.
2651 for (n = 0; n < 3; n++) {
2652 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2653 lwsl_err("%s: stdin dup2 failed\n", __func__);
2656 close(cgi->pipe_fds[n][!(n == 0)]);
2659 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2660 for (m = 0; m < n; m++) {
2661 p = strchr(env_array[m], '=');
2663 setenv(env_array[m], p, 1);
2665 execvp(exec_array[0], (char * const *)&exec_array[0]);
2667 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2673 /* drop us from the pt cgi list */
2674 pt->cgi_list = cgi->cgi_list;
2677 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2679 for (n = 0; n < 3; n++)
2680 if (wsi->cgi->stdwsi[n])
2681 lws_free_wsi(cgi->stdwsi[n]);
2684 for (n = 0; n < 3; n++) {
2685 if (cgi->pipe_fds[n][0])
2686 close(cgi->pipe_fds[n][0]);
2687 if (cgi->pipe_fds[n][1])
2688 close(cgi->pipe_fds[n][1]);
2691 lws_free_set_NULL(wsi->cgi);
2693 lwsl_err("%s: failed\n", __func__);
2698 /* we have to parse out these headers in the CGI output */
2700 static const char * const significant_hdr[SIGNIFICANT_HDR_COUNT] = {
2704 "transfer-encoding: chunked",
2707 LWS_VISIBLE LWS_EXTERN int
2708 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2711 unsigned char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2712 *end = &buf[sizeof(buf) - 1 - LWS_PRE];
2718 while (wsi->hdr_state != LHCS_PAYLOAD) {
2719 /* we have to separate header / finalize and
2720 * payload chunks, since they need to be
2721 * handled separately
2724 switch (wsi->hdr_state) {
2727 lwsl_info("LHCS_RESPONSE: issuing response %d\n",
2728 wsi->cgi->response_code);
2729 if (lws_add_http_header_status(wsi, wsi->cgi->response_code, &p, end))
2731 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2732 (unsigned char *)"close", 5, &p, end))
2734 n = lws_write(wsi, start, p - start,
2735 LWS_WRITE_HTTP_HEADERS);
2737 /* finalize cached headers before dumping them */
2738 if (lws_finalize_http_header(wsi,
2739 (unsigned char **)&wsi->cgi->headers_pos,
2740 (unsigned char *)wsi->cgi->headers_end)) {
2742 lwsl_notice("finalize failed\n");
2746 wsi->hdr_state = LHCS_DUMP_HEADERS;
2747 wsi->reason_bf |= 8;
2748 lws_callback_on_writable(wsi);
2749 /* back to the loop for writeability again */
2752 case LHCS_DUMP_HEADERS:
2754 n = wsi->cgi->headers_pos - wsi->cgi->headers_dumped;
2758 lwsl_debug("LHCS_DUMP_HEADERS: %d\n", n);
2760 m = lws_write(wsi, (unsigned char *)wsi->cgi->headers_dumped,
2761 n, LWS_WRITE_HTTP_HEADERS);
2763 lwsl_debug("%s: write says %d\n", __func__, m);
2766 wsi->cgi->headers_dumped += n;
2767 if (wsi->cgi->headers_dumped == wsi->cgi->headers_pos) {
2768 wsi->hdr_state = LHCS_PAYLOAD;
2769 lws_free_set_NULL(wsi->cgi->headers_buf);
2770 lwsl_debug("freed cgi headers\n");
2772 wsi->reason_bf |= 8;
2773 lws_callback_on_writable(wsi);
2776 /* writeability becomes uncertain now we wrote
2777 * something, we must return to the event loop
2782 if (!wsi->cgi->headers_buf) {
2783 /* if we don't already have a headers buf, cook one up */
2785 wsi->cgi->headers_buf = malloc(n);
2786 if (!wsi->cgi->headers_buf) {
2791 lwsl_debug("allocated cgi hdrs\n");
2792 wsi->cgi->headers_pos = wsi->cgi->headers_buf;
2793 wsi->cgi->headers_dumped = wsi->cgi->headers_pos;
2794 wsi->cgi->headers_end = wsi->cgi->headers_buf + n - 1;
2796 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2797 wsi->cgi->match[n] = 0;
2802 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2804 if (errno != EAGAIN) {
2805 lwsl_debug("%s: read says %d\n", __func__, n);
2811 if (wsi->cgi->headers_pos >= wsi->cgi->headers_end - 4) {
2812 lwsl_notice("CGI headers larger than buffer size\n");
2818 lwsl_debug("-- 0x%02X %c %d %d\n", (unsigned char)c, c, wsi->cgi->match[1], wsi->hdr_state);
2821 switch (wsi->hdr_state) {
2824 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2825 /* significant headers with numeric decimal payloads */
2826 if (!significant_hdr[n][wsi->cgi->match[n]] &&
2827 (c >= '0' && c <= '9') &&
2828 wsi->cgi->lp < sizeof(wsi->cgi->l) - 1) {
2829 wsi->cgi->l[wsi->cgi->lp++] = c;
2830 wsi->cgi->l[wsi->cgi->lp] = '\0';
2832 case SIGNIFICANT_HDR_CONTENT_LENGTH:
2833 wsi->cgi->content_length = atoll(wsi->cgi->l);
2835 case SIGNIFICANT_HDR_STATUS:
2836 wsi->cgi->response_code = atol(wsi->cgi->l);
2837 lwsl_debug("Status set to %d\n", wsi->cgi->response_code);
2843 /* hits up to the NUL are sticky until next hdr */
2844 if (significant_hdr[n][wsi->cgi->match[n]]) {
2845 if (tolower(c) == significant_hdr[n][wsi->cgi->match[n]])
2846 wsi->cgi->match[n]++;
2848 wsi->cgi->match[n] = 0;
2852 /* some cgi only send us \x0a for EOL */
2854 wsi->hdr_state = LCHS_SINGLE_0A;
2855 *wsi->cgi->headers_pos++ = '\x0d';
2857 *wsi->cgi->headers_pos++ = c;
2859 wsi->hdr_state = LCHS_LF1;
2861 if (wsi->hdr_state != LCHS_HEADER &&
2862 !significant_hdr[SIGNIFICANT_HDR_TRANSFER_ENCODING][wsi->cgi->match[SIGNIFICANT_HDR_TRANSFER_ENCODING]]) {
2863 lwsl_debug("cgi produced chunked\n");
2864 wsi->cgi->explicitly_chunked = 1;
2867 /* presence of Location: mandates 302 retcode */
2868 if (wsi->hdr_state != LCHS_HEADER &&
2869 !significant_hdr[SIGNIFICANT_HDR_LOCATION][wsi->cgi->match[SIGNIFICANT_HDR_LOCATION]]) {
2870 lwsl_debug("CGI: Location hdr seen\n");
2871 wsi->cgi->response_code = 302;
2876 *wsi->cgi->headers_pos++ = c;
2878 wsi->hdr_state = LCHS_CR2;
2881 /* we got \r[^\n]... it's unreasonable */
2882 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2888 wsi->hdr_state = LCHS_LF2;
2891 wsi->hdr_state = LCHS_HEADER;
2892 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2893 wsi->cgi->match[n] = 0;
2898 case LCHS_SINGLE_0A:
2901 lwsl_debug("Content-Length: %lld\n", (unsigned long long)wsi->cgi->content_length);
2902 wsi->hdr_state = LHCS_RESPONSE;
2903 /* drop the \0xa ... finalize will add it if needed */
2907 /* we got \r\n\r[^\n]... it's unreasonable */
2909 /* we got \x0anext header, it's reasonable */
2910 *wsi->cgi->headers_pos++ = c;
2911 wsi->hdr_state = LCHS_HEADER;
2912 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2913 wsi->cgi->match[n] = 0;
2921 /* ran out of input, ended the headers, or filled up the headers buf */
2922 if (!n || wsi->hdr_state == LHCS_PAYLOAD)
2926 /* payload processing */
2928 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2929 start, sizeof(buf) - LWS_PRE);
2931 if (n < 0 && errno != EAGAIN) {
2932 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2936 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2937 //lwsl_notice("write %d\n", m);
2939 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2942 wsi->cgi->content_length_seen += m;
2948 LWS_VISIBLE LWS_EXTERN int
2949 lws_cgi_kill(struct lws *wsi)
2951 struct lws_cgi_args args;
2954 lwsl_debug("%s: %p\n", __func__, wsi);
2959 if (wsi->cgi->pid > 0) {
2960 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2962 lwsl_debug("%s: PID %d reaped\n", __func__,
2966 /* kill the process group */
2967 n = kill(-wsi->cgi->pid, SIGTERM);
2968 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2969 wsi->cgi->pid, n, errno);
2972 * hum seen errno=3 when process is listed in ps,
2973 * it seems we don't always retain process grouping
2975 * Direct these fallback attempt to the exact child
2977 n = kill(wsi->cgi->pid, SIGTERM);
2979 n = kill(wsi->cgi->pid, SIGPIPE);
2981 n = kill(wsi->cgi->pid, SIGKILL);
2983 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2984 __func__, wsi->cgi->pid, errno);
2988 /* He could be unkillable because he's a zombie */
2991 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2993 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2995 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2997 lwsl_debug("%s: reaped PID %d\n", __func__, n);
3003 args.stdwsi = &wsi->cgi->stdwsi[0];
3005 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
3006 wsi->protocol->callback,
3007 wsi, LWS_CALLBACK_CGI_TERMINATED,
3009 (void *)&args, 0)) {
3011 if (!wsi->cgi->being_closed)
3012 lws_close_free_wsi(wsi, 0);
3019 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
3021 struct lws_cgi **pcgi, *cgi = NULL;
3025 /* find finished guys but don't reap yet */
3026 n = waitpid(-1, &status, WNOHANG);
3029 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
3031 pcgi = &pt->cgi_list;
3033 /* check all the subprocesses on the cgi list */
3035 /* get the next one first as list may change */
3037 pcgi = &(*pcgi)->cgi_list;
3042 /* finish sending cached headers */
3043 if (cgi->headers_buf)
3046 /* wait for stdout to be drained */
3047 if (cgi->content_length > cgi->content_length_seen)
3050 if (cgi->content_length) {
3051 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3052 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3056 waitpid(n, &status, WNOHANG);
3058 * he's already terminated so no need for kill()
3059 * but we should do the terminated cgi callback
3060 * and close him if he's not already closing
3062 if (n == cgi->pid) {
3063 lwsl_debug("%s: found PID %d on cgi list\n",
3066 if (!cgi->content_length && cgi->explicitly_chunked) {
3068 * well, if he sends chunked... give him 5s after the
3069 * cgi terminated to send buffered
3071 cgi->chunked_grace++;
3077 lws_cgi_kill(cgi->wsi);
3083 /* if not found on the cgi list, as he's one of ours, reap */
3085 lwsl_debug("%s: reading PID %d although no cgi match\n",
3087 waitpid(n, &status, WNOHANG);
3091 /* disable this to confirm timeout cgi cleanup flow */
3093 pcgi = &pt->cgi_list;
3095 /* check all the subprocesses on the cgi list */
3097 /* get the next one first as list may change */
3099 pcgi = &(*pcgi)->cgi_list;
3104 /* we deferred killing him after reaping his PID */
3105 if (cgi->chunked_grace) {
3106 cgi->chunked_grace++;
3107 if (cgi->chunked_grace < 5)
3112 /* finish sending cached headers */
3113 if (cgi->headers_buf)
3116 /* wait for stdout to be drained */
3117 if (cgi->content_length > cgi->content_length_seen)
3120 if (cgi->content_length)
3121 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3122 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3125 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
3127 if (!cgi->content_length) {
3129 * well, if he sends chunked... give him 5s after the
3130 * cgi terminated to send buffered
3132 cgi->chunked_grace++;
3136 lwsl_debug("%s: found PID %d on cgi list\n",
3137 __func__, cgi->pid);
3140 lws_cgi_kill(cgi->wsi);
3147 /* general anti zombie defence */
3148 // n = waitpid(-1, &status, WNOHANG);
3150 // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
3156 #ifdef LWS_NO_EXTENSIONS
3158 lws_set_extension_option(struct lws *wsi, const char *ext_name,
3159 const char *opt_name, const char *opt_val)
3165 #ifdef LWS_WITH_ACCESS_LOG
3167 lws_access_log(struct lws *wsi)
3169 char *p = wsi->access_log.user_agent, ass[512];
3172 if (!wsi->access_log_pending)
3175 if (!wsi->access_log.header_log)
3181 l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
3182 wsi->access_log.header_log,
3183 wsi->access_log.response, wsi->access_log.sent, p);
3185 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
3186 if (write(wsi->vhost->log_fd, ass, l) != l)
3187 lwsl_err("Failed to write log\n");
3189 lwsl_err("%s", ass);
3191 if (wsi->access_log.header_log) {
3192 lws_free(wsi->access_log.header_log);
3193 wsi->access_log.header_log = NULL;
3195 if (wsi->access_log.user_agent) {
3196 lws_free(wsi->access_log.user_agent);
3197 wsi->access_log.user_agent = NULL;
3199 wsi->access_log_pending = 0;
3206 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
3208 const struct lws_vhost *vh = ctx->vhost_list;
3212 cs->rx += vh->conn_stats.rx;
3213 cs->tx += vh->conn_stats.tx;
3214 cs->conn += vh->conn_stats.conn;
3215 cs->trans += vh->conn_stats.trans;
3216 cs->ws_upg += vh->conn_stats.ws_upg;
3217 cs->http2_upg += vh->conn_stats.http2_upg;
3218 cs->rejected += vh->conn_stats.rejected;
3220 vh = vh->vhost_next;
3224 #ifdef LWS_WITH_SERVER_STATUS
3227 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
3229 static const char * const prots[] = {
3238 char *orig = buf, *end = buf + len - 1, first = 1;
3244 buf += lws_snprintf(buf, end - buf,
3245 "{\n \"name\":\"%s\",\n"
3246 " \"port\":\"%d\",\n"
3247 " \"use_ssl\":\"%d\",\n"
3248 " \"sts\":\"%d\",\n"
3249 " \"rx\":\"%llu\",\n"
3250 " \"tx\":\"%llu\",\n"
3251 " \"conn\":\"%lu\",\n"
3252 " \"trans\":\"%lu\",\n"
3253 " \"ws_upg\":\"%lu\",\n"
3254 " \"rejected\":\"%lu\",\n"
3255 " \"http2_upg\":\"%lu\""
3257 vh->name, vh->listen_port,
3258 #ifdef LWS_OPENSSL_SUPPORT
3263 !!(vh->options & LWS_SERVER_OPTION_STS),
3264 vh->conn_stats.rx, vh->conn_stats.tx,
3265 vh->conn_stats.conn, vh->conn_stats.trans,
3266 vh->conn_stats.ws_upg,
3267 vh->conn_stats.rejected,
3268 vh->conn_stats.http2_upg
3271 if (vh->mount_list) {
3272 const struct lws_http_mount *m = vh->mount_list;
3274 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
3277 buf += lws_snprintf(buf, end - buf, ",");
3278 buf += lws_snprintf(buf, end - buf,
3279 "\n {\n \"mountpoint\":\"%s\",\n"
3280 " \"origin\":\"%s%s\",\n"
3281 " \"cache_max_age\":\"%d\",\n"
3282 " \"cache_reuse\":\"%d\",\n"
3283 " \"cache_revalidate\":\"%d\",\n"
3284 " \"cache_intermediaries\":\"%d\"\n"
3287 prots[m->origin_protocol],
3291 m->cache_revalidate,
3292 m->cache_intermediaries);
3294 buf += lws_snprintf(buf, end - buf,
3295 ",\n \"default\":\"%s\"",
3297 buf += lws_snprintf(buf, end - buf, "\n }");
3301 buf += lws_snprintf(buf, end - buf, "\n ]");
3304 if (vh->protocols) {
3308 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
3309 while (n < vh->count_protocols) {
3311 buf += lws_snprintf(buf, end - buf, ",");
3312 buf += lws_snprintf(buf, end - buf,
3314 " \"status\":\"ok\"\n }\n }"
3316 vh->protocols[n].name);
3320 buf += lws_snprintf(buf, end - buf, "\n ]");
3323 buf += lws_snprintf(buf, end - buf, "\n}");
3329 LWS_EXTERN LWS_VISIBLE int
3330 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
3333 char *orig = buf, *end = buf + len - 1, first = 1;
3334 const struct lws_vhost *vh = context->vhost_list;
3335 const struct lws_context_per_thread *pt;
3336 time_t t = time(NULL);
3337 int n, listening = 0, cgi_count = 0;
3338 struct lws_conn_stats cs;
3341 struct lws_cgi * const *pcgi;
3344 #ifdef LWS_USE_LIBUV
3348 buf += lws_snprintf(buf, end - buf, "{ "
3349 "\"version\":\"%s\",\n"
3350 "\"uptime\":\"%ld\",\n",
3351 lws_get_library_version(),
3354 #ifdef LWS_HAVE_GETLOADAVG
3359 m = getloadavg(d, 3);
3360 for (n = 0; n < m; n++) {
3361 buf += lws_snprintf(buf, end - buf,
3362 "\"l%d\":\"%.2f\",\n",
3368 buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
3370 buf += lws_snprintf(buf, end - buf, "{ "
3371 "\"context_uptime\":\"%ld\",\n"
3372 "\"cgi_spawned\":\"%d\",\n"
3373 "\"pt_fd_max\":\"%d\",\n"
3374 "\"ah_pool_max\":\"%d\",\n"
3375 "\"deprecated\":\"%d\",\n"
3376 "\"wsi_alive\":\"%d\",\n",
3377 (unsigned long)(t - context->time_up),
3378 context->count_cgi_spawned,
3379 context->fd_limit_per_thread,
3380 context->max_http_header_pool,
3381 context->deprecated,
3382 context->count_wsi_allocated);
3384 buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
3385 for (n = 0; n < context->count_threads; n++) {
3386 pt = &context->pt[n];
3388 buf += lws_snprintf(buf, end - buf, ",");
3389 buf += lws_snprintf(buf, end - buf,
3391 " \"fds_count\":\"%d\",\n"
3392 " \"ah_pool_inuse\":\"%d\",\n"
3393 " \"ah_wait_list\":\"%d\"\n"
3396 pt->ah_count_in_use,
3397 pt->ah_wait_list_length);
3400 buf += lws_snprintf(buf, end - buf, "]");
3402 buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3405 vh = context->vhost_list;
3407 cs = context->conn_stats;
3408 lws_sum_stats(context, &cs);
3415 buf += lws_json_dump_vhost(vh, buf, end - buf);
3420 vh = vh->vhost_next;
3423 buf += lws_snprintf(buf, end - buf,
3424 "],\n\"listen_wsi\":\"%d\",\n"
3425 " \"rx\":\"%llu\",\n"
3426 " \"tx\":\"%llu\",\n"
3427 " \"conn\":\"%lu\",\n"
3428 " \"trans\":\"%lu\",\n"
3429 " \"ws_upg\":\"%lu\",\n"
3430 " \"rejected\":\"%lu\",\n"
3431 " \"http2_upg\":\"%lu\"",
3433 cs.rx, cs.tx, cs.conn, cs.trans,
3434 cs.ws_upg, cs.rejected, cs.http2_upg);
3437 for (n = 0; n < context->count_threads; n++) {
3438 pt = &context->pt[n];
3439 pcgi = &pt->cgi_list;
3442 pcgi = &(*pcgi)->cgi_list;
3448 buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3451 buf += lws_snprintf(buf, end - buf, "}");
3454 buf += lws_snprintf(buf, end - buf, "]}\n ");
3461 #if defined(LWS_WITH_STATS)
3463 LWS_VISIBLE LWS_EXTERN uint64_t
3464 lws_stats_get(struct lws_context *context, int index)
3466 if (index >= LWSSTATS_SIZE)
3469 return context->lws_stats[index];
3472 LWS_VISIBLE LWS_EXTERN void
3473 lws_stats_log_dump(struct lws_context *context)
3475 struct lws_vhost *v = context->vhost_list;
3478 if (!context->updated)
3481 context->updated = 0;
3484 lwsl_notice("LWS internal statistics dump ----->\n");
3485 lwsl_notice("LWSSTATS_C_CONNECTIONS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_CONNECTIONS));
3486 lwsl_notice("LWSSTATS_C_API_CLOSE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_CLOSE));
3487 lwsl_notice("LWSSTATS_C_API_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_READ));
3488 lwsl_notice("LWSSTATS_C_API_LWS_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_LWS_WRITE));
3489 lwsl_notice("LWSSTATS_C_API_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_WRITE));
3490 lwsl_notice("LWSSTATS_C_WRITE_PARTIALS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITE_PARTIALS));
3491 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_REQ));
3492 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_EFF_REQ));
3493 lwsl_notice("LWSSTATS_C_WRITEABLE_CB: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB));
3494 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_FAILED));
3495 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED));
3496 lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX));
3498 lwsl_notice("LWSSTATS_C_TIMEOUTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_TIMEOUTS));
3499 lwsl_notice("LWSSTATS_C_SERVICE_ENTRY: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SERVICE_ENTRY));
3500 lwsl_notice("LWSSTATS_B_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ));
3501 lwsl_notice("LWSSTATS_B_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE));
3502 lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS));
3503 lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000);
3504 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED))
3505 lwsl_notice(" Avg accept delay: %8llums\n",
3506 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) /
3507 lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000);
3508 lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / 1000);
3509 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX))
3510 lwsl_notice(" Avg accept-rx delay: %8llums\n",
3511 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) /
3512 lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000);
3514 lwsl_notice("LWSSTATS_MS_WRITABLE_DELAY: %8lluus\n",
3515 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY));
3516 lwsl_notice("LWSSTATS_MS_WORST_WRITABLE_DELAY: %8lluus\n",
3517 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WORST_WRITABLE_DELAY));
3518 if (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))
3519 lwsl_notice(" Avg writable delay: %8lluus\n",
3520 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY) /
3521 lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)));
3522 lwsl_notice("Simultaneous SSL restriction: %8d/%d/%d\n", context->simultaneous_ssl,
3523 context->simultaneous_ssl_restriction, context->ssl_gate_accepts);
3525 lwsl_notice("Live wsi: %8d\n", context->count_wsi_allocated);
3527 #if defined(LWS_WITH_STATS)
3528 context->updated = 1;
3534 struct lws_context_per_thread *pt = &context->pt[(int)v->lserv_wsi->tsi];
3535 struct lws_pollfd *pfd;
3537 pfd = &pt->fds[v->lserv_wsi->position_in_fds_table];
3539 lwsl_notice(" Listen port %d actual POLLIN: %d\n",
3540 v->listen_port, (int)pfd->events & LWS_POLLIN);
3546 for (n = 0; n < context->count_threads; n++) {
3547 struct lws_context_per_thread *pt = &context->pt[n];
3551 lwsl_notice("PT %d\n", n + 1);
3555 lwsl_notice(" AH in use / max: %d / %d\n",
3556 pt->ah_count_in_use,
3557 context->max_http_header_pool);
3559 wl = pt->ah_wait_list;
3562 wl = wl->u.hdr.ah_wait_list;
3565 lwsl_notice(" AH wait list count / actual: %d / %d\n",
3566 pt->ah_wait_list_length, m);
3575 lws_stats_atomic_bump(struct lws_context * context,
3576 struct lws_context_per_thread *pt, int index, uint64_t bump)
3579 context->lws_stats[index] += bump;
3580 if (index != LWSSTATS_C_SERVICE_ENTRY)
3581 context->updated = 1;
3586 lws_stats_atomic_max(struct lws_context * context,
3587 struct lws_context_per_thread *pt, int index, uint64_t val)
3590 if (val > context->lws_stats[index]) {
3591 context->lws_stats[index] = val;
3592 context->updated = 1;