Skip to content
Snippets Groups Projects
server.c 45.4 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,
    
    Andy Green's avatar
    Andy Green committed
    			struct lws_vhost *vhost)
    
    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
    	struct lws_vhost *vh;
    
    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
    	vh = vhost->context->vhost_list;
    	while (vh) {
    		if (vh->listen_port == info->port) {
    			if ((!info->iface && !vh->iface) ||
    			    (info->iface && vh->iface &&
    			    !strcmp(info->iface, vh->iface))) {
    				vhost->listen_port = info->port;
    				vhost->iface = info->iface;
    				lwsl_notice(" using listen skt from vhost %s\n",
    					    vh->name);
    				return 0;
    			}
    		}
    		vh = vh->vhost_next;
    	}
    
    
    Andy Green's avatar
    Andy Green committed
    #if LWS_POSIX
    
    Andy Green's avatar
    Andy Green committed
    #if defined(__linux__)
    
    Andy Green's avatar
    Andy Green committed
    	limit = vhost->context->count_threads;
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    	for (m = 0; m < limit; m++) {
    
    Yeonjun Lim's avatar
    Yeonjun Lim committed
    #ifdef LWS_USE_UNIX_SOCK
    
    	if (LWS_UNIX_SOCK_ENABLED(vhost))
    
    Yeonjun Lim's avatar
    Yeonjun Lim committed
    		sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
    	else
    #endif
    
    #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
    
    Andy Green's avatar
    Andy Green committed
    	if (vhost->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
    
    Andy Green's avatar
    Andy Green committed
    	lws_plat_set_socket_options(vhost, sockfd);
    
    Andy Green's avatar
    Andy Green committed
    #if LWS_POSIX
    
    	n = lws_socket_bind(vhost, sockfd, info->port, info->iface);
    
    Andy Green's avatar
    Andy Green committed
    		goto bail;
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    Andy Green's avatar
    Andy Green committed
    	vhost->listen_port = info->port;
    	vhost->iface = info->iface;
    
    	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 = vhost->context;
    
    Andy Green's avatar
    Andy Green committed
    	wsi->mode = LWSCM_SERVER_LISTENER;
    
    Andy Green's avatar
    Andy Green committed
    	wsi->protocol = vhost->protocols;
    
    Andy Green's avatar
    Andy Green committed
    	wsi->tsi = m;
    
    Andy Green's avatar
    Andy Green committed
    	wsi->vhost = vhost;
    	wsi->listener = 1;
    
    Andy Green's avatar
    Andy Green committed
    	vhost->context->pt[m].wsi_listening = wsi;
    	if (insert_wsi_socket_into_fds(vhost->context, wsi))
    
    Andy Green's avatar
    Andy Green committed
    		goto bail;
    
    Andy Green's avatar
    Andy Green committed
    	vhost->context->count_wsi_allocated++;
    	vhost->lserv_wsi = wsi;
    
    Andy Green's avatar
    Andy Green committed
    #if LWS_POSIX
    
    Andy Green's avatar
    Andy Green committed
    	listen(wsi->sock, LWS_SOMAXCONN);
    
    Andy Green's avatar
    Andy Green committed
    	} /* for each thread able to independently listen */
    
    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
    
    Yeonjun Lim's avatar
    Yeonjun Lim committed
    	if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) {
    #ifdef LWS_USE_UNIX_SOCK
    
    		if (LWS_UNIX_SOCK_ENABLED(vhost))
    
    Yeonjun Lim's avatar
    Yeonjun Lim committed
    			lwsl_notice(" Listening on \"%s\"\n", info->iface);
    		else
    #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;
    }
    
    
    Andy Green's avatar
    Andy Green committed
    struct lws_vhost *
    lws_select_vhost(struct lws_context *context, int port, const char *servername)
    {
    	struct lws_vhost *vhost = context->vhost_list;
    
    	while (vhost) {
    		if (port == vhost->listen_port &&
    		    !strcmp(vhost->name, servername)) {
    			lwsl_info("SNI: Found: %s\n", servername);
    			return vhost;
    		}
    		vhost = vhost->vhost_next;
    	}
    
    	return NULL;
    }
    
    static const char * get_mimetype(const char *file)
    {
    	int n = strlen(file);
    
    	if (n < 5)
    		return NULL;
    
    	if (!strcmp(&file[n - 4], ".ico"))
    		return "image/x-icon";
    
    
    	if (!strcmp(&file[n - 4], ".gif"))
    		return "image/gif";
    
    	if (!strcmp(&file[n - 3], ".js"))
    		return "text/javascript";
    
    
    Andy Green's avatar
    Andy Green committed
    	if (!strcmp(&file[n - 4], ".png"))
    		return "image/png";
    
    
    Andy Green's avatar
    Andy Green committed
    	if (!strcmp(&file[n - 4], ".jpg"))
    		return "image/jpeg";
    
    
    Andy Green's avatar
    Andy Green committed
    	if (!strcmp(&file[n - 5], ".html"))
    		return "text/html";
    
    	if (!strcmp(&file[n - 4], ".css"))
    		return "text/css";
    
    
    	if (!strcmp(&file[n - 4], ".ttf"))
    		return "application/x-font-ttf";
    
    
    Andy Green's avatar
    Andy Green committed
    	return NULL;
    }
    
    int lws_http_serve(struct lws *wsi, char *uri, const char *origin)
    {
    	const char *mimetype;
    
    Andy Green's avatar
    Andy Green committed
    	struct stat st;
    	char path[256], sym[256];
    
    Andy Green's avatar
    Andy Green committed
    	unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
    	unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
    
    Andy Green's avatar
    Andy Green committed
    	int n, spin = 0;
    
    Andy Green's avatar
    Andy Green committed
    
    	snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
    
    
    Andy Green's avatar
    Andy Green committed
    	do {
    		spin++;
    
    		if (stat(path, &st)) {
    			lwsl_err("unable to stat %s\n", path);
    			goto bail;
    		}
    
    		lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
    
    Andy Green's avatar
    Andy Green committed
    #if !defined(WIN32)
    
    Andy Green's avatar
    Andy Green committed
    		if ((S_IFMT & st.st_mode) == S_IFLNK) {
    			if (readlink(path, sym, sizeof(sym))) {
    				lwsl_err("Failed to read link %s\n", path);
    				goto bail;
    			}
    			lwsl_debug("symlink %s -> %s\n", path, sym);
    			snprintf(path, sizeof(path) - 1, "%s", sym);
    		}
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    Andy Green's avatar
    Andy Green committed
    		if ((S_IFMT & st.st_mode) == S_IFDIR) {
    			lwsl_debug("default filename append to dir\n");
    			snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
    				 origin, uri);
    		}
    
    	} while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
    
    
    Andy Green's avatar
    Andy Green committed
    	if (spin == 5)
    
    Andy Green's avatar
    Andy Green committed
    		lwsl_err("symlink loop %s \n", path);
    
    Andy Green's avatar
    Andy Green committed
    
    	n = sprintf(sym, "%08lX%08lX", (unsigned long)st.st_size,
    				   (unsigned long)st.st_mtime);
    
    	if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
    		/*
    		 * he thinks he has some version of it already,
    		 * check if the tag matches
    		 */
    		if (!strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
    
    			lwsl_notice("%s: ETAG match %s %s\n", __func__,
    				    uri, origin);
    
    			/* we don't need to send the payload */
    			if (lws_add_http_header_status(wsi, 304, &p, end))
    				return -1;
    			if (lws_add_http_header_by_token(wsi,
    					WSI_TOKEN_HTTP_ETAG,
    					(unsigned char *)sym, n, &p, end))
    				return -1;
    			if (lws_finalize_http_header(wsi, &p, end))
    				return -1;
    
    			n = lws_write(wsi, start, p - start,
    					LWS_WRITE_HTTP_HEADERS);
    			if (n != (p - start)) {
    				lwsl_err("_write returned %d from %d\n", n, p - start);
    				return -1;
    			}
    
    			return lws_http_transaction_completed(wsi);
    		}
    
    Andy Green's avatar
    Andy Green committed
    	if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
    			(unsigned char *)sym, n, &p, end))
    		return -1;
    
    
    Andy Green's avatar
    Andy Green committed
    	mimetype = get_mimetype(path);
    	if (!mimetype) {
    		lwsl_err("unknown mimetype for %s", path);
    
    Andy Green's avatar
    Andy Green committed
    		goto bail;
    
    Andy Green's avatar
    Andy Green committed
    	}
    
    
    Andy Green's avatar
    Andy Green committed
    	n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
    
    Andy Green's avatar
    Andy Green committed
    
    
    Andy Green's avatar
    Andy Green committed
    	if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
    		return -1; /* error or can't reuse connection: close the socket */
    
    	return 0;
    
    Andy Green's avatar
    Andy Green committed
    bail:
    	lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
    
    	return -1;
    
    Andy Green's avatar
    Andy Green committed
    }
    
    
    int
    lws_http_action(struct lws *wsi)
    
    	struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
    
    	enum http_connection_type connection_type;
    
    	enum http_version request_version;
    
    	struct lws_http_mount *hm, *hit = NULL;
    
    	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, best = 0;
    
    	int meth = -1;
    
    	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,
    
    #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
    
    	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);
    
    	/* we insist on absolute paths */
    
    	if (uri_ptr[0] != '/') {
    		lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
    
    		goto bail_nuke_ah;
    	}
    
    
    	/* 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);
    	}
    
    
    Andy Green's avatar
    Andy Green committed
    	if (wsi->http2_substream) {
    		wsi->u.http.request_version = HTTP_VERSION_2;
    	} else {
    		/* 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;
    
    Andy Green's avatar
    Andy Green committed
    		/* 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
    
    Andy Green's avatar
    Andy Green committed
    			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;
    
    Andy Green's avatar
    Andy Green committed
    		n = sprintf((char *)end, "https://%s/",
    
    			    lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
    
    
    		n = lws_http_redirect(wsi, end, n, &p, end);
    
    			goto bail_nuke_ah;
    
    		return lws_http_transaction_completed(wsi);
    	}
    
    Andy Green's avatar
    Andy Green committed
    #endif
    
    #ifdef LWS_WITH_ACCESS_LOG
    	/*
    	 * Produce Apache-compatible log string for wsi, like this:
    	 *
    	 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
    	 * "GET /aep-screen.png HTTP/1.1"
    	 * 200 152987 "https://libwebsockets.org/index.html"
    	 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
    	 *
    	 */
    	{
    		static const char * const hver[] = {
    			"http/1.0", "http/1.1", "http/2"
    		};
    #ifdef LWS_USE_IPV6
    		char ads[INET6_ADDRSTRLEN];
    #else
    		char ads[INET_ADDRSTRLEN];
    #endif
    		char da[64];
    		const char *pa, *me;
    		struct tm *tmp;
    		time_t t = time(NULL);
    		int l = 256;
    
    		if (wsi->access_log_pending)
    			lws_access_log(wsi);
    
    		wsi->access_log.header_log = lws_malloc(l);
    
    		tmp = localtime(&t);
    		if (tmp)
    			strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
    		else
    			strcpy(da, "01/Jan/1970:00:00:00 +0000");
    
    		pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
    		if (!pa)
    			pa = "(unknown)";
    
    		if (meth >= 0)
    			me = method_names[meth];
    		else
    			me = "unknown";
    
    		snprintf(wsi->access_log.header_log, l,
    			 "%s - - [%s] \"%s %s %s\"",
    			 pa, da, me, uri_ptr,
    			 hver[wsi->u.http.request_version]);
    
    		l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
    		if (l) {
    			wsi->access_log.user_agent = lws_malloc(l + 2);
    			lws_hdr_copy(wsi, wsi->access_log.user_agent,
    				     l + 1, WSI_TOKEN_HTTP_USER_AGENT);
    		}
    		wsi->access_log_pending = 1;
    	}
    #endif
    
    
    Andy Green's avatar
    Andy Green committed
    	/* can we serve it from the mount list? */
    
    	hm = wsi->vhost->mount_list;
    	while (hm) {
    		if (uri_len >= hm->mountpoint_len &&
    
    Andy Green's avatar
    Andy Green committed
    		    !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
    		    (uri_ptr[hm->mountpoint_len] == '\0' ||
    		     uri_ptr[hm->mountpoint_len] == '/' ||
    		     hm->mountpoint_len == 1)
    		    ) {
    
    Andy Green's avatar
    Andy Green committed
    			if ((hm->origin_protocol == LWSMPRO_CGI ||
    			     lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI)) &&
    			    hm->mountpoint_len > best) {
    
    				best = hm->mountpoint_len;
    				hit = hm;
    			}
    
    Andy Green's avatar
    Andy Green committed
    		}
    		hm = hm->mount_next;
    	}
    
    	if (hit) {
    		char *s = uri_ptr + hit->mountpoint_len;
    
    
    Andy Green's avatar
    Andy Green committed
    		lwsl_debug("*** hit %d %d %s\n", hit->mountpoint_len,
    			   hit->origin_protocol , hit->origin);
    
    
    		/*
    		 * if we have a mountpoint like https://xxx.com/yyy
    		 * there is an implied / at the end for our purposes since
    		 * we can only mount on a "directory".
    		 *
    		 * But if we just go with that, the browser cannot understand
    		 * that he is actually looking down one "directory level", so
    		 * even though we give him /yyy/abc.html he acts like the
    		 * current directory level is /.  So relative urls like "x.png"
    		 * wrongly look outside the mountpoint.
    		 *
    		 * Therefore if we didn't come in on a url with an explicit
    		 * / at the end, we must redirect to add it so the browser
    		 * understands he is one "directory level" down.
    		 */
    
    Andy Green's avatar
    Andy Green committed
    		if ((hit->mountpoint_len > 1 || (hit->origin_protocol & 4)) &&
    
    Andy Green's avatar
    Andy Green committed
    		    (*s != '/' || (hit->origin_protocol & 4)) &&
    		    (hit->origin_protocol != LWSMPRO_CGI)) {
    
    Andy Green's avatar
    Andy Green committed
    			unsigned char *start = pt->serv_buf + LWS_PRE,
    
    					      *p = start, *end = p + 512;
    
    Andy Green's avatar
    Andy Green committed
    			static const char *oprot[] = {
    				"http://", "https://"
    			};
    
    
    			lwsl_notice("Doing 301 '%s' org %s\n", s, hit->origin);
    
    Andy Green's avatar
    Andy Green committed
    			if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
    				goto bail_nuke_ah;
    
    			/* > at start indicates deal with by redirect */
    			if (hit->origin_protocol & 4)
    				n = snprintf((char *)end, 256, "%s%s",
    					    oprot[hit->origin_protocol & 1],
    					    hit->origin);
    			else
    				n = snprintf((char *)end, 256,
    				    "https://%s/%s/",
    				    lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
    				    uri_ptr);
    
    
    			n = lws_http_redirect(wsi, end, n, &p, end);
    
    Andy Green's avatar
    Andy Green committed
    			if ((int)n < 0)
    				goto bail_nuke_ah;
    
    			return lws_http_transaction_completed(wsi);
    		}
    
    #ifdef LWS_WITH_CGI
    		/* did we hit something with a cgi:// origin? */
    		if (hit->origin_protocol == LWSMPRO_CGI) {
    			const char *cmd[] = {
    				NULL, /* replace with cgi path */
    				NULL
    			};
    			unsigned char *p, *end, buffer[256];
    
    			lwsl_debug("%s: cgi\n", __func__);
    			cmd[0] = hit->origin;
    
    Andy Green's avatar
    Andy Green committed
    
    			n = 5;
    			if (hit->cgi_timeout)
    				n = hit->cgi_timeout;
    
    			n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
    
    Andy Green's avatar
    Andy Green committed
    				    hit->cgienv);
    			if (n) {
    				lwsl_err("%s: cgi failed\n");
    				return -1;
    
    Andy Green's avatar
    Andy Green committed
    			p = buffer + LWS_PRE;
    			end = p + sizeof(buffer) - LWS_PRE;
    
    			if (lws_add_http_header_status(wsi, 200, &p, end))
    				return 1;
    			if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
    					(unsigned char *)"close", 5, &p, end))
    				return 1;
    			n = lws_write(wsi, buffer + LWS_PRE,
    				      p - (buffer + LWS_PRE),
    				      LWS_WRITE_HTTP_HEADERS);
    
    
    Andy Green's avatar
    Andy Green committed
    			goto deal_body;
    
    Andy Green's avatar
    Andy Green committed
    		}
    #endif
    
    Andy Green's avatar
    Andy Green committed
    		n = strlen(s);
    		if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
    
    			s = (char *)hit->def;
    		if (!s)
    			s = "index.html";
    
    Andy Green's avatar
    Andy Green committed
    		wsi->cache_secs = hit->cache_max_age;
    		wsi->cache_reuse = hit->cache_reusable;
    		wsi->cache_revalidate = hit->cache_revalidate;
    		wsi->cache_intermediaries = hit->cache_intermediaries;
    
    		n = lws_http_serve(wsi, s, hit->origin);
    
    Andy Green's avatar
    Andy Green committed
    		n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
    
    Andy Green's avatar
    Andy Green committed
    				    wsi->user_space, uri_ptr, uri_len);
    
    	if (n) {
    		lwsl_info("LWS_CALLBACK_HTTP closing\n");
    
    		return 1;
    	}
    
    Andy Green's avatar
    Andy Green committed
    #ifdef LWS_WITH_CGI
    deal_body:
    #endif
    
    	 * 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;
    
    Andy Green's avatar
    Andy Green committed
    		if (wsi->mode != LWSCM_HTTP_SERVING &&
    		    wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
    			lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
    			goto bail_nuke_ah;
    		}
    
    		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
    		/* select vhost */
    
    		if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
    			struct lws_vhost *vhost = lws_select_vhost(
    				context, wsi->vhost->listen_port,
    				lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
    
    			if (vhost)
    				wsi->vhost = vhost;
    		}
    
    		wsi->vhost->trans++;
    		if (!wsi->conn_stat_done) {
    			wsi->vhost->conn++;
    			wsi->conn_stat_done = 1;
    		}
    
    
    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")) {
    
    Andy Green's avatar
    Andy Green committed
    				wsi->vhost->ws_upgrades++;
    
    				lwsl_info("Upgrade to ws\n");
    				goto upgrade_ws;
    			}
    #ifdef LWS_USE_HTTP2
    			if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
    
    Andy Green's avatar
    Andy Green committed
    					"h2c")) {
    
    Andy Green's avatar
    Andy Green committed
    				wsi->vhost->http2_upgrades++;
    
    Andy Green's avatar
    Andy Green committed
    				lwsl_info("Upgrade to h2c\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;
    
    Andy Green's avatar
    Andy Green committed
    		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) {
    
    			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;
    
    Andy Green's avatar
    Andy Green committed
    			while (wsi->vhost->protocols[n].callback) {
    				if (wsi->vhost->protocols[n].name &&
    				    !strcmp(wsi->vhost->protocols[n].name,
    
    					    protocol_name)) {
    
    Andy Green's avatar
    Andy Green committed
    					wsi->protocol = &wsi->vhost->protocols[n];
    
    		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 send the protocol list header...
    
    			 * allow it and match to protocol 0
    			 */
    			lwsl_info("defaulting to prot 0 handler\n");
    
    Andy Green's avatar
    Andy Green committed
    			wsi->protocol = &wsi->vhost->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);
    
    		/*
    		 * stitch protocol choice into the vh protocol linked list
    		 * We always insert ourselves at the start of the list
    		 *
    		 * X <-> B
    		 * X <-> pAn <-> pB
    		 */
    		//lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
    		//		__func__,
    		//		wsi->vhost->same_vh_protocol_list[n],
    		//		wsi->same_vh_protocol_prev);
    		wsi->same_vh_protocol_prev = /* guy who points to us */
    			&wsi->vhost->same_vh_protocol_list[n];
    		wsi->same_vh_protocol_next = /* old first guy is our next */
    				wsi->vhost->same_vh_protocol_list[n];
    		/* we become the new first guy */
    		wsi->vhost->same_vh_protocol_list[n] = wsi;
    
    		if (wsi->same_vh_protocol_next)
    			/* old first guy points back to us now */
    			wsi->same_vh_protocol_next->same_vh_protocol_prev =
    					&wsi->same_vh_protocol_next;
    
    
    
    
    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)
    		 *