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;
154 context = wsi->context;
155 pt = &context->pt[(int)wsi->tsi];
157 /* if we have children, close them first */
158 if (wsi->child_list) {
159 wsi2 = wsi->child_list;
161 //lwsl_notice("%s: closing %p: close child %p\n",
162 // __func__, wsi, wsi2);
163 wsi1 = wsi2->sibling_list;
164 //lwsl_notice("%s: closing %p: next sibling %p\n",
165 // __func__, wsi2, wsi1);
167 /* stop it doing shutdown processing */
168 wsi2->socket_is_permanently_unusable = 1;
169 lws_close_free_wsi(wsi2, reason);
172 wsi->child_list = NULL;
176 if (wsi->mode == LWSCM_CGI) {
177 /* we are not a network connection, but a handler for CGI io */
178 if (wsi->parent && wsi->parent->cgi)
179 /* end the binding between us and master */
180 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
181 wsi->socket_is_permanently_unusable = 1;
183 lwsl_debug("------ %s: detected cgi fdhandler wsi %p\n", __func__, wsi);
184 goto just_kill_connection;
188 /* we have a cgi going, we must kill it */
189 wsi->cgi->being_closed = 1;
194 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
195 wsi->u.http.fd != LWS_INVALID_FILE) {
196 lws_plat_file_close(wsi, wsi->u.http.fd);
197 wsi->u.http.fd = LWS_INVALID_FILE;
198 wsi->vhost->protocols[0].callback(wsi,
199 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
201 if (wsi->socket_is_permanently_unusable ||
202 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
203 wsi->state == LWSS_SHUTDOWN)
204 goto just_kill_connection;
206 wsi->state_pre_close = wsi->state;
208 switch (wsi->state_pre_close) {
209 case LWSS_DEAD_SOCKET:
212 /* we tried the polite way... */
213 case LWSS_AWAITING_CLOSE_ACK:
214 goto just_kill_connection;
216 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
217 if (wsi->trunc_len) {
218 lws_callback_on_writable(wsi);
221 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
222 goto just_kill_connection;
224 if (wsi->trunc_len) {
225 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
226 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
227 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
233 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
234 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
235 goto just_kill_connection;
237 if (wsi->mode == LWSCM_HTTP_SERVING)
238 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
239 wsi->user_space, NULL, 0);
240 if (wsi->mode == LWSCM_HTTP_CLIENT)
241 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
242 wsi->user_space, NULL, 0);
245 * are his extensions okay with him closing? Eg he might be a mux
246 * parent and just his ch1 aspect is closing?
249 if (lws_ext_cb_active(wsi,
250 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
251 lwsl_ext("extension vetoed close\n");
256 * flush any tx pending from extensions, since we may send close packet
257 * if there are problems with send, just nuke the connection
262 eff_buf.token = NULL;
263 eff_buf.token_len = 0;
265 /* show every extension the new incoming data */
267 m = lws_ext_cb_active(wsi,
268 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
270 lwsl_ext("Extension reports fatal error\n");
271 goto just_kill_connection;
275 * at least one extension told us he has more
276 * to spill, so we will go around again after
280 /* assuming they left us something to send, send it */
282 if (eff_buf.token_len)
283 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
284 eff_buf.token_len) !=
286 lwsl_debug("close: ext spill failed\n");
287 goto just_kill_connection;
292 * signal we are closing, lws_write will
293 * add any necessary version-specific stuff. If the write fails,
294 * no worries we are closing anyway. If we didn't initiate this
295 * close, then our state has been changed to
296 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
298 * Likewise if it's a second call to close this connection after we
299 * sent the close indication to the peer already, we are in state
300 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
303 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
304 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
305 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
306 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
307 lwsl_debug("sending close indication...\n");
309 /* if no prepared close reason, use 1000 and no aux data */
310 if (!wsi->u.ws.close_in_ping_buffer_len) {
311 wsi->u.ws.close_in_ping_buffer_len = 2;
312 wsi->u.ws.ping_payload_buf[LWS_PRE] =
313 (reason >> 16) & 0xff;
314 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
318 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
319 wsi->u.ws.close_in_ping_buffer_len,
323 * we have sent a nice protocol level indication we
324 * now wish to close, we should not send anything more
326 wsi->state = LWSS_AWAITING_CLOSE_ACK;
329 * ...and we should wait for a reply for a bit
332 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
333 lwsl_debug("sent close indication, awaiting ack\n");
338 lwsl_info("close: sending close packet failed, hanging up\n");
340 /* else, the send failed and we should just hang up */
343 just_kill_connection:
345 /* detach ourselves from parent's child list */
346 pwsi = &wsi->parent->child_list;
349 lwsl_notice("%s: detach %p from parent %p\n",
350 __func__, wsi, wsi->parent);
351 *pwsi = wsi->sibling_list;
354 pwsi = &(*pwsi)->sibling_list;
357 lwsl_err("%s: failed to detach from parent\n",
363 * Testing with ab shows that we have to stage the socket close when
364 * the system is under stress... shutdown any further TX, change the
365 * state to one that won't emit anything more, and wait with a timeout
366 * for the POLLIN to show a zero-size rx before coming back and doing
369 if (wsi->state != LWSS_SHUTDOWN &&
370 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
371 !wsi->socket_is_permanently_unusable) {
372 lwsl_info("%s: shutting down connection: %p (sock %d)\n", __func__, wsi, wsi->sock);
373 n = shutdown(wsi->sock, SHUT_WR);
375 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
377 // This causes problems with disconnection when the events are half closing connection
378 // FD_READ | FD_CLOSE (33)
380 /* libuv: no event available to guarantee completion */
381 if (!LWS_LIBUV_ENABLED(context)) {
383 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
384 wsi->state = LWSS_SHUTDOWN;
385 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
386 context->timeout_secs);
393 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
395 #ifdef LWS_WITH_HTTP_PROXY
397 lws_rewrite_destroy(wsi->rw);
402 * we won't be servicing or receiving anything further from this guy
403 * delete socket from the internal poll list if still present
405 lws_ssl_remove_wsi_from_buffered_list(wsi);
406 lws_remove_from_timeout_list(wsi);
408 /* checking return redundant since we anyway close */
409 remove_wsi_socket_from_fds(wsi);
411 wsi->state = LWSS_DEAD_SOCKET;
413 lws_free_set_NULL(wsi->rxflow_buffer);
415 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
416 wsi->mode == LWSCM_WS_SERVING ||
417 wsi->mode == LWSCM_WS_CLIENT) {
419 if (wsi->u.ws.rx_draining_ext) {
420 struct lws **w = &pt->rx_draining_ext_list;
422 wsi->u.ws.rx_draining_ext = 0;
423 /* remove us from context draining ext list */
426 *w = wsi->u.ws.rx_draining_ext_list;
429 w = &((*w)->u.ws.rx_draining_ext_list);
431 wsi->u.ws.rx_draining_ext_list = NULL;
434 if (wsi->u.ws.tx_draining_ext) {
435 struct lws **w = &pt->tx_draining_ext_list;
437 wsi->u.ws.tx_draining_ext = 0;
438 /* remove us from context draining ext list */
441 *w = wsi->u.ws.tx_draining_ext_list;
444 w = &((*w)->u.ws.tx_draining_ext_list);
446 wsi->u.ws.tx_draining_ext_list = NULL;
448 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
450 if (wsi->trunc_alloc)
451 /* not going to be completed... nuke it */
452 lws_free_set_NULL(wsi->trunc_alloc);
454 wsi->u.ws.ping_payload_len = 0;
455 wsi->u.ws.ping_pending_flag = 0;
458 /* tell the user it's all over for this guy */
460 if (wsi->protocol && wsi->protocol->callback &&
461 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
462 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
463 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
464 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
465 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
466 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
467 lwsl_debug("calling back CLOSED\n");
468 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
469 wsi->user_space, NULL, 0);
470 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
471 lwsl_debug("calling back CLOSED_HTTP\n");
472 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
473 wsi->user_space, NULL, 0 );
474 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
475 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
476 lwsl_debug("Connection closed before server reply\n");
477 wsi->vhost->protocols[0].callback(wsi,
478 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
479 wsi->user_space, NULL, 0);
481 lwsl_debug("not calling back closed mode=%d state=%d\n",
482 wsi->mode, wsi->state_pre_close);
484 /* deallocate any active extension contexts */
486 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
487 lwsl_warn("extension destruction failed\n");
489 * inform all extensions in case they tracked this guy out of band
490 * even though not active on him specifically
492 if (lws_ext_cb_all_exts(context, wsi,
493 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
494 lwsl_warn("ext destroy wsi failed\n");
496 wsi->socket_is_permanently_unusable = 1;
499 if (LWS_LIBUV_ENABLED(context)) {
500 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
501 /* libuv has to do his own close handle processing asynchronously */
502 lws_libuv_closehandle(wsi);
508 lws_close_free_wsi_final(wsi);
512 lws_close_free_wsi_final(struct lws *wsi)
516 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
518 //lwsl_err("*** closing sockfd %d\n", wsi->sock);
519 n = compatible_close(wsi->sock);
521 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
524 compatible_close(wsi->sock);
526 wsi->sock = LWS_SOCK_INVALID;
529 /* outermost destroy notification for wsi (user_space still intact) */
530 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
531 wsi->user_space, NULL, 0);
535 for (n = 0; n < 6; n++)
536 if (wsi->cgi->pipe_fds[n / 2][n & 1] >= 0) {
537 lwsl_notice(" closing %d\n", wsi->cgi->pipe_fds[n / 2][n & 1]);
538 close(wsi->cgi->pipe_fds[n / 2][n & 1]);
549 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
553 ipv6 = LWS_IPV6_ENABLED(context);
557 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
562 lws_get_addresses(struct lws_context *context, void *ads, char *name,
563 int name_len, char *rip, int rip_len)
566 struct addrinfo ai, *res;
567 struct sockaddr_in addr4;
572 addr4.sin_family = AF_UNSPEC;
575 if (LWS_IPV6_ENABLED(context)) {
576 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
577 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
581 // Strip off the IPv4 to IPv6 header if one exists
582 if (strncmp(rip, "::ffff:", 7) == 0)
583 memmove(rip, rip + 7, strlen(rip) - 6);
585 getnameinfo((struct sockaddr *)ads,
586 sizeof(struct sockaddr_in6), name,
587 name_len, NULL, 0, 0);
593 struct addrinfo *result;
595 memset(&ai, 0, sizeof ai);
596 ai.ai_family = PF_UNSPEC;
597 ai.ai_socktype = SOCK_STREAM;
598 ai.ai_flags = AI_CANONNAME;
600 if (getnameinfo((struct sockaddr *)ads,
601 sizeof(struct sockaddr_in),
602 name, name_len, NULL, 0, 0))
608 if (getaddrinfo(name, NULL, &ai, &result))
612 while (addr4.sin_family == AF_UNSPEC && res) {
613 switch (res->ai_family) {
615 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
616 addr4.sin_family = AF_INET;
622 freeaddrinfo(result);
625 if (addr4.sin_family == AF_UNSPEC)
628 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
645 * lws_get_peer_addresses() - Get client address information
646 * @wsi: Local struct lws associated with
647 * @fd: Connection socket descriptor
648 * @name: Buffer to take client address name
649 * @name_len: Length of client address name buffer
650 * @rip: Buffer to take client address IP dotted quad
651 * @rip_len: Length of client address IP buffer
653 * This function fills in @name and @rip with the name and IP of
654 * the client connected with socket descriptor @fd. Names may be
655 * truncated if there is not enough room. If either cannot be
656 * determined, they will be returned as valid zero-length strings.
660 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
661 int name_len, char *rip, int rip_len)
666 struct sockaddr_in6 sin6;
668 struct sockaddr_in sin4;
669 struct lws_context *context = wsi->context;
676 lws_latency_pre(context, wsi);
679 if (LWS_IPV6_ENABLED(context)) {
689 if (getpeername(fd, p, &len) < 0) {
690 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
694 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
697 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
709 * lws_context_user() - get the user data associated with the context
710 * @context: Websocket context
712 * This returns the optional user allocation that can be attached to
713 * the context the sockets live in at context_create time. It's a way
714 * to let all sockets serviced in the same context share data without
715 * using globals statics in the user code.
718 lws_context_user(struct lws_context *context)
720 return context->user_space;
723 LWS_VISIBLE struct lws_vhost *
724 lws_vhost_get(struct lws *wsi)
729 LWS_VISIBLE const struct lws_protocols *
730 lws_protocol_get(struct lws *wsi)
732 return wsi->protocol;
737 * lws_callback_all_protocol() - Callback all connections using
738 * the given protocol with the given reason
740 * @protocol: Protocol whose connections will get callbacks
741 * @reason: Callback reason index
745 lws_callback_all_protocol(struct lws_context *context,
746 const struct lws_protocols *protocol, int reason)
748 struct lws_context_per_thread *pt = &context->pt[0];
749 unsigned int n, m = context->count_threads;
753 for (n = 0; n < pt->fds_count; n++) {
754 wsi = wsi_from_fd(context, pt->fds[n].fd);
757 if (wsi->protocol == protocol)
758 protocol->callback(wsi, reason, wsi->user_space,
768 * lws_callback_all_protocol_vhost() - Callback all connections using
769 * the given protocol with the given reason
771 * @vh: Vhost whose connections will get callbacks
772 * @protocol: Which protocol to match
773 * @reason: Callback reason index
777 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
778 const struct lws_protocols *protocol, int reason)
780 struct lws_context *context = vh->context;
781 struct lws_context_per_thread *pt = &context->pt[0];
782 unsigned int n, m = context->count_threads;
786 for (n = 0; n < pt->fds_count; n++) {
787 wsi = wsi_from_fd(context, pt->fds[n].fd);
790 if (wsi->vhost == vh && wsi->protocol == protocol)
791 protocol->callback(wsi, reason, wsi->user_space,
803 * lws_get_socket_fd() - returns the socket file descriptor
805 * You will not need this unless you are doing something special
807 * @wsi: Websocket connection instance
811 lws_get_socket_fd(struct lws *wsi)
820 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
821 int ret, int completed)
823 unsigned long long u;
826 u = time_in_microseconds();
829 wsi->latency_start = u;
830 if (!wsi->action_start)
831 wsi->action_start = u;
835 if (wsi->action_start == wsi->latency_start)
837 "Completion first try lat %lluus: %p: ret %d: %s\n",
838 u - wsi->latency_start,
839 (void *)wsi, ret, action);
842 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
843 u - wsi->action_start,
844 u - wsi->latency_start,
845 (void *)wsi, ret, action);
846 wsi->action_start = 0;
848 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
849 u - wsi->latency_start, (void *)wsi, ret, action);
851 if (u - wsi->latency_start > context->worst_latency) {
852 context->worst_latency = u - wsi->latency_start;
853 strcpy(context->worst_latency_info, buf);
855 lwsl_latency("%s", buf);
862 * lws_rx_flow_control() - Enable and disable socket servicing for
865 * If the output side of a server process becomes choked, this allows flow
866 * control for the input side.
868 * @wsi: Websocket connection instance to get callback for
869 * @enable: 0 = disable read servicing for this connection, 1 = enable
873 lws_rx_flow_control(struct lws *wsi, int enable)
875 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
878 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
879 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
885 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
887 * When the user server code realizes it can accept more input, it can
888 * call this to have the RX flow restriction removed from all connections using
889 * the given protocol.
891 * @protocol: all connections using this protocol will be allowed to receive
895 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
896 const struct lws_protocols *protocol)
898 const struct lws_context_per_thread *pt = &context->pt[0];
900 unsigned int n, m = context->count_threads;
903 for (n = 0; n < pt->fds_count; n++) {
904 wsi = wsi_from_fd(context, pt->fds[n].fd);
907 if (wsi->protocol == protocol)
908 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
916 * lws_canonical_hostname() - returns this host's hostname
918 * This is typically used by client code to fill in the host parameter
919 * when making a client connection. You can only call it after the context
922 * @context: Websocket context
924 LWS_VISIBLE extern const char *
925 lws_canonical_hostname(struct lws_context *context)
927 return (const char *)context->canonical_hostname;
930 int user_callback_handle_rxflow(lws_callback_function callback_function,
932 enum lws_callback_reasons reason, void *user,
933 void *in, size_t len)
937 n = callback_function(wsi, reason, user, in, len);
939 n = _lws_rx_flow_control(wsi);
946 * lws_set_proxy() - Setups proxy to lws_context.
947 * @context: pointer to struct lws_context you want set proxy to
948 * @proxy: pointer to c string containing proxy in format address:port
950 * Returns 0 if proxy string was parsed and proxy was setup.
951 * Returns -1 if @proxy is NULL or has incorrect format.
953 * This is only required if your OS does not provide the http_proxy
954 * environment variable (eg, OSX)
956 * IMPORTANT! You should call this function right after creation of the
957 * lws_context and before call to connect. If you call this
958 * function after connect behavior is undefined.
959 * This function will override proxy settings made on lws_context
960 * creation with genenv() call.
964 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
972 p = strchr(proxy, '@');
973 if (p) { /* auth is around */
975 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
978 strncpy(authstring, proxy, p - proxy);
979 // null termination not needed on input
980 if (lws_b64_encode_string(authstring, (p - proxy),
981 vhost->proxy_basic_auth_token,
982 sizeof vhost->proxy_basic_auth_token) < 0)
985 lwsl_notice(" Proxy auth in use\n");
989 vhost->proxy_basic_auth_token[0] = '\0';
991 strncpy(vhost->http_proxy_address, proxy,
992 sizeof(vhost->http_proxy_address) - 1);
993 vhost->http_proxy_address[
994 sizeof(vhost->http_proxy_address) - 1] = '\0';
996 p = strchr(vhost->http_proxy_address, ':');
997 if (!p && !vhost->http_proxy_port) {
998 lwsl_err("http_proxy needs to be ads:port\n");
1004 vhost->http_proxy_port = atoi(p + 1);
1008 lwsl_notice(" Proxy %s:%u\n", vhost->http_proxy_address,
1009 vhost->http_proxy_port);
1014 lwsl_err("proxy auth too long\n");
1020 * lws_get_protocol() - Returns a protocol pointer from a websocket
1022 * @wsi: pointer to struct websocket you want to know the protocol of
1025 * Some apis can act on all live connections of a given protocol,
1026 * this is how you can get a pointer to the active protocol if needed.
1029 LWS_VISIBLE const struct lws_protocols *
1030 lws_get_protocol(struct lws *wsi)
1032 return wsi->protocol;
1036 lws_is_final_fragment(struct lws *wsi)
1038 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
1039 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
1040 wsi->u.ws.rx_draining_ext);
1041 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1044 LWS_VISIBLE unsigned char
1045 lws_get_reserved_bits(struct lws *wsi)
1047 return wsi->u.ws.rsv;
1051 lws_ensure_user_space(struct lws *wsi)
1053 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1057 /* allocate the per-connection user memory (if any) */
1059 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1060 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1061 if (wsi->user_space == NULL) {
1062 lwsl_err("Out of memory for conn user space\n");
1066 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
1067 __func__, wsi, wsi->protocol->per_session_data_size,
1073 * lwsl_timestamp: generate logging timestamp string
1075 * @level: logging level
1076 * @p: char * buffer to take timestamp
1079 * returns length written in p
1082 lwsl_timestamp(int level, char *p, int len)
1084 time_t o_now = time(NULL);
1085 unsigned long long now;
1086 struct tm *ptm = NULL;
1094 ptm = localtime(&o_now);
1096 if (localtime_r(&o_now, &tm))
1101 for (n = 0; n < LLL_COUNT; n++) {
1102 if (level != (1 << n))
1104 now = time_in_microseconds() / 100;
1106 n = snprintf(p, len,
1107 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1108 ptm->tm_year + 1900,
1114 (int)(now % 10000), log_level_names[n]);
1116 n = snprintf(p, len, "[%llu:%04d] %s: ",
1117 (unsigned long long) now / 10000,
1118 (int)(now % 10000), log_level_names[n]);
1125 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1129 lwsl_timestamp(level, buf, sizeof(buf));
1131 fprintf(stderr, "%s%s", buf, line);
1134 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1138 if (!(log_level & filter))
1141 vsnprintf(buf, sizeof(buf), format, vl);
1142 buf[sizeof(buf) - 1] = '\0';
1144 lwsl_emit(filter, buf);
1147 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1151 va_start(ap, format);
1152 _lws_logv(filter, format, ap);
1157 * lws_set_log_level() - Set the logging bitfield
1158 * @level: OR together the LLL_ debug contexts you want output from
1159 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1160 * function to perform log string emission instead of
1161 * the default stderr one.
1163 * log level defaults to "err", "warn" and "notice" contexts enabled and
1164 * emission on stderr.
1167 LWS_VISIBLE void lws_set_log_level(int level,
1168 void (*func)(int level, const char *line))
1176 * lws_use_ssl() - Find out if connection is using SSL
1177 * @wsi: websocket connection to check
1179 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1180 * using verified cert, and 2 if using SSL but the cert was not
1181 * checked (appears for client wsi told to skip check on connection)
1184 lws_is_ssl(struct lws *wsi)
1186 #ifdef LWS_OPENSSL_SUPPORT
1187 return wsi->use_ssl;
1195 * lws_partial_buffered() - find out if lws buffered the last write
1196 * @wsi: websocket connection to check
1198 * Returns 1 if you cannot use lws_write because the last
1199 * write on this connection is still buffered, and can't be cleared without
1200 * returning to the service loop and waiting for the connection to be
1203 * If you will try to do >1 lws_write call inside a single
1204 * WRITEABLE callback, you must check this after every write and bail if
1205 * set, ask for a new writeable callback and continue writing from there.
1207 * This is never set at the start of a writeable callback, but any write
1212 lws_partial_buffered(struct lws *wsi)
1214 return !!wsi->trunc_len;
1217 void lws_set_protocol_write_pending(struct lws *wsi,
1218 enum lws_pending_protocol_send pend)
1220 lwsl_info("setting pps %d\n", pend);
1223 lwsl_err("pps overwrite\n");
1225 lws_rx_flow_control(wsi, 0);
1226 lws_callback_on_writable(wsi);
1230 lws_get_peer_write_allowance(struct lws *wsi)
1232 #ifdef LWS_USE_HTTP2
1233 /* only if we are using HTTP2 on this connection */
1234 if (wsi->mode != LWSCM_HTTP2_SERVING)
1236 /* user is only interested in how much he can send, or that he can't */
1237 if (wsi->u.http2.tx_credit <= 0)
1240 return wsi->u.http2.tx_credit;
1248 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1250 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1251 memset(&wsi->u, 0, sizeof(wsi->u));
1255 LWS_VISIBLE struct lws_plat_file_ops *
1256 lws_get_fops(struct lws_context *context)
1258 return &context->fops;
1261 LWS_VISIBLE LWS_EXTERN struct lws_context *
1262 lws_get_context(const struct lws *wsi)
1264 return wsi->context;
1267 LWS_VISIBLE LWS_EXTERN int
1268 lws_get_count_threads(struct lws_context *context)
1270 return context->count_threads;
1273 LWS_VISIBLE LWS_EXTERN void *
1274 lws_wsi_user(struct lws *wsi)
1276 return wsi->user_space;
1279 LWS_VISIBLE LWS_EXTERN struct lws *
1280 lws_get_parent(const struct lws *wsi)
1285 LWS_VISIBLE LWS_EXTERN struct lws *
1286 lws_get_child(const struct lws *wsi)
1288 return wsi->child_list;
1291 LWS_VISIBLE LWS_EXTERN void
1292 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1293 unsigned char *buf, size_t len)
1295 unsigned char *p, *start;
1296 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1298 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1300 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1302 *p++ = (((int)status) >> 8) & 0xff;
1303 *p++ = ((int)status) & 0xff;
1306 while (len-- && p < start + budget)
1309 wsi->u.ws.close_in_ping_buffer_len = p - start;
1313 _lws_rx_flow_control(struct lws *wsi)
1315 /* there is no pending change */
1316 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1317 lwsl_debug("%s: no pending change\n", __func__);
1321 /* stuff is still buffered, not ready to really accept new input */
1322 if (wsi->rxflow_buffer) {
1323 /* get ourselves called back to deal with stashed buffer */
1324 lws_callback_on_writable(wsi);
1328 /* pending is cleared, we can change rxflow state */
1330 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1332 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1333 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1335 /* adjust the pollfd for this wsi */
1337 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1338 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1339 lwsl_info("%s: fail\n", __func__);
1343 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1350 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1352 static const unsigned char e0f4[] = {
1353 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1354 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1355 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1356 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1357 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1358 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1359 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1360 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1361 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1362 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1363 0x80 | ((4 - 1) << 2) | 1, /* ea */
1364 0x80 | ((4 - 1) << 2) | 1, /* eb */
1365 0x80 | ((4 - 1) << 2) | 1, /* ec */
1366 0x80 | ((2 - 1) << 2) | 1, /* ed */
1367 0x80 | ((4 - 1) << 2) | 1, /* ee */
1368 0x80 | ((4 - 1) << 2) | 1, /* ef */
1369 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1370 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1371 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1372 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1373 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1376 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1377 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1379 unsigned char s = *state;
1382 unsigned char c = *buf++;
1386 if (c < 0xc2 || c > 0xf4)
1389 s = 0x80 | ((4 - 1) << 2);
1394 if (c < (s & 0xf0) ||
1395 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1397 s = e0f4[21 + (s & 3)];
1407 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1408 * Notice it does so by dropping '\0' into input string
1409 * and the leading / on the path is consequently lost
1411 * @p: incoming uri string.. will get written to
1412 * @prot: result pointer for protocol part (https://)
1413 * @ads: result pointer for address part
1414 * @port: result pointer for port part
1415 * @path: result pointer for path part
1418 LWS_VISIBLE LWS_EXTERN int
1419 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1423 static const char *slash = "/";
1425 /* cut up the location into address, port and path */
1427 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1438 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1440 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1443 while (*p && *p != ':' && *p != '/')
1448 while (*p && *p != '/')
1461 #ifdef LWS_NO_EXTENSIONS
1463 /* we need to provide dummy callbacks for internal exts
1464 * so user code runs when faced with a lib compiled with
1465 * extensions disabled.
1469 lws_extension_callback_pm_deflate(struct lws_context *context,
1470 const struct lws_extension *ext,
1472 enum lws_extension_callback_reasons reason,
1473 void *user, void *in, size_t len)
1488 lws_socket_bind(struct lws_context *context, int sockfd, int port,
1492 #ifdef LWS_USE_UNIX_SOCK
1493 struct sockaddr_un serv_unix;
1496 struct sockaddr_in6 serv_addr6;
1498 struct sockaddr_in serv_addr4;
1499 socklen_t len = sizeof(struct sockaddr);
1501 struct sockaddr_in sin;
1504 #ifdef LWS_USE_UNIX_SOCK
1505 if (LWS_UNIX_SOCK_ENABLED(context)) {
1506 v = (struct sockaddr *)&serv_unix;
1507 n = sizeof(struct sockaddr_un);
1508 bzero((char *) &serv_unix, sizeof(serv_unix));
1509 serv_unix.sun_family = AF_UNIX;
1510 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1511 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1515 strcpy(serv_unix.sun_path, iface);
1519 if (LWS_IPV6_ENABLED(context)) {
1520 v = (struct sockaddr *)&serv_addr6;
1521 n = sizeof(struct sockaddr_in6);
1522 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1523 serv_addr6.sin6_addr = in6addr_any;
1524 serv_addr6.sin6_family = AF_INET6;
1525 serv_addr6.sin6_port = htons(port);
1529 v = (struct sockaddr *)&serv_addr4;
1530 n = sizeof(serv_addr4);
1531 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1532 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1533 serv_addr4.sin_family = AF_INET;
1536 interface_to_sa(context, iface,
1537 (struct sockaddr_in *)v, n) < 0) {
1538 lwsl_err("Unable to find interface %s\n", iface);
1542 serv_addr4.sin_port = htons(port);
1545 n = bind(sockfd, v, n);
1546 #ifdef LWS_USE_UNIX_SOCK
1547 if (n < 0 && LWS_UNIX_SOCK_ENABLED(context)) {
1548 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1549 sockfd, iface, n, LWS_ERRNO);
1554 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1555 sockfd, port, n, LWS_ERRNO);
1559 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1560 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1562 port = ntohs(sin.sin_port);
1568 LWS_VISIBLE LWS_EXTERN int
1569 lws_urlencode(const char *in, int inlen, char *out, int outlen)
1571 const char *hex = "0123456789ABCDEF";
1572 char *start = out, *end = out + outlen;
1574 while (inlen-- && out < end - 4) {
1575 if ((*in >= 'A' && *in <= 'Z') ||
1576 (*in >= 'a' && *in <= 'z') ||
1577 (*in >= '0' && *in <= '9') ||
1585 *out++ = hex[(*in) >> 4];
1586 *out++ = hex[(*in++) & 15];
1597 LWS_VISIBLE LWS_EXTERN int
1598 lws_finalize_startup(struct lws_context *context)
1600 struct lws_context_creation_info info;
1602 info.uid = context->uid;
1603 info.gid = context->gid;
1605 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1606 lws_plat_drop_app_privileges(&info);
1612 LWS_VISIBLE LWS_EXTERN int
1613 lws_is_cgi(struct lws *wsi) {
1624 lws_create_basic_wsi(struct lws_context *context, int tsi)
1626 struct lws *new_wsi;
1628 if ((unsigned int)context->pt[tsi].fds_count ==
1629 context->fd_limit_per_thread - 1) {
1630 lwsl_err("no space for new conn\n");
1634 new_wsi = lws_zalloc(sizeof(struct lws));
1635 if (new_wsi == NULL) {
1636 lwsl_err("Out of memory for new connection\n");
1641 new_wsi->context = context;
1642 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1643 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1645 /* intialize the instance struct */
1647 new_wsi->state = LWSS_CGI;
1648 new_wsi->mode = LWSCM_CGI;
1649 new_wsi->hdr_parsing_completed = 0;
1650 new_wsi->position_in_fds_table = -1;
1653 * these can only be set once the protocol is known
1654 * we set an unestablished connection's protocol pointer
1655 * to the start of the defauly vhost supported list, so it can look
1656 * for matching ones during the handshake
1658 new_wsi->protocol = context->vhost_list->protocols;
1659 new_wsi->user_space = NULL;
1660 new_wsi->ietf_spec_revision = 0;
1661 new_wsi->sock = LWS_SOCK_INVALID;
1662 context->count_wsi_allocated++;
1668 * lws_cgi: spawn network-connected cgi process
1670 * @wsi: connection to own the process
1671 * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1674 LWS_VISIBLE LWS_EXTERN int
1675 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
1676 int timeout_secs, struct lws_protocol_vhost_options *mp_cgienv)
1678 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1679 char *env_array[30], cgi_path[400], e[1024], *p = e,
1680 *end = p + sizeof(e) - 1, tok[256], *t;
1681 struct lws_cgi *cgi;
1682 int n, m, i, uritok = WSI_TOKEN_GET_URI;
1685 * give the master wsi a cgi struct
1688 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1690 lwsl_err("%s: OOM\n", __func__);
1695 cgi->wsi = wsi; /* set cgi's owning wsi */
1697 /* create pipes for [stdin|stdout] and [stderr] */
1699 for (n = 0; n < 3; n++)
1700 if (pipe(cgi->pipe_fds[n]) == -1)
1703 /* create cgi wsis for each stdin/out/err fd */
1705 for (n = 0; n < 3; n++) {
1706 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1707 if (!cgi->stdwsi[n])
1709 cgi->stdwsi[n]->cgi_channel = n;
1710 cgi->stdwsi[n]->vhost = wsi->vhost;
1712 lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
1713 cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
1715 /* read side is 0, stdin we want the write side, others read */
1716 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1717 fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK);
1720 for (n = 0; n < 3; n++) {
1721 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->sock);
1722 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1724 cgi->stdwsi[n]->parent = wsi;
1725 cgi->stdwsi[n]->sibling_list = wsi->child_list;
1726 wsi->child_list = cgi->stdwsi[n];
1729 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1730 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1731 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1733 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1734 cgi->stdwsi[LWS_STDIN]->sock, cgi->stdwsi[LWS_STDOUT]->sock,
1735 cgi->stdwsi[LWS_STDERR]->sock);
1737 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1739 /* the cgi stdout is always sending us http1.x header data first */
1740 wsi->hdr_state = LCHS_HEADER;
1742 /* add us to the pt list of active cgis */
1743 cgi->cgi_list = pt->cgi_list;
1746 /* prepare his CGI env */
1750 if (lws_is_ssl(wsi))
1751 env_array[n++] = "HTTPS=ON";
1752 if (wsi->u.hdr.ah) {
1753 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1754 uritok = WSI_TOKEN_POST_URI;
1755 snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
1756 lws_hdr_simple_ptr(wsi, uritok));
1757 cgi_path[sizeof(cgi_path) - 1] = '\0';
1758 env_array[n++] = cgi_path;
1759 if (uritok == WSI_TOKEN_POST_URI)
1760 env_array[n++] = "REQUEST_METHOD=POST";
1762 env_array[n++] = "REQUEST_METHOD=GET";
1765 p += snprintf(p, end - p, "QUERY_STRING=");
1766 /* dump the individual URI Arg parameters */
1769 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
1770 WSI_TOKEN_HTTP_URI_ARGS, m);
1774 while (*t && *t != '=' && p < end - 4)
1778 i = lws_urlencode(t, i- (t - tok), p, end - p);
1790 p += snprintf(p, end - p, "PATH_INFO=%s",
1791 lws_hdr_simple_ptr(wsi, uritok) +
1792 script_uri_path_len);
1795 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
1797 p += snprintf(p, end - p, "HTTP_REFERER=%s",
1798 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
1801 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1803 p += snprintf(p, end - p, "HTTP_HOST=%s",
1804 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1807 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
1809 p += snprintf(p, end - p, "HTTP_COOKIE=%s",
1810 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
1813 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
1815 p += snprintf(p, end - p, "USER_AGENT=%s",
1816 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
1819 if (uritok == WSI_TOKEN_POST_URI) {
1820 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
1822 p += snprintf(p, end - p, "CONTENT_TYPE=%s",
1823 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
1826 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
1828 p += snprintf(p, end - p, "CONTENT_LENGTH=%s",
1829 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
1834 p += snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
1838 p += snprintf(p, end - p, "%s=%s", mp_cgienv->name,
1840 lwsl_notice(" Applying mount-specific cgi env '%s'\n",
1843 mp_cgienv = mp_cgienv->next;
1846 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1847 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
1848 env_array[n] = NULL;
1851 for (m = 0; m < n; m++)
1852 lwsl_err(" %s\n", env_array[m]);
1855 /* we are ready with the redirection pipes... run the thing */
1856 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1862 lwsl_err("fork failed, errno %d", errno);
1867 /* we are the parent process */
1870 /* somewhere we can at least read things and enter it */
1872 lwsl_notice("%s: Failed to chdir\n", __func__);
1874 /* We are the forked process, redirect and kill inherited things.
1876 * Because of vfork(), we cannot do anything that changes pages in
1877 * the parent environment. Stuff that changes kernel state for the
1878 * process is OK. Stuff that happens after the execvpe() is OK.
1881 for (n = 0; n < 3; n++)
1882 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
1883 lwsl_err("%s: stdin dup2 failed\n", __func__);
1887 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1888 for (m = 0; m < n; m++) {
1889 p = strchr(env_array[m], '=');
1891 setenv(env_array[m], p, 1);
1893 execvp(exec_array[0], (char * const *)&exec_array[0]);
1895 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
1901 /* drop us from the pt cgi list */
1902 pt->cgi_list = cgi->cgi_list;
1905 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
1907 for (n = 0; n < 3; n++)
1908 if (wsi->cgi->stdwsi[n])
1909 lws_free_wsi(cgi->stdwsi[n]);
1912 for (n = 0; n < 3; n++) {
1913 if (cgi->pipe_fds[n][0])
1914 close(cgi->pipe_fds[n][0]);
1915 if (cgi->pipe_fds[n][1])
1916 close(cgi->pipe_fds[n][1]);
1919 lws_free_set_NULL(wsi->cgi);
1921 lwsl_err("%s: failed\n", __func__);
1926 * lws_cgi_write_split_headers: write cgi output accounting for header part
1928 * @wsi: connection to own the process
1930 LWS_VISIBLE LWS_EXTERN int
1931 lws_cgi_write_split_stdout_headers(struct lws *wsi)
1933 int n, m, match = 0, lp = 0;
1934 static const char * const content_length = "content-length: ";
1935 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
1936 *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
1941 while (wsi->hdr_state != LHCS_PAYLOAD) {
1942 /* we have to separate header / finalize and
1943 * payload chunks, since they need to be
1944 * handled separately
1946 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
1948 if (errno != EAGAIN) {
1949 lwsl_debug("%s: read says %d\n", __func__, n);
1956 lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
1957 switch (wsi->hdr_state) {
1959 if (!content_length[match] &&
1960 (c >= '0' && c <= '9') &&
1961 lp < sizeof(l) - 1) {
1964 wsi->cgi->content_length = atol(l);
1966 if (tolower(c) == content_length[match])
1971 /* some cgi only send us \x0a for EOL */
1973 wsi->hdr_state = LCHS_SINGLE_0A;
1978 wsi->hdr_state = LCHS_LF1;
1986 wsi->hdr_state = LCHS_CR2;
1989 /* we got \r[^\n]... it's unreasonable */
1990 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
1996 wsi->hdr_state = LCHS_LF2;
1999 wsi->hdr_state = LCHS_HEADER;
2004 case LCHS_SINGLE_0A:
2007 lwsl_err("Content-Length: %ld\n", wsi->cgi->content_length);
2008 wsi->hdr_state = LHCS_PAYLOAD;
2009 /* drop the \0xa ... finalize will add it if needed */
2010 lws_finalize_http_header(wsi,
2011 (unsigned char **)&p,
2012 (unsigned char *)end);
2016 /* we got \r\n\r[^\n]... it's unreasonable */
2018 /* we got \x0anext header, it's reasonable */
2020 wsi->hdr_state = LCHS_HEADER;
2027 /* ran out of input, ended the headers, or filled up the headers buf */
2028 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2030 m = lws_write(wsi, (unsigned char *)start,
2031 p - start, LWS_WRITE_HTTP_HEADERS);
2033 lwsl_debug("%s: write says %d\n", __func__, m);
2036 /* writeability becomes uncertain now we wrote
2037 * something, we must return to the event loop
2044 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2045 start, sizeof(buf) - LWS_PRE);
2047 if (n < 0 && errno != EAGAIN) {
2048 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2052 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2053 //lwsl_notice("write %d\n", m);
2055 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2058 wsi->cgi->content_length_seen += m;
2065 * lws_cgi_kill: terminate cgi process associated with wsi
2067 * @wsi: connection to own the process
2069 LWS_VISIBLE LWS_EXTERN int
2070 lws_cgi_kill(struct lws *wsi)
2072 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2073 struct lws_cgi **pcgi = &pt->cgi_list;
2074 struct lws_cgi_args args;
2075 int n, status, do_close = 0;
2077 lwsl_debug("!!!!! %s: %p\n", __func__, wsi);
2082 if (wsi->cgi->pid > 0) {
2083 /* kill the process */
2084 n = kill(wsi->cgi->pid, SIGTERM);
2086 lwsl_err("%s: failed\n", __func__);
2089 waitpid(wsi->cgi->pid, &status, 0); /* !!! may hang !!! */
2092 args.stdwsi = &wsi->cgi->stdwsi[0];
2094 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2095 wsi->protocol->callback,
2096 wsi, LWS_CALLBACK_CGI_TERMINATED,
2098 (void *)&args, 0)) {
2100 do_close = !wsi->cgi->being_closed;
2103 /* remove us from the cgi list */
2105 if (*pcgi == wsi->cgi) {
2106 /* drop us from the pt cgi list */
2107 *pcgi = (*pcgi)->cgi_list;
2110 pcgi = &(*pcgi)->cgi_list;
2114 lwsl_debug("!!!!! %s: do_close\n", __func__);
2115 lws_close_free_wsi(wsi, 0);
2122 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2124 struct lws_cgi **pcgi = &pt->cgi_list, *cgi;
2127 /* check all the subprocesses on the cgi list for termination */
2129 /* get the next one because we may close current one next */
2131 pcgi = &(*pcgi)->cgi_list;
2136 /* wait for stdout to be drained */
2137 if (cgi->content_length > cgi->content_length_seen)
2140 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2141 lwsl_notice("content length seen: %ld\n", cgi->content_length_seen);
2143 lws_cgi_kill(cgi->wsi);
2144 pcgi = &pt->cgi_list;
2152 #ifdef LWS_NO_EXTENSIONS
2154 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2155 const char *opt_name, const char *opt_val)