/*
 * lws-minimal-secure-streams-proxy
 *
 * 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.
 *
 *
 * This is the proxy part for examples built to use it to connect to... it has
 * the policy and the core SS function, but it doesn't contain any of the user
 * code "business logic"... that's in the clients.
 *
 * The proxy side has the policy and performs the onward connection proxying
 * fulfilment.  The clients state the streamtype name they want and ask for the
 * client to do the connection part.
 *
 * Rideshare information is being parsed out at the proxy side; the SSS RX part
 * also brings with it rideshare names.
 *
 * Metadata is passed back over SSS from the client in the TX messages for the
 * proxy to use per the policy.
 */

#include <libwebsockets.h>

enum {
	LWS_SW_C,
	LWS_SW_I,
	LWS_SW_P,
	LWS_SW_HELP,
};

static const struct lws_switches switches[] = {
	[LWS_SW_C]	= { "-c",              "Policy filepath" },
	[LWS_SW_I]	= { "-i",              "Interface to bind to" },
	[LWS_SW_P]	= { "-p",              "Port number to listen or connect on" },
	[LWS_SW_HELP]	= { "--help",		"Show this help information" },
};

#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>

#if defined(__APPLE__) || defined(__linux__)
#include <execinfo.h>
#include <assert.h>
#endif

#define TEST_CLIENT_ID "SN12345678"

static int interrupted, bad = 1, port = 0 /* unix domain socket */;
static const char *ibind = NULL; /* default to unix domain skt "proxy.ss.lws" */
static lws_state_notify_link_t nl;
static struct lws_context *context;

/*
 * We just define enough policy so it can fetch the latest one securely.
 *
 * If using SSPC, we use the proxy's policy, not this
 */


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\":"	"30,"
			"\"svalidhup\":"	"35"
		"}}"
	  "],"
	  "\"certs\": [" /* named individual certificates in BASE64 DER */
		/*
		 * Let's Encrypt certs for warmcat.com / libwebsockets.org
		 *
		 * We fetch the real policy from there using SS and switch to
		 * using that.
		 */
				"{\"isrg_root_x1\": \""
	"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw"
	"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh"
	"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4"
	"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu"
	"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY"
	"MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc"
	"h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+"
	"0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U"
	"A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW"
	"T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH"
	"B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC"
	"B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv"
	"KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn"
	"OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQ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MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw"
	"CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg"
	"R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00"
	"MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT"
	"ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw"
	"EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW"
	"+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9"
	"ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T"
	"AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI"
	"zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW"
	"tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1"
	"/q4AaOeMSQ+2b1tbFfLn"
		"\"}"
	  "],"
	  "\"trust_stores\": [" /* named cert chains */
		"{"
			"\"name\": \"le_via_isrg\","
			"\"stack\": ["
				"\"isrg_root_x1\","
				"\"isrg_root_x2\""
			"]"
		"}"
	  "],"
	  "\"s\": [{"
		"\"captive_portal_detect\": {"
			"\"endpoint\": \"connectivitycheck.android.com\","
			"\"http_url\": \"generate_204\","
			"\"port\": 80,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"opportunistic\": true,"
			"\"http_expect\": 204,"
			"\"http_fail_redirect\": true"
		"},"
		"\"fetch_policy\": {"
			"\"endpoint\":"		"\"warmcat.com\","
			"\"port\":"		"443,"
			"\"protocol\":"		"\"h1\","
			"\"http_method\":"	"\"GET\","
			"\"http_url\":"		"\"policy/minimal-proxy-v4.2-v2.json\","
			"\"tls\":"		"true,"
			"\"opportunistic\":"	"true,"
			"\"retry\":"		"\"default\","
			"\"tls_trust_store\":"	"\"le_via_isrg\""
		"}}"
	"}"
;

