2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "private-libwebsockets.h"
24 #ifdef LWS_HAVE_SYS_TYPES_H
25 #include <sys/types.h>
28 #if defined(WIN32) || defined(_WIN32)
34 #if defined(WIN32) || defined(_WIN32)
41 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
42 static void (*lwsl_emit)(int level, const char *line)
43 #ifndef LWS_PLAT_OPTEE
47 #ifndef LWS_PLAT_OPTEE
48 static const char * const log_level_names[] = {
66 lws_free_wsi(struct lws *wsi)
71 /* Protocol user data may be allocated either internally by lws
72 * or by specified the user.
73 * We should only free what we allocated. */
74 if (wsi->protocol && wsi->protocol->per_session_data_size &&
75 wsi->user_space && !wsi->user_space_externally_allocated)
76 lws_free(wsi->user_space);
78 lws_free_set_NULL(wsi->rxflow_buffer);
79 lws_free_set_NULL(wsi->trunc_alloc);
81 /* we may not have an ah, but may be on the waiting list... */
82 lwsl_info("ah det due to close\n");
83 lws_header_table_detach(wsi, 0);
85 wsi->context->count_wsi_allocated--;
86 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
87 wsi->context->count_wsi_allocated);
93 lws_remove_from_timeout_list(struct lws *wsi)
95 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
97 if (!wsi->timeout_list_prev) /* ie, not part of the list */
101 /* if we have a next guy, set his prev to our prev */
102 if (wsi->timeout_list)
103 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
104 /* set our prev guy to our next guy instead of us */
105 *wsi->timeout_list_prev = wsi->timeout_list;
107 /* we're out of the list, we should not point anywhere any more */
108 wsi->timeout_list_prev = NULL;
109 wsi->timeout_list = NULL;
114 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
116 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
123 if (reason && !wsi->timeout_list_prev) {
124 /* our next guy is current first guy */
125 wsi->timeout_list = pt->timeout_list;
126 /* if there is a next guy, set his prev ptr to our next ptr */
127 if (wsi->timeout_list)
128 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
129 /* our prev ptr is first ptr */
130 wsi->timeout_list_prev = &pt->timeout_list;
131 /* set the first guy to be us */
132 *wsi->timeout_list_prev = wsi;
135 lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
136 wsi->pending_timeout_limit = now + secs;
137 wsi->pending_timeout = reason;
142 lws_remove_from_timeout_list(wsi);
146 lws_remove_child_from_any_parent(struct lws *wsi)
154 /* detach ourselves from parent's child list */
155 pwsi = &wsi->parent->child_list;
158 lwsl_info("%s: detach %p from parent %p\n",
159 __func__, wsi, wsi->parent);
160 *pwsi = wsi->sibling_list;
164 pwsi = &(*pwsi)->sibling_list;
167 lwsl_err("%s: failed to detach from parent\n", __func__);
173 lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)
175 // if (wsi->protocol == p)
177 const struct lws_protocols *vp = wsi->vhost->protocols, *vpo;
180 wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,
181 wsi->user_space, NULL, 0);
182 if (!wsi->user_space_externally_allocated)
183 lws_free_set_NULL(wsi->user_space);
185 lws_same_vh_protocol_remove(wsi);
191 if (lws_ensure_user_space(wsi))
194 if (p > vp && p < &vp[wsi->vhost->count_protocols])
195 lws_same_vh_protocol_insert(wsi, p - vp);
197 int n = wsi->vhost->count_protocols;
203 if (p->name && vp->name && !strcmp(p->name, vp->name)) {
205 lws_same_vh_protocol_insert(wsi, vp - vpo);
211 lwsl_err("%s: protocol %p is not in vhost %s protocols list\n",
212 __func__, p, wsi->vhost->name);
215 if (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,
216 wsi->user_space, NULL, 0))
223 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
225 struct lws_context_per_thread *pt;
226 struct lws *wsi1, *wsi2;
227 struct lws_context *context;
228 struct lws_tokens eff_buf;
235 #if defined(LWS_WITH_ESP8266)
236 if (wsi->premature_rx)
237 lws_free(wsi->premature_rx);
239 if (wsi->pending_send_completion && !wsi->close_is_pending_send_completion) {
240 lwsl_notice("delaying close\n");
241 wsi->close_is_pending_send_completion = 1;
247 /* we're closing, losing some rx is OK */
248 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
250 context = wsi->context;
251 pt = &context->pt[(int)wsi->tsi];
252 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_CLOSE, 1);
254 /* if we have children, close them first */
255 if (wsi->child_list) {
256 wsi2 = wsi->child_list;
258 //lwsl_notice("%s: closing %p: close child %p\n",
259 // __func__, wsi, wsi2);
260 wsi1 = wsi2->sibling_list;
261 //lwsl_notice("%s: closing %p: next sibling %p\n",
262 // __func__, wsi2, wsi1);
264 /* stop it doing shutdown processing */
265 wsi2->socket_is_permanently_unusable = 1;
266 lws_close_free_wsi(wsi2, reason);
269 wsi->child_list = NULL;
272 if (wsi->mode == LWSCM_RAW_FILEDESC) {
273 lws_remove_child_from_any_parent(wsi);
274 remove_wsi_socket_from_fds(wsi);
275 wsi->protocol->callback(wsi,
276 LWS_CALLBACK_RAW_CLOSE_FILE,
277 wsi->user_space, NULL, 0);
282 if (wsi->mode == LWSCM_CGI) {
283 /* we are not a network connection, but a handler for CGI io */
284 if (wsi->parent && wsi->parent->cgi)
285 /* end the binding between us and master */
286 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
287 wsi->socket_is_permanently_unusable = 1;
289 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
290 goto just_kill_connection;
294 struct lws_cgi **pcgi = &pt->cgi_list;
295 /* remove us from the cgi list */
296 lwsl_debug("%s: remove cgi %p from list\n", __func__, wsi->cgi);
298 if (*pcgi == wsi->cgi) {
299 /* drop us from the pt cgi list */
300 *pcgi = (*pcgi)->cgi_list;
303 pcgi = &(*pcgi)->cgi_list;
305 /* we have a cgi going, we must kill it */
306 wsi->cgi->being_closed = 1;
311 if (wsi->mode == LWSCM_RAW) {
312 wsi->protocol->callback(wsi,
313 LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0);
314 wsi->socket_is_permanently_unusable = 1;
315 goto just_kill_connection;
318 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
319 wsi->u.http.fop_fd != NULL) {
320 lws_vfs_file_close(&wsi->u.http.fop_fd);
321 wsi->vhost->protocols->callback(wsi,
322 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
323 wsi->told_user_closed = 1;
325 if (wsi->socket_is_permanently_unusable ||
326 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
327 wsi->state == LWSS_SHUTDOWN)
328 goto just_kill_connection;
330 wsi->state_pre_close = wsi->state;
332 switch (wsi->state_pre_close) {
333 case LWSS_DEAD_SOCKET:
336 /* we tried the polite way... */
337 case LWSS_AWAITING_CLOSE_ACK:
338 goto just_kill_connection;
340 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
341 if (wsi->trunc_len) {
342 lws_callback_on_writable(wsi);
345 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
346 goto just_kill_connection;
348 if (wsi->trunc_len) {
349 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
350 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
351 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
357 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
358 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
359 goto just_kill_connection;
361 if (wsi->mode == LWSCM_HTTP_SERVING) {
363 wsi->vhost->protocols->callback(wsi,
364 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
365 wsi->user_space, NULL, 0);
366 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
367 wsi->user_space, NULL, 0);
368 wsi->told_user_closed = 1;
370 if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
371 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
372 wsi->user_space, NULL, 0);
373 wsi->told_user_closed = 1;
377 * are his extensions okay with him closing? Eg he might be a mux
378 * parent and just his ch1 aspect is closing?
381 if (lws_ext_cb_active(wsi,
382 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
383 lwsl_ext("extension vetoed close\n");
388 * flush any tx pending from extensions, since we may send close packet
389 * if there are problems with send, just nuke the connection
394 eff_buf.token = NULL;
395 eff_buf.token_len = 0;
397 /* show every extension the new incoming data */
399 m = lws_ext_cb_active(wsi,
400 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
402 lwsl_ext("Extension reports fatal error\n");
403 goto just_kill_connection;
407 * at least one extension told us he has more
408 * to spill, so we will go around again after
412 /* assuming they left us something to send, send it */
414 if (eff_buf.token_len)
415 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
416 eff_buf.token_len) !=
418 lwsl_debug("close: ext spill failed\n");
419 goto just_kill_connection;
424 * signal we are closing, lws_write will
425 * add any necessary version-specific stuff. If the write fails,
426 * no worries we are closing anyway. If we didn't initiate this
427 * close, then our state has been changed to
428 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
430 * Likewise if it's a second call to close this connection after we
431 * sent the close indication to the peer already, we are in state
432 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
435 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
436 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
437 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
438 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
439 lwsl_debug("sending close indication...\n");
441 /* if no prepared close reason, use 1000 and no aux data */
442 if (!wsi->u.ws.close_in_ping_buffer_len) {
443 wsi->u.ws.close_in_ping_buffer_len = 2;
444 wsi->u.ws.ping_payload_buf[LWS_PRE] =
445 (reason >> 8) & 0xff;
446 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
450 #if defined (LWS_WITH_ESP8266)
451 wsi->close_is_pending_send_completion = 1;
453 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
454 wsi->u.ws.close_in_ping_buffer_len,
458 * we have sent a nice protocol level indication we
459 * now wish to close, we should not send anything more
461 wsi->state = LWSS_AWAITING_CLOSE_ACK;
464 * ...and we should wait for a reply for a bit
467 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
468 lwsl_debug("sent close indication, awaiting ack\n");
473 lwsl_info("close: sending close packet failed, hanging up\n");
475 /* else, the send failed and we should just hang up */
478 just_kill_connection:
480 lws_remove_child_from_any_parent(wsi);
483 /* manage the vhost same protocol list entry */
485 if (wsi->same_vh_protocol_prev) { // we are on the vh list
487 // make guy who pointed to us, point to what our next was pointing to
488 *wsi->same_vh_protocol_prev = wsi->same_vh_protocol_next;
490 // if we had a next guy...
491 if (wsi->same_vh_protocol_next)
492 // have him point back to our prev
493 wsi->same_vh_protocol_next->same_vh_protocol_prev =
494 wsi->same_vh_protocol_prev;
500 * Testing with ab shows that we have to stage the socket close when
501 * the system is under stress... shutdown any further TX, change the
502 * state to one that won't emit anything more, and wait with a timeout
503 * for the POLLIN to show a zero-size rx before coming back and doing
506 if (wsi->mode != LWSCM_RAW &&
507 !(wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) &&
508 wsi->state != LWSS_SHUTDOWN &&
509 wsi->state != LWSS_CLIENT_UNCONNECTED &&
510 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
511 !wsi->socket_is_permanently_unusable) {
512 #ifdef LWS_OPENSSL_SUPPORT
513 if (lws_is_ssl(wsi) && wsi->ssl)
515 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);
516 n = SSL_shutdown(wsi->ssl);
517 if (n == 1) /* If finished the SSL shutdown, then do socket shutdown, else need to retry SSL shutdown */
518 n = shutdown(wsi->desc.sockfd, SHUT_WR);
520 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
523 int shutdown_error = SSL_get_error(wsi->ssl, n);
524 lwsl_debug("SSL_shutdown returned %d, SSL_get_error: %d\n", n, shutdown_error);
525 if (shutdown_error == SSL_ERROR_WANT_READ) {
526 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
528 } else if (shutdown_error == SSL_ERROR_WANT_WRITE) {
529 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLOUT);
531 } else { // actual error occurred, just close the connection
532 n = shutdown(wsi->desc.sockfd, SHUT_WR);
539 lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, (int)(long)wsi->desc.sockfd, wsi->state);
540 n = shutdown(wsi->desc.sockfd, SHUT_WR);
543 lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
545 // This causes problems with disconnection when the events are half closing connection
546 // FD_READ | FD_CLOSE (33)
547 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP32)
548 /* libuv: no event available to guarantee completion */
549 if (!LWS_LIBUV_ENABLED(context)) {
551 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
552 wsi->state = LWSS_SHUTDOWN;
553 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
554 context->timeout_secs);
562 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
563 wsi, wsi->desc.sockfd);
565 #ifdef LWS_WITH_HTTP_PROXY
567 lws_rewrite_destroy(wsi->rw);
572 * we won't be servicing or receiving anything further from this guy
573 * delete socket from the internal poll list if still present
575 lws_ssl_remove_wsi_from_buffered_list(wsi);
577 lws_remove_from_timeout_list(wsi);
579 /* checking return redundant since we anyway close */
580 if (wsi->desc.sockfd != LWS_SOCK_INVALID)
581 remove_wsi_socket_from_fds(wsi);
583 #if defined(LWS_WITH_ESP8266)
584 espconn_disconnect(wsi->desc.sockfd);
587 wsi->state = LWSS_DEAD_SOCKET;
589 lws_free_set_NULL(wsi->rxflow_buffer);
590 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
591 wsi->mode == LWSCM_WS_SERVING ||
592 wsi->mode == LWSCM_WS_CLIENT) {
594 if (wsi->u.ws.rx_draining_ext) {
595 struct lws **w = &pt->rx_draining_ext_list;
597 wsi->u.ws.rx_draining_ext = 0;
598 /* remove us from context draining ext list */
601 *w = wsi->u.ws.rx_draining_ext_list;
604 w = &((*w)->u.ws.rx_draining_ext_list);
606 wsi->u.ws.rx_draining_ext_list = NULL;
609 if (wsi->u.ws.tx_draining_ext) {
610 struct lws **w = &pt->tx_draining_ext_list;
612 wsi->u.ws.tx_draining_ext = 0;
613 /* remove us from context draining ext list */
616 *w = wsi->u.ws.tx_draining_ext_list;
619 w = &((*w)->u.ws.tx_draining_ext_list);
621 wsi->u.ws.tx_draining_ext_list = NULL;
623 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
625 if (wsi->trunc_alloc)
626 /* not going to be completed... nuke it */
627 lws_free_set_NULL(wsi->trunc_alloc);
629 wsi->u.ws.ping_payload_len = 0;
630 wsi->u.ws.ping_pending_flag = 0;
633 /* tell the user it's all over for this guy */
635 if (wsi->mode != LWSCM_RAW && wsi->protocol && wsi->protocol->callback &&
636 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
637 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
638 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
639 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
640 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
641 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
643 if (wsi->user_space) {
644 lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s\n", __func__, wsi, wsi->protocol->name);
645 wsi->protocol->callback(wsi,
646 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
647 wsi->user_space, NULL, 0);
649 lwsl_debug("calling back CLOSED\n");
650 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
651 wsi->user_space, NULL, 0);
652 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
653 lwsl_debug("calling back CLOSED_HTTP\n");
654 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
655 wsi->user_space, NULL, 0 );
656 } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
657 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
658 !wsi->already_did_cce) {
659 wsi->vhost->protocols[0].callback(wsi,
660 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
661 wsi->user_space, NULL, 0);
663 lwsl_debug("not calling back closed mode=%d state=%d\n",
664 wsi->mode, wsi->state_pre_close);
666 /* deallocate any active extension contexts */
668 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
669 lwsl_warn("extension destruction failed\n");
671 * inform all extensions in case they tracked this guy out of band
672 * even though not active on him specifically
674 if (lws_ext_cb_all_exts(context, wsi,
675 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
676 lwsl_warn("ext destroy wsi failed\n");
680 wsi->socket_is_permanently_unusable = 1;
683 if (LWS_LIBUV_ENABLED(context)) {
684 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
685 /* libuv has to do his own close handle processing asynchronously */
686 lws_libuv_closehandle(wsi);
692 lws_close_free_wsi_final(wsi);
696 lws_close_free_wsi_final(struct lws *wsi)
700 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->desc.sockfd)) {
702 //lwsl_err("*** closing sockfd %d\n", wsi->desc.sockfd);
703 n = compatible_close(wsi->desc.sockfd);
705 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
708 compatible_close(wsi->desc.sockfd);
711 wsi->desc.sockfd = LWS_SOCK_INVALID;
714 /* outermost destroy notification for wsi (user_space still intact) */
715 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
716 wsi->user_space, NULL, 0);
720 for (n = 0; n < 6; n++) {
721 if (wsi->cgi->pipe_fds[n / 2][n & 1] == 0)
722 lwsl_err("ZERO FD IN CGI CLOSE");
724 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
725 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
735 LWS_VISIBLE LWS_EXTERN const char *
736 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
738 int n = 0, sl = strlen(name);
740 while (lws_hdr_copy_fragment(wsi, buf, len,
741 WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
743 if (!strncmp(buf, name, sl))
752 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
754 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
758 ipv6 = LWS_IPV6_ENABLED(vh);
762 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
766 #ifndef LWS_PLAT_OPTEE
769 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
770 int name_len, char *rip, int rip_len)
773 struct addrinfo ai, *res;
774 struct sockaddr_in addr4;
779 addr4.sin_family = AF_UNSPEC;
782 if (LWS_IPV6_ENABLED(vh)) {
783 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
784 lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
788 // Strip off the IPv4 to IPv6 header if one exists
789 if (strncmp(rip, "::ffff:", 7) == 0)
790 memmove(rip, rip + 7, strlen(rip) - 6);
792 getnameinfo((struct sockaddr *)ads,
793 sizeof(struct sockaddr_in6), name,
794 name_len, NULL, 0, 0);
800 struct addrinfo *result;
802 memset(&ai, 0, sizeof ai);
803 ai.ai_family = PF_UNSPEC;
804 ai.ai_socktype = SOCK_STREAM;
805 ai.ai_flags = AI_CANONNAME;
806 #if !defined(LWS_WITH_ESP32)
807 if (getnameinfo((struct sockaddr *)ads,
808 sizeof(struct sockaddr_in),
809 name, name_len, NULL, 0, 0))
815 if (getaddrinfo(name, NULL, &ai, &result))
819 while (addr4.sin_family == AF_UNSPEC && res) {
820 switch (res->ai_family) {
822 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
823 addr4.sin_family = AF_INET;
829 freeaddrinfo(result);
832 if (addr4.sin_family == AF_UNSPEC)
835 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
853 LWS_VISIBLE const char *
854 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
859 struct sockaddr_in6 sin6;
861 struct sockaddr_in sin4;
866 if (LWS_IPV6_ENABLED(wsi->vhost)) {
880 if (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {
881 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
885 return lws_plat_inet_ntop(af, q, name, namelen);
887 #if defined(LWS_WITH_ESP8266)
888 return lws_plat_get_peer_simple(wsi, name, namelen);
897 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
898 int name_len, char *rip, int rip_len)
900 #ifndef LWS_PLAT_OPTEE
904 struct sockaddr_in6 sin6;
906 struct sockaddr_in sin4;
907 struct lws_context *context = wsi->context;
914 lws_latency_pre(context, wsi);
917 if (LWS_IPV6_ENABLED(wsi->vhost)) {
927 if (getpeername(fd, p, &len) < 0) {
928 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
932 ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
935 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
948 lws_context_user(struct lws_context *context)
950 return context->user_space;
953 LWS_VISIBLE struct lws_vhost *
954 lws_vhost_get(struct lws *wsi)
959 LWS_VISIBLE struct lws_vhost *
960 lws_get_vhost(struct lws *wsi)
965 LWS_VISIBLE const struct lws_protocols *
966 lws_protocol_get(struct lws *wsi)
968 return wsi->protocol;
971 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
972 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
976 for (n = 0; n < vh->count_protocols; n++)
977 if (!strcmp(name, vh->protocols[n].name))
978 return &vh->protocols[n];
984 lws_callback_all_protocol(struct lws_context *context,
985 const struct lws_protocols *protocol, int reason)
987 struct lws_context_per_thread *pt = &context->pt[0];
988 unsigned int n, m = context->count_threads;
992 for (n = 0; n < pt->fds_count; n++) {
993 wsi = wsi_from_fd(context, pt->fds[n].fd);
996 if (wsi->protocol == protocol)
997 protocol->callback(wsi, reason, wsi->user_space,
1007 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
1008 const struct lws_protocols *protocol, int reason)
1010 struct lws_context *context = vh->context;
1011 struct lws_context_per_thread *pt = &context->pt[0];
1012 unsigned int n, m = context->count_threads;
1016 for (n = 0; n < pt->fds_count; n++) {
1017 wsi = wsi_from_fd(context, pt->fds[n].fd);
1020 if (wsi->vhost == vh && wsi->protocol == protocol)
1021 protocol->callback(wsi, reason, wsi->user_space,
1030 LWS_VISIBLE LWS_EXTERN int
1031 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
1035 for (n = 0; n < wsi->vhost->count_protocols; n++)
1036 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
1042 LWS_VISIBLE LWS_EXTERN void
1043 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)
1045 context->fops = fops;
1048 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1049 lws_vfs_tell(lws_fop_fd_t fop_fd)
1054 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1055 lws_vfs_get_length(lws_fop_fd_t fop_fd)
1060 LWS_VISIBLE LWS_EXTERN uint32_t
1061 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd)
1063 return fop_fd->mod_time;
1066 LWS_VISIBLE lws_fileofs_t
1067 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1070 lwsl_debug("%s: seeking to %ld, len %ld\n", __func__, (long)offset, (long)fop_fd->len);
1071 ofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);
1072 lwsl_debug("%s: result %ld, fop_fd pos %ld\n", __func__, (long)ofs, (long)fop_fd->pos);
1077 LWS_VISIBLE lws_fileofs_t
1078 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1080 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len + fop_fd->pos + offset);
1084 const struct lws_plat_file_ops *
1085 lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,
1088 const struct lws_plat_file_ops *pf;
1089 const char *p = vfs_path;
1094 /* no non-platform fops, just use that */
1100 * scan the vfs path looking for indications we are to be
1101 * handled by a specific fops
1109 /* the first one is always platform fops, so skip */
1113 while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {
1114 if (p >= vfs_path + pf->fi[n].len)
1115 if (!strncmp(p - (pf->fi[n].len - 1),
1117 pf->fi[n].len - 1)) {
1132 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
1133 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
1134 lws_fop_flags_t *flags)
1136 const char *vpath = "";
1137 const struct lws_plat_file_ops *selected = lws_vfs_select_fops(
1138 fops, vfs_path, &vpath);
1140 return selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);
1145 * lws_now_secs() - seconds since 1970-1-1
1148 LWS_VISIBLE LWS_EXTERN unsigned long
1153 gettimeofday(&tv, NULL);
1162 lws_get_socket_fd(struct lws *wsi)
1164 return wsi->desc.sockfd;
1171 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
1172 int ret, int completed)
1174 unsigned long long u;
1177 u = time_in_microseconds();
1180 wsi->latency_start = u;
1181 if (!wsi->action_start)
1182 wsi->action_start = u;
1186 if (wsi->action_start == wsi->latency_start)
1188 "Completion first try lat %lluus: %p: ret %d: %s\n",
1189 u - wsi->latency_start,
1190 (void *)wsi, ret, action);
1193 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1194 u - wsi->action_start,
1195 u - wsi->latency_start,
1196 (void *)wsi, ret, action);
1197 wsi->action_start = 0;
1199 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1200 u - wsi->latency_start, (void *)wsi, ret, action);
1202 if (u - wsi->latency_start > context->worst_latency) {
1203 context->worst_latency = u - wsi->latency_start;
1204 strcpy(context->worst_latency_info, buf);
1206 lwsl_latency("%s", buf);
1211 lws_rx_flow_control(struct lws *wsi, int enable)
1213 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1216 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1217 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1223 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1224 const struct lws_protocols *protocol)
1226 const struct lws_context_per_thread *pt = &context->pt[0];
1228 unsigned int n, m = context->count_threads;
1231 for (n = 0; n < pt->fds_count; n++) {
1232 wsi = wsi_from_fd(context, pt->fds[n].fd);
1235 if (wsi->protocol == protocol)
1236 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1242 LWS_VISIBLE extern const char *
1243 lws_canonical_hostname(struct lws_context *context)
1245 return (const char *)context->canonical_hostname;
1248 int user_callback_handle_rxflow(lws_callback_function callback_function,
1250 enum lws_callback_reasons reason, void *user,
1251 void *in, size_t len)
1255 n = callback_function(wsi, reason, user, in, len);
1257 n = _lws_rx_flow_control(wsi);
1262 #if defined(LWS_WITH_ESP8266)
1264 #define strchr ets_strchr
1268 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1270 #if !defined(LWS_WITH_ESP8266)
1272 char authstring[96];
1277 /* we have to deal with a possible redundant leading http:// */
1278 if (!strncmp(proxy, "http://", 7))
1281 p = strchr(proxy, '@');
1282 if (p) { /* auth is around */
1284 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1287 strncpy(authstring, proxy, p - proxy);
1288 // null termination not needed on input
1289 if (lws_b64_encode_string(authstring, (p - proxy),
1290 vhost->proxy_basic_auth_token,
1291 sizeof vhost->proxy_basic_auth_token) < 0)
1294 lwsl_info(" Proxy auth in use\n");
1298 vhost->proxy_basic_auth_token[0] = '\0';
1300 strncpy(vhost->http_proxy_address, proxy,
1301 sizeof(vhost->http_proxy_address) - 1);
1302 vhost->http_proxy_address[
1303 sizeof(vhost->http_proxy_address) - 1] = '\0';
1305 p = strchr(vhost->http_proxy_address, ':');
1306 if (!p && !vhost->http_proxy_port) {
1307 lwsl_err("http_proxy needs to be ads:port\n");
1313 vhost->http_proxy_port = atoi(p + 1);
1317 lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1318 vhost->http_proxy_port);
1323 lwsl_err("proxy auth too long\n");
1328 LWS_VISIBLE const struct lws_protocols *
1329 lws_get_protocol(struct lws *wsi)
1331 return wsi->protocol;
1335 lws_is_final_fragment(struct lws *wsi)
1337 lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1338 wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1339 (long)wsi->u.ws.rx_draining_ext);
1340 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1343 LWS_VISIBLE unsigned char
1344 lws_get_reserved_bits(struct lws *wsi)
1346 return wsi->u.ws.rsv;
1350 lws_ensure_user_space(struct lws *wsi)
1352 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1356 /* allocate the per-connection user memory (if any) */
1358 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1359 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1360 if (wsi->user_space == NULL) {
1361 lwsl_err("Out of memory for conn user space\n");
1365 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1366 __func__, wsi, (long)wsi->protocol->per_session_data_size,
1372 lwsl_timestamp(int level, char *p, int len)
1374 #ifndef LWS_PLAT_OPTEE
1375 time_t o_now = time(NULL);
1376 unsigned long long now;
1377 struct tm *ptm = NULL;
1385 ptm = localtime(&o_now);
1387 if (localtime_r(&o_now, &tm))
1392 for (n = 0; n < LLL_COUNT; n++) {
1393 if (level != (1 << n))
1395 now = time_in_microseconds() / 100;
1397 n = lws_snprintf(p, len,
1398 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1399 ptm->tm_year + 1900,
1405 (int)(now % 10000), log_level_names[n]);
1407 n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1408 (unsigned long long) now / 10000,
1409 (int)(now % 10000), log_level_names[n]);
1416 #ifndef LWS_PLAT_OPTEE
1417 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1419 #if !defined(LWS_WITH_ESP8266)
1422 lwsl_timestamp(level, buf, sizeof(buf));
1423 fprintf(stderr, "%s%s", buf, line);
1428 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1430 #if defined(LWS_WITH_ESP8266)
1437 if (!(log_level & filter))
1440 n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1442 #if defined(LWS_WITH_ESP8266)
1443 buf[sizeof(buf) - 1] = '\0';
1445 /* vnsprintf returns what it would have written, even if truncated */
1446 if (n > sizeof(buf) - 1)
1447 n = sizeof(buf) - 1;
1452 lwsl_emit(filter, buf);
1455 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1459 va_start(ap, format);
1460 _lws_logv(filter, format, ap);
1464 LWS_VISIBLE void lws_set_log_level(int level,
1465 void (*func)(int level, const char *line))
1472 LWS_VISIBLE int lwsl_visible(int level)
1474 return log_level & level;
1478 lws_is_ssl(struct lws *wsi)
1480 #ifdef LWS_OPENSSL_SUPPORT
1481 return wsi->use_ssl;
1488 #ifdef LWS_OPENSSL_SUPPORT
1490 lws_get_ssl(struct lws *wsi)
1497 lws_partial_buffered(struct lws *wsi)
1499 return !!wsi->trunc_len;
1502 void lws_set_protocol_write_pending(struct lws *wsi,
1503 enum lws_pending_protocol_send pend)
1505 lwsl_info("setting pps %d\n", pend);
1508 lwsl_err("pps overwrite\n");
1510 lws_rx_flow_control(wsi, 0);
1511 lws_callback_on_writable(wsi);
1515 lws_get_peer_write_allowance(struct lws *wsi)
1517 #ifdef LWS_USE_HTTP2
1518 /* only if we are using HTTP2 on this connection */
1519 if (wsi->mode != LWSCM_HTTP2_SERVING)
1521 /* user is only interested in how much he can send, or that he can't */
1522 if (wsi->u.http2.tx_credit <= 0)
1525 return wsi->u.http2.tx_credit;
1533 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1535 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1536 memset(&wsi->u, 0, sizeof(wsi->u));
1540 LWS_VISIBLE struct lws_plat_file_ops *
1541 lws_get_fops(struct lws_context *context)
1543 return (struct lws_plat_file_ops *)context->fops;
1546 LWS_VISIBLE LWS_EXTERN struct lws_context *
1547 lws_get_context(const struct lws *wsi)
1549 return wsi->context;
1552 LWS_VISIBLE LWS_EXTERN int
1553 lws_get_count_threads(struct lws_context *context)
1555 return context->count_threads;
1558 LWS_VISIBLE LWS_EXTERN void *
1559 lws_wsi_user(struct lws *wsi)
1561 return wsi->user_space;
1564 LWS_VISIBLE LWS_EXTERN void
1565 lws_set_wsi_user(struct lws *wsi, void *data)
1567 if (wsi->user_space_externally_allocated)
1568 wsi->user_space = data;
1570 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1574 LWS_VISIBLE LWS_EXTERN struct lws *
1575 lws_get_parent(const struct lws *wsi)
1580 LWS_VISIBLE LWS_EXTERN struct lws *
1581 lws_get_child(const struct lws *wsi)
1583 return wsi->child_list;
1586 LWS_VISIBLE LWS_EXTERN void
1587 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1588 unsigned char *buf, size_t len)
1590 unsigned char *p, *start;
1591 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1593 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1595 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1597 *p++ = (((int)status) >> 8) & 0xff;
1598 *p++ = ((int)status) & 0xff;
1601 while (len-- && p < start + budget)
1604 wsi->u.ws.close_in_ping_buffer_len = p - start;
1608 _lws_rx_flow_control(struct lws *wsi)
1610 struct lws *wsic = wsi->child_list;
1612 /* if he has children, do those if they were changed */
1614 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1615 _lws_rx_flow_control(wsic);
1617 wsic = wsic->sibling_list;
1620 /* there is no pending change */
1621 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1622 // lwsl_debug("%s: no pending change\n", __func__);
1626 /* stuff is still buffered, not ready to really accept new input */
1627 if (wsi->rxflow_buffer) {
1628 /* get ourselves called back to deal with stashed buffer */
1629 lws_callback_on_writable(wsi);
1633 /* pending is cleared, we can change rxflow state */
1635 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1637 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1638 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1640 /* adjust the pollfd for this wsi */
1642 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1643 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1644 lwsl_info("%s: fail\n", __func__);
1648 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1655 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1657 static const unsigned char e0f4[] = {
1658 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1659 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1660 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1661 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1662 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1663 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1664 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1665 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1666 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1667 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1668 0x80 | ((4 - 1) << 2) | 1, /* ea */
1669 0x80 | ((4 - 1) << 2) | 1, /* eb */
1670 0x80 | ((4 - 1) << 2) | 1, /* ec */
1671 0x80 | ((2 - 1) << 2) | 1, /* ed */
1672 0x80 | ((4 - 1) << 2) | 1, /* ee */
1673 0x80 | ((4 - 1) << 2) | 1, /* ef */
1674 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1675 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1676 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1677 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1678 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1681 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1682 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1684 unsigned char s = *state;
1687 unsigned char c = *buf++;
1691 if (c < 0xc2 || c > 0xf4)
1694 s = 0x80 | ((4 - 1) << 2);
1699 if (c < (s & 0xf0) ||
1700 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1702 s = e0f4[21 + (s & 3)];
1711 LWS_VISIBLE LWS_EXTERN int
1712 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1716 static const char *slash = "/";
1718 /* cut up the location into address, port and path */
1720 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1731 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1733 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1739 while (*p && *p != ']')
1746 while (*p && *p != ':' && *p != '/')
1752 while (*p && *p != '/')
1765 #ifdef LWS_NO_EXTENSIONS
1767 /* we need to provide dummy callbacks for internal exts
1768 * so user code runs when faced with a lib compiled with
1769 * extensions disabled.
1773 lws_extension_callback_pm_deflate(struct lws_context *context,
1774 const struct lws_extension *ext,
1776 enum lws_extension_callback_reasons reason,
1777 void *user, void *in, size_t len)
1792 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1796 #ifdef LWS_USE_UNIX_SOCK
1797 struct sockaddr_un serv_unix;
1800 struct sockaddr_in6 serv_addr6;
1802 struct sockaddr_in serv_addr4;
1803 #ifndef LWS_PLAT_OPTEE
1804 socklen_t len = sizeof(struct sockaddr);
1807 struct sockaddr_in sin;
1810 #ifdef LWS_USE_UNIX_SOCK
1811 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1812 v = (struct sockaddr *)&serv_unix;
1813 n = sizeof(struct sockaddr_un);
1814 bzero((char *) &serv_unix, sizeof(serv_unix));
1815 serv_unix.sun_family = AF_UNIX;
1816 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1817 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1821 strcpy(serv_unix.sun_path, iface);
1822 if (serv_unix.sun_path[0] == '@')
1823 serv_unix.sun_path[0] = '\0';
1827 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1828 if (LWS_IPV6_ENABLED(vhost)) {
1829 v = (struct sockaddr *)&serv_addr6;
1830 n = sizeof(struct sockaddr_in6);
1831 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1833 interface_to_sa(vhost, iface,
1834 (struct sockaddr_in *)v, n) < 0) {
1835 lwsl_err("Unable to find interface %s\n", iface);
1840 struct ifaddrs *addrs, *addr;
1841 char ip[NI_MAXHOST];
1845 for (addr = addrs; addr; addr = addr->ifa_next) {
1846 if (!addr->ifa_addr ||
1847 addr->ifa_addr->sa_family != AF_INET6)
1850 getnameinfo(addr->ifa_addr,
1851 sizeof(struct sockaddr_in6),
1853 NULL, 0, NI_NUMERICHOST);
1857 if (ip[i++] == '%') {
1862 if (!strcmp(ip, iface)) {
1863 serv_addr6.sin6_scope_id =
1864 if_nametoindex(addr->ifa_name);
1871 serv_addr6.sin6_family = AF_INET6;
1872 serv_addr6.sin6_port = htons(port);
1876 v = (struct sockaddr *)&serv_addr4;
1877 n = sizeof(serv_addr4);
1878 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1879 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1880 serv_addr4.sin_family = AF_INET;
1881 #if !defined(LWS_WITH_ESP32)
1884 interface_to_sa(vhost, iface,
1885 (struct sockaddr_in *)v, n) < 0) {
1886 lwsl_err("Unable to find interface %s\n", iface);
1890 serv_addr4.sin_port = htons(port);
1893 n = bind(sockfd, v, n);
1894 #ifdef LWS_USE_UNIX_SOCK
1895 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
1896 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1897 sockfd, iface, n, LWS_ERRNO);
1902 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1903 sockfd, port, n, LWS_ERRNO);
1907 #ifndef LWS_PLAT_OPTEE
1908 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1909 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1912 port = ntohs(sin.sin_port);
1919 lws_restart_ws_ping_pong_timer(struct lws *wsi)
1921 if (!wsi->context->ws_ping_pong_interval)
1923 if (wsi->state != LWSS_ESTABLISHED)
1926 wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
1927 wsi->context->ws_ping_pong_interval;
1930 static const char *hex = "0123456789ABCDEF";
1932 LWS_VISIBLE LWS_EXTERN const char *
1933 lws_sql_purify(char *escaped, const char *string, int len)
1935 const char *p = string;
1938 while (*p && len-- > 2) {
1952 LWS_VISIBLE LWS_EXTERN const char *
1953 lws_json_purify(char *escaped, const char *string, int len)
1955 const char *p = string;
1963 while (*p && len-- > 6) {
1964 if (*p == '\"' || *p == '\\' || *p < 0x20) {
1969 *q++ = hex[((*p) >> 4) & 15];
1970 *q++ = hex[(*p) & 15];
1981 LWS_VISIBLE LWS_EXTERN const char *
1982 lws_urlencode(char *escaped, const char *string, int len)
1984 const char *p = string;
1987 while (*p && len-- > 3) {
1993 if ((*p >= '0' && *p <= '9') ||
1994 (*p >= 'A' && *p <= 'Z') ||
1995 (*p >= 'a' && *p <= 'z')) {
2000 *q++ = hex[(*p >> 4) & 0xf];
2001 *q++ = hex[*p & 0xf];
2011 LWS_VISIBLE LWS_EXTERN int
2012 lws_urldecode(char *string, const char *escaped, int len)
2017 while (*escaped && len) {
2020 if (*escaped == '%') {
2025 if (*escaped == '+') {
2031 *string++ = *escaped++;
2035 n = char_to_hex(*escaped);
2044 n = char_to_hex(*escaped);
2048 *string++ = sum | n;
2060 LWS_VISIBLE LWS_EXTERN int
2061 lws_finalize_startup(struct lws_context *context)
2063 struct lws_context_creation_info info;
2065 info.uid = context->uid;
2066 info.gid = context->gid;
2068 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2069 lws_plat_drop_app_privileges(&info);
2075 lws_snprintf(char *str, size_t size, const char *format, ...)
2083 va_start(ap, format);
2084 n = vsnprintf(str, size, format, ap);
2094 LWS_VISIBLE LWS_EXTERN int
2095 lws_is_cgi(struct lws *wsi) {
2106 urlencode(const char *in, int inlen, char *out, int outlen)
2108 char *start = out, *end = out + outlen;
2110 while (inlen-- && out < end - 4) {
2111 if ((*in >= 'A' && *in <= 'Z') ||
2112 (*in >= 'a' && *in <= 'z') ||
2113 (*in >= '0' && *in <= '9') ||
2127 *out++ = hex[(*in) >> 4];
2128 *out++ = hex[(*in++) & 15];
2139 lws_create_basic_wsi(struct lws_context *context, int tsi)
2141 struct lws *new_wsi;
2143 if ((unsigned int)context->pt[tsi].fds_count ==
2144 context->fd_limit_per_thread - 1) {
2145 lwsl_err("no space for new conn\n");
2149 new_wsi = lws_zalloc(sizeof(struct lws));
2150 if (new_wsi == NULL) {
2151 lwsl_err("Out of memory for new connection\n");
2156 new_wsi->context = context;
2157 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2158 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2160 /* initialize the instance struct */
2162 new_wsi->state = LWSS_CGI;
2163 new_wsi->mode = LWSCM_CGI;
2164 new_wsi->hdr_parsing_completed = 0;
2165 new_wsi->position_in_fds_table = -1;
2168 * these can only be set once the protocol is known
2169 * we set an unestablished connection's protocol pointer
2170 * to the start of the defauly vhost supported list, so it can look
2171 * for matching ones during the handshake
2173 new_wsi->protocol = context->vhost_list->protocols;
2174 new_wsi->user_space = NULL;
2175 new_wsi->ietf_spec_revision = 0;
2176 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2177 context->count_wsi_allocated++;
2182 LWS_VISIBLE LWS_EXTERN int
2183 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2184 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2186 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2187 char *env_array[30], cgi_path[400], e[1024], *p = e,
2188 *end = p + sizeof(e) - 1, tok[256], *t;
2189 struct lws_cgi *cgi;
2190 int n, m, i, uritok = -1;
2193 * give the master wsi a cgi struct
2196 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2198 lwsl_err("%s: OOM\n", __func__);
2203 cgi->wsi = wsi; /* set cgi's owning wsi */
2205 /* create pipes for [stdin|stdout] and [stderr] */
2207 for (n = 0; n < 3; n++)
2208 if (pipe(cgi->pipe_fds[n]) == -1)
2211 /* create cgi wsis for each stdin/out/err fd */
2213 for (n = 0; n < 3; n++) {
2214 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2215 if (!cgi->stdwsi[n])
2217 cgi->stdwsi[n]->cgi_channel = n;
2218 cgi->stdwsi[n]->vhost = wsi->vhost;
2220 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2221 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2223 /* read side is 0, stdin we want the write side, others read */
2224 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2225 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2226 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2231 for (n = 0; n < 3; n++) {
2232 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2233 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2235 cgi->stdwsi[n]->parent = wsi;
2236 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2237 wsi->child_list = cgi->stdwsi[n];
2240 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2241 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2242 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2244 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2245 cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2246 cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2247 cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2249 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2251 /* the cgi stdout is always sending us http1.x header data first */
2252 wsi->hdr_state = LCHS_HEADER;
2254 /* add us to the pt list of active cgis */
2255 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2256 cgi->cgi_list = pt->cgi_list;
2259 /* prepare his CGI env */
2263 if (lws_is_ssl(wsi))
2264 env_array[n++] = "HTTPS=ON";
2265 if (wsi->u.hdr.ah) {
2266 static const unsigned char meths[] = {
2269 WSI_TOKEN_OPTIONS_URI,
2271 WSI_TOKEN_PATCH_URI,
2272 WSI_TOKEN_DELETE_URI,
2274 static const char * const meth_names[] = {
2275 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2278 for (m = 0; m < ARRAY_SIZE(meths); m++)
2279 if (lws_hdr_total_length(wsi, meths[m]) >=
2280 script_uri_path_len) {
2288 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2289 lws_hdr_simple_ptr(wsi, uritok));
2290 cgi_path[sizeof(cgi_path) - 1] = '\0';
2291 env_array[n++] = cgi_path;
2294 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2299 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2300 /* dump the individual URI Arg parameters */
2303 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2304 WSI_TOKEN_HTTP_URI_ARGS, m);
2308 while (*t && *t != '=' && p < end - 4)
2312 i = urlencode(t, i- (t - tok), p, end - p);
2324 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2325 lws_hdr_simple_ptr(wsi, uritok) +
2326 script_uri_path_len);
2329 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2331 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2332 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2335 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2337 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2338 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2341 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2343 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2344 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2347 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2349 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2350 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2353 if (uritok == WSI_TOKEN_POST_URI) {
2354 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2356 p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2357 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2360 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2362 p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2363 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2368 p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2372 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2374 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2377 mp_cgienv = mp_cgienv->next;
2380 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2381 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2382 env_array[n] = NULL;
2385 for (m = 0; m < n; m++)
2386 lwsl_err(" %s\n", env_array[m]);
2390 * Actually having made the env, as a cgi we don't need the ah
2393 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
2394 lws_header_table_detach(wsi, 0);
2396 /* we are ready with the redirection pipes... run the thing */
2397 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2403 lwsl_err("fork failed, errno %d", errno);
2407 #if defined(__linux__)
2408 prctl(PR_SET_PDEATHSIG, SIGTERM);
2410 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2413 /* we are the parent process */
2414 wsi->context->count_cgi_spawned++;
2415 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2419 /* somewhere we can at least read things and enter it */
2421 lwsl_notice("%s: Failed to chdir\n", __func__);
2423 /* We are the forked process, redirect and kill inherited things.
2425 * Because of vfork(), we cannot do anything that changes pages in
2426 * the parent environment. Stuff that changes kernel state for the
2427 * process is OK. Stuff that happens after the execvpe() is OK.
2430 for (n = 0; n < 3; n++)
2431 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2432 lwsl_err("%s: stdin dup2 failed\n", __func__);
2436 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2437 for (m = 0; m < n; m++) {
2438 p = strchr(env_array[m], '=');
2440 setenv(env_array[m], p, 1);
2442 execvp(exec_array[0], (char * const *)&exec_array[0]);
2444 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2450 /* drop us from the pt cgi list */
2451 pt->cgi_list = cgi->cgi_list;
2454 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2456 for (n = 0; n < 3; n++)
2457 if (wsi->cgi->stdwsi[n])
2458 lws_free_wsi(cgi->stdwsi[n]);
2461 for (n = 0; n < 3; n++) {
2462 if (cgi->pipe_fds[n][0])
2463 close(cgi->pipe_fds[n][0]);
2464 if (cgi->pipe_fds[n][1])
2465 close(cgi->pipe_fds[n][1]);
2468 lws_free_set_NULL(wsi->cgi);
2470 lwsl_err("%s: failed\n", __func__);
2475 LWS_VISIBLE LWS_EXTERN int
2476 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2478 int n, m, match = 0, lp = 0;
2479 static const char * const content_length = "content-length: ";
2480 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2481 *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
2486 while (wsi->hdr_state != LHCS_PAYLOAD) {
2487 /* we have to separate header / finalize and
2488 * payload chunks, since they need to be
2489 * handled separately
2491 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2493 if (errno != EAGAIN) {
2494 lwsl_debug("%s: read says %d\n", __func__, n);
2501 lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
2502 switch (wsi->hdr_state) {
2504 if (!content_length[match] &&
2505 (c >= '0' && c <= '9') &&
2506 lp < sizeof(l) - 1) {
2509 wsi->cgi->content_length = atol(l);
2511 if (tolower(c) == content_length[match])
2516 /* some cgi only send us \x0a for EOL */
2518 wsi->hdr_state = LCHS_SINGLE_0A;
2523 wsi->hdr_state = LCHS_LF1;
2531 wsi->hdr_state = LCHS_CR2;
2534 /* we got \r[^\n]... it's unreasonable */
2535 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2541 wsi->hdr_state = LCHS_LF2;
2544 wsi->hdr_state = LCHS_HEADER;
2549 case LCHS_SINGLE_0A:
2552 lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
2553 wsi->hdr_state = LHCS_PAYLOAD;
2554 /* drop the \0xa ... finalize will add it if needed */
2555 if (lws_finalize_http_header(wsi,
2556 (unsigned char **)&p,
2557 (unsigned char *)end))
2562 /* we got \r\n\r[^\n]... it's unreasonable */
2564 /* we got \x0anext header, it's reasonable */
2566 wsi->hdr_state = LCHS_HEADER;
2573 /* ran out of input, ended the headers, or filled up the headers buf */
2574 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2576 m = lws_write(wsi, (unsigned char *)start,
2577 p - start, LWS_WRITE_HTTP_HEADERS);
2579 lwsl_debug("%s: write says %d\n", __func__, m);
2582 /* writeability becomes uncertain now we wrote
2583 * something, we must return to the event loop
2590 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2591 start, sizeof(buf) - LWS_PRE);
2593 if (n < 0 && errno != EAGAIN) {
2594 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2598 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2599 //lwsl_notice("write %d\n", m);
2601 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2604 wsi->cgi->content_length_seen += m;
2610 LWS_VISIBLE LWS_EXTERN int
2611 lws_cgi_kill(struct lws *wsi)
2613 struct lws_cgi_args args;
2616 lwsl_debug("%s: %p\n", __func__, wsi);
2621 if (wsi->cgi->pid > 0) {
2622 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2624 lwsl_debug("%s: PID %d reaped\n", __func__,
2628 /* kill the process group */
2629 n = kill(-wsi->cgi->pid, SIGTERM);
2630 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2631 wsi->cgi->pid, n, errno);
2634 * hum seen errno=3 when process is listed in ps,
2635 * it seems we don't always retain process grouping
2637 * Direct these fallback attempt to the exact child
2639 n = kill(wsi->cgi->pid, SIGTERM);
2641 n = kill(wsi->cgi->pid, SIGPIPE);
2643 n = kill(wsi->cgi->pid, SIGKILL);
2645 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2646 __func__, wsi->cgi->pid, errno);
2650 /* He could be unkillable because he's a zombie */
2653 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2655 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2657 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2659 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2665 args.stdwsi = &wsi->cgi->stdwsi[0];
2667 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2668 wsi->protocol->callback,
2669 wsi, LWS_CALLBACK_CGI_TERMINATED,
2671 (void *)&args, 0)) {
2673 if (!wsi->cgi->being_closed)
2674 lws_close_free_wsi(wsi, 0);
2681 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2683 struct lws_cgi **pcgi, *cgi = NULL;
2687 /* find finished guys but don't reap yet */
2688 n = waitpid(-1, &status, WNOHANG);
2691 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
2693 pcgi = &pt->cgi_list;
2695 /* check all the subprocesses on the cgi list */
2697 /* get the next one first as list may change */
2699 pcgi = &(*pcgi)->cgi_list;
2704 /* wait for stdout to be drained */
2705 if (cgi->content_length > cgi->content_length_seen)
2708 if (cgi->content_length) {
2709 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2710 __func__, cgi->wsi, cgi->content_length_seen);
2714 waitpid(n, &status, WNOHANG);
2716 * he's already terminated so no need for kill()
2717 * but we should do the terminated cgi callback
2718 * and close him if he's not already closing
2720 if (n == cgi->pid) {
2721 lwsl_debug("%s: found PID %d on cgi list\n",
2724 if (!cgi->content_length) {
2726 * well, if he sends chunked... give him 5s after the
2727 * cgi terminated to send buffered
2729 cgi->chunked_grace++;
2735 lws_cgi_kill(cgi->wsi);
2741 /* if not found on the cgi list, as he's one of ours, reap */
2743 lwsl_debug("%s: reading PID %d although no cgi match\n",
2745 waitpid(n, &status, WNOHANG);
2749 /* disable this to confirm timeout cgi cleanup flow */
2751 pcgi = &pt->cgi_list;
2753 /* check all the subprocesses on the cgi list */
2755 /* get the next one first as list may change */
2757 pcgi = &(*pcgi)->cgi_list;
2762 /* we deferred killing him after reaping his PID */
2763 if (cgi->chunked_grace) {
2764 cgi->chunked_grace++;
2765 if (cgi->chunked_grace < 5)
2770 /* wait for stdout to be drained */
2771 if (cgi->content_length > cgi->content_length_seen)
2774 if (cgi->content_length)
2775 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2776 __func__, cgi->wsi, cgi->content_length_seen);
2779 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2781 if (!cgi->content_length) {
2783 * well, if he sends chunked... give him 5s after the
2784 * cgi terminated to send buffered
2786 cgi->chunked_grace++;
2790 lwsl_debug("%s: found PID %d on cgi list\n",
2791 __func__, cgi->pid);
2794 lws_cgi_kill(cgi->wsi);
2801 /* general anti zombie defence */
2802 // n = waitpid(-1, &status, WNOHANG);
2804 // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
2810 #ifdef LWS_NO_EXTENSIONS
2812 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2813 const char *opt_name, const char *opt_val)
2819 #ifdef LWS_WITH_ACCESS_LOG
2821 lws_access_log(struct lws *wsi)
2823 char *p = wsi->access_log.user_agent, ass[512];
2826 if (!wsi->access_log_pending)
2829 if (!wsi->access_log.header_log)
2835 l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
2836 wsi->access_log.header_log,
2837 wsi->access_log.response, wsi->access_log.sent, p);
2839 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
2840 if (write(wsi->vhost->log_fd, ass, l) != l)
2841 lwsl_err("Failed to write log\n");
2843 lwsl_err("%s", ass);
2845 if (wsi->access_log.header_log) {
2846 lws_free(wsi->access_log.header_log);
2847 wsi->access_log.header_log = NULL;
2849 if (wsi->access_log.user_agent) {
2850 lws_free(wsi->access_log.user_agent);
2851 wsi->access_log.user_agent = NULL;
2853 wsi->access_log_pending = 0;
2860 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
2862 const struct lws_vhost *vh = ctx->vhost_list;
2866 cs->rx += vh->conn_stats.rx;
2867 cs->tx += vh->conn_stats.tx;
2868 cs->conn += vh->conn_stats.conn;
2869 cs->trans += vh->conn_stats.trans;
2870 cs->ws_upg += vh->conn_stats.ws_upg;
2871 cs->http2_upg += vh->conn_stats.http2_upg;
2872 cs->rejected += vh->conn_stats.rejected;
2874 vh = vh->vhost_next;
2878 #ifdef LWS_WITH_SERVER_STATUS
2881 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
2883 static const char * const prots[] = {
2892 char *orig = buf, *end = buf + len - 1, first = 1;
2898 buf += lws_snprintf(buf, end - buf,
2899 "{\n \"name\":\"%s\",\n"
2900 " \"port\":\"%d\",\n"
2901 " \"use_ssl\":\"%d\",\n"
2902 " \"sts\":\"%d\",\n"
2903 " \"rx\":\"%llu\",\n"
2904 " \"tx\":\"%llu\",\n"
2905 " \"conn\":\"%lu\",\n"
2906 " \"trans\":\"%lu\",\n"
2907 " \"ws_upg\":\"%lu\",\n"
2908 " \"rejected\":\"%lu\",\n"
2909 " \"http2_upg\":\"%lu\""
2911 vh->name, vh->listen_port,
2912 #ifdef LWS_OPENSSL_SUPPORT
2917 !!(vh->options & LWS_SERVER_OPTION_STS),
2918 vh->conn_stats.rx, vh->conn_stats.tx,
2919 vh->conn_stats.conn, vh->conn_stats.trans,
2920 vh->conn_stats.ws_upg,
2921 vh->conn_stats.rejected,
2922 vh->conn_stats.http2_upg
2925 if (vh->mount_list) {
2926 const struct lws_http_mount *m = vh->mount_list;
2928 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
2931 buf += lws_snprintf(buf, end - buf, ",");
2932 buf += lws_snprintf(buf, end - buf,
2933 "\n {\n \"mountpoint\":\"%s\",\n"
2934 " \"origin\":\"%s%s\",\n"
2935 " \"cache_max_age\":\"%d\",\n"
2936 " \"cache_reuse\":\"%d\",\n"
2937 " \"cache_revalidate\":\"%d\",\n"
2938 " \"cache_intermediaries\":\"%d\"\n"
2941 prots[m->origin_protocol],
2945 m->cache_revalidate,
2946 m->cache_intermediaries);
2948 buf += lws_snprintf(buf, end - buf,
2949 ",\n \"default\":\"%s\"",
2951 buf += lws_snprintf(buf, end - buf, "\n }");
2955 buf += lws_snprintf(buf, end - buf, "\n ]");
2958 if (vh->protocols) {
2962 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
2963 while (n < vh->count_protocols) {
2965 buf += lws_snprintf(buf, end - buf, ",");
2966 buf += lws_snprintf(buf, end - buf,
2968 " \"status\":\"ok\"\n }\n }"
2970 vh->protocols[n].name);
2974 buf += lws_snprintf(buf, end - buf, "\n ]");
2977 buf += lws_snprintf(buf, end - buf, "\n}");
2983 LWS_EXTERN LWS_VISIBLE int
2984 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
2987 char *orig = buf, *end = buf + len - 1, first = 1;
2988 const struct lws_vhost *vh = context->vhost_list;
2989 const struct lws_context_per_thread *pt;
2990 time_t t = time(NULL);
2991 int n, listening = 0, cgi_count = 0;
2992 struct lws_conn_stats cs;
2995 struct lws_cgi * const *pcgi;
2998 #ifdef LWS_USE_LIBUV
3002 buf += lws_snprintf(buf, end - buf, "{ "
3003 "\"version\":\"%s\",\n"
3004 "\"uptime\":\"%ld\",\n",
3005 lws_get_library_version(),
3008 #ifdef LWS_HAVE_GETLOADAVG
3013 m = getloadavg(d, 3);
3014 for (n = 0; n < m; n++) {
3015 buf += lws_snprintf(buf, end - buf,
3016 "\"l%d\":\"%.2f\",\n",
3022 buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
3024 buf += lws_snprintf(buf, end - buf, "{ "
3025 "\"context_uptime\":\"%ld\",\n"
3026 "\"cgi_spawned\":\"%d\",\n"
3027 "\"pt_fd_max\":\"%d\",\n"
3028 "\"ah_pool_max\":\"%d\",\n"
3029 "\"deprecated\":\"%d\",\n"
3030 "\"wsi_alive\":\"%d\",\n",
3031 (unsigned long)(t - context->time_up),
3032 context->count_cgi_spawned,
3033 context->fd_limit_per_thread,
3034 context->max_http_header_pool,
3035 context->deprecated,
3036 context->count_wsi_allocated);
3038 buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
3039 for (n = 0; n < context->count_threads; n++) {
3040 pt = &context->pt[n];
3042 buf += lws_snprintf(buf, end - buf, ",");
3043 buf += lws_snprintf(buf, end - buf,
3045 " \"fds_count\":\"%d\",\n"
3046 " \"ah_pool_inuse\":\"%d\",\n"
3047 " \"ah_wait_list\":\"%d\"\n"
3050 pt->ah_count_in_use,
3051 pt->ah_wait_list_length);
3054 buf += lws_snprintf(buf, end - buf, "]");
3056 buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3059 vh = context->vhost_list;
3061 cs = context->conn_stats;
3062 lws_sum_stats(context, &cs);
3069 buf += lws_json_dump_vhost(vh, buf, end - buf);
3074 vh = vh->vhost_next;
3077 buf += lws_snprintf(buf, end - buf,
3078 "],\n\"listen_wsi\":\"%d\",\n"
3079 " \"rx\":\"%llu\",\n"
3080 " \"tx\":\"%llu\",\n"
3081 " \"conn\":\"%lu\",\n"
3082 " \"trans\":\"%lu\",\n"
3083 " \"ws_upg\":\"%lu\",\n"
3084 " \"rejected\":\"%lu\",\n"
3085 " \"http2_upg\":\"%lu\"",
3087 cs.rx, cs.tx, cs.conn, cs.trans,
3088 cs.ws_upg, cs.rejected, cs.http2_upg);
3091 for (n = 0; n < context->count_threads; n++) {
3092 pt = &context->pt[n];
3093 pcgi = &pt->cgi_list;
3096 pcgi = &(*pcgi)->cgi_list;
3102 buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3105 buf += lws_snprintf(buf, end - buf, "}");
3108 buf += lws_snprintf(buf, end - buf, "]}\n ");
3115 #if defined(LWS_WITH_STATS)
3117 LWS_VISIBLE LWS_EXTERN uint64_t
3118 lws_stats_get(struct lws_context *context, int index)
3120 if (index >= LWSSTATS_SIZE)
3123 return context->lws_stats[index];
3126 LWS_VISIBLE LWS_EXTERN void
3127 lws_stats_log_dump(struct lws_context *context)
3129 struct lws_vhost *v = context->vhost_list;
3132 if (!context->updated)
3135 context->updated = 0;
3138 lwsl_notice("LWS internal statistics dump ----->\n");
3139 lwsl_notice("LWSSTATS_C_CONNECTIONS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_CONNECTIONS));
3140 lwsl_notice("LWSSTATS_C_API_CLOSE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_CLOSE));
3141 lwsl_notice("LWSSTATS_C_API_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_READ));
3142 lwsl_notice("LWSSTATS_C_API_LWS_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_LWS_WRITE));
3143 lwsl_notice("LWSSTATS_C_API_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_WRITE));
3144 lwsl_notice("LWSSTATS_C_WRITE_PARTIALS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITE_PARTIALS));
3145 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_REQ));
3146 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_EFF_REQ));
3147 lwsl_notice("LWSSTATS_C_WRITEABLE_CB: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB));
3148 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_FAILED));
3149 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED));
3150 lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX));
3152 lwsl_notice("LWSSTATS_C_TIMEOUTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_TIMEOUTS));
3153 lwsl_notice("LWSSTATS_C_SERVICE_ENTRY: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SERVICE_ENTRY));
3154 lwsl_notice("LWSSTATS_B_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ));
3155 lwsl_notice("LWSSTATS_B_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE));
3156 lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS));
3157 lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000);
3158 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED))
3159 lwsl_notice(" Avg accept delay: %8llums\n",
3160 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) /
3161 lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000);
3162 lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / 1000);
3163 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX))
3164 lwsl_notice(" Avg accept-rx delay: %8llums\n",
3165 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) /
3166 lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000);
3168 lwsl_notice("LWSSTATS_MS_WRITABLE_DELAY: %8lluus\n",
3169 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY));
3170 lwsl_notice("LWSSTATS_MS_WORST_WRITABLE_DELAY: %8lluus\n",
3171 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WORST_WRITABLE_DELAY));
3172 if (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))
3173 lwsl_notice(" Avg writable delay: %8lluus\n",
3174 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY) /
3175 lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)));
3176 lwsl_notice("Simultaneous SSL restriction: %8d/%d/%d\n", context->simultaneous_ssl,
3177 context->simultaneous_ssl_restriction, context->ssl_gate_accepts);
3179 lwsl_notice("Live wsi: %8d\n", context->count_wsi_allocated);
3181 #if defined(LWS_WITH_STATS)
3182 context->updated = 1;
3186 if (v->use_ssl && v->lserv_wsi) {
3187 struct lws_context_per_thread *pt = &context->pt[(int)v->lserv_wsi->tsi];
3188 struct lws_pollfd *pfd;
3190 pfd = &pt->fds[v->lserv_wsi->position_in_fds_table];
3192 lwsl_notice(" Listen port %d actual POLLIN: %d\n",
3193 v->listen_port, (int)pfd->events & LWS_POLLIN);
3199 for (n = 0; n < context->count_threads; n++) {
3200 struct lws_context_per_thread *pt = &context->pt[n];
3204 lwsl_notice("PT %d\n", n + 1);
3208 lwsl_notice(" AH in use / max: %d / %d\n",
3209 pt->ah_count_in_use,
3210 context->max_http_header_pool);
3212 wl = pt->ah_wait_list;
3215 wl = wl->u.hdr.ah_wait_list;
3218 lwsl_notice(" AH wait list count / actual: %d / %d\n",
3219 pt->ah_wait_list_length, m);
3228 lws_stats_atomic_bump(struct lws_context * context,
3229 struct lws_context_per_thread *pt, int index, uint64_t bump)
3232 context->lws_stats[index] += bump;
3233 if (index != LWSSTATS_C_SERVICE_ENTRY)
3234 context->updated = 1;
3239 lws_stats_atomic_max(struct lws_context * context,
3240 struct lws_context_per_thread *pt, int index, uint64_t val)
3243 if (val > context->lws_stats[index]) {
3244 context->lws_stats[index] = val;
3245 context->updated = 1;