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)
68 struct lws_context_per_thread *pt;
74 pt = &wsi->context->pt[(int)wsi->tsi];
76 /* Protocol user data may be allocated either internally by lws
77 * or by specified the user.
78 * We should only free what we allocated. */
79 if (wsi->protocol && wsi->protocol->per_session_data_size &&
80 wsi->user_space && !wsi->user_space_externally_allocated)
81 lws_free(wsi->user_space);
83 lws_free_set_NULL(wsi->rxflow_buffer);
84 lws_free_set_NULL(wsi->trunc_alloc);
86 /* we may not have an ah, but may be on the waiting list... */
87 lwsl_info("ah det due to close\n");
88 /* we're closing, losing some rx is OK */
89 lws_header_table_force_to_detachable_state(wsi);
90 lws_header_table_detach(wsi, 0);
93 for (n = 0; n < wsi->context->max_http_header_pool; n++) {
94 if (pt->ah_pool[n].in_use &&
95 pt->ah_pool[n].wsi == wsi) {
96 lwsl_err("%s: ah leak: wsi %p\n", __func__, wsi);
97 pt->ah_pool[n].in_use = 0;
98 pt->ah_pool[n].wsi = NULL;
99 pt->ah_count_in_use--;
104 /* since we will destroy the wsi, make absolutely sure now */
106 lws_ssl_remove_wsi_from_buffered_list(wsi);
107 lws_remove_from_timeout_list(wsi);
109 wsi->context->count_wsi_allocated--;
110 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
111 wsi->context->count_wsi_allocated);
117 lws_remove_from_timeout_list(struct lws *wsi)
119 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
121 if (!wsi->timeout_list_prev) /* ie, not part of the list */
125 /* if we have a next guy, set his prev to our prev */
126 if (wsi->timeout_list)
127 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
128 /* set our prev guy to our next guy instead of us */
129 *wsi->timeout_list_prev = wsi->timeout_list;
131 /* we're out of the list, we should not point anywhere any more */
132 wsi->timeout_list_prev = NULL;
133 wsi->timeout_list = NULL;
138 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
140 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
143 if (secs == LWS_TO_KILL_SYNC) {
144 lws_remove_from_timeout_list(wsi);
145 lwsl_debug("synchronously killing %p\n", wsi);
146 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
154 if (reason && !wsi->timeout_list_prev) {
155 /* our next guy is current first guy */
156 wsi->timeout_list = pt->timeout_list;
157 /* if there is a next guy, set his prev ptr to our next ptr */
158 if (wsi->timeout_list)
159 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
160 /* our prev ptr is first ptr */
161 wsi->timeout_list_prev = &pt->timeout_list;
162 /* set the first guy to be us */
163 *wsi->timeout_list_prev = wsi;
166 lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
167 wsi->pending_timeout_limit = now + secs;
168 wsi->pending_timeout = reason;
173 lws_remove_from_timeout_list(wsi);
177 lws_remove_child_from_any_parent(struct lws *wsi)
185 /* detach ourselves from parent's child list */
186 pwsi = &wsi->parent->child_list;
189 lwsl_info("%s: detach %p from parent %p\n",
190 __func__, wsi, wsi->parent);
192 if (wsi->parent->protocol)
193 wsi->parent->protocol->callback(wsi,
194 LWS_CALLBACK_CHILD_CLOSING,
195 wsi->parent->user_space, wsi, 0);
197 *pwsi = wsi->sibling_list;
201 pwsi = &(*pwsi)->sibling_list;
204 lwsl_err("%s: failed to detach from parent\n", __func__);
210 lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)
212 // if (wsi->protocol == p)
214 const struct lws_protocols *vp = wsi->vhost->protocols, *vpo;
217 wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,
218 wsi->user_space, NULL, 0);
219 if (!wsi->user_space_externally_allocated)
220 lws_free_set_NULL(wsi->user_space);
222 lws_same_vh_protocol_remove(wsi);
228 if (lws_ensure_user_space(wsi))
231 if (p > vp && p < &vp[wsi->vhost->count_protocols])
232 lws_same_vh_protocol_insert(wsi, p - vp);
234 int n = wsi->vhost->count_protocols;
240 if (p->name && vp->name && !strcmp(p->name, vp->name)) {
242 lws_same_vh_protocol_insert(wsi, vp - vpo);
248 lwsl_err("%s: protocol %p is not in vhost %s protocols list\n",
249 __func__, p, wsi->vhost->name);
252 if (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,
253 wsi->user_space, NULL, 0))
260 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
262 struct lws_context_per_thread *pt;
263 struct lws *wsi1, *wsi2;
264 struct lws_context *context;
265 struct lws_tokens eff_buf;
268 lwsl_debug("%s: %p\n", __func__, wsi);
274 #if defined(LWS_WITH_ESP8266)
275 if (wsi->premature_rx)
276 lws_free(wsi->premature_rx);
278 if (wsi->pending_send_completion && !wsi->close_is_pending_send_completion) {
279 lwsl_notice("delaying close\n");
280 wsi->close_is_pending_send_completion = 1;
285 /* we're closing, losing some rx is OK */
286 lws_header_table_force_to_detachable_state(wsi);
288 context = wsi->context;
289 pt = &context->pt[(int)wsi->tsi];
290 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_CLOSE, 1);
292 /* if we have children, close them first */
293 if (wsi->child_list) {
294 wsi2 = wsi->child_list;
296 //lwsl_notice("%s: closing %p: close child %p\n",
297 // __func__, wsi, wsi2);
298 wsi1 = wsi2->sibling_list;
299 //lwsl_notice("%s: closing %p: next sibling %p\n",
300 // __func__, wsi2, wsi1);
302 /* stop it doing shutdown processing */
303 wsi2->socket_is_permanently_unusable = 1;
304 lws_close_free_wsi(wsi2, reason);
307 wsi->child_list = NULL;
310 if (wsi->mode == LWSCM_RAW_FILEDESC) {
311 lws_remove_child_from_any_parent(wsi);
312 remove_wsi_socket_from_fds(wsi);
313 wsi->protocol->callback(wsi,
314 LWS_CALLBACK_RAW_CLOSE_FILE,
315 wsi->user_space, NULL, 0);
320 if (wsi->mode == LWSCM_CGI) {
321 /* we are not a network connection, but a handler for CGI io */
322 if (wsi->parent && wsi->parent->cgi)
323 /* end the binding between us and master */
324 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
325 wsi->socket_is_permanently_unusable = 1;
327 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
328 goto just_kill_connection;
332 struct lws_cgi **pcgi = &pt->cgi_list;
333 /* remove us from the cgi list */
334 lwsl_debug("%s: remove cgi %p from list\n", __func__, wsi->cgi);
336 if (*pcgi == wsi->cgi) {
337 /* drop us from the pt cgi list */
338 *pcgi = (*pcgi)->cgi_list;
341 pcgi = &(*pcgi)->cgi_list;
343 if (wsi->cgi->headers_buf) {
344 lwsl_debug("close: freed cgi headers\n");
345 lws_free_set_NULL(wsi->cgi->headers_buf);
347 /* we have a cgi going, we must kill it */
348 wsi->cgi->being_closed = 1;
353 #if !defined(LWS_NO_CLIENT)
354 if (wsi->mode == LWSCM_HTTP_CLIENT ||
355 wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
356 wsi->mode == LWSCM_WSCL_WAITING_PROXY_REPLY ||
357 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE ||
358 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE2 ||
359 wsi->mode == LWSCM_WSCL_WAITING_SSL ||
360 wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
361 wsi->mode == LWSCM_WSCL_WAITING_EXTENSION_CONNECT ||
362 wsi->mode == LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY ||
363 wsi->mode == LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY ||
364 wsi->mode == LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY)
365 if (wsi->u.hdr.stash)
366 lws_free_set_NULL(wsi->u.hdr.stash);
369 if (wsi->mode == LWSCM_RAW) {
370 wsi->protocol->callback(wsi,
371 LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0);
372 wsi->socket_is_permanently_unusable = 1;
373 goto just_kill_connection;
376 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
377 wsi->u.http.fop_fd != NULL) {
378 lws_vfs_file_close(&wsi->u.http.fop_fd);
379 wsi->vhost->protocols->callback(wsi,
380 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
381 wsi->told_user_closed = 1;
383 if (wsi->socket_is_permanently_unusable ||
384 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
385 wsi->state == LWSS_SHUTDOWN)
386 goto just_kill_connection;
388 wsi->state_pre_close = wsi->state;
390 switch (wsi->state_pre_close) {
391 case LWSS_DEAD_SOCKET:
394 /* we tried the polite way... */
395 case LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION:
396 case LWSS_AWAITING_CLOSE_ACK:
397 goto just_kill_connection;
399 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
400 if (wsi->trunc_len) {
401 lws_callback_on_writable(wsi);
404 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
405 goto just_kill_connection;
407 if (wsi->trunc_len) {
408 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
409 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
410 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
416 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
417 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
418 goto just_kill_connection;
420 if (wsi->mode == LWSCM_HTTP_SERVING) {
422 wsi->vhost->protocols->callback(wsi,
423 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
424 wsi->user_space, NULL, 0);
425 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
426 wsi->user_space, NULL, 0);
427 wsi->told_user_closed = 1;
429 if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
430 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
431 wsi->user_space, NULL, 0);
432 wsi->told_user_closed = 1;
436 * are his extensions okay with him closing? Eg he might be a mux
437 * parent and just his ch1 aspect is closing?
440 if (lws_ext_cb_active(wsi,
441 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
442 lwsl_ext("extension vetoed close\n");
447 * flush any tx pending from extensions, since we may send close packet
448 * if there are problems with send, just nuke the connection
453 eff_buf.token = NULL;
454 eff_buf.token_len = 0;
456 /* show every extension the new incoming data */
458 m = lws_ext_cb_active(wsi,
459 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
461 lwsl_ext("Extension reports fatal error\n");
462 goto just_kill_connection;
466 * at least one extension told us he has more
467 * to spill, so we will go around again after
471 /* assuming they left us something to send, send it */
473 if (eff_buf.token_len)
474 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
475 eff_buf.token_len) !=
477 lwsl_debug("close: ext spill failed\n");
478 goto just_kill_connection;
483 * signal we are closing, lws_write will
484 * add any necessary version-specific stuff. If the write fails,
485 * no worries we are closing anyway. If we didn't initiate this
486 * close, then our state has been changed to
487 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
489 * Likewise if it's a second call to close this connection after we
490 * sent the close indication to the peer already, we are in state
491 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
494 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
495 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
496 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
497 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
498 lwsl_debug("sending close indication...\n");
500 /* if no prepared close reason, use 1000 and no aux data */
501 if (!wsi->u.ws.close_in_ping_buffer_len) {
502 wsi->u.ws.close_in_ping_buffer_len = 2;
503 wsi->u.ws.ping_payload_buf[LWS_PRE] =
504 (reason >> 8) & 0xff;
505 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
509 #if defined (LWS_WITH_ESP8266)
510 wsi->close_is_pending_send_completion = 1;
513 lwsl_debug("waiting for chance to send close\n");
514 wsi->waiting_to_send_close_frame = 1;
515 wsi->state = LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION;
516 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 2);
517 lws_callback_on_writable(wsi);
522 just_kill_connection:
524 lws_remove_child_from_any_parent(wsi);
527 /* manage the vhost same protocol list entry */
529 if (wsi->same_vh_protocol_prev) { // we are on the vh list
531 // make guy who pointed to us, point to what our next was pointing to
532 *wsi->same_vh_protocol_prev = wsi->same_vh_protocol_next;
534 // if we had a next guy...
535 if (wsi->same_vh_protocol_next)
536 // have him point back to our prev
537 wsi->same_vh_protocol_next->same_vh_protocol_prev =
538 wsi->same_vh_protocol_prev;
544 * Testing with ab shows that we have to stage the socket close when
545 * the system is under stress... shutdown any further TX, change the
546 * state to one that won't emit anything more, and wait with a timeout
547 * for the POLLIN to show a zero-size rx before coming back and doing
550 if (wsi->mode != LWSCM_RAW &&
551 !(wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) &&
552 wsi->state != LWSS_SHUTDOWN &&
553 wsi->state != LWSS_CLIENT_UNCONNECTED &&
554 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
555 !wsi->socket_is_permanently_unusable) {
556 #ifdef LWS_OPENSSL_SUPPORT
557 if (lws_is_ssl(wsi) && wsi->ssl)
559 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);
560 n = SSL_shutdown(wsi->ssl);
561 if (n == 1) /* If finished the SSL shutdown, then do socket shutdown, else need to retry SSL shutdown */
562 n = shutdown(wsi->desc.sockfd, SHUT_WR);
564 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
567 int shutdown_error = SSL_get_error(wsi->ssl, n);
568 lwsl_debug("SSL_shutdown returned %d, SSL_get_error: %d\n", n, shutdown_error);
569 if (shutdown_error == SSL_ERROR_WANT_READ) {
570 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
572 } else if (shutdown_error == SSL_ERROR_WANT_WRITE) {
573 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLOUT);
575 } else { // actual error occurred, just close the connection
576 n = shutdown(wsi->desc.sockfd, SHUT_WR);
583 lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, (int)(long)wsi->desc.sockfd, wsi->state);
584 n = shutdown(wsi->desc.sockfd, SHUT_WR);
587 lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
589 // This causes problems with disconnection when the events are half closing connection
590 // FD_READ | FD_CLOSE (33)
591 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP32)
592 /* libuv: no event available to guarantee completion */
593 if (!LWS_LIBUV_ENABLED(context)) {
595 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
596 wsi->state = LWSS_SHUTDOWN;
597 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
598 context->timeout_secs);
606 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
607 wsi, wsi->desc.sockfd);
609 #ifdef LWS_WITH_HTTP_PROXY
611 lws_rewrite_destroy(wsi->rw);
616 * we won't be servicing or receiving anything further from this guy
617 * delete socket from the internal poll list if still present
619 lws_ssl_remove_wsi_from_buffered_list(wsi);
621 lws_remove_from_timeout_list(wsi);
623 /* checking return redundant since we anyway close */
624 if (wsi->desc.sockfd != LWS_SOCK_INVALID)
625 remove_wsi_socket_from_fds(wsi);
627 lws_same_vh_protocol_remove(wsi);
629 #if defined(LWS_WITH_ESP8266)
630 espconn_disconnect(wsi->desc.sockfd);
633 wsi->state = LWSS_DEAD_SOCKET;
635 lws_free_set_NULL(wsi->rxflow_buffer);
636 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
637 wsi->mode == LWSCM_WS_SERVING ||
638 wsi->mode == LWSCM_WS_CLIENT) {
640 if (wsi->u.ws.rx_draining_ext) {
641 struct lws **w = &pt->rx_draining_ext_list;
643 wsi->u.ws.rx_draining_ext = 0;
644 /* remove us from context draining ext list */
647 *w = wsi->u.ws.rx_draining_ext_list;
650 w = &((*w)->u.ws.rx_draining_ext_list);
652 wsi->u.ws.rx_draining_ext_list = NULL;
655 if (wsi->u.ws.tx_draining_ext) {
656 struct lws **w = &pt->tx_draining_ext_list;
658 wsi->u.ws.tx_draining_ext = 0;
659 /* remove us from context draining ext list */
662 *w = wsi->u.ws.tx_draining_ext_list;
665 w = &((*w)->u.ws.tx_draining_ext_list);
667 wsi->u.ws.tx_draining_ext_list = NULL;
669 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
671 if (wsi->trunc_alloc)
672 /* not going to be completed... nuke it */
673 lws_free_set_NULL(wsi->trunc_alloc);
675 wsi->u.ws.ping_payload_len = 0;
676 wsi->u.ws.ping_pending_flag = 0;
679 /* tell the user it's all over for this guy */
681 if (wsi->mode != LWSCM_RAW && wsi->protocol && wsi->protocol->callback &&
682 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
683 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
684 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
685 (wsi->state_pre_close == LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION) ||
686 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
687 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
688 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
690 if (wsi->user_space) {
691 lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s\n", __func__, wsi, wsi->protocol->name);
692 wsi->protocol->callback(wsi,
693 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
694 wsi->user_space, NULL, 0);
696 lwsl_debug("calling back CLOSED\n");
697 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
698 wsi->user_space, NULL, 0);
699 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
700 lwsl_debug("calling back CLOSED_HTTP\n");
701 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
702 wsi->user_space, NULL, 0 );
703 } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
704 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
705 !wsi->already_did_cce) {
706 wsi->vhost->protocols[0].callback(wsi,
707 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
708 wsi->user_space, NULL, 0);
710 lwsl_debug("not calling back closed mode=%d state=%d\n",
711 wsi->mode, wsi->state_pre_close);
713 /* deallocate any active extension contexts */
715 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
716 lwsl_warn("extension destruction failed\n");
718 * inform all extensions in case they tracked this guy out of band
719 * even though not active on him specifically
721 if (lws_ext_cb_all_exts(context, wsi,
722 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
723 lwsl_warn("ext destroy wsi failed\n");
727 wsi->socket_is_permanently_unusable = 1;
730 if (!wsi->parent_carries_io)
731 if (LWS_LIBUV_ENABLED(context)) {
733 lwsl_debug("%s: stopping listner libuv poll\n", __func__);
734 uv_poll_stop(&wsi->w_read.uv_watcher);
736 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
737 /* libuv has to do his own close handle processing asynchronously */
738 lws_libuv_closehandle(wsi);
744 lws_close_free_wsi_final(wsi);
748 lws_close_free_wsi_final(struct lws *wsi)
752 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->desc.sockfd)) {
754 //lwsl_err("*** closing sockfd %d\n", wsi->desc.sockfd);
755 n = compatible_close(wsi->desc.sockfd);
757 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
760 compatible_close(wsi->desc.sockfd);
763 wsi->desc.sockfd = LWS_SOCK_INVALID;
766 /* outermost destroy notification for wsi (user_space still intact) */
767 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
768 wsi->user_space, NULL, 0);
772 for (n = 0; n < 6; n++) {
773 if (wsi->cgi->pipe_fds[n / 2][n & 1] == 0)
774 lwsl_err("ZERO FD IN CGI CLOSE");
776 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
777 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
787 LWS_VISIBLE LWS_EXTERN const char *
788 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
790 int n = 0, sl = strlen(name);
792 while (lws_hdr_copy_fragment(wsi, buf, len,
793 WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
795 if (!strncmp(buf, name, sl))
804 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
806 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
810 ipv6 = LWS_IPV6_ENABLED(vh);
814 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
818 #ifndef LWS_PLAT_OPTEE
821 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
822 int name_len, char *rip, int rip_len)
825 struct addrinfo ai, *res;
826 struct sockaddr_in addr4;
830 addr4.sin_family = AF_UNSPEC;
833 if (LWS_IPV6_ENABLED(vh)) {
834 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
835 lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
839 // Strip off the IPv4 to IPv6 header if one exists
840 if (strncmp(rip, "::ffff:", 7) == 0)
841 memmove(rip, rip + 7, strlen(rip) - 6);
843 getnameinfo((struct sockaddr *)ads,
844 sizeof(struct sockaddr_in6), name,
845 name_len, NULL, 0, 0);
851 struct addrinfo *result;
853 memset(&ai, 0, sizeof ai);
854 ai.ai_family = PF_UNSPEC;
855 ai.ai_socktype = SOCK_STREAM;
856 ai.ai_flags = AI_CANONNAME;
857 #if !defined(LWS_WITH_ESP32)
858 if (getnameinfo((struct sockaddr *)ads,
859 sizeof(struct sockaddr_in),
860 name, name_len, NULL, 0, 0))
864 if (getaddrinfo(name, NULL, &ai, &result))
868 while (addr4.sin_family == AF_UNSPEC && res) {
869 switch (res->ai_family) {
871 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
872 addr4.sin_family = AF_INET;
878 freeaddrinfo(result);
881 if (addr4.sin_family == AF_UNSPEC)
884 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
902 LWS_VISIBLE const char *
903 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
908 struct sockaddr_in6 sin6;
910 struct sockaddr_in sin4;
914 if (wsi->parent_carries_io)
918 if (LWS_IPV6_ENABLED(wsi->vhost)) {
932 if (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {
933 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
937 return lws_plat_inet_ntop(af, q, name, namelen);
939 #if defined(LWS_WITH_ESP8266)
940 return lws_plat_get_peer_simple(wsi, name, namelen);
949 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
950 int name_len, char *rip, int rip_len)
952 #ifndef LWS_PLAT_OPTEE
956 struct sockaddr_in6 sin6;
958 struct sockaddr_in sin4;
959 struct lws_context *context = wsi->context;
966 lws_latency_pre(context, wsi);
969 if (LWS_IPV6_ENABLED(wsi->vhost)) {
979 if (getpeername(fd, p, &len) < 0) {
980 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
984 ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
987 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
1000 lws_context_user(struct lws_context *context)
1002 return context->user_space;
1005 LWS_VISIBLE struct lws_vhost *
1006 lws_vhost_get(struct lws *wsi)
1011 LWS_VISIBLE struct lws_vhost *
1012 lws_get_vhost(struct lws *wsi)
1017 LWS_VISIBLE const struct lws_protocols *
1018 lws_protocol_get(struct lws *wsi)
1020 return wsi->protocol;
1023 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1024 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
1028 for (n = 0; n < vh->count_protocols; n++)
1029 if (!strcmp(name, vh->protocols[n].name))
1030 return &vh->protocols[n];
1036 lws_callback_all_protocol(struct lws_context *context,
1037 const struct lws_protocols *protocol, int reason)
1039 struct lws_context_per_thread *pt = &context->pt[0];
1040 unsigned int n, m = context->count_threads;
1044 for (n = 0; n < pt->fds_count; n++) {
1045 wsi = wsi_from_fd(context, pt->fds[n].fd);
1048 if (wsi->protocol == protocol)
1049 protocol->callback(wsi, reason, wsi->user_space,
1059 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
1060 const struct lws_protocols *protocol, int reason)
1062 struct lws_context *context = vh->context;
1063 struct lws_context_per_thread *pt = &context->pt[0];
1064 unsigned int n, m = context->count_threads;
1068 for (n = 0; n < pt->fds_count; n++) {
1069 wsi = wsi_from_fd(context, pt->fds[n].fd);
1072 if (wsi->vhost == vh && wsi->protocol == protocol)
1073 protocol->callback(wsi, reason, wsi->user_space,
1082 LWS_VISIBLE LWS_EXTERN int
1083 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
1087 for (n = 0; n < wsi->vhost->count_protocols; n++)
1088 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
1094 LWS_VISIBLE LWS_EXTERN void
1095 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)
1097 context->fops = fops;
1100 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1101 lws_vfs_tell(lws_fop_fd_t fop_fd)
1106 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1107 lws_vfs_get_length(lws_fop_fd_t fop_fd)
1112 LWS_VISIBLE LWS_EXTERN uint32_t
1113 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd)
1115 return fop_fd->mod_time;
1118 LWS_VISIBLE lws_fileofs_t
1119 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1122 lwsl_debug("%s: seeking to %ld, len %ld\n", __func__, (long)offset, (long)fop_fd->len);
1123 ofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);
1124 lwsl_debug("%s: result %ld, fop_fd pos %ld\n", __func__, (long)ofs, (long)fop_fd->pos);
1129 LWS_VISIBLE lws_fileofs_t
1130 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1132 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len + fop_fd->pos + offset);
1136 const struct lws_plat_file_ops *
1137 lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,
1140 const struct lws_plat_file_ops *pf;
1141 const char *p = vfs_path;
1146 /* no non-platform fops, just use that */
1152 * scan the vfs path looking for indications we are to be
1153 * handled by a specific fops
1161 /* the first one is always platform fops, so skip */
1165 while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {
1166 if (p >= vfs_path + pf->fi[n].len)
1167 if (!strncmp(p - (pf->fi[n].len - 1),
1169 pf->fi[n].len - 1)) {
1184 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
1185 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
1186 lws_fop_flags_t *flags)
1188 const char *vpath = "";
1189 const struct lws_plat_file_ops *selected = lws_vfs_select_fops(
1190 fops, vfs_path, &vpath);
1192 return selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);
1197 * lws_now_secs() - seconds since 1970-1-1
1200 LWS_VISIBLE LWS_EXTERN unsigned long
1205 gettimeofday(&tv, NULL);
1214 lws_get_socket_fd(struct lws *wsi)
1216 return wsi->desc.sockfd;
1223 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
1224 int ret, int completed)
1226 unsigned long long u;
1229 u = time_in_microseconds();
1232 wsi->latency_start = u;
1233 if (!wsi->action_start)
1234 wsi->action_start = u;
1238 if (wsi->action_start == wsi->latency_start)
1240 "Completion first try lat %lluus: %p: ret %d: %s\n",
1241 u - wsi->latency_start,
1242 (void *)wsi, ret, action);
1245 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1246 u - wsi->action_start,
1247 u - wsi->latency_start,
1248 (void *)wsi, ret, action);
1249 wsi->action_start = 0;
1251 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1252 u - wsi->latency_start, (void *)wsi, ret, action);
1254 if (u - wsi->latency_start > context->worst_latency) {
1255 context->worst_latency = u - wsi->latency_start;
1256 strcpy(context->worst_latency_info, buf);
1258 lwsl_latency("%s", buf);
1263 lws_rx_flow_control(struct lws *wsi, int enable)
1265 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1268 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1269 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1275 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1276 const struct lws_protocols *protocol)
1278 const struct lws_context_per_thread *pt = &context->pt[0];
1280 unsigned int n, m = context->count_threads;
1283 for (n = 0; n < pt->fds_count; n++) {
1284 wsi = wsi_from_fd(context, pt->fds[n].fd);
1287 if (wsi->protocol == protocol)
1288 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1294 LWS_VISIBLE extern const char *
1295 lws_canonical_hostname(struct lws_context *context)
1297 return (const char *)context->canonical_hostname;
1300 int user_callback_handle_rxflow(lws_callback_function callback_function,
1302 enum lws_callback_reasons reason, void *user,
1303 void *in, size_t len)
1307 n = callback_function(wsi, reason, user, in, len);
1309 n = _lws_rx_flow_control(wsi);
1314 #if defined(LWS_WITH_ESP8266)
1316 #define strchr ets_strchr
1320 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1322 #if !defined(LWS_WITH_ESP8266)
1324 char authstring[96];
1329 /* we have to deal with a possible redundant leading http:// */
1330 if (!strncmp(proxy, "http://", 7))
1333 p = strchr(proxy, '@');
1334 if (p) { /* auth is around */
1336 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1339 strncpy(authstring, proxy, p - proxy);
1340 // null termination not needed on input
1341 if (lws_b64_encode_string(authstring, (p - proxy),
1342 vhost->proxy_basic_auth_token,
1343 sizeof vhost->proxy_basic_auth_token) < 0)
1346 lwsl_info(" Proxy auth in use\n");
1350 vhost->proxy_basic_auth_token[0] = '\0';
1352 strncpy(vhost->http_proxy_address, proxy,
1353 sizeof(vhost->http_proxy_address) - 1);
1354 vhost->http_proxy_address[
1355 sizeof(vhost->http_proxy_address) - 1] = '\0';
1357 p = strchr(vhost->http_proxy_address, ':');
1358 if (!p && !vhost->http_proxy_port) {
1359 lwsl_err("http_proxy needs to be ads:port\n");
1365 vhost->http_proxy_port = atoi(p + 1);
1369 lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1370 vhost->http_proxy_port);
1375 lwsl_err("proxy auth too long\n");
1380 #if defined(LWS_WITH_SOCKS5)
1382 lws_set_socks(struct lws_vhost *vhost, const char *socks)
1384 #if !defined(LWS_WITH_ESP8266)
1385 char *p_at, *p_colon;
1392 vhost->socks_user[0] = '\0';
1393 vhost->socks_password[0] = '\0';
1395 p_at = strchr(socks, '@');
1396 if (p_at) { /* auth is around */
1397 if ((unsigned int)(p_at - socks) > (sizeof(user)
1398 + sizeof(password) - 2)) {
1399 lwsl_err("Socks auth too long\n");
1403 p_colon = strchr(socks, ':');
1405 if ((unsigned int)(p_colon - socks) > (sizeof(user)
1407 lwsl_err("Socks user too long\n");
1410 if ((unsigned int)(p_at - p_colon) > (sizeof(password)
1412 lwsl_err("Socks password too long\n");
1416 strncpy(vhost->socks_user, socks, p_colon - socks);
1417 strncpy(vhost->socks_password, p_colon + 1,
1418 p_at - (p_colon + 1));
1420 lwsl_info(" Socks auth, user: %s, password: %s\n",
1421 vhost->socks_user, vhost->socks_password );
1426 strncpy(vhost->socks_proxy_address, socks,
1427 sizeof(vhost->socks_proxy_address) - 1);
1428 vhost->socks_proxy_address[sizeof(vhost->socks_proxy_address) - 1]
1431 p_colon = strchr(vhost->socks_proxy_address, ':');
1432 if (!p_colon && !vhost->socks_proxy_port) {
1433 lwsl_err("socks_proxy needs to be address:port\n");
1438 vhost->socks_proxy_port = atoi(p_colon + 1);
1442 lwsl_info(" Socks %s:%u\n", vhost->socks_proxy_address,
1443 vhost->socks_proxy_port);
1453 LWS_VISIBLE const struct lws_protocols *
1454 lws_get_protocol(struct lws *wsi)
1456 return wsi->protocol;
1460 lws_is_final_fragment(struct lws *wsi)
1462 lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1463 wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1464 (long)wsi->u.ws.rx_draining_ext);
1465 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1469 lws_is_first_fragment(struct lws *wsi)
1471 return wsi->u.ws.first_fragment;
1474 LWS_VISIBLE unsigned char
1475 lws_get_reserved_bits(struct lws *wsi)
1477 return wsi->u.ws.rsv;
1481 lws_ensure_user_space(struct lws *wsi)
1483 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1487 /* allocate the per-connection user memory (if any) */
1489 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1490 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1491 if (wsi->user_space == NULL) {
1492 lwsl_err("Out of memory for conn user space\n");
1496 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1497 __func__, wsi, (long)wsi->protocol->per_session_data_size,
1503 lwsl_timestamp(int level, char *p, int len)
1505 #ifndef LWS_PLAT_OPTEE
1506 time_t o_now = time(NULL);
1507 unsigned long long now;
1508 struct tm *ptm = NULL;
1516 ptm = localtime(&o_now);
1518 if (localtime_r(&o_now, &tm))
1523 for (n = 0; n < LLL_COUNT; n++) {
1524 if (level != (1 << n))
1526 now = time_in_microseconds() / 100;
1528 n = lws_snprintf(p, len,
1529 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1530 ptm->tm_year + 1900,
1536 (int)(now % 10000), log_level_names[n]);
1538 n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1539 (unsigned long long) now / 10000,
1540 (int)(now % 10000), log_level_names[n]);
1547 #ifndef LWS_PLAT_OPTEE
1548 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1550 #if !defined(LWS_WITH_ESP8266)
1553 lwsl_timestamp(level, buf, sizeof(buf));
1554 fprintf(stderr, "%s%s", buf, line);
1559 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1561 #if defined(LWS_WITH_ESP8266)
1568 if (!(log_level & filter))
1571 n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1573 #if defined(LWS_WITH_ESP8266)
1574 buf[sizeof(buf) - 1] = '\0';
1576 /* vnsprintf returns what it would have written, even if truncated */
1577 if (n > sizeof(buf) - 1)
1578 n = sizeof(buf) - 1;
1583 lwsl_emit(filter, buf);
1586 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1590 va_start(ap, format);
1591 _lws_logv(filter, format, ap);
1595 LWS_VISIBLE void lws_set_log_level(int level,
1596 void (*func)(int level, const char *line))
1603 LWS_VISIBLE int lwsl_visible(int level)
1605 return log_level & level;
1609 lws_is_ssl(struct lws *wsi)
1611 #ifdef LWS_OPENSSL_SUPPORT
1612 return wsi->use_ssl;
1619 #ifdef LWS_OPENSSL_SUPPORT
1621 lws_get_ssl(struct lws *wsi)
1628 lws_partial_buffered(struct lws *wsi)
1630 return !!wsi->trunc_len;
1633 void lws_set_protocol_write_pending(struct lws *wsi,
1634 enum lws_pending_protocol_send pend)
1636 lwsl_info("setting pps %d\n", pend);
1639 lwsl_err("pps overwrite\n");
1641 lws_rx_flow_control(wsi, 0);
1642 lws_callback_on_writable(wsi);
1646 lws_get_peer_write_allowance(struct lws *wsi)
1648 #ifdef LWS_USE_HTTP2
1649 /* only if we are using HTTP2 on this connection */
1650 if (wsi->mode != LWSCM_HTTP2_SERVING)
1652 /* user is only interested in how much he can send, or that he can't */
1653 if (wsi->u.http2.tx_credit <= 0)
1656 return wsi->u.http2.tx_credit;
1664 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1666 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1667 memset(&wsi->u, 0, sizeof(wsi->u));
1671 LWS_VISIBLE struct lws_plat_file_ops *
1672 lws_get_fops(struct lws_context *context)
1674 return (struct lws_plat_file_ops *)context->fops;
1677 LWS_VISIBLE LWS_EXTERN struct lws_context *
1678 lws_get_context(const struct lws *wsi)
1680 return wsi->context;
1683 LWS_VISIBLE LWS_EXTERN int
1684 lws_get_count_threads(struct lws_context *context)
1686 return context->count_threads;
1689 LWS_VISIBLE LWS_EXTERN void *
1690 lws_wsi_user(struct lws *wsi)
1692 return wsi->user_space;
1695 LWS_VISIBLE LWS_EXTERN void
1696 lws_set_wsi_user(struct lws *wsi, void *data)
1698 if (wsi->user_space_externally_allocated)
1699 wsi->user_space = data;
1701 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1705 LWS_VISIBLE LWS_EXTERN struct lws *
1706 lws_get_parent(const struct lws *wsi)
1711 LWS_VISIBLE LWS_EXTERN struct lws *
1712 lws_get_child(const struct lws *wsi)
1714 return wsi->child_list;
1717 LWS_VISIBLE LWS_EXTERN void
1718 lws_set_parent_carries_io(struct lws *wsi)
1720 wsi->parent_carries_io = 1;
1723 LWS_VISIBLE LWS_EXTERN void *
1724 lws_get_opaque_parent_data(const struct lws *wsi)
1726 return wsi->opaque_parent_data;
1729 LWS_VISIBLE LWS_EXTERN void
1730 lws_set_opaque_parent_data(struct lws *wsi, void *data)
1732 wsi->opaque_parent_data = data;
1735 LWS_VISIBLE LWS_EXTERN int
1736 lws_get_child_pending_on_writable(const struct lws *wsi)
1738 return wsi->parent_pending_cb_on_writable;
1741 LWS_VISIBLE LWS_EXTERN void
1742 lws_clear_child_pending_on_writable(struct lws *wsi)
1744 wsi->parent_pending_cb_on_writable = 0;
1747 LWS_VISIBLE LWS_EXTERN int
1748 lws_get_close_length(struct lws *wsi)
1750 return wsi->u.ws.close_in_ping_buffer_len;
1753 LWS_VISIBLE LWS_EXTERN unsigned char *
1754 lws_get_close_payload(struct lws *wsi)
1756 return &wsi->u.ws.ping_payload_buf[LWS_PRE];
1759 LWS_VISIBLE LWS_EXTERN void
1760 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1761 unsigned char *buf, size_t len)
1763 unsigned char *p, *start;
1764 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1766 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1768 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1770 *p++ = (((int)status) >> 8) & 0xff;
1771 *p++ = ((int)status) & 0xff;
1774 while (len-- && p < start + budget)
1777 wsi->u.ws.close_in_ping_buffer_len = p - start;
1781 _lws_rx_flow_control(struct lws *wsi)
1783 struct lws *wsic = wsi->child_list;
1785 /* if he has children, do those if they were changed */
1787 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1788 _lws_rx_flow_control(wsic);
1790 wsic = wsic->sibling_list;
1793 /* there is no pending change */
1794 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1795 // lwsl_debug("%s: no pending change\n", __func__);
1799 /* stuff is still buffered, not ready to really accept new input */
1800 if (wsi->rxflow_buffer) {
1801 /* get ourselves called back to deal with stashed buffer */
1802 lws_callback_on_writable(wsi);
1806 /* pending is cleared, we can change rxflow state */
1808 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1810 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1811 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1813 /* adjust the pollfd for this wsi */
1815 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1816 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1817 lwsl_info("%s: fail\n", __func__);
1821 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1828 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1830 static const unsigned char e0f4[] = {
1831 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1832 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1833 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1834 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1835 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1836 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1837 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1838 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1839 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1840 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1841 0x80 | ((4 - 1) << 2) | 1, /* ea */
1842 0x80 | ((4 - 1) << 2) | 1, /* eb */
1843 0x80 | ((4 - 1) << 2) | 1, /* ec */
1844 0x80 | ((2 - 1) << 2) | 1, /* ed */
1845 0x80 | ((4 - 1) << 2) | 1, /* ee */
1846 0x80 | ((4 - 1) << 2) | 1, /* ef */
1847 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1848 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1849 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1850 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1851 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1854 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1855 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1857 unsigned char s = *state;
1860 unsigned char c = *buf++;
1864 if (c < 0xc2 || c > 0xf4)
1867 s = 0x80 | ((4 - 1) << 2);
1872 if (c < (s & 0xf0) ||
1873 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1875 s = e0f4[21 + (s & 3)];
1884 LWS_VISIBLE LWS_EXTERN int
1885 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1889 static const char *slash = "/";
1891 /* cut up the location into address, port and path */
1893 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1904 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1906 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1912 while (*p && *p != ']')
1919 while (*p && *p != ':' && *p != '/')
1925 while (*p && *p != '/')
1938 #ifdef LWS_NO_EXTENSIONS
1940 /* we need to provide dummy callbacks for internal exts
1941 * so user code runs when faced with a lib compiled with
1942 * extensions disabled.
1946 lws_extension_callback_pm_deflate(struct lws_context *context,
1947 const struct lws_extension *ext,
1949 enum lws_extension_callback_reasons reason,
1950 void *user, void *in, size_t len)
1965 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1969 #ifdef LWS_USE_UNIX_SOCK
1970 struct sockaddr_un serv_unix;
1973 struct sockaddr_in6 serv_addr6;
1975 struct sockaddr_in serv_addr4;
1976 #ifndef LWS_PLAT_OPTEE
1977 socklen_t len = sizeof(struct sockaddr_storage);
1980 struct sockaddr_storage sin;
1983 #ifdef LWS_USE_UNIX_SOCK
1984 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1985 v = (struct sockaddr *)&serv_unix;
1986 n = sizeof(struct sockaddr_un);
1987 bzero((char *) &serv_unix, sizeof(serv_unix));
1988 serv_unix.sun_family = AF_UNIX;
1989 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1990 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1994 strcpy(serv_unix.sun_path, iface);
1995 if (serv_unix.sun_path[0] == '@')
1996 serv_unix.sun_path[0] = '\0';
2000 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
2001 if (LWS_IPV6_ENABLED(vhost)) {
2002 v = (struct sockaddr *)&serv_addr6;
2003 n = sizeof(struct sockaddr_in6);
2004 bzero((char *) &serv_addr6, sizeof(serv_addr6));
2006 if (interface_to_sa(vhost, iface,
2007 (struct sockaddr_in *)v, n) < 0) {
2008 lwsl_err("Unable to find interface %s\n", iface);
2011 serv_addr6.sin6_scope_id = lws_get_addr_scope(iface);
2014 serv_addr6.sin6_family = AF_INET6;
2015 serv_addr6.sin6_port = htons(port);
2019 v = (struct sockaddr *)&serv_addr4;
2020 n = sizeof(serv_addr4);
2021 bzero((char *) &serv_addr4, sizeof(serv_addr4));
2022 serv_addr4.sin_addr.s_addr = INADDR_ANY;
2023 serv_addr4.sin_family = AF_INET;
2024 #if !defined(LWS_WITH_ESP32)
2027 interface_to_sa(vhost, iface,
2028 (struct sockaddr_in *)v, n) < 0) {
2029 lwsl_err("Unable to find interface %s\n", iface);
2033 serv_addr4.sin_port = htons(port);
2036 n = bind(sockfd, v, n);
2037 #ifdef LWS_USE_UNIX_SOCK
2038 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
2039 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
2040 sockfd, iface, n, LWS_ERRNO);
2045 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
2046 sockfd, port, n, LWS_ERRNO);
2050 #ifndef LWS_PLAT_OPTEE
2051 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
2052 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
2055 #if defined(LWS_USE_IPV6)
2056 port = (sin.ss_family == AF_INET6) ?
2057 ntohs(((struct sockaddr_in6 *) &sin)->sin6_port) :
2058 ntohs(((struct sockaddr_in *) &sin)->sin_port);
2060 port = ntohs(((struct sockaddr_in *) &sin)->sin_port);
2067 #if defined(LWS_USE_IPV6)
2068 LWS_EXTERN unsigned long
2069 lws_get_addr_scope(const char *ipaddr)
2071 unsigned long scope = 0;
2074 struct ifaddrs *addrs, *addr;
2075 char ip[NI_MAXHOST];
2079 for (addr = addrs; addr; addr = addr->ifa_next) {
2080 if (!addr->ifa_addr ||
2081 addr->ifa_addr->sa_family != AF_INET6)
2084 getnameinfo(addr->ifa_addr,
2085 sizeof(struct sockaddr_in6),
2087 NULL, 0, NI_NUMERICHOST);
2091 if (ip[i++] == '%') {
2096 if (!strcmp(ip, ipaddr)) {
2097 scope = if_nametoindex(addr->ifa_name);
2103 PIP_ADAPTER_ADDRESSES adapter, addrs = NULL;
2104 PIP_ADAPTER_UNICAST_ADDRESS addr;
2107 struct sockaddr_in6 *sockaddr;
2108 char ip[NI_MAXHOST];
2112 for (i = 0; i < 5; i++)
2114 ret = GetAdaptersAddresses(AF_INET6, GAA_FLAG_INCLUDE_PREFIX,
2115 NULL, addrs, &size);
2116 if ((ret == NO_ERROR) || (ret == ERROR_NO_DATA)) {
2118 } else if (ret == ERROR_BUFFER_OVERFLOW)
2122 addrs = (IP_ADAPTER_ADDRESSES *) malloc(size);
2130 lwsl_err("Failed to get IPv6 address table (%d)", ret);
2135 if ((ret == NO_ERROR) && (addrs))
2138 while ((adapter) && (!found))
2140 addr = adapter->FirstUnicastAddress;
2141 while ((addr) && (!found))
2143 if (addr->Address.lpSockaddr->sa_family == AF_INET6)
2145 sockaddr = (struct sockaddr_in6 *) (addr->Address.lpSockaddr);
2147 lws_plat_inet_ntop(sockaddr->sin6_family, &sockaddr->sin6_addr,
2150 if (!strcmp(ip, ipaddr)) {
2151 scope = sockaddr->sin6_scope_id;
2158 adapter = adapter->Next;
2170 lws_restart_ws_ping_pong_timer(struct lws *wsi)
2172 if (!wsi->context->ws_ping_pong_interval)
2174 if (wsi->state != LWSS_ESTABLISHED)
2177 wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
2178 wsi->context->ws_ping_pong_interval;
2181 static const char *hex = "0123456789ABCDEF";
2183 LWS_VISIBLE LWS_EXTERN const char *
2184 lws_sql_purify(char *escaped, const char *string, int len)
2186 const char *p = string;
2189 while (*p && len-- > 2) {
2203 LWS_VISIBLE LWS_EXTERN const char *
2204 lws_json_purify(char *escaped, const char *string, int len)
2206 const char *p = string;
2214 while (*p && len-- > 6) {
2215 if (*p == '\"' || *p == '\\' || *p < 0x20) {
2220 *q++ = hex[((*p) >> 4) & 15];
2221 *q++ = hex[(*p) & 15];
2232 LWS_VISIBLE LWS_EXTERN const char *
2233 lws_urlencode(char *escaped, const char *string, int len)
2235 const char *p = string;
2238 while (*p && len-- > 3) {
2244 if ((*p >= '0' && *p <= '9') ||
2245 (*p >= 'A' && *p <= 'Z') ||
2246 (*p >= 'a' && *p <= 'z')) {
2251 *q++ = hex[(*p >> 4) & 0xf];
2252 *q++ = hex[*p & 0xf];
2262 LWS_VISIBLE LWS_EXTERN int
2263 lws_urldecode(char *string, const char *escaped, int len)
2268 while (*escaped && len) {
2271 if (*escaped == '%') {
2276 if (*escaped == '+') {
2282 *string++ = *escaped++;
2286 n = char_to_hex(*escaped);
2295 n = char_to_hex(*escaped);
2299 *string++ = sum | n;
2311 LWS_VISIBLE LWS_EXTERN int
2312 lws_finalize_startup(struct lws_context *context)
2314 struct lws_context_creation_info info;
2316 info.uid = context->uid;
2317 info.gid = context->gid;
2319 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
2320 memcpy(info.caps, context->caps, sizeof(info.caps));
2321 info.count_caps = context->count_caps;
2324 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2325 lws_plat_drop_app_privileges(&info);
2331 lws_snprintf(char *str, size_t size, const char *format, ...)
2339 va_start(ap, format);
2340 n = vsnprintf(str, size, format, ap);
2350 LWS_VISIBLE LWS_EXTERN int
2351 lws_is_cgi(struct lws *wsi) {
2362 urlencode(const char *in, int inlen, char *out, int outlen)
2364 char *start = out, *end = out + outlen;
2366 while (inlen-- && out < end - 4) {
2367 if ((*in >= 'A' && *in <= 'Z') ||
2368 (*in >= 'a' && *in <= 'z') ||
2369 (*in >= '0' && *in <= '9') ||
2383 *out++ = hex[(*in) >> 4];
2384 *out++ = hex[(*in++) & 15];
2395 lws_create_basic_wsi(struct lws_context *context, int tsi)
2397 struct lws *new_wsi;
2399 if ((unsigned int)context->pt[tsi].fds_count ==
2400 context->fd_limit_per_thread - 1) {
2401 lwsl_err("no space for new conn\n");
2405 new_wsi = lws_zalloc(sizeof(struct lws));
2406 if (new_wsi == NULL) {
2407 lwsl_err("Out of memory for new connection\n");
2412 new_wsi->context = context;
2413 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2414 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2416 /* initialize the instance struct */
2418 new_wsi->state = LWSS_CGI;
2419 new_wsi->mode = LWSCM_CGI;
2420 new_wsi->hdr_parsing_completed = 0;
2421 new_wsi->position_in_fds_table = -1;
2424 * these can only be set once the protocol is known
2425 * we set an unestablished connection's protocol pointer
2426 * to the start of the defauly vhost supported list, so it can look
2427 * for matching ones during the handshake
2429 new_wsi->protocol = context->vhost_list->protocols;
2430 new_wsi->user_space = NULL;
2431 new_wsi->ietf_spec_revision = 0;
2432 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2433 context->count_wsi_allocated++;
2438 LWS_VISIBLE LWS_EXTERN int
2439 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2440 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2442 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2443 char *env_array[30], cgi_path[400], e[1024], *p = e,
2444 *end = p + sizeof(e) - 1, tok[256], *t;
2445 struct lws_cgi *cgi;
2446 int n, m, i, uritok = -1;
2449 * give the master wsi a cgi struct
2452 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2454 lwsl_err("%s: OOM\n", __func__);
2458 wsi->cgi->response_code = HTTP_STATUS_OK;
2461 cgi->wsi = wsi; /* set cgi's owning wsi */
2463 /* create pipes for [stdin|stdout] and [stderr] */
2465 for (n = 0; n < 3; n++)
2466 if (pipe(cgi->pipe_fds[n]) == -1)
2469 /* create cgi wsis for each stdin/out/err fd */
2471 for (n = 0; n < 3; n++) {
2472 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2473 if (!cgi->stdwsi[n])
2475 cgi->stdwsi[n]->cgi_channel = n;
2476 cgi->stdwsi[n]->vhost = wsi->vhost;
2478 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2479 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2481 /* read side is 0, stdin we want the write side, others read */
2482 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2483 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2484 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2489 for (n = 0; n < 3; n++) {
2490 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2491 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2493 cgi->stdwsi[n]->parent = wsi;
2494 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2495 wsi->child_list = cgi->stdwsi[n];
2498 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2499 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2500 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2502 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2503 cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2504 cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2505 cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2507 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2509 /* the cgi stdout is always sending us http1.x header data first */
2510 wsi->hdr_state = LCHS_HEADER;
2512 /* add us to the pt list of active cgis */
2513 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2514 cgi->cgi_list = pt->cgi_list;
2517 /* prepare his CGI env */
2521 if (lws_is_ssl(wsi))
2522 env_array[n++] = "HTTPS=ON";
2523 if (wsi->u.hdr.ah) {
2524 static const unsigned char meths[] = {
2527 WSI_TOKEN_OPTIONS_URI,
2529 WSI_TOKEN_PATCH_URI,
2530 WSI_TOKEN_DELETE_URI,
2532 static const char * const meth_names[] = {
2533 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2536 for (m = 0; m < ARRAY_SIZE(meths); m++)
2537 if (lws_hdr_total_length(wsi, meths[m]) >=
2538 script_uri_path_len) {
2546 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2547 lws_hdr_simple_ptr(wsi, uritok));
2548 cgi_path[sizeof(cgi_path) - 1] = '\0';
2549 env_array[n++] = cgi_path;
2552 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2557 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2558 /* dump the individual URI Arg parameters */
2561 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2562 WSI_TOKEN_HTTP_URI_ARGS, m);
2566 while (*t && *t != '=' && p < end - 4)
2570 i = urlencode(t, i- (t - tok), p, end - p);
2582 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2583 lws_hdr_simple_ptr(wsi, uritok) +
2584 script_uri_path_len);
2587 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2589 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2590 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2593 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2595 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2596 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2599 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2601 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2602 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2605 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2607 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2608 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2611 if (uritok == WSI_TOKEN_POST_URI) {
2612 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2614 p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2615 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2618 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2620 p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2621 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2626 p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2630 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2632 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2635 mp_cgienv = mp_cgienv->next;
2638 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2639 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2640 env_array[n] = NULL;
2643 for (m = 0; m < n; m++)
2644 lwsl_err(" %s\n", env_array[m]);
2648 * Actually having made the env, as a cgi we don't need the ah
2651 if (lws_header_table_is_in_detachable_state(wsi))
2652 lws_header_table_detach(wsi, 0);
2654 /* we are ready with the redirection pipes... run the thing */
2655 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2661 lwsl_err("fork failed, errno %d", errno);
2665 #if defined(__linux__)
2666 prctl(PR_SET_PDEATHSIG, SIGTERM);
2668 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2671 /* we are the parent process */
2672 wsi->context->count_cgi_spawned++;
2673 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2677 /* somewhere we can at least read things and enter it */
2679 lwsl_notice("%s: Failed to chdir\n", __func__);
2681 /* We are the forked process, redirect and kill inherited things.
2683 * Because of vfork(), we cannot do anything that changes pages in
2684 * the parent environment. Stuff that changes kernel state for the
2685 * process is OK. Stuff that happens after the execvpe() is OK.
2688 for (n = 0; n < 3; n++) {
2689 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2690 lwsl_err("%s: stdin dup2 failed\n", __func__);
2693 close(cgi->pipe_fds[n][!(n == 0)]);
2696 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2697 for (m = 0; m < n; m++) {
2698 p = strchr(env_array[m], '=');
2700 setenv(env_array[m], p, 1);
2702 execvp(exec_array[0], (char * const *)&exec_array[0]);
2704 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2710 /* drop us from the pt cgi list */
2711 pt->cgi_list = cgi->cgi_list;
2714 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2716 for (n = 0; n < 3; n++)
2717 if (wsi->cgi->stdwsi[n])
2718 lws_free_wsi(cgi->stdwsi[n]);
2721 for (n = 0; n < 3; n++) {
2722 if (cgi->pipe_fds[n][0])
2723 close(cgi->pipe_fds[n][0]);
2724 if (cgi->pipe_fds[n][1])
2725 close(cgi->pipe_fds[n][1]);
2728 lws_free_set_NULL(wsi->cgi);
2730 lwsl_err("%s: failed\n", __func__);
2735 /* we have to parse out these headers in the CGI output */
2737 static const char * const significant_hdr[SIGNIFICANT_HDR_COUNT] = {
2741 "transfer-encoding: chunked",
2744 LWS_VISIBLE LWS_EXTERN int
2745 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2748 unsigned char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2749 *end = &buf[sizeof(buf) - 1 - LWS_PRE];
2755 while (wsi->hdr_state != LHCS_PAYLOAD) {
2756 /* we have to separate header / finalize and
2757 * payload chunks, since they need to be
2758 * handled separately
2761 switch (wsi->hdr_state) {
2764 lwsl_info("LHCS_RESPONSE: issuing response %d\n",
2765 wsi->cgi->response_code);
2766 if (lws_add_http_header_status(wsi, wsi->cgi->response_code, &p, end))
2768 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2769 (unsigned char *)"close", 5, &p, end))
2771 n = lws_write(wsi, start, p - start,
2772 LWS_WRITE_HTTP_HEADERS);
2774 /* finalize cached headers before dumping them */
2775 if (lws_finalize_http_header(wsi,
2776 (unsigned char **)&wsi->cgi->headers_pos,
2777 (unsigned char *)wsi->cgi->headers_end)) {
2779 lwsl_notice("finalize failed\n");
2783 wsi->hdr_state = LHCS_DUMP_HEADERS;
2784 wsi->reason_bf |= 8;
2785 lws_callback_on_writable(wsi);
2786 /* back to the loop for writeability again */
2789 case LHCS_DUMP_HEADERS:
2791 n = wsi->cgi->headers_pos - wsi->cgi->headers_dumped;
2795 lwsl_debug("LHCS_DUMP_HEADERS: %d\n", n);
2797 m = lws_write(wsi, (unsigned char *)wsi->cgi->headers_dumped,
2798 n, LWS_WRITE_HTTP_HEADERS);
2800 lwsl_debug("%s: write says %d\n", __func__, m);
2803 wsi->cgi->headers_dumped += n;
2804 if (wsi->cgi->headers_dumped == wsi->cgi->headers_pos) {
2805 wsi->hdr_state = LHCS_PAYLOAD;
2806 lws_free_set_NULL(wsi->cgi->headers_buf);
2807 lwsl_debug("freed cgi headers\n");
2809 wsi->reason_bf |= 8;
2810 lws_callback_on_writable(wsi);
2813 /* writeability becomes uncertain now we wrote
2814 * something, we must return to the event loop
2819 if (!wsi->cgi->headers_buf) {
2820 /* if we don't already have a headers buf, cook one up */
2822 wsi->cgi->headers_buf = malloc(n);
2823 if (!wsi->cgi->headers_buf) {
2828 lwsl_debug("allocated cgi hdrs\n");
2829 wsi->cgi->headers_pos = wsi->cgi->headers_buf;
2830 wsi->cgi->headers_dumped = wsi->cgi->headers_pos;
2831 wsi->cgi->headers_end = wsi->cgi->headers_buf + n - 1;
2833 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2834 wsi->cgi->match[n] = 0;
2839 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2841 if (errno != EAGAIN) {
2842 lwsl_debug("%s: read says %d\n", __func__, n);
2848 if (wsi->cgi->headers_pos >= wsi->cgi->headers_end - 4) {
2849 lwsl_notice("CGI headers larger than buffer size\n");
2855 lwsl_debug("-- 0x%02X %c %d %d\n", (unsigned char)c, c, wsi->cgi->match[1], wsi->hdr_state);
2858 switch (wsi->hdr_state) {
2861 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2862 /* significant headers with numeric decimal payloads */
2863 if (!significant_hdr[n][wsi->cgi->match[n]] &&
2864 (c >= '0' && c <= '9') &&
2865 wsi->cgi->lp < sizeof(wsi->cgi->l) - 1) {
2866 wsi->cgi->l[wsi->cgi->lp++] = c;
2867 wsi->cgi->l[wsi->cgi->lp] = '\0';
2869 case SIGNIFICANT_HDR_CONTENT_LENGTH:
2870 wsi->cgi->content_length = atoll(wsi->cgi->l);
2872 case SIGNIFICANT_HDR_STATUS:
2873 wsi->cgi->response_code = atol(wsi->cgi->l);
2874 lwsl_debug("Status set to %d\n", wsi->cgi->response_code);
2880 /* hits up to the NUL are sticky until next hdr */
2881 if (significant_hdr[n][wsi->cgi->match[n]]) {
2882 if (tolower(c) == significant_hdr[n][wsi->cgi->match[n]])
2883 wsi->cgi->match[n]++;
2885 wsi->cgi->match[n] = 0;
2889 /* some cgi only send us \x0a for EOL */
2891 wsi->hdr_state = LCHS_SINGLE_0A;
2892 *wsi->cgi->headers_pos++ = '\x0d';
2894 *wsi->cgi->headers_pos++ = c;
2896 wsi->hdr_state = LCHS_LF1;
2898 if (wsi->hdr_state != LCHS_HEADER &&
2899 !significant_hdr[SIGNIFICANT_HDR_TRANSFER_ENCODING][wsi->cgi->match[SIGNIFICANT_HDR_TRANSFER_ENCODING]]) {
2900 lwsl_debug("cgi produced chunked\n");
2901 wsi->cgi->explicitly_chunked = 1;
2904 /* presence of Location: mandates 302 retcode */
2905 if (wsi->hdr_state != LCHS_HEADER &&
2906 !significant_hdr[SIGNIFICANT_HDR_LOCATION][wsi->cgi->match[SIGNIFICANT_HDR_LOCATION]]) {
2907 lwsl_debug("CGI: Location hdr seen\n");
2908 wsi->cgi->response_code = 302;
2913 *wsi->cgi->headers_pos++ = c;
2915 wsi->hdr_state = LCHS_CR2;
2918 /* we got \r[^\n]... it's unreasonable */
2919 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2925 wsi->hdr_state = LCHS_LF2;
2928 wsi->hdr_state = LCHS_HEADER;
2929 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2930 wsi->cgi->match[n] = 0;
2935 case LCHS_SINGLE_0A:
2938 lwsl_debug("Content-Length: %lld\n", (unsigned long long)wsi->cgi->content_length);
2939 wsi->hdr_state = LHCS_RESPONSE;
2940 /* drop the \0xa ... finalize will add it if needed */
2944 /* we got \r\n\r[^\n]... it's unreasonable */
2946 /* we got \x0anext header, it's reasonable */
2947 *wsi->cgi->headers_pos++ = c;
2948 wsi->hdr_state = LCHS_HEADER;
2949 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2950 wsi->cgi->match[n] = 0;
2958 /* ran out of input, ended the headers, or filled up the headers buf */
2959 if (!n || wsi->hdr_state == LHCS_PAYLOAD)
2963 /* payload processing */
2965 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2966 start, sizeof(buf) - LWS_PRE);
2968 if (n < 0 && errno != EAGAIN) {
2969 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2973 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2974 //lwsl_notice("write %d\n", m);
2976 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2979 wsi->cgi->content_length_seen += m;
2985 LWS_VISIBLE LWS_EXTERN int
2986 lws_cgi_kill(struct lws *wsi)
2988 struct lws_cgi_args args;
2991 lwsl_debug("%s: %p\n", __func__, wsi);
2996 if (wsi->cgi->pid > 0) {
2997 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2999 lwsl_debug("%s: PID %d reaped\n", __func__,
3003 /* kill the process group */
3004 n = kill(-wsi->cgi->pid, SIGTERM);
3005 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
3006 wsi->cgi->pid, n, errno);
3009 * hum seen errno=3 when process is listed in ps,
3010 * it seems we don't always retain process grouping
3012 * Direct these fallback attempt to the exact child
3014 n = kill(wsi->cgi->pid, SIGTERM);
3016 n = kill(wsi->cgi->pid, SIGPIPE);
3018 n = kill(wsi->cgi->pid, SIGKILL);
3020 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
3021 __func__, wsi->cgi->pid, errno);
3025 /* He could be unkillable because he's a zombie */
3028 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
3030 lwsl_debug("%s: reaped PID %d\n", __func__, n);
3032 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
3034 lwsl_debug("%s: reaped PID %d\n", __func__, n);
3040 args.stdwsi = &wsi->cgi->stdwsi[0];
3042 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
3043 wsi->protocol->callback,
3044 wsi, LWS_CALLBACK_CGI_TERMINATED,
3046 (void *)&args, 0)) {
3048 if (!wsi->cgi->being_closed)
3049 lws_close_free_wsi(wsi, 0);
3056 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
3058 struct lws_cgi **pcgi, *cgi = NULL;
3062 /* find finished guys but don't reap yet */
3063 n = waitpid(-1, &status, WNOHANG);
3066 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
3068 pcgi = &pt->cgi_list;
3070 /* check all the subprocesses on the cgi list */
3072 /* get the next one first as list may change */
3074 pcgi = &(*pcgi)->cgi_list;
3079 /* finish sending cached headers */
3080 if (cgi->headers_buf)
3083 /* wait for stdout to be drained */
3084 if (cgi->content_length > cgi->content_length_seen)
3087 if (cgi->content_length) {
3088 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3089 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3093 waitpid(n, &status, WNOHANG);
3095 * he's already terminated so no need for kill()
3096 * but we should do the terminated cgi callback
3097 * and close him if he's not already closing
3099 if (n == cgi->pid) {
3100 lwsl_debug("%s: found PID %d on cgi list\n",
3103 if (!cgi->content_length && cgi->explicitly_chunked) {
3105 * well, if he sends chunked... give him 5s after the
3106 * cgi terminated to send buffered
3108 cgi->chunked_grace++;
3114 lws_cgi_kill(cgi->wsi);
3120 /* if not found on the cgi list, as he's one of ours, reap */
3122 lwsl_debug("%s: reading PID %d although no cgi match\n",
3124 waitpid(n, &status, WNOHANG);
3128 /* disable this to confirm timeout cgi cleanup flow */
3130 pcgi = &pt->cgi_list;
3132 /* check all the subprocesses on the cgi list */
3134 /* get the next one first as list may change */
3136 pcgi = &(*pcgi)->cgi_list;
3141 /* we deferred killing him after reaping his PID */
3142 if (cgi->chunked_grace) {
3143 cgi->chunked_grace++;
3144 if (cgi->chunked_grace < 5)
3149 /* finish sending cached headers */
3150 if (cgi->headers_buf)
3153 /* wait for stdout to be drained */
3154 if (cgi->content_length > cgi->content_length_seen)
3157 if (cgi->content_length)
3158 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3159 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3162 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
3164 if (!cgi->content_length) {
3166 * well, if he sends chunked... give him 5s after the
3167 * cgi terminated to send buffered
3169 cgi->chunked_grace++;
3173 lwsl_debug("%s: found PID %d on cgi list\n",
3174 __func__, cgi->pid);
3177 lws_cgi_kill(cgi->wsi);
3184 /* general anti zombie defence */
3185 // n = waitpid(-1, &status, WNOHANG);
3187 // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
3193 #ifdef LWS_NO_EXTENSIONS
3195 lws_set_extension_option(struct lws *wsi, const char *ext_name,
3196 const char *opt_name, const char *opt_val)
3202 #ifdef LWS_WITH_ACCESS_LOG
3204 lws_access_log(struct lws *wsi)
3206 char *p = wsi->access_log.user_agent, ass[512];
3209 if (!wsi->access_log_pending)
3212 if (!wsi->access_log.header_log)
3218 l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
3219 wsi->access_log.header_log,
3220 wsi->access_log.response, wsi->access_log.sent, p);
3222 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
3223 if (write(wsi->vhost->log_fd, ass, l) != l)
3224 lwsl_err("Failed to write log\n");
3226 lwsl_err("%s", ass);
3228 if (wsi->access_log.header_log) {
3229 lws_free(wsi->access_log.header_log);
3230 wsi->access_log.header_log = NULL;
3232 if (wsi->access_log.user_agent) {
3233 lws_free(wsi->access_log.user_agent);
3234 wsi->access_log.user_agent = NULL;
3236 wsi->access_log_pending = 0;
3243 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
3245 const struct lws_vhost *vh = ctx->vhost_list;
3249 cs->rx += vh->conn_stats.rx;
3250 cs->tx += vh->conn_stats.tx;
3251 cs->conn += vh->conn_stats.conn;
3252 cs->trans += vh->conn_stats.trans;
3253 cs->ws_upg += vh->conn_stats.ws_upg;
3254 cs->http2_upg += vh->conn_stats.http2_upg;
3255 cs->rejected += vh->conn_stats.rejected;
3257 vh = vh->vhost_next;
3261 #ifdef LWS_WITH_SERVER_STATUS
3264 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
3266 static const char * const prots[] = {
3275 char *orig = buf, *end = buf + len - 1, first = 1;
3281 buf += lws_snprintf(buf, end - buf,
3282 "{\n \"name\":\"%s\",\n"
3283 " \"port\":\"%d\",\n"
3284 " \"use_ssl\":\"%d\",\n"
3285 " \"sts\":\"%d\",\n"
3286 " \"rx\":\"%llu\",\n"
3287 " \"tx\":\"%llu\",\n"
3288 " \"conn\":\"%lu\",\n"
3289 " \"trans\":\"%lu\",\n"
3290 " \"ws_upg\":\"%lu\",\n"
3291 " \"rejected\":\"%lu\",\n"
3292 " \"http2_upg\":\"%lu\""
3294 vh->name, vh->listen_port,
3295 #ifdef LWS_OPENSSL_SUPPORT
3300 !!(vh->options & LWS_SERVER_OPTION_STS),
3301 vh->conn_stats.rx, vh->conn_stats.tx,
3302 vh->conn_stats.conn, vh->conn_stats.trans,
3303 vh->conn_stats.ws_upg,
3304 vh->conn_stats.rejected,
3305 vh->conn_stats.http2_upg
3308 if (vh->mount_list) {
3309 const struct lws_http_mount *m = vh->mount_list;
3311 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
3314 buf += lws_snprintf(buf, end - buf, ",");
3315 buf += lws_snprintf(buf, end - buf,
3316 "\n {\n \"mountpoint\":\"%s\",\n"
3317 " \"origin\":\"%s%s\",\n"
3318 " \"cache_max_age\":\"%d\",\n"
3319 " \"cache_reuse\":\"%d\",\n"
3320 " \"cache_revalidate\":\"%d\",\n"
3321 " \"cache_intermediaries\":\"%d\"\n"
3324 prots[m->origin_protocol],
3328 m->cache_revalidate,
3329 m->cache_intermediaries);
3331 buf += lws_snprintf(buf, end - buf,
3332 ",\n \"default\":\"%s\"",
3334 buf += lws_snprintf(buf, end - buf, "\n }");
3338 buf += lws_snprintf(buf, end - buf, "\n ]");
3341 if (vh->protocols) {
3345 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
3346 while (n < vh->count_protocols) {
3348 buf += lws_snprintf(buf, end - buf, ",");
3349 buf += lws_snprintf(buf, end - buf,
3351 " \"status\":\"ok\"\n }\n }"
3353 vh->protocols[n].name);
3357 buf += lws_snprintf(buf, end - buf, "\n ]");
3360 buf += lws_snprintf(buf, end - buf, "\n}");
3366 LWS_EXTERN LWS_VISIBLE int
3367 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
3370 char *orig = buf, *end = buf + len - 1, first = 1;
3371 const struct lws_vhost *vh = context->vhost_list;
3372 const struct lws_context_per_thread *pt;
3373 time_t t = time(NULL);
3374 int n, listening = 0, cgi_count = 0;
3375 struct lws_conn_stats cs;
3378 struct lws_cgi * const *pcgi;
3381 #ifdef LWS_USE_LIBUV
3385 buf += lws_snprintf(buf, end - buf, "{ "
3386 "\"version\":\"%s\",\n"
3387 "\"uptime\":\"%ld\",\n",
3388 lws_get_library_version(),
3391 #ifdef LWS_HAVE_GETLOADAVG
3396 m = getloadavg(d, 3);
3397 for (n = 0; n < m; n++) {
3398 buf += lws_snprintf(buf, end - buf,
3399 "\"l%d\":\"%.2f\",\n",
3405 buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
3407 buf += lws_snprintf(buf, end - buf, "{ "
3408 "\"context_uptime\":\"%ld\",\n"
3409 "\"cgi_spawned\":\"%d\",\n"
3410 "\"pt_fd_max\":\"%d\",\n"
3411 "\"ah_pool_max\":\"%d\",\n"
3412 "\"deprecated\":\"%d\",\n"
3413 "\"wsi_alive\":\"%d\",\n",
3414 (unsigned long)(t - context->time_up),
3415 context->count_cgi_spawned,
3416 context->fd_limit_per_thread,
3417 context->max_http_header_pool,
3418 context->deprecated,
3419 context->count_wsi_allocated);
3421 buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
3422 for (n = 0; n < context->count_threads; n++) {
3423 pt = &context->pt[n];
3425 buf += lws_snprintf(buf, end - buf, ",");
3426 buf += lws_snprintf(buf, end - buf,
3428 " \"fds_count\":\"%d\",\n"
3429 " \"ah_pool_inuse\":\"%d\",\n"
3430 " \"ah_wait_list\":\"%d\"\n"
3433 pt->ah_count_in_use,
3434 pt->ah_wait_list_length);
3437 buf += lws_snprintf(buf, end - buf, "]");
3439 buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3442 vh = context->vhost_list;
3444 cs = context->conn_stats;
3445 lws_sum_stats(context, &cs);
3452 buf += lws_json_dump_vhost(vh, buf, end - buf);
3457 vh = vh->vhost_next;
3460 buf += lws_snprintf(buf, end - buf,
3461 "],\n\"listen_wsi\":\"%d\",\n"
3462 " \"rx\":\"%llu\",\n"
3463 " \"tx\":\"%llu\",\n"
3464 " \"conn\":\"%lu\",\n"
3465 " \"trans\":\"%lu\",\n"
3466 " \"ws_upg\":\"%lu\",\n"
3467 " \"rejected\":\"%lu\",\n"
3468 " \"http2_upg\":\"%lu\"",
3470 cs.rx, cs.tx, cs.conn, cs.trans,
3471 cs.ws_upg, cs.rejected, cs.http2_upg);
3474 for (n = 0; n < context->count_threads; n++) {
3475 pt = &context->pt[n];
3476 pcgi = &pt->cgi_list;
3479 pcgi = &(*pcgi)->cgi_list;
3485 buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3488 buf += lws_snprintf(buf, end - buf, "}");
3491 buf += lws_snprintf(buf, end - buf, "]}\n ");
3498 #if defined(LWS_WITH_STATS)
3500 LWS_VISIBLE LWS_EXTERN uint64_t
3501 lws_stats_get(struct lws_context *context, int index)
3503 if (index >= LWSSTATS_SIZE)
3506 return context->lws_stats[index];
3509 LWS_VISIBLE LWS_EXTERN void
3510 lws_stats_log_dump(struct lws_context *context)
3512 struct lws_vhost *v = context->vhost_list;
3515 if (!context->updated)
3518 context->updated = 0;
3521 lwsl_notice("LWS internal statistics dump ----->\n");
3522 lwsl_notice("LWSSTATS_C_CONNECTIONS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_CONNECTIONS));
3523 lwsl_notice("LWSSTATS_C_API_CLOSE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_CLOSE));
3524 lwsl_notice("LWSSTATS_C_API_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_READ));
3525 lwsl_notice("LWSSTATS_C_API_LWS_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_LWS_WRITE));
3526 lwsl_notice("LWSSTATS_C_API_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_WRITE));
3527 lwsl_notice("LWSSTATS_C_WRITE_PARTIALS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITE_PARTIALS));
3528 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_REQ));
3529 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_EFF_REQ));
3530 lwsl_notice("LWSSTATS_C_WRITEABLE_CB: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB));
3531 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_FAILED));
3532 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED));
3533 lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX));
3535 lwsl_notice("LWSSTATS_C_TIMEOUTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_TIMEOUTS));
3536 lwsl_notice("LWSSTATS_C_SERVICE_ENTRY: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SERVICE_ENTRY));
3537 lwsl_notice("LWSSTATS_B_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ));
3538 lwsl_notice("LWSSTATS_B_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE));
3539 lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS));
3540 lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000);
3541 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED))
3542 lwsl_notice(" Avg accept delay: %8llums\n",
3543 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) /
3544 lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000);
3545 lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / 1000);
3546 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX))
3547 lwsl_notice(" Avg accept-rx delay: %8llums\n",
3548 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) /
3549 lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000);
3551 lwsl_notice("LWSSTATS_MS_WRITABLE_DELAY: %8lluus\n",
3552 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY));
3553 lwsl_notice("LWSSTATS_MS_WORST_WRITABLE_DELAY: %8lluus\n",
3554 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WORST_WRITABLE_DELAY));
3555 if (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))
3556 lwsl_notice(" Avg writable delay: %8lluus\n",
3557 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY) /
3558 lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)));
3559 lwsl_notice("Simultaneous SSL restriction: %8d/%d/%d\n", context->simultaneous_ssl,
3560 context->simultaneous_ssl_restriction, context->ssl_gate_accepts);
3562 lwsl_notice("Live wsi: %8d\n", context->count_wsi_allocated);
3564 #if defined(LWS_WITH_STATS)
3565 context->updated = 1;
3571 struct lws_context_per_thread *pt = &context->pt[(int)v->lserv_wsi->tsi];
3572 struct lws_pollfd *pfd;
3574 pfd = &pt->fds[v->lserv_wsi->position_in_fds_table];
3576 lwsl_notice(" Listen port %d actual POLLIN: %d\n",
3577 v->listen_port, (int)pfd->events & LWS_POLLIN);
3583 for (n = 0; n < context->count_threads; n++) {
3584 struct lws_context_per_thread *pt = &context->pt[n];
3588 lwsl_notice("PT %d\n", n + 1);
3592 lwsl_notice(" AH in use / max: %d / %d\n",
3593 pt->ah_count_in_use,
3594 context->max_http_header_pool);
3596 wl = pt->ah_wait_list;
3599 wl = wl->u.hdr.ah_wait_list;
3602 lwsl_notice(" AH wait list count / actual: %d / %d\n",
3603 pt->ah_wait_list_length, m);
3612 lws_stats_atomic_bump(struct lws_context * context,
3613 struct lws_context_per_thread *pt, int index, uint64_t bump)
3616 context->lws_stats[index] += bump;
3617 if (index != LWSSTATS_C_SERVICE_ENTRY)
3618 context->updated = 1;
3623 lws_stats_atomic_max(struct lws_context * context,
3624 struct lws_context_per_thread *pt, int index, uint64_t val)
3627 if (val > context->lws_stats[index]) {
3628 context->lws_stats[index] = val;
3629 context->updated = 1;