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]);
562 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
566 ipv6 = LWS_IPV6_ENABLED(context);
570 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
575 lws_get_addresses(struct lws_context *context, void *ads, char *name,
576 int name_len, char *rip, int rip_len)
579 struct addrinfo ai, *res;
580 struct sockaddr_in addr4;
585 addr4.sin_family = AF_UNSPEC;
588 if (LWS_IPV6_ENABLED(context)) {
589 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
590 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
594 // Strip off the IPv4 to IPv6 header if one exists
595 if (strncmp(rip, "::ffff:", 7) == 0)
596 memmove(rip, rip + 7, strlen(rip) - 6);
598 getnameinfo((struct sockaddr *)ads,
599 sizeof(struct sockaddr_in6), name,
600 name_len, NULL, 0, 0);
606 struct addrinfo *result;
608 memset(&ai, 0, sizeof ai);
609 ai.ai_family = PF_UNSPEC;
610 ai.ai_socktype = SOCK_STREAM;
611 ai.ai_flags = AI_CANONNAME;
613 if (getnameinfo((struct sockaddr *)ads,
614 sizeof(struct sockaddr_in),
615 name, name_len, NULL, 0, 0))
621 if (getaddrinfo(name, NULL, &ai, &result))
625 while (addr4.sin_family == AF_UNSPEC && res) {
626 switch (res->ai_family) {
628 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
629 addr4.sin_family = AF_INET;
635 freeaddrinfo(result);
638 if (addr4.sin_family == AF_UNSPEC)
641 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
658 * lws_get_peer_simple() - Get client address information without RDNS
659 * @wsi: Local struct lws associated with
660 * @name: Buffer to take client address name
661 * @name_len: Length of client address name buffer
663 * This provides a 123.123.123.123 type IP address in @name from the
664 * peer that has connected to @wsi
667 LWS_VISIBLE const char *
668 lws_get_peer_simple(struct lws *wsi, char *name, int namelen)
673 struct sockaddr_in6 sin6;
675 struct sockaddr_in sin4;
680 if (LWS_IPV6_ENABLED(wsi->context)) {
694 if (getpeername(wsi->sock, p, &len) < 0 || len > olen) {
695 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
699 return lws_plat_inet_ntop(af, q, name, namelen);
706 * lws_get_peer_addresses() - Get client address information
707 * @wsi: Local struct lws associated with
708 * @fd: Connection socket descriptor
709 * @name: Buffer to take client address name
710 * @name_len: Length of client address name buffer
711 * @rip: Buffer to take client address IP dotted quad
712 * @rip_len: Length of client address IP buffer
714 * This function fills in @name and @rip with the name and IP of
715 * the client connected with socket descriptor @fd. Names may be
716 * truncated if there is not enough room. If either cannot be
717 * determined, they will be returned as valid zero-length strings.
721 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
722 int name_len, char *rip, int rip_len)
727 struct sockaddr_in6 sin6;
729 struct sockaddr_in sin4;
730 struct lws_context *context = wsi->context;
737 lws_latency_pre(context, wsi);
740 if (LWS_IPV6_ENABLED(context)) {
750 if (getpeername(fd, p, &len) < 0) {
751 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
755 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
758 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
770 * lws_context_user() - get the user data associated with the context
771 * @context: Websocket context
773 * This returns the optional user allocation that can be attached to
774 * the context the sockets live in at context_create time. It's a way
775 * to let all sockets serviced in the same context share data without
776 * using globals statics in the user code.
779 lws_context_user(struct lws_context *context)
781 return context->user_space;
784 LWS_VISIBLE struct lws_vhost *
785 lws_vhost_get(struct lws *wsi)
790 LWS_VISIBLE struct lws_vhost *
791 lws_get_vhost(struct lws *wsi)
796 LWS_VISIBLE const struct lws_protocols *
797 lws_protocol_get(struct lws *wsi)
799 return wsi->protocol;
804 * lws_callback_all_protocol() - Callback all connections using
805 * the given protocol with the given reason
807 * @protocol: Protocol whose connections will get callbacks
808 * @reason: Callback reason index
812 lws_callback_all_protocol(struct lws_context *context,
813 const struct lws_protocols *protocol, int reason)
815 struct lws_context_per_thread *pt = &context->pt[0];
816 unsigned int n, m = context->count_threads;
820 for (n = 0; n < pt->fds_count; n++) {
821 wsi = wsi_from_fd(context, pt->fds[n].fd);
824 if (wsi->protocol == protocol)
825 protocol->callback(wsi, reason, wsi->user_space,
835 * lws_callback_all_protocol_vhost() - Callback all connections using
836 * the given protocol with the given reason
838 * @vh: Vhost whose connections will get callbacks
839 * @protocol: Which protocol to match
840 * @reason: Callback reason index
844 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
845 const struct lws_protocols *protocol, int reason)
847 struct lws_context *context = vh->context;
848 struct lws_context_per_thread *pt = &context->pt[0];
849 unsigned int n, m = context->count_threads;
853 for (n = 0; n < pt->fds_count; n++) {
854 wsi = wsi_from_fd(context, pt->fds[n].fd);
857 if (wsi->vhost == vh && wsi->protocol == protocol)
858 protocol->callback(wsi, reason, wsi->user_space,
870 * lws_get_socket_fd() - returns the socket file descriptor
872 * You will not need this unless you are doing something special
874 * @wsi: Websocket connection instance
878 lws_get_socket_fd(struct lws *wsi)
887 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
888 int ret, int completed)
890 unsigned long long u;
893 u = time_in_microseconds();
896 wsi->latency_start = u;
897 if (!wsi->action_start)
898 wsi->action_start = u;
902 if (wsi->action_start == wsi->latency_start)
904 "Completion first try lat %lluus: %p: ret %d: %s\n",
905 u - wsi->latency_start,
906 (void *)wsi, ret, action);
909 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
910 u - wsi->action_start,
911 u - wsi->latency_start,
912 (void *)wsi, ret, action);
913 wsi->action_start = 0;
915 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
916 u - wsi->latency_start, (void *)wsi, ret, action);
918 if (u - wsi->latency_start > context->worst_latency) {
919 context->worst_latency = u - wsi->latency_start;
920 strcpy(context->worst_latency_info, buf);
922 lwsl_latency("%s", buf);
929 * lws_rx_flow_control() - Enable and disable socket servicing for
932 * If the output side of a server process becomes choked, this allows flow
933 * control for the input side.
935 * @wsi: Websocket connection instance to get callback for
936 * @enable: 0 = disable read servicing for this connection, 1 = enable
940 lws_rx_flow_control(struct lws *wsi, int enable)
942 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
945 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
946 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
952 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
954 * When the user server code realizes it can accept more input, it can
955 * call this to have the RX flow restriction removed from all connections using
956 * the given protocol.
958 * @protocol: all connections using this protocol will be allowed to receive
962 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
963 const struct lws_protocols *protocol)
965 const struct lws_context_per_thread *pt = &context->pt[0];
967 unsigned int n, m = context->count_threads;
970 for (n = 0; n < pt->fds_count; n++) {
971 wsi = wsi_from_fd(context, pt->fds[n].fd);
974 if (wsi->protocol == protocol)
975 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
983 * lws_canonical_hostname() - returns this host's hostname
985 * This is typically used by client code to fill in the host parameter
986 * when making a client connection. You can only call it after the context
989 * @context: Websocket context
991 LWS_VISIBLE extern const char *
992 lws_canonical_hostname(struct lws_context *context)
994 return (const char *)context->canonical_hostname;
997 int user_callback_handle_rxflow(lws_callback_function callback_function,
999 enum lws_callback_reasons reason, void *user,
1000 void *in, size_t len)
1004 n = callback_function(wsi, reason, user, in, len);
1006 n = _lws_rx_flow_control(wsi);
1013 * lws_set_proxy() - Setups proxy to lws_context.
1014 * @context: pointer to struct lws_context you want set proxy to
1015 * @proxy: pointer to c string containing proxy in format address:port
1017 * Returns 0 if proxy string was parsed and proxy was setup.
1018 * Returns -1 if @proxy is NULL or has incorrect format.
1020 * This is only required if your OS does not provide the http_proxy
1021 * environment variable (eg, OSX)
1023 * IMPORTANT! You should call this function right after creation of the
1024 * lws_context and before call to connect. If you call this
1025 * function after connect behavior is undefined.
1026 * This function will override proxy settings made on lws_context
1027 * creation with genenv() call.
1031 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1034 char authstring[96];
1039 p = strchr(proxy, '@');
1040 if (p) { /* auth is around */
1042 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1045 strncpy(authstring, proxy, p - proxy);
1046 // null termination not needed on input
1047 if (lws_b64_encode_string(authstring, (p - proxy),
1048 vhost->proxy_basic_auth_token,
1049 sizeof vhost->proxy_basic_auth_token) < 0)
1052 lwsl_notice(" Proxy auth in use\n");
1056 vhost->proxy_basic_auth_token[0] = '\0';
1058 strncpy(vhost->http_proxy_address, proxy,
1059 sizeof(vhost->http_proxy_address) - 1);
1060 vhost->http_proxy_address[
1061 sizeof(vhost->http_proxy_address) - 1] = '\0';
1063 p = strchr(vhost->http_proxy_address, ':');
1064 if (!p && !vhost->http_proxy_port) {
1065 lwsl_err("http_proxy needs to be ads:port\n");
1071 vhost->http_proxy_port = atoi(p + 1);
1075 lwsl_notice(" Proxy %s:%u\n", vhost->http_proxy_address,
1076 vhost->http_proxy_port);
1081 lwsl_err("proxy auth too long\n");
1087 * lws_get_protocol() - Returns a protocol pointer from a websocket
1089 * @wsi: pointer to struct websocket you want to know the protocol of
1092 * Some apis can act on all live connections of a given protocol,
1093 * this is how you can get a pointer to the active protocol if needed.
1096 LWS_VISIBLE const struct lws_protocols *
1097 lws_get_protocol(struct lws *wsi)
1099 return wsi->protocol;
1103 lws_is_final_fragment(struct lws *wsi)
1105 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
1106 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
1107 wsi->u.ws.rx_draining_ext);
1108 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1111 LWS_VISIBLE unsigned char
1112 lws_get_reserved_bits(struct lws *wsi)
1114 return wsi->u.ws.rsv;
1118 lws_ensure_user_space(struct lws *wsi)
1120 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1124 /* allocate the per-connection user memory (if any) */
1126 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1127 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1128 if (wsi->user_space == NULL) {
1129 lwsl_err("Out of memory for conn user space\n");
1133 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
1134 __func__, wsi, wsi->protocol->per_session_data_size,
1140 * lwsl_timestamp: generate logging timestamp string
1142 * @level: logging level
1143 * @p: char * buffer to take timestamp
1146 * returns length written in p
1149 lwsl_timestamp(int level, char *p, int len)
1151 time_t o_now = time(NULL);
1152 unsigned long long now;
1153 struct tm *ptm = NULL;
1161 ptm = localtime(&o_now);
1163 if (localtime_r(&o_now, &tm))
1168 for (n = 0; n < LLL_COUNT; n++) {
1169 if (level != (1 << n))
1171 now = time_in_microseconds() / 100;
1173 n = snprintf(p, len,
1174 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1175 ptm->tm_year + 1900,
1181 (int)(now % 10000), log_level_names[n]);
1183 n = snprintf(p, len, "[%llu:%04d] %s: ",
1184 (unsigned long long) now / 10000,
1185 (int)(now % 10000), log_level_names[n]);
1192 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1196 lwsl_timestamp(level, buf, sizeof(buf));
1198 fprintf(stderr, "%s%s", buf, line);
1201 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1205 if (!(log_level & filter))
1208 vsnprintf(buf, sizeof(buf), format, vl);
1209 buf[sizeof(buf) - 1] = '\0';
1211 lwsl_emit(filter, buf);
1214 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1218 va_start(ap, format);
1219 _lws_logv(filter, format, ap);
1224 * lws_set_log_level() - Set the logging bitfield
1225 * @level: OR together the LLL_ debug contexts you want output from
1226 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1227 * function to perform log string emission instead of
1228 * the default stderr one.
1230 * log level defaults to "err", "warn" and "notice" contexts enabled and
1231 * emission on stderr.
1234 LWS_VISIBLE void lws_set_log_level(int level,
1235 void (*func)(int level, const char *line))
1243 * lws_use_ssl() - Find out if connection is using SSL
1244 * @wsi: websocket connection to check
1246 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1247 * using verified cert, and 2 if using SSL but the cert was not
1248 * checked (appears for client wsi told to skip check on connection)
1251 lws_is_ssl(struct lws *wsi)
1253 #ifdef LWS_OPENSSL_SUPPORT
1254 return wsi->use_ssl;
1262 * lws_partial_buffered() - find out if lws buffered the last write
1263 * @wsi: websocket connection to check
1265 * Returns 1 if you cannot use lws_write because the last
1266 * write on this connection is still buffered, and can't be cleared without
1267 * returning to the service loop and waiting for the connection to be
1270 * If you will try to do >1 lws_write call inside a single
1271 * WRITEABLE callback, you must check this after every write and bail if
1272 * set, ask for a new writeable callback and continue writing from there.
1274 * This is never set at the start of a writeable callback, but any write
1279 lws_partial_buffered(struct lws *wsi)
1281 return !!wsi->trunc_len;
1284 void lws_set_protocol_write_pending(struct lws *wsi,
1285 enum lws_pending_protocol_send pend)
1287 lwsl_info("setting pps %d\n", pend);
1290 lwsl_err("pps overwrite\n");
1292 lws_rx_flow_control(wsi, 0);
1293 lws_callback_on_writable(wsi);
1297 lws_get_peer_write_allowance(struct lws *wsi)
1299 #ifdef LWS_USE_HTTP2
1300 /* only if we are using HTTP2 on this connection */
1301 if (wsi->mode != LWSCM_HTTP2_SERVING)
1303 /* user is only interested in how much he can send, or that he can't */
1304 if (wsi->u.http2.tx_credit <= 0)
1307 return wsi->u.http2.tx_credit;
1315 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1317 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1318 memset(&wsi->u, 0, sizeof(wsi->u));
1322 LWS_VISIBLE struct lws_plat_file_ops *
1323 lws_get_fops(struct lws_context *context)
1325 return &context->fops;
1328 LWS_VISIBLE LWS_EXTERN struct lws_context *
1329 lws_get_context(const struct lws *wsi)
1331 return wsi->context;
1334 LWS_VISIBLE LWS_EXTERN int
1335 lws_get_count_threads(struct lws_context *context)
1337 return context->count_threads;
1340 LWS_VISIBLE LWS_EXTERN void *
1341 lws_wsi_user(struct lws *wsi)
1343 return wsi->user_space;
1346 LWS_VISIBLE LWS_EXTERN struct lws *
1347 lws_get_parent(const struct lws *wsi)
1352 LWS_VISIBLE LWS_EXTERN struct lws *
1353 lws_get_child(const struct lws *wsi)
1355 return wsi->child_list;
1358 LWS_VISIBLE LWS_EXTERN void
1359 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1360 unsigned char *buf, size_t len)
1362 unsigned char *p, *start;
1363 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1365 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1367 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1369 *p++ = (((int)status) >> 8) & 0xff;
1370 *p++ = ((int)status) & 0xff;
1373 while (len-- && p < start + budget)
1376 wsi->u.ws.close_in_ping_buffer_len = p - start;
1380 _lws_rx_flow_control(struct lws *wsi)
1382 /* there is no pending change */
1383 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1384 lwsl_debug("%s: no pending change\n", __func__);
1388 /* stuff is still buffered, not ready to really accept new input */
1389 if (wsi->rxflow_buffer) {
1390 /* get ourselves called back to deal with stashed buffer */
1391 lws_callback_on_writable(wsi);
1395 /* pending is cleared, we can change rxflow state */
1397 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1399 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1400 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1402 /* adjust the pollfd for this wsi */
1404 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1405 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1406 lwsl_info("%s: fail\n", __func__);
1410 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1417 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1419 static const unsigned char e0f4[] = {
1420 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1421 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1422 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1423 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1424 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1425 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1426 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1427 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1428 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1429 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1430 0x80 | ((4 - 1) << 2) | 1, /* ea */
1431 0x80 | ((4 - 1) << 2) | 1, /* eb */
1432 0x80 | ((4 - 1) << 2) | 1, /* ec */
1433 0x80 | ((2 - 1) << 2) | 1, /* ed */
1434 0x80 | ((4 - 1) << 2) | 1, /* ee */
1435 0x80 | ((4 - 1) << 2) | 1, /* ef */
1436 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1437 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1438 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1439 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1440 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1443 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1444 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1446 unsigned char s = *state;
1449 unsigned char c = *buf++;
1453 if (c < 0xc2 || c > 0xf4)
1456 s = 0x80 | ((4 - 1) << 2);
1461 if (c < (s & 0xf0) ||
1462 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1464 s = e0f4[21 + (s & 3)];
1474 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1475 * Notice it does so by dropping '\0' into input string
1476 * and the leading / on the path is consequently lost
1478 * @p: incoming uri string.. will get written to
1479 * @prot: result pointer for protocol part (https://)
1480 * @ads: result pointer for address part
1481 * @port: result pointer for port part
1482 * @path: result pointer for path part
1485 LWS_VISIBLE LWS_EXTERN int
1486 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1490 static const char *slash = "/";
1492 /* cut up the location into address, port and path */
1494 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1505 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1507 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1510 while (*p && *p != ':' && *p != '/')
1515 while (*p && *p != '/')
1528 #ifdef LWS_NO_EXTENSIONS
1530 /* we need to provide dummy callbacks for internal exts
1531 * so user code runs when faced with a lib compiled with
1532 * extensions disabled.
1536 lws_extension_callback_pm_deflate(struct lws_context *context,
1537 const struct lws_extension *ext,
1539 enum lws_extension_callback_reasons reason,
1540 void *user, void *in, size_t len)
1555 lws_socket_bind(struct lws_vhost *vhost, int sockfd, int port,
1559 #ifdef LWS_USE_UNIX_SOCK
1560 struct sockaddr_un serv_unix;
1563 struct sockaddr_in6 serv_addr6;
1565 struct sockaddr_in serv_addr4;
1566 socklen_t len = sizeof(struct sockaddr);
1568 struct sockaddr_in sin;
1571 #ifdef LWS_USE_UNIX_SOCK
1572 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1573 v = (struct sockaddr *)&serv_unix;
1574 n = sizeof(struct sockaddr_un);
1575 bzero((char *) &serv_unix, sizeof(serv_unix));
1576 serv_unix.sun_family = AF_UNIX;
1577 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1578 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1582 strcpy(serv_unix.sun_path, iface);
1583 if (serv_unix.sun_path[0] == '@')
1584 serv_unix.sun_path[0] = '\0';
1589 if (LWS_IPV6_ENABLED(vhost->context)) {
1590 v = (struct sockaddr *)&serv_addr6;
1591 n = sizeof(struct sockaddr_in6);
1592 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1593 serv_addr6.sin6_addr = in6addr_any;
1594 serv_addr6.sin6_family = AF_INET6;
1595 serv_addr6.sin6_port = htons(port);
1599 v = (struct sockaddr *)&serv_addr4;
1600 n = sizeof(serv_addr4);
1601 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1602 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1603 serv_addr4.sin_family = AF_INET;
1606 interface_to_sa(vhost->context, iface,
1607 (struct sockaddr_in *)v, n) < 0) {
1608 lwsl_err("Unable to find interface %s\n", iface);
1612 serv_addr4.sin_port = htons(port);
1615 n = bind(sockfd, v, n);
1616 #ifdef LWS_USE_UNIX_SOCK
1617 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
1618 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1619 sockfd, iface, n, LWS_ERRNO);
1624 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1625 sockfd, port, n, LWS_ERRNO);
1629 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1630 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1632 port = ntohs(sin.sin_port);
1638 LWS_VISIBLE LWS_EXTERN int
1639 lws_urlencode(const char *in, int inlen, char *out, int outlen)
1641 const char *hex = "0123456789ABCDEF";
1642 char *start = out, *end = out + outlen;
1644 while (inlen-- && out < end - 4) {
1645 if ((*in >= 'A' && *in <= 'Z') ||
1646 (*in >= 'a' && *in <= 'z') ||
1647 (*in >= '0' && *in <= '9') ||
1655 *out++ = hex[(*in) >> 4];
1656 *out++ = hex[(*in++) & 15];
1667 LWS_VISIBLE LWS_EXTERN int
1668 lws_finalize_startup(struct lws_context *context)
1670 struct lws_context_creation_info info;
1672 info.uid = context->uid;
1673 info.gid = context->gid;
1675 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1676 lws_plat_drop_app_privileges(&info);
1682 LWS_VISIBLE LWS_EXTERN int
1683 lws_is_cgi(struct lws *wsi) {
1694 lws_create_basic_wsi(struct lws_context *context, int tsi)
1696 struct lws *new_wsi;
1698 if ((unsigned int)context->pt[tsi].fds_count ==
1699 context->fd_limit_per_thread - 1) {
1700 lwsl_err("no space for new conn\n");
1704 new_wsi = lws_zalloc(sizeof(struct lws));
1705 if (new_wsi == NULL) {
1706 lwsl_err("Out of memory for new connection\n");
1711 new_wsi->context = context;
1712 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1713 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1715 /* intialize the instance struct */
1717 new_wsi->state = LWSS_CGI;
1718 new_wsi->mode = LWSCM_CGI;
1719 new_wsi->hdr_parsing_completed = 0;
1720 new_wsi->position_in_fds_table = -1;
1723 * these can only be set once the protocol is known
1724 * we set an unestablished connection's protocol pointer
1725 * to the start of the defauly vhost supported list, so it can look
1726 * for matching ones during the handshake
1728 new_wsi->protocol = context->vhost_list->protocols;
1729 new_wsi->user_space = NULL;
1730 new_wsi->ietf_spec_revision = 0;
1731 new_wsi->sock = LWS_SOCK_INVALID;
1732 context->count_wsi_allocated++;
1738 * lws_cgi: spawn network-connected cgi process
1740 * @wsi: connection to own the process
1741 * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1744 LWS_VISIBLE LWS_EXTERN int
1745 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
1746 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
1748 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1749 char *env_array[30], cgi_path[400], e[1024], *p = e,
1750 *end = p + sizeof(e) - 1, tok[256], *t;
1751 struct lws_cgi *cgi;
1752 int n, m, i, uritok = WSI_TOKEN_GET_URI;
1755 * give the master wsi a cgi struct
1758 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1760 lwsl_err("%s: OOM\n", __func__);
1765 cgi->wsi = wsi; /* set cgi's owning wsi */
1767 /* create pipes for [stdin|stdout] and [stderr] */
1769 for (n = 0; n < 3; n++)
1770 if (pipe(cgi->pipe_fds[n]) == -1)
1773 /* create cgi wsis for each stdin/out/err fd */
1775 for (n = 0; n < 3; n++) {
1776 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1777 if (!cgi->stdwsi[n])
1779 cgi->stdwsi[n]->cgi_channel = n;
1780 cgi->stdwsi[n]->vhost = wsi->vhost;
1782 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
1783 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
1785 /* read side is 0, stdin we want the write side, others read */
1786 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1787 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
1788 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
1793 for (n = 0; n < 3; n++) {
1794 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->sock);
1795 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1797 cgi->stdwsi[n]->parent = wsi;
1798 cgi->stdwsi[n]->sibling_list = wsi->child_list;
1799 wsi->child_list = cgi->stdwsi[n];
1802 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1803 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1804 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1806 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1807 cgi->stdwsi[LWS_STDIN]->sock, cgi->stdwsi[LWS_STDOUT]->sock,
1808 cgi->stdwsi[LWS_STDERR]->sock);
1810 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1812 /* the cgi stdout is always sending us http1.x header data first */
1813 wsi->hdr_state = LCHS_HEADER;
1815 /* add us to the pt list of active cgis */
1816 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
1817 cgi->cgi_list = pt->cgi_list;
1820 /* prepare his CGI env */
1824 if (lws_is_ssl(wsi))
1825 env_array[n++] = "HTTPS=ON";
1826 if (wsi->u.hdr.ah) {
1827 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1828 uritok = WSI_TOKEN_POST_URI;
1829 snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
1830 lws_hdr_simple_ptr(wsi, uritok));
1831 cgi_path[sizeof(cgi_path) - 1] = '\0';
1832 env_array[n++] = cgi_path;
1833 if (uritok == WSI_TOKEN_POST_URI)
1834 env_array[n++] = "REQUEST_METHOD=POST";
1836 env_array[n++] = "REQUEST_METHOD=GET";
1839 p += snprintf(p, end - p, "QUERY_STRING=");
1840 /* dump the individual URI Arg parameters */
1843 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
1844 WSI_TOKEN_HTTP_URI_ARGS, m);
1848 while (*t && *t != '=' && p < end - 4)
1852 i = lws_urlencode(t, i- (t - tok), p, end - p);
1864 p += snprintf(p, end - p, "PATH_INFO=%s",
1865 lws_hdr_simple_ptr(wsi, uritok) +
1866 script_uri_path_len);
1869 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
1871 p += snprintf(p, end - p, "HTTP_REFERER=%s",
1872 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
1875 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1877 p += snprintf(p, end - p, "HTTP_HOST=%s",
1878 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1881 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
1883 p += snprintf(p, end - p, "HTTP_COOKIE=%s",
1884 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
1887 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
1889 p += snprintf(p, end - p, "USER_AGENT=%s",
1890 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
1893 if (uritok == WSI_TOKEN_POST_URI) {
1894 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
1896 p += snprintf(p, end - p, "CONTENT_TYPE=%s",
1897 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
1900 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
1902 p += snprintf(p, end - p, "CONTENT_LENGTH=%s",
1903 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
1908 p += snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
1912 p += snprintf(p, end - p, "%s=%s", mp_cgienv->name,
1914 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
1917 mp_cgienv = mp_cgienv->next;
1920 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1921 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
1922 env_array[n] = NULL;
1925 for (m = 0; m < n; m++)
1926 lwsl_err(" %s\n", env_array[m]);
1930 * Actually having made the env, as a cgi we don't need the ah
1933 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
1934 lws_header_table_detach(wsi, 0);
1936 /* we are ready with the redirection pipes... run the thing */
1937 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1943 lwsl_err("fork failed, errno %d", errno);
1947 #if defined(__linux__)
1948 prctl(PR_SET_PDEATHSIG, SIGTERM);
1950 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
1953 /* we are the parent process */
1954 wsi->context->count_cgi_spawned++;
1955 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
1959 /* somewhere we can at least read things and enter it */
1961 lwsl_notice("%s: Failed to chdir\n", __func__);
1963 /* We are the forked process, redirect and kill inherited things.
1965 * Because of vfork(), we cannot do anything that changes pages in
1966 * the parent environment. Stuff that changes kernel state for the
1967 * process is OK. Stuff that happens after the execvpe() is OK.
1970 for (n = 0; n < 3; n++)
1971 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
1972 lwsl_err("%s: stdin dup2 failed\n", __func__);
1976 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1977 for (m = 0; m < n; m++) {
1978 p = strchr(env_array[m], '=');
1980 setenv(env_array[m], p, 1);
1982 execvp(exec_array[0], (char * const *)&exec_array[0]);
1984 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
1990 /* drop us from the pt cgi list */
1991 pt->cgi_list = cgi->cgi_list;
1994 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
1996 for (n = 0; n < 3; n++)
1997 if (wsi->cgi->stdwsi[n])
1998 lws_free_wsi(cgi->stdwsi[n]);
2001 for (n = 0; n < 3; n++) {
2002 if (cgi->pipe_fds[n][0])
2003 close(cgi->pipe_fds[n][0]);
2004 if (cgi->pipe_fds[n][1])
2005 close(cgi->pipe_fds[n][1]);
2008 lws_free_set_NULL(wsi->cgi);
2010 lwsl_err("%s: failed\n", __func__);
2015 * lws_cgi_write_split_headers: write cgi output accounting for header part
2017 * @wsi: connection to own the process
2019 LWS_VISIBLE LWS_EXTERN int
2020 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2022 int n, m, match = 0, lp = 0;
2023 static const char * const content_length = "content-length: ";
2024 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2025 *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
2030 while (wsi->hdr_state != LHCS_PAYLOAD) {
2031 /* we have to separate header / finalize and
2032 * payload chunks, since they need to be
2033 * handled separately
2035 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2037 if (errno != EAGAIN) {
2038 lwsl_debug("%s: read says %d\n", __func__, n);
2045 lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
2046 switch (wsi->hdr_state) {
2048 if (!content_length[match] &&
2049 (c >= '0' && c <= '9') &&
2050 lp < sizeof(l) - 1) {
2053 wsi->cgi->content_length = atol(l);
2055 if (tolower(c) == content_length[match])
2060 /* some cgi only send us \x0a for EOL */
2062 wsi->hdr_state = LCHS_SINGLE_0A;
2067 wsi->hdr_state = LCHS_LF1;
2075 wsi->hdr_state = LCHS_CR2;
2078 /* we got \r[^\n]... it's unreasonable */
2079 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2085 wsi->hdr_state = LCHS_LF2;
2088 wsi->hdr_state = LCHS_HEADER;
2093 case LCHS_SINGLE_0A:
2096 lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
2097 wsi->hdr_state = LHCS_PAYLOAD;
2098 /* drop the \0xa ... finalize will add it if needed */
2099 if (lws_finalize_http_header(wsi,
2100 (unsigned char **)&p,
2101 (unsigned char *)end))
2106 /* we got \r\n\r[^\n]... it's unreasonable */
2108 /* we got \x0anext header, it's reasonable */
2110 wsi->hdr_state = LCHS_HEADER;
2117 /* ran out of input, ended the headers, or filled up the headers buf */
2118 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2120 m = lws_write(wsi, (unsigned char *)start,
2121 p - start, LWS_WRITE_HTTP_HEADERS);
2123 lwsl_debug("%s: write says %d\n", __func__, m);
2126 /* writeability becomes uncertain now we wrote
2127 * something, we must return to the event loop
2134 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2135 start, sizeof(buf) - LWS_PRE);
2137 if (n < 0 && errno != EAGAIN) {
2138 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2142 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2143 //lwsl_notice("write %d\n", m);
2145 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2148 wsi->cgi->content_length_seen += m;
2155 * lws_cgi_kill: terminate cgi process associated with wsi
2157 * @wsi: connection to own the process
2159 LWS_VISIBLE LWS_EXTERN int
2160 lws_cgi_kill(struct lws *wsi)
2162 struct lws_cgi_args args;
2165 lwsl_debug("%s: %p\n", __func__, wsi);
2170 if (wsi->cgi->pid > 0) {
2171 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2173 lwsl_debug("%s: PID %d reaped\n", __func__,
2177 /* kill the process group */
2178 n = kill(-wsi->cgi->pid, SIGTERM);
2179 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2180 wsi->cgi->pid, n, errno);
2183 * hum seen errno=3 when process is listed in ps,
2184 * it seems we don't always retain process grouping
2186 * Direct these fallback attempt to the exact child
2188 n = kill(wsi->cgi->pid, SIGTERM);
2190 n = kill(wsi->cgi->pid, SIGPIPE);
2192 n = kill(wsi->cgi->pid, SIGKILL);
2194 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2195 __func__, wsi->cgi->pid, errno);
2199 /* He could be unkillable because he's a zombie */
2202 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2204 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2206 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2208 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2214 args.stdwsi = &wsi->cgi->stdwsi[0];
2216 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2217 wsi->protocol->callback,
2218 wsi, LWS_CALLBACK_CGI_TERMINATED,
2220 (void *)&args, 0)) {
2222 if (!wsi->cgi->being_closed)
2223 lws_close_free_wsi(wsi, 0);
2230 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2232 struct lws_cgi **pcgi, *cgi = NULL;
2236 /* find finished guys but don't reap yet */
2237 n = waitpid(-1, &status, WNOHANG | WNOWAIT);
2240 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
2242 pcgi = &pt->cgi_list;
2244 /* check all the subprocesses on the cgi list */
2246 /* get the next one first as list may change */
2248 pcgi = &(*pcgi)->cgi_list;
2253 /* wait for stdout to be drained */
2254 if (cgi->content_length > cgi->content_length_seen)
2257 if (cgi->content_length) {
2258 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2259 __func__, cgi->wsi, cgi->content_length_seen);
2263 waitpid(n, &status, WNOHANG);
2265 * he's already terminated so no need for kill()
2266 * but we should do the terminated cgi callback
2267 * and close him if he's not already closing
2269 if (n == cgi->pid) {
2270 lwsl_debug("%s: found PID %d on cgi list\n",
2274 lws_cgi_kill(cgi->wsi);
2280 /* if not found on the cgi list, as he's one of ours, reap */
2282 lwsl_debug("%s: reading PID %d although no cgi match\n",
2284 waitpid(n, &status, WNOHANG);
2288 /* disable this to confirm timeout cgi cleanup flow */
2290 pcgi = &pt->cgi_list;
2292 /* check all the subprocesses on the cgi list */
2294 /* get the next one first as list may change */
2296 pcgi = &(*pcgi)->cgi_list;
2301 /* wait for stdout to be drained */
2302 if (cgi->content_length > cgi->content_length_seen)
2305 if (cgi->content_length) {
2306 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2307 __func__, cgi->wsi, cgi->content_length_seen);
2311 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2313 lwsl_debug("%s: found PID %d on cgi list\n",
2314 __func__, cgi->pid);
2317 lws_cgi_kill(cgi->wsi);
2324 /* general anti zombie defence */
2325 n = waitpid(-1, &status, WNOHANG);
2327 lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
2333 #ifdef LWS_NO_EXTENSIONS
2335 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2336 const char *opt_name, const char *opt_val)
2342 #ifdef LWS_WITH_ACCESS_LOG
2344 lws_access_log(struct lws *wsi)
2346 char *p = wsi->access_log.user_agent, ass[512];
2349 if (!wsi->access_log_pending)
2352 if (!wsi->access_log.header_log)
2358 l = snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
2359 wsi->access_log.header_log,
2360 wsi->access_log.response, wsi->access_log.sent, p);
2362 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
2363 if (write(wsi->vhost->log_fd, ass, l) != l)
2364 lwsl_err("Failed to write log\n");
2366 lwsl_err("%s", ass);
2368 if (wsi->access_log.header_log) {
2369 lws_free(wsi->access_log.header_log);
2370 wsi->access_log.header_log = NULL;
2372 if (wsi->access_log.user_agent) {
2373 lws_free(wsi->access_log.user_agent);
2374 wsi->access_log.user_agent = NULL;
2376 wsi->access_log_pending = 0;
2382 #ifdef LWS_WITH_SERVER_STATUS
2385 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
2387 static const char * const prots[] = {
2396 char *orig = buf, *end = buf + len - 1, first = 1;
2402 buf += snprintf(buf, end - buf,
2403 "{\n \"name\":\"%s\",\n"
2404 " \"port\":\"%d\",\n"
2405 " \"use_ssl\":\"%d\",\n"
2406 " \"sts\":\"%d\",\n"
2407 " \"rx\":\"%llu\",\n"
2408 " \"tx\":\"%llu\",\n"
2409 " \"conn\":\"%lu\",\n"
2410 " \"trans\":\"%lu\",\n"
2411 " \"ws_upg\":\"%lu\",\n"
2412 " \"http2_upg\":\"%lu\""
2414 vh->name, vh->listen_port,
2415 #ifdef LWS_OPENSSL_SUPPORT
2420 !!(vh->options & LWS_SERVER_OPTION_STS),
2421 vh->rx, vh->tx, vh->conn, vh->trans, vh->ws_upgrades,
2425 if (vh->mount_list) {
2426 const struct lws_http_mount *m = vh->mount_list;
2428 buf += snprintf(buf, end - buf, ",\n \"mounts\":[");
2431 buf += snprintf(buf, end - buf, ",");
2432 buf += snprintf(buf, end - buf,
2433 "\n {\n \"mountpoint\":\"%s\",\n"
2434 " \"origin\":\"%s%s\",\n"
2435 " \"cache_max_age\":\"%d\",\n"
2436 " \"cache_reuse\":\"%d\",\n"
2437 " \"cache_revalidate\":\"%d\",\n"
2438 " \"cache_intermediaries\":\"%d\"\n"
2441 prots[m->origin_protocol],
2445 m->cache_revalidate,
2446 m->cache_intermediaries);
2448 buf += snprintf(buf, end - buf,
2449 ",\n \"default\":\"%s\"",
2451 buf += snprintf(buf, end - buf, "\n }");
2455 buf += snprintf(buf, end - buf, "\n ]");
2458 if (vh->protocols) {
2462 buf += snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
2463 while (n < vh->count_protocols) {
2465 buf += snprintf(buf, end - buf, ",");
2466 buf += snprintf(buf, end - buf,
2468 " \"status\":\"ok\"\n }\n }"
2470 vh->protocols[n].name);
2474 buf += snprintf(buf, end - buf, "\n ]");
2477 buf += snprintf(buf, end - buf, "\n}");
2483 LWS_EXTERN LWS_VISIBLE int
2484 lws_json_dump_context(const struct lws_context *context, char *buf, int len)
2486 char *orig = buf, *end = buf + len - 1, first = 1;
2487 const struct lws_vhost *vh = context->vhost_list;
2490 struct lws_cgi * const *pcgi;
2492 const struct lws_context_per_thread *pt;
2493 time_t t = time(NULL);
2494 int listening = 0, cgi_count = 0, n;
2496 buf += snprintf(buf, end - buf, "{ "
2497 "\"version\":\"%s\",\n"
2498 "\"uptime\":\"%ld\",\n"
2499 "\"cgi_spawned\":\"%d\",\n"
2500 "\"pt_fd_max\":\"%d\",\n"
2501 "\"ah_pool_max\":\"%d\",\n"
2502 "\"wsi_alive\":\"%d\",\n",
2503 lws_get_library_version(),
2504 (unsigned long)(t - context->time_up),
2505 context->count_cgi_spawned,
2506 context->fd_limit_per_thread,
2507 context->max_http_header_pool,
2508 context->count_wsi_allocated);
2509 #ifdef LWS_HAVE_GETLOADAVG
2514 m = getloadavg(d, 3);
2515 for (n = 0; n < m; n++) {
2516 buf += snprintf(buf, end - buf,
2517 "\"l%d\":\"%.2f\",\n",
2523 buf += snprintf(buf, end - buf, "\"pt\":[\n ");
2524 for (n = 0; n < context->count_threads; n++) {
2525 pt = &context->pt[n];
2527 buf += snprintf(buf, end - buf, ",");
2528 buf += snprintf(buf, end - buf,
2530 " \"fds_count\":\"%d\",\n"
2531 " \"ah_pool_inuse\":\"%d\",\n"
2532 " \"ah_wait_list\":\"%d\"\n"
2535 pt->ah_count_in_use,
2536 pt->ah_wait_list_length);
2539 buf += snprintf(buf, end - buf, "], \"vhosts\":[\n ");
2545 buf += lws_json_dump_vhost(vh, buf, end - buf);
2549 vh = vh->vhost_next;
2552 buf += snprintf(buf, end - buf, "],\n\"listen_wsi\":\"%d\"",
2556 for (n = 0; n < context->count_threads; n++) {
2557 pt = &context->pt[n];
2558 pcgi = &pt->cgi_list;
2561 pcgi = &(*pcgi)->cgi_list;
2567 buf += snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
2570 buf += snprintf(buf, end - buf, "}\n ");