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)
33 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
34 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
36 static const char * const log_level_names[] = {
50 lws_free_wsi(struct lws *wsi)
55 /* Protocol user data may be allocated either internally by lws
56 * or by specified the user.
57 * We should only free what we allocated. */
58 if (wsi->protocol && wsi->protocol->per_session_data_size &&
59 wsi->user_space && !wsi->user_space_externally_allocated)
60 lws_free(wsi->user_space);
62 lws_free_set_NULL(wsi->rxflow_buffer);
63 lws_free_set_NULL(wsi->trunc_alloc);
66 /* we're closing, losing some rx is OK */
67 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
69 /* we may not have an ah, but may be on the waiting list... */
70 lws_header_table_detach(wsi, 0);
72 wsi->context->count_wsi_allocated--;
73 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
74 wsi->context->count_wsi_allocated);
80 lws_remove_from_timeout_list(struct lws *wsi)
82 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
84 if (!wsi->timeout_list_prev) /* ie, not part of the list */
88 /* if we have a next guy, set his prev to our prev */
89 if (wsi->timeout_list)
90 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
91 /* set our prev guy to our next guy instead of us */
92 *wsi->timeout_list_prev = wsi->timeout_list;
94 /* we're out of the list, we should not point anywhere any more */
95 wsi->timeout_list_prev = NULL;
96 wsi->timeout_list = NULL;
101 * lws_set_timeout() - marks the wsi as subject to a timeout
103 * You will not need this unless you are doing something special
105 * @wsi: Websocket connection instance
106 * @reason: timeout reason
107 * @secs: how many seconds
111 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
113 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
120 if (reason && !wsi->timeout_list_prev) {
121 /* our next guy is current first guy */
122 wsi->timeout_list = pt->timeout_list;
123 /* if there is a next guy, set his prev ptr to our next ptr */
124 if (wsi->timeout_list)
125 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
126 /* our prev ptr is first ptr */
127 wsi->timeout_list_prev = &pt->timeout_list;
128 /* set the first guy to be us */
129 *wsi->timeout_list_prev = wsi;
132 lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
133 wsi->pending_timeout_limit = now + secs;
134 wsi->pending_timeout = reason;
139 lws_remove_from_timeout_list(wsi);
143 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
145 struct lws_context_per_thread *pt;
146 struct lws **pwsi, *wsi1, *wsi2;
147 struct lws_context *context;
148 struct lws_tokens eff_buf;
156 context = wsi->context;
157 pt = &context->pt[(int)wsi->tsi];
159 /* if we have children, close them first */
160 if (wsi->child_list) {
161 wsi2 = wsi->child_list;
163 //lwsl_notice("%s: closing %p: close child %p\n",
164 // __func__, wsi, wsi2);
165 wsi1 = wsi2->sibling_list;
166 //lwsl_notice("%s: closing %p: next sibling %p\n",
167 // __func__, wsi2, wsi1);
169 /* stop it doing shutdown processing */
170 wsi2->socket_is_permanently_unusable = 1;
171 lws_close_free_wsi(wsi2, reason);
174 wsi->child_list = NULL;
178 if (wsi->mode == LWSCM_CGI) {
179 /* we are not a network connection, but a handler for CGI io */
180 if (wsi->parent && wsi->parent->cgi)
181 /* end the binding between us and master */
182 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
183 wsi->socket_is_permanently_unusable = 1;
185 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
186 goto just_kill_connection;
190 struct lws_cgi **pcgi = &pt->cgi_list;
191 /* remove us from the cgi list */
192 lwsl_notice("%s: remove cgi %p from list\n", __func__, wsi->cgi);
194 if (*pcgi == wsi->cgi) {
195 /* drop us from the pt cgi list */
196 *pcgi = (*pcgi)->cgi_list;
199 pcgi = &(*pcgi)->cgi_list;
201 /* we have a cgi going, we must kill it */
202 wsi->cgi->being_closed = 1;
207 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
208 wsi->u.http.fd != LWS_INVALID_FILE) {
209 lws_plat_file_close(wsi, wsi->u.http.fd);
210 wsi->u.http.fd = LWS_INVALID_FILE;
211 wsi->vhost->protocols[0].callback(wsi,
212 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
214 if (wsi->socket_is_permanently_unusable ||
215 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
216 wsi->state == LWSS_SHUTDOWN)
217 goto just_kill_connection;
219 wsi->state_pre_close = wsi->state;
221 switch (wsi->state_pre_close) {
222 case LWSS_DEAD_SOCKET:
225 /* we tried the polite way... */
226 case LWSS_AWAITING_CLOSE_ACK:
227 goto just_kill_connection;
229 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
230 if (wsi->trunc_len) {
231 lws_callback_on_writable(wsi);
234 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
235 goto just_kill_connection;
237 if (wsi->trunc_len) {
238 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
239 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
240 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
246 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
247 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
248 goto just_kill_connection;
250 if (wsi->mode == LWSCM_HTTP_SERVING)
251 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
252 wsi->user_space, NULL, 0);
253 if (wsi->mode == LWSCM_HTTP_CLIENT)
254 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
255 wsi->user_space, NULL, 0);
258 * are his extensions okay with him closing? Eg he might be a mux
259 * parent and just his ch1 aspect is closing?
262 if (lws_ext_cb_active(wsi,
263 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
264 lwsl_ext("extension vetoed close\n");
269 * flush any tx pending from extensions, since we may send close packet
270 * if there are problems with send, just nuke the connection
275 eff_buf.token = NULL;
276 eff_buf.token_len = 0;
278 /* show every extension the new incoming data */
280 m = lws_ext_cb_active(wsi,
281 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
283 lwsl_ext("Extension reports fatal error\n");
284 goto just_kill_connection;
288 * at least one extension told us he has more
289 * to spill, so we will go around again after
293 /* assuming they left us something to send, send it */
295 if (eff_buf.token_len)
296 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
297 eff_buf.token_len) !=
299 lwsl_debug("close: ext spill failed\n");
300 goto just_kill_connection;
305 * signal we are closing, lws_write will
306 * add any necessary version-specific stuff. If the write fails,
307 * no worries we are closing anyway. If we didn't initiate this
308 * close, then our state has been changed to
309 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
311 * Likewise if it's a second call to close this connection after we
312 * sent the close indication to the peer already, we are in state
313 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
316 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
317 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
318 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
319 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
320 lwsl_debug("sending close indication...\n");
322 /* if no prepared close reason, use 1000 and no aux data */
323 if (!wsi->u.ws.close_in_ping_buffer_len) {
324 wsi->u.ws.close_in_ping_buffer_len = 2;
325 wsi->u.ws.ping_payload_buf[LWS_PRE] =
326 (reason >> 16) & 0xff;
327 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
331 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
332 wsi->u.ws.close_in_ping_buffer_len,
336 * we have sent a nice protocol level indication we
337 * now wish to close, we should not send anything more
339 wsi->state = LWSS_AWAITING_CLOSE_ACK;
342 * ...and we should wait for a reply for a bit
345 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
346 lwsl_debug("sent close indication, awaiting ack\n");
351 lwsl_info("close: sending close packet failed, hanging up\n");
353 /* else, the send failed and we should just hang up */
356 just_kill_connection:
358 /* detach ourselves from parent's child list */
359 pwsi = &wsi->parent->child_list;
362 lwsl_notice("%s: detach %p from parent %p\n",
363 __func__, wsi, wsi->parent);
364 *pwsi = wsi->sibling_list;
367 pwsi = &(*pwsi)->sibling_list;
370 lwsl_err("%s: failed to detach from parent\n",
376 * Testing with ab shows that we have to stage the socket close when
377 * the system is under stress... shutdown any further TX, change the
378 * state to one that won't emit anything more, and wait with a timeout
379 * for the POLLIN to show a zero-size rx before coming back and doing
382 if (wsi->state != LWSS_SHUTDOWN &&
383 wsi->state != LWSS_CLIENT_UNCONNECTED &&
384 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
385 !wsi->socket_is_permanently_unusable) {
386 lwsl_info("%s: shutting down connection: %p (sock %d, state %d)\n", __func__, wsi, wsi->sock, wsi->state);
387 n = shutdown(wsi->sock, SHUT_WR);
389 lwsl_debug("closing: shutdown (state %d) ret %d\n", wsi->state, LWS_ERRNO);
391 // This causes problems with disconnection when the events are half closing connection
392 // FD_READ | FD_CLOSE (33)
394 /* libuv: no event available to guarantee completion */
395 if (!LWS_LIBUV_ENABLED(context)) {
397 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
398 wsi->state = LWSS_SHUTDOWN;
399 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
400 context->timeout_secs);
407 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
409 #ifdef LWS_WITH_HTTP_PROXY
411 lws_rewrite_destroy(wsi->rw);
416 * we won't be servicing or receiving anything further from this guy
417 * delete socket from the internal poll list if still present
419 lws_ssl_remove_wsi_from_buffered_list(wsi);
420 lws_remove_from_timeout_list(wsi);
422 /* checking return redundant since we anyway close */
423 remove_wsi_socket_from_fds(wsi);
425 wsi->state = LWSS_DEAD_SOCKET;
427 lws_free_set_NULL(wsi->rxflow_buffer);
429 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
430 wsi->mode == LWSCM_WS_SERVING ||
431 wsi->mode == LWSCM_WS_CLIENT) {
433 if (wsi->u.ws.rx_draining_ext) {
434 struct lws **w = &pt->rx_draining_ext_list;
436 wsi->u.ws.rx_draining_ext = 0;
437 /* remove us from context draining ext list */
440 *w = wsi->u.ws.rx_draining_ext_list;
443 w = &((*w)->u.ws.rx_draining_ext_list);
445 wsi->u.ws.rx_draining_ext_list = NULL;
448 if (wsi->u.ws.tx_draining_ext) {
449 struct lws **w = &pt->tx_draining_ext_list;
451 wsi->u.ws.tx_draining_ext = 0;
452 /* remove us from context draining ext list */
455 *w = wsi->u.ws.tx_draining_ext_list;
458 w = &((*w)->u.ws.tx_draining_ext_list);
460 wsi->u.ws.tx_draining_ext_list = NULL;
462 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
464 if (wsi->trunc_alloc)
465 /* not going to be completed... nuke it */
466 lws_free_set_NULL(wsi->trunc_alloc);
468 wsi->u.ws.ping_payload_len = 0;
469 wsi->u.ws.ping_pending_flag = 0;
472 /* tell the user it's all over for this guy */
474 if (wsi->protocol && wsi->protocol->callback &&
475 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
476 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
477 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
478 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
479 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
480 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
481 lwsl_debug("calling back CLOSED\n");
482 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
483 wsi->user_space, NULL, 0);
484 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
485 lwsl_debug("calling back CLOSED_HTTP\n");
486 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
487 wsi->user_space, NULL, 0 );
488 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
489 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
490 lwsl_debug("Connection closed before server reply\n");
491 wsi->vhost->protocols[0].callback(wsi,
492 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
493 wsi->user_space, NULL, 0);
495 lwsl_debug("not calling back closed mode=%d state=%d\n",
496 wsi->mode, wsi->state_pre_close);
498 /* deallocate any active extension contexts */
500 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
501 lwsl_warn("extension destruction failed\n");
503 * inform all extensions in case they tracked this guy out of band
504 * even though not active on him specifically
506 if (lws_ext_cb_all_exts(context, wsi,
507 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
508 lwsl_warn("ext destroy wsi failed\n");
510 wsi->socket_is_permanently_unusable = 1;
513 if (LWS_LIBUV_ENABLED(context)) {
514 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
515 /* libuv has to do his own close handle processing asynchronously */
516 lws_libuv_closehandle(wsi);
522 lws_close_free_wsi_final(wsi);
526 lws_close_free_wsi_final(struct lws *wsi)
530 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
532 //lwsl_err("*** closing sockfd %d\n", wsi->sock);
533 n = compatible_close(wsi->sock);
535 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
538 compatible_close(wsi->sock);
540 wsi->sock = LWS_SOCK_INVALID;
543 /* outermost destroy notification for wsi (user_space still intact) */
544 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
545 wsi->user_space, NULL, 0);
549 for (n = 0; n < 6; n++)
550 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0)
551 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
561 * lws_get_urlarg_by_name() - return pointer to arg value if present
562 * @wsi: the connection to check
563 * @name: the arg name, like "token="
564 * @buf: the buffer to receive the urlarg (including the name= part)
565 * @len: the length of the buffer to receive the urlarg
567 * Returns NULL if not found or a pointer inside @buf to just after the
571 LWS_VISIBLE LWS_EXTERN const char *
572 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)
574 int n = 0, sl = strlen(name);
576 while (lws_hdr_copy_fragment(wsi, buf, len,
577 WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {
579 if (!strncmp(buf, name, sl))
590 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
594 ipv6 = LWS_IPV6_ENABLED(context);
598 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
603 lws_get_addresses(struct lws_context *context, void *ads, char *name,
604 int name_len, char *rip, int rip_len)
607 struct addrinfo ai, *res;
608 struct sockaddr_in addr4;
613 addr4.sin_family = AF_UNSPEC;
616 if (LWS_IPV6_ENABLED(context)) {
617 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
618 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
622 // Strip off the IPv4 to IPv6 header if one exists
623 if (strncmp(rip, "::ffff:", 7) == 0)
624 memmove(rip, rip + 7, strlen(rip) - 6);
626 getnameinfo((struct sockaddr *)ads,
627 sizeof(struct sockaddr_in6), name,
628 name_len, NULL, 0, 0);
634 struct addrinfo *result;
636 memset(&ai, 0, sizeof ai);
637 ai.ai_family = PF_UNSPEC;
638 ai.ai_socktype = SOCK_STREAM;
639 ai.ai_flags = AI_CANONNAME;
641 if (getnameinfo((struct sockaddr *)ads,
642 sizeof(struct sockaddr_in),
643 name, name_len, NULL, 0, 0))
649 if (getaddrinfo(name, NULL, &ai, &result))
653 while (addr4.sin_family == AF_UNSPEC && res) {
654 switch (res->ai_family) {
656 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
657 addr4.sin_family = AF_INET;
663 freeaddrinfo(result);
666 if (addr4.sin_family == AF_UNSPEC)
669 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
686 * lws_get_peer_simple() - Get client address information without RDNS
687 * @wsi: Local struct lws associated with
688 * @name: Buffer to take client address name
689 * @name_len: Length of client address name buffer
691 * This provides a 123.123.123.123 type IP address in @name from the
692 * peer that has connected to @wsi
695 LWS_VISIBLE const char *
696 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
701 struct sockaddr_in6 sin6;
703 struct sockaddr_in sin4;
708 if (LWS_IPV6_ENABLED(wsi->context)) {
722 if (getpeername(wsi->sock, p, &len) < 0 || len > olen) {
723 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
727 return lws_plat_inet_ntop(af, q, name, namelen);
734 * lws_get_peer_addresses() - Get client address information
735 * @wsi: Local struct lws associated with
736 * @fd: Connection socket descriptor
737 * @name: Buffer to take client address name
738 * @name_len: Length of client address name buffer
739 * @rip: Buffer to take client address IP dotted quad
740 * @rip_len: Length of client address IP buffer
742 * This function fills in @name and @rip with the name and IP of
743 * the client connected with socket descriptor @fd. Names may be
744 * truncated if there is not enough room. If either cannot be
745 * determined, they will be returned as valid zero-length strings.
749 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
750 int name_len, char *rip, int rip_len)
755 struct sockaddr_in6 sin6;
757 struct sockaddr_in sin4;
758 struct lws_context *context = wsi->context;
765 lws_latency_pre(context, wsi);
768 if (LWS_IPV6_ENABLED(context)) {
778 if (getpeername(fd, p, &len) < 0) {
779 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
783 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
786 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
798 * lws_context_user() - get the user data associated with the context
799 * @context: Websocket context
801 * This returns the optional user allocation that can be attached to
802 * the context the sockets live in at context_create time. It's a way
803 * to let all sockets serviced in the same context share data without
804 * using globals statics in the user code.
807 lws_context_user(struct lws_context *context)
809 return context->user_space;
812 LWS_VISIBLE struct lws_vhost *
813 lws_vhost_get(struct lws *wsi)
818 LWS_VISIBLE struct lws_vhost *
819 lws_get_vhost(struct lws *wsi)
824 LWS_VISIBLE const struct lws_protocols *
825 lws_protocol_get(struct lws *wsi)
827 return wsi->protocol;
832 * lws_callback_all_protocol() - Callback all connections using
833 * the given protocol with the given reason
835 * @protocol: Protocol whose connections will get callbacks
836 * @reason: Callback reason index
840 lws_callback_all_protocol(struct lws_context *context,
841 const struct lws_protocols *protocol, int reason)
843 struct lws_context_per_thread *pt = &context->pt[0];
844 unsigned int n, m = context->count_threads;
848 for (n = 0; n < pt->fds_count; n++) {
849 wsi = wsi_from_fd(context, pt->fds[n].fd);
852 if (wsi->protocol == protocol)
853 protocol->callback(wsi, reason, wsi->user_space,
863 * lws_callback_all_protocol_vhost() - Callback all connections using
864 * the given protocol with the given reason
866 * @vh: Vhost whose connections will get callbacks
867 * @protocol: Which protocol to match
868 * @reason: Callback reason index
872 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
873 const struct lws_protocols *protocol, int reason)
875 struct lws_context *context = vh->context;
876 struct lws_context_per_thread *pt = &context->pt[0];
877 unsigned int n, m = context->count_threads;
881 for (n = 0; n < pt->fds_count; n++) {
882 wsi = wsi_from_fd(context, pt->fds[n].fd);
885 if (wsi->vhost == vh && wsi->protocol == protocol)
886 protocol->callback(wsi, reason, wsi->user_space,
898 * lws_get_socket_fd() - returns the socket file descriptor
900 * You will not need this unless you are doing something special
902 * @wsi: Websocket connection instance
906 lws_get_socket_fd(struct lws *wsi)
915 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
916 int ret, int completed)
918 unsigned long long u;
921 u = time_in_microseconds();
924 wsi->latency_start = u;
925 if (!wsi->action_start)
926 wsi->action_start = u;
930 if (wsi->action_start == wsi->latency_start)
932 "Completion first try lat %lluus: %p: ret %d: %s\n",
933 u - wsi->latency_start,
934 (void *)wsi, ret, action);
937 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
938 u - wsi->action_start,
939 u - wsi->latency_start,
940 (void *)wsi, ret, action);
941 wsi->action_start = 0;
943 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
944 u - wsi->latency_start, (void *)wsi, ret, action);
946 if (u - wsi->latency_start > context->worst_latency) {
947 context->worst_latency = u - wsi->latency_start;
948 strcpy(context->worst_latency_info, buf);
950 lwsl_latency("%s", buf);
957 * lws_rx_flow_control() - Enable and disable socket servicing for
960 * If the output side of a server process becomes choked, this allows flow
961 * control for the input side.
963 * @wsi: Websocket connection instance to get callback for
964 * @enable: 0 = disable read servicing for this connection, 1 = enable
968 lws_rx_flow_control(struct lws *wsi, int enable)
970 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
973 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
974 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
980 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
982 * When the user server code realizes it can accept more input, it can
983 * call this to have the RX flow restriction removed from all connections using
984 * the given protocol.
986 * @protocol: all connections using this protocol will be allowed to receive
990 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
991 const struct lws_protocols *protocol)
993 const struct lws_context_per_thread *pt = &context->pt[0];
995 unsigned int n, m = context->count_threads;
998 for (n = 0; n < pt->fds_count; n++) {
999 wsi = wsi_from_fd(context, pt->fds[n].fd);
1002 if (wsi->protocol == protocol)
1003 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1011 * lws_canonical_hostname() - returns this host's hostname
1013 * This is typically used by client code to fill in the host parameter
1014 * when making a client connection. You can only call it after the context
1017 * @context: Websocket context
1019 LWS_VISIBLE extern const char *
1020 lws_canonical_hostname(struct lws_context *context)
1022 return (const char *)context->canonical_hostname;
1025 int user_callback_handle_rxflow(lws_callback_function callback_function,
1027 enum lws_callback_reasons reason, void *user,
1028 void *in, size_t len)
1032 n = callback_function(wsi, reason, user, in, len);
1034 n = _lws_rx_flow_control(wsi);
1041 * lws_set_proxy() - Setups proxy to lws_context.
1042 * @context: pointer to struct lws_context you want set proxy to
1043 * @proxy: pointer to c string containing proxy in format address:port
1045 * Returns 0 if proxy string was parsed and proxy was setup.
1046 * Returns -1 if @proxy is NULL or has incorrect format.
1048 * This is only required if your OS does not provide the http_proxy
1049 * environment variable (eg, OSX)
1051 * IMPORTANT! You should call this function right after creation of the
1052 * lws_context and before call to connect. If you call this
1053 * function after connect behavior is undefined.
1054 * This function will override proxy settings made on lws_context
1055 * creation with genenv() call.
1059 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1062 char authstring[96];
1067 p = strchr(proxy, '@');
1068 if (p) { /* auth is around */
1070 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1073 strncpy(authstring, proxy, p - proxy);
1074 // null termination not needed on input
1075 if (lws_b64_encode_string(authstring, (p - proxy),
1076 vhost->proxy_basic_auth_token,
1077 sizeof vhost->proxy_basic_auth_token) < 0)
1080 lwsl_notice(" Proxy auth in use\n");
1084 vhost->proxy_basic_auth_token[0] = '\0';
1086 strncpy(vhost->http_proxy_address, proxy,
1087 sizeof(vhost->http_proxy_address) - 1);
1088 vhost->http_proxy_address[
1089 sizeof(vhost->http_proxy_address) - 1] = '\0';
1091 p = strchr(vhost->http_proxy_address, ':');
1092 if (!p && !vhost->http_proxy_port) {
1093 lwsl_err("http_proxy needs to be ads:port\n");
1099 vhost->http_proxy_port = atoi(p + 1);
1103 lwsl_notice(" Proxy %s:%u\n", vhost->http_proxy_address,
1104 vhost->http_proxy_port);
1109 lwsl_err("proxy auth too long\n");
1115 * lws_get_protocol() - Returns a protocol pointer from a websocket
1117 * @wsi: pointer to struct websocket you want to know the protocol of
1120 * Some apis can act on all live connections of a given protocol,
1121 * this is how you can get a pointer to the active protocol if needed.
1124 LWS_VISIBLE const struct lws_protocols *
1125 lws_get_protocol(struct lws *wsi)
1127 return wsi->protocol;
1131 lws_is_final_fragment(struct lws *wsi)
1133 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
1134 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
1135 wsi->u.ws.rx_draining_ext);
1136 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1139 LWS_VISIBLE unsigned char
1140 lws_get_reserved_bits(struct lws *wsi)
1142 return wsi->u.ws.rsv;
1146 lws_ensure_user_space(struct lws *wsi)
1148 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1152 /* allocate the per-connection user memory (if any) */
1154 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1155 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1156 if (wsi->user_space == NULL) {
1157 lwsl_err("Out of memory for conn user space\n");
1161 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
1162 __func__, wsi, wsi->protocol->per_session_data_size,
1168 * lwsl_timestamp: generate logging timestamp string
1170 * @level: logging level
1171 * @p: char * buffer to take timestamp
1174 * returns length written in p
1177 lwsl_timestamp(int level, char *p, int len)
1179 time_t o_now = time(NULL);
1180 unsigned long long now;
1181 struct tm *ptm = NULL;
1189 ptm = localtime(&o_now);
1191 if (localtime_r(&o_now, &tm))
1196 for (n = 0; n < LLL_COUNT; n++) {
1197 if (level != (1 << n))
1199 now = time_in_microseconds() / 100;
1201 n = snprintf(p, len,
1202 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1203 ptm->tm_year + 1900,
1209 (int)(now % 10000), log_level_names[n]);
1211 n = snprintf(p, len, "[%llu:%04d] %s: ",
1212 (unsigned long long) now / 10000,
1213 (int)(now % 10000), log_level_names[n]);
1220 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1224 lwsl_timestamp(level, buf, sizeof(buf));
1226 fprintf(stderr, "%s%s", buf, line);
1229 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1233 if (!(log_level & filter))
1236 vsnprintf(buf, sizeof(buf), format, vl);
1237 buf[sizeof(buf) - 1] = '\0';
1239 lwsl_emit(filter, buf);
1242 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1246 va_start(ap, format);
1247 _lws_logv(filter, format, ap);
1252 * lws_set_log_level() - Set the logging bitfield
1253 * @level: OR together the LLL_ debug contexts you want output from
1254 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1255 * function to perform log string emission instead of
1256 * the default stderr one.
1258 * log level defaults to "err", "warn" and "notice" contexts enabled and
1259 * emission on stderr.
1262 LWS_VISIBLE void lws_set_log_level(int level,
1263 void (*func)(int level, const char *line))
1271 * lws_use_ssl() - Find out if connection is using SSL
1272 * @wsi: websocket connection to check
1274 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1275 * using verified cert, and 2 if using SSL but the cert was not
1276 * checked (appears for client wsi told to skip check on connection)
1279 lws_is_ssl(struct lws *wsi)
1281 #ifdef LWS_OPENSSL_SUPPORT
1282 return wsi->use_ssl;
1290 * lws_partial_buffered() - find out if lws buffered the last write
1291 * @wsi: websocket connection to check
1293 * Returns 1 if you cannot use lws_write because the last
1294 * write on this connection is still buffered, and can't be cleared without
1295 * returning to the service loop and waiting for the connection to be
1298 * If you will try to do >1 lws_write call inside a single
1299 * WRITEABLE callback, you must check this after every write and bail if
1300 * set, ask for a new writeable callback and continue writing from there.
1302 * This is never set at the start of a writeable callback, but any write
1307 lws_partial_buffered(struct lws *wsi)
1309 return !!wsi->trunc_len;
1312 void lws_set_protocol_write_pending(struct lws *wsi,
1313 enum lws_pending_protocol_send pend)
1315 lwsl_info("setting pps %d\n", pend);
1318 lwsl_err("pps overwrite\n");
1320 lws_rx_flow_control(wsi, 0);
1321 lws_callback_on_writable(wsi);
1325 lws_get_peer_write_allowance(struct lws *wsi)
1327 #ifdef LWS_USE_HTTP2
1328 /* only if we are using HTTP2 on this connection */
1329 if (wsi->mode != LWSCM_HTTP2_SERVING)
1331 /* user is only interested in how much he can send, or that he can't */
1332 if (wsi->u.http2.tx_credit <= 0)
1335 return wsi->u.http2.tx_credit;
1343 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1345 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1346 memset(&wsi->u, 0, sizeof(wsi->u));
1350 LWS_VISIBLE struct lws_plat_file_ops *
1351 lws_get_fops(struct lws_context *context)
1353 return &context->fops;
1357 * lws_get_context - Allow geting lws_context from a Websocket connection
1360 * With this function, users can access context in the callback function.
1361 * Otherwise users may have to declare context as a global variable.
1363 * @wsi: Websocket connection instance
1366 LWS_VISIBLE LWS_EXTERN struct lws_context *
1367 lws_get_context(const struct lws *wsi)
1369 return wsi->context;
1372 LWS_VISIBLE LWS_EXTERN int
1373 lws_get_count_threads(struct lws_context *context)
1375 return context->count_threads;
1378 LWS_VISIBLE LWS_EXTERN void *
1379 lws_wsi_user(struct lws *wsi)
1381 return wsi->user_space;
1384 LWS_VISIBLE LWS_EXTERN struct lws *
1385 lws_get_parent(const struct lws *wsi)
1390 LWS_VISIBLE LWS_EXTERN struct lws *
1391 lws_get_child(const struct lws *wsi)
1393 return wsi->child_list;
1396 LWS_VISIBLE LWS_EXTERN void
1397 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1398 unsigned char *buf, size_t len)
1400 unsigned char *p, *start;
1401 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1403 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1405 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1407 *p++ = (((int)status) >> 8) & 0xff;
1408 *p++ = ((int)status) & 0xff;
1411 while (len-- && p < start + budget)
1414 wsi->u.ws.close_in_ping_buffer_len = p - start;
1418 _lws_rx_flow_control(struct lws *wsi)
1420 /* there is no pending change */
1421 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1422 lwsl_debug("%s: no pending change\n", __func__);
1426 /* stuff is still buffered, not ready to really accept new input */
1427 if (wsi->rxflow_buffer) {
1428 /* get ourselves called back to deal with stashed buffer */
1429 lws_callback_on_writable(wsi);
1433 /* pending is cleared, we can change rxflow state */
1435 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1437 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1438 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1440 /* adjust the pollfd for this wsi */
1442 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1443 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1444 lwsl_info("%s: fail\n", __func__);
1448 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1455 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1457 static const unsigned char e0f4[] = {
1458 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1459 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1460 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1461 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1462 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1463 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1464 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1465 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1466 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1467 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1468 0x80 | ((4 - 1) << 2) | 1, /* ea */
1469 0x80 | ((4 - 1) << 2) | 1, /* eb */
1470 0x80 | ((4 - 1) << 2) | 1, /* ec */
1471 0x80 | ((2 - 1) << 2) | 1, /* ed */
1472 0x80 | ((4 - 1) << 2) | 1, /* ee */
1473 0x80 | ((4 - 1) << 2) | 1, /* ef */
1474 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1475 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1476 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1477 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1478 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1481 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1482 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1484 unsigned char s = *state;
1487 unsigned char c = *buf++;
1491 if (c < 0xc2 || c > 0xf4)
1494 s = 0x80 | ((4 - 1) << 2);
1499 if (c < (s & 0xf0) ||
1500 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1502 s = e0f4[21 + (s & 3)];
1512 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1513 * Notice it does so by dropping '\0' into input string
1514 * and the leading / on the path is consequently lost
1516 * @p: incoming uri string.. will get written to
1517 * @prot: result pointer for protocol part (https://)
1518 * @ads: result pointer for address part
1519 * @port: result pointer for port part
1520 * @path: result pointer for path part
1523 LWS_VISIBLE LWS_EXTERN int
1524 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1528 static const char *slash = "/";
1530 /* cut up the location into address, port and path */
1532 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1543 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1545 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1548 while (*p && *p != ':' && *p != '/')
1553 while (*p && *p != '/')
1566 #ifdef LWS_NO_EXTENSIONS
1568 /* we need to provide dummy callbacks for internal exts
1569 * so user code runs when faced with a lib compiled with
1570 * extensions disabled.
1574 lws_extension_callback_pm_deflate(struct lws_context *context,
1575 const struct lws_extension *ext,
1577 enum lws_extension_callback_reasons reason,
1578 void *user, void *in, size_t len)
1593 lws_socket_bind(struct lws_vhost *vhost, int sockfd, int port,
1597 #ifdef LWS_USE_UNIX_SOCK
1598 struct sockaddr_un serv_unix;
1601 struct sockaddr_in6 serv_addr6;
1603 struct sockaddr_in serv_addr4;
1604 socklen_t len = sizeof(struct sockaddr);
1606 struct sockaddr_in sin;
1609 #ifdef LWS_USE_UNIX_SOCK
1610 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1611 v = (struct sockaddr *)&serv_unix;
1612 n = sizeof(struct sockaddr_un);
1613 bzero((char *) &serv_unix, sizeof(serv_unix));
1614 serv_unix.sun_family = AF_UNIX;
1615 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1616 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1620 strcpy(serv_unix.sun_path, iface);
1621 if (serv_unix.sun_path[0] == '@')
1622 serv_unix.sun_path[0] = '\0';
1627 if (LWS_IPV6_ENABLED(vhost->context)) {
1628 v = (struct sockaddr *)&serv_addr6;
1629 n = sizeof(struct sockaddr_in6);
1630 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1631 serv_addr6.sin6_addr = in6addr_any;
1632 serv_addr6.sin6_family = AF_INET6;
1633 serv_addr6.sin6_port = htons(port);
1637 v = (struct sockaddr *)&serv_addr4;
1638 n = sizeof(serv_addr4);
1639 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1640 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1641 serv_addr4.sin_family = AF_INET;
1644 interface_to_sa(vhost->context, iface,
1645 (struct sockaddr_in *)v, n) < 0) {
1646 lwsl_err("Unable to find interface %s\n", iface);
1650 serv_addr4.sin_port = htons(port);
1653 n = bind(sockfd, v, n);
1654 #ifdef LWS_USE_UNIX_SOCK
1655 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
1656 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1657 sockfd, iface, n, LWS_ERRNO);
1662 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1663 sockfd, port, n, LWS_ERRNO);
1667 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1668 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1670 port = ntohs(sin.sin_port);
1676 LWS_VISIBLE LWS_EXTERN int
1677 lws_urlencode(const char *in, int inlen, char *out, int outlen)
1679 const char *hex = "0123456789ABCDEF";
1680 char *start = out, *end = out + outlen;
1682 while (inlen-- && out < end - 4) {
1683 if ((*in >= 'A' && *in <= 'Z') ||
1684 (*in >= 'a' && *in <= 'z') ||
1685 (*in >= '0' && *in <= '9') ||
1693 *out++ = hex[(*in) >> 4];
1694 *out++ = hex[(*in++) & 15];
1705 LWS_VISIBLE LWS_EXTERN int
1706 lws_finalize_startup(struct lws_context *context)
1708 struct lws_context_creation_info info;
1710 info.uid = context->uid;
1711 info.gid = context->gid;
1713 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1714 lws_plat_drop_app_privileges(&info);
1720 LWS_VISIBLE LWS_EXTERN int
1721 lws_is_cgi(struct lws *wsi) {
1732 lws_create_basic_wsi(struct lws_context *context, int tsi)
1734 struct lws *new_wsi;
1736 if ((unsigned int)context->pt[tsi].fds_count ==
1737 context->fd_limit_per_thread - 1) {
1738 lwsl_err("no space for new conn\n");
1742 new_wsi = lws_zalloc(sizeof(struct lws));
1743 if (new_wsi == NULL) {
1744 lwsl_err("Out of memory for new connection\n");
1749 new_wsi->context = context;
1750 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1751 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1753 /* intialize the instance struct */
1755 new_wsi->state = LWSS_CGI;
1756 new_wsi->mode = LWSCM_CGI;
1757 new_wsi->hdr_parsing_completed = 0;
1758 new_wsi->position_in_fds_table = -1;
1761 * these can only be set once the protocol is known
1762 * we set an unestablished connection's protocol pointer
1763 * to the start of the defauly vhost supported list, so it can look
1764 * for matching ones during the handshake
1766 new_wsi->protocol = context->vhost_list->protocols;
1767 new_wsi->user_space = NULL;
1768 new_wsi->ietf_spec_revision = 0;
1769 new_wsi->sock = LWS_SOCK_INVALID;
1770 context->count_wsi_allocated++;
1776 * lws_cgi: spawn network-connected cgi process
1778 * @wsi: connection to own the process
1779 * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1782 LWS_VISIBLE LWS_EXTERN int
1783 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
1784 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
1786 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1787 char *env_array[30], cgi_path[400], e[1024], *p = e,
1788 *end = p + sizeof(e) - 1, tok[256], *t;
1789 struct lws_cgi *cgi;
1790 int n, m, i, uritok = WSI_TOKEN_GET_URI;
1793 * give the master wsi a cgi struct
1796 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1798 lwsl_err("%s: OOM\n", __func__);
1803 cgi->wsi = wsi; /* set cgi's owning wsi */
1805 /* create pipes for [stdin|stdout] and [stderr] */
1807 for (n = 0; n < 3; n++)
1808 if (pipe(cgi->pipe_fds[n]) == -1)
1811 /* create cgi wsis for each stdin/out/err fd */
1813 for (n = 0; n < 3; n++) {
1814 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1815 if (!cgi->stdwsi[n])
1817 cgi->stdwsi[n]->cgi_channel = n;
1818 cgi->stdwsi[n]->vhost = wsi->vhost;
1820 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
1821 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
1823 /* read side is 0, stdin we want the write side, others read */
1824 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1825 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
1826 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
1831 for (n = 0; n < 3; n++) {
1832 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->sock);
1833 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1835 cgi->stdwsi[n]->parent = wsi;
1836 cgi->stdwsi[n]->sibling_list = wsi->child_list;
1837 wsi->child_list = cgi->stdwsi[n];
1840 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1841 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1842 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1844 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1845 cgi->stdwsi[LWS_STDIN]->sock, cgi->stdwsi[LWS_STDOUT]->sock,
1846 cgi->stdwsi[LWS_STDERR]->sock);
1848 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1850 /* the cgi stdout is always sending us http1.x header data first */
1851 wsi->hdr_state = LCHS_HEADER;
1853 /* add us to the pt list of active cgis */
1854 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
1855 cgi->cgi_list = pt->cgi_list;
1858 /* prepare his CGI env */
1862 if (lws_is_ssl(wsi))
1863 env_array[n++] = "HTTPS=ON";
1864 if (wsi->u.hdr.ah) {
1865 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1866 uritok = WSI_TOKEN_POST_URI;
1867 snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
1868 lws_hdr_simple_ptr(wsi, uritok));
1869 cgi_path[sizeof(cgi_path) - 1] = '\0';
1870 env_array[n++] = cgi_path;
1871 if (uritok == WSI_TOKEN_POST_URI)
1872 env_array[n++] = "REQUEST_METHOD=POST";
1874 env_array[n++] = "REQUEST_METHOD=GET";
1877 p += snprintf(p, end - p, "QUERY_STRING=");
1878 /* dump the individual URI Arg parameters */
1881 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
1882 WSI_TOKEN_HTTP_URI_ARGS, m);
1886 while (*t && *t != '=' && p < end - 4)
1890 i = lws_urlencode(t, i- (t - tok), p, end - p);
1902 p += snprintf(p, end - p, "PATH_INFO=%s",
1903 lws_hdr_simple_ptr(wsi, uritok) +
1904 script_uri_path_len);
1907 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
1909 p += snprintf(p, end - p, "HTTP_REFERER=%s",
1910 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
1913 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1915 p += snprintf(p, end - p, "HTTP_HOST=%s",
1916 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1919 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
1921 p += snprintf(p, end - p, "HTTP_COOKIE=%s",
1922 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
1925 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
1927 p += snprintf(p, end - p, "USER_AGENT=%s",
1928 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
1931 if (uritok == WSI_TOKEN_POST_URI) {
1932 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
1934 p += snprintf(p, end - p, "CONTENT_TYPE=%s",
1935 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
1938 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
1940 p += snprintf(p, end - p, "CONTENT_LENGTH=%s",
1941 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
1946 p += snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
1950 p += snprintf(p, end - p, "%s=%s", mp_cgienv->name,
1952 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
1955 mp_cgienv = mp_cgienv->next;
1958 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1959 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
1960 env_array[n] = NULL;
1963 for (m = 0; m < n; m++)
1964 lwsl_err(" %s\n", env_array[m]);
1968 * Actually having made the env, as a cgi we don't need the ah
1971 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
1972 lws_header_table_detach(wsi, 0);
1974 /* we are ready with the redirection pipes... run the thing */
1975 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1981 lwsl_err("fork failed, errno %d", errno);
1985 #if defined(__linux__)
1986 prctl(PR_SET_PDEATHSIG, SIGTERM);
1988 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
1991 /* we are the parent process */
1992 wsi->context->count_cgi_spawned++;
1993 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
1997 /* somewhere we can at least read things and enter it */
1999 lwsl_notice("%s: Failed to chdir\n", __func__);
2001 /* We are the forked process, redirect and kill inherited things.
2003 * Because of vfork(), we cannot do anything that changes pages in
2004 * the parent environment. Stuff that changes kernel state for the
2005 * process is OK. Stuff that happens after the execvpe() is OK.
2008 for (n = 0; n < 3; n++)
2009 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
2010 lwsl_err("%s: stdin dup2 failed\n", __func__);
2014 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
2015 for (m = 0; m < n; m++) {
2016 p = strchr(env_array[m], '=');
2018 setenv(env_array[m], p, 1);
2020 execvp(exec_array[0], (char * const *)&exec_array[0]);
2022 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
2028 /* drop us from the pt cgi list */
2029 pt->cgi_list = cgi->cgi_list;
2032 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
2034 for (n = 0; n < 3; n++)
2035 if (wsi->cgi->stdwsi[n])
2036 lws_free_wsi(cgi->stdwsi[n]);
2039 for (n = 0; n < 3; n++) {
2040 if (cgi->pipe_fds[n][0])
2041 close(cgi->pipe_fds[n][0]);
2042 if (cgi->pipe_fds[n][1])
2043 close(cgi->pipe_fds[n][1]);
2046 lws_free_set_NULL(wsi->cgi);
2048 lwsl_err("%s: failed\n", __func__);
2053 * lws_cgi_write_split_headers: write cgi output accounting for header part
2055 * @wsi: connection to own the process
2057 LWS_VISIBLE LWS_EXTERN int
2058 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2060 int n, m, match = 0, lp = 0;
2061 static const char * const content_length = "content-length: ";
2062 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2063 *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
2068 while (wsi->hdr_state != LHCS_PAYLOAD) {
2069 /* we have to separate header / finalize and
2070 * payload chunks, since they need to be
2071 * handled separately
2073 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2075 if (errno != EAGAIN) {
2076 lwsl_debug("%s: read says %d\n", __func__, n);
2083 lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
2084 switch (wsi->hdr_state) {
2086 if (!content_length[match] &&
2087 (c >= '0' && c <= '9') &&
2088 lp < sizeof(l) - 1) {
2091 wsi->cgi->content_length = atol(l);
2093 if (tolower(c) == content_length[match])
2098 /* some cgi only send us \x0a for EOL */
2100 wsi->hdr_state = LCHS_SINGLE_0A;
2105 wsi->hdr_state = LCHS_LF1;
2113 wsi->hdr_state = LCHS_CR2;
2116 /* we got \r[^\n]... it's unreasonable */
2117 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2123 wsi->hdr_state = LCHS_LF2;
2126 wsi->hdr_state = LCHS_HEADER;
2131 case LCHS_SINGLE_0A:
2134 lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
2135 wsi->hdr_state = LHCS_PAYLOAD;
2136 /* drop the \0xa ... finalize will add it if needed */
2137 if (lws_finalize_http_header(wsi,
2138 (unsigned char **)&p,
2139 (unsigned char *)end))
2144 /* we got \r\n\r[^\n]... it's unreasonable */
2146 /* we got \x0anext header, it's reasonable */
2148 wsi->hdr_state = LCHS_HEADER;
2155 /* ran out of input, ended the headers, or filled up the headers buf */
2156 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2158 m = lws_write(wsi, (unsigned char *)start,
2159 p - start, LWS_WRITE_HTTP_HEADERS);
2161 lwsl_debug("%s: write says %d\n", __func__, m);
2164 /* writeability becomes uncertain now we wrote
2165 * something, we must return to the event loop
2172 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2173 start, sizeof(buf) - LWS_PRE);
2175 if (n < 0 && errno != EAGAIN) {
2176 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2180 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2181 //lwsl_notice("write %d\n", m);
2183 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2186 wsi->cgi->content_length_seen += m;
2193 * lws_cgi_kill: terminate cgi process associated with wsi
2195 * @wsi: connection to own the process
2197 LWS_VISIBLE LWS_EXTERN int
2198 lws_cgi_kill(struct lws *wsi)
2200 struct lws_cgi_args args;
2203 lwsl_debug("%s: %p\n", __func__, wsi);
2208 if (wsi->cgi->pid > 0) {
2209 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2211 lwsl_debug("%s: PID %d reaped\n", __func__,
2215 /* kill the process group */
2216 n = kill(-wsi->cgi->pid, SIGTERM);
2217 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2218 wsi->cgi->pid, n, errno);
2221 * hum seen errno=3 when process is listed in ps,
2222 * it seems we don't always retain process grouping
2224 * Direct these fallback attempt to the exact child
2226 n = kill(wsi->cgi->pid, SIGTERM);
2228 n = kill(wsi->cgi->pid, SIGPIPE);
2230 n = kill(wsi->cgi->pid, SIGKILL);
2232 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2233 __func__, wsi->cgi->pid, errno);
2237 /* He could be unkillable because he's a zombie */
2240 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2242 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2244 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2246 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2252 args.stdwsi = &wsi->cgi->stdwsi[0];
2254 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2255 wsi->protocol->callback,
2256 wsi, LWS_CALLBACK_CGI_TERMINATED,
2258 (void *)&args, 0)) {
2260 if (!wsi->cgi->being_closed)
2261 lws_close_free_wsi(wsi, 0);
2268 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2270 struct lws_cgi **pcgi, *cgi = NULL;
2274 /* find finished guys but don't reap yet */
2275 n = waitpid(-1, &status, WNOHANG | WNOWAIT);
2278 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
2280 pcgi = &pt->cgi_list;
2282 /* check all the subprocesses on the cgi list */
2284 /* get the next one first as list may change */
2286 pcgi = &(*pcgi)->cgi_list;
2291 /* wait for stdout to be drained */
2292 if (cgi->content_length > cgi->content_length_seen)
2295 if (cgi->content_length) {
2296 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2297 __func__, cgi->wsi, cgi->content_length_seen);
2301 waitpid(n, &status, WNOHANG);
2303 * he's already terminated so no need for kill()
2304 * but we should do the terminated cgi callback
2305 * and close him if he's not already closing
2307 if (n == cgi->pid) {
2308 lwsl_debug("%s: found PID %d on cgi list\n",
2312 lws_cgi_kill(cgi->wsi);
2318 /* if not found on the cgi list, as he's one of ours, reap */
2320 lwsl_debug("%s: reading PID %d although no cgi match\n",
2322 waitpid(n, &status, WNOHANG);
2326 /* disable this to confirm timeout cgi cleanup flow */
2328 pcgi = &pt->cgi_list;
2330 /* check all the subprocesses on the cgi list */
2332 /* get the next one first as list may change */
2334 pcgi = &(*pcgi)->cgi_list;
2339 /* wait for stdout to be drained */
2340 if (cgi->content_length > cgi->content_length_seen)
2343 if (cgi->content_length) {
2344 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2345 __func__, cgi->wsi, cgi->content_length_seen);
2349 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2351 lwsl_debug("%s: found PID %d on cgi list\n",
2352 __func__, cgi->pid);
2355 lws_cgi_kill(cgi->wsi);
2362 /* general anti zombie defence */
2363 n = waitpid(-1, &status, WNOHANG);
2365 lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
2371 #ifdef LWS_NO_EXTENSIONS
2373 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2374 const char *opt_name, const char *opt_val)
2380 #ifdef LWS_WITH_ACCESS_LOG
2382 lws_access_log(struct lws *wsi)
2384 char *p = wsi->access_log.user_agent, ass[512];
2387 if (!wsi->access_log_pending)
2390 if (!wsi->access_log.header_log)
2396 l = snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
2397 wsi->access_log.header_log,
2398 wsi->access_log.response, wsi->access_log.sent, p);
2400 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
2401 if (write(wsi->vhost->log_fd, ass, l) != l)
2402 lwsl_err("Failed to write log\n");
2404 lwsl_err("%s", ass);
2406 if (wsi->access_log.header_log) {
2407 lws_free(wsi->access_log.header_log);
2408 wsi->access_log.header_log = NULL;
2410 if (wsi->access_log.user_agent) {
2411 lws_free(wsi->access_log.user_agent);
2412 wsi->access_log.user_agent = NULL;
2414 wsi->access_log_pending = 0;
2420 #ifdef LWS_WITH_SERVER_STATUS
2423 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
2425 static const char * const prots[] = {
2434 char *orig = buf, *end = buf + len - 1, first = 1;
2440 buf += snprintf(buf, end - buf,
2441 "{\n \"name\":\"%s\",\n"
2442 " \"port\":\"%d\",\n"
2443 " \"use_ssl\":\"%d\",\n"
2444 " \"sts\":\"%d\",\n"
2445 " \"rx\":\"%llu\",\n"
2446 " \"tx\":\"%llu\",\n"
2447 " \"conn\":\"%lu\",\n"
2448 " \"trans\":\"%lu\",\n"
2449 " \"ws_upg\":\"%lu\",\n"
2450 " \"http2_upg\":\"%lu\""
2452 vh->name, vh->listen_port,
2453 #ifdef LWS_OPENSSL_SUPPORT
2458 !!(vh->options & LWS_SERVER_OPTION_STS),
2459 vh->rx, vh->tx, vh->conn, vh->trans, vh->ws_upgrades,
2463 if (vh->mount_list) {
2464 const struct lws_http_mount *m = vh->mount_list;
2466 buf += snprintf(buf, end - buf, ",\n \"mounts\":[");
2469 buf += snprintf(buf, end - buf, ",");
2470 buf += snprintf(buf, end - buf,
2471 "\n {\n \"mountpoint\":\"%s\",\n"
2472 " \"origin\":\"%s%s\",\n"
2473 " \"cache_max_age\":\"%d\",\n"
2474 " \"cache_reuse\":\"%d\",\n"
2475 " \"cache_revalidate\":\"%d\",\n"
2476 " \"cache_intermediaries\":\"%d\"\n"
2479 prots[m->origin_protocol],
2483 m->cache_revalidate,
2484 m->cache_intermediaries);
2486 buf += snprintf(buf, end - buf,
2487 ",\n \"default\":\"%s\"",
2489 buf += snprintf(buf, end - buf, "\n }");
2493 buf += snprintf(buf, end - buf, "\n ]");
2496 if (vh->protocols) {
2500 buf += snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
2501 while (n < vh->count_protocols) {
2503 buf += snprintf(buf, end - buf, ",");
2504 buf += snprintf(buf, end - buf,
2506 " \"status\":\"ok\"\n }\n }"
2508 vh->protocols[n].name);
2512 buf += snprintf(buf, end - buf, "\n ]");
2515 buf += snprintf(buf, end - buf, "\n}");
2521 LWS_EXTERN LWS_VISIBLE int
2522 lws_json_dump_context(const struct lws_context *context, char *buf, int len)
2524 char *orig = buf, *end = buf + len - 1, first = 1;
2525 const struct lws_vhost *vh = context->vhost_list;
2528 struct lws_cgi * const *pcgi;
2530 const struct lws_context_per_thread *pt;
2531 time_t t = time(NULL);
2532 int listening = 0, cgi_count = 0, n;
2534 buf += snprintf(buf, end - buf, "{ "
2535 "\"version\":\"%s\",\n"
2536 "\"uptime\":\"%ld\",\n"
2537 "\"cgi_spawned\":\"%d\",\n"
2538 "\"pt_fd_max\":\"%d\",\n"
2539 "\"ah_pool_max\":\"%d\",\n"
2540 "\"wsi_alive\":\"%d\",\n",
2541 lws_get_library_version(),
2542 (unsigned long)(t - context->time_up),
2543 context->count_cgi_spawned,
2544 context->fd_limit_per_thread,
2545 context->max_http_header_pool,
2546 context->count_wsi_allocated);
2547 #ifdef LWS_HAVE_GETLOADAVG
2552 m = getloadavg(d, 3);
2553 for (n = 0; n < m; n++) {
2554 buf += snprintf(buf, end - buf,
2555 "\"l%d\":\"%.2f\",\n",
2561 buf += snprintf(buf, end - buf, "\"pt\":[\n ");
2562 for (n = 0; n < context->count_threads; n++) {
2563 pt = &context->pt[n];
2565 buf += snprintf(buf, end - buf, ",");
2566 buf += snprintf(buf, end - buf,
2568 " \"fds_count\":\"%d\",\n"
2569 " \"ah_pool_inuse\":\"%d\",\n"
2570 " \"ah_wait_list\":\"%d\"\n"
2573 pt->ah_count_in_use,
2574 pt->ah_wait_list_length);
2577 buf += snprintf(buf, end - buf, "], \"vhosts\":[\n ");
2583 buf += lws_json_dump_vhost(vh, buf, end - buf);
2587 vh = vh->vhost_next;
2590 buf += snprintf(buf, end - buf, "],\n\"listen_wsi\":\"%d\"",
2594 for (n = 0; n < context->count_threads; n++) {
2595 pt = &context->pt[n];
2596 pcgi = &pt->cgi_list;
2599 pcgi = &(*pcgi)->cgi_list;
2605 buf += snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
2608 buf += snprintf(buf, end - buf, "}\n ");