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 #if defined(WIN32) || defined(_WIN32)
33 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
34 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
36 static const char * const log_level_names[] = {
50 lws_free_wsi(struct lws *wsi)
55 /* Protocol user data may be allocated either internally by lws
56 * or by specified the user.
57 * We should only free what we allocated. */
58 if (wsi->protocol && wsi->protocol->per_session_data_size &&
59 wsi->user_space && !wsi->user_space_externally_allocated)
60 lws_free(wsi->user_space);
62 lws_free_set_NULL(wsi->rxflow_buffer);
63 lws_free_set_NULL(wsi->trunc_alloc);
66 /* we're closing, losing some rx is OK */
67 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
69 /* we may not have an ah, but may be on the waiting list... */
70 lws_header_table_detach(wsi, 0);
72 wsi->context->count_wsi_allocated--;
73 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
74 wsi->context->count_wsi_allocated);
80 lws_remove_from_timeout_list(struct lws *wsi)
82 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
84 if (!wsi->timeout_list_prev) /* ie, not part of the list */
88 /* if we have a next guy, set his prev to our prev */
89 if (wsi->timeout_list)
90 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
91 /* set our prev guy to our next guy instead of us */
92 *wsi->timeout_list_prev = wsi->timeout_list;
94 /* we're out of the list, we should not point anywhere any more */
95 wsi->timeout_list_prev = NULL;
96 wsi->timeout_list = NULL;
101 * lws_set_timeout() - marks the wsi as subject to a timeout
103 * You will not need this unless you are doing something special
105 * @wsi: Websocket connection instance
106 * @reason: timeout reason
107 * @secs: how many seconds
111 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
113 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
120 if (reason && !wsi->timeout_list_prev) {
121 /* our next guy is current first guy */
122 wsi->timeout_list = pt->timeout_list;
123 /* if there is a next guy, set his prev ptr to our next ptr */
124 if (wsi->timeout_list)
125 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
126 /* our prev ptr is first ptr */
127 wsi->timeout_list_prev = &pt->timeout_list;
128 /* set the first guy to be us */
129 *wsi->timeout_list_prev = wsi;
132 lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
133 wsi->pending_timeout_limit = now + secs;
134 wsi->pending_timeout = reason;
139 lws_remove_from_timeout_list(wsi);
143 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
145 struct lws_context_per_thread *pt;
146 struct lws **pwsi, *wsi1, *wsi2;
147 struct lws_context *context;
148 struct lws_tokens eff_buf;
154 context = wsi->context;
155 pt = &context->pt[(int)wsi->tsi];
157 /* if we have children, close them first */
158 if (wsi->child_list) {
159 wsi2 = wsi->child_list;
161 lwsl_notice("%s: closing %p: close child %p\n",
162 __func__, wsi, wsi2);
163 wsi1 = wsi2->sibling_list;
164 lws_close_free_wsi(wsi2, reason);
170 if (wsi->mode == LWSCM_CGI) {
171 /* we are not a network connection, but a handler for CGI io */
172 if (wsi->parent && wsi->parent->cgi)
173 /* end the binding between us and master */
174 wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
175 wsi->socket_is_permanently_unusable = 1;
177 goto just_kill_connection;
181 /* we have a cgi going, we must kill it */
182 wsi->cgi->being_closed = 1;
187 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
188 wsi->u.http.fd != LWS_INVALID_FILE) {
189 lwsl_debug("closing http file\n");
190 lws_plat_file_close(wsi, wsi->u.http.fd);
191 wsi->u.http.fd = LWS_INVALID_FILE;
192 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
193 wsi->user_space, NULL, 0);
195 if (wsi->socket_is_permanently_unusable ||
196 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
197 wsi->state == LWSS_SHUTDOWN)
198 goto just_kill_connection;
200 wsi->state_pre_close = wsi->state;
202 switch (wsi->state_pre_close) {
203 case LWSS_DEAD_SOCKET:
206 /* we tried the polite way... */
207 case LWSS_AWAITING_CLOSE_ACK:
208 goto just_kill_connection;
210 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
211 if (wsi->trunc_len) {
212 lws_callback_on_writable(wsi);
215 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
216 goto just_kill_connection;
218 if (wsi->trunc_len) {
219 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
220 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
221 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
227 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
228 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
229 goto just_kill_connection;
231 if (wsi->mode == LWSCM_HTTP_SERVING)
232 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
233 wsi->user_space, NULL, 0);
234 if (wsi->mode == LWSCM_HTTP_CLIENT)
235 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
236 wsi->user_space, NULL, 0);
239 * are his extensions okay with him closing? Eg he might be a mux
240 * parent and just his ch1 aspect is closing?
243 if (lws_ext_cb_active(wsi,
244 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
245 lwsl_ext("extension vetoed close\n");
250 * flush any tx pending from extensions, since we may send close packet
251 * if there are problems with send, just nuke the connection
256 eff_buf.token = NULL;
257 eff_buf.token_len = 0;
259 /* show every extension the new incoming data */
261 m = lws_ext_cb_active(wsi,
262 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
264 lwsl_ext("Extension reports fatal error\n");
265 goto just_kill_connection;
269 * at least one extension told us he has more
270 * to spill, so we will go around again after
274 /* assuming they left us something to send, send it */
276 if (eff_buf.token_len)
277 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
278 eff_buf.token_len) !=
280 lwsl_debug("close: ext spill failed\n");
281 goto just_kill_connection;
286 * signal we are closing, lws_write will
287 * add any necessary version-specific stuff. If the write fails,
288 * no worries we are closing anyway. If we didn't initiate this
289 * close, then our state has been changed to
290 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
292 * Likewise if it's a second call to close this connection after we
293 * sent the close indication to the peer already, we are in state
294 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
297 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
298 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
299 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
300 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
301 lwsl_debug("sending close indication...\n");
303 /* if no prepared close reason, use 1000 and no aux data */
304 if (!wsi->u.ws.close_in_ping_buffer_len) {
305 wsi->u.ws.close_in_ping_buffer_len = 2;
306 wsi->u.ws.ping_payload_buf[LWS_PRE] =
307 (reason >> 16) & 0xff;
308 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
312 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
313 wsi->u.ws.close_in_ping_buffer_len,
317 * we have sent a nice protocol level indication we
318 * now wish to close, we should not send anything more
320 wsi->state = LWSS_AWAITING_CLOSE_ACK;
323 * ...and we should wait for a reply for a bit
326 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
327 lwsl_debug("sent close indication, awaiting ack\n");
332 lwsl_info("close: sending close packet failed, hanging up\n");
334 /* else, the send failed and we should just hang up */
337 just_kill_connection:
339 /* detach ourselves from parent's child list */
340 pwsi = &wsi->parent->child_list;
343 lwsl_notice("%s: detach %p from parent %p\n",
344 __func__, wsi, wsi->parent);
345 *pwsi = wsi->sibling_list;
348 pwsi = &(*pwsi)->sibling_list;
351 lwsl_err("%s: failed to detach from parent\n",
357 * Testing with ab shows that we have to stage the socket close when
358 * the system is under stress... shutdown any further TX, change the
359 * state to one that won't emit anything more, and wait with a timeout
360 * for the POLLIN to show a zero-size rx before coming back and doing
363 if (wsi->state != LWSS_SHUTDOWN &&
364 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
365 !wsi->socket_is_permanently_unusable) {
366 lwsl_info("%s: shutting down connection: %p\n", __func__, wsi);
367 n = shutdown(wsi->sock, SHUT_WR);
369 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
371 // This causes problems with disconnection when the events are half closing connection
372 // FD_READ | FD_CLOSE (33)
374 /* libuv: no event available to guarantee completion */
375 if (!LWS_LIBUV_ENABLED(context)) {
377 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
378 wsi->state = LWSS_SHUTDOWN;
379 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
380 context->timeout_secs);
387 lwsl_info("%s: real just_kill_connection: %p\n", __func__, wsi);
390 * we won't be servicing or receiving anything further from this guy
391 * delete socket from the internal poll list if still present
393 lws_ssl_remove_wsi_from_buffered_list(wsi);
394 lws_remove_from_timeout_list(wsi);
396 /* checking return redundant since we anyway close */
397 remove_wsi_socket_from_fds(wsi);
399 wsi->state = LWSS_DEAD_SOCKET;
401 lws_free_set_NULL(wsi->rxflow_buffer);
403 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
404 wsi->mode == LWSCM_WS_SERVING ||
405 wsi->mode == LWSCM_WS_CLIENT) {
407 if (wsi->u.ws.rx_draining_ext) {
408 struct lws **w = &pt->rx_draining_ext_list;
410 wsi->u.ws.rx_draining_ext = 0;
411 /* remove us from context draining ext list */
414 *w = wsi->u.ws.rx_draining_ext_list;
417 w = &((*w)->u.ws.rx_draining_ext_list);
419 wsi->u.ws.rx_draining_ext_list = NULL;
422 if (wsi->u.ws.tx_draining_ext) {
423 struct lws **w = &pt->tx_draining_ext_list;
425 wsi->u.ws.tx_draining_ext = 0;
426 /* remove us from context draining ext list */
429 *w = wsi->u.ws.tx_draining_ext_list;
432 w = &((*w)->u.ws.tx_draining_ext_list);
434 wsi->u.ws.tx_draining_ext_list = NULL;
436 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
438 if (wsi->trunc_alloc)
439 /* not going to be completed... nuke it */
440 lws_free_set_NULL(wsi->trunc_alloc);
442 wsi->u.ws.ping_payload_len = 0;
443 wsi->u.ws.ping_pending_flag = 0;
446 /* tell the user it's all over for this guy */
448 if (wsi->protocol && wsi->protocol->callback &&
449 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
450 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
451 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
452 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
453 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
454 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
455 lwsl_debug("calling back CLOSED\n");
456 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
457 wsi->user_space, NULL, 0);
458 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
459 lwsl_debug("calling back CLOSED_HTTP\n");
460 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
461 wsi->user_space, NULL, 0 );
462 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
463 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
464 lwsl_debug("Connection closed before server reply\n");
465 context->protocols[0].callback(wsi,
466 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
467 wsi->user_space, NULL, 0);
469 lwsl_debug("not calling back closed mode=%d state=%d\n",
470 wsi->mode, wsi->state_pre_close);
472 /* deallocate any active extension contexts */
474 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
475 lwsl_warn("extension destruction failed\n");
477 * inform all extensions in case they tracked this guy out of band
478 * even though not active on him specifically
480 if (lws_ext_cb_all_exts(context, wsi,
481 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
482 lwsl_warn("ext destroy wsi failed\n");
484 wsi->socket_is_permanently_unusable = 1;
487 if (LWS_LIBUV_ENABLED(context)) {
488 /* libuv has to do his own close handle processing asynchronously */
489 lws_libuv_closehandle(wsi);
495 lws_close_free_wsi_final(wsi);
499 lws_close_free_wsi_final(struct lws *wsi)
503 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
505 n = compatible_close(wsi->sock);
507 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
510 compatible_close(wsi->sock);
512 wsi->sock = LWS_SOCK_INVALID;
515 /* outermost destroy notification for wsi (user_space still intact) */
516 wsi->context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
517 wsi->user_space, NULL, 0);
524 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
528 ipv6 = LWS_IPV6_ENABLED(context);
532 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
537 lws_get_addresses(struct lws_context *context, void *ads, char *name,
538 int name_len, char *rip, int rip_len)
541 struct addrinfo ai, *res;
542 struct sockaddr_in addr4;
547 addr4.sin_family = AF_UNSPEC;
550 if (LWS_IPV6_ENABLED(context)) {
551 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
552 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
556 // Strip off the IPv4 to IPv6 header if one exists
557 if (strncmp(rip, "::ffff:", 7) == 0)
558 memmove(rip, rip + 7, strlen(rip) - 6);
560 getnameinfo((struct sockaddr *)ads,
561 sizeof(struct sockaddr_in6), name,
562 name_len, NULL, 0, 0);
568 struct addrinfo *result;
570 memset(&ai, 0, sizeof ai);
571 ai.ai_family = PF_UNSPEC;
572 ai.ai_socktype = SOCK_STREAM;
573 ai.ai_flags = AI_CANONNAME;
575 if (getnameinfo((struct sockaddr *)ads,
576 sizeof(struct sockaddr_in),
577 name, name_len, NULL, 0, 0))
583 if (getaddrinfo(name, NULL, &ai, &result))
587 while (addr4.sin_family == AF_UNSPEC && res) {
588 switch (res->ai_family) {
590 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
591 addr4.sin_family = AF_INET;
597 freeaddrinfo(result);
600 if (addr4.sin_family == AF_UNSPEC)
603 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
620 * lws_get_peer_addresses() - Get client address information
621 * @wsi: Local struct lws associated with
622 * @fd: Connection socket descriptor
623 * @name: Buffer to take client address name
624 * @name_len: Length of client address name buffer
625 * @rip: Buffer to take client address IP dotted quad
626 * @rip_len: Length of client address IP buffer
628 * This function fills in @name and @rip with the name and IP of
629 * the client connected with socket descriptor @fd. Names may be
630 * truncated if there is not enough room. If either cannot be
631 * determined, they will be returned as valid zero-length strings.
635 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
636 int name_len, char *rip, int rip_len)
641 struct sockaddr_in6 sin6;
643 struct sockaddr_in sin4;
644 struct lws_context *context = wsi->context;
651 lws_latency_pre(context, wsi);
654 if (LWS_IPV6_ENABLED(context)) {
664 if (getpeername(fd, p, &len) < 0) {
665 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
669 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
672 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
684 * lws_context_user() - get the user data associated with the context
685 * @context: Websocket context
687 * This returns the optional user allocation that can be attached to
688 * the context the sockets live in at context_create time. It's a way
689 * to let all sockets serviced in the same context share data without
690 * using globals statics in the user code.
693 lws_context_user(struct lws_context *context)
695 return context->user_space;
700 * lws_callback_all_protocol() - Callback all connections using
701 * the given protocol with the given reason
703 * @protocol: Protocol whose connections will get callbacks
704 * @reason: Callback reason index
708 lws_callback_all_protocol(struct lws_context *context,
709 const struct lws_protocols *protocol, int reason)
711 struct lws_context_per_thread *pt = &context->pt[0];
712 unsigned int n, m = context->count_threads;
716 for (n = 0; n < pt->fds_count; n++) {
717 wsi = wsi_from_fd(context, pt->fds[n].fd);
720 if (wsi->protocol == protocol)
721 protocol->callback(wsi, reason, wsi->user_space,
733 * lws_get_socket_fd() - returns the socket file descriptor
735 * You will not need this unless you are doing something special
737 * @wsi: Websocket connection instance
741 lws_get_socket_fd(struct lws *wsi)
750 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
751 int ret, int completed)
753 unsigned long long u;
756 u = time_in_microseconds();
759 wsi->latency_start = u;
760 if (!wsi->action_start)
761 wsi->action_start = u;
765 if (wsi->action_start == wsi->latency_start)
767 "Completion first try lat %lluus: %p: ret %d: %s\n",
768 u - wsi->latency_start,
769 (void *)wsi, ret, action);
772 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
773 u - wsi->action_start,
774 u - wsi->latency_start,
775 (void *)wsi, ret, action);
776 wsi->action_start = 0;
778 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
779 u - wsi->latency_start, (void *)wsi, ret, action);
781 if (u - wsi->latency_start > context->worst_latency) {
782 context->worst_latency = u - wsi->latency_start;
783 strcpy(context->worst_latency_info, buf);
785 lwsl_latency("%s", buf);
792 * lws_rx_flow_control() - Enable and disable socket servicing for
795 * If the output side of a server process becomes choked, this allows flow
796 * control for the input side.
798 * @wsi: Websocket connection instance to get callback for
799 * @enable: 0 = disable read servicing for this connection, 1 = enable
803 lws_rx_flow_control(struct lws *wsi, int enable)
805 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
808 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
809 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
815 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
817 * When the user server code realizes it can accept more input, it can
818 * call this to have the RX flow restriction removed from all connections using
819 * the given protocol.
821 * @protocol: all connections using this protocol will be allowed to receive
825 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
826 const struct lws_protocols *protocol)
828 const struct lws_context_per_thread *pt = &context->pt[0];
830 unsigned int n, m = context->count_threads;
833 for (n = 0; n < pt->fds_count; n++) {
834 wsi = wsi_from_fd(context, pt->fds[n].fd);
837 if (wsi->protocol == protocol)
838 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
846 * lws_canonical_hostname() - returns this host's hostname
848 * This is typically used by client code to fill in the host parameter
849 * when making a client connection. You can only call it after the context
852 * @context: Websocket context
854 LWS_VISIBLE extern const char *
855 lws_canonical_hostname(struct lws_context *context)
857 return (const char *)context->canonical_hostname;
860 int user_callback_handle_rxflow(lws_callback_function callback_function,
862 enum lws_callback_reasons reason, void *user,
863 void *in, size_t len)
867 n = callback_function(wsi, reason, user, in, len);
869 n = _lws_rx_flow_control(wsi);
876 * lws_set_proxy() - Setups proxy to lws_context.
877 * @context: pointer to struct lws_context you want set proxy to
878 * @proxy: pointer to c string containing proxy in format address:port
880 * Returns 0 if proxy string was parsed and proxy was setup.
881 * Returns -1 if @proxy is NULL or has incorrect format.
883 * This is only required if your OS does not provide the http_proxy
884 * environment variable (eg, OSX)
886 * IMPORTANT! You should call this function right after creation of the
887 * lws_context and before call to connect. If you call this
888 * function after connect behavior is undefined.
889 * This function will override proxy settings made on lws_context
890 * creation with genenv() call.
894 lws_set_proxy(struct lws_context *context, const char *proxy)
902 p = strchr(proxy, '@');
903 if (p) { /* auth is around */
905 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
908 strncpy(authstring, proxy, p - proxy);
909 // null termination not needed on input
910 if (lws_b64_encode_string(authstring, (p - proxy),
911 context->proxy_basic_auth_token,
912 sizeof context->proxy_basic_auth_token) < 0)
915 lwsl_notice(" Proxy auth in use\n");
919 context->proxy_basic_auth_token[0] = '\0';
921 strncpy(context->http_proxy_address, proxy,
922 sizeof(context->http_proxy_address) - 1);
923 context->http_proxy_address[
924 sizeof(context->http_proxy_address) - 1] = '\0';
926 p = strchr(context->http_proxy_address, ':');
927 if (!p && !context->http_proxy_port) {
928 lwsl_err("http_proxy needs to be ads:port\n");
934 context->http_proxy_port = atoi(p + 1);
938 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
939 context->http_proxy_port);
944 lwsl_err("proxy auth too long\n");
950 * lws_get_protocol() - Returns a protocol pointer from a websocket
952 * @wsi: pointer to struct websocket you want to know the protocol of
955 * Some apis can act on all live connections of a given protocol,
956 * this is how you can get a pointer to the active protocol if needed.
959 LWS_VISIBLE const struct lws_protocols *
960 lws_get_protocol(struct lws *wsi)
962 return wsi->protocol;
966 lws_is_final_fragment(struct lws *wsi)
968 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
969 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
970 wsi->u.ws.rx_draining_ext);
971 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
974 LWS_VISIBLE unsigned char
975 lws_get_reserved_bits(struct lws *wsi)
977 return wsi->u.ws.rsv;
981 lws_ensure_user_space(struct lws *wsi)
983 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
987 /* allocate the per-connection user memory (if any) */
989 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
990 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
991 if (wsi->user_space == NULL) {
992 lwsl_err("Out of memory for conn user space\n");
996 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
997 __func__, wsi, wsi->protocol->per_session_data_size,
1003 * lwsl_timestamp: generate logging timestamp string
1005 * @level: logging level
1006 * @p: char * buffer to take timestamp
1009 * returns length written in p
1012 lwsl_timestamp(int level, char *p, int len)
1014 time_t o_now = time(NULL);
1015 unsigned long long now;
1016 struct tm *ptm = NULL;
1024 ptm = localtime(&o_now);
1026 if (localtime_r(&o_now, &tm))
1031 for (n = 0; n < LLL_COUNT; n++) {
1032 if (level != (1 << n))
1034 now = time_in_microseconds() / 100;
1036 n = snprintf(p, len,
1037 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1038 ptm->tm_year + 1900,
1044 (int)(now % 10000), log_level_names[n]);
1046 n = snprintf(p, len, "[%llu:%04d] %s: ",
1047 (unsigned long long) now / 10000,
1048 (int)(now % 10000), log_level_names[n]);
1055 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1059 lwsl_timestamp(level, buf, sizeof(buf));
1061 fprintf(stderr, "%s%s", buf, line);
1064 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1068 if (!(log_level & filter))
1071 vsnprintf(buf, sizeof(buf), format, vl);
1072 buf[sizeof(buf) - 1] = '\0';
1074 lwsl_emit(filter, buf);
1077 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1081 va_start(ap, format);
1082 _lws_logv(filter, format, ap);
1087 * lws_set_log_level() - Set the logging bitfield
1088 * @level: OR together the LLL_ debug contexts you want output from
1089 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1090 * function to perform log string emission instead of
1091 * the default stderr one.
1093 * log level defaults to "err", "warn" and "notice" contexts enabled and
1094 * emission on stderr.
1097 LWS_VISIBLE void lws_set_log_level(int level,
1098 void (*func)(int level, const char *line))
1106 * lws_use_ssl() - Find out if connection is using SSL
1107 * @wsi: websocket connection to check
1109 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1110 * using verified cert, and 2 if using SSL but the cert was not
1111 * checked (appears for client wsi told to skip check on connection)
1114 lws_is_ssl(struct lws *wsi)
1116 #ifdef LWS_OPENSSL_SUPPORT
1117 return wsi->use_ssl;
1125 * lws_partial_buffered() - find out if lws buffered the last write
1126 * @wsi: websocket connection to check
1128 * Returns 1 if you cannot use lws_write because the last
1129 * write on this connection is still buffered, and can't be cleared without
1130 * returning to the service loop and waiting for the connection to be
1133 * If you will try to do >1 lws_write call inside a single
1134 * WRITEABLE callback, you must check this after every write and bail if
1135 * set, ask for a new writeable callback and continue writing from there.
1137 * This is never set at the start of a writeable callback, but any write
1142 lws_partial_buffered(struct lws *wsi)
1144 return !!wsi->trunc_len;
1147 void lws_set_protocol_write_pending(struct lws *wsi,
1148 enum lws_pending_protocol_send pend)
1150 lwsl_info("setting pps %d\n", pend);
1153 lwsl_err("pps overwrite\n");
1155 lws_rx_flow_control(wsi, 0);
1156 lws_callback_on_writable(wsi);
1160 lws_get_peer_write_allowance(struct lws *wsi)
1162 #ifdef LWS_USE_HTTP2
1163 /* only if we are using HTTP2 on this connection */
1164 if (wsi->mode != LWSCM_HTTP2_SERVING)
1166 /* user is only interested in how much he can send, or that he can't */
1167 if (wsi->u.http2.tx_credit <= 0)
1170 return wsi->u.http2.tx_credit;
1178 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1180 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1181 memset(&wsi->u, 0, sizeof(wsi->u));
1185 LWS_VISIBLE struct lws_plat_file_ops *
1186 lws_get_fops(struct lws_context *context)
1188 return &context->fops;
1191 LWS_VISIBLE LWS_EXTERN struct lws_context *
1192 lws_get_context(const struct lws *wsi)
1194 return wsi->context;
1197 LWS_VISIBLE LWS_EXTERN int
1198 lws_get_count_threads(struct lws_context *context)
1200 return context->count_threads;
1203 LWS_VISIBLE LWS_EXTERN void *
1204 lws_wsi_user(struct lws *wsi)
1206 return wsi->user_space;
1209 LWS_VISIBLE LWS_EXTERN struct lws *
1210 lws_get_parent(const struct lws *wsi)
1215 LWS_VISIBLE LWS_EXTERN struct lws *
1216 lws_get_child(const struct lws *wsi)
1218 return wsi->child_list;
1221 LWS_VISIBLE LWS_EXTERN void
1222 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1223 unsigned char *buf, size_t len)
1225 unsigned char *p, *start;
1226 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1228 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1230 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1232 *p++ = (((int)status) >> 8) & 0xff;
1233 *p++ = ((int)status) & 0xff;
1236 while (len-- && p < start + budget)
1239 wsi->u.ws.close_in_ping_buffer_len = p - start;
1243 _lws_rx_flow_control(struct lws *wsi)
1245 /* there is no pending change */
1246 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1247 lwsl_debug("%s: no pending change\n", __func__);
1251 /* stuff is still buffered, not ready to really accept new input */
1252 if (wsi->rxflow_buffer) {
1253 /* get ourselves called back to deal with stashed buffer */
1254 lws_callback_on_writable(wsi);
1258 /* pending is cleared, we can change rxflow state */
1260 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1262 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1263 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1265 /* adjust the pollfd for this wsi */
1267 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1268 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1269 lwsl_info("%s: fail\n", __func__);
1273 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1280 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1282 static const unsigned char e0f4[] = {
1283 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1284 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1285 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1286 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1287 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1288 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1289 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1290 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1291 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1292 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1293 0x80 | ((4 - 1) << 2) | 1, /* ea */
1294 0x80 | ((4 - 1) << 2) | 1, /* eb */
1295 0x80 | ((4 - 1) << 2) | 1, /* ec */
1296 0x80 | ((2 - 1) << 2) | 1, /* ed */
1297 0x80 | ((4 - 1) << 2) | 1, /* ee */
1298 0x80 | ((4 - 1) << 2) | 1, /* ef */
1299 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1300 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1301 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1302 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1303 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1306 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1307 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1309 unsigned char s = *state;
1312 unsigned char c = *buf++;
1316 if (c < 0xc2 || c > 0xf4)
1319 s = 0x80 | ((4 - 1) << 2);
1324 if (c < (s & 0xf0) ||
1325 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1327 s = e0f4[21 + (s & 3)];
1337 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1338 * Notice it does so by dropping '\0' into input string
1339 * and the leading / on the path is consequently lost
1341 * @p: incoming uri string.. will get written to
1342 * @prot: result pointer for protocol part (https://)
1343 * @ads: result pointer for address part
1344 * @port: result pointer for port part
1345 * @path: result pointer for path part
1348 LWS_VISIBLE LWS_EXTERN int
1349 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1353 static const char *slash = "/";
1355 /* cut up the location into address, port and path */
1357 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1368 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1370 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1373 while (*p && *p != ':' && *p != '/')
1378 while (*p && *p != '/')
1391 #ifdef LWS_NO_EXTENSIONS
1393 /* we need to provide dummy callbacks for internal exts
1394 * so user code runs when faced with a lib compiled with
1395 * extensions disabled.
1399 lws_extension_callback_pm_deflate(struct lws_context *context,
1400 const struct lws_extension *ext,
1402 enum lws_extension_callback_reasons reason,
1403 void *user, void *in, size_t len)
1417 LWS_VISIBLE LWS_EXTERN int
1418 lws_is_cgi(struct lws *wsi) {
1429 lws_create_basic_wsi(struct lws_context *context, int tsi)
1431 struct lws *new_wsi;
1433 if ((unsigned int)context->pt[tsi].fds_count ==
1434 context->fd_limit_per_thread - 1) {
1435 lwsl_err("no space for new conn\n");
1439 new_wsi = lws_zalloc(sizeof(struct lws));
1440 if (new_wsi == NULL) {
1441 lwsl_err("Out of memory for new connection\n");
1446 new_wsi->context = context;
1447 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1448 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1450 /* intialize the instance struct */
1452 new_wsi->state = LWSS_CGI;
1453 new_wsi->mode = LWSCM_CGI;
1454 new_wsi->hdr_parsing_completed = 0;
1455 new_wsi->position_in_fds_table = -1;
1458 * these can only be set once the protocol is known
1459 * we set an unestablished connection's protocol pointer
1460 * to the start of the supported list, so it can look
1461 * for matching ones during the handshake
1463 new_wsi->protocol = context->protocols;
1464 new_wsi->user_space = NULL;
1465 new_wsi->ietf_spec_revision = 0;
1466 new_wsi->sock = LWS_SOCK_INVALID;
1467 context->count_wsi_allocated++;
1473 * lws_cgi: spawn network-connected cgi process
1475 * @wsi: connection to own the process
1476 * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1479 LWS_VISIBLE LWS_EXTERN int
1480 lws_cgi(struct lws *wsi, char * const *exec_array, int timeout_secs)
1482 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1483 char *env_array[30], cgi_path[400];
1484 struct lws_cgi *cgi;
1488 * give the master wsi a cgi struct
1491 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1493 lwsl_err("%s: OOM\n", __func__);
1498 cgi->wsi = wsi; /* set cgi's owning wsi */
1500 /* create pipes for [stdin|stdout] and [stderr] */
1502 for (n = 0; n < 3; n++)
1503 if (pipe(cgi->pipe_fds[n]) == -1)
1506 /* create cgi wsis for each stdin/out/err fd */
1508 for (n = 0; n < 3; n++) {
1509 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1510 if (!cgi->stdwsi[n])
1512 cgi->stdwsi[n]->cgi_channel = n;
1513 /* read side is 0, stdin we want the write side, others read */
1514 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1515 fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK);
1518 for (n = 0; n < 3; n++) {
1519 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1521 cgi->stdwsi[n]->parent = wsi;
1522 cgi->stdwsi[n]->sibling_list = wsi->child_list;
1523 wsi->child_list = cgi->stdwsi[n];
1526 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1527 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1528 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1530 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1531 cgi->stdwsi[LWS_STDIN]->sock,
1532 cgi->stdwsi[LWS_STDOUT]->sock,
1533 cgi->stdwsi[LWS_STDERR]->sock);
1535 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1539 /* add us to the pt list of active cgis */
1540 cgi->cgi_list = pt->cgi_list;
1543 /* prepare his CGI env */
1546 if (wsi->u.hdr.ah) {
1547 snprintf(cgi_path, sizeof(cgi_path) - 1, "PATH_INFO=%s",
1548 lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI));
1549 cgi_path[sizeof(cgi_path) - 1] = '\0';
1550 env_array[n++] = cgi_path;
1551 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1552 env_array[n++] = "REQUEST_METHOD=POST";
1554 env_array[n++] = "REQUEST_METHOD=GET";
1556 if (lws_is_ssl(wsi))
1557 env_array[n++] = "HTTPS=ON";
1558 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1559 env_array[n++] = "PATH=/bin:/usr/bin:/usrlocal/bin";
1560 env_array[n] = NULL;
1562 /* we are ready with the redirection pipes... run the thing */
1563 #ifdef LWS_HAVE_VFORK
1569 lwsl_err("fork failed, errno %d", errno);
1574 /* we are the parent process */
1577 /* We are the forked process, redirect and kill inherited things.
1579 * Because of vfork(), we cannot do anything that changes pages in
1580 * the parent environment. Stuff that changes kernel state for the
1581 * process is OK. Stuff that happens after the execvpe() is OK.
1584 for (n = 0; n < 3; n++) {
1585 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
1586 lwsl_err("%s: stdin dup2 failed\n", __func__);
1589 close(cgi->pipe_fds[n][!(n == 0)]);
1592 execvpe(exec_array[0], &exec_array[0], &env_array[0]);
1596 /* drop us from the pt cgi list */
1597 pt->cgi_list = cgi->cgi_list;
1600 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
1602 for (n = 0; n < 3; n++)
1603 if (wsi->cgi->stdwsi[n])
1604 lws_free_wsi(cgi->stdwsi[n]);
1607 for (n = 0; n < 3; n++) {
1608 if (cgi->pipe_fds[n][0])
1609 close(cgi->pipe_fds[n][0]);
1610 if (cgi->pipe_fds[n][1])
1611 close(cgi->pipe_fds[n][1]);
1614 lws_free_set_NULL(wsi->cgi);
1616 lwsl_err("%s: failed\n", __func__);
1622 * lws_cgi_kill: terminate cgi process associated with wsi
1624 * @wsi: connection to own the process
1626 LWS_VISIBLE LWS_EXTERN int
1627 lws_cgi_kill(struct lws *wsi)
1629 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1630 struct lws_cgi **pcgi = &pt->cgi_list;
1631 struct lws_cgi_args args;
1632 int n, status, do_close = 0;
1637 lwsl_notice("%s: wsi %p\n", __func__, wsi);
1641 if (wsi->cgi->pid > 0) {
1642 /* kill the process */
1643 n = kill(wsi->cgi->pid, SIGTERM);
1645 lwsl_err("%s: failed\n", __func__);
1648 waitpid(wsi->cgi->pid, &status, 0); /* !!! may hang !!! */
1651 args.stdwsi = &wsi->cgi->stdwsi[0];
1653 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
1654 wsi->protocol->callback,
1655 wsi, LWS_CALLBACK_CGI_TERMINATED,
1657 (void *)&args, 0)) {
1659 do_close = !wsi->cgi->being_closed;
1662 /* remove us from the cgi list */
1664 if (*pcgi == wsi->cgi) {
1665 /* drop us from the pt cgi list */
1666 *pcgi = (*pcgi)->cgi_list;
1669 pcgi = &(*pcgi)->cgi_list;
1672 for (n = 0 ; n < 3; n++) {
1673 if (wsi->cgi->pipe_fds[n][!!(n == 0)] >= 0) {
1674 close(wsi->cgi->pipe_fds[n][!!(n == 0)]);
1675 wsi->cgi->pipe_fds[n][!!(n == 0)] = -1;
1679 lws_free_set_NULL(wsi->cgi);
1682 lws_close_free_wsi(wsi, 0);
1688 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
1690 struct lws_cgi **pcgi = &pt->cgi_list, *cgi;
1693 /* check all the subprocesses on the cgi list for termination */
1695 /* get the next one because we may close current one next */
1697 pcgi = &(*pcgi)->cgi_list;
1700 waitpid(cgi->pid, &status, WNOHANG) > 0) {
1702 lws_cgi_kill(cgi->wsi);
1703 pcgi = &pt->cgi_list;