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[] = {
42 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
43 struct libwebsocket *wsi, enum lws_close_status reason)
47 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
48 LWS_SEND_BUFFER_POST_PADDING];
49 struct lws_tokens eff_buf;
54 old_state = wsi->state;
56 if (wsi->socket_is_permanently_unusable)
57 goto just_kill_connection;
60 case WSI_STATE_DEAD_SOCKET:
63 /* we tried the polite way... */
64 case WSI_STATE_AWAITING_CLOSE_ACK:
65 goto just_kill_connection;
67 case WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE:
68 if (wsi->truncated_send_len) {
69 libwebsocket_callback_on_writable(context, wsi);
72 lwsl_info("wsi %p completed WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
73 goto just_kill_connection;
75 if (wsi->truncated_send_len) {
76 lwsl_info("wsi %p entering WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi);
77 wsi->state = WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE;
83 wsi->u.ws.close_reason = reason;
85 if (wsi->mode == LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT ||
86 wsi->mode == LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE) {
88 context->protocols[0].callback(context, wsi,
89 LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, NULL, 0);
91 lws_free_header_table(wsi);
92 goto just_kill_connection;
95 if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) {
96 if (wsi->u.http.fd != LWS_INVALID_FILE) {
97 lwsl_debug("closing http file\n");
98 compatible_file_close(wsi->u.http.fd);
99 wsi->u.http.fd = LWS_INVALID_FILE;
100 context->protocols[0].callback(context, wsi,
101 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
106 * are his extensions okay with him closing? Eg he might be a mux
107 * parent and just his ch1 aspect is closing?
110 if (lws_ext_callback_for_each_active(wsi,
111 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) {
112 lwsl_ext("extension vetoed close\n");
117 * flush any tx pending from extensions, since we may send close packet
118 * if there are problems with send, just nuke the connection
123 eff_buf.token = NULL;
124 eff_buf.token_len = 0;
126 /* show every extension the new incoming data */
128 m = lws_ext_callback_for_each_active(wsi,
129 LWS_EXT_CALLBACK_FLUSH_PENDING_TX, &eff_buf, 0);
131 lwsl_ext("Extension reports fatal error\n");
132 goto just_kill_connection;
136 * at least one extension told us he has more
137 * to spill, so we will go around again after
141 /* assuming they left us something to send, send it */
143 if (eff_buf.token_len)
144 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
145 eff_buf.token_len) != eff_buf.token_len) {
146 lwsl_debug("close: ext spill failed\n");
147 goto just_kill_connection;
152 * signal we are closing, libwebsocket_write will
153 * add any necessary version-specific stuff. If the write fails,
154 * no worries we are closing anyway. If we didn't initiate this
155 * close, then our state has been changed to
156 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
158 * Likewise if it's a second call to close this connection after we
159 * sent the close indication to the peer already, we are in state
160 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
163 if (old_state == WSI_STATE_ESTABLISHED &&
164 reason != LWS_CLOSE_STATUS_NOSTATUS) {
166 lwsl_debug("sending close indication...\n");
168 /* make valgrind happy */
169 memset(buf, 0, sizeof(buf));
170 n = libwebsocket_write(wsi,
171 &buf[LWS_SEND_BUFFER_PRE_PADDING + 2],
175 * we have sent a nice protocol level indication we
176 * now wish to close, we should not send anything more
179 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
182 * ...and we should wait for a reply for a bit
186 libwebsocket_set_timeout(wsi,
187 PENDING_TIMEOUT_CLOSE_ACK, 1);
189 lwsl_debug("sent close indication, awaiting ack\n");
194 lwsl_info("close: sending close packet failed, hanging up\n");
196 /* else, the send failed and we should just hang up */
199 just_kill_connection:
201 lwsl_debug("close: just_kill_connection\n");
204 * we won't be servicing or receiving anything further from this guy
205 * delete socket from the internal poll list if still present
208 remove_wsi_socket_from_fds(context, wsi);
210 wsi->state = WSI_STATE_DEAD_SOCKET;
212 if (wsi->rxflow_buffer) {
213 free(wsi->rxflow_buffer);
214 wsi->rxflow_buffer = NULL;
217 if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING && wsi->u.hdr.ah) {
219 wsi->u.hdr.ah = NULL;
222 if ((old_state == WSI_STATE_ESTABLISHED ||
223 wsi->mode == LWS_CONNMODE_WS_SERVING ||
224 wsi->mode == LWS_CONNMODE_WS_CLIENT)) {
226 if (wsi->u.ws.rx_user_buffer) {
227 free(wsi->u.ws.rx_user_buffer);
228 wsi->u.ws.rx_user_buffer = NULL;
231 if (wsi->truncated_send_malloc) {
232 /* not going to be completed... nuke it */
233 free(wsi->truncated_send_malloc);
234 wsi->truncated_send_malloc = NULL;
235 wsi->truncated_send_len = 0;
237 if (wsi->u.ws.ping_payload_buf) {
238 free(wsi->u.ws.ping_payload_buf);
239 wsi->u.ws.ping_payload_buf = NULL;
240 wsi->u.ws.ping_payload_alloc = 0;
241 wsi->u.ws.ping_payload_len = 0;
245 /* tell the user it's all over for this guy */
247 if (wsi->protocol && wsi->protocol->callback &&
248 ((old_state == WSI_STATE_ESTABLISHED) ||
249 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
250 (old_state == WSI_STATE_AWAITING_CLOSE_ACK) ||
251 (old_state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE))) {
252 lwsl_debug("calling back CLOSED\n");
253 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
254 wsi->user_space, NULL, 0);
255 } else if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) {
256 lwsl_debug("calling back CLOSED_HTTP\n");
257 context->protocols[0].callback(context, wsi,
258 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0 );
260 lwsl_debug("not calling back closed\n");
262 /* deallocate any active extension contexts */
264 if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_DESTROY, NULL, 0) < 0)
265 lwsl_warn("extension destruction failed\n");
266 #ifndef LWS_NO_EXTENSIONS
267 for (n = 0; n < wsi->count_active_extensions; n++)
268 free(wsi->active_extensions_user[n]);
271 * inform all extensions in case they tracked this guy out of band
272 * even though not active on him specifically
274 if (lws_ext_callback_for_each_extension_type(context, wsi,
275 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0)
276 lwsl_warn("ext destroy wsi failed\n");
278 /* lwsl_info("closing fd=%d\n", wsi->sock); */
280 if (!lws_ssl_close(wsi) && wsi->sock >= 0) {
281 n = shutdown(wsi->sock, SHUT_RDWR);
283 lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO);
285 n = compatible_close(wsi->sock);
287 lwsl_debug("closing: close ret %d\n", LWS_ERRNO);
290 /* outermost destroy notification for wsi (user_space still intact) */
291 context->protocols[0].callback(context, wsi,
292 LWS_CALLBACK_WSI_DESTROY, wsi->user_space, NULL, 0);
294 if (wsi->protocol && wsi->protocol->per_session_data_size &&
295 wsi->user_space && !wsi->user_space_externally_allocated)
296 free(wsi->user_space);
298 /* As a precaution, free the header table in case it lingered: */
299 lws_free_header_table(wsi);
304 * libwebsockets_get_peer_addresses() - Get client address information
305 * @context: Libwebsockets context
306 * @wsi: Local struct libwebsocket associated with
307 * @fd: Connection socket descriptor
308 * @name: Buffer to take client address name
309 * @name_len: Length of client address name buffer
310 * @rip: Buffer to take client address IP dotted quad
311 * @rip_len: Length of client address IP buffer
313 * This function fills in @name and @rip with the name and IP of
314 * the client connected with socket descriptor @fd. Names may be
315 * truncated if there is not enough room. If either cannot be
316 * determined, they will be returned as valid zero-length strings.
320 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
321 struct libwebsocket *wsi, int fd, char *name, int name_len,
322 char *rip, int rip_len)
326 struct sockaddr_in6 sin6;
328 struct sockaddr_in sin4;
329 struct hostent *host;
330 struct hostent *host1;
335 struct sockaddr_un *un;
342 lws_latency_pre(context, wsi);
345 if (LWS_IPV6_ENABLED(context)) {
348 if (getpeername(fd, (struct sockaddr *) &sin6, &len) < 0) {
349 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
353 if (!lws_plat_inet_ntop(AF_INET6, &sin6.sin6_addr, rip, rip_len)) {
354 lwsl_err("inet_ntop", strerror(LWS_ERRNO));
358 // Strip off the IPv4 to IPv6 header if one exists
359 if (strncmp(rip, "::ffff:", 7) == 0)
360 memmove(rip, rip + 7, strlen(rip) - 6);
362 getnameinfo((struct sockaddr *)&sin6,
363 sizeof(struct sockaddr_in6), name,
364 name_len, NULL, 0, 0);
370 if (getpeername(fd, (struct sockaddr *) &sin4, &len) < 0) {
371 lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO));
374 host = gethostbyaddr((char *) &sin4.sin_addr,
375 sizeof(sin4.sin_addr), AF_INET);
377 lwsl_warn("gethostbyaddr: %s\n", strerror(LWS_ERRNO));
381 strncpy(name, host->h_name, name_len);
382 name[name_len - 1] = '\0';
384 host1 = gethostbyname(host->h_name);
387 p = (unsigned char *)host1;
390 p = (unsigned char *)host1->h_addr_list[n++];
393 if ((host1->h_addrtype != AF_INET)
395 && (host1->h_addrtype != AF_LOCAL)
400 if (host1->h_addrtype == AF_INET)
401 sprintf(ip, "%u.%u.%u.%u",
402 p[0], p[1], p[2], p[3]);
405 un = (struct sockaddr_un *)p;
406 strncpy(ip, un->sun_path, sizeof(ip) - 1);
407 ip[sizeof(ip) - 1] = '\0';
411 strncpy(rip, ip, rip_len);
412 rip[rip_len - 1] = '\0';
418 lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1);
424 * libwebsocket_context_user() - get the user data associated with the context
425 * @context: Websocket context
427 * This returns the optional user allocation that can be attached to
428 * the context the sockets live in at context_create time. It's a way
429 * to let all sockets serviced in the same context share data without
430 * using globals statics in the user code.
433 libwebsocket_context_user(struct libwebsocket_context *context)
435 return context->user_space;
440 * libwebsocket_callback_all_protocol() - Callback all connections using
441 * the given protocol with the given reason
443 * @protocol: Protocol whose connections will get callbacks
444 * @reason: Callback reason index
448 libwebsocket_callback_all_protocol(
449 const struct libwebsocket_protocols *protocol, int reason)
451 struct libwebsocket_context *context = protocol->owning_server;
453 struct libwebsocket *wsi;
455 for (n = 0; n < context->fds_count; n++) {
456 wsi = context->lws_lookup[context->fds[n].fd];
459 if (wsi->protocol == protocol)
460 protocol->callback(context, wsi,
461 reason, wsi->user_space, NULL, 0);
468 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
470 * You will not need this unless you are doing something special
472 * @wsi: Websocket connection instance
473 * @reason: timeout reason
474 * @secs: how many seconds
478 libwebsocket_set_timeout(struct libwebsocket *wsi,
479 enum pending_timeout reason, int secs)
485 wsi->pending_timeout_limit = now + secs;
486 wsi->pending_timeout = reason;
491 * libwebsocket_get_socket_fd() - returns the socket file descriptor
493 * You will not need this unless you are doing something special
495 * @wsi: Websocket connection instance
499 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
506 lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi,
507 const char *action, int ret, int completed)
509 unsigned long long u;
512 u = time_in_microseconds();
515 wsi->latency_start = u;
516 if (!wsi->action_start)
517 wsi->action_start = u;
521 if (wsi->action_start == wsi->latency_start)
523 "Completion first try lat %lluus: %p: ret %d: %s\n",
524 u - wsi->latency_start,
525 (void *)wsi, ret, action);
528 "Completion %lluus: lat %lluus: %p: ret %d: %s\n",
529 u - wsi->action_start,
530 u - wsi->latency_start,
531 (void *)wsi, ret, action);
532 wsi->action_start = 0;
534 sprintf(buf, "lat %lluus: %p: ret %d: %s\n",
535 u - wsi->latency_start, (void *)wsi, ret, action);
537 if (u - wsi->latency_start > context->worst_latency) {
538 context->worst_latency = u - wsi->latency_start;
539 strcpy(context->worst_latency_info, buf);
541 lwsl_latency("%s", buf);
548 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
551 * If the output side of a server process becomes choked, this allows flow
552 * control for the input side.
554 * @wsi: Websocket connection instance to get callback for
555 * @enable: 0 = disable read servicing for this connection, 1 = enable
559 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
561 if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW))
564 lwsl_info("libwebsocket_rx_flow_control(0x%p, %d)\n", wsi, enable);
565 wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
571 * libwebsocket_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
573 * When the user server code realizes it can accept more input, it can
574 * call this to have the RX flow restriction removed from all connections using
575 * the given protocol.
577 * @protocol: all connections using this protocol will be allowed to receive
581 libwebsocket_rx_flow_allow_all_protocol(
582 const struct libwebsocket_protocols *protocol)
584 struct libwebsocket_context *context = protocol->owning_server;
586 struct libwebsocket *wsi;
588 for (n = 0; n < context->fds_count; n++) {
589 wsi = context->lws_lookup[context->fds[n].fd];
592 if (wsi->protocol == protocol)
593 libwebsocket_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
599 * libwebsocket_canonical_hostname() - returns this host's hostname
601 * This is typically used by client code to fill in the host parameter
602 * when making a client connection. You can only call it after the context
605 * @context: Websocket context
607 LWS_VISIBLE extern const char *
608 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
610 return (const char *)context->canonical_hostname;
613 int user_callback_handle_rxflow(callback_function callback_function,
614 struct libwebsocket_context *context,
615 struct libwebsocket *wsi,
616 enum libwebsocket_callback_reasons reason, void *user,
617 void *in, size_t len)
621 n = callback_function(context, wsi, reason, user, in, len);
623 n = _libwebsocket_rx_flow_control(wsi);
630 * libwebsocket_set_proxy() - Setups proxy to libwebsocket_context.
631 * @context: pointer to struct libwebsocket_context you want set proxy to
632 * @proxy: pointer to c string containing proxy in format address:port
634 * Returns 0 if proxy string was parsed and proxy was setup.
635 * Returns -1 if @proxy is NULL or has incorrect format.
637 * This is only required if your OS does not provide the http_proxy
638 * environment variable (eg, OSX)
640 * IMPORTANT! You should call this function right after creation of the
641 * libwebsocket_context and before call to connect. If you call this
642 * function after connect behavior is undefined.
643 * This function will override proxy settings made on libwebsocket_context
644 * creation with genenv() call.
648 libwebsocket_set_proxy(struct libwebsocket_context *context, const char *proxy)
655 strncpy(context->http_proxy_address, proxy,
656 sizeof(context->http_proxy_address) - 1);
657 context->http_proxy_address[
658 sizeof(context->http_proxy_address) - 1] = '\0';
660 p = strchr(context->http_proxy_address, ':');
662 lwsl_err("http_proxy needs to be ads:port\n");
667 context->http_proxy_port = atoi(p + 1);
669 lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
670 context->http_proxy_port);
676 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
678 * @wsi: pointer to struct websocket you want to know the protocol of
681 * Some apis can act on all live connections of a given protocol,
682 * this is how you can get a pointer to the active protocol if needed.
685 LWS_VISIBLE const struct libwebsocket_protocols *
686 libwebsockets_get_protocol(struct libwebsocket *wsi)
688 return wsi->protocol;
692 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
694 return wsi->u.ws.final;
697 LWS_VISIBLE unsigned char
698 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
700 return wsi->u.ws.rsv;
704 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
706 lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol);
710 /* allocate the per-connection user memory (if any) */
712 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
713 wsi->user_space = malloc(
714 wsi->protocol->per_session_data_size);
715 if (wsi->user_space == NULL) {
716 lwsl_err("Out of memory for conn user space\n");
719 memset(wsi->user_space, 0,
720 wsi->protocol->per_session_data_size);
722 lwsl_info("%s: %p protocol pss %u, user_space=%d\n", __func__, wsi, wsi->protocol->per_session_data_size, wsi->user_space);
726 LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)
729 unsigned long long now;
733 for (n = 0; n < LLL_COUNT; n++)
734 if (level == (1 << n)) {
735 now = time_in_microseconds() / 100;
736 sprintf(buf, "[%lu:%04d] %s: ", (unsigned long) now / 10000,
737 (int)(now % 10000), log_level_names[n]);
741 fprintf(stderr, "%s%s", buf, line);
745 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
750 if (!(log_level & filter))
753 va_start(ap, format);
754 vsnprintf(buf, sizeof(buf), format, ap);
755 buf[sizeof(buf) - 1] = '\0';
758 lwsl_emit(filter, buf);
762 * lws_set_log_level() - Set the logging bitfield
763 * @level: OR together the LLL_ debug contexts you want output from
764 * @log_emit_function: NULL to leave it as it is, or a user-supplied
765 * function to perform log string emission instead of
766 * the default stderr one.
768 * log level defaults to "err", "warn" and "notice" contexts enabled and
769 * emission on stderr.
772 LWS_VISIBLE void lws_set_log_level(int level, void (*log_emit_function)(int level,
776 if (log_emit_function)
777 lwsl_emit = log_emit_function;
781 * lws_use_ssl() - Find out if connection is using SSL
782 * @wsi: websocket connection to check
784 * Returns 0 if the connection is not using SSL, 1 if using SSL and
785 * using verified cert, and 2 if using SSL but the cert was not
786 * checked (appears for client wsi told to skip check on connection)
789 lws_is_ssl(struct libwebsocket *wsi)
791 #ifdef LWS_OPENSSL_SUPPORT
799 * lws_partial_buffered() - find out if lws buffered the last write
800 * @wsi: websocket connection to check
802 * Returns 1 if you cannot use libwebsocket_write because the last
803 * write on this connection is still buffered, and can't be cleared without
804 * returning to the service loop and waiting for the connection to be
807 * If you will try to do >1 libwebsocket_write call inside a single
808 * WRITEABLE callback, you must check this after every write and bail if
809 * set, ask for a new writeable callback and continue writing from there.
811 * This is never set at the start of a writeable callback, but any write
816 lws_partial_buffered(struct libwebsocket *wsi)
818 return !!wsi->truncated_send_len;
821 void lws_set_protocol_write_pending(struct libwebsocket_context *context,
822 struct libwebsocket *wsi,
823 enum lws_pending_protocol_send pend)
825 lwsl_info("setting pps %d\n", pend);
828 lwsl_err("pps overwrite\n");
830 libwebsocket_rx_flow_control(wsi, 0);
831 libwebsocket_callback_on_writable(context, wsi);
835 lws_get_peer_write_allowance(struct libwebsocket *wsi)
838 /* only if we are using HTTP2 on this connection */
839 if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING)
841 /* user is only interested in how much he can send, or that he can't */
842 if (wsi->u.http2.tx_credit <= 0)
845 return wsi->u.http2.tx_credit;
852 lws_union_transition(struct libwebsocket *wsi, enum connection_mode mode)
854 memset(&wsi->u, 0, sizeof(wsi->u));