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 !defined(LWS_NO_CLIENT)
330 if (wsi->mode == LWSCM_HTTP_CLIENT ||
331 wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
332 wsi->mode == LWSCM_WSCL_WAITING_PROXY_REPLY ||
333 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE ||
334 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE2 ||
335 wsi->mode == LWSCM_WSCL_WAITING_SSL ||
336 wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
337 wsi->mode == LWSCM_WSCL_WAITING_EXTENSION_CONNECT ||
338 wsi->mode == LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY ||
339 wsi->mode == LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY ||
340 wsi->mode == LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY)
341 if (wsi->u.hdr.stash)
342 lws_free_set_NULL(wsi->u.hdr.stash);
345 if (wsi->mode == LWSCM_RAW) {
346 wsi->protocol->callback(wsi,
347 LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0);
348 wsi->socket_is_permanently_unusable = 1;
349 goto just_kill_connection;
352 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
353 wsi->u.http.fop_fd != NULL) {
354 lws_vfs_file_close(&wsi->u.http.fop_fd);
355 wsi->vhost->protocols->callback(wsi,
356 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
357 wsi->told_user_closed = 1;
359 if (wsi->socket_is_permanently_unusable ||
360 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
361 wsi->state == LWSS_SHUTDOWN)
362 goto just_kill_connection;
364 wsi->state_pre_close = wsi->state;
366 switch (wsi->state_pre_close) {
367 case LWSS_DEAD_SOCKET:
370 /* we tried the polite way... */
371 case LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION:
372 case LWSS_AWAITING_CLOSE_ACK:
373 goto just_kill_connection;
375 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
376 if (wsi->trunc_len) {
377 lws_callback_on_writable(wsi);
380 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
381 goto just_kill_connection;
383 if (wsi->trunc_len) {
384 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
385 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
386 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
392 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
393 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
394 goto just_kill_connection;
396 if (wsi->mode == LWSCM_HTTP_SERVING) {
398 wsi->vhost->protocols->callback(wsi,
399 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
400 wsi->user_space, NULL, 0);
401 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
402 wsi->user_space, NULL, 0);
403 wsi->told_user_closed = 1;
405 if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
406 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
407 wsi->user_space, NULL, 0);
408 wsi->told_user_closed = 1;
412 * are his extensions okay with him closing? Eg he might be a mux
413 * parent and just his ch1 aspect is closing?
416 if (lws_ext_cb_active(wsi,
417 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
418 lwsl_ext("extension vetoed close\n");
423 * flush any tx pending from extensions, since we may send close packet
424 * if there are problems with send, just nuke the connection
429 eff_buf.token = NULL;
430 eff_buf.token_len = 0;
432 /* show every extension the new incoming data */
434 m = lws_ext_cb_active(wsi,
435 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
437 lwsl_ext("Extension reports fatal error\n");
438 goto just_kill_connection;
442 * at least one extension told us he has more
443 * to spill, so we will go around again after
447 /* assuming they left us something to send, send it */
449 if (eff_buf.token_len)
450 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
451 eff_buf.token_len) !=
453 lwsl_debug("close: ext spill failed\n");
454 goto just_kill_connection;
459 * signal we are closing, lws_write will
460 * add any necessary version-specific stuff. If the write fails,
461 * no worries we are closing anyway. If we didn't initiate this
462 * close, then our state has been changed to
463 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
465 * Likewise if it's a second call to close this connection after we
466 * sent the close indication to the peer already, we are in state
467 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
470 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
471 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
472 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
473 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
474 lwsl_debug("sending close indication...\n");
476 /* if no prepared close reason, use 1000 and no aux data */
477 if (!wsi->u.ws.close_in_ping_buffer_len) {
478 wsi->u.ws.close_in_ping_buffer_len = 2;
479 wsi->u.ws.ping_payload_buf[LWS_PRE] =
480 (reason >> 8) & 0xff;
481 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
485 #if defined (LWS_WITH_ESP8266)
486 wsi->close_is_pending_send_completion = 1;
489 lwsl_debug("waiting for chance to send close\n");
490 wsi->waiting_to_send_close_frame = 1;
491 wsi->state = LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION;
492 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 2);
493 lws_callback_on_writable(wsi);
498 just_kill_connection:
500 lws_remove_child_from_any_parent(wsi);
503 /* manage the vhost same protocol list entry */
505 if (wsi->same_vh_protocol_prev) { // we are on the vh list
507 // make guy who pointed to us, point to what our next was pointing to
508 *wsi->same_vh_protocol_prev = wsi->same_vh_protocol_next;
510 // if we had a next guy...
511 if (wsi->same_vh_protocol_next)
512 // have him point back to our prev
513 wsi->same_vh_protocol_next->same_vh_protocol_prev =
514 wsi->same_vh_protocol_prev;
520 * Testing with ab shows that we have to stage the socket close when
521 * the system is under stress... shutdown any further TX, change the
522 * state to one that won't emit anything more, and wait with a timeout
523 * for the POLLIN to show a zero-size rx before coming back and doing
526 if (wsi->mode != LWSCM_RAW &&
527 !(wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) &&
528 wsi->state != LWSS_SHUTDOWN &&
529 wsi->state != LWSS_CLIENT_UNCONNECTED &&
530 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
531 !wsi->socket_is_permanently_unusable) {
532 #ifdef LWS_OPENSSL_SUPPORT
533 if (lws_is_ssl(wsi) && wsi->ssl)
535 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);
536 n = SSL_shutdown(wsi->ssl);
537 if (n == 1) /* If finished the SSL shutdown, then do socket shutdown, else need to retry SSL shutdown */
538 n = shutdown(wsi->desc.sockfd, SHUT_WR);
540 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
543 int shutdown_error = SSL_get_error(wsi->ssl, n);
544 lwsl_debug("SSL_shutdown returned %d, SSL_get_error: %d\n", n, shutdown_error);
545 if (shutdown_error == SSL_ERROR_WANT_READ) {
546 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
548 } else if (shutdown_error == SSL_ERROR_WANT_WRITE) {
549 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLOUT);
551 } else { // actual error occurred, just close the connection
552 n = shutdown(wsi->desc.sockfd, SHUT_WR);
559 lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, (int)(long)wsi->desc.sockfd, wsi->state);
560 n = shutdown(wsi->desc.sockfd, SHUT_WR);
563 lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
565 // This causes problems with disconnection when the events are half closing connection
566 // FD_READ | FD_CLOSE (33)
567 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP32)
568 /* libuv: no event available to guarantee completion */
569 if (!LWS_LIBUV_ENABLED(context)) {
571 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
572 wsi->state = LWSS_SHUTDOWN;
573 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
574 context->timeout_secs);
582 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
583 wsi, wsi->desc.sockfd);
585 #ifdef LWS_WITH_HTTP_PROXY
587 lws_rewrite_destroy(wsi->rw);
592 * we won't be servicing or receiving anything further from this guy
593 * delete socket from the internal poll list if still present
595 lws_ssl_remove_wsi_from_buffered_list(wsi);
597 lws_remove_from_timeout_list(wsi);
599 /* checking return redundant since we anyway close */
600 if (wsi->desc.sockfd != LWS_SOCK_INVALID)
601 remove_wsi_socket_from_fds(wsi);
603 lws_same_vh_protocol_remove(wsi);
605 #if defined(LWS_WITH_ESP8266)
606 espconn_disconnect(wsi->desc.sockfd);
609 wsi->state = LWSS_DEAD_SOCKET;
611 lws_free_set_NULL(wsi->rxflow_buffer);
612 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
613 wsi->mode == LWSCM_WS_SERVING ||
614 wsi->mode == LWSCM_WS_CLIENT) {
616 if (wsi->u.ws.rx_draining_ext) {
617 struct lws **w = &pt->rx_draining_ext_list;
619 wsi->u.ws.rx_draining_ext = 0;
620 /* remove us from context draining ext list */
623 *w = wsi->u.ws.rx_draining_ext_list;
626 w = &((*w)->u.ws.rx_draining_ext_list);
628 wsi->u.ws.rx_draining_ext_list = NULL;
631 if (wsi->u.ws.tx_draining_ext) {
632 struct lws **w = &pt->tx_draining_ext_list;
634 wsi->u.ws.tx_draining_ext = 0;
635 /* remove us from context draining ext list */
638 *w = wsi->u.ws.tx_draining_ext_list;
641 w = &((*w)->u.ws.tx_draining_ext_list);
643 wsi->u.ws.tx_draining_ext_list = NULL;
645 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
647 if (wsi->trunc_alloc)
648 /* not going to be completed... nuke it */
649 lws_free_set_NULL(wsi->trunc_alloc);
651 wsi->u.ws.ping_payload_len = 0;
652 wsi->u.ws.ping_pending_flag = 0;
655 /* tell the user it's all over for this guy */
657 if (wsi->mode != LWSCM_RAW && wsi->protocol && wsi->protocol->callback &&
658 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
659 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
660 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
661 (wsi->state_pre_close == LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION) ||
662 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
663 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
664 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
666 if (wsi->user_space) {
667 lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s\n", __func__, wsi, wsi->protocol->name);
668 wsi->protocol->callback(wsi,
669 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
670 wsi->user_space, NULL, 0);
672 lwsl_debug("calling back CLOSED\n");
673 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
674 wsi->user_space, NULL, 0);
675 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
676 lwsl_debug("calling back CLOSED_HTTP\n");
677 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
678 wsi->user_space, NULL, 0 );
679 } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
680 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
681 !wsi->already_did_cce) {
682 wsi->vhost->protocols[0].callback(wsi,
683 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
684 wsi->user_space, NULL, 0);
686 lwsl_debug("not calling back closed mode=%d state=%d\n",
687 wsi->mode, wsi->state_pre_close);
689 /* deallocate any active extension contexts */
691 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
692 lwsl_warn("extension destruction failed\n");
694 * inform all extensions in case they tracked this guy out of band
695 * even though not active on him specifically
697 if (lws_ext_cb_all_exts(context, wsi,
698 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
699 lwsl_warn("ext destroy wsi failed\n");
703 wsi->socket_is_permanently_unusable = 1;
706 if (!wsi->parent_carries_io)
707 if (LWS_LIBUV_ENABLED(context)) {
709 lwsl_debug("%s: stopping listner libuv poll\n", __func__);
710 uv_poll_stop(&wsi->w_read.uv_watcher);
712 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
713 /* libuv has to do his own close handle processing asynchronously */
714 lws_libuv_closehandle(wsi);
720 lws_close_free_wsi_final(wsi);
724 lws_close_free_wsi_final(struct lws *wsi)
728 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->desc.sockfd)) {
730 //lwsl_err("*** closing sockfd %d\n", wsi->desc.sockfd);
731 n = compatible_close(wsi->desc.sockfd);
733 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
736 compatible_close(wsi->desc.sockfd);
739 wsi->desc.sockfd = LWS_SOCK_INVALID;
742 /* outermost destroy notification for wsi (user_space still intact) */
743 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
744 wsi->user_space, NULL, 0);
748 for (n = 0; n < 6; n++) {
749 if (wsi->cgi->pipe_fds[n / 2][n & 1] == 0)
750 lwsl_err("ZERO FD IN CGI CLOSE");
752 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
753 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
763 LWS_VISIBLE LWS_EXTERN const char *
764 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
766 int n = 0, sl = strlen(name);
768 while (lws_hdr_copy_fragment(wsi, buf, len,
769 WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
771 if (!strncmp(buf, name, sl))
780 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
782 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
786 ipv6 = LWS_IPV6_ENABLED(vh);
790 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
794 #ifndef LWS_PLAT_OPTEE
797 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
798 int name_len, char *rip, int rip_len)
801 struct addrinfo ai, *res;
802 struct sockaddr_in addr4;
807 addr4.sin_family = AF_UNSPEC;
810 if (LWS_IPV6_ENABLED(vh)) {
811 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
812 lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
816 // Strip off the IPv4 to IPv6 header if one exists
817 if (strncmp(rip, "::ffff:", 7) == 0)
818 memmove(rip, rip + 7, strlen(rip) - 6);
820 getnameinfo((struct sockaddr *)ads,
821 sizeof(struct sockaddr_in6), name,
822 name_len, NULL, 0, 0);
828 struct addrinfo *result;
830 memset(&ai, 0, sizeof ai);
831 ai.ai_family = PF_UNSPEC;
832 ai.ai_socktype = SOCK_STREAM;
833 ai.ai_flags = AI_CANONNAME;
834 #if !defined(LWS_WITH_ESP32)
835 if (getnameinfo((struct sockaddr *)ads,
836 sizeof(struct sockaddr_in),
837 name, name_len, NULL, 0, 0))
843 if (getaddrinfo(name, NULL, &ai, &result))
847 while (addr4.sin_family == AF_UNSPEC && res) {
848 switch (res->ai_family) {
850 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
851 addr4.sin_family = AF_INET;
857 freeaddrinfo(result);
860 if (addr4.sin_family == AF_UNSPEC)
863 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
881 LWS_VISIBLE const char *
882 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
887 struct sockaddr_in6 sin6;
889 struct sockaddr_in sin4;
893 if (wsi->parent_carries_io)
897 if (LWS_IPV6_ENABLED(wsi->vhost)) {
911 if (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {
912 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
916 return lws_plat_inet_ntop(af, q, name, namelen);
918 #if defined(LWS_WITH_ESP8266)
919 return lws_plat_get_peer_simple(wsi, name, namelen);
928 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
929 int name_len, char *rip, int rip_len)
931 #ifndef LWS_PLAT_OPTEE
935 struct sockaddr_in6 sin6;
937 struct sockaddr_in sin4;
938 struct lws_context *context = wsi->context;
945 lws_latency_pre(context, wsi);
948 if (LWS_IPV6_ENABLED(wsi->vhost)) {
958 if (getpeername(fd, p, &len) < 0) {
959 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
963 ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
966 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
979 lws_context_user(struct lws_context *context)
981 return context->user_space;
984 LWS_VISIBLE struct lws_vhost *
985 lws_vhost_get(struct lws *wsi)
990 LWS_VISIBLE struct lws_vhost *
991 lws_get_vhost(struct lws *wsi)
996 LWS_VISIBLE const struct lws_protocols *
997 lws_protocol_get(struct lws *wsi)
999 return wsi->protocol;
1002 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1003 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
1007 for (n = 0; n < vh->count_protocols; n++)
1008 if (!strcmp(name, vh->protocols[n].name))
1009 return &vh->protocols[n];
1015 lws_callback_all_protocol(struct lws_context *context,
1016 const struct lws_protocols *protocol, int reason)
1018 struct lws_context_per_thread *pt = &context->pt[0];
1019 unsigned int n, m = context->count_threads;
1023 for (n = 0; n < pt->fds_count; n++) {
1024 wsi = wsi_from_fd(context, pt->fds[n].fd);
1027 if (wsi->protocol == protocol)
1028 protocol->callback(wsi, reason, wsi->user_space,
1038 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
1039 const struct lws_protocols *protocol, int reason)
1041 struct lws_context *context = vh->context;
1042 struct lws_context_per_thread *pt = &context->pt[0];
1043 unsigned int n, m = context->count_threads;
1047 for (n = 0; n < pt->fds_count; n++) {
1048 wsi = wsi_from_fd(context, pt->fds[n].fd);
1051 if (wsi->vhost == vh && wsi->protocol == protocol)
1052 protocol->callback(wsi, reason, wsi->user_space,
1061 LWS_VISIBLE LWS_EXTERN int
1062 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
1066 for (n = 0; n < wsi->vhost->count_protocols; n++)
1067 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
1073 LWS_VISIBLE LWS_EXTERN void
1074 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)
1076 context->fops = fops;
1079 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1080 lws_vfs_tell(lws_fop_fd_t fop_fd)
1085 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1086 lws_vfs_get_length(lws_fop_fd_t fop_fd)
1091 LWS_VISIBLE LWS_EXTERN uint32_t
1092 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd)
1094 return fop_fd->mod_time;
1097 LWS_VISIBLE lws_fileofs_t
1098 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1101 lwsl_debug("%s: seeking to %ld, len %ld\n", __func__, (long)offset, (long)fop_fd->len);
1102 ofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);
1103 lwsl_debug("%s: result %ld, fop_fd pos %ld\n", __func__, (long)ofs, (long)fop_fd->pos);
1108 LWS_VISIBLE lws_fileofs_t
1109 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1111 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len + fop_fd->pos + offset);
1115 const struct lws_plat_file_ops *
1116 lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,
1119 const struct lws_plat_file_ops *pf;
1120 const char *p = vfs_path;
1125 /* no non-platform fops, just use that */
1131 * scan the vfs path looking for indications we are to be
1132 * handled by a specific fops
1140 /* the first one is always platform fops, so skip */
1144 while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {
1145 if (p >= vfs_path + pf->fi[n].len)
1146 if (!strncmp(p - (pf->fi[n].len - 1),
1148 pf->fi[n].len - 1)) {
1163 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
1164 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
1165 lws_fop_flags_t *flags)
1167 const char *vpath = "";
1168 const struct lws_plat_file_ops *selected = lws_vfs_select_fops(
1169 fops, vfs_path, &vpath);
1171 return selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);
1176 * lws_now_secs() - seconds since 1970-1-1
1179 LWS_VISIBLE LWS_EXTERN unsigned long
1184 gettimeofday(&tv, NULL);
1193 lws_get_socket_fd(struct lws *wsi)
1195 return wsi->desc.sockfd;
1202 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
1203 int ret, int completed)
1205 unsigned long long u;
1208 u = time_in_microseconds();
1211 wsi->latency_start = u;
1212 if (!wsi->action_start)
1213 wsi->action_start = u;
1217 if (wsi->action_start == wsi->latency_start)
1219 "Completion first try lat %lluus: %p: ret %d: %s\n",
1220 u - wsi->latency_start,
1221 (void *)wsi, ret, action);
1224 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1225 u - wsi->action_start,
1226 u - wsi->latency_start,
1227 (void *)wsi, ret, action);
1228 wsi->action_start = 0;
1230 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1231 u - wsi->latency_start, (void *)wsi, ret, action);
1233 if (u - wsi->latency_start > context->worst_latency) {
1234 context->worst_latency = u - wsi->latency_start;
1235 strcpy(context->worst_latency_info, buf);
1237 lwsl_latency("%s", buf);
1242 lws_rx_flow_control(struct lws *wsi, int enable)
1244 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1247 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1248 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1254 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1255 const struct lws_protocols *protocol)
1257 const struct lws_context_per_thread *pt = &context->pt[0];
1259 unsigned int n, m = context->count_threads;
1262 for (n = 0; n < pt->fds_count; n++) {
1263 wsi = wsi_from_fd(context, pt->fds[n].fd);
1266 if (wsi->protocol == protocol)
1267 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1273 LWS_VISIBLE extern const char *
1274 lws_canonical_hostname(struct lws_context *context)
1276 return (const char *)context->canonical_hostname;
1279 int user_callback_handle_rxflow(lws_callback_function callback_function,
1281 enum lws_callback_reasons reason, void *user,
1282 void *in, size_t len)
1286 n = callback_function(wsi, reason, user, in, len);
1288 n = _lws_rx_flow_control(wsi);
1293 #if defined(LWS_WITH_ESP8266)
1295 #define strchr ets_strchr
1299 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1301 #if !defined(LWS_WITH_ESP8266)
1303 char authstring[96];
1308 /* we have to deal with a possible redundant leading http:// */
1309 if (!strncmp(proxy, "http://", 7))
1312 p = strchr(proxy, '@');
1313 if (p) { /* auth is around */
1315 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1318 strncpy(authstring, proxy, p - proxy);
1319 // null termination not needed on input
1320 if (lws_b64_encode_string(authstring, (p - proxy),
1321 vhost->proxy_basic_auth_token,
1322 sizeof vhost->proxy_basic_auth_token) < 0)
1325 lwsl_info(" Proxy auth in use\n");
1329 vhost->proxy_basic_auth_token[0] = '\0';
1331 strncpy(vhost->http_proxy_address, proxy,
1332 sizeof(vhost->http_proxy_address) - 1);
1333 vhost->http_proxy_address[
1334 sizeof(vhost->http_proxy_address) - 1] = '\0';
1336 p = strchr(vhost->http_proxy_address, ':');
1337 if (!p && !vhost->http_proxy_port) {
1338 lwsl_err("http_proxy needs to be ads:port\n");
1344 vhost->http_proxy_port = atoi(p + 1);
1348 lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1349 vhost->http_proxy_port);
1354 lwsl_err("proxy auth too long\n");
1359 #if defined(LWS_WITH_SOCKS5)
1361 lws_set_socks(struct lws_vhost *vhost, const char *socks)
1363 #if !defined(LWS_WITH_ESP8266)
1364 char *p_at, *p_colon;
1371 vhost->socks_user[0] = '\0';
1372 vhost->socks_password[0] = '\0';
1374 p_at = strchr(socks, '@');
1375 if (p_at) { /* auth is around */
1376 if ((unsigned int)(p_at - socks) > (sizeof(user)
1377 + sizeof(password) - 2)) {
1378 lwsl_err("Socks auth too long\n");
1382 p_colon = strchr(socks, ':');
1384 if ((unsigned int)(p_colon - socks) > (sizeof(user)
1386 lwsl_err("Socks user too long\n");
1389 if ((unsigned int)(p_at - p_colon) > (sizeof(password)
1391 lwsl_err("Socks password too long\n");
1395 strncpy(vhost->socks_user, socks, p_colon - socks);
1396 strncpy(vhost->socks_password, p_colon + 1,
1397 p_at - (p_colon + 1));
1399 lwsl_info(" Socks auth, user: %s, password: %s\n",
1400 vhost->socks_user, vhost->socks_password );
1405 strncpy(vhost->socks_proxy_address, socks,
1406 sizeof(vhost->socks_proxy_address) - 1);
1407 vhost->socks_proxy_address[sizeof(vhost->socks_proxy_address) - 1]
1410 p_colon = strchr(vhost->socks_proxy_address, ':');
1411 if (!p_colon && !vhost->socks_proxy_port) {
1412 lwsl_err("socks_proxy needs to be address:port\n");
1417 vhost->socks_proxy_port = atoi(p_colon + 1);
1421 lwsl_info(" Socks %s:%u\n", vhost->socks_proxy_address,
1422 vhost->socks_proxy_port);
1432 LWS_VISIBLE const struct lws_protocols *
1433 lws_get_protocol(struct lws *wsi)
1435 return wsi->protocol;
1439 lws_is_final_fragment(struct lws *wsi)
1441 lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1442 wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1443 (long)wsi->u.ws.rx_draining_ext);
1444 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1448 lws_is_first_fragment(struct lws *wsi)
1450 return wsi->u.ws.first_fragment;
1453 LWS_VISIBLE unsigned char
1454 lws_get_reserved_bits(struct lws *wsi)
1456 return wsi->u.ws.rsv;
1460 lws_ensure_user_space(struct lws *wsi)
1462 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1466 /* allocate the per-connection user memory (if any) */
1468 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1469 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1470 if (wsi->user_space == NULL) {
1471 lwsl_err("Out of memory for conn user space\n");
1475 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1476 __func__, wsi, (long)wsi->protocol->per_session_data_size,
1482 lwsl_timestamp(int level, char *p, int len)
1484 #ifndef LWS_PLAT_OPTEE
1485 time_t o_now = time(NULL);
1486 unsigned long long now;
1487 struct tm *ptm = NULL;
1495 ptm = localtime(&o_now);
1497 if (localtime_r(&o_now, &tm))
1502 for (n = 0; n < LLL_COUNT; n++) {
1503 if (level != (1 << n))
1505 now = time_in_microseconds() / 100;
1507 n = lws_snprintf(p, len,
1508 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1509 ptm->tm_year + 1900,
1515 (int)(now % 10000), log_level_names[n]);
1517 n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1518 (unsigned long long) now / 10000,
1519 (int)(now % 10000), log_level_names[n]);
1526 #ifndef LWS_PLAT_OPTEE
1527 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1529 #if !defined(LWS_WITH_ESP8266)
1532 lwsl_timestamp(level, buf, sizeof(buf));
1533 fprintf(stderr, "%s%s", buf, line);
1538 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1540 #if defined(LWS_WITH_ESP8266)
1547 if (!(log_level & filter))
1550 n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1552 #if defined(LWS_WITH_ESP8266)
1553 buf[sizeof(buf) - 1] = '\0';
1555 /* vnsprintf returns what it would have written, even if truncated */
1556 if (n > sizeof(buf) - 1)
1557 n = sizeof(buf) - 1;
1562 lwsl_emit(filter, buf);
1565 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1569 va_start(ap, format);
1570 _lws_logv(filter, format, ap);
1574 LWS_VISIBLE void lws_set_log_level(int level,
1575 void (*func)(int level, const char *line))
1582 LWS_VISIBLE int lwsl_visible(int level)
1584 return log_level & level;
1588 lws_is_ssl(struct lws *wsi)
1590 #ifdef LWS_OPENSSL_SUPPORT
1591 return wsi->use_ssl;
1598 #ifdef LWS_OPENSSL_SUPPORT
1600 lws_get_ssl(struct lws *wsi)
1607 lws_partial_buffered(struct lws *wsi)
1609 return !!wsi->trunc_len;
1612 void lws_set_protocol_write_pending(struct lws *wsi,
1613 enum lws_pending_protocol_send pend)
1615 lwsl_info("setting pps %d\n", pend);
1618 lwsl_err("pps overwrite\n");
1620 lws_rx_flow_control(wsi, 0);
1621 lws_callback_on_writable(wsi);
1625 lws_get_peer_write_allowance(struct lws *wsi)
1627 #ifdef LWS_USE_HTTP2
1628 /* only if we are using HTTP2 on this connection */
1629 if (wsi->mode != LWSCM_HTTP2_SERVING)
1631 /* user is only interested in how much he can send, or that he can't */
1632 if (wsi->u.http2.tx_credit <= 0)
1635 return wsi->u.http2.tx_credit;
1643 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1645 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1646 memset(&wsi->u, 0, sizeof(wsi->u));
1650 LWS_VISIBLE struct lws_plat_file_ops *
1651 lws_get_fops(struct lws_context *context)
1653 return (struct lws_plat_file_ops *)context->fops;
1656 LWS_VISIBLE LWS_EXTERN struct lws_context *
1657 lws_get_context(const struct lws *wsi)
1659 return wsi->context;
1662 LWS_VISIBLE LWS_EXTERN int
1663 lws_get_count_threads(struct lws_context *context)
1665 return context->count_threads;
1668 LWS_VISIBLE LWS_EXTERN void *
1669 lws_wsi_user(struct lws *wsi)
1671 return wsi->user_space;
1674 LWS_VISIBLE LWS_EXTERN void
1675 lws_set_wsi_user(struct lws *wsi, void *data)
1677 if (wsi->user_space_externally_allocated)
1678 wsi->user_space = data;
1680 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1684 LWS_VISIBLE LWS_EXTERN struct lws *
1685 lws_get_parent(const struct lws *wsi)
1690 LWS_VISIBLE LWS_EXTERN struct lws *
1691 lws_get_child(const struct lws *wsi)
1693 return wsi->child_list;
1696 LWS_VISIBLE LWS_EXTERN void
1697 lws_set_parent_carries_io(struct lws *wsi)
1699 wsi->parent_carries_io = 1;
1702 LWS_VISIBLE LWS_EXTERN void *
1703 lws_get_opaque_parent_data(const struct lws *wsi)
1705 return wsi->opaque_parent_data;
1708 LWS_VISIBLE LWS_EXTERN void
1709 lws_set_opaque_parent_data(struct lws *wsi, void *data)
1711 wsi->opaque_parent_data = data;
1714 LWS_VISIBLE LWS_EXTERN int
1715 lws_get_child_pending_on_writable(const struct lws *wsi)
1717 return wsi->parent_pending_cb_on_writable;
1720 LWS_VISIBLE LWS_EXTERN void
1721 lws_clear_child_pending_on_writable(struct lws *wsi)
1723 wsi->parent_pending_cb_on_writable = 0;
1726 LWS_VISIBLE LWS_EXTERN int
1727 lws_get_close_length(struct lws *wsi)
1729 return wsi->u.ws.close_in_ping_buffer_len;
1732 LWS_VISIBLE LWS_EXTERN unsigned char *
1733 lws_get_close_payload(struct lws *wsi)
1735 return &wsi->u.ws.ping_payload_buf[LWS_PRE];
1738 LWS_VISIBLE LWS_EXTERN void
1739 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1740 unsigned char *buf, size_t len)
1742 unsigned char *p, *start;
1743 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1745 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1747 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1749 *p++ = (((int)status) >> 8) & 0xff;
1750 *p++ = ((int)status) & 0xff;
1753 while (len-- && p < start + budget)
1756 wsi->u.ws.close_in_ping_buffer_len = p - start;
1760 _lws_rx_flow_control(struct lws *wsi)
1762 struct lws *wsic = wsi->child_list;
1764 /* if he has children, do those if they were changed */
1766 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1767 _lws_rx_flow_control(wsic);
1769 wsic = wsic->sibling_list;
1772 /* there is no pending change */
1773 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1774 // lwsl_debug("%s: no pending change\n", __func__);
1778 /* stuff is still buffered, not ready to really accept new input */
1779 if (wsi->rxflow_buffer) {
1780 /* get ourselves called back to deal with stashed buffer */
1781 lws_callback_on_writable(wsi);
1785 /* pending is cleared, we can change rxflow state */
1787 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1789 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1790 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1792 /* adjust the pollfd for this wsi */
1794 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1795 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1796 lwsl_info("%s: fail\n", __func__);
1800 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1807 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1809 static const unsigned char e0f4[] = {
1810 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1811 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1812 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1813 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1814 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1815 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1816 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1817 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1818 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1819 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1820 0x80 | ((4 - 1) << 2) | 1, /* ea */
1821 0x80 | ((4 - 1) << 2) | 1, /* eb */
1822 0x80 | ((4 - 1) << 2) | 1, /* ec */
1823 0x80 | ((2 - 1) << 2) | 1, /* ed */
1824 0x80 | ((4 - 1) << 2) | 1, /* ee */
1825 0x80 | ((4 - 1) << 2) | 1, /* ef */
1826 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1827 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1828 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1829 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1830 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1833 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1834 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1836 unsigned char s = *state;
1839 unsigned char c = *buf++;
1843 if (c < 0xc2 || c > 0xf4)
1846 s = 0x80 | ((4 - 1) << 2);
1851 if (c < (s & 0xf0) ||
1852 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1854 s = e0f4[21 + (s & 3)];
1863 LWS_VISIBLE LWS_EXTERN int
1864 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1868 static const char *slash = "/";
1870 /* cut up the location into address, port and path */
1872 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1883 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1885 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1891 while (*p && *p != ']')
1898 while (*p && *p != ':' && *p != '/')
1904 while (*p && *p != '/')
1917 #ifdef LWS_NO_EXTENSIONS
1919 /* we need to provide dummy callbacks for internal exts
1920 * so user code runs when faced with a lib compiled with
1921 * extensions disabled.
1925 lws_extension_callback_pm_deflate(struct lws_context *context,
1926 const struct lws_extension *ext,
1928 enum lws_extension_callback_reasons reason,
1929 void *user, void *in, size_t len)
1944 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1948 #ifdef LWS_USE_UNIX_SOCK
1949 struct sockaddr_un serv_unix;
1952 struct sockaddr_in6 serv_addr6;
1954 struct sockaddr_in serv_addr4;
1955 #ifndef LWS_PLAT_OPTEE
1956 socklen_t len = sizeof(struct sockaddr_storage);
1959 struct sockaddr_storage sin;
1962 #ifdef LWS_USE_UNIX_SOCK
1963 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1964 v = (struct sockaddr *)&serv_unix;
1965 n = sizeof(struct sockaddr_un);
1966 bzero((char *) &serv_unix, sizeof(serv_unix));
1967 serv_unix.sun_family = AF_UNIX;
1968 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1969 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1973 strcpy(serv_unix.sun_path, iface);
1974 if (serv_unix.sun_path[0] == '@')
1975 serv_unix.sun_path[0] = '\0';
1979 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1980 if (LWS_IPV6_ENABLED(vhost)) {
1981 v = (struct sockaddr *)&serv_addr6;
1982 n = sizeof(struct sockaddr_in6);
1983 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1985 if (interface_to_sa(vhost, iface,
1986 (struct sockaddr_in *)v, n) < 0) {
1987 lwsl_err("Unable to find interface %s\n", iface);
1990 serv_addr6.sin6_scope_id = lws_get_addr_scope(iface);
1993 serv_addr6.sin6_family = AF_INET6;
1994 serv_addr6.sin6_port = htons(port);
1998 v = (struct sockaddr *)&serv_addr4;
1999 n = sizeof(serv_addr4);
2000 bzero((char *) &serv_addr4, sizeof(serv_addr4));
2001 serv_addr4.sin_addr.s_addr = INADDR_ANY;
2002 serv_addr4.sin_family = AF_INET;
2003 #if !defined(LWS_WITH_ESP32)
2006 interface_to_sa(vhost, iface,
2007 (struct sockaddr_in *)v, n) < 0) {
2008 lwsl_err("Unable to find interface %s\n", iface);
2012 serv_addr4.sin_port = htons(port);
2015 n = bind(sockfd, v, n);
2016 #ifdef LWS_USE_UNIX_SOCK
2017 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
2018 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
2019 sockfd, iface, n, LWS_ERRNO);
2024 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
2025 sockfd, port, n, LWS_ERRNO);
2029 #ifndef LWS_PLAT_OPTEE
2030 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
2031 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
2034 #if defined(LWS_USE_IPV6)
2035 port = (sin.ss_family == AF_INET6) ?
2036 ntohs(((struct sockaddr_in6 *) &sin)->sin6_port) :
2037 ntohs(((struct sockaddr_in *) &sin)->sin_port);
2039 port = ntohs(((struct sockaddr_in *) &sin)->sin_port);
2046 #if defined(LWS_USE_IPV6)
2047 LWS_EXTERN unsigned long
2048 lws_get_addr_scope(const char *ipaddr)
2050 unsigned long scope = 0;
2053 struct ifaddrs *addrs, *addr;
2054 char ip[NI_MAXHOST];
2058 for (addr = addrs; addr; addr = addr->ifa_next) {
2059 if (!addr->ifa_addr ||
2060 addr->ifa_addr->sa_family != AF_INET6)
2063 getnameinfo(addr->ifa_addr,
2064 sizeof(struct sockaddr_in6),
2066 NULL, 0, NI_NUMERICHOST);
2070 if (ip[i++] == '%') {
2075 if (!strcmp(ip, ipaddr)) {
2076 scope = if_nametoindex(addr->ifa_name);
2082 PIP_ADAPTER_ADDRESSES adapter, addrs = NULL;
2083 PIP_ADAPTER_UNICAST_ADDRESS addr;
2086 struct sockaddr_in6 *sockaddr;
2087 char ip[NI_MAXHOST];
2091 for (i = 0; i < 5; i++)
2093 ret = GetAdaptersAddresses(AF_INET6, GAA_FLAG_INCLUDE_PREFIX,
2094 NULL, addrs, &size);
2095 if ((ret == NO_ERROR) || (ret == ERROR_NO_DATA)) {
2097 } else if (ret == ERROR_BUFFER_OVERFLOW)
2101 addrs = (IP_ADAPTER_ADDRESSES *) malloc(size);
2109 lwsl_err("Failed to get IPv6 address table (%d)", ret);
2114 if ((ret == NO_ERROR) && (addrs))
2117 while ((adapter) && (!found))
2119 addr = adapter->FirstUnicastAddress;
2120 while ((addr) && (!found))
2122 if (addr->Address.lpSockaddr->sa_family == AF_INET6)
2124 sockaddr = (struct sockaddr_in6 *) (addr->Address.lpSockaddr);
2126 lws_plat_inet_ntop(sockaddr->sin6_family, &sockaddr->sin6_addr,
2129 if (!strcmp(ip, ipaddr)) {
2130 scope = sockaddr->sin6_scope_id;
2137 adapter = adapter->Next;
2149 lws_restart_ws_ping_pong_timer(struct lws *wsi)
2151 if (!wsi->context->ws_ping_pong_interval)
2153 if (wsi->state != LWSS_ESTABLISHED)
2156 wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
2157 wsi->context->ws_ping_pong_interval;
2160 static const char *hex = "0123456789ABCDEF";
2162 LWS_VISIBLE LWS_EXTERN const char *
2163 lws_sql_purify(char *escaped, const char *string, int len)
2165 const char *p = string;
2168 while (*p && len-- > 2) {
2182 LWS_VISIBLE LWS_EXTERN const char *
2183 lws_json_purify(char *escaped, const char *string, int len)
2185 const char *p = string;
2193 while (*p && len-- > 6) {
2194 if (*p == '\"' || *p == '\\' || *p < 0x20) {
2199 *q++ = hex[((*p) >> 4) & 15];
2200 *q++ = hex[(*p) & 15];
2211 LWS_VISIBLE LWS_EXTERN const char *
2212 lws_urlencode(char *escaped, const char *string, int len)
2214 const char *p = string;
2217 while (*p && len-- > 3) {
2223 if ((*p >= '0' && *p <= '9') ||
2224 (*p >= 'A' && *p <= 'Z') ||
2225 (*p >= 'a' && *p <= 'z')) {
2230 *q++ = hex[(*p >> 4) & 0xf];
2231 *q++ = hex[*p & 0xf];
2241 LWS_VISIBLE LWS_EXTERN int
2242 lws_urldecode(char *string, const char *escaped, int len)
2247 while (*escaped && len) {
2250 if (*escaped == '%') {
2255 if (*escaped == '+') {
2261 *string++ = *escaped++;
2265 n = char_to_hex(*escaped);
2274 n = char_to_hex(*escaped);
2278 *string++ = sum | n;
2290 LWS_VISIBLE LWS_EXTERN int
2291 lws_finalize_startup(struct lws_context *context)
2293 struct lws_context_creation_info info;
2295 info.uid = context->uid;
2296 info.gid = context->gid;
2298 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
2299 memcpy(info.caps, context->caps, sizeof(info.caps));
2300 info.count_caps = context->count_caps;
2303 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2304 lws_plat_drop_app_privileges(&info);
2310 lws_snprintf(char *str, size_t size, const char *format, ...)
2318 va_start(ap, format);
2319 n = vsnprintf(str, size, format, ap);
2329 LWS_VISIBLE LWS_EXTERN int
2330 lws_is_cgi(struct lws *wsi) {
2341 urlencode(const char *in, int inlen, char *out, int outlen)
2343 char *start = out, *end = out + outlen;
2345 while (inlen-- && out < end - 4) {
2346 if ((*in >= 'A' && *in <= 'Z') ||
2347 (*in >= 'a' && *in <= 'z') ||
2348 (*in >= '0' && *in <= '9') ||
2362 *out++ = hex[(*in) >> 4];
2363 *out++ = hex[(*in++) & 15];
2374 lws_create_basic_wsi(struct lws_context *context, int tsi)
2376 struct lws *new_wsi;
2378 if ((unsigned int)context->pt[tsi].fds_count ==
2379 context->fd_limit_per_thread - 1) {
2380 lwsl_err("no space for new conn\n");
2384 new_wsi = lws_zalloc(sizeof(struct lws));
2385 if (new_wsi == NULL) {
2386 lwsl_err("Out of memory for new connection\n");
2391 new_wsi->context = context;
2392 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2393 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2395 /* initialize the instance struct */
2397 new_wsi->state = LWSS_CGI;
2398 new_wsi->mode = LWSCM_CGI;
2399 new_wsi->hdr_parsing_completed = 0;
2400 new_wsi->position_in_fds_table = -1;
2403 * these can only be set once the protocol is known
2404 * we set an unestablished connection's protocol pointer
2405 * to the start of the defauly vhost supported list, so it can look
2406 * for matching ones during the handshake
2408 new_wsi->protocol = context->vhost_list->protocols;
2409 new_wsi->user_space = NULL;
2410 new_wsi->ietf_spec_revision = 0;
2411 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2412 context->count_wsi_allocated++;
2417 LWS_VISIBLE LWS_EXTERN int
2418 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2419 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2421 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2422 char *env_array[30], cgi_path[400], e[1024], *p = e,
2423 *end = p + sizeof(e) - 1, tok[256], *t;
2424 struct lws_cgi *cgi;
2425 int n, m, i, uritok = -1;
2428 * give the master wsi a cgi struct
2431 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2433 lwsl_err("%s: OOM\n", __func__);
2437 wsi->cgi->response_code = HTTP_STATUS_OK;
2440 cgi->wsi = wsi; /* set cgi's owning wsi */
2442 /* create pipes for [stdin|stdout] and [stderr] */
2444 for (n = 0; n < 3; n++)
2445 if (pipe(cgi->pipe_fds[n]) == -1)
2448 /* create cgi wsis for each stdin/out/err fd */
2450 for (n = 0; n < 3; n++) {
2451 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2452 if (!cgi->stdwsi[n])
2454 cgi->stdwsi[n]->cgi_channel = n;
2455 cgi->stdwsi[n]->vhost = wsi->vhost;
2457 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2458 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2460 /* read side is 0, stdin we want the write side, others read */
2461 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2462 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2463 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2468 for (n = 0; n < 3; n++) {
2469 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2470 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2472 cgi->stdwsi[n]->parent = wsi;
2473 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2474 wsi->child_list = cgi->stdwsi[n];
2477 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2478 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2479 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2481 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2482 cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2483 cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2484 cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2486 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2488 /* the cgi stdout is always sending us http1.x header data first */
2489 wsi->hdr_state = LCHS_HEADER;
2491 /* add us to the pt list of active cgis */
2492 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2493 cgi->cgi_list = pt->cgi_list;
2496 /* prepare his CGI env */
2500 if (lws_is_ssl(wsi))
2501 env_array[n++] = "HTTPS=ON";
2502 if (wsi->u.hdr.ah) {
2503 static const unsigned char meths[] = {
2506 WSI_TOKEN_OPTIONS_URI,
2508 WSI_TOKEN_PATCH_URI,
2509 WSI_TOKEN_DELETE_URI,
2511 static const char * const meth_names[] = {
2512 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2515 for (m = 0; m < ARRAY_SIZE(meths); m++)
2516 if (lws_hdr_total_length(wsi, meths[m]) >=
2517 script_uri_path_len) {
2525 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2526 lws_hdr_simple_ptr(wsi, uritok));
2527 cgi_path[sizeof(cgi_path) - 1] = '\0';
2528 env_array[n++] = cgi_path;
2531 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2536 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2537 /* dump the individual URI Arg parameters */
2540 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2541 WSI_TOKEN_HTTP_URI_ARGS, m);
2545 while (*t && *t != '=' && p < end - 4)
2549 i = urlencode(t, i- (t - tok), p, end - p);
2561 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2562 lws_hdr_simple_ptr(wsi, uritok) +
2563 script_uri_path_len);
2566 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2568 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2569 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2572 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2574 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2575 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2578 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2580 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2581 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2584 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2586 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2587 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2590 if (uritok == WSI_TOKEN_POST_URI) {
2591 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2593 p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2594 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2597 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2599 p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2600 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2605 p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2609 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2611 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2614 mp_cgienv = mp_cgienv->next;
2617 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2618 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2619 env_array[n] = NULL;
2622 for (m = 0; m < n; m++)
2623 lwsl_err(" %s\n", env_array[m]);
2627 * Actually having made the env, as a cgi we don't need the ah
2630 if (lws_header_table_is_in_detachable_state(wsi))
2631 lws_header_table_detach(wsi, 0);
2633 /* we are ready with the redirection pipes... run the thing */
2634 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2640 lwsl_err("fork failed, errno %d", errno);
2644 #if defined(__linux__)
2645 prctl(PR_SET_PDEATHSIG, SIGTERM);
2647 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2650 /* we are the parent process */
2651 wsi->context->count_cgi_spawned++;
2652 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2656 /* somewhere we can at least read things and enter it */
2658 lwsl_notice("%s: Failed to chdir\n", __func__);
2660 /* We are the forked process, redirect and kill inherited things.
2662 * Because of vfork(), we cannot do anything that changes pages in
2663 * the parent environment. Stuff that changes kernel state for the
2664 * process is OK. Stuff that happens after the execvpe() is OK.
2667 for (n = 0; n < 3; n++) {
2668 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2669 lwsl_err("%s: stdin dup2 failed\n", __func__);
2672 close(cgi->pipe_fds[n][!(n == 0)]);
2675 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2676 for (m = 0; m < n; m++) {
2677 p = strchr(env_array[m], '=');
2679 setenv(env_array[m], p, 1);
2681 execvp(exec_array[0], (char * const *)&exec_array[0]);
2683 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2689 /* drop us from the pt cgi list */
2690 pt->cgi_list = cgi->cgi_list;
2693 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2695 for (n = 0; n < 3; n++)
2696 if (wsi->cgi->stdwsi[n])
2697 lws_free_wsi(cgi->stdwsi[n]);
2700 for (n = 0; n < 3; n++) {
2701 if (cgi->pipe_fds[n][0])
2702 close(cgi->pipe_fds[n][0]);
2703 if (cgi->pipe_fds[n][1])
2704 close(cgi->pipe_fds[n][1]);
2707 lws_free_set_NULL(wsi->cgi);
2709 lwsl_err("%s: failed\n", __func__);
2714 /* we have to parse out these headers in the CGI output */
2716 static const char * const significant_hdr[SIGNIFICANT_HDR_COUNT] = {
2720 "transfer-encoding: chunked",
2723 LWS_VISIBLE LWS_EXTERN int
2724 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2727 unsigned char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2728 *end = &buf[sizeof(buf) - 1 - LWS_PRE];
2734 while (wsi->hdr_state != LHCS_PAYLOAD) {
2735 /* we have to separate header / finalize and
2736 * payload chunks, since they need to be
2737 * handled separately
2740 switch (wsi->hdr_state) {
2743 lwsl_info("LHCS_RESPONSE: issuing response %d\n",
2744 wsi->cgi->response_code);
2745 if (lws_add_http_header_status(wsi, wsi->cgi->response_code, &p, end))
2747 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2748 (unsigned char *)"close", 5, &p, end))
2750 n = lws_write(wsi, start, p - start,
2751 LWS_WRITE_HTTP_HEADERS);
2753 /* finalize cached headers before dumping them */
2754 if (lws_finalize_http_header(wsi,
2755 (unsigned char **)&wsi->cgi->headers_pos,
2756 (unsigned char *)wsi->cgi->headers_end)) {
2758 lwsl_notice("finalize failed\n");
2762 wsi->hdr_state = LHCS_DUMP_HEADERS;
2763 wsi->reason_bf |= 8;
2764 lws_callback_on_writable(wsi);
2765 /* back to the loop for writeability again */
2768 case LHCS_DUMP_HEADERS:
2770 n = wsi->cgi->headers_pos - wsi->cgi->headers_dumped;
2774 lwsl_debug("LHCS_DUMP_HEADERS: %d\n", n);
2776 m = lws_write(wsi, (unsigned char *)wsi->cgi->headers_dumped,
2777 n, LWS_WRITE_HTTP_HEADERS);
2779 lwsl_debug("%s: write says %d\n", __func__, m);
2782 wsi->cgi->headers_dumped += n;
2783 if (wsi->cgi->headers_dumped == wsi->cgi->headers_pos) {
2784 wsi->hdr_state = LHCS_PAYLOAD;
2785 lws_free_set_NULL(wsi->cgi->headers_buf);
2786 lwsl_debug("freed cgi headers\n");
2788 wsi->reason_bf |= 8;
2789 lws_callback_on_writable(wsi);
2792 /* writeability becomes uncertain now we wrote
2793 * something, we must return to the event loop
2798 if (!wsi->cgi->headers_buf) {
2799 /* if we don't already have a headers buf, cook one up */
2801 wsi->cgi->headers_buf = malloc(n);
2802 if (!wsi->cgi->headers_buf) {
2807 lwsl_debug("allocated cgi hdrs\n");
2808 wsi->cgi->headers_pos = wsi->cgi->headers_buf;
2809 wsi->cgi->headers_dumped = wsi->cgi->headers_pos;
2810 wsi->cgi->headers_end = wsi->cgi->headers_buf + n - 1;
2812 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2813 wsi->cgi->match[n] = 0;
2818 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2820 if (errno != EAGAIN) {
2821 lwsl_debug("%s: read says %d\n", __func__, n);
2827 if (wsi->cgi->headers_pos >= wsi->cgi->headers_end - 4) {
2828 lwsl_notice("CGI headers larger than buffer size\n");
2834 lwsl_debug("-- 0x%02X %c %d %d\n", (unsigned char)c, c, wsi->cgi->match[1], wsi->hdr_state);
2837 switch (wsi->hdr_state) {
2840 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2841 /* significant headers with numeric decimal payloads */
2842 if (!significant_hdr[n][wsi->cgi->match[n]] &&
2843 (c >= '0' && c <= '9') &&
2844 wsi->cgi->lp < sizeof(wsi->cgi->l) - 1) {
2845 wsi->cgi->l[wsi->cgi->lp++] = c;
2846 wsi->cgi->l[wsi->cgi->lp] = '\0';
2848 case SIGNIFICANT_HDR_CONTENT_LENGTH:
2849 wsi->cgi->content_length = atoll(wsi->cgi->l);
2851 case SIGNIFICANT_HDR_STATUS:
2852 wsi->cgi->response_code = atol(wsi->cgi->l);
2853 lwsl_debug("Status set to %d\n", wsi->cgi->response_code);
2859 /* hits up to the NUL are sticky until next hdr */
2860 if (significant_hdr[n][wsi->cgi->match[n]]) {
2861 if (tolower(c) == significant_hdr[n][wsi->cgi->match[n]])
2862 wsi->cgi->match[n]++;
2864 wsi->cgi->match[n] = 0;
2868 /* some cgi only send us \x0a for EOL */
2870 wsi->hdr_state = LCHS_SINGLE_0A;
2871 *wsi->cgi->headers_pos++ = '\x0d';
2873 *wsi->cgi->headers_pos++ = c;
2875 wsi->hdr_state = LCHS_LF1;
2877 if (wsi->hdr_state != LCHS_HEADER &&
2878 !significant_hdr[SIGNIFICANT_HDR_TRANSFER_ENCODING][wsi->cgi->match[SIGNIFICANT_HDR_TRANSFER_ENCODING]]) {
2879 lwsl_debug("cgi produced chunked\n");
2880 wsi->cgi->explicitly_chunked = 1;
2883 /* presence of Location: mandates 302 retcode */
2884 if (wsi->hdr_state != LCHS_HEADER &&
2885 !significant_hdr[SIGNIFICANT_HDR_LOCATION][wsi->cgi->match[SIGNIFICANT_HDR_LOCATION]]) {
2886 lwsl_debug("CGI: Location hdr seen\n");
2887 wsi->cgi->response_code = 302;
2892 *wsi->cgi->headers_pos++ = c;
2894 wsi->hdr_state = LCHS_CR2;
2897 /* we got \r[^\n]... it's unreasonable */
2898 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2904 wsi->hdr_state = LCHS_LF2;
2907 wsi->hdr_state = LCHS_HEADER;
2908 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2909 wsi->cgi->match[n] = 0;
2914 case LCHS_SINGLE_0A:
2917 lwsl_debug("Content-Length: %lld\n", (unsigned long long)wsi->cgi->content_length);
2918 wsi->hdr_state = LHCS_RESPONSE;
2919 /* drop the \0xa ... finalize will add it if needed */
2923 /* we got \r\n\r[^\n]... it's unreasonable */
2925 /* we got \x0anext header, it's reasonable */
2926 *wsi->cgi->headers_pos++ = c;
2927 wsi->hdr_state = LCHS_HEADER;
2928 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2929 wsi->cgi->match[n] = 0;
2937 /* ran out of input, ended the headers, or filled up the headers buf */
2938 if (!n || wsi->hdr_state == LHCS_PAYLOAD)
2942 /* payload processing */
2944 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2945 start, sizeof(buf) - LWS_PRE);
2947 if (n < 0 && errno != EAGAIN) {
2948 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2952 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2953 //lwsl_notice("write %d\n", m);
2955 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2958 wsi->cgi->content_length_seen += m;
2964 LWS_VISIBLE LWS_EXTERN int
2965 lws_cgi_kill(struct lws *wsi)
2967 struct lws_cgi_args args;
2970 lwsl_debug("%s: %p\n", __func__, wsi);
2975 if (wsi->cgi->pid > 0) {
2976 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2978 lwsl_debug("%s: PID %d reaped\n", __func__,
2982 /* kill the process group */
2983 n = kill(-wsi->cgi->pid, SIGTERM);
2984 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2985 wsi->cgi->pid, n, errno);
2988 * hum seen errno=3 when process is listed in ps,
2989 * it seems we don't always retain process grouping
2991 * Direct these fallback attempt to the exact child
2993 n = kill(wsi->cgi->pid, SIGTERM);
2995 n = kill(wsi->cgi->pid, SIGPIPE);
2997 n = kill(wsi->cgi->pid, SIGKILL);
2999 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
3000 __func__, wsi->cgi->pid, errno);
3004 /* He could be unkillable because he's a zombie */
3007 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
3009 lwsl_debug("%s: reaped PID %d\n", __func__, n);
3011 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
3013 lwsl_debug("%s: reaped PID %d\n", __func__, n);
3019 args.stdwsi = &wsi->cgi->stdwsi[0];
3021 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
3022 wsi->protocol->callback,
3023 wsi, LWS_CALLBACK_CGI_TERMINATED,
3025 (void *)&args, 0)) {
3027 if (!wsi->cgi->being_closed)
3028 lws_close_free_wsi(wsi, 0);
3035 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
3037 struct lws_cgi **pcgi, *cgi = NULL;
3041 /* find finished guys but don't reap yet */
3042 n = waitpid(-1, &status, WNOHANG);
3045 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
3047 pcgi = &pt->cgi_list;
3049 /* check all the subprocesses on the cgi list */
3051 /* get the next one first as list may change */
3053 pcgi = &(*pcgi)->cgi_list;
3058 /* finish sending cached headers */
3059 if (cgi->headers_buf)
3062 /* wait for stdout to be drained */
3063 if (cgi->content_length > cgi->content_length_seen)
3066 if (cgi->content_length) {
3067 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3068 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3072 waitpid(n, &status, WNOHANG);
3074 * he's already terminated so no need for kill()
3075 * but we should do the terminated cgi callback
3076 * and close him if he's not already closing
3078 if (n == cgi->pid) {
3079 lwsl_debug("%s: found PID %d on cgi list\n",
3082 if (!cgi->content_length && cgi->explicitly_chunked) {
3084 * well, if he sends chunked... give him 5s after the
3085 * cgi terminated to send buffered
3087 cgi->chunked_grace++;
3093 lws_cgi_kill(cgi->wsi);
3099 /* if not found on the cgi list, as he's one of ours, reap */
3101 lwsl_debug("%s: reading PID %d although no cgi match\n",
3103 waitpid(n, &status, WNOHANG);
3107 /* disable this to confirm timeout cgi cleanup flow */
3109 pcgi = &pt->cgi_list;
3111 /* check all the subprocesses on the cgi list */
3113 /* get the next one first as list may change */
3115 pcgi = &(*pcgi)->cgi_list;
3120 /* we deferred killing him after reaping his PID */
3121 if (cgi->chunked_grace) {
3122 cgi->chunked_grace++;
3123 if (cgi->chunked_grace < 5)
3128 /* finish sending cached headers */
3129 if (cgi->headers_buf)
3132 /* wait for stdout to be drained */
3133 if (cgi->content_length > cgi->content_length_seen)
3136 if (cgi->content_length)
3137 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3138 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3141 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
3143 if (!cgi->content_length) {
3145 * well, if he sends chunked... give him 5s after the
3146 * cgi terminated to send buffered
3148 cgi->chunked_grace++;
3152 lwsl_debug("%s: found PID %d on cgi list\n",
3153 __func__, cgi->pid);
3156 lws_cgi_kill(cgi->wsi);
3163 /* general anti zombie defence */
3164 // n = waitpid(-1, &status, WNOHANG);
3166 // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
3172 #ifdef LWS_NO_EXTENSIONS
3174 lws_set_extension_option(struct lws *wsi, const char *ext_name,
3175 const char *opt_name, const char *opt_val)
3181 #ifdef LWS_WITH_ACCESS_LOG
3183 lws_access_log(struct lws *wsi)
3185 char *p = wsi->access_log.user_agent, ass[512];
3188 if (!wsi->access_log_pending)
3191 if (!wsi->access_log.header_log)
3197 l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
3198 wsi->access_log.header_log,
3199 wsi->access_log.response, wsi->access_log.sent, p);
3201 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
3202 if (write(wsi->vhost->log_fd, ass, l) != l)
3203 lwsl_err("Failed to write log\n");
3205 lwsl_err("%s", ass);
3207 if (wsi->access_log.header_log) {
3208 lws_free(wsi->access_log.header_log);
3209 wsi->access_log.header_log = NULL;
3211 if (wsi->access_log.user_agent) {
3212 lws_free(wsi->access_log.user_agent);
3213 wsi->access_log.user_agent = NULL;
3215 wsi->access_log_pending = 0;
3222 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
3224 const struct lws_vhost *vh = ctx->vhost_list;
3228 cs->rx += vh->conn_stats.rx;
3229 cs->tx += vh->conn_stats.tx;
3230 cs->conn += vh->conn_stats.conn;
3231 cs->trans += vh->conn_stats.trans;
3232 cs->ws_upg += vh->conn_stats.ws_upg;
3233 cs->http2_upg += vh->conn_stats.http2_upg;
3234 cs->rejected += vh->conn_stats.rejected;
3236 vh = vh->vhost_next;
3240 #ifdef LWS_WITH_SERVER_STATUS
3243 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
3245 static const char * const prots[] = {
3254 char *orig = buf, *end = buf + len - 1, first = 1;
3260 buf += lws_snprintf(buf, end - buf,
3261 "{\n \"name\":\"%s\",\n"
3262 " \"port\":\"%d\",\n"
3263 " \"use_ssl\":\"%d\",\n"
3264 " \"sts\":\"%d\",\n"
3265 " \"rx\":\"%llu\",\n"
3266 " \"tx\":\"%llu\",\n"
3267 " \"conn\":\"%lu\",\n"
3268 " \"trans\":\"%lu\",\n"
3269 " \"ws_upg\":\"%lu\",\n"
3270 " \"rejected\":\"%lu\",\n"
3271 " \"http2_upg\":\"%lu\""
3273 vh->name, vh->listen_port,
3274 #ifdef LWS_OPENSSL_SUPPORT
3279 !!(vh->options & LWS_SERVER_OPTION_STS),
3280 vh->conn_stats.rx, vh->conn_stats.tx,
3281 vh->conn_stats.conn, vh->conn_stats.trans,
3282 vh->conn_stats.ws_upg,
3283 vh->conn_stats.rejected,
3284 vh->conn_stats.http2_upg
3287 if (vh->mount_list) {
3288 const struct lws_http_mount *m = vh->mount_list;
3290 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
3293 buf += lws_snprintf(buf, end - buf, ",");
3294 buf += lws_snprintf(buf, end - buf,
3295 "\n {\n \"mountpoint\":\"%s\",\n"
3296 " \"origin\":\"%s%s\",\n"
3297 " \"cache_max_age\":\"%d\",\n"
3298 " \"cache_reuse\":\"%d\",\n"
3299 " \"cache_revalidate\":\"%d\",\n"
3300 " \"cache_intermediaries\":\"%d\"\n"
3303 prots[m->origin_protocol],
3307 m->cache_revalidate,
3308 m->cache_intermediaries);
3310 buf += lws_snprintf(buf, end - buf,
3311 ",\n \"default\":\"%s\"",
3313 buf += lws_snprintf(buf, end - buf, "\n }");
3317 buf += lws_snprintf(buf, end - buf, "\n ]");
3320 if (vh->protocols) {
3324 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
3325 while (n < vh->count_protocols) {
3327 buf += lws_snprintf(buf, end - buf, ",");
3328 buf += lws_snprintf(buf, end - buf,
3330 " \"status\":\"ok\"\n }\n }"
3332 vh->protocols[n].name);
3336 buf += lws_snprintf(buf, end - buf, "\n ]");
3339 buf += lws_snprintf(buf, end - buf, "\n}");
3345 LWS_EXTERN LWS_VISIBLE int
3346 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
3349 char *orig = buf, *end = buf + len - 1, first = 1;
3350 const struct lws_vhost *vh = context->vhost_list;
3351 const struct lws_context_per_thread *pt;
3352 time_t t = time(NULL);
3353 int n, listening = 0, cgi_count = 0;
3354 struct lws_conn_stats cs;
3357 struct lws_cgi * const *pcgi;
3360 #ifdef LWS_USE_LIBUV
3364 buf += lws_snprintf(buf, end - buf, "{ "
3365 "\"version\":\"%s\",\n"
3366 "\"uptime\":\"%ld\",\n",
3367 lws_get_library_version(),
3370 #ifdef LWS_HAVE_GETLOADAVG
3375 m = getloadavg(d, 3);
3376 for (n = 0; n < m; n++) {
3377 buf += lws_snprintf(buf, end - buf,
3378 "\"l%d\":\"%.2f\",\n",
3384 buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
3386 buf += lws_snprintf(buf, end - buf, "{ "
3387 "\"context_uptime\":\"%ld\",\n"
3388 "\"cgi_spawned\":\"%d\",\n"
3389 "\"pt_fd_max\":\"%d\",\n"
3390 "\"ah_pool_max\":\"%d\",\n"
3391 "\"deprecated\":\"%d\",\n"
3392 "\"wsi_alive\":\"%d\",\n",
3393 (unsigned long)(t - context->time_up),
3394 context->count_cgi_spawned,
3395 context->fd_limit_per_thread,
3396 context->max_http_header_pool,
3397 context->deprecated,
3398 context->count_wsi_allocated);
3400 buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
3401 for (n = 0; n < context->count_threads; n++) {
3402 pt = &context->pt[n];
3404 buf += lws_snprintf(buf, end - buf, ",");
3405 buf += lws_snprintf(buf, end - buf,
3407 " \"fds_count\":\"%d\",\n"
3408 " \"ah_pool_inuse\":\"%d\",\n"
3409 " \"ah_wait_list\":\"%d\"\n"
3412 pt->ah_count_in_use,
3413 pt->ah_wait_list_length);
3416 buf += lws_snprintf(buf, end - buf, "]");
3418 buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3421 vh = context->vhost_list;
3423 cs = context->conn_stats;
3424 lws_sum_stats(context, &cs);
3431 buf += lws_json_dump_vhost(vh, buf, end - buf);
3436 vh = vh->vhost_next;
3439 buf += lws_snprintf(buf, end - buf,
3440 "],\n\"listen_wsi\":\"%d\",\n"
3441 " \"rx\":\"%llu\",\n"
3442 " \"tx\":\"%llu\",\n"
3443 " \"conn\":\"%lu\",\n"
3444 " \"trans\":\"%lu\",\n"
3445 " \"ws_upg\":\"%lu\",\n"
3446 " \"rejected\":\"%lu\",\n"
3447 " \"http2_upg\":\"%lu\"",
3449 cs.rx, cs.tx, cs.conn, cs.trans,
3450 cs.ws_upg, cs.rejected, cs.http2_upg);
3453 for (n = 0; n < context->count_threads; n++) {
3454 pt = &context->pt[n];
3455 pcgi = &pt->cgi_list;
3458 pcgi = &(*pcgi)->cgi_list;
3464 buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3467 buf += lws_snprintf(buf, end - buf, "}");
3470 buf += lws_snprintf(buf, end - buf, "]}\n ");
3477 #if defined(LWS_WITH_STATS)
3479 LWS_VISIBLE LWS_EXTERN uint64_t
3480 lws_stats_get(struct lws_context *context, int index)
3482 if (index >= LWSSTATS_SIZE)
3485 return context->lws_stats[index];
3488 LWS_VISIBLE LWS_EXTERN void
3489 lws_stats_log_dump(struct lws_context *context)
3491 struct lws_vhost *v = context->vhost_list;
3494 if (!context->updated)
3497 context->updated = 0;
3500 lwsl_notice("LWS internal statistics dump ----->\n");
3501 lwsl_notice("LWSSTATS_C_CONNECTIONS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_CONNECTIONS));
3502 lwsl_notice("LWSSTATS_C_API_CLOSE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_CLOSE));
3503 lwsl_notice("LWSSTATS_C_API_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_READ));
3504 lwsl_notice("LWSSTATS_C_API_LWS_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_LWS_WRITE));
3505 lwsl_notice("LWSSTATS_C_API_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_WRITE));
3506 lwsl_notice("LWSSTATS_C_WRITE_PARTIALS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITE_PARTIALS));
3507 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_REQ));
3508 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_EFF_REQ));
3509 lwsl_notice("LWSSTATS_C_WRITEABLE_CB: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB));
3510 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_FAILED));
3511 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED));
3512 lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX));
3514 lwsl_notice("LWSSTATS_C_TIMEOUTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_TIMEOUTS));
3515 lwsl_notice("LWSSTATS_C_SERVICE_ENTRY: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SERVICE_ENTRY));
3516 lwsl_notice("LWSSTATS_B_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ));
3517 lwsl_notice("LWSSTATS_B_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE));
3518 lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS));
3519 lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000);
3520 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED))
3521 lwsl_notice(" Avg accept delay: %8llums\n",
3522 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) /
3523 lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000);
3524 lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / 1000);
3525 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX))
3526 lwsl_notice(" Avg accept-rx delay: %8llums\n",
3527 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) /
3528 lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000);
3530 lwsl_notice("LWSSTATS_MS_WRITABLE_DELAY: %8lluus\n",
3531 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY));
3532 lwsl_notice("LWSSTATS_MS_WORST_WRITABLE_DELAY: %8lluus\n",
3533 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WORST_WRITABLE_DELAY));
3534 if (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))
3535 lwsl_notice(" Avg writable delay: %8lluus\n",
3536 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY) /
3537 lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)));
3538 lwsl_notice("Simultaneous SSL restriction: %8d/%d/%d\n", context->simultaneous_ssl,
3539 context->simultaneous_ssl_restriction, context->ssl_gate_accepts);
3541 lwsl_notice("Live wsi: %8d\n", context->count_wsi_allocated);
3543 #if defined(LWS_WITH_STATS)
3544 context->updated = 1;
3550 struct lws_context_per_thread *pt = &context->pt[(int)v->lserv_wsi->tsi];
3551 struct lws_pollfd *pfd;
3553 pfd = &pt->fds[v->lserv_wsi->position_in_fds_table];
3555 lwsl_notice(" Listen port %d actual POLLIN: %d\n",
3556 v->listen_port, (int)pfd->events & LWS_POLLIN);
3562 for (n = 0; n < context->count_threads; n++) {
3563 struct lws_context_per_thread *pt = &context->pt[n];
3567 lwsl_notice("PT %d\n", n + 1);
3571 lwsl_notice(" AH in use / max: %d / %d\n",
3572 pt->ah_count_in_use,
3573 context->max_http_header_pool);
3575 wl = pt->ah_wait_list;
3578 wl = wl->u.hdr.ah_wait_list;
3581 lwsl_notice(" AH wait list count / actual: %d / %d\n",
3582 pt->ah_wait_list_length, m);
3591 lws_stats_atomic_bump(struct lws_context * context,
3592 struct lws_context_per_thread *pt, int index, uint64_t bump)
3595 context->lws_stats[index] += bump;
3596 if (index != LWSSTATS_C_SERVICE_ENTRY)
3597 context->updated = 1;
3602 lws_stats_atomic_max(struct lws_context * context,
3603 struct lws_context_per_thread *pt, int index, uint64_t val)
3606 if (val > context->lws_stats[index]) {
3607 context->lws_stats[index] = val;
3608 context->updated = 1;