static const char *canned_root_token_payload =
	"grant_type=refresh_token"
	"&refresh_token=Atzr|IwEBIJedGXjDqsU_vMxykqOMg"
	"SHfYe3CPcedueWEMWSDMaDnEmiW8RlR1Kns7Cb4B-TOSnqp7ifVsY4BMY2B8tpHfO39XP"
	"zfu9HapGjTR458IyHX44FE71pWJkGZ79uVBpljP4sazJuk8XS3Oe_yLnm_DIO6fU1nU3Y"
	"0flYmsOiOAQE_gRk_pdlmEtHnpMA-9rLw3mkY5L89Ty9kUygBsiFaYatouROhbsTn8-jW"
	"k1zZLUDpT6ICtBXSnrCIg0pUbZevPFhTwdXd6eX-u4rq0W-XaDvPWFO7au-iPb4Zk5eZE"
	"iX6sissYrtNmuEXc2uHu7MnQO1hHCaTdIO2CANVumf-PHSD8xseamyh04sLV5JgFzY45S"
	"KvKMajiUZuLkMokOx86rjC2Hdkx5DO7G-dbG1ufBDG-N79pFMSs7Ck5pc283IdLoJkCQc"
	"AGvTX8o8I29QqkcGou-9TKhOJmpX8As94T61ok0UqqEKPJ7RhfQHHYdCtsdwxgvfVr9qI"
	"xL_hDCcTho8opCVX-6QhJHl6SQFlTw13"
	"&client_id="
		"amzn1.application-oa2-client.4823334c434b4190a2b5a42c07938a2d";

#if defined(LWS_WITH_SECURE_STREAMS_AUTH_SIGV4)
static char *aws_keyid = NULL,
	    *aws_key = NULL;
#endif

static const uint8_t client_key[] = {
	0x30, 0x82, 0x04, 0xa4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00,
	0xd9, 0x64, 0x2a, 0x43, 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x9d, 0xa1, 0x24, 0xb0, 0x11, 0x1c, 0x54, 0xce, 0xef, 0x70, 0xe9, 0xd5,
	0x26, 0xc1, 0xd6, 0xce, 0xa6, 0x4b, 0x21, 0xc6, 0x19, 0x00, 0x8e, 0x89, 
	0xe8, 0x8f, 0xb0, 0x11, 0x03, 0x00, 0xda, 0x5f, 0x9a, 0x53, 0x2a, 0x2b,
	0x23, 0x01, 0xa9, 0x25, 0xe4, 0xbb, 0xf8, 0xf4, 0x15, 0x92, 0x95, 0xb1,
	0xb1, 0x13, 0xff, 0xea, 0xb9, 0x2d, 0x86, 0xe3, 0xd8, 0xe0, 0x41, 0xe0,
	0x7b, 0x18, 0x8d, 0x7a, 0x79, 0x10, 0x13, 0x0f, 0xfc, 0xca, 0x08, 0x4d,
	0xa8, 0x9e, 0xcb, 0x66, 0x7c, 0x53, 0xea, 0xae, 0xee, 0xf1, 0x8b, 0x2f,
	0x94, 0x08, 0x72, 0x7c
};

