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 #if defined(LWS_WITH_SOCKS5)
1330 lws_set_socks(struct lws_vhost *vhost, const char *socks)
1332 #if !defined(LWS_WITH_ESP8266)
1333 char *p_at, *p_colon;
1340 vhost->socks_user[0] = '\0';
1341 vhost->socks_password[0] = '\0';
1343 p_at = strchr(socks, '@');
1344 if (p_at) { /* auth is around */
1345 if ((unsigned int)(p_at - socks) > (sizeof(user)
1346 + sizeof(password) - 2)) {
1347 lwsl_err("Socks auth too long\n");
1351 p_colon = strchr(socks, ':');
1353 if ((unsigned int)(p_colon - socks) > (sizeof(user)
1355 lwsl_err("Socks user too long\n");
1358 if ((unsigned int)(p_at - p_colon) > (sizeof(password)
1360 lwsl_err("Socks password too long\n");
1364 strncpy(vhost->socks_user, socks, p_colon - socks);
1365 strncpy(vhost->socks_password, p_colon + 1,
1366 p_at - (p_colon + 1));
1368 lwsl_info(" Socks auth, user: %s, password: %s\n",
1369 vhost->socks_user, vhost->socks_password );
1374 strncpy(vhost->socks_proxy_address, socks,
1375 sizeof(vhost->socks_proxy_address) - 1);
1376 vhost->socks_proxy_address[sizeof(vhost->socks_proxy_address) - 1]
1379 p_colon = strchr(vhost->socks_proxy_address, ':');
1380 if (!p_colon && !vhost->socks_proxy_port) {
1381 lwsl_err("socks_proxy needs to be address:port\n");
1386 vhost->socks_proxy_port = atoi(p_colon + 1);
1390 lwsl_info(" Socks %s:%u\n", vhost->socks_proxy_address,
1391 vhost->socks_proxy_port);
1401 LWS_VISIBLE const struct lws_protocols *
1402 lws_get_protocol(struct lws *wsi)
1404 return wsi->protocol;
1408 lws_is_final_fragment(struct lws *wsi)
1410 lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1411 wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1412 (long)wsi->u.ws.rx_draining_ext);
1413 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1416 LWS_VISIBLE unsigned char
1417 lws_get_reserved_bits(struct lws *wsi)
1419 return wsi->u.ws.rsv;
1423 lws_ensure_user_space(struct lws *wsi)
1425 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1429 /* allocate the per-connection user memory (if any) */
1431 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1432 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1433 if (wsi->user_space == NULL) {
1434 lwsl_err("Out of memory for conn user space\n");
1438 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1439 __func__, wsi, (long)wsi->protocol->per_session_data_size,
1445 lwsl_timestamp(int level, char *p, int len)
1447 #ifndef LWS_PLAT_OPTEE
1448 time_t o_now = time(NULL);
1449 unsigned long long now;
1450 struct tm *ptm = NULL;
1458 ptm = localtime(&o_now);
1460 if (localtime_r(&o_now, &tm))
1465 for (n = 0; n < LLL_COUNT; n++) {
1466 if (level != (1 << n))
1468 now = time_in_microseconds() / 100;
1470 n = lws_snprintf(p, len,
1471 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1472 ptm->tm_year + 1900,
1478 (int)(now % 10000), log_level_names[n]);
1480 n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1481 (unsigned long long) now / 10000,
1482 (int)(now % 10000), log_level_names[n]);
1489 #ifndef LWS_PLAT_OPTEE
1490 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1492 #if !defined(LWS_WITH_ESP8266)
1495 lwsl_timestamp(level, buf, sizeof(buf));
1496 fprintf(stderr, "%s%s", buf, line);
1501 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1503 #if defined(LWS_WITH_ESP8266)
1510 if (!(log_level & filter))
1513 n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1515 #if defined(LWS_WITH_ESP8266)
1516 buf[sizeof(buf) - 1] = '\0';
1518 /* vnsprintf returns what it would have written, even if truncated */
1519 if (n > sizeof(buf) - 1)
1520 n = sizeof(buf) - 1;
1525 lwsl_emit(filter, buf);
1528 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1532 va_start(ap, format);
1533 _lws_logv(filter, format, ap);
1537 LWS_VISIBLE void lws_set_log_level(int level,
1538 void (*func)(int level, const char *line))
1545 LWS_VISIBLE int lwsl_visible(int level)
1547 return log_level & level;
1551 lws_is_ssl(struct lws *wsi)
1553 #ifdef LWS_OPENSSL_SUPPORT
1554 return wsi->use_ssl;
1561 #ifdef LWS_OPENSSL_SUPPORT
1563 lws_get_ssl(struct lws *wsi)
1570 lws_partial_buffered(struct lws *wsi)
1572 return !!wsi->trunc_len;
1575 void lws_set_protocol_write_pending(struct lws *wsi,
1576 enum lws_pending_protocol_send pend)
1578 lwsl_info("setting pps %d\n", pend);
1581 lwsl_err("pps overwrite\n");
1583 lws_rx_flow_control(wsi, 0);
1584 lws_callback_on_writable(wsi);
1588 lws_get_peer_write_allowance(struct lws *wsi)
1590 #ifdef LWS_USE_HTTP2
1591 /* only if we are using HTTP2 on this connection */
1592 if (wsi->mode != LWSCM_HTTP2_SERVING)
1594 /* user is only interested in how much he can send, or that he can't */
1595 if (wsi->u.http2.tx_credit <= 0)
1598 return wsi->u.http2.tx_credit;
1606 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1608 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1609 memset(&wsi->u, 0, sizeof(wsi->u));
1613 LWS_VISIBLE struct lws_plat_file_ops *
1614 lws_get_fops(struct lws_context *context)
1616 return (struct lws_plat_file_ops *)context->fops;
1619 LWS_VISIBLE LWS_EXTERN struct lws_context *
1620 lws_get_context(const struct lws *wsi)
1622 return wsi->context;
1625 LWS_VISIBLE LWS_EXTERN int
1626 lws_get_count_threads(struct lws_context *context)
1628 return context->count_threads;
1631 LWS_VISIBLE LWS_EXTERN void *
1632 lws_wsi_user(struct lws *wsi)
1634 return wsi->user_space;
1637 LWS_VISIBLE LWS_EXTERN void
1638 lws_set_wsi_user(struct lws *wsi, void *data)
1640 if (wsi->user_space_externally_allocated)
1641 wsi->user_space = data;
1643 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1647 LWS_VISIBLE LWS_EXTERN struct lws *
1648 lws_get_parent(const struct lws *wsi)
1653 LWS_VISIBLE LWS_EXTERN struct lws *
1654 lws_get_child(const struct lws *wsi)
1656 return wsi->child_list;
1659 LWS_VISIBLE LWS_EXTERN void
1660 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1661 unsigned char *buf, size_t len)
1663 unsigned char *p, *start;
1664 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1666 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1668 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1670 *p++ = (((int)status) >> 8) & 0xff;
1671 *p++ = ((int)status) & 0xff;
1674 while (len-- && p < start + budget)
1677 wsi->u.ws.close_in_ping_buffer_len = p - start;
1681 _lws_rx_flow_control(struct lws *wsi)
1683 struct lws *wsic = wsi->child_list;
1685 /* if he has children, do those if they were changed */
1687 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1688 _lws_rx_flow_control(wsic);
1690 wsic = wsic->sibling_list;
1693 /* there is no pending change */
1694 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1695 // lwsl_debug("%s: no pending change\n", __func__);
1699 /* stuff is still buffered, not ready to really accept new input */
1700 if (wsi->rxflow_buffer) {
1701 /* get ourselves called back to deal with stashed buffer */
1702 lws_callback_on_writable(wsi);
1706 /* pending is cleared, we can change rxflow state */
1708 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1710 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1711 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1713 /* adjust the pollfd for this wsi */
1715 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1716 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1717 lwsl_info("%s: fail\n", __func__);
1721 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1728 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1730 static const unsigned char e0f4[] = {
1731 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1732 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1733 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1734 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1735 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1736 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1737 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1738 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1739 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1740 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1741 0x80 | ((4 - 1) << 2) | 1, /* ea */
1742 0x80 | ((4 - 1) << 2) | 1, /* eb */
1743 0x80 | ((4 - 1) << 2) | 1, /* ec */
1744 0x80 | ((2 - 1) << 2) | 1, /* ed */
1745 0x80 | ((4 - 1) << 2) | 1, /* ee */
1746 0x80 | ((4 - 1) << 2) | 1, /* ef */
1747 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1748 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1749 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1750 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1751 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1754 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1755 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1757 unsigned char s = *state;
1760 unsigned char c = *buf++;
1764 if (c < 0xc2 || c > 0xf4)
1767 s = 0x80 | ((4 - 1) << 2);
1772 if (c < (s & 0xf0) ||
1773 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1775 s = e0f4[21 + (s & 3)];
1784 LWS_VISIBLE LWS_EXTERN int
1785 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1789 static const char *slash = "/";
1791 /* cut up the location into address, port and path */
1793 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1804 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1806 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1812 while (*p && *p != ']')
1819 while (*p && *p != ':' && *p != '/')
1825 while (*p && *p != '/')
1838 #ifdef LWS_NO_EXTENSIONS
1840 /* we need to provide dummy callbacks for internal exts
1841 * so user code runs when faced with a lib compiled with
1842 * extensions disabled.
1846 lws_extension_callback_pm_deflate(struct lws_context *context,
1847 const struct lws_extension *ext,
1849 enum lws_extension_callback_reasons reason,
1850 void *user, void *in, size_t len)
1865 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1869 #ifdef LWS_USE_UNIX_SOCK
1870 struct sockaddr_un serv_unix;
1873 struct sockaddr_in6 serv_addr6;
1875 struct sockaddr_in serv_addr4;
1876 #ifndef LWS_PLAT_OPTEE
1877 socklen_t len = sizeof(struct sockaddr);
1880 struct sockaddr_in sin;
1883 #ifdef LWS_USE_UNIX_SOCK
1884 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1885 v = (struct sockaddr *)&serv_unix;
1886 n = sizeof(struct sockaddr_un);
1887 bzero((char *) &serv_unix, sizeof(serv_unix));
1888 serv_unix.sun_family = AF_UNIX;
1889 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1890 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1894 strcpy(serv_unix.sun_path, iface);
1895 if (serv_unix.sun_path[0] == '@')
1896 serv_unix.sun_path[0] = '\0';
1900 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1901 if (LWS_IPV6_ENABLED(vhost)) {
1902 v = (struct sockaddr *)&serv_addr6;
1903 n = sizeof(struct sockaddr_in6);
1904 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1906 interface_to_sa(vhost, iface,
1907 (struct sockaddr_in *)v, n) < 0) {
1908 lwsl_err("Unable to find interface %s\n", iface);
1913 struct ifaddrs *addrs, *addr;
1914 char ip[NI_MAXHOST];
1918 for (addr = addrs; addr; addr = addr->ifa_next) {
1919 if (!addr->ifa_addr ||
1920 addr->ifa_addr->sa_family != AF_INET6)
1923 getnameinfo(addr->ifa_addr,
1924 sizeof(struct sockaddr_in6),
1926 NULL, 0, NI_NUMERICHOST);
1930 if (ip[i++] == '%') {
1935 if (!strcmp(ip, iface)) {
1936 serv_addr6.sin6_scope_id =
1937 if_nametoindex(addr->ifa_name);
1944 serv_addr6.sin6_family = AF_INET6;
1945 serv_addr6.sin6_port = htons(port);
1949 v = (struct sockaddr *)&serv_addr4;
1950 n = sizeof(serv_addr4);
1951 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1952 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1953 serv_addr4.sin_family = AF_INET;
1954 #if !defined(LWS_WITH_ESP32)
1957 interface_to_sa(vhost, iface,
1958 (struct sockaddr_in *)v, n) < 0) {
1959 lwsl_err("Unable to find interface %s\n", iface);
1963 serv_addr4.sin_port = htons(port);
1966 n = bind(sockfd, v, n);
1967 #ifdef LWS_USE_UNIX_SOCK
1968 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
1969 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1970 sockfd, iface, n, LWS_ERRNO);
1975 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1976 sockfd, port, n, LWS_ERRNO);
1980 #ifndef LWS_PLAT_OPTEE
1981 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1982 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1985 port = ntohs(sin.sin_port);
1992 lws_restart_ws_ping_pong_timer(struct lws *wsi)
1994 if (!wsi->context->ws_ping_pong_interval)
1996 if (wsi->state != LWSS_ESTABLISHED)
1999 wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
2000 wsi->context->ws_ping_pong_interval;
2003 static const char *hex = "0123456789ABCDEF";
2005 LWS_VISIBLE LWS_EXTERN const char *
2006 lws_sql_purify(char *escaped, const char *string, int len)
2008 const char *p = string;
2011 while (*p && len-- > 2) {
2025 LWS_VISIBLE LWS_EXTERN const char *
2026 lws_json_purify(char *escaped, const char *string, int len)
2028 const char *p = string;
2036 while (*p && len-- > 6) {
2037 if (*p == '\"' || *p == '\\' || *p < 0x20) {
2042 *q++ = hex[((*p) >> 4) & 15];
2043 *q++ = hex[(*p) & 15];
2054 LWS_VISIBLE LWS_EXTERN const char *
2055 lws_urlencode(char *escaped, const char *string, int len)
2057 const char *p = string;
2060 while (*p && len-- > 3) {
2066 if ((*p >= '0' && *p <= '9') ||
2067 (*p >= 'A' && *p <= 'Z') ||
2068 (*p >= 'a' && *p <= 'z')) {
2073 *q++ = hex[(*p >> 4) & 0xf];
2074 *q++ = hex[*p & 0xf];
2084 LWS_VISIBLE LWS_EXTERN int
2085 lws_urldecode(char *string, const char *escaped, int len)
2090 while (*escaped && len) {
2093 if (*escaped == '%') {
2098 if (*escaped == '+') {
2104 *string++ = *escaped++;
2108 n = char_to_hex(*escaped);
2117 n = char_to_hex(*escaped);
2121 *string++ = sum | n;
2133 LWS_VISIBLE LWS_EXTERN int
2134 lws_finalize_startup(struct lws_context *context)
2136 struct lws_context_creation_info info;
2138 info.uid = context->uid;
2139 info.gid = context->gid;
2141 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2142 lws_plat_drop_app_privileges(&info);
2148 lws_snprintf(char *str, size_t size, const char *format, ...)
2156 va_start(ap, format);
2157 n = vsnprintf(str, size, format, ap);
2167 LWS_VISIBLE LWS_EXTERN int
2168 lws_is_cgi(struct lws *wsi) {
2179 urlencode(const char *in, int inlen, char *out, int outlen)
2181 char *start = out, *end = out + outlen;
2183 while (inlen-- && out < end - 4) {
2184 if ((*in >= 'A' && *in <= 'Z') ||
2185 (*in >= 'a' && *in <= 'z') ||
2186 (*in >= '0' && *in <= '9') ||
2200 *out++ = hex[(*in) >> 4];
2201 *out++ = hex[(*in++) & 15];
2212 lws_create_basic_wsi(struct lws_context *context, int tsi)
2214 struct lws *new_wsi;
2216 if ((unsigned int)context->pt[tsi].fds_count ==
2217 context->fd_limit_per_thread - 1) {
2218 lwsl_err("no space for new conn\n");
2222 new_wsi = lws_zalloc(sizeof(struct lws));
2223 if (new_wsi == NULL) {
2224 lwsl_err("Out of memory for new connection\n");
2229 new_wsi->context = context;
2230 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2231 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2233 /* initialize the instance struct */
2235 new_wsi->state = LWSS_CGI;
2236 new_wsi->mode = LWSCM_CGI;
2237 new_wsi->hdr_parsing_completed = 0;
2238 new_wsi->position_in_fds_table = -1;
2241 * these can only be set once the protocol is known
2242 * we set an unestablished connection's protocol pointer
2243 * to the start of the defauly vhost supported list, so it can look
2244 * for matching ones during the handshake
2246 new_wsi->protocol = context->vhost_list->protocols;
2247 new_wsi->user_space = NULL;
2248 new_wsi->ietf_spec_revision = 0;
2249 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2250 context->count_wsi_allocated++;
2255 LWS_VISIBLE LWS_EXTERN int
2256 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2257 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2259 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2260 char *env_array[30], cgi_path[400], e[1024], *p = e,
2261 *end = p + sizeof(e) - 1, tok[256], *t;
2262 struct lws_cgi *cgi;
2263 int n, m, i, uritok = -1;
2266 * give the master wsi a cgi struct
2269 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2271 lwsl_err("%s: OOM\n", __func__);
2276 cgi->wsi = wsi; /* set cgi's owning wsi */
2278 /* create pipes for [stdin|stdout] and [stderr] */
2280 for (n = 0; n < 3; n++)
2281 if (pipe(cgi->pipe_fds[n]) == -1)
2284 /* create cgi wsis for each stdin/out/err fd */
2286 for (n = 0; n < 3; n++) {
2287 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2288 if (!cgi->stdwsi[n])
2290 cgi->stdwsi[n]->cgi_channel = n;
2291 cgi->stdwsi[n]->vhost = wsi->vhost;
2293 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2294 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2296 /* read side is 0, stdin we want the write side, others read */
2297 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2298 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2299 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2304 for (n = 0; n < 3; n++) {
2305 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2306 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2308 cgi->stdwsi[n]->parent = wsi;
2309 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2310 wsi->child_list = cgi->stdwsi[n];
2313 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2314 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2315 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2317 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2318 cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2319 cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2320 cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2322 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2324 /* the cgi stdout is always sending us http1.x header data first */
2325 wsi->hdr_state = LCHS_HEADER;
2327 /* add us to the pt list of active cgis */
2328 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2329 cgi->cgi_list = pt->cgi_list;
2332 /* prepare his CGI env */
2336 if (lws_is_ssl(wsi))
2337 env_array[n++] = "HTTPS=ON";
2338 if (wsi->u.hdr.ah) {
2339 static const unsigned char meths[] = {
2342 WSI_TOKEN_OPTIONS_URI,
2344 WSI_TOKEN_PATCH_URI,
2345 WSI_TOKEN_DELETE_URI,
2347 static const char * const meth_names[] = {
2348 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2351 for (m = 0; m < ARRAY_SIZE(meths); m++)
2352 if (lws_hdr_total_length(wsi, meths[m]) >=
2353 script_uri_path_len) {
2361 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2362 lws_hdr_simple_ptr(wsi, uritok));
2363 cgi_path[sizeof(cgi_path) - 1] = '\0';
2364 env_array[n++] = cgi_path;
2367 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2372 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2373 /* dump the individual URI Arg parameters */
2376 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2377 WSI_TOKEN_HTTP_URI_ARGS, m);
2381 while (*t && *t != '=' && p < end - 4)
2385 i = urlencode(t, i- (t - tok), p, end - p);
2397 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2398 lws_hdr_simple_ptr(wsi, uritok) +
2399 script_uri_path_len);
2402 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2404 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2405 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2408 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2410 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2411 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2414 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2416 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2417 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2420 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2422 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2423 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2426 if (uritok == WSI_TOKEN_POST_URI) {
2427 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2429 p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2430 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2433 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2435 p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2436 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2441 p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2445 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2447 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2450 mp_cgienv = mp_cgienv->next;
2453 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2454 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2455 env_array[n] = NULL;
2458 for (m = 0; m < n; m++)
2459 lwsl_err(" %s\n", env_array[m]);
2463 * Actually having made the env, as a cgi we don't need the ah
2466 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
2467 lws_header_table_detach(wsi, 0);
2469 /* we are ready with the redirection pipes... run the thing */
2470 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2476 lwsl_err("fork failed, errno %d", errno);
2480 #if defined(__linux__)
2481 prctl(PR_SET_PDEATHSIG, SIGTERM);
2483 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2486 /* we are the parent process */
2487 wsi->context->count_cgi_spawned++;
2488 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2492 /* somewhere we can at least read things and enter it */
2494 lwsl_notice("%s: Failed to chdir\n", __func__);
2496 /* We are the forked process, redirect and kill inherited things.
2498 * Because of vfork(), we cannot do anything that changes pages in
2499 * the parent environment. Stuff that changes kernel state for the
2500 * process is OK. Stuff that happens after the execvpe() is OK.
2503 for (n = 0; n < 3; n++)
2504 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2505 lwsl_err("%s: stdin dup2 failed\n", __func__);
2509 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2510 for (m = 0; m < n; m++) {
2511 p = strchr(env_array[m], '=');
2513 setenv(env_array[m], p, 1);
2515 execvp(exec_array[0], (char * const *)&exec_array[0]);
2517 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2523 /* drop us from the pt cgi list */
2524 pt->cgi_list = cgi->cgi_list;
2527 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2529 for (n = 0; n < 3; n++)
2530 if (wsi->cgi->stdwsi[n])
2531 lws_free_wsi(cgi->stdwsi[n]);
2534 for (n = 0; n < 3; n++) {
2535 if (cgi->pipe_fds[n][0])
2536 close(cgi->pipe_fds[n][0]);
2537 if (cgi->pipe_fds[n][1])
2538 close(cgi->pipe_fds[n][1]);
2541 lws_free_set_NULL(wsi->cgi);
2543 lwsl_err("%s: failed\n", __func__);
2548 LWS_VISIBLE LWS_EXTERN int
2549 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2551 int n, m, match = 0, lp = 0;
2552 static const char * const content_length = "content-length: ";
2553 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2554 *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
2559 while (wsi->hdr_state != LHCS_PAYLOAD) {
2560 /* we have to separate header / finalize and
2561 * payload chunks, since they need to be
2562 * handled separately
2564 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2566 if (errno != EAGAIN) {
2567 lwsl_debug("%s: read says %d\n", __func__, n);
2574 lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
2575 switch (wsi->hdr_state) {
2577 if (!content_length[match] &&
2578 (c >= '0' && c <= '9') &&
2579 lp < sizeof(l) - 1) {
2582 wsi->cgi->content_length = atol(l);
2584 if (tolower(c) == content_length[match])
2589 /* some cgi only send us \x0a for EOL */
2591 wsi->hdr_state = LCHS_SINGLE_0A;
2596 wsi->hdr_state = LCHS_LF1;
2604 wsi->hdr_state = LCHS_CR2;
2607 /* we got \r[^\n]... it's unreasonable */
2608 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2614 wsi->hdr_state = LCHS_LF2;
2617 wsi->hdr_state = LCHS_HEADER;
2622 case LCHS_SINGLE_0A:
2625 lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
2626 wsi->hdr_state = LHCS_PAYLOAD;
2627 /* drop the \0xa ... finalize will add it if needed */
2628 if (lws_finalize_http_header(wsi,
2629 (unsigned char **)&p,
2630 (unsigned char *)end))
2635 /* we got \r\n\r[^\n]... it's unreasonable */
2637 /* we got \x0anext header, it's reasonable */
2639 wsi->hdr_state = LCHS_HEADER;
2646 /* ran out of input, ended the headers, or filled up the headers buf */
2647 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2649 m = lws_write(wsi, (unsigned char *)start,
2650 p - start, LWS_WRITE_HTTP_HEADERS);
2652 lwsl_debug("%s: write says %d\n", __func__, m);
2655 /* writeability becomes uncertain now we wrote
2656 * something, we must return to the event loop
2663 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2664 start, sizeof(buf) - LWS_PRE);
2666 if (n < 0 && errno != EAGAIN) {
2667 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2671 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2672 //lwsl_notice("write %d\n", m);
2674 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2677 wsi->cgi->content_length_seen += m;
2683 LWS_VISIBLE LWS_EXTERN int
2684 lws_cgi_kill(struct lws *wsi)
2686 struct lws_cgi_args args;
2689 lwsl_debug("%s: %p\n", __func__, wsi);
2694 if (wsi->cgi->pid > 0) {
2695 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2697 lwsl_debug("%s: PID %d reaped\n", __func__,
2701 /* kill the process group */
2702 n = kill(-wsi->cgi->pid, SIGTERM);
2703 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2704 wsi->cgi->pid, n, errno);
2707 * hum seen errno=3 when process is listed in ps,
2708 * it seems we don't always retain process grouping
2710 * Direct these fallback attempt to the exact child
2712 n = kill(wsi->cgi->pid, SIGTERM);
2714 n = kill(wsi->cgi->pid, SIGPIPE);
2716 n = kill(wsi->cgi->pid, SIGKILL);
2718 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2719 __func__, wsi->cgi->pid, errno);
2723 /* He could be unkillable because he's a zombie */
2726 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2728 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2730 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2732 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2738 args.stdwsi = &wsi->cgi->stdwsi[0];
2740 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2741 wsi->protocol->callback,
2742 wsi, LWS_CALLBACK_CGI_TERMINATED,
2744 (void *)&args, 0)) {
2746 if (!wsi->cgi->being_closed)
2747 lws_close_free_wsi(wsi, 0);
2754 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2756 struct lws_cgi **pcgi, *cgi = NULL;
2760 /* find finished guys but don't reap yet */
2761 n = waitpid(-1, &status, WNOHANG);
2764 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
2766 pcgi = &pt->cgi_list;
2768 /* check all the subprocesses on the cgi list */
2770 /* get the next one first as list may change */
2772 pcgi = &(*pcgi)->cgi_list;
2777 /* wait for stdout to be drained */
2778 if (cgi->content_length > cgi->content_length_seen)
2781 if (cgi->content_length) {
2782 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2783 __func__, cgi->wsi, cgi->content_length_seen);
2787 waitpid(n, &status, WNOHANG);
2789 * he's already terminated so no need for kill()
2790 * but we should do the terminated cgi callback
2791 * and close him if he's not already closing
2793 if (n == cgi->pid) {
2794 lwsl_debug("%s: found PID %d on cgi list\n",
2797 if (!cgi->content_length) {
2799 * well, if he sends chunked... give him 5s after the
2800 * cgi terminated to send buffered
2802 cgi->chunked_grace++;
2808 lws_cgi_kill(cgi->wsi);
2814 /* if not found on the cgi list, as he's one of ours, reap */
2816 lwsl_debug("%s: reading PID %d although no cgi match\n",
2818 waitpid(n, &status, WNOHANG);
2822 /* disable this to confirm timeout cgi cleanup flow */
2824 pcgi = &pt->cgi_list;
2826 /* check all the subprocesses on the cgi list */
2828 /* get the next one first as list may change */
2830 pcgi = &(*pcgi)->cgi_list;
2835 /* we deferred killing him after reaping his PID */
2836 if (cgi->chunked_grace) {
2837 cgi->chunked_grace++;
2838 if (cgi->chunked_grace < 5)
2843 /* wait for stdout to be drained */
2844 if (cgi->content_length > cgi->content_length_seen)
2847 if (cgi->content_length)
2848 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2849 __func__, cgi->wsi, cgi->content_length_seen);
2852 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2854 if (!cgi->content_length) {
2856 * well, if he sends chunked... give him 5s after the
2857 * cgi terminated to send buffered
2859 cgi->chunked_grace++;
2863 lwsl_debug("%s: found PID %d on cgi list\n",
2864 __func__, cgi->pid);
2867 lws_cgi_kill(cgi->wsi);
2874 /* general anti zombie defence */
2875 // n = waitpid(-1, &status, WNOHANG);
2877 // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
2883 #ifdef LWS_NO_EXTENSIONS
2885 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2886 const char *opt_name, const char *opt_val)
2892 #ifdef LWS_WITH_ACCESS_LOG
2894 lws_access_log(struct lws *wsi)
2896 char *p = wsi->access_log.user_agent, ass[512];
2899 if (!wsi->access_log_pending)
2902 if (!wsi->access_log.header_log)
2908 l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
2909 wsi->access_log.header_log,
2910 wsi->access_log.response, wsi->access_log.sent, p);
2912 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
2913 if (write(wsi->vhost->log_fd, ass, l) != l)
2914 lwsl_err("Failed to write log\n");
2916 lwsl_err("%s", ass);
2918 if (wsi->access_log.header_log) {
2919 lws_free(wsi->access_log.header_log);
2920 wsi->access_log.header_log = NULL;
2922 if (wsi->access_log.user_agent) {
2923 lws_free(wsi->access_log.user_agent);
2924 wsi->access_log.user_agent = NULL;
2926 wsi->access_log_pending = 0;
2933 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
2935 const struct lws_vhost *vh = ctx->vhost_list;
2939 cs->rx += vh->conn_stats.rx;
2940 cs->tx += vh->conn_stats.tx;
2941 cs->conn += vh->conn_stats.conn;
2942 cs->trans += vh->conn_stats.trans;
2943 cs->ws_upg += vh->conn_stats.ws_upg;
2944 cs->http2_upg += vh->conn_stats.http2_upg;
2945 cs->rejected += vh->conn_stats.rejected;
2947 vh = vh->vhost_next;
2951 #ifdef LWS_WITH_SERVER_STATUS
2954 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
2956 static const char * const prots[] = {
2965 char *orig = buf, *end = buf + len - 1, first = 1;
2971 buf += lws_snprintf(buf, end - buf,
2972 "{\n \"name\":\"%s\",\n"
2973 " \"port\":\"%d\",\n"
2974 " \"use_ssl\":\"%d\",\n"
2975 " \"sts\":\"%d\",\n"
2976 " \"rx\":\"%llu\",\n"
2977 " \"tx\":\"%llu\",\n"
2978 " \"conn\":\"%lu\",\n"
2979 " \"trans\":\"%lu\",\n"
2980 " \"ws_upg\":\"%lu\",\n"
2981 " \"rejected\":\"%lu\",\n"
2982 " \"http2_upg\":\"%lu\""
2984 vh->name, vh->listen_port,
2985 #ifdef LWS_OPENSSL_SUPPORT
2990 !!(vh->options & LWS_SERVER_OPTION_STS),
2991 vh->conn_stats.rx, vh->conn_stats.tx,
2992 vh->conn_stats.conn, vh->conn_stats.trans,
2993 vh->conn_stats.ws_upg,
2994 vh->conn_stats.rejected,
2995 vh->conn_stats.http2_upg
2998 if (vh->mount_list) {
2999 const struct lws_http_mount *m = vh->mount_list;
3001 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
3004 buf += lws_snprintf(buf, end - buf, ",");
3005 buf += lws_snprintf(buf, end - buf,
3006 "\n {\n \"mountpoint\":\"%s\",\n"
3007 " \"origin\":\"%s%s\",\n"
3008 " \"cache_max_age\":\"%d\",\n"
3009 " \"cache_reuse\":\"%d\",\n"
3010 " \"cache_revalidate\":\"%d\",\n"
3011 " \"cache_intermediaries\":\"%d\"\n"
3014 prots[m->origin_protocol],
3018 m->cache_revalidate,
3019 m->cache_intermediaries);
3021 buf += lws_snprintf(buf, end - buf,
3022 ",\n \"default\":\"%s\"",
3024 buf += lws_snprintf(buf, end - buf, "\n }");
3028 buf += lws_snprintf(buf, end - buf, "\n ]");
3031 if (vh->protocols) {
3035 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
3036 while (n < vh->count_protocols) {
3038 buf += lws_snprintf(buf, end - buf, ",");
3039 buf += lws_snprintf(buf, end - buf,
3041 " \"status\":\"ok\"\n }\n }"
3043 vh->protocols[n].name);
3047 buf += lws_snprintf(buf, end - buf, "\n ]");
3050 buf += lws_snprintf(buf, end - buf, "\n}");
3056 LWS_EXTERN LWS_VISIBLE int
3057 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
3060 char *orig = buf, *end = buf + len - 1, first = 1;
3061 const struct lws_vhost *vh = context->vhost_list;
3062 const struct lws_context_per_thread *pt;
3063 time_t t = time(NULL);
3064 int n, listening = 0, cgi_count = 0;
3065 struct lws_conn_stats cs;
3068 struct lws_cgi * const *pcgi;
3071 #ifdef LWS_USE_LIBUV
3075 buf += lws_snprintf(buf, end - buf, "{ "
3076 "\"version\":\"%s\",\n"
3077 "\"uptime\":\"%ld\",\n",
3078 lws_get_library_version(),
3081 #ifdef LWS_HAVE_GETLOADAVG
3086 m = getloadavg(d, 3);
3087 for (n = 0; n < m; n++) {
3088 buf += lws_snprintf(buf, end - buf,
3089 "\"l%d\":\"%.2f\",\n",
3095 buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
3097 buf += lws_snprintf(buf, end - buf, "{ "
3098 "\"context_uptime\":\"%ld\",\n"
3099 "\"cgi_spawned\":\"%d\",\n"
3100 "\"pt_fd_max\":\"%d\",\n"
3101 "\"ah_pool_max\":\"%d\",\n"
3102 "\"deprecated\":\"%d\",\n"
3103 "\"wsi_alive\":\"%d\",\n",
3104 (unsigned long)(t - context->time_up),
3105 context->count_cgi_spawned,
3106 context->fd_limit_per_thread,
3107 context->max_http_header_pool,
3108 context->deprecated,
3109 context->count_wsi_allocated);
3111 buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
3112 for (n = 0; n < context->count_threads; n++) {
3113 pt = &context->pt[n];
3115 buf += lws_snprintf(buf, end - buf, ",");
3116 buf += lws_snprintf(buf, end - buf,
3118 " \"fds_count\":\"%d\",\n"
3119 " \"ah_pool_inuse\":\"%d\",\n"
3120 " \"ah_wait_list\":\"%d\"\n"
3123 pt->ah_count_in_use,
3124 pt->ah_wait_list_length);
3127 buf += lws_snprintf(buf, end - buf, "]");
3129 buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3132 vh = context->vhost_list;
3134 cs = context->conn_stats;
3135 lws_sum_stats(context, &cs);
3142 buf += lws_json_dump_vhost(vh, buf, end - buf);
3147 vh = vh->vhost_next;
3150 buf += lws_snprintf(buf, end - buf,
3151 "],\n\"listen_wsi\":\"%d\",\n"
3152 " \"rx\":\"%llu\",\n"
3153 " \"tx\":\"%llu\",\n"
3154 " \"conn\":\"%lu\",\n"
3155 " \"trans\":\"%lu\",\n"
3156 " \"ws_upg\":\"%lu\",\n"
3157 " \"rejected\":\"%lu\",\n"
3158 " \"http2_upg\":\"%lu\"",
3160 cs.rx, cs.tx, cs.conn, cs.trans,
3161 cs.ws_upg, cs.rejected, cs.http2_upg);
3164 for (n = 0; n < context->count_threads; n++) {
3165 pt = &context->pt[n];
3166 pcgi = &pt->cgi_list;
3169 pcgi = &(*pcgi)->cgi_list;
3175 buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3178 buf += lws_snprintf(buf, end - buf, "}");
3181 buf += lws_snprintf(buf, end - buf, "]}\n ");
3188 #if defined(LWS_WITH_STATS)
3190 LWS_VISIBLE LWS_EXTERN uint64_t
3191 lws_stats_get(struct lws_context *context, int index)
3193 if (index >= LWSSTATS_SIZE)
3196 return context->lws_stats[index];
3199 LWS_VISIBLE LWS_EXTERN void
3200 lws_stats_log_dump(struct lws_context *context)
3202 struct lws_vhost *v = context->vhost_list;
3205 if (!context->updated)
3208 context->updated = 0;
3211 lwsl_notice("LWS internal statistics dump ----->\n");
3212 lwsl_notice("LWSSTATS_C_CONNECTIONS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_CONNECTIONS));
3213 lwsl_notice("LWSSTATS_C_API_CLOSE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_CLOSE));
3214 lwsl_notice("LWSSTATS_C_API_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_READ));
3215 lwsl_notice("LWSSTATS_C_API_LWS_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_LWS_WRITE));
3216 lwsl_notice("LWSSTATS_C_API_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_WRITE));
3217 lwsl_notice("LWSSTATS_C_WRITE_PARTIALS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITE_PARTIALS));
3218 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_REQ));
3219 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_EFF_REQ));
3220 lwsl_notice("LWSSTATS_C_WRITEABLE_CB: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB));
3221 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_FAILED));
3222 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED));
3223 lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX));
3225 lwsl_notice("LWSSTATS_C_TIMEOUTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_TIMEOUTS));
3226 lwsl_notice("LWSSTATS_C_SERVICE_ENTRY: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SERVICE_ENTRY));
3227 lwsl_notice("LWSSTATS_B_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ));
3228 lwsl_notice("LWSSTATS_B_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE));
3229 lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS));
3230 lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000);
3231 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED))
3232 lwsl_notice(" Avg accept delay: %8llums\n",
3233 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) /
3234 lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000);
3235 lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / 1000);
3236 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX))
3237 lwsl_notice(" Avg accept-rx delay: %8llums\n",
3238 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) /
3239 lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000);
3241 lwsl_notice("LWSSTATS_MS_WRITABLE_DELAY: %8lluus\n",
3242 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY));
3243 lwsl_notice("LWSSTATS_MS_WORST_WRITABLE_DELAY: %8lluus\n",
3244 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WORST_WRITABLE_DELAY));
3245 if (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))
3246 lwsl_notice(" Avg writable delay: %8lluus\n",
3247 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY) /
3248 lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)));
3249 lwsl_notice("Simultaneous SSL restriction: %8d/%d/%d\n", context->simultaneous_ssl,
3250 context->simultaneous_ssl_restriction, context->ssl_gate_accepts);
3252 lwsl_notice("Live wsi: %8d\n", context->count_wsi_allocated);
3254 #if defined(LWS_WITH_STATS)
3255 context->updated = 1;
3259 if (v->use_ssl && v->lserv_wsi) {
3260 struct lws_context_per_thread *pt = &context->pt[(int)v->lserv_wsi->tsi];
3261 struct lws_pollfd *pfd;
3263 pfd = &pt->fds[v->lserv_wsi->position_in_fds_table];
3265 lwsl_notice(" Listen port %d actual POLLIN: %d\n",
3266 v->listen_port, (int)pfd->events & LWS_POLLIN);
3272 for (n = 0; n < context->count_threads; n++) {
3273 struct lws_context_per_thread *pt = &context->pt[n];
3277 lwsl_notice("PT %d\n", n + 1);
3281 lwsl_notice(" AH in use / max: %d / %d\n",
3282 pt->ah_count_in_use,
3283 context->max_http_header_pool);
3285 wl = pt->ah_wait_list;
3288 wl = wl->u.hdr.ah_wait_list;
3291 lwsl_notice(" AH wait list count / actual: %d / %d\n",
3292 pt->ah_wait_list_length, m);
3301 lws_stats_atomic_bump(struct lws_context * context,
3302 struct lws_context_per_thread *pt, int index, uint64_t bump)
3305 context->lws_stats[index] += bump;
3306 if (index != LWSSTATS_C_SERVICE_ENTRY)
3307 context->updated = 1;
3312 lws_stats_atomic_max(struct lws_context * context,
3313 struct lws_context_per_thread *pt, int index, uint64_t val)
3316 if (val > context->lws_stats[index]) {
3317 context->lws_stats[index] = val;
3318 context->updated = 1;