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 wsi->context->count_wsi_allocated--;
105 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
106 wsi->context->count_wsi_allocated);
112 lws_remove_from_timeout_list(struct lws *wsi)
114 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
116 if (!wsi->timeout_list_prev) /* ie, not part of the list */
120 /* if we have a next guy, set his prev to our prev */
121 if (wsi->timeout_list)
122 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
123 /* set our prev guy to our next guy instead of us */
124 *wsi->timeout_list_prev = wsi->timeout_list;
126 /* we're out of the list, we should not point anywhere any more */
127 wsi->timeout_list_prev = NULL;
128 wsi->timeout_list = NULL;
133 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
135 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
138 if (secs == LWS_TO_KILL_SYNC) {
139 lws_remove_from_timeout_list(wsi);
140 lwsl_debug("synchronously killing %p\n", wsi);
141 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
149 if (reason && !wsi->timeout_list_prev) {
150 /* our next guy is current first guy */
151 wsi->timeout_list = pt->timeout_list;
152 /* if there is a next guy, set his prev ptr to our next ptr */
153 if (wsi->timeout_list)
154 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
155 /* our prev ptr is first ptr */
156 wsi->timeout_list_prev = &pt->timeout_list;
157 /* set the first guy to be us */
158 *wsi->timeout_list_prev = wsi;
161 lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
162 wsi->pending_timeout_limit = now + secs;
163 wsi->pending_timeout = reason;
168 lws_remove_from_timeout_list(wsi);
172 lws_remove_child_from_any_parent(struct lws *wsi)
180 /* detach ourselves from parent's child list */
181 pwsi = &wsi->parent->child_list;
184 lwsl_info("%s: detach %p from parent %p\n",
185 __func__, wsi, wsi->parent);
187 if (wsi->parent->protocol)
188 wsi->parent->protocol->callback(wsi,
189 LWS_CALLBACK_CHILD_CLOSING,
190 wsi->parent->user_space, wsi, 0);
192 *pwsi = wsi->sibling_list;
196 pwsi = &(*pwsi)->sibling_list;
199 lwsl_err("%s: failed to detach from parent\n", __func__);
205 lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)
207 // if (wsi->protocol == p)
209 const struct lws_protocols *vp = wsi->vhost->protocols, *vpo;
212 wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,
213 wsi->user_space, NULL, 0);
214 if (!wsi->user_space_externally_allocated)
215 lws_free_set_NULL(wsi->user_space);
217 lws_same_vh_protocol_remove(wsi);
223 if (lws_ensure_user_space(wsi))
226 if (p > vp && p < &vp[wsi->vhost->count_protocols])
227 lws_same_vh_protocol_insert(wsi, p - vp);
229 int n = wsi->vhost->count_protocols;
235 if (p->name && vp->name && !strcmp(p->name, vp->name)) {
237 lws_same_vh_protocol_insert(wsi, vp - vpo);
243 lwsl_err("%s: protocol %p is not in vhost %s protocols list\n",
244 __func__, p, wsi->vhost->name);
247 if (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,
248 wsi->user_space, NULL, 0))
255 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
257 struct lws_context_per_thread *pt;
258 struct lws *wsi1, *wsi2;
259 struct lws_context *context;
260 struct lws_tokens eff_buf;
263 lwsl_debug("%s: %p\n", __func__, wsi);
269 #if defined(LWS_WITH_ESP8266)
270 if (wsi->premature_rx)
271 lws_free(wsi->premature_rx);
273 if (wsi->pending_send_completion && !wsi->close_is_pending_send_completion) {
274 lwsl_notice("delaying close\n");
275 wsi->close_is_pending_send_completion = 1;
280 /* we're closing, losing some rx is OK */
281 lws_header_table_force_to_detachable_state(wsi);
283 context = wsi->context;
284 pt = &context->pt[(int)wsi->tsi];
285 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_CLOSE, 1);
287 /* if we have children, close them first */
288 if (wsi->child_list) {
289 wsi2 = wsi->child_list;
291 //lwsl_notice("%s: closing %p: close child %p\n",
292 // __func__, wsi, wsi2);
293 wsi1 = wsi2->sibling_list;
294 //lwsl_notice("%s: closing %p: next sibling %p\n",
295 // __func__, wsi2, wsi1);
297 /* stop it doing shutdown processing */
298 wsi2->socket_is_permanently_unusable = 1;
299 lws_close_free_wsi(wsi2, reason);
302 wsi->child_list = NULL;
305 if (wsi->mode == LWSCM_RAW_FILEDESC) {
306 lws_remove_child_from_any_parent(wsi);
307 remove_wsi_socket_from_fds(wsi);
308 wsi->protocol->callback(wsi,
309 LWS_CALLBACK_RAW_CLOSE_FILE,
310 wsi->user_space, NULL, 0);
315 if (wsi->mode == LWSCM_CGI) {
316 /* we are not a network connection, but a handler for CGI io */
317 if (wsi->parent && wsi->parent->cgi)
318 /* end the binding between us and master */
319 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
320 wsi->socket_is_permanently_unusable = 1;
322 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
323 goto just_kill_connection;
327 struct lws_cgi **pcgi = &pt->cgi_list;
328 /* remove us from the cgi list */
329 lwsl_debug("%s: remove cgi %p from list\n", __func__, wsi->cgi);
331 if (*pcgi == wsi->cgi) {
332 /* drop us from the pt cgi list */
333 *pcgi = (*pcgi)->cgi_list;
336 pcgi = &(*pcgi)->cgi_list;
338 if (wsi->cgi->headers_buf) {
339 lwsl_debug("close: freed cgi headers\n");
340 lws_free_set_NULL(wsi->cgi->headers_buf);
342 /* we have a cgi going, we must kill it */
343 wsi->cgi->being_closed = 1;
348 #if !defined(LWS_NO_CLIENT)
349 if (wsi->mode == LWSCM_HTTP_CLIENT ||
350 wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
351 wsi->mode == LWSCM_WSCL_WAITING_PROXY_REPLY ||
352 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE ||
353 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE2 ||
354 wsi->mode == LWSCM_WSCL_WAITING_SSL ||
355 wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
356 wsi->mode == LWSCM_WSCL_WAITING_EXTENSION_CONNECT ||
357 wsi->mode == LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY ||
358 wsi->mode == LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY ||
359 wsi->mode == LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY)
360 if (wsi->u.hdr.stash)
361 lws_free_set_NULL(wsi->u.hdr.stash);
364 if (wsi->mode == LWSCM_RAW) {
365 wsi->protocol->callback(wsi,
366 LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0);
367 wsi->socket_is_permanently_unusable = 1;
368 goto just_kill_connection;
371 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
372 wsi->u.http.fop_fd != NULL) {
373 lws_vfs_file_close(&wsi->u.http.fop_fd);
374 wsi->vhost->protocols->callback(wsi,
375 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
376 wsi->told_user_closed = 1;
378 if (wsi->socket_is_permanently_unusable ||
379 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
380 wsi->state == LWSS_SHUTDOWN)
381 goto just_kill_connection;
383 wsi->state_pre_close = wsi->state;
385 switch (wsi->state_pre_close) {
386 case LWSS_DEAD_SOCKET:
389 /* we tried the polite way... */
390 case LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION:
391 case LWSS_AWAITING_CLOSE_ACK:
392 goto just_kill_connection;
394 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
395 if (wsi->trunc_len) {
396 lws_callback_on_writable(wsi);
399 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
400 goto just_kill_connection;
402 if (wsi->trunc_len) {
403 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
404 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
405 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
411 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
412 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
413 goto just_kill_connection;
415 if (wsi->mode == LWSCM_HTTP_SERVING) {
417 wsi->vhost->protocols->callback(wsi,
418 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
419 wsi->user_space, NULL, 0);
420 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
421 wsi->user_space, NULL, 0);
422 wsi->told_user_closed = 1;
424 if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
425 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
426 wsi->user_space, NULL, 0);
427 wsi->told_user_closed = 1;
431 * are his extensions okay with him closing? Eg he might be a mux
432 * parent and just his ch1 aspect is closing?
435 if (lws_ext_cb_active(wsi,
436 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
437 lwsl_ext("extension vetoed close\n");
442 * flush any tx pending from extensions, since we may send close packet
443 * if there are problems with send, just nuke the connection
448 eff_buf.token = NULL;
449 eff_buf.token_len = 0;
451 /* show every extension the new incoming data */
453 m = lws_ext_cb_active(wsi,
454 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
456 lwsl_ext("Extension reports fatal error\n");
457 goto just_kill_connection;
461 * at least one extension told us he has more
462 * to spill, so we will go around again after
466 /* assuming they left us something to send, send it */
468 if (eff_buf.token_len)
469 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
470 eff_buf.token_len) !=
472 lwsl_debug("close: ext spill failed\n");
473 goto just_kill_connection;
478 * signal we are closing, lws_write will
479 * add any necessary version-specific stuff. If the write fails,
480 * no worries we are closing anyway. If we didn't initiate this
481 * close, then our state has been changed to
482 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
484 * Likewise if it's a second call to close this connection after we
485 * sent the close indication to the peer already, we are in state
486 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
489 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
490 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
491 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
492 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
493 lwsl_debug("sending close indication...\n");
495 /* if no prepared close reason, use 1000 and no aux data */
496 if (!wsi->u.ws.close_in_ping_buffer_len) {
497 wsi->u.ws.close_in_ping_buffer_len = 2;
498 wsi->u.ws.ping_payload_buf[LWS_PRE] =
499 (reason >> 8) & 0xff;
500 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
504 #if defined (LWS_WITH_ESP8266)
505 wsi->close_is_pending_send_completion = 1;
508 lwsl_debug("waiting for chance to send close\n");
509 wsi->waiting_to_send_close_frame = 1;
510 wsi->state = LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION;
511 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 2);
512 lws_callback_on_writable(wsi);
517 just_kill_connection:
519 lws_remove_child_from_any_parent(wsi);
522 /* manage the vhost same protocol list entry */
524 if (wsi->same_vh_protocol_prev) { // we are on the vh list
526 // make guy who pointed to us, point to what our next was pointing to
527 *wsi->same_vh_protocol_prev = wsi->same_vh_protocol_next;
529 // if we had a next guy...
530 if (wsi->same_vh_protocol_next)
531 // have him point back to our prev
532 wsi->same_vh_protocol_next->same_vh_protocol_prev =
533 wsi->same_vh_protocol_prev;
539 * Testing with ab shows that we have to stage the socket close when
540 * the system is under stress... shutdown any further TX, change the
541 * state to one that won't emit anything more, and wait with a timeout
542 * for the POLLIN to show a zero-size rx before coming back and doing
545 if (wsi->mode != LWSCM_RAW &&
546 !(wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) &&
547 wsi->state != LWSS_SHUTDOWN &&
548 wsi->state != LWSS_CLIENT_UNCONNECTED &&
549 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
550 !wsi->socket_is_permanently_unusable) {
551 #ifdef LWS_OPENSSL_SUPPORT
552 if (lws_is_ssl(wsi) && wsi->ssl)
554 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);
555 n = SSL_shutdown(wsi->ssl);
556 if (n == 1) /* If finished the SSL shutdown, then do socket shutdown, else need to retry SSL shutdown */
557 n = shutdown(wsi->desc.sockfd, SHUT_WR);
559 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
562 int shutdown_error = SSL_get_error(wsi->ssl, n);
563 lwsl_debug("SSL_shutdown returned %d, SSL_get_error: %d\n", n, shutdown_error);
564 if (shutdown_error == SSL_ERROR_WANT_READ) {
565 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
567 } else if (shutdown_error == SSL_ERROR_WANT_WRITE) {
568 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLOUT);
570 } else { // actual error occurred, just close the connection
571 n = shutdown(wsi->desc.sockfd, SHUT_WR);
578 lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, (int)(long)wsi->desc.sockfd, wsi->state);
579 n = shutdown(wsi->desc.sockfd, SHUT_WR);
582 lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
584 // This causes problems with disconnection when the events are half closing connection
585 // FD_READ | FD_CLOSE (33)
586 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP32)
587 /* libuv: no event available to guarantee completion */
588 if (!LWS_LIBUV_ENABLED(context)) {
590 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
591 wsi->state = LWSS_SHUTDOWN;
592 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
593 context->timeout_secs);
601 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
602 wsi, wsi->desc.sockfd);
604 #ifdef LWS_WITH_HTTP_PROXY
606 lws_rewrite_destroy(wsi->rw);
611 * we won't be servicing or receiving anything further from this guy
612 * delete socket from the internal poll list if still present
614 lws_ssl_remove_wsi_from_buffered_list(wsi);
616 lws_remove_from_timeout_list(wsi);
618 /* checking return redundant since we anyway close */
619 if (wsi->desc.sockfd != LWS_SOCK_INVALID)
620 remove_wsi_socket_from_fds(wsi);
622 lws_same_vh_protocol_remove(wsi);
624 #if defined(LWS_WITH_ESP8266)
625 espconn_disconnect(wsi->desc.sockfd);
628 wsi->state = LWSS_DEAD_SOCKET;
630 lws_free_set_NULL(wsi->rxflow_buffer);
631 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
632 wsi->mode == LWSCM_WS_SERVING ||
633 wsi->mode == LWSCM_WS_CLIENT) {
635 if (wsi->u.ws.rx_draining_ext) {
636 struct lws **w = &pt->rx_draining_ext_list;
638 wsi->u.ws.rx_draining_ext = 0;
639 /* remove us from context draining ext list */
642 *w = wsi->u.ws.rx_draining_ext_list;
645 w = &((*w)->u.ws.rx_draining_ext_list);
647 wsi->u.ws.rx_draining_ext_list = NULL;
650 if (wsi->u.ws.tx_draining_ext) {
651 struct lws **w = &pt->tx_draining_ext_list;
653 wsi->u.ws.tx_draining_ext = 0;
654 /* remove us from context draining ext list */
657 *w = wsi->u.ws.tx_draining_ext_list;
660 w = &((*w)->u.ws.tx_draining_ext_list);
662 wsi->u.ws.tx_draining_ext_list = NULL;
664 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
666 if (wsi->trunc_alloc)
667 /* not going to be completed... nuke it */
668 lws_free_set_NULL(wsi->trunc_alloc);
670 wsi->u.ws.ping_payload_len = 0;
671 wsi->u.ws.ping_pending_flag = 0;
674 /* tell the user it's all over for this guy */
676 if (wsi->mode != LWSCM_RAW && wsi->protocol && wsi->protocol->callback &&
677 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
678 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
679 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
680 (wsi->state_pre_close == LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION) ||
681 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
682 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
683 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
685 if (wsi->user_space) {
686 lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s\n", __func__, wsi, wsi->protocol->name);
687 wsi->protocol->callback(wsi,
688 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
689 wsi->user_space, NULL, 0);
691 lwsl_debug("calling back CLOSED\n");
692 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
693 wsi->user_space, NULL, 0);
694 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
695 lwsl_debug("calling back CLOSED_HTTP\n");
696 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
697 wsi->user_space, NULL, 0 );
698 } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
699 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
700 !wsi->already_did_cce) {
701 wsi->vhost->protocols[0].callback(wsi,
702 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
703 wsi->user_space, NULL, 0);
705 lwsl_debug("not calling back closed mode=%d state=%d\n",
706 wsi->mode, wsi->state_pre_close);
708 /* deallocate any active extension contexts */
710 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
711 lwsl_warn("extension destruction failed\n");
713 * inform all extensions in case they tracked this guy out of band
714 * even though not active on him specifically
716 if (lws_ext_cb_all_exts(context, wsi,
717 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
718 lwsl_warn("ext destroy wsi failed\n");
722 wsi->socket_is_permanently_unusable = 1;
725 if (!wsi->parent_carries_io)
726 if (LWS_LIBUV_ENABLED(context)) {
728 lwsl_debug("%s: stopping listner libuv poll\n", __func__);
729 uv_poll_stop(&wsi->w_read.uv_watcher);
731 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
732 /* libuv has to do his own close handle processing asynchronously */
733 lws_libuv_closehandle(wsi);
739 lws_close_free_wsi_final(wsi);
743 lws_close_free_wsi_final(struct lws *wsi)
747 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->desc.sockfd)) {
749 //lwsl_err("*** closing sockfd %d\n", wsi->desc.sockfd);
750 n = compatible_close(wsi->desc.sockfd);
752 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
755 compatible_close(wsi->desc.sockfd);
758 wsi->desc.sockfd = LWS_SOCK_INVALID;
761 /* outermost destroy notification for wsi (user_space still intact) */
762 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
763 wsi->user_space, NULL, 0);
767 for (n = 0; n < 6; n++) {
768 if (wsi->cgi->pipe_fds[n / 2][n & 1] == 0)
769 lwsl_err("ZERO FD IN CGI CLOSE");
771 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
772 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
782 LWS_VISIBLE LWS_EXTERN const char *
783 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
785 int n = 0, sl = strlen(name);
787 while (lws_hdr_copy_fragment(wsi, buf, len,
788 WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
790 if (!strncmp(buf, name, sl))
799 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
801 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
805 ipv6 = LWS_IPV6_ENABLED(vh);
809 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
813 #ifndef LWS_PLAT_OPTEE
816 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
817 int name_len, char *rip, int rip_len)
820 struct addrinfo ai, *res;
821 struct sockaddr_in addr4;
825 addr4.sin_family = AF_UNSPEC;
828 if (LWS_IPV6_ENABLED(vh)) {
829 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
830 lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
834 // Strip off the IPv4 to IPv6 header if one exists
835 if (strncmp(rip, "::ffff:", 7) == 0)
836 memmove(rip, rip + 7, strlen(rip) - 6);
838 getnameinfo((struct sockaddr *)ads,
839 sizeof(struct sockaddr_in6), name,
840 name_len, NULL, 0, 0);
846 struct addrinfo *result;
848 memset(&ai, 0, sizeof ai);
849 ai.ai_family = PF_UNSPEC;
850 ai.ai_socktype = SOCK_STREAM;
851 ai.ai_flags = AI_CANONNAME;
852 #if !defined(LWS_WITH_ESP32)
853 if (getnameinfo((struct sockaddr *)ads,
854 sizeof(struct sockaddr_in),
855 name, name_len, NULL, 0, 0))
859 if (getaddrinfo(name, NULL, &ai, &result))
863 while (addr4.sin_family == AF_UNSPEC && res) {
864 switch (res->ai_family) {
866 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
867 addr4.sin_family = AF_INET;
873 freeaddrinfo(result);
876 if (addr4.sin_family == AF_UNSPEC)
879 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
897 LWS_VISIBLE const char *
898 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
903 struct sockaddr_in6 sin6;
905 struct sockaddr_in sin4;
909 if (wsi->parent_carries_io)
913 if (LWS_IPV6_ENABLED(wsi->vhost)) {
927 if (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {
928 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
932 return lws_plat_inet_ntop(af, q, name, namelen);
934 #if defined(LWS_WITH_ESP8266)
935 return lws_plat_get_peer_simple(wsi, name, namelen);
944 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
945 int name_len, char *rip, int rip_len)
947 #ifndef LWS_PLAT_OPTEE
951 struct sockaddr_in6 sin6;
953 struct sockaddr_in sin4;
954 struct lws_context *context = wsi->context;
961 lws_latency_pre(context, wsi);
964 if (LWS_IPV6_ENABLED(wsi->vhost)) {
974 if (getpeername(fd, p, &len) < 0) {
975 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
979 ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
982 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
995 lws_context_user(struct lws_context *context)
997 return context->user_space;
1000 LWS_VISIBLE struct lws_vhost *
1001 lws_vhost_get(struct lws *wsi)
1006 LWS_VISIBLE struct lws_vhost *
1007 lws_get_vhost(struct lws *wsi)
1012 LWS_VISIBLE const struct lws_protocols *
1013 lws_protocol_get(struct lws *wsi)
1015 return wsi->protocol;
1018 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1019 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
1023 for (n = 0; n < vh->count_protocols; n++)
1024 if (!strcmp(name, vh->protocols[n].name))
1025 return &vh->protocols[n];
1031 lws_callback_all_protocol(struct lws_context *context,
1032 const struct lws_protocols *protocol, int reason)
1034 struct lws_context_per_thread *pt = &context->pt[0];
1035 unsigned int n, m = context->count_threads;
1039 for (n = 0; n < pt->fds_count; n++) {
1040 wsi = wsi_from_fd(context, pt->fds[n].fd);
1043 if (wsi->protocol == protocol)
1044 protocol->callback(wsi, reason, wsi->user_space,
1054 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
1055 const struct lws_protocols *protocol, int reason)
1057 struct lws_context *context = vh->context;
1058 struct lws_context_per_thread *pt = &context->pt[0];
1059 unsigned int n, m = context->count_threads;
1063 for (n = 0; n < pt->fds_count; n++) {
1064 wsi = wsi_from_fd(context, pt->fds[n].fd);
1067 if (wsi->vhost == vh && wsi->protocol == protocol)
1068 protocol->callback(wsi, reason, wsi->user_space,
1077 LWS_VISIBLE LWS_EXTERN int
1078 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
1082 for (n = 0; n < wsi->vhost->count_protocols; n++)
1083 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
1089 LWS_VISIBLE LWS_EXTERN void
1090 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)
1092 context->fops = fops;
1095 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1096 lws_vfs_tell(lws_fop_fd_t fop_fd)
1101 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1102 lws_vfs_get_length(lws_fop_fd_t fop_fd)
1107 LWS_VISIBLE LWS_EXTERN uint32_t
1108 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd)
1110 return fop_fd->mod_time;
1113 LWS_VISIBLE lws_fileofs_t
1114 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1117 lwsl_debug("%s: seeking to %ld, len %ld\n", __func__, (long)offset, (long)fop_fd->len);
1118 ofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);
1119 lwsl_debug("%s: result %ld, fop_fd pos %ld\n", __func__, (long)ofs, (long)fop_fd->pos);
1124 LWS_VISIBLE lws_fileofs_t
1125 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1127 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len + fop_fd->pos + offset);
1131 const struct lws_plat_file_ops *
1132 lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,
1135 const struct lws_plat_file_ops *pf;
1136 const char *p = vfs_path;
1141 /* no non-platform fops, just use that */
1147 * scan the vfs path looking for indications we are to be
1148 * handled by a specific fops
1156 /* the first one is always platform fops, so skip */
1160 while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {
1161 if (p >= vfs_path + pf->fi[n].len)
1162 if (!strncmp(p - (pf->fi[n].len - 1),
1164 pf->fi[n].len - 1)) {
1179 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
1180 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
1181 lws_fop_flags_t *flags)
1183 const char *vpath = "";
1184 const struct lws_plat_file_ops *selected = lws_vfs_select_fops(
1185 fops, vfs_path, &vpath);
1187 return selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);
1192 * lws_now_secs() - seconds since 1970-1-1
1195 LWS_VISIBLE LWS_EXTERN unsigned long
1200 gettimeofday(&tv, NULL);
1209 lws_get_socket_fd(struct lws *wsi)
1211 return wsi->desc.sockfd;
1218 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
1219 int ret, int completed)
1221 unsigned long long u;
1224 u = time_in_microseconds();
1227 wsi->latency_start = u;
1228 if (!wsi->action_start)
1229 wsi->action_start = u;
1233 if (wsi->action_start == wsi->latency_start)
1235 "Completion first try lat %lluus: %p: ret %d: %s\n",
1236 u - wsi->latency_start,
1237 (void *)wsi, ret, action);
1240 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1241 u - wsi->action_start,
1242 u - wsi->latency_start,
1243 (void *)wsi, ret, action);
1244 wsi->action_start = 0;
1246 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1247 u - wsi->latency_start, (void *)wsi, ret, action);
1249 if (u - wsi->latency_start > context->worst_latency) {
1250 context->worst_latency = u - wsi->latency_start;
1251 strcpy(context->worst_latency_info, buf);
1253 lwsl_latency("%s", buf);
1258 lws_rx_flow_control(struct lws *wsi, int enable)
1260 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1263 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1264 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1270 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1271 const struct lws_protocols *protocol)
1273 const struct lws_context_per_thread *pt = &context->pt[0];
1275 unsigned int n, m = context->count_threads;
1278 for (n = 0; n < pt->fds_count; n++) {
1279 wsi = wsi_from_fd(context, pt->fds[n].fd);
1282 if (wsi->protocol == protocol)
1283 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1289 LWS_VISIBLE extern const char *
1290 lws_canonical_hostname(struct lws_context *context)
1292 return (const char *)context->canonical_hostname;
1295 int user_callback_handle_rxflow(lws_callback_function callback_function,
1297 enum lws_callback_reasons reason, void *user,
1298 void *in, size_t len)
1302 n = callback_function(wsi, reason, user, in, len);
1304 n = _lws_rx_flow_control(wsi);
1309 #if defined(LWS_WITH_ESP8266)
1311 #define strchr ets_strchr
1315 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1317 #if !defined(LWS_WITH_ESP8266)
1319 char authstring[96];
1324 /* we have to deal with a possible redundant leading http:// */
1325 if (!strncmp(proxy, "http://", 7))
1328 p = strchr(proxy, '@');
1329 if (p) { /* auth is around */
1331 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1334 strncpy(authstring, proxy, p - proxy);
1335 // null termination not needed on input
1336 if (lws_b64_encode_string(authstring, (p - proxy),
1337 vhost->proxy_basic_auth_token,
1338 sizeof vhost->proxy_basic_auth_token) < 0)
1341 lwsl_info(" Proxy auth in use\n");
1345 vhost->proxy_basic_auth_token[0] = '\0';
1347 strncpy(vhost->http_proxy_address, proxy,
1348 sizeof(vhost->http_proxy_address) - 1);
1349 vhost->http_proxy_address[
1350 sizeof(vhost->http_proxy_address) - 1] = '\0';
1352 p = strchr(vhost->http_proxy_address, ':');
1353 if (!p && !vhost->http_proxy_port) {
1354 lwsl_err("http_proxy needs to be ads:port\n");
1360 vhost->http_proxy_port = atoi(p + 1);
1364 lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1365 vhost->http_proxy_port);
1370 lwsl_err("proxy auth too long\n");
1375 #if defined(LWS_WITH_SOCKS5)
1377 lws_set_socks(struct lws_vhost *vhost, const char *socks)
1379 #if !defined(LWS_WITH_ESP8266)
1380 char *p_at, *p_colon;
1387 vhost->socks_user[0] = '\0';
1388 vhost->socks_password[0] = '\0';
1390 p_at = strchr(socks, '@');
1391 if (p_at) { /* auth is around */
1392 if ((unsigned int)(p_at - socks) > (sizeof(user)
1393 + sizeof(password) - 2)) {
1394 lwsl_err("Socks auth too long\n");
1398 p_colon = strchr(socks, ':');
1400 if ((unsigned int)(p_colon - socks) > (sizeof(user)
1402 lwsl_err("Socks user too long\n");
1405 if ((unsigned int)(p_at - p_colon) > (sizeof(password)
1407 lwsl_err("Socks password too long\n");
1411 strncpy(vhost->socks_user, socks, p_colon - socks);
1412 strncpy(vhost->socks_password, p_colon + 1,
1413 p_at - (p_colon + 1));
1415 lwsl_info(" Socks auth, user: %s, password: %s\n",
1416 vhost->socks_user, vhost->socks_password );
1421 strncpy(vhost->socks_proxy_address, socks,
1422 sizeof(vhost->socks_proxy_address) - 1);
1423 vhost->socks_proxy_address[sizeof(vhost->socks_proxy_address) - 1]
1426 p_colon = strchr(vhost->socks_proxy_address, ':');
1427 if (!p_colon && !vhost->socks_proxy_port) {
1428 lwsl_err("socks_proxy needs to be address:port\n");
1433 vhost->socks_proxy_port = atoi(p_colon + 1);
1437 lwsl_info(" Socks %s:%u\n", vhost->socks_proxy_address,
1438 vhost->socks_proxy_port);
1448 LWS_VISIBLE const struct lws_protocols *
1449 lws_get_protocol(struct lws *wsi)
1451 return wsi->protocol;
1455 lws_is_final_fragment(struct lws *wsi)
1457 lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1458 wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1459 (long)wsi->u.ws.rx_draining_ext);
1460 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1464 lws_is_first_fragment(struct lws *wsi)
1466 return wsi->u.ws.first_fragment;
1469 LWS_VISIBLE unsigned char
1470 lws_get_reserved_bits(struct lws *wsi)
1472 return wsi->u.ws.rsv;
1476 lws_ensure_user_space(struct lws *wsi)
1478 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1482 /* allocate the per-connection user memory (if any) */
1484 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1485 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1486 if (wsi->user_space == NULL) {
1487 lwsl_err("Out of memory for conn user space\n");
1491 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1492 __func__, wsi, (long)wsi->protocol->per_session_data_size,
1498 lwsl_timestamp(int level, char *p, int len)
1500 #ifndef LWS_PLAT_OPTEE
1501 time_t o_now = time(NULL);
1502 unsigned long long now;
1503 struct tm *ptm = NULL;
1511 ptm = localtime(&o_now);
1513 if (localtime_r(&o_now, &tm))
1518 for (n = 0; n < LLL_COUNT; n++) {
1519 if (level != (1 << n))
1521 now = time_in_microseconds() / 100;
1523 n = lws_snprintf(p, len,
1524 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1525 ptm->tm_year + 1900,
1531 (int)(now % 10000), log_level_names[n]);
1533 n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1534 (unsigned long long) now / 10000,
1535 (int)(now % 10000), log_level_names[n]);
1542 #ifndef LWS_PLAT_OPTEE
1543 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1545 #if !defined(LWS_WITH_ESP8266)
1548 lwsl_timestamp(level, buf, sizeof(buf));
1549 fprintf(stderr, "%s%s", buf, line);
1554 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1556 #if defined(LWS_WITH_ESP8266)
1563 if (!(log_level & filter))
1566 n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1568 #if defined(LWS_WITH_ESP8266)
1569 buf[sizeof(buf) - 1] = '\0';
1571 /* vnsprintf returns what it would have written, even if truncated */
1572 if (n > sizeof(buf) - 1)
1573 n = sizeof(buf) - 1;
1578 lwsl_emit(filter, buf);
1581 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1585 va_start(ap, format);
1586 _lws_logv(filter, format, ap);
1590 LWS_VISIBLE void lws_set_log_level(int level,
1591 void (*func)(int level, const char *line))
1598 LWS_VISIBLE int lwsl_visible(int level)
1600 return log_level & level;
1604 lws_is_ssl(struct lws *wsi)
1606 #ifdef LWS_OPENSSL_SUPPORT
1607 return wsi->use_ssl;
1614 #ifdef LWS_OPENSSL_SUPPORT
1616 lws_get_ssl(struct lws *wsi)
1623 lws_partial_buffered(struct lws *wsi)
1625 return !!wsi->trunc_len;
1628 void lws_set_protocol_write_pending(struct lws *wsi,
1629 enum lws_pending_protocol_send pend)
1631 lwsl_info("setting pps %d\n", pend);
1634 lwsl_err("pps overwrite\n");
1636 lws_rx_flow_control(wsi, 0);
1637 lws_callback_on_writable(wsi);
1641 lws_get_peer_write_allowance(struct lws *wsi)
1643 #ifdef LWS_USE_HTTP2
1644 /* only if we are using HTTP2 on this connection */
1645 if (wsi->mode != LWSCM_HTTP2_SERVING)
1647 /* user is only interested in how much he can send, or that he can't */
1648 if (wsi->u.http2.tx_credit <= 0)
1651 return wsi->u.http2.tx_credit;
1659 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1661 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1662 memset(&wsi->u, 0, sizeof(wsi->u));
1666 LWS_VISIBLE struct lws_plat_file_ops *
1667 lws_get_fops(struct lws_context *context)
1669 return (struct lws_plat_file_ops *)context->fops;
1672 LWS_VISIBLE LWS_EXTERN struct lws_context *
1673 lws_get_context(const struct lws *wsi)
1675 return wsi->context;
1678 LWS_VISIBLE LWS_EXTERN int
1679 lws_get_count_threads(struct lws_context *context)
1681 return context->count_threads;
1684 LWS_VISIBLE LWS_EXTERN void *
1685 lws_wsi_user(struct lws *wsi)
1687 return wsi->user_space;
1690 LWS_VISIBLE LWS_EXTERN void
1691 lws_set_wsi_user(struct lws *wsi, void *data)
1693 if (wsi->user_space_externally_allocated)
1694 wsi->user_space = data;
1696 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1700 LWS_VISIBLE LWS_EXTERN struct lws *
1701 lws_get_parent(const struct lws *wsi)
1706 LWS_VISIBLE LWS_EXTERN struct lws *
1707 lws_get_child(const struct lws *wsi)
1709 return wsi->child_list;
1712 LWS_VISIBLE LWS_EXTERN void
1713 lws_set_parent_carries_io(struct lws *wsi)
1715 wsi->parent_carries_io = 1;
1718 LWS_VISIBLE LWS_EXTERN void *
1719 lws_get_opaque_parent_data(const struct lws *wsi)
1721 return wsi->opaque_parent_data;
1724 LWS_VISIBLE LWS_EXTERN void
1725 lws_set_opaque_parent_data(struct lws *wsi, void *data)
1727 wsi->opaque_parent_data = data;
1730 LWS_VISIBLE LWS_EXTERN int
1731 lws_get_child_pending_on_writable(const struct lws *wsi)
1733 return wsi->parent_pending_cb_on_writable;
1736 LWS_VISIBLE LWS_EXTERN void
1737 lws_clear_child_pending_on_writable(struct lws *wsi)
1739 wsi->parent_pending_cb_on_writable = 0;
1742 LWS_VISIBLE LWS_EXTERN int
1743 lws_get_close_length(struct lws *wsi)
1745 return wsi->u.ws.close_in_ping_buffer_len;
1748 LWS_VISIBLE LWS_EXTERN unsigned char *
1749 lws_get_close_payload(struct lws *wsi)
1751 return &wsi->u.ws.ping_payload_buf[LWS_PRE];
1754 LWS_VISIBLE LWS_EXTERN void
1755 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1756 unsigned char *buf, size_t len)
1758 unsigned char *p, *start;
1759 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1761 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1763 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1765 *p++ = (((int)status) >> 8) & 0xff;
1766 *p++ = ((int)status) & 0xff;
1769 while (len-- && p < start + budget)
1772 wsi->u.ws.close_in_ping_buffer_len = p - start;
1776 _lws_rx_flow_control(struct lws *wsi)
1778 struct lws *wsic = wsi->child_list;
1780 /* if he has children, do those if they were changed */
1782 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1783 _lws_rx_flow_control(wsic);
1785 wsic = wsic->sibling_list;
1788 /* there is no pending change */
1789 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1790 // lwsl_debug("%s: no pending change\n", __func__);
1794 /* stuff is still buffered, not ready to really accept new input */
1795 if (wsi->rxflow_buffer) {
1796 /* get ourselves called back to deal with stashed buffer */
1797 lws_callback_on_writable(wsi);
1801 /* pending is cleared, we can change rxflow state */
1803 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1805 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1806 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1808 /* adjust the pollfd for this wsi */
1810 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1811 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1812 lwsl_info("%s: fail\n", __func__);
1816 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1823 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1825 static const unsigned char e0f4[] = {
1826 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1827 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1828 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1829 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1830 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1831 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1832 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1833 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1834 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1835 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1836 0x80 | ((4 - 1) << 2) | 1, /* ea */
1837 0x80 | ((4 - 1) << 2) | 1, /* eb */
1838 0x80 | ((4 - 1) << 2) | 1, /* ec */
1839 0x80 | ((2 - 1) << 2) | 1, /* ed */
1840 0x80 | ((4 - 1) << 2) | 1, /* ee */
1841 0x80 | ((4 - 1) << 2) | 1, /* ef */
1842 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1843 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1844 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1845 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1846 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1849 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1850 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1852 unsigned char s = *state;
1855 unsigned char c = *buf++;
1859 if (c < 0xc2 || c > 0xf4)
1862 s = 0x80 | ((4 - 1) << 2);
1867 if (c < (s & 0xf0) ||
1868 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1870 s = e0f4[21 + (s & 3)];
1879 LWS_VISIBLE LWS_EXTERN int
1880 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1884 static const char *slash = "/";
1886 /* cut up the location into address, port and path */
1888 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1899 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1901 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1907 while (*p && *p != ']')
1914 while (*p && *p != ':' && *p != '/')
1920 while (*p && *p != '/')
1933 #ifdef LWS_NO_EXTENSIONS
1935 /* we need to provide dummy callbacks for internal exts
1936 * so user code runs when faced with a lib compiled with
1937 * extensions disabled.
1941 lws_extension_callback_pm_deflate(struct lws_context *context,
1942 const struct lws_extension *ext,
1944 enum lws_extension_callback_reasons reason,
1945 void *user, void *in, size_t len)
1960 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1964 #ifdef LWS_USE_UNIX_SOCK
1965 struct sockaddr_un serv_unix;
1968 struct sockaddr_in6 serv_addr6;
1970 struct sockaddr_in serv_addr4;
1971 #ifndef LWS_PLAT_OPTEE
1972 socklen_t len = sizeof(struct sockaddr_storage);
1975 struct sockaddr_storage sin;
1978 #ifdef LWS_USE_UNIX_SOCK
1979 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1980 v = (struct sockaddr *)&serv_unix;
1981 n = sizeof(struct sockaddr_un);
1982 bzero((char *) &serv_unix, sizeof(serv_unix));
1983 serv_unix.sun_family = AF_UNIX;
1984 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1985 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1989 strcpy(serv_unix.sun_path, iface);
1990 if (serv_unix.sun_path[0] == '@')
1991 serv_unix.sun_path[0] = '\0';
1995 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1996 if (LWS_IPV6_ENABLED(vhost)) {
1997 v = (struct sockaddr *)&serv_addr6;
1998 n = sizeof(struct sockaddr_in6);
1999 bzero((char *) &serv_addr6, sizeof(serv_addr6));
2001 if (interface_to_sa(vhost, iface,
2002 (struct sockaddr_in *)v, n) < 0) {
2003 lwsl_err("Unable to find interface %s\n", iface);
2006 serv_addr6.sin6_scope_id = lws_get_addr_scope(iface);
2009 serv_addr6.sin6_family = AF_INET6;
2010 serv_addr6.sin6_port = htons(port);
2014 v = (struct sockaddr *)&serv_addr4;
2015 n = sizeof(serv_addr4);
2016 bzero((char *) &serv_addr4, sizeof(serv_addr4));
2017 serv_addr4.sin_addr.s_addr = INADDR_ANY;
2018 serv_addr4.sin_family = AF_INET;
2019 #if !defined(LWS_WITH_ESP32)
2022 interface_to_sa(vhost, iface,
2023 (struct sockaddr_in *)v, n) < 0) {
2024 lwsl_err("Unable to find interface %s\n", iface);
2028 serv_addr4.sin_port = htons(port);
2031 n = bind(sockfd, v, n);
2032 #ifdef LWS_USE_UNIX_SOCK
2033 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
2034 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
2035 sockfd, iface, n, LWS_ERRNO);
2040 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
2041 sockfd, port, n, LWS_ERRNO);
2045 #ifndef LWS_PLAT_OPTEE
2046 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
2047 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
2050 #if defined(LWS_USE_IPV6)
2051 port = (sin.ss_family == AF_INET6) ?
2052 ntohs(((struct sockaddr_in6 *) &sin)->sin6_port) :
2053 ntohs(((struct sockaddr_in *) &sin)->sin_port);
2055 port = ntohs(((struct sockaddr_in *) &sin)->sin_port);
2062 #if defined(LWS_USE_IPV6)
2063 LWS_EXTERN unsigned long
2064 lws_get_addr_scope(const char *ipaddr)
2066 unsigned long scope = 0;
2069 struct ifaddrs *addrs, *addr;
2070 char ip[NI_MAXHOST];
2074 for (addr = addrs; addr; addr = addr->ifa_next) {
2075 if (!addr->ifa_addr ||
2076 addr->ifa_addr->sa_family != AF_INET6)
2079 getnameinfo(addr->ifa_addr,
2080 sizeof(struct sockaddr_in6),
2082 NULL, 0, NI_NUMERICHOST);
2086 if (ip[i++] == '%') {
2091 if (!strcmp(ip, ipaddr)) {
2092 scope = if_nametoindex(addr->ifa_name);
2098 PIP_ADAPTER_ADDRESSES adapter, addrs = NULL;
2099 PIP_ADAPTER_UNICAST_ADDRESS addr;
2102 struct sockaddr_in6 *sockaddr;
2103 char ip[NI_MAXHOST];
2107 for (i = 0; i < 5; i++)
2109 ret = GetAdaptersAddresses(AF_INET6, GAA_FLAG_INCLUDE_PREFIX,
2110 NULL, addrs, &size);
2111 if ((ret == NO_ERROR) || (ret == ERROR_NO_DATA)) {
2113 } else if (ret == ERROR_BUFFER_OVERFLOW)
2117 addrs = (IP_ADAPTER_ADDRESSES *) malloc(size);
2125 lwsl_err("Failed to get IPv6 address table (%d)", ret);
2130 if ((ret == NO_ERROR) && (addrs))
2133 while ((adapter) && (!found))
2135 addr = adapter->FirstUnicastAddress;
2136 while ((addr) && (!found))
2138 if (addr->Address.lpSockaddr->sa_family == AF_INET6)
2140 sockaddr = (struct sockaddr_in6 *) (addr->Address.lpSockaddr);
2142 lws_plat_inet_ntop(sockaddr->sin6_family, &sockaddr->sin6_addr,
2145 if (!strcmp(ip, ipaddr)) {
2146 scope = sockaddr->sin6_scope_id;
2153 adapter = adapter->Next;
2165 lws_restart_ws_ping_pong_timer(struct lws *wsi)
2167 if (!wsi->context->ws_ping_pong_interval)
2169 if (wsi->state != LWSS_ESTABLISHED)
2172 wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
2173 wsi->context->ws_ping_pong_interval;
2176 static const char *hex = "0123456789ABCDEF";
2178 LWS_VISIBLE LWS_EXTERN const char *
2179 lws_sql_purify(char *escaped, const char *string, int len)
2181 const char *p = string;
2184 while (*p && len-- > 2) {
2198 LWS_VISIBLE LWS_EXTERN const char *
2199 lws_json_purify(char *escaped, const char *string, int len)
2201 const char *p = string;
2209 while (*p && len-- > 6) {
2210 if (*p == '\"' || *p == '\\' || *p < 0x20) {
2215 *q++ = hex[((*p) >> 4) & 15];
2216 *q++ = hex[(*p) & 15];
2227 LWS_VISIBLE LWS_EXTERN const char *
2228 lws_urlencode(char *escaped, const char *string, int len)
2230 const char *p = string;
2233 while (*p && len-- > 3) {
2239 if ((*p >= '0' && *p <= '9') ||
2240 (*p >= 'A' && *p <= 'Z') ||
2241 (*p >= 'a' && *p <= 'z')) {
2246 *q++ = hex[(*p >> 4) & 0xf];
2247 *q++ = hex[*p & 0xf];
2257 LWS_VISIBLE LWS_EXTERN int
2258 lws_urldecode(char *string, const char *escaped, int len)
2263 while (*escaped && len) {
2266 if (*escaped == '%') {
2271 if (*escaped == '+') {
2277 *string++ = *escaped++;
2281 n = char_to_hex(*escaped);
2290 n = char_to_hex(*escaped);
2294 *string++ = sum | n;
2306 LWS_VISIBLE LWS_EXTERN int
2307 lws_finalize_startup(struct lws_context *context)
2309 struct lws_context_creation_info info;
2311 info.uid = context->uid;
2312 info.gid = context->gid;
2314 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
2315 memcpy(info.caps, context->caps, sizeof(info.caps));
2316 info.count_caps = context->count_caps;
2319 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2320 lws_plat_drop_app_privileges(&info);
2326 lws_snprintf(char *str, size_t size, const char *format, ...)
2334 va_start(ap, format);
2335 n = vsnprintf(str, size, format, ap);
2345 LWS_VISIBLE LWS_EXTERN int
2346 lws_is_cgi(struct lws *wsi) {
2357 urlencode(const char *in, int inlen, char *out, int outlen)
2359 char *start = out, *end = out + outlen;
2361 while (inlen-- && out < end - 4) {
2362 if ((*in >= 'A' && *in <= 'Z') ||
2363 (*in >= 'a' && *in <= 'z') ||
2364 (*in >= '0' && *in <= '9') ||
2378 *out++ = hex[(*in) >> 4];
2379 *out++ = hex[(*in++) & 15];
2390 lws_create_basic_wsi(struct lws_context *context, int tsi)
2392 struct lws *new_wsi;
2394 if ((unsigned int)context->pt[tsi].fds_count ==
2395 context->fd_limit_per_thread - 1) {
2396 lwsl_err("no space for new conn\n");
2400 new_wsi = lws_zalloc(sizeof(struct lws));
2401 if (new_wsi == NULL) {
2402 lwsl_err("Out of memory for new connection\n");
2407 new_wsi->context = context;
2408 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2409 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2411 /* initialize the instance struct */
2413 new_wsi->state = LWSS_CGI;
2414 new_wsi->mode = LWSCM_CGI;
2415 new_wsi->hdr_parsing_completed = 0;
2416 new_wsi->position_in_fds_table = -1;
2419 * these can only be set once the protocol is known
2420 * we set an unestablished connection's protocol pointer
2421 * to the start of the defauly vhost supported list, so it can look
2422 * for matching ones during the handshake
2424 new_wsi->protocol = context->vhost_list->protocols;
2425 new_wsi->user_space = NULL;
2426 new_wsi->ietf_spec_revision = 0;
2427 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2428 context->count_wsi_allocated++;
2433 LWS_VISIBLE LWS_EXTERN int
2434 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2435 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2437 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2438 char *env_array[30], cgi_path[400], e[1024], *p = e,
2439 *end = p + sizeof(e) - 1, tok[256], *t;
2440 struct lws_cgi *cgi;
2441 int n, m, i, uritok = -1;
2444 * give the master wsi a cgi struct
2447 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2449 lwsl_err("%s: OOM\n", __func__);
2453 wsi->cgi->response_code = HTTP_STATUS_OK;
2456 cgi->wsi = wsi; /* set cgi's owning wsi */
2458 /* create pipes for [stdin|stdout] and [stderr] */
2460 for (n = 0; n < 3; n++)
2461 if (pipe(cgi->pipe_fds[n]) == -1)
2464 /* create cgi wsis for each stdin/out/err fd */
2466 for (n = 0; n < 3; n++) {
2467 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2468 if (!cgi->stdwsi[n])
2470 cgi->stdwsi[n]->cgi_channel = n;
2471 cgi->stdwsi[n]->vhost = wsi->vhost;
2473 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2474 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2476 /* read side is 0, stdin we want the write side, others read */
2477 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2478 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2479 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2484 for (n = 0; n < 3; n++) {
2485 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2486 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2488 cgi->stdwsi[n]->parent = wsi;
2489 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2490 wsi->child_list = cgi->stdwsi[n];
2493 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2494 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2495 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2497 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2498 cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2499 cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2500 cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2502 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2504 /* the cgi stdout is always sending us http1.x header data first */
2505 wsi->hdr_state = LCHS_HEADER;
2507 /* add us to the pt list of active cgis */
2508 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2509 cgi->cgi_list = pt->cgi_list;
2512 /* prepare his CGI env */
2516 if (lws_is_ssl(wsi))
2517 env_array[n++] = "HTTPS=ON";
2518 if (wsi->u.hdr.ah) {
2519 static const unsigned char meths[] = {
2522 WSI_TOKEN_OPTIONS_URI,
2524 WSI_TOKEN_PATCH_URI,
2525 WSI_TOKEN_DELETE_URI,
2527 static const char * const meth_names[] = {
2528 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2531 for (m = 0; m < ARRAY_SIZE(meths); m++)
2532 if (lws_hdr_total_length(wsi, meths[m]) >=
2533 script_uri_path_len) {
2541 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2542 lws_hdr_simple_ptr(wsi, uritok));
2543 cgi_path[sizeof(cgi_path) - 1] = '\0';
2544 env_array[n++] = cgi_path;
2547 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2552 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2553 /* dump the individual URI Arg parameters */
2556 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2557 WSI_TOKEN_HTTP_URI_ARGS, m);
2561 while (*t && *t != '=' && p < end - 4)
2565 i = urlencode(t, i- (t - tok), p, end - p);
2577 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2578 lws_hdr_simple_ptr(wsi, uritok) +
2579 script_uri_path_len);
2582 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2584 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2585 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2588 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2590 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2591 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2594 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2596 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2597 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2600 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2602 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2603 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2606 if (uritok == WSI_TOKEN_POST_URI) {
2607 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2609 p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2610 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2613 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2615 p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2616 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2621 p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2625 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2627 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2630 mp_cgienv = mp_cgienv->next;
2633 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2634 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2635 env_array[n] = NULL;
2638 for (m = 0; m < n; m++)
2639 lwsl_err(" %s\n", env_array[m]);
2643 * Actually having made the env, as a cgi we don't need the ah
2646 if (lws_header_table_is_in_detachable_state(wsi))
2647 lws_header_table_detach(wsi, 0);
2649 /* we are ready with the redirection pipes... run the thing */
2650 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2656 lwsl_err("fork failed, errno %d", errno);
2660 #if defined(__linux__)
2661 prctl(PR_SET_PDEATHSIG, SIGTERM);
2663 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2666 /* we are the parent process */
2667 wsi->context->count_cgi_spawned++;
2668 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2672 /* somewhere we can at least read things and enter it */
2674 lwsl_notice("%s: Failed to chdir\n", __func__);
2676 /* We are the forked process, redirect and kill inherited things.
2678 * Because of vfork(), we cannot do anything that changes pages in
2679 * the parent environment. Stuff that changes kernel state for the
2680 * process is OK. Stuff that happens after the execvpe() is OK.
2683 for (n = 0; n < 3; n++) {
2684 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2685 lwsl_err("%s: stdin dup2 failed\n", __func__);
2688 close(cgi->pipe_fds[n][!(n == 0)]);
2691 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2692 for (m = 0; m < n; m++) {
2693 p = strchr(env_array[m], '=');
2695 setenv(env_array[m], p, 1);
2697 execvp(exec_array[0], (char * const *)&exec_array[0]);
2699 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2705 /* drop us from the pt cgi list */
2706 pt->cgi_list = cgi->cgi_list;
2709 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2711 for (n = 0; n < 3; n++)
2712 if (wsi->cgi->stdwsi[n])
2713 lws_free_wsi(cgi->stdwsi[n]);
2716 for (n = 0; n < 3; n++) {
2717 if (cgi->pipe_fds[n][0])
2718 close(cgi->pipe_fds[n][0]);
2719 if (cgi->pipe_fds[n][1])
2720 close(cgi->pipe_fds[n][1]);
2723 lws_free_set_NULL(wsi->cgi);
2725 lwsl_err("%s: failed\n", __func__);
2730 /* we have to parse out these headers in the CGI output */
2732 static const char * const significant_hdr[SIGNIFICANT_HDR_COUNT] = {
2736 "transfer-encoding: chunked",
2739 LWS_VISIBLE LWS_EXTERN int
2740 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2743 unsigned char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2744 *end = &buf[sizeof(buf) - 1 - LWS_PRE];
2750 while (wsi->hdr_state != LHCS_PAYLOAD) {
2751 /* we have to separate header / finalize and
2752 * payload chunks, since they need to be
2753 * handled separately
2756 switch (wsi->hdr_state) {
2759 lwsl_info("LHCS_RESPONSE: issuing response %d\n",
2760 wsi->cgi->response_code);
2761 if (lws_add_http_header_status(wsi, wsi->cgi->response_code, &p, end))
2763 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2764 (unsigned char *)"close", 5, &p, end))
2766 n = lws_write(wsi, start, p - start,
2767 LWS_WRITE_HTTP_HEADERS);
2769 /* finalize cached headers before dumping them */
2770 if (lws_finalize_http_header(wsi,
2771 (unsigned char **)&wsi->cgi->headers_pos,
2772 (unsigned char *)wsi->cgi->headers_end)) {
2774 lwsl_notice("finalize failed\n");
2778 wsi->hdr_state = LHCS_DUMP_HEADERS;
2779 wsi->reason_bf |= 8;
2780 lws_callback_on_writable(wsi);
2781 /* back to the loop for writeability again */
2784 case LHCS_DUMP_HEADERS:
2786 n = wsi->cgi->headers_pos - wsi->cgi->headers_dumped;
2790 lwsl_debug("LHCS_DUMP_HEADERS: %d\n", n);
2792 m = lws_write(wsi, (unsigned char *)wsi->cgi->headers_dumped,
2793 n, LWS_WRITE_HTTP_HEADERS);
2795 lwsl_debug("%s: write says %d\n", __func__, m);
2798 wsi->cgi->headers_dumped += n;
2799 if (wsi->cgi->headers_dumped == wsi->cgi->headers_pos) {
2800 wsi->hdr_state = LHCS_PAYLOAD;
2801 lws_free_set_NULL(wsi->cgi->headers_buf);
2802 lwsl_debug("freed cgi headers\n");
2804 wsi->reason_bf |= 8;
2805 lws_callback_on_writable(wsi);
2808 /* writeability becomes uncertain now we wrote
2809 * something, we must return to the event loop
2814 if (!wsi->cgi->headers_buf) {
2815 /* if we don't already have a headers buf, cook one up */
2817 wsi->cgi->headers_buf = malloc(n);
2818 if (!wsi->cgi->headers_buf) {
2823 lwsl_debug("allocated cgi hdrs\n");
2824 wsi->cgi->headers_pos = wsi->cgi->headers_buf;
2825 wsi->cgi->headers_dumped = wsi->cgi->headers_pos;
2826 wsi->cgi->headers_end = wsi->cgi->headers_buf + n - 1;
2828 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2829 wsi->cgi->match[n] = 0;
2834 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2836 if (errno != EAGAIN) {
2837 lwsl_debug("%s: read says %d\n", __func__, n);
2843 if (wsi->cgi->headers_pos >= wsi->cgi->headers_end - 4) {
2844 lwsl_notice("CGI headers larger than buffer size\n");
2850 lwsl_debug("-- 0x%02X %c %d %d\n", (unsigned char)c, c, wsi->cgi->match[1], wsi->hdr_state);
2853 switch (wsi->hdr_state) {
2856 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2857 /* significant headers with numeric decimal payloads */
2858 if (!significant_hdr[n][wsi->cgi->match[n]] &&
2859 (c >= '0' && c <= '9') &&
2860 wsi->cgi->lp < sizeof(wsi->cgi->l) - 1) {
2861 wsi->cgi->l[wsi->cgi->lp++] = c;
2862 wsi->cgi->l[wsi->cgi->lp] = '\0';
2864 case SIGNIFICANT_HDR_CONTENT_LENGTH:
2865 wsi->cgi->content_length = atoll(wsi->cgi->l);
2867 case SIGNIFICANT_HDR_STATUS:
2868 wsi->cgi->response_code = atol(wsi->cgi->l);
2869 lwsl_debug("Status set to %d\n", wsi->cgi->response_code);
2875 /* hits up to the NUL are sticky until next hdr */
2876 if (significant_hdr[n][wsi->cgi->match[n]]) {
2877 if (tolower(c) == significant_hdr[n][wsi->cgi->match[n]])
2878 wsi->cgi->match[n]++;
2880 wsi->cgi->match[n] = 0;
2884 /* some cgi only send us \x0a for EOL */
2886 wsi->hdr_state = LCHS_SINGLE_0A;
2887 *wsi->cgi->headers_pos++ = '\x0d';
2889 *wsi->cgi->headers_pos++ = c;
2891 wsi->hdr_state = LCHS_LF1;
2893 if (wsi->hdr_state != LCHS_HEADER &&
2894 !significant_hdr[SIGNIFICANT_HDR_TRANSFER_ENCODING][wsi->cgi->match[SIGNIFICANT_HDR_TRANSFER_ENCODING]]) {
2895 lwsl_debug("cgi produced chunked\n");
2896 wsi->cgi->explicitly_chunked = 1;
2899 /* presence of Location: mandates 302 retcode */
2900 if (wsi->hdr_state != LCHS_HEADER &&
2901 !significant_hdr[SIGNIFICANT_HDR_LOCATION][wsi->cgi->match[SIGNIFICANT_HDR_LOCATION]]) {
2902 lwsl_debug("CGI: Location hdr seen\n");
2903 wsi->cgi->response_code = 302;
2908 *wsi->cgi->headers_pos++ = c;
2910 wsi->hdr_state = LCHS_CR2;
2913 /* we got \r[^\n]... it's unreasonable */
2914 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2920 wsi->hdr_state = LCHS_LF2;
2923 wsi->hdr_state = LCHS_HEADER;
2924 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2925 wsi->cgi->match[n] = 0;
2930 case LCHS_SINGLE_0A:
2933 lwsl_debug("Content-Length: %lld\n", (unsigned long long)wsi->cgi->content_length);
2934 wsi->hdr_state = LHCS_RESPONSE;
2935 /* drop the \0xa ... finalize will add it if needed */
2939 /* we got \r\n\r[^\n]... it's unreasonable */
2941 /* we got \x0anext header, it's reasonable */
2942 *wsi->cgi->headers_pos++ = c;
2943 wsi->hdr_state = LCHS_HEADER;
2944 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2945 wsi->cgi->match[n] = 0;
2953 /* ran out of input, ended the headers, or filled up the headers buf */
2954 if (!n || wsi->hdr_state == LHCS_PAYLOAD)
2958 /* payload processing */
2960 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2961 start, sizeof(buf) - LWS_PRE);
2963 if (n < 0 && errno != EAGAIN) {
2964 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2968 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2969 //lwsl_notice("write %d\n", m);
2971 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2974 wsi->cgi->content_length_seen += m;
2980 LWS_VISIBLE LWS_EXTERN int
2981 lws_cgi_kill(struct lws *wsi)
2983 struct lws_cgi_args args;
2986 lwsl_debug("%s: %p\n", __func__, wsi);
2991 if (wsi->cgi->pid > 0) {
2992 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2994 lwsl_debug("%s: PID %d reaped\n", __func__,
2998 /* kill the process group */
2999 n = kill(-wsi->cgi->pid, SIGTERM);
3000 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
3001 wsi->cgi->pid, n, errno);
3004 * hum seen errno=3 when process is listed in ps,
3005 * it seems we don't always retain process grouping
3007 * Direct these fallback attempt to the exact child
3009 n = kill(wsi->cgi->pid, SIGTERM);
3011 n = kill(wsi->cgi->pid, SIGPIPE);
3013 n = kill(wsi->cgi->pid, SIGKILL);
3015 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
3016 __func__, wsi->cgi->pid, errno);
3020 /* He could be unkillable because he's a zombie */
3023 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
3025 lwsl_debug("%s: reaped PID %d\n", __func__, n);
3027 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
3029 lwsl_debug("%s: reaped PID %d\n", __func__, n);
3035 args.stdwsi = &wsi->cgi->stdwsi[0];
3037 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
3038 wsi->protocol->callback,
3039 wsi, LWS_CALLBACK_CGI_TERMINATED,
3041 (void *)&args, 0)) {
3043 if (!wsi->cgi->being_closed)
3044 lws_close_free_wsi(wsi, 0);
3051 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
3053 struct lws_cgi **pcgi, *cgi = NULL;
3057 /* find finished guys but don't reap yet */
3058 n = waitpid(-1, &status, WNOHANG);
3061 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
3063 pcgi = &pt->cgi_list;
3065 /* check all the subprocesses on the cgi list */
3067 /* get the next one first as list may change */
3069 pcgi = &(*pcgi)->cgi_list;
3074 /* finish sending cached headers */
3075 if (cgi->headers_buf)
3078 /* wait for stdout to be drained */
3079 if (cgi->content_length > cgi->content_length_seen)
3082 if (cgi->content_length) {
3083 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3084 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3088 waitpid(n, &status, WNOHANG);
3090 * he's already terminated so no need for kill()
3091 * but we should do the terminated cgi callback
3092 * and close him if he's not already closing
3094 if (n == cgi->pid) {
3095 lwsl_debug("%s: found PID %d on cgi list\n",
3098 if (!cgi->content_length && cgi->explicitly_chunked) {
3100 * well, if he sends chunked... give him 5s after the
3101 * cgi terminated to send buffered
3103 cgi->chunked_grace++;
3109 lws_cgi_kill(cgi->wsi);
3115 /* if not found on the cgi list, as he's one of ours, reap */
3117 lwsl_debug("%s: reading PID %d although no cgi match\n",
3119 waitpid(n, &status, WNOHANG);
3123 /* disable this to confirm timeout cgi cleanup flow */
3125 pcgi = &pt->cgi_list;
3127 /* check all the subprocesses on the cgi list */
3129 /* get the next one first as list may change */
3131 pcgi = &(*pcgi)->cgi_list;
3136 /* we deferred killing him after reaping his PID */
3137 if (cgi->chunked_grace) {
3138 cgi->chunked_grace++;
3139 if (cgi->chunked_grace < 5)
3144 /* finish sending cached headers */
3145 if (cgi->headers_buf)
3148 /* wait for stdout to be drained */
3149 if (cgi->content_length > cgi->content_length_seen)
3152 if (cgi->content_length)
3153 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3154 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3157 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
3159 if (!cgi->content_length) {
3161 * well, if he sends chunked... give him 5s after the
3162 * cgi terminated to send buffered
3164 cgi->chunked_grace++;
3168 lwsl_debug("%s: found PID %d on cgi list\n",
3169 __func__, cgi->pid);
3172 lws_cgi_kill(cgi->wsi);
3179 /* general anti zombie defence */
3180 // n = waitpid(-1, &status, WNOHANG);
3182 // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
3188 #ifdef LWS_NO_EXTENSIONS
3190 lws_set_extension_option(struct lws *wsi, const char *ext_name,
3191 const char *opt_name, const char *opt_val)
3197 #ifdef LWS_WITH_ACCESS_LOG
3199 lws_access_log(struct lws *wsi)
3201 char *p = wsi->access_log.user_agent, ass[512];
3204 if (!wsi->access_log_pending)
3207 if (!wsi->access_log.header_log)
3213 l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
3214 wsi->access_log.header_log,
3215 wsi->access_log.response, wsi->access_log.sent, p);
3217 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
3218 if (write(wsi->vhost->log_fd, ass, l) != l)
3219 lwsl_err("Failed to write log\n");
3221 lwsl_err("%s", ass);
3223 if (wsi->access_log.header_log) {
3224 lws_free(wsi->access_log.header_log);
3225 wsi->access_log.header_log = NULL;
3227 if (wsi->access_log.user_agent) {
3228 lws_free(wsi->access_log.user_agent);
3229 wsi->access_log.user_agent = NULL;
3231 wsi->access_log_pending = 0;
3238 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
3240 const struct lws_vhost *vh = ctx->vhost_list;
3244 cs->rx += vh->conn_stats.rx;
3245 cs->tx += vh->conn_stats.tx;
3246 cs->conn += vh->conn_stats.conn;
3247 cs->trans += vh->conn_stats.trans;
3248 cs->ws_upg += vh->conn_stats.ws_upg;
3249 cs->http2_upg += vh->conn_stats.http2_upg;
3250 cs->rejected += vh->conn_stats.rejected;
3252 vh = vh->vhost_next;
3256 #ifdef LWS_WITH_SERVER_STATUS
3259 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
3261 static const char * const prots[] = {
3270 char *orig = buf, *end = buf + len - 1, first = 1;
3276 buf += lws_snprintf(buf, end - buf,
3277 "{\n \"name\":\"%s\",\n"
3278 " \"port\":\"%d\",\n"
3279 " \"use_ssl\":\"%d\",\n"
3280 " \"sts\":\"%d\",\n"
3281 " \"rx\":\"%llu\",\n"
3282 " \"tx\":\"%llu\",\n"
3283 " \"conn\":\"%lu\",\n"
3284 " \"trans\":\"%lu\",\n"
3285 " \"ws_upg\":\"%lu\",\n"
3286 " \"rejected\":\"%lu\",\n"
3287 " \"http2_upg\":\"%lu\""
3289 vh->name, vh->listen_port,
3290 #ifdef LWS_OPENSSL_SUPPORT
3295 !!(vh->options & LWS_SERVER_OPTION_STS),
3296 vh->conn_stats.rx, vh->conn_stats.tx,
3297 vh->conn_stats.conn, vh->conn_stats.trans,
3298 vh->conn_stats.ws_upg,
3299 vh->conn_stats.rejected,
3300 vh->conn_stats.http2_upg
3303 if (vh->mount_list) {
3304 const struct lws_http_mount *m = vh->mount_list;
3306 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
3309 buf += lws_snprintf(buf, end - buf, ",");
3310 buf += lws_snprintf(buf, end - buf,
3311 "\n {\n \"mountpoint\":\"%s\",\n"
3312 " \"origin\":\"%s%s\",\n"
3313 " \"cache_max_age\":\"%d\",\n"
3314 " \"cache_reuse\":\"%d\",\n"
3315 " \"cache_revalidate\":\"%d\",\n"
3316 " \"cache_intermediaries\":\"%d\"\n"
3319 prots[m->origin_protocol],
3323 m->cache_revalidate,
3324 m->cache_intermediaries);
3326 buf += lws_snprintf(buf, end - buf,
3327 ",\n \"default\":\"%s\"",
3329 buf += lws_snprintf(buf, end - buf, "\n }");
3333 buf += lws_snprintf(buf, end - buf, "\n ]");
3336 if (vh->protocols) {
3340 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
3341 while (n < vh->count_protocols) {
3343 buf += lws_snprintf(buf, end - buf, ",");
3344 buf += lws_snprintf(buf, end - buf,
3346 " \"status\":\"ok\"\n }\n }"
3348 vh->protocols[n].name);
3352 buf += lws_snprintf(buf, end - buf, "\n ]");
3355 buf += lws_snprintf(buf, end - buf, "\n}");
3361 LWS_EXTERN LWS_VISIBLE int
3362 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
3365 char *orig = buf, *end = buf + len - 1, first = 1;
3366 const struct lws_vhost *vh = context->vhost_list;
3367 const struct lws_context_per_thread *pt;
3368 time_t t = time(NULL);
3369 int n, listening = 0, cgi_count = 0;
3370 struct lws_conn_stats cs;
3373 struct lws_cgi * const *pcgi;
3376 #ifdef LWS_USE_LIBUV
3380 buf += lws_snprintf(buf, end - buf, "{ "
3381 "\"version\":\"%s\",\n"
3382 "\"uptime\":\"%ld\",\n",
3383 lws_get_library_version(),
3386 #ifdef LWS_HAVE_GETLOADAVG
3391 m = getloadavg(d, 3);
3392 for (n = 0; n < m; n++) {
3393 buf += lws_snprintf(buf, end - buf,
3394 "\"l%d\":\"%.2f\",\n",
3400 buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
3402 buf += lws_snprintf(buf, end - buf, "{ "
3403 "\"context_uptime\":\"%ld\",\n"
3404 "\"cgi_spawned\":\"%d\",\n"
3405 "\"pt_fd_max\":\"%d\",\n"
3406 "\"ah_pool_max\":\"%d\",\n"
3407 "\"deprecated\":\"%d\",\n"
3408 "\"wsi_alive\":\"%d\",\n",
3409 (unsigned long)(t - context->time_up),
3410 context->count_cgi_spawned,
3411 context->fd_limit_per_thread,
3412 context->max_http_header_pool,
3413 context->deprecated,
3414 context->count_wsi_allocated);
3416 buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
3417 for (n = 0; n < context->count_threads; n++) {
3418 pt = &context->pt[n];
3420 buf += lws_snprintf(buf, end - buf, ",");
3421 buf += lws_snprintf(buf, end - buf,
3423 " \"fds_count\":\"%d\",\n"
3424 " \"ah_pool_inuse\":\"%d\",\n"
3425 " \"ah_wait_list\":\"%d\"\n"
3428 pt->ah_count_in_use,
3429 pt->ah_wait_list_length);
3432 buf += lws_snprintf(buf, end - buf, "]");
3434 buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3437 vh = context->vhost_list;
3439 cs = context->conn_stats;
3440 lws_sum_stats(context, &cs);
3447 buf += lws_json_dump_vhost(vh, buf, end - buf);
3452 vh = vh->vhost_next;
3455 buf += lws_snprintf(buf, end - buf,
3456 "],\n\"listen_wsi\":\"%d\",\n"
3457 " \"rx\":\"%llu\",\n"
3458 " \"tx\":\"%llu\",\n"
3459 " \"conn\":\"%lu\",\n"
3460 " \"trans\":\"%lu\",\n"
3461 " \"ws_upg\":\"%lu\",\n"
3462 " \"rejected\":\"%lu\",\n"
3463 " \"http2_upg\":\"%lu\"",
3465 cs.rx, cs.tx, cs.conn, cs.trans,
3466 cs.ws_upg, cs.rejected, cs.http2_upg);
3469 for (n = 0; n < context->count_threads; n++) {
3470 pt = &context->pt[n];
3471 pcgi = &pt->cgi_list;
3474 pcgi = &(*pcgi)->cgi_list;
3480 buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3483 buf += lws_snprintf(buf, end - buf, "}");
3486 buf += lws_snprintf(buf, end - buf, "]}\n ");
3493 #if defined(LWS_WITH_STATS)
3495 LWS_VISIBLE LWS_EXTERN uint64_t
3496 lws_stats_get(struct lws_context *context, int index)
3498 if (index >= LWSSTATS_SIZE)
3501 return context->lws_stats[index];
3504 LWS_VISIBLE LWS_EXTERN void
3505 lws_stats_log_dump(struct lws_context *context)
3507 struct lws_vhost *v = context->vhost_list;
3510 if (!context->updated)
3513 context->updated = 0;
3516 lwsl_notice("LWS internal statistics dump ----->\n");
3517 lwsl_notice("LWSSTATS_C_CONNECTIONS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_CONNECTIONS));
3518 lwsl_notice("LWSSTATS_C_API_CLOSE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_CLOSE));
3519 lwsl_notice("LWSSTATS_C_API_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_READ));
3520 lwsl_notice("LWSSTATS_C_API_LWS_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_LWS_WRITE));
3521 lwsl_notice("LWSSTATS_C_API_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_WRITE));
3522 lwsl_notice("LWSSTATS_C_WRITE_PARTIALS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITE_PARTIALS));
3523 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_REQ));
3524 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_EFF_REQ));
3525 lwsl_notice("LWSSTATS_C_WRITEABLE_CB: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB));
3526 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_FAILED));
3527 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED));
3528 lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX));
3530 lwsl_notice("LWSSTATS_C_TIMEOUTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_TIMEOUTS));
3531 lwsl_notice("LWSSTATS_C_SERVICE_ENTRY: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SERVICE_ENTRY));
3532 lwsl_notice("LWSSTATS_B_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ));
3533 lwsl_notice("LWSSTATS_B_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE));
3534 lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS));
3535 lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000);
3536 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED))
3537 lwsl_notice(" Avg accept delay: %8llums\n",
3538 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) /
3539 lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000);
3540 lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / 1000);
3541 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX))
3542 lwsl_notice(" Avg accept-rx delay: %8llums\n",
3543 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) /
3544 lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000);
3546 lwsl_notice("LWSSTATS_MS_WRITABLE_DELAY: %8lluus\n",
3547 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY));
3548 lwsl_notice("LWSSTATS_MS_WORST_WRITABLE_DELAY: %8lluus\n",
3549 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WORST_WRITABLE_DELAY));
3550 if (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))
3551 lwsl_notice(" Avg writable delay: %8lluus\n",
3552 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY) /
3553 lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)));
3554 lwsl_notice("Simultaneous SSL restriction: %8d/%d/%d\n", context->simultaneous_ssl,
3555 context->simultaneous_ssl_restriction, context->ssl_gate_accepts);
3557 lwsl_notice("Live wsi: %8d\n", context->count_wsi_allocated);
3559 #if defined(LWS_WITH_STATS)
3560 context->updated = 1;
3566 struct lws_context_per_thread *pt = &context->pt[(int)v->lserv_wsi->tsi];
3567 struct lws_pollfd *pfd;
3569 pfd = &pt->fds[v->lserv_wsi->position_in_fds_table];
3571 lwsl_notice(" Listen port %d actual POLLIN: %d\n",
3572 v->listen_port, (int)pfd->events & LWS_POLLIN);
3578 for (n = 0; n < context->count_threads; n++) {
3579 struct lws_context_per_thread *pt = &context->pt[n];
3583 lwsl_notice("PT %d\n", n + 1);
3587 lwsl_notice(" AH in use / max: %d / %d\n",
3588 pt->ah_count_in_use,
3589 context->max_http_header_pool);
3591 wl = pt->ah_wait_list;
3594 wl = wl->u.hdr.ah_wait_list;
3597 lwsl_notice(" AH wait list count / actual: %d / %d\n",
3598 pt->ah_wait_list_length, m);
3607 lws_stats_atomic_bump(struct lws_context * context,
3608 struct lws_context_per_thread *pt, int index, uint64_t bump)
3611 context->lws_stats[index] += bump;
3612 if (index != LWSSTATS_C_SERVICE_ENTRY)
3613 context->updated = 1;
3618 lws_stats_atomic_max(struct lws_context * context,
3619 struct lws_context_per_thread *pt, int index, uint64_t val)
3622 if (val > context->lws_stats[index]) {
3623 context->lws_stats[index] = val;
3624 context->updated = 1;