Skip to content
Snippets Groups Projects
server.c 33.9 KiB
Newer Older
  • Learn to ignore specific revisions
  • /*
     * libwebsockets - small server side websockets and web server implementation
     *
    
     * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
    
     *
     *  This library is free software; you can redistribute it and/or
     *  modify it under the terms of the GNU Lesser General Public
     *  License as published by the Free Software Foundation:
     *  version 2.1 of the License.
     *
     *  This library is distributed in the hope that it will be useful,
     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     *  Lesser General Public License for more details.
     *
     *  You should have received a copy of the GNU Lesser General Public
     *  License along with this library; if not, write to the Free Software
     *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     *  MA  02110-1301  USA
     */
    
    
    #include "private-libwebsockets.h"
    
    
    int
    lws_context_init_server(struct lws_context_creation_info *info,
    			struct lws_context *context)
    
    Andy Green's avatar
    Andy Green committed
    	int n, opt = 1, limit = 1;
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    	lws_sockfd_type sockfd;
    
    Andy Green's avatar
    Andy Green committed
    	int m = 0;
    
    
    	/* set up our external listening socket we serve on */
    
    	if (info->port == CONTEXT_PORT_NO_LISTEN)
    		return 0;
    
    
    Andy Green's avatar
    Andy Green committed
    #if LWS_POSIX
    
    Andy Green's avatar
    Andy Green committed
    #if defined(__linux__)
    	limit = context->count_threads;
    #endif
    
    	for (m = 0; m < limit; m++) {
    
    #ifdef LWS_USE_IPV6
    	if (LWS_IPV6_ENABLED(context))
    		sockfd = socket(AF_INET6, SOCK_STREAM, 0);
    	else
    #endif
    		sockfd = socket(AF_INET, SOCK_STREAM, 0);
    
    	if (sockfd == -1) {
    
    Andy Green's avatar
    Andy Green committed
    #else
    	sockfd = mbed3_create_tcp_stream_socket();
    	if (!lws_sockfd_valid(sockfd)) {
    #endif
    
    Andy Green's avatar
    Andy Green committed
    #if LWS_POSIX
    
    	/*
    	 * allow us to restart even if old sockets in TIME_WAIT
    	 */
    
    	if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
    
    		       (const void *)&opt, sizeof(opt)) < 0) {
    
    		compatible_close(sockfd);
    
    #if defined(__linux__) && defined(SO_REUSEPORT) && LWS_MAX_SMP > 1
    	if (context->count_threads > 1)
    		if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
    				(const void *)&opt, sizeof(opt)) < 0) {
    			compatible_close(sockfd);
    			return 1;
    		}
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    	lws_plat_set_socket_options(context, sockfd);
    
    
    Andy Green's avatar
    Andy Green committed
    #if LWS_POSIX
    
    	n = lws_socket_bind(context, sockfd, info->port, info->iface);
    	if (n < 0)
    
    Andy Green's avatar
    Andy Green committed
    		goto bail;
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    	wsi = lws_zalloc(sizeof(struct lws));
    
    	if (wsi == NULL) {
    		lwsl_err("Out of mem\n");
    
    Andy Green's avatar
    Andy Green committed
    		goto bail;
    
    Andy Green's avatar
    Andy Green committed
    	wsi->context = context;
    
    Andy Green's avatar
    Andy Green committed
    	wsi->mode = LWSCM_SERVER_LISTENER;
    
    Andy Green's avatar
    Andy Green committed
    	wsi->protocol = context->protocols;
    
    Andy Green's avatar
    Andy Green committed
    	wsi->tsi = m;
    
    Andy Green's avatar
    Andy Green committed
    	context->pt[m].wsi_listening = wsi;
    
    Andy Green's avatar
    Andy Green committed
    	if (insert_wsi_socket_into_fds(context, wsi))
    		goto bail;
    
    Andy Green's avatar
    Andy Green committed
    	context->count_wsi_allocated++;
    
    Andy Green's avatar
    Andy Green committed
    	context->pt[m].lserv_fd = sockfd;
    
    Andy Green's avatar
    Andy Green committed
    #if LWS_POSIX
    
    Andy Green's avatar
    Andy Green committed
    	listen(wsi->sock, LWS_SOMAXCONN);
    	} /* for each thread able to independently lister */
    
    Andy Green's avatar
    Andy Green committed
    #else
    
    Andy Green's avatar
    Andy Green committed
    	mbed3_tcp_stream_bind(wsi->sock, info->port, wsi);
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    	lwsl_notice(" Listening on port %d\n", info->port);
    
    Andy Green's avatar
    Andy Green committed
    
    bail:
    	compatible_close(sockfd);
    
    	return 1;
    
    Andy Green's avatar
    Andy Green committed
    _lws_server_listen_accept_flow_control(struct lws *twsi, int on)
    
    Andy Green's avatar
    Andy Green committed
    	struct lws_context_per_thread *pt = &twsi->context->pt[(int)twsi->tsi];
    	struct lws *wsi = pt->wsi_listening;
    
    Andy Green's avatar
    Andy Green committed
    	if (!wsi || twsi->context->being_destroyed)
    
    Andy Green's avatar
    Andy Green committed
    	lwsl_debug("%s: Thr %d: LISTEN wsi %p: state %d\n",
    		   __func__, twsi->tsi, (void *)wsi, on);
    
    	if (on)
    		n = lws_change_pollfd(wsi, 0, LWS_POLLIN);
    	else
    		n = lws_change_pollfd(wsi, LWS_POLLIN, 0);
    
    	return n;
    }
    
    
    int
    lws_http_action(struct lws *wsi)
    
    #ifdef LWS_OPENSSL_SUPPORT
    
    	struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
    
    	enum http_connection_type connection_type;
    
    	enum http_version request_version;
    
    	unsigned int n, count = 0;
    
    	char http_version_str[10];
    	char http_conn_str[20];
    
    	int http_version_len;
    	char *uri_ptr = NULL;
    	int uri_len = 0;
    
    
    	static const unsigned char methods[] = {
    		WSI_TOKEN_GET_URI,
    		WSI_TOKEN_POST_URI,
    		WSI_TOKEN_OPTIONS_URI,
    		WSI_TOKEN_PUT_URI,
    		WSI_TOKEN_PATCH_URI,
    		WSI_TOKEN_DELETE_URI,
    
    #ifdef LWS_USE_HTTP2
    
    		WSI_TOKEN_HTTP_COLON_PATH,
    
    #ifdef _DEBUG
    
    	static const char * const method_names[] = {
    		"GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
    #ifdef LWS_USE_HTTP2
    		":path",
    #endif
    	};
    
    #endif
    
    	/* it's not websocket.... shall we accept it as http? */
    
    	for (n = 0; n < ARRAY_SIZE(methods); n++)
    		if (lws_hdr_total_length(wsi, methods[n]))
    			count++;
    	if (!count) {
    
    		lwsl_warn("Missing URI in HTTP request\n");
    		goto bail_nuke_ah;
    	}
    
    
    	if (count != 1) {
    		lwsl_warn("multiple methods?\n");
    
    		goto bail_nuke_ah;
    	}
    
    
    	if (lws_ensure_user_space(wsi))
    
    		goto bail_nuke_ah;
    
    
    	for (n = 0; n < ARRAY_SIZE(methods); n++)
    		if (lws_hdr_total_length(wsi, methods[n])) {
    			uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
    			uri_len = lws_hdr_total_length(wsi, methods[n]);
    			lwsl_info("Method: %s request for '%s'\n",
    				  	method_names[n], uri_ptr);
    			break;
    		}
    
    
    	/* HTTP header had a content length? */
    
    	wsi->u.http.content_length = 0;
    
    	if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
    		lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
    		lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
    
    		wsi->u.http.content_length = 100 * 1024 * 1024;
    
    	if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
    		lws_hdr_copy(wsi, content_length_str,
    
    			     sizeof(content_length_str) - 1,
    			     WSI_TOKEN_HTTP_CONTENT_LENGTH);
    
    		wsi->u.http.content_length = atoi(content_length_str);
    	}
    
    	/* http_version? Default to 1.0, override with token: */
    	request_version = HTTP_VERSION_1_0;
    
    	/* Works for single digit HTTP versions. : */
    	http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
    	if (http_version_len > 7) {
    		lws_hdr_copy(wsi, http_version_str,
    				sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
    		if (http_version_str[5] == '1' && http_version_str[7] == '1')
    			request_version = HTTP_VERSION_1_1;
    	}
    	wsi->u.http.request_version = request_version;
    
    	/* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
    	if (request_version == HTTP_VERSION_1_1)
    		connection_type = HTTP_CONNECTION_KEEP_ALIVE;
    	else
    		connection_type = HTTP_CONNECTION_CLOSE;
    
    	/* Override default if http "Connection:" header: */
    	if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
    		lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
    			     WSI_TOKEN_CONNECTION);
    		http_conn_str[sizeof(http_conn_str) - 1] = '\0';
    		if (!strcasecmp(http_conn_str, "keep-alive"))
    			connection_type = HTTP_CONNECTION_KEEP_ALIVE;
    		else
    
    			if (!strcasecmp(http_conn_str, "close"))
    
    				connection_type = HTTP_CONNECTION_CLOSE;
    	}
    	wsi->u.http.connection_type = connection_type;
    
    
    	n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
    
    				    wsi->user_space, uri_ptr, uri_len);
    
    Andy Green's avatar
    Andy Green committed
    	if (n) {
    		lwsl_info("LWS_CALLBACK_HTTP closing\n");
    
    Andy Green's avatar
    Andy Green committed
    		return 1;
    
    Andy Green's avatar
    Andy Green committed
    	 * if there is content supposed to be coming,
    	 * put a timeout on it having arrived
    
    Andy Green's avatar
    Andy Green committed
    	lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
    
    Andy Green's avatar
    Andy Green committed
    			wsi->context->timeout_secs);
    
    #ifdef LWS_OPENSSL_SUPPORT
    
    	if (wsi->redirect_to_https) {
    		/*
    
    		 * we accepted http:// only so we could redirect to
    
    		 * https://, so issue the redirect.  Create the redirection
    		 * URI from the host: header and ignore the path part
    		 */
    		unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
    			      *end = p + 512;
    
    		if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
    			goto bail_nuke_ah;
    		if (lws_add_http_header_status(wsi, 301, &p, end))
    			goto bail_nuke_ah;
    		n = sprintf((char *)end, "https://%s/",
    			    lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
    		if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_LOCATION,
    				end, n, &p, end))
    			goto bail_nuke_ah;
    		if (lws_finalize_http_header(wsi, &p, end))
    			goto bail_nuke_ah;
    		n = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);
    
    			goto bail_nuke_ah;
    
    		return lws_http_transaction_completed(wsi);
    	}
    
    Andy Green's avatar
    Andy Green committed
    	n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
    				    wsi->user_space, uri_ptr, uri_len);
    
    	if (n) {
    		lwsl_info("LWS_CALLBACK_HTTP closing\n");
    
    		return 1;
    	}
    
    	 * If we're not issuing a file, check for content_length or
    	 * HTTP keep-alive. No keep-alive header allocation for
    
    	 * ISSUING_FILE, as this uses HTTP/1.0.
    	 *
    
    	 * In any case, return 0 and let lws_read decide how to
    
    	 * proceed based on state
    	 */
    
    Andy Green's avatar
    Andy Green committed
    	if (wsi->state != LWSS_HTTP_ISSUING_FILE)
    
    		/* Prepare to read body if we have a content length: */
    		if (wsi->u.http.content_length > 0)
    
    Andy Green's avatar
    Andy Green committed
    			wsi->state = LWSS_HTTP_BODY;
    
    
    	return 0;
    
    bail_nuke_ah:
    
    Andy Green's avatar
    Andy Green committed
    	/* we're closing, losing some rx is OK */
    	wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
    
    Andy Green's avatar
    Andy Green committed
    	lws_header_table_detach(wsi, 1);
    
    int
    lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
    
    Andy Green's avatar
    Andy Green committed
    	struct lws_context *context = lws_get_context(wsi);
    
    Andy Green's avatar
    Andy Green committed
    	struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
    	struct _lws_header_related hdr;
    
    	struct allocated_headers *ah;
    
    	int protocol_len, n, hit;
    
    	char protocol_list[128];
    	char protocol_name[32];
    	char *p;
    
    Andy Green's avatar
    Andy Green committed
    	assert(len < 10000000);
    
    Andy Green's avatar
    Andy Green committed
    	assert(wsi->u.hdr.ah);
    
    		wsi->more_rx_waiting = !!len;
    
    
    		assert(wsi->mode == LWSCM_HTTP_SERVING);
    
    
    		if (lws_parse(wsi, *(*buf)++)) {
    
    			lwsl_info("lws_parse failed\n");
    
    			goto bail_nuke_ah;
    		}
    
    		if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
    			continue;
    
    
    		lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
    		lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
    				wsi->more_rx_waiting);
    
    Andy Green's avatar
    Andy Green committed
    		wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
    
    		lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
    
    
    		/* is this websocket protocol or normal http 1.0? */
    
    
    		if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
    			if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
    					"websocket")) {
    				lwsl_info("Upgrade to ws\n");
    				goto upgrade_ws;
    			}
    #ifdef LWS_USE_HTTP2
    			if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
    					"h2c-14")) {
    				lwsl_info("Upgrade to h2c-14\n");
    				goto upgrade_h2c;
    			}
    #endif
    			lwsl_err("Unknown upgrade\n");
    			/* dunno what he wanted to upgrade to */
    			goto bail_nuke_ah;
    		}
    
    		/* no upgrade ack... he remained as HTTP */
    
    		lwsl_info("No upgrade\n");
    		ah = wsi->u.hdr.ah;
    
    		lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
    		wsi->state = LWSS_HTTP;
    		wsi->u.http.fd = LWS_INVALID_FILE;
    
    		/* expose it at the same offset as u.hdr */
    		wsi->u.http.ah = ah;
    		lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi, (void *)wsi->u.hdr.ah);
    
    		n = lws_http_action(wsi);
    
    #ifdef LWS_USE_HTTP2
    upgrade_h2c:
    		if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
    			lwsl_err("missing http2_settings\n");
    
    			goto bail_nuke_ah;
    		}
    
    
    		lwsl_err("h2c upgrade...\n");
    
    		p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
    		/* convert the peer's HTTP-Settings */
    
    		n = lws_b64_decode_string(p, protocol_list,
    					  sizeof(protocol_list));
    
    		if (n < 0) {
    			lwsl_parser("HTTP2_SETTINGS too long\n");
    			return 1;
    		}
    
    		/* adopt the header info */
    
    		ah = wsi->u.hdr.ah;
    
    Andy Green's avatar
    Andy Green committed
    		lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
    
    		/* http2 union member has http union struct at start */
    		wsi->u.http.ah = ah;
    
    		lws_http2_init(&wsi->u.http2.peer_settings);
    		lws_http2_init(&wsi->u.http2.my_settings);
    
    		/* HTTP2 union */
    
    		lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
    				(unsigned char *)protocol_list, n);
    
    
    		strcpy(protocol_list,
    		       "HTTP/1.1 101 Switching Protocols\x0d\x0a"
    		      "Connection: Upgrade\x0d\x0a"
    		      "Upgrade: h2c\x0d\x0a\x0d\x0a");
    
    Andy Green's avatar
    Andy Green committed
    		n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
    					strlen(protocol_list));
    		if (n != strlen(protocol_list)) {
    
    			lwsl_debug("http2 switch: ERROR writing to socket\n");
    			return 1;
    		}
    
    Andy Green's avatar
    Andy Green committed
    		wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
    
    upgrade_ws:
    
    			lwsl_err("NULL protocol at lws_read\n");
    
    		 * Select the first protocol we support from the list
    		 * the client sent us.
    		 *
    		 * Copy it to remove header fragmentation
    
    		if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
    				 WSI_TOKEN_PROTOCOL) < 0) {
    			lwsl_err("protocol list too long");
    			goto bail_nuke_ah;
    		}
    
    		protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
    		protocol_list[protocol_len] = '\0';
    		p = protocol_list;
    		hit = 0;
    
    		while (*p && !hit) {
    
    Andy Green's avatar
    Andy Green committed
    			unsigned int n = 0;
    
    			while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
    				protocol_name[n++] = *p++;
    			protocol_name[n] = '\0';
    			if (*p)
    				p++;
    
    			lwsl_info("checking %s\n", protocol_name);
    
    			n = 0;
    
    			while (context->protocols[n].callback) {
    				if (context->protocols[n].name &&
    				    !strcmp(context->protocols[n].name,
    
    					    protocol_name)) {
    					lwsl_info("prot match %d\n", n);
    					wsi->protocol = &context->protocols[n];
    					hit = 1;
    
    		if (!hit) {
    
    			if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
    				lwsl_err("No protocol from \"%s\" supported\n",
    
    					 protocol_list);
    
    			/*
    			 * some clients only have one protocol and
    			 * do not sent the protocol list header...
    			 * allow it and match to protocol 0
    			 */
    			lwsl_info("defaulting to prot 0 handler\n");
    			wsi->protocol = &context->protocols[0];
    
    		if (lws_ensure_user_space(wsi))
    
    			goto bail_nuke_ah;
    
    		/*
    		 * Give the user code a chance to study the request and
    		 * have the opportunity to deny it
    		 */
    
    
    		if ((wsi->protocol->callback)(wsi,
    
    				LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
    				wsi->user_space,
    			      lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
    			lwsl_warn("User code denied connection\n");
    			goto bail_nuke_ah;
    		}
    
    		/*
    		 * Perform the handshake according to the protocol version the
    		 * client announced
    		 */
    
    		switch (wsi->ietf_spec_revision) {
    		case 13:
    			lwsl_parser("lws_parse calling handshake_04\n");
    			if (handshake_0405(context, wsi)) {
    				lwsl_info("hs0405 has failed the connection\n");
    				goto bail_nuke_ah;
    			}
    			break;
    
    		default:
    			lwsl_warn("Unknown client spec version %d\n",
    
    Andy Green's avatar
    Andy Green committed
    				  wsi->ietf_spec_revision);
    
    Andy Green's avatar
    Andy Green committed
    		/* we are upgrading to ws, so http/1.1 and keepalive +
    		 * pipelined header considerations about keeping the ah around
    		 * no longer apply.  However it's common for the first ws
    		 * protocol data to have been coalesced with the browser
    		 * upgrade request and to already be in the ah rx buffer.
    		 */
    
    
    Andy Green's avatar
    Andy Green committed
    		lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
    			  __func__, wsi, wsi->u.hdr.ah->rxpos,
    			  wsi->u.hdr.ah->rxlen);
    
    Andy Green's avatar
    Andy Green committed
    		lws_pt_lock(pt);
    		hdr = wsi->u.hdr;
    
    Andy Green's avatar
    Andy Green committed
    		lws_union_transition(wsi, LWSCM_WS_SERVING);
    
    Andy Green's avatar
    Andy Green committed
    		/*
    		 * first service is WS mode will notice this, use the RX and
    		 * then detach the ah (caution: we are not in u.hdr union
    		 * mode any more then... ah_temp member is at start the same
    		 * though)
    		 *
    
    Peter Pentchev's avatar
    Peter Pentchev committed
    		 * Because rxpos/rxlen shows something in the ah, we will get
    
    Andy Green's avatar
    Andy Green committed
    		 * service guaranteed next time around the event loop
    		 *
    		 * All union members begin with hdr, so we can use it even
    		 * though we transitioned to ws union mode (the ah detach
    		 * code uses it anyway).
    		 */
    		wsi->u.hdr = hdr;
    		lws_pt_unlock(pt);
    
    
    		/*
    		 * create the frame buffer for this connection according to the
    		 * size mentioned in the protocol definition.  If 0 there, use
    		 * a big default for compatibility
    		 */
    
    		n = wsi->protocol->rx_buffer_size;
    		if (!n)
    			n = LWS_MAX_SOCKET_IO_BUF;
    
    		n += LWS_PRE;
    		wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
    		if (!wsi->u.ws.rx_ubuf) {
    
    			lwsl_err("Out of Mem allocating rx buffer %d\n", n);
    			return 1;
    		}
    
    Andy Green's avatar
    Andy Green committed
    		wsi->u.ws.rx_ubuf_alloc = n;
    
    		lwsl_info("Allocating RX buffer %d\n", n);
    
    Andy Green's avatar
    Andy Green committed
    #if LWS_POSIX
    
    		if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
    			       (const char *)&n, sizeof n)) {
    
    			lwsl_warn("Failed to set SNDBUF to %d", n);
    			return 1;
    		}
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    Andy Green's avatar
    Andy Green committed
    		lwsl_parser("accepted v%02d connection\n",
    			    wsi->ietf_spec_revision);
    
    	} /* while all chars are handled */
    
    	return 0;
    
    bail_nuke_ah:
    	/* drop the header info */
    
    Andy Green's avatar
    Andy Green committed
    	/* we're closing, losing some rx is OK */
    	wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
    
    Andy Green's avatar
    Andy Green committed
    	lws_header_table_detach(wsi, 1);
    
    Andy Green's avatar
    Andy Green committed
    
    
    Andy Green's avatar
    Andy Green committed
    static int
    lws_get_idlest_tsi(struct lws_context *context)
    {
    	unsigned int lowest = ~0;
    	int n = 0, hit = -1;
    
    	for (; n < context->count_threads; n++) {
    
    Andy Green's avatar
    Andy Green committed
    		if ((unsigned int)context->pt[n].fds_count !=
    		    context->fd_limit_per_thread - 1 &&
    
    Andy Green's avatar
    Andy Green committed
    		    (unsigned int)context->pt[n].fds_count < lowest) {
    			lowest = context->pt[n].fds_count;
    			hit = n;
    		}
    	}
    
    	return hit;
    }
    
    
    struct lws *
    lws_create_new_server_wsi(struct lws_context *context)
    
    Andy Green's avatar
    Andy Green committed
    	int n = lws_get_idlest_tsi(context);
    
    	if (n < 0) {
    		lwsl_err("no space for new conn\n");
    		return NULL;
    	}
    
    	new_wsi = lws_zalloc(sizeof(struct lws));
    
    	if (new_wsi == NULL) {
    		lwsl_err("Out of memory for new connection\n");
    		return NULL;
    	}
    
    
    Andy Green's avatar
    Andy Green committed
    	new_wsi->tsi = n;
    	lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
    
    
    Andy Green's avatar
    Andy Green committed
    	new_wsi->context = context;
    
    	new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
    
    	new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
    
    
    	/* intialize the instance struct */
    
    
    Andy Green's avatar
    Andy Green committed
    	new_wsi->state = LWSS_HTTP;
    	new_wsi->mode = LWSCM_HTTP_SERVING;
    
    	new_wsi->hdr_parsing_completed = 0;
    
    #ifdef LWS_OPENSSL_SUPPORT
    	new_wsi->use_ssl = LWS_SSL_ENABLED(context);
    #endif
    
    
    	/*
    	 * these can only be set once the protocol is known
    	 * we set an unestablished connection's protocol pointer
    	 * to the start of the supported list, so it can look
    	 * for matching ones during the handshake
    	 */
    	new_wsi->protocol = context->protocols;
    	new_wsi->user_space = NULL;
    	new_wsi->ietf_spec_revision = 0;
    
    	new_wsi->sock = LWS_SOCK_INVALID;
    
    Andy Green's avatar
    Andy Green committed
    	context->count_wsi_allocated++;
    
    	/*
    	 * outermost create notification for wsi
    	 * no user_space because no protocol selection
    	 */
    
    Andy Green's avatar
    Andy Green committed
    	context->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
    				       NULL, NULL, 0);
    
    Andy Green's avatar
    Andy Green committed
    /**
     * lws_http_transaction_completed() - wait for new http transaction or close
     * @wsi:	websocket connection
     *
     *	Returns 1 if the HTTP connection must close now
     *	Returns 0 and resets connection to wait for new HTTP header /
     *	  transaction if possible
     */
    
    
    LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
    lws_http_transaction_completed(struct lws *wsi)
    
    Andy Green's avatar
    Andy Green committed
    {
    
    	lwsl_debug("%s: wsi %p\n", __func__, wsi);
    
    Andy Green's avatar
    Andy Green committed
    	/* if we can't go back to accept new headers, drop the connection */
    	if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
    
    Andy Green's avatar
    Andy Green committed
    		lwsl_info("%s: %p: close connection\n", __func__, wsi);
    
    Andy Green's avatar
    Andy Green committed
    		return 1;
    	}
    
    	/* otherwise set ourselves up ready to go again */
    
    Andy Green's avatar
    Andy Green committed
    	wsi->state = LWSS_HTTP;
    	wsi->mode = LWSCM_HTTP_SERVING;
    
    	wsi->u.http.content_length = 0;
    
    	wsi->hdr_parsing_completed = 0;
    
    
    	/* He asked for it to stay alive indefinitely */
    
    	lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
    
    	/*
    	 * We already know we are on http1.1 / keepalive and the next thing
    	 * coming will be another header set.
    	 *
    	 * If there is no pending rx and we still have the ah, drop it and
    	 * reacquire a new ah when the new headers start to arrive.  (Otherwise
    	 * we needlessly hog an ah indefinitely.)
    	 *
    	 * However if there is pending rx and we know from the keepalive state
    	 * that is already at least the start of another header set, simply
    	 * reset the existing header table and keep it.
    
    		lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
    				wsi->more_rx_waiting);
    
    		if (!wsi->more_rx_waiting) {
    
    			wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
    
    Andy Green's avatar
    Andy Green committed
    			lws_header_table_detach(wsi, 1);
    
    Andy Green's avatar
    Andy Green committed
    			lws_header_table_reset(wsi, 1);
    
    
    	/* If we're (re)starting on headers, need other implied init */
    	wsi->u.hdr.ues = URIES_IDLE;
    
    Andy Green's avatar
    Andy Green committed
    	lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
    
    Andy Green's avatar
    Andy Green committed
    	return 0;
    }
    
    
    Andy Green's avatar
    Andy Green committed
    /**
     * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
     * @context: lws context
     * @accept_fd: fd of already-accepted socket to adopt
     *
     * Either returns new wsi bound to accept_fd, or closes accept_fd and
     * returns NULL, having cleaned up any new wsi pieces.
     *
     * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
     * to ws or just serve http.
    
    Andy Green's avatar
    Andy Green committed
     */
    
    LWS_VISIBLE struct lws *
    lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
    
    Andy Green's avatar
    Andy Green committed
    {
    
    Andy Green's avatar
    Andy Green committed
    	struct lws *new_wsi = lws_create_new_server_wsi(context);
    
    Andy Green's avatar
    Andy Green committed
    
    
    Andy Green's avatar
    Andy Green committed
    	if (!new_wsi) {
    		compatible_close(accept_fd);
    		return NULL;
    	}
    
    Andy Green's avatar
    Andy Green committed
    	lwsl_info("%s: new wsi %p, sockfd %d\n", __func__, new_wsi, accept_fd);
    
    Andy Green's avatar
    Andy Green committed
    
    
    Andy Green's avatar
    Andy Green committed
    	new_wsi->sock = accept_fd;
    
    Andy Green's avatar
    Andy Green committed
    	/* the transport is accepted... give him time to negotiate */
    	lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
    
    Andy Green's avatar
    Andy Green committed
    			context->timeout_secs);
    
    Andy Green's avatar
    Andy Green committed
    
    #if LWS_POSIX == 0
    	mbed3_tcp_stream_accept(accept_fd, new_wsi);
    #endif
    
    	/*
    	 * A new connection was accepted. Give the user a chance to
    	 * set properties of the newly created wsi. There's no protocol
    	 * selected yet so we issue this to protocols[0]
    	 */
    	if ((context->protocols[0].callback)(new_wsi,
    	     LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
    		compatible_close(new_wsi->sock);
    		lws_free(new_wsi);
    		return NULL;
    	}
    
    	lws_libev_accept(new_wsi, new_wsi->sock);
    
    Andy Green's avatar
    Andy Green committed
    	lws_libuv_accept(new_wsi, new_wsi->sock);
    
    Andy Green's avatar
    Andy Green committed
    
    	if (!LWS_SSL_ENABLED(context)) {
    		if (insert_wsi_socket_into_fds(context, new_wsi))
    			goto fail;
    	} else {
    		new_wsi->mode = LWSCM_SSL_INIT;
    		if (lws_server_socket_service_ssl(new_wsi, accept_fd))
    			goto fail;
    	}
    
    	return new_wsi;
    
    fail:
    	lwsl_err("%s: fail\n", __func__);
    	lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
    
    	return NULL;
    
    /**
     * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
     * @context:	lws context
     * @accept_fd:	fd of already-accepted socket to adopt
     * @readbuf:	NULL or pointer to data that must be drained before reading from
     *		accept_fd
     * @len:	The length of the data held at @readbuf
     *
     * Either returns new wsi bound to accept_fd, or closes accept_fd and
     * returns NULL, having cleaned up any new wsi pieces.
     *
     * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
     * to ws or just serve http.
     *
     * If your external code did not already read from the socket, you can use
     * lws_adopt_socket() instead.
     *
     * This api is guaranteed to use the data at @readbuf first, before reading from
     * the socket.
     *
     * @readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
     */
    
    LWS_VISIBLE LWS_EXTERN struct lws *
    lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
    			 const char *readbuf, size_t len)
    {
    	struct lws *wsi = lws_adopt_socket(context, accept_fd);
    
    Andy Green's avatar
    Andy Green committed
    	struct lws_context_per_thread *pt;
    
    	struct allocated_headers *ah;
    
    Andy Green's avatar
    Andy Green committed
    	struct lws_pollfd *pfd;
    
    
    	if (!wsi)
    		return NULL;
    
    	if (!readbuf)
    		return wsi;
    
    	if (len > sizeof(ah->rx)) {
    		lwsl_err("%s: rx in too big\n", __func__);
    		goto bail;
    	}
    	/*
    	 * we can't process the initial read data until we can attach an ah.
    	 *
    	 * if one is available, get it and place the data in his ah rxbuf...
    	 * wsi with ah that have pending rxbuf get auto-POLLIN service.
    
    Andy Green's avatar
    Andy Green committed
    	 *
    	 * no autoservice because we didn't get a chance to attach the
    	 * readbuf data to wsi or ah yet, and we will do it next if we get
    	 * the ah.
    
    Andy Green's avatar
    Andy Green committed
    	if (!lws_header_table_attach(wsi, 0)) {
    
    		ah = wsi->u.hdr.ah;
    		memcpy(ah->rx, readbuf, len);
    		ah->rxpos = 0;
    		ah->rxlen = len;
    
    
    Andy Green's avatar
    Andy Green committed
    		lwsl_notice("%s: calling service on readbuf ah\n", __func__);
    		pt = &context->pt[(int)wsi->tsi];
    
    		/* unlike a normal connect, we have the headers already
    		 * (or the first part of them anyway).
    		 * libuv won't come back and service us without a network
    		 * event, so we need to do the header service right here.
    		 */
    		pfd = &pt->fds[wsi->position_in_fds_table];
    		pfd->revents |= LWS_POLLIN;
    		lwsl_err("%s: calling service\n", __func__);
    		if (lws_service_fd_tsi(context, pfd, wsi->tsi))
    			/* service closed us */
    			return NULL;
    
    
    		return wsi;
    	}
    
    Andy Green's avatar
    Andy Green committed
    	lwsl_err("%s: deferring handling ah\n", __func__);
    
    	/*
    	 * hum if no ah came, we are on the wait list and must defer
    	 * dealing with this until the ah arrives.
    	 *
    	 * later successful lws_header_table_attach() will apply the
    
    Andy Green's avatar
    Andy Green committed
    	 * below to the rx buffer (via lws_header_table_reset()).
    
    	 */
    	wsi->u.hdr.preamble_rx = lws_malloc(len);
    
    	memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
    
    	wsi->u.hdr.preamble_rx_len = len;
    
    	return wsi;
    
    bail:
    	lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
    
    	return NULL;
    }
    
    
    Andy Green's avatar
    Andy Green committed
    LWS_VISIBLE int
    lws_server_socket_service(struct lws_context *context, struct lws *wsi,
    			  struct lws_pollfd *pollfd)
    
    Andy Green's avatar
    Andy Green committed
    	struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
    
    Andy Green's avatar
    Andy Green committed
    	lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
    
    Andy Green's avatar
    Andy Green committed
    	struct allocated_headers *ah;
    
    Andy Green's avatar
    Andy Green committed
    #if LWS_POSIX
    
    	struct sockaddr_in cli_addr;
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    Andy Green's avatar
    Andy Green committed
    	case LWSCM_HTTP_SERVING:
    	case LWSCM_HTTP_SERVING_ACCEPTED:
    	case LWSCM_HTTP2_SERVING:
    
    
    		/* handle http headers coming in */
    
    
    Andy Green's avatar
    Andy Green committed
    		/* pending truncated sends have uber priority */
    
    
    Andy Green's avatar
    Andy Green committed
    		if (wsi->trunc_len) {
    			if (!(pollfd->revents & LWS_POLLOUT))
    				break;
    
    
    Andy Green's avatar
    Andy Green committed
    			if (lws_issue_raw(wsi, wsi->trunc_alloc +
    					       wsi->trunc_offset,
    
    Andy Green's avatar
    Andy Green committed
    					  wsi->trunc_len) < 0)
    				goto fail;
    
    Andy Green's avatar
    Andy Green committed
    			/*
    
    Andy Green's avatar
    Andy Green committed
    			 * we can't afford to allow input processing to send
    
    Andy Green's avatar
    Andy Green committed
    			 * something new, so spin around he event loop until
    			 * he doesn't have any partials
    			 */
    			break;
    		}
    
    
    		/* any incoming data ready? */
    
    
    Andy Green's avatar
    Andy Green committed
    		if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
    
    Andy Green's avatar
    Andy Green committed
    			goto try_pollout;
    
    
    Andy Green's avatar
    Andy Green committed
    		/* these states imply we MUST have an ah attached */
    
    		if (wsi->state == LWSS_HTTP ||
    		    wsi->state == LWSS_HTTP_ISSUING_FILE ||
    		    wsi->state == LWSS_HTTP_HEADERS) {
    			if (!wsi->u.hdr.ah)
    
    Andy Green's avatar
    Andy Green committed
    				/* no autoservice beacuse we will do it next */
    				if (lws_header_table_attach(wsi, 0))
    
    Andy Green's avatar
    Andy Green committed
    					goto try_pollout;
    
    			ah = wsi->u.hdr.ah;
    
    			lwsl_debug("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
    				   ah->rxpos, ah->rxlen);
    
    			/* if nothing in ah rx buffer, get some fresh rx */
    			if (ah->rxpos == ah->rxlen) {
    				ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
    						   sizeof(ah->rx));
    				ah->rxpos = 0;
    				lwsl_debug("%s: wsi %p, ah->rxlen = %d\r\n",
    					   __func__, wsi, ah->rxlen);
    				switch (ah->rxlen) {
    				case 0:
    					lwsl_info("%s: read 0 len\n", __func__);
    					/* lwsl_info("   state=%d\n", wsi->state); */
    //					if (!wsi->hdr_parsing_completed)
    //						lws_header_table_detach(wsi);
    					/* fallthru */
    				case LWS_SSL_CAPABLE_ERROR:
    					goto fail;
    				case LWS_SSL_CAPABLE_MORE_SERVICE:
    					ah->rxlen = ah->rxpos = 0;
    					goto try_pollout;
    				}