2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "private-libwebsockets.h"
24 #ifdef LWS_HAVE_SYS_TYPES_H
25 #include <sys/types.h>
28 #if defined(WIN32) || defined(_WIN32)
34 #if defined(WIN32) || defined(_WIN32)
41 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
42 static void (*lwsl_emit)(int level, const char *line)
43 #ifndef LWS_PLAT_OPTEE
47 #ifndef LWS_PLAT_OPTEE
48 static const char * const log_level_names[] = {
66 lws_free_wsi(struct lws *wsi)
71 /* Protocol user data may be allocated either internally by lws
72 * or by specified the user.
73 * We should only free what we allocated. */
74 if (wsi->protocol && wsi->protocol->per_session_data_size &&
75 wsi->user_space && !wsi->user_space_externally_allocated)
76 lws_free(wsi->user_space);
78 lws_free_set_NULL(wsi->rxflow_buffer);
79 lws_free_set_NULL(wsi->trunc_alloc);
81 /* we may not have an ah, but may be on the waiting list... */
82 lwsl_info("ah det due to close\n");
83 lws_header_table_detach(wsi, 0);
85 wsi->context->count_wsi_allocated--;
86 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
87 wsi->context->count_wsi_allocated);
93 lws_remove_from_timeout_list(struct lws *wsi)
95 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
97 if (!wsi->timeout_list_prev) /* ie, not part of the list */
101 /* if we have a next guy, set his prev to our prev */
102 if (wsi->timeout_list)
103 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
104 /* set our prev guy to our next guy instead of us */
105 *wsi->timeout_list_prev = wsi->timeout_list;
107 /* we're out of the list, we should not point anywhere any more */
108 wsi->timeout_list_prev = NULL;
109 wsi->timeout_list = NULL;
114 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
116 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
123 if (reason && !wsi->timeout_list_prev) {
124 /* our next guy is current first guy */
125 wsi->timeout_list = pt->timeout_list;
126 /* if there is a next guy, set his prev ptr to our next ptr */
127 if (wsi->timeout_list)
128 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
129 /* our prev ptr is first ptr */
130 wsi->timeout_list_prev = &pt->timeout_list;
131 /* set the first guy to be us */
132 *wsi->timeout_list_prev = wsi;
135 lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
136 wsi->pending_timeout_limit = now + secs;
137 wsi->pending_timeout = reason;
142 lws_remove_from_timeout_list(wsi);
146 lws_remove_child_from_any_parent(struct lws *wsi)
154 /* detach ourselves from parent's child list */
155 pwsi = &wsi->parent->child_list;
158 lwsl_info("%s: detach %p from parent %p\n",
159 __func__, wsi, wsi->parent);
160 *pwsi = wsi->sibling_list;
164 pwsi = &(*pwsi)->sibling_list;
167 lwsl_err("%s: failed to detach from parent\n", __func__);
173 lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)
175 // if (wsi->protocol == p)
177 const struct lws_protocols *vp = wsi->vhost->protocols, *vpo;
180 wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,
181 wsi->user_space, NULL, 0);
182 if (!wsi->user_space_externally_allocated)
183 lws_free_set_NULL(wsi->user_space);
185 lws_same_vh_protocol_remove(wsi);
191 if (lws_ensure_user_space(wsi))
194 if (p > vp && p < &vp[wsi->vhost->count_protocols])
195 lws_same_vh_protocol_insert(wsi, p - vp);
197 int n = wsi->vhost->count_protocols;
203 if (p->name && vp->name && !strcmp(p->name, vp->name)) {
205 lws_same_vh_protocol_insert(wsi, vp - vpo);
211 lwsl_err("%s: protocol %p is not in vhost %s protocols list\n",
212 __func__, p, wsi->vhost->name);
215 if (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,
216 wsi->user_space, NULL, 0))
223 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
225 struct lws_context_per_thread *pt;
226 struct lws *wsi1, *wsi2;
227 struct lws_context *context;
228 struct lws_tokens eff_buf;
235 #if defined(LWS_WITH_ESP8266)
236 if (wsi->premature_rx)
237 lws_free(wsi->premature_rx);
239 if (wsi->pending_send_completion && !wsi->close_is_pending_send_completion) {
240 lwsl_notice("delaying close\n");
241 wsi->close_is_pending_send_completion = 1;
247 /* we're closing, losing some rx is OK */
248 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
250 context = wsi->context;
251 pt = &context->pt[(int)wsi->tsi];
252 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_CLOSE, 1);
254 /* if we have children, close them first */
255 if (wsi->child_list) {
256 wsi2 = wsi->child_list;
258 //lwsl_notice("%s: closing %p: close child %p\n",
259 // __func__, wsi, wsi2);
260 wsi1 = wsi2->sibling_list;
261 //lwsl_notice("%s: closing %p: next sibling %p\n",
262 // __func__, wsi2, wsi1);
264 /* stop it doing shutdown processing */
265 wsi2->socket_is_permanently_unusable = 1;
266 lws_close_free_wsi(wsi2, reason);
269 wsi->child_list = NULL;
272 if (wsi->mode == LWSCM_RAW_FILEDESC) {
273 lws_remove_child_from_any_parent(wsi);
274 remove_wsi_socket_from_fds(wsi);
275 wsi->protocol->callback(wsi,
276 LWS_CALLBACK_RAW_CLOSE_FILE,
277 wsi->user_space, NULL, 0);
282 if (wsi->mode == LWSCM_CGI) {
283 /* we are not a network connection, but a handler for CGI io */
284 if (wsi->parent && wsi->parent->cgi)
285 /* end the binding between us and master */
286 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
287 wsi->socket_is_permanently_unusable = 1;
289 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
290 goto just_kill_connection;
294 struct lws_cgi **pcgi = &pt->cgi_list;
295 /* remove us from the cgi list */
296 lwsl_debug("%s: remove cgi %p from list\n", __func__, wsi->cgi);
298 if (*pcgi == wsi->cgi) {
299 /* drop us from the pt cgi list */
300 *pcgi = (*pcgi)->cgi_list;
303 pcgi = &(*pcgi)->cgi_list;
305 if (wsi->cgi->headers_buf) {
306 lwsl_debug("close: freed cgi headers\n");
307 lws_free_set_NULL(wsi->cgi->headers_buf);
309 /* we have a cgi going, we must kill it */
310 wsi->cgi->being_closed = 1;
315 if (wsi->mode == LWSCM_RAW) {
316 wsi->protocol->callback(wsi,
317 LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0);
318 wsi->socket_is_permanently_unusable = 1;
319 goto just_kill_connection;
322 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
323 wsi->u.http.fop_fd != NULL) {
324 lws_vfs_file_close(&wsi->u.http.fop_fd);
325 wsi->vhost->protocols->callback(wsi,
326 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
327 wsi->told_user_closed = 1;
329 if (wsi->socket_is_permanently_unusable ||
330 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
331 wsi->state == LWSS_SHUTDOWN)
332 goto just_kill_connection;
334 wsi->state_pre_close = wsi->state;
336 switch (wsi->state_pre_close) {
337 case LWSS_DEAD_SOCKET:
340 /* we tried the polite way... */
341 case LWSS_AWAITING_CLOSE_ACK:
342 goto just_kill_connection;
344 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
345 if (wsi->trunc_len) {
346 lws_callback_on_writable(wsi);
349 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
350 goto just_kill_connection;
352 if (wsi->trunc_len) {
353 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
354 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
355 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
361 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
362 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
363 goto just_kill_connection;
365 if (wsi->mode == LWSCM_HTTP_SERVING) {
367 wsi->vhost->protocols->callback(wsi,
368 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
369 wsi->user_space, NULL, 0);
370 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
371 wsi->user_space, NULL, 0);
372 wsi->told_user_closed = 1;
374 if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) {
375 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
376 wsi->user_space, NULL, 0);
377 wsi->told_user_closed = 1;
381 * are his extensions okay with him closing? Eg he might be a mux
382 * parent and just his ch1 aspect is closing?
385 if (lws_ext_cb_active(wsi,
386 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
387 lwsl_ext("extension vetoed close\n");
392 * flush any tx pending from extensions, since we may send close packet
393 * if there are problems with send, just nuke the connection
398 eff_buf.token = NULL;
399 eff_buf.token_len = 0;
401 /* show every extension the new incoming data */
403 m = lws_ext_cb_active(wsi,
404 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
406 lwsl_ext("Extension reports fatal error\n");
407 goto just_kill_connection;
411 * at least one extension told us he has more
412 * to spill, so we will go around again after
416 /* assuming they left us something to send, send it */
418 if (eff_buf.token_len)
419 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
420 eff_buf.token_len) !=
422 lwsl_debug("close: ext spill failed\n");
423 goto just_kill_connection;
428 * signal we are closing, lws_write will
429 * add any necessary version-specific stuff. If the write fails,
430 * no worries we are closing anyway. If we didn't initiate this
431 * close, then our state has been changed to
432 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
434 * Likewise if it's a second call to close this connection after we
435 * sent the close indication to the peer already, we are in state
436 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
439 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
440 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
441 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
442 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
443 lwsl_debug("sending close indication...\n");
445 /* if no prepared close reason, use 1000 and no aux data */
446 if (!wsi->u.ws.close_in_ping_buffer_len) {
447 wsi->u.ws.close_in_ping_buffer_len = 2;
448 wsi->u.ws.ping_payload_buf[LWS_PRE] =
449 (reason >> 8) & 0xff;
450 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
454 #if defined (LWS_WITH_ESP8266)
455 wsi->close_is_pending_send_completion = 1;
457 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
458 wsi->u.ws.close_in_ping_buffer_len,
462 * we have sent a nice protocol level indication we
463 * now wish to close, we should not send anything more
465 wsi->state = LWSS_AWAITING_CLOSE_ACK;
468 * ...and we should wait for a reply for a bit
471 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
472 lwsl_debug("sent close indication, awaiting ack\n");
477 lwsl_info("close: sending close packet failed, hanging up\n");
479 /* else, the send failed and we should just hang up */
482 just_kill_connection:
484 lws_remove_child_from_any_parent(wsi);
487 /* manage the vhost same protocol list entry */
489 if (wsi->same_vh_protocol_prev) { // we are on the vh list
491 // make guy who pointed to us, point to what our next was pointing to
492 *wsi->same_vh_protocol_prev = wsi->same_vh_protocol_next;
494 // if we had a next guy...
495 if (wsi->same_vh_protocol_next)
496 // have him point back to our prev
497 wsi->same_vh_protocol_next->same_vh_protocol_prev =
498 wsi->same_vh_protocol_prev;
504 * Testing with ab shows that we have to stage the socket close when
505 * the system is under stress... shutdown any further TX, change the
506 * state to one that won't emit anything more, and wait with a timeout
507 * for the POLLIN to show a zero-size rx before coming back and doing
510 if (wsi->mode != LWSCM_RAW &&
511 !(wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) &&
512 wsi->state != LWSS_SHUTDOWN &&
513 wsi->state != LWSS_CLIENT_UNCONNECTED &&
514 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
515 !wsi->socket_is_permanently_unusable) {
516 #ifdef LWS_OPENSSL_SUPPORT
517 if (lws_is_ssl(wsi) && wsi->ssl)
519 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);
520 n = SSL_shutdown(wsi->ssl);
521 if (n == 1) /* If finished the SSL shutdown, then do socket shutdown, else need to retry SSL shutdown */
522 n = shutdown(wsi->desc.sockfd, SHUT_WR);
524 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
527 int shutdown_error = SSL_get_error(wsi->ssl, n);
528 lwsl_debug("SSL_shutdown returned %d, SSL_get_error: %d\n", n, shutdown_error);
529 if (shutdown_error == SSL_ERROR_WANT_READ) {
530 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
532 } else if (shutdown_error == SSL_ERROR_WANT_WRITE) {
533 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLOUT);
535 } else { // actual error occurred, just close the connection
536 n = shutdown(wsi->desc.sockfd, SHUT_WR);
543 lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, (int)(long)wsi->desc.sockfd, wsi->state);
544 n = shutdown(wsi->desc.sockfd, SHUT_WR);
547 lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
549 // This causes problems with disconnection when the events are half closing connection
550 // FD_READ | FD_CLOSE (33)
551 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP32)
552 /* libuv: no event available to guarantee completion */
553 if (!LWS_LIBUV_ENABLED(context)) {
555 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
556 wsi->state = LWSS_SHUTDOWN;
557 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
558 context->timeout_secs);
566 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
567 wsi, wsi->desc.sockfd);
569 #ifdef LWS_WITH_HTTP_PROXY
571 lws_rewrite_destroy(wsi->rw);
576 * we won't be servicing or receiving anything further from this guy
577 * delete socket from the internal poll list if still present
579 lws_ssl_remove_wsi_from_buffered_list(wsi);
581 lws_remove_from_timeout_list(wsi);
583 /* checking return redundant since we anyway close */
584 if (wsi->desc.sockfd != LWS_SOCK_INVALID)
585 remove_wsi_socket_from_fds(wsi);
587 #if defined(LWS_WITH_ESP8266)
588 espconn_disconnect(wsi->desc.sockfd);
591 wsi->state = LWSS_DEAD_SOCKET;
593 lws_free_set_NULL(wsi->rxflow_buffer);
594 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
595 wsi->mode == LWSCM_WS_SERVING ||
596 wsi->mode == LWSCM_WS_CLIENT) {
598 if (wsi->u.ws.rx_draining_ext) {
599 struct lws **w = &pt->rx_draining_ext_list;
601 wsi->u.ws.rx_draining_ext = 0;
602 /* remove us from context draining ext list */
605 *w = wsi->u.ws.rx_draining_ext_list;
608 w = &((*w)->u.ws.rx_draining_ext_list);
610 wsi->u.ws.rx_draining_ext_list = NULL;
613 if (wsi->u.ws.tx_draining_ext) {
614 struct lws **w = &pt->tx_draining_ext_list;
616 wsi->u.ws.tx_draining_ext = 0;
617 /* remove us from context draining ext list */
620 *w = wsi->u.ws.tx_draining_ext_list;
623 w = &((*w)->u.ws.tx_draining_ext_list);
625 wsi->u.ws.tx_draining_ext_list = NULL;
627 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
629 if (wsi->trunc_alloc)
630 /* not going to be completed... nuke it */
631 lws_free_set_NULL(wsi->trunc_alloc);
633 wsi->u.ws.ping_payload_len = 0;
634 wsi->u.ws.ping_pending_flag = 0;
637 /* tell the user it's all over for this guy */
639 if (wsi->mode != LWSCM_RAW && wsi->protocol && wsi->protocol->callback &&
640 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
641 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
642 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
643 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
644 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
645 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
647 if (wsi->user_space) {
648 lwsl_debug("%s: doing LWS_CALLBACK_HTTP_DROP_PROTOCOL for %p prot %s\n", __func__, wsi, wsi->protocol->name);
649 wsi->protocol->callback(wsi,
650 LWS_CALLBACK_HTTP_DROP_PROTOCOL,
651 wsi->user_space, NULL, 0);
653 lwsl_debug("calling back CLOSED\n");
654 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
655 wsi->user_space, NULL, 0);
656 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
657 lwsl_debug("calling back CLOSED_HTTP\n");
658 wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
659 wsi->user_space, NULL, 0 );
660 } else if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
661 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) &&
662 !wsi->already_did_cce) {
663 wsi->vhost->protocols[0].callback(wsi,
664 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
665 wsi->user_space, NULL, 0);
667 lwsl_debug("not calling back closed mode=%d state=%d\n",
668 wsi->mode, wsi->state_pre_close);
670 /* deallocate any active extension contexts */
672 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
673 lwsl_warn("extension destruction failed\n");
675 * inform all extensions in case they tracked this guy out of band
676 * even though not active on him specifically
678 if (lws_ext_cb_all_exts(context, wsi,
679 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
680 lwsl_warn("ext destroy wsi failed\n");
684 wsi->socket_is_permanently_unusable = 1;
687 if (LWS_LIBUV_ENABLED(context)) {
688 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
689 /* libuv has to do his own close handle processing asynchronously */
690 lws_libuv_closehandle(wsi);
696 lws_close_free_wsi_final(wsi);
700 lws_close_free_wsi_final(struct lws *wsi)
704 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->desc.sockfd)) {
706 //lwsl_err("*** closing sockfd %d\n", wsi->desc.sockfd);
707 n = compatible_close(wsi->desc.sockfd);
709 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
712 compatible_close(wsi->desc.sockfd);
715 wsi->desc.sockfd = LWS_SOCK_INVALID;
718 /* outermost destroy notification for wsi (user_space still intact) */
719 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
720 wsi->user_space, NULL, 0);
724 for (n = 0; n < 6; n++) {
725 if (wsi->cgi->pipe_fds[n / 2][n & 1] == 0)
726 lwsl_err("ZERO FD IN CGI CLOSE");
728 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
729 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
739 LWS_VISIBLE LWS_EXTERN const char *
740 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
742 int n = 0, sl = strlen(name);
744 while (lws_hdr_copy_fragment(wsi, buf, len,
745 WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
747 if (!strncmp(buf, name, sl))
756 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
758 interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
762 ipv6 = LWS_IPV6_ENABLED(vh);
766 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
770 #ifndef LWS_PLAT_OPTEE
773 lws_get_addresses(struct lws_vhost *vh, void *ads, char *name,
774 int name_len, char *rip, int rip_len)
777 struct addrinfo ai, *res;
778 struct sockaddr_in addr4;
783 addr4.sin_family = AF_UNSPEC;
786 if (LWS_IPV6_ENABLED(vh)) {
787 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
788 lwsl_err("inet_ntop: %s", strerror(LWS_ERRNO));
792 // Strip off the IPv4 to IPv6 header if one exists
793 if (strncmp(rip, "::ffff:", 7) == 0)
794 memmove(rip, rip + 7, strlen(rip) - 6);
796 getnameinfo((struct sockaddr *)ads,
797 sizeof(struct sockaddr_in6), name,
798 name_len, NULL, 0, 0);
804 struct addrinfo *result;
806 memset(&ai, 0, sizeof ai);
807 ai.ai_family = PF_UNSPEC;
808 ai.ai_socktype = SOCK_STREAM;
809 ai.ai_flags = AI_CANONNAME;
810 #if !defined(LWS_WITH_ESP32)
811 if (getnameinfo((struct sockaddr *)ads,
812 sizeof(struct sockaddr_in),
813 name, name_len, NULL, 0, 0))
819 if (getaddrinfo(name, NULL, &ai, &result))
823 while (addr4.sin_family == AF_UNSPEC && res) {
824 switch (res->ai_family) {
826 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
827 addr4.sin_family = AF_INET;
833 freeaddrinfo(result);
836 if (addr4.sin_family == AF_UNSPEC)
839 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
857 LWS_VISIBLE const char *
858 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
863 struct sockaddr_in6 sin6;
865 struct sockaddr_in sin4;
870 if (LWS_IPV6_ENABLED(wsi->vhost)) {
884 if (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {
885 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
889 return lws_plat_inet_ntop(af, q, name, namelen);
891 #if defined(LWS_WITH_ESP8266)
892 return lws_plat_get_peer_simple(wsi, name, namelen);
901 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
902 int name_len, char *rip, int rip_len)
904 #ifndef LWS_PLAT_OPTEE
908 struct sockaddr_in6 sin6;
910 struct sockaddr_in sin4;
911 struct lws_context *context = wsi->context;
918 lws_latency_pre(context, wsi);
921 if (LWS_IPV6_ENABLED(wsi->vhost)) {
931 if (getpeername(fd, p, &len) < 0) {
932 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
936 ret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);
939 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
952 lws_context_user(struct lws_context *context)
954 return context->user_space;
957 LWS_VISIBLE struct lws_vhost *
958 lws_vhost_get(struct lws *wsi)
963 LWS_VISIBLE struct lws_vhost *
964 lws_get_vhost(struct lws *wsi)
969 LWS_VISIBLE const struct lws_protocols *
970 lws_protocol_get(struct lws *wsi)
972 return wsi->protocol;
975 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
976 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
980 for (n = 0; n < vh->count_protocols; n++)
981 if (!strcmp(name, vh->protocols[n].name))
982 return &vh->protocols[n];
988 lws_callback_all_protocol(struct lws_context *context,
989 const struct lws_protocols *protocol, int reason)
991 struct lws_context_per_thread *pt = &context->pt[0];
992 unsigned int n, m = context->count_threads;
996 for (n = 0; n < pt->fds_count; n++) {
997 wsi = wsi_from_fd(context, pt->fds[n].fd);
1000 if (wsi->protocol == protocol)
1001 protocol->callback(wsi, reason, wsi->user_space,
1011 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
1012 const struct lws_protocols *protocol, int reason)
1014 struct lws_context *context = vh->context;
1015 struct lws_context_per_thread *pt = &context->pt[0];
1016 unsigned int n, m = context->count_threads;
1020 for (n = 0; n < pt->fds_count; n++) {
1021 wsi = wsi_from_fd(context, pt->fds[n].fd);
1024 if (wsi->vhost == vh && wsi->protocol == protocol)
1025 protocol->callback(wsi, reason, wsi->user_space,
1034 LWS_VISIBLE LWS_EXTERN int
1035 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)
1039 for (n = 0; n < wsi->vhost->count_protocols; n++)
1040 if (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))
1046 LWS_VISIBLE LWS_EXTERN void
1047 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)
1049 context->fops = fops;
1052 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1053 lws_vfs_tell(lws_fop_fd_t fop_fd)
1058 LWS_VISIBLE LWS_EXTERN lws_filepos_t
1059 lws_vfs_get_length(lws_fop_fd_t fop_fd)
1064 LWS_VISIBLE LWS_EXTERN uint32_t
1065 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd)
1067 return fop_fd->mod_time;
1070 LWS_VISIBLE lws_fileofs_t
1071 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1074 lwsl_debug("%s: seeking to %ld, len %ld\n", __func__, (long)offset, (long)fop_fd->len);
1075 ofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);
1076 lwsl_debug("%s: result %ld, fop_fd pos %ld\n", __func__, (long)ofs, (long)fop_fd->pos);
1081 LWS_VISIBLE lws_fileofs_t
1082 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
1084 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len + fop_fd->pos + offset);
1088 const struct lws_plat_file_ops *
1089 lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,
1092 const struct lws_plat_file_ops *pf;
1093 const char *p = vfs_path;
1098 /* no non-platform fops, just use that */
1104 * scan the vfs path looking for indications we are to be
1105 * handled by a specific fops
1113 /* the first one is always platform fops, so skip */
1117 while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {
1118 if (p >= vfs_path + pf->fi[n].len)
1119 if (!strncmp(p - (pf->fi[n].len - 1),
1121 pf->fi[n].len - 1)) {
1136 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
1137 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
1138 lws_fop_flags_t *flags)
1140 const char *vpath = "";
1141 const struct lws_plat_file_ops *selected = lws_vfs_select_fops(
1142 fops, vfs_path, &vpath);
1144 return selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);
1149 * lws_now_secs() - seconds since 1970-1-1
1152 LWS_VISIBLE LWS_EXTERN unsigned long
1157 gettimeofday(&tv, NULL);
1166 lws_get_socket_fd(struct lws *wsi)
1168 return wsi->desc.sockfd;
1175 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
1176 int ret, int completed)
1178 unsigned long long u;
1181 u = time_in_microseconds();
1184 wsi->latency_start = u;
1185 if (!wsi->action_start)
1186 wsi->action_start = u;
1190 if (wsi->action_start == wsi->latency_start)
1192 "Completion first try lat %lluus: %p: ret %d: %s\n",
1193 u - wsi->latency_start,
1194 (void *)wsi, ret, action);
1197 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
1198 u - wsi->action_start,
1199 u - wsi->latency_start,
1200 (void *)wsi, ret, action);
1201 wsi->action_start = 0;
1203 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
1204 u - wsi->latency_start, (void *)wsi, ret, action);
1206 if (u - wsi->latency_start > context->worst_latency) {
1207 context->worst_latency = u - wsi->latency_start;
1208 strcpy(context->worst_latency_info, buf);
1210 lwsl_latency("%s", buf);
1215 lws_rx_flow_control(struct lws *wsi, int enable)
1217 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
1220 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
1221 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1227 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1228 const struct lws_protocols *protocol)
1230 const struct lws_context_per_thread *pt = &context->pt[0];
1232 unsigned int n, m = context->count_threads;
1235 for (n = 0; n < pt->fds_count; n++) {
1236 wsi = wsi_from_fd(context, pt->fds[n].fd);
1239 if (wsi->protocol == protocol)
1240 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1246 LWS_VISIBLE extern const char *
1247 lws_canonical_hostname(struct lws_context *context)
1249 return (const char *)context->canonical_hostname;
1252 int user_callback_handle_rxflow(lws_callback_function callback_function,
1254 enum lws_callback_reasons reason, void *user,
1255 void *in, size_t len)
1259 n = callback_function(wsi, reason, user, in, len);
1261 n = _lws_rx_flow_control(wsi);
1266 #if defined(LWS_WITH_ESP8266)
1268 #define strchr ets_strchr
1272 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1274 #if !defined(LWS_WITH_ESP8266)
1276 char authstring[96];
1281 /* we have to deal with a possible redundant leading http:// */
1282 if (!strncmp(proxy, "http://", 7))
1285 p = strchr(proxy, '@');
1286 if (p) { /* auth is around */
1288 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1291 strncpy(authstring, proxy, p - proxy);
1292 // null termination not needed on input
1293 if (lws_b64_encode_string(authstring, (p - proxy),
1294 vhost->proxy_basic_auth_token,
1295 sizeof vhost->proxy_basic_auth_token) < 0)
1298 lwsl_info(" Proxy auth in use\n");
1302 vhost->proxy_basic_auth_token[0] = '\0';
1304 strncpy(vhost->http_proxy_address, proxy,
1305 sizeof(vhost->http_proxy_address) - 1);
1306 vhost->http_proxy_address[
1307 sizeof(vhost->http_proxy_address) - 1] = '\0';
1309 p = strchr(vhost->http_proxy_address, ':');
1310 if (!p && !vhost->http_proxy_port) {
1311 lwsl_err("http_proxy needs to be ads:port\n");
1317 vhost->http_proxy_port = atoi(p + 1);
1321 lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address,
1322 vhost->http_proxy_port);
1327 lwsl_err("proxy auth too long\n");
1332 #if defined(LWS_WITH_SOCKS5)
1334 lws_set_socks(struct lws_vhost *vhost, const char *socks)
1336 #if !defined(LWS_WITH_ESP8266)
1337 char *p_at, *p_colon;
1344 vhost->socks_user[0] = '\0';
1345 vhost->socks_password[0] = '\0';
1347 p_at = strchr(socks, '@');
1348 if (p_at) { /* auth is around */
1349 if ((unsigned int)(p_at - socks) > (sizeof(user)
1350 + sizeof(password) - 2)) {
1351 lwsl_err("Socks auth too long\n");
1355 p_colon = strchr(socks, ':');
1357 if ((unsigned int)(p_colon - socks) > (sizeof(user)
1359 lwsl_err("Socks user too long\n");
1362 if ((unsigned int)(p_at - p_colon) > (sizeof(password)
1364 lwsl_err("Socks password too long\n");
1368 strncpy(vhost->socks_user, socks, p_colon - socks);
1369 strncpy(vhost->socks_password, p_colon + 1,
1370 p_at - (p_colon + 1));
1372 lwsl_info(" Socks auth, user: %s, password: %s\n",
1373 vhost->socks_user, vhost->socks_password );
1378 strncpy(vhost->socks_proxy_address, socks,
1379 sizeof(vhost->socks_proxy_address) - 1);
1380 vhost->socks_proxy_address[sizeof(vhost->socks_proxy_address) - 1]
1383 p_colon = strchr(vhost->socks_proxy_address, ':');
1384 if (!p_colon && !vhost->socks_proxy_port) {
1385 lwsl_err("socks_proxy needs to be address:port\n");
1390 vhost->socks_proxy_port = atoi(p_colon + 1);
1394 lwsl_info(" Socks %s:%u\n", vhost->socks_proxy_address,
1395 vhost->socks_proxy_port);
1405 LWS_VISIBLE const struct lws_protocols *
1406 lws_get_protocol(struct lws *wsi)
1408 return wsi->protocol;
1412 lws_is_final_fragment(struct lws *wsi)
1414 lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
1415 wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length,
1416 (long)wsi->u.ws.rx_draining_ext);
1417 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1420 LWS_VISIBLE unsigned char
1421 lws_get_reserved_bits(struct lws *wsi)
1423 return wsi->u.ws.rsv;
1427 lws_ensure_user_space(struct lws *wsi)
1429 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1433 /* allocate the per-connection user memory (if any) */
1435 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1436 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1437 if (wsi->user_space == NULL) {
1438 lwsl_err("Out of memory for conn user space\n");
1442 lwsl_info("%s: %p protocol pss %lu, user_space=%p\n",
1443 __func__, wsi, (long)wsi->protocol->per_session_data_size,
1449 lwsl_timestamp(int level, char *p, int len)
1451 #ifndef LWS_PLAT_OPTEE
1452 time_t o_now = time(NULL);
1453 unsigned long long now;
1454 struct tm *ptm = NULL;
1462 ptm = localtime(&o_now);
1464 if (localtime_r(&o_now, &tm))
1469 for (n = 0; n < LLL_COUNT; n++) {
1470 if (level != (1 << n))
1472 now = time_in_microseconds() / 100;
1474 n = lws_snprintf(p, len,
1475 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1476 ptm->tm_year + 1900,
1482 (int)(now % 10000), log_level_names[n]);
1484 n = lws_snprintf(p, len, "[%llu:%04d] %s: ",
1485 (unsigned long long) now / 10000,
1486 (int)(now % 10000), log_level_names[n]);
1493 #ifndef LWS_PLAT_OPTEE
1494 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1496 #if !defined(LWS_WITH_ESP8266)
1499 lwsl_timestamp(level, buf, sizeof(buf));
1500 fprintf(stderr, "%s%s", buf, line);
1505 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1507 #if defined(LWS_WITH_ESP8266)
1514 if (!(log_level & filter))
1517 n = vsnprintf(buf, sizeof(buf) - 1, format, vl);
1519 #if defined(LWS_WITH_ESP8266)
1520 buf[sizeof(buf) - 1] = '\0';
1522 /* vnsprintf returns what it would have written, even if truncated */
1523 if (n > sizeof(buf) - 1)
1524 n = sizeof(buf) - 1;
1529 lwsl_emit(filter, buf);
1532 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1536 va_start(ap, format);
1537 _lws_logv(filter, format, ap);
1541 LWS_VISIBLE void lws_set_log_level(int level,
1542 void (*func)(int level, const char *line))
1549 LWS_VISIBLE int lwsl_visible(int level)
1551 return log_level & level;
1555 lws_is_ssl(struct lws *wsi)
1557 #ifdef LWS_OPENSSL_SUPPORT
1558 return wsi->use_ssl;
1565 #ifdef LWS_OPENSSL_SUPPORT
1567 lws_get_ssl(struct lws *wsi)
1574 lws_partial_buffered(struct lws *wsi)
1576 return !!wsi->trunc_len;
1579 void lws_set_protocol_write_pending(struct lws *wsi,
1580 enum lws_pending_protocol_send pend)
1582 lwsl_info("setting pps %d\n", pend);
1585 lwsl_err("pps overwrite\n");
1587 lws_rx_flow_control(wsi, 0);
1588 lws_callback_on_writable(wsi);
1592 lws_get_peer_write_allowance(struct lws *wsi)
1594 #ifdef LWS_USE_HTTP2
1595 /* only if we are using HTTP2 on this connection */
1596 if (wsi->mode != LWSCM_HTTP2_SERVING)
1598 /* user is only interested in how much he can send, or that he can't */
1599 if (wsi->u.http2.tx_credit <= 0)
1602 return wsi->u.http2.tx_credit;
1610 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1612 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1613 memset(&wsi->u, 0, sizeof(wsi->u));
1617 LWS_VISIBLE struct lws_plat_file_ops *
1618 lws_get_fops(struct lws_context *context)
1620 return (struct lws_plat_file_ops *)context->fops;
1623 LWS_VISIBLE LWS_EXTERN struct lws_context *
1624 lws_get_context(const struct lws *wsi)
1626 return wsi->context;
1629 LWS_VISIBLE LWS_EXTERN int
1630 lws_get_count_threads(struct lws_context *context)
1632 return context->count_threads;
1635 LWS_VISIBLE LWS_EXTERN void *
1636 lws_wsi_user(struct lws *wsi)
1638 return wsi->user_space;
1641 LWS_VISIBLE LWS_EXTERN void
1642 lws_set_wsi_user(struct lws *wsi, void *data)
1644 if (wsi->user_space_externally_allocated)
1645 wsi->user_space = data;
1647 lwsl_err("%s: Cannot set internally-allocated user_space\n",
1651 LWS_VISIBLE LWS_EXTERN struct lws *
1652 lws_get_parent(const struct lws *wsi)
1657 LWS_VISIBLE LWS_EXTERN struct lws *
1658 lws_get_child(const struct lws *wsi)
1660 return wsi->child_list;
1663 LWS_VISIBLE LWS_EXTERN void
1664 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1665 unsigned char *buf, size_t len)
1667 unsigned char *p, *start;
1668 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1670 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1672 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1674 *p++ = (((int)status) >> 8) & 0xff;
1675 *p++ = ((int)status) & 0xff;
1678 while (len-- && p < start + budget)
1681 wsi->u.ws.close_in_ping_buffer_len = p - start;
1685 _lws_rx_flow_control(struct lws *wsi)
1687 struct lws *wsic = wsi->child_list;
1689 /* if he has children, do those if they were changed */
1691 if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)
1692 _lws_rx_flow_control(wsic);
1694 wsic = wsic->sibling_list;
1697 /* there is no pending change */
1698 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1699 // lwsl_debug("%s: no pending change\n", __func__);
1703 /* stuff is still buffered, not ready to really accept new input */
1704 if (wsi->rxflow_buffer) {
1705 /* get ourselves called back to deal with stashed buffer */
1706 lws_callback_on_writable(wsi);
1710 /* pending is cleared, we can change rxflow state */
1712 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1714 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1715 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1717 /* adjust the pollfd for this wsi */
1719 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1720 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1721 lwsl_info("%s: fail\n", __func__);
1725 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1732 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1734 static const unsigned char e0f4[] = {
1735 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1736 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1737 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1738 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1739 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1740 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1741 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1742 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1743 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1744 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1745 0x80 | ((4 - 1) << 2) | 1, /* ea */
1746 0x80 | ((4 - 1) << 2) | 1, /* eb */
1747 0x80 | ((4 - 1) << 2) | 1, /* ec */
1748 0x80 | ((2 - 1) << 2) | 1, /* ed */
1749 0x80 | ((4 - 1) << 2) | 1, /* ee */
1750 0x80 | ((4 - 1) << 2) | 1, /* ef */
1751 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1752 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1753 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1754 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1755 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1758 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1759 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1761 unsigned char s = *state;
1764 unsigned char c = *buf++;
1768 if (c < 0xc2 || c > 0xf4)
1771 s = 0x80 | ((4 - 1) << 2);
1776 if (c < (s & 0xf0) ||
1777 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1779 s = e0f4[21 + (s & 3)];
1788 LWS_VISIBLE LWS_EXTERN int
1789 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1793 static const char *slash = "/";
1795 /* cut up the location into address, port and path */
1797 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1808 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1810 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1816 while (*p && *p != ']')
1823 while (*p && *p != ':' && *p != '/')
1829 while (*p && *p != '/')
1842 #ifdef LWS_NO_EXTENSIONS
1844 /* we need to provide dummy callbacks for internal exts
1845 * so user code runs when faced with a lib compiled with
1846 * extensions disabled.
1850 lws_extension_callback_pm_deflate(struct lws_context *context,
1851 const struct lws_extension *ext,
1853 enum lws_extension_callback_reasons reason,
1854 void *user, void *in, size_t len)
1869 lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,
1873 #ifdef LWS_USE_UNIX_SOCK
1874 struct sockaddr_un serv_unix;
1877 struct sockaddr_in6 serv_addr6;
1879 struct sockaddr_in serv_addr4;
1880 #ifndef LWS_PLAT_OPTEE
1881 socklen_t len = sizeof(struct sockaddr);
1884 struct sockaddr_in sin;
1887 #ifdef LWS_USE_UNIX_SOCK
1888 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1889 v = (struct sockaddr *)&serv_unix;
1890 n = sizeof(struct sockaddr_un);
1891 bzero((char *) &serv_unix, sizeof(serv_unix));
1892 serv_unix.sun_family = AF_UNIX;
1893 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1894 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1898 strcpy(serv_unix.sun_path, iface);
1899 if (serv_unix.sun_path[0] == '@')
1900 serv_unix.sun_path[0] = '\0';
1904 #if defined(LWS_USE_IPV6) && !defined(LWS_WITH_ESP32)
1905 if (LWS_IPV6_ENABLED(vhost)) {
1906 v = (struct sockaddr *)&serv_addr6;
1907 n = sizeof(struct sockaddr_in6);
1908 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1910 interface_to_sa(vhost, iface,
1911 (struct sockaddr_in *)v, n) < 0) {
1912 lwsl_err("Unable to find interface %s\n", iface);
1917 struct ifaddrs *addrs, *addr;
1918 char ip[NI_MAXHOST];
1922 for (addr = addrs; addr; addr = addr->ifa_next) {
1923 if (!addr->ifa_addr ||
1924 addr->ifa_addr->sa_family != AF_INET6)
1927 getnameinfo(addr->ifa_addr,
1928 sizeof(struct sockaddr_in6),
1930 NULL, 0, NI_NUMERICHOST);
1934 if (ip[i++] == '%') {
1939 if (!strcmp(ip, iface)) {
1940 serv_addr6.sin6_scope_id =
1941 if_nametoindex(addr->ifa_name);
1948 serv_addr6.sin6_family = AF_INET6;
1949 serv_addr6.sin6_port = htons(port);
1953 v = (struct sockaddr *)&serv_addr4;
1954 n = sizeof(serv_addr4);
1955 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1956 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1957 serv_addr4.sin_family = AF_INET;
1958 #if !defined(LWS_WITH_ESP32)
1961 interface_to_sa(vhost, iface,
1962 (struct sockaddr_in *)v, n) < 0) {
1963 lwsl_err("Unable to find interface %s\n", iface);
1967 serv_addr4.sin_port = htons(port);
1970 n = bind(sockfd, v, n);
1971 #ifdef LWS_USE_UNIX_SOCK
1972 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
1973 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1974 sockfd, iface, n, LWS_ERRNO);
1979 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1980 sockfd, port, n, LWS_ERRNO);
1984 #ifndef LWS_PLAT_OPTEE
1985 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1986 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1989 port = ntohs(sin.sin_port);
1996 lws_restart_ws_ping_pong_timer(struct lws *wsi)
1998 if (!wsi->context->ws_ping_pong_interval)
2000 if (wsi->state != LWSS_ESTABLISHED)
2003 wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() +
2004 wsi->context->ws_ping_pong_interval;
2007 static const char *hex = "0123456789ABCDEF";
2009 LWS_VISIBLE LWS_EXTERN const char *
2010 lws_sql_purify(char *escaped, const char *string, int len)
2012 const char *p = string;
2015 while (*p && len-- > 2) {
2029 LWS_VISIBLE LWS_EXTERN const char *
2030 lws_json_purify(char *escaped, const char *string, int len)
2032 const char *p = string;
2040 while (*p && len-- > 6) {
2041 if (*p == '\"' || *p == '\\' || *p < 0x20) {
2046 *q++ = hex[((*p) >> 4) & 15];
2047 *q++ = hex[(*p) & 15];
2058 LWS_VISIBLE LWS_EXTERN const char *
2059 lws_urlencode(char *escaped, const char *string, int len)
2061 const char *p = string;
2064 while (*p && len-- > 3) {
2070 if ((*p >= '0' && *p <= '9') ||
2071 (*p >= 'A' && *p <= 'Z') ||
2072 (*p >= 'a' && *p <= 'z')) {
2077 *q++ = hex[(*p >> 4) & 0xf];
2078 *q++ = hex[*p & 0xf];
2088 LWS_VISIBLE LWS_EXTERN int
2089 lws_urldecode(char *string, const char *escaped, int len)
2094 while (*escaped && len) {
2097 if (*escaped == '%') {
2102 if (*escaped == '+') {
2108 *string++ = *escaped++;
2112 n = char_to_hex(*escaped);
2121 n = char_to_hex(*escaped);
2125 *string++ = sum | n;
2137 LWS_VISIBLE LWS_EXTERN int
2138 lws_finalize_startup(struct lws_context *context)
2140 struct lws_context_creation_info info;
2142 info.uid = context->uid;
2143 info.gid = context->gid;
2145 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
2146 lws_plat_drop_app_privileges(&info);
2152 lws_snprintf(char *str, size_t size, const char *format, ...)
2160 va_start(ap, format);
2161 n = vsnprintf(str, size, format, ap);
2171 LWS_VISIBLE LWS_EXTERN int
2172 lws_is_cgi(struct lws *wsi) {
2183 urlencode(const char *in, int inlen, char *out, int outlen)
2185 char *start = out, *end = out + outlen;
2187 while (inlen-- && out < end - 4) {
2188 if ((*in >= 'A' && *in <= 'Z') ||
2189 (*in >= 'a' && *in <= 'z') ||
2190 (*in >= '0' && *in <= '9') ||
2204 *out++ = hex[(*in) >> 4];
2205 *out++ = hex[(*in++) & 15];
2216 lws_create_basic_wsi(struct lws_context *context, int tsi)
2218 struct lws *new_wsi;
2220 if ((unsigned int)context->pt[tsi].fds_count ==
2221 context->fd_limit_per_thread - 1) {
2222 lwsl_err("no space for new conn\n");
2226 new_wsi = lws_zalloc(sizeof(struct lws));
2227 if (new_wsi == NULL) {
2228 lwsl_err("Out of memory for new connection\n");
2233 new_wsi->context = context;
2234 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
2235 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
2237 /* initialize the instance struct */
2239 new_wsi->state = LWSS_CGI;
2240 new_wsi->mode = LWSCM_CGI;
2241 new_wsi->hdr_parsing_completed = 0;
2242 new_wsi->position_in_fds_table = -1;
2245 * these can only be set once the protocol is known
2246 * we set an unestablished connection's protocol pointer
2247 * to the start of the defauly vhost supported list, so it can look
2248 * for matching ones during the handshake
2250 new_wsi->protocol = context->vhost_list->protocols;
2251 new_wsi->user_space = NULL;
2252 new_wsi->ietf_spec_revision = 0;
2253 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
2254 context->count_wsi_allocated++;
2259 LWS_VISIBLE LWS_EXTERN int
2260 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
2261 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
2263 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2264 char *env_array[30], cgi_path[400], e[1024], *p = e,
2265 *end = p + sizeof(e) - 1, tok[256], *t;
2266 struct lws_cgi *cgi;
2267 int n, m, i, uritok = -1;
2270 * give the master wsi a cgi struct
2273 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
2275 lwsl_err("%s: OOM\n", __func__);
2279 wsi->cgi->response_code = HTTP_STATUS_OK;
2282 cgi->wsi = wsi; /* set cgi's owning wsi */
2284 /* create pipes for [stdin|stdout] and [stderr] */
2286 for (n = 0; n < 3; n++)
2287 if (pipe(cgi->pipe_fds[n]) == -1)
2290 /* create cgi wsis for each stdin/out/err fd */
2292 for (n = 0; n < 3; n++) {
2293 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
2294 if (!cgi->stdwsi[n])
2296 cgi->stdwsi[n]->cgi_channel = n;
2297 cgi->stdwsi[n]->vhost = wsi->vhost;
2299 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
2300 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
2302 /* read side is 0, stdin we want the write side, others read */
2303 cgi->stdwsi[n]->desc.sockfd = cgi->pipe_fds[n][!!(n == 0)];
2304 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
2305 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
2310 for (n = 0; n < 3; n++) {
2311 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->desc);
2312 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
2314 cgi->stdwsi[n]->parent = wsi;
2315 cgi->stdwsi[n]->sibling_list = wsi->child_list;
2316 wsi->child_list = cgi->stdwsi[n];
2319 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
2320 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
2321 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
2323 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
2324 cgi->stdwsi[LWS_STDIN]->desc.sockfd,
2325 cgi->stdwsi[LWS_STDOUT]->desc.sockfd,
2326 cgi->stdwsi[LWS_STDERR]->desc.sockfd);
2328 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
2330 /* the cgi stdout is always sending us http1.x header data first */
2331 wsi->hdr_state = LCHS_HEADER;
2333 /* add us to the pt list of active cgis */
2334 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
2335 cgi->cgi_list = pt->cgi_list;
2338 /* prepare his CGI env */
2342 if (lws_is_ssl(wsi))
2343 env_array[n++] = "HTTPS=ON";
2344 if (wsi->u.hdr.ah) {
2345 static const unsigned char meths[] = {
2348 WSI_TOKEN_OPTIONS_URI,
2350 WSI_TOKEN_PATCH_URI,
2351 WSI_TOKEN_DELETE_URI,
2353 static const char * const meth_names[] = {
2354 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
2357 for (m = 0; m < ARRAY_SIZE(meths); m++)
2358 if (lws_hdr_total_length(wsi, meths[m]) >=
2359 script_uri_path_len) {
2367 lws_snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
2368 lws_hdr_simple_ptr(wsi, uritok));
2369 cgi_path[sizeof(cgi_path) - 1] = '\0';
2370 env_array[n++] = cgi_path;
2373 p += lws_snprintf(p, end - p, "REQUEST_METHOD=%s",
2378 p += lws_snprintf(p, end - p, "QUERY_STRING=");
2379 /* dump the individual URI Arg parameters */
2382 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
2383 WSI_TOKEN_HTTP_URI_ARGS, m);
2387 while (*t && *t != '=' && p < end - 4)
2391 i = urlencode(t, i- (t - tok), p, end - p);
2403 p += lws_snprintf(p, end - p, "PATH_INFO=%s",
2404 lws_hdr_simple_ptr(wsi, uritok) +
2405 script_uri_path_len);
2408 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
2410 p += lws_snprintf(p, end - p, "HTTP_REFERER=%s",
2411 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
2414 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2416 p += lws_snprintf(p, end - p, "HTTP_HOST=%s",
2417 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2420 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
2422 p += lws_snprintf(p, end - p, "HTTP_COOKIE=%s",
2423 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
2426 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
2428 p += lws_snprintf(p, end - p, "USER_AGENT=%s",
2429 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
2432 if (uritok == WSI_TOKEN_POST_URI) {
2433 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
2435 p += lws_snprintf(p, end - p, "CONTENT_TYPE=%s",
2436 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
2439 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
2441 p += lws_snprintf(p, end - p, "CONTENT_LENGTH=%s",
2442 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
2447 p += lws_snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
2451 p += lws_snprintf(p, end - p, "%s=%s", mp_cgienv->name,
2453 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
2456 mp_cgienv = mp_cgienv->next;
2459 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
2460 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
2461 env_array[n] = NULL;
2464 for (m = 0; m < n; m++)
2465 lwsl_err(" %s\n", env_array[m]);
2469 * Actually having made the env, as a cgi we don't need the ah
2472 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
2473 lws_header_table_detach(wsi, 0);
2475 /* we are ready with the redirection pipes... run the thing */
2476 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2482 lwsl_err("fork failed, errno %d", errno);
2486 #if defined(__linux__)
2487 prctl(PR_SET_PDEATHSIG, SIGTERM);
2489 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
2492 /* we are the parent process */
2493 wsi->context->count_cgi_spawned++;
2494 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
2498 /* somewhere we can at least read things and enter it */
2500 lwsl_notice("%s: Failed to chdir\n", __func__);
2502 /* We are the forked process, redirect and kill inherited things.
2504 * Because of vfork(), we cannot do anything that changes pages in
2505 * the parent environment. Stuff that changes kernel state for the
2506 * process is OK. Stuff that happens after the execvpe() is OK.
2509 for (n = 0; n < 3; n++) {
2510 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2511 lwsl_err("%s: stdin dup2 failed\n", __func__);
2514 close(cgi->pipe_fds[n][!(n == 0)]);
2517 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2518 for (m = 0; m < n; m++) {
2519 p = strchr(env_array[m], '=');
2521 setenv(env_array[m], p, 1);
2523 execvp(exec_array[0], (char * const *)&exec_array[0]);
2525 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2531 /* drop us from the pt cgi list */
2532 pt->cgi_list = cgi->cgi_list;
2535 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2537 for (n = 0; n < 3; n++)
2538 if (wsi->cgi->stdwsi[n])
2539 lws_free_wsi(cgi->stdwsi[n]);
2542 for (n = 0; n < 3; n++) {
2543 if (cgi->pipe_fds[n][0])
2544 close(cgi->pipe_fds[n][0]);
2545 if (cgi->pipe_fds[n][1])
2546 close(cgi->pipe_fds[n][1]);
2549 lws_free_set_NULL(wsi->cgi);
2551 lwsl_err("%s: failed\n", __func__);
2556 /* we have to parse out these headers in the CGI output */
2558 static const char * const significant_hdr[SIGNIFICANT_HDR_COUNT] = {
2562 "transfer-encoding: chunked",
2565 LWS_VISIBLE LWS_EXTERN int
2566 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2569 unsigned char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2570 *end = &buf[sizeof(buf) - 1 - LWS_PRE];
2576 while (wsi->hdr_state != LHCS_PAYLOAD) {
2577 /* we have to separate header / finalize and
2578 * payload chunks, since they need to be
2579 * handled separately
2582 switch (wsi->hdr_state) {
2585 lwsl_info("LHCS_RESPONSE: issuing response %d\n",
2586 wsi->cgi->response_code);
2587 if (lws_add_http_header_status(wsi, wsi->cgi->response_code, &p, end))
2589 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2590 (unsigned char *)"close", 5, &p, end))
2592 n = lws_write(wsi, start, p - start,
2593 LWS_WRITE_HTTP_HEADERS);
2595 /* finalize cached headers before dumping them */
2596 if (lws_finalize_http_header(wsi,
2597 (unsigned char **)&wsi->cgi->headers_pos,
2598 (unsigned char *)wsi->cgi->headers_end)) {
2600 lwsl_notice("finalize failed\n");
2604 wsi->hdr_state = LHCS_DUMP_HEADERS;
2605 wsi->reason_bf |= 8;
2606 lws_callback_on_writable(wsi);
2607 /* back to the loop for writeability again */
2610 case LHCS_DUMP_HEADERS:
2612 n = wsi->cgi->headers_pos - wsi->cgi->headers_dumped;
2616 lwsl_debug("LHCS_DUMP_HEADERS: %d\n", n);
2618 m = lws_write(wsi, (unsigned char *)wsi->cgi->headers_dumped,
2619 n, LWS_WRITE_HTTP_HEADERS);
2621 lwsl_debug("%s: write says %d\n", __func__, m);
2624 wsi->cgi->headers_dumped += n;
2625 if (wsi->cgi->headers_dumped == wsi->cgi->headers_pos) {
2626 wsi->hdr_state = LHCS_PAYLOAD;
2627 lws_free_set_NULL(wsi->cgi->headers_buf);
2628 lwsl_debug("freed cgi headers\n");
2630 wsi->reason_bf |= 8;
2631 lws_callback_on_writable(wsi);
2634 /* writeability becomes uncertain now we wrote
2635 * something, we must return to the event loop
2640 if (!wsi->cgi->headers_buf) {
2641 /* if we don't already have a headers buf, cook one up */
2643 wsi->cgi->headers_buf = malloc(n);
2644 if (!wsi->cgi->headers_buf) {
2649 lwsl_debug("allocated cgi hdrs\n");
2650 wsi->cgi->headers_pos = wsi->cgi->headers_buf;
2651 wsi->cgi->headers_dumped = wsi->cgi->headers_pos;
2652 wsi->cgi->headers_end = wsi->cgi->headers_buf + n - 1;
2654 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2655 wsi->cgi->match[n] = 0;
2660 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2662 if (errno != EAGAIN) {
2663 lwsl_debug("%s: read says %d\n", __func__, n);
2669 if (wsi->cgi->headers_pos >= wsi->cgi->headers_end - 4) {
2670 lwsl_notice("CGI headers larger than buffer size\n");
2676 lwsl_debug("-- 0x%02X %c %d %d\n", (unsigned char)c, c, wsi->cgi->match[1], wsi->hdr_state);
2679 switch (wsi->hdr_state) {
2682 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++) {
2683 /* significant headers with numeric decimal payloads */
2684 if (!significant_hdr[n][wsi->cgi->match[n]] &&
2685 (c >= '0' && c <= '9') &&
2686 wsi->cgi->lp < sizeof(wsi->cgi->l) - 1) {
2687 wsi->cgi->l[wsi->cgi->lp++] = c;
2688 wsi->cgi->l[wsi->cgi->lp] = '\0';
2690 case SIGNIFICANT_HDR_CONTENT_LENGTH:
2691 wsi->cgi->content_length = atol(wsi->cgi->l);
2693 case SIGNIFICANT_HDR_STATUS:
2694 wsi->cgi->response_code = atol(wsi->cgi->l);
2695 lwsl_debug("Status set to %d\n", wsi->cgi->response_code);
2701 /* hits up to the NUL are sticky until next hdr */
2702 if (significant_hdr[n][wsi->cgi->match[n]]) {
2703 if (tolower(c) == significant_hdr[n][wsi->cgi->match[n]])
2704 wsi->cgi->match[n]++;
2706 wsi->cgi->match[n] = 0;
2710 /* some cgi only send us \x0a for EOL */
2712 wsi->hdr_state = LCHS_SINGLE_0A;
2713 *wsi->cgi->headers_pos++ = '\x0d';
2715 *wsi->cgi->headers_pos++ = c;
2717 wsi->hdr_state = LCHS_LF1;
2719 if (wsi->hdr_state != LCHS_HEADER &&
2720 !significant_hdr[SIGNIFICANT_HDR_TRANSFER_ENCODING][wsi->cgi->match[SIGNIFICANT_HDR_TRANSFER_ENCODING]]) {
2721 lwsl_debug("cgi produced chunked\n");
2722 wsi->cgi->explicitly_chunked = 1;
2725 /* presence of Location: mandates 302 retcode */
2726 if (wsi->hdr_state != LCHS_HEADER &&
2727 !significant_hdr[SIGNIFICANT_HDR_LOCATION][wsi->cgi->match[SIGNIFICANT_HDR_LOCATION]]) {
2728 lwsl_debug("CGI: Location hdr seen\n");
2729 wsi->cgi->response_code = 302;
2734 *wsi->cgi->headers_pos++ = c;
2736 wsi->hdr_state = LCHS_CR2;
2739 /* we got \r[^\n]... it's unreasonable */
2740 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2746 wsi->hdr_state = LCHS_LF2;
2749 wsi->hdr_state = LCHS_HEADER;
2750 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2751 wsi->cgi->match[n] = 0;
2756 case LCHS_SINGLE_0A:
2759 lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
2760 wsi->hdr_state = LHCS_RESPONSE;
2761 /* drop the \0xa ... finalize will add it if needed */
2765 /* we got \r\n\r[^\n]... it's unreasonable */
2767 /* we got \x0anext header, it's reasonable */
2768 *wsi->cgi->headers_pos++ = c;
2769 wsi->hdr_state = LCHS_HEADER;
2770 for (n = 0; n < SIGNIFICANT_HDR_COUNT; n++)
2771 wsi->cgi->match[n] = 0;
2779 /* ran out of input, ended the headers, or filled up the headers buf */
2780 if (!n || wsi->hdr_state == LHCS_PAYLOAD)
2784 /* payload processing */
2786 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2787 start, sizeof(buf) - LWS_PRE);
2789 if (n < 0 && errno != EAGAIN) {
2790 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2794 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2795 //lwsl_notice("write %d\n", m);
2797 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2800 wsi->cgi->content_length_seen += m;
2806 LWS_VISIBLE LWS_EXTERN int
2807 lws_cgi_kill(struct lws *wsi)
2809 struct lws_cgi_args args;
2812 lwsl_debug("%s: %p\n", __func__, wsi);
2817 if (wsi->cgi->pid > 0) {
2818 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2820 lwsl_debug("%s: PID %d reaped\n", __func__,
2824 /* kill the process group */
2825 n = kill(-wsi->cgi->pid, SIGTERM);
2826 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2827 wsi->cgi->pid, n, errno);
2830 * hum seen errno=3 when process is listed in ps,
2831 * it seems we don't always retain process grouping
2833 * Direct these fallback attempt to the exact child
2835 n = kill(wsi->cgi->pid, SIGTERM);
2837 n = kill(wsi->cgi->pid, SIGPIPE);
2839 n = kill(wsi->cgi->pid, SIGKILL);
2841 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2842 __func__, wsi->cgi->pid, errno);
2846 /* He could be unkillable because he's a zombie */
2849 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2851 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2853 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2855 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2861 args.stdwsi = &wsi->cgi->stdwsi[0];
2863 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2864 wsi->protocol->callback,
2865 wsi, LWS_CALLBACK_CGI_TERMINATED,
2867 (void *)&args, 0)) {
2869 if (!wsi->cgi->being_closed)
2870 lws_close_free_wsi(wsi, 0);
2877 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2879 struct lws_cgi **pcgi, *cgi = NULL;
2883 /* find finished guys but don't reap yet */
2884 n = waitpid(-1, &status, WNOHANG);
2887 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
2889 pcgi = &pt->cgi_list;
2891 /* check all the subprocesses on the cgi list */
2893 /* get the next one first as list may change */
2895 pcgi = &(*pcgi)->cgi_list;
2900 /* finish sending cached headers */
2901 if (cgi->headers_buf)
2904 /* wait for stdout to be drained */
2905 if (cgi->content_length > cgi->content_length_seen)
2908 if (cgi->content_length) {
2909 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2910 __func__, cgi->wsi, cgi->content_length_seen);
2914 waitpid(n, &status, WNOHANG);
2916 * he's already terminated so no need for kill()
2917 * but we should do the terminated cgi callback
2918 * and close him if he's not already closing
2920 if (n == cgi->pid) {
2921 lwsl_debug("%s: found PID %d on cgi list\n",
2924 if (!cgi->content_length && cgi->explicitly_chunked) {
2926 * well, if he sends chunked... give him 5s after the
2927 * cgi terminated to send buffered
2929 cgi->chunked_grace++;
2935 lws_cgi_kill(cgi->wsi);
2941 /* if not found on the cgi list, as he's one of ours, reap */
2943 lwsl_debug("%s: reading PID %d although no cgi match\n",
2945 waitpid(n, &status, WNOHANG);
2949 /* disable this to confirm timeout cgi cleanup flow */
2951 pcgi = &pt->cgi_list;
2953 /* check all the subprocesses on the cgi list */
2955 /* get the next one first as list may change */
2957 pcgi = &(*pcgi)->cgi_list;
2962 /* we deferred killing him after reaping his PID */
2963 if (cgi->chunked_grace) {
2964 cgi->chunked_grace++;
2965 if (cgi->chunked_grace < 5)
2970 /* finish sending cached headers */
2971 if (cgi->headers_buf)
2974 /* wait for stdout to be drained */
2975 if (cgi->content_length > cgi->content_length_seen)
2978 if (cgi->content_length)
2979 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2980 __func__, cgi->wsi, cgi->content_length_seen);
2983 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2985 if (!cgi->content_length) {
2987 * well, if he sends chunked... give him 5s after the
2988 * cgi terminated to send buffered
2990 cgi->chunked_grace++;
2994 lwsl_debug("%s: found PID %d on cgi list\n",
2995 __func__, cgi->pid);
2998 lws_cgi_kill(cgi->wsi);
3005 /* general anti zombie defence */
3006 // n = waitpid(-1, &status, WNOHANG);
3008 // lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
3014 #ifdef LWS_NO_EXTENSIONS
3016 lws_set_extension_option(struct lws *wsi, const char *ext_name,
3017 const char *opt_name, const char *opt_val)
3023 #ifdef LWS_WITH_ACCESS_LOG
3025 lws_access_log(struct lws *wsi)
3027 char *p = wsi->access_log.user_agent, ass[512];
3030 if (!wsi->access_log_pending)
3033 if (!wsi->access_log.header_log)
3039 l = lws_snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
3040 wsi->access_log.header_log,
3041 wsi->access_log.response, wsi->access_log.sent, p);
3043 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
3044 if (write(wsi->vhost->log_fd, ass, l) != l)
3045 lwsl_err("Failed to write log\n");
3047 lwsl_err("%s", ass);
3049 if (wsi->access_log.header_log) {
3050 lws_free(wsi->access_log.header_log);
3051 wsi->access_log.header_log = NULL;
3053 if (wsi->access_log.user_agent) {
3054 lws_free(wsi->access_log.user_agent);
3055 wsi->access_log.user_agent = NULL;
3057 wsi->access_log_pending = 0;
3064 lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)
3066 const struct lws_vhost *vh = ctx->vhost_list;
3070 cs->rx += vh->conn_stats.rx;
3071 cs->tx += vh->conn_stats.tx;
3072 cs->conn += vh->conn_stats.conn;
3073 cs->trans += vh->conn_stats.trans;
3074 cs->ws_upg += vh->conn_stats.ws_upg;
3075 cs->http2_upg += vh->conn_stats.http2_upg;
3076 cs->rejected += vh->conn_stats.rejected;
3078 vh = vh->vhost_next;
3082 #ifdef LWS_WITH_SERVER_STATUS
3085 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
3087 static const char * const prots[] = {
3096 char *orig = buf, *end = buf + len - 1, first = 1;
3102 buf += lws_snprintf(buf, end - buf,
3103 "{\n \"name\":\"%s\",\n"
3104 " \"port\":\"%d\",\n"
3105 " \"use_ssl\":\"%d\",\n"
3106 " \"sts\":\"%d\",\n"
3107 " \"rx\":\"%llu\",\n"
3108 " \"tx\":\"%llu\",\n"
3109 " \"conn\":\"%lu\",\n"
3110 " \"trans\":\"%lu\",\n"
3111 " \"ws_upg\":\"%lu\",\n"
3112 " \"rejected\":\"%lu\",\n"
3113 " \"http2_upg\":\"%lu\""
3115 vh->name, vh->listen_port,
3116 #ifdef LWS_OPENSSL_SUPPORT
3121 !!(vh->options & LWS_SERVER_OPTION_STS),
3122 vh->conn_stats.rx, vh->conn_stats.tx,
3123 vh->conn_stats.conn, vh->conn_stats.trans,
3124 vh->conn_stats.ws_upg,
3125 vh->conn_stats.rejected,
3126 vh->conn_stats.http2_upg
3129 if (vh->mount_list) {
3130 const struct lws_http_mount *m = vh->mount_list;
3132 buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":[");
3135 buf += lws_snprintf(buf, end - buf, ",");
3136 buf += lws_snprintf(buf, end - buf,
3137 "\n {\n \"mountpoint\":\"%s\",\n"
3138 " \"origin\":\"%s%s\",\n"
3139 " \"cache_max_age\":\"%d\",\n"
3140 " \"cache_reuse\":\"%d\",\n"
3141 " \"cache_revalidate\":\"%d\",\n"
3142 " \"cache_intermediaries\":\"%d\"\n"
3145 prots[m->origin_protocol],
3149 m->cache_revalidate,
3150 m->cache_intermediaries);
3152 buf += lws_snprintf(buf, end - buf,
3153 ",\n \"default\":\"%s\"",
3155 buf += lws_snprintf(buf, end - buf, "\n }");
3159 buf += lws_snprintf(buf, end - buf, "\n ]");
3162 if (vh->protocols) {
3166 buf += lws_snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
3167 while (n < vh->count_protocols) {
3169 buf += lws_snprintf(buf, end - buf, ",");
3170 buf += lws_snprintf(buf, end - buf,
3172 " \"status\":\"ok\"\n }\n }"
3174 vh->protocols[n].name);
3178 buf += lws_snprintf(buf, end - buf, "\n ]");
3181 buf += lws_snprintf(buf, end - buf, "\n}");
3187 LWS_EXTERN LWS_VISIBLE int
3188 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
3191 char *orig = buf, *end = buf + len - 1, first = 1;
3192 const struct lws_vhost *vh = context->vhost_list;
3193 const struct lws_context_per_thread *pt;
3194 time_t t = time(NULL);
3195 int n, listening = 0, cgi_count = 0;
3196 struct lws_conn_stats cs;
3199 struct lws_cgi * const *pcgi;
3202 #ifdef LWS_USE_LIBUV
3206 buf += lws_snprintf(buf, end - buf, "{ "
3207 "\"version\":\"%s\",\n"
3208 "\"uptime\":\"%ld\",\n",
3209 lws_get_library_version(),
3212 #ifdef LWS_HAVE_GETLOADAVG
3217 m = getloadavg(d, 3);
3218 for (n = 0; n < m; n++) {
3219 buf += lws_snprintf(buf, end - buf,
3220 "\"l%d\":\"%.2f\",\n",
3226 buf += lws_snprintf(buf, end - buf, "\"contexts\":[\n");
3228 buf += lws_snprintf(buf, end - buf, "{ "
3229 "\"context_uptime\":\"%ld\",\n"
3230 "\"cgi_spawned\":\"%d\",\n"
3231 "\"pt_fd_max\":\"%d\",\n"
3232 "\"ah_pool_max\":\"%d\",\n"
3233 "\"deprecated\":\"%d\",\n"
3234 "\"wsi_alive\":\"%d\",\n",
3235 (unsigned long)(t - context->time_up),
3236 context->count_cgi_spawned,
3237 context->fd_limit_per_thread,
3238 context->max_http_header_pool,
3239 context->deprecated,
3240 context->count_wsi_allocated);
3242 buf += lws_snprintf(buf, end - buf, "\"pt\":[\n ");
3243 for (n = 0; n < context->count_threads; n++) {
3244 pt = &context->pt[n];
3246 buf += lws_snprintf(buf, end - buf, ",");
3247 buf += lws_snprintf(buf, end - buf,
3249 " \"fds_count\":\"%d\",\n"
3250 " \"ah_pool_inuse\":\"%d\",\n"
3251 " \"ah_wait_list\":\"%d\"\n"
3254 pt->ah_count_in_use,
3255 pt->ah_wait_list_length);
3258 buf += lws_snprintf(buf, end - buf, "]");
3260 buf += lws_snprintf(buf, end - buf, ", \"vhosts\":[\n ");
3263 vh = context->vhost_list;
3265 cs = context->conn_stats;
3266 lws_sum_stats(context, &cs);
3273 buf += lws_json_dump_vhost(vh, buf, end - buf);
3278 vh = vh->vhost_next;
3281 buf += lws_snprintf(buf, end - buf,
3282 "],\n\"listen_wsi\":\"%d\",\n"
3283 " \"rx\":\"%llu\",\n"
3284 " \"tx\":\"%llu\",\n"
3285 " \"conn\":\"%lu\",\n"
3286 " \"trans\":\"%lu\",\n"
3287 " \"ws_upg\":\"%lu\",\n"
3288 " \"rejected\":\"%lu\",\n"
3289 " \"http2_upg\":\"%lu\"",
3291 cs.rx, cs.tx, cs.conn, cs.trans,
3292 cs.ws_upg, cs.rejected, cs.http2_upg);
3295 for (n = 0; n < context->count_threads; n++) {
3296 pt = &context->pt[n];
3297 pcgi = &pt->cgi_list;
3300 pcgi = &(*pcgi)->cgi_list;
3306 buf += lws_snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
3309 buf += lws_snprintf(buf, end - buf, "}");
3312 buf += lws_snprintf(buf, end - buf, "]}\n ");
3319 #if defined(LWS_WITH_STATS)
3321 LWS_VISIBLE LWS_EXTERN uint64_t
3322 lws_stats_get(struct lws_context *context, int index)
3324 if (index >= LWSSTATS_SIZE)
3327 return context->lws_stats[index];
3330 LWS_VISIBLE LWS_EXTERN void
3331 lws_stats_log_dump(struct lws_context *context)
3333 struct lws_vhost *v = context->vhost_list;
3336 if (!context->updated)
3339 context->updated = 0;
3342 lwsl_notice("LWS internal statistics dump ----->\n");
3343 lwsl_notice("LWSSTATS_C_CONNECTIONS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_CONNECTIONS));
3344 lwsl_notice("LWSSTATS_C_API_CLOSE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_CLOSE));
3345 lwsl_notice("LWSSTATS_C_API_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_READ));
3346 lwsl_notice("LWSSTATS_C_API_LWS_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_LWS_WRITE));
3347 lwsl_notice("LWSSTATS_C_API_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_WRITE));
3348 lwsl_notice("LWSSTATS_C_WRITE_PARTIALS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITE_PARTIALS));
3349 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_REQ));
3350 lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_EFF_REQ));
3351 lwsl_notice("LWSSTATS_C_WRITEABLE_CB: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB));
3352 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_FAILED));
3353 lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED));
3354 lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX));
3356 lwsl_notice("LWSSTATS_C_TIMEOUTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_TIMEOUTS));
3357 lwsl_notice("LWSSTATS_C_SERVICE_ENTRY: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SERVICE_ENTRY));
3358 lwsl_notice("LWSSTATS_B_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ));
3359 lwsl_notice("LWSSTATS_B_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE));
3360 lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS));
3361 lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000);
3362 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED))
3363 lwsl_notice(" Avg accept delay: %8llums\n",
3364 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) /
3365 lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000);
3366 lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / 1000);
3367 if (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX))
3368 lwsl_notice(" Avg accept-rx delay: %8llums\n",
3369 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) /
3370 lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000);
3372 lwsl_notice("LWSSTATS_MS_WRITABLE_DELAY: %8lluus\n",
3373 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY));
3374 lwsl_notice("LWSSTATS_MS_WORST_WRITABLE_DELAY: %8lluus\n",
3375 (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WORST_WRITABLE_DELAY));
3376 if (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))
3377 lwsl_notice(" Avg writable delay: %8lluus\n",
3378 (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY) /
3379 lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)));
3380 lwsl_notice("Simultaneous SSL restriction: %8d/%d/%d\n", context->simultaneous_ssl,
3381 context->simultaneous_ssl_restriction, context->ssl_gate_accepts);
3383 lwsl_notice("Live wsi: %8d\n", context->count_wsi_allocated);
3385 #if defined(LWS_WITH_STATS)
3386 context->updated = 1;
3390 if (v->use_ssl && v->lserv_wsi) {
3391 struct lws_context_per_thread *pt = &context->pt[(int)v->lserv_wsi->tsi];
3392 struct lws_pollfd *pfd;
3394 pfd = &pt->fds[v->lserv_wsi->position_in_fds_table];
3396 lwsl_notice(" Listen port %d actual POLLIN: %d\n",
3397 v->listen_port, (int)pfd->events & LWS_POLLIN);
3403 for (n = 0; n < context->count_threads; n++) {
3404 struct lws_context_per_thread *pt = &context->pt[n];
3408 lwsl_notice("PT %d\n", n + 1);
3412 lwsl_notice(" AH in use / max: %d / %d\n",
3413 pt->ah_count_in_use,
3414 context->max_http_header_pool);
3416 wl = pt->ah_wait_list;
3419 wl = wl->u.hdr.ah_wait_list;
3422 lwsl_notice(" AH wait list count / actual: %d / %d\n",
3423 pt->ah_wait_list_length, m);
3432 lws_stats_atomic_bump(struct lws_context * context,
3433 struct lws_context_per_thread *pt, int index, uint64_t bump)
3436 context->lws_stats[index] += bump;
3437 if (index != LWSSTATS_C_SERVICE_ENTRY)
3438 context->updated = 1;
3443 lws_stats_atomic_max(struct lws_context * context,
3444 struct lws_context_per_thread *pt, int index, uint64_t val)
3447 if (val > context->lws_stats[index]) {
3448 context->lws_stats[index] = val;
3449 context->updated = 1;