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 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
25 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
27 static const char * const log_level_names[] = {
41 lws_free_wsi(struct lws *wsi)
46 /* Protocol user data may be allocated either internally by lws
47 * or by specified the user.
48 * We should only free what we allocated. */
49 if (wsi->protocol && wsi->protocol->per_session_data_size &&
50 wsi->user_space && !wsi->user_space_externally_allocated)
51 lws_free(wsi->user_space);
53 lws_free_set_NULL(wsi->rxflow_buffer);
54 lws_free_set_NULL(wsi->trunc_alloc);
57 /* we're closing, losing some rx is OK */
58 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
59 lws_header_table_detach(wsi);
62 wsi->context->count_wsi_allocated--;
63 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
64 wsi->context->count_wsi_allocated);
70 lws_remove_from_timeout_list(struct lws *wsi)
72 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
74 if (!wsi->timeout_list_prev) /* ie, not part of the list */
78 /* if we have a next guy, set his prev to our prev */
79 if (wsi->timeout_list)
80 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
81 /* set our prev guy to our next guy instead of us */
82 *wsi->timeout_list_prev = wsi->timeout_list;
84 /* we're out of the list, we should not point anywhere any more */
85 wsi->timeout_list_prev = NULL;
86 wsi->timeout_list = NULL;
91 * lws_set_timeout() - marks the wsi as subject to a timeout
93 * You will not need this unless you are doing something special
95 * @wsi: Websocket connection instance
96 * @reason: timeout reason
97 * @secs: how many seconds
101 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
103 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
110 if (reason && !wsi->timeout_list_prev) {
111 /* our next guy is current first guy */
112 wsi->timeout_list = pt->timeout_list;
113 /* if there is a next guy, set his prev ptr to our next ptr */
114 if (wsi->timeout_list)
115 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
116 /* our prev ptr is first ptr */
117 wsi->timeout_list_prev = &pt->timeout_list;
118 /* set the first guy to be us */
119 *wsi->timeout_list_prev = wsi;
122 wsi->pending_timeout_limit = now + secs;
123 wsi->pending_timeout = reason;
128 lws_remove_from_timeout_list(wsi);
132 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
134 struct lws_context *context;
135 struct lws_context_per_thread *pt;
137 struct lws_tokens eff_buf;
142 context = wsi->context;
143 pt = &context->pt[(int)wsi->tsi];
145 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
146 wsi->u.http.fd != LWS_INVALID_FILE) {
147 lwsl_debug("closing http file\n");
148 lws_plat_file_close(wsi, wsi->u.http.fd);
149 wsi->u.http.fd = LWS_INVALID_FILE;
150 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
151 wsi->user_space, NULL, 0);
153 if (wsi->socket_is_permanently_unusable ||
154 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
155 wsi->state == LWSS_SHUTDOWN)
156 goto just_kill_connection;
158 wsi->state_pre_close = wsi->state;
160 switch (wsi->state_pre_close) {
161 case LWSS_DEAD_SOCKET:
164 /* we tried the polite way... */
165 case LWSS_AWAITING_CLOSE_ACK:
166 goto just_kill_connection;
168 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
169 if (wsi->trunc_len) {
170 lws_callback_on_writable(wsi);
173 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
174 goto just_kill_connection;
176 if (wsi->trunc_len) {
177 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
178 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
179 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
185 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
186 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
187 goto just_kill_connection;
189 if (wsi->mode == LWSCM_HTTP_SERVING)
190 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
191 wsi->user_space, NULL, 0);
194 * are his extensions okay with him closing? Eg he might be a mux
195 * parent and just his ch1 aspect is closing?
198 if (lws_ext_cb_active(wsi,
199 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
200 lwsl_ext("extension vetoed close\n");
205 * flush any tx pending from extensions, since we may send close packet
206 * if there are problems with send, just nuke the connection
211 eff_buf.token = NULL;
212 eff_buf.token_len = 0;
214 /* show every extension the new incoming data */
216 m = lws_ext_cb_active(wsi,
217 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
219 lwsl_ext("Extension reports fatal error\n");
220 goto just_kill_connection;
224 * at least one extension told us he has more
225 * to spill, so we will go around again after
229 /* assuming they left us something to send, send it */
231 if (eff_buf.token_len)
232 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
233 eff_buf.token_len) !=
235 lwsl_debug("close: ext spill failed\n");
236 goto just_kill_connection;
241 * signal we are closing, lws_write will
242 * add any necessary version-specific stuff. If the write fails,
243 * no worries we are closing anyway. If we didn't initiate this
244 * close, then our state has been changed to
245 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
247 * Likewise if it's a second call to close this connection after we
248 * sent the close indication to the peer already, we are in state
249 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
252 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
253 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
254 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
255 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
256 lwsl_debug("sending close indication...\n");
258 /* if no prepared close reason, use 1000 and no aux data */
259 if (!wsi->u.ws.close_in_ping_buffer_len) {
260 wsi->u.ws.close_in_ping_buffer_len = 2;
261 wsi->u.ws.ping_payload_buf[LWS_PRE] =
262 (reason >> 16) & 0xff;
263 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
267 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
268 wsi->u.ws.close_in_ping_buffer_len,
272 * we have sent a nice protocol level indication we
273 * now wish to close, we should not send anything more
275 wsi->state = LWSS_AWAITING_CLOSE_ACK;
278 * ...and we should wait for a reply for a bit
281 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
282 lwsl_debug("sent close indication, awaiting ack\n");
287 lwsl_info("close: sending close packet failed, hanging up\n");
289 /* else, the send failed and we should just hang up */
292 just_kill_connection:
296 * Testing with ab shows that we have to stage the socket close when
297 * the system is under stress... shutdown any further TX, change the
298 * state to one that won't emit anything more, and wait with a timeout
299 * for the POLLIN to show a zero-size rx before coming back and doing
302 if (wsi->state != LWSS_SHUTDOWN &&
303 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
304 !wsi->socket_is_permanently_unusable) {
305 lwsl_info("%s: shutting down connection: %p\n", __func__, wsi);
306 n = shutdown(wsi->sock, SHUT_WR);
308 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
310 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
311 wsi->state = LWSS_SHUTDOWN;
312 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
313 context->timeout_secs);
318 lwsl_info("%s: real just_kill_connection: %p\n", __func__, wsi);
321 * we won't be servicing or receiving anything further from this guy
322 * delete socket from the internal poll list if still present
324 lws_ssl_remove_wsi_from_buffered_list(wsi);
325 lws_remove_from_timeout_list(wsi);
327 /* checking return redundant since we anyway close */
328 remove_wsi_socket_from_fds(wsi);
330 wsi->state = LWSS_DEAD_SOCKET;
332 lws_free_set_NULL(wsi->rxflow_buffer);
334 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
335 wsi->mode == LWSCM_WS_SERVING ||
336 wsi->mode == LWSCM_WS_CLIENT) {
338 if (wsi->u.ws.rx_draining_ext) {
339 struct lws **w = &pt->rx_draining_ext_list;
341 wsi->u.ws.rx_draining_ext = 0;
342 /* remove us from context draining ext list */
345 *w = wsi->u.ws.rx_draining_ext_list;
348 w = &((*w)->u.ws.rx_draining_ext_list);
350 wsi->u.ws.rx_draining_ext_list = NULL;
353 if (wsi->u.ws.tx_draining_ext) {
354 struct lws **w = &pt->tx_draining_ext_list;
356 wsi->u.ws.tx_draining_ext = 0;
357 /* remove us from context draining ext list */
360 *w = wsi->u.ws.tx_draining_ext_list;
363 w = &((*w)->u.ws.tx_draining_ext_list);
365 wsi->u.ws.tx_draining_ext_list = NULL;
367 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
369 if (wsi->trunc_alloc)
370 /* not going to be completed... nuke it */
371 lws_free_set_NULL(wsi->trunc_alloc);
373 wsi->u.ws.ping_payload_len = 0;
374 wsi->u.ws.ping_pending_flag = 0;
377 /* tell the user it's all over for this guy */
379 if (wsi->protocol && wsi->protocol->callback &&
380 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
381 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
382 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
383 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
384 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
385 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
386 lwsl_debug("calling back CLOSED\n");
387 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
388 wsi->user_space, NULL, 0);
389 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
390 lwsl_debug("calling back CLOSED_HTTP\n");
391 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
392 wsi->user_space, NULL, 0 );
393 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
394 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
395 lwsl_debug("Connection closed before server reply\n");
396 context->protocols[0].callback(wsi,
397 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
398 wsi->user_space, NULL, 0);
400 lwsl_debug("not calling back closed mode=%d state=%d\n",
401 wsi->mode, wsi->state_pre_close);
403 /* deallocate any active extension contexts */
405 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
406 lwsl_warn("extension destruction failed\n");
408 * inform all extensions in case they tracked this guy out of band
409 * even though not active on him specifically
411 if (lws_ext_cb_all_exts(context, wsi,
412 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
413 lwsl_warn("ext destroy wsi failed\n");
415 wsi->socket_is_permanently_unusable = 1;
418 if (LWS_LIBUV_ENABLED(context)) {
419 /* libuv has to do his own close handle processing asynchronously */
420 lws_libuv_closehandle(wsi);
426 lws_close_free_wsi_final(wsi);
430 lws_close_free_wsi_final(struct lws *wsi)
434 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
436 n = compatible_close(wsi->sock);
438 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
441 compatible_close(wsi->sock);
443 wsi->sock = LWS_SOCK_INVALID;
446 /* outermost destroy notification for wsi (user_space still intact) */
447 wsi->context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
448 wsi->user_space, NULL, 0);
455 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
459 ipv6 = LWS_IPV6_ENABLED(context);
463 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
468 lws_get_addresses(struct lws_context *context, void *ads, char *name,
469 int name_len, char *rip, int rip_len)
472 struct addrinfo ai, *res;
473 struct sockaddr_in addr4;
478 addr4.sin_family = AF_UNSPEC;
481 if (LWS_IPV6_ENABLED(context)) {
482 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
483 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
487 // Strip off the IPv4 to IPv6 header if one exists
488 if (strncmp(rip, "::ffff:", 7) == 0)
489 memmove(rip, rip + 7, strlen(rip) - 6);
491 getnameinfo((struct sockaddr *)ads,
492 sizeof(struct sockaddr_in6), name,
493 name_len, NULL, 0, 0);
499 struct addrinfo *result;
501 memset(&ai, 0, sizeof ai);
502 ai.ai_family = PF_UNSPEC;
503 ai.ai_socktype = SOCK_STREAM;
504 ai.ai_flags = AI_CANONNAME;
506 if (getnameinfo((struct sockaddr *)ads,
507 sizeof(struct sockaddr_in),
508 name, name_len, NULL, 0, 0))
514 if (getaddrinfo(name, NULL, &ai, &result))
518 while (addr4.sin_family == AF_UNSPEC && res) {
519 switch (res->ai_family) {
521 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
522 addr4.sin_family = AF_INET;
528 freeaddrinfo(result);
531 if (addr4.sin_family == AF_UNSPEC)
534 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
551 * lws_get_peer_addresses() - Get client address information
552 * @wsi: Local struct lws associated with
553 * @fd: Connection socket descriptor
554 * @name: Buffer to take client address name
555 * @name_len: Length of client address name buffer
556 * @rip: Buffer to take client address IP dotted quad
557 * @rip_len: Length of client address IP buffer
559 * This function fills in @name and @rip with the name and IP of
560 * the client connected with socket descriptor @fd. Names may be
561 * truncated if there is not enough room. If either cannot be
562 * determined, they will be returned as valid zero-length strings.
566 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
567 int name_len, char *rip, int rip_len)
572 struct sockaddr_in6 sin6;
574 struct sockaddr_in sin4;
575 struct lws_context *context = wsi->context;
582 lws_latency_pre(context, wsi);
585 if (LWS_IPV6_ENABLED(context)) {
595 if (getpeername(fd, p, &len) < 0) {
596 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
600 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
603 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
615 * lws_context_user() - get the user data associated with the context
616 * @context: Websocket context
618 * This returns the optional user allocation that can be attached to
619 * the context the sockets live in at context_create time. It's a way
620 * to let all sockets serviced in the same context share data without
621 * using globals statics in the user code.
624 lws_context_user(struct lws_context *context)
626 return context->user_space;
631 * lws_callback_all_protocol() - Callback all connections using
632 * the given protocol with the given reason
634 * @protocol: Protocol whose connections will get callbacks
635 * @reason: Callback reason index
639 lws_callback_all_protocol(struct lws_context *context,
640 const struct lws_protocols *protocol, int reason)
642 struct lws_context_per_thread *pt = &context->pt[0];
643 unsigned int n, m = context->count_threads;
647 for (n = 0; n < pt->fds_count; n++) {
648 wsi = wsi_from_fd(context, pt->fds[n].fd);
651 if (wsi->protocol == protocol)
652 protocol->callback(wsi, reason, wsi->user_space,
664 * lws_get_socket_fd() - returns the socket file descriptor
666 * You will not need this unless you are doing something special
668 * @wsi: Websocket connection instance
672 lws_get_socket_fd(struct lws *wsi)
681 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
682 int ret, int completed)
684 unsigned long long u;
687 u = time_in_microseconds();
690 wsi->latency_start = u;
691 if (!wsi->action_start)
692 wsi->action_start = u;
696 if (wsi->action_start == wsi->latency_start)
698 "Completion first try lat %lluus: %p: ret %d: %s\n",
699 u - wsi->latency_start,
700 (void *)wsi, ret, action);
703 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
704 u - wsi->action_start,
705 u - wsi->latency_start,
706 (void *)wsi, ret, action);
707 wsi->action_start = 0;
709 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
710 u - wsi->latency_start, (void *)wsi, ret, action);
712 if (u - wsi->latency_start > context->worst_latency) {
713 context->worst_latency = u - wsi->latency_start;
714 strcpy(context->worst_latency_info, buf);
716 lwsl_latency("%s", buf);
723 * lws_rx_flow_control() - Enable and disable socket servicing for
726 * If the output side of a server process becomes choked, this allows flow
727 * control for the input side.
729 * @wsi: Websocket connection instance to get callback for
730 * @enable: 0 = disable read servicing for this connection, 1 = enable
734 lws_rx_flow_control(struct lws *wsi, int enable)
736 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
739 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
740 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
746 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
748 * When the user server code realizes it can accept more input, it can
749 * call this to have the RX flow restriction removed from all connections using
750 * the given protocol.
752 * @protocol: all connections using this protocol will be allowed to receive
756 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
757 const struct lws_protocols *protocol)
759 const struct lws_context_per_thread *pt = &context->pt[0];
761 unsigned int n, m = context->count_threads;
764 for (n = 0; n < pt->fds_count; n++) {
765 wsi = wsi_from_fd(context, pt->fds[n].fd);
768 if (wsi->protocol == protocol)
769 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
777 * lws_canonical_hostname() - returns this host's hostname
779 * This is typically used by client code to fill in the host parameter
780 * when making a client connection. You can only call it after the context
783 * @context: Websocket context
785 LWS_VISIBLE extern const char *
786 lws_canonical_hostname(struct lws_context *context)
788 return (const char *)context->canonical_hostname;
791 int user_callback_handle_rxflow(lws_callback_function callback_function,
793 enum lws_callback_reasons reason, void *user,
794 void *in, size_t len)
798 n = callback_function(wsi, reason, user, in, len);
800 n = _lws_rx_flow_control(wsi);
807 * lws_set_proxy() - Setups proxy to lws_context.
808 * @context: pointer to struct lws_context you want set proxy to
809 * @proxy: pointer to c string containing proxy in format address:port
811 * Returns 0 if proxy string was parsed and proxy was setup.
812 * Returns -1 if @proxy is NULL or has incorrect format.
814 * This is only required if your OS does not provide the http_proxy
815 * environment variable (eg, OSX)
817 * IMPORTANT! You should call this function right after creation of the
818 * lws_context and before call to connect. If you call this
819 * function after connect behavior is undefined.
820 * This function will override proxy settings made on lws_context
821 * creation with genenv() call.
825 lws_set_proxy(struct lws_context *context, const char *proxy)
833 p = strchr(proxy, '@');
834 if (p) { /* auth is around */
836 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
839 strncpy(authstring, proxy, p - proxy);
840 // null termination not needed on input
841 if (lws_b64_encode_string(authstring, (p - proxy),
842 context->proxy_basic_auth_token,
843 sizeof context->proxy_basic_auth_token) < 0)
846 lwsl_notice(" Proxy auth in use\n");
850 context->proxy_basic_auth_token[0] = '\0';
852 strncpy(context->http_proxy_address, proxy,
853 sizeof(context->http_proxy_address) - 1);
854 context->http_proxy_address[
855 sizeof(context->http_proxy_address) - 1] = '\0';
857 p = strchr(context->http_proxy_address, ':');
858 if (!p && !context->http_proxy_port) {
859 lwsl_err("http_proxy needs to be ads:port\n");
865 context->http_proxy_port = atoi(p + 1);
869 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
870 context->http_proxy_port);
875 lwsl_err("proxy auth too long\n");
881 * lws_get_protocol() - Returns a protocol pointer from a websocket
883 * @wsi: pointer to struct websocket you want to know the protocol of
886 * Some apis can act on all live connections of a given protocol,
887 * this is how you can get a pointer to the active protocol if needed.
890 LWS_VISIBLE const struct lws_protocols *
891 lws_get_protocol(struct lws *wsi)
893 return wsi->protocol;
897 lws_is_final_fragment(struct lws *wsi)
899 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
900 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
901 wsi->u.ws.rx_draining_ext);
902 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
905 LWS_VISIBLE unsigned char
906 lws_get_reserved_bits(struct lws *wsi)
908 return wsi->u.ws.rsv;
912 lws_ensure_user_space(struct lws *wsi)
914 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
918 /* allocate the per-connection user memory (if any) */
920 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
921 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
922 if (wsi->user_space == NULL) {
923 lwsl_err("Out of memory for conn user space\n");
927 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
928 __func__, wsi, wsi->protocol->per_session_data_size,
933 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
935 time_t o_now = time(NULL);
936 unsigned long long now;
937 struct tm *ptm = NULL;
945 ptm = localtime(&o_now);
947 if (localtime_r(&o_now, &tm))
951 for (n = 0; n < LLL_COUNT; n++) {
952 if (level != (1 << n))
954 now = time_in_microseconds() / 100;
956 sprintf(buf, "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
963 (int)(now % 10000), log_level_names[n]);
965 sprintf(buf, "[%llu:%04d] %s: ",
966 (unsigned long long) now / 10000,
967 (int)(now % 10000), log_level_names[n]);
971 fprintf(stderr, "%s%s", buf, line);
974 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
978 if (!(log_level & filter))
981 vsnprintf(buf, sizeof(buf), format, vl);
982 buf[sizeof(buf) - 1] = '\0';
984 lwsl_emit(filter, buf);
987 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
991 va_start(ap, format);
992 _lws_logv(filter, format, ap);
997 * lws_set_log_level() - Set the logging bitfield
998 * @level: OR together the LLL_ debug contexts you want output from
999 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1000 * function to perform log string emission instead of
1001 * the default stderr one.
1003 * log level defaults to "err", "warn" and "notice" contexts enabled and
1004 * emission on stderr.
1007 LWS_VISIBLE void lws_set_log_level(int level,
1008 void (*func)(int level, const char *line))
1016 * lws_use_ssl() - Find out if connection is using SSL
1017 * @wsi: websocket connection to check
1019 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1020 * using verified cert, and 2 if using SSL but the cert was not
1021 * checked (appears for client wsi told to skip check on connection)
1024 lws_is_ssl(struct lws *wsi)
1026 #ifdef LWS_OPENSSL_SUPPORT
1027 return wsi->use_ssl;
1035 * lws_partial_buffered() - find out if lws buffered the last write
1036 * @wsi: websocket connection to check
1038 * Returns 1 if you cannot use lws_write because the last
1039 * write on this connection is still buffered, and can't be cleared without
1040 * returning to the service loop and waiting for the connection to be
1043 * If you will try to do >1 lws_write call inside a single
1044 * WRITEABLE callback, you must check this after every write and bail if
1045 * set, ask for a new writeable callback and continue writing from there.
1047 * This is never set at the start of a writeable callback, but any write
1052 lws_partial_buffered(struct lws *wsi)
1054 return !!wsi->trunc_len;
1057 void lws_set_protocol_write_pending(struct lws *wsi,
1058 enum lws_pending_protocol_send pend)
1060 lwsl_info("setting pps %d\n", pend);
1063 lwsl_err("pps overwrite\n");
1065 lws_rx_flow_control(wsi, 0);
1066 lws_callback_on_writable(wsi);
1070 lws_get_peer_write_allowance(struct lws *wsi)
1072 #ifdef LWS_USE_HTTP2
1073 /* only if we are using HTTP2 on this connection */
1074 if (wsi->mode != LWSCM_HTTP2_SERVING)
1076 /* user is only interested in how much he can send, or that he can't */
1077 if (wsi->u.http2.tx_credit <= 0)
1080 return wsi->u.http2.tx_credit;
1088 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1090 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1091 memset(&wsi->u, 0, sizeof(wsi->u));
1095 LWS_VISIBLE struct lws_plat_file_ops *
1096 lws_get_fops(struct lws_context *context)
1098 return &context->fops;
1101 LWS_VISIBLE LWS_EXTERN struct lws_context *
1102 lws_get_context(const struct lws *wsi)
1104 return wsi->context;
1107 LWS_VISIBLE LWS_EXTERN int
1108 lws_get_count_threads(struct lws_context *context)
1110 return context->count_threads;
1113 LWS_VISIBLE LWS_EXTERN void *
1114 lws_wsi_user(struct lws *wsi)
1116 return wsi->user_space;
1119 LWS_VISIBLE LWS_EXTERN void
1120 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1121 unsigned char *buf, size_t len)
1123 unsigned char *p, *start;
1124 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1126 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1128 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1130 *p++ = (((int)status) >> 8) & 0xff;
1131 *p++ = ((int)status) & 0xff;
1134 while (len-- && p < start + budget)
1137 wsi->u.ws.close_in_ping_buffer_len = p - start;
1141 _lws_rx_flow_control(struct lws *wsi)
1143 /* there is no pending change */
1144 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1145 lwsl_debug("%s: no pending change\n", __func__);
1149 /* stuff is still buffered, not ready to really accept new input */
1150 if (wsi->rxflow_buffer) {
1151 /* get ourselves called back to deal with stashed buffer */
1152 lws_callback_on_writable(wsi);
1156 /* pending is cleared, we can change rxflow state */
1158 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1160 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1161 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1163 /* adjust the pollfd for this wsi */
1165 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1166 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1167 lwsl_info("%s: fail\n", __func__);
1171 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1178 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1180 static const unsigned char e0f4[] = {
1181 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1182 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1183 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1184 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1185 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1186 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1187 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1188 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1189 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1190 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1191 0x80 | ((4 - 1) << 2) | 1, /* ea */
1192 0x80 | ((4 - 1) << 2) | 1, /* eb */
1193 0x80 | ((4 - 1) << 2) | 1, /* ec */
1194 0x80 | ((2 - 1) << 2) | 1, /* ed */
1195 0x80 | ((4 - 1) << 2) | 1, /* ee */
1196 0x80 | ((4 - 1) << 2) | 1, /* ef */
1197 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1198 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1199 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1200 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1201 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1204 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1205 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1207 unsigned char s = *state;
1210 unsigned char c = *buf++;
1214 if (c < 0xc2 || c > 0xf4)
1217 s = 0x80 | ((4 - 1) << 2);
1222 if (c < (s & 0xf0) ||
1223 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1225 s = e0f4[21 + (s & 3)];
1235 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1236 * Notice it does so by dropping '\0' into input string
1237 * and the leading / on the path is consequently lost
1239 * @p: incoming uri string.. will get written to
1240 * @prot: result pointer for protocol part (https://)
1241 * @ads: result pointer for address part
1242 * @port: result pointer for port part
1243 * @path: result pointer for path part
1246 LWS_VISIBLE LWS_EXTERN int
1247 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1251 static const char *slash = "/";
1253 /* cut up the location into address, port and path */
1255 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1266 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1268 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1271 while (*p && *p != ':' && *p != '/')
1276 while (*p && *p != '/')
1289 #ifdef LWS_NO_EXTENSIONS
1291 /* we need to provide dummy callbacks for internal exts
1292 * so user code runs when faced with a lib compiled with
1293 * extensions disabled.
1297 lws_extension_callback_pm_deflate(struct lws_context *context,
1298 const struct lws_extension *ext,
1300 enum lws_extension_callback_reasons reason,
1301 void *user, void *in, size_t len)