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(struct lws *wsi, char *name, int namelen)
663 struct sockaddr_in6 sin6;
665 struct sockaddr_in sin4;
670 if (LWS_IPV6_ENABLED(wsi->context)) {
684 if (getpeername(wsi->sock, p, &len) < 0 || len > olen) {
685 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
689 return lws_plat_inet_ntop(af, q, name, namelen);
696 * lws_get_peer_addresses() - Get client address information
697 * @wsi: Local struct lws associated with
698 * @fd: Connection socket descriptor
699 * @name: Buffer to take client address name
700 * @name_len: Length of client address name buffer
701 * @rip: Buffer to take client address IP dotted quad
702 * @rip_len: Length of client address IP buffer
704 * This function fills in @name and @rip with the name and IP of
705 * the client connected with socket descriptor @fd. Names may be
706 * truncated if there is not enough room. If either cannot be
707 * determined, they will be returned as valid zero-length strings.
711 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
712 int name_len, char *rip, int rip_len)
717 struct sockaddr_in6 sin6;
719 struct sockaddr_in sin4;
720 struct lws_context *context = wsi->context;
727 lws_latency_pre(context, wsi);
730 if (LWS_IPV6_ENABLED(context)) {
740 if (getpeername(fd, p, &len) < 0) {
741 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
745 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
748 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
760 * lws_context_user() - get the user data associated with the context
761 * @context: Websocket context
763 * This returns the optional user allocation that can be attached to
764 * the context the sockets live in at context_create time. It's a way
765 * to let all sockets serviced in the same context share data without
766 * using globals statics in the user code.
769 lws_context_user(struct lws_context *context)
771 return context->user_space;
774 LWS_VISIBLE struct lws_vhost *
775 lws_vhost_get(struct lws *wsi)
780 LWS_VISIBLE const struct lws_protocols *
781 lws_protocol_get(struct lws *wsi)
783 return wsi->protocol;
788 * lws_callback_all_protocol() - Callback all connections using
789 * the given protocol with the given reason
791 * @protocol: Protocol whose connections will get callbacks
792 * @reason: Callback reason index
796 lws_callback_all_protocol(struct lws_context *context,
797 const struct lws_protocols *protocol, int reason)
799 struct lws_context_per_thread *pt = &context->pt[0];
800 unsigned int n, m = context->count_threads;
804 for (n = 0; n < pt->fds_count; n++) {
805 wsi = wsi_from_fd(context, pt->fds[n].fd);
808 if (wsi->protocol == protocol)
809 protocol->callback(wsi, reason, wsi->user_space,
819 * lws_callback_all_protocol_vhost() - Callback all connections using
820 * the given protocol with the given reason
822 * @vh: Vhost whose connections will get callbacks
823 * @protocol: Which protocol to match
824 * @reason: Callback reason index
828 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
829 const struct lws_protocols *protocol, int reason)
831 struct lws_context *context = vh->context;
832 struct lws_context_per_thread *pt = &context->pt[0];
833 unsigned int n, m = context->count_threads;
837 for (n = 0; n < pt->fds_count; n++) {
838 wsi = wsi_from_fd(context, pt->fds[n].fd);
841 if (wsi->vhost == vh && wsi->protocol == protocol)
842 protocol->callback(wsi, reason, wsi->user_space,
854 * lws_get_socket_fd() - returns the socket file descriptor
856 * You will not need this unless you are doing something special
858 * @wsi: Websocket connection instance
862 lws_get_socket_fd(struct lws *wsi)
871 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
872 int ret, int completed)
874 unsigned long long u;
877 u = time_in_microseconds();
880 wsi->latency_start = u;
881 if (!wsi->action_start)
882 wsi->action_start = u;
886 if (wsi->action_start == wsi->latency_start)
888 "Completion first try lat %lluus: %p: ret %d: %s\n",
889 u - wsi->latency_start,
890 (void *)wsi, ret, action);
893 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
894 u - wsi->action_start,
895 u - wsi->latency_start,
896 (void *)wsi, ret, action);
897 wsi->action_start = 0;
899 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
900 u - wsi->latency_start, (void *)wsi, ret, action);
902 if (u - wsi->latency_start > context->worst_latency) {
903 context->worst_latency = u - wsi->latency_start;
904 strcpy(context->worst_latency_info, buf);
906 lwsl_latency("%s", buf);
913 * lws_rx_flow_control() - Enable and disable socket servicing for
916 * If the output side of a server process becomes choked, this allows flow
917 * control for the input side.
919 * @wsi: Websocket connection instance to get callback for
920 * @enable: 0 = disable read servicing for this connection, 1 = enable
924 lws_rx_flow_control(struct lws *wsi, int enable)
926 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
929 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
930 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
936 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
938 * When the user server code realizes it can accept more input, it can
939 * call this to have the RX flow restriction removed from all connections using
940 * the given protocol.
942 * @protocol: all connections using this protocol will be allowed to receive
946 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
947 const struct lws_protocols *protocol)
949 const struct lws_context_per_thread *pt = &context->pt[0];
951 unsigned int n, m = context->count_threads;
954 for (n = 0; n < pt->fds_count; n++) {
955 wsi = wsi_from_fd(context, pt->fds[n].fd);
958 if (wsi->protocol == protocol)
959 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
967 * lws_canonical_hostname() - returns this host's hostname
969 * This is typically used by client code to fill in the host parameter
970 * when making a client connection. You can only call it after the context
973 * @context: Websocket context
975 LWS_VISIBLE extern const char *
976 lws_canonical_hostname(struct lws_context *context)
978 return (const char *)context->canonical_hostname;
981 int user_callback_handle_rxflow(lws_callback_function callback_function,
983 enum lws_callback_reasons reason, void *user,
984 void *in, size_t len)
988 n = callback_function(wsi, reason, user, in, len);
990 n = _lws_rx_flow_control(wsi);
997 * lws_set_proxy() - Setups proxy to lws_context.
998 * @context: pointer to struct lws_context you want set proxy to
999 * @proxy: pointer to c string containing proxy in format address:port
1001 * Returns 0 if proxy string was parsed and proxy was setup.
1002 * Returns -1 if @proxy is NULL or has incorrect format.
1004 * This is only required if your OS does not provide the http_proxy
1005 * environment variable (eg, OSX)
1007 * IMPORTANT! You should call this function right after creation of the
1008 * lws_context and before call to connect. If you call this
1009 * function after connect behavior is undefined.
1010 * This function will override proxy settings made on lws_context
1011 * creation with genenv() call.
1015 lws_set_proxy(struct lws_vhost *vhost, const char *proxy)
1018 char authstring[96];
1023 p = strchr(proxy, '@');
1024 if (p) { /* auth is around */
1026 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
1029 strncpy(authstring, proxy, p - proxy);
1030 // null termination not needed on input
1031 if (lws_b64_encode_string(authstring, (p - proxy),
1032 vhost->proxy_basic_auth_token,
1033 sizeof vhost->proxy_basic_auth_token) < 0)
1036 lwsl_notice(" Proxy auth in use\n");
1040 vhost->proxy_basic_auth_token[0] = '\0';
1042 strncpy(vhost->http_proxy_address, proxy,
1043 sizeof(vhost->http_proxy_address) - 1);
1044 vhost->http_proxy_address[
1045 sizeof(vhost->http_proxy_address) - 1] = '\0';
1047 p = strchr(vhost->http_proxy_address, ':');
1048 if (!p && !vhost->http_proxy_port) {
1049 lwsl_err("http_proxy needs to be ads:port\n");
1055 vhost->http_proxy_port = atoi(p + 1);
1059 lwsl_notice(" Proxy %s:%u\n", vhost->http_proxy_address,
1060 vhost->http_proxy_port);
1065 lwsl_err("proxy auth too long\n");
1071 * lws_get_protocol() - Returns a protocol pointer from a websocket
1073 * @wsi: pointer to struct websocket you want to know the protocol of
1076 * Some apis can act on all live connections of a given protocol,
1077 * this is how you can get a pointer to the active protocol if needed.
1080 LWS_VISIBLE const struct lws_protocols *
1081 lws_get_protocol(struct lws *wsi)
1083 return wsi->protocol;
1087 lws_is_final_fragment(struct lws *wsi)
1089 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
1090 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
1091 wsi->u.ws.rx_draining_ext);
1092 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
1095 LWS_VISIBLE unsigned char
1096 lws_get_reserved_bits(struct lws *wsi)
1098 return wsi->u.ws.rsv;
1102 lws_ensure_user_space(struct lws *wsi)
1104 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
1108 /* allocate the per-connection user memory (if any) */
1110 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
1111 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
1112 if (wsi->user_space == NULL) {
1113 lwsl_err("Out of memory for conn user space\n");
1117 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
1118 __func__, wsi, wsi->protocol->per_session_data_size,
1124 * lwsl_timestamp: generate logging timestamp string
1126 * @level: logging level
1127 * @p: char * buffer to take timestamp
1130 * returns length written in p
1133 lwsl_timestamp(int level, char *p, int len)
1135 time_t o_now = time(NULL);
1136 unsigned long long now;
1137 struct tm *ptm = NULL;
1145 ptm = localtime(&o_now);
1147 if (localtime_r(&o_now, &tm))
1152 for (n = 0; n < LLL_COUNT; n++) {
1153 if (level != (1 << n))
1155 now = time_in_microseconds() / 100;
1157 n = snprintf(p, len,
1158 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1159 ptm->tm_year + 1900,
1165 (int)(now % 10000), log_level_names[n]);
1167 n = snprintf(p, len, "[%llu:%04d] %s: ",
1168 (unsigned long long) now / 10000,
1169 (int)(now % 10000), log_level_names[n]);
1176 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1180 lwsl_timestamp(level, buf, sizeof(buf));
1182 fprintf(stderr, "%s%s", buf, line);
1185 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1189 if (!(log_level & filter))
1192 vsnprintf(buf, sizeof(buf), format, vl);
1193 buf[sizeof(buf) - 1] = '\0';
1195 lwsl_emit(filter, buf);
1198 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1202 va_start(ap, format);
1203 _lws_logv(filter, format, ap);
1208 * lws_set_log_level() - Set the logging bitfield
1209 * @level: OR together the LLL_ debug contexts you want output from
1210 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1211 * function to perform log string emission instead of
1212 * the default stderr one.
1214 * log level defaults to "err", "warn" and "notice" contexts enabled and
1215 * emission on stderr.
1218 LWS_VISIBLE void lws_set_log_level(int level,
1219 void (*func)(int level, const char *line))
1227 * lws_use_ssl() - Find out if connection is using SSL
1228 * @wsi: websocket connection to check
1230 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1231 * using verified cert, and 2 if using SSL but the cert was not
1232 * checked (appears for client wsi told to skip check on connection)
1235 lws_is_ssl(struct lws *wsi)
1237 #ifdef LWS_OPENSSL_SUPPORT
1238 return wsi->use_ssl;
1246 * lws_partial_buffered() - find out if lws buffered the last write
1247 * @wsi: websocket connection to check
1249 * Returns 1 if you cannot use lws_write because the last
1250 * write on this connection is still buffered, and can't be cleared without
1251 * returning to the service loop and waiting for the connection to be
1254 * If you will try to do >1 lws_write call inside a single
1255 * WRITEABLE callback, you must check this after every write and bail if
1256 * set, ask for a new writeable callback and continue writing from there.
1258 * This is never set at the start of a writeable callback, but any write
1263 lws_partial_buffered(struct lws *wsi)
1265 return !!wsi->trunc_len;
1268 void lws_set_protocol_write_pending(struct lws *wsi,
1269 enum lws_pending_protocol_send pend)
1271 lwsl_info("setting pps %d\n", pend);
1274 lwsl_err("pps overwrite\n");
1276 lws_rx_flow_control(wsi, 0);
1277 lws_callback_on_writable(wsi);
1281 lws_get_peer_write_allowance(struct lws *wsi)
1283 #ifdef LWS_USE_HTTP2
1284 /* only if we are using HTTP2 on this connection */
1285 if (wsi->mode != LWSCM_HTTP2_SERVING)
1287 /* user is only interested in how much he can send, or that he can't */
1288 if (wsi->u.http2.tx_credit <= 0)
1291 return wsi->u.http2.tx_credit;
1299 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1301 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1302 memset(&wsi->u, 0, sizeof(wsi->u));
1306 LWS_VISIBLE struct lws_plat_file_ops *
1307 lws_get_fops(struct lws_context *context)
1309 return &context->fops;
1312 LWS_VISIBLE LWS_EXTERN struct lws_context *
1313 lws_get_context(const struct lws *wsi)
1315 return wsi->context;
1318 LWS_VISIBLE LWS_EXTERN int
1319 lws_get_count_threads(struct lws_context *context)
1321 return context->count_threads;
1324 LWS_VISIBLE LWS_EXTERN void *
1325 lws_wsi_user(struct lws *wsi)
1327 return wsi->user_space;
1330 LWS_VISIBLE LWS_EXTERN struct lws *
1331 lws_get_parent(const struct lws *wsi)
1336 LWS_VISIBLE LWS_EXTERN struct lws *
1337 lws_get_child(const struct lws *wsi)
1339 return wsi->child_list;
1342 LWS_VISIBLE LWS_EXTERN void
1343 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1344 unsigned char *buf, size_t len)
1346 unsigned char *p, *start;
1347 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1349 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1351 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1353 *p++ = (((int)status) >> 8) & 0xff;
1354 *p++ = ((int)status) & 0xff;
1357 while (len-- && p < start + budget)
1360 wsi->u.ws.close_in_ping_buffer_len = p - start;
1364 _lws_rx_flow_control(struct lws *wsi)
1366 /* there is no pending change */
1367 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1368 lwsl_debug("%s: no pending change\n", __func__);
1372 /* stuff is still buffered, not ready to really accept new input */
1373 if (wsi->rxflow_buffer) {
1374 /* get ourselves called back to deal with stashed buffer */
1375 lws_callback_on_writable(wsi);
1379 /* pending is cleared, we can change rxflow state */
1381 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1383 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1384 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1386 /* adjust the pollfd for this wsi */
1388 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1389 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1390 lwsl_info("%s: fail\n", __func__);
1394 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1401 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1403 static const unsigned char e0f4[] = {
1404 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1405 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1406 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1407 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1408 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1409 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1410 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1411 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1412 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1413 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1414 0x80 | ((4 - 1) << 2) | 1, /* ea */
1415 0x80 | ((4 - 1) << 2) | 1, /* eb */
1416 0x80 | ((4 - 1) << 2) | 1, /* ec */
1417 0x80 | ((2 - 1) << 2) | 1, /* ed */
1418 0x80 | ((4 - 1) << 2) | 1, /* ee */
1419 0x80 | ((4 - 1) << 2) | 1, /* ef */
1420 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1421 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1422 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1423 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1424 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1427 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1428 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1430 unsigned char s = *state;
1433 unsigned char c = *buf++;
1437 if (c < 0xc2 || c > 0xf4)
1440 s = 0x80 | ((4 - 1) << 2);
1445 if (c < (s & 0xf0) ||
1446 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1448 s = e0f4[21 + (s & 3)];
1458 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1459 * Notice it does so by dropping '\0' into input string
1460 * and the leading / on the path is consequently lost
1462 * @p: incoming uri string.. will get written to
1463 * @prot: result pointer for protocol part (https://)
1464 * @ads: result pointer for address part
1465 * @port: result pointer for port part
1466 * @path: result pointer for path part
1469 LWS_VISIBLE LWS_EXTERN int
1470 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1474 static const char *slash = "/";
1476 /* cut up the location into address, port and path */
1478 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1489 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1491 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1494 while (*p && *p != ':' && *p != '/')
1499 while (*p && *p != '/')
1512 #ifdef LWS_NO_EXTENSIONS
1514 /* we need to provide dummy callbacks for internal exts
1515 * so user code runs when faced with a lib compiled with
1516 * extensions disabled.
1520 lws_extension_callback_pm_deflate(struct lws_context *context,
1521 const struct lws_extension *ext,
1523 enum lws_extension_callback_reasons reason,
1524 void *user, void *in, size_t len)
1539 lws_socket_bind(struct lws_vhost *vhost, int sockfd, int port,
1543 #ifdef LWS_USE_UNIX_SOCK
1544 struct sockaddr_un serv_unix;
1547 struct sockaddr_in6 serv_addr6;
1549 struct sockaddr_in serv_addr4;
1550 socklen_t len = sizeof(struct sockaddr);
1552 struct sockaddr_in sin;
1555 #ifdef LWS_USE_UNIX_SOCK
1556 if (LWS_UNIX_SOCK_ENABLED(vhost)) {
1557 v = (struct sockaddr *)&serv_unix;
1558 n = sizeof(struct sockaddr_un);
1559 bzero((char *) &serv_unix, sizeof(serv_unix));
1560 serv_unix.sun_family = AF_UNIX;
1561 if (sizeof(serv_unix.sun_path) <= strlen(iface)) {
1562 lwsl_err("\"%s\" too long for UNIX domain socket\n",
1566 strcpy(serv_unix.sun_path, iface);
1567 if (serv_unix.sun_path[0] == '@')
1568 serv_unix.sun_path[0] = '\0';
1573 if (LWS_IPV6_ENABLED(vhost->context)) {
1574 v = (struct sockaddr *)&serv_addr6;
1575 n = sizeof(struct sockaddr_in6);
1576 bzero((char *) &serv_addr6, sizeof(serv_addr6));
1577 serv_addr6.sin6_addr = in6addr_any;
1578 serv_addr6.sin6_family = AF_INET6;
1579 serv_addr6.sin6_port = htons(port);
1583 v = (struct sockaddr *)&serv_addr4;
1584 n = sizeof(serv_addr4);
1585 bzero((char *) &serv_addr4, sizeof(serv_addr4));
1586 serv_addr4.sin_addr.s_addr = INADDR_ANY;
1587 serv_addr4.sin_family = AF_INET;
1590 interface_to_sa(vhost->context, iface,
1591 (struct sockaddr_in *)v, n) < 0) {
1592 lwsl_err("Unable to find interface %s\n", iface);
1596 serv_addr4.sin_port = htons(port);
1599 n = bind(sockfd, v, n);
1600 #ifdef LWS_USE_UNIX_SOCK
1601 if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {
1602 lwsl_err("ERROR on binding fd %d to \"%s\" (%d %d)\n",
1603 sockfd, iface, n, LWS_ERRNO);
1608 lwsl_err("ERROR on binding fd %d to port %d (%d %d)\n",
1609 sockfd, port, n, LWS_ERRNO);
1613 if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
1614 lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
1616 port = ntohs(sin.sin_port);
1622 LWS_VISIBLE LWS_EXTERN int
1623 lws_urlencode(const char *in, int inlen, char *out, int outlen)
1625 const char *hex = "0123456789ABCDEF";
1626 char *start = out, *end = out + outlen;
1628 while (inlen-- && out < end - 4) {
1629 if ((*in >= 'A' && *in <= 'Z') ||
1630 (*in >= 'a' && *in <= 'z') ||
1631 (*in >= '0' && *in <= '9') ||
1639 *out++ = hex[(*in) >> 4];
1640 *out++ = hex[(*in++) & 15];
1651 LWS_VISIBLE LWS_EXTERN int
1652 lws_finalize_startup(struct lws_context *context)
1654 struct lws_context_creation_info info;
1656 info.uid = context->uid;
1657 info.gid = context->gid;
1659 if (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))
1660 lws_plat_drop_app_privileges(&info);
1666 LWS_VISIBLE LWS_EXTERN int
1667 lws_is_cgi(struct lws *wsi) {
1678 lws_create_basic_wsi(struct lws_context *context, int tsi)
1680 struct lws *new_wsi;
1682 if ((unsigned int)context->pt[tsi].fds_count ==
1683 context->fd_limit_per_thread - 1) {
1684 lwsl_err("no space for new conn\n");
1688 new_wsi = lws_zalloc(sizeof(struct lws));
1689 if (new_wsi == NULL) {
1690 lwsl_err("Out of memory for new connection\n");
1695 new_wsi->context = context;
1696 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1697 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1699 /* intialize the instance struct */
1701 new_wsi->state = LWSS_CGI;
1702 new_wsi->mode = LWSCM_CGI;
1703 new_wsi->hdr_parsing_completed = 0;
1704 new_wsi->position_in_fds_table = -1;
1707 * these can only be set once the protocol is known
1708 * we set an unestablished connection's protocol pointer
1709 * to the start of the defauly vhost supported list, so it can look
1710 * for matching ones during the handshake
1712 new_wsi->protocol = context->vhost_list->protocols;
1713 new_wsi->user_space = NULL;
1714 new_wsi->ietf_spec_revision = 0;
1715 new_wsi->sock = LWS_SOCK_INVALID;
1716 context->count_wsi_allocated++;
1722 * lws_cgi: spawn network-connected cgi process
1724 * @wsi: connection to own the process
1725 * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1728 LWS_VISIBLE LWS_EXTERN int
1729 lws_cgi(struct lws *wsi, const char * const *exec_array, int script_uri_path_len,
1730 int timeout_secs, const struct lws_protocol_vhost_options *mp_cgienv)
1732 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1733 char *env_array[30], cgi_path[400], e[1024], *p = e,
1734 *end = p + sizeof(e) - 1, tok[256], *t;
1735 struct lws_cgi *cgi;
1736 int n, m, i, uritok = WSI_TOKEN_GET_URI;
1739 * give the master wsi a cgi struct
1742 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1744 lwsl_err("%s: OOM\n", __func__);
1749 cgi->wsi = wsi; /* set cgi's owning wsi */
1751 /* create pipes for [stdin|stdout] and [stderr] */
1753 for (n = 0; n < 3; n++)
1754 if (pipe(cgi->pipe_fds[n]) == -1)
1757 /* create cgi wsis for each stdin/out/err fd */
1759 for (n = 0; n < 3; n++) {
1760 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1761 if (!cgi->stdwsi[n])
1763 cgi->stdwsi[n]->cgi_channel = n;
1764 cgi->stdwsi[n]->vhost = wsi->vhost;
1766 // lwsl_err("%s: cgi %p: pipe fd %d -> fd %d / %d\n", __func__, wsi, n,
1767 // cgi->pipe_fds[n][!!(n == 0)], cgi->pipe_fds[n][!(n == 0)]);
1769 /* read side is 0, stdin we want the write side, others read */
1770 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1771 if (fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK) < 0) {
1772 lwsl_err("%s: setting NONBLOCK failed\n", __func__);
1777 for (n = 0; n < 3; n++) {
1778 lws_libuv_accept(cgi->stdwsi[n], cgi->stdwsi[n]->sock);
1779 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1781 cgi->stdwsi[n]->parent = wsi;
1782 cgi->stdwsi[n]->sibling_list = wsi->child_list;
1783 wsi->child_list = cgi->stdwsi[n];
1786 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1787 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1788 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1790 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1791 cgi->stdwsi[LWS_STDIN]->sock, cgi->stdwsi[LWS_STDOUT]->sock,
1792 cgi->stdwsi[LWS_STDERR]->sock);
1794 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1796 /* the cgi stdout is always sending us http1.x header data first */
1797 wsi->hdr_state = LCHS_HEADER;
1799 /* add us to the pt list of active cgis */
1800 lwsl_debug("%s: adding cgi %p to list\n", __func__, wsi->cgi);
1801 cgi->cgi_list = pt->cgi_list;
1804 /* prepare his CGI env */
1808 if (lws_is_ssl(wsi))
1809 env_array[n++] = "HTTPS=ON";
1810 if (wsi->u.hdr.ah) {
1811 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1812 uritok = WSI_TOKEN_POST_URI;
1813 snprintf(cgi_path, sizeof(cgi_path) - 1, "REQUEST_URI=%s",
1814 lws_hdr_simple_ptr(wsi, uritok));
1815 cgi_path[sizeof(cgi_path) - 1] = '\0';
1816 env_array[n++] = cgi_path;
1817 if (uritok == WSI_TOKEN_POST_URI)
1818 env_array[n++] = "REQUEST_METHOD=POST";
1820 env_array[n++] = "REQUEST_METHOD=GET";
1823 p += snprintf(p, end - p, "QUERY_STRING=");
1824 /* dump the individual URI Arg parameters */
1827 i = lws_hdr_copy_fragment(wsi, tok, sizeof(tok),
1828 WSI_TOKEN_HTTP_URI_ARGS, m);
1832 while (*t && *t != '=' && p < end - 4)
1836 i = lws_urlencode(t, i- (t - tok), p, end - p);
1848 p += snprintf(p, end - p, "PATH_INFO=%s",
1849 lws_hdr_simple_ptr(wsi, uritok) +
1850 script_uri_path_len);
1853 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER)) {
1855 p += snprintf(p, end - p, "HTTP_REFERER=%s",
1856 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_REFERER));
1859 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1861 p += snprintf(p, end - p, "HTTP_HOST=%s",
1862 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1865 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
1867 p += snprintf(p, end - p, "HTTP_COOKIE=%s",
1868 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COOKIE));
1871 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT)) {
1873 p += snprintf(p, end - p, "USER_AGENT=%s",
1874 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_USER_AGENT));
1877 if (uritok == WSI_TOKEN_POST_URI) {
1878 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
1880 p += snprintf(p, end - p, "CONTENT_TYPE=%s",
1881 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE));
1884 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
1886 p += snprintf(p, end - p, "CONTENT_LENGTH=%s",
1887 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH));
1892 p += snprintf(p, end - p, "SCRIPT_PATH=%s", exec_array[0]) + 1;
1896 p += snprintf(p, end - p, "%s=%s", mp_cgienv->name,
1898 lwsl_debug(" Applying mount-specific cgi env '%s'\n",
1901 mp_cgienv = mp_cgienv->next;
1904 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1905 env_array[n++] = "PATH=/bin:/usr/bin:/usr/local/bin:/var/www/cgi-bin";
1906 env_array[n] = NULL;
1909 for (m = 0; m < n; m++)
1910 lwsl_err(" %s\n", env_array[m]);
1914 * Actually having made the env, as a cgi we don't need the ah
1917 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen)
1918 lws_header_table_detach(wsi, 0);
1920 /* we are ready with the redirection pipes... run the thing */
1921 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1927 lwsl_err("fork failed, errno %d", errno);
1931 #if defined(__linux__)
1932 prctl(PR_SET_PDEATHSIG, SIGTERM);
1934 setpgrp(); /* stops on-daemonized main processess getting SIGINT from TTY */
1937 /* we are the parent process */
1938 wsi->context->count_cgi_spawned++;
1939 lwsl_debug("%s: cgi %p spawned PID %d\n", __func__, cgi, cgi->pid);
1943 /* somewhere we can at least read things and enter it */
1945 lwsl_notice("%s: Failed to chdir\n", __func__);
1947 /* We are the forked process, redirect and kill inherited things.
1949 * Because of vfork(), we cannot do anything that changes pages in
1950 * the parent environment. Stuff that changes kernel state for the
1951 * process is OK. Stuff that happens after the execvpe() is OK.
1954 for (n = 0; n < 3; n++)
1955 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
1956 lwsl_err("%s: stdin dup2 failed\n", __func__);
1960 #if !defined(LWS_HAVE_VFORK) || !defined(LWS_HAVE_EXECVPE)
1961 for (m = 0; m < n; m++) {
1962 p = strchr(env_array[m], '=');
1964 setenv(env_array[m], p, 1);
1966 execvp(exec_array[0], (char * const *)&exec_array[0]);
1968 execvpe(exec_array[0], (char * const *)&exec_array[0], &env_array[0]);
1974 /* drop us from the pt cgi list */
1975 pt->cgi_list = cgi->cgi_list;
1978 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
1980 for (n = 0; n < 3; n++)
1981 if (wsi->cgi->stdwsi[n])
1982 lws_free_wsi(cgi->stdwsi[n]);
1985 for (n = 0; n < 3; n++) {
1986 if (cgi->pipe_fds[n][0])
1987 close(cgi->pipe_fds[n][0]);
1988 if (cgi->pipe_fds[n][1])
1989 close(cgi->pipe_fds[n][1]);
1992 lws_free_set_NULL(wsi->cgi);
1994 lwsl_err("%s: failed\n", __func__);
1999 * lws_cgi_write_split_headers: write cgi output accounting for header part
2001 * @wsi: connection to own the process
2003 LWS_VISIBLE LWS_EXTERN int
2004 lws_cgi_write_split_stdout_headers(struct lws *wsi)
2006 int n, m, match = 0, lp = 0;
2007 static const char * const content_length = "content-length: ";
2008 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
2009 *end = &buf[sizeof(buf) - 1 - LWS_PRE], c, l[12];
2014 while (wsi->hdr_state != LHCS_PAYLOAD) {
2015 /* we have to separate header / finalize and
2016 * payload chunks, since they need to be
2017 * handled separately
2019 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]), &c, 1);
2021 if (errno != EAGAIN) {
2022 lwsl_debug("%s: read says %d\n", __func__, n);
2029 lwsl_debug("-- 0x%02X %c\n", (unsigned char)c, c);
2030 switch (wsi->hdr_state) {
2032 if (!content_length[match] &&
2033 (c >= '0' && c <= '9') &&
2034 lp < sizeof(l) - 1) {
2037 wsi->cgi->content_length = atol(l);
2039 if (tolower(c) == content_length[match])
2044 /* some cgi only send us \x0a for EOL */
2046 wsi->hdr_state = LCHS_SINGLE_0A;
2051 wsi->hdr_state = LCHS_LF1;
2059 wsi->hdr_state = LCHS_CR2;
2062 /* we got \r[^\n]... it's unreasonable */
2063 lwsl_debug("%s: funny CRLF 0x%02X\n", __func__, (unsigned char)c);
2069 wsi->hdr_state = LCHS_LF2;
2072 wsi->hdr_state = LCHS_HEADER;
2077 case LCHS_SINGLE_0A:
2080 lwsl_debug("Content-Length: %ld\n", wsi->cgi->content_length);
2081 wsi->hdr_state = LHCS_PAYLOAD;
2082 /* drop the \0xa ... finalize will add it if needed */
2083 if (lws_finalize_http_header(wsi,
2084 (unsigned char **)&p,
2085 (unsigned char *)end))
2090 /* we got \r\n\r[^\n]... it's unreasonable */
2092 /* we got \x0anext header, it's reasonable */
2094 wsi->hdr_state = LCHS_HEADER;
2101 /* ran out of input, ended the headers, or filled up the headers buf */
2102 if (!n || wsi->hdr_state == LHCS_PAYLOAD || (p + 4) == end) {
2104 m = lws_write(wsi, (unsigned char *)start,
2105 p - start, LWS_WRITE_HTTP_HEADERS);
2107 lwsl_debug("%s: write says %d\n", __func__, m);
2110 /* writeability becomes uncertain now we wrote
2111 * something, we must return to the event loop
2118 n = read(lws_get_socket_fd(wsi->cgi->stdwsi[LWS_STDOUT]),
2119 start, sizeof(buf) - LWS_PRE);
2121 if (n < 0 && errno != EAGAIN) {
2122 lwsl_debug("%s: stdout read says %d\n", __func__, n);
2126 m = lws_write(wsi, (unsigned char *)start, n, LWS_WRITE_HTTP);
2127 //lwsl_notice("write %d\n", m);
2129 lwsl_debug("%s: stdout write says %d\n", __func__, m);
2132 wsi->cgi->content_length_seen += m;
2139 * lws_cgi_kill: terminate cgi process associated with wsi
2141 * @wsi: connection to own the process
2143 LWS_VISIBLE LWS_EXTERN int
2144 lws_cgi_kill(struct lws *wsi)
2146 struct lws_cgi_args args;
2149 lwsl_debug("%s: %p\n", __func__, wsi);
2154 if (wsi->cgi->pid > 0) {
2155 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2157 lwsl_debug("%s: PID %d reaped\n", __func__,
2161 /* kill the process group */
2162 n = kill(-wsi->cgi->pid, SIGTERM);
2163 lwsl_debug("%s: SIGTERM child PID %d says %d (errno %d)\n", __func__,
2164 wsi->cgi->pid, n, errno);
2167 * hum seen errno=3 when process is listed in ps,
2168 * it seems we don't always retain process grouping
2170 * Direct these fallback attempt to the exact child
2172 n = kill(wsi->cgi->pid, SIGTERM);
2174 n = kill(wsi->cgi->pid, SIGPIPE);
2176 n = kill(wsi->cgi->pid, SIGKILL);
2178 lwsl_err("%s: SIGKILL PID %d failed errno %d (maybe zombie)\n",
2179 __func__, wsi->cgi->pid, errno);
2183 /* He could be unkillable because he's a zombie */
2186 n = waitpid(-wsi->cgi->pid, &status, WNOHANG);
2188 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2190 n = waitpid(wsi->cgi->pid, &status, WNOHANG);
2192 lwsl_debug("%s: reaped PID %d\n", __func__, n);
2198 args.stdwsi = &wsi->cgi->stdwsi[0];
2200 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
2201 wsi->protocol->callback,
2202 wsi, LWS_CALLBACK_CGI_TERMINATED,
2204 (void *)&args, 0)) {
2206 if (!wsi->cgi->being_closed)
2207 lws_close_free_wsi(wsi, 0);
2214 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
2216 struct lws_cgi **pcgi, *cgi = NULL;
2220 /* find finished guys but don't reap yet */
2221 n = waitpid(-1, &status, WNOHANG | WNOWAIT);
2224 lwsl_debug("%s: observed PID %d terminated\n", __func__, n);
2226 pcgi = &pt->cgi_list;
2228 /* check all the subprocesses on the cgi list */
2230 /* get the next one first as list may change */
2232 pcgi = &(*pcgi)->cgi_list;
2237 /* wait for stdout to be drained */
2238 if (cgi->content_length > cgi->content_length_seen)
2241 if (cgi->content_length) {
2242 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2243 __func__, cgi->wsi, cgi->content_length_seen);
2247 waitpid(n, &status, WNOHANG);
2249 * he's already terminated so no need for kill()
2250 * but we should do the terminated cgi callback
2251 * and close him if he's not already closing
2253 if (n == cgi->pid) {
2254 lwsl_debug("%s: found PID %d on cgi list\n",
2258 lws_cgi_kill(cgi->wsi);
2264 /* if not found on the cgi list, as he's one of ours, reap */
2266 lwsl_debug("%s: reading PID %d although no cgi match\n",
2268 waitpid(n, &status, WNOHANG);
2272 /* disable this to confirm timeout cgi cleanup flow */
2274 pcgi = &pt->cgi_list;
2276 /* check all the subprocesses on the cgi list */
2278 /* get the next one first as list may change */
2280 pcgi = &(*pcgi)->cgi_list;
2285 /* wait for stdout to be drained */
2286 if (cgi->content_length > cgi->content_length_seen)
2289 if (cgi->content_length) {
2290 lwsl_debug("%s: wsi %p: expected content length seen: %ld\n",
2291 __func__, cgi->wsi, cgi->content_length_seen);
2295 if (waitpid(cgi->pid, &status, WNOHANG) > 0) {
2297 lwsl_debug("%s: found PID %d on cgi list\n",
2298 __func__, cgi->pid);
2301 lws_cgi_kill(cgi->wsi);
2308 /* general anti zombie defence */
2309 n = waitpid(-1, &status, WNOHANG);
2311 lwsl_notice("%s: anti-zombie wait says %d\n", __func__, n);
2317 #ifdef LWS_NO_EXTENSIONS
2319 lws_set_extension_option(struct lws *wsi, const char *ext_name,
2320 const char *opt_name, const char *opt_val)
2326 #ifdef LWS_WITH_ACCESS_LOG
2328 lws_access_log(struct lws *wsi)
2330 char *p = wsi->access_log.user_agent, ass[512];
2333 if (!wsi->access_log_pending)
2336 if (!wsi->access_log.header_log)
2342 l = snprintf(ass, sizeof(ass) - 1, "%s %d %lu %s\n",
2343 wsi->access_log.header_log,
2344 wsi->access_log.response, wsi->access_log.sent, p);
2346 if (wsi->vhost->log_fd != (int)LWS_INVALID_FILE) {
2347 if (write(wsi->vhost->log_fd, ass, l) != l)
2348 lwsl_err("Failed to write log\n");
2350 lwsl_err("%s", ass);
2352 if (wsi->access_log.header_log) {
2353 lws_free(wsi->access_log.header_log);
2354 wsi->access_log.header_log = NULL;
2356 if (wsi->access_log.user_agent) {
2357 lws_free(wsi->access_log.user_agent);
2358 wsi->access_log.user_agent = NULL;
2360 wsi->access_log_pending = 0;
2366 #ifdef LWS_WITH_SERVER_STATUS
2369 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)
2371 static const char * const prots[] = {
2380 char *orig = buf, *end = buf + len - 1, first = 1;
2386 buf += snprintf(buf, end - buf,
2387 "{\n \"name\":\"%s\",\n"
2388 " \"port\":\"%d\",\n"
2389 " \"use_ssl\":\"%d\",\n"
2390 " \"sts\":\"%d\",\n"
2391 " \"rx\":\"%llu\",\n"
2392 " \"tx\":\"%llu\",\n"
2393 " \"conn\":\"%lu\",\n"
2394 " \"trans\":\"%lu\",\n"
2395 " \"ws_upg\":\"%lu\",\n"
2396 " \"http2_upg\":\"%lu\""
2398 vh->name, vh->listen_port,
2399 #ifdef LWS_OPENSSL_SUPPORT
2404 !!(vh->options & LWS_SERVER_OPTION_STS),
2405 vh->rx, vh->tx, vh->conn, vh->trans, vh->ws_upgrades,
2409 if (vh->mount_list) {
2410 const struct lws_http_mount *m = vh->mount_list;
2412 buf += snprintf(buf, end - buf, ",\n \"mounts\":[");
2415 buf += snprintf(buf, end - buf, ",");
2416 buf += snprintf(buf, end - buf,
2417 "\n {\n \"mountpoint\":\"%s\",\n"
2418 " \"origin\":\"%s%s\",\n"
2419 " \"cache_max_age\":\"%d\",\n"
2420 " \"cache_reuse\":\"%d\",\n"
2421 " \"cache_revalidate\":\"%d\",\n"
2422 " \"cache_intermediaries\":\"%d\"\n"
2425 prots[m->origin_protocol],
2429 m->cache_revalidate,
2430 m->cache_intermediaries);
2432 buf += snprintf(buf, end - buf,
2433 ",\n \"default\":\"%s\"",
2435 buf += snprintf(buf, end - buf, "\n }");
2439 buf += snprintf(buf, end - buf, "\n ]");
2442 if (vh->protocols) {
2446 buf += snprintf(buf, end - buf, ",\n \"ws-protocols\":[");
2447 while (n < vh->count_protocols) {
2449 buf += snprintf(buf, end - buf, ",");
2450 buf += snprintf(buf, end - buf,
2452 " \"status\":\"ok\"\n }\n }"
2454 vh->protocols[n].name);
2458 buf += snprintf(buf, end - buf, "\n ]");
2461 buf += snprintf(buf, end - buf, "\n}");
2467 LWS_EXTERN LWS_VISIBLE int
2468 lws_json_dump_context(const struct lws_context *context, char *buf, int len)
2470 char *orig = buf, *end = buf + len - 1, first = 1;
2471 const struct lws_vhost *vh = context->vhost_list;
2474 struct lws_cgi * const *pcgi;
2476 const struct lws_context_per_thread *pt;
2477 time_t t = time(NULL);
2478 int listening = 0, cgi_count = 0, n;
2480 buf += snprintf(buf, end - buf, "{ "
2481 "\"version\":\"%s\",\n"
2482 "\"uptime\":\"%ld\",\n"
2483 "\"cgi_spawned\":\"%d\",\n"
2484 "\"pt_fd_max\":\"%d\",\n"
2485 "\"ah_pool_max\":\"%d\",\n"
2486 "\"wsi_alive\":\"%d\",\n",
2487 lws_get_library_version(),
2488 (unsigned long)(t - context->time_up),
2489 context->count_cgi_spawned,
2490 context->fd_limit_per_thread,
2491 context->max_http_header_pool,
2492 context->count_wsi_allocated);
2493 #ifdef LWS_HAVE_GETLOADAVG
2498 m = getloadavg(d, 3);
2499 for (n = 0; n < m; n++) {
2500 buf += snprintf(buf, end - buf,
2501 "\"l%d\":\"%.2f\",\n",
2507 buf += snprintf(buf, end - buf, "\"pt\":[\n ");
2508 for (n = 0; n < context->count_threads; n++) {
2509 pt = &context->pt[n];
2511 buf += snprintf(buf, end - buf, ",");
2512 buf += snprintf(buf, end - buf,
2514 " \"fds_count\":\"%d\",\n"
2515 " \"ah_pool_inuse\":\"%d\",\n"
2516 " \"ah_wait_list\":\"%d\"\n"
2519 pt->ah_count_in_use,
2520 pt->ah_wait_list_length);
2523 buf += snprintf(buf, end - buf, "], \"vhosts\":[\n ");
2529 buf += lws_json_dump_vhost(vh, buf, end - buf);
2533 vh = vh->vhost_next;
2536 buf += snprintf(buf, end - buf, "],\n\"listen_wsi\":\"%d\"",
2540 for (n = 0; n < context->count_threads; n++) {
2541 pt = &context->pt[n];
2542 pcgi = &pt->cgi_list;
2545 pcgi = &(*pcgi)->cgi_list;
2551 buf += snprintf(buf, end - buf, ",\n \"cgi_alive\":\"%d\"\n ",
2554 buf += snprintf(buf, end - buf, "}\n ");