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 goto just_kill_connection;
187 /* we have a cgi going, we must kill it */
188 wsi->cgi->being_closed = 1;
193 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
194 wsi->u.http.fd != LWS_INVALID_FILE) {
195 lws_plat_file_close(wsi, wsi->u.http.fd);
196 wsi->u.http.fd = LWS_INVALID_FILE;
197 wsi->vhost->protocols[0].callback(wsi,
198 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
200 if (wsi->socket_is_permanently_unusable ||
201 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
202 wsi->state == LWSS_SHUTDOWN)
203 goto just_kill_connection;
205 wsi->state_pre_close = wsi->state;
207 switch (wsi->state_pre_close) {
208 case LWSS_DEAD_SOCKET:
211 /* we tried the polite way... */
212 case LWSS_AWAITING_CLOSE_ACK:
213 goto just_kill_connection;
215 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
216 if (wsi->trunc_len) {
217 lws_callback_on_writable(wsi);
220 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
221 goto just_kill_connection;
223 if (wsi->trunc_len) {
224 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
225 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
226 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
232 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
233 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
234 goto just_kill_connection;
236 if (wsi->mode == LWSCM_HTTP_SERVING)
237 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
238 wsi->user_space, NULL, 0);
239 if (wsi->mode == LWSCM_HTTP_CLIENT)
240 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
241 wsi->user_space, NULL, 0);
244 * are his extensions okay with him closing? Eg he might be a mux
245 * parent and just his ch1 aspect is closing?
248 if (lws_ext_cb_active(wsi,
249 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
250 lwsl_ext("extension vetoed close\n");
255 * flush any tx pending from extensions, since we may send close packet
256 * if there are problems with send, just nuke the connection
261 eff_buf.token = NULL;
262 eff_buf.token_len = 0;
264 /* show every extension the new incoming data */
266 m = lws_ext_cb_active(wsi,
267 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
269 lwsl_ext("Extension reports fatal error\n");
270 goto just_kill_connection;
274 * at least one extension told us he has more
275 * to spill, so we will go around again after
279 /* assuming they left us something to send, send it */
281 if (eff_buf.token_len)
282 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
283 eff_buf.token_len) !=
285 lwsl_debug("close: ext spill failed\n");
286 goto just_kill_connection;
291 * signal we are closing, lws_write will
292 * add any necessary version-specific stuff. If the write fails,
293 * no worries we are closing anyway. If we didn't initiate this
294 * close, then our state has been changed to
295 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
297 * Likewise if it's a second call to close this connection after we
298 * sent the close indication to the peer already, we are in state
299 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
302 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
303 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
304 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
305 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
306 lwsl_debug("sending close indication...\n");
308 /* if no prepared close reason, use 1000 and no aux data */
309 if (!wsi->u.ws.close_in_ping_buffer_len) {
310 wsi->u.ws.close_in_ping_buffer_len = 2;
311 wsi->u.ws.ping_payload_buf[LWS_PRE] =
312 (reason >> 16) & 0xff;
313 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
317 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
318 wsi->u.ws.close_in_ping_buffer_len,
322 * we have sent a nice protocol level indication we
323 * now wish to close, we should not send anything more
325 wsi->state = LWSS_AWAITING_CLOSE_ACK;
328 * ...and we should wait for a reply for a bit
331 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
332 lwsl_debug("sent close indication, awaiting ack\n");
337 lwsl_info("close: sending close packet failed, hanging up\n");
339 /* else, the send failed and we should just hang up */
342 just_kill_connection:
344 /* detach ourselves from parent's child list */
345 pwsi = &wsi->parent->child_list;
348 lwsl_notice("%s: detach %p from parent %p\n",
349 __func__, wsi, wsi->parent);
350 *pwsi = wsi->sibling_list;
353 pwsi = &(*pwsi)->sibling_list;
356 lwsl_err("%s: failed to detach from parent\n",
362 * Testing with ab shows that we have to stage the socket close when
363 * the system is under stress... shutdown any further TX, change the
364 * state to one that won't emit anything more, and wait with a timeout
365 * for the POLLIN to show a zero-size rx before coming back and doing
368 if (wsi->state != LWSS_SHUTDOWN &&
369 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
370 !wsi->socket_is_permanently_unusable) {
371 lwsl_info("%s: shutting down connection: %p (sock %d)\n", __func__, wsi, wsi->sock);
372 n = shutdown(wsi->sock, SHUT_WR);
374 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
376 // This causes problems with disconnection when the events are half closing connection
377 // FD_READ | FD_CLOSE (33)
379 /* libuv: no event available to guarantee completion */
380 if (!LWS_LIBUV_ENABLED(context)) {
382 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
383 wsi->state = LWSS_SHUTDOWN;
384 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
385 context->timeout_secs);
392 lwsl_info("%s: real just_kill_connection: %p (sockfd %d)\n", __func__,
394 #ifdef LWS_WITH_HTTP_PROXY
396 lws_rewrite_destroy(wsi->rw);
401 * we won't be servicing or receiving anything further from this guy
402 * delete socket from the internal poll list if still present
404 lws_ssl_remove_wsi_from_buffered_list(wsi);
405 lws_remove_from_timeout_list(wsi);
407 /* checking return redundant since we anyway close */
408 remove_wsi_socket_from_fds(wsi);
410 wsi->state = LWSS_DEAD_SOCKET;
412 lws_free_set_NULL(wsi->rxflow_buffer);
414 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
415 wsi->mode == LWSCM_WS_SERVING ||
416 wsi->mode == LWSCM_WS_CLIENT) {
418 if (wsi->u.ws.rx_draining_ext) {
419 struct lws **w = &pt->rx_draining_ext_list;
421 wsi->u.ws.rx_draining_ext = 0;
422 /* remove us from context draining ext list */
425 *w = wsi->u.ws.rx_draining_ext_list;
428 w = &((*w)->u.ws.rx_draining_ext_list);
430 wsi->u.ws.rx_draining_ext_list = NULL;
433 if (wsi->u.ws.tx_draining_ext) {
434 struct lws **w = &pt->tx_draining_ext_list;
436 wsi->u.ws.tx_draining_ext = 0;
437 /* remove us from context draining ext list */
440 *w = wsi->u.ws.tx_draining_ext_list;
443 w = &((*w)->u.ws.tx_draining_ext_list);
445 wsi->u.ws.tx_draining_ext_list = NULL;
447 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
449 if (wsi->trunc_alloc)
450 /* not going to be completed... nuke it */
451 lws_free_set_NULL(wsi->trunc_alloc);
453 wsi->u.ws.ping_payload_len = 0;
454 wsi->u.ws.ping_pending_flag = 0;
457 /* tell the user it's all over for this guy */
459 if (wsi->protocol && wsi->protocol->callback &&
460 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
461 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
462 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
463 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
464 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
465 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
466 lwsl_debug("calling back CLOSED\n");
467 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
468 wsi->user_space, NULL, 0);
469 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
470 lwsl_debug("calling back CLOSED_HTTP\n");
471 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
472 wsi->user_space, NULL, 0 );
473 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
474 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
475 lwsl_debug("Connection closed before server reply\n");
476 wsi->vhost->protocols[0].callback(wsi,
477 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
478 wsi->user_space, NULL, 0);
480 lwsl_debug("not calling back closed mode=%d state=%d\n",
481 wsi->mode, wsi->state_pre_close);
483 /* deallocate any active extension contexts */
485 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
486 lwsl_warn("extension destruction failed\n");
488 * inform all extensions in case they tracked this guy out of band
489 * even though not active on him specifically
491 if (lws_ext_cb_all_exts(context, wsi,
492 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
493 lwsl_warn("ext destroy wsi failed\n");
495 wsi->socket_is_permanently_unusable = 1;
498 if (LWS_LIBUV_ENABLED(context)) {
499 /* libuv has to do his own close handle processing asynchronously */
500 lws_libuv_closehandle(wsi);
506 lws_close_free_wsi_final(wsi);
510 lws_close_free_wsi_final(struct lws *wsi)
514 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
516 //lwsl_err("*** closing sockfd %d\n", wsi->sock);
517 n = compatible_close(wsi->sock);
519 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
522 compatible_close(wsi->sock);
524 wsi->sock = LWS_SOCK_INVALID;
527 /* outermost destroy notification for wsi (user_space still intact) */
528 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
529 wsi->user_space, NULL, 0);
536 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
540 ipv6 = LWS_IPV6_ENABLED(context);
544 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
549 lws_get_addresses(struct lws_context *context, void *ads, char *name,
550 int name_len, char *rip, int rip_len)
553 struct addrinfo ai, *res;
554 struct sockaddr_in addr4;
559 addr4.sin_family = AF_UNSPEC;
562 if (LWS_IPV6_ENABLED(context)) {
563 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
564 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
568 // Strip off the IPv4 to IPv6 header if one exists
569 if (strncmp(rip, "::ffff:", 7) == 0)
570 memmove(rip, rip + 7, strlen(rip) - 6);
572 getnameinfo((struct sockaddr *)ads,
573 sizeof(struct sockaddr_in6), name,
574 name_len, NULL, 0, 0);
580 struct addrinfo *result;
582 memset(&ai, 0, sizeof ai);
583 ai.ai_family = PF_UNSPEC;
584 ai.ai_socktype = SOCK_STREAM;
585 ai.ai_flags = AI_CANONNAME;
587 if (getnameinfo((struct sockaddr *)ads,
588 sizeof(struct sockaddr_in),
589 name, name_len, NULL, 0, 0))
595 if (getaddrinfo(name, NULL, &ai, &result))
599 while (addr4.sin_family == AF_UNSPEC && res) {
600 switch (res->ai_family) {
602 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
603 addr4.sin_family = AF_INET;
609 freeaddrinfo(result);
612 if (addr4.sin_family == AF_UNSPEC)
615 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
632 * lws_get_peer_addresses() - Get client address information
633 * @wsi: Local struct lws associated with
634 * @fd: Connection socket descriptor
635 * @name: Buffer to take client address name
636 * @name_len: Length of client address name buffer
637 * @rip: Buffer to take client address IP dotted quad
638 * @rip_len: Length of client address IP buffer
640 * This function fills in @name and @rip with the name and IP of
641 * the client connected with socket descriptor @fd. Names may be
642 * truncated if there is not enough room. If either cannot be
643 * determined, they will be returned as valid zero-length strings.
647 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
648 int name_len, char *rip, int rip_len)
653 struct sockaddr_in6 sin6;
655 struct sockaddr_in sin4;
656 struct lws_context *context = wsi->context;
663 lws_latency_pre(context, wsi);
666 if (LWS_IPV6_ENABLED(context)) {
676 if (getpeername(fd, p, &len) < 0) {
677 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
681 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
684 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
696 * lws_context_user() - get the user data associated with the context
697 * @context: Websocket context
699 * This returns the optional user allocation that can be attached to
700 * the context the sockets live in at context_create time. It's a way
701 * to let all sockets serviced in the same context share data without
702 * using globals statics in the user code.
705 lws_context_user(struct lws_context *context)
707 return context->user_space;
710 LWS_VISIBLE struct lws_vhost *
711 lws_vhost_get(struct lws *wsi)
716 LWS_VISIBLE const struct lws_protocols *
717 lws_protocol_get(struct lws *wsi)
719 return wsi->protocol;
724 * lws_callback_all_protocol() - Callback all connections using
725 * the given protocol with the given reason
727 * @protocol: Protocol whose connections will get callbacks
728 * @reason: Callback reason index
732 lws_callback_all_protocol(struct lws_context *context,
733 const struct lws_protocols *protocol, int reason)
735 struct lws_context_per_thread *pt = &context->pt[0];
736 unsigned int n, m = context->count_threads;
740 for (n = 0; n < pt->fds_count; n++) {
741 wsi = wsi_from_fd(context, pt->fds[n].fd);
744 if (wsi->protocol == protocol)
745 protocol->callback(wsi, reason, wsi->user_space,
755 * lws_callback_all_protocol_vhost() - Callback all connections using
756 * the given protocol with the given reason
758 * @vh: Vhost whose connections will get callbacks
759 * @protocol: Which protocol to match
760 * @reason: Callback reason index
764 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
765 const struct lws_protocols *protocol, int reason)
767 struct lws_context *context = vh->context;
768 struct lws_context_per_thread *pt = &context->pt[0];
769 unsigned int n, m = context->count_threads;
773 for (n = 0; n < pt->fds_count; n++) {
774 wsi = wsi_from_fd(context, pt->fds[n].fd);
777 if (wsi->vhost == vh && wsi->protocol == protocol)
778 protocol->callback(wsi, reason, wsi->user_space,
790 * lws_get_socket_fd() - returns the socket file descriptor
792 * You will not need this unless you are doing something special
794 * @wsi: Websocket connection instance
798 lws_get_socket_fd(struct lws *wsi)
807 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
808 int ret, int completed)
810 unsigned long long u;
813 u = time_in_microseconds();
816 wsi->latency_start = u;
817 if (!wsi->action_start)
818 wsi->action_start = u;
822 if (wsi->action_start == wsi->latency_start)
824 "Completion first try lat %lluus: %p: ret %d: %s\n",
825 u - wsi->latency_start,
826 (void *)wsi, ret, action);
829 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
830 u - wsi->action_start,
831 u - wsi->latency_start,
832 (void *)wsi, ret, action);
833 wsi->action_start = 0;
835 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
836 u - wsi->latency_start, (void *)wsi, ret, action);
838 if (u - wsi->latency_start > context->worst_latency) {
839 context->worst_latency = u - wsi->latency_start;
840 strcpy(context->worst_latency_info, buf);
842 lwsl_latency("%s", buf);
849 * lws_rx_flow_control() - Enable and disable socket servicing for
852 * If the output side of a server process becomes choked, this allows flow
853 * control for the input side.
855 * @wsi: Websocket connection instance to get callback for
856 * @enable: 0 = disable read servicing for this connection, 1 = enable
860 lws_rx_flow_control(struct lws *wsi, int enable)
862 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
865 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
866 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
872 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
874 * When the user server code realizes it can accept more input, it can
875 * call this to have the RX flow restriction removed from all connections using
876 * the given protocol.
878 * @protocol: all connections using this protocol will be allowed to receive
882 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
883 const struct lws_protocols *protocol)
885 const struct lws_context_per_thread *pt = &context->pt[0];
887 unsigned int n, m = context->count_threads;
890 for (n = 0; n < pt->fds_count; n++) {
891 wsi = wsi_from_fd(context, pt->fds[n].fd);
894 if (wsi->protocol == protocol)
895 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
903 * lws_canonical_hostname() - returns this host's hostname
905 * This is typically used by client code to fill in the host parameter
906 * when making a client connection. You can only call it after the context
909 * @context: Websocket context
911 LWS_VISIBLE extern const char *
912 lws_canonical_hostname(struct lws_context *context)
914 return (const char *)context->canonical_hostname;
917 int user_callback_handle_rxflow(lws_callback_function callback_function,
919 enum lws_callback_reasons reason, void *user,
920 void *in, size_t len)
924 n = callback_function(wsi, reason, user, in, len);
926 n = _lws_rx_flow_control(wsi);
933 * lws_set_proxy() - Setups proxy to lws_context.
934 * @context: pointer to struct lws_context you want set proxy to
935 * @proxy: pointer to c string containing proxy in format address:port
937 * Returns 0 if proxy string was parsed and proxy was setup.
938 * Returns -1 if @proxy is NULL or has incorrect format.
940 * This is only required if your OS does not provide the http_proxy
941 * environment variable (eg, OSX)
943 * IMPORTANT! You should call this function right after creation of the
944 * lws_context and before call to connect. If you call this
945 * function after connect behavior is undefined.
946 * This function will override proxy settings made on lws_context
947 * creation with genenv() call.
951 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
959 p = strchr(proxy, '@');
960 if (p) { /* auth is around */
962 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
965 strncpy(authstring, proxy, p - proxy);
966 // null termination not needed on input
967 if (lws_b64_encode_string(authstring, (p - proxy),
968 vhost->proxy_basic_auth_token,
969 sizeof vhost->proxy_basic_auth_token) < 0)
972 lwsl_notice(" Proxy auth in use\n");
976 vhost->proxy_basic_auth_token[0] = '\0';
978 strncpy(vhost->http_proxy_address, proxy,
979 sizeof(vhost->http_proxy_address) - 1);
980 vhost->http_proxy_address[
981 sizeof(vhost->http_proxy_address) - 1] = '\0';
983 p = strchr(vhost->http_proxy_address, ':');
984 if (!p && !vhost->http_proxy_port) {
985 lwsl_err("http_proxy needs to be ads:port\n");
991 vhost->http_proxy_port = atoi(p + 1);
995 lwsl_notice(" Proxy %s:%u\n", vhost->http_proxy_address,
996 vhost->http_proxy_port);
1001 lwsl_err("proxy auth too long\n");
1007 * lws_get_protocol() - Returns a protocol pointer from a websocket
1009 * @wsi: pointer to struct websocket you want to know the protocol of
1012 * Some apis can act on all live connections of a given protocol,
1013 * this is how you can get a pointer to the active protocol if needed.
1016 LWS_VISIBLE const struct lws_protocols *
1017 lws_get_protocol(struct lws *wsi)
1019 return wsi->protocol;
1023 lws_is_final_fragment(struct lws *wsi)
1025 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
1026 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
1027 wsi->u.ws.rx_draining_ext);
1028 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1031 LWS_VISIBLE unsigned char
1032 lws_get_reserved_bits(struct lws *wsi)
1034 return wsi->u.ws.rsv;
1038 lws_ensure_user_space(struct lws *wsi)
1040 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1044 /* allocate the per-connection user memory (if any) */
1046 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1047 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1048 if (wsi->user_space == NULL) {
1049 lwsl_err("Out of memory for conn user space\n");
1053 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
1054 __func__, wsi, wsi->protocol->per_session_data_size,
1060 * lwsl_timestamp: generate logging timestamp string
1062 * @level: logging level
1063 * @p: char * buffer to take timestamp
1066 * returns length written in p
1069 lwsl_timestamp(int level, char *p, int len)
1071 time_t o_now = time(NULL);
1072 unsigned long long now;
1073 struct tm *ptm = NULL;
1081 ptm = localtime(&o_now);
1083 if (localtime_r(&o_now, &tm))
1088 for (n = 0; n < LLL_COUNT; n++) {
1089 if (level != (1 << n))
1091 now = time_in_microseconds() / 100;
1093 n = snprintf(p, len,
1094 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1095 ptm->tm_year + 1900,
1101 (int)(now % 10000), log_level_names[n]);
1103 n = snprintf(p, len, "[%llu:%04d] %s: ",
1104 (unsigned long long) now / 10000,
1105 (int)(now % 10000), log_level_names[n]);
1112 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1116 lwsl_timestamp(level, buf, sizeof(buf));
1118 fprintf(stderr, "%s%s", buf, line);
1121 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1125 if (!(log_level & filter))
1128 vsnprintf(buf, sizeof(buf), format, vl);
1129 buf[sizeof(buf) - 1] = '\0';
1131 lwsl_emit(filter, buf);
1134 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1138 va_start(ap, format);
1139 _lws_logv(filter, format, ap);
1144 * lws_set_log_level() - Set the logging bitfield
1145 * @level: OR together the LLL_ debug contexts you want output from
1146 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1147 * function to perform log string emission instead of
1148 * the default stderr one.
1150 * log level defaults to "err", "warn" and "notice" contexts enabled and
1151 * emission on stderr.
1154 LWS_VISIBLE void lws_set_log_level(int level,
1155 void (*func)(int level, const char *line))
1163 * lws_use_ssl() - Find out if connection is using SSL
1164 * @wsi: websocket connection to check
1166 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1167 * using verified cert, and 2 if using SSL but the cert was not
1168 * checked (appears for client wsi told to skip check on connection)
1171 lws_is_ssl(struct lws *wsi)
1173 #ifdef LWS_OPENSSL_SUPPORT
1174 return wsi->use_ssl;
1182 * lws_partial_buffered() - find out if lws buffered the last write
1183 * @wsi: websocket connection to check
1185 * Returns 1 if you cannot use lws_write because the last
1186 * write on this connection is still buffered, and can't be cleared without
1187 * returning to the service loop and waiting for the connection to be
1190 * If you will try to do >1 lws_write call inside a single
1191 * WRITEABLE callback, you must check this after every write and bail if
1192 * set, ask for a new writeable callback and continue writing from there.
1194 * This is never set at the start of a writeable callback, but any write
1199 lws_partial_buffered(struct lws *wsi)
1201 return !!wsi->trunc_len;
1204 void lws_set_protocol_write_pending(struct lws *wsi,
1205 enum lws_pending_protocol_send pend)
1207 lwsl_info("setting pps %d\n", pend);
1210 lwsl_err("pps overwrite\n");
1212 lws_rx_flow_control(wsi, 0);
1213 lws_callback_on_writable(wsi);
1217 lws_get_peer_write_allowance(struct lws *wsi)
1219 #ifdef LWS_USE_HTTP2
1220 /* only if we are using HTTP2 on this connection */
1221 if (wsi->mode != LWSCM_HTTP2_SERVING)
1223 /* user is only interested in how much he can send, or that he can't */
1224 if (wsi->u.http2.tx_credit <= 0)
1227 return wsi->u.http2.tx_credit;
1235 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1237 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1238 memset(&wsi->u, 0, sizeof(wsi->u));
1242 LWS_VISIBLE struct lws_plat_file_ops *
1243 lws_get_fops(struct lws_context *context)
1245 return &context->fops;
1248 LWS_VISIBLE LWS_EXTERN struct lws_context *
1249 lws_get_context(const struct lws *wsi)
1251 return wsi->context;
1254 LWS_VISIBLE LWS_EXTERN int
1255 lws_get_count_threads(struct lws_context *context)
1257 return context->count_threads;
1260 LWS_VISIBLE LWS_EXTERN void *
1261 lws_wsi_user(struct lws *wsi)
1263 return wsi->user_space;
1266 LWS_VISIBLE LWS_EXTERN struct lws *
1267 lws_get_parent(const struct lws *wsi)
1272 LWS_VISIBLE LWS_EXTERN struct lws *
1273 lws_get_child(const struct lws *wsi)
1275 return wsi->child_list;
1278 LWS_VISIBLE LWS_EXTERN void
1279 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1280 unsigned char *buf, size_t len)
1282 unsigned char *p, *start;
1283 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1285 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1287 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1289 *p++ = (((int)status) >> 8) & 0xff;
1290 *p++ = ((int)status) & 0xff;
1293 while (len-- && p < start + budget)
1296 wsi->u.ws.close_in_ping_buffer_len = p - start;
1300 _lws_rx_flow_control(struct lws *wsi)
1302 /* there is no pending change */
1303 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1304 lwsl_debug("%s: no pending change\n", __func__);
1308 /* stuff is still buffered, not ready to really accept new input */
1309 if (wsi->rxflow_buffer) {
1310 /* get ourselves called back to deal with stashed buffer */
1311 lws_callback_on_writable(wsi);
1315 /* pending is cleared, we can change rxflow state */
1317 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1319 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1320 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1322 /* adjust the pollfd for this wsi */
1324 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1325 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1326 lwsl_info("%s: fail\n", __func__);
1330 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1337 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1339 static const unsigned char e0f4[] = {
1340 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1341 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1342 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1343 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1344 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1345 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1346 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1347 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1348 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1349 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1350 0x80 | ((4 - 1) << 2) | 1, /* ea */
1351 0x80 | ((4 - 1) << 2) | 1, /* eb */
1352 0x80 | ((4 - 1) << 2) | 1, /* ec */
1353 0x80 | ((2 - 1) << 2) | 1, /* ed */
1354 0x80 | ((4 - 1) << 2) | 1, /* ee */
1355 0x80 | ((4 - 1) << 2) | 1, /* ef */
1356 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1357 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1358 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1359 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1360 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1363 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1364 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1366 unsigned char s = *state;
1369 unsigned char c = *buf++;
1373 if (c < 0xc2 || c > 0xf4)
1376 s = 0x80 | ((4 - 1) << 2);
1381 if (c < (s & 0xf0) ||
1382 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1384 s = e0f4[21 + (s & 3)];
1394 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1395 * Notice it does so by dropping '\0' into input string
1396 * and the leading / on the path is consequently lost
1398 * @p: incoming uri string.. will get written to
1399 * @prot: result pointer for protocol part (https://)
1400 * @ads: result pointer for address part
1401 * @port: result pointer for port part
1402 * @path: result pointer for path part
1405 LWS_VISIBLE LWS_EXTERN int
1406 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1410 static const char *slash = "/";
1412 /* cut up the location into address, port and path */
1414 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1425 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1427 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1430 while (*p && *p != ':' && *p != '/')
1435 while (*p && *p != '/')
1448 #ifdef LWS_NO_EXTENSIONS
1450 /* we need to provide dummy callbacks for internal exts
1451 * so user code runs when faced with a lib compiled with
1452 * extensions disabled.
1456 lws_extension_callback_pm_deflate(struct lws_context *context,
1457 const struct lws_extension *ext,
1459 enum lws_extension_callback_reasons reason,
1460 void *user, void *in, size_t len)
1475 lws_socket_bind(struct lws_context *context, int sockfd, int port,
1480 struct sockaddr_in6 serv_addr6;
1482 struct sockaddr_in serv_addr4;
1483 socklen_t len = sizeof(struct sockaddr);
1485 struct sockaddr_in sin;
1489 if (LWS_IPV6_ENABLED(context)) {
1490 v = (struct sockaddr *)&serv_addr6;
1491 n = sizeof(struct sockaddr_in6);
1492 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1493 serv_addr6.sin6_addr = in6addr_any;
1494 serv_addr6.sin6_family = AF_INET6;
1495 serv_addr6.sin6_port = htons(port);
1499 v = (struct sockaddr *)&serv_addr4;
1500 n = sizeof(serv_addr4);
1501 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1502 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1503 serv_addr4.sin_family = AF_INET;
1506 interface_to_sa(context, iface,
1507 (struct sockaddr_in *)v, n) < 0) {
1508 lwsl_err("Unable to find interface %s\n", iface);
1512 serv_addr4.sin_port = htons(port);
1515 n = bind(sockfd, v, n);
1517 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1518 sockfd, port, n, LWS_ERRNO);
1522 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1523 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1525 port = ntohs(sin.sin_port);
1531 LWS_VISIBLE LWS_EXTERN int
1532 lws_urlencode(const char *in, int inlen, char *out, int outlen)
1534 const char *hex = "0123456789ABCDEF";
1535 char *start = out, *end = out + outlen;
1537 while (inlen-- && out > end - 4) {
1538 if ((*in >= 'A' && *in <= 'Z') ||
1539 (*in >= 'a' && *in <= 'z') ||
1540 (*in >= '0' && *in <= '9') ||
1548 *out++ = hex[(*in) >> 4];
1549 *out++ = hex[(*in++) & 15];
1560 LWS_VISIBLE LWS_EXTERN int
1561 lws_finalize_startup(struct lws_context *context)
1563 struct lws_context_creation_info info;
1565 info.uid = context->uid;
1566 info.gid = context->gid;
1568 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1569 lws_plat_drop_app_privileges(&info);
1575 LWS_VISIBLE LWS_EXTERN int
1576 lws_is_cgi(struct lws *wsi) {
1587 lws_create_basic_wsi(struct lws_context *context, int tsi)
1589 struct lws *new_wsi;
1591 if ((unsigned int)context->pt[tsi].fds_count ==
1592 context->fd_limit_per_thread - 1) {
1593 lwsl_err("no space for new conn\n");
1597 new_wsi = lws_zalloc(sizeof(struct lws));
1598 if (new_wsi == NULL) {
1599 lwsl_err("Out of memory for new connection\n");
1604 new_wsi->context = context;
1605 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1606 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1608 /* intialize the instance struct */
1610 new_wsi->state = LWSS_CGI;
1611 new_wsi->mode = LWSCM_CGI;
1612 new_wsi->hdr_parsing_completed = 0;
1613 new_wsi->position_in_fds_table = -1;
1616 * these can only be set once the protocol is known
1617 * we set an unestablished connection's protocol pointer
1618 * to the start of the defauly vhost supported list, so it can look
1619 * for matching ones during the handshake
1621 new_wsi->protocol = context->vhost_list->protocols;
1622 new_wsi->user_space = NULL;
1623 new_wsi->ietf_spec_revision = 0;
1624 new_wsi->sock = LWS_SOCK_INVALID;
1625 context->count_wsi_allocated++;
1631 * lws_cgi: spawn network-connected cgi process
1633 * @wsi: connection to own the process
1634 * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1637 LWS_VISIBLE LWS_EXTERN int
1638 lws_cgi(struct lws *wsi, char * const *exec_array, int script_uri_path_len,
1641 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1642 char *env_array[30], cgi_path[400], e[1024], *p = e,
1643 *end = p + sizeof(e) - 1, tok[256];
1644 struct lws_cgi *cgi;
1648 * give the master wsi a cgi struct
1651 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1653 lwsl_err("%s: OOM\n", __func__);
1658 cgi->wsi = wsi; /* set cgi's owning wsi */
1660 /* create pipes for [stdin|stdout] and [stderr] */
1662 for (n = 0; n < 3; n++)
1663 if (pipe(cgi->pipe_fds[n]) == -1)
1666 /* create cgi wsis for each stdin/out/err fd */
1668 for (n = 0; n < 3; n++) {
1669 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1670 if (!cgi->stdwsi[n])
1672 cgi->stdwsi[n]->cgi_channel = n;
1673 /* read side is 0, stdin we want the write side, others read */
1674 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1675 fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK);
1678 for (n = 0; n < 3; n++) {
1679 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1681 cgi->stdwsi[n]->parent = wsi;
1682 cgi->stdwsi[n]->sibling_list = wsi->child_list;
1683 wsi->child_list = cgi->stdwsi[n];
1686 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1687 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1688 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1690 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1691 cgi->stdwsi[LWS_STDIN]->sock, cgi->stdwsi[LWS_STDOUT]->sock,
1692 cgi->stdwsi[LWS_STDERR]->sock);
1694 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1696 /* the cgi stdout is always sending us http1.x header data first */
1697 wsi->hdr_state = LCHS_HEADER;
1699 /* add us to the pt list of active cgis */
1700 cgi->cgi_list = pt->cgi_list;
1703 /* prepare his CGI env */
1707 if (lws_is_ssl(wsi))
1708 env_array[n++] = "HTTPS=ON";
1709 if (wsi->u.hdr.ah) {
1710 snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
1711 lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI));
1712 cgi_path[sizeof(cgi_path) - 1] = '\0';
1713 env_array[n++] = cgi_path;
1714 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1715 env_array[n++] = "REQUEST_METHOD=POST";
1717 env_array[n++] = "REQUEST_METHOD=GET";
1720 p += snprintf(p, end - p, "QUERY_STRING=");
1721 /* dump the individual URI Arg parameters */
1724 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
1725 WSI_TOKEN_HTTP_URI_ARGS, m);
1728 i = lws_urlencode(tok, i, p, end - p);
1738 p += snprintf(p, end - p, "PATH_INFO=%s",
1739 lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI) +
1740 script_uri_path_len);
1743 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
1745 p += snprintf(p, end - p, "HTTP_REFERER=%s",
1746 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
1749 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1751 p += snprintf(p, end - p, "HTTP_HOST=%s",
1752 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1755 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
1757 p += snprintf(p, end - p, "USER_AGENT=%s",
1758 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
1762 p += snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[2]) + 1;
1764 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1765 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
1766 env_array[n] = NULL;
1769 for (m = 0; m < n; m++)
1770 lwsl_err(" %s\n", env_array[m]);
1773 /* we are ready with the redirection pipes... run the thing */
1774 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1780 lwsl_err("fork failed, errno %d", errno);
1785 /* we are the parent process */
1788 /* We are the forked process, redirect and kill inherited things.
1790 * Because of vfork(), we cannot do anything that changes pages in
1791 * the parent environment. Stuff that changes kernel state for the
1792 * process is OK. Stuff that happens after the execvpe() is OK.
1795 for (n = 0; n < 3; n++) {
1796 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
1797 lwsl_err("%s: stdin dup2 failed\n", __func__);
1800 close(cgi->pipe_fds[n][!(n == 0)]);
1803 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1804 for (m = 0; m < n; m++) {
1805 p = strchr(env_array[m], '=');
1807 setenv(env_array[m], p, 1);
1809 execvp(exec_array[0], &exec_array[0]);
1811 execvpe(exec_array[0], &exec_array[0], &env_array[0]);
1817 /* drop us from the pt cgi list */
1818 pt->cgi_list = cgi->cgi_list;
1821 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
1823 for (n = 0; n < 3; n++)
1824 if (wsi->cgi->stdwsi[n])
1825 lws_free_wsi(cgi->stdwsi[n]);
1828 for (n = 0; n < 3; n++) {
1829 if (cgi->pipe_fds[n][0])
1830 close(cgi->pipe_fds[n][0]);
1831 if (cgi->pipe_fds[n][1])
1832 close(cgi->pipe_fds[n][1]);
1835 lws_free_set_NULL(wsi->cgi);
1837 lwsl_err("%s: failed\n", __func__);
1842 * lws_cgi_write_split_headers: write cgi output accounting for header part
1844 * @wsi: connection to own the process
1846 LWS_VISIBLE LWS_EXTERN int
1847 lws_cgi_write_split_stdout_headers(struct lws *wsi)
1850 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
1851 *end = &buf[sizeof(buf) - 1 - LWS_PRE], c;
1853 while (wsi->hdr_state != LHCS_PAYLOAD) {
1854 /* we have to separate header / finalize and
1855 * payload chunks, since they need to be
1856 * handled separately
1858 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
1860 if (errno != EAGAIN)
1866 //lwsl_err("-- %c\n", c);
1867 switch (wsi->hdr_state) {
1871 wsi->hdr_state = LCHS_LF1;
1878 wsi->hdr_state = LCHS_CR2;
1881 /* we got \r[^\n]... it's unreasonable */
1886 wsi->hdr_state = LCHS_LF2;
1893 wsi->hdr_state = LHCS_PAYLOAD;
1894 /* drop the \0xa ... finalize will add it if needed */
1895 lws_finalize_http_header(wsi,
1896 (unsigned char **)&p,
1897 (unsigned char *)end);
1900 /* we got \r\n\r[^\n]... it's unreasonable */
1907 /* ran out of input, ended the headers, or filled up the headers buf */
1908 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
1910 m = lws_write(wsi, (unsigned char *)start,
1911 p - start, LWS_WRITE_HTTP_HEADERS);
1914 /* writeability becomes uncertain now we wrote
1915 * something, we must return to the event loop
1921 //lwsl_err("%s: stdout\n", __func__);
1922 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
1923 start, sizeof(buf) - LWS_PRE);
1925 if (n < 0 && errno != EAGAIN)
1928 m = lws_write(wsi, (unsigned char *)start, n,
1930 //lwsl_notice("write %d\n", m);
1939 * lws_cgi_kill: terminate cgi process associated with wsi
1941 * @wsi: connection to own the process
1943 LWS_VISIBLE LWS_EXTERN int
1944 lws_cgi_kill(struct lws *wsi)
1946 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1947 struct lws_cgi **pcgi = &pt->cgi_list;
1948 struct lws_cgi_args args;
1949 int n, status, do_close = 0;
1954 // lwsl_notice("%s: wsi %p\n", __func__, wsi);
1958 if (wsi->cgi->pid > 0) {
1959 /* kill the process */
1960 n = kill(wsi->cgi->pid, SIGTERM);
1962 lwsl_err("%s: failed\n", __func__);
1965 waitpid(wsi->cgi->pid, &status, 0); /* !!! may hang !!! */
1968 args.stdwsi = &wsi->cgi->stdwsi[0];
1970 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
1971 wsi->protocol->callback,
1972 wsi, LWS_CALLBACK_CGI_TERMINATED,
1974 (void *)&args, 0)) {
1976 do_close = !wsi->cgi->being_closed;
1979 /* remove us from the cgi list */
1981 if (*pcgi == wsi->cgi) {
1982 /* drop us from the pt cgi list */
1983 *pcgi = (*pcgi)->cgi_list;
1986 pcgi = &(*pcgi)->cgi_list;
1989 for (n = 0 ; n < 3; n++) {
1990 if (wsi->cgi->pipe_fds[n][!!(n == 0)] >= 0) {
1991 close(wsi->cgi->pipe_fds[n][!!(n == 0)]);
1992 wsi->cgi->pipe_fds[n][!!(n == 0)] = -1;
1996 lws_free_set_NULL(wsi->cgi);
1999 lws_close_free_wsi(wsi, 0);
2005 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2007 struct lws_cgi **pcgi = &pt->cgi_list, *cgi;
2010 /* check all the subprocesses on the cgi list for termination */
2012 /* get the next one because we may close current one next */
2014 pcgi = &(*pcgi)->cgi_list;
2017 waitpid(cgi->pid, &status, WNOHANG) > 0) {
2019 lws_cgi_kill(cgi->wsi);
2020 pcgi = &pt->cgi_list;
2028 #ifdef LWS_NO_EXTENSIONS
2030 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2031 const char *opt_name, const char *opt_val)