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"
23 #include <sys/types.h>
24 #if defined(WIN32) || defined(_WIN32)
29 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
30 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
32 static const char * const log_level_names[] = {
46 lws_free_wsi(struct lws *wsi)
51 /* Protocol user data may be allocated either internally by lws
52 * or by specified the user.
53 * We should only free what we allocated. */
54 if (wsi->protocol && wsi->protocol->per_session_data_size &&
55 wsi->user_space && !wsi->user_space_externally_allocated)
56 lws_free(wsi->user_space);
58 lws_free_set_NULL(wsi->rxflow_buffer);
59 lws_free_set_NULL(wsi->trunc_alloc);
62 /* we're closing, losing some rx is OK */
63 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
64 lws_header_table_detach(wsi);
67 wsi->context->count_wsi_allocated--;
68 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
69 wsi->context->count_wsi_allocated);
75 lws_remove_from_timeout_list(struct lws *wsi)
77 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
79 if (!wsi->timeout_list_prev) /* ie, not part of the list */
83 /* if we have a next guy, set his prev to our prev */
84 if (wsi->timeout_list)
85 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
86 /* set our prev guy to our next guy instead of us */
87 *wsi->timeout_list_prev = wsi->timeout_list;
89 /* we're out of the list, we should not point anywhere any more */
90 wsi->timeout_list_prev = NULL;
91 wsi->timeout_list = NULL;
96 * lws_set_timeout() - marks the wsi as subject to a timeout
98 * You will not need this unless you are doing something special
100 * @wsi: Websocket connection instance
101 * @reason: timeout reason
102 * @secs: how many seconds
106 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
108 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
115 if (reason && !wsi->timeout_list_prev) {
116 /* our next guy is current first guy */
117 wsi->timeout_list = pt->timeout_list;
118 /* if there is a next guy, set his prev ptr to our next ptr */
119 if (wsi->timeout_list)
120 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
121 /* our prev ptr is first ptr */
122 wsi->timeout_list_prev = &pt->timeout_list;
123 /* set the first guy to be us */
124 *wsi->timeout_list_prev = wsi;
127 lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
128 wsi->pending_timeout_limit = now + secs;
129 wsi->pending_timeout = reason;
134 lws_remove_from_timeout_list(wsi);
138 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
140 struct lws_context *context;
141 struct lws_context_per_thread *pt;
143 struct lws_tokens eff_buf;
148 context = wsi->context;
149 pt = &context->pt[(int)wsi->tsi];
152 if (wsi->mode == LWSCM_CGI) {
153 /* we are not a network connection, but a handler for CGI io */
155 assert(wsi->master->cgi);
156 assert(wsi->master->cgi->stdwsi[(int)wsi->cgi_channel] == wsi);
157 /* end the binding between us and master */
158 wsi->master->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
160 wsi->socket_is_permanently_unusable = 1;
162 goto just_kill_connection;
166 /* we have a cgi going, we must kill it and close the
167 * related stdin/out/err wsis first
169 wsi->cgi->being_closed = 1;
174 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
175 wsi->u.http.fd != LWS_INVALID_FILE) {
176 lwsl_debug("closing http file\n");
177 lws_plat_file_close(wsi, wsi->u.http.fd);
178 wsi->u.http.fd = LWS_INVALID_FILE;
179 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
180 wsi->user_space, NULL, 0);
182 if (wsi->socket_is_permanently_unusable ||
183 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
184 wsi->state == LWSS_SHUTDOWN)
185 goto just_kill_connection;
187 wsi->state_pre_close = wsi->state;
189 switch (wsi->state_pre_close) {
190 case LWSS_DEAD_SOCKET:
193 /* we tried the polite way... */
194 case LWSS_AWAITING_CLOSE_ACK:
195 goto just_kill_connection;
197 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
198 if (wsi->trunc_len) {
199 lws_callback_on_writable(wsi);
202 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
203 goto just_kill_connection;
205 if (wsi->trunc_len) {
206 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
207 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
208 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
214 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
215 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
216 goto just_kill_connection;
218 if (wsi->mode == LWSCM_HTTP_SERVING)
219 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
220 wsi->user_space, NULL, 0);
223 * are his extensions okay with him closing? Eg he might be a mux
224 * parent and just his ch1 aspect is closing?
227 if (lws_ext_cb_active(wsi,
228 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
229 lwsl_ext("extension vetoed close\n");
234 * flush any tx pending from extensions, since we may send close packet
235 * if there are problems with send, just nuke the connection
240 eff_buf.token = NULL;
241 eff_buf.token_len = 0;
243 /* show every extension the new incoming data */
245 m = lws_ext_cb_active(wsi,
246 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
248 lwsl_ext("Extension reports fatal error\n");
249 goto just_kill_connection;
253 * at least one extension told us he has more
254 * to spill, so we will go around again after
258 /* assuming they left us something to send, send it */
260 if (eff_buf.token_len)
261 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
262 eff_buf.token_len) !=
264 lwsl_debug("close: ext spill failed\n");
265 goto just_kill_connection;
270 * signal we are closing, lws_write will
271 * add any necessary version-specific stuff. If the write fails,
272 * no worries we are closing anyway. If we didn't initiate this
273 * close, then our state has been changed to
274 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
276 * Likewise if it's a second call to close this connection after we
277 * sent the close indication to the peer already, we are in state
278 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
281 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
282 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
283 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
284 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
285 lwsl_debug("sending close indication...\n");
287 /* if no prepared close reason, use 1000 and no aux data */
288 if (!wsi->u.ws.close_in_ping_buffer_len) {
289 wsi->u.ws.close_in_ping_buffer_len = 2;
290 wsi->u.ws.ping_payload_buf[LWS_PRE] =
291 (reason >> 16) & 0xff;
292 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
296 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
297 wsi->u.ws.close_in_ping_buffer_len,
301 * we have sent a nice protocol level indication we
302 * now wish to close, we should not send anything more
304 wsi->state = LWSS_AWAITING_CLOSE_ACK;
307 * ...and we should wait for a reply for a bit
310 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
311 lwsl_debug("sent close indication, awaiting ack\n");
316 lwsl_info("close: sending close packet failed, hanging up\n");
318 /* else, the send failed and we should just hang up */
321 just_kill_connection:
325 * Testing with ab shows that we have to stage the socket close when
326 * the system is under stress... shutdown any further TX, change the
327 * state to one that won't emit anything more, and wait with a timeout
328 * for the POLLIN to show a zero-size rx before coming back and doing
331 if (wsi->state != LWSS_SHUTDOWN &&
332 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
333 !wsi->socket_is_permanently_unusable) {
334 lwsl_info("%s: shutting down connection: %p\n", __func__, wsi);
335 n = shutdown(wsi->sock, SHUT_WR);
337 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
339 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
340 wsi->state = LWSS_SHUTDOWN;
341 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
342 context->timeout_secs);
347 lwsl_info("%s: real just_kill_connection: %p\n", __func__, wsi);
350 * we won't be servicing or receiving anything further from this guy
351 * delete socket from the internal poll list if still present
353 lws_ssl_remove_wsi_from_buffered_list(wsi);
354 lws_remove_from_timeout_list(wsi);
356 /* checking return redundant since we anyway close */
357 remove_wsi_socket_from_fds(wsi);
359 wsi->state = LWSS_DEAD_SOCKET;
361 lws_free_set_NULL(wsi->rxflow_buffer);
363 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
364 wsi->mode == LWSCM_WS_SERVING ||
365 wsi->mode == LWSCM_WS_CLIENT) {
367 if (wsi->u.ws.rx_draining_ext) {
368 struct lws **w = &pt->rx_draining_ext_list;
370 wsi->u.ws.rx_draining_ext = 0;
371 /* remove us from context draining ext list */
374 *w = wsi->u.ws.rx_draining_ext_list;
377 w = &((*w)->u.ws.rx_draining_ext_list);
379 wsi->u.ws.rx_draining_ext_list = NULL;
382 if (wsi->u.ws.tx_draining_ext) {
383 struct lws **w = &pt->tx_draining_ext_list;
385 wsi->u.ws.tx_draining_ext = 0;
386 /* remove us from context draining ext list */
389 *w = wsi->u.ws.tx_draining_ext_list;
392 w = &((*w)->u.ws.tx_draining_ext_list);
394 wsi->u.ws.tx_draining_ext_list = NULL;
396 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
398 if (wsi->trunc_alloc)
399 /* not going to be completed... nuke it */
400 lws_free_set_NULL(wsi->trunc_alloc);
402 wsi->u.ws.ping_payload_len = 0;
403 wsi->u.ws.ping_pending_flag = 0;
406 /* tell the user it's all over for this guy */
408 if (wsi->protocol && wsi->protocol->callback &&
409 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
410 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
411 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
412 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
413 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
414 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
415 lwsl_debug("calling back CLOSED\n");
416 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
417 wsi->user_space, NULL, 0);
418 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
419 lwsl_debug("calling back CLOSED_HTTP\n");
420 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
421 wsi->user_space, NULL, 0 );
422 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
423 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
424 lwsl_debug("Connection closed before server reply\n");
425 context->protocols[0].callback(wsi,
426 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
427 wsi->user_space, NULL, 0);
429 lwsl_debug("not calling back closed mode=%d state=%d\n",
430 wsi->mode, wsi->state_pre_close);
432 /* deallocate any active extension contexts */
434 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
435 lwsl_warn("extension destruction failed\n");
437 * inform all extensions in case they tracked this guy out of band
438 * even though not active on him specifically
440 if (lws_ext_cb_all_exts(context, wsi,
441 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
442 lwsl_warn("ext destroy wsi failed\n");
444 wsi->socket_is_permanently_unusable = 1;
447 if (LWS_LIBUV_ENABLED(context)) {
448 /* libuv has to do his own close handle processing asynchronously */
449 lws_libuv_closehandle(wsi);
455 lws_close_free_wsi_final(wsi);
459 lws_close_free_wsi_final(struct lws *wsi)
463 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
465 n = compatible_close(wsi->sock);
467 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
470 compatible_close(wsi->sock);
472 wsi->sock = LWS_SOCK_INVALID;
475 /* outermost destroy notification for wsi (user_space still intact) */
476 wsi->context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
477 wsi->user_space, NULL, 0);
484 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
488 ipv6 = LWS_IPV6_ENABLED(context);
492 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
497 lws_get_addresses(struct lws_context *context, void *ads, char *name,
498 int name_len, char *rip, int rip_len)
501 struct addrinfo ai, *res;
502 struct sockaddr_in addr4;
507 addr4.sin_family = AF_UNSPEC;
510 if (LWS_IPV6_ENABLED(context)) {
511 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
512 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
516 // Strip off the IPv4 to IPv6 header if one exists
517 if (strncmp(rip, "::ffff:", 7) == 0)
518 memmove(rip, rip + 7, strlen(rip) - 6);
520 getnameinfo((struct sockaddr *)ads,
521 sizeof(struct sockaddr_in6), name,
522 name_len, NULL, 0, 0);
528 struct addrinfo *result;
530 memset(&ai, 0, sizeof ai);
531 ai.ai_family = PF_UNSPEC;
532 ai.ai_socktype = SOCK_STREAM;
533 ai.ai_flags = AI_CANONNAME;
535 if (getnameinfo((struct sockaddr *)ads,
536 sizeof(struct sockaddr_in),
537 name, name_len, NULL, 0, 0))
543 if (getaddrinfo(name, NULL, &ai, &result))
547 while (addr4.sin_family == AF_UNSPEC && res) {
548 switch (res->ai_family) {
550 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
551 addr4.sin_family = AF_INET;
557 freeaddrinfo(result);
560 if (addr4.sin_family == AF_UNSPEC)
563 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
580 * lws_get_peer_addresses() - Get client address information
581 * @wsi: Local struct lws associated with
582 * @fd: Connection socket descriptor
583 * @name: Buffer to take client address name
584 * @name_len: Length of client address name buffer
585 * @rip: Buffer to take client address IP dotted quad
586 * @rip_len: Length of client address IP buffer
588 * This function fills in @name and @rip with the name and IP of
589 * the client connected with socket descriptor @fd. Names may be
590 * truncated if there is not enough room. If either cannot be
591 * determined, they will be returned as valid zero-length strings.
595 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
596 int name_len, char *rip, int rip_len)
601 struct sockaddr_in6 sin6;
603 struct sockaddr_in sin4;
604 struct lws_context *context = wsi->context;
611 lws_latency_pre(context, wsi);
614 if (LWS_IPV6_ENABLED(context)) {
624 if (getpeername(fd, p, &len) < 0) {
625 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
629 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
632 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
644 * lws_context_user() - get the user data associated with the context
645 * @context: Websocket context
647 * This returns the optional user allocation that can be attached to
648 * the context the sockets live in at context_create time. It's a way
649 * to let all sockets serviced in the same context share data without
650 * using globals statics in the user code.
653 lws_context_user(struct lws_context *context)
655 return context->user_space;
660 * lws_callback_all_protocol() - Callback all connections using
661 * the given protocol with the given reason
663 * @protocol: Protocol whose connections will get callbacks
664 * @reason: Callback reason index
668 lws_callback_all_protocol(struct lws_context *context,
669 const struct lws_protocols *protocol, int reason)
671 struct lws_context_per_thread *pt = &context->pt[0];
672 unsigned int n, m = context->count_threads;
676 for (n = 0; n < pt->fds_count; n++) {
677 wsi = wsi_from_fd(context, pt->fds[n].fd);
680 if (wsi->protocol == protocol)
681 protocol->callback(wsi, reason, wsi->user_space,
693 * lws_get_socket_fd() - returns the socket file descriptor
695 * You will not need this unless you are doing something special
697 * @wsi: Websocket connection instance
701 lws_get_socket_fd(struct lws *wsi)
710 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
711 int ret, int completed)
713 unsigned long long u;
716 u = time_in_microseconds();
719 wsi->latency_start = u;
720 if (!wsi->action_start)
721 wsi->action_start = u;
725 if (wsi->action_start == wsi->latency_start)
727 "Completion first try lat %lluus: %p: ret %d: %s\n",
728 u - wsi->latency_start,
729 (void *)wsi, ret, action);
732 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
733 u - wsi->action_start,
734 u - wsi->latency_start,
735 (void *)wsi, ret, action);
736 wsi->action_start = 0;
738 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
739 u - wsi->latency_start, (void *)wsi, ret, action);
741 if (u - wsi->latency_start > context->worst_latency) {
742 context->worst_latency = u - wsi->latency_start;
743 strcpy(context->worst_latency_info, buf);
745 lwsl_latency("%s", buf);
752 * lws_rx_flow_control() - Enable and disable socket servicing for
755 * If the output side of a server process becomes choked, this allows flow
756 * control for the input side.
758 * @wsi: Websocket connection instance to get callback for
759 * @enable: 0 = disable read servicing for this connection, 1 = enable
763 lws_rx_flow_control(struct lws *wsi, int enable)
765 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
768 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
769 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
775 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
777 * When the user server code realizes it can accept more input, it can
778 * call this to have the RX flow restriction removed from all connections using
779 * the given protocol.
781 * @protocol: all connections using this protocol will be allowed to receive
785 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
786 const struct lws_protocols *protocol)
788 const struct lws_context_per_thread *pt = &context->pt[0];
790 unsigned int n, m = context->count_threads;
793 for (n = 0; n < pt->fds_count; n++) {
794 wsi = wsi_from_fd(context, pt->fds[n].fd);
797 if (wsi->protocol == protocol)
798 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
806 * lws_canonical_hostname() - returns this host's hostname
808 * This is typically used by client code to fill in the host parameter
809 * when making a client connection. You can only call it after the context
812 * @context: Websocket context
814 LWS_VISIBLE extern const char *
815 lws_canonical_hostname(struct lws_context *context)
817 return (const char *)context->canonical_hostname;
820 int user_callback_handle_rxflow(lws_callback_function callback_function,
822 enum lws_callback_reasons reason, void *user,
823 void *in, size_t len)
827 n = callback_function(wsi, reason, user, in, len);
829 n = _lws_rx_flow_control(wsi);
836 * lws_set_proxy() - Setups proxy to lws_context.
837 * @context: pointer to struct lws_context you want set proxy to
838 * @proxy: pointer to c string containing proxy in format address:port
840 * Returns 0 if proxy string was parsed and proxy was setup.
841 * Returns -1 if @proxy is NULL or has incorrect format.
843 * This is only required if your OS does not provide the http_proxy
844 * environment variable (eg, OSX)
846 * IMPORTANT! You should call this function right after creation of the
847 * lws_context and before call to connect. If you call this
848 * function after connect behavior is undefined.
849 * This function will override proxy settings made on lws_context
850 * creation with genenv() call.
854 lws_set_proxy(struct lws_context *context, const char *proxy)
862 p = strchr(proxy, '@');
863 if (p) { /* auth is around */
865 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
868 strncpy(authstring, proxy, p - proxy);
869 // null termination not needed on input
870 if (lws_b64_encode_string(authstring, (p - proxy),
871 context->proxy_basic_auth_token,
872 sizeof context->proxy_basic_auth_token) < 0)
875 lwsl_notice(" Proxy auth in use\n");
879 context->proxy_basic_auth_token[0] = '\0';
881 strncpy(context->http_proxy_address, proxy,
882 sizeof(context->http_proxy_address) - 1);
883 context->http_proxy_address[
884 sizeof(context->http_proxy_address) - 1] = '\0';
886 p = strchr(context->http_proxy_address, ':');
887 if (!p && !context->http_proxy_port) {
888 lwsl_err("http_proxy needs to be ads:port\n");
894 context->http_proxy_port = atoi(p + 1);
898 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
899 context->http_proxy_port);
904 lwsl_err("proxy auth too long\n");
910 * lws_get_protocol() - Returns a protocol pointer from a websocket
912 * @wsi: pointer to struct websocket you want to know the protocol of
915 * Some apis can act on all live connections of a given protocol,
916 * this is how you can get a pointer to the active protocol if needed.
919 LWS_VISIBLE const struct lws_protocols *
920 lws_get_protocol(struct lws *wsi)
922 return wsi->protocol;
926 lws_is_final_fragment(struct lws *wsi)
928 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
929 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
930 wsi->u.ws.rx_draining_ext);
931 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
934 LWS_VISIBLE unsigned char
935 lws_get_reserved_bits(struct lws *wsi)
937 return wsi->u.ws.rsv;
941 lws_ensure_user_space(struct lws *wsi)
943 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
947 /* allocate the per-connection user memory (if any) */
949 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
950 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
951 if (wsi->user_space == NULL) {
952 lwsl_err("Out of memory for conn user space\n");
956 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
957 __func__, wsi, wsi->protocol->per_session_data_size,
963 * lwsl_timestamp: generate logging timestamp string
965 * @level: logging level
966 * @p: char * buffer to take timestamp
969 * returns length written in p
972 lwsl_timestamp(int level, char *p, int len)
974 time_t o_now = time(NULL);
975 unsigned long long now;
976 struct tm *ptm = NULL;
983 ptm = localtime(&o_now);
985 if (localtime_r(&o_now, &tm))
989 for (n = 0; n < LLL_COUNT; n++) {
990 if (level != (1 << n))
992 now = time_in_microseconds() / 100;
995 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1002 (int)(now % 10000), log_level_names[n]);
1004 n = snprintf(p, len, "[%llu:%04d] %s: ",
1005 (unsigned long long) now / 10000,
1006 (int)(now % 10000), log_level_names[n]);
1013 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1017 lwsl_timestamp(level, buf, sizeof(buf));
1019 fprintf(stderr, "%s%s", buf, line);
1022 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1026 if (!(log_level & filter))
1029 vsnprintf(buf, sizeof(buf), format, vl);
1030 buf[sizeof(buf) - 1] = '\0';
1032 lwsl_emit(filter, buf);
1035 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1039 va_start(ap, format);
1040 _lws_logv(filter, format, ap);
1045 * lws_set_log_level() - Set the logging bitfield
1046 * @level: OR together the LLL_ debug contexts you want output from
1047 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1048 * function to perform log string emission instead of
1049 * the default stderr one.
1051 * log level defaults to "err", "warn" and "notice" contexts enabled and
1052 * emission on stderr.
1055 LWS_VISIBLE void lws_set_log_level(int level,
1056 void (*func)(int level, const char *line))
1064 * lws_use_ssl() - Find out if connection is using SSL
1065 * @wsi: websocket connection to check
1067 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1068 * using verified cert, and 2 if using SSL but the cert was not
1069 * checked (appears for client wsi told to skip check on connection)
1072 lws_is_ssl(struct lws *wsi)
1074 #ifdef LWS_OPENSSL_SUPPORT
1075 return wsi->use_ssl;
1083 * lws_partial_buffered() - find out if lws buffered the last write
1084 * @wsi: websocket connection to check
1086 * Returns 1 if you cannot use lws_write because the last
1087 * write on this connection is still buffered, and can't be cleared without
1088 * returning to the service loop and waiting for the connection to be
1091 * If you will try to do >1 lws_write call inside a single
1092 * WRITEABLE callback, you must check this after every write and bail if
1093 * set, ask for a new writeable callback and continue writing from there.
1095 * This is never set at the start of a writeable callback, but any write
1100 lws_partial_buffered(struct lws *wsi)
1102 return !!wsi->trunc_len;
1105 void lws_set_protocol_write_pending(struct lws *wsi,
1106 enum lws_pending_protocol_send pend)
1108 lwsl_info("setting pps %d\n", pend);
1111 lwsl_err("pps overwrite\n");
1113 lws_rx_flow_control(wsi, 0);
1114 lws_callback_on_writable(wsi);
1118 lws_get_peer_write_allowance(struct lws *wsi)
1120 #ifdef LWS_USE_HTTP2
1121 /* only if we are using HTTP2 on this connection */
1122 if (wsi->mode != LWSCM_HTTP2_SERVING)
1124 /* user is only interested in how much he can send, or that he can't */
1125 if (wsi->u.http2.tx_credit <= 0)
1128 return wsi->u.http2.tx_credit;
1136 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1138 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1139 memset(&wsi->u, 0, sizeof(wsi->u));
1143 LWS_VISIBLE struct lws_plat_file_ops *
1144 lws_get_fops(struct lws_context *context)
1146 return &context->fops;
1149 LWS_VISIBLE LWS_EXTERN struct lws_context *
1150 lws_get_context(const struct lws *wsi)
1152 return wsi->context;
1155 LWS_VISIBLE LWS_EXTERN int
1156 lws_get_count_threads(struct lws_context *context)
1158 return context->count_threads;
1161 LWS_VISIBLE LWS_EXTERN void *
1162 lws_wsi_user(struct lws *wsi)
1164 return wsi->user_space;
1167 LWS_VISIBLE LWS_EXTERN void
1168 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1169 unsigned char *buf, size_t len)
1171 unsigned char *p, *start;
1172 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1174 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1176 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1178 *p++ = (((int)status) >> 8) & 0xff;
1179 *p++ = ((int)status) & 0xff;
1182 while (len-- && p < start + budget)
1185 wsi->u.ws.close_in_ping_buffer_len = p - start;
1189 _lws_rx_flow_control(struct lws *wsi)
1191 /* there is no pending change */
1192 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1193 lwsl_debug("%s: no pending change\n", __func__);
1197 /* stuff is still buffered, not ready to really accept new input */
1198 if (wsi->rxflow_buffer) {
1199 /* get ourselves called back to deal with stashed buffer */
1200 lws_callback_on_writable(wsi);
1204 /* pending is cleared, we can change rxflow state */
1206 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1208 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1209 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1211 /* adjust the pollfd for this wsi */
1213 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1214 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1215 lwsl_info("%s: fail\n", __func__);
1219 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1226 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1228 static const unsigned char e0f4[] = {
1229 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1230 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1231 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1232 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1233 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1234 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1235 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1236 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1237 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1238 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1239 0x80 | ((4 - 1) << 2) | 1, /* ea */
1240 0x80 | ((4 - 1) << 2) | 1, /* eb */
1241 0x80 | ((4 - 1) << 2) | 1, /* ec */
1242 0x80 | ((2 - 1) << 2) | 1, /* ed */
1243 0x80 | ((4 - 1) << 2) | 1, /* ee */
1244 0x80 | ((4 - 1) << 2) | 1, /* ef */
1245 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1246 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1247 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1248 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1249 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1252 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1253 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1255 unsigned char s = *state;
1258 unsigned char c = *buf++;
1262 if (c < 0xc2 || c > 0xf4)
1265 s = 0x80 | ((4 - 1) << 2);
1270 if (c < (s & 0xf0) ||
1271 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1273 s = e0f4[21 + (s & 3)];
1283 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1284 * Notice it does so by dropping '\0' into input string
1285 * and the leading / on the path is consequently lost
1287 * @p: incoming uri string.. will get written to
1288 * @prot: result pointer for protocol part (https://)
1289 * @ads: result pointer for address part
1290 * @port: result pointer for port part
1291 * @path: result pointer for path part
1294 LWS_VISIBLE LWS_EXTERN int
1295 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1299 static const char *slash = "/";
1301 /* cut up the location into address, port and path */
1303 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1314 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1316 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1319 while (*p && *p != ':' && *p != '/')
1324 while (*p && *p != '/')
1337 #ifdef LWS_NO_EXTENSIONS
1339 /* we need to provide dummy callbacks for internal exts
1340 * so user code runs when faced with a lib compiled with
1341 * extensions disabled.
1345 lws_extension_callback_pm_deflate(struct lws_context *context,
1346 const struct lws_extension *ext,
1348 enum lws_extension_callback_reasons reason,
1349 void *user, void *in, size_t len)
1363 LWS_VISIBLE LWS_EXTERN int
1364 lws_is_cgi(struct lws *wsi) {
1375 lws_create_basic_wsi(struct lws_context *context, int tsi)
1377 struct lws *new_wsi;
1379 if ((unsigned int)context->pt[tsi].fds_count ==
1380 context->fd_limit_per_thread - 1) {
1381 lwsl_err("no space for new conn\n");
1385 new_wsi = lws_zalloc(sizeof(struct lws));
1386 if (new_wsi == NULL) {
1387 lwsl_err("Out of memory for new connection\n");
1392 new_wsi->context = context;
1393 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1394 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1396 /* intialize the instance struct */
1398 new_wsi->state = LWSS_CGI;
1399 new_wsi->mode = LWSCM_CGI;
1400 new_wsi->hdr_parsing_completed = 0;
1401 new_wsi->position_in_fds_table = -1;
1404 * these can only be set once the protocol is known
1405 * we set an unestablished connection's protocol pointer
1406 * to the start of the supported list, so it can look
1407 * for matching ones during the handshake
1409 new_wsi->protocol = context->protocols;
1410 new_wsi->user_space = NULL;
1411 new_wsi->ietf_spec_revision = 0;
1412 new_wsi->sock = LWS_SOCK_INVALID;
1413 context->count_wsi_allocated++;
1419 * lws_cgi: spawn network-connected cgi process
1421 * @wsi: connection to own the process
1422 * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1425 LWS_VISIBLE LWS_EXTERN int
1426 lws_cgi(struct lws *wsi, char * const *exec_array, int timeout_secs)
1428 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1429 char *env_array[30], cgi_path[400];
1430 struct lws_cgi *cgi;
1434 * give the master wsi a cgi struct
1437 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1439 lwsl_err("%s: OOM\n", __func__);
1444 cgi->wsi = wsi; /* set cgi's owning wsi */
1446 /* create pipes for [stdin|stdout] and [stderr] */
1448 for (n = 0; n < 3; n++)
1449 if (pipe(cgi->pipe_fds[n]) == -1)
1452 /* create cgi wsis for each stdin/out/err fd */
1454 for (n = 0; n < 3; n++) {
1455 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1456 if (!cgi->stdwsi[n])
1458 cgi->stdwsi[n]->cgi_channel = n;
1459 /* read side is 0, stdin we want the write side, others read */
1460 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1461 fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK);
1464 for (n = 0; n < 3; n++) {
1465 cgi->stdwsi[n]->master = wsi;
1466 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1470 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1471 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1472 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1474 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1475 cgi->stdwsi[LWS_STDIN]->sock,
1476 cgi->stdwsi[LWS_STDOUT]->sock,
1477 cgi->stdwsi[LWS_STDERR]->sock);
1479 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1481 /* add us to the pt list of active cgis */
1482 cgi->cgi_list = pt->cgi_list;
1485 /* prepare his CGI env */
1488 if (wsi->u.hdr.ah) {
1489 snprintf(cgi_path, sizeof(cgi_path) - 1, "PATH_INFO=%s",
1490 lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI));
1491 cgi_path[sizeof(cgi_path) - 1] = '\0';
1492 env_array[n++] = cgi_path;
1493 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1494 env_array[n++] = "REQUEST_METHOD=POST";
1496 env_array[n++] = "REQUEST_METHOD=GET";
1498 if (lws_is_ssl(wsi))
1499 env_array[n++] = "HTTPS=ON";
1500 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1501 env_array[n++] = "PATH=/bin:/usr/bin:/usrlocal/bin";
1502 env_array[n] = NULL;
1504 /* we are ready with the redirection pipes... run the thing */
1505 #ifdef LWS_HAVE_VFORK
1511 lwsl_err("fork failed, errno %d", errno);
1516 /* we are the parent process */
1519 /* We are the forked process, redirect and kill inherited things.
1521 * Because of vfork(), we cannot do anything that changes pages in
1522 * the parent environment. Stuff that changes kernel state for the
1523 * process is OK. Stuff that happens after the execvpe() is OK.
1526 for (n = 0; n < 3; n++) {
1527 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
1528 lwsl_err("%s: stdin dup2 failed\n", __func__);
1531 close(cgi->pipe_fds[n][!(n == 0)]);
1534 execvpe(exec_array[0], &exec_array[0], &env_array[0]);
1538 /* drop us from the pt cgi list */
1539 pt->cgi_list = cgi->cgi_list;
1542 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
1544 for (n = 0; n < 3; n++)
1545 if (wsi->cgi->stdwsi[n])
1546 lws_free_wsi(cgi->stdwsi[n]);
1549 for (n = 0; n < 3; n++) {
1550 if (cgi->pipe_fds[n][0])
1551 close(cgi->pipe_fds[n][0]);
1552 if (cgi->pipe_fds[n][1])
1553 close(cgi->pipe_fds[n][1]);
1556 lws_free_set_NULL(wsi->cgi);
1558 lwsl_err("%s: failed\n", __func__);
1564 * lws_cgi_kill: terminate cgi process associated with wsi
1566 * @wsi: connection to own the process
1568 LWS_VISIBLE LWS_EXTERN int
1569 lws_cgi_kill(struct lws *wsi)
1571 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1572 struct lws_cgi **pcgi = &pt->cgi_list;
1573 struct lws_cgi_args args;
1574 int n, status, do_close = 0;
1579 lwsl_notice("%s: wsi %p\n", __func__, wsi);
1583 if (wsi->cgi->pid > 0) {
1584 /* kill the process */
1585 n = kill(wsi->cgi->pid, SIGTERM);
1587 lwsl_err("%s: failed\n", __func__);
1590 waitpid(wsi->cgi->pid, &status, 0); /* !!! may hang !!! */
1593 args.stdwsi = &wsi->cgi->stdwsi[0];
1595 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
1596 wsi->protocol->callback,
1597 wsi, LWS_CALLBACK_CGI_TERMINATED,
1599 (void *)&args, 0)) {
1601 do_close = !wsi->cgi->being_closed;
1604 /* remove us from the cgi list */
1606 if (*pcgi == wsi->cgi) {
1607 /* drop us from the pt cgi list */
1608 *pcgi = (*pcgi)->cgi_list;
1611 pcgi = &(*pcgi)->cgi_list;
1614 for (n = 0 ; n < 3; n++) {
1615 if (wsi->cgi->pipe_fds[n][!!(n == 0)] >= 0) {
1616 close(wsi->cgi->pipe_fds[n][!!(n == 0)]);
1617 wsi->cgi->pipe_fds[n][!!(n == 0)] = -1;
1619 lws_close_free_wsi(wsi->cgi->stdwsi[n], 0);
1623 lws_free_set_NULL(wsi->cgi);
1626 lws_close_free_wsi(wsi, 0);
1632 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
1634 struct lws_cgi **pcgi = &pt->cgi_list, *cgi;
1637 /* check all the subprocesses on the cgi list for termination */
1639 /* get the next one because we may close current one next */
1641 pcgi = &(*pcgi)->cgi_list;
1644 waitpid(cgi->pid, &status, WNOHANG) > 0) {
1646 lws_cgi_kill(cgi->wsi);
1647 pcgi = &pt->cgi_list;