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"
23 #include <sys/types.h>
24 #if defined(WIN32) || defined(_WIN32)
29 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
30 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
32 static const char * const log_level_names[] = {
46 lws_free_wsi(struct lws *wsi)
51 /* Protocol user data may be allocated either internally by lws
52 * or by specified the user.
53 * We should only free what we allocated. */
54 if (wsi->protocol && wsi->protocol->per_session_data_size &&
55 wsi->user_space && !wsi->user_space_externally_allocated)
56 lws_free(wsi->user_space);
58 lws_free_set_NULL(wsi->rxflow_buffer);
59 lws_free_set_NULL(wsi->trunc_alloc);
62 /* we're closing, losing some rx is OK */
63 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
65 /* we may not have an ah, but may be on the waiting list... */
66 lws_header_table_detach(wsi);
68 wsi->context->count_wsi_allocated--;
69 lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi,
70 wsi->context->count_wsi_allocated);
76 lws_remove_from_timeout_list(struct lws *wsi)
78 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
80 if (!wsi->timeout_list_prev) /* ie, not part of the list */
84 /* if we have a next guy, set his prev to our prev */
85 if (wsi->timeout_list)
86 wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev;
87 /* set our prev guy to our next guy instead of us */
88 *wsi->timeout_list_prev = wsi->timeout_list;
90 /* we're out of the list, we should not point anywhere any more */
91 wsi->timeout_list_prev = NULL;
92 wsi->timeout_list = NULL;
97 * lws_set_timeout() - marks the wsi as subject to a timeout
99 * You will not need this unless you are doing something special
101 * @wsi: Websocket connection instance
102 * @reason: timeout reason
103 * @secs: how many seconds
107 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
109 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
116 if (reason && !wsi->timeout_list_prev) {
117 /* our next guy is current first guy */
118 wsi->timeout_list = pt->timeout_list;
119 /* if there is a next guy, set his prev ptr to our next ptr */
120 if (wsi->timeout_list)
121 wsi->timeout_list->timeout_list_prev = &wsi->timeout_list;
122 /* our prev ptr is first ptr */
123 wsi->timeout_list_prev = &pt->timeout_list;
124 /* set the first guy to be us */
125 *wsi->timeout_list_prev = wsi;
128 lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs);
129 wsi->pending_timeout_limit = now + secs;
130 wsi->pending_timeout = reason;
135 lws_remove_from_timeout_list(wsi);
139 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
141 struct lws_context *context;
142 struct lws_context_per_thread *pt;
144 struct lws_tokens eff_buf;
149 context = wsi->context;
150 pt = &context->pt[(int)wsi->tsi];
153 if (wsi->mode == LWSCM_CGI) {
154 /* we are not a network connection, but a handler for CGI io */
156 assert(wsi->master->cgi);
157 assert(wsi->master->cgi->stdwsi[(int)wsi->cgi_channel] == wsi);
158 /* end the binding between us and master */
159 wsi->master->cgi->stdwsi[(int)wsi->cgi_channel] = NULL;
161 wsi->socket_is_permanently_unusable = 1;
163 goto just_kill_connection;
167 /* we have a cgi going, we must kill it and close the
168 * related stdin/out/err wsis first
170 wsi->cgi->being_closed = 1;
175 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
176 wsi->u.http.fd != LWS_INVALID_FILE) {
177 lwsl_debug("closing http file\n");
178 lws_plat_file_close(wsi, wsi->u.http.fd);
179 wsi->u.http.fd = LWS_INVALID_FILE;
180 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
181 wsi->user_space, NULL, 0);
183 if (wsi->socket_is_permanently_unusable ||
184 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||
185 wsi->state == LWSS_SHUTDOWN)
186 goto just_kill_connection;
188 wsi->state_pre_close = wsi->state;
190 switch (wsi->state_pre_close) {
191 case LWSS_DEAD_SOCKET:
194 /* we tried the polite way... */
195 case LWSS_AWAITING_CLOSE_ACK:
196 goto just_kill_connection;
198 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
199 if (wsi->trunc_len) {
200 lws_callback_on_writable(wsi);
203 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
204 goto just_kill_connection;
206 if (wsi->trunc_len) {
207 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
208 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
209 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
215 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
216 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
217 goto just_kill_connection;
219 if (wsi->mode == LWSCM_HTTP_SERVING)
220 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
221 wsi->user_space, NULL, 0);
224 * are his extensions okay with him closing? Eg he might be a mux
225 * parent and just his ch1 aspect is closing?
228 if (lws_ext_cb_active(wsi,
229 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
230 lwsl_ext("extension vetoed close\n");
235 * flush any tx pending from extensions, since we may send close packet
236 * if there are problems with send, just nuke the connection
241 eff_buf.token = NULL;
242 eff_buf.token_len = 0;
244 /* show every extension the new incoming data */
246 m = lws_ext_cb_active(wsi,
247 LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0);
249 lwsl_ext("Extension reports fatal error\n");
250 goto just_kill_connection;
254 * at least one extension told us he has more
255 * to spill, so we will go around again after
259 /* assuming they left us something to send, send it */
261 if (eff_buf.token_len)
262 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
263 eff_buf.token_len) !=
265 lwsl_debug("close: ext spill failed\n");
266 goto just_kill_connection;
271 * signal we are closing, lws_write will
272 * add any necessary version-specific stuff. If the write fails,
273 * no worries we are closing anyway. If we didn't initiate this
274 * close, then our state has been changed to
275 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
277 * Likewise if it's a second call to close this connection after we
278 * sent the close indication to the peer already, we are in state
279 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
282 if (wsi->state_pre_close == LWSS_ESTABLISHED &&
283 (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */
284 (reason != LWS_CLOSE_STATUS_NOSTATUS &&
285 (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) {
286 lwsl_debug("sending close indication...\n");
288 /* if no prepared close reason, use 1000 and no aux data */
289 if (!wsi->u.ws.close_in_ping_buffer_len) {
290 wsi->u.ws.close_in_ping_buffer_len = 2;
291 wsi->u.ws.ping_payload_buf[LWS_PRE] =
292 (reason >> 16) & 0xff;
293 wsi->u.ws.ping_payload_buf[LWS_PRE + 1] =
297 n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE],
298 wsi->u.ws.close_in_ping_buffer_len,
302 * we have sent a nice protocol level indication we
303 * now wish to close, we should not send anything more
305 wsi->state = LWSS_AWAITING_CLOSE_ACK;
308 * ...and we should wait for a reply for a bit
311 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
312 lwsl_debug("sent close indication, awaiting ack\n");
317 lwsl_info("close: sending close packet failed, hanging up\n");
319 /* else, the send failed and we should just hang up */
322 just_kill_connection:
326 * Testing with ab shows that we have to stage the socket close when
327 * the system is under stress... shutdown any further TX, change the
328 * state to one that won't emit anything more, and wait with a timeout
329 * for the POLLIN to show a zero-size rx before coming back and doing
332 if (wsi->state != LWSS_SHUTDOWN &&
333 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&
334 !wsi->socket_is_permanently_unusable) {
335 lwsl_info("%s: shutting down connection: %p\n", __func__, wsi);
336 n = shutdown(wsi->sock, SHUT_WR);
338 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
340 lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);
341 wsi->state = LWSS_SHUTDOWN;
342 lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,
343 context->timeout_secs);
348 lwsl_info("%s: real just_kill_connection: %p\n", __func__, wsi);
351 * we won't be servicing or receiving anything further from this guy
352 * delete socket from the internal poll list if still present
354 lws_ssl_remove_wsi_from_buffered_list(wsi);
355 lws_remove_from_timeout_list(wsi);
357 /* checking return redundant since we anyway close */
358 remove_wsi_socket_from_fds(wsi);
360 wsi->state = LWSS_DEAD_SOCKET;
362 lws_free_set_NULL(wsi->rxflow_buffer);
364 if (wsi->state_pre_close == LWSS_ESTABLISHED ||
365 wsi->mode == LWSCM_WS_SERVING ||
366 wsi->mode == LWSCM_WS_CLIENT) {
368 if (wsi->u.ws.rx_draining_ext) {
369 struct lws **w = &pt->rx_draining_ext_list;
371 wsi->u.ws.rx_draining_ext = 0;
372 /* remove us from context draining ext list */
375 *w = wsi->u.ws.rx_draining_ext_list;
378 w = &((*w)->u.ws.rx_draining_ext_list);
380 wsi->u.ws.rx_draining_ext_list = NULL;
383 if (wsi->u.ws.tx_draining_ext) {
384 struct lws **w = &pt->tx_draining_ext_list;
386 wsi->u.ws.tx_draining_ext = 0;
387 /* remove us from context draining ext list */
390 *w = wsi->u.ws.tx_draining_ext_list;
393 w = &((*w)->u.ws.tx_draining_ext_list);
395 wsi->u.ws.tx_draining_ext_list = NULL;
397 lws_free_set_NULL(wsi->u.ws.rx_ubuf);
399 if (wsi->trunc_alloc)
400 /* not going to be completed... nuke it */
401 lws_free_set_NULL(wsi->trunc_alloc);
403 wsi->u.ws.ping_payload_len = 0;
404 wsi->u.ws.ping_pending_flag = 0;
407 /* tell the user it's all over for this guy */
409 if (wsi->protocol && wsi->protocol->callback &&
410 ((wsi->state_pre_close == LWSS_ESTABLISHED) ||
411 (wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY) ||
412 (wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK) ||
413 (wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) ||
414 (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) ||
415 (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) {
416 lwsl_debug("calling back CLOSED\n");
417 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
418 wsi->user_space, NULL, 0);
419 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
420 lwsl_debug("calling back CLOSED_HTTP\n");
421 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
422 wsi->user_space, NULL, 0 );
423 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
424 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
425 lwsl_debug("Connection closed before server reply\n");
426 context->protocols[0].callback(wsi,
427 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
428 wsi->user_space, NULL, 0);
430 lwsl_debug("not calling back closed mode=%d state=%d\n",
431 wsi->mode, wsi->state_pre_close);
433 /* deallocate any active extension contexts */
435 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
436 lwsl_warn("extension destruction failed\n");
438 * inform all extensions in case they tracked this guy out of band
439 * even though not active on him specifically
441 if (lws_ext_cb_all_exts(context, wsi,
442 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
443 lwsl_warn("ext destroy wsi failed\n");
445 wsi->socket_is_permanently_unusable = 1;
448 if (LWS_LIBUV_ENABLED(context)) {
449 /* libuv has to do his own close handle processing asynchronously */
450 lws_libuv_closehandle(wsi);
456 lws_close_free_wsi_final(wsi);
460 lws_close_free_wsi_final(struct lws *wsi)
464 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
466 n = compatible_close(wsi->sock);
468 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
471 compatible_close(wsi->sock);
473 wsi->sock = LWS_SOCK_INVALID;
476 /* outermost destroy notification for wsi (user_space still intact) */
477 wsi->context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
478 wsi->user_space, NULL, 0);
485 interface_to_sa(struct lws_context *context, const char *ifname, struct sockaddr_in *addr, size_t addrlen)
489 ipv6 = LWS_IPV6_ENABLED(context);
493 return lws_interface_to_sa(ipv6, ifname, addr, addrlen);
498 lws_get_addresses(struct lws_context *context, void *ads, char *name,
499 int name_len, char *rip, int rip_len)
502 struct addrinfo ai, *res;
503 struct sockaddr_in addr4;
508 addr4.sin_family = AF_UNSPEC;
511 if (LWS_IPV6_ENABLED(context)) {
512 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
513 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
517 // Strip off the IPv4 to IPv6 header if one exists
518 if (strncmp(rip, "::ffff:", 7) == 0)
519 memmove(rip, rip + 7, strlen(rip) - 6);
521 getnameinfo((struct sockaddr *)ads,
522 sizeof(struct sockaddr_in6), name,
523 name_len, NULL, 0, 0);
529 struct addrinfo *result;
531 memset(&ai, 0, sizeof ai);
532 ai.ai_family = PF_UNSPEC;
533 ai.ai_socktype = SOCK_STREAM;
534 ai.ai_flags = AI_CANONNAME;
536 if (getnameinfo((struct sockaddr *)ads,
537 sizeof(struct sockaddr_in),
538 name, name_len, NULL, 0, 0))
544 if (getaddrinfo(name, NULL, &ai, &result))
548 while (addr4.sin_family == AF_UNSPEC && res) {
549 switch (res->ai_family) {
551 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
552 addr4.sin_family = AF_INET;
558 freeaddrinfo(result);
561 if (addr4.sin_family == AF_UNSPEC)
564 if (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)
581 * lws_get_peer_addresses() - Get client address information
582 * @wsi: Local struct lws associated with
583 * @fd: Connection socket descriptor
584 * @name: Buffer to take client address name
585 * @name_len: Length of client address name buffer
586 * @rip: Buffer to take client address IP dotted quad
587 * @rip_len: Length of client address IP buffer
589 * This function fills in @name and @rip with the name and IP of
590 * the client connected with socket descriptor @fd. Names may be
591 * truncated if there is not enough room. If either cannot be
592 * determined, they will be returned as valid zero-length strings.
596 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
597 int name_len, char *rip, int rip_len)
602 struct sockaddr_in6 sin6;
604 struct sockaddr_in sin4;
605 struct lws_context *context = wsi->context;
612 lws_latency_pre(context, wsi);
615 if (LWS_IPV6_ENABLED(context)) {
625 if (getpeername(fd, p, &len) < 0) {
626 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
630 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
633 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
645 * lws_context_user() - get the user data associated with the context
646 * @context: Websocket context
648 * This returns the optional user allocation that can be attached to
649 * the context the sockets live in at context_create time. It's a way
650 * to let all sockets serviced in the same context share data without
651 * using globals statics in the user code.
654 lws_context_user(struct lws_context *context)
656 return context->user_space;
661 * lws_callback_all_protocol() - Callback all connections using
662 * the given protocol with the given reason
664 * @protocol: Protocol whose connections will get callbacks
665 * @reason: Callback reason index
669 lws_callback_all_protocol(struct lws_context *context,
670 const struct lws_protocols *protocol, int reason)
672 struct lws_context_per_thread *pt = &context->pt[0];
673 unsigned int n, m = context->count_threads;
677 for (n = 0; n < pt->fds_count; n++) {
678 wsi = wsi_from_fd(context, pt->fds[n].fd);
681 if (wsi->protocol == protocol)
682 protocol->callback(wsi, reason, wsi->user_space,
694 * lws_get_socket_fd() - returns the socket file descriptor
696 * You will not need this unless you are doing something special
698 * @wsi: Websocket connection instance
702 lws_get_socket_fd(struct lws *wsi)
711 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
712 int ret, int completed)
714 unsigned long long u;
717 u = time_in_microseconds();
720 wsi->latency_start = u;
721 if (!wsi->action_start)
722 wsi->action_start = u;
726 if (wsi->action_start == wsi->latency_start)
728 "Completion first try lat %lluus: %p: ret %d: %s\n",
729 u - wsi->latency_start,
730 (void *)wsi, ret, action);
733 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
734 u - wsi->action_start,
735 u - wsi->latency_start,
736 (void *)wsi, ret, action);
737 wsi->action_start = 0;
739 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
740 u - wsi->latency_start, (void *)wsi, ret, action);
742 if (u - wsi->latency_start > context->worst_latency) {
743 context->worst_latency = u - wsi->latency_start;
744 strcpy(context->worst_latency_info, buf);
746 lwsl_latency("%s", buf);
753 * lws_rx_flow_control() - Enable and disable socket servicing for
756 * If the output side of a server process becomes choked, this allows flow
757 * control for the input side.
759 * @wsi: Websocket connection instance to get callback for
760 * @enable: 0 = disable read servicing for this connection, 1 = enable
764 lws_rx_flow_control(struct lws *wsi, int enable)
766 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
769 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
770 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
776 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
778 * When the user server code realizes it can accept more input, it can
779 * call this to have the RX flow restriction removed from all connections using
780 * the given protocol.
782 * @protocol: all connections using this protocol will be allowed to receive
786 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
787 const struct lws_protocols *protocol)
789 const struct lws_context_per_thread *pt = &context->pt[0];
791 unsigned int n, m = context->count_threads;
794 for (n = 0; n < pt->fds_count; n++) {
795 wsi = wsi_from_fd(context, pt->fds[n].fd);
798 if (wsi->protocol == protocol)
799 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
807 * lws_canonical_hostname() - returns this host's hostname
809 * This is typically used by client code to fill in the host parameter
810 * when making a client connection. You can only call it after the context
813 * @context: Websocket context
815 LWS_VISIBLE extern const char *
816 lws_canonical_hostname(struct lws_context *context)
818 return (const char *)context->canonical_hostname;
821 int user_callback_handle_rxflow(lws_callback_function callback_function,
823 enum lws_callback_reasons reason, void *user,
824 void *in, size_t len)
828 n = callback_function(wsi, reason, user, in, len);
830 n = _lws_rx_flow_control(wsi);
837 * lws_set_proxy() - Setups proxy to lws_context.
838 * @context: pointer to struct lws_context you want set proxy to
839 * @proxy: pointer to c string containing proxy in format address:port
841 * Returns 0 if proxy string was parsed and proxy was setup.
842 * Returns -1 if @proxy is NULL or has incorrect format.
844 * This is only required if your OS does not provide the http_proxy
845 * environment variable (eg, OSX)
847 * IMPORTANT! You should call this function right after creation of the
848 * lws_context and before call to connect. If you call this
849 * function after connect behavior is undefined.
850 * This function will override proxy settings made on lws_context
851 * creation with genenv() call.
855 lws_set_proxy(struct lws_context *context, const char *proxy)
863 p = strchr(proxy, '@');
864 if (p) { /* auth is around */
866 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
869 strncpy(authstring, proxy, p - proxy);
870 // null termination not needed on input
871 if (lws_b64_encode_string(authstring, (p - proxy),
872 context->proxy_basic_auth_token,
873 sizeof context->proxy_basic_auth_token) < 0)
876 lwsl_notice(" Proxy auth in use\n");
880 context->proxy_basic_auth_token[0] = '\0';
882 strncpy(context->http_proxy_address, proxy,
883 sizeof(context->http_proxy_address) - 1);
884 context->http_proxy_address[
885 sizeof(context->http_proxy_address) - 1] = '\0';
887 p = strchr(context->http_proxy_address, ':');
888 if (!p && !context->http_proxy_port) {
889 lwsl_err("http_proxy needs to be ads:port\n");
895 context->http_proxy_port = atoi(p + 1);
899 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
900 context->http_proxy_port);
905 lwsl_err("proxy auth too long\n");
911 * lws_get_protocol() - Returns a protocol pointer from a websocket
913 * @wsi: pointer to struct websocket you want to know the protocol of
916 * Some apis can act on all live connections of a given protocol,
917 * this is how you can get a pointer to the active protocol if needed.
920 LWS_VISIBLE const struct lws_protocols *
921 lws_get_protocol(struct lws *wsi)
923 return wsi->protocol;
927 lws_is_final_fragment(struct lws *wsi)
929 lwsl_info("%s: final %d, rx pk length %d, draining %d", __func__,
930 wsi->u.ws.final, wsi->u.ws.rx_packet_length,
931 wsi->u.ws.rx_draining_ext);
932 return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && !wsi->u.ws.rx_draining_ext;
935 LWS_VISIBLE unsigned char
936 lws_get_reserved_bits(struct lws *wsi)
938 return wsi->u.ws.rsv;
942 lws_ensure_user_space(struct lws *wsi)
944 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
948 /* allocate the per-connection user memory (if any) */
950 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
951 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
952 if (wsi->user_space == NULL) {
953 lwsl_err("Out of memory for conn user space\n");
957 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
958 __func__, wsi, wsi->protocol->per_session_data_size,
964 * lwsl_timestamp: generate logging timestamp string
966 * @level: logging level
967 * @p: char * buffer to take timestamp
970 * returns length written in p
973 lwsl_timestamp(int level, char *p, int len)
975 time_t o_now = time(NULL);
976 unsigned long long now;
977 struct tm *ptm = NULL;
984 ptm = localtime(&o_now);
986 if (localtime_r(&o_now, &tm))
990 for (n = 0; n < LLL_COUNT; n++) {
991 if (level != (1 << n))
993 now = time_in_microseconds() / 100;
996 "[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: ",
1003 (int)(now % 10000), log_level_names[n]);
1005 n = snprintf(p, len, "[%llu:%04d] %s: ",
1006 (unsigned long long) now / 10000,
1007 (int)(now % 10000), log_level_names[n]);
1014 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
1018 lwsl_timestamp(level, buf, sizeof(buf));
1020 fprintf(stderr, "%s%s", buf, line);
1023 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
1027 if (!(log_level & filter))
1030 vsnprintf(buf, sizeof(buf), format, vl);
1031 buf[sizeof(buf) - 1] = '\0';
1033 lwsl_emit(filter, buf);
1036 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
1040 va_start(ap, format);
1041 _lws_logv(filter, format, ap);
1046 * lws_set_log_level() - Set the logging bitfield
1047 * @level: OR together the LLL_ debug contexts you want output from
1048 * @log_emit_function: NULL to leave it as it is, or a user-supplied
1049 * function to perform log string emission instead of
1050 * the default stderr one.
1052 * log level defaults to "err", "warn" and "notice" contexts enabled and
1053 * emission on stderr.
1056 LWS_VISIBLE void lws_set_log_level(int level,
1057 void (*func)(int level, const char *line))
1065 * lws_use_ssl() - Find out if connection is using SSL
1066 * @wsi: websocket connection to check
1068 * Returns 0 if the connection is not using SSL, 1 if using SSL and
1069 * using verified cert, and 2 if using SSL but the cert was not
1070 * checked (appears for client wsi told to skip check on connection)
1073 lws_is_ssl(struct lws *wsi)
1075 #ifdef LWS_OPENSSL_SUPPORT
1076 return wsi->use_ssl;
1084 * lws_partial_buffered() - find out if lws buffered the last write
1085 * @wsi: websocket connection to check
1087 * Returns 1 if you cannot use lws_write because the last
1088 * write on this connection is still buffered, and can't be cleared without
1089 * returning to the service loop and waiting for the connection to be
1092 * If you will try to do >1 lws_write call inside a single
1093 * WRITEABLE callback, you must check this after every write and bail if
1094 * set, ask for a new writeable callback and continue writing from there.
1096 * This is never set at the start of a writeable callback, but any write
1101 lws_partial_buffered(struct lws *wsi)
1103 return !!wsi->trunc_len;
1106 void lws_set_protocol_write_pending(struct lws *wsi,
1107 enum lws_pending_protocol_send pend)
1109 lwsl_info("setting pps %d\n", pend);
1112 lwsl_err("pps overwrite\n");
1114 lws_rx_flow_control(wsi, 0);
1115 lws_callback_on_writable(wsi);
1119 lws_get_peer_write_allowance(struct lws *wsi)
1121 #ifdef LWS_USE_HTTP2
1122 /* only if we are using HTTP2 on this connection */
1123 if (wsi->mode != LWSCM_HTTP2_SERVING)
1125 /* user is only interested in how much he can send, or that he can't */
1126 if (wsi->u.http2.tx_credit <= 0)
1129 return wsi->u.http2.tx_credit;
1137 lws_union_transition(struct lws *wsi, enum connection_mode mode)
1139 lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode);
1140 memset(&wsi->u, 0, sizeof(wsi->u));
1144 LWS_VISIBLE struct lws_plat_file_ops *
1145 lws_get_fops(struct lws_context *context)
1147 return &context->fops;
1150 LWS_VISIBLE LWS_EXTERN struct lws_context *
1151 lws_get_context(const struct lws *wsi)
1153 return wsi->context;
1156 LWS_VISIBLE LWS_EXTERN int
1157 lws_get_count_threads(struct lws_context *context)
1159 return context->count_threads;
1162 LWS_VISIBLE LWS_EXTERN void *
1163 lws_wsi_user(struct lws *wsi)
1165 return wsi->user_space;
1168 LWS_VISIBLE LWS_EXTERN void
1169 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1170 unsigned char *buf, size_t len)
1172 unsigned char *p, *start;
1173 int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE;
1175 assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT);
1177 start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE];
1179 *p++ = (((int)status) >> 8) & 0xff;
1180 *p++ = ((int)status) & 0xff;
1183 while (len-- && p < start + budget)
1186 wsi->u.ws.close_in_ping_buffer_len = p - start;
1190 _lws_rx_flow_control(struct lws *wsi)
1192 /* there is no pending change */
1193 if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) {
1194 lwsl_debug("%s: no pending change\n", __func__);
1198 /* stuff is still buffered, not ready to really accept new input */
1199 if (wsi->rxflow_buffer) {
1200 /* get ourselves called back to deal with stashed buffer */
1201 lws_callback_on_writable(wsi);
1205 /* pending is cleared, we can change rxflow state */
1207 wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1209 lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1210 wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);
1212 /* adjust the pollfd for this wsi */
1214 if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
1215 if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
1216 lwsl_info("%s: fail\n", __func__);
1220 if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
1227 lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)
1229 static const unsigned char e0f4[] = {
1230 0xa0 | ((2 - 1) << 2) | 1, /* e0 */
1231 0x80 | ((4 - 1) << 2) | 1, /* e1 */
1232 0x80 | ((4 - 1) << 2) | 1, /* e2 */
1233 0x80 | ((4 - 1) << 2) | 1, /* e3 */
1234 0x80 | ((4 - 1) << 2) | 1, /* e4 */
1235 0x80 | ((4 - 1) << 2) | 1, /* e5 */
1236 0x80 | ((4 - 1) << 2) | 1, /* e6 */
1237 0x80 | ((4 - 1) << 2) | 1, /* e7 */
1238 0x80 | ((4 - 1) << 2) | 1, /* e8 */
1239 0x80 | ((4 - 1) << 2) | 1, /* e9 */
1240 0x80 | ((4 - 1) << 2) | 1, /* ea */
1241 0x80 | ((4 - 1) << 2) | 1, /* eb */
1242 0x80 | ((4 - 1) << 2) | 1, /* ec */
1243 0x80 | ((2 - 1) << 2) | 1, /* ed */
1244 0x80 | ((4 - 1) << 2) | 1, /* ee */
1245 0x80 | ((4 - 1) << 2) | 1, /* ef */
1246 0x90 | ((3 - 1) << 2) | 2, /* f0 */
1247 0x80 | ((4 - 1) << 2) | 2, /* f1 */
1248 0x80 | ((4 - 1) << 2) | 2, /* f2 */
1249 0x80 | ((4 - 1) << 2) | 2, /* f3 */
1250 0x80 | ((1 - 1) << 2) | 2, /* f4 */
1253 0x80 | ((4 - 1) << 2) | 0, /* s2 */
1254 0x80 | ((4 - 1) << 2) | 1, /* s3 */
1256 unsigned char s = *state;
1259 unsigned char c = *buf++;
1263 if (c < 0xc2 || c > 0xf4)
1266 s = 0x80 | ((4 - 1) << 2);
1271 if (c < (s & 0xf0) ||
1272 c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))
1274 s = e0f4[21 + (s & 3)];
1284 * lws_parse_uri: cut up prot:/ads:port/path into pieces
1285 * Notice it does so by dropping '\0' into input string
1286 * and the leading / on the path is consequently lost
1288 * @p: incoming uri string.. will get written to
1289 * @prot: result pointer for protocol part (https://)
1290 * @ads: result pointer for address part
1291 * @port: result pointer for port part
1292 * @path: result pointer for path part
1295 LWS_VISIBLE LWS_EXTERN int
1296 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1300 static const char *slash = "/";
1302 /* cut up the location into address, port and path */
1304 while (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))
1315 if (!strcmp(*prot, "http") || !strcmp(*prot, "ws"))
1317 else if (!strcmp(*prot, "https") || !strcmp(*prot, "wss"))
1320 while (*p && *p != ':' && *p != '/')
1325 while (*p && *p != '/')
1338 #ifdef LWS_NO_EXTENSIONS
1340 /* we need to provide dummy callbacks for internal exts
1341 * so user code runs when faced with a lib compiled with
1342 * extensions disabled.
1346 lws_extension_callback_pm_deflate(struct lws_context *context,
1347 const struct lws_extension *ext,
1349 enum lws_extension_callback_reasons reason,
1350 void *user, void *in, size_t len)
1364 LWS_VISIBLE LWS_EXTERN int
1365 lws_is_cgi(struct lws *wsi) {
1376 lws_create_basic_wsi(struct lws_context *context, int tsi)
1378 struct lws *new_wsi;
1380 if ((unsigned int)context->pt[tsi].fds_count ==
1381 context->fd_limit_per_thread - 1) {
1382 lwsl_err("no space for new conn\n");
1386 new_wsi = lws_zalloc(sizeof(struct lws));
1387 if (new_wsi == NULL) {
1388 lwsl_err("Out of memory for new connection\n");
1393 new_wsi->context = context;
1394 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1395 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1397 /* intialize the instance struct */
1399 new_wsi->state = LWSS_CGI;
1400 new_wsi->mode = LWSCM_CGI;
1401 new_wsi->hdr_parsing_completed = 0;
1402 new_wsi->position_in_fds_table = -1;
1405 * these can only be set once the protocol is known
1406 * we set an unestablished connection's protocol pointer
1407 * to the start of the supported list, so it can look
1408 * for matching ones during the handshake
1410 new_wsi->protocol = context->protocols;
1411 new_wsi->user_space = NULL;
1412 new_wsi->ietf_spec_revision = 0;
1413 new_wsi->sock = LWS_SOCK_INVALID;
1414 context->count_wsi_allocated++;
1420 * lws_cgi: spawn network-connected cgi process
1422 * @wsi: connection to own the process
1423 * @exec_array: array of "exec-name" "arg1" ... "argn" NULL
1426 LWS_VISIBLE LWS_EXTERN int
1427 lws_cgi(struct lws *wsi, char * const *exec_array, int timeout_secs)
1429 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1430 char *env_array[30], cgi_path[400];
1431 struct lws_cgi *cgi;
1435 * give the master wsi a cgi struct
1438 wsi->cgi = lws_zalloc(sizeof(*wsi->cgi));
1440 lwsl_err("%s: OOM\n", __func__);
1445 cgi->wsi = wsi; /* set cgi's owning wsi */
1447 /* create pipes for [stdin|stdout] and [stderr] */
1449 for (n = 0; n < 3; n++)
1450 if (pipe(cgi->pipe_fds[n]) == -1)
1453 /* create cgi wsis for each stdin/out/err fd */
1455 for (n = 0; n < 3; n++) {
1456 cgi->stdwsi[n] = lws_create_basic_wsi(wsi->context, wsi->tsi);
1457 if (!cgi->stdwsi[n])
1459 cgi->stdwsi[n]->cgi_channel = n;
1460 /* read side is 0, stdin we want the write side, others read */
1461 cgi->stdwsi[n]->sock = cgi->pipe_fds[n][!!(n == 0)];
1462 fcntl(cgi->pipe_fds[n][!!(n == 0)], F_SETFL, O_NONBLOCK);
1465 for (n = 0; n < 3; n++) {
1466 cgi->stdwsi[n]->master = wsi;
1467 if (insert_wsi_socket_into_fds(wsi->context, cgi->stdwsi[n]))
1471 lws_change_pollfd(cgi->stdwsi[LWS_STDIN], LWS_POLLIN, LWS_POLLOUT);
1472 lws_change_pollfd(cgi->stdwsi[LWS_STDOUT], LWS_POLLOUT, LWS_POLLIN);
1473 lws_change_pollfd(cgi->stdwsi[LWS_STDERR], LWS_POLLOUT, LWS_POLLIN);
1475 lwsl_debug("%s: fds in %d, out %d, err %d\n", __func__,
1476 cgi->stdwsi[LWS_STDIN]->sock,
1477 cgi->stdwsi[LWS_STDOUT]->sock,
1478 cgi->stdwsi[LWS_STDERR]->sock);
1480 lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, timeout_secs);
1482 /* add us to the pt list of active cgis */
1483 cgi->cgi_list = pt->cgi_list;
1486 /* prepare his CGI env */
1489 if (wsi->u.hdr.ah) {
1490 snprintf(cgi_path, sizeof(cgi_path) - 1, "PATH_INFO=%s",
1491 lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI));
1492 cgi_path[sizeof(cgi_path) - 1] = '\0';
1493 env_array[n++] = cgi_path;
1494 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
1495 env_array[n++] = "REQUEST_METHOD=POST";
1497 env_array[n++] = "REQUEST_METHOD=GET";
1499 if (lws_is_ssl(wsi))
1500 env_array[n++] = "HTTPS=ON";
1501 env_array[n++] = "SERVER_SOFTWARE=libwebsockets";
1502 env_array[n++] = "PATH=/bin:/usr/bin:/usrlocal/bin";
1503 env_array[n] = NULL;
1505 /* we are ready with the redirection pipes... run the thing */
1506 #ifdef LWS_HAVE_VFORK
1512 lwsl_err("fork failed, errno %d", errno);
1517 /* we are the parent process */
1520 /* We are the forked process, redirect and kill inherited things.
1522 * Because of vfork(), we cannot do anything that changes pages in
1523 * the parent environment. Stuff that changes kernel state for the
1524 * process is OK. Stuff that happens after the execvpe() is OK.
1527 for (n = 0; n < 3; n++) {
1528 if (dup2(cgi->pipe_fds[n][!(n == 0)], n) < 0) {
1529 lwsl_err("%s: stdin dup2 failed\n", __func__);
1532 close(cgi->pipe_fds[n][!(n == 0)]);
1535 execvpe(exec_array[0], &exec_array[0], &env_array[0]);
1539 /* drop us from the pt cgi list */
1540 pt->cgi_list = cgi->cgi_list;
1543 remove_wsi_socket_from_fds(wsi->cgi->stdwsi[n]);
1545 for (n = 0; n < 3; n++)
1546 if (wsi->cgi->stdwsi[n])
1547 lws_free_wsi(cgi->stdwsi[n]);
1550 for (n = 0; n < 3; n++) {
1551 if (cgi->pipe_fds[n][0])
1552 close(cgi->pipe_fds[n][0]);
1553 if (cgi->pipe_fds[n][1])
1554 close(cgi->pipe_fds[n][1]);
1557 lws_free_set_NULL(wsi->cgi);
1559 lwsl_err("%s: failed\n", __func__);
1565 * lws_cgi_kill: terminate cgi process associated with wsi
1567 * @wsi: connection to own the process
1569 LWS_VISIBLE LWS_EXTERN int
1570 lws_cgi_kill(struct lws *wsi)
1572 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1573 struct lws_cgi **pcgi = &pt->cgi_list;
1574 struct lws_cgi_args args;
1575 int n, status, do_close = 0;
1580 lwsl_notice("%s: wsi %p\n", __func__, wsi);
1584 if (wsi->cgi->pid > 0) {
1585 /* kill the process */
1586 n = kill(wsi->cgi->pid, SIGTERM);
1588 lwsl_err("%s: failed\n", __func__);
1591 waitpid(wsi->cgi->pid, &status, 0); /* !!! may hang !!! */
1594 args.stdwsi = &wsi->cgi->stdwsi[0];
1596 if (wsi->cgi->pid != -1 && user_callback_handle_rxflow(
1597 wsi->protocol->callback,
1598 wsi, LWS_CALLBACK_CGI_TERMINATED,
1600 (void *)&args, 0)) {
1602 do_close = !wsi->cgi->being_closed;
1605 /* remove us from the cgi list */
1607 if (*pcgi == wsi->cgi) {
1608 /* drop us from the pt cgi list */
1609 *pcgi = (*pcgi)->cgi_list;
1612 pcgi = &(*pcgi)->cgi_list;
1615 for (n = 0 ; n < 3; n++) {
1616 if (wsi->cgi->pipe_fds[n][!!(n == 0)] >= 0) {
1617 close(wsi->cgi->pipe_fds[n][!!(n == 0)]);
1618 wsi->cgi->pipe_fds[n][!!(n == 0)] = -1;
1620 lws_close_free_wsi(wsi->cgi->stdwsi[n], 0);
1624 lws_free_set_NULL(wsi->cgi);
1627 lws_close_free_wsi(wsi, 0);
1633 lws_cgi_kill_terminated(struct lws_context_per_thread *pt)
1635 struct lws_cgi **pcgi = &pt->cgi_list, *cgi;
1638 /* check all the subprocesses on the cgi list for termination */
1640 /* get the next one because we may close current one next */
1642 pcgi = &(*pcgi)->cgi_list;
1645 waitpid(cgi->pid, &status, WNOHANG) > 0) {
1647 lws_cgi_kill(cgi->wsi);
1648 pcgi = &pt->cgi_list;