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 (!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];
253 /* if we have children, close them first */
254 if (wsi->child_list) {
255 wsi2 = wsi->child_list;
257 //lwsl_notice("%s: closing %p: close child %p\n",
258 // __func__, wsi, wsi2);
259 wsi1 = wsi2->sibling_list;
260 //lwsl_notice("%s: closing %p: next sibling %p\n",
261 // __func__, wsi2, wsi1);
263 /* stop it doing shutdown processing */
264 wsi2->socket_is_permanently_unusable = 1;
265 lws_close_free_wsi(wsi2, reason);
268 wsi->child_list = NULL;
271 if (wsi->mode == LWSCM_RAW_FILEDESC) {
272 lws_remove_child_from_any_parent(wsi);
273 remove_wsi_socket_from_fds(wsi);
274 wsi->protocol->callback(wsi,
275 LWS_CALLBACK_RAW_CLOSE_FILE,
276 wsi->user_space, NULL, 0);
281 if (wsi->mode == LWSCM_CGI) {
282 /* we are not a network connection, but a handler for CGI io */
283 if (wsi->parent && wsi->parent->cgi)
284 /* end the binding between us and master */
285 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
286 wsi->socket_is_permanently_unusable = 1;
288 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
289 goto just_kill_connection;
293 struct lws_cgi **pcgi = &pt->cgi_list;
294 /* remove us from the cgi list */
295 lwsl_debug("%s: remove cgi %p from list\n", __func__, wsi->cgi);
297 if (*pcgi == wsi->cgi) {
298 /* drop us from the pt cgi list */
299 *pcgi = (*pcgi)->cgi_list;
302 pcgi = &(*pcgi)->cgi_list;
304 /* we have a cgi going, we must kill it */
305 wsi->cgi->being_closed = 1;
310 if (wsi->mode == LWSCM_RAW) {
311 wsi->protocol->callback(wsi,
312 LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0);
313 wsi->socket_is_permanently_unusable = 1;
314 goto just_kill_connection;
317 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
318 wsi->u.http.fop_fd != NULL) {
319 lws_vfs_file_close(&wsi->u.http.fop_fd);
320 wsi->vhost->protocols->callback(wsi,
321 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
322 wsi->told_user_closed = 1;
324 if (wsi->socket_is_permanently_unusable ||
325 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
326 wsi->state == LWSS_SHUTDOWN)
327 goto just_kill_connection;
329 wsi->state_pre_close = wsi->state;
331 switch (wsi->state_pre_close) {
332 case LWSS_DEAD_SOCKET:
335 /* we tried the polite way... */
336 case LWSS_AWAITING_CLOSE_ACK:
337 goto just_kill_connection;
339 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
340 if (wsi->trunc_len) {
341 lws_callback_on_writable(wsi);
344 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
345 goto just_kill_connection;
347 if (wsi->trunc_len) {
348 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
349 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
350 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
356 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
357 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
358 goto just_kill_connection;
360 if (wsi->mode == LWSCM_HTTP_SERVING) {
362 wsi->vhost->protocols->callback(wsi,
363 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
364 wsi->user_space, NULL, 0);
365 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
366 wsi->user_space, NULL, 0);
367 wsi->told_user_closed = 1;
369 if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
370 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
371 wsi->user_space, NULL, 0);
372 wsi->told_user_closed = 1;
376 * are his extensions okay with him closing? Eg he might be a mux
377 * parent and just his ch1 aspect is closing?
380 if (lws_ext_cb_active(wsi,
381 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
382 lwsl_ext("extension vetoed close\n");
387 * flush any tx pending from extensions, since we may send close packet
388 * if there are problems with send, just nuke the connection
393 eff_buf.token = NULL;
394 eff_buf.token_len = 0;
396 /* show every extension the new incoming data */
398 m = lws_ext_cb_active(wsi,
399 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
401 lwsl_ext("Extension reports fatal error\n");
402 goto just_kill_connection;
406 * at least one extension told us he has more
407 * to spill, so we will go around again after
411 /* assuming they left us something to send, send it */
413 if (eff_buf.token_len)
414 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
415 eff_buf.token_len) !=
417 lwsl_debug("close: ext spill failed\n");
418 goto just_kill_connection;
423 * signal we are closing, lws_write will
424 * add any necessary version-specific stuff. If the write fails,
425 * no worries we are closing anyway. If we didn't initiate this
426 * close, then our state has been changed to
427 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
429 * Likewise if it's a second call to close this connection after we
430 * sent the close indication to the peer already, we are in state
431 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
434 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
435 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
436 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
437 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
438 lwsl_debug("sending close indication...\n");
440 /* if no prepared close reason, use 1000 and no aux data */
441 if (!wsi->u.ws.close_in_ping_buffer_len) {
442 wsi->u.ws.close_in_ping_buffer_len = 2;
443 wsi->u.ws.ping_payload_buf[LWS_PRE] =
444 (reason >> 8) & 0xff;
445 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
449 #if defined (LWS_WITH_ESP8266)
450 wsi->close_is_pending_send_completion = 1;
452 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
453 wsi->u.ws.close_in_ping_buffer_len,
457 * we have sent a nice protocol level indication we
458 * now wish to close, we should not send anything more
460 wsi->state = LWSS_AWAITING_CLOSE_ACK;
463 * ...and we should wait for a reply for a bit
466 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
467 lwsl_debug("sent close indication, awaiting ack\n");
472 lwsl_info("close: sending close packet failed, hanging up\n");
474 /* else, the send failed and we should just hang up */
477 just_kill_connection:
479 lws_remove_child_from_any_parent(wsi);
482 /* manage the vhost same protocol list entry */
484 if (wsi->same_vh_protocol_prev) { // we are on the vh list
486 // make guy who pointed to us, point to what our next was pointing to
487 *wsi->same_vh_protocol_prev = wsi->same_vh_protocol_next;
489 // if we had a next guy...
490 if (wsi->same_vh_protocol_next)
491 // have him point back to our prev
492 wsi->same_vh_protocol_next->same_vh_protocol_prev =
493 wsi->same_vh_protocol_prev;
499 * Testing with ab shows that we have to stage the socket close when
500 * the system is under stress... shutdown any further TX, change the
501 * state to one that won't emit anything more, and wait with a timeout
502 * for the POLLIN to show a zero-size rx before coming back and doing
505 if (wsi->mode != LWSCM_RAW &&
506 !(wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) &&
507 wsi->state != LWSS_SHUTDOWN &&
508 wsi->state != LWSS_CLIENT_UNCONNECTED &&
509 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
510 !wsi->socket_is_permanently_unusable) {
511 #ifdef LWS_OPENSSL_SUPPORT
512 if (lws_is_ssl(wsi) && wsi->ssl)
514 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);
515 n = SSL_shutdown(wsi->ssl);
516 if (n == 1) /* If finished the SSL shutdown, then do socket shutdown, else need to retry SSL shutdown */
517 n = shutdown(wsi->desc.sockfd, SHUT_WR);
519 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
524 lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, (int)(long)wsi->desc.sockfd, wsi->state);
525 n = shutdown(wsi->desc.sockfd, SHUT_WR);
528 lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
530 // This causes problems with disconnection when the events are half closing connection
531 // FD_READ | FD_CLOSE (33)
532 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP32)
533 /* libuv: no event available to guarantee completion */
534 if (!LWS_LIBUV_ENABLED(context)) {
536 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
537 wsi->state = LWSS_SHUTDOWN;
538 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
539 context->timeout_secs);
547 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
548 wsi, wsi->desc.sockfd);
550 #ifdef LWS_WITH_HTTP_PROXY
552 lws_rewrite_destroy(wsi->rw);
557 * we won't be servicing or receiving anything further from this guy
558 * delete socket from the internal poll list if still present
560 lws_ssl_remove_wsi_from_buffered_list(wsi);
562 lws_remove_from_timeout_list(wsi);
564 /* checking return redundant since we anyway close */
565 if (wsi->desc.sockfd != LWS_SOCK_INVALID)
566 remove_wsi_socket_from_fds(wsi);
568 #if defined(LWS_WITH_ESP8266)
569 espconn_disconnect(wsi->desc.sockfd);
572 wsi->state = LWSS_DEAD_SOCKET;
574 lws_free_set_NULL(wsi->rxflow_buffer);
575 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
576 wsi->mode == LWSCM_WS_SERVING ||
577 wsi->mode == LWSCM_WS_CLIENT) {
579 if (wsi->u.ws.rx_draining_ext) {
580 struct lws **w = &pt->rx_draining_ext_list;
582 wsi->u.ws.rx_draining_ext = 0;
583 /* remove us from context draining ext list */
586 *w = wsi->u.ws.rx_draining_ext_list;
589 w = &((*w)->u.ws.rx_draining_ext_list);
591 wsi->u.ws.rx_draining_ext_list = NULL;
594 if (wsi->u.ws.tx_draining_ext) {
595 struct lws **w = &pt->tx_draining_ext_list;
597 wsi->u.ws.tx_draining_ext = 0;
598 /* remove us from context draining ext list */
601 *w = wsi->u.ws.tx_draining_ext_list;
604 w = &((*w)->u.ws.tx_draining_ext_list);
606 wsi->u.ws.tx_draining_ext_list = NULL;
608 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
610 if (wsi->trunc_alloc)
611 /* not going to be completed... nuke it */
612 lws_free_set_NULL(wsi->trunc_alloc);
614 wsi->u.ws.ping_payload_len = 0;
615 wsi->u.ws.ping_pending_flag = 0;
618 /* tell the user it's all over for this guy */
620 if (wsi->mode != LWSCM_RAW && wsi->protocol && wsi->protocol->callback &&
621 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
622 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
623 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
624 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
625 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
626 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
628 if (wsi->user_space) {
629 lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s\n", __func__, wsi, wsi->protocol->name);
630 wsi->protocol->callback(wsi,
631 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
632 wsi->user_space, NULL, 0);
634 lwsl_debug("calling back CLOSED\n");
635 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
636 wsi->user_space, NULL, 0);
637 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
638 lwsl_debug("calling back CLOSED_HTTP\n");
639 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
640 wsi->user_space, NULL, 0 );
641 } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
642 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
643 !wsi->already_did_cce) {
644 wsi->vhost->protocols[0].callback(wsi,
645 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
646 wsi->user_space, NULL, 0);
648 lwsl_debug("not calling back closed mode=%d state=%d\n",
649 wsi->mode, wsi->state_pre_close);
651 /* deallocate any active extension contexts */
653 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
654 lwsl_warn("extension destruction failed\n");
656 * inform all extensions in case they tracked this guy out of band
657 * even though not active on him specifically
659 if (lws_ext_cb_all_exts(context, wsi,
660 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
661 lwsl_warn("ext destroy wsi failed\n");
665 wsi->socket_is_permanently_unusable = 1;
668 if (LWS_LIBUV_ENABLED(context)) {
669 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
670 /* libuv has to do his own close handle processing asynchronously */
671 lws_libuv_closehandle(wsi);
677 lws_close_free_wsi_final(wsi);
681 lws_close_free_wsi_final(struct lws *wsi)
685 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->desc.sockfd)) {
687 //lwsl_err("*** closing sockfd %d\n", wsi->desc.sockfd);
688 n = compatible_close(wsi->desc.sockfd);
690 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
693 compatible_close(wsi->desc.sockfd);
696 wsi->desc.sockfd = LWS_SOCK_INVALID;
699 /* outermost destroy notification for wsi (user_space still intact) */
700 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
701 wsi->user_space, NULL, 0);
705 for (n = 0; n < 6; n++) {
706 if (wsi->cgi->pipe_fds[n / 2][n & 1] == 0)
707 lwsl_err("ZERO FD IN CGI CLOSE");
709 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
710 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
720 LWS_VISIBLE LWS_EXTERN const char *
721 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
723 int n = 0, sl = strlen(name);
725 while (lws_hdr_copy_fragment(wsi, buf, len,
726 WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
728 if (!strncmp(buf, name, sl))
737 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
739 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
743 ipv6 = LWS_IPV6_ENABLED(vh);
747 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
751 #ifndef LWS_PLAT_OPTEE
754 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
755 int name_len, char *rip, int rip_len)
758 struct addrinfo ai, *res;
759 struct sockaddr_in addr4;
764 addr4.sin_family = AF_UNSPEC;
767 if (LWS_IPV6_ENABLED(vh)) {
768 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
769 lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
773 // Strip off the IPv4 to IPv6 header if one exists
774 if (strncmp(rip, "::ffff:", 7) == 0)
775 memmove(rip, rip + 7, strlen(rip) - 6);
777 getnameinfo((struct sockaddr *)ads,
778 sizeof(struct sockaddr_in6), name,
779 name_len, NULL, 0, 0);
785 struct addrinfo *result;
787 memset(&ai, 0, sizeof ai);
788 ai.ai_family = PF_UNSPEC;
789 ai.ai_socktype = SOCK_STREAM;
790 ai.ai_flags = AI_CANONNAME;
791 #if !defined(LWS_WITH_ESP32)
792 if (getnameinfo((struct sockaddr *)ads,
793 sizeof(struct sockaddr_in),
794 name, name_len, NULL, 0, 0))
800 if (getaddrinfo(name, NULL, &ai, &result))
804 while (addr4.sin_family == AF_UNSPEC && res) {
805 switch (res->ai_family) {
807 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
808 addr4.sin_family = AF_INET;
814 freeaddrinfo(result);
817 if (addr4.sin_family == AF_UNSPEC)
820 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
838 LWS_VISIBLE const char *
839 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
844 struct sockaddr_in6 sin6;
846 struct sockaddr_in sin4;
851 if (LWS_IPV6_ENABLED(wsi->vhost)) {
865 if (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {
866 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
870 return lws_plat_inet_ntop(af, q, name, namelen);
872 #if defined(LWS_WITH_ESP8266)
873 return lws_plat_get_peer_simple(wsi, name, namelen);
882 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
883 int name_len, char *rip, int rip_len)
885 #ifndef LWS_PLAT_OPTEE
889 struct sockaddr_in6 sin6;
891 struct sockaddr_in sin4;
892 struct lws_context *context = wsi->context;
899 lws_latency_pre(context, wsi);
902 if (LWS_IPV6_ENABLED(wsi->vhost)) {
912 if (getpeername(fd, p, &len) < 0) {
913 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
917 ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
920 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
933 lws_context_user(struct lws_context *context)
935 return context->user_space;
938 LWS_VISIBLE struct lws_vhost *
939 lws_vhost_get(struct lws *wsi)
944 LWS_VISIBLE struct lws_vhost *
945 lws_get_vhost(struct lws *wsi)
950 LWS_VISIBLE const struct lws_protocols *
951 lws_protocol_get(struct lws *wsi)
953 return wsi->protocol;
956 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
957 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
961 for (n = 0; n < vh->count_protocols; n++)
962 if (!strcmp(name, vh->protocols[n].name))
963 return &vh->protocols[n];
969 lws_callback_all_protocol(struct lws_context *context,
970 const struct lws_protocols *protocol, int reason)
972 struct lws_context_per_thread *pt = &context->pt[0];
973 unsigned int n, m = context->count_threads;
977 for (n = 0; n < pt->fds_count; n++) {
978 wsi = wsi_from_fd(context, pt->fds[n].fd);
981 if (wsi->protocol == protocol)
982 protocol->callback(wsi, reason, wsi->user_space,
992 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
993 const struct lws_protocols *protocol, int reason)
995 struct lws_context *context = vh->context;
996 struct lws_context_per_thread *pt = &context->pt[0];
997 unsigned int n, m = context->count_threads;
1001 for (n = 0; n < pt->fds_count; n++) {
1002 wsi = wsi_from_fd(context, pt->fds[n].fd);
1005 if (wsi->vhost == vh && wsi->protocol == protocol)
1006 protocol->callback(wsi, reason, wsi->user_space,
1015 LWS_VISIBLE LWS_EXTERN int
1016 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
1020 for (n = 0; n < wsi->vhost->count_protocols; n++)
1021 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
1027 LWS_VISIBLE LWS_EXTERN void
1028 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)
1030 context->fops = fops;
1033 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1034 lws_vfs_tell(lws_fop_fd_t fop_fd)
1039 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1040 lws_vfs_get_length(lws_fop_fd_t fop_fd)
1045 LWS_VISIBLE LWS_EXTERN uint32_t
1046 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd)
1048 return fop_fd->mod_time;
1051 LWS_VISIBLE lws_fileofs_t
1052 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1055 lwsl_debug("%s: seeking to %ld, len %ld\n", __func__, (long)offset, (long)fop_fd->len);
1056 ofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);
1057 lwsl_debug("%s: result %ld, fop_fd pos %ld\n", __func__, (long)ofs, (long)fop_fd->pos);
1062 LWS_VISIBLE lws_fileofs_t
1063 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1065 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len + fop_fd->pos + offset);
1069 const struct lws_plat_file_ops *
1070 lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,
1073 const struct lws_plat_file_ops *pf;
1074 const char *p = vfs_path;
1079 /* no non-platform fops, just use that */
1085 * scan the vfs path looking for indications we are to be
1086 * handled by a specific fops
1094 /* the first one is always platform fops, so skip */
1098 while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {
1099 if (p >= vfs_path + pf->fi[n].len)
1100 if (!strncmp(p - (pf->fi[n].len - 1),
1102 pf->fi[n].len - 1)) {
1117 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
1118 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
1119 lws_fop_flags_t *flags)
1121 const char *vpath = "";
1122 const struct lws_plat_file_ops *selected = lws_vfs_select_fops(
1123 fops, vfs_path, &vpath);
1125 return selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);
1130 * lws_now_secs() - seconds since 1970-1-1
1133 LWS_VISIBLE LWS_EXTERN unsigned long
1138 gettimeofday(&tv, NULL);
1147 lws_get_socket_fd(struct lws *wsi)
1149 return wsi->desc.sockfd;
1156 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
1157 int ret, int completed)
1159 unsigned long long u;
1162 u = time_in_microseconds();
1165 wsi->latency_start = u;
1166 if (!wsi->action_start)
1167 wsi->action_start = u;
1171 if (wsi->action_start == wsi->latency_start)
1173 "Completion first try lat %lluus: %p: ret %d: %s\n",
1174 u - wsi->latency_start,
1175 (void *)wsi, ret, action);
1178 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1179 u - wsi->action_start,
1180 u - wsi->latency_start,
1181 (void *)wsi, ret, action);
1182 wsi->action_start = 0;
1184 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1185 u - wsi->latency_start, (void *)wsi, ret, action);
1187 if (u - wsi->latency_start > context->worst_latency) {
1188 context->worst_latency = u - wsi->latency_start;
1189 strcpy(context->worst_latency_info, buf);
1191 lwsl_latency("%s", buf);
1196 lws_rx_flow_control(struct lws *wsi, int enable)
1198 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1201 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1202 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1208 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1209 const struct lws_protocols *protocol)
1211 const struct lws_context_per_thread *pt = &context->pt[0];
1213 unsigned int n, m = context->count_threads;
1216 for (n = 0; n < pt->fds_count; n++) {
1217 wsi = wsi_from_fd(context, pt->fds[n].fd);
1220 if (wsi->protocol == protocol)
1221 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1227 LWS_VISIBLE extern const char *
1228 lws_canonical_hostname(struct lws_context *context)
1230 return (const char *)context->canonical_hostname;
1233 int user_callback_handle_rxflow(lws_callback_function callback_function,
1235 enum lws_callback_reasons reason, void *user,
1236 void *in, size_t len)
1240 n = callback_function(wsi, reason, user, in, len);
1242 n = _lws_rx_flow_control(wsi);
1247 #if defined(LWS_WITH_ESP8266)
1249 #define strchr ets_strchr
1253 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1255 #if !defined(LWS_WITH_ESP8266)
1257 char authstring[96];
1262 /* we have to deal with a possible redundant leading http:// */
1263 if (!strncmp(proxy, "http://", 7))
1266 p = strchr(proxy, '@');
1267 if (p) { /* auth is around */
1269 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1272 strncpy(authstring, proxy, p - proxy);
1273 // null termination not needed on input
1274 if (lws_b64_encode_string(authstring, (p - proxy),
1275 vhost->proxy_basic_auth_token,
1276 sizeof vhost->proxy_basic_auth_token) < 0)
1279 lwsl_info(" Proxy auth in use\n");
1283 vhost->proxy_basic_auth_token[0] = '\0';
1285 strncpy(vhost->http_proxy_address, proxy,
1286 sizeof(vhost->http_proxy_address) - 1);
1287 vhost->http_proxy_address[
1288 sizeof(vhost->http_proxy_address) - 1] = '\0';
1290 p = strchr(vhost->http_proxy_address, ':');
1291 if (!p && !vhost->http_proxy_port) {
1292 lwsl_err("http_proxy needs to be ads:port\n");
1298 vhost->http_proxy_port = atoi(p + 1);
1302 lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1303 vhost->http_proxy_port);
1308 lwsl_err("proxy auth too long\n");
1313 LWS_VISIBLE const struct lws_protocols *
1314 lws_get_protocol(struct lws *wsi)
1316 return wsi->protocol;
1320 lws_is_final_fragment(struct lws *wsi)
1322 lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1323 wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1324 (long)wsi->u.ws.rx_draining_ext);
1325 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1328 LWS_VISIBLE unsigned char
1329 lws_get_reserved_bits(struct lws *wsi)
1331 return wsi->u.ws.rsv;
1335 lws_ensure_user_space(struct lws *wsi)
1337 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1341 /* allocate the per-connection user memory (if any) */
1343 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1344 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1345 if (wsi->user_space == NULL) {
1346 lwsl_err("Out of memory for conn user space\n");
1350 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1351 __func__, wsi, (long)wsi->protocol->per_session_data_size,
1357 lwsl_timestamp(int level, char *p, int len)
1359 #ifndef LWS_PLAT_OPTEE
1360 time_t o_now = time(NULL);
1361 unsigned long long now;
1362 struct tm *ptm = NULL;
1370 ptm = localtime(&o_now);
1372 if (localtime_r(&o_now, &tm))
1377 for (n = 0; n < LLL_COUNT; n++) {
1378 if (level != (1 << n))
1380 now = time_in_microseconds() / 100;
1382 n = lws_snprintf(p, len,
1383 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1384 ptm->tm_year + 1900,
1390 (int)(now % 10000), log_level_names[n]);
1392 n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1393 (unsigned long long) now / 10000,
1394 (int)(now % 10000), log_level_names[n]);
1401 #ifndef LWS_PLAT_OPTEE
1402 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1404 #if !defined(LWS_WITH_ESP8266)
1407 lwsl_timestamp(level, buf, sizeof(buf));
1408 fprintf(stderr, "%s%s", buf, line);
1413 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1415 #if defined(LWS_WITH_ESP8266)
1422 if (!(log_level & filter))
1425 n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1427 #if defined(LWS_WITH_ESP8266)
1428 buf[sizeof(buf) - 1] = '\0';
1430 /* vnsprintf returns what it would have written, even if truncated */
1431 if (n > sizeof(buf) - 1)
1432 n = sizeof(buf) - 1;
1437 lwsl_emit(filter, buf);
1440 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1444 va_start(ap, format);
1445 _lws_logv(filter, format, ap);
1449 LWS_VISIBLE void lws_set_log_level(int level,
1450 void (*func)(int level, const char *line))
1457 LWS_VISIBLE int lwsl_visible(int level)
1459 return log_level & level;
1463 lws_is_ssl(struct lws *wsi)
1465 #ifdef LWS_OPENSSL_SUPPORT
1466 return wsi->use_ssl;
1473 #ifdef LWS_OPENSSL_SUPPORT
1475 lws_get_ssl(struct lws *wsi)
1482 lws_partial_buffered(struct lws *wsi)
1484 return !!wsi->trunc_len;
1487 void lws_set_protocol_write_pending(struct lws *wsi,
1488 enum lws_pending_protocol_send pend)
1490 lwsl_info("setting pps %d\n", pend);
1493 lwsl_err("pps overwrite\n");
1495 lws_rx_flow_control(wsi, 0);
1496 lws_callback_on_writable(wsi);
1500 lws_get_peer_write_allowance(struct lws *wsi)
1502 #ifdef LWS_USE_HTTP2
1503 /* only if we are using HTTP2 on this connection */
1504 if (wsi->mode != LWSCM_HTTP2_SERVING)
1506 /* user is only interested in how much he can send, or that he can't */
1507 if (wsi->u.http2.tx_credit <= 0)
1510 return wsi->u.http2.tx_credit;
1518 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1520 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1521 memset(&wsi->u, 0, sizeof(wsi->u));
1525 LWS_VISIBLE struct lws_plat_file_ops *
1526 lws_get_fops(struct lws_context *context)
1528 return (struct lws_plat_file_ops *)context->fops;
1531 LWS_VISIBLE LWS_EXTERN struct lws_context *
1532 lws_get_context(const struct lws *wsi)
1534 return wsi->context;
1537 LWS_VISIBLE LWS_EXTERN int
1538 lws_get_count_threads(struct lws_context *context)
1540 return context->count_threads;
1543 LWS_VISIBLE LWS_EXTERN void *
1544 lws_wsi_user(struct lws *wsi)
1546 return wsi->user_space;
1549 LWS_VISIBLE LWS_EXTERN void
1550 lws_set_wsi_user(struct lws *wsi, void *data)
1552 if (wsi->user_space_externally_allocated)
1553 wsi->user_space = data;
1555 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1559 LWS_VISIBLE LWS_EXTERN struct lws *
1560 lws_get_parent(const struct lws *wsi)
1565 LWS_VISIBLE LWS_EXTERN struct lws *
1566 lws_get_child(const struct lws *wsi)
1568 return wsi->child_list;
1571 LWS_VISIBLE LWS_EXTERN void
1572 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1573 unsigned char *buf, size_t len)
1575 unsigned char *p, *start;
1576 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1578 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1580 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1582 *p++ = (((int)status) >> 8) & 0xff;
1583 *p++ = ((int)status) & 0xff;
1586 while (len-- && p < start + budget)
1589 wsi->u.ws.close_in_ping_buffer_len = p - start;
1593 _lws_rx_flow_control(struct lws *wsi)
1595 struct lws *wsic = wsi->child_list;
1597 /* if he has children, do those if they were changed */
1599 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1600 _lws_rx_flow_control(wsic);
1602 wsic = wsic->sibling_list;
1605 /* there is no pending change */
1606 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1607 // lwsl_debug("%s: no pending change\n", __func__);
1611 /* stuff is still buffered, not ready to really accept new input */
1612 if (wsi->rxflow_buffer) {
1613 /* get ourselves called back to deal with stashed buffer */
1614 lws_callback_on_writable(wsi);
1618 /* pending is cleared, we can change rxflow state */
1620 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1622 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1623 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1625 /* adjust the pollfd for this wsi */
1627 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1628 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1629 lwsl_info("%s: fail\n", __func__);
1633 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1640 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1642 static const unsigned char e0f4[] = {
1643 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1644 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1645 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1646 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1647 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1648 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1649 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1650 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1651 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1652 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1653 0x80 | ((4 - 1) << 2) | 1, /* ea */
1654 0x80 | ((4 - 1) << 2) | 1, /* eb */
1655 0x80 | ((4 - 1) << 2) | 1, /* ec */
1656 0x80 | ((2 - 1) << 2) | 1, /* ed */
1657 0x80 | ((4 - 1) << 2) | 1, /* ee */
1658 0x80 | ((4 - 1) << 2) | 1, /* ef */
1659 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1660 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1661 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1662 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1663 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1666 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1667 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1669 unsigned char s = *state;
1672 unsigned char c = *buf++;
1676 if (c < 0xc2 || c > 0xf4)
1679 s = 0x80 | ((4 - 1) << 2);
1684 if (c < (s & 0xf0) ||
1685 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1687 s = e0f4[21 + (s & 3)];
1696 LWS_VISIBLE LWS_EXTERN int
1697 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1701 static const char *slash = "/";
1703 /* cut up the location into address, port and path */
1705 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1716 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1718 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1724 while (*p && *p != ']')
1731 while (*p && *p != ':' && *p != '/')
1737 while (*p && *p != '/')
1750 #ifdef LWS_NO_EXTENSIONS
1752 /* we need to provide dummy callbacks for internal exts
1753 * so user code runs when faced with a lib compiled with
1754 * extensions disabled.
1758 lws_extension_callback_pm_deflate(struct lws_context *context,
1759 const struct lws_extension *ext,
1761 enum lws_extension_callback_reasons reason,
1762 void *user, void *in, size_t len)
1777 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1781 #ifdef LWS_USE_UNIX_SOCK
1782 struct sockaddr_un serv_unix;
1785 struct sockaddr_in6 serv_addr6;
1787 struct sockaddr_in serv_addr4;
1788 #ifndef LWS_PLAT_OPTEE
1789 socklen_t len = sizeof(struct sockaddr);
1792 struct sockaddr_in sin;
1795 #ifdef LWS_USE_UNIX_SOCK
1796 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1797 v = (struct sockaddr *)&serv_unix;
1798 n = sizeof(struct sockaddr_un);
1799 bzero((char *) &serv_unix, sizeof(serv_unix));
1800 serv_unix.sun_family = AF_UNIX;
1801 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1802 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1806 strcpy(serv_unix.sun_path, iface);
1807 if (serv_unix.sun_path[0] == '@')
1808 serv_unix.sun_path[0] = '\0';
1812 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1813 if (LWS_IPV6_ENABLED(vhost)) {
1814 v = (struct sockaddr *)&serv_addr6;
1815 n = sizeof(struct sockaddr_in6);
1816 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1818 interface_to_sa(vhost, iface,
1819 (struct sockaddr_in *)v, n) < 0) {
1820 lwsl_err("Unable to find interface %s\n", iface);
1825 struct ifaddrs *addrs, *addr;
1826 char ip[NI_MAXHOST];
1830 for (addr = addrs; addr; addr = addr->ifa_next) {
1831 if (!addr->ifa_addr ||
1832 addr->ifa_addr->sa_family != AF_INET6)
1835 getnameinfo(addr->ifa_addr,
1836 sizeof(struct sockaddr_in6),
1838 NULL, 0, NI_NUMERICHOST);
1842 if (ip[i++] == '%') {
1847 if (!strcmp(ip, iface)) {
1848 serv_addr6.sin6_scope_id =
1849 if_nametoindex(addr->ifa_name);
1856 serv_addr6.sin6_family = AF_INET6;
1857 serv_addr6.sin6_port = htons(port);
1861 v = (struct sockaddr *)&serv_addr4;
1862 n = sizeof(serv_addr4);
1863 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1864 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1865 serv_addr4.sin_family = AF_INET;
1866 #if !defined(LWS_WITH_ESP32)
1869 interface_to_sa(vhost, iface,
1870 (struct sockaddr_in *)v, n) < 0) {
1871 lwsl_err("Unable to find interface %s\n", iface);
1875 serv_addr4.sin_port = htons(port);
1878 n = bind(sockfd, v, n);
1879 #ifdef LWS_USE_UNIX_SOCK
1880 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
1881 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1882 sockfd, iface, n, LWS_ERRNO);
1887 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1888 sockfd, port, n, LWS_ERRNO);
1892 #ifndef LWS_PLAT_OPTEE
1893 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1894 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1897 port = ntohs(sin.sin_port);
1904 lws_restart_ws_ping_pong_timer(struct lws *wsi)
1906 if (!wsi->context->ws_ping_pong_interval)
1908 if (wsi->state != LWSS_ESTABLISHED)
1911 wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
1912 wsi->context->ws_ping_pong_interval;
1915 static const char *hex = "0123456789ABCDEF";
1917 LWS_VISIBLE LWS_EXTERN const char *
1918 lws_sql_purify(char *escaped, const char *string, int len)
1920 const char *p = string;
1923 while (*p && len-- > 2) {
1937 LWS_VISIBLE LWS_EXTERN const char *
1938 lws_json_purify(char *escaped, const char *string, int len)
1940 const char *p = string;
1948 while (*p && len-- > 6) {
1949 if (*p == '\"' || *p == '\\' || *p < 0x20) {
1954 *q++ = hex[((*p) >> 4) & 15];
1955 *q++ = hex[(*p) & 15];
1966 LWS_VISIBLE LWS_EXTERN const char *
1967 lws_urlencode(char *escaped, const char *string, int len)
1969 const char *p = string;
1972 while (*p && len-- > 3) {
1978 if ((*p >= '0' && *p <= '9') ||
1979 (*p >= 'A' && *p <= 'Z') ||
1980 (*p >= 'a' && *p <= 'z')) {
1985 *q++ = hex[(*p >> 4) & 0xf];
1986 *q++ = hex[*p & 0xf];
1996 LWS_VISIBLE LWS_EXTERN int
1997 lws_urldecode(char *string, const char *escaped, int len)
2002 while (*escaped && len) {
2005 if (*escaped == '%') {
2010 if (*escaped == '+') {
2016 *string++ = *escaped++;
2020 n = char_to_hex(*escaped);
2029 n = char_to_hex(*escaped);
2033 *string++ = sum | n;
2045 LWS_VISIBLE LWS_EXTERN int
2046 lws_finalize_startup(struct lws_context *context)
2048 struct lws_context_creation_info info;
2050 info.uid = context->uid;
2051 info.gid = context->gid;
2053 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2054 lws_plat_drop_app_privileges(&info);
2060 lws_snprintf(char *str, size_t size, const char *format, ...)
2068 va_start(ap, format);
2069 n = vsnprintf(str, size, format, ap);
2079 LWS_VISIBLE LWS_EXTERN int
2080 lws_is_cgi(struct lws *wsi) {
2091 urlencode(const char *in, int inlen, char *out, int outlen)
2093 char *start = out, *end = out + outlen;
2095 while (inlen-- && out < end - 4) {
2096 if ((*in >= 'A' && *in <= 'Z') ||
2097 (*in >= 'a' && *in <= 'z') ||
2098 (*in >= '0' && *in <= '9') ||
2112 *out++ = hex[(*in) >> 4];
2113 *out++ = hex[(*in++) & 15];
2124 lws_create_basic_wsi(struct lws_context *context, int tsi)
2126 struct lws *new_wsi;
2128 if ((unsigned int)context->pt[tsi].fds_count ==
2129 context->fd_limit_per_thread - 1) {
2130 lwsl_err("no space for new conn\n");
2134 new_wsi = lws_zalloc(sizeof(struct lws));
2135 if (new_wsi == NULL) {
2136 lwsl_err("Out of memory for new connection\n");
2141 new_wsi->context = context;
2142 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2143 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2145 /* initialize the instance struct */
2147 new_wsi->state = LWSS_CGI;
2148 new_wsi->mode = LWSCM_CGI;
2149 new_wsi->hdr_parsing_completed = 0;
2150 new_wsi->position_in_fds_table = -1;
2153 * these can only be set once the protocol is known
2154 * we set an unestablished connection's protocol pointer
2155 * to the start of the defauly vhost supported list, so it can look
2156 * for matching ones during the handshake
2158 new_wsi->protocol = context->vhost_list->protocols;
2159 new_wsi->user_space = NULL;
2160 new_wsi->ietf_spec_revision = 0;
2161 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2162 context->count_wsi_allocated++;
2167 LWS_VISIBLE LWS_EXTERN int
2168 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2169 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2171 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2172 char *env_array[30], cgi_path[400], e[1024], *p = e,
2173 *end = p + sizeof(e) - 1, tok[256], *t;
2174 struct lws_cgi *cgi;
2175 int n, m, i, uritok = -1;
2178 * give the master wsi a cgi struct
2181 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2183 lwsl_err("%s: OOM\n", __func__);
2188 cgi->wsi = wsi; /* set cgi's owning wsi */
2190 /* create pipes for [stdin|stdout] and [stderr] */
2192 for (n = 0; n < 3; n++)
2193 if (pipe(cgi->pipe_fds[n]) == -1)
2196 /* create cgi wsis for each stdin/out/err fd */
2198 for (n = 0; n < 3; n++) {
2199 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2200 if (!cgi->stdwsi[n])
2202 cgi->stdwsi[n]->cgi_channel = n;
2203 cgi->stdwsi[n]->vhost = wsi->vhost;
2205 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2206 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2208 /* read side is 0, stdin we want the write side, others read */
2209 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2210 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2211 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2216 for (n = 0; n < 3; n++) {
2217 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2218 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2220 cgi->stdwsi[n]->parent = wsi;
2221 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2222 wsi->child_list = cgi->stdwsi[n];
2225 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2226 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2227 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2229 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2230 cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2231 cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2232 cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2234 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2236 /* the cgi stdout is always sending us http1.x header data first */
2237 wsi->hdr_state = LCHS_HEADER;
2239 /* add us to the pt list of active cgis */
2240 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2241 cgi->cgi_list = pt->cgi_list;
2244 /* prepare his CGI env */
2248 if (lws_is_ssl(wsi))
2249 env_array[n++] = "HTTPS=ON";
2250 if (wsi->u.hdr.ah) {
2251 static const unsigned char meths[] = {
2254 WSI_TOKEN_OPTIONS_URI,
2256 WSI_TOKEN_PATCH_URI,
2257 WSI_TOKEN_DELETE_URI,
2259 static const char * const meth_names[] = {
2260 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2263 for (m = 0; m < ARRAY_SIZE(meths); m++)
2264 if (lws_hdr_total_length(wsi, meths[m]) >=
2265 script_uri_path_len) {
2273 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2274 lws_hdr_simple_ptr(wsi, uritok));
2275 cgi_path[sizeof(cgi_path) - 1] = '\0';
2276 env_array[n++] = cgi_path;
2279 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2284 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2285 /* dump the individual URI Arg parameters */
2288 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2289 WSI_TOKEN_HTTP_URI_ARGS, m);
2293 while (*t && *t != '=' && p < end - 4)
2297 i = urlencode(t, i- (t - tok), p, end - p);
2309 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2310 lws_hdr_simple_ptr(wsi, uritok) +
2311 script_uri_path_len);
2314 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2316 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2317 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2320 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2322 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2323 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2326 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2328 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2329 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2332 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2334 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2335 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2338 if (uritok == WSI_TOKEN_POST_URI) {
2339 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2341 p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2342 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2345 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2347 p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2348 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2353 p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2357 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2359 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2362 mp_cgienv = mp_cgienv->next;
2365 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2366 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2367 env_array[n] = NULL;
2370 for (m = 0; m < n; m++)
2371 lwsl_err(" %s\n", env_array[m]);
2375 * Actually having made the env, as a cgi we don't need the ah
2378 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
2379 lws_header_table_detach(wsi, 0);
2381 /* we are ready with the redirection pipes... run the thing */
2382 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2388 lwsl_err("fork failed, errno %d", errno);
2392 #if defined(__linux__)
2393 prctl(PR_SET_PDEATHSIG, SIGTERM);
2395 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2398 /* we are the parent process */
2399 wsi->context->count_cgi_spawned++;
2400 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2404 /* somewhere we can at least read things and enter it */
2406 lwsl_notice("%s: Failed to chdir\n", __func__);
2408 /* We are the forked process, redirect and kill inherited things.
2410 * Because of vfork(), we cannot do anything that changes pages in
2411 * the parent environment. Stuff that changes kernel state for the
2412 * process is OK. Stuff that happens after the execvpe() is OK.
2415 for (n = 0; n < 3; n++)
2416 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2417 lwsl_err("%s: stdin dup2 failed\n", __func__);
2421 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2422 for (m = 0; m < n; m++) {
2423 p = strchr(env_array[m], '=');
2425 setenv(env_array[m], p, 1);
2427 execvp(exec_array[0], (char * const *)&exec_array[0]);
2429 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2435 /* drop us from the pt cgi list */
2436 pt->cgi_list = cgi->cgi_list;
2439 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2441 for (n = 0; n < 3; n++)
2442 if (wsi->cgi->stdwsi[n])
2443 lws_free_wsi(cgi->stdwsi[n]);
2446 for (n = 0; n < 3; n++) {
2447 if (cgi->pipe_fds[n][0])
2448 close(cgi->pipe_fds[n][0]);
2449 if (cgi->pipe_fds[n][1])
2450 close(cgi->pipe_fds[n][1]);
2453 lws_free_set_NULL(wsi->cgi);
2455 lwsl_err("%s: failed\n", __func__);
2460 LWS_VISIBLE LWS_EXTERN int
2461 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2463 int n, m, match = 0, lp = 0;
2464 static const char * const content_length = "content-length: ";
2465 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2466 *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
2471 while (wsi->hdr_state != LHCS_PAYLOAD) {
2472 /* we have to separate header / finalize and
2473 * payload chunks, since they need to be
2474 * handled separately
2476 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2478 if (errno != EAGAIN) {
2479 lwsl_debug("%s: read says %d\n", __func__, n);
2486 lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
2487 switch (wsi->hdr_state) {
2489 if (!content_length[match] &&
2490 (c >= '0' && c <= '9') &&
2491 lp < sizeof(l) - 1) {
2494 wsi->cgi->content_length = atol(l);
2496 if (tolower(c) == content_length[match])
2501 /* some cgi only send us \x0a for EOL */
2503 wsi->hdr_state = LCHS_SINGLE_0A;
2508 wsi->hdr_state = LCHS_LF1;
2516 wsi->hdr_state = LCHS_CR2;
2519 /* we got \r[^\n]... it's unreasonable */
2520 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2526 wsi->hdr_state = LCHS_LF2;
2529 wsi->hdr_state = LCHS_HEADER;
2534 case LCHS_SINGLE_0A:
2537 lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
2538 wsi->hdr_state = LHCS_PAYLOAD;
2539 /* drop the \0xa ... finalize will add it if needed */
2540 if (lws_finalize_http_header(wsi,
2541 (unsigned char **)&p,
2542 (unsigned char *)end))
2547 /* we got \r\n\r[^\n]... it's unreasonable */
2549 /* we got \x0anext header, it's reasonable */
2551 wsi->hdr_state = LCHS_HEADER;
2558 /* ran out of input, ended the headers, or filled up the headers buf */
2559 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2561 m = lws_write(wsi, (unsigned char *)start,
2562 p - start, LWS_WRITE_HTTP_HEADERS);
2564 lwsl_debug("%s: write says %d\n", __func__, m);
2567 /* writeability becomes uncertain now we wrote
2568 * something, we must return to the event loop
2575 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2576 start, sizeof(buf) - LWS_PRE);
2578 if (n < 0 && errno != EAGAIN) {
2579 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2583 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2584 //lwsl_notice("write %d\n", m);
2586 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2589 wsi->cgi->content_length_seen += m;
2595 LWS_VISIBLE LWS_EXTERN int
2596 lws_cgi_kill(struct lws *wsi)
2598 struct lws_cgi_args args;
2601 lwsl_debug("%s: %p\n", __func__, wsi);
2606 if (wsi->cgi->pid > 0) {
2607 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2609 lwsl_debug("%s: PID %d reaped\n", __func__,
2613 /* kill the process group */
2614 n = kill(-wsi->cgi->pid, SIGTERM);
2615 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2616 wsi->cgi->pid, n, errno);
2619 * hum seen errno=3 when process is listed in ps,
2620 * it seems we don't always retain process grouping
2622 * Direct these fallback attempt to the exact child
2624 n = kill(wsi->cgi->pid, SIGTERM);
2626 n = kill(wsi->cgi->pid, SIGPIPE);
2628 n = kill(wsi->cgi->pid, SIGKILL);
2630 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2631 __func__, wsi->cgi->pid, errno);
2635 /* He could be unkillable because he's a zombie */
2638 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2640 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2642 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2644 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2650 args.stdwsi = &wsi->cgi->stdwsi[0];
2652 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2653 wsi->protocol->callback,
2654 wsi, LWS_CALLBACK_CGI_TERMINATED,
2656 (void *)&args, 0)) {
2658 if (!wsi->cgi->being_closed)
2659 lws_close_free_wsi(wsi, 0);
2666 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2668 struct lws_cgi **pcgi, *cgi = NULL;
2672 /* find finished guys but don't reap yet */
2673 n = waitpid(-1, &status, WNOHANG);
2676 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
2678 pcgi = &pt->cgi_list;
2680 /* check all the subprocesses on the cgi list */
2682 /* get the next one first as list may change */
2684 pcgi = &(*pcgi)->cgi_list;
2689 /* wait for stdout to be drained */
2690 if (cgi->content_length > cgi->content_length_seen)
2693 if (cgi->content_length) {
2694 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2695 __func__, cgi->wsi, cgi->content_length_seen);
2699 waitpid(n, &status, WNOHANG);
2701 * he's already terminated so no need for kill()
2702 * but we should do the terminated cgi callback
2703 * and close him if he's not already closing
2705 if (n == cgi->pid) {
2706 lwsl_debug("%s: found PID %d on cgi list\n",
2709 if (!cgi->content_length) {
2711 * well, if he sends chunked... give him 5s after the
2712 * cgi terminated to send buffered
2714 cgi->chunked_grace++;
2720 lws_cgi_kill(cgi->wsi);
2726 /* if not found on the cgi list, as he's one of ours, reap */
2728 lwsl_debug("%s: reading PID %d although no cgi match\n",
2730 waitpid(n, &status, WNOHANG);
2734 /* disable this to confirm timeout cgi cleanup flow */
2736 pcgi = &pt->cgi_list;
2738 /* check all the subprocesses on the cgi list */
2740 /* get the next one first as list may change */
2742 pcgi = &(*pcgi)->cgi_list;
2747 /* we deferred killing him after reaping his PID */
2748 if (cgi->chunked_grace) {
2749 cgi->chunked_grace++;
2750 if (cgi->chunked_grace < 5)
2755 /* wait for stdout to be drained */
2756 if (cgi->content_length > cgi->content_length_seen)
2759 if (cgi->content_length)
2760 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2761 __func__, cgi->wsi, cgi->content_length_seen);
2764 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2766 if (!cgi->content_length) {
2768 * well, if he sends chunked... give him 5s after the
2769 * cgi terminated to send buffered
2771 cgi->chunked_grace++;
2775 lwsl_debug("%s: found PID %d on cgi list\n",
2776 __func__, cgi->pid);
2779 lws_cgi_kill(cgi->wsi);
2786 /* general anti zombie defence */
2787 // n = waitpid(-1, &status, WNOHANG);
2789 // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
2795 #ifdef LWS_NO_EXTENSIONS
2797 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2798 const char *opt_name, const char *opt_val)
2804 #ifdef LWS_WITH_ACCESS_LOG
2806 lws_access_log(struct lws *wsi)
2808 char *p = wsi->access_log.user_agent, ass[512];
2811 if (!wsi->access_log_pending)
2814 if (!wsi->access_log.header_log)
2820 l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
2821 wsi->access_log.header_log,
2822 wsi->access_log.response, wsi->access_log.sent, p);
2824 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
2825 if (write(wsi->vhost->log_fd, ass, l) != l)
2826 lwsl_err("Failed to write log\n");
2828 lwsl_err("%s", ass);
2830 if (wsi->access_log.header_log) {
2831 lws_free(wsi->access_log.header_log);
2832 wsi->access_log.header_log = NULL;
2834 if (wsi->access_log.user_agent) {
2835 lws_free(wsi->access_log.user_agent);
2836 wsi->access_log.user_agent = NULL;
2838 wsi->access_log_pending = 0;
2845 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
2847 const struct lws_vhost *vh = ctx->vhost_list;
2851 cs->rx += vh->conn_stats.rx;
2852 cs->tx += vh->conn_stats.tx;
2853 cs->conn += vh->conn_stats.conn;
2854 cs->trans += vh->conn_stats.trans;
2855 cs->ws_upg += vh->conn_stats.ws_upg;
2856 cs->http2_upg += vh->conn_stats.http2_upg;
2857 cs->rejected += vh->conn_stats.rejected;
2859 vh = vh->vhost_next;
2863 #ifdef LWS_WITH_SERVER_STATUS
2866 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
2868 static const char * const prots[] = {
2877 char *orig = buf, *end = buf + len - 1, first = 1;
2883 buf += lws_snprintf(buf, end - buf,
2884 "{\n \"name\":\"%s\",\n"
2885 " \"port\":\"%d\",\n"
2886 " \"use_ssl\":\"%d\",\n"
2887 " \"sts\":\"%d\",\n"
2888 " \"rx\":\"%llu\",\n"
2889 " \"tx\":\"%llu\",\n"
2890 " \"conn\":\"%lu\",\n"
2891 " \"trans\":\"%lu\",\n"
2892 " \"ws_upg\":\"%lu\",\n"
2893 " \"rejected\":\"%lu\",\n"
2894 " \"http2_upg\":\"%lu\""
2896 vh->name, vh->listen_port,
2897 #ifdef LWS_OPENSSL_SUPPORT
2902 !!(vh->options & LWS_SERVER_OPTION_STS),
2903 vh->conn_stats.rx, vh->conn_stats.tx,
2904 vh->conn_stats.conn, vh->conn_stats.trans,
2905 vh->conn_stats.ws_upg,
2906 vh->conn_stats.rejected,
2907 vh->conn_stats.http2_upg
2910 if (vh->mount_list) {
2911 const struct lws_http_mount *m = vh->mount_list;
2913 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
2916 buf += lws_snprintf(buf, end - buf, ",");
2917 buf += lws_snprintf(buf, end - buf,
2918 "\n {\n \"mountpoint\":\"%s\",\n"
2919 " \"origin\":\"%s%s\",\n"
2920 " \"cache_max_age\":\"%d\",\n"
2921 " \"cache_reuse\":\"%d\",\n"
2922 " \"cache_revalidate\":\"%d\",\n"
2923 " \"cache_intermediaries\":\"%d\"\n"
2926 prots[m->origin_protocol],
2930 m->cache_revalidate,
2931 m->cache_intermediaries);
2933 buf += lws_snprintf(buf, end - buf,
2934 ",\n \"default\":\"%s\"",
2936 buf += lws_snprintf(buf, end - buf, "\n }");
2940 buf += lws_snprintf(buf, end - buf, "\n ]");
2943 if (vh->protocols) {
2947 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
2948 while (n < vh->count_protocols) {
2950 buf += lws_snprintf(buf, end - buf, ",");
2951 buf += lws_snprintf(buf, end - buf,
2953 " \"status\":\"ok\"\n }\n }"
2955 vh->protocols[n].name);
2959 buf += lws_snprintf(buf, end - buf, "\n ]");
2962 buf += lws_snprintf(buf, end - buf, "\n}");
2968 LWS_EXTERN LWS_VISIBLE int
2969 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
2972 char *orig = buf, *end = buf + len - 1, first = 1;
2973 const struct lws_vhost *vh = context->vhost_list;
2974 const struct lws_context_per_thread *pt;
2975 time_t t = time(NULL);
2976 int n, listening = 0, cgi_count = 0;
2977 struct lws_conn_stats cs;
2980 struct lws_cgi * const *pcgi;
2983 #ifdef LWS_USE_LIBUV
2987 buf += lws_snprintf(buf, end - buf, "{ "
2988 "\"version\":\"%s\",\n"
2989 "\"uptime\":\"%ld\",\n",
2990 lws_get_library_version(),
2993 #ifdef LWS_HAVE_GETLOADAVG
2998 m = getloadavg(d, 3);
2999 for (n = 0; n < m; n++) {
3000 buf += lws_snprintf(buf, end - buf,
3001 "\"l%d\":\"%.2f\",\n",
3007 buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
3009 buf += lws_snprintf(buf, end - buf, "{ "
3010 "\"context_uptime\":\"%ld\",\n"
3011 "\"cgi_spawned\":\"%d\",\n"
3012 "\"pt_fd_max\":\"%d\",\n"
3013 "\"ah_pool_max\":\"%d\",\n"
3014 "\"deprecated\":\"%d\",\n"
3015 "\"wsi_alive\":\"%d\",\n",
3016 (unsigned long)(t - context->time_up),
3017 context->count_cgi_spawned,
3018 context->fd_limit_per_thread,
3019 context->max_http_header_pool,
3020 context->deprecated,
3021 context->count_wsi_allocated);
3023 buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
3024 for (n = 0; n < context->count_threads; n++) {
3025 pt = &context->pt[n];
3027 buf += lws_snprintf(buf, end - buf, ",");
3028 buf += lws_snprintf(buf, end - buf,
3030 " \"fds_count\":\"%d\",\n"
3031 " \"ah_pool_inuse\":\"%d\",\n"
3032 " \"ah_wait_list\":\"%d\"\n"
3035 pt->ah_count_in_use,
3036 pt->ah_wait_list_length);
3039 buf += lws_snprintf(buf, end - buf, "]");
3041 buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3044 vh = context->vhost_list;
3046 cs = context->conn_stats;
3047 lws_sum_stats(context, &cs);
3054 buf += lws_json_dump_vhost(vh, buf, end - buf);
3059 vh = vh->vhost_next;
3062 buf += lws_snprintf(buf, end - buf,
3063 "],\n\"listen_wsi\":\"%d\",\n"
3064 " \"rx\":\"%llu\",\n"
3065 " \"tx\":\"%llu\",\n"
3066 " \"conn\":\"%lu\",\n"
3067 " \"trans\":\"%lu\",\n"
3068 " \"ws_upg\":\"%lu\",\n"
3069 " \"rejected\":\"%lu\",\n"
3070 " \"http2_upg\":\"%lu\"",
3072 cs.rx, cs.tx, cs.conn, cs.trans,
3073 cs.ws_upg, cs.rejected, cs.http2_upg);
3076 for (n = 0; n < context->count_threads; n++) {
3077 pt = &context->pt[n];
3078 pcgi = &pt->cgi_list;
3081 pcgi = &(*pcgi)->cgi_list;
3087 buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3090 buf += lws_snprintf(buf, end - buf, "}");
3093 buf += lws_snprintf(buf, end - buf, "]}\n ");