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)
78 if (wsi->timeout_list)
79 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
80 *wsi->timeout_list_prev = wsi->timeout_list;
82 wsi->timeout_list_prev = NULL;
83 wsi->timeout_list = NULL;
88 * lws_set_timeout() - marks the wsi as subject to a timeout
90 * You will not need this unless you are doing something special
92 * @wsi: Websocket connection instance
93 * @reason: timeout reason
94 * @secs: how many seconds
98 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
100 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
107 if (!wsi->pending_timeout && reason) {
108 wsi->timeout_list = pt->timeout_list;
109 if (wsi->timeout_list)
110 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
111 wsi->timeout_list_prev = &pt->timeout_list;
112 *wsi->timeout_list_prev = wsi;
115 wsi->pending_timeout_limit = now + secs;
116 wsi->pending_timeout = reason;
121 lws_remove_from_timeout_list(wsi);
125 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
127 struct lws_context *context;
128 struct lws_context_per_thread *pt;
130 struct lws_tokens eff_buf;
135 context = wsi->context;
136 pt = &context->pt[(int)wsi->tsi];
138 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
139 wsi->u.http.fd != LWS_INVALID_FILE) {
140 lwsl_debug("closing http file\n");
141 lws_plat_file_close(wsi, wsi->u.http.fd);
142 wsi->u.http.fd = LWS_INVALID_FILE;
143 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
144 wsi->user_space, NULL, 0);
146 if (wsi->socket_is_permanently_unusable ||
147 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
148 wsi->state == LWSS_SHUTDOWN)
149 goto just_kill_connection;
151 wsi->state_pre_close = wsi->state;
153 switch (wsi->state_pre_close) {
154 case LWSS_DEAD_SOCKET:
157 /* we tried the polite way... */
158 case LWSS_AWAITING_CLOSE_ACK:
159 goto just_kill_connection;
161 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
162 if (wsi->trunc_len) {
163 lws_callback_on_writable(wsi);
166 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
167 goto just_kill_connection;
169 if (wsi->trunc_len) {
170 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
171 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
172 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
178 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
179 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
180 goto just_kill_connection;
182 if (wsi->mode == LWSCM_HTTP_SERVING)
183 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
184 wsi->user_space, NULL, 0);
187 * are his extensions okay with him closing? Eg he might be a mux
188 * parent and just his ch1 aspect is closing?
191 if (lws_ext_cb_active(wsi,
192 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
193 lwsl_ext("extension vetoed close\n");
198 * flush any tx pending from extensions, since we may send close packet
199 * if there are problems with send, just nuke the connection
204 eff_buf.token = NULL;
205 eff_buf.token_len = 0;
207 /* show every extension the new incoming data */
209 m = lws_ext_cb_active(wsi,
210 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
212 lwsl_ext("Extension reports fatal error\n");
213 goto just_kill_connection;
217 * at least one extension told us he has more
218 * to spill, so we will go around again after
222 /* assuming they left us something to send, send it */
224 if (eff_buf.token_len)
225 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
226 eff_buf.token_len) !=
228 lwsl_debug("close: ext spill failed\n");
229 goto just_kill_connection;
234 * signal we are closing, lws_write will
235 * add any necessary version-specific stuff. If the write fails,
236 * no worries we are closing anyway. If we didn't initiate this
237 * close, then our state has been changed to
238 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
240 * Likewise if it's a second call to close this connection after we
241 * sent the close indication to the peer already, we are in state
242 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
245 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
246 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
247 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
248 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
249 lwsl_debug("sending close indication...\n");
251 /* if no prepared close reason, use 1000 and no aux data */
252 if (!wsi->u.ws.close_in_ping_buffer_len) {
253 wsi->u.ws.close_in_ping_buffer_len = 2;
254 wsi->u.ws.ping_payload_buf[LWS_PRE] =
255 (reason >> 16) & 0xff;
256 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
260 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
261 wsi->u.ws.close_in_ping_buffer_len,
265 * we have sent a nice protocol level indication we
266 * now wish to close, we should not send anything more
268 wsi->state = LWSS_AWAITING_CLOSE_ACK;
271 * ...and we should wait for a reply for a bit
274 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
275 lwsl_debug("sent close indication, awaiting ack\n");
280 lwsl_info("close: sending close packet failed, hanging up\n");
282 /* else, the send failed and we should just hang up */
285 just_kill_connection:
289 * Testing with ab shows that we have to stage the socket close when
290 * the system is under stress... shutdown any further TX, change the
291 * state to one that won't emit anything more, and wait with a timeout
292 * for the POLLIN to show a zero-size rx before coming back and doing
295 if (wsi->state != LWSS_SHUTDOWN &&
296 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
297 !wsi->socket_is_permanently_unusable) {
298 lwsl_info("%s: shutting down connection: %p\n", __func__, wsi);
299 n = shutdown(wsi->sock, SHUT_WR);
301 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
302 wsi->state = LWSS_SHUTDOWN;
303 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
304 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
305 context->timeout_secs);
310 lwsl_info("%s: real just_kill_connection: %p\n", __func__, wsi);
313 * we won't be servicing or receiving anything further from this guy
314 * delete socket from the internal poll list if still present
316 lws_ssl_remove_wsi_from_buffered_list(wsi);
317 lws_remove_from_timeout_list(wsi);
319 /* checking return redundant since we anyway close */
320 remove_wsi_socket_from_fds(wsi);
322 wsi->state = LWSS_DEAD_SOCKET;
324 lws_free_set_NULL(wsi->rxflow_buffer);
326 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
327 wsi->mode == LWSCM_WS_SERVING ||
328 wsi->mode == LWSCM_WS_CLIENT) {
330 if (wsi->u.ws.rx_draining_ext) {
331 struct lws **w = &pt->rx_draining_ext_list;
333 wsi->u.ws.rx_draining_ext = 0;
334 /* remove us from context draining ext list */
337 *w = wsi->u.ws.rx_draining_ext_list;
340 w = &((*w)->u.ws.rx_draining_ext_list);
342 wsi->u.ws.rx_draining_ext_list = NULL;
345 if (wsi->u.ws.tx_draining_ext) {
346 struct lws **w = &pt->tx_draining_ext_list;
348 wsi->u.ws.tx_draining_ext = 0;
349 /* remove us from context draining ext list */
352 *w = wsi->u.ws.tx_draining_ext_list;
355 w = &((*w)->u.ws.tx_draining_ext_list);
357 wsi->u.ws.tx_draining_ext_list = NULL;
359 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
361 if (wsi->trunc_alloc)
362 /* not going to be completed... nuke it */
363 lws_free_set_NULL(wsi->trunc_alloc);
365 wsi->u.ws.ping_payload_len = 0;
366 wsi->u.ws.ping_pending_flag = 0;
369 /* tell the user it's all over for this guy */
371 if (wsi->protocol && wsi->protocol->callback &&
372 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
373 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
374 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
375 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE))) {
376 lwsl_debug("calling back CLOSED\n");
377 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
378 wsi->user_space, NULL, 0);
379 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
380 lwsl_debug("calling back CLOSED_HTTP\n");
381 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
382 wsi->user_space, NULL, 0 );
383 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
384 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
385 lwsl_debug("Connection closed before server reply\n");
386 context->protocols[0].callback(wsi,
387 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
388 wsi->user_space, NULL, 0);
390 lwsl_debug("not calling back closed mode=%d state=%d\n",
391 wsi->mode, wsi->state_pre_close);
393 /* deallocate any active extension contexts */
395 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
396 lwsl_warn("extension destruction failed\n");
398 * inform all extensions in case they tracked this guy out of band
399 * even though not active on him specifically
401 if (lws_ext_cb_all_exts(context, wsi,
402 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
403 lwsl_warn("ext destroy wsi failed\n");
405 wsi->socket_is_permanently_unusable = 1;
408 if (LWS_LIBUV_ENABLED(context)) {
409 /* libuv has to do his own close handle processing asynchronously */
410 lws_libuv_closehandle(wsi);
416 lws_close_free_wsi_final(wsi);
420 lws_close_free_wsi_final(struct lws *wsi)
424 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
426 n = compatible_close(wsi->sock);
428 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
431 compatible_close(wsi->sock);
433 wsi->sock = LWS_SOCK_INVALID;
436 /* outermost destroy notification for wsi (user_space still intact) */
437 wsi->context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
438 wsi->user_space, NULL, 0);
445 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
449 ipv6 = LWS_IPV6_ENABLED(context);
453 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
458 lws_get_addresses(struct lws_context *context, void *ads, char *name,
459 int name_len, char *rip, int rip_len)
462 struct addrinfo ai, *res;
463 struct sockaddr_in addr4;
468 addr4.sin_family = AF_UNSPEC;
471 if (LWS_IPV6_ENABLED(context)) {
472 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
473 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
477 // Strip off the IPv4 to IPv6 header if one exists
478 if (strncmp(rip, "::ffff:", 7) == 0)
479 memmove(rip, rip + 7, strlen(rip) - 6);
481 getnameinfo((struct sockaddr *)ads,
482 sizeof(struct sockaddr_in6), name,
483 name_len, NULL, 0, 0);
489 struct addrinfo *result;
491 memset(&ai, 0, sizeof ai);
492 ai.ai_family = PF_UNSPEC;
493 ai.ai_socktype = SOCK_STREAM;
494 ai.ai_flags = AI_CANONNAME;
496 if (getnameinfo((struct sockaddr *)ads,
497 sizeof(struct sockaddr_in),
498 name, name_len, NULL, 0, 0))
504 if (getaddrinfo(name, NULL, &ai, &result))
508 while (addr4.sin_family == AF_UNSPEC && res) {
509 switch (res->ai_family) {
511 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
512 addr4.sin_family = AF_INET;
518 freeaddrinfo(result);
521 if (addr4.sin_family == AF_UNSPEC)
524 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
541 * lws_get_peer_addresses() - Get client address information
542 * @wsi: Local struct lws associated with
543 * @fd: Connection socket descriptor
544 * @name: Buffer to take client address name
545 * @name_len: Length of client address name buffer
546 * @rip: Buffer to take client address IP dotted quad
547 * @rip_len: Length of client address IP buffer
549 * This function fills in @name and @rip with the name and IP of
550 * the client connected with socket descriptor @fd. Names may be
551 * truncated if there is not enough room. If either cannot be
552 * determined, they will be returned as valid zero-length strings.
556 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
557 int name_len, char *rip, int rip_len)
562 struct sockaddr_in6 sin6;
564 struct sockaddr_in sin4;
565 struct lws_context *context = wsi->context;
572 lws_latency_pre(context, wsi);
575 if (LWS_IPV6_ENABLED(context)) {
585 if (getpeername(fd, p, &len) < 0) {
586 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
590 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
593 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
605 * lws_context_user() - get the user data associated with the context
606 * @context: Websocket context
608 * This returns the optional user allocation that can be attached to
609 * the context the sockets live in at context_create time. It's a way
610 * to let all sockets serviced in the same context share data without
611 * using globals statics in the user code.
614 lws_context_user(struct lws_context *context)
616 return context->user_space;
621 * lws_callback_all_protocol() - Callback all connections using
622 * the given protocol with the given reason
624 * @protocol: Protocol whose connections will get callbacks
625 * @reason: Callback reason index
629 lws_callback_all_protocol(struct lws_context *context,
630 const struct lws_protocols *protocol, int reason)
632 struct lws_context_per_thread *pt = &context->pt[0];
633 unsigned int n, m = context->count_threads;
637 for (n = 0; n < pt->fds_count; n++) {
638 wsi = wsi_from_fd(context, pt->fds[n].fd);
641 if (wsi->protocol == protocol)
642 protocol->callback(wsi, reason, wsi->user_space,
654 * lws_get_socket_fd() - returns the socket file descriptor
656 * You will not need this unless you are doing something special
658 * @wsi: Websocket connection instance
662 lws_get_socket_fd(struct lws *wsi)
671 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
672 int ret, int completed)
674 unsigned long long u;
677 u = time_in_microseconds();
680 wsi->latency_start = u;
681 if (!wsi->action_start)
682 wsi->action_start = u;
686 if (wsi->action_start == wsi->latency_start)
688 "Completion first try lat %lluus: %p: ret %d: %s\n",
689 u - wsi->latency_start,
690 (void *)wsi, ret, action);
693 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
694 u - wsi->action_start,
695 u - wsi->latency_start,
696 (void *)wsi, ret, action);
697 wsi->action_start = 0;
699 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
700 u - wsi->latency_start, (void *)wsi, ret, action);
702 if (u - wsi->latency_start > context->worst_latency) {
703 context->worst_latency = u - wsi->latency_start;
704 strcpy(context->worst_latency_info, buf);
706 lwsl_latency("%s", buf);
713 * lws_rx_flow_control() - Enable and disable socket servicing for
716 * If the output side of a server process becomes choked, this allows flow
717 * control for the input side.
719 * @wsi: Websocket connection instance to get callback for
720 * @enable: 0 = disable read servicing for this connection, 1 = enable
724 lws_rx_flow_control(struct lws *wsi, int enable)
726 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
729 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
730 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
736 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
738 * When the user server code realizes it can accept more input, it can
739 * call this to have the RX flow restriction removed from all connections using
740 * the given protocol.
742 * @protocol: all connections using this protocol will be allowed to receive
746 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
747 const struct lws_protocols *protocol)
749 const struct lws_context_per_thread *pt = &context->pt[0];
751 unsigned int n, m = context->count_threads;
754 for (n = 0; n < pt->fds_count; n++) {
755 wsi = wsi_from_fd(context, pt->fds[n].fd);
758 if (wsi->protocol == protocol)
759 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
767 * lws_canonical_hostname() - returns this host's hostname
769 * This is typically used by client code to fill in the host parameter
770 * when making a client connection. You can only call it after the context
773 * @context: Websocket context
775 LWS_VISIBLE extern const char *
776 lws_canonical_hostname(struct lws_context *context)
778 return (const char *)context->canonical_hostname;
781 int user_callback_handle_rxflow(lws_callback_function callback_function,
783 enum lws_callback_reasons reason, void *user,
784 void *in, size_t len)
788 n = callback_function(wsi, reason, user, in, len);
790 n = _lws_rx_flow_control(wsi);
797 * lws_set_proxy() - Setups proxy to lws_context.
798 * @context: pointer to struct lws_context you want set proxy to
799 * @proxy: pointer to c string containing proxy in format address:port
801 * Returns 0 if proxy string was parsed and proxy was setup.
802 * Returns -1 if @proxy is NULL or has incorrect format.
804 * This is only required if your OS does not provide the http_proxy
805 * environment variable (eg, OSX)
807 * IMPORTANT! You should call this function right after creation of the
808 * lws_context and before call to connect. If you call this
809 * function after connect behavior is undefined.
810 * This function will override proxy settings made on lws_context
811 * creation with genenv() call.
815 lws_set_proxy(struct lws_context *context, const char *proxy)
823 p = strchr(proxy, '@');
824 if (p) { /* auth is around */
826 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
829 strncpy(authstring, proxy, p - proxy);
830 // null termination not needed on input
831 if (lws_b64_encode_string(authstring, (p - proxy),
832 context->proxy_basic_auth_token,
833 sizeof context->proxy_basic_auth_token) < 0)
836 lwsl_notice(" Proxy auth in use\n");
840 context->proxy_basic_auth_token[0] = '\0';
842 strncpy(context->http_proxy_address, proxy,
843 sizeof(context->http_proxy_address) - 1);
844 context->http_proxy_address[
845 sizeof(context->http_proxy_address) - 1] = '\0';
847 p = strchr(context->http_proxy_address, ':');
848 if (!p && !context->http_proxy_port) {
849 lwsl_err("http_proxy needs to be ads:port\n");
855 context->http_proxy_port = atoi(p + 1);
859 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
860 context->http_proxy_port);
865 lwsl_err("proxy auth too long\n");
871 * lws_get_protocol() - Returns a protocol pointer from a websocket
873 * @wsi: pointer to struct websocket you want to know the protocol of
876 * Some apis can act on all live connections of a given protocol,
877 * this is how you can get a pointer to the active protocol if needed.
880 LWS_VISIBLE const struct lws_protocols *
881 lws_get_protocol(struct lws *wsi)
883 return wsi->protocol;
887 lws_is_final_fragment(struct lws *wsi)
889 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
890 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
891 wsi->u.ws.rx_draining_ext);
892 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
895 LWS_VISIBLE unsigned char
896 lws_get_reserved_bits(struct lws *wsi)
898 return wsi->u.ws.rsv;
902 lws_ensure_user_space(struct lws *wsi)
904 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
908 /* allocate the per-connection user memory (if any) */
910 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
911 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
912 if (wsi->user_space == NULL) {
913 lwsl_err("Out of memory for conn user space\n");
917 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
918 __func__, wsi, wsi->protocol->per_session_data_size,
923 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
925 unsigned long long now;
930 for (n = 0; n < LLL_COUNT; n++) {
931 if (level != (1 << n))
933 now = time_in_microseconds() / 100;
934 sprintf(buf, "[%llu:%04d] %s: ",
935 (unsigned long long) now / 10000,
936 (int)(now % 10000), log_level_names[n]);
940 fprintf(stderr, "%s%s", buf, line);
943 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
947 if (!(log_level & filter))
950 vsnprintf(buf, sizeof(buf), format, vl);
951 buf[sizeof(buf) - 1] = '\0';
953 lwsl_emit(filter, buf);
956 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
960 va_start(ap, format);
961 _lws_logv(filter, format, ap);
966 * lws_set_log_level() - Set the logging bitfield
967 * @level: OR together the LLL_ debug contexts you want output from
968 * @log_emit_function: NULL to leave it as it is, or a user-supplied
969 * function to perform log string emission instead of
970 * the default stderr one.
972 * log level defaults to "err", "warn" and "notice" contexts enabled and
973 * emission on stderr.
976 LWS_VISIBLE void lws_set_log_level(int level,
977 void (*func)(int level, const char *line))
985 * lws_use_ssl() - Find out if connection is using SSL
986 * @wsi: websocket connection to check
988 * Returns 0 if the connection is not using SSL, 1 if using SSL and
989 * using verified cert, and 2 if using SSL but the cert was not
990 * checked (appears for client wsi told to skip check on connection)
993 lws_is_ssl(struct lws *wsi)
995 #ifdef LWS_OPENSSL_SUPPORT
1004 * lws_partial_buffered() - find out if lws buffered the last write
1005 * @wsi: websocket connection to check
1007 * Returns 1 if you cannot use lws_write because the last
1008 * write on this connection is still buffered, and can't be cleared without
1009 * returning to the service loop and waiting for the connection to be
1012 * If you will try to do >1 lws_write call inside a single
1013 * WRITEABLE callback, you must check this after every write and bail if
1014 * set, ask for a new writeable callback and continue writing from there.
1016 * This is never set at the start of a writeable callback, but any write
1021 lws_partial_buffered(struct lws *wsi)
1023 return !!wsi->trunc_len;
1026 void lws_set_protocol_write_pending(struct lws *wsi,
1027 enum lws_pending_protocol_send pend)
1029 lwsl_info("setting pps %d\n", pend);
1032 lwsl_err("pps overwrite\n");
1034 lws_rx_flow_control(wsi, 0);
1035 lws_callback_on_writable(wsi);
1039 lws_get_peer_write_allowance(struct lws *wsi)
1041 #ifdef LWS_USE_HTTP2
1042 /* only if we are using HTTP2 on this connection */
1043 if (wsi->mode != LWSCM_HTTP2_SERVING)
1045 /* user is only interested in how much he can send, or that he can't */
1046 if (wsi->u.http2.tx_credit <= 0)
1049 return wsi->u.http2.tx_credit;
1057 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1059 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1060 memset(&wsi->u, 0, sizeof(wsi->u));
1064 LWS_VISIBLE struct lws_plat_file_ops *
1065 lws_get_fops(struct lws_context *context)
1067 return &context->fops;
1070 LWS_VISIBLE LWS_EXTERN struct lws_context *
1071 lws_get_context(const struct lws *wsi)
1073 return wsi->context;
1076 LWS_VISIBLE LWS_EXTERN int
1077 lws_get_count_threads(struct lws_context *context)
1079 return context->count_threads;
1082 LWS_VISIBLE LWS_EXTERN void *
1083 lws_wsi_user(struct lws *wsi)
1085 return wsi->user_space;
1088 LWS_VISIBLE LWS_EXTERN void
1089 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1090 unsigned char *buf, size_t len)
1092 unsigned char *p, *start;
1093 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1095 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1097 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1099 *p++ = (((int)status) >> 8) & 0xff;
1100 *p++ = ((int)status) & 0xff;
1103 while (len-- && p < start + budget)
1106 wsi->u.ws.close_in_ping_buffer_len = p - start;
1110 _lws_rx_flow_control(struct lws *wsi)
1112 /* there is no pending change */
1113 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1114 lwsl_debug("%s: no pending change\n", __func__);
1118 /* stuff is still buffered, not ready to really accept new input */
1119 if (wsi->rxflow_buffer) {
1120 /* get ourselves called back to deal with stashed buffer */
1121 lws_callback_on_writable(wsi);
1125 /* pending is cleared, we can change rxflow state */
1127 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1129 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1130 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1132 /* adjust the pollfd for this wsi */
1134 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1135 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1136 lwsl_info("%s: fail\n", __func__);
1140 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1147 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1149 static const unsigned char e0f4[] = {
1150 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1151 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1152 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1153 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1154 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1155 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1156 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1157 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1158 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1159 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1160 0x80 | ((4 - 1) << 2) | 1, /* ea */
1161 0x80 | ((4 - 1) << 2) | 1, /* eb */
1162 0x80 | ((4 - 1) << 2) | 1, /* ec */
1163 0x80 | ((2 - 1) << 2) | 1, /* ed */
1164 0x80 | ((4 - 1) << 2) | 1, /* ee */
1165 0x80 | ((4 - 1) << 2) | 1, /* ef */
1166 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1167 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1168 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1169 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1170 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1173 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1174 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1176 unsigned char s = *state;
1179 unsigned char c = *buf++;
1183 if (c < 0xc2 || c > 0xf4)
1186 s = 0x80 | ((4 - 1) << 2);
1191 if (c < (s & 0xf0) ||
1192 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1194 s = e0f4[21 + (s & 3)];
1204 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1205 * Notice it does so by dropping '\0' into input string
1206 * and the leading / on the path is consequently lost
1208 * @p: incoming uri string.. will get written to
1209 * @prot: result pointer for protocol part (https://)
1210 * @ads: result pointer for address part
1211 * @port: result pointer for port part
1212 * @path: result pointer for path part
1215 LWS_VISIBLE LWS_EXTERN int
1216 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1220 static const char *slash = "/";
1222 /* cut up the location into address, port and path */
1224 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1235 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1237 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1240 while (*p && *p != ':' && *p != '/')
1245 while (*p && *p != '/')
1258 #ifdef LWS_NO_EXTENSIONS
1260 /* we need to provide dummy callbacks for internal exts
1261 * so user code runs when faced with a lib compiled with
1262 * extensions disabled.
1266 lws_extension_callback_pm_deflate(struct lws_context *context,
1267 const struct lws_extension *ext,
1269 enum lws_extension_callback_reasons reason,
1270 void *user, void *in, size_t len)