1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 - 2019 Andy Green <andy@warmcat.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  */
24 
25 #include "private-lib-core.h"
26 
27 const char * const method_names[] = {
28 	"GET", "POST",
29 #if defined(LWS_WITH_HTTP_UNCOMMON_HEADERS)
30 	"OPTIONS", "PUT", "PATCH", "DELETE",
31 #endif
32 	"CONNECT", "HEAD",
33 #ifdef LWS_WITH_HTTP2
34 	":path",
35 #endif
36 	};
37 
38 #if defined(LWS_WITH_FILE_OPS)
39 static const char * const intermediates[] = { "private", "public" };
40 #endif
41 
42 /*
43  * return 0: all done
44  *        1: nonfatal error
45  *       <0: fatal error
46  *
47  *       REQUIRES CONTEXT LOCK HELD
48  */
49 
50 #if defined(LWS_WITH_SERVER)
51 int
_lws_vhost_init_server(const struct lws_context_creation_info * info,struct lws_vhost * vhost)52 _lws_vhost_init_server(const struct lws_context_creation_info *info,
53 		       struct lws_vhost *vhost)
54 {
55 	struct lws_context_per_thread *pt;
56 	int n, opt = 1, limit = 1;
57 	lws_sockfd_type sockfd;
58 	int m = 0, is;
59 #if defined(LWS_WITH_IPV6)
60 	int af = 0;
61 #endif
62 	struct lws_vhost *vh;
63 	struct lws *wsi;
64 
65 	(void)method_names;
66 	(void)opt;
67 
68 	if (info) {
69 		vhost->iface = info->iface;
70 		vhost->listen_port = info->port;
71 	}
72 
73 	/* set up our external listening socket we serve on */
74 
75 	if (vhost->listen_port == CONTEXT_PORT_NO_LISTEN ||
76 	    vhost->listen_port == CONTEXT_PORT_NO_LISTEN_SERVER)
77 		return 0;
78 
79 	vh = vhost->context->vhost_list;
80 	while (vh) {
81 		if (vh->listen_port == vhost->listen_port) {
82 			if (((!vhost->iface && !vh->iface) ||
83 			    (vhost->iface && vh->iface &&
84 			    !strcmp(vhost->iface, vh->iface))) &&
85 			   vh->lserv_wsi
86 			) {
87 				lwsl_notice(" using listen skt from vhost %s\n",
88 					    vh->name);
89 				return 0;
90 			}
91 		}
92 		vh = vh->vhost_next;
93 	}
94 
95 	if (vhost->iface) {
96 		/*
97 		 * let's check before we do anything else about the disposition
98 		 * of the interface he wants to bind to...
99 		 */
100 		is = lws_socket_bind(vhost, NULL, LWS_SOCK_INVALID,
101 				     vhost->listen_port, vhost->iface, 1);
102 		lwsl_debug("initial if check says %d\n", is);
103 
104 		if (is == LWS_ITOSA_BUSY)
105 			/* treat as fatal */
106 			return -1;
107 
108 deal:
109 
110 		lws_start_foreach_llp(struct lws_vhost **, pv,
111 				      vhost->context->no_listener_vhost_list) {
112 			if (is >= LWS_ITOSA_USABLE && *pv == vhost) {
113 				/* on the list and shouldn't be: remove it */
114 				lwsl_debug("deferred iface: removing vh %s\n",
115 						(*pv)->name);
116 				*pv = vhost->no_listener_vhost_list;
117 				vhost->no_listener_vhost_list = NULL;
118 				goto done_list;
119 			}
120 			if (is < LWS_ITOSA_USABLE && *pv == vhost)
121 				goto done_list;
122 		} lws_end_foreach_llp(pv, no_listener_vhost_list);
123 
124 		/* not on the list... */
125 
126 		if (is < LWS_ITOSA_USABLE) {
127 
128 			/* ... but needs to be: so add it */
129 
130 			lwsl_debug("deferred iface: adding vh %s\n", vhost->name);
131 			vhost->no_listener_vhost_list =
132 					vhost->context->no_listener_vhost_list;
133 			vhost->context->no_listener_vhost_list = vhost;
134 		}
135 
136 done_list:
137 
138 		switch (is) {
139 		default:
140 			break;
141 		case LWS_ITOSA_NOT_EXIST:
142 			/* can't add it */
143 			if (info) /* first time */
144 				lwsl_err("VH %s: iface %s port %d DOESN'T EXIST\n",
145 				 vhost->name, vhost->iface, vhost->listen_port);
146 			else
147 				return -1;
148 			return (info->options & LWS_SERVER_OPTION_FAIL_UPON_UNABLE_TO_BIND) ==
149 					LWS_SERVER_OPTION_FAIL_UPON_UNABLE_TO_BIND?
150 				-1 : 1;
151 		case LWS_ITOSA_NOT_USABLE:
152 			/* can't add it */
153 			if (info) /* first time */
154 				lwsl_err("VH %s: iface %s port %d NOT USABLE\n",
155 				 vhost->name, vhost->iface, vhost->listen_port);
156 			else
157 				return -1;
158 			return (info->options & LWS_SERVER_OPTION_FAIL_UPON_UNABLE_TO_BIND) ==
159 					LWS_SERVER_OPTION_FAIL_UPON_UNABLE_TO_BIND?
160 				-1 : 1;
161 		}
162 	}
163 
164 	(void)n;
165 #if defined(__linux__)
166 #ifdef LWS_WITH_UNIX_SOCK
167 	/*
168 	 * A Unix domain sockets cannot be bound for several times, even if we set
169 	 * the SO_REUSE* options on.
170 	 * However, fortunately, each thread is able to independently listen when
171 	 * running on a reasonably new Linux kernel. So we can safely assume
172 	 * creating just one listening socket for a multi-threaded environment won't
173 	 * fail in most cases.
174 	 */
175 	if (!LWS_UNIX_SOCK_ENABLED(vhost))
176 #endif
177 	limit = vhost->context->count_threads;
178 #endif
179 
180 	for (m = 0; m < limit; m++) {
181 
182 		if (lws_fi(&vhost->fic, "listenskt")) {
183 			sockfd = LWS_SOCK_INVALID;
184 		} else {
185 
186 #ifdef LWS_WITH_UNIX_SOCK
187 			if (LWS_UNIX_SOCK_ENABLED(vhost))
188 				sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
189 			else {
190 #endif
191 
192 #if defined(LWS_WITH_IPV6)
193 			/*
194 			 * We have to assess iface if it's around, to choose
195 			 * ahead of time to create a socket with the right AF
196 			 */
197 
198 			if (vhost->iface) {
199 				uint8_t buf[16];
200 				int q;
201 
202 				q = lws_parse_numeric_address(vhost->iface, buf, sizeof(buf));
203 
204 				if (q == 4)
205 					af = AF_INET;
206 				if (q == 16)
207 					af = AF_INET6;
208 			}
209 
210 			if (LWS_IPV6_ENABLED(vhost) && af != AF_INET)
211 				sockfd = socket(AF_INET6, SOCK_STREAM, 0);
212 			else
213 #endif
214 				sockfd = socket(AF_INET, SOCK_STREAM, 0);
215 
216 #ifdef LWS_WITH_UNIX_SOCK
217 			}
218 #endif
219 		}
220 
221 		if (sockfd == LWS_SOCK_INVALID) {
222 			lwsl_err("ERROR opening socket\n");
223 			return 1;
224 		}
225 #if !defined(LWS_PLAT_FREERTOS)
226 #if (defined(WIN32) || defined(_WIN32)) && defined(SO_EXCLUSIVEADDRUSE)
227 		/*
228 		 * only accept that we are the only listener on the port
229 		 * https://msdn.microsoft.com/zh-tw/library/
230 		 *    windows/desktop/ms740621(v=vs.85).aspx
231 		 *
232 		 * for lws, to match Linux, we default to exclusive listen
233 		 */
234 		if (!lws_check_opt(vhost->options,
235 				LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE)) {
236 			if (setsockopt(sockfd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
237 				       (const void *)&opt, sizeof(opt)) < 0) {
238 				lwsl_err("reuseaddr failed\n");
239 				compatible_close(sockfd);
240 				return -1;
241 			}
242 		} else
243 #endif
244 
245 		/*
246 		 * allow us to restart even if old sockets in TIME_WAIT
247 		 */
248 		if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
249 			       (const void *)&opt, sizeof(opt)) < 0) {
250 			lwsl_err("reuseaddr failed\n");
251 			compatible_close(sockfd);
252 			return -1;
253 		}
254 
255 #if defined(LWS_WITH_IPV6) && defined(IPV6_V6ONLY)
256 		if (LWS_IPV6_ENABLED(vhost) &&
257 		    vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY) {
258 			int value = (vhost->options &
259 				LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE) ? 1 : 0;
260 			if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
261 				      (const void*)&value, sizeof(value)) < 0) {
262 				compatible_close(sockfd);
263 				return -1;
264 			}
265 		}
266 #endif
267 
268 #if defined(__linux__) && defined(SO_REUSEPORT)
269 		/* keep coverity happy */
270 #if LWS_MAX_SMP > 1
271 		n = 1;
272 #else
273 		n = lws_check_opt(vhost->options,
274 				  LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE);
275 #endif
276 		if (n && vhost->context->count_threads > 1)
277 			if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
278 					(const void *)&opt, sizeof(opt)) < 0) {
279 				compatible_close(sockfd);
280 				return -1;
281 			}
282 #endif
283 #endif
284 		lws_plat_set_socket_options(vhost, sockfd, 0);
285 
286 		is = lws_socket_bind(vhost, NULL, sockfd, vhost->listen_port,
287 				     vhost->iface, 1);
288 		if (is == LWS_ITOSA_BUSY) {
289 			/* treat as fatal */
290 			compatible_close(sockfd);
291 
292 			return -1;
293 		}
294 
295 		/*
296 		 * There is a race where the network device may come up and then
297 		 * go away and fail here.  So correctly handle unexpected failure
298 		 * here despite we earlier confirmed it.
299 		 */
300 		if (is < 0) {
301 			lwsl_info("%s: lws_socket_bind says %d\n", __func__, is);
302 			compatible_close(sockfd);
303 			goto deal;
304 		}
305 
306 		/*
307 		 * Create the listen wsi and customize it
308 		 */
309 
310 		lws_context_lock(vhost->context, __func__);
311 		wsi = __lws_wsi_create_with_role(vhost->context, m, &role_ops_listen);
312 		lws_context_unlock(vhost->context);
313 		if (wsi == NULL) {
314 			lwsl_err("Out of mem\n");
315 			goto bail;
316 		}
317 
318 #ifdef LWS_WITH_UNIX_SOCK
319 		if (!LWS_UNIX_SOCK_ENABLED(vhost))
320 #endif
321 		{
322 			wsi->unix_skt = 1;
323 			vhost->listen_port = is;
324 
325 			lwsl_debug("%s: lws_socket_bind says %d\n", __func__, is);
326 		}
327 
328 		wsi->desc.sockfd = sockfd;
329 		wsi->a.protocol = vhost->protocols;
330 		lws_vhost_bind_wsi(vhost, wsi);
331 		wsi->listener = 1;
332 
333 		if (wsi->a.context->event_loop_ops->init_vhost_listen_wsi)
334 			wsi->a.context->event_loop_ops->init_vhost_listen_wsi(wsi);
335 
336 		pt = &vhost->context->pt[m];
337 		lws_pt_lock(pt, __func__);
338 
339 		if (__insert_wsi_socket_into_fds(vhost->context, wsi)) {
340 			lwsl_notice("inserting wsi socket into fds failed\n");
341 			lws_pt_unlock(pt);
342 			goto bail;
343 		}
344 
345 		vhost->lserv_wsi = wsi;
346 		lws_pt_unlock(pt);
347 
348 		n = listen(wsi->desc.sockfd, LWS_SOMAXCONN);
349 		if (n < 0) {
350 			lwsl_err("listen failed with error %d\n", LWS_ERRNO);
351 			vhost->lserv_wsi = NULL;
352 			__remove_wsi_socket_from_fds(wsi);
353 			goto bail;
354 		}
355 
356 		if (wsi)
357 			__lws_lc_tag(&vhost->context->lcg[LWSLCG_WSI],
358 				     &wsi->lc, "listen|%s|%s|%d", vhost->name,
359 				     vhost->iface ? vhost->iface : "",
360 				     (int)vhost->listen_port);
361 
362 	} /* for each thread able to independently listen */
363 
364 	if (!lws_check_opt(vhost->context->options,
365 			   LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) {
366 #ifdef LWS_WITH_UNIX_SOCK
367 		if (LWS_UNIX_SOCK_ENABLED(vhost))
368 			lwsl_info(" Listening on \"%s\"\n", vhost->iface);
369 		else
370 #endif
371 			lwsl_info(" Listening on port %d\n", vhost->listen_port);
372         }
373 
374 	// info->port = vhost->listen_port;
375 
376 	return 0;
377 
378 bail:
379 	compatible_close(sockfd);
380 
381 	return -1;
382 }
383 #endif
384 
385 struct lws_vhost *
lws_select_vhost(struct lws_context * context,int port,const char * servername)386 lws_select_vhost(struct lws_context *context, int port, const char *servername)
387 {
388 	struct lws_vhost *vhost = context->vhost_list;
389 	const char *p;
390 	int n, colon;
391 
392 	n = (int)strlen(servername);
393 	colon = n;
394 	p = strchr(servername, ':');
395 	if (p)
396 		colon = lws_ptr_diff(p, servername);
397 
398 	/* Priotity 1: first try exact matches */
399 
400 	while (vhost) {
401 		if (port == vhost->listen_port &&
402 		    !strncmp(vhost->name, servername, (unsigned int)colon)) {
403 			lwsl_info("SNI: Found: %s\n", servername);
404 			return vhost;
405 		}
406 		vhost = vhost->vhost_next;
407 	}
408 
409 	/*
410 	 * Priority 2: if no exact matches, try matching *.vhost-name
411 	 * unintentional matches are possible but resolve to x.com for *.x.com
412 	 * which is reasonable.  If exact match exists we already chose it and
413 	 * never reach here.  SSL will still fail it if the cert doesn't allow
414 	 * *.x.com.
415 	 */
416 	vhost = context->vhost_list;
417 	while (vhost) {
418 		int m = (int)strlen(vhost->name);
419 		if (port && port == vhost->listen_port &&
420 		    m <= (colon - 2) &&
421 		    servername[colon - m - 1] == '.' &&
422 		    !strncmp(vhost->name, servername + colon - m, (unsigned int)m)) {
423 			lwsl_info("SNI: Found %s on wildcard: %s\n",
424 				    servername, vhost->name);
425 			return vhost;
426 		}
427 		vhost = vhost->vhost_next;
428 	}
429 
430 	/* Priority 3: match the first vhost on our port */
431 
432 	vhost = context->vhost_list;
433 	while (vhost) {
434 		if (port && port == vhost->listen_port) {
435 			lwsl_info("%s: vhost match to %s based on port %d\n",
436 					__func__, vhost->name, port);
437 			return vhost;
438 		}
439 		vhost = vhost->vhost_next;
440 	}
441 
442 	/* no match */
443 
444 	return NULL;
445 }
446 
447 static const struct lws_mimetype {
448 	const char *extension;
449 	const char *mimetype;
450 } server_mimetypes[] = {
451 	{ ".html", "text/html" },
452 	{ ".htm", "text/html" },
453 	{ ".js", "text/javascript" },
454 	{ ".css", "text/css" },
455 	{ ".png", "image/png" },
456 	{ ".jpg", "image/jpeg" },
457 	{ ".jpeg", "image/jpeg" },
458 	{ ".ico", "image/x-icon" },
459 	{ ".gif", "image/gif" },
460 	{ ".svg", "image/svg+xml" },
461 	{ ".ttf", "application/x-font-ttf" },
462 	{ ".otf", "application/font-woff" },
463 	{ ".woff", "application/font-woff" },
464 	{ ".woff2", "application/font-woff2" },
465 	{ ".gz", "application/gzip" },
466 	{ ".txt", "text/plain" },
467 	{ ".xml", "application/xml" },
468 	{ ".json", "application/json" },
469 	{ ".mjs", "text/javascript" },
470 };
471 
472 const char *
lws_get_mimetype(const char * file,const struct lws_http_mount * m)473 lws_get_mimetype(const char *file, const struct lws_http_mount *m)
474 {
475 	const struct lws_protocol_vhost_options *pvo;
476 	size_t n = strlen(file), len, i;
477 	const char *fallback_mimetype = NULL;
478 	const struct lws_mimetype *mt;
479 
480 	/* prioritize user-defined mimetypes */
481 	for (pvo = m ? m->extra_mimetypes : NULL; pvo; pvo = pvo->next) {
482 		/* ie, match anything */
483 		if (!fallback_mimetype && pvo->name[0] == '*') {
484 			fallback_mimetype = pvo->value;
485 			continue;
486 		}
487 
488 		len = strlen(pvo->name);
489 		if (n > len && !strcasecmp(&file[n - len], pvo->name)) {
490 			lwsl_info("%s: match to user mimetype: %s\n", __func__,
491 				  pvo->value);
492 			return pvo->value;
493 		}
494 	}
495 
496 	/* fallback to server-defined mimetypes */
497 	for (i = 0; i < LWS_ARRAY_SIZE(server_mimetypes); ++i) {
498 		mt = &server_mimetypes[i];
499 
500 		len = strlen(mt->extension);
501 		if (n > len && !strcasecmp(&file[n - len], mt->extension)) {
502 			lwsl_info("%s: match to server mimetype: %s\n", __func__,
503 				  mt->mimetype);
504 			return mt->mimetype;
505 		}
506 	}
507 
508 	/* fallback to '*' if defined */
509 	if (fallback_mimetype) {
510 		lwsl_info("%s: match to any mimetype: %s\n", __func__,
511 			  fallback_mimetype);
512 		return fallback_mimetype;
513 	}
514 
515 	return NULL;
516 }
517 
518 #if defined(LWS_WITH_FILE_OPS)
519 static lws_fop_flags_t
lws_vfs_prepare_flags(struct lws * wsi)520 lws_vfs_prepare_flags(struct lws *wsi)
521 {
522 	lws_fop_flags_t f = 0;
523 
524 	if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING))
525 		return f;
526 
527 	if (strstr(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING),
528 		   "gzip")) {
529 		lwsl_info("client indicates GZIP is acceptable\n");
530 		f |= LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP;
531 	}
532 
533 	return f;
534 }
535 
536 static int
lws_http_serve(struct lws * wsi,char * uri,const char * origin,const struct lws_http_mount * m)537 lws_http_serve(struct lws *wsi, char *uri, const char *origin,
538 	       const struct lws_http_mount *m)
539 {
540 	const struct lws_protocol_vhost_options *pvo = m->interpret;
541 	struct lws_process_html_args args;
542 	const char *mimetype;
543 #if !defined(_WIN32_WCE)
544 	const struct lws_plat_file_ops *fops;
545 	const char *vpath;
546 	lws_fop_flags_t fflags = LWS_O_RDONLY;
547 #if defined(WIN32) && defined(LWS_HAVE__STAT32I64)
548 	struct _stat32i64 st;
549 #else
550 	struct stat st;
551 #endif
552 	int spin = 0;
553 #endif
554 	char path[256], sym[2048];
555 	unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
556 	unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
557 #if !defined(WIN32) && !defined(LWS_PLAT_FREERTOS)
558 	size_t len;
559 #endif
560 	int n;
561 
562 	wsi->handling_404 = 0;
563 	if (!wsi->a.vhost)
564 		return -1;
565 
566 #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
567 	if (wsi->a.vhost->http.error_document_404 &&
568 	    !strcmp(uri, wsi->a.vhost->http.error_document_404))
569 		wsi->handling_404 = 1;
570 #endif
571 
572 	lws_snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
573 
574 #if !defined(_WIN32_WCE)
575 
576 	fflags |= lws_vfs_prepare_flags(wsi);
577 
578 	do {
579 		spin++;
580 		fops = lws_vfs_select_fops(wsi->a.context->fops, path, &vpath);
581 
582 		if (wsi->http.fop_fd)
583 			lws_vfs_file_close(&wsi->http.fop_fd);
584 
585 		wsi->http.fop_fd = fops->LWS_FOP_OPEN(wsi->a.context->fops,
586 							path, vpath, &fflags);
587 		if (!wsi->http.fop_fd) {
588 			lwsl_info("%s: Unable to open '%s': errno %d\n",
589 				  __func__, path, errno);
590 
591 			return 1;
592 		}
593 
594 		/* if it can't be statted, don't try */
595 		if (fflags & LWS_FOP_FLAG_VIRTUAL)
596 			break;
597 #if defined(LWS_PLAT_FREERTOS)
598 		break;
599 #endif
600 #if !defined(WIN32)
601 		if (fstat(wsi->http.fop_fd->fd, &st)) {
602 			lwsl_info("unable to stat %s\n", path);
603 			goto notfound;
604 		}
605 #else
606 #if defined(LWS_HAVE__STAT32I64)
607 		if (_stat32i64(path, &st)) {
608 			lwsl_info("unable to stat %s\n", path);
609 			goto notfound;
610 		}
611 #else
612 		if (stat(path, &st)) {
613 			lwsl_info("unable to stat %s\n", path);
614 			goto notfound;
615 		}
616 #endif
617 #endif
618 
619 		wsi->http.fop_fd->mod_time = (uint32_t)st.st_mtime;
620 		fflags |= LWS_FOP_FLAG_MOD_TIME_VALID;
621 
622 #if !defined(WIN32) && !defined(LWS_PLAT_FREERTOS)
623 		if ((S_IFMT & st.st_mode) == S_IFLNK) {
624 			len = (size_t)readlink(path, sym, sizeof(sym) - 1);
625 			if (len) {
626 				lwsl_err("Failed to read link %s\n", path);
627 				goto notfound;
628 			}
629 			sym[len] = '\0';
630 			lwsl_debug("symlink %s -> %s\n", path, sym);
631 			lws_snprintf(path, sizeof(path) - 1, "%s", sym);
632 		}
633 #endif
634 		if ((S_IFMT & st.st_mode) == S_IFDIR) {
635 			lwsl_debug("default filename append to dir\n");
636 			lws_snprintf(path, sizeof(path) - 1, "%s/%s/%s",
637 				 origin, uri, m->def ? m->def : "index.html");
638 		}
639 
640 	} while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
641 
642 	if (spin == 5)
643 		lwsl_err("symlink loop %s \n", path);
644 
645 	n = sprintf(sym, "%08llX%08lX",
646 		    (unsigned long long)lws_vfs_get_length(wsi->http.fop_fd),
647 		    (unsigned long)lws_vfs_get_mod_time(wsi->http.fop_fd));
648 
649 	/* disable ranges if IF_RANGE token invalid */
650 
651 	if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_RANGE))
652 		if (strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_RANGE)))
653 			/* differs - defeat Range: */
654 			wsi->http.ah->frag_index[WSI_TOKEN_HTTP_RANGE] = 0;
655 
656 	if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
657 		/*
658 		 * he thinks he has some version of it already,
659 		 * check if the tag matches
660 		 */
661 		if (!strcmp(sym, lws_hdr_simple_ptr(wsi,
662 					WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
663 
664 			char cache_control[50], *cc = "no-store";
665 			int cclen = 8;
666 
667 			lwsl_debug("%s: ETAG match %s %s\n", __func__,
668 				   uri, origin);
669 
670 			/* we don't need to send the payload */
671 			if (lws_add_http_header_status(wsi,
672 					HTTP_STATUS_NOT_MODIFIED, &p, end)) {
673 				lwsl_err("%s: failed adding not modified\n",
674 						__func__);
675 				return -1;
676 			}
677 
678 			if (lws_add_http_header_by_token(wsi,
679 					WSI_TOKEN_HTTP_ETAG,
680 					(unsigned char *)sym, n, &p, end))
681 				return -1;
682 
683 			/* but we still need to send cache control... */
684 
685 			if (m->cache_max_age && m->cache_reusable) {
686 				if (!m->cache_revalidate) {
687 					cc = cache_control;
688 					cclen = sprintf(cache_control,
689 						"%s, max-age=%u",
690 						intermediates[wsi->cache_intermediaries],
691 						m->cache_max_age);
692 				} else {
693 					cc = cache_control;
694                                         cclen = sprintf(cache_control,
695                                         	"must-revalidate, %s, max-age=%u",
696                                                 intermediates[wsi->cache_intermediaries],
697                                                 m->cache_max_age);
698 				}
699 			}
700 
701 			if (lws_add_http_header_by_token(wsi,
702 					WSI_TOKEN_HTTP_CACHE_CONTROL,
703 					(unsigned char *)cc, cclen, &p, end))
704 				return -1;
705 
706 			if (lws_finalize_http_header(wsi, &p, end))
707 				return -1;
708 
709 			n = lws_write(wsi, start, lws_ptr_diff_size_t(p, start),
710 				      LWS_WRITE_HTTP_HEADERS |
711 				      LWS_WRITE_H2_STREAM_END);
712 			if (n != lws_ptr_diff(p, start)) {
713 				lwsl_err("_write returned %d from %ld\n", n,
714 					 (long)(p - start));
715 				return -1;
716 			}
717 
718 			lws_vfs_file_close(&wsi->http.fop_fd);
719 
720 			if (lws_http_transaction_completed(wsi))
721 				return -1;
722 
723 			return 0;
724 		}
725 	}
726 
727 	if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
728 			(unsigned char *)sym, n, &p, end))
729 		return -1;
730 #endif
731 
732 	mimetype = lws_get_mimetype(path, m);
733 	if (!mimetype) {
734 		lwsl_info("unknown mimetype for %s\n", path);
735 		if (lws_return_http_status(wsi,
736 				HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL) ||
737 		    lws_http_transaction_completed(wsi))
738 			return -1;
739 
740 		return 0;
741 	}
742 	if (!mimetype[0])
743 		lwsl_debug("sending no mimetype for %s\n", path);
744 
745 	wsi->sending_chunked = 0;
746 	wsi->interpreting = 0;
747 
748 	/*
749 	 * check if this is in the list of file suffixes to be interpreted by
750 	 * a protocol
751 	 */
752 	while (pvo) {
753 		n = (int)strlen(path);
754 		if (n > (int)strlen(pvo->name) &&
755 		    !strcmp(&path[(unsigned int)n - strlen(pvo->name)], pvo->name)) {
756 			wsi->interpreting = 1;
757 			if (!wsi->mux_substream)
758 				wsi->sending_chunked = 1;
759 
760 			wsi->protocol_interpret_idx = (char)(
761 				lws_vhost_name_to_protocol(wsi->a.vhost,
762 							   pvo->value) -
763 				&lws_get_vhost(wsi)->protocols[0]);
764 
765 			lwsl_debug("want %s interpreted by %s (pcol is %s)\n", path,
766 				    wsi->a.vhost->protocols[
767 				             (int)wsi->protocol_interpret_idx].name,
768 				             wsi->a.protocol->name);
769 			if (lws_bind_protocol(wsi, &wsi->a.vhost->protocols[
770 			          (int)wsi->protocol_interpret_idx], __func__))
771 				return -1;
772 
773 			if (lws_ensure_user_space(wsi))
774 				return -1;
775 			break;
776 		}
777 		pvo = pvo->next;
778 	}
779 
780 	if (wsi->sending_chunked) {
781 		if (lws_add_http_header_by_token(wsi,
782 				WSI_TOKEN_HTTP_TRANSFER_ENCODING,
783 				(unsigned char *)"chunked", 7,
784 				&p, end))
785 			return -1;
786 	}
787 
788 	if (m->protocol) {
789 		const struct lws_protocols *pp = lws_vhost_name_to_protocol(
790 						       wsi->a.vhost, m->protocol);
791 
792 		if (lws_bind_protocol(wsi, pp, __func__))
793 			return -1;
794 		args.p = (char *)p;
795 		args.max_len = lws_ptr_diff(end, p);
796 		if (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS,
797 					  wsi->user_space, &args, 0))
798 			return -1;
799 		p = (unsigned char *)args.p;
800 	}
801 
802 	*p = '\0';
803 	n = lws_serve_http_file(wsi, path, mimetype, (char *)start,
804 				lws_ptr_diff(p, start));
805 
806 	if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
807 		return -1; /* error or can't reuse connection: close the socket */
808 
809 	return 0;
810 
811 notfound:
812 
813 	return 1;
814 }
815 #endif
816 
817 #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
818 const struct lws_http_mount *
lws_find_mount(struct lws * wsi,const char * uri_ptr,int uri_len)819 lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len)
820 {
821 	const struct lws_http_mount *hm, *hit = NULL;
822 	int best = 0;
823 
824 	hm = wsi->a.vhost->http.mount_list;
825 	while (hm) {
826 		if (uri_len >= hm->mountpoint_len &&
827 		    !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
828 		    (uri_ptr[hm->mountpoint_len] == '\0' ||
829 		     uri_ptr[hm->mountpoint_len] == '/' ||
830 		     hm->mountpoint_len == 1)
831 		    ) {
832 #if defined(LWS_WITH_SYS_METRICS)
833 			lws_metrics_tag_wsi_add(wsi, "mnt", hm->mountpoint);
834 #endif
835 
836 			if (hm->origin_protocol == LWSMPRO_CALLBACK ||
837 			    ((hm->origin_protocol == LWSMPRO_CGI ||
838 			     lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) ||
839 			     lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
840 #if defined(LWS_WITH_HTTP_UNCOMMON_HEADERS)
841 			     lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI) ||
842 			     lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
843 			     lws_hdr_total_length(wsi, WSI_TOKEN_DELETE_URI) ||
844 #endif
845 			     lws_hdr_total_length(wsi, WSI_TOKEN_HEAD_URI) ||
846 #if defined(LWS_ROLE_H2)
847 			     (wsi->mux_substream &&
848 				lws_hdr_total_length(wsi,
849 						WSI_TOKEN_HTTP_COLON_PATH)) ||
850 #endif
851 			     hm->protocol) &&
852 			    hm->mountpoint_len > best)) {
853 				best = hm->mountpoint_len;
854 				hit = hm;
855 			}
856 		}
857 		hm = hm->mount_next;
858 	}
859 
860 	return hit;
861 }
862 #endif
863 
864 #if defined(LWS_WITH_HTTP_BASIC_AUTH) && !defined(LWS_PLAT_FREERTOS) && defined(LWS_WITH_FILE_OPS)
865 static int
lws_find_string_in_file(const char * filename,const char * string,int stringlen)866 lws_find_string_in_file(const char *filename, const char *string, int stringlen)
867 {
868 	char buf[128];
869 	int fd, match = 0, pos = 0, n = 0, hit = 0;
870 
871 	fd = lws_open(filename, O_RDONLY);
872 	if (fd < 0) {
873 		lwsl_err("can't open auth file: %s\n", filename);
874 		return 0;
875 	}
876 
877 	while (1) {
878 		if (pos == n) {
879 			n = (int)read(fd, buf, sizeof(buf));
880 			if (n <= 0) {
881 				if (match == stringlen)
882 					hit = 1;
883 				break;
884 			}
885 			pos = 0;
886 		}
887 
888 		if (match == stringlen) {
889 			if (buf[pos] == '\r' || buf[pos] == '\n') {
890 				hit = 1;
891 				break;
892 			}
893 			match = 0;
894 		}
895 
896 		if (buf[pos] == string[match])
897 			match++;
898 		else
899 			match = 0;
900 
901 		pos++;
902 	}
903 
904 	close(fd);
905 
906 	return hit;
907 }
908 #endif
909 
910 #if defined(LWS_WITH_HTTP_BASIC_AUTH)
911 
912 int
lws_unauthorised_basic_auth(struct lws * wsi)913 lws_unauthorised_basic_auth(struct lws *wsi)
914 {
915 	struct lws_context_per_thread *pt = &wsi->a.context->pt[(int)wsi->tsi];
916 	unsigned char *start = pt->serv_buf + LWS_PRE,
917 		      *p = start, *end = p + 2048;
918 	char buf[64];
919 	int n;
920 
921 	/* no auth... tell him it is required */
922 
923 	if (lws_add_http_header_status(wsi, HTTP_STATUS_UNAUTHORIZED, &p, end))
924 		return -1;
925 
926 	n = lws_snprintf(buf, sizeof(buf), "Basic realm=\"lwsws\"");
927 	if (lws_add_http_header_by_token(wsi,
928 			WSI_TOKEN_HTTP_WWW_AUTHENTICATE,
929 			(unsigned char *)buf, n, &p, end))
930 		return -1;
931 
932 	if (lws_add_http_header_content_length(wsi, 0, &p, end))
933 		return -1;
934 
935 	if (lws_finalize_http_header(wsi, &p, end))
936 		return -1;
937 
938 	n = lws_write(wsi, start, lws_ptr_diff_size_t(p, start), LWS_WRITE_HTTP_HEADERS |
939 					     LWS_WRITE_H2_STREAM_END);
940 	if (n < 0)
941 		return -1;
942 
943 	return lws_http_transaction_completed(wsi);
944 
945 }
946 
947 #endif
948 
lws_clean_url(char * p)949 int lws_clean_url(char *p)
950 {
951 	if (p[0] == 'h' && p[1] == 't' && p[2] == 't' && p[3] == 'p') {
952 		p += 4;
953 		if (*p == 's')
954 		p++;
955 		if (*p == ':') {
956 			p++;
957 			if (*p == '/')
958 			p++;
959 		}
960 	}
961 
962 	while (*p) {
963 		if (p[0] == '/' && p[1] == '/') {
964 			char *p1 = p;
965 			while (*p1) {
966 				*p1 = p1[1];
967 				p1++;
968 			}
969 			continue;
970 		}
971 		p++;
972 	}
973 
974 	return 0;
975 }
976 
977 static const unsigned char methods[] = {
978 	WSI_TOKEN_GET_URI,
979 	WSI_TOKEN_POST_URI,
980 #if defined(LWS_WITH_HTTP_UNCOMMON_HEADERS)
981 	WSI_TOKEN_OPTIONS_URI,
982 	WSI_TOKEN_PUT_URI,
983 	WSI_TOKEN_PATCH_URI,
984 	WSI_TOKEN_DELETE_URI,
985 #endif
986 	WSI_TOKEN_CONNECT,
987 	WSI_TOKEN_HEAD_URI,
988 #ifdef LWS_WITH_HTTP2
989 	WSI_TOKEN_HTTP_COLON_PATH,
990 #endif
991 };
992 
993 int
lws_http_get_uri_and_method(struct lws * wsi,char ** puri_ptr,int * puri_len)994 lws_http_get_uri_and_method(struct lws *wsi, char **puri_ptr, int *puri_len)
995 {
996 	int n, count = 0;
997 
998 	for (n = 0; n < (int)LWS_ARRAY_SIZE(methods); n++)
999 		if (lws_hdr_total_length(wsi, methods[n]))
1000 			count++;
1001 	if (!count) {
1002 		lwsl_warn("Missing URI in HTTP request\n");
1003 		return -1;
1004 	}
1005 
1006 	if (count != 1 &&
1007 	    !((wsi->mux_substream || wsi->h2_stream_carries_ws)
1008 #if defined(LWS_ROLE_H2)
1009 			    &&
1010 	      lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COLON_PATH)
1011 #endif
1012 	      )) {
1013 		lwsl_warn("multiple methods?\n");
1014 		return -1;
1015 	}
1016 
1017 	for (n = 0; n < (int)LWS_ARRAY_SIZE(methods); n++)
1018 		if (lws_hdr_total_length(wsi, methods[n])) {
1019 			*puri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
1020 			*puri_len = lws_hdr_total_length(wsi, methods[n]);
1021 			return n;
1022 		}
1023 
1024 	return -1;
1025 }
1026 
1027 #if defined(LWS_WITH_HTTP_BASIC_AUTH)
1028 
1029 enum lws_check_basic_auth_results
lws_check_basic_auth(struct lws * wsi,const char * basic_auth_login_file,unsigned int auth_mode)1030 lws_check_basic_auth(struct lws *wsi, const char *basic_auth_login_file,
1031 		     unsigned int auth_mode)
1032 {
1033 #if defined(LWS_WITH_FILE_OPS)
1034 	char b64[160], plain[(sizeof(b64) * 3) / 4], *pcolon;
1035 	int m, ml, fi, bar;
1036 
1037 	if (!basic_auth_login_file && auth_mode == LWSAUTHM_DEFAULT)
1038 		return LCBA_CONTINUE;
1039 
1040 	/* Did he send auth? */
1041 	ml = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_AUTHORIZATION);
1042 	if (!ml)
1043 		return LCBA_FAILED_AUTH;
1044 
1045 	/* Disallow fragmentation monkey business */
1046 
1047 	fi = wsi->http.ah->frag_index[WSI_TOKEN_HTTP_AUTHORIZATION];
1048 	if (wsi->http.ah->frags[fi].nfrag) {
1049 		lwsl_err("fragmented basic auth header not allowed\n");
1050 		return LCBA_FAILED_AUTH;
1051 	}
1052 
1053 	m = lws_hdr_copy(wsi, b64, sizeof(b64),
1054 			 WSI_TOKEN_HTTP_AUTHORIZATION);
1055 	if (m < 7) {
1056 		lwsl_err("b64 auth too long\n");
1057 		return LCBA_END_TRANSACTION;
1058 	}
1059 
1060 	b64[5] = '\0';
1061 	if (strcasecmp(b64, "Basic")) {
1062 		lwsl_err("auth missing basic: %s\n", b64);
1063 		return LCBA_END_TRANSACTION;
1064 	}
1065 
1066 	/* It'll be like Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l */
1067 
1068 	m = lws_b64_decode_string(b64 + 6, plain, sizeof(plain) - 1);
1069 	if (m < 0) {
1070 		lwsl_err("plain auth too long\n");
1071 		return LCBA_END_TRANSACTION;
1072 	}
1073 
1074 	plain[m] = '\0';
1075 	pcolon = strchr(plain, ':');
1076 	if (!pcolon) {
1077 		lwsl_err("basic auth format broken\n");
1078 		return LCBA_END_TRANSACTION;
1079 	}
1080 
1081 	switch (auth_mode) {
1082 	case LWSAUTHM_DEFAULT:
1083 		if (lws_find_string_in_file(basic_auth_login_file, plain, m))
1084 			break;
1085 		lwsl_err("%s: basic auth lookup failed\n", __func__);
1086 		return LCBA_FAILED_AUTH;
1087 
1088 	case LWSAUTHM_BASIC_AUTH_CALLBACK:
1089 		bar = wsi->a.protocol->callback(wsi,
1090 				LWS_CALLBACK_VERIFY_BASIC_AUTHORIZATION,
1091 				wsi->user_space, plain, (unsigned int)m);
1092 		if (!bar)
1093 			return LCBA_FAILED_AUTH;
1094 		break;
1095 	default:
1096 		/* Invalid auth mode so lets fail all authentication attempts */
1097 		return LCBA_FAILED_AUTH;
1098 	}
1099 
1100 	/*
1101 	 * Rewrite WSI_TOKEN_HTTP_AUTHORIZATION so it is just the
1102 	 * authorized username
1103 	 */
1104 
1105 	*pcolon = '\0';
1106 	wsi->http.ah->frags[fi].len = (uint16_t)lws_ptr_diff_size_t(pcolon, &plain[0]);
1107 	pcolon = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_AUTHORIZATION);
1108 	strncpy(pcolon, plain, (unsigned int)(ml - 1));
1109 	pcolon[ml - 1] = '\0';
1110 	lwsl_info("%s: basic auth accepted for %s\n", __func__,
1111 		 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_AUTHORIZATION));
1112 
1113 	return LCBA_CONTINUE;
1114 #else
1115 	return LCBA_FAILED_AUTH;
1116 #endif
1117 }
1118 
1119 #endif
1120 
1121 #if defined(LWS_WITH_HTTP_PROXY)
1122 /*
1123  * Set up an onward http proxy connection according to the mount this
1124  * uri falls under.  Notice this can also be starting the proxying of what was
1125  * originally an incoming h1 upgrade, or an h2 ws "upgrade".
1126  */
1127 int
lws_http_proxy_start(struct lws * wsi,const struct lws_http_mount * hit,char * uri_ptr,char ws)1128 lws_http_proxy_start(struct lws *wsi, const struct lws_http_mount *hit,
1129 		     char *uri_ptr, char ws)
1130 {
1131 	char ads[96], rpath[256], host[96], *pcolon, *pslash, unix_skt = 0;
1132 	struct lws_client_connect_info i;
1133 	struct lws *cwsi;
1134 	int n, na;
1135 
1136 #if defined(LWS_ROLE_WS)
1137 	if (ws)
1138 		/*
1139 		 * Neither our inbound ws upgrade request side, nor our onward
1140 		 * ws client connection on our side can bind to the actual
1141 		 * protocol that only the remote inbound side and the remote
1142 		 * onward side understand.
1143 		 *
1144 		 * Instead these are both bound to our built-in "lws-ws-proxy"
1145 		 * protocol, which understands how to proxy between the two
1146 		 * sides.
1147 		 *
1148 		 * We bind the parent, inbound part here and our side of the
1149 		 * onward client connection is bound to the same handler using
1150 		 * the .local_protocol_name.
1151 		 */
1152 		lws_bind_protocol(wsi, &lws_ws_proxy, __func__);
1153 #endif
1154 	memset(&i, 0, sizeof(i));
1155 	i.context = lws_get_context(wsi);
1156 
1157 	if (hit->origin[0] == '+')
1158 		unix_skt = 1;
1159 
1160 	pcolon = strchr(hit->origin, ':');
1161 	pslash = strchr(hit->origin, '/');
1162 	if (!pslash) {
1163 		lwsl_err("Proxy mount origin '%s' must have /\n", hit->origin);
1164 		return -1;
1165 	}
1166 
1167 	if (unix_skt) {
1168 		if (!pcolon) {
1169 			lwsl_err("Proxy mount origin for unix skt must "
1170 				 "have address delimited by :\n");
1171 
1172 			return -1;
1173 		}
1174 		n = lws_ptr_diff(pcolon, hit->origin);
1175 		pslash = pcolon;
1176 	} else {
1177 		if (pcolon > pslash)
1178 			pcolon = NULL;
1179 
1180 		if (pcolon)
1181 			n = (int)(pcolon - hit->origin);
1182 		else
1183 			n = (int)(pslash - hit->origin);
1184 
1185 		if (n >= (int)sizeof(ads) - 2)
1186 			n = sizeof(ads) - 2;
1187 	}
1188 
1189 	memcpy(ads, hit->origin, (unsigned int)n);
1190 	ads[n] = '\0';
1191 
1192 	i.address = ads;
1193 	i.port = 80;
1194 	if (hit->origin_protocol == LWSMPRO_HTTPS) {
1195 		i.port = 443;
1196 		i.ssl_connection = 1;
1197 	}
1198 	if (pcolon)
1199 		i.port = atoi(pcolon + 1);
1200 
1201 	n = lws_snprintf(rpath, sizeof(rpath) - 1, "/%s/%s",
1202 			 pslash + 1, uri_ptr + hit->mountpoint_len) - 1;
1203 	lws_clean_url(rpath);
1204 	n = (int)strlen(rpath);
1205 	if (n && rpath[n - 1] == '/')
1206 		n--;
1207 
1208 	na = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_URI_ARGS);
1209 	if (na) {
1210 		char *p;
1211 		int budg;
1212 
1213 		if (!n) /* don't start with the ?... use the first / if so */
1214 			n++;
1215 
1216 		p = rpath + n;
1217 
1218 		if (na >= (int)sizeof(rpath) - n - 2) {
1219 			lwsl_info("%s: query string %d longer "
1220 				  "than we can handle\n", __func__,
1221 				  na);
1222 
1223 			return -1;
1224 		}
1225 
1226 		*p++ = '?';
1227 		budg = lws_hdr_copy(wsi, p,
1228 			     (int)(&rpath[sizeof(rpath) - 1] - p),
1229 			     WSI_TOKEN_HTTP_URI_ARGS);
1230 	       if (budg > 0)
1231 		       p += budg;
1232 
1233 		*p = '\0';
1234 	}
1235 
1236 	i.path = rpath;
1237 	lwsl_notice("%s: proxied path '%s'\n", __func__, i.path);
1238 
1239 	/* incoming may be h1 or h2... if he sends h1 HOST, use that
1240 	 * directly, otherwise we must convert h2 :authority to h1
1241 	 * host */
1242 
1243 	i.host = NULL;
1244 #if defined(LWS_ROLE_H2)
1245 	n = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COLON_AUTHORITY);
1246 	if (n > 0)
1247 		i.host = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COLON_AUTHORITY);
1248 	else
1249 #endif
1250 	{
1251 		n = lws_hdr_total_length(wsi, WSI_TOKEN_HOST);
1252 		if (n > 0) {
1253 			i.host = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST);
1254 		}
1255 	}
1256 
1257 #if 0
1258 	if (i.address[0] != '+' ||
1259 	    !lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST))
1260 		i.host = i.address;
1261 	else
1262 		i.host = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST);
1263 #endif
1264 	i.origin = NULL;
1265 	if (!ws) {
1266 		if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_POST_URI)
1267 #if defined(LWS_WITH_HTTP2)
1268 								|| (
1269 			lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COLON_METHOD) &&
1270 			!strcmp(lws_hdr_simple_ptr(wsi,
1271 					WSI_TOKEN_HTTP_COLON_METHOD), "post")
1272 			)
1273 #endif
1274 		)
1275 			i.method = "POST";
1276 		else
1277 			i.method = "GET";
1278 	}
1279 
1280 	if (i.host)
1281 		lws_snprintf(host, sizeof(host), "%s:%u", i.host,
1282 					wsi->a.vhost->listen_port);
1283 	else
1284 		lws_snprintf(host, sizeof(host), "%s:%d", i.address, i.port);
1285 
1286 	i.host = host;
1287 
1288 	i.alpn = "http/1.1";
1289 	i.parent_wsi = wsi;
1290 	i.pwsi = &cwsi;
1291 #if defined(LWS_ROLE_WS)
1292 	i.protocol = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
1293 	if (ws)
1294 		i.local_protocol_name = "lws-ws-proxy";
1295 #endif
1296 
1297 //	i.uri_replace_from = hit->origin;
1298 //	i.uri_replace_to = hit->mountpoint;
1299 
1300 	lwsl_info("proxying to %s port %d url %s, ssl %d, from %s, to %s\n",
1301 		   i.address, i.port, i.path, i.ssl_connection,
1302 		   i.uri_replace_from, i.uri_replace_to);
1303 
1304 	if (!lws_client_connect_via_info(&i)) {
1305 		lwsl_err("proxy connect fail\n");
1306 
1307 		/*
1308 		 * ... we can't do the proxy action, but we can
1309 		 * cleanly return him a 503 and a description
1310 		 */
1311 
1312 		lws_return_http_status(wsi,
1313 			HTTP_STATUS_SERVICE_UNAVAILABLE,
1314 			"<h1>Service Temporarily Unavailable</h1>"
1315 			"The server is temporarily unable to service "
1316 			"your request due to maintenance downtime or "
1317 			"capacity problems. Please try again later.");
1318 
1319 		return 1;
1320 	}
1321 
1322 	lwsl_info("%s: setting proxy clientside on %s (parent %s)\n",
1323 		  __func__, lws_wsi_tag(cwsi), lws_wsi_tag(lws_get_parent(cwsi)));
1324 
1325 	cwsi->http.proxy_clientside = 1;
1326 	if (ws) {
1327 		wsi->proxied_ws_parent = 1;
1328 		cwsi->h1_ws_proxied = 1;
1329 		if (i.protocol) {
1330 			lwsl_debug("%s: (requesting '%s')\n",
1331 					__func__, i.protocol);
1332 		}
1333 	}
1334 
1335 	return 0;
1336 }
1337 #endif
1338 
1339 
1340 static const char * const oprot[] = {
1341 	"http://", "https://"
1342 };
1343 
1344 
1345 static int
lws_http_redirect_hit(struct lws_context_per_thread * pt,struct lws * wsi,const struct lws_http_mount * hit,char * uri_ptr,int uri_len,int * h)1346 lws_http_redirect_hit(struct lws_context_per_thread *pt, struct lws *wsi,
1347 		      const struct lws_http_mount *hit, char *uri_ptr,
1348 		      int uri_len, int *h)
1349 {
1350 	char *s;
1351 	int n;
1352 
1353 	*h = 0;
1354 	s = uri_ptr + hit->mountpoint_len;
1355 
1356 	/*
1357 	 * if we have a mountpoint like https://xxx.com/yyy
1358 	 * there is an implied / at the end for our purposes since
1359 	 * we can only mount on a "directory".
1360 	 *
1361 	 * But if we just go with that, the browser cannot understand
1362 	 * that he is actually looking down one "directory level", so
1363 	 * even though we give him /yyy/abc.html he acts like the
1364 	 * current directory level is /.  So relative urls like "x.png"
1365 	 * wrongly look outside the mountpoint.
1366 	 *
1367 	 * Therefore if we didn't come in on a url with an explicit
1368 	 * / at the end, we must redirect to add it so the browser
1369 	 * understands he is one "directory level" down.
1370 	 */
1371 	if ((hit->mountpoint_len > 1 ||
1372 	     (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
1373 	      hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
1374 	    (*s != '/' ||
1375 	     (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
1376 	      hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
1377 	    (hit->origin_protocol != LWSMPRO_CGI &&
1378 	     hit->origin_protocol != LWSMPRO_CALLBACK)) {
1379 		unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
1380 			      *end = p + wsi->a.context->pt_serv_buf_size -
1381 					LWS_PRE - 512;
1382 
1383 		*h = 1;
1384 
1385 		lwsl_info("Doing 301 '%s' org %s\n", s, hit->origin);
1386 
1387 		/* > at start indicates deal with by redirect */
1388 		if (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
1389 		    hit->origin_protocol == LWSMPRO_REDIR_HTTPS)
1390 			n = lws_snprintf((char *)end, 256, "%s%s",
1391 				    oprot[hit->origin_protocol & 1],
1392 				    hit->origin);
1393 		else {
1394 			if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1395 #if defined(LWS_ROLE_H2)
1396 				if (!lws_hdr_total_length(wsi,
1397 						WSI_TOKEN_HTTP_COLON_AUTHORITY))
1398 #endif
1399 					goto bail_nuke_ah;
1400 #if defined(LWS_ROLE_H2)
1401 				n = lws_snprintf((char *)end, 256,
1402 				    "%s%s%s/", oprot[!!lws_is_ssl(wsi)],
1403 				    lws_hdr_simple_ptr(wsi,
1404 						WSI_TOKEN_HTTP_COLON_AUTHORITY),
1405 				    uri_ptr);
1406 #else
1407 				;
1408 #endif
1409 			} else
1410 				n = lws_snprintf((char *)end, 256,
1411 				    "%s%s%s/", oprot[!!lws_is_ssl(wsi)],
1412 				    lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
1413 				    uri_ptr);
1414 		}
1415 
1416 		lws_clean_url((char *)end);
1417 		n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
1418 				      end, n, &p, end);
1419 		if ((int)n < 0)
1420 			goto bail_nuke_ah;
1421 
1422 		return lws_http_transaction_completed(wsi);
1423 	}
1424 
1425 	return 0;
1426 
1427 bail_nuke_ah:
1428 	lws_header_table_detach(wsi, 1);
1429 
1430 	return 1;
1431 }
1432 
1433 int
lws_http_action(struct lws * wsi)1434 lws_http_action(struct lws *wsi)
1435 {
1436 	struct lws_context_per_thread *pt = &wsi->a.context->pt[(int)wsi->tsi];
1437 	int uri_len = 0, meth, m, http_version_len, ha;
1438 	const struct lws_http_mount *hit = NULL;
1439 	enum http_version request_version;
1440 	struct lws_process_html_args args;
1441 	enum http_conn_type conn_type;
1442 	char content_length_str[32];
1443 	char http_version_str[12];
1444 	char http_conn_str[25];
1445 	char *uri_ptr = NULL;
1446 #if defined(LWS_WITH_FILE_OPS)
1447 	char *s;
1448 #endif
1449 	unsigned int n;
1450 
1451 	meth = lws_http_get_uri_and_method(wsi, &uri_ptr, &uri_len);
1452 	if (meth < 0 || meth >= (int)LWS_ARRAY_SIZE(method_names))
1453 		goto bail_nuke_ah;
1454 
1455 	lws_metrics_tag_wsi_add(wsi, "vh", wsi->a.vhost->name);
1456 	lws_metrics_tag_wsi_add(wsi, "meth", method_names[meth]);
1457 
1458 	/* we insist on absolute paths */
1459 
1460 	if (!uri_ptr || uri_ptr[0] != '/') {
1461 		lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
1462 
1463 		goto bail_nuke_ah;
1464 	}
1465 
1466 	lwsl_info("Method: '%s' (%d), request for '%s'\n", method_names[meth],
1467 		  meth, uri_ptr);
1468 
1469 	if (wsi->role_ops &&
1470 	    lws_rops_fidx(wsi->role_ops, LWS_ROPS_check_upgrades))
1471 		switch (lws_rops_func_fidx(wsi->role_ops,
1472 					   LWS_ROPS_check_upgrades).
1473 							check_upgrades(wsi)) {
1474 		case LWS_UPG_RET_DONE:
1475 			return 0;
1476 		case LWS_UPG_RET_CONTINUE:
1477 			break;
1478 		case LWS_UPG_RET_BAIL:
1479 			goto bail_nuke_ah;
1480 		}
1481 
1482 	if (lws_ensure_user_space(wsi))
1483 		goto bail_nuke_ah;
1484 
1485 	/* HTTP header had a content length? */
1486 
1487 	wsi->http.rx_content_length = 0;
1488 	wsi->http.content_length_explicitly_zero = 0;
1489 	if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)
1490 #if defined(LWS_WITH_HTTP_UNCOMMON_HEADERS)
1491 			||
1492 	    lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
1493 	    lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI)
1494 #endif
1495 	    )
1496 		wsi->http.rx_content_length = 100 * 1024 * 1024;
1497 
1498 	if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH) &&
1499 	    lws_hdr_copy(wsi, content_length_str,
1500 			 sizeof(content_length_str) - 1,
1501 			 WSI_TOKEN_HTTP_CONTENT_LENGTH) > 0) {
1502 		wsi->http.rx_content_remain = wsi->http.rx_content_length =
1503 				(lws_filepos_t)atoll(content_length_str);
1504 		if (!wsi->http.rx_content_length) {
1505 			wsi->http.content_length_explicitly_zero = 1;
1506 			lwsl_debug("%s: explicit 0 content-length\n", __func__);
1507 		}
1508 	}
1509 
1510 	if (wsi->mux_substream) {
1511 		wsi->http.request_version = HTTP_VERSION_2;
1512 	} else {
1513 		/* http_version? Default to 1.0, override with token: */
1514 		request_version = HTTP_VERSION_1_0;
1515 
1516 		/* Works for single digit HTTP versions. : */
1517 		http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
1518 		if (http_version_len > 7 &&
1519 		    lws_hdr_copy(wsi, http_version_str,
1520 				 sizeof(http_version_str) - 1,
1521 				 WSI_TOKEN_HTTP) > 0 &&
1522 		    http_version_str[5] == '1' && http_version_str[7] == '1')
1523 			request_version = HTTP_VERSION_1_1;
1524 
1525 		wsi->http.request_version = request_version;
1526 
1527 		/* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
1528 		if (request_version == HTTP_VERSION_1_1)
1529 			conn_type = HTTP_CONNECTION_KEEP_ALIVE;
1530 		else
1531 			conn_type = HTTP_CONNECTION_CLOSE;
1532 
1533 		/* Override default if http "Connection:" header: */
1534 		if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION) &&
1535 		    lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
1536 				 WSI_TOKEN_CONNECTION) > 0) {
1537 			http_conn_str[sizeof(http_conn_str) - 1] = '\0';
1538 			if (!strcasecmp(http_conn_str, "keep-alive"))
1539 				conn_type = HTTP_CONNECTION_KEEP_ALIVE;
1540 			else
1541 				if (!strcasecmp(http_conn_str, "close"))
1542 					conn_type = HTTP_CONNECTION_CLOSE;
1543 		}
1544 		wsi->http.conn_type = conn_type;
1545 	}
1546 
1547 	n = (unsigned int)wsi->a.protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
1548 				    wsi->user_space, uri_ptr, (unsigned int)uri_len);
1549 	if (n) {
1550 		lwsl_info("LWS_CALLBACK_HTTP closing\n");
1551 
1552 		return 1;
1553 	}
1554 	/*
1555 	 * if there is content supposed to be coming,
1556 	 * put a timeout on it having arrived
1557 	 */
1558 	if (!wsi->mux_stream_immortal)
1559 		lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
1560 				(int)wsi->a.context->timeout_secs);
1561 #if defined(LWS_WITH_TLS)
1562 	if (wsi->tls.redirect_to_https) {
1563 		/*
1564 		 * We accepted http:// only so we could redirect to
1565 		 * https://, so issue the redirect.  Create the redirection
1566 		 * URI from the host: header, and regenerate the path part from
1567 		 * the parsed pieces
1568 		 */
1569 		unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
1570 			      *end = p + wsi->a.context->pt_serv_buf_size -
1571 				     LWS_PRE;
1572 
1573 		n = (unsigned int)lws_hdr_total_length(wsi, WSI_TOKEN_HOST);
1574 		if (!n || n > 128)
1575 			goto bail_nuke_ah;
1576 
1577 		if (!lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST))
1578 			goto bail_nuke_ah;
1579 
1580 		p += lws_snprintf((char *)p, lws_ptr_diff_size_t(end, p), "https://");
1581 		memcpy(p, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST), n);
1582 		p += n;
1583 		*p++ = '/';
1584 		if (uri_len >= lws_ptr_diff(end, p))
1585 			goto bail_nuke_ah;
1586 
1587 		if (uri_ptr[0])
1588 			p--;
1589 		memcpy(p, uri_ptr, (unsigned int)uri_len);
1590 		p += uri_len;
1591 
1592 		n = 0;
1593 		while (lws_hdr_copy_fragment(wsi, (char *)p + 1,
1594 					     lws_ptr_diff(end, p) - 2,
1595 					     WSI_TOKEN_HTTP_URI_ARGS, (int)n) > 0) {
1596 			*p = n ? '&' : '?';
1597 			p += strlen((char *)p);
1598 			if (p >= end - 2)
1599 				goto bail_nuke_ah;
1600 			n++;
1601 		}
1602 
1603 		n = (unsigned int)lws_ptr_diff(p, start);
1604 
1605 		p += LWS_PRE;
1606 		n = (unsigned int)lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
1607 				      start, (int)n, &p, end);
1608 		if ((int)n < 0)
1609 			goto bail_nuke_ah;
1610 
1611 		return lws_http_transaction_completed(wsi);
1612 	}
1613 #endif
1614 
1615 #ifdef LWS_WITH_ACCESS_LOG
1616 	lws_prepare_access_log_info(wsi, uri_ptr, uri_len, meth);
1617 #endif
1618 
1619 	/* can we serve it from the mount list? */
1620 
1621 	hit = lws_find_mount(wsi, uri_ptr, uri_len);
1622 	if (!hit) {
1623 		/* deferred cleanup and reset to protocols[0] */
1624 
1625 		lwsl_info("no hit\n");
1626 
1627 		if (lws_bind_protocol(wsi, &wsi->a.vhost->protocols[0],
1628 				      "no mount hit"))
1629 			return 1;
1630 
1631 		lwsi_set_state(wsi, LRS_DOING_TRANSACTION);
1632 
1633 		m = wsi->a.protocol->callback(wsi, LWS_CALLBACK_HTTP,
1634 				    wsi->user_space, uri_ptr, (unsigned int)uri_len);
1635 
1636 		goto after;
1637 	}
1638 
1639 #if defined(LWS_WITH_FILE_OPS)
1640 	s = uri_ptr + hit->mountpoint_len;
1641 #endif
1642 	n = (unsigned int)lws_http_redirect_hit(pt, wsi, hit, uri_ptr, uri_len, &ha);
1643 	if (ha)
1644 		return (int)n;
1645 
1646 #if defined(LWS_WITH_HTTP_BASIC_AUTH)
1647 
1648 	/* basic auth? */
1649 
1650 	switch (lws_check_basic_auth(wsi, hit->basic_auth_login_file,
1651 				     hit->auth_mask & AUTH_MODE_MASK)) {
1652 	case LCBA_CONTINUE:
1653 		break;
1654 	case LCBA_FAILED_AUTH:
1655 		return lws_unauthorised_basic_auth(wsi);
1656 	case LCBA_END_TRANSACTION:
1657 		lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
1658 		return lws_http_transaction_completed(wsi);
1659 	}
1660 #endif
1661 
1662 #if defined(LWS_WITH_HTTP_PROXY)
1663 	/*
1664 	 * The mount is a reverse proxy?
1665 	 */
1666 
1667 	// if (hit)
1668 	// lwsl_notice("%s: origin_protocol: %d\n", __func__, hit->origin_protocol);
1669 	//else
1670 	//	lwsl_notice("%s: no hit\n", __func__);
1671 
1672 	if (hit->origin_protocol == LWSMPRO_HTTPS ||
1673 	    hit->origin_protocol == LWSMPRO_HTTP) {
1674 		n = (unsigned int)lws_http_proxy_start(wsi, hit, uri_ptr, 0);
1675 		// lwsl_notice("proxy start says %d\n", n);
1676 		if (n)
1677 			return (int)n;
1678 
1679 		goto deal_body;
1680 	}
1681 #endif
1682 
1683 	/*
1684 	 * A particular protocol callback is mounted here?
1685 	 *
1686 	 * For the duration of this http transaction, bind us to the
1687 	 * associated protocol
1688 	 */
1689 	if (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {
1690 		const struct lws_protocols *pp;
1691 		const char *name = hit->origin;
1692 		if (hit->protocol)
1693 			name = hit->protocol;
1694 
1695 		pp = lws_vhost_name_to_protocol(wsi->a.vhost, name);
1696 		if (!pp) {
1697 			lwsl_err("Unable to find plugin '%s'\n",
1698 				 hit->origin);
1699 			return 1;
1700 		}
1701 
1702 		if (lws_bind_protocol(wsi, pp, "http action CALLBACK bind"))
1703 			return 1;
1704 
1705 		lwsl_debug("%s: %s, checking access rights for mask 0x%x\n",
1706 				__func__, hit->origin, hit->auth_mask);
1707 
1708 		args.p = uri_ptr;
1709 		args.len = uri_len;
1710 		args.max_len = hit->auth_mask & ~AUTH_MODE_MASK;
1711 		args.final = 0; /* used to signal callback dealt with it */
1712 		args.chunked = 0;
1713 
1714 		n = (unsigned int)wsi->a.protocol->callback(wsi,
1715 					    LWS_CALLBACK_CHECK_ACCESS_RIGHTS,
1716 					    wsi->user_space, &args, 0);
1717 		if (n) {
1718 			lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,
1719 					       NULL);
1720 			goto bail_nuke_ah;
1721 		}
1722 		if (args.final) /* callback completely handled it well */
1723 			return 0;
1724 
1725 		if (hit->cgienv && wsi->a.protocol->callback(wsi,
1726 				LWS_CALLBACK_HTTP_PMO,
1727 				wsi->user_space, (void *)hit->cgienv, 0))
1728 			return 1;
1729 
1730 		if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
1731 			m = wsi->a.protocol->callback(wsi, LWS_CALLBACK_HTTP,
1732 					    wsi->user_space,
1733 					    uri_ptr + hit->mountpoint_len,
1734 					    (unsigned int)uri_len - hit->mountpoint_len);
1735 			goto after;
1736 		}
1737 	}
1738 
1739 #ifdef LWS_WITH_CGI
1740 	/* did we hit something with a cgi:// origin? */
1741 	if (hit->origin_protocol == LWSMPRO_CGI) {
1742 		const char *cmd[] = {
1743 			NULL, /* replace with cgi path */
1744 			NULL
1745 		};
1746 
1747 		lwsl_debug("%s: cgi\n", __func__);
1748 		cmd[0] = hit->origin;
1749 
1750 		n = 5;
1751 		if (hit->cgi_timeout)
1752 			n = (unsigned int)hit->cgi_timeout;
1753 
1754 		n = (unsigned int)lws_cgi(wsi, cmd, hit->mountpoint_len, (int)n,
1755 			    hit->cgienv);
1756 		if (n) {
1757 			lwsl_err("%s: cgi failed\n", __func__);
1758 			return -1;
1759 		}
1760 
1761 		goto deal_body;
1762 	}
1763 #endif
1764 
1765 #if defined(LWS_WITH_FILE_OPS)
1766 	n = (unsigned int)(uri_len - lws_ptr_diff(s, uri_ptr));
1767 	if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
1768 		s = (char *)hit->def;
1769 	if (!s)
1770 		s = "index.html";
1771 #endif
1772 
1773 	wsi->cache_secs = (unsigned int)hit->cache_max_age;
1774 	wsi->cache_reuse = hit->cache_reusable;
1775 	wsi->cache_revalidate = hit->cache_revalidate;
1776 	wsi->cache_intermediaries = hit->cache_intermediaries;
1777 
1778 #if defined(LWS_WITH_FILE_OPS)
1779 	m = 1;
1780 	if (hit->origin_protocol == LWSMPRO_FILE)
1781 		m = lws_http_serve(wsi, s, hit->origin, hit);
1782 
1783 	if (m > 0)
1784 #endif
1785 	{
1786 		/*
1787 		 * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1788 		 */
1789 		if (hit->protocol) {
1790 			const struct lws_protocols *pp =
1791 					lws_vhost_name_to_protocol(
1792 						wsi->a.vhost, hit->protocol);
1793 
1794 			/* coverity */
1795 			if (!pp)
1796 				return 1;
1797 
1798 			lwsi_set_state(wsi, LRS_DOING_TRANSACTION);
1799 
1800 			if (lws_bind_protocol(wsi, pp, "http_action HTTP"))
1801 				return 1;
1802 
1803 			m = pp->callback(wsi, LWS_CALLBACK_HTTP,
1804 					 wsi->user_space,
1805 					 uri_ptr + hit->mountpoint_len,
1806 					 (size_t)(uri_len - hit->mountpoint_len));
1807 		} else
1808 			m = wsi->a.protocol->callback(wsi, LWS_CALLBACK_HTTP,
1809 				    wsi->user_space, uri_ptr, (size_t)uri_len);
1810 	}
1811 
1812 after:
1813 	if (m) {
1814 		lwsl_info("LWS_CALLBACK_HTTP closing\n");
1815 
1816 		return 1;
1817 	}
1818 
1819 #if defined(LWS_WITH_CGI) || defined(LWS_WITH_HTTP_PROXY)
1820 deal_body:
1821 #endif
1822 	/*
1823 	 * If we're not issuing a file, check for content_length or
1824 	 * HTTP keep-alive. No keep-alive header allocation for
1825 	 * ISSUING_FILE, as this uses HTTP/1.0.
1826 	 *
1827 	 * In any case, return 0 and let lws_read decide how to
1828 	 * proceed based on state
1829 	 */
1830 	if (lwsi_state(wsi) == LRS_ISSUING_FILE)
1831 		return 0;
1832 
1833 	/* Prepare to read body if we have a content length: */
1834 	lwsl_debug("wsi->http.rx_content_length %lld %d %d\n",
1835 		   (long long)wsi->http.rx_content_length,
1836 		   wsi->upgraded_to_http2, wsi->mux_substream);
1837 
1838 	if (wsi->http.content_length_explicitly_zero &&
1839 	    lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
1840 
1841 		/*
1842 		 * POST with an explicit content-length of zero
1843 		 *
1844 		 * If we don't give the user code the empty HTTP_BODY callback,
1845 		 * he may become confused to hear the HTTP_BODY_COMPLETION (due
1846 		 * to, eg, instantiation of lws_spa never happened).
1847 		 *
1848 		 * HTTP_BODY_COMPLETION is responsible for sending the result
1849 		 * status code and result body if any, and to do the transaction
1850 		 * complete processing.
1851 		 */
1852 		if (wsi->a.protocol->callback(wsi, LWS_CALLBACK_HTTP_BODY,
1853 					    wsi->user_space, NULL, 0))
1854 			return 1;
1855 		if (wsi->a.protocol->callback(wsi, LWS_CALLBACK_HTTP_BODY_COMPLETION,
1856 					    wsi->user_space, NULL, 0))
1857 			return 1;
1858 
1859 		return 0;
1860 	}
1861 
1862 	if (wsi->http.rx_content_length <= 0)
1863 		return 0;
1864 
1865 	if (lwsi_state(wsi) != LRS_DISCARD_BODY) {
1866 		lwsi_set_state(wsi, LRS_BODY);
1867 		lwsl_info("%s: %s: LRS_BODY state set (0x%x)\n", __func__,
1868 			  lws_wsi_tag(wsi), (int)wsi->wsistate);
1869 	}
1870 	wsi->http.rx_content_remain = wsi->http.rx_content_length;
1871 
1872 	/*
1873 	 * At this point we have transitioned from deferred
1874 	 * action to expecting BODY on the stream wsi, if it's
1875 	 * in a bundle like h2.  So if the stream wsi has its
1876 	 * own buflist, we need to deal with that first.
1877 	 */
1878 
1879 	while (1) {
1880 		struct lws_tokens ebuf;
1881 		int m;
1882 
1883 		ebuf.len = (int)lws_buflist_next_segment_len(&wsi->buflist,
1884 							     &ebuf.token);
1885 		if (!ebuf.len)
1886 			break;
1887 
1888 		lwsl_debug("%s: consuming %d\n", __func__, (int)ebuf.len);
1889 		m = lws_read_h1(wsi, ebuf.token, (lws_filepos_t)ebuf.len);
1890 		if (m < 0)
1891 			return -1;
1892 
1893 		if (lws_buflist_aware_finished_consuming(wsi, &ebuf, m, 1,
1894 							 __func__))
1895 			return -1;
1896 	}
1897 
1898 	return 0;
1899 
1900 bail_nuke_ah:
1901 	lws_header_table_detach(wsi, 1);
1902 
1903 	return 1;
1904 }
1905 
1906 int
lws_confirm_host_header(struct lws * wsi)1907 lws_confirm_host_header(struct lws *wsi)
1908 {
1909 	struct lws_tokenize ts;
1910 	lws_tokenize_elem e;
1911 	int port = 80, n;
1912 	char buf[128];
1913 
1914 	/*
1915 	 * this vhost wants us to validate what the
1916 	 * client sent against our vhost name
1917 	 */
1918 
1919 	if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1920 		lwsl_info("%s: missing host on upgrade\n", __func__);
1921 
1922 		return 1;
1923 	}
1924 
1925 #if defined(LWS_WITH_TLS)
1926 	if (wsi->tls.ssl)
1927 		port = 443;
1928 #endif
1929 
1930 	lws_tokenize_init(&ts, buf, LWS_TOKENIZE_F_DOT_NONTERM /* server.com */|
1931 				    LWS_TOKENIZE_F_NO_FLOATS /* 1.server.com */|
1932 				    LWS_TOKENIZE_F_MINUS_NONTERM /* a-b.com */);
1933 	n = lws_hdr_copy(wsi, buf, sizeof(buf) - 1, WSI_TOKEN_HOST);
1934 	if (n <= 0) {
1935 		lwsl_info("%s: missing or oversize host header\n", __func__);
1936 		return 1;
1937 	}
1938 	ts.len = (size_t)n;
1939 
1940 	if (lws_tokenize(&ts) != LWS_TOKZE_TOKEN)
1941 		goto bad_format;
1942 
1943 	if (strncmp(ts.token, wsi->a.vhost->name, ts.token_len)) {
1944 		buf[(size_t)(ts.token - buf) + ts.token_len] = '\0';
1945 		lwsl_info("%s: '%s' in host hdr but vhost name %s\n",
1946 			  __func__, ts.token, wsi->a.vhost->name);
1947 		return 1;
1948 	}
1949 
1950 	e = lws_tokenize(&ts);
1951 	if (e == LWS_TOKZE_DELIMITER && ts.token[0] == ':') {
1952 		if (lws_tokenize(&ts) != LWS_TOKZE_INTEGER)
1953 			goto bad_format;
1954 		else
1955 			port = atoi(ts.token);
1956 	} else
1957 		if (e != LWS_TOKZE_ENDED)
1958 			goto bad_format;
1959 
1960 	if (wsi->a.vhost->listen_port != port) {
1961 		lwsl_info("%s: host port %d mismatches vhost port %d\n",
1962 			  __func__, port, wsi->a.vhost->listen_port);
1963 		return 1;
1964 	}
1965 
1966 	lwsl_debug("%s: host header OK\n", __func__);
1967 
1968 	return 0;
1969 
1970 bad_format:
1971 	lwsl_info("%s: bad host header format\n", __func__);
1972 
1973 	return 1;
1974 }
1975 
1976 #if defined(LWS_WITH_SERVER)
1977 int
lws_http_to_fallback(struct lws * wsi,unsigned char * obuf,size_t olen)1978 lws_http_to_fallback(struct lws *wsi, unsigned char *obuf, size_t olen)
1979 {
1980 	const struct lws_role_ops *role = &role_ops_raw_skt;
1981 	const struct lws_protocols *p1, *protocol =
1982 			 &wsi->a.vhost->protocols[wsi->a.vhost->raw_protocol_index];
1983 	char ipbuf[64];
1984 	int n;
1985 
1986 	if (wsi->a.vhost->listen_accept_role &&
1987 	    lws_role_by_name(wsi->a.vhost->listen_accept_role))
1988 		role = lws_role_by_name(wsi->a.vhost->listen_accept_role);
1989 
1990 	if (wsi->a.vhost->listen_accept_protocol) {
1991 		p1 = lws_vhost_name_to_protocol(wsi->a.vhost,
1992 			    wsi->a.vhost->listen_accept_protocol);
1993 		if (p1)
1994 			protocol = p1;
1995 	}
1996 
1997 	lws_bind_protocol(wsi, protocol, __func__);
1998 
1999 	lws_role_transition(wsi, LWSIFR_SERVER, LRS_ESTABLISHED, role);
2000 
2001 	lws_header_table_detach(wsi, 0);
2002 	lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
2003 
2004 	n = LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED;
2005 	if (wsi->role_ops->adoption_cb[1])
2006 		n = wsi->role_ops->adoption_cb[1];
2007 
2008 	ipbuf[0] = '\0';
2009 #if !defined(LWS_PLAT_OPTEE)
2010 	lws_get_peer_simple(wsi, ipbuf, sizeof(ipbuf));
2011 #endif
2012 
2013 	lwsl_notice("%s: vh %s, peer: %s, role %s, "
2014 		    "protocol %s, cb %d, ah %p\n", __func__, wsi->a.vhost->name,
2015 		    ipbuf, role ? role->name : "null", protocol->name, n,
2016 		    wsi->http.ah);
2017 
2018 	if ((wsi->a.protocol->callback)(wsi, (enum lws_callback_reasons)n, wsi->user_space, NULL, 0))
2019 		return 1;
2020 
2021 	n = LWS_CALLBACK_RAW_RX;
2022 	if (wsi->role_ops->rx_cb[lwsi_role_server(wsi)])
2023 		n = wsi->role_ops->rx_cb[lwsi_role_server(wsi)];
2024 	if (wsi->a.protocol->callback(wsi, (enum lws_callback_reasons)n, wsi->user_space, obuf, olen))
2025 		return 1;
2026 
2027 	return 0;
2028 }
2029 
2030 int
lws_handshake_server(struct lws * wsi,unsigned char ** buf,size_t len)2031 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
2032 {
2033 	struct lws_context *context = lws_get_context(wsi);
2034 	struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2035 #if defined(LWS_WITH_HTTP2)
2036 	struct allocated_headers *ah;
2037 #endif
2038 	unsigned char *obuf = *buf;
2039 #if defined(LWS_WITH_HTTP2)
2040 	char tbuf[128], *p;
2041 #endif
2042 	size_t olen = len;
2043 	int n = 0, m, i;
2044 
2045 	if (len >= 10000000) {
2046 		lwsl_err("%s: assert: len %ld\n", __func__, (long)len);
2047 		assert(0);
2048 	}
2049 
2050 	if (!wsi->http.ah) {
2051 		lwsl_err("%s: assert: NULL ah\n", __func__);
2052 		assert(0);
2053 	}
2054 
2055 	while (len) {
2056 		if (!lwsi_role_server(wsi) || !lwsi_role_http(wsi)) {
2057 			lwsl_err("%s: bad wsi role 0x%x\n", __func__,
2058 					(int)lwsi_role(wsi));
2059 			goto bail_nuke_ah;
2060 		}
2061 
2062 		i = (int)len;
2063 		m = lws_parse(wsi, *buf, &i);
2064 		lwsl_info("%s: parsed count %d\n", __func__, (int)len - i);
2065 		(*buf) += (int)len - i;
2066 		len = (unsigned int)i;
2067 
2068 		if (m == LPR_DO_FALLBACK) {
2069 
2070 			/*
2071 			 * http parser went off the rails and
2072 			 * LWS_SERVER_OPTION_FALLBACK_TO_APPLY_LISTEN_
2073 			 * ACCEPT_CONFIG is set on this vhost.
2074 			 *
2075 			 * We are transitioning from http with an AH, to
2076 			 * a backup role (raw-skt, by default).  Drop
2077 			 * the ah, bind to the role with mode as
2078 			 * ESTABLISHED.
2079 			 */
2080 raw_transition:
2081 
2082 			if (lws_http_to_fallback(wsi, obuf, olen)) {
2083 				lwsl_info("%s: fallback -> close\n", __func__);
2084 				goto bail_nuke_ah;
2085 			}
2086 
2087 			(*buf) = obuf + olen;
2088 
2089 			return 0;
2090 		}
2091 		if (m) {
2092 			lwsl_info("lws_parse failed\n");
2093 			goto bail_nuke_ah;
2094 		}
2095 
2096 		/* coverity... */
2097 		if (!wsi->http.ah)
2098 			goto bail_nuke_ah;
2099 
2100 		if (wsi->http.ah->parser_state != WSI_PARSING_COMPLETE)
2101 			continue;
2102 
2103 		lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
2104 
2105 		/* select vhost */
2106 
2107 		if (wsi->a.vhost->listen_port &&
2108 		    lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
2109 			struct lws_vhost *vhost = lws_select_vhost(
2110 				context, wsi->a.vhost->listen_port,
2111 				lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
2112 
2113 			if (vhost)
2114 				lws_vhost_bind_wsi(vhost, wsi);
2115 		} else
2116 			lwsl_info("no host\n");
2117 
2118 		if ((!lwsi_role_h2(wsi) || !lwsi_role_server(wsi)) &&
2119 		    (!wsi->conn_stat_done))
2120 			wsi->conn_stat_done = 1;
2121 
2122 		/* check for unwelcome guests */
2123 #if defined(LWS_WITH_HTTP_UNCOMMON_HEADERS)
2124 		if (wsi->a.context->reject_service_keywords) {
2125 			const struct lws_protocol_vhost_options *rej =
2126 					wsi->a.context->reject_service_keywords;
2127 			char ua[384], *msg = NULL;
2128 
2129 			if (lws_hdr_copy(wsi, ua, sizeof(ua) - 1,
2130 					 WSI_TOKEN_HTTP_USER_AGENT) > 0) {
2131 #ifdef LWS_WITH_ACCESS_LOG
2132 				char *uri_ptr = NULL;
2133 				int meth, uri_len;
2134 #endif
2135 				ua[sizeof(ua) - 1] = '\0';
2136 				while (rej) {
2137 					if (!strstr(ua, rej->name)) {
2138 						rej = rej->next;
2139 						continue;
2140 					}
2141 
2142 					msg = strchr(rej->value, ' ');
2143 					if (msg)
2144 						msg++;
2145 					lws_return_http_status(wsi,
2146 						(unsigned int)atoi(rej->value), msg);
2147 #ifdef LWS_WITH_ACCESS_LOG
2148 					meth = lws_http_get_uri_and_method(wsi,
2149 							&uri_ptr, &uri_len);
2150 					if (meth >= 0)
2151 						lws_prepare_access_log_info(wsi,
2152 							uri_ptr, uri_len, meth);
2153 
2154 					/* wsi close will do the log */
2155 #endif
2156 					/*
2157 					 * We don't want anything from
2158 					 * this rejected guy.  Follow
2159 					 * the close flow, not the
2160 					 * transaction complete flow.
2161 					 */
2162 					goto bail_nuke_ah;
2163 				}
2164 			}
2165 		}
2166 #endif
2167 		/*
2168 		 * So he may have come to us requesting one or another kind
2169 		 * of upgrade from http... but we may want to redirect him at
2170 		 * http level.  In that case, we need to check the redirect
2171 		 * situation even though he's not actually wanting http and
2172 		 * prioritize returning that if there is one.
2173 		 */
2174 
2175 		{
2176 			const struct lws_http_mount *hit = NULL;
2177 			int uri_len = 0, ha, n;
2178 			char *uri_ptr = NULL;
2179 
2180 			n = lws_http_get_uri_and_method(wsi, &uri_ptr, &uri_len);
2181 			if (n >= 0) {
2182 				hit = lws_find_mount(wsi, uri_ptr, uri_len);
2183 				if (hit) {
2184 					n = lws_http_redirect_hit(pt, wsi, hit, uri_ptr,
2185 								  uri_len, &ha);
2186 					if (ha)
2187 						return n;
2188 				}
2189 			}
2190 		}
2191 
2192 
2193 
2194 		if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECT)) {
2195 			lwsl_info("Changing to RAW mode\n");
2196 			goto raw_transition;
2197 		}
2198 
2199 		lwsi_set_state(wsi, LRS_PRE_WS_SERVING_ACCEPT);
2200 		lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
2201 
2202 		if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
2203 
2204 			const char *up = lws_hdr_simple_ptr(wsi,
2205 							    WSI_TOKEN_UPGRADE);
2206 
2207 			if (strcasecmp(up, "websocket") &&
2208 			    strcasecmp(up, "h2c")) {
2209 				lwsl_info("Unknown upgrade '%s'\n", up);
2210 
2211 				if (lws_return_http_status(wsi,
2212 						HTTP_STATUS_FORBIDDEN, NULL) ||
2213 				    lws_http_transaction_completed(wsi))
2214 					goto bail_nuke_ah;
2215 			}
2216 
2217 			n = user_callback_handle_rxflow(wsi->a.protocol->callback,
2218 					wsi, LWS_CALLBACK_HTTP_CONFIRM_UPGRADE,
2219 					wsi->user_space, (char *)up, 0);
2220 
2221 			/* just hang up? */
2222 
2223 			if (n < 0)
2224 				goto bail_nuke_ah;
2225 
2226 			/* callback returned headers already, do t_c? */
2227 
2228 			if (n > 0) {
2229 				if (lws_http_transaction_completed(wsi))
2230 					goto bail_nuke_ah;
2231 
2232 				/* continue on */
2233 
2234 				return 0;
2235 			}
2236 
2237 			/* callback said 0, it was allowed */
2238 
2239 			if (wsi->a.vhost->options &
2240 			    LWS_SERVER_OPTION_VHOST_UPG_STRICT_HOST_CHECK &&
2241 			    lws_confirm_host_header(wsi))
2242 				goto bail_nuke_ah;
2243 
2244 			if (!strcasecmp(up, "websocket")) {
2245 #if defined(LWS_ROLE_WS)
2246 				lws_metrics_tag_wsi_add(wsi, "upg", "ws");
2247 				lwsl_info("Upgrade to ws\n");
2248 				goto upgrade_ws;
2249 #endif
2250 			}
2251 #if defined(LWS_WITH_HTTP2)
2252 			if (!strcasecmp(up, "h2c")) {
2253 				lws_metrics_tag_wsi_add(wsi, "upg", "h2c");
2254 				lwsl_info("Upgrade to h2c\n");
2255 				goto upgrade_h2c;
2256 			}
2257 #endif
2258 		}
2259 
2260 		/* no upgrade ack... he remained as HTTP */
2261 
2262 		lwsl_info("%s: %s: No upgrade\n", __func__, lws_wsi_tag(wsi));
2263 
2264 		lwsi_set_state(wsi, LRS_ESTABLISHED);
2265 #if defined(LWS_WITH_FILE_OPS)
2266 		wsi->http.fop_fd = NULL;
2267 #endif
2268 
2269 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
2270 		lws_http_compression_validate(wsi);
2271 #endif
2272 
2273 		lwsl_debug("%s: %s: ah %p\n", __func__, lws_wsi_tag(wsi),
2274 			   (void *)wsi->http.ah);
2275 
2276 		n = lws_http_action(wsi);
2277 
2278 		return n;
2279 
2280 #if defined(LWS_WITH_HTTP2)
2281 upgrade_h2c:
2282 		if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
2283 			lwsl_info("missing http2_settings\n");
2284 			goto bail_nuke_ah;
2285 		}
2286 
2287 		lwsl_info("h2c upgrade...\n");
2288 
2289 		p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
2290 		/* convert the peer's HTTP-Settings */
2291 		n = lws_b64_decode_string(p, tbuf, sizeof(tbuf));
2292 		if (n < 0) {
2293 			lwsl_parser("HTTP2_SETTINGS too long\n");
2294 			return 1;
2295 		}
2296 
2297 		wsi->upgraded_to_http2 = 1;
2298 
2299 		/* adopt the header info */
2300 
2301 		ah = wsi->http.ah;
2302 		lws_role_transition(wsi, LWSIFR_SERVER, LRS_H2_AWAIT_PREFACE,
2303 				    &role_ops_h2);
2304 
2305 		/* http2 union member has http union struct at start */
2306 		wsi->http.ah = ah;
2307 
2308 		if (!wsi->h2.h2n) {
2309 			wsi->h2.h2n = lws_zalloc(sizeof(*wsi->h2.h2n), "h2n");
2310 			if (!wsi->h2.h2n)
2311 				return 1;
2312 		}
2313 
2314 		lws_h2_init(wsi);
2315 
2316 		/* HTTP2 union */
2317 
2318 		lws_h2_settings(wsi, &wsi->h2.h2n->peer_set, (uint8_t *)tbuf, n);
2319 
2320 		lws_hpack_dynamic_size(wsi, (int)wsi->h2.h2n->peer_set.s[
2321 		                                      H2SET_HEADER_TABLE_SIZE]);
2322 
2323 		strcpy(tbuf, "HTTP/1.1 101 Switching Protocols\x0d\x0a"
2324 			      "Connection: Upgrade\x0d\x0a"
2325 			      "Upgrade: h2c\x0d\x0a\x0d\x0a");
2326 		m = (int)strlen(tbuf);
2327 		n = lws_issue_raw(wsi, (unsigned char *)tbuf, (unsigned int)m);
2328 		if (n != m) {
2329 			lwsl_debug("http2 switch: ERROR writing to socket\n");
2330 			return 1;
2331 		}
2332 
2333 		return 0;
2334 #endif
2335 #if defined(LWS_ROLE_WS)
2336 upgrade_ws:
2337 		if (lws_process_ws_upgrade(wsi))
2338 			goto bail_nuke_ah;
2339 
2340 		return 0;
2341 #endif
2342 	} /* while all chars are handled */
2343 
2344 	return 0;
2345 
2346 bail_nuke_ah:
2347 	/* drop the header info */
2348 	lws_header_table_detach(wsi, 1);
2349 
2350 	return 1;
2351 }
2352 #endif
2353 
2354 int LWS_WARN_UNUSED_RESULT
lws_http_transaction_completed(struct lws * wsi)2355 lws_http_transaction_completed(struct lws *wsi)
2356 {
2357 	int n;
2358 
2359 	if (wsi->http.cgi_transaction_complete)
2360 		return 0;
2361 
2362 	if (lws_has_buffered_out(wsi)
2363 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
2364 			|| wsi->http.comp_ctx.buflist_comp ||
2365 	    wsi->http.comp_ctx.may_have_more
2366 #endif
2367 	) {
2368 		/*
2369 		 * ...so he tried to send something large as the http reply,
2370 		 * it went as a partial, but he immediately said the
2371 		 * transaction was completed.
2372 		 *
2373 		 * Defer the transaction completed until the last part of the
2374 		 * partial is sent.
2375 		 */
2376 		lwsl_debug("%s: %s: deferring due to partial\n", __func__,
2377 				lws_wsi_tag(wsi));
2378 		wsi->http.deferred_transaction_completed = 1;
2379 		lws_callback_on_writable(wsi);
2380 
2381 		return 0;
2382 	}
2383 	/*
2384 	 * Are we finishing the transaction before we have consumed any body?
2385 	 *
2386 	 * For h1 this would kill keepalive pipelining, and for h2, considering
2387 	 * it can extend over multiple DATA frames, it would kill the network
2388 	 * connection.
2389 	 */
2390 	if (wsi->http.rx_content_length && wsi->http.rx_content_remain) {
2391 		/*
2392 		 * are we already in LRS_DISCARD_BODY and didn't clear the
2393 		 * remaining before trying to complete the transaction again?
2394 		 */
2395 		if (lwsi_state(wsi) == LRS_DISCARD_BODY)
2396 			return -1;
2397 		/*
2398 		 * let's defer transaction completed processing until we
2399 		 * discarded the remaining body
2400 		 */
2401 		lwsi_set_state(wsi, LRS_DISCARD_BODY);
2402 
2403 		return 0;
2404 	}
2405 
2406 #if defined(LWS_WITH_SYS_METRICS)
2407 	{
2408 		char tmp[10];
2409 
2410 		lws_snprintf(tmp, sizeof(tmp), "%u", wsi->http.response_code);
2411 		lws_metrics_tag_wsi_add(wsi, "status", tmp);
2412 	}
2413 #endif
2414 
2415 	lwsl_info("%s: %s\n", __func__, lws_wsi_tag(wsi));
2416 
2417 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
2418 	lws_http_compression_destroy(wsi);
2419 #endif
2420 	lws_access_log(wsi);
2421 
2422 	if (!wsi->hdr_parsing_completed
2423 #if defined(LWS_WITH_CGI)
2424 			&& !wsi->http.cgi
2425 #endif
2426 	) {
2427 		char peer[64];
2428 
2429 #if !defined(LWS_PLAT_OPTEE)
2430 		lws_get_peer_simple(wsi, peer, sizeof(peer) - 1);
2431 #else
2432 		peer[0] = '\0';
2433 #endif
2434 		peer[sizeof(peer) - 1] = '\0';
2435 		lwsl_info("%s: (from %s) ignoring, ah parsing incomplete\n",
2436 				__func__, peer);
2437 		return 0;
2438 	}
2439 
2440 #if defined(LWS_WITH_CGI)
2441 	if (wsi->http.cgi) {
2442 		lwsl_debug("%s: cleaning cgi\n", __func__);
2443 		wsi->http.cgi_transaction_complete = 1;
2444 		lws_cgi_remove_and_kill(wsi);
2445 		lws_spawn_piped_destroy(&wsi->http.cgi->lsp);
2446 		lws_sul_cancel(&wsi->http.cgi->sul_grace);
2447 
2448 		lws_free_set_NULL(wsi->http.cgi);
2449 		wsi->http.cgi_transaction_complete = 0;
2450 	}
2451 #endif
2452 
2453 	/* if we can't go back to accept new headers, drop the connection */
2454 	if (wsi->mux_substream)
2455 		return 1;
2456 
2457 	if (wsi->seen_zero_length_recv)
2458 		return 1;
2459 
2460 	if (wsi->http.conn_type != HTTP_CONNECTION_KEEP_ALIVE) {
2461 		lwsl_info("%s: %s: close connection\n", __func__, lws_wsi_tag(wsi));
2462 		return 1;
2463 	}
2464 
2465 	if (lws_bind_protocol(wsi, &wsi->a.vhost->protocols[0], __func__))
2466 		return 1;
2467 
2468 	/*
2469 	 * otherwise set ourselves up ready to go again, but because we have no
2470 	 * idea about the wsi writability, we make put it in a holding state
2471 	 * until we can verify POLLOUT.  The part of this that confirms POLLOUT
2472 	 * with no partials is in lws_server_socket_service() below.
2473 	 */
2474 	lwsl_debug("%s: %s: setting DEF_ACT from 0x%x: %p\n", __func__,
2475 		   lws_wsi_tag(wsi), (int)wsi->wsistate, wsi->buflist);
2476 	lwsi_set_state(wsi, LRS_DEFERRING_ACTION);
2477 	wsi->http.tx_content_length = 0;
2478 	wsi->http.tx_content_remain = 0;
2479 	wsi->hdr_parsing_completed = 0;
2480 	wsi->sending_chunked = 0;
2481 #ifdef LWS_WITH_ACCESS_LOG
2482 	wsi->http.access_log.sent = 0;
2483 #endif
2484 #if defined(LWS_WITH_FILE_OPS) && (defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2))
2485 	if (lwsi_role_http(wsi) && lwsi_role_server(wsi) &&
2486 	    wsi->http.fop_fd != NULL)
2487 		lws_vfs_file_close(&wsi->http.fop_fd);
2488 #endif
2489 
2490 	n = NO_PENDING_TIMEOUT;
2491 	if (wsi->a.vhost->keepalive_timeout)
2492 		n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
2493 	lws_set_timeout(wsi, (enum pending_timeout)n, wsi->a.vhost->keepalive_timeout);
2494 
2495 	/*
2496 	 * We already know we are on http1.1 / keepalive and the next thing
2497 	 * coming will be another header set.
2498 	 *
2499 	 * If there is no pending rx and we still have the ah, drop it and
2500 	 * reacquire a new ah when the new headers start to arrive.  (Otherwise
2501 	 * we needlessly hog an ah indefinitely.)
2502 	 *
2503 	 * However if there is pending rx and we know from the keepalive state
2504 	 * that is already at least the start of another header set, simply
2505 	 * reset the existing header table and keep it.
2506 	 */
2507 	if (wsi->http.ah) {
2508 		// lws_buflist_describe(&wsi->buflist, wsi, __func__);
2509 		if (!lws_buflist_next_segment_len(&wsi->buflist, NULL)) {
2510 			lwsl_debug("%s: %s: nothing in buflist, detaching ah\n",
2511 				  __func__, lws_wsi_tag(wsi));
2512 			lws_header_table_detach(wsi, 1);
2513 #ifdef LWS_WITH_TLS
2514 			/*
2515 			 * additionally... if we are hogging an SSL instance
2516 			 * with no pending pipelined headers (or ah now), and
2517 			 * SSL is scarce, drop this connection without waiting
2518 			 */
2519 
2520 			if (wsi->a.vhost->tls.use_ssl &&
2521 			    wsi->a.context->simultaneous_ssl_restriction &&
2522 			    wsi->a.context->simultaneous_ssl ==
2523 				   wsi->a.context->simultaneous_ssl_restriction) {
2524 				lwsl_info("%s: simultaneous_ssl_restriction\n",
2525 					  __func__);
2526 				return 1;
2527 			}
2528 #endif
2529 		} else {
2530 			lwsl_info("%s: %s: resetting/keeping ah as pipeline\n",
2531 				  __func__, lws_wsi_tag(wsi));
2532 			lws_header_table_reset(wsi, 0);
2533 			/*
2534 			 * If we kept the ah, we should restrict the amount
2535 			 * of time we are willing to keep it.  Otherwise it
2536 			 * will be bound the whole time the connection remains
2537 			 * open.
2538 			 */
2539 			lws_set_timeout(wsi, PENDING_TIMEOUT_HOLDING_AH,
2540 					wsi->a.vhost->keepalive_timeout);
2541 		}
2542 		/* If we're (re)starting on headers, need other implied init */
2543 		if (wsi->http.ah)
2544 			wsi->http.ah->ues = URIES_IDLE;
2545 
2546 		//lwsi_set_state(wsi, LRS_ESTABLISHED); // !!!
2547 	} else
2548 		if (lws_buflist_next_segment_len(&wsi->buflist, NULL))
2549 			if (lws_header_table_attach(wsi, 0))
2550 				lwsl_debug("acquired ah\n");
2551 
2552 	lwsl_debug("%s: %s: keep-alive await new transaction (state 0x%x)\n",
2553 		   __func__, lws_wsi_tag(wsi), (int)wsi->wsistate);
2554 	lws_callback_on_writable(wsi);
2555 
2556 	return 0;
2557 }
2558 
2559 #if defined(LWS_WITH_FILE_OPS)
2560 int
lws_serve_http_file(struct lws * wsi,const char * file,const char * content_type,const char * other_headers,int other_headers_len)2561 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2562 		    const char *other_headers, int other_headers_len)
2563 {
2564 	struct lws_context *context = lws_get_context(wsi);
2565 	struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2566 	unsigned char *response = pt->serv_buf + LWS_PRE;
2567 #if defined(LWS_WITH_RANGES)
2568 	struct lws_range_parsing *rp = &wsi->http.range;
2569 #endif
2570 	int ret = 0, cclen = 8, n = HTTP_STATUS_OK;
2571 	char cache_control[50], *cc = "no-store";
2572 	lws_fop_flags_t fflags = LWS_O_RDONLY;
2573 	const struct lws_plat_file_ops *fops;
2574 	lws_filepos_t total_content_length;
2575 	unsigned char *p = response;
2576 	unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;
2577 	const char *vpath;
2578 #if defined(LWS_WITH_RANGES)
2579 	int ranges;
2580 #endif
2581 
2582 	if (wsi->handling_404)
2583 		n = HTTP_STATUS_NOT_FOUND;
2584 
2585 	/*
2586 	 * We either call the platform fops .open with first arg platform fops,
2587 	 * or we call fops_zip .open with first arg platform fops, and fops_zip
2588 	 * open will decide whether to switch to fops_zip or stay with fops_def.
2589 	 *
2590 	 * If wsi->http.fop_fd is already set, the caller already opened it
2591 	 */
2592 	if (!wsi->http.fop_fd) {
2593 		fops = lws_vfs_select_fops(wsi->a.context->fops, file, &vpath);
2594 		fflags |= lws_vfs_prepare_flags(wsi);
2595 		wsi->http.fop_fd = fops->LWS_FOP_OPEN(wsi->a.context->fops,
2596 							file, vpath, &fflags);
2597 		if (!wsi->http.fop_fd) {
2598 			lwsl_info("%s: Unable to open: '%s': errno %d\n",
2599 				  __func__, file, errno);
2600 			if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND,
2601 						   NULL))
2602 						return -1;
2603 			return !wsi->mux_substream;
2604 		}
2605 	}
2606 
2607 	/*
2608 	 * Caution... wsi->http.fop_fd is live from here
2609 	 */
2610 
2611 	wsi->http.filelen = lws_vfs_get_length(wsi->http.fop_fd);
2612 	total_content_length = wsi->http.filelen;
2613 
2614 #if defined(LWS_WITH_RANGES)
2615 	ranges = lws_ranges_init(wsi, rp, wsi->http.filelen);
2616 
2617 	lwsl_debug("Range count %d\n", ranges);
2618 	/*
2619 	 * no ranges -> 200;
2620 	 *  1 range  -> 206 + Content-Type: normal; Content-Range;
2621 	 *  more     -> 206 + Content-Type: multipart/byteranges
2622 	 *  		Repeat the true Content-Type in each multipart header
2623 	 *  		along with Content-Range
2624 	 */
2625 	if (ranges < 0) {
2626 		/* it means he expressed a range in Range:, but it was illegal */
2627 		lws_return_http_status(wsi,
2628 				HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE, NULL);
2629 		if (lws_http_transaction_completed(wsi))
2630 			goto bail; /* <0 means just hang up */
2631 
2632 		lws_vfs_file_close(&wsi->http.fop_fd);
2633 
2634 		return 0; /* == 0 means we did the transaction complete */
2635 	}
2636 	if (ranges)
2637 		n = HTTP_STATUS_PARTIAL_CONTENT;
2638 #endif
2639 
2640 	if (lws_add_http_header_status(wsi, (unsigned int)n, &p, end))
2641 		goto bail;
2642 
2643 	if ((wsi->http.fop_fd->flags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP |
2644 		       LWS_FOP_FLAG_COMPR_IS_GZIP)) ==
2645 	    (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) {
2646 		if (lws_add_http_header_by_token(wsi,
2647 			WSI_TOKEN_HTTP_CONTENT_ENCODING,
2648 			(unsigned char *)"gzip", 4, &p, end))
2649 			goto bail;
2650 		lwsl_info("file is being provided in gzip\n");
2651 	}
2652 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
2653 	else {
2654 		/*
2655 		 * if we know its very compressible, and we can use
2656 		 * compression, then use the most preferred compression
2657 		 * method that the client said he will accept
2658 		 */
2659 
2660 		if (!wsi->interpreting && (
2661 		     !strncmp(content_type, "text/", 5) ||
2662 		     !strcmp(content_type, "application/javascript") ||
2663 		     !strcmp(content_type, "image/svg+xml")))
2664 			lws_http_compression_apply(wsi, NULL, &p, end, 0);
2665 	}
2666 #endif
2667 
2668 	if (
2669 #if defined(LWS_WITH_RANGES)
2670 	    ranges < 2 &&
2671 #endif
2672 	    content_type && content_type[0])
2673 		if (lws_add_http_header_by_token(wsi,
2674 						 WSI_TOKEN_HTTP_CONTENT_TYPE,
2675 						 (unsigned char *)content_type,
2676 						 (int)strlen(content_type),
2677 						 &p, end))
2678 			goto bail;
2679 
2680 #if defined(LWS_WITH_RANGES)
2681 	if (ranges >= 2) { /* multipart byteranges */
2682 		lws_strncpy(wsi->http.multipart_content_type, content_type,
2683 			sizeof(wsi->http.multipart_content_type));
2684 
2685 		if (lws_add_http_header_by_token(wsi,
2686 						 WSI_TOKEN_HTTP_CONTENT_TYPE,
2687 						 (unsigned char *)
2688 						 "multipart/byteranges; "
2689 						 "boundary=_lws",
2690 			 	 	 	 20, &p, end))
2691 			goto bail;
2692 
2693 		/*
2694 		 *  our overall content length has to include
2695 		 *
2696 		 *  - (n + 1) x "_lws\r\n"
2697 		 *  - n x Content-Type: xxx/xxx\r\n
2698 		 *  - n x Content-Range: bytes xxx-yyy/zzz\r\n
2699 		 *  - n x /r/n
2700 		 *  - the actual payloads (aggregated in rp->agg)
2701 		 *
2702 		 *  Precompute it for the main response header
2703 		 */
2704 
2705 		total_content_length = (lws_filepos_t)rp->agg +
2706 				       6 /* final _lws\r\n */;
2707 
2708 		lws_ranges_reset(rp);
2709 		while (lws_ranges_next(rp)) {
2710 			n = lws_snprintf(cache_control, sizeof(cache_control),
2711 					"bytes %llu-%llu/%llu",
2712 					rp->start, rp->end, rp->extent);
2713 
2714 			total_content_length = total_content_length +
2715 					(lws_filepos_t)(
2716 				6 /* header _lws\r\n */ +
2717 				/* Content-Type: xxx/xxx\r\n */
2718 				14 + (int)strlen(content_type) + 2 +
2719 				/* Content-Range: xxxx\r\n */
2720 				15 + n + 2 +
2721 				2); /* /r/n */
2722 		}
2723 
2724 		lws_ranges_reset(rp);
2725 		lws_ranges_next(rp);
2726 	}
2727 
2728 	if (ranges == 1) {
2729 		total_content_length = (lws_filepos_t)rp->agg;
2730 		n = lws_snprintf(cache_control, sizeof(cache_control),
2731 				 "bytes %llu-%llu/%llu",
2732 				 rp->start, rp->end, rp->extent);
2733 
2734 		if (lws_add_http_header_by_token(wsi,
2735 						 WSI_TOKEN_HTTP_CONTENT_RANGE,
2736 						 (unsigned char *)cache_control,
2737 						 n, &p, end))
2738 			goto bail;
2739 	}
2740 
2741 	wsi->http.range.inside = 0;
2742 
2743 	if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ACCEPT_RANGES,
2744 					 (unsigned char *)"bytes", 5, &p, end))
2745 		goto bail;
2746 #endif
2747 
2748 	if (!wsi->mux_substream) {
2749 		/* for http/1.1 ... */
2750 		if (!wsi->sending_chunked
2751 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
2752 				&& !wsi->http.lcs
2753 #endif
2754 		) {
2755 			/* ... if not already using chunked and not using an
2756 			 * http compression translation, then send the naive
2757 			 * content length
2758 			 */
2759 			if (lws_add_http_header_content_length(wsi,
2760 						total_content_length, &p, end))
2761 				goto bail;
2762 		} else {
2763 
2764 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
2765 			if (wsi->http.lcs) {
2766 
2767 				/* ...otherwise, for http 1 it must go chunked.
2768 				 * For the compression case, the reason is we
2769 				 * compress on the fly and do not know the
2770 				 * compressed content-length until it has all
2771 				 * been sent.  Http/1.1 pipelining must be able
2772 				 * to know where the transaction boundaries are
2773 				 * ... so chunking...
2774 				 */
2775 				if (lws_add_http_header_by_token(wsi,
2776 						WSI_TOKEN_HTTP_TRANSFER_ENCODING,
2777 						(unsigned char *)"chunked", 7,
2778 						&p, end))
2779 					goto bail;
2780 
2781 				/*
2782 				 * ...this is fun, isn't it :-)  For h1 that is
2783 				 * using an http compression translation, the
2784 				 * compressor must chunk its output privately.
2785 				 *
2786 				 * h2 doesn't need (or support) any of this
2787 				 * crap.
2788 				 */
2789 				lwsl_debug("setting chunking\n");
2790 				wsi->http.comp_ctx.chunking = 1;
2791 			}
2792 #endif
2793 		}
2794 	}
2795 
2796 	if (wsi->cache_secs && wsi->cache_reuse) {
2797 		if (!wsi->cache_revalidate) {
2798 			cc = cache_control;
2799 			cclen = sprintf(cache_control, "%s, max-age=%u",
2800 				    intermediates[wsi->cache_intermediaries],
2801 				    wsi->cache_secs);
2802 		} else {
2803 			cc = cache_control;
2804 			cclen = sprintf(cache_control,
2805 					"must-revalidate, %s, max-age=%u",
2806                                 intermediates[wsi->cache_intermediaries],
2807                                                     wsi->cache_secs);
2808 
2809 		}
2810 	}
2811 
2812 	/* Only add cache control if its not specified by any other_headers. */
2813 	if (!other_headers ||
2814 	    (!strstr(other_headers, "cache-control") &&
2815 	     !strstr(other_headers, "Cache-Control"))) {
2816 		if (lws_add_http_header_by_token(wsi,
2817 				WSI_TOKEN_HTTP_CACHE_CONTROL,
2818 				(unsigned char *)cc, cclen, &p, end))
2819 			goto bail;
2820 	}
2821 
2822 	if (other_headers) {
2823 		if ((end - p) < other_headers_len)
2824 			goto bail;
2825 		memcpy(p, other_headers, (unsigned int)other_headers_len);
2826 		p += other_headers_len;
2827 	}
2828 
2829 	if (lws_finalize_http_header(wsi, &p, end))
2830 		goto bail;
2831 
2832 	ret = lws_write(wsi, response, lws_ptr_diff_size_t(p, response), LWS_WRITE_HTTP_HEADERS);
2833 	if (ret != (p - response)) {
2834 		lwsl_err("_write returned %d from %ld\n", ret,
2835 			 (long)(p - response));
2836 		goto bail;
2837 	}
2838 
2839 	wsi->http.filepos = 0;
2840 	lwsi_set_state(wsi, LRS_ISSUING_FILE);
2841 
2842 	if (lws_hdr_total_length(wsi, WSI_TOKEN_HEAD_URI)) {
2843 		/* we do not emit the body */
2844 		lws_vfs_file_close(&wsi->http.fop_fd);
2845 		if (lws_http_transaction_completed(wsi))
2846 			goto bail;
2847 
2848 		return 0;
2849 	}
2850 
2851 	lws_callback_on_writable(wsi);
2852 
2853 	return 0;
2854 
2855 bail:
2856 	lws_vfs_file_close(&wsi->http.fop_fd);
2857 
2858 	return -1;
2859 }
2860 #endif
2861 
2862 #if defined(LWS_WITH_FILE_OPS)
2863 
lws_serve_http_file_fragment(struct lws * wsi)2864 int lws_serve_http_file_fragment(struct lws *wsi)
2865 {
2866 	struct lws_context *context = wsi->a.context;
2867 	struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2868 	struct lws_process_html_args args;
2869 	lws_filepos_t amount, poss;
2870 	unsigned char *p, *pstart;
2871 #if defined(LWS_WITH_RANGES)
2872 	unsigned char finished = 0;
2873 #endif
2874 #if defined(LWS_ROLE_H2)
2875 	struct lws *nwsi;
2876 #endif
2877 	int n, m;
2878 
2879 	lwsl_debug("wsi->mux_substream %d\n", wsi->mux_substream);
2880 
2881 	do {
2882 
2883 		/* priority 1: buffered output */
2884 
2885 		if (lws_has_buffered_out(wsi)) {
2886 			if (lws_issue_raw(wsi, NULL, 0) < 0) {
2887 				lwsl_info("%s: closing\n", __func__);
2888 				goto file_had_it;
2889 			}
2890 			break;
2891 		}
2892 
2893 		/* priority 2: buffered pre-compression-transform */
2894 
2895 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
2896 	if (wsi->http.comp_ctx.buflist_comp ||
2897 	    wsi->http.comp_ctx.may_have_more) {
2898 		enum lws_write_protocol wp = LWS_WRITE_HTTP;
2899 
2900 		lwsl_info("%s: completing comp partial (buflist %p, may %d)\n",
2901 			   __func__, wsi->http.comp_ctx.buflist_comp,
2902 			   wsi->http.comp_ctx.may_have_more);
2903 
2904 		if (lws_rops_fidx(wsi->role_ops, LWS_ROPS_write_role_protocol) &&
2905 		    lws_rops_func_fidx(wsi->role_ops, LWS_ROPS_write_role_protocol).
2906 					write_role_protocol(wsi, NULL, 0, &wp) < 0) {
2907 			lwsl_info("%s signalling to close\n", __func__);
2908 			goto file_had_it;
2909 		}
2910 		lws_callback_on_writable(wsi);
2911 
2912 		break;
2913 	}
2914 #endif
2915 
2916 		if (wsi->http.filepos == wsi->http.filelen)
2917 			goto all_sent;
2918 
2919 		n = 0;
2920 		p = pstart = pt->serv_buf + LWS_H2_FRAME_HEADER_LENGTH;
2921 
2922 #if defined(LWS_WITH_RANGES)
2923 		if (wsi->http.range.count_ranges && !wsi->http.range.inside) {
2924 
2925 			lwsl_notice("%s: doing range start %llu\n", __func__,
2926 				    wsi->http.range.start);
2927 
2928 			if ((long long)lws_vfs_file_seek_cur(wsi->http.fop_fd,
2929 						   (lws_fileofs_t)wsi->http.range.start -
2930 						   (lws_fileofs_t)wsi->http.filepos) < 0)
2931 				goto file_had_it;
2932 
2933 			wsi->http.filepos = wsi->http.range.start;
2934 
2935 			if (wsi->http.range.count_ranges > 1) {
2936 				n =  lws_snprintf((char *)p,
2937 						context->pt_serv_buf_size -
2938 						LWS_H2_FRAME_HEADER_LENGTH,
2939 					"_lws\x0d\x0a"
2940 					"Content-Type: %s\x0d\x0a"
2941 					"Content-Range: bytes "
2942 						"%llu-%llu/%llu\x0d\x0a"
2943 					"\x0d\x0a",
2944 					wsi->http.multipart_content_type,
2945 					wsi->http.range.start,
2946 					wsi->http.range.end,
2947 					wsi->http.range.extent);
2948 				p += n;
2949 			}
2950 
2951 			wsi->http.range.budget = wsi->http.range.end -
2952 						   wsi->http.range.start + 1;
2953 			wsi->http.range.inside = 1;
2954 		}
2955 #endif
2956 
2957 		poss = context->pt_serv_buf_size;
2958 
2959 #if defined(LWS_ROLE_H2)
2960                /*
2961                 * If it's h2, restrict any lump that we are sending to the
2962                 * max h2 frame size the peer indicated he could handle in
2963                 * his SETTINGS
2964                 */
2965                nwsi = lws_get_network_wsi(wsi);
2966                if (nwsi->h2.h2n &&
2967                    poss > (lws_filepos_t)nwsi->h2.h2n->peer_set.s[H2SET_MAX_FRAME_SIZE])
2968                        poss = (lws_filepos_t)nwsi->h2.h2n->peer_set.s[H2SET_MAX_FRAME_SIZE];
2969 #endif
2970 		poss = poss - (lws_filepos_t)(n + LWS_H2_FRAME_HEADER_LENGTH);
2971 
2972 		if (wsi->http.tx_content_length)
2973 			if (poss > wsi->http.tx_content_remain)
2974 				poss = wsi->http.tx_content_remain;
2975 
2976 		/*
2977 		 * If there is a hint about how much we will do well to send at
2978 		 * one time, restrict ourselves to only trying to send that.
2979 		 */
2980 		if (wsi->a.protocol->tx_packet_size &&
2981 		    poss > wsi->a.protocol->tx_packet_size)
2982 			poss = wsi->a.protocol->tx_packet_size;
2983 
2984 		if (lws_rops_fidx(wsi->role_ops, LWS_ROPS_tx_credit)) {
2985 			lws_filepos_t txc = (unsigned int)lws_rops_func_fidx(wsi->role_ops,
2986 							       LWS_ROPS_tx_credit).
2987 					tx_credit(wsi, LWSTXCR_US_TO_PEER, 0);
2988 
2989 			if (!txc) {
2990 				/*
2991 				 * We shouldn't've been able to get the
2992 				 * WRITEABLE if we are skint
2993 				 */
2994 				lwsl_notice("%s: %s: no tx credit\n", __func__,
2995 						lws_wsi_tag(wsi));
2996 
2997 				return 0;
2998 			}
2999 			if (txc < poss)
3000 				poss = txc;
3001 
3002 			/*
3003 			 * Tracking consumption of the actual payload amount
3004 			 * will be handled when the role data frame is sent...
3005 			 */
3006 		}
3007 
3008 #if defined(LWS_WITH_RANGES)
3009 		if (wsi->http.range.count_ranges) {
3010 			if (wsi->http.range.count_ranges > 1)
3011 				poss -= 7; /* allow for final boundary */
3012 			if (poss > wsi->http.range.budget)
3013 				poss = wsi->http.range.budget;
3014 		}
3015 #endif
3016 		if (wsi->sending_chunked) {
3017 			/* we need to drop the chunk size in here */
3018 			p += 10;
3019 			/* allow for the chunk to grow by 128 in translation */
3020 			poss -= 10 + 128;
3021 		}
3022 
3023 		amount = 0;
3024 		if (lws_vfs_file_read(wsi->http.fop_fd, &amount, p, poss) < 0)
3025 			goto file_had_it; /* caller will close */
3026 
3027 		if (wsi->sending_chunked)
3028 			n = (int)amount;
3029 		else
3030 			n = lws_ptr_diff(p, pstart) + (int)amount;
3031 
3032 		lwsl_debug("%s: sending %d\n", __func__, n);
3033 
3034 		if (n) {
3035 			lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
3036 					(int)context->timeout_secs);
3037 
3038 			if (wsi->interpreting) {
3039 				args.p = (char *)p;
3040 				args.len = n;
3041 				args.max_len = (int)(unsigned int)poss + 128;
3042 				args.final = wsi->http.filepos + (unsigned int)n ==
3043 							wsi->http.filelen;
3044 				args.chunked = wsi->sending_chunked;
3045 				if (user_callback_handle_rxflow(
3046 				     wsi->a.vhost->protocols[
3047 				     (int)wsi->protocol_interpret_idx].callback,
3048 				     wsi, LWS_CALLBACK_PROCESS_HTML,
3049 				     wsi->user_space, &args, 0) < 0)
3050 					goto file_had_it;
3051 				n = args.len;
3052 				p = (unsigned char *)args.p;
3053 			} else
3054 				p = pstart;
3055 
3056 #if defined(LWS_WITH_RANGES)
3057 			if (wsi->http.range.send_ctr + 1 ==
3058 				wsi->http.range.count_ranges && // last range
3059 			    wsi->http.range.count_ranges > 1 && // was 2+ ranges (ie, multipart)
3060 			    wsi->http.range.budget - amount == 0) {// final part
3061 				n += lws_snprintf((char *)pstart + n, 6,
3062 					"_lws\x0d\x0a"); // append trailing boundary
3063 				lwsl_debug("added trailing boundary\n");
3064 			}
3065 #endif
3066 			m = lws_write(wsi, p, (unsigned int)n, wsi->http.filepos + amount ==
3067 					wsi->http.filelen ?
3068 					 LWS_WRITE_HTTP_FINAL : LWS_WRITE_HTTP);
3069 			if (m < 0)
3070 				goto file_had_it;
3071 
3072 			wsi->http.filepos += amount;
3073 
3074 #if defined(LWS_WITH_RANGES)
3075 			if (wsi->http.range.count_ranges >= 1) {
3076 				wsi->http.range.budget -= amount;
3077 				if (wsi->http.range.budget == 0) {
3078 					lwsl_notice("range budget exhausted\n");
3079 					wsi->http.range.inside = 0;
3080 					wsi->http.range.send_ctr++;
3081 
3082 					if (lws_ranges_next(&wsi->http.range) < 1) {
3083 						finished = 1;
3084 						goto all_sent;
3085 					}
3086 				}
3087 			}
3088 #endif
3089 
3090 			if (m != n) {
3091 				/* adjust for what was not sent */
3092 				if (lws_vfs_file_seek_cur(wsi->http.fop_fd,
3093 							   m - n) ==
3094 							     (lws_fileofs_t)-1)
3095 					goto file_had_it;
3096 			}
3097 		}
3098 
3099 all_sent:
3100 		if ((!lws_has_buffered_out(wsi)
3101 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
3102 				&& !wsi->http.comp_ctx.buflist_comp &&
3103 		    !wsi->http.comp_ctx.may_have_more
3104 #endif
3105 		    ) && (wsi->http.filepos >= wsi->http.filelen
3106 #if defined(LWS_WITH_RANGES)
3107 		    || finished)
3108 #else
3109 		)
3110 #endif
3111 		) {
3112 			lwsi_set_state(wsi, LRS_ESTABLISHED);
3113 			/* we might be in keepalive, so close it off here */
3114 			lws_vfs_file_close(&wsi->http.fop_fd);
3115 
3116 			lwsl_debug("file completed\n");
3117 
3118 			if (wsi->a.protocol->callback &&
3119 			    user_callback_handle_rxflow(wsi->a.protocol->callback,
3120 					wsi, LWS_CALLBACK_HTTP_FILE_COMPLETION,
3121 					wsi->user_space, NULL, 0) < 0) {
3122 					/*
3123 					 * For http/1.x, the choices from
3124 					 * transaction_completed are either
3125 					 * 0 to use the connection for pipelined
3126 					 * or nonzero to hang it up.
3127 					 *
3128 					 * However for http/2. while we are
3129 					 * still interested in hanging up the
3130 					 * nwsi if there was a network-level
3131 					 * fatal error, simply completing the
3132 					 * transaction is a matter of the stream
3133 					 * state, not the root connection at the
3134 					 * network level
3135 					 */
3136 					if (wsi->mux_substream)
3137 						return 1;
3138 					else
3139 						return -1;
3140 				}
3141 
3142 			return 1;  /* >0 indicates completed */
3143 		}
3144 		/*
3145 		 * while(1) here causes us to spam the whole file contents into
3146 		 * a hugely bloated output buffer if it ever can't send the
3147 		 * whole chunk...
3148 		 */
3149 	} while (!lws_send_pipe_choked(wsi));
3150 
3151 	lws_callback_on_writable(wsi);
3152 
3153 	return 0; /* indicates further processing must be done */
3154 
3155 file_had_it:
3156 	lws_vfs_file_close(&wsi->http.fop_fd);
3157 
3158 	return -1;
3159 }
3160 
3161 #endif
3162 
3163 #if defined(LWS_WITH_SERVER)
3164 void
lws_server_get_canonical_hostname(struct lws_context * context,const struct lws_context_creation_info * info)3165 lws_server_get_canonical_hostname(struct lws_context *context,
3166 				  const struct lws_context_creation_info *info)
3167 {
3168 	if (lws_check_opt(info->options,
3169 			LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
3170 		return;
3171 #if !defined(LWS_PLAT_FREERTOS)
3172 	/* find canonical hostname */
3173 	if (gethostname((char *)context->canonical_hostname,
3174 		        sizeof(context->canonical_hostname) - 1))
3175 		lws_strncpy((char *)context->canonical_hostname, "unknown",
3176 			    sizeof(context->canonical_hostname));
3177 
3178 	lwsl_info(" canonical_hostname = %s\n", context->canonical_hostname);
3179 #else
3180 	(void)context;
3181 #endif
3182 }
3183 #endif
3184 
3185 int
lws_chunked_html_process(struct lws_process_html_args * args,struct lws_process_html_state * s)3186 lws_chunked_html_process(struct lws_process_html_args *args,
3187 			 struct lws_process_html_state *s)
3188 {
3189 	char *sp, buffer[32];
3190 	const char *pc;
3191 	int old_len, n;
3192 
3193 	/* do replacements */
3194 	sp = args->p;
3195 	old_len = args->len;
3196 	args->len = 0;
3197 	s->start = sp;
3198 	while (sp < args->p + old_len) {
3199 
3200 		if (args->len + 7 >= args->max_len) {
3201 			lwsl_err("Used up interpret padding\n");
3202 			return -1;
3203 		}
3204 
3205 		if ((!s->pos && *sp == '$') || s->pos) {
3206 			int hits = 0, hit = 0;
3207 
3208 			if (!s->pos)
3209 				s->start = sp;
3210 			s->swallow[s->pos++] = *sp;
3211 			if (s->pos == sizeof(s->swallow) - 1)
3212 				goto skip;
3213 			for (n = 0; n < s->count_vars; n++)
3214 				if (!strncmp(s->swallow, s->vars[n], (unsigned int)s->pos)) {
3215 					hits++;
3216 					hit = n;
3217 				}
3218 			if (!hits) {
3219 skip:
3220 				s->swallow[s->pos] = '\0';
3221 				memcpy(s->start, s->swallow, (unsigned int)s->pos);
3222 				args->len++;
3223 				s->pos = 0;
3224 				sp = s->start + 1;
3225 				continue;
3226 			}
3227 			if (hits == 1 && s->pos == (int)strlen(s->vars[hit])) {
3228 				pc = s->replace(s->data, hit);
3229 				if (!pc)
3230 					pc = "NULL";
3231 				n = (int)strlen(pc);
3232 				s->swallow[s->pos] = '\0';
3233 				if (n != s->pos) {
3234 					memmove(s->start + n, s->start + s->pos,
3235 						(unsigned int)(old_len - (sp - args->p) - 1));
3236 					old_len += (n - s->pos) + 1;
3237 				}
3238 				memcpy(s->start, pc, (unsigned int)n);
3239 				args->len++;
3240 				sp = s->start + 1;
3241 
3242 				s->pos = 0;
3243 			}
3244 			sp++;
3245 			continue;
3246 		}
3247 
3248 		args->len++;
3249 		sp++;
3250 	}
3251 
3252 	if (args->chunked) {
3253 		/* no space left for final chunk trailer */
3254 		if (args->final && args->len + 7 >= args->max_len)
3255 			return -1;
3256 
3257 		n = sprintf(buffer, "%X\x0d\x0a", args->len);
3258 
3259 		args->p -= n;
3260 		memcpy(args->p, buffer, (unsigned int)n);
3261 		args->len += n;
3262 
3263 		if (args->final) {
3264 			sp = args->p + args->len;
3265 			*sp++ = '\x0d';
3266 			*sp++ = '\x0a';
3267 			*sp++ = '0';
3268 			*sp++ = '\x0d';
3269 			*sp++ = '\x0a';
3270 			*sp++ = '\x0d';
3271 			*sp++ = '\x0a';
3272 			args->len += 7;
3273 		} else {
3274 			sp = args->p + args->len;
3275 			*sp++ = '\x0d';
3276 			*sp++ = '\x0a';
3277 			args->len += 2;
3278 		}
3279 	}
3280 
3281 	return 0;
3282 }
3283