/*
 * lws-minimal-secure-streams-server
 *
 * Written in 2010-2020 by Andy Green <andy@warmcat.com>
 *
 * This file is made available under the Creative Commons CC0 1.0
 * Universal Public Domain Dedication.
 */

#include <libwebsockets.h>
#include <string.h>
#include <signal.h>

extern const lws_ss_info_t ssi_client, ssi_server;

static struct lws_context *context;
int interrupted, bad = 1, multipart;
static const char * const default_ss_policy =
	"{"
	  "\"release\":"			"\"01234567\","
	  "\"product\":"			"\"myproduct\","
	  "\"schema-version\":"			"1,"
	  "\"retry\": ["	/* named backoff / retry strategies */
		"{\"default\": {"
			"\"backoff\": ["	 "1000,"
						 "2000,"
						 "3000,"
						 "5000,"
						"10000"
				"],"
			"\"conceal\":"		"5,"
			"\"jitterpc\":"		"20,"
			"\"svalidping\":"	"300,"
			"\"svalidhup\":"	"310"
		"}}"
	  "],"
	  "\"certs\": [" /* named individual certificates in BASE64 DER */
		/*
		 * Need to be in order from root cert... notice sometimes as
		 * with Let's Encrypt there are multiple possible validation
		 * paths, all the pieces for one validation path must be
		 * given, excluding the server cert itself.  Let's Encrypt
		 * intermediate is signed by their ISRG Root CA but also is
		 * cross-signed by an IdenTrust intermediate that's widely
		 * deployed in browsers.  We use the ISRG path because that
		 * way we can skip the extra IdenTrust root cert.
		 */
			"{\"isrg_root_x1\": \""
	"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw"
	"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh"
	"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4"
	"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu"
	"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY"
	"MTCCAiIwDQYJKoZIhvcNAQEBBQ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fDQ4e3RM"
	"OMz3ZFiaMaJsGGNf4++d9TmMgk4Ns6oDs6Tb9AECggEBAJYzd+SOYo26iBu3nw3L"
	"65uEeh6xou8pXH0Tu4gQrPQTRZZ/nT3iNgOwqu1gRuxcq7TOjt41UdqIKO8vN7/A"
	"aJavCpaKoIMowy/aGCbvAvjNPpU3unU8jdl/t08EXs79S5IKPcgAx87sTTi7KDN5"
	"SYt4tr2uPEe53NTXuSatilG5QCyExIELOuzWAMKzg7CAiIlNS9foWeLyVkBgCQ6S"
	"me/L8ta+mUDy37K6vC34jh9vK9yrwF6X44ItRoOJafCaVfGI+175q/eWcqTX4q+I"
	"G4tKls4sL4mgOJLq+ra50aYMxbcuommctPMXU6CrrYyQpPTHMNVDQy2ttFdsq9iK"
	"TncCggEBAMmt/8yvPflS+xv3kg/ZBvR9JB1In2n3rUCYYD47ReKFqJ03Vmq5C9nY"
	"56s9w7OUO8perBXlJYmKZQhO4293lvxZD2Iq4NcZbVSCMoHAUzhzY3brdgtSIxa2"
	"gGveGAezZ38qKIU26dkz7deECY4vrsRkwhpTW0LGVCpjcQoaKvymAoCmAs8V2oMr"
	"Ziw1YQ9uOUoWwOqm1wZqmVcOXvPIS2gWAs3fQlWjH9hkcQTMsUaXQDOD0aqkSY3E"
	"NqOvbCV1/oUpRi3076khCoAXI1bKSn/AvR3KDP14B5toHI/F5OTSEiGhhHesgRrs"
	"fBrpEY1IATtPq1taBZZogRqI3rOkkPk="
		"\"}"
	  "],"
	  "\"trust_stores\": [" /* named cert chains */
		"{"
			"\"name\": \"le_via_isrg\","
			"\"stack\": ["
				"\"isrg_root_x1\""
			"]"
		"}"
	  "],"
	  "\"s\": ["
		/*
		 * Client streamtypes
		 */

		"{\"mintest\": {"
			"\"endpoint\":"		"\"warmcat.com\","
			"\"port\":"		"443,"
			"\"protocol\":"		"\"h2\","
			"\"http_method\":"	"\"GET\","
			"\"http_url\":"		"\"index.html\","
			"\"tls\":"		"true,"
			"\"retry\":"		"\"default\","
			"\"tls_trust_store\":"	"\"le_via_isrg\""
		"}},"

		/*
		 * This streamtype represents an h2 server listening on :7681,
		 * using a 100-y self-signed tls cert
		 */

		"{\"myserver\": {"
			/* if given, "endpoint" is network if to bind to */
			"\"server\":"		"true,"
			"\"port\":"		"7681,"
			"\"protocol\":"		"\"h1\","
			"\"metadata\": [{"
				"\"mime\": \"Content-Type:\","
				"\"method\": \"\","
				"\"path\": \"\""
			"}],"
			"\"tls\":"		"true,"
			/*
			 * A ws server is an http server, if you give a
			 * ws_subprotocol here it's understood we also serve
			 * that ove ws or wss according to tls
			 */
			"\"ws_subprotocol\":"	"\"mywsprotocol\","
			"\"server_cert\":"	"\"self_localhost\","
			"\"server_key\":"	"\"self_localhost_key\""
		"}},"

	  "]"
	"}"
;

static int
smd_cb(void *opaque, lws_smd_class_t c, lws_usec_t ts, void *buf, size_t len)
{
	if ((c & LWSSMDCL_SYSTEM_STATE) &&
	    !lws_json_simple_strcmp(buf, len, "\"state\":", "OPERATIONAL")) {

		/* create the secure streams */

		lwsl_notice("%s: creating server stream\n", __func__);

		if (lws_ss_create(context, 0, &ssi_server, NULL, NULL,
				  NULL, NULL)) {
			lwsl_err("%s: failed to create secure stream\n",
				 __func__);
			bad = 1;
			interrupted = 1;
			lws_cancel_service(context);
			return -1;
		}
#if 0
		lwsl_notice("%s: creating client stream\n", __func__);

		if (lws_ss_create(context, 0, &ssi_client, NULL, NULL,
				  NULL, NULL)) {
			lwsl_err("%s: failed to create secure stream\n",
				 __func__);
			return -1;
		}
#endif
	}

	return 0;
}

static void
sigint_handler(int sig)
{
	interrupted = 1;
}

int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	int n = 0;

	signal(SIGINT, sigint_handler);

	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
	lws_cmdline_option_handle_builtin(argc, argv, &info);

	if (lws_cmdline_option(argc, argv, "-m"))
		multipart = 1;

	lwsl_user("LWS Secure Streams Server\n");

	info.options			= LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
					  LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
	info.fd_limit_per_thread	= 1 + 6 + 1;
	info.pss_policies_json		= default_ss_policy;
	info.port			= CONTEXT_PORT_NO_LISTEN;
	info.early_smd_cb		= smd_cb;
	info.early_smd_class_filter	= LWSSMDCL_SYSTEM_STATE;

	context = lws_create_context(&info);
	if (!context) {
		lwsl_err("lws init failed\n");
		return 1;
	}

	/* the event loop */

	while (n >= 0 && !interrupted)
		n = lws_service(context, 0);

	bad = 0;

	lws_context_destroy(context);
	lwsl_user("Completed: %s\n", bad ? "failed" : "OK");

	return bad;
}
