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)
151 /* detach ourselves from parent's child list */
152 pwsi = &wsi->parent->child_list;
155 //lwsl_notice("%s: detach %p from parent %p\n",
156 // __func__, wsi, wsi->parent);
157 *pwsi = wsi->sibling_list;
160 pwsi = &(*pwsi)->sibling_list;
163 lwsl_err("%s: failed to detach from parent\n",
169 lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)
171 // if (wsi->protocol == p)
175 wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,
176 wsi->user_space, NULL, 0);
177 if (!wsi->user_space_externally_allocated)
178 lws_free_set_NULL(wsi->user_space);
184 if (lws_ensure_user_space(wsi))
187 if (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,
188 wsi->user_space, NULL, 0))
195 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
197 struct lws_context_per_thread *pt;
198 struct lws *wsi1, *wsi2;
199 struct lws_context *context;
200 struct lws_tokens eff_buf;
207 #if defined(LWS_WITH_ESP8266)
208 if (wsi->premature_rx)
209 lws_free(wsi->premature_rx);
211 if (wsi->pending_send_completion && !wsi->close_is_pending_send_completion) {
212 lwsl_notice("delaying close\n");
213 wsi->close_is_pending_send_completion = 1;
219 /* we're closing, losing some rx is OK */
220 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
222 context = wsi->context;
223 pt = &context->pt[(int)wsi->tsi];
225 /* if we have children, close them first */
226 if (wsi->child_list) {
227 wsi2 = wsi->child_list;
229 //lwsl_notice("%s: closing %p: close child %p\n",
230 // __func__, wsi, wsi2);
231 wsi1 = wsi2->sibling_list;
232 //lwsl_notice("%s: closing %p: next sibling %p\n",
233 // __func__, wsi2, wsi1);
235 /* stop it doing shutdown processing */
236 wsi2->socket_is_permanently_unusable = 1;
237 lws_close_free_wsi(wsi2, reason);
240 wsi->child_list = NULL;
243 if (wsi->mode == LWSCM_RAW_FILEDESC) {
244 lws_remove_child_from_any_parent(wsi);
245 remove_wsi_socket_from_fds(wsi);
246 wsi->protocol->callback(wsi,
247 LWS_CALLBACK_RAW_CLOSE_FILE,
248 wsi->user_space, NULL, 0);
253 if (wsi->mode == LWSCM_CGI) {
254 /* we are not a network connection, but a handler for CGI io */
255 if (wsi->parent && wsi->parent->cgi)
256 /* end the binding between us and master */
257 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
258 wsi->socket_is_permanently_unusable = 1;
260 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
261 goto just_kill_connection;
265 struct lws_cgi **pcgi = &pt->cgi_list;
266 /* remove us from the cgi list */
267 lwsl_debug("%s: remove cgi %p from list\n", __func__, wsi->cgi);
269 if (*pcgi == wsi->cgi) {
270 /* drop us from the pt cgi list */
271 *pcgi = (*pcgi)->cgi_list;
274 pcgi = &(*pcgi)->cgi_list;
276 /* we have a cgi going, we must kill it */
277 wsi->cgi->being_closed = 1;
282 if (wsi->mode == LWSCM_RAW) {
283 wsi->protocol->callback(wsi,
284 LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0);
285 wsi->socket_is_permanently_unusable = 1;
286 goto just_kill_connection;
289 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
290 wsi->u.http.fop_fd != NULL) {
291 lws_vfs_file_close(&wsi->u.http.fop_fd);
292 wsi->vhost->protocols->callback(wsi,
293 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
294 wsi->told_user_closed = 1;
296 if (wsi->socket_is_permanently_unusable ||
297 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
298 wsi->state == LWSS_SHUTDOWN)
299 goto just_kill_connection;
301 wsi->state_pre_close = wsi->state;
303 switch (wsi->state_pre_close) {
304 case LWSS_DEAD_SOCKET:
307 /* we tried the polite way... */
308 case LWSS_AWAITING_CLOSE_ACK:
309 goto just_kill_connection;
311 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
312 if (wsi->trunc_len) {
313 lws_callback_on_writable(wsi);
316 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
317 goto just_kill_connection;
319 if (wsi->trunc_len) {
320 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
321 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
322 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
328 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
329 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
330 goto just_kill_connection;
332 if (wsi->mode == LWSCM_HTTP_SERVING) {
334 wsi->vhost->protocols->callback(wsi,
335 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
336 wsi->user_space, NULL, 0);
337 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
338 wsi->user_space, NULL, 0);
339 wsi->told_user_closed = 1;
341 if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
342 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
343 wsi->user_space, NULL, 0);
344 wsi->told_user_closed = 1;
348 * are his extensions okay with him closing? Eg he might be a mux
349 * parent and just his ch1 aspect is closing?
352 if (lws_ext_cb_active(wsi,
353 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
354 lwsl_ext("extension vetoed close\n");
359 * flush any tx pending from extensions, since we may send close packet
360 * if there are problems with send, just nuke the connection
365 eff_buf.token = NULL;
366 eff_buf.token_len = 0;
368 /* show every extension the new incoming data */
370 m = lws_ext_cb_active(wsi,
371 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
373 lwsl_ext("Extension reports fatal error\n");
374 goto just_kill_connection;
378 * at least one extension told us he has more
379 * to spill, so we will go around again after
383 /* assuming they left us something to send, send it */
385 if (eff_buf.token_len)
386 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
387 eff_buf.token_len) !=
389 lwsl_debug("close: ext spill failed\n");
390 goto just_kill_connection;
395 * signal we are closing, lws_write will
396 * add any necessary version-specific stuff. If the write fails,
397 * no worries we are closing anyway. If we didn't initiate this
398 * close, then our state has been changed to
399 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
401 * Likewise if it's a second call to close this connection after we
402 * sent the close indication to the peer already, we are in state
403 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
406 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
407 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
408 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
409 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
410 lwsl_debug("sending close indication...\n");
412 /* if no prepared close reason, use 1000 and no aux data */
413 if (!wsi->u.ws.close_in_ping_buffer_len) {
414 wsi->u.ws.close_in_ping_buffer_len = 2;
415 wsi->u.ws.ping_payload_buf[LWS_PRE] =
416 (reason >> 8) & 0xff;
417 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
421 #if defined (LWS_WITH_ESP8266)
422 wsi->close_is_pending_send_completion = 1;
424 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
425 wsi->u.ws.close_in_ping_buffer_len,
429 * we have sent a nice protocol level indication we
430 * now wish to close, we should not send anything more
432 wsi->state = LWSS_AWAITING_CLOSE_ACK;
435 * ...and we should wait for a reply for a bit
438 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
439 lwsl_debug("sent close indication, awaiting ack\n");
444 lwsl_info("close: sending close packet failed, hanging up\n");
446 /* else, the send failed and we should just hang up */
449 just_kill_connection:
451 lws_remove_child_from_any_parent(wsi);
454 /* manage the vhost same protocol list entry */
456 if (wsi->same_vh_protocol_prev) { // we are on the vh list
458 // make guy who pointed to us, point to what our next was pointing to
459 *wsi->same_vh_protocol_prev = wsi->same_vh_protocol_next;
461 // if we had a next guy...
462 if (wsi->same_vh_protocol_next)
463 // have him point back to our prev
464 wsi->same_vh_protocol_next->same_vh_protocol_prev =
465 wsi->same_vh_protocol_prev;
471 * Testing with ab shows that we have to stage the socket close when
472 * the system is under stress... shutdown any further TX, change the
473 * state to one that won't emit anything more, and wait with a timeout
474 * for the POLLIN to show a zero-size rx before coming back and doing
477 if (wsi->mode != LWSCM_RAW && wsi->state != LWSS_SHUTDOWN &&
478 wsi->state != LWSS_CLIENT_UNCONNECTED &&
479 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
480 !wsi->socket_is_permanently_unusable) {
481 #ifdef LWS_OPENSSL_SUPPORT
482 if (lws_is_ssl(wsi) && wsi->ssl)
484 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);
485 n = SSL_shutdown(wsi->ssl);
486 if (n == 0) /* Complete bidirectional SSL shutdown */
487 SSL_shutdown(wsi->ssl);
488 n = shutdown(wsi->desc.sockfd, SHUT_WR);
493 lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, (int)(long)wsi->desc.sockfd, wsi->state);
494 n = shutdown(wsi->desc.sockfd, SHUT_WR);
497 lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
499 // This causes problems with disconnection when the events are half closing connection
500 // FD_READ | FD_CLOSE (33)
502 /* libuv: no event available to guarantee completion */
503 if (!LWS_LIBUV_ENABLED(context)) {
505 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
506 wsi->state = LWSS_SHUTDOWN;
507 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
508 context->timeout_secs);
515 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
516 wsi, wsi->desc.sockfd);
518 #ifdef LWS_WITH_HTTP_PROXY
520 lws_rewrite_destroy(wsi->rw);
525 * we won't be servicing or receiving anything further from this guy
526 * delete socket from the internal poll list if still present
528 lws_ssl_remove_wsi_from_buffered_list(wsi);
530 lws_remove_from_timeout_list(wsi);
532 /* checking return redundant since we anyway close */
533 if (wsi->desc.sockfd != LWS_SOCK_INVALID)
534 remove_wsi_socket_from_fds(wsi);
536 #if defined(LWS_WITH_ESP8266)
537 espconn_disconnect(wsi->desc.sockfd);
540 wsi->state = LWSS_DEAD_SOCKET;
542 lws_free_set_NULL(wsi->rxflow_buffer);
544 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
545 wsi->mode == LWSCM_WS_SERVING ||
546 wsi->mode == LWSCM_WS_CLIENT) {
548 if (wsi->u.ws.rx_draining_ext) {
549 struct lws **w = &pt->rx_draining_ext_list;
551 wsi->u.ws.rx_draining_ext = 0;
552 /* remove us from context draining ext list */
555 *w = wsi->u.ws.rx_draining_ext_list;
558 w = &((*w)->u.ws.rx_draining_ext_list);
560 wsi->u.ws.rx_draining_ext_list = NULL;
563 if (wsi->u.ws.tx_draining_ext) {
564 struct lws **w = &pt->tx_draining_ext_list;
566 wsi->u.ws.tx_draining_ext = 0;
567 /* remove us from context draining ext list */
570 *w = wsi->u.ws.tx_draining_ext_list;
573 w = &((*w)->u.ws.tx_draining_ext_list);
575 wsi->u.ws.tx_draining_ext_list = NULL;
577 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
579 if (wsi->trunc_alloc)
580 /* not going to be completed... nuke it */
581 lws_free_set_NULL(wsi->trunc_alloc);
583 wsi->u.ws.ping_payload_len = 0;
584 wsi->u.ws.ping_pending_flag = 0;
587 /* tell the user it's all over for this guy */
589 if (wsi->mode != LWSCM_RAW && wsi->protocol && wsi->protocol->callback &&
590 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
591 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
592 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
593 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
594 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
595 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
597 if (wsi->user_space) {
598 lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s\n", __func__, wsi, wsi->protocol->name);
599 wsi->protocol->callback(wsi,
600 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
601 wsi->user_space, NULL, 0);
603 lwsl_debug("calling back CLOSED\n");
604 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
605 wsi->user_space, NULL, 0);
606 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
607 lwsl_debug("calling back CLOSED_HTTP\n");
608 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
609 wsi->user_space, NULL, 0 );
610 } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
611 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
612 !wsi->already_did_cce) {
613 wsi->vhost->protocols[0].callback(wsi,
614 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
615 wsi->user_space, NULL, 0);
617 lwsl_debug("not calling back closed mode=%d state=%d\n",
618 wsi->mode, wsi->state_pre_close);
620 /* deallocate any active extension contexts */
622 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
623 lwsl_warn("extension destruction failed\n");
625 * inform all extensions in case they tracked this guy out of band
626 * even though not active on him specifically
628 if (lws_ext_cb_all_exts(context, wsi,
629 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
630 lwsl_warn("ext destroy wsi failed\n");
633 wsi->socket_is_permanently_unusable = 1;
636 if (LWS_LIBUV_ENABLED(context)) {
637 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
638 /* libuv has to do his own close handle processing asynchronously */
639 lws_libuv_closehandle(wsi);
645 lws_close_free_wsi_final(wsi);
649 lws_close_free_wsi_final(struct lws *wsi)
653 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->desc.sockfd)) {
655 //lwsl_err("*** closing sockfd %d\n", wsi->desc.sockfd);
656 n = compatible_close(wsi->desc.sockfd);
658 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
661 compatible_close(wsi->desc.sockfd);
664 wsi->desc.sockfd = LWS_SOCK_INVALID;
667 /* outermost destroy notification for wsi (user_space still intact) */
668 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
669 wsi->user_space, NULL, 0);
673 for (n = 0; n < 6; n++) {
674 if (wsi->cgi->pipe_fds[n / 2][n & 1] == 0)
675 lwsl_err("ZERO FD IN CGI CLOSE");
677 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
678 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
688 LWS_VISIBLE LWS_EXTERN const char *
689 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
691 int n = 0, sl = strlen(name);
693 while (lws_hdr_copy_fragment(wsi, buf, len,
694 WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
696 if (!strncmp(buf, name, sl))
705 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
707 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
711 ipv6 = LWS_IPV6_ENABLED(vh);
715 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
719 #ifndef LWS_PLAT_OPTEE
722 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
723 int name_len, char *rip, int rip_len)
726 struct addrinfo ai, *res;
727 struct sockaddr_in addr4;
732 addr4.sin_family = AF_UNSPEC;
735 if (LWS_IPV6_ENABLED(vh)) {
736 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
737 lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
741 // Strip off the IPv4 to IPv6 header if one exists
742 if (strncmp(rip, "::ffff:", 7) == 0)
743 memmove(rip, rip + 7, strlen(rip) - 6);
745 getnameinfo((struct sockaddr *)ads,
746 sizeof(struct sockaddr_in6), name,
747 name_len, NULL, 0, 0);
753 struct addrinfo *result;
755 memset(&ai, 0, sizeof ai);
756 ai.ai_family = PF_UNSPEC;
757 ai.ai_socktype = SOCK_STREAM;
758 ai.ai_flags = AI_CANONNAME;
759 #if !defined(LWS_WITH_ESP32)
760 if (getnameinfo((struct sockaddr *)ads,
761 sizeof(struct sockaddr_in),
762 name, name_len, NULL, 0, 0))
768 if (getaddrinfo(name, NULL, &ai, &result))
772 while (addr4.sin_family == AF_UNSPEC && res) {
773 switch (res->ai_family) {
775 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
776 addr4.sin_family = AF_INET;
782 freeaddrinfo(result);
785 if (addr4.sin_family == AF_UNSPEC)
788 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
806 LWS_VISIBLE const char *
807 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
812 struct sockaddr_in6 sin6;
814 struct sockaddr_in sin4;
819 if (LWS_IPV6_ENABLED(wsi->vhost)) {
833 if (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {
834 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
838 return lws_plat_inet_ntop(af, q, name, namelen);
840 #if defined(LWS_WITH_ESP8266)
841 return lws_plat_get_peer_simple(wsi, name, namelen);
850 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
851 int name_len, char *rip, int rip_len)
853 #ifndef LWS_PLAT_OPTEE
857 struct sockaddr_in6 sin6;
859 struct sockaddr_in sin4;
860 struct lws_context *context = wsi->context;
867 lws_latency_pre(context, wsi);
870 if (LWS_IPV6_ENABLED(wsi->vhost)) {
880 if (getpeername(fd, p, &len) < 0) {
881 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
885 ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
888 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
901 lws_context_user(struct lws_context *context)
903 return context->user_space;
906 LWS_VISIBLE struct lws_vhost *
907 lws_vhost_get(struct lws *wsi)
912 LWS_VISIBLE struct lws_vhost *
913 lws_get_vhost(struct lws *wsi)
918 LWS_VISIBLE const struct lws_protocols *
919 lws_protocol_get(struct lws *wsi)
921 return wsi->protocol;
924 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
925 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
929 for (n = 0; n < vh->count_protocols; n++)
930 if (!strcmp(name, vh->protocols[n].name))
931 return &vh->protocols[n];
937 lws_callback_all_protocol(struct lws_context *context,
938 const struct lws_protocols *protocol, int reason)
940 struct lws_context_per_thread *pt = &context->pt[0];
941 unsigned int n, m = context->count_threads;
945 for (n = 0; n < pt->fds_count; n++) {
946 wsi = wsi_from_fd(context, pt->fds[n].fd);
949 if (wsi->protocol == protocol)
950 protocol->callback(wsi, reason, wsi->user_space,
960 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
961 const struct lws_protocols *protocol, int reason)
963 struct lws_context *context = vh->context;
964 struct lws_context_per_thread *pt = &context->pt[0];
965 unsigned int n, m = context->count_threads;
969 for (n = 0; n < pt->fds_count; n++) {
970 wsi = wsi_from_fd(context, pt->fds[n].fd);
973 if (wsi->vhost == vh && wsi->protocol == protocol)
974 protocol->callback(wsi, reason, wsi->user_space,
983 LWS_VISIBLE LWS_EXTERN int
984 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
988 for (n = 0; n < wsi->vhost->count_protocols; n++)
989 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
995 LWS_VISIBLE LWS_EXTERN void
996 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)
998 context->fops = fops;
1001 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1002 lws_vfs_tell(lws_fop_fd_t fop_fd)
1007 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1008 lws_vfs_get_length(lws_fop_fd_t fop_fd)
1013 LWS_VISIBLE LWS_EXTERN uint32_t
1014 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd)
1016 return fop_fd->mod_time;
1019 LWS_VISIBLE lws_fileofs_t
1020 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1023 lwsl_debug("%s: seeking to %ld, len %ld\n", __func__, (long)offset, (long)fop_fd->len);
1024 ofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);
1025 lwsl_debug("%s: result %ld, fop_fd pos %ld\n", __func__, (long)ofs, (long)fop_fd->pos);
1030 LWS_VISIBLE lws_fileofs_t
1031 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1033 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len + fop_fd->pos + offset);
1037 const struct lws_plat_file_ops *
1038 lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,
1041 const struct lws_plat_file_ops *pf;
1042 const char *p = vfs_path;
1047 /* no non-platform fops, just use that */
1053 * scan the vfs path looking for indications we are to be
1054 * handled by a specific fops
1062 /* the first one is always platform fops, so skip */
1066 while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {
1067 if (p >= vfs_path + pf->fi[n].len)
1068 if (!strncmp(p - (pf->fi[n].len - 1),
1070 pf->fi[n].len - 1)) {
1085 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
1086 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
1087 lws_fop_flags_t *flags)
1089 const char *vpath = "";
1090 const struct lws_plat_file_ops *selected = lws_vfs_select_fops(
1091 fops, vfs_path, &vpath);
1093 return selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);
1098 * lws_now_secs() - seconds since 1970-1-1
1101 LWS_VISIBLE LWS_EXTERN unsigned long
1106 gettimeofday(&tv, NULL);
1115 lws_get_socket_fd(struct lws *wsi)
1117 return wsi->desc.sockfd;
1124 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
1125 int ret, int completed)
1127 unsigned long long u;
1130 u = time_in_microseconds();
1133 wsi->latency_start = u;
1134 if (!wsi->action_start)
1135 wsi->action_start = u;
1139 if (wsi->action_start == wsi->latency_start)
1141 "Completion first try lat %lluus: %p: ret %d: %s\n",
1142 u - wsi->latency_start,
1143 (void *)wsi, ret, action);
1146 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1147 u - wsi->action_start,
1148 u - wsi->latency_start,
1149 (void *)wsi, ret, action);
1150 wsi->action_start = 0;
1152 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1153 u - wsi->latency_start, (void *)wsi, ret, action);
1155 if (u - wsi->latency_start > context->worst_latency) {
1156 context->worst_latency = u - wsi->latency_start;
1157 strcpy(context->worst_latency_info, buf);
1159 lwsl_latency("%s", buf);
1164 lws_rx_flow_control(struct lws *wsi, int enable)
1166 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1169 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1170 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1176 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1177 const struct lws_protocols *protocol)
1179 const struct lws_context_per_thread *pt = &context->pt[0];
1181 unsigned int n, m = context->count_threads;
1184 for (n = 0; n < pt->fds_count; n++) {
1185 wsi = wsi_from_fd(context, pt->fds[n].fd);
1188 if (wsi->protocol == protocol)
1189 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1195 LWS_VISIBLE extern const char *
1196 lws_canonical_hostname(struct lws_context *context)
1198 return (const char *)context->canonical_hostname;
1201 int user_callback_handle_rxflow(lws_callback_function callback_function,
1203 enum lws_callback_reasons reason, void *user,
1204 void *in, size_t len)
1208 n = callback_function(wsi, reason, user, in, len);
1210 n = _lws_rx_flow_control(wsi);
1215 #if defined(LWS_WITH_ESP8266)
1217 #define strchr ets_strchr
1221 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1223 #if !defined(LWS_WITH_ESP8266)
1225 char authstring[96];
1230 /* we have to deal with a possible redundant leading http:// */
1231 if (!strncmp(proxy, "http://", 7))
1234 p = strchr(proxy, '@');
1235 if (p) { /* auth is around */
1237 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1240 strncpy(authstring, proxy, p - proxy);
1241 // null termination not needed on input
1242 if (lws_b64_encode_string(authstring, (p - proxy),
1243 vhost->proxy_basic_auth_token,
1244 sizeof vhost->proxy_basic_auth_token) < 0)
1247 lwsl_info(" Proxy auth in use\n");
1251 vhost->proxy_basic_auth_token[0] = '\0';
1253 strncpy(vhost->http_proxy_address, proxy,
1254 sizeof(vhost->http_proxy_address) - 1);
1255 vhost->http_proxy_address[
1256 sizeof(vhost->http_proxy_address) - 1] = '\0';
1258 p = strchr(vhost->http_proxy_address, ':');
1259 if (!p && !vhost->http_proxy_port) {
1260 lwsl_err("http_proxy needs to be ads:port\n");
1266 vhost->http_proxy_port = atoi(p + 1);
1270 lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1271 vhost->http_proxy_port);
1276 lwsl_err("proxy auth too long\n");
1281 LWS_VISIBLE const struct lws_protocols *
1282 lws_get_protocol(struct lws *wsi)
1284 return wsi->protocol;
1288 lws_is_final_fragment(struct lws *wsi)
1290 lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1291 wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1292 (long)wsi->u.ws.rx_draining_ext);
1293 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1296 LWS_VISIBLE unsigned char
1297 lws_get_reserved_bits(struct lws *wsi)
1299 return wsi->u.ws.rsv;
1303 lws_ensure_user_space(struct lws *wsi)
1305 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1309 /* allocate the per-connection user memory (if any) */
1311 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1312 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1313 if (wsi->user_space == NULL) {
1314 lwsl_err("Out of memory for conn user space\n");
1318 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1319 __func__, wsi, (long)wsi->protocol->per_session_data_size,
1325 lwsl_timestamp(int level, char *p, int len)
1327 #ifndef LWS_PLAT_OPTEE
1328 time_t o_now = time(NULL);
1329 unsigned long long now;
1330 struct tm *ptm = NULL;
1338 ptm = localtime(&o_now);
1340 if (localtime_r(&o_now, &tm))
1345 for (n = 0; n < LLL_COUNT; n++) {
1346 if (level != (1 << n))
1348 now = time_in_microseconds() / 100;
1350 n = lws_snprintf(p, len,
1351 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1352 ptm->tm_year + 1900,
1358 (int)(now % 10000), log_level_names[n]);
1360 n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1361 (unsigned long long) now / 10000,
1362 (int)(now % 10000), log_level_names[n]);
1369 #ifndef LWS_PLAT_OPTEE
1370 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1372 #if !defined(LWS_WITH_ESP8266)
1375 lwsl_timestamp(level, buf, sizeof(buf));
1376 fprintf(stderr, "%s%s", buf, line);
1381 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1383 #if defined(LWS_WITH_ESP8266)
1390 if (!(log_level & filter))
1393 n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1395 #if defined(LWS_WITH_ESP8266)
1396 buf[sizeof(buf) - 1] = '\0';
1398 /* vnsprintf returns what it would have written, even if truncated */
1399 if (n > sizeof(buf) - 1)
1400 n = sizeof(buf) - 1;
1405 lwsl_emit(filter, buf);
1408 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1412 va_start(ap, format);
1413 _lws_logv(filter, format, ap);
1417 LWS_VISIBLE void lws_set_log_level(int level,
1418 void (*func)(int level, const char *line))
1425 LWS_VISIBLE int lwsl_visible(int level)
1427 return log_level & level;
1431 lws_is_ssl(struct lws *wsi)
1433 #ifdef LWS_OPENSSL_SUPPORT
1434 return wsi->use_ssl;
1441 #ifdef LWS_OPENSSL_SUPPORT
1443 lws_get_ssl(struct lws *wsi)
1450 lws_partial_buffered(struct lws *wsi)
1452 return !!wsi->trunc_len;
1455 void lws_set_protocol_write_pending(struct lws *wsi,
1456 enum lws_pending_protocol_send pend)
1458 lwsl_info("setting pps %d\n", pend);
1461 lwsl_err("pps overwrite\n");
1463 lws_rx_flow_control(wsi, 0);
1464 lws_callback_on_writable(wsi);
1468 lws_get_peer_write_allowance(struct lws *wsi)
1470 #ifdef LWS_USE_HTTP2
1471 /* only if we are using HTTP2 on this connection */
1472 if (wsi->mode != LWSCM_HTTP2_SERVING)
1474 /* user is only interested in how much he can send, or that he can't */
1475 if (wsi->u.http2.tx_credit <= 0)
1478 return wsi->u.http2.tx_credit;
1486 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1488 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1489 memset(&wsi->u, 0, sizeof(wsi->u));
1493 LWS_VISIBLE struct lws_plat_file_ops *
1494 lws_get_fops(struct lws_context *context)
1496 return (struct lws_plat_file_ops *)context->fops;
1499 LWS_VISIBLE LWS_EXTERN struct lws_context *
1500 lws_get_context(const struct lws *wsi)
1502 return wsi->context;
1505 LWS_VISIBLE LWS_EXTERN int
1506 lws_get_count_threads(struct lws_context *context)
1508 return context->count_threads;
1511 LWS_VISIBLE LWS_EXTERN void *
1512 lws_wsi_user(struct lws *wsi)
1514 return wsi->user_space;
1517 LWS_VISIBLE LWS_EXTERN void
1518 lws_set_wsi_user(struct lws *wsi, void *data)
1520 if (wsi->user_space_externally_allocated)
1521 wsi->user_space = data;
1523 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1527 LWS_VISIBLE LWS_EXTERN struct lws *
1528 lws_get_parent(const struct lws *wsi)
1533 LWS_VISIBLE LWS_EXTERN struct lws *
1534 lws_get_child(const struct lws *wsi)
1536 return wsi->child_list;
1539 LWS_VISIBLE LWS_EXTERN void
1540 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1541 unsigned char *buf, size_t len)
1543 unsigned char *p, *start;
1544 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1546 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1548 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1550 *p++ = (((int)status) >> 8) & 0xff;
1551 *p++ = ((int)status) & 0xff;
1554 while (len-- && p < start + budget)
1557 wsi->u.ws.close_in_ping_buffer_len = p - start;
1561 _lws_rx_flow_control(struct lws *wsi)
1563 struct lws *wsic = wsi->child_list;
1565 /* if he has children, do those if they were changed */
1567 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1568 _lws_rx_flow_control(wsic);
1570 wsic = wsic->sibling_list;
1573 /* there is no pending change */
1574 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1575 lwsl_debug("%s: no pending change\n", __func__);
1579 /* stuff is still buffered, not ready to really accept new input */
1580 if (wsi->rxflow_buffer) {
1581 /* get ourselves called back to deal with stashed buffer */
1582 lws_callback_on_writable(wsi);
1586 /* pending is cleared, we can change rxflow state */
1588 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1590 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1591 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1593 /* adjust the pollfd for this wsi */
1595 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1596 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1597 lwsl_info("%s: fail\n", __func__);
1601 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1608 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1610 static const unsigned char e0f4[] = {
1611 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1612 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1613 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1614 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1615 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1616 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1617 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1618 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1619 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1620 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1621 0x80 | ((4 - 1) << 2) | 1, /* ea */
1622 0x80 | ((4 - 1) << 2) | 1, /* eb */
1623 0x80 | ((4 - 1) << 2) | 1, /* ec */
1624 0x80 | ((2 - 1) << 2) | 1, /* ed */
1625 0x80 | ((4 - 1) << 2) | 1, /* ee */
1626 0x80 | ((4 - 1) << 2) | 1, /* ef */
1627 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1628 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1629 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1630 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1631 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1634 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1635 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1637 unsigned char s = *state;
1640 unsigned char c = *buf++;
1644 if (c < 0xc2 || c > 0xf4)
1647 s = 0x80 | ((4 - 1) << 2);
1652 if (c < (s & 0xf0) ||
1653 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1655 s = e0f4[21 + (s & 3)];
1664 LWS_VISIBLE LWS_EXTERN int
1665 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1669 static const char *slash = "/";
1671 /* cut up the location into address, port and path */
1673 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1684 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1686 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1692 while (*p && *p != ']')
1699 while (*p && *p != ':' && *p != '/')
1705 while (*p && *p != '/')
1718 #ifdef LWS_NO_EXTENSIONS
1720 /* we need to provide dummy callbacks for internal exts
1721 * so user code runs when faced with a lib compiled with
1722 * extensions disabled.
1726 lws_extension_callback_pm_deflate(struct lws_context *context,
1727 const struct lws_extension *ext,
1729 enum lws_extension_callback_reasons reason,
1730 void *user, void *in, size_t len)
1745 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1749 #ifdef LWS_USE_UNIX_SOCK
1750 struct sockaddr_un serv_unix;
1753 struct sockaddr_in6 serv_addr6;
1755 struct sockaddr_in serv_addr4;
1756 #ifndef LWS_PLAT_OPTEE
1757 socklen_t len = sizeof(struct sockaddr);
1760 struct sockaddr_in sin;
1763 #ifdef LWS_USE_UNIX_SOCK
1764 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1765 v = (struct sockaddr *)&serv_unix;
1766 n = sizeof(struct sockaddr_un);
1767 bzero((char *) &serv_unix, sizeof(serv_unix));
1768 serv_unix.sun_family = AF_UNIX;
1769 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1770 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1774 strcpy(serv_unix.sun_path, iface);
1775 if (serv_unix.sun_path[0] == '@')
1776 serv_unix.sun_path[0] = '\0';
1780 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1781 if (LWS_IPV6_ENABLED(vhost)) {
1782 v = (struct sockaddr *)&serv_addr6;
1783 n = sizeof(struct sockaddr_in6);
1784 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1786 interface_to_sa(vhost, iface,
1787 (struct sockaddr_in *)v, n) < 0) {
1788 lwsl_err("Unable to find interface %s\n", iface);
1793 struct ifaddrs *addrs, *addr;
1794 char ip[NI_MAXHOST];
1798 for (addr = addrs; addr; addr = addr->ifa_next) {
1799 if (!addr->ifa_addr ||
1800 addr->ifa_addr->sa_family != AF_INET6)
1803 getnameinfo(addr->ifa_addr,
1804 sizeof(struct sockaddr_in6),
1806 NULL, 0, NI_NUMERICHOST);
1810 if (ip[i++] == '%') {
1815 if (!strcmp(ip, iface)) {
1816 serv_addr6.sin6_scope_id =
1817 if_nametoindex(addr->ifa_name);
1824 serv_addr6.sin6_family = AF_INET6;
1825 serv_addr6.sin6_port = htons(port);
1829 v = (struct sockaddr *)&serv_addr4;
1830 n = sizeof(serv_addr4);
1831 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1832 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1833 serv_addr4.sin_family = AF_INET;
1834 #if !defined(LWS_WITH_ESP32)
1837 interface_to_sa(vhost, iface,
1838 (struct sockaddr_in *)v, n) < 0) {
1839 lwsl_err("Unable to find interface %s\n", iface);
1843 serv_addr4.sin_port = htons(port);
1846 n = bind(sockfd, v, n);
1847 #ifdef LWS_USE_UNIX_SOCK
1848 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
1849 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1850 sockfd, iface, n, LWS_ERRNO);
1855 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1856 sockfd, port, n, LWS_ERRNO);
1860 #ifndef LWS_PLAT_OPTEE
1861 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1862 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1865 port = ntohs(sin.sin_port);
1872 lws_restart_ws_ping_pong_timer(struct lws *wsi)
1874 if (!wsi->context->ws_ping_pong_interval)
1876 if (wsi->state != LWSS_ESTABLISHED)
1879 wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
1880 wsi->context->ws_ping_pong_interval;
1883 static const char *hex = "0123456789ABCDEF";
1885 LWS_VISIBLE LWS_EXTERN const char *
1886 lws_sql_purify(char *escaped, const char *string, int len)
1888 const char *p = string;
1891 while (*p && len-- > 2) {
1905 LWS_VISIBLE LWS_EXTERN const char *
1906 lws_json_purify(char *escaped, const char *string, int len)
1908 const char *p = string;
1916 while (*p && len-- > 6) {
1917 if (*p == '\"' || *p == '\\' || *p < 0x20) {
1922 *q++ = hex[((*p) >> 4) & 15];
1923 *q++ = hex[(*p) & 15];
1934 LWS_VISIBLE LWS_EXTERN const char *
1935 lws_urlencode(char *escaped, const char *string, int len)
1937 const char *p = string;
1940 while (*p && len-- > 3) {
1946 if ((*p >= '0' && *p <= '9') ||
1947 (*p >= 'A' && *p <= 'Z') ||
1948 (*p >= 'a' && *p <= 'z')) {
1953 *q++ = hex[(*p >> 4) & 0xf];
1954 *q++ = hex[*p & 0xf];
1964 LWS_VISIBLE LWS_EXTERN int
1965 lws_urldecode(char *string, const char *escaped, int len)
1970 while (*escaped && len) {
1973 if (*escaped == '%') {
1978 if (*escaped == '+') {
1984 *string++ = *escaped++;
1988 n = char_to_hex(*escaped);
1997 n = char_to_hex(*escaped);
2001 *string++ = sum | n;
2013 LWS_VISIBLE LWS_EXTERN int
2014 lws_finalize_startup(struct lws_context *context)
2016 struct lws_context_creation_info info;
2018 info.uid = context->uid;
2019 info.gid = context->gid;
2021 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2022 lws_plat_drop_app_privileges(&info);
2028 lws_snprintf(char *str, size_t size, const char *format, ...)
2036 va_start(ap, format);
2037 n = vsnprintf(str, size, format, ap);
2047 LWS_VISIBLE LWS_EXTERN int
2048 lws_is_cgi(struct lws *wsi) {
2059 urlencode(const char *in, int inlen, char *out, int outlen)
2061 char *start = out, *end = out + outlen;
2063 while (inlen-- && out < end - 4) {
2064 if ((*in >= 'A' && *in <= 'Z') ||
2065 (*in >= 'a' && *in <= 'z') ||
2066 (*in >= '0' && *in <= '9') ||
2080 *out++ = hex[(*in) >> 4];
2081 *out++ = hex[(*in++) & 15];
2092 lws_create_basic_wsi(struct lws_context *context, int tsi)
2094 struct lws *new_wsi;
2096 if ((unsigned int)context->pt[tsi].fds_count ==
2097 context->fd_limit_per_thread - 1) {
2098 lwsl_err("no space for new conn\n");
2102 new_wsi = lws_zalloc(sizeof(struct lws));
2103 if (new_wsi == NULL) {
2104 lwsl_err("Out of memory for new connection\n");
2109 new_wsi->context = context;
2110 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2111 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2113 /* initialize the instance struct */
2115 new_wsi->state = LWSS_CGI;
2116 new_wsi->mode = LWSCM_CGI;
2117 new_wsi->hdr_parsing_completed = 0;
2118 new_wsi->position_in_fds_table = -1;
2121 * these can only be set once the protocol is known
2122 * we set an unestablished connection's protocol pointer
2123 * to the start of the defauly vhost supported list, so it can look
2124 * for matching ones during the handshake
2126 new_wsi->protocol = context->vhost_list->protocols;
2127 new_wsi->user_space = NULL;
2128 new_wsi->ietf_spec_revision = 0;
2129 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2130 context->count_wsi_allocated++;
2135 LWS_VISIBLE LWS_EXTERN int
2136 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2137 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2139 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2140 char *env_array[30], cgi_path[400], e[1024], *p = e,
2141 *end = p + sizeof(e) - 1, tok[256], *t;
2142 struct lws_cgi *cgi;
2143 int n, m, i, uritok = -1;
2146 * give the master wsi a cgi struct
2149 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2151 lwsl_err("%s: OOM\n", __func__);
2156 cgi->wsi = wsi; /* set cgi's owning wsi */
2158 /* create pipes for [stdin|stdout] and [stderr] */
2160 for (n = 0; n < 3; n++)
2161 if (pipe(cgi->pipe_fds[n]) == -1)
2164 /* create cgi wsis for each stdin/out/err fd */
2166 for (n = 0; n < 3; n++) {
2167 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2168 if (!cgi->stdwsi[n])
2170 cgi->stdwsi[n]->cgi_channel = n;
2171 cgi->stdwsi[n]->vhost = wsi->vhost;
2173 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2174 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2176 /* read side is 0, stdin we want the write side, others read */
2177 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2178 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2179 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2184 for (n = 0; n < 3; n++) {
2185 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2186 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2188 cgi->stdwsi[n]->parent = wsi;
2189 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2190 wsi->child_list = cgi->stdwsi[n];
2193 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2194 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2195 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2197 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2198 cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2199 cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2200 cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2202 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2204 /* the cgi stdout is always sending us http1.x header data first */
2205 wsi->hdr_state = LCHS_HEADER;
2207 /* add us to the pt list of active cgis */
2208 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2209 cgi->cgi_list = pt->cgi_list;
2212 /* prepare his CGI env */
2216 if (lws_is_ssl(wsi))
2217 env_array[n++] = "HTTPS=ON";
2218 if (wsi->u.hdr.ah) {
2219 static const unsigned char meths[] = {
2222 WSI_TOKEN_OPTIONS_URI,
2224 WSI_TOKEN_PATCH_URI,
2225 WSI_TOKEN_DELETE_URI,
2227 static const char * const meth_names[] = {
2228 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2231 for (m = 0; m < ARRAY_SIZE(meths); m++)
2232 if (lws_hdr_total_length(wsi, meths[m]) >=
2233 script_uri_path_len) {
2241 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2242 lws_hdr_simple_ptr(wsi, uritok));
2243 cgi_path[sizeof(cgi_path) - 1] = '\0';
2244 env_array[n++] = cgi_path;
2247 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2252 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2253 /* dump the individual URI Arg parameters */
2256 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2257 WSI_TOKEN_HTTP_URI_ARGS, m);
2261 while (*t && *t != '=' && p < end - 4)
2265 i = urlencode(t, i- (t - tok), p, end - p);
2277 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2278 lws_hdr_simple_ptr(wsi, uritok) +
2279 script_uri_path_len);
2282 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2284 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2285 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2288 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2290 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2291 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2294 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2296 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2297 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2300 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2302 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2303 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2306 if (uritok == WSI_TOKEN_POST_URI) {
2307 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2309 p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2310 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2313 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2315 p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2316 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2321 p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2325 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2327 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2330 mp_cgienv = mp_cgienv->next;
2333 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2334 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2335 env_array[n] = NULL;
2338 for (m = 0; m < n; m++)
2339 lwsl_err(" %s\n", env_array[m]);
2343 * Actually having made the env, as a cgi we don't need the ah
2346 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
2347 lws_header_table_detach(wsi, 0);
2349 /* we are ready with the redirection pipes... run the thing */
2350 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2356 lwsl_err("fork failed, errno %d", errno);
2360 #if defined(__linux__)
2361 prctl(PR_SET_PDEATHSIG, SIGTERM);
2363 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2366 /* we are the parent process */
2367 wsi->context->count_cgi_spawned++;
2368 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2372 /* somewhere we can at least read things and enter it */
2374 lwsl_notice("%s: Failed to chdir\n", __func__);
2376 /* We are the forked process, redirect and kill inherited things.
2378 * Because of vfork(), we cannot do anything that changes pages in
2379 * the parent environment. Stuff that changes kernel state for the
2380 * process is OK. Stuff that happens after the execvpe() is OK.
2383 for (n = 0; n < 3; n++)
2384 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2385 lwsl_err("%s: stdin dup2 failed\n", __func__);
2389 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2390 for (m = 0; m < n; m++) {
2391 p = strchr(env_array[m], '=');
2393 setenv(env_array[m], p, 1);
2395 execvp(exec_array[0], (char * const *)&exec_array[0]);
2397 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2403 /* drop us from the pt cgi list */
2404 pt->cgi_list = cgi->cgi_list;
2407 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2409 for (n = 0; n < 3; n++)
2410 if (wsi->cgi->stdwsi[n])
2411 lws_free_wsi(cgi->stdwsi[n]);
2414 for (n = 0; n < 3; n++) {
2415 if (cgi->pipe_fds[n][0])
2416 close(cgi->pipe_fds[n][0]);
2417 if (cgi->pipe_fds[n][1])
2418 close(cgi->pipe_fds[n][1]);
2421 lws_free_set_NULL(wsi->cgi);
2423 lwsl_err("%s: failed\n", __func__);
2428 LWS_VISIBLE LWS_EXTERN int
2429 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2431 int n, m, match = 0, lp = 0;
2432 static const char * const content_length = "content-length: ";
2433 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2434 *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
2439 while (wsi->hdr_state != LHCS_PAYLOAD) {
2440 /* we have to separate header / finalize and
2441 * payload chunks, since they need to be
2442 * handled separately
2444 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2446 if (errno != EAGAIN) {
2447 lwsl_debug("%s: read says %d\n", __func__, n);
2454 lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
2455 switch (wsi->hdr_state) {
2457 if (!content_length[match] &&
2458 (c >= '0' && c <= '9') &&
2459 lp < sizeof(l) - 1) {
2462 wsi->cgi->content_length = atol(l);
2464 if (tolower(c) == content_length[match])
2469 /* some cgi only send us \x0a for EOL */
2471 wsi->hdr_state = LCHS_SINGLE_0A;
2476 wsi->hdr_state = LCHS_LF1;
2484 wsi->hdr_state = LCHS_CR2;
2487 /* we got \r[^\n]... it's unreasonable */
2488 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2494 wsi->hdr_state = LCHS_LF2;
2497 wsi->hdr_state = LCHS_HEADER;
2502 case LCHS_SINGLE_0A:
2505 lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
2506 wsi->hdr_state = LHCS_PAYLOAD;
2507 /* drop the \0xa ... finalize will add it if needed */
2508 if (lws_finalize_http_header(wsi,
2509 (unsigned char **)&p,
2510 (unsigned char *)end))
2515 /* we got \r\n\r[^\n]... it's unreasonable */
2517 /* we got \x0anext header, it's reasonable */
2519 wsi->hdr_state = LCHS_HEADER;
2526 /* ran out of input, ended the headers, or filled up the headers buf */
2527 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2529 m = lws_write(wsi, (unsigned char *)start,
2530 p - start, LWS_WRITE_HTTP_HEADERS);
2532 lwsl_debug("%s: write says %d\n", __func__, m);
2535 /* writeability becomes uncertain now we wrote
2536 * something, we must return to the event loop
2543 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2544 start, sizeof(buf) - LWS_PRE);
2546 if (n < 0 && errno != EAGAIN) {
2547 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2551 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2552 //lwsl_notice("write %d\n", m);
2554 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2557 wsi->cgi->content_length_seen += m;
2563 LWS_VISIBLE LWS_EXTERN int
2564 lws_cgi_kill(struct lws *wsi)
2566 struct lws_cgi_args args;
2569 lwsl_debug("%s: %p\n", __func__, wsi);
2574 if (wsi->cgi->pid > 0) {
2575 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2577 lwsl_debug("%s: PID %d reaped\n", __func__,
2581 /* kill the process group */
2582 n = kill(-wsi->cgi->pid, SIGTERM);
2583 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2584 wsi->cgi->pid, n, errno);
2587 * hum seen errno=3 when process is listed in ps,
2588 * it seems we don't always retain process grouping
2590 * Direct these fallback attempt to the exact child
2592 n = kill(wsi->cgi->pid, SIGTERM);
2594 n = kill(wsi->cgi->pid, SIGPIPE);
2596 n = kill(wsi->cgi->pid, SIGKILL);
2598 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2599 __func__, wsi->cgi->pid, errno);
2603 /* He could be unkillable because he's a zombie */
2606 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2608 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2610 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2612 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2618 args.stdwsi = &wsi->cgi->stdwsi[0];
2620 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2621 wsi->protocol->callback,
2622 wsi, LWS_CALLBACK_CGI_TERMINATED,
2624 (void *)&args, 0)) {
2626 if (!wsi->cgi->being_closed)
2627 lws_close_free_wsi(wsi, 0);
2634 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2636 struct lws_cgi **pcgi, *cgi = NULL;
2640 /* find finished guys but don't reap yet */
2641 n = waitpid(-1, &status, WNOHANG);
2644 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
2646 pcgi = &pt->cgi_list;
2648 /* check all the subprocesses on the cgi list */
2650 /* get the next one first as list may change */
2652 pcgi = &(*pcgi)->cgi_list;
2657 /* wait for stdout to be drained */
2658 if (cgi->content_length > cgi->content_length_seen)
2661 if (cgi->content_length) {
2662 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2663 __func__, cgi->wsi, cgi->content_length_seen);
2667 waitpid(n, &status, WNOHANG);
2669 * he's already terminated so no need for kill()
2670 * but we should do the terminated cgi callback
2671 * and close him if he's not already closing
2673 if (n == cgi->pid) {
2674 lwsl_debug("%s: found PID %d on cgi list\n",
2677 if (!cgi->content_length) {
2679 * well, if he sends chunked... give him 5s after the
2680 * cgi terminated to send buffered
2682 cgi->chunked_grace++;
2688 lws_cgi_kill(cgi->wsi);
2694 /* if not found on the cgi list, as he's one of ours, reap */
2696 lwsl_debug("%s: reading PID %d although no cgi match\n",
2698 waitpid(n, &status, WNOHANG);
2702 /* disable this to confirm timeout cgi cleanup flow */
2704 pcgi = &pt->cgi_list;
2706 /* check all the subprocesses on the cgi list */
2708 /* get the next one first as list may change */
2710 pcgi = &(*pcgi)->cgi_list;
2715 /* we deferred killing him after reaping his PID */
2716 if (cgi->chunked_grace) {
2717 cgi->chunked_grace++;
2718 if (cgi->chunked_grace < 5)
2723 /* wait for stdout to be drained */
2724 if (cgi->content_length > cgi->content_length_seen)
2727 if (cgi->content_length)
2728 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2729 __func__, cgi->wsi, cgi->content_length_seen);
2732 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2734 if (!cgi->content_length) {
2736 * well, if he sends chunked... give him 5s after the
2737 * cgi terminated to send buffered
2739 cgi->chunked_grace++;
2743 lwsl_debug("%s: found PID %d on cgi list\n",
2744 __func__, cgi->pid);
2747 lws_cgi_kill(cgi->wsi);
2754 /* general anti zombie defence */
2755 // n = waitpid(-1, &status, WNOHANG);
2757 // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
2763 #ifdef LWS_NO_EXTENSIONS
2765 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2766 const char *opt_name, const char *opt_val)
2772 #ifdef LWS_WITH_ACCESS_LOG
2774 lws_access_log(struct lws *wsi)
2776 char *p = wsi->access_log.user_agent, ass[512];
2779 if (!wsi->access_log_pending)
2782 if (!wsi->access_log.header_log)
2788 l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
2789 wsi->access_log.header_log,
2790 wsi->access_log.response, wsi->access_log.sent, p);
2792 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
2793 if (write(wsi->vhost->log_fd, ass, l) != l)
2794 lwsl_err("Failed to write log\n");
2796 lwsl_err("%s", ass);
2798 if (wsi->access_log.header_log) {
2799 lws_free(wsi->access_log.header_log);
2800 wsi->access_log.header_log = NULL;
2802 if (wsi->access_log.user_agent) {
2803 lws_free(wsi->access_log.user_agent);
2804 wsi->access_log.user_agent = NULL;
2806 wsi->access_log_pending = 0;
2813 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
2815 const struct lws_vhost *vh = ctx->vhost_list;
2819 cs->rx += vh->conn_stats.rx;
2820 cs->tx += vh->conn_stats.tx;
2821 cs->conn += vh->conn_stats.conn;
2822 cs->trans += vh->conn_stats.trans;
2823 cs->ws_upg += vh->conn_stats.ws_upg;
2824 cs->http2_upg += vh->conn_stats.http2_upg;
2825 cs->rejected += vh->conn_stats.rejected;
2827 vh = vh->vhost_next;
2831 #ifdef LWS_WITH_SERVER_STATUS
2834 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
2836 static const char * const prots[] = {
2845 char *orig = buf, *end = buf + len - 1, first = 1;
2851 buf += lws_snprintf(buf, end - buf,
2852 "{\n \"name\":\"%s\",\n"
2853 " \"port\":\"%d\",\n"
2854 " \"use_ssl\":\"%d\",\n"
2855 " \"sts\":\"%d\",\n"
2856 " \"rx\":\"%llu\",\n"
2857 " \"tx\":\"%llu\",\n"
2858 " \"conn\":\"%lu\",\n"
2859 " \"trans\":\"%lu\",\n"
2860 " \"ws_upg\":\"%lu\",\n"
2861 " \"rejected\":\"%lu\",\n"
2862 " \"http2_upg\":\"%lu\""
2864 vh->name, vh->listen_port,
2865 #ifdef LWS_OPENSSL_SUPPORT
2870 !!(vh->options & LWS_SERVER_OPTION_STS),
2871 vh->conn_stats.rx, vh->conn_stats.tx,
2872 vh->conn_stats.conn, vh->conn_stats.trans,
2873 vh->conn_stats.ws_upg,
2874 vh->conn_stats.rejected,
2875 vh->conn_stats.http2_upg
2878 if (vh->mount_list) {
2879 const struct lws_http_mount *m = vh->mount_list;
2881 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
2884 buf += lws_snprintf(buf, end - buf, ",");
2885 buf += lws_snprintf(buf, end - buf,
2886 "\n {\n \"mountpoint\":\"%s\",\n"
2887 " \"origin\":\"%s%s\",\n"
2888 " \"cache_max_age\":\"%d\",\n"
2889 " \"cache_reuse\":\"%d\",\n"
2890 " \"cache_revalidate\":\"%d\",\n"
2891 " \"cache_intermediaries\":\"%d\"\n"
2894 prots[m->origin_protocol],
2898 m->cache_revalidate,
2899 m->cache_intermediaries);
2901 buf += lws_snprintf(buf, end - buf,
2902 ",\n \"default\":\"%s\"",
2904 buf += lws_snprintf(buf, end - buf, "\n }");
2908 buf += lws_snprintf(buf, end - buf, "\n ]");
2911 if (vh->protocols) {
2915 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
2916 while (n < vh->count_protocols) {
2918 buf += lws_snprintf(buf, end - buf, ",");
2919 buf += lws_snprintf(buf, end - buf,
2921 " \"status\":\"ok\"\n }\n }"
2923 vh->protocols[n].name);
2927 buf += lws_snprintf(buf, end - buf, "\n ]");
2930 buf += lws_snprintf(buf, end - buf, "\n}");
2936 LWS_EXTERN LWS_VISIBLE int
2937 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
2940 char *orig = buf, *end = buf + len - 1, first = 1;
2941 const struct lws_vhost *vh = context->vhost_list;
2942 const struct lws_context_per_thread *pt;
2943 time_t t = time(NULL);
2944 int n, listening = 0, cgi_count = 0;
2945 struct lws_conn_stats cs;
2948 struct lws_cgi * const *pcgi;
2951 #ifdef LWS_USE_LIBUV
2955 buf += lws_snprintf(buf, end - buf, "{ "
2956 "\"version\":\"%s\",\n"
2957 "\"uptime\":\"%ld\",\n",
2958 lws_get_library_version(),
2961 #ifdef LWS_HAVE_GETLOADAVG
2966 m = getloadavg(d, 3);
2967 for (n = 0; n < m; n++) {
2968 buf += lws_snprintf(buf, end - buf,
2969 "\"l%d\":\"%.2f\",\n",
2975 buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
2977 buf += lws_snprintf(buf, end - buf, "{ "
2978 "\"context_uptime\":\"%ld\",\n"
2979 "\"cgi_spawned\":\"%d\",\n"
2980 "\"pt_fd_max\":\"%d\",\n"
2981 "\"ah_pool_max\":\"%d\",\n"
2982 "\"deprecated\":\"%d\",\n"
2983 "\"wsi_alive\":\"%d\",\n",
2984 (unsigned long)(t - context->time_up),
2985 context->count_cgi_spawned,
2986 context->fd_limit_per_thread,
2987 context->max_http_header_pool,
2988 context->deprecated,
2989 context->count_wsi_allocated);
2991 buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
2992 for (n = 0; n < context->count_threads; n++) {
2993 pt = &context->pt[n];
2995 buf += lws_snprintf(buf, end - buf, ",");
2996 buf += lws_snprintf(buf, end - buf,
2998 " \"fds_count\":\"%d\",\n"
2999 " \"ah_pool_inuse\":\"%d\",\n"
3000 " \"ah_wait_list\":\"%d\"\n"
3003 pt->ah_count_in_use,
3004 pt->ah_wait_list_length);
3007 buf += lws_snprintf(buf, end - buf, "]");
3009 buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3012 vh = context->vhost_list;
3014 cs = context->conn_stats;
3015 lws_sum_stats(context, &cs);
3022 buf += lws_json_dump_vhost(vh, buf, end - buf);
3027 vh = vh->vhost_next;
3030 buf += lws_snprintf(buf, end - buf,
3031 "],\n\"listen_wsi\":\"%d\",\n"
3032 " \"rx\":\"%llu\",\n"
3033 " \"tx\":\"%llu\",\n"
3034 " \"conn\":\"%lu\",\n"
3035 " \"trans\":\"%lu\",\n"
3036 " \"ws_upg\":\"%lu\",\n"
3037 " \"rejected\":\"%lu\",\n"
3038 " \"http2_upg\":\"%lu\"",
3040 cs.rx, cs.tx, cs.conn, cs.trans,
3041 cs.ws_upg, cs.rejected, cs.http2_upg);
3044 for (n = 0; n < context->count_threads; n++) {
3045 pt = &context->pt[n];
3046 pcgi = &pt->cgi_list;
3049 pcgi = &(*pcgi)->cgi_list;
3055 buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3058 buf += lws_snprintf(buf, end - buf, "}");
3061 buf += lws_snprintf(buf, end - buf, "]}\n ");