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 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
29 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
31 static const char * const log_level_names[] = {
45 lws_free_wsi(struct lws *wsi)
50 /* Protocol user data may be allocated either internally by lws
51 * or by specified the user.
52 * We should only free what we allocated. */
53 if (wsi->protocol && wsi->protocol->per_session_data_size &&
54 wsi->user_space && !wsi->user_space_externally_allocated)
55 lws_free(wsi->user_space);
57 lws_free_set_NULL(wsi->rxflow_buffer);
58 lws_free_set_NULL(wsi->trunc_alloc);
61 /* we're closing, losing some rx is OK */
62 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
64 /* we may not have an ah, but may be on the waiting list... */
65 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 wsi->pending_timeout_limit = now + secs;
128 wsi->pending_timeout = reason;
133 lws_remove_from_timeout_list(wsi);
137 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
139 struct lws_context *context;
140 struct lws_context_per_thread *pt;
142 struct lws_tokens eff_buf;
147 context = wsi->context;
148 pt = &context->pt[(int)wsi->tsi];
150 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
151 wsi->u.http.fd != LWS_INVALID_FILE) {
152 lwsl_debug("closing http file\n");
153 lws_plat_file_close(wsi, wsi->u.http.fd);
154 wsi->u.http.fd = LWS_INVALID_FILE;
155 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
156 wsi->user_space, NULL, 0);
158 if (wsi->socket_is_permanently_unusable ||
159 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
160 wsi->state == LWSS_SHUTDOWN)
161 goto just_kill_connection;
163 wsi->state_pre_close = wsi->state;
165 switch (wsi->state_pre_close) {
166 case LWSS_DEAD_SOCKET:
169 /* we tried the polite way... */
170 case LWSS_AWAITING_CLOSE_ACK:
171 goto just_kill_connection;
173 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
174 if (wsi->trunc_len) {
175 lws_callback_on_writable(wsi);
178 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
179 goto just_kill_connection;
181 if (wsi->trunc_len) {
182 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
183 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
184 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
190 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
191 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
192 goto just_kill_connection;
194 if (wsi->mode == LWSCM_HTTP_SERVING)
195 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
196 wsi->user_space, NULL, 0);
199 * are his extensions okay with him closing? Eg he might be a mux
200 * parent and just his ch1 aspect is closing?
203 if (lws_ext_cb_active(wsi,
204 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
205 lwsl_ext("extension vetoed close\n");
210 * flush any tx pending from extensions, since we may send close packet
211 * if there are problems with send, just nuke the connection
216 eff_buf.token = NULL;
217 eff_buf.token_len = 0;
219 /* show every extension the new incoming data */
221 m = lws_ext_cb_active(wsi,
222 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
224 lwsl_ext("Extension reports fatal error\n");
225 goto just_kill_connection;
229 * at least one extension told us he has more
230 * to spill, so we will go around again after
234 /* assuming they left us something to send, send it */
236 if (eff_buf.token_len)
237 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
238 eff_buf.token_len) !=
240 lwsl_debug("close: ext spill failed\n");
241 goto just_kill_connection;
246 * signal we are closing, lws_write will
247 * add any necessary version-specific stuff. If the write fails,
248 * no worries we are closing anyway. If we didn't initiate this
249 * close, then our state has been changed to
250 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
252 * Likewise if it's a second call to close this connection after we
253 * sent the close indication to the peer already, we are in state
254 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
257 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
258 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
259 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
260 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
261 lwsl_debug("sending close indication...\n");
263 /* if no prepared close reason, use 1000 and no aux data */
264 if (!wsi->u.ws.close_in_ping_buffer_len) {
265 wsi->u.ws.close_in_ping_buffer_len = 2;
266 wsi->u.ws.ping_payload_buf[LWS_PRE] =
267 (reason >> 16) & 0xff;
268 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
272 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
273 wsi->u.ws.close_in_ping_buffer_len,
277 * we have sent a nice protocol level indication we
278 * now wish to close, we should not send anything more
280 wsi->state = LWSS_AWAITING_CLOSE_ACK;
283 * ...and we should wait for a reply for a bit
286 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
287 lwsl_debug("sent close indication, awaiting ack\n");
292 lwsl_info("close: sending close packet failed, hanging up\n");
294 /* else, the send failed and we should just hang up */
297 just_kill_connection:
301 * Testing with ab shows that we have to stage the socket close when
302 * the system is under stress... shutdown any further TX, change the
303 * state to one that won't emit anything more, and wait with a timeout
304 * for the POLLIN to show a zero-size rx before coming back and doing
307 if (wsi->state != LWSS_SHUTDOWN &&
308 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
309 !wsi->socket_is_permanently_unusable) {
310 lwsl_info("%s: shutting down connection: %p\n", __func__, wsi);
311 n = shutdown(wsi->sock, SHUT_WR);
313 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
315 // This causes problems with disconnection when the events are half closing connection
316 // FD_READ | FD_CLOSE (33)
318 /* libuv: no event available to guarantee completion */
319 if (!LWS_LIBUV_ENABLED(context)) {
321 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
322 wsi->state = LWSS_SHUTDOWN;
323 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
324 context->timeout_secs);
331 lwsl_info("%s: real just_kill_connection: %p\n", __func__, wsi);
334 * we won't be servicing or receiving anything further from this guy
335 * delete socket from the internal poll list if still present
337 lws_ssl_remove_wsi_from_buffered_list(wsi);
338 lws_remove_from_timeout_list(wsi);
340 /* checking return redundant since we anyway close */
341 remove_wsi_socket_from_fds(wsi);
343 wsi->state = LWSS_DEAD_SOCKET;
345 lws_free_set_NULL(wsi->rxflow_buffer);
347 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
348 wsi->mode == LWSCM_WS_SERVING ||
349 wsi->mode == LWSCM_WS_CLIENT) {
351 if (wsi->u.ws.rx_draining_ext) {
352 struct lws **w = &pt->rx_draining_ext_list;
354 wsi->u.ws.rx_draining_ext = 0;
355 /* remove us from context draining ext list */
358 *w = wsi->u.ws.rx_draining_ext_list;
361 w = &((*w)->u.ws.rx_draining_ext_list);
363 wsi->u.ws.rx_draining_ext_list = NULL;
366 if (wsi->u.ws.tx_draining_ext) {
367 struct lws **w = &pt->tx_draining_ext_list;
369 wsi->u.ws.tx_draining_ext = 0;
370 /* remove us from context draining ext list */
373 *w = wsi->u.ws.tx_draining_ext_list;
376 w = &((*w)->u.ws.tx_draining_ext_list);
378 wsi->u.ws.tx_draining_ext_list = NULL;
380 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
382 if (wsi->trunc_alloc)
383 /* not going to be completed... nuke it */
384 lws_free_set_NULL(wsi->trunc_alloc);
386 wsi->u.ws.ping_payload_len = 0;
387 wsi->u.ws.ping_pending_flag = 0;
390 /* tell the user it's all over for this guy */
392 if (wsi->protocol && wsi->protocol->callback &&
393 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
394 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
395 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
396 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
397 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
398 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
399 lwsl_debug("calling back CLOSED\n");
400 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
401 wsi->user_space, NULL, 0);
402 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
403 lwsl_debug("calling back CLOSED_HTTP\n");
404 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
405 wsi->user_space, NULL, 0 );
406 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
407 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
410 lwsl_debug("Connection closed before server reply\n");
411 errorString = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
413 context->protocols[0].callback(wsi,
414 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
415 wsi->user_space, errorString,
416 (unsigned int)strlen(errorString));
418 context->protocols[0].callback(wsi,
419 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
420 wsi->user_space, NULL, 0);
423 lwsl_debug("not calling back closed mode=%d state=%d\n",
424 wsi->mode, wsi->state_pre_close);
426 /* deallocate any active extension contexts */
428 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
429 lwsl_warn("extension destruction failed\n");
431 * inform all extensions in case they tracked this guy out of band
432 * even though not active on him specifically
434 if (lws_ext_cb_all_exts(context, wsi,
435 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
436 lwsl_warn("ext destroy wsi failed\n");
438 wsi->socket_is_permanently_unusable = 1;
441 if (LWS_LIBUV_ENABLED(context)) {
442 /* libuv has to do his own close handle processing asynchronously */
443 lws_libuv_closehandle(wsi);
449 lws_close_free_wsi_final(wsi);
453 lws_close_free_wsi_final(struct lws *wsi)
457 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
459 n = compatible_close(wsi->sock);
461 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
464 compatible_close(wsi->sock);
466 wsi->sock = LWS_SOCK_INVALID;
469 /* outermost destroy notification for wsi (user_space still intact) */
470 wsi->context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
471 wsi->user_space, NULL, 0);
478 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
482 ipv6 = LWS_IPV6_ENABLED(context);
486 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
491 lws_get_addresses(struct lws_context *context, void *ads, char *name,
492 int name_len, char *rip, int rip_len)
495 struct addrinfo ai, *res;
496 struct sockaddr_in addr4;
501 addr4.sin_family = AF_UNSPEC;
504 if (LWS_IPV6_ENABLED(context)) {
505 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
506 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
510 // Strip off the IPv4 to IPv6 header if one exists
511 if (strncmp(rip, "::ffff:", 7) == 0)
512 memmove(rip, rip + 7, strlen(rip) - 6);
514 getnameinfo((struct sockaddr *)ads,
515 sizeof(struct sockaddr_in6), name,
516 name_len, NULL, 0, 0);
522 struct addrinfo *result;
524 memset(&ai, 0, sizeof ai);
525 ai.ai_family = PF_UNSPEC;
526 ai.ai_socktype = SOCK_STREAM;
527 ai.ai_flags = AI_CANONNAME;
529 if (getnameinfo((struct sockaddr *)ads,
530 sizeof(struct sockaddr_in),
531 name, name_len, NULL, 0, 0))
537 if (getaddrinfo(name, NULL, &ai, &result))
541 while (addr4.sin_family == AF_UNSPEC && res) {
542 switch (res->ai_family) {
544 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
545 addr4.sin_family = AF_INET;
551 freeaddrinfo(result);
554 if (addr4.sin_family == AF_UNSPEC)
557 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
574 * lws_get_peer_addresses() - Get client address information
575 * @wsi: Local struct lws associated with
576 * @fd: Connection socket descriptor
577 * @name: Buffer to take client address name
578 * @name_len: Length of client address name buffer
579 * @rip: Buffer to take client address IP dotted quad
580 * @rip_len: Length of client address IP buffer
582 * This function fills in @name and @rip with the name and IP of
583 * the client connected with socket descriptor @fd. Names may be
584 * truncated if there is not enough room. If either cannot be
585 * determined, they will be returned as valid zero-length strings.
589 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
590 int name_len, char *rip, int rip_len)
595 struct sockaddr_in6 sin6;
597 struct sockaddr_in sin4;
598 struct lws_context *context = wsi->context;
605 lws_latency_pre(context, wsi);
608 if (LWS_IPV6_ENABLED(context)) {
618 if (getpeername(fd, p, &len) < 0) {
619 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
623 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
626 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
638 * lws_context_user() - get the user data associated with the context
639 * @context: Websocket context
641 * This returns the optional user allocation that can be attached to
642 * the context the sockets live in at context_create time. It's a way
643 * to let all sockets serviced in the same context share data without
644 * using globals statics in the user code.
647 lws_context_user(struct lws_context *context)
649 return context->user_space;
654 * lws_callback_all_protocol() - Callback all connections using
655 * the given protocol with the given reason
657 * @protocol: Protocol whose connections will get callbacks
658 * @reason: Callback reason index
662 lws_callback_all_protocol(struct lws_context *context,
663 const struct lws_protocols *protocol, int reason)
665 struct lws_context_per_thread *pt = &context->pt[0];
666 unsigned int n, m = context->count_threads;
670 for (n = 0; n < pt->fds_count; n++) {
671 wsi = wsi_from_fd(context, pt->fds[n].fd);
674 if (wsi->protocol == protocol)
675 protocol->callback(wsi, reason, wsi->user_space,
687 * lws_get_socket_fd() - returns the socket file descriptor
689 * You will not need this unless you are doing something special
691 * @wsi: Websocket connection instance
695 lws_get_socket_fd(struct lws *wsi)
704 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
705 int ret, int completed)
707 unsigned long long u;
710 u = time_in_microseconds();
713 wsi->latency_start = u;
714 if (!wsi->action_start)
715 wsi->action_start = u;
719 if (wsi->action_start == wsi->latency_start)
721 "Completion first try lat %lluus: %p: ret %d: %s\n",
722 u - wsi->latency_start,
723 (void *)wsi, ret, action);
726 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
727 u - wsi->action_start,
728 u - wsi->latency_start,
729 (void *)wsi, ret, action);
730 wsi->action_start = 0;
732 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
733 u - wsi->latency_start, (void *)wsi, ret, action);
735 if (u - wsi->latency_start > context->worst_latency) {
736 context->worst_latency = u - wsi->latency_start;
737 strcpy(context->worst_latency_info, buf);
739 lwsl_latency("%s", buf);
746 * lws_rx_flow_control() - Enable and disable socket servicing for
749 * If the output side of a server process becomes choked, this allows flow
750 * control for the input side.
752 * @wsi: Websocket connection instance to get callback for
753 * @enable: 0 = disable read servicing for this connection, 1 = enable
757 lws_rx_flow_control(struct lws *wsi, int enable)
759 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
762 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
763 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
769 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
771 * When the user server code realizes it can accept more input, it can
772 * call this to have the RX flow restriction removed from all connections using
773 * the given protocol.
775 * @protocol: all connections using this protocol will be allowed to receive
779 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
780 const struct lws_protocols *protocol)
782 const struct lws_context_per_thread *pt = &context->pt[0];
784 unsigned int n, m = context->count_threads;
787 for (n = 0; n < pt->fds_count; n++) {
788 wsi = wsi_from_fd(context, pt->fds[n].fd);
791 if (wsi->protocol == protocol)
792 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
800 * lws_canonical_hostname() - returns this host's hostname
802 * This is typically used by client code to fill in the host parameter
803 * when making a client connection. You can only call it after the context
806 * @context: Websocket context
808 LWS_VISIBLE extern const char *
809 lws_canonical_hostname(struct lws_context *context)
811 return (const char *)context->canonical_hostname;
814 int user_callback_handle_rxflow(lws_callback_function callback_function,
816 enum lws_callback_reasons reason, void *user,
817 void *in, size_t len)
821 n = callback_function(wsi, reason, user, in, len);
823 n = _lws_rx_flow_control(wsi);
830 * lws_set_proxy() - Setups proxy to lws_context.
831 * @context: pointer to struct lws_context you want set proxy to
832 * @proxy: pointer to c string containing proxy in format address:port
834 * Returns 0 if proxy string was parsed and proxy was setup.
835 * Returns -1 if @proxy is NULL or has incorrect format.
837 * This is only required if your OS does not provide the http_proxy
838 * environment variable (eg, OSX)
840 * IMPORTANT! You should call this function right after creation of the
841 * lws_context and before call to connect. If you call this
842 * function after connect behavior is undefined.
843 * This function will override proxy settings made on lws_context
844 * creation with genenv() call.
848 lws_set_proxy(struct lws_context *context, const char *proxy)
856 p = strchr(proxy, '@');
857 if (p) { /* auth is around */
859 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
862 strncpy(authstring, proxy, p - proxy);
863 // null termination not needed on input
864 if (lws_b64_encode_string(authstring, (p - proxy),
865 context->proxy_basic_auth_token,
866 sizeof context->proxy_basic_auth_token) < 0)
869 lwsl_notice(" Proxy auth in use\n");
873 context->proxy_basic_auth_token[0] = '\0';
875 strncpy(context->http_proxy_address, proxy,
876 sizeof(context->http_proxy_address) - 1);
877 context->http_proxy_address[
878 sizeof(context->http_proxy_address) - 1] = '\0';
880 p = strchr(context->http_proxy_address, ':');
881 if (!p && !context->http_proxy_port) {
882 lwsl_err("http_proxy needs to be ads:port\n");
888 context->http_proxy_port = atoi(p + 1);
892 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
893 context->http_proxy_port);
898 lwsl_err("proxy auth too long\n");
904 * lws_get_protocol() - Returns a protocol pointer from a websocket
906 * @wsi: pointer to struct websocket you want to know the protocol of
909 * Some apis can act on all live connections of a given protocol,
910 * this is how you can get a pointer to the active protocol if needed.
913 LWS_VISIBLE const struct lws_protocols *
914 lws_get_protocol(struct lws *wsi)
916 return wsi->protocol;
920 lws_is_final_fragment(struct lws *wsi)
922 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
923 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
924 wsi->u.ws.rx_draining_ext);
925 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
928 LWS_VISIBLE unsigned char
929 lws_get_reserved_bits(struct lws *wsi)
931 return wsi->u.ws.rsv;
935 lws_ensure_user_space(struct lws *wsi)
937 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
941 /* allocate the per-connection user memory (if any) */
943 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
944 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
945 if (wsi->user_space == NULL) {
946 lwsl_err("Out of memory for conn user space\n");
950 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
951 __func__, wsi, wsi->protocol->per_session_data_size,
956 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
958 time_t o_now = time(NULL);
959 unsigned long long now;
960 struct tm *ptm = NULL;
969 ptm = localtime(&o_now);
971 if (localtime_r(&o_now, &tm))
976 for (n = 0; n < LLL_COUNT; n++) {
977 if (level != (1 << n))
979 now = time_in_microseconds() / 100;
981 sprintf(buf, "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
988 (int)(now % 10000), log_level_names[n]);
990 sprintf(buf, "[%llu:%04d] %s: ",
991 (unsigned long long) now / 10000,
992 (int)(now % 10000), log_level_names[n]);
996 fprintf(stderr, "%s%s", buf, line);
999 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1003 if (!(log_level & filter))
1006 vsnprintf(buf, sizeof(buf), format, vl);
1007 buf[sizeof(buf) - 1] = '\0';
1009 lwsl_emit(filter, buf);
1012 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1016 va_start(ap, format);
1017 _lws_logv(filter, format, ap);
1022 * lws_set_log_level() - Set the logging bitfield
1023 * @level: OR together the LLL_ debug contexts you want output from
1024 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1025 * function to perform log string emission instead of
1026 * the default stderr one.
1028 * log level defaults to "err", "warn" and "notice" contexts enabled and
1029 * emission on stderr.
1032 LWS_VISIBLE void lws_set_log_level(int level,
1033 void (*func)(int level, const char *line))
1041 * lws_use_ssl() - Find out if connection is using SSL
1042 * @wsi: websocket connection to check
1044 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1045 * using verified cert, and 2 if using SSL but the cert was not
1046 * checked (appears for client wsi told to skip check on connection)
1049 lws_is_ssl(struct lws *wsi)
1051 #ifdef LWS_OPENSSL_SUPPORT
1052 return wsi->use_ssl;
1060 * lws_partial_buffered() - find out if lws buffered the last write
1061 * @wsi: websocket connection to check
1063 * Returns 1 if you cannot use lws_write because the last
1064 * write on this connection is still buffered, and can't be cleared without
1065 * returning to the service loop and waiting for the connection to be
1068 * If you will try to do >1 lws_write call inside a single
1069 * WRITEABLE callback, you must check this after every write and bail if
1070 * set, ask for a new writeable callback and continue writing from there.
1072 * This is never set at the start of a writeable callback, but any write
1077 lws_partial_buffered(struct lws *wsi)
1079 return !!wsi->trunc_len;
1082 void lws_set_protocol_write_pending(struct lws *wsi,
1083 enum lws_pending_protocol_send pend)
1085 lwsl_info("setting pps %d\n", pend);
1088 lwsl_err("pps overwrite\n");
1090 lws_rx_flow_control(wsi, 0);
1091 lws_callback_on_writable(wsi);
1095 lws_get_peer_write_allowance(struct lws *wsi)
1097 #ifdef LWS_USE_HTTP2
1098 /* only if we are using HTTP2 on this connection */
1099 if (wsi->mode != LWSCM_HTTP2_SERVING)
1101 /* user is only interested in how much he can send, or that he can't */
1102 if (wsi->u.http2.tx_credit <= 0)
1105 return wsi->u.http2.tx_credit;
1113 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1115 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1116 memset(&wsi->u, 0, sizeof(wsi->u));
1120 LWS_VISIBLE struct lws_plat_file_ops *
1121 lws_get_fops(struct lws_context *context)
1123 return &context->fops;
1126 LWS_VISIBLE LWS_EXTERN struct lws_context *
1127 lws_get_context(const struct lws *wsi)
1129 return wsi->context;
1132 LWS_VISIBLE LWS_EXTERN int
1133 lws_get_count_threads(struct lws_context *context)
1135 return context->count_threads;
1138 LWS_VISIBLE LWS_EXTERN void *
1139 lws_wsi_user(struct lws *wsi)
1141 return wsi->user_space;
1144 LWS_VISIBLE LWS_EXTERN void
1145 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1146 unsigned char *buf, size_t len)
1148 unsigned char *p, *start;
1149 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1151 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1153 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1155 *p++ = (((int)status) >> 8) & 0xff;
1156 *p++ = ((int)status) & 0xff;
1159 while (len-- && p < start + budget)
1162 wsi->u.ws.close_in_ping_buffer_len = p - start;
1166 _lws_rx_flow_control(struct lws *wsi)
1168 /* there is no pending change */
1169 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1170 lwsl_debug("%s: no pending change\n", __func__);
1174 /* stuff is still buffered, not ready to really accept new input */
1175 if (wsi->rxflow_buffer) {
1176 /* get ourselves called back to deal with stashed buffer */
1177 lws_callback_on_writable(wsi);
1181 /* pending is cleared, we can change rxflow state */
1183 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1185 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1186 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1188 /* adjust the pollfd for this wsi */
1190 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1191 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1192 lwsl_info("%s: fail\n", __func__);
1196 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1203 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1205 static const unsigned char e0f4[] = {
1206 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1207 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1208 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1209 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1210 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1211 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1212 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1213 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1214 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1215 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1216 0x80 | ((4 - 1) << 2) | 1, /* ea */
1217 0x80 | ((4 - 1) << 2) | 1, /* eb */
1218 0x80 | ((4 - 1) << 2) | 1, /* ec */
1219 0x80 | ((2 - 1) << 2) | 1, /* ed */
1220 0x80 | ((4 - 1) << 2) | 1, /* ee */
1221 0x80 | ((4 - 1) << 2) | 1, /* ef */
1222 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1223 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1224 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1225 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1226 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1229 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1230 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1232 unsigned char s = *state;
1235 unsigned char c = *buf++;
1239 if (c < 0xc2 || c > 0xf4)
1242 s = 0x80 | ((4 - 1) << 2);
1247 if (c < (s & 0xf0) ||
1248 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1250 s = e0f4[21 + (s & 3)];
1260 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1261 * Notice it does so by dropping '\0' into input string
1262 * and the leading / on the path is consequently lost
1264 * @p: incoming uri string.. will get written to
1265 * @prot: result pointer for protocol part (https://)
1266 * @ads: result pointer for address part
1267 * @port: result pointer for port part
1268 * @path: result pointer for path part
1271 LWS_VISIBLE LWS_EXTERN int
1272 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1276 static const char *slash = "/";
1278 /* cut up the location into address, port and path */
1280 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1291 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1293 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1296 while (*p && *p != ':' && *p != '/')
1301 while (*p && *p != '/')
1315 lws_snprintf(char *str, size_t size, const char *format, ...)
1323 va_start(ap, format);
1324 n = vsnprintf(str, size, format, ap);
1333 #ifdef LWS_NO_EXTENSIONS
1335 /* we need to provide dummy callbacks for internal exts
1336 * so user code runs when faced with a lib compiled with
1337 * extensions disabled.
1341 lws_extension_callback_pm_deflate(struct lws_context *context,
1342 const struct lws_extension *ext,
1344 enum lws_extension_callback_reasons reason,
1345 void *user, void *in, size_t len)