static const uint8_t client_cert_der[] = {
	0x30, 0x82, 0x03, 0x9b, 0x30, 0x82, 0x02, 0x83, 0xa0, 0x03, 0x02, 0x01,
	0x02, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 
	0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x81, 0x90, 0x31, 0x0b,
	0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x47, 0x42, 0x31,
	0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0e, 0x55, 0x6e,
	0x69, 0x74, 0x65, 0x64, 0x20, 0x4b, 0x69, 0x6e, 0x67, 0x64, 0x6f, 0x6d, 
	0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x05, 0x44,
	0x65, 0x72, 0x62, 0x79, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04,
	0x0a, 0x0c, 0x09, 0x4d, 0x6f, 0x73, 0x71, 0x75, 0x69, 0x74, 0x74, 0x6f,
	0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x02, 0x43, 
	0x41, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x0d,
	0x6d, 0x6f, 0x73, 0x71, 0x75, 0x69, 0x74, 0x74, 0x6f, 0x2e, 0x6f, 0x72,
	0x67, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
	0x0d, 0x01, 0x09, 0x01, 0x16, 0x10, 0x72, 0x6f, 0x67, 0x65, 0x72, 0x40, 
	0x61, 0x74, 0x63, 0x68, 0x6f, 0x6f, 0x2e, 0x6f, 0x72, 0x67, 0x30, 0x1e,
	0x17, 0x0d, 0x32, 0x31, 0x31, 0x31, 0x30, 0x33, 0x32, 0x32, 0x33, 0x39,
	0x35, 0x31, 0x5a, 0x17, 0x0d, 0x32, 0x32, 0x30, 0x32, 0x30, 0x31, 0x32,
	0x32, 0x33, 0x39, 0x35, 0x31, 0x5a, 0x30, 0x75, 0x31, 0x0b, 0x30, 0x09, 
	0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30,
	0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x43, 0x61, 0x6c, 0x69,
	0x66, 0x6f, 0x72, 0x6e, 0x69, 0x61, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03,
	0x55, 0x04, 0x07, 0x0c, 0x09, 0x53, 0x75, 0x6e, 0x6e, 0x79, 0x76, 0x61, 
	0x6c, 0x65, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c,
	0x0d, 0x6c, 0x69, 0x62, 0x77, 0x65, 0x62, 0x73, 0x6f, 0x63, 0x6b, 0x65,
	0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d9, 
	0x54, 0xf0, 0x68, 0x16, 0xf5, 0xb9, 0x94, 0x48, 0x3e, 0x6d, 0x5f, 0xd2,
	0x11, 0xf2, 0x33, 0x7f, 0x6b, 0x1f, 0x08, 0x77, 0xe1, 0x82, 0x18, 0x04,
	0x6c, 0x01, 0x39, 0xf9, 0x75, 0xcb, 0x9d, 0x87, 0x62, 0x11, 0x08, 0x15,
	0xe3, 0xd6, 0x05, 0x79, 0x51, 0xa1, 0x51, 0xb9, 0x9b, 0x61, 0x52, 0x82,
	0x9f, 0x8f, 0x1b, 0x39, 0xbb, 0xb5, 0xcd, 0xb2, 0x37, 0x74, 0xfd, 0x08,
	0x85, 0xe7, 0x8f, 0xbd, 0xe1, 0xd0, 0x18, 0x57, 0xd0, 0x3d, 0xbb, 0x37,
	0x80, 0xbf, 0x3e, 0x5f, 0x6f, 0x2a, 0x1b, 0x73, 0xc7, 0x41, 0xa7, 0x62,
	0x9a, 0x9b, 0x7f
};

static int
app_system_state_nf(lws_state_manager_t *mgr, lws_state_notify_link_t *link,
		    int current, int target)
{
	struct lws_context *context = lws_system_context_from_system_mgr(mgr);
	lws_system_blob_t *ab = lws_system_get_blob(context,
				LWS_SYSBLOB_TYPE_AUTH, 1 /* AUTH_IDX_ROOT */);
	size_t size;

	/*
	 * For the things we care about, let's notice if we are trying to get
	 * past them when we haven't solved them yet, and make the system
	 * state wait while we trigger the dependent action.
	 */
	lwsl_user("%s: current %d, target %d\n", __func__, current, target);

	switch (target) {
	case LWS_SYSTATE_REGISTERED:
		size = lws_system_blob_get_size(ab);
		if (size)
			break;

		/* let's register our canned root token so auth can use it */
		lws_system_blob_direct_set(ab,
				(const uint8_t *)canned_root_token_payload,
				strlen(canned_root_token_payload));
		break;
	case LWS_SYSTATE_OPERATIONAL:
		if (current == LWS_SYSTATE_OPERATIONAL) {
#if defined(LWS_WITH_SECURE_STREAMS_AUTH_SIGV4)

			if (lws_aws_filesystem_credentials_helper(
						  "~/.aws/credentials",
						  "aws_access_key_id",
						  "aws_secret_access_key",
						  &aws_keyid, &aws_key))
				return -1;

			lws_ss_sigv4_set_aws_key(context, 0, aws_keyid, aws_key);
#endif

			lws_system_blob_direct_set(
				lws_system_get_blob(context, LWS_SYSBLOB_TYPE_MQTT_CLIENT_ID, 0),
				(const uint8_t*)TEST_CLIENT_ID, strlen(TEST_CLIENT_ID));

			lws_system_blob_direct_set(
				lws_system_get_blob(context, LWS_SYSBLOB_TYPE_CLIENT_CERT_DER, 0),
				client_cert_der, sizeof(client_cert_der));

			lws_system_blob_direct_set(
				lws_system_get_blob(context, LWS_SYSBLOB_TYPE_CLIENT_KEY_DER, 0),
				client_key, sizeof(client_key));

			/*
			 * At this point we have DHCP, ntp, system auth token
			 * and we can reasonably create the proxy
			 */
			if (lws_ss_proxy_create(context, ibind, port)) {
				lwsl_err("%s: failed to create ss proxy\n",
						__func__);
				return -1;
			}
		}
		break;
	case LWS_SYSTATE_POLICY_INVALID:
		/*
		 * This is a NOP since we used direct set... but in a real
		 * system this could easily change to be done on the heap, then
		 * this would be important
		 */
		lws_system_blob_destroy(lws_system_get_blob(context,
					LWS_SYSBLOB_TYPE_AUTH,
					1 /* AUTH_IDX_ROOT */));
		break;
	}

	return 0;
}

