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;
826 addr4.sin_family = AF_UNSPEC;
829 if (LWS_IPV6_ENABLED(vh)) {
830 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
831 lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
835 // Strip off the IPv4 to IPv6 header if one exists
836 if (strncmp(rip, "::ffff:", 7) == 0)
837 memmove(rip, rip + 7, strlen(rip) - 6);
839 getnameinfo((struct sockaddr *)ads,
840 sizeof(struct sockaddr_in6), name,
841 name_len, NULL, 0, 0);
847 struct addrinfo *result;
849 memset(&ai, 0, sizeof ai);
850 ai.ai_family = PF_UNSPEC;
851 ai.ai_socktype = SOCK_STREAM;
852 ai.ai_flags = AI_CANONNAME;
853 #if !defined(LWS_WITH_ESP32)
854 if (getnameinfo((struct sockaddr *)ads,
855 sizeof(struct sockaddr_in),
856 name, name_len, NULL, 0, 0))
862 if (getaddrinfo(name, NULL, &ai, &result))
866 while (addr4.sin_family == AF_UNSPEC && res) {
867 switch (res->ai_family) {
869 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
870 addr4.sin_family = AF_INET;
876 freeaddrinfo(result);
879 if (addr4.sin_family == AF_UNSPEC)
882 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
900 LWS_VISIBLE const char *
901 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
906 struct sockaddr_in6 sin6;
908 struct sockaddr_in sin4;
912 if (wsi->parent_carries_io)
916 if (LWS_IPV6_ENABLED(wsi->vhost)) {
930 if (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {
931 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
935 return lws_plat_inet_ntop(af, q, name, namelen);
937 #if defined(LWS_WITH_ESP8266)
938 return lws_plat_get_peer_simple(wsi, name, namelen);
947 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
948 int name_len, char *rip, int rip_len)
950 #ifndef LWS_PLAT_OPTEE
954 struct sockaddr_in6 sin6;
956 struct sockaddr_in sin4;
957 struct lws_context *context = wsi->context;
964 lws_latency_pre(context, wsi);
967 if (LWS_IPV6_ENABLED(wsi->vhost)) {
977 if (getpeername(fd, p, &len) < 0) {
978 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
982 ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
985 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
998 lws_context_user(struct lws_context *context)
1000 return context->user_space;
1003 LWS_VISIBLE struct lws_vhost *
1004 lws_vhost_get(struct lws *wsi)
1009 LWS_VISIBLE struct lws_vhost *
1010 lws_get_vhost(struct lws *wsi)
1015 LWS_VISIBLE const struct lws_protocols *
1016 lws_protocol_get(struct lws *wsi)
1018 return wsi->protocol;
1021 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1022 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
1026 for (n = 0; n < vh->count_protocols; n++)
1027 if (!strcmp(name, vh->protocols[n].name))
1028 return &vh->protocols[n];
1034 lws_callback_all_protocol(struct lws_context *context,
1035 const struct lws_protocols *protocol, int reason)
1037 struct lws_context_per_thread *pt = &context->pt[0];
1038 unsigned int n, m = context->count_threads;
1042 for (n = 0; n < pt->fds_count; n++) {
1043 wsi = wsi_from_fd(context, pt->fds[n].fd);
1046 if (wsi->protocol == protocol)
1047 protocol->callback(wsi, reason, wsi->user_space,
1057 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
1058 const struct lws_protocols *protocol, int reason)
1060 struct lws_context *context = vh->context;
1061 struct lws_context_per_thread *pt = &context->pt[0];
1062 unsigned int n, m = context->count_threads;
1066 for (n = 0; n < pt->fds_count; n++) {
1067 wsi = wsi_from_fd(context, pt->fds[n].fd);
1070 if (wsi->vhost == vh && wsi->protocol == protocol)
1071 protocol->callback(wsi, reason, wsi->user_space,
1080 LWS_VISIBLE LWS_EXTERN int
1081 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
1085 for (n = 0; n < wsi->vhost->count_protocols; n++)
1086 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
1092 LWS_VISIBLE LWS_EXTERN void
1093 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)
1095 context->fops = fops;
1098 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1099 lws_vfs_tell(lws_fop_fd_t fop_fd)
1104 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1105 lws_vfs_get_length(lws_fop_fd_t fop_fd)
1110 LWS_VISIBLE LWS_EXTERN uint32_t
1111 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd)
1113 return fop_fd->mod_time;
1116 LWS_VISIBLE lws_fileofs_t
1117 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1120 lwsl_debug("%s: seeking to %ld, len %ld\n", __func__, (long)offset, (long)fop_fd->len);
1121 ofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);
1122 lwsl_debug("%s: result %ld, fop_fd pos %ld\n", __func__, (long)ofs, (long)fop_fd->pos);
1127 LWS_VISIBLE lws_fileofs_t
1128 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1130 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len + fop_fd->pos + offset);
1134 const struct lws_plat_file_ops *
1135 lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,
1138 const struct lws_plat_file_ops *pf;
1139 const char *p = vfs_path;
1144 /* no non-platform fops, just use that */
1150 * scan the vfs path looking for indications we are to be
1151 * handled by a specific fops
1159 /* the first one is always platform fops, so skip */
1163 while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {
1164 if (p >= vfs_path + pf->fi[n].len)
1165 if (!strncmp(p - (pf->fi[n].len - 1),
1167 pf->fi[n].len - 1)) {
1182 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
1183 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
1184 lws_fop_flags_t *flags)
1186 const char *vpath = "";
1187 const struct lws_plat_file_ops *selected = lws_vfs_select_fops(
1188 fops, vfs_path, &vpath);
1190 return selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);
1195 * lws_now_secs() - seconds since 1970-1-1
1198 LWS_VISIBLE LWS_EXTERN unsigned long
1203 gettimeofday(&tv, NULL);
1212 lws_get_socket_fd(struct lws *wsi)
1214 return wsi->desc.sockfd;
1221 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
1222 int ret, int completed)
1224 unsigned long long u;
1227 u = time_in_microseconds();
1230 wsi->latency_start = u;
1231 if (!wsi->action_start)
1232 wsi->action_start = u;
1236 if (wsi->action_start == wsi->latency_start)
1238 "Completion first try lat %lluus: %p: ret %d: %s\n",
1239 u - wsi->latency_start,
1240 (void *)wsi, ret, action);
1243 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1244 u - wsi->action_start,
1245 u - wsi->latency_start,
1246 (void *)wsi, ret, action);
1247 wsi->action_start = 0;
1249 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1250 u - wsi->latency_start, (void *)wsi, ret, action);
1252 if (u - wsi->latency_start > context->worst_latency) {
1253 context->worst_latency = u - wsi->latency_start;
1254 strcpy(context->worst_latency_info, buf);
1256 lwsl_latency("%s", buf);
1261 lws_rx_flow_control(struct lws *wsi, int enable)
1263 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1266 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1267 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1273 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1274 const struct lws_protocols *protocol)
1276 const struct lws_context_per_thread *pt = &context->pt[0];
1278 unsigned int n, m = context->count_threads;
1281 for (n = 0; n < pt->fds_count; n++) {
1282 wsi = wsi_from_fd(context, pt->fds[n].fd);
1285 if (wsi->protocol == protocol)
1286 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1292 LWS_VISIBLE extern const char *
1293 lws_canonical_hostname(struct lws_context *context)
1295 return (const char *)context->canonical_hostname;
1298 int user_callback_handle_rxflow(lws_callback_function callback_function,
1300 enum lws_callback_reasons reason, void *user,
1301 void *in, size_t len)
1305 n = callback_function(wsi, reason, user, in, len);
1307 n = _lws_rx_flow_control(wsi);
1312 #if defined(LWS_WITH_ESP8266)
1314 #define strchr ets_strchr
1318 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1320 #if !defined(LWS_WITH_ESP8266)
1322 char authstring[96];
1327 /* we have to deal with a possible redundant leading http:// */
1328 if (!strncmp(proxy, "http://", 7))
1331 p = strchr(proxy, '@');
1332 if (p) { /* auth is around */
1334 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1337 strncpy(authstring, proxy, p - proxy);
1338 // null termination not needed on input
1339 if (lws_b64_encode_string(authstring, (p - proxy),
1340 vhost->proxy_basic_auth_token,
1341 sizeof vhost->proxy_basic_auth_token) < 0)
1344 lwsl_info(" Proxy auth in use\n");
1348 vhost->proxy_basic_auth_token[0] = '\0';
1350 strncpy(vhost->http_proxy_address, proxy,
1351 sizeof(vhost->http_proxy_address) - 1);
1352 vhost->http_proxy_address[
1353 sizeof(vhost->http_proxy_address) - 1] = '\0';
1355 p = strchr(vhost->http_proxy_address, ':');
1356 if (!p && !vhost->http_proxy_port) {
1357 lwsl_err("http_proxy needs to be ads:port\n");
1363 vhost->http_proxy_port = atoi(p + 1);
1367 lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1368 vhost->http_proxy_port);
1373 lwsl_err("proxy auth too long\n");
1378 #if defined(LWS_WITH_SOCKS5)
1380 lws_set_socks(struct lws_vhost *vhost, const char *socks)
1382 #if !defined(LWS_WITH_ESP8266)
1383 char *p_at, *p_colon;
1390 vhost->socks_user[0] = '\0';
1391 vhost->socks_password[0] = '\0';
1393 p_at = strchr(socks, '@');
1394 if (p_at) { /* auth is around */
1395 if ((unsigned int)(p_at - socks) > (sizeof(user)
1396 + sizeof(password) - 2)) {
1397 lwsl_err("Socks auth too long\n");
1401 p_colon = strchr(socks, ':');
1403 if ((unsigned int)(p_colon - socks) > (sizeof(user)
1405 lwsl_err("Socks user too long\n");
1408 if ((unsigned int)(p_at - p_colon) > (sizeof(password)
1410 lwsl_err("Socks password too long\n");
1414 strncpy(vhost->socks_user, socks, p_colon - socks);
1415 strncpy(vhost->socks_password, p_colon + 1,
1416 p_at - (p_colon + 1));
1418 lwsl_info(" Socks auth, user: %s, password: %s\n",
1419 vhost->socks_user, vhost->socks_password );
1424 strncpy(vhost->socks_proxy_address, socks,
1425 sizeof(vhost->socks_proxy_address) - 1);
1426 vhost->socks_proxy_address[sizeof(vhost->socks_proxy_address) - 1]
1429 p_colon = strchr(vhost->socks_proxy_address, ':');
1430 if (!p_colon && !vhost->socks_proxy_port) {
1431 lwsl_err("socks_proxy needs to be address:port\n");
1436 vhost->socks_proxy_port = atoi(p_colon + 1);
1440 lwsl_info(" Socks %s:%u\n", vhost->socks_proxy_address,
1441 vhost->socks_proxy_port);
1451 LWS_VISIBLE const struct lws_protocols *
1452 lws_get_protocol(struct lws *wsi)
1454 return wsi->protocol;
1458 lws_is_final_fragment(struct lws *wsi)
1460 lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1461 wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1462 (long)wsi->u.ws.rx_draining_ext);
1463 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1467 lws_is_first_fragment(struct lws *wsi)
1469 return wsi->u.ws.first_fragment;
1472 LWS_VISIBLE unsigned char
1473 lws_get_reserved_bits(struct lws *wsi)
1475 return wsi->u.ws.rsv;
1479 lws_ensure_user_space(struct lws *wsi)
1481 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1485 /* allocate the per-connection user memory (if any) */
1487 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1488 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1489 if (wsi->user_space == NULL) {
1490 lwsl_err("Out of memory for conn user space\n");
1494 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1495 __func__, wsi, (long)wsi->protocol->per_session_data_size,
1501 lwsl_timestamp(int level, char *p, int len)
1503 #ifndef LWS_PLAT_OPTEE
1504 time_t o_now = time(NULL);
1505 unsigned long long now;
1506 struct tm *ptm = NULL;
1514 ptm = localtime(&o_now);
1516 if (localtime_r(&o_now, &tm))
1521 for (n = 0; n < LLL_COUNT; n++) {
1522 if (level != (1 << n))
1524 now = time_in_microseconds() / 100;
1526 n = lws_snprintf(p, len,
1527 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1528 ptm->tm_year + 1900,
1534 (int)(now % 10000), log_level_names[n]);
1536 n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1537 (unsigned long long) now / 10000,
1538 (int)(now % 10000), log_level_names[n]);
1545 #ifndef LWS_PLAT_OPTEE
1546 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1548 #if !defined(LWS_WITH_ESP8266)
1551 lwsl_timestamp(level, buf, sizeof(buf));
1552 fprintf(stderr, "%s%s", buf, line);
1557 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1559 #if defined(LWS_WITH_ESP8266)
1566 if (!(log_level & filter))
1569 n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1571 #if defined(LWS_WITH_ESP8266)
1572 buf[sizeof(buf) - 1] = '\0';
1574 /* vnsprintf returns what it would have written, even if truncated */
1575 if (n > sizeof(buf) - 1)
1576 n = sizeof(buf) - 1;
1581 lwsl_emit(filter, buf);
1584 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1588 va_start(ap, format);
1589 _lws_logv(filter, format, ap);
1593 LWS_VISIBLE void lws_set_log_level(int level,
1594 void (*func)(int level, const char *line))
1601 LWS_VISIBLE int lwsl_visible(int level)
1603 return log_level & level;
1607 lws_is_ssl(struct lws *wsi)
1609 #ifdef LWS_OPENSSL_SUPPORT
1610 return wsi->use_ssl;
1617 #ifdef LWS_OPENSSL_SUPPORT
1619 lws_get_ssl(struct lws *wsi)
1626 lws_partial_buffered(struct lws *wsi)
1628 return !!wsi->trunc_len;
1631 void lws_set_protocol_write_pending(struct lws *wsi,
1632 enum lws_pending_protocol_send pend)
1634 lwsl_info("setting pps %d\n", pend);
1637 lwsl_err("pps overwrite\n");
1639 lws_rx_flow_control(wsi, 0);
1640 lws_callback_on_writable(wsi);
1644 lws_get_peer_write_allowance(struct lws *wsi)
1646 #ifdef LWS_USE_HTTP2
1647 /* only if we are using HTTP2 on this connection */
1648 if (wsi->mode != LWSCM_HTTP2_SERVING)
1650 /* user is only interested in how much he can send, or that he can't */
1651 if (wsi->u.http2.tx_credit <= 0)
1654 return wsi->u.http2.tx_credit;
1662 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1664 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1665 memset(&wsi->u, 0, sizeof(wsi->u));
1669 LWS_VISIBLE struct lws_plat_file_ops *
1670 lws_get_fops(struct lws_context *context)
1672 return (struct lws_plat_file_ops *)context->fops;
1675 LWS_VISIBLE LWS_EXTERN struct lws_context *
1676 lws_get_context(const struct lws *wsi)
1678 return wsi->context;
1681 LWS_VISIBLE LWS_EXTERN int
1682 lws_get_count_threads(struct lws_context *context)
1684 return context->count_threads;
1687 LWS_VISIBLE LWS_EXTERN void *
1688 lws_wsi_user(struct lws *wsi)
1690 return wsi->user_space;
1693 LWS_VISIBLE LWS_EXTERN void
1694 lws_set_wsi_user(struct lws *wsi, void *data)
1696 if (wsi->user_space_externally_allocated)
1697 wsi->user_space = data;
1699 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1703 LWS_VISIBLE LWS_EXTERN struct lws *
1704 lws_get_parent(const struct lws *wsi)
1709 LWS_VISIBLE LWS_EXTERN struct lws *
1710 lws_get_child(const struct lws *wsi)
1712 return wsi->child_list;
1715 LWS_VISIBLE LWS_EXTERN void
1716 lws_set_parent_carries_io(struct lws *wsi)
1718 wsi->parent_carries_io = 1;
1721 LWS_VISIBLE LWS_EXTERN void *
1722 lws_get_opaque_parent_data(const struct lws *wsi)
1724 return wsi->opaque_parent_data;
1727 LWS_VISIBLE LWS_EXTERN void
1728 lws_set_opaque_parent_data(struct lws *wsi, void *data)
1730 wsi->opaque_parent_data = data;
1733 LWS_VISIBLE LWS_EXTERN int
1734 lws_get_child_pending_on_writable(const struct lws *wsi)
1736 return wsi->parent_pending_cb_on_writable;
1739 LWS_VISIBLE LWS_EXTERN void
1740 lws_clear_child_pending_on_writable(struct lws *wsi)
1742 wsi->parent_pending_cb_on_writable = 0;
1745 LWS_VISIBLE LWS_EXTERN int
1746 lws_get_close_length(struct lws *wsi)
1748 return wsi->u.ws.close_in_ping_buffer_len;
1751 LWS_VISIBLE LWS_EXTERN unsigned char *
1752 lws_get_close_payload(struct lws *wsi)
1754 return &wsi->u.ws.ping_payload_buf[LWS_PRE];
1757 LWS_VISIBLE LWS_EXTERN void
1758 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1759 unsigned char *buf, size_t len)
1761 unsigned char *p, *start;
1762 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1764 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1766 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1768 *p++ = (((int)status) >> 8) & 0xff;
1769 *p++ = ((int)status) & 0xff;
1772 while (len-- && p < start + budget)
1775 wsi->u.ws.close_in_ping_buffer_len = p - start;
1779 _lws_rx_flow_control(struct lws *wsi)
1781 struct lws *wsic = wsi->child_list;
1783 /* if he has children, do those if they were changed */
1785 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1786 _lws_rx_flow_control(wsic);
1788 wsic = wsic->sibling_list;
1791 /* there is no pending change */
1792 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1793 // lwsl_debug("%s: no pending change\n", __func__);
1797 /* stuff is still buffered, not ready to really accept new input */
1798 if (wsi->rxflow_buffer) {
1799 /* get ourselves called back to deal with stashed buffer */
1800 lws_callback_on_writable(wsi);
1804 /* pending is cleared, we can change rxflow state */
1806 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1808 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1809 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1811 /* adjust the pollfd for this wsi */
1813 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1814 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1815 lwsl_info("%s: fail\n", __func__);
1819 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1826 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1828 static const unsigned char e0f4[] = {
1829 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1830 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1831 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1832 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1833 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1834 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1835 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1836 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1837 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1838 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1839 0x80 | ((4 - 1) << 2) | 1, /* ea */
1840 0x80 | ((4 - 1) << 2) | 1, /* eb */
1841 0x80 | ((4 - 1) << 2) | 1, /* ec */
1842 0x80 | ((2 - 1) << 2) | 1, /* ed */
1843 0x80 | ((4 - 1) << 2) | 1, /* ee */
1844 0x80 | ((4 - 1) << 2) | 1, /* ef */
1845 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1846 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1847 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1848 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1849 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1852 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1853 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1855 unsigned char s = *state;
1858 unsigned char c = *buf++;
1862 if (c < 0xc2 || c > 0xf4)
1865 s = 0x80 | ((4 - 1) << 2);
1870 if (c < (s & 0xf0) ||
1871 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1873 s = e0f4[21 + (s & 3)];
1882 LWS_VISIBLE LWS_EXTERN int
1883 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1887 static const char *slash = "/";
1889 /* cut up the location into address, port and path */
1891 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1902 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1904 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1910 while (*p && *p != ']')
1917 while (*p && *p != ':' && *p != '/')
1923 while (*p && *p != '/')
1936 #ifdef LWS_NO_EXTENSIONS
1938 /* we need to provide dummy callbacks for internal exts
1939 * so user code runs when faced with a lib compiled with
1940 * extensions disabled.
1944 lws_extension_callback_pm_deflate(struct lws_context *context,
1945 const struct lws_extension *ext,
1947 enum lws_extension_callback_reasons reason,
1948 void *user, void *in, size_t len)
1963 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1967 #ifdef LWS_USE_UNIX_SOCK
1968 struct sockaddr_un serv_unix;
1971 struct sockaddr_in6 serv_addr6;
1973 struct sockaddr_in serv_addr4;
1974 #ifndef LWS_PLAT_OPTEE
1975 socklen_t len = sizeof(struct sockaddr_storage);
1978 struct sockaddr_storage sin;
1981 #ifdef LWS_USE_UNIX_SOCK
1982 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1983 v = (struct sockaddr *)&serv_unix;
1984 n = sizeof(struct sockaddr_un);
1985 bzero((char *) &serv_unix, sizeof(serv_unix));
1986 serv_unix.sun_family = AF_UNIX;
1987 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1988 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1992 strcpy(serv_unix.sun_path, iface);
1993 if (serv_unix.sun_path[0] == '@')
1994 serv_unix.sun_path[0] = '\0';
1998 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1999 if (LWS_IPV6_ENABLED(vhost)) {
2000 v = (struct sockaddr *)&serv_addr6;
2001 n = sizeof(struct sockaddr_in6);
2002 bzero((char *) &serv_addr6, sizeof(serv_addr6));
2004 if (interface_to_sa(vhost, iface,
2005 (struct sockaddr_in *)v, n) < 0) {
2006 lwsl_err("Unable to find interface %s\n", iface);
2009 serv_addr6.sin6_scope_id = lws_get_addr_scope(iface);
2012 serv_addr6.sin6_family = AF_INET6;
2013 serv_addr6.sin6_port = htons(port);
2017 v = (struct sockaddr *)&serv_addr4;
2018 n = sizeof(serv_addr4);
2019 bzero((char *) &serv_addr4, sizeof(serv_addr4));
2020 serv_addr4.sin_addr.s_addr = INADDR_ANY;
2021 serv_addr4.sin_family = AF_INET;
2022 #if !defined(LWS_WITH_ESP32)
2025 interface_to_sa(vhost, iface,
2026 (struct sockaddr_in *)v, n) < 0) {
2027 lwsl_err("Unable to find interface %s\n", iface);
2031 serv_addr4.sin_port = htons(port);
2034 n = bind(sockfd, v, n);
2035 #ifdef LWS_USE_UNIX_SOCK
2036 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
2037 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
2038 sockfd, iface, n, LWS_ERRNO);
2043 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
2044 sockfd, port, n, LWS_ERRNO);
2048 #ifndef LWS_PLAT_OPTEE
2049 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
2050 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
2053 #if defined(LWS_USE_IPV6)
2054 port = (sin.ss_family == AF_INET6) ?
2055 ntohs(((struct sockaddr_in6 *) &sin)->sin6_port) :
2056 ntohs(((struct sockaddr_in *) &sin)->sin_port);
2058 port = ntohs(((struct sockaddr_in *) &sin)->sin_port);
2065 #if defined(LWS_USE_IPV6)
2066 LWS_EXTERN unsigned long
2067 lws_get_addr_scope(const char *ipaddr)
2069 unsigned long scope = 0;
2072 struct ifaddrs *addrs, *addr;
2073 char ip[NI_MAXHOST];
2077 for (addr = addrs; addr; addr = addr->ifa_next) {
2078 if (!addr->ifa_addr ||
2079 addr->ifa_addr->sa_family != AF_INET6)
2082 getnameinfo(addr->ifa_addr,
2083 sizeof(struct sockaddr_in6),
2085 NULL, 0, NI_NUMERICHOST);
2089 if (ip[i++] == '%') {
2094 if (!strcmp(ip, ipaddr)) {
2095 scope = if_nametoindex(addr->ifa_name);
2101 PIP_ADAPTER_ADDRESSES adapter, addrs = NULL;
2102 PIP_ADAPTER_UNICAST_ADDRESS addr;
2105 struct sockaddr_in6 *sockaddr;
2106 char ip[NI_MAXHOST];
2110 for (i = 0; i < 5; i++)
2112 ret = GetAdaptersAddresses(AF_INET6, GAA_FLAG_INCLUDE_PREFIX,
2113 NULL, addrs, &size);
2114 if ((ret == NO_ERROR) || (ret == ERROR_NO_DATA)) {
2116 } else if (ret == ERROR_BUFFER_OVERFLOW)
2120 addrs = (IP_ADAPTER_ADDRESSES *) malloc(size);
2128 lwsl_err("Failed to get IPv6 address table (%d)", ret);
2133 if ((ret == NO_ERROR) && (addrs))
2136 while ((adapter) && (!found))
2138 addr = adapter->FirstUnicastAddress;
2139 while ((addr) && (!found))
2141 if (addr->Address.lpSockaddr->sa_family == AF_INET6)
2143 sockaddr = (struct sockaddr_in6 *) (addr->Address.lpSockaddr);
2145 lws_plat_inet_ntop(sockaddr->sin6_family, &sockaddr->sin6_addr,
2148 if (!strcmp(ip, ipaddr)) {
2149 scope = sockaddr->sin6_scope_id;
2156 adapter = adapter->Next;
2168 lws_restart_ws_ping_pong_timer(struct lws *wsi)
2170 if (!wsi->context->ws_ping_pong_interval)
2172 if (wsi->state != LWSS_ESTABLISHED)
2175 wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
2176 wsi->context->ws_ping_pong_interval;
2179 static const char *hex = "0123456789ABCDEF";
2181 LWS_VISIBLE LWS_EXTERN const char *
2182 lws_sql_purify(char *escaped, const char *string, int len)
2184 const char *p = string;
2187 while (*p && len-- > 2) {
2201 LWS_VISIBLE LWS_EXTERN const char *
2202 lws_json_purify(char *escaped, const char *string, int len)
2204 const char *p = string;
2212 while (*p && len-- > 6) {
2213 if (*p == '\"' || *p == '\\' || *p < 0x20) {
2218 *q++ = hex[((*p) >> 4) & 15];
2219 *q++ = hex[(*p) & 15];
2230 LWS_VISIBLE LWS_EXTERN const char *
2231 lws_urlencode(char *escaped, const char *string, int len)
2233 const char *p = string;
2236 while (*p && len-- > 3) {
2242 if ((*p >= '0' && *p <= '9') ||
2243 (*p >= 'A' && *p <= 'Z') ||
2244 (*p >= 'a' && *p <= 'z')) {
2249 *q++ = hex[(*p >> 4) & 0xf];
2250 *q++ = hex[*p & 0xf];
2260 LWS_VISIBLE LWS_EXTERN int
2261 lws_urldecode(char *string, const char *escaped, int len)
2266 while (*escaped && len) {
2269 if (*escaped == '%') {
2274 if (*escaped == '+') {
2280 *string++ = *escaped++;
2284 n = char_to_hex(*escaped);
2293 n = char_to_hex(*escaped);
2297 *string++ = sum | n;
2309 LWS_VISIBLE LWS_EXTERN int
2310 lws_finalize_startup(struct lws_context *context)
2312 struct lws_context_creation_info info;
2314 info.uid = context->uid;
2315 info.gid = context->gid;
2317 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
2318 memcpy(info.caps, context->caps, sizeof(info.caps));
2319 info.count_caps = context->count_caps;
2322 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2323 lws_plat_drop_app_privileges(&info);
2329 lws_snprintf(char *str, size_t size, const char *format, ...)
2337 va_start(ap, format);
2338 n = vsnprintf(str, size, format, ap);
2348 LWS_VISIBLE LWS_EXTERN int
2349 lws_is_cgi(struct lws *wsi) {
2360 urlencode(const char *in, int inlen, char *out, int outlen)
2362 char *start = out, *end = out + outlen;
2364 while (inlen-- && out < end - 4) {
2365 if ((*in >= 'A' && *in <= 'Z') ||
2366 (*in >= 'a' && *in <= 'z') ||
2367 (*in >= '0' && *in <= '9') ||
2381 *out++ = hex[(*in) >> 4];
2382 *out++ = hex[(*in++) & 15];
2393 lws_create_basic_wsi(struct lws_context *context, int tsi)
2395 struct lws *new_wsi;
2397 if ((unsigned int)context->pt[tsi].fds_count ==
2398 context->fd_limit_per_thread - 1) {
2399 lwsl_err("no space for new conn\n");
2403 new_wsi = lws_zalloc(sizeof(struct lws));
2404 if (new_wsi == NULL) {
2405 lwsl_err("Out of memory for new connection\n");
2410 new_wsi->context = context;
2411 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2412 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2414 /* initialize the instance struct */
2416 new_wsi->state = LWSS_CGI;
2417 new_wsi->mode = LWSCM_CGI;
2418 new_wsi->hdr_parsing_completed = 0;
2419 new_wsi->position_in_fds_table = -1;
2422 * these can only be set once the protocol is known
2423 * we set an unestablished connection's protocol pointer
2424 * to the start of the defauly vhost supported list, so it can look
2425 * for matching ones during the handshake
2427 new_wsi->protocol = context->vhost_list->protocols;
2428 new_wsi->user_space = NULL;
2429 new_wsi->ietf_spec_revision = 0;
2430 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2431 context->count_wsi_allocated++;
2436 LWS_VISIBLE LWS_EXTERN int
2437 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2438 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2440 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2441 char *env_array[30], cgi_path[400], e[1024], *p = e,
2442 *end = p + sizeof(e) - 1, tok[256], *t;
2443 struct lws_cgi *cgi;
2444 int n, m, i, uritok = -1;
2447 * give the master wsi a cgi struct
2450 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2452 lwsl_err("%s: OOM\n", __func__);
2456 wsi->cgi->response_code = HTTP_STATUS_OK;
2459 cgi->wsi = wsi; /* set cgi's owning wsi */
2461 /* create pipes for [stdin|stdout] and [stderr] */
2463 for (n = 0; n < 3; n++)
2464 if (pipe(cgi->pipe_fds[n]) == -1)
2467 /* create cgi wsis for each stdin/out/err fd */
2469 for (n = 0; n < 3; n++) {
2470 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2471 if (!cgi->stdwsi[n])
2473 cgi->stdwsi[n]->cgi_channel = n;
2474 cgi->stdwsi[n]->vhost = wsi->vhost;
2476 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2477 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2479 /* read side is 0, stdin we want the write side, others read */
2480 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2481 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2482 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2487 for (n = 0; n < 3; n++) {
2488 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2489 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2491 cgi->stdwsi[n]->parent = wsi;
2492 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2493 wsi->child_list = cgi->stdwsi[n];
2496 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2497 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2498 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2500 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2501 cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2502 cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2503 cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2505 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2507 /* the cgi stdout is always sending us http1.x header data first */
2508 wsi->hdr_state = LCHS_HEADER;
2510 /* add us to the pt list of active cgis */
2511 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2512 cgi->cgi_list = pt->cgi_list;
2515 /* prepare his CGI env */
2519 if (lws_is_ssl(wsi))
2520 env_array[n++] = "HTTPS=ON";
2521 if (wsi->u.hdr.ah) {
2522 static const unsigned char meths[] = {
2525 WSI_TOKEN_OPTIONS_URI,
2527 WSI_TOKEN_PATCH_URI,
2528 WSI_TOKEN_DELETE_URI,
2530 static const char * const meth_names[] = {
2531 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2534 for (m = 0; m < ARRAY_SIZE(meths); m++)
2535 if (lws_hdr_total_length(wsi, meths[m]) >=
2536 script_uri_path_len) {
2544 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2545 lws_hdr_simple_ptr(wsi, uritok));
2546 cgi_path[sizeof(cgi_path) - 1] = '\0';
2547 env_array[n++] = cgi_path;
2550 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2555 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2556 /* dump the individual URI Arg parameters */
2559 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2560 WSI_TOKEN_HTTP_URI_ARGS, m);
2564 while (*t && *t != '=' && p < end - 4)
2568 i = urlencode(t, i- (t - tok), p, end - p);
2580 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2581 lws_hdr_simple_ptr(wsi, uritok) +
2582 script_uri_path_len);
2585 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2587 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2588 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2591 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2593 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2594 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2597 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2599 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2600 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2603 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2605 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2606 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2609 if (uritok == WSI_TOKEN_POST_URI) {
2610 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2612 p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2613 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2616 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2618 p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2619 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2624 p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2628 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2630 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2633 mp_cgienv = mp_cgienv->next;
2636 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2637 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2638 env_array[n] = NULL;
2641 for (m = 0; m < n; m++)
2642 lwsl_err(" %s\n", env_array[m]);
2646 * Actually having made the env, as a cgi we don't need the ah
2649 if (lws_header_table_is_in_detachable_state(wsi))
2650 lws_header_table_detach(wsi, 0);
2652 /* we are ready with the redirection pipes... run the thing */
2653 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2659 lwsl_err("fork failed, errno %d", errno);
2663 #if defined(__linux__)
2664 prctl(PR_SET_PDEATHSIG, SIGTERM);
2666 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2669 /* we are the parent process */
2670 wsi->context->count_cgi_spawned++;
2671 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2675 /* somewhere we can at least read things and enter it */
2677 lwsl_notice("%s: Failed to chdir\n", __func__);
2679 /* We are the forked process, redirect and kill inherited things.
2681 * Because of vfork(), we cannot do anything that changes pages in
2682 * the parent environment. Stuff that changes kernel state for the
2683 * process is OK. Stuff that happens after the execvpe() is OK.
2686 for (n = 0; n < 3; n++) {
2687 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2688 lwsl_err("%s: stdin dup2 failed\n", __func__);
2691 close(cgi->pipe_fds[n][!(n == 0)]);
2694 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2695 for (m = 0; m < n; m++) {
2696 p = strchr(env_array[m], '=');
2698 setenv(env_array[m], p, 1);
2700 execvp(exec_array[0], (char * const *)&exec_array[0]);
2702 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2708 /* drop us from the pt cgi list */
2709 pt->cgi_list = cgi->cgi_list;
2712 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2714 for (n = 0; n < 3; n++)
2715 if (wsi->cgi->stdwsi[n])
2716 lws_free_wsi(cgi->stdwsi[n]);
2719 for (n = 0; n < 3; n++) {
2720 if (cgi->pipe_fds[n][0])
2721 close(cgi->pipe_fds[n][0]);
2722 if (cgi->pipe_fds[n][1])
2723 close(cgi->pipe_fds[n][1]);
2726 lws_free_set_NULL(wsi->cgi);
2728 lwsl_err("%s: failed\n", __func__);
2733 /* we have to parse out these headers in the CGI output */
2735 static const char * const significant_hdr[SIGNIFICANT_HDR_COUNT] = {
2739 "transfer-encoding: chunked",
2742 LWS_VISIBLE LWS_EXTERN int
2743 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2746 unsigned char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2747 *end = &buf[sizeof(buf) - 1 - LWS_PRE];
2753 while (wsi->hdr_state != LHCS_PAYLOAD) {
2754 /* we have to separate header / finalize and
2755 * payload chunks, since they need to be
2756 * handled separately
2759 switch (wsi->hdr_state) {
2762 lwsl_info("LHCS_RESPONSE: issuing response %d\n",
2763 wsi->cgi->response_code);
2764 if (lws_add_http_header_status(wsi, wsi->cgi->response_code, &p, end))
2766 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2767 (unsigned char *)"close", 5, &p, end))
2769 n = lws_write(wsi, start, p - start,
2770 LWS_WRITE_HTTP_HEADERS);
2772 /* finalize cached headers before dumping them */
2773 if (lws_finalize_http_header(wsi,
2774 (unsigned char **)&wsi->cgi->headers_pos,
2775 (unsigned char *)wsi->cgi->headers_end)) {
2777 lwsl_notice("finalize failed\n");
2781 wsi->hdr_state = LHCS_DUMP_HEADERS;
2782 wsi->reason_bf |= 8;
2783 lws_callback_on_writable(wsi);
2784 /* back to the loop for writeability again */
2787 case LHCS_DUMP_HEADERS:
2789 n = wsi->cgi->headers_pos - wsi->cgi->headers_dumped;
2793 lwsl_debug("LHCS_DUMP_HEADERS: %d\n", n);
2795 m = lws_write(wsi, (unsigned char *)wsi->cgi->headers_dumped,
2796 n, LWS_WRITE_HTTP_HEADERS);
2798 lwsl_debug("%s: write says %d\n", __func__, m);
2801 wsi->cgi->headers_dumped += n;
2802 if (wsi->cgi->headers_dumped == wsi->cgi->headers_pos) {
2803 wsi->hdr_state = LHCS_PAYLOAD;
2804 lws_free_set_NULL(wsi->cgi->headers_buf);
2805 lwsl_debug("freed cgi headers\n");
2807 wsi->reason_bf |= 8;
2808 lws_callback_on_writable(wsi);
2811 /* writeability becomes uncertain now we wrote
2812 * something, we must return to the event loop
2817 if (!wsi->cgi->headers_buf) {
2818 /* if we don't already have a headers buf, cook one up */
2820 wsi->cgi->headers_buf = malloc(n);
2821 if (!wsi->cgi->headers_buf) {
2826 lwsl_debug("allocated cgi hdrs\n");
2827 wsi->cgi->headers_pos = wsi->cgi->headers_buf;
2828 wsi->cgi->headers_dumped = wsi->cgi->headers_pos;
2829 wsi->cgi->headers_end = wsi->cgi->headers_buf + n - 1;
2831 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2832 wsi->cgi->match[n] = 0;
2837 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2839 if (errno != EAGAIN) {
2840 lwsl_debug("%s: read says %d\n", __func__, n);
2846 if (wsi->cgi->headers_pos >= wsi->cgi->headers_end - 4) {
2847 lwsl_notice("CGI headers larger than buffer size\n");
2853 lwsl_debug("-- 0x%02X %c %d %d\n", (unsigned char)c, c, wsi->cgi->match[1], wsi->hdr_state);
2856 switch (wsi->hdr_state) {
2859 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2860 /* significant headers with numeric decimal payloads */
2861 if (!significant_hdr[n][wsi->cgi->match[n]] &&
2862 (c >= '0' && c <= '9') &&
2863 wsi->cgi->lp < sizeof(wsi->cgi->l) - 1) {
2864 wsi->cgi->l[wsi->cgi->lp++] = c;
2865 wsi->cgi->l[wsi->cgi->lp] = '\0';
2867 case SIGNIFICANT_HDR_CONTENT_LENGTH:
2868 wsi->cgi->content_length = atoll(wsi->cgi->l);
2870 case SIGNIFICANT_HDR_STATUS:
2871 wsi->cgi->response_code = atol(wsi->cgi->l);
2872 lwsl_debug("Status set to %d\n", wsi->cgi->response_code);
2878 /* hits up to the NUL are sticky until next hdr */
2879 if (significant_hdr[n][wsi->cgi->match[n]]) {
2880 if (tolower(c) == significant_hdr[n][wsi->cgi->match[n]])
2881 wsi->cgi->match[n]++;
2883 wsi->cgi->match[n] = 0;
2887 /* some cgi only send us \x0a for EOL */
2889 wsi->hdr_state = LCHS_SINGLE_0A;
2890 *wsi->cgi->headers_pos++ = '\x0d';
2892 *wsi->cgi->headers_pos++ = c;
2894 wsi->hdr_state = LCHS_LF1;
2896 if (wsi->hdr_state != LCHS_HEADER &&
2897 !significant_hdr[SIGNIFICANT_HDR_TRANSFER_ENCODING][wsi->cgi->match[SIGNIFICANT_HDR_TRANSFER_ENCODING]]) {
2898 lwsl_debug("cgi produced chunked\n");
2899 wsi->cgi->explicitly_chunked = 1;
2902 /* presence of Location: mandates 302 retcode */
2903 if (wsi->hdr_state != LCHS_HEADER &&
2904 !significant_hdr[SIGNIFICANT_HDR_LOCATION][wsi->cgi->match[SIGNIFICANT_HDR_LOCATION]]) {
2905 lwsl_debug("CGI: Location hdr seen\n");
2906 wsi->cgi->response_code = 302;
2911 *wsi->cgi->headers_pos++ = c;
2913 wsi->hdr_state = LCHS_CR2;
2916 /* we got \r[^\n]... it's unreasonable */
2917 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2923 wsi->hdr_state = LCHS_LF2;
2926 wsi->hdr_state = LCHS_HEADER;
2927 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2928 wsi->cgi->match[n] = 0;
2933 case LCHS_SINGLE_0A:
2936 lwsl_debug("Content-Length: %lld\n", (unsigned long long)wsi->cgi->content_length);
2937 wsi->hdr_state = LHCS_RESPONSE;
2938 /* drop the \0xa ... finalize will add it if needed */
2942 /* we got \r\n\r[^\n]... it's unreasonable */
2944 /* we got \x0anext header, it's reasonable */
2945 *wsi->cgi->headers_pos++ = c;
2946 wsi->hdr_state = LCHS_HEADER;
2947 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2948 wsi->cgi->match[n] = 0;
2956 /* ran out of input, ended the headers, or filled up the headers buf */
2957 if (!n || wsi->hdr_state == LHCS_PAYLOAD)
2961 /* payload processing */
2963 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2964 start, sizeof(buf) - LWS_PRE);
2966 if (n < 0 && errno != EAGAIN) {
2967 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2971 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2972 //lwsl_notice("write %d\n", m);
2974 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2977 wsi->cgi->content_length_seen += m;
2983 LWS_VISIBLE LWS_EXTERN int
2984 lws_cgi_kill(struct lws *wsi)
2986 struct lws_cgi_args args;
2989 lwsl_debug("%s: %p\n", __func__, wsi);
2994 if (wsi->cgi->pid > 0) {
2995 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2997 lwsl_debug("%s: PID %d reaped\n", __func__,
3001 /* kill the process group */
3002 n = kill(-wsi->cgi->pid, SIGTERM);
3003 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
3004 wsi->cgi->pid, n, errno);
3007 * hum seen errno=3 when process is listed in ps,
3008 * it seems we don't always retain process grouping
3010 * Direct these fallback attempt to the exact child
3012 n = kill(wsi->cgi->pid, SIGTERM);
3014 n = kill(wsi->cgi->pid, SIGPIPE);
3016 n = kill(wsi->cgi->pid, SIGKILL);
3018 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
3019 __func__, wsi->cgi->pid, errno);
3023 /* He could be unkillable because he's a zombie */
3026 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
3028 lwsl_debug("%s: reaped PID %d\n", __func__, n);
3030 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
3032 lwsl_debug("%s: reaped PID %d\n", __func__, n);
3038 args.stdwsi = &wsi->cgi->stdwsi[0];
3040 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
3041 wsi->protocol->callback,
3042 wsi, LWS_CALLBACK_CGI_TERMINATED,
3044 (void *)&args, 0)) {
3046 if (!wsi->cgi->being_closed)
3047 lws_close_free_wsi(wsi, 0);
3054 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
3056 struct lws_cgi **pcgi, *cgi = NULL;
3060 /* find finished guys but don't reap yet */
3061 n = waitpid(-1, &status, WNOHANG);
3064 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
3066 pcgi = &pt->cgi_list;
3068 /* check all the subprocesses on the cgi list */
3070 /* get the next one first as list may change */
3072 pcgi = &(*pcgi)->cgi_list;
3077 /* finish sending cached headers */
3078 if (cgi->headers_buf)
3081 /* wait for stdout to be drained */
3082 if (cgi->content_length > cgi->content_length_seen)
3085 if (cgi->content_length) {
3086 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3087 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3091 waitpid(n, &status, WNOHANG);
3093 * he's already terminated so no need for kill()
3094 * but we should do the terminated cgi callback
3095 * and close him if he's not already closing
3097 if (n == cgi->pid) {
3098 lwsl_debug("%s: found PID %d on cgi list\n",
3101 if (!cgi->content_length && cgi->explicitly_chunked) {
3103 * well, if he sends chunked... give him 5s after the
3104 * cgi terminated to send buffered
3106 cgi->chunked_grace++;
3112 lws_cgi_kill(cgi->wsi);
3118 /* if not found on the cgi list, as he's one of ours, reap */
3120 lwsl_debug("%s: reading PID %d although no cgi match\n",
3122 waitpid(n, &status, WNOHANG);
3126 /* disable this to confirm timeout cgi cleanup flow */
3128 pcgi = &pt->cgi_list;
3130 /* check all the subprocesses on the cgi list */
3132 /* get the next one first as list may change */
3134 pcgi = &(*pcgi)->cgi_list;
3139 /* we deferred killing him after reaping his PID */
3140 if (cgi->chunked_grace) {
3141 cgi->chunked_grace++;
3142 if (cgi->chunked_grace < 5)
3147 /* finish sending cached headers */
3148 if (cgi->headers_buf)
3151 /* wait for stdout to be drained */
3152 if (cgi->content_length > cgi->content_length_seen)
3155 if (cgi->content_length)
3156 lwsl_debug("%s: wsi %p: expected content length seen: %lld\n",
3157 __func__, cgi->wsi, (unsigned long long)cgi->content_length_seen);
3160 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
3162 if (!cgi->content_length) {
3164 * well, if he sends chunked... give him 5s after the
3165 * cgi terminated to send buffered
3167 cgi->chunked_grace++;
3171 lwsl_debug("%s: found PID %d on cgi list\n",
3172 __func__, cgi->pid);
3175 lws_cgi_kill(cgi->wsi);
3182 /* general anti zombie defence */
3183 // n = waitpid(-1, &status, WNOHANG);
3185 // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
3191 #ifdef LWS_NO_EXTENSIONS
3193 lws_set_extension_option(struct lws *wsi, const char *ext_name,
3194 const char *opt_name, const char *opt_val)
3200 #ifdef LWS_WITH_ACCESS_LOG
3202 lws_access_log(struct lws *wsi)
3204 char *p = wsi->access_log.user_agent, ass[512];
3207 if (!wsi->access_log_pending)
3210 if (!wsi->access_log.header_log)
3216 l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
3217 wsi->access_log.header_log,
3218 wsi->access_log.response, wsi->access_log.sent, p);
3220 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
3221 if (write(wsi->vhost->log_fd, ass, l) != l)
3222 lwsl_err("Failed to write log\n");
3224 lwsl_err("%s", ass);
3226 if (wsi->access_log.header_log) {
3227 lws_free(wsi->access_log.header_log);
3228 wsi->access_log.header_log = NULL;
3230 if (wsi->access_log.user_agent) {
3231 lws_free(wsi->access_log.user_agent);
3232 wsi->access_log.user_agent = NULL;
3234 wsi->access_log_pending = 0;
3241 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
3243 const struct lws_vhost *vh = ctx->vhost_list;
3247 cs->rx += vh->conn_stats.rx;
3248 cs->tx += vh->conn_stats.tx;
3249 cs->conn += vh->conn_stats.conn;
3250 cs->trans += vh->conn_stats.trans;
3251 cs->ws_upg += vh->conn_stats.ws_upg;
3252 cs->http2_upg += vh->conn_stats.http2_upg;
3253 cs->rejected += vh->conn_stats.rejected;
3255 vh = vh->vhost_next;
3259 #ifdef LWS_WITH_SERVER_STATUS
3262 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
3264 static const char * const prots[] = {
3273 char *orig = buf, *end = buf + len - 1, first = 1;
3279 buf += lws_snprintf(buf, end - buf,
3280 "{\n \"name\":\"%s\",\n"
3281 " \"port\":\"%d\",\n"
3282 " \"use_ssl\":\"%d\",\n"
3283 " \"sts\":\"%d\",\n"
3284 " \"rx\":\"%llu\",\n"
3285 " \"tx\":\"%llu\",\n"
3286 " \"conn\":\"%lu\",\n"
3287 " \"trans\":\"%lu\",\n"
3288 " \"ws_upg\":\"%lu\",\n"
3289 " \"rejected\":\"%lu\",\n"
3290 " \"http2_upg\":\"%lu\""
3292 vh->name, vh->listen_port,
3293 #ifdef LWS_OPENSSL_SUPPORT
3298 !!(vh->options & LWS_SERVER_OPTION_STS),
3299 vh->conn_stats.rx, vh->conn_stats.tx,
3300 vh->conn_stats.conn, vh->conn_stats.trans,
3301 vh->conn_stats.ws_upg,
3302 vh->conn_stats.rejected,
3303 vh->conn_stats.http2_upg
3306 if (vh->mount_list) {
3307 const struct lws_http_mount *m = vh->mount_list;
3309 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
3312 buf += lws_snprintf(buf, end - buf, ",");
3313 buf += lws_snprintf(buf, end - buf,
3314 "\n {\n \"mountpoint\":\"%s\",\n"
3315 " \"origin\":\"%s%s\",\n"
3316 " \"cache_max_age\":\"%d\",\n"
3317 " \"cache_reuse\":\"%d\",\n"
3318 " \"cache_revalidate\":\"%d\",\n"
3319 " \"cache_intermediaries\":\"%d\"\n"
3322 prots[m->origin_protocol],
3326 m->cache_revalidate,
3327 m->cache_intermediaries);
3329 buf += lws_snprintf(buf, end - buf,
3330 ",\n \"default\":\"%s\"",
3332 buf += lws_snprintf(buf, end - buf, "\n }");
3336 buf += lws_snprintf(buf, end - buf, "\n ]");
3339 if (vh->protocols) {
3343 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
3344 while (n < vh->count_protocols) {
3346 buf += lws_snprintf(buf, end - buf, ",");
3347 buf += lws_snprintf(buf, end - buf,
3349 " \"status\":\"ok\"\n }\n }"
3351 vh->protocols[n].name);
3355 buf += lws_snprintf(buf, end - buf, "\n ]");
3358 buf += lws_snprintf(buf, end - buf, "\n}");
3364 LWS_EXTERN LWS_VISIBLE int
3365 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
3368 char *orig = buf, *end = buf + len - 1, first = 1;
3369 const struct lws_vhost *vh = context->vhost_list;
3370 const struct lws_context_per_thread *pt;
3371 time_t t = time(NULL);
3372 int n, listening = 0, cgi_count = 0;
3373 struct lws_conn_stats cs;
3376 struct lws_cgi * const *pcgi;
3379 #ifdef LWS_USE_LIBUV
3383 buf += lws_snprintf(buf, end - buf, "{ "
3384 "\"version\":\"%s\",\n"
3385 "\"uptime\":\"%ld\",\n",
3386 lws_get_library_version(),
3389 #ifdef LWS_HAVE_GETLOADAVG
3394 m = getloadavg(d, 3);
3395 for (n = 0; n < m; n++) {
3396 buf += lws_snprintf(buf, end - buf,
3397 "\"l%d\":\"%.2f\",\n",
3403 buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
3405 buf += lws_snprintf(buf, end - buf, "{ "
3406 "\"context_uptime\":\"%ld\",\n"
3407 "\"cgi_spawned\":\"%d\",\n"
3408 "\"pt_fd_max\":\"%d\",\n"
3409 "\"ah_pool_max\":\"%d\",\n"
3410 "\"deprecated\":\"%d\",\n"
3411 "\"wsi_alive\":\"%d\",\n",
3412 (unsigned long)(t - context->time_up),
3413 context->count_cgi_spawned,
3414 context->fd_limit_per_thread,
3415 context->max_http_header_pool,
3416 context->deprecated,
3417 context->count_wsi_allocated);
3419 buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
3420 for (n = 0; n < context->count_threads; n++) {
3421 pt = &context->pt[n];
3423 buf += lws_snprintf(buf, end - buf, ",");
3424 buf += lws_snprintf(buf, end - buf,
3426 " \"fds_count\":\"%d\",\n"
3427 " \"ah_pool_inuse\":\"%d\",\n"
3428 " \"ah_wait_list\":\"%d\"\n"
3431 pt->ah_count_in_use,
3432 pt->ah_wait_list_length);
3435 buf += lws_snprintf(buf, end - buf, "]");
3437 buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3440 vh = context->vhost_list;
3442 cs = context->conn_stats;
3443 lws_sum_stats(context, &cs);
3450 buf += lws_json_dump_vhost(vh, buf, end - buf);
3455 vh = vh->vhost_next;
3458 buf += lws_snprintf(buf, end - buf,
3459 "],\n\"listen_wsi\":\"%d\",\n"
3460 " \"rx\":\"%llu\",\n"
3461 " \"tx\":\"%llu\",\n"
3462 " \"conn\":\"%lu\",\n"
3463 " \"trans\":\"%lu\",\n"
3464 " \"ws_upg\":\"%lu\",\n"
3465 " \"rejected\":\"%lu\",\n"
3466 " \"http2_upg\":\"%lu\"",
3468 cs.rx, cs.tx, cs.conn, cs.trans,
3469 cs.ws_upg, cs.rejected, cs.http2_upg);
3472 for (n = 0; n < context->count_threads; n++) {
3473 pt = &context->pt[n];
3474 pcgi = &pt->cgi_list;
3477 pcgi = &(*pcgi)->cgi_list;
3483 buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3486 buf += lws_snprintf(buf, end - buf, "}");
3489 buf += lws_snprintf(buf, end - buf, "]}\n ");
3496 #if defined(LWS_WITH_STATS)
3498 LWS_VISIBLE LWS_EXTERN uint64_t
3499 lws_stats_get(struct lws_context *context, int index)
3501 if (index >= LWSSTATS_SIZE)
3504 return context->lws_stats[index];
3507 LWS_VISIBLE LWS_EXTERN void
3508 lws_stats_log_dump(struct lws_context *context)
3510 struct lws_vhost *v = context->vhost_list;
3513 if (!context->updated)
3516 context->updated = 0;
3519 lwsl_notice("LWS internal statistics dump ----->\n");
3520 lwsl_notice("LWSSTATS_C_CONNECTIONS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_CONNECTIONS));
3521 lwsl_notice("LWSSTATS_C_API_CLOSE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_CLOSE));
3522 lwsl_notice("LWSSTATS_C_API_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_READ));
3523 lwsl_notice("LWSSTATS_C_API_LWS_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_LWS_WRITE));
3524 lwsl_notice("LWSSTATS_C_API_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_WRITE));
3525 lwsl_notice("LWSSTATS_C_WRITE_PARTIALS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITE_PARTIALS));
3526 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_REQ));
3527 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_EFF_REQ));
3528 lwsl_notice("LWSSTATS_C_WRITEABLE_CB: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB));
3529 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_FAILED));
3530 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED));
3531 lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX));
3533 lwsl_notice("LWSSTATS_C_TIMEOUTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_TIMEOUTS));
3534 lwsl_notice("LWSSTATS_C_SERVICE_ENTRY: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SERVICE_ENTRY));
3535 lwsl_notice("LWSSTATS_B_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ));
3536 lwsl_notice("LWSSTATS_B_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE));
3537 lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS));
3538 lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000);
3539 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED))
3540 lwsl_notice(" Avg accept delay: %8llums\n",
3541 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) /
3542 lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000);
3543 lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / 1000);
3544 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX))
3545 lwsl_notice(" Avg accept-rx delay: %8llums\n",
3546 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) /
3547 lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000);
3549 lwsl_notice("LWSSTATS_MS_WRITABLE_DELAY: %8lluus\n",
3550 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY));
3551 lwsl_notice("LWSSTATS_MS_WORST_WRITABLE_DELAY: %8lluus\n",
3552 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WORST_WRITABLE_DELAY));
3553 if (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))
3554 lwsl_notice(" Avg writable delay: %8lluus\n",
3555 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY) /
3556 lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)));
3557 lwsl_notice("Simultaneous SSL restriction: %8d/%d/%d\n", context->simultaneous_ssl,
3558 context->simultaneous_ssl_restriction, context->ssl_gate_accepts);
3560 lwsl_notice("Live wsi: %8d\n", context->count_wsi_allocated);
3562 #if defined(LWS_WITH_STATS)
3563 context->updated = 1;
3569 struct lws_context_per_thread *pt = &context->pt[(int)v->lserv_wsi->tsi];
3570 struct lws_pollfd *pfd;
3572 pfd = &pt->fds[v->lserv_wsi->position_in_fds_table];
3574 lwsl_notice(" Listen port %d actual POLLIN: %d\n",
3575 v->listen_port, (int)pfd->events & LWS_POLLIN);
3581 for (n = 0; n < context->count_threads; n++) {
3582 struct lws_context_per_thread *pt = &context->pt[n];
3586 lwsl_notice("PT %d\n", n + 1);
3590 lwsl_notice(" AH in use / max: %d / %d\n",
3591 pt->ah_count_in_use,
3592 context->max_http_header_pool);
3594 wl = pt->ah_wait_list;
3597 wl = wl->u.hdr.ah_wait_list;
3600 lwsl_notice(" AH wait list count / actual: %d / %d\n",
3601 pt->ah_wait_list_length, m);
3610 lws_stats_atomic_bump(struct lws_context * context,
3611 struct lws_context_per_thread *pt, int index, uint64_t bump)
3614 context->lws_stats[index] += bump;
3615 if (index != LWSSTATS_C_SERVICE_ENTRY)
3616 context->updated = 1;
3621 lws_stats_atomic_max(struct lws_context * context,
3622 struct lws_context_per_thread *pt, int index, uint64_t val)
3625 if (val > context->lws_stats[index]) {
3626 context->lws_stats[index] = val;
3627 context->updated = 1;