1/*
2 * lws-minimal-http-server
3 *
4 * Written in 2010-2019 by Andy Green <andy@warmcat.com>
5 *
6 * This file is made available under the Creative Commons CC0 1.0
7 * Universal Public Domain Dedication.
8 *
9 * This demonstrates the most minimal http server you can make with lws.
10 *
11 * To keep it simple, it serves stuff from the subdirectory
12 * "./mount-origin" of the directory it was started in.
13 * You can change that by changing mount.origin below.
14 */
15
16#include <libwebsockets.h>
17#include <string.h>
18#include <signal.h>
19
20static int interrupted;
21
22static const struct lws_http_mount mount = {
23	/* .mount_next */		NULL,		/* linked-list "next" */
24	/* .mountpoint */		"/",		/* mountpoint URL */
25	/* .origin */			"./mount-origin", /* serve from dir */
26	/* .def */			"index.html",	/* default filename */
27	/* .protocol */			NULL,
28	/* .cgienv */			NULL,
29	/* .extra_mimetypes */		NULL,
30	/* .interpret */		NULL,
31	/* .cgi_timeout */		0,
32	/* .cache_max_age */		0,
33	/* .auth_mask */		0,
34	/* .cache_reusable */		0,
35	/* .cache_revalidate */		0,
36	/* .cache_intermediaries */	0,
37	/* .origin_protocol */		LWSMPRO_FILE,	/* files in a dir */
38	/* .mountpoint_len */		1,		/* char count */
39	/* .basic_auth_login_file */	NULL,
40};
41
42void sigint_handler(int sig)
43{
44	interrupted = 1;
45}
46
47int main(int argc, const char **argv)
48{
49	struct lws_context_creation_info info;
50	struct lws_context *context;
51	const char *p;
52	int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
53			/* for LLL_ verbosity above NOTICE to be built into lws,
54			 * lws must have been configured and built with
55			 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */
56			/* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */
57			/* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */
58			/* | LLL_DEBUG */;
59
60	signal(SIGINT, sigint_handler);
61
62	if ((p = lws_cmdline_option(argc, argv, "-d")))
63		logs = atoi(p);
64
65	lws_set_log_level(logs, NULL);
66	lwsl_user("LWS minimal http server | visit http://localhost:7681\n");
67
68	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
69	info.port = 7681;
70	info.mounts = &mount;
71	info.error_document_404 = "/404.html";
72	info.options =
73		LWS_SERVER_OPTION_HTTP_HEADERS_SECURITY_BEST_PRACTICES_ENFORCE;
74
75	if (lws_cmdline_option(argc, argv, "--h2-prior-knowledge"))
76		info.options |= LWS_SERVER_OPTION_H2_PRIOR_KNOWLEDGE;
77
78	context = lws_create_context(&info);
79	if (!context) {
80		lwsl_err("lws init failed\n");
81		return 1;
82	}
83
84	while (n >= 0 && !interrupted)
85		n = lws_service(context, 0);
86
87	lws_context_destroy(context);
88
89	return 0;
90}
91