2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "private-libwebsockets.h"
24 int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
25 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
27 static const char * const log_level_names[] = {
41 lws_free_wsi(struct lws *wsi)
46 /* Protocol user data may be allocated either internally by lws
47 * or by specified the user.
48 * We should only free what we allocated. */
49 if (wsi->protocol && wsi->protocol->per_session_data_size &&
50 wsi->user_space && !wsi->user_space_externally_allocated)
51 lws_free(wsi->user_space);
53 lws_free_set_NULL(wsi->rxflow_buffer);
54 lws_free_set_NULL(wsi->trunc_alloc);
55 lws_free_header_table(wsi);
60 lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason)
62 struct lws_context *context = wsi->context;
63 int n, m, ret, old_state;
64 struct lws_tokens eff_buf;
65 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
66 LWS_SEND_BUFFER_POST_PADDING];
71 old_state = wsi->state;
73 if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED &&
74 wsi->u.http.fd != LWS_INVALID_FILE) {
75 lwsl_debug("closing http file\n");
76 lws_plat_file_close(wsi, wsi->u.http.fd);
77 wsi->u.http.fd = LWS_INVALID_FILE;
78 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
79 wsi->user_space, NULL, 0);
81 if (wsi->socket_is_permanently_unusable ||
82 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)
83 goto just_kill_connection;
86 case LWSS_DEAD_SOCKET:
89 /* we tried the polite way... */
90 case LWSS_AWAITING_CLOSE_ACK:
91 goto just_kill_connection;
93 case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE:
95 lws_callback_on_writable(wsi);
98 lwsl_info("wsi %p completed LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
99 goto just_kill_connection;
101 if (wsi->trunc_len) {
102 lwsl_info("wsi %p entering LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
103 wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE;
104 lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);
110 wsi->u.ws.close_reason = reason;
112 if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT ||
113 wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE)
114 goto just_kill_connection;
116 if (wsi->mode == LWSCM_HTTP_SERVING)
117 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
118 wsi->user_space, NULL, 0);
121 * are his extensions okay with him closing? Eg he might be a mux
122 * parent and just his ch1 aspect is closing?
125 if (lws_ext_cb_wsi_active_exts(wsi,
126 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
127 lwsl_ext("extension vetoed close\n");
132 * flush any tx pending from extensions, since we may send close packet
133 * if there are problems with send, just nuke the connection
138 eff_buf.token = NULL;
139 eff_buf.token_len = 0;
141 /* show every extension the new incoming data */
143 m = lws_ext_cb_wsi_active_exts(wsi,
144 LWS_EXT_CALLBACK_FLUSH_PENDING_TX, &eff_buf, 0);
146 lwsl_ext("Extension reports fatal error\n");
147 goto just_kill_connection;
151 * at least one extension told us he has more
152 * to spill, so we will go around again after
156 /* assuming they left us something to send, send it */
158 if (eff_buf.token_len)
159 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
160 eff_buf.token_len) !=
162 lwsl_debug("close: ext spill failed\n");
163 goto just_kill_connection;
168 * signal we are closing, lws_write will
169 * add any necessary version-specific stuff. If the write fails,
170 * no worries we are closing anyway. If we didn't initiate this
171 * close, then our state has been changed to
172 * LWSS_RETURNED_CLOSE_ALREADY and we will skip this.
174 * Likewise if it's a second call to close this connection after we
175 * sent the close indication to the peer already, we are in state
176 * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time.
179 if (old_state == LWSS_ESTABLISHED &&
180 reason != LWS_CLOSE_STATUS_NOSTATUS &&
181 reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY) {
182 lwsl_debug("sending close indication...\n");
183 /* make valgrind happy */
184 memset(buf, 0, sizeof(buf));
185 n = lws_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING + 2],
189 * we have sent a nice protocol level indication we
190 * now wish to close, we should not send anything more
192 wsi->state = LWSS_AWAITING_CLOSE_ACK;
195 * ...and we should wait for a reply for a bit
198 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1);
199 lwsl_debug("sent close indication, awaiting ack\n");
204 lwsl_info("close: sending close packet failed, hanging up\n");
206 /* else, the send failed and we should just hang up */
209 just_kill_connection:
211 lwsl_debug("close: just_kill_connection\n");
214 * we won't be servicing or receiving anything further from this guy
215 * delete socket from the internal poll list if still present
217 lws_ssl_remove_wsi_from_buffered_list(wsi);
219 /* checking return redundant since we anyway close */
220 remove_wsi_socket_from_fds(wsi);
222 wsi->state = LWSS_DEAD_SOCKET;
224 lws_free_set_NULL(wsi->rxflow_buffer);
225 lws_free_header_table(wsi);
227 if (old_state == LWSS_ESTABLISHED ||
228 wsi->mode == LWSCM_WS_SERVING ||
229 wsi->mode == LWSCM_WS_CLIENT) {
231 lws_free_set_NULL(wsi->u.ws.rx_user_buffer);
233 if (wsi->trunc_alloc)
234 /* not going to be completed... nuke it */
235 lws_free_set_NULL(wsi->trunc_alloc);
237 if (wsi->u.ws.ping_payload_buf) {
238 lws_free_set_NULL(wsi->u.ws.ping_payload_buf);
239 wsi->u.ws.ping_payload_alloc = 0;
240 wsi->u.ws.ping_payload_len = 0;
241 wsi->u.ws.ping_pending_flag = 0;
245 /* tell the user it's all over for this guy */
247 if (wsi->protocol && wsi->protocol->callback &&
248 ((old_state == LWSS_ESTABLISHED) ||
249 (old_state == LWSS_RETURNED_CLOSE_ALREADY) ||
250 (old_state == LWSS_AWAITING_CLOSE_ACK) ||
251 (old_state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE))) {
252 lwsl_debug("calling back CLOSED\n");
253 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
254 wsi->user_space, NULL, 0);
255 } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) {
256 lwsl_debug("calling back CLOSED_HTTP\n");
257 context->protocols[0].callback(wsi, LWS_CALLBACK_CLOSED_HTTP,
258 wsi->user_space, NULL, 0 );
259 } else if (wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY ||
260 wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
261 lwsl_debug("Connection closed before server reply\n");
262 context->protocols[0].callback(wsi,
263 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
264 wsi->user_space, NULL, 0);
266 lwsl_debug("not calling back closed mode=%d state=%d\n",
267 wsi->mode, old_state);
269 /* deallocate any active extension contexts */
271 if (lws_ext_cb_wsi_active_exts(wsi, LWS_EXT_CALLBACK_DESTROY, NULL, 0) < 0)
272 lwsl_warn("extension destruction failed\n");
273 #ifndef LWS_NO_EXTENSIONS
274 for (n = 0; n < wsi->count_active_extensions; n++)
275 lws_free(wsi->active_extensions_user[n]);
278 * inform all extensions in case they tracked this guy out of band
279 * even though not active on him specifically
281 if (lws_ext_cb_all_exts(context, wsi,
282 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
283 lwsl_warn("ext destroy wsi failed\n");
285 if (!lws_ssl_close(wsi) && lws_socket_is_valid(wsi->sock)) {
287 n = shutdown(wsi->sock, SHUT_RDWR);
289 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
291 n = compatible_close(wsi->sock);
293 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
296 compatible_close(wsi->sock);
298 wsi->sock = LWS_SOCK_INVALID;
301 /* outermost destroy notification for wsi (user_space still intact) */
302 context->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,
303 wsi->user_space, NULL, 0);
309 lws_get_addresses(struct lws_context *context, void *ads, char *name,
310 int name_len, char *rip, int rip_len)
313 struct addrinfo ai, *res;
314 struct sockaddr_in addr4;
319 addr4.sin_family = AF_UNSPEC;
322 if (LWS_IPV6_ENABLED(context)) {
323 if (!lws_plat_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ads)->sin6_addr, rip, rip_len)) {
324 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
328 // Strip off the IPv4 to IPv6 header if one exists
329 if (strncmp(rip, "::ffff:", 7) == 0)
330 memmove(rip, rip + 7, strlen(rip) - 6);
332 getnameinfo((struct sockaddr *)ads,
333 sizeof(struct sockaddr_in6), name,
334 name_len, NULL, 0, 0);
340 struct addrinfo *result;
342 memset(&ai, 0, sizeof ai);
343 ai.ai_family = PF_UNSPEC;
344 ai.ai_socktype = SOCK_STREAM;
345 ai.ai_flags = AI_CANONNAME;
347 if (getnameinfo((struct sockaddr *)ads,
348 sizeof(struct sockaddr_in),
349 name, name_len, NULL, 0, 0))
355 if (getaddrinfo(name, NULL, &ai, &result))
359 while (addr4.sin_family == AF_UNSPEC && res) {
360 switch (res->ai_family) {
362 addr4.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
363 addr4.sin_family = AF_INET;
369 freeaddrinfo(result);
372 if (addr4.sin_family == AF_UNSPEC)
375 lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len);
391 * lws_get_peer_addresses() - Get client address information
392 * @wsi: Local struct lws associated with
393 * @fd: Connection socket descriptor
394 * @name: Buffer to take client address name
395 * @name_len: Length of client address name buffer
396 * @rip: Buffer to take client address IP dotted quad
397 * @rip_len: Length of client address IP buffer
399 * This function fills in @name and @rip with the name and IP of
400 * the client connected with socket descriptor @fd. Names may be
401 * truncated if there is not enough room. If either cannot be
402 * determined, they will be returned as valid zero-length strings.
406 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
407 int name_len, char *rip, int rip_len)
412 struct sockaddr_in6 sin6;
414 struct sockaddr_in sin4;
415 struct lws_context *context = wsi->context;
422 lws_latency_pre(context, wsi);
425 if (LWS_IPV6_ENABLED(context)) {
435 if (getpeername(fd, p, &len) < 0) {
436 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
440 ret = lws_get_addresses(context, p, name, name_len, rip, rip_len);
443 lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1);
455 * lws_context_user() - get the user data associated with the context
456 * @context: Websocket context
458 * This returns the optional user allocation that can be attached to
459 * the context the sockets live in at context_create time. It's a way
460 * to let all sockets serviced in the same context share data without
461 * using globals statics in the user code.
464 lws_context_user(struct lws_context *context)
466 return context->user_space;
471 * lws_callback_all_protocol() - Callback all connections using
472 * the given protocol with the given reason
474 * @protocol: Protocol whose connections will get callbacks
475 * @reason: Callback reason index
479 lws_callback_all_protocol(struct lws_context *context,
480 const struct lws_protocols *protocol, int reason)
485 for (n = 0; n < context->fds_count; n++) {
486 wsi = wsi_from_fd(context, context->fds[n].fd);
489 if (wsi->protocol == protocol)
490 protocol->callback(wsi, reason, wsi->user_space, NULL, 0);
497 * lws_set_timeout() - marks the wsi as subject to a timeout
499 * You will not need this unless you are doing something special
501 * @wsi: Websocket connection instance
502 * @reason: timeout reason
503 * @secs: how many seconds
507 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)
513 wsi->pending_timeout_limit = now + secs;
514 wsi->pending_timeout = reason;
521 * lws_get_socket_fd() - returns the socket file descriptor
523 * You will not need this unless you are doing something special
525 * @wsi: Websocket connection instance
529 lws_get_socket_fd(struct lws *wsi)
538 lws_latency(struct lws_context *context, struct lws *wsi, const char *action,
539 int ret, int completed)
541 unsigned long long u;
544 u = time_in_microseconds();
547 wsi->latency_start = u;
548 if (!wsi->action_start)
549 wsi->action_start = u;
553 if (wsi->action_start == wsi->latency_start)
555 "Completion first try lat %lluus: %p: ret %d: %s\n",
556 u - wsi->latency_start,
557 (void *)wsi, ret, action);
560 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
561 u - wsi->action_start,
562 u - wsi->latency_start,
563 (void *)wsi, ret, action);
564 wsi->action_start = 0;
566 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
567 u - wsi->latency_start, (void *)wsi, ret, action);
569 if (u - wsi->latency_start > context->worst_latency) {
570 context->worst_latency = u - wsi->latency_start;
571 strcpy(context->worst_latency_info, buf);
573 lwsl_latency("%s", buf);
580 * lws_rx_flow_control() - Enable and disable socket servicing for
583 * If the output side of a server process becomes choked, this allows flow
584 * control for the input side.
586 * @wsi: Websocket connection instance to get callback for
587 * @enable: 0 = disable read servicing for this connection, 1 = enable
591 lws_rx_flow_control(struct lws *wsi, int enable)
593 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
596 lwsl_info("%s: (0x%p, %d)\n", __func__, wsi, enable);
597 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
603 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
605 * When the user server code realizes it can accept more input, it can
606 * call this to have the RX flow restriction removed from all connections using
607 * the given protocol.
609 * @protocol: all connections using this protocol will be allowed to receive
613 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
614 const struct lws_protocols *protocol)
619 for (n = 0; n < context->fds_count; n++) {
620 wsi = wsi_from_fd(context, context->fds[n].fd);
623 if (wsi->protocol == protocol)
624 lws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
630 * lws_canonical_hostname() - returns this host's hostname
632 * This is typically used by client code to fill in the host parameter
633 * when making a client connection. You can only call it after the context
636 * @context: Websocket context
638 LWS_VISIBLE extern const char *
639 lws_canonical_hostname(struct lws_context *context)
641 return (const char *)context->canonical_hostname;
644 int user_callback_handle_rxflow(callback_function callback_function,
646 enum lws_callback_reasons reason, void *user,
647 void *in, size_t len)
651 n = callback_function(wsi, reason, user, in, len);
653 n = _lws_rx_flow_control(wsi);
660 * lws_set_proxy() - Setups proxy to lws_context.
661 * @context: pointer to struct lws_context you want set proxy to
662 * @proxy: pointer to c string containing proxy in format address:port
664 * Returns 0 if proxy string was parsed and proxy was setup.
665 * Returns -1 if @proxy is NULL or has incorrect format.
667 * This is only required if your OS does not provide the http_proxy
668 * environment variable (eg, OSX)
670 * IMPORTANT! You should call this function right after creation of the
671 * lws_context and before call to connect. If you call this
672 * function after connect behavior is undefined.
673 * This function will override proxy settings made on lws_context
674 * creation with genenv() call.
678 lws_set_proxy(struct lws_context *context, const char *proxy)
686 p = strchr(proxy, '@');
687 if (p) { /* auth is around */
689 if ((unsigned int)(p - proxy) > sizeof(authstring) - 1)
692 strncpy(authstring, proxy, p - proxy);
693 // null termination not needed on input
694 if (lws_b64_encode_string(authstring, (p - proxy),
695 context->proxy_basic_auth_token,
696 sizeof context->proxy_basic_auth_token) < 0)
699 lwsl_notice(" Proxy auth in use\n");
703 context->proxy_basic_auth_token[0] = '\0';
705 strncpy(context->http_proxy_address, proxy,
706 sizeof(context->http_proxy_address) - 1);
707 context->http_proxy_address[
708 sizeof(context->http_proxy_address) - 1] = '\0';
710 p = strchr(context->http_proxy_address, ':');
711 if (!p && !context->http_proxy_port) {
712 lwsl_err("http_proxy needs to be ads:port\n");
718 context->http_proxy_port = atoi(p + 1);
722 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
723 context->http_proxy_port);
728 lwsl_err("proxy auth too long\n");
734 * lws_get_protocol() - Returns a protocol pointer from a websocket
736 * @wsi: pointer to struct websocket you want to know the protocol of
739 * Some apis can act on all live connections of a given protocol,
740 * this is how you can get a pointer to the active protocol if needed.
743 LWS_VISIBLE const struct lws_protocols *
744 lws_get_protocol(struct lws *wsi)
746 return wsi->protocol;
750 lws_is_final_fragment(struct lws *wsi)
752 return wsi->u.ws.final;
755 LWS_VISIBLE unsigned char
756 lws_get_reserved_bits(struct lws *wsi)
758 return wsi->u.ws.rsv;
762 lws_ensure_user_space(struct lws *wsi)
764 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
768 /* allocate the per-connection user memory (if any) */
770 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
771 wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size);
772 if (wsi->user_space == NULL) {
773 lwsl_err("Out of memory for conn user space\n");
777 lwsl_info("%s: %p protocol pss %u, user_space=%d\n",
778 __func__, wsi, wsi->protocol->per_session_data_size,
783 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
785 unsigned long long now;
790 for (n = 0; n < LLL_COUNT; n++) {
791 if (level != (1 << n))
793 now = time_in_microseconds() / 100;
794 sprintf(buf, "[%llu:%04d] %s: ",
795 (unsigned long long) now / 10000,
796 (int)(now % 10000), log_level_names[n]);
800 fprintf(stderr, "%s%s", buf, line);
803 LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)
807 if (!(log_level & filter))
810 vsnprintf(buf, sizeof(buf), format, vl);
811 buf[sizeof(buf) - 1] = '\0';
813 lwsl_emit(filter, buf);
816 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
820 va_start(ap, format);
821 _lws_logv(filter, format, ap);
826 * lws_set_log_level() - Set the logging bitfield
827 * @level: OR together the LLL_ debug contexts you want output from
828 * @log_emit_function: NULL to leave it as it is, or a user-supplied
829 * function to perform log string emission instead of
830 * the default stderr one.
832 * log level defaults to "err", "warn" and "notice" contexts enabled and
833 * emission on stderr.
836 LWS_VISIBLE void lws_set_log_level(int level,
837 void (*func)(int level, const char *line))
845 * lws_use_ssl() - Find out if connection is using SSL
846 * @wsi: websocket connection to check
848 * Returns 0 if the connection is not using SSL, 1 if using SSL and
849 * using verified cert, and 2 if using SSL but the cert was not
850 * checked (appears for client wsi told to skip check on connection)
853 lws_is_ssl(struct lws *wsi)
855 #ifdef LWS_OPENSSL_SUPPORT
864 * lws_partial_buffered() - find out if lws buffered the last write
865 * @wsi: websocket connection to check
867 * Returns 1 if you cannot use lws_write because the last
868 * write on this connection is still buffered, and can't be cleared without
869 * returning to the service loop and waiting for the connection to be
872 * If you will try to do >1 lws_write call inside a single
873 * WRITEABLE callback, you must check this after every write and bail if
874 * set, ask for a new writeable callback and continue writing from there.
876 * This is never set at the start of a writeable callback, but any write
881 lws_partial_buffered(struct lws *wsi)
883 return !!wsi->trunc_len;
886 void lws_set_protocol_write_pending(struct lws *wsi,
887 enum lws_pending_protocol_send pend)
889 lwsl_info("setting pps %d\n", pend);
892 lwsl_err("pps overwrite\n");
894 lws_rx_flow_control(wsi, 0);
895 lws_callback_on_writable(wsi);
899 lws_get_peer_write_allowance(struct lws *wsi)
902 /* only if we are using HTTP2 on this connection */
903 if (wsi->mode != LWSCM_HTTP2_SERVING)
905 /* user is only interested in how much he can send, or that he can't */
906 if (wsi->u.http2.tx_credit <= 0)
909 return wsi->u.http2.tx_credit;
917 lws_union_transition(struct lws *wsi, enum connection_mode mode)
919 memset(&wsi->u, 0, sizeof(wsi->u));
923 LWS_VISIBLE struct lws_plat_file_ops *
924 lws_get_fops(struct lws_context *context)
926 return &context->fops;
929 LWS_VISIBLE LWS_EXTERN struct lws_context *
930 lws_get_context(const struct lws *wsi)
935 LWS_VISIBLE LWS_EXTERN void *
936 lws_wsi_user(struct lws *wsi)
938 return wsi->user_space;