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);
56 * These union members have an ah at the start
58 * struct _lws_http_mode_related http;
59 * struct _lws_http2_related http2;
60 * struct _lws_header_related hdr;
62 * basically ws-related union member does not
64 if (wsi->mode != LWSCM_WS_CLIENT &&
65 wsi->mode != LWSCM_WS_SERVING)
66 lws_free_header_table(wsi);
72 lws_remove_from_timeout_list(struct lws *wsi)
74 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
76 if (!wsi->timeout_list_prev)
80 if (wsi->timeout_list)
81 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
82 *wsi->timeout_list_prev = wsi->timeout_list;
84 wsi->timeout_list_prev = NULL;
85 wsi->timeout_list = NULL;
90 * lws_set_timeout() - marks the wsi as subject to a timeout
92 * You will not need this unless you are doing something special
94 * @wsi: Websocket connection instance
95 * @reason: timeout reason
96 * @secs: how many seconds
100 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
102 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
109 if (!wsi->pending_timeout && reason) {
110 wsi->timeout_list = pt->timeout_list;
111 if (wsi->timeout_list)
112 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
113 wsi->timeout_list_prev = &pt->timeout_list;
114 *wsi->timeout_list_prev = wsi;
117 wsi->pending_timeout_limit = now + secs;
118 wsi->pending_timeout = reason;
123 lws_remove_from_timeout_list(wsi);
127 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
129 struct lws_context *context;
130 struct lws_context_per_thread *pt;
132 struct lws_tokens eff_buf;
137 context = wsi->context;
138 pt = &context->pt[(int)wsi->tsi];
140 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
141 wsi->u.http.fd != LWS_INVALID_FILE) {
142 lwsl_debug("closing http file\n");
143 lws_plat_file_close(wsi, wsi->u.http.fd);
144 wsi->u.http.fd = LWS_INVALID_FILE;
145 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
146 wsi->user_space, NULL, 0);
148 if (wsi->socket_is_permanently_unusable ||
149 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
150 wsi->state == LWSS_SHUTDOWN)
151 goto just_kill_connection;
153 wsi->state_pre_close = wsi->state;
155 switch (wsi->state_pre_close) {
156 case LWSS_DEAD_SOCKET:
159 /* we tried the polite way... */
160 case LWSS_AWAITING_CLOSE_ACK:
161 goto just_kill_connection;
163 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
164 if (wsi->trunc_len) {
165 lws_callback_on_writable(wsi);
168 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
169 goto just_kill_connection;
171 if (wsi->trunc_len) {
172 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
173 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
174 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
180 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
181 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
182 goto just_kill_connection;
184 if (wsi->mode == LWSCM_HTTP_SERVING)
185 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
186 wsi->user_space, NULL, 0);
189 * are his extensions okay with him closing? Eg he might be a mux
190 * parent and just his ch1 aspect is closing?
193 if (lws_ext_cb_active(wsi,
194 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
195 lwsl_ext("extension vetoed close\n");
200 * flush any tx pending from extensions, since we may send close packet
201 * if there are problems with send, just nuke the connection
206 eff_buf.token = NULL;
207 eff_buf.token_len = 0;
209 /* show every extension the new incoming data */
211 m = lws_ext_cb_active(wsi,
212 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
214 lwsl_ext("Extension reports fatal error\n");
215 goto just_kill_connection;
219 * at least one extension told us he has more
220 * to spill, so we will go around again after
224 /* assuming they left us something to send, send it */
226 if (eff_buf.token_len)
227 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
228 eff_buf.token_len) !=
230 lwsl_debug("close: ext spill failed\n");
231 goto just_kill_connection;
236 * signal we are closing, lws_write will
237 * add any necessary version-specific stuff. If the write fails,
238 * no worries we are closing anyway. If we didn't initiate this
239 * close, then our state has been changed to
240 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
242 * Likewise if it's a second call to close this connection after we
243 * sent the close indication to the peer already, we are in state
244 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
247 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
248 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
249 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
250 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
251 lwsl_debug("sending close indication...\n");
253 /* if no prepared close reason, use 1000 and no aux data */
254 if (!wsi->u.ws.close_in_ping_buffer_len) {
255 wsi->u.ws.close_in_ping_buffer_len = 2;
256 wsi->u.ws.ping_payload_buf[LWS_PRE] =
257 (reason >> 16) & 0xff;
258 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
262 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
263 wsi->u.ws.close_in_ping_buffer_len,
267 * we have sent a nice protocol level indication we
268 * now wish to close, we should not send anything more
270 wsi->state = LWSS_AWAITING_CLOSE_ACK;
273 * ...and we should wait for a reply for a bit
276 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
277 lwsl_debug("sent close indication, awaiting ack\n");
282 lwsl_info("close: sending close packet failed, hanging up\n");
284 /* else, the send failed and we should just hang up */
287 just_kill_connection:
291 * Testing with ab shows that we have to stage the socket close when
292 * the system is under stress... shutdown any further TX, change the
293 * state to one that won't emit anything more, and wait with a timeout
294 * for the POLLIN to show a zero-size rx before coming back and doing
297 if (wsi->state != LWSS_SHUTDOWN) {
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,
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;
407 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
409 n = compatible_close(wsi->sock);
411 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
414 compatible_close(wsi->sock);
416 wsi->sock = LWS_SOCK_INVALID;
419 /* outermost destroy notification for wsi (user_space still intact) */
420 context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
421 wsi->user_space, NULL, 0);
428 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
432 ipv6 = LWS_IPV6_ENABLED(context);
436 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
441 lws_get_addresses(struct lws_context *context, void *ads, char *name,
442 int name_len, char *rip, int rip_len)
445 struct addrinfo ai, *res;
446 struct sockaddr_in addr4;
451 addr4.sin_family = AF_UNSPEC;
454 if (LWS_IPV6_ENABLED(context)) {
455 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
456 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
460 // Strip off the IPv4 to IPv6 header if one exists
461 if (strncmp(rip, "::ffff:", 7) == 0)
462 memmove(rip, rip + 7, strlen(rip) - 6);
464 getnameinfo((struct sockaddr *)ads,
465 sizeof(struct sockaddr_in6), name,
466 name_len, NULL, 0, 0);
472 struct addrinfo *result;
474 memset(&ai, 0, sizeof ai);
475 ai.ai_family = PF_UNSPEC;
476 ai.ai_socktype = SOCK_STREAM;
477 ai.ai_flags = AI_CANONNAME;
479 if (getnameinfo((struct sockaddr *)ads,
480 sizeof(struct sockaddr_in),
481 name, name_len, NULL, 0, 0))
487 if (getaddrinfo(name, NULL, &ai, &result))
491 while (addr4.sin_family == AF_UNSPEC && res) {
492 switch (res->ai_family) {
494 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
495 addr4.sin_family = AF_INET;
501 freeaddrinfo(result);
504 if (addr4.sin_family == AF_UNSPEC)
507 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
524 * lws_get_peer_addresses() - Get client address information
525 * @wsi: Local struct lws associated with
526 * @fd: Connection socket descriptor
527 * @name: Buffer to take client address name
528 * @name_len: Length of client address name buffer
529 * @rip: Buffer to take client address IP dotted quad
530 * @rip_len: Length of client address IP buffer
532 * This function fills in @name and @rip with the name and IP of
533 * the client connected with socket descriptor @fd. Names may be
534 * truncated if there is not enough room. If either cannot be
535 * determined, they will be returned as valid zero-length strings.
539 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
540 int name_len, char *rip, int rip_len)
545 struct sockaddr_in6 sin6;
547 struct sockaddr_in sin4;
548 struct lws_context *context = wsi->context;
555 lws_latency_pre(context, wsi);
558 if (LWS_IPV6_ENABLED(context)) {
568 if (getpeername(fd, p, &len) < 0) {
569 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
573 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
576 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
588 * lws_context_user() - get the user data associated with the context
589 * @context: Websocket context
591 * This returns the optional user allocation that can be attached to
592 * the context the sockets live in at context_create time. It's a way
593 * to let all sockets serviced in the same context share data without
594 * using globals statics in the user code.
597 lws_context_user(struct lws_context *context)
599 return context->user_space;
604 * lws_callback_all_protocol() - Callback all connections using
605 * the given protocol with the given reason
607 * @protocol: Protocol whose connections will get callbacks
608 * @reason: Callback reason index
612 lws_callback_all_protocol(struct lws_context *context,
613 const struct lws_protocols *protocol, int reason)
615 struct lws_context_per_thread *pt = &context->pt[0];
616 unsigned int n, m = context->count_threads;
620 for (n = 0; n < pt->fds_count; n++) {
621 wsi = wsi_from_fd(context, pt->fds[n].fd);
624 if (wsi->protocol == protocol)
625 protocol->callback(wsi, reason, wsi->user_space,
637 * lws_get_socket_fd() - returns the socket file descriptor
639 * You will not need this unless you are doing something special
641 * @wsi: Websocket connection instance
645 lws_get_socket_fd(struct lws *wsi)
654 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
655 int ret, int completed)
657 unsigned long long u;
660 u = time_in_microseconds();
663 wsi->latency_start = u;
664 if (!wsi->action_start)
665 wsi->action_start = u;
669 if (wsi->action_start == wsi->latency_start)
671 "Completion first try lat %lluus: %p: ret %d: %s\n",
672 u - wsi->latency_start,
673 (void *)wsi, ret, action);
676 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
677 u - wsi->action_start,
678 u - wsi->latency_start,
679 (void *)wsi, ret, action);
680 wsi->action_start = 0;
682 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
683 u - wsi->latency_start, (void *)wsi, ret, action);
685 if (u - wsi->latency_start > context->worst_latency) {
686 context->worst_latency = u - wsi->latency_start;
687 strcpy(context->worst_latency_info, buf);
689 lwsl_latency("%s", buf);
696 * lws_rx_flow_control() - Enable and disable socket servicing for
699 * If the output side of a server process becomes choked, this allows flow
700 * control for the input side.
702 * @wsi: Websocket connection instance to get callback for
703 * @enable: 0 = disable read servicing for this connection, 1 = enable
707 lws_rx_flow_control(struct lws *wsi, int enable)
709 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
712 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
713 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
719 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
721 * When the user server code realizes it can accept more input, it can
722 * call this to have the RX flow restriction removed from all connections using
723 * the given protocol.
725 * @protocol: all connections using this protocol will be allowed to receive
729 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
730 const struct lws_protocols *protocol)
732 const struct lws_context_per_thread *pt = &context->pt[0];
734 unsigned int n, m = context->count_threads;
737 for (n = 0; n < pt->fds_count; n++) {
738 wsi = wsi_from_fd(context, pt->fds[n].fd);
741 if (wsi->protocol == protocol)
742 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
750 * lws_canonical_hostname() - returns this host's hostname
752 * This is typically used by client code to fill in the host parameter
753 * when making a client connection. You can only call it after the context
756 * @context: Websocket context
758 LWS_VISIBLE extern const char *
759 lws_canonical_hostname(struct lws_context *context)
761 return (const char *)context->canonical_hostname;
764 int user_callback_handle_rxflow(lws_callback_function callback_function,
766 enum lws_callback_reasons reason, void *user,
767 void *in, size_t len)
771 n = callback_function(wsi, reason, user, in, len);
773 n = _lws_rx_flow_control(wsi);
780 * lws_set_proxy() - Setups proxy to lws_context.
781 * @context: pointer to struct lws_context you want set proxy to
782 * @proxy: pointer to c string containing proxy in format address:port
784 * Returns 0 if proxy string was parsed and proxy was setup.
785 * Returns -1 if @proxy is NULL or has incorrect format.
787 * This is only required if your OS does not provide the http_proxy
788 * environment variable (eg, OSX)
790 * IMPORTANT! You should call this function right after creation of the
791 * lws_context and before call to connect. If you call this
792 * function after connect behavior is undefined.
793 * This function will override proxy settings made on lws_context
794 * creation with genenv() call.
798 lws_set_proxy(struct lws_context *context, const char *proxy)
806 p = strchr(proxy, '@');
807 if (p) { /* auth is around */
809 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
812 strncpy(authstring, proxy, p - proxy);
813 // null termination not needed on input
814 if (lws_b64_encode_string(authstring, (p - proxy),
815 context->proxy_basic_auth_token,
816 sizeof context->proxy_basic_auth_token) < 0)
819 lwsl_notice(" Proxy auth in use\n");
823 context->proxy_basic_auth_token[0] = '\0';
825 strncpy(context->http_proxy_address, proxy,
826 sizeof(context->http_proxy_address) - 1);
827 context->http_proxy_address[
828 sizeof(context->http_proxy_address) - 1] = '\0';
830 p = strchr(context->http_proxy_address, ':');
831 if (!p && !context->http_proxy_port) {
832 lwsl_err("http_proxy needs to be ads:port\n");
838 context->http_proxy_port = atoi(p + 1);
842 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
843 context->http_proxy_port);
848 lwsl_err("proxy auth too long\n");
854 * lws_get_protocol() - Returns a protocol pointer from a websocket
856 * @wsi: pointer to struct websocket you want to know the protocol of
859 * Some apis can act on all live connections of a given protocol,
860 * this is how you can get a pointer to the active protocol if needed.
863 LWS_VISIBLE const struct lws_protocols *
864 lws_get_protocol(struct lws *wsi)
866 return wsi->protocol;
870 lws_is_final_fragment(struct lws *wsi)
872 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
873 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
874 wsi->u.ws.rx_draining_ext);
875 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
878 LWS_VISIBLE unsigned char
879 lws_get_reserved_bits(struct lws *wsi)
881 return wsi->u.ws.rsv;
885 lws_ensure_user_space(struct lws *wsi)
887 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
891 /* allocate the per-connection user memory (if any) */
893 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
894 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
895 if (wsi->user_space == NULL) {
896 lwsl_err("Out of memory for conn user space\n");
900 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
901 __func__, wsi, wsi->protocol->per_session_data_size,
906 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
908 unsigned long long now;
913 for (n = 0; n < LLL_COUNT; n++) {
914 if (level != (1 << n))
916 now = time_in_microseconds() / 100;
917 sprintf(buf, "[%llu:%04d] %s: ",
918 (unsigned long long) now / 10000,
919 (int)(now % 10000), log_level_names[n]);
923 fprintf(stderr, "%s%s", buf, line);
926 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
930 if (!(log_level & filter))
933 vsnprintf(buf, sizeof(buf), format, vl);
934 buf[sizeof(buf) - 1] = '\0';
936 lwsl_emit(filter, buf);
939 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
943 va_start(ap, format);
944 _lws_logv(filter, format, ap);
949 * lws_set_log_level() - Set the logging bitfield
950 * @level: OR together the LLL_ debug contexts you want output from
951 * @log_emit_function: NULL to leave it as it is, or a user-supplied
952 * function to perform log string emission instead of
953 * the default stderr one.
955 * log level defaults to "err", "warn" and "notice" contexts enabled and
956 * emission on stderr.
959 LWS_VISIBLE void lws_set_log_level(int level,
960 void (*func)(int level, const char *line))
968 * lws_use_ssl() - Find out if connection is using SSL
969 * @wsi: websocket connection to check
971 * Returns 0 if the connection is not using SSL, 1 if using SSL and
972 * using verified cert, and 2 if using SSL but the cert was not
973 * checked (appears for client wsi told to skip check on connection)
976 lws_is_ssl(struct lws *wsi)
978 #ifdef LWS_OPENSSL_SUPPORT
987 * lws_partial_buffered() - find out if lws buffered the last write
988 * @wsi: websocket connection to check
990 * Returns 1 if you cannot use lws_write because the last
991 * write on this connection is still buffered, and can't be cleared without
992 * returning to the service loop and waiting for the connection to be
995 * If you will try to do >1 lws_write call inside a single
996 * WRITEABLE callback, you must check this after every write and bail if
997 * set, ask for a new writeable callback and continue writing from there.
999 * This is never set at the start of a writeable callback, but any write
1004 lws_partial_buffered(struct lws *wsi)
1006 return !!wsi->trunc_len;
1009 void lws_set_protocol_write_pending(struct lws *wsi,
1010 enum lws_pending_protocol_send pend)
1012 lwsl_info("setting pps %d\n", pend);
1015 lwsl_err("pps overwrite\n");
1017 lws_rx_flow_control(wsi, 0);
1018 lws_callback_on_writable(wsi);
1022 lws_get_peer_write_allowance(struct lws *wsi)
1024 #ifdef LWS_USE_HTTP2
1025 /* only if we are using HTTP2 on this connection */
1026 if (wsi->mode != LWSCM_HTTP2_SERVING)
1028 /* user is only interested in how much he can send, or that he can't */
1029 if (wsi->u.http2.tx_credit <= 0)
1032 return wsi->u.http2.tx_credit;
1040 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1042 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1043 memset(&wsi->u, 0, sizeof(wsi->u));
1047 LWS_VISIBLE struct lws_plat_file_ops *
1048 lws_get_fops(struct lws_context *context)
1050 return &context->fops;
1053 LWS_VISIBLE LWS_EXTERN struct lws_context *
1054 lws_get_context(const struct lws *wsi)
1056 return wsi->context;
1059 LWS_VISIBLE LWS_EXTERN int
1060 lws_get_count_threads(struct lws_context *context)
1062 return context->count_threads;
1065 LWS_VISIBLE LWS_EXTERN void *
1066 lws_wsi_user(struct lws *wsi)
1068 return wsi->user_space;
1071 LWS_VISIBLE LWS_EXTERN void
1072 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1073 unsigned char *buf, size_t len)
1075 unsigned char *p, *start;
1076 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1078 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1080 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1082 *p++ = (((int)status) >> 8) & 0xff;
1083 *p++ = ((int)status) & 0xff;
1086 while (len-- && p < start + budget)
1089 wsi->u.ws.close_in_ping_buffer_len = p - start;
1093 _lws_rx_flow_control(struct lws *wsi)
1095 /* there is no pending change */
1096 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1097 lwsl_debug("%s: no pending change\n", __func__);
1101 /* stuff is still buffered, not ready to really accept new input */
1102 if (wsi->rxflow_buffer) {
1103 /* get ourselves called back to deal with stashed buffer */
1104 lws_callback_on_writable(wsi);
1108 /* pending is cleared, we can change rxflow state */
1110 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1112 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1113 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1115 /* adjust the pollfd for this wsi */
1117 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1118 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1119 lwsl_info("%s: fail\n", __func__);
1123 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1130 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1132 static const unsigned char e0f4[] = {
1133 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1134 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1135 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1136 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1137 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1138 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1139 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1140 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1141 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1142 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1143 0x80 | ((4 - 1) << 2) | 1, /* ea */
1144 0x80 | ((4 - 1) << 2) | 1, /* eb */
1145 0x80 | ((4 - 1) << 2) | 1, /* ec */
1146 0x80 | ((2 - 1) << 2) | 1, /* ed */
1147 0x80 | ((4 - 1) << 2) | 1, /* ee */
1148 0x80 | ((4 - 1) << 2) | 1, /* ef */
1149 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1150 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1151 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1152 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1153 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1156 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1157 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1159 unsigned char s = *state;
1162 unsigned char c = *buf++;
1166 if (c < 0xc2 || c > 0xf4)
1169 s = 0x80 | ((4 - 1) << 2);
1174 if (c < (s & 0xf0) ||
1175 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1177 s = e0f4[21 + (s & 3)];
1187 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1188 * Notice it does so by dropping '\0' into input string
1189 * and the leading / on the path is consequently lost
1191 * @p: incoming uri string.. will get written to
1192 * @prot: result pointer for protocol part (https://)
1193 * @ads: result pointer for address part
1194 * @port: result pointer for port part
1195 * @path: result pointer for path part
1198 LWS_VISIBLE LWS_EXTERN int
1199 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1203 static const char *slash = "/";
1205 /* cut up the location into address, port and path */
1207 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1218 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1220 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1223 while (*p && *p != ':' && *p != '/')
1228 while (*p && *p != '/')
1241 #ifdef LWS_NO_EXTENSIONS
1243 /* we need to provide dummy callbacks for internal exts
1244 * so user code runs when faced with a lib compiled with
1245 * extensions disabled.
1249 lws_extension_callback_pm_deflate(struct lws_context *context,
1250 const struct lws_extension *ext,
1252 enum lws_extension_callback_reasons reason,
1253 void *user, void *in, size_t len)