static lws_state_notify_link_t * const app_notifier_list[] = {
	&nl, NULL
};

#if defined(LWS_WITH_SYS_METRICS)

static int
my_metric_report(lws_metric_pub_t *mp)
{
	lws_metric_bucket_t *sub = mp->u.hist.head;
	char buf[192];

	do {
		if (lws_metrics_format(mp, &sub, buf, sizeof(buf)))
			lwsl_user("%s: %s\n", __func__, buf);
	} while ((mp->flags & LWSMTFL_REPORT_HIST) && sub);

	/* 0 = leave metric to accumulate, 1 = reset the metric */

	return 1;
}

static const lws_system_ops_t system_ops = {
	.metric_report = my_metric_report,
};

#endif

static void
sigint_handler(int sig)
{
	lwsl_notice("%s\n", __func__);
	interrupted = 1;
	lws_cancel_service(context);
}

int main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	const char *p;
	char *file_buf = NULL;
	int n = 0;
	(void)switches;

	if ((argc == 1) || lws_cmdline_option(argc, argv, switches[LWS_SW_HELP].sw)) {
		lws_switches_print_help(argv[0], switches, LWS_ARRAY_SIZE(switches));
		return 0;
	}


	lws_context_info_defaults(&info, NULL);lws_cmdline_option_handle_builtin(argc, argv, &info);

	signal(SIGINT, sigint_handler);

	/* connect to ssproxy via UDS by default, else via tcp with this port */
	if ((p = lws_cmdline_option(argc, argv, switches[LWS_SW_P].sw)))
		{
			int __pt = atoi(p);
			if (__pt < 0 || __pt > 65535) {
				lwsl_err("Port %d is outside valid 16-bit range\n", __pt);
				return 1;
			}
			port = __pt;
		}

	/* UDS "proxy.ss.lws" in abstract namespace, else this socket path;
	 * when -p given this can specify the network interface to bind to */
	if ((p = lws_cmdline_option(argc, argv, switches[LWS_SW_I].sw)))
		ibind = p;

	lwsl_user("LWS secure streams Proxy [-d<verb>]\n");

	info.fd_limit_per_thread = 1 + 26 + 1;
	info.port = CONTEXT_PORT_NO_LISTEN;
	if ((p = lws_cmdline_option(argc, argv, switches[LWS_SW_C].sw))) {
		int fd = open(p, O_RDONLY);
		if (fd >= 0) {
			size_t s = (size_t)lseek(fd, 0, SEEK_END);
			file_buf = malloc(s + 1);
			lseek(fd, 0, SEEK_SET);
			read(fd, file_buf, s);
			file_buf[s] = '\0';
			close(fd);
			info.pss_policies_json = file_buf;
		}
	} else {
		info.pss_policies_json = default_ss_policy;
	}
	
	info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
		       LWS_SERVER_OPTION_H2_JUST_FIX_WINDOW_UPDATE_OVERFLOW |
		       LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;

	/* integrate us with lws system state management when context created */
	nl.name = "app";
	nl.notify_cb = app_system_state_nf;
	info.register_notifier_list = app_notifier_list;

	info.pt_serv_buf_size = (unsigned int)((6144 * 2) + 2048);
	info.max_http_header_data = (unsigned short)(6144 + 2048);

#if defined(LWS_WITH_SYS_METRICS)
	info.system_ops = &system_ops;
	info.metrics_prefix = "ssproxy";
#endif

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

	/* the event loop */

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

	bad = 0;

#if defined(LWS_WITH_SECURE_STREAMS_AUTH_SIGV4)
	if (aws_keyid)
		free(aws_keyid);
	if (aws_key)
		free(aws_key);
#endif

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

	return bad;
}
