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 *context;
146 struct lws_context_per_thread *pt;
148 struct lws_tokens eff_buf;
153 context = wsi->context;
154 pt = &context->pt[(int)wsi->tsi];
157 if (wsi->mode == LWSCM_CGI) {
158 /* we are not a network connection, but a handler for CGI io */
160 assert(wsi->master->cgi);
161 assert(wsi->master->cgi->stdwsi[(int)wsi->cgi_channel] == wsi);
162 /* end the binding between us and master */
163 wsi->master->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
165 wsi->socket_is_permanently_unusable = 1;
167 goto just_kill_connection;
171 /* we have a cgi going, we must kill it and close the
172 * related stdin/out/err wsis first
174 wsi->cgi->being_closed = 1;
179 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
180 wsi->u.http.fd != LWS_INVALID_FILE) {
181 lwsl_debug("closing http file\n");
182 lws_plat_file_close(wsi, wsi->u.http.fd);
183 wsi->u.http.fd = LWS_INVALID_FILE;
184 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
185 wsi->user_space, NULL, 0);
187 if (wsi->socket_is_permanently_unusable ||
188 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
189 wsi->state == LWSS_SHUTDOWN)
190 goto just_kill_connection;
192 wsi->state_pre_close = wsi->state;
194 switch (wsi->state_pre_close) {
195 case LWSS_DEAD_SOCKET:
198 /* we tried the polite way... */
199 case LWSS_AWAITING_CLOSE_ACK:
200 goto just_kill_connection;
202 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
203 if (wsi->trunc_len) {
204 lws_callback_on_writable(wsi);
207 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
208 goto just_kill_connection;
210 if (wsi->trunc_len) {
211 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
212 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
213 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
219 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
220 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
221 goto just_kill_connection;
223 if (wsi->mode == LWSCM_HTTP_SERVING)
224 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
225 wsi->user_space, NULL, 0);
226 if (wsi->mode == LWSCM_HTTP_CLIENT)
227 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_CLIENT_HTTP,
228 wsi->user_space, NULL, 0);
231 * are his extensions okay with him closing? Eg he might be a mux
232 * parent and just his ch1 aspect is closing?
235 if (lws_ext_cb_active(wsi,
236 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
237 lwsl_ext("extension vetoed close\n");
242 * flush any tx pending from extensions, since we may send close packet
243 * if there are problems with send, just nuke the connection
248 eff_buf.token = NULL;
249 eff_buf.token_len = 0;
251 /* show every extension the new incoming data */
253 m = lws_ext_cb_active(wsi,
254 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
256 lwsl_ext("Extension reports fatal error\n");
257 goto just_kill_connection;
261 * at least one extension told us he has more
262 * to spill, so we will go around again after
266 /* assuming they left us something to send, send it */
268 if (eff_buf.token_len)
269 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
270 eff_buf.token_len) !=
272 lwsl_debug("close: ext spill failed\n");
273 goto just_kill_connection;
278 * signal we are closing, lws_write will
279 * add any necessary version-specific stuff. If the write fails,
280 * no worries we are closing anyway. If we didn't initiate this
281 * close, then our state has been changed to
282 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
284 * Likewise if it's a second call to close this connection after we
285 * sent the close indication to the peer already, we are in state
286 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
289 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
290 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
291 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
292 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
293 lwsl_debug("sending close indication...\n");
295 /* if no prepared close reason, use 1000 and no aux data */
296 if (!wsi->u.ws.close_in_ping_buffer_len) {
297 wsi->u.ws.close_in_ping_buffer_len = 2;
298 wsi->u.ws.ping_payload_buf[LWS_PRE] =
299 (reason >> 16) & 0xff;
300 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
304 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
305 wsi->u.ws.close_in_ping_buffer_len,
309 * we have sent a nice protocol level indication we
310 * now wish to close, we should not send anything more
312 wsi->state = LWSS_AWAITING_CLOSE_ACK;
315 * ...and we should wait for a reply for a bit
318 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
319 lwsl_debug("sent close indication, awaiting ack\n");
324 lwsl_info("close: sending close packet failed, hanging up\n");
326 /* else, the send failed and we should just hang up */
329 just_kill_connection:
333 * Testing with ab shows that we have to stage the socket close when
334 * the system is under stress... shutdown any further TX, change the
335 * state to one that won't emit anything more, and wait with a timeout
336 * for the POLLIN to show a zero-size rx before coming back and doing
339 if (wsi->state != LWSS_SHUTDOWN &&
340 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
341 !wsi->socket_is_permanently_unusable) {
342 lwsl_info("%s: shutting down connection: %p\n", __func__, wsi);
343 n = shutdown(wsi->sock, SHUT_WR);
345 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
347 // This causes problems with disconnection when the events are half closing connection
348 // FD_READ | FD_CLOSE (33)
350 /* libuv: no event available to guarantee completion */
351 if (!LWS_LIBUV_ENABLED(context)) {
353 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
354 wsi->state = LWSS_SHUTDOWN;
355 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
356 context->timeout_secs);
363 lwsl_info("%s: real just_kill_connection: %p\n", __func__, wsi);
366 * we won't be servicing or receiving anything further from this guy
367 * delete socket from the internal poll list if still present
369 lws_ssl_remove_wsi_from_buffered_list(wsi);
370 lws_remove_from_timeout_list(wsi);
372 /* checking return redundant since we anyway close */
373 remove_wsi_socket_from_fds(wsi);
375 wsi->state = LWSS_DEAD_SOCKET;
377 lws_free_set_NULL(wsi->rxflow_buffer);
379 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
380 wsi->mode == LWSCM_WS_SERVING ||
381 wsi->mode == LWSCM_WS_CLIENT) {
383 if (wsi->u.ws.rx_draining_ext) {
384 struct lws **w = &pt->rx_draining_ext_list;
386 wsi->u.ws.rx_draining_ext = 0;
387 /* remove us from context draining ext list */
390 *w = wsi->u.ws.rx_draining_ext_list;
393 w = &((*w)->u.ws.rx_draining_ext_list);
395 wsi->u.ws.rx_draining_ext_list = NULL;
398 if (wsi->u.ws.tx_draining_ext) {
399 struct lws **w = &pt->tx_draining_ext_list;
401 wsi->u.ws.tx_draining_ext = 0;
402 /* remove us from context draining ext list */
405 *w = wsi->u.ws.tx_draining_ext_list;
408 w = &((*w)->u.ws.tx_draining_ext_list);
410 wsi->u.ws.tx_draining_ext_list = NULL;
412 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
414 if (wsi->trunc_alloc)
415 /* not going to be completed... nuke it */
416 lws_free_set_NULL(wsi->trunc_alloc);
418 wsi->u.ws.ping_payload_len = 0;
419 wsi->u.ws.ping_pending_flag = 0;
422 /* tell the user it's all over for this guy */
424 if (wsi->protocol && wsi->protocol->callback &&
425 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
426 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
427 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
428 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
429 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
430 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
431 lwsl_debug("calling back CLOSED\n");
432 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
433 wsi->user_space, NULL, 0);
434 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
435 lwsl_debug("calling back CLOSED_HTTP\n");
436 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
437 wsi->user_space, NULL, 0 );
438 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
439 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
440 lwsl_debug("Connection closed before server reply\n");
441 context->protocols[0].callback(wsi,
442 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
443 wsi->user_space, NULL, 0);
445 lwsl_debug("not calling back closed mode=%d state=%d\n",
446 wsi->mode, wsi->state_pre_close);
448 /* deallocate any active extension contexts */
450 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
451 lwsl_warn("extension destruction failed\n");
453 * inform all extensions in case they tracked this guy out of band
454 * even though not active on him specifically
456 if (lws_ext_cb_all_exts(context, wsi,
457 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
458 lwsl_warn("ext destroy wsi failed\n");
460 wsi->socket_is_permanently_unusable = 1;
463 if (LWS_LIBUV_ENABLED(context)) {
464 /* libuv has to do his own close handle processing asynchronously */
465 lws_libuv_closehandle(wsi);
471 lws_close_free_wsi_final(wsi);
475 lws_close_free_wsi_final(struct lws *wsi)
479 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
481 n = compatible_close(wsi->sock);
483 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
486 compatible_close(wsi->sock);
488 wsi->sock = LWS_SOCK_INVALID;
491 /* outermost destroy notification for wsi (user_space still intact) */
492 wsi->context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
493 wsi->user_space, NULL, 0);
500 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
504 ipv6 = LWS_IPV6_ENABLED(context);
508 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
513 lws_get_addresses(struct lws_context *context, void *ads, char *name,
514 int name_len, char *rip, int rip_len)
517 struct addrinfo ai, *res;
518 struct sockaddr_in addr4;
523 addr4.sin_family = AF_UNSPEC;
526 if (LWS_IPV6_ENABLED(context)) {
527 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
528 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
532 // Strip off the IPv4 to IPv6 header if one exists
533 if (strncmp(rip, "::ffff:", 7) == 0)
534 memmove(rip, rip + 7, strlen(rip) - 6);
536 getnameinfo((struct sockaddr *)ads,
537 sizeof(struct sockaddr_in6), name,
538 name_len, NULL, 0, 0);
544 struct addrinfo *result;
546 memset(&ai, 0, sizeof ai);
547 ai.ai_family = PF_UNSPEC;
548 ai.ai_socktype = SOCK_STREAM;
549 ai.ai_flags = AI_CANONNAME;
551 if (getnameinfo((struct sockaddr *)ads,
552 sizeof(struct sockaddr_in),
553 name, name_len, NULL, 0, 0))
559 if (getaddrinfo(name, NULL, &ai, &result))
563 while (addr4.sin_family == AF_UNSPEC && res) {
564 switch (res->ai_family) {
566 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
567 addr4.sin_family = AF_INET;
573 freeaddrinfo(result);
576 if (addr4.sin_family == AF_UNSPEC)
579 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
596 * lws_get_peer_addresses() - Get client address information
597 * @wsi: Local struct lws associated with
598 * @fd: Connection socket descriptor
599 * @name: Buffer to take client address name
600 * @name_len: Length of client address name buffer
601 * @rip: Buffer to take client address IP dotted quad
602 * @rip_len: Length of client address IP buffer
604 * This function fills in @name and @rip with the name and IP of
605 * the client connected with socket descriptor @fd. Names may be
606 * truncated if there is not enough room. If either cannot be
607 * determined, they will be returned as valid zero-length strings.
611 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
612 int name_len, char *rip, int rip_len)
617 struct sockaddr_in6 sin6;
619 struct sockaddr_in sin4;
620 struct lws_context *context = wsi->context;
627 lws_latency_pre(context, wsi);
630 if (LWS_IPV6_ENABLED(context)) {
640 if (getpeername(fd, p, &len) < 0) {
641 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
645 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
648 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
660 * lws_context_user() - get the user data associated with the context
661 * @context: Websocket context
663 * This returns the optional user allocation that can be attached to
664 * the context the sockets live in at context_create time. It's a way
665 * to let all sockets serviced in the same context share data without
666 * using globals statics in the user code.
669 lws_context_user(struct lws_context *context)
671 return context->user_space;
676 * lws_callback_all_protocol() - Callback all connections using
677 * the given protocol with the given reason
679 * @protocol: Protocol whose connections will get callbacks
680 * @reason: Callback reason index
684 lws_callback_all_protocol(struct lws_context *context,
685 const struct lws_protocols *protocol, int reason)
687 struct lws_context_per_thread *pt = &context->pt[0];
688 unsigned int n, m = context->count_threads;
692 for (n = 0; n < pt->fds_count; n++) {
693 wsi = wsi_from_fd(context, pt->fds[n].fd);
696 if (wsi->protocol == protocol)
697 protocol->callback(wsi, reason, wsi->user_space,
709 * lws_get_socket_fd() - returns the socket file descriptor
711 * You will not need this unless you are doing something special
713 * @wsi: Websocket connection instance
717 lws_get_socket_fd(struct lws *wsi)
726 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
727 int ret, int completed)
729 unsigned long long u;
732 u = time_in_microseconds();
735 wsi->latency_start = u;
736 if (!wsi->action_start)
737 wsi->action_start = u;
741 if (wsi->action_start == wsi->latency_start)
743 "Completion first try lat %lluus: %p: ret %d: %s\n",
744 u - wsi->latency_start,
745 (void *)wsi, ret, action);
748 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
749 u - wsi->action_start,
750 u - wsi->latency_start,
751 (void *)wsi, ret, action);
752 wsi->action_start = 0;
754 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
755 u - wsi->latency_start, (void *)wsi, ret, action);
757 if (u - wsi->latency_start > context->worst_latency) {
758 context->worst_latency = u - wsi->latency_start;
759 strcpy(context->worst_latency_info, buf);
761 lwsl_latency("%s", buf);
768 * lws_rx_flow_control() - Enable and disable socket servicing for
771 * If the output side of a server process becomes choked, this allows flow
772 * control for the input side.
774 * @wsi: Websocket connection instance to get callback for
775 * @enable: 0 = disable read servicing for this connection, 1 = enable
779 lws_rx_flow_control(struct lws *wsi, int enable)
781 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
784 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
785 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
791 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
793 * When the user server code realizes it can accept more input, it can
794 * call this to have the RX flow restriction removed from all connections using
795 * the given protocol.
797 * @protocol: all connections using this protocol will be allowed to receive
801 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
802 const struct lws_protocols *protocol)
804 const struct lws_context_per_thread *pt = &context->pt[0];
806 unsigned int n, m = context->count_threads;
809 for (n = 0; n < pt->fds_count; n++) {
810 wsi = wsi_from_fd(context, pt->fds[n].fd);
813 if (wsi->protocol == protocol)
814 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
822 * lws_canonical_hostname() - returns this host's hostname
824 * This is typically used by client code to fill in the host parameter
825 * when making a client connection. You can only call it after the context
828 * @context: Websocket context
830 LWS_VISIBLE extern const char *
831 lws_canonical_hostname(struct lws_context *context)
833 return (const char *)context->canonical_hostname;
836 int user_callback_handle_rxflow(lws_callback_function callback_function,
838 enum lws_callback_reasons reason, void *user,
839 void *in, size_t len)
843 n = callback_function(wsi, reason, user, in, len);
845 n = _lws_rx_flow_control(wsi);
852 * lws_set_proxy() - Setups proxy to lws_context.
853 * @context: pointer to struct lws_context you want set proxy to
854 * @proxy: pointer to c string containing proxy in format address:port
856 * Returns 0 if proxy string was parsed and proxy was setup.
857 * Returns -1 if @proxy is NULL or has incorrect format.
859 * This is only required if your OS does not provide the http_proxy
860 * environment variable (eg, OSX)
862 * IMPORTANT! You should call this function right after creation of the
863 * lws_context and before call to connect. If you call this
864 * function after connect behavior is undefined.
865 * This function will override proxy settings made on lws_context
866 * creation with genenv() call.
870 lws_set_proxy(struct lws_context *context, const char *proxy)
878 p = strchr(proxy, '@');
879 if (p) { /* auth is around */
881 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
884 strncpy(authstring, proxy, p - proxy);
885 // null termination not needed on input
886 if (lws_b64_encode_string(authstring, (p - proxy),
887 context->proxy_basic_auth_token,
888 sizeof context->proxy_basic_auth_token) < 0)
891 lwsl_notice(" Proxy auth in use\n");
895 context->proxy_basic_auth_token[0] = '\0';
897 strncpy(context->http_proxy_address, proxy,
898 sizeof(context->http_proxy_address) - 1);
899 context->http_proxy_address[
900 sizeof(context->http_proxy_address) - 1] = '\0';
902 p = strchr(context->http_proxy_address, ':');
903 if (!p && !context->http_proxy_port) {
904 lwsl_err("http_proxy needs to be ads:port\n");
910 context->http_proxy_port = atoi(p + 1);
914 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
915 context->http_proxy_port);
920 lwsl_err("proxy auth too long\n");
926 * lws_get_protocol() - Returns a protocol pointer from a websocket
928 * @wsi: pointer to struct websocket you want to know the protocol of
931 * Some apis can act on all live connections of a given protocol,
932 * this is how you can get a pointer to the active protocol if needed.
935 LWS_VISIBLE const struct lws_protocols *
936 lws_get_protocol(struct lws *wsi)
938 return wsi->protocol;
942 lws_is_final_fragment(struct lws *wsi)
944 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
945 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
946 wsi->u.ws.rx_draining_ext);
947 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
950 LWS_VISIBLE unsigned char
951 lws_get_reserved_bits(struct lws *wsi)
953 return wsi->u.ws.rsv;
957 lws_ensure_user_space(struct lws *wsi)
959 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
963 /* allocate the per-connection user memory (if any) */
965 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
966 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
967 if (wsi->user_space == NULL) {
968 lwsl_err("Out of memory for conn user space\n");
972 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
973 __func__, wsi, wsi->protocol->per_session_data_size,
979 * lwsl_timestamp: generate logging timestamp string
981 * @level: logging level
982 * @p: char * buffer to take timestamp
985 * returns length written in p
988 lwsl_timestamp(int level, char *p, int len)
990 time_t o_now = time(NULL);
991 unsigned long long now;
992 struct tm *ptm = NULL;
1000 ptm = localtime(&o_now);
1002 if (localtime_r(&o_now, &tm))
1007 for (n = 0; n < LLL_COUNT; n++) {
1008 if (level != (1 << n))
1010 now = time_in_microseconds() / 100;
1012 n = snprintf(p, len,
1013 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1014 ptm->tm_year + 1900,
1020 (int)(now % 10000), log_level_names[n]);
1022 n = snprintf(p, len, "[%llu:%04d] %s: ",
1023 (unsigned long long) now / 10000,
1024 (int)(now % 10000), log_level_names[n]);
1031 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1035 lwsl_timestamp(level, buf, sizeof(buf));
1037 fprintf(stderr, "%s%s", buf, line);
1040 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1044 if (!(log_level & filter))
1047 vsnprintf(buf, sizeof(buf), format, vl);
1048 buf[sizeof(buf) - 1] = '\0';
1050 lwsl_emit(filter, buf);
1053 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1057 va_start(ap, format);
1058 _lws_logv(filter, format, ap);
1063 * lws_set_log_level() - Set the logging bitfield
1064 * @level: OR together the LLL_ debug contexts you want output from
1065 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1066 * function to perform log string emission instead of
1067 * the default stderr one.
1069 * log level defaults to "err", "warn" and "notice" contexts enabled and
1070 * emission on stderr.
1073 LWS_VISIBLE void lws_set_log_level(int level,
1074 void (*func)(int level, const char *line))
1082 * lws_use_ssl() - Find out if connection is using SSL
1083 * @wsi: websocket connection to check
1085 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1086 * using verified cert, and 2 if using SSL but the cert was not
1087 * checked (appears for client wsi told to skip check on connection)
1090 lws_is_ssl(struct lws *wsi)
1092 #ifdef LWS_OPENSSL_SUPPORT
1093 return wsi->use_ssl;
1101 * lws_partial_buffered() - find out if lws buffered the last write
1102 * @wsi: websocket connection to check
1104 * Returns 1 if you cannot use lws_write because the last
1105 * write on this connection is still buffered, and can't be cleared without
1106 * returning to the service loop and waiting for the connection to be
1109 * If you will try to do >1 lws_write call inside a single
1110 * WRITEABLE callback, you must check this after every write and bail if
1111 * set, ask for a new writeable callback and continue writing from there.
1113 * This is never set at the start of a writeable callback, but any write
1118 lws_partial_buffered(struct lws *wsi)
1120 return !!wsi->trunc_len;
1123 void lws_set_protocol_write_pending(struct lws *wsi,
1124 enum lws_pending_protocol_send pend)
1126 lwsl_info("setting pps %d\n", pend);
1129 lwsl_err("pps overwrite\n");
1131 lws_rx_flow_control(wsi, 0);
1132 lws_callback_on_writable(wsi);
1136 lws_get_peer_write_allowance(struct lws *wsi)
1138 #ifdef LWS_USE_HTTP2
1139 /* only if we are using HTTP2 on this connection */
1140 if (wsi->mode != LWSCM_HTTP2_SERVING)
1142 /* user is only interested in how much he can send, or that he can't */
1143 if (wsi->u.http2.tx_credit <= 0)
1146 return wsi->u.http2.tx_credit;
1154 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1156 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1157 memset(&wsi->u, 0, sizeof(wsi->u));
1161 LWS_VISIBLE struct lws_plat_file_ops *
1162 lws_get_fops(struct lws_context *context)
1164 return &context->fops;
1167 LWS_VISIBLE LWS_EXTERN struct lws_context *
1168 lws_get_context(const struct lws *wsi)
1170 return wsi->context;
1173 LWS_VISIBLE LWS_EXTERN int
1174 lws_get_count_threads(struct lws_context *context)
1176 return context->count_threads;
1179 LWS_VISIBLE LWS_EXTERN void *
1180 lws_wsi_user(struct lws *wsi)
1182 return wsi->user_space;
1185 LWS_VISIBLE LWS_EXTERN void
1186 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1187 unsigned char *buf, size_t len)
1189 unsigned char *p, *start;
1190 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1192 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1194 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1196 *p++ = (((int)status) >> 8) & 0xff;
1197 *p++ = ((int)status) & 0xff;
1200 while (len-- && p < start + budget)
1203 wsi->u.ws.close_in_ping_buffer_len = p - start;
1207 _lws_rx_flow_control(struct lws *wsi)
1209 /* there is no pending change */
1210 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1211 lwsl_debug("%s: no pending change\n", __func__);
1215 /* stuff is still buffered, not ready to really accept new input */
1216 if (wsi->rxflow_buffer) {
1217 /* get ourselves called back to deal with stashed buffer */
1218 lws_callback_on_writable(wsi);
1222 /* pending is cleared, we can change rxflow state */
1224 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1226 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1227 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1229 /* adjust the pollfd for this wsi */
1231 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1232 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1233 lwsl_info("%s: fail\n", __func__);
1237 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1244 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1246 static const unsigned char e0f4[] = {
1247 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1248 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1249 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1250 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1251 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1252 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1253 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1254 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1255 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1256 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1257 0x80 | ((4 - 1) << 2) | 1, /* ea */
1258 0x80 | ((4 - 1) << 2) | 1, /* eb */
1259 0x80 | ((4 - 1) << 2) | 1, /* ec */
1260 0x80 | ((2 - 1) << 2) | 1, /* ed */
1261 0x80 | ((4 - 1) << 2) | 1, /* ee */
1262 0x80 | ((4 - 1) << 2) | 1, /* ef */
1263 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1264 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1265 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1266 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1267 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1270 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1271 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1273 unsigned char s = *state;
1276 unsigned char c = *buf++;
1280 if (c < 0xc2 || c > 0xf4)
1283 s = 0x80 | ((4 - 1) << 2);
1288 if (c < (s & 0xf0) ||
1289 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1291 s = e0f4[21 + (s & 3)];
1301 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1302 * Notice it does so by dropping '\0' into input string
1303 * and the leading / on the path is consequently lost
1305 * @p: incoming uri string.. will get written to
1306 * @prot: result pointer for protocol part (https://)
1307 * @ads: result pointer for address part
1308 * @port: result pointer for port part
1309 * @path: result pointer for path part
1312 LWS_VISIBLE LWS_EXTERN int
1313 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1317 static const char *slash = "/";
1319 /* cut up the location into address, port and path */
1321 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1332 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1334 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1337 while (*p && *p != ':' && *p != '/')
1342 while (*p && *p != '/')
1355 #ifdef LWS_NO_EXTENSIONS
1357 /* we need to provide dummy callbacks for internal exts
1358 * so user code runs when faced with a lib compiled with
1359 * extensions disabled.
1363 lws_extension_callback_pm_deflate(struct lws_context *context,
1364 const struct lws_extension *ext,
1366 enum lws_extension_callback_reasons reason,
1367 void *user, void *in, size_t len)
1381 LWS_VISIBLE LWS_EXTERN int
1382 lws_is_cgi(struct lws *wsi) {
1393 lws_create_basic_wsi(struct lws_context *context, int tsi)
1395 struct lws *new_wsi;
1397 if ((unsigned int)context->pt[tsi].fds_count ==
1398 context->fd_limit_per_thread - 1) {
1399 lwsl_err("no space for new conn\n");
1403 new_wsi = lws_zalloc(sizeof(struct lws));
1404 if (new_wsi == NULL) {
1405 lwsl_err("Out of memory for new connection\n");
1410 new_wsi->context = context;
1411 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1412 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1414 /* intialize the instance struct */
1416 new_wsi->state = LWSS_CGI;
1417 new_wsi->mode = LWSCM_CGI;
1418 new_wsi->hdr_parsing_completed = 0;
1419 new_wsi->position_in_fds_table = -1;
1422 * these can only be set once the protocol is known
1423 * we set an unestablished connection's protocol pointer
1424 * to the start of the supported list, so it can look
1425 * for matching ones during the handshake
1427 new_wsi->protocol = context->protocols;
1428 new_wsi->user_space = NULL;
1429 new_wsi->ietf_spec_revision = 0;
1430 new_wsi->sock = LWS_SOCK_INVALID;
1431 context->count_wsi_allocated++;
1437 * lws_cgi: spawn network-connected cgi process
1439 * @wsi: connection to own the process
1440 * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1443 LWS_VISIBLE LWS_EXTERN int
1444 lws_cgi(struct lws *wsi, char * const *exec_array, int timeout_secs)
1446 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1447 char *env_array[30], cgi_path[400];
1448 struct lws_cgi *cgi;
1452 * give the master wsi a cgi struct
1455 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1457 lwsl_err("%s: OOM\n", __func__);
1462 cgi->wsi = wsi; /* set cgi's owning wsi */
1464 /* create pipes for [stdin|stdout] and [stderr] */
1466 for (n = 0; n < 3; n++)
1467 if (pipe(cgi->pipe_fds[n]) == -1)
1470 /* create cgi wsis for each stdin/out/err fd */
1472 for (n = 0; n < 3; n++) {
1473 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1474 if (!cgi->stdwsi[n])
1476 cgi->stdwsi[n]->cgi_channel = n;
1477 /* read side is 0, stdin we want the write side, others read */
1478 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1479 fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK);
1482 for (n = 0; n < 3; n++) {
1483 cgi->stdwsi[n]->master = wsi;
1484 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1488 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1489 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1490 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1492 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1493 cgi->stdwsi[LWS_STDIN]->sock,
1494 cgi->stdwsi[LWS_STDOUT]->sock,
1495 cgi->stdwsi[LWS_STDERR]->sock);
1497 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1499 /* add us to the pt list of active cgis */
1500 cgi->cgi_list = pt->cgi_list;
1503 /* prepare his CGI env */
1506 if (wsi->u.hdr.ah) {
1507 snprintf(cgi_path, sizeof(cgi_path) - 1, "PATH_INFO=%s",
1508 lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI));
1509 cgi_path[sizeof(cgi_path) - 1] = '\0';
1510 env_array[n++] = cgi_path;
1511 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1512 env_array[n++] = "REQUEST_METHOD=POST";
1514 env_array[n++] = "REQUEST_METHOD=GET";
1516 if (lws_is_ssl(wsi))
1517 env_array[n++] = "HTTPS=ON";
1518 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1519 env_array[n++] = "PATH=/bin:/usr/bin:/usrlocal/bin";
1520 env_array[n] = NULL;
1522 /* we are ready with the redirection pipes... run the thing */
1523 #ifdef LWS_HAVE_VFORK
1529 lwsl_err("fork failed, errno %d", errno);
1534 /* we are the parent process */
1537 /* We are the forked process, redirect and kill inherited things.
1539 * Because of vfork(), we cannot do anything that changes pages in
1540 * the parent environment. Stuff that changes kernel state for the
1541 * process is OK. Stuff that happens after the execvpe() is OK.
1544 for (n = 0; n < 3; n++) {
1545 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
1546 lwsl_err("%s: stdin dup2 failed\n", __func__);
1549 close(cgi->pipe_fds[n][!(n == 0)]);
1552 execvpe(exec_array[0], &exec_array[0], &env_array[0]);
1556 /* drop us from the pt cgi list */
1557 pt->cgi_list = cgi->cgi_list;
1560 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
1562 for (n = 0; n < 3; n++)
1563 if (wsi->cgi->stdwsi[n])
1564 lws_free_wsi(cgi->stdwsi[n]);
1567 for (n = 0; n < 3; n++) {
1568 if (cgi->pipe_fds[n][0])
1569 close(cgi->pipe_fds[n][0]);
1570 if (cgi->pipe_fds[n][1])
1571 close(cgi->pipe_fds[n][1]);
1574 lws_free_set_NULL(wsi->cgi);
1576 lwsl_err("%s: failed\n", __func__);
1582 * lws_cgi_kill: terminate cgi process associated with wsi
1584 * @wsi: connection to own the process
1586 LWS_VISIBLE LWS_EXTERN int
1587 lws_cgi_kill(struct lws *wsi)
1589 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1590 struct lws_cgi **pcgi = &pt->cgi_list;
1591 struct lws_cgi_args args;
1592 int n, status, do_close = 0;
1597 lwsl_notice("%s: wsi %p\n", __func__, wsi);
1601 if (wsi->cgi->pid > 0) {
1602 /* kill the process */
1603 n = kill(wsi->cgi->pid, SIGTERM);
1605 lwsl_err("%s: failed\n", __func__);
1608 waitpid(wsi->cgi->pid, &status, 0); /* !!! may hang !!! */
1611 args.stdwsi = &wsi->cgi->stdwsi[0];
1613 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
1614 wsi->protocol->callback,
1615 wsi, LWS_CALLBACK_CGI_TERMINATED,
1617 (void *)&args, 0)) {
1619 do_close = !wsi->cgi->being_closed;
1622 /* remove us from the cgi list */
1624 if (*pcgi == wsi->cgi) {
1625 /* drop us from the pt cgi list */
1626 *pcgi = (*pcgi)->cgi_list;
1629 pcgi = &(*pcgi)->cgi_list;
1632 for (n = 0 ; n < 3; n++) {
1633 if (wsi->cgi->pipe_fds[n][!!(n == 0)] >= 0) {
1634 close(wsi->cgi->pipe_fds[n][!!(n == 0)]);
1635 wsi->cgi->pipe_fds[n][!!(n == 0)] = -1;
1637 lws_close_free_wsi(wsi->cgi->stdwsi[n], 0);
1641 lws_free_set_NULL(wsi->cgi);
1644 lws_close_free_wsi(wsi, 0);
1650 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
1652 struct lws_cgi **pcgi = &pt->cgi_list, *cgi;
1655 /* check all the subprocesses on the cgi list for termination */
1657 /* get the next one because we may close current one next */
1659 pcgi = &(*pcgi)->cgi_list;
1662 waitpid(cgi->pid, &status, WNOHANG) > 0) {
1664 lws_cgi_kill(cgi->wsi);
1665 pcgi = &pt->cgi_list;