/*
 * lws-minimal-secure-streams
 *
 * 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 demonstrates various kinds of successful and failed connection
 * situations in order to confirm the correct states are coming.
 *
 * You can control how much bulk data is requested from the peer using
 * --amount xxx, the default without that is 12345 bytes.
 */

#include <libwebsockets.h>

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

static const struct lws_switches switches[] = {
	[LWS_SW_C]	= { "-c",              "Policy filepath" },
	[LWS_SW_AMOUNT]	= { "--amount",        "Amount of something" },
	[LWS_SW_A]	= { "-a",              "Enable -a feature" },
	[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>

static int interrupted, tests, tests_pass, tests_fail, doing_a_retry;
static lws_sorted_usec_list_t sul_next_test;
static lws_state_notify_link_t nl;
struct lws_context *context;
struct lws_ss_handle *h;
size_t amount = 12345;

static void
tests_start_next(lws_sorted_usec_list_t *sul);

/*
 * If the -proxy app is fulfilling our connection, then we don't need to have
 * the policy in the client.
 *
 * When we build with LWS_SS_USE_SSPC, the apis hook up to a proxy process over
 * a Unix Domain Socket.  To test that, you need to separately run the
 * ./lws-minimal-secure-streams-proxy test app on the same machine.
 */

#if !defined(LWS_SS_USE_SSPC)
static const char * const default_ss_policy =
	"{"
	  "\"release\":"			"\"01234567\","
	  "\"product\":"			"\"myproduct\","
	  "\"schema-version\":"			"1,"
#if defined(VIA_LOCALHOST_SOCKS)
	  "\"via-socks5\":"                     "\"127.0.0.1:1080\","
#endif

	  "\"retry\": ["	/* named backoff / retry strategies */
		"{\"default\": {"
			"\"backoff\": [	 1000, 1000 "
				"],"
			"\"conceal\":"		"2,"
			"\"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"
	"OlFuhjuef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bSMgHFzZM9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peV"
	"KVuRF4fn9tBb6dNqcmzU5L/qwIFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+Uh"
	"nMJbulHheb4mjUcAwhmahRWa6VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4c"
	"X8jJGKLhD+rcdqsq08p8kDi1L93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34Gf"
	"ID5yHI9Y/QCB/IIDEgEw+OyQmjgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAU"
	"wAwEB/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7I"
	"QTgoIMA0GCSqGSIb3DQEBCwUAA4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5"
	"IpDB/G/wkjUu0yKGX9rbxenDIU5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZ"
	"ERxhlbI1Bjjt/msv0tadQ1wUsN+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2"
	"V8viTO96LXFvKWlJbYK8U90vvo/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR"
	"1bldZwgJcJmApzyMZFo6IQ6XU5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob"
	"2xJNDd2ZhwLnoQdeXeGADbkpyrqXRfboQnoZsG4q5WTP468SQvvG5\"}"
	  "],"
	  "\"trust_stores\": [" /* named cert chains */
		"{"
			"\"name\": \"api_amazon_com\","
			"\"stack\": [\"digicert_global_ca_g2\", \"digicert_global_root_g2\"]"
		"}, { \"name\": \"arca1\", \"stack\": [\"amazon_root_ca_1\"]},"
		"{"
			"\"name\": \"le_via_isrg\","
			"\"stack\": ["
				"\"isrg_root_x1\","
				"\"isrg_root_x2\""
			"]"
		"}"
	  "],"
	  "\"s\": ["

		"{\"api_amazon_com_auth\": {"
			"\"endpoint\": \"api.amazon.com\","
			"\"port\": 443,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"POST\","
			"\"http_url\": \"auth/o2/token\","
			"\"plugins\": [],"
			"\"tls\": true,"
			"\"h2q_oflow_txcr\": true,"
			"\"http_www_form_urlencoded\": true,"
			"\"http_no_content_length\": true,"
			"\"retry\": \"default\","
			"\"tls_trust_store\": \"api_amazon_com\""
		"}},{"

		/*
		 * Just get a 200 from httpbin
		 * on h1:80, h1:443 and h2:443
		 *
		 * sanity check that we're working at all
		 */

		    "\"t_h1\": {"
			"\"endpoint\": \"127.0.0.1\","
			"\"port\": 7681,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/status/200\","
			"\"timeout_ms\": 10000,"
			"\"retry\": \"default\""
		"}},{"
		    "\"t_h1_tls\": {"
			"\"endpoint\": \"libwebsockets.org\","
			"\"port\": 443,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/httpbin/status/200\","
			"\"tls\": true,"
			"\"retry\": \"default\","
			"\"timeout_ms\": 10000,"
			"\"tls_trust_store\": \"le_via_isrg\""
		"}},{"
		    "\"t_h2_tls\": {"
			"\"endpoint\": \"libwebsockets.org\","
			"\"port\": 443,"
			"\"protocol\": \"h2\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/httpbin/status/200\","
			"\"tls\": true,"
			"\"nghttp2_quirk_end_stream\": true,"
			"\"h2q_oflow_txcr\": true,"
			"\"timeout_ms\": 10000,"
			"\"retry\": \"default\","
			"\"tls_trust_store\": \"le_via_isrg\""
		"}},{"

		/*
		 * 10s delayed response from httpbin.org
		 * on h1:80, h1:443 and h2:443
		 *
		 * used to trigger timeout testing
		 */

		    "\"d_h1\": {"
			"\"endpoint\": \"127.0.0.1\","
			"\"port\": 7681,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/delay/10\","
			"\"timeout_ms\": 3000,"
			"\"retry\": \"default\""
		"}},{"
		    "\"d_h1_tls\": {"
			"\"endpoint\": \"libwebsockets.org\","
			"\"port\": 443,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/httpbin/delay/10\","
			"\"tls\": true,"
			"\"timeout_ms\": 3000,"
			"\"retry\": \"default\","
			"\"tls_trust_store\": \"le_via_isrg\""
		"}},{"
		    "\"d_h2_tls\": {"
			"\"endpoint\": \"libwebsockets.org\","
			"\"port\": 443,"
			"\"protocol\": \"h2\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/httpbin/delay/15\","
			"\"tls\": true,"
			"\"nghttp2_quirk_end_stream\": true,"
			"\"h2q_oflow_txcr\": true,"
			"\"timeout_ms\": 3000,"
			"\"retry\": \"default\","
			"\"tls_trust_store\": \"le_via_isrg\""
		"}},{"

		/*
		 * get NXDOMAIN for bogus.nope
		 * on h1:80, h1:443 and h2:443
		 *
		 * Triggers unreachable and eventually all_retries_failed
		 */

		    "\"nxd_h1\": {"
			"\"endpoint\": \"bogus.nope\","
			"\"port\": 80,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/status/200\","
			"\"timeout_ms\": 5000,"
			"\"retry\": \"default\""
		"}},{"
		    "\"nxd_h1_tls\": {"
			"\"endpoint\": \"bogus.nope\","
			"\"port\": 443,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/status/200\","
			"\"tls\": true,"
			"\"timeout_ms\": 5000,"
			"\"retry\": \"default\","
			"\"tls_trust_store\": \"arca1\""
		"}},{"
		    "\"nxd_h2_tls\": {"
			"\"endpoint\": \"bogus.nope\","
			"\"port\": 443,"
			"\"protocol\": \"h2\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/status/200\","
			"\"tls\": true,"
			"\"nghttp2_quirk_end_stream\": true,"
			"\"h2q_oflow_txcr\": true,"
			"\"timeout_ms\": 5000,"
			"\"retry\": \"default\","
			"\"tls_trust_store\": \"arca1\""
		"}},{"

		/*
		 * bulk payload transfer from httpbin.org
		 * on h1:80, h1:443 and h2:443
		 *
		 * Sanity check larger payload
		 */

		    "\"bulk_h1\": {"
			"\"endpoint\": \"127.0.0.1\","
			"\"port\": 7681,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/bytes/${amount}\","
			"\"metadata\": [{"
					"\"amount\": \"\""
				"}],"
			"\"timeout_ms\": 10000,"
			"\"retry\": \"default\""
		"}},{"
		    "\"bulk_h1_tls\": {"
			"\"endpoint\": \"libwebsockets.org\","
			"\"port\": 443,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"httpbin/bytes/${amount}\","
			"\"metadata\": [{"
					"\"amount\": \"\""
				"}],"
			"\"tls\": true,"
			"\"timeout_ms\": 10000,"
			"\"retry\": \"default\","
			"\"tls_trust_store\": \"le_via_isrg\""
		"}},{"
		    "\"bulk_h2_tls\": {"
			"\"endpoint\": \"libwebsockets.org\","
			"\"port\": 443,"
			"\"protocol\": \"h2\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"httpbin/bytes/${amount}\","
			"\"metadata\": [{"
					"\"amount\": \"\""
				"}],"
			"\"tls\": true,"
			"\"nghttp2_quirk_end_stream\": true,"
			"\"h2q_oflow_txcr\": true,"
			"\"timeout_ms\": 10000,"
			"\"retry\": \"default\","
			"\"tls_trust_store\": \"le_via_isrg\""

		"}},{"

		/*
		 * Various kinds of tls failure
		 *
		 * hostname.badcert.warmcat.com: serves valid cert but for
		 *				 warmcat.com
		 *
		 * warmcat.com:446: serves valid but expired cert
		 *
		 * I don't have an easy way to make the test for "not valid yet"
		 * cert without root
		 *
		 * invalidca.badcert.warmcat.com:  selfsigned cert for that
		 *				   hostname
		 */

		    "\"badcert_hostname\": {"
			"\"endpoint\": \"hostname.badcert.warmcat.com\","
			"\"port\": 443,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/\","
			"\"tls\": true,"
			"\"timeout_ms\": 3000,"
			"\"retry\": \"default\","
			"\"tls_trust_store\": \"le_via_isrg\""
		"}},{"
		    "\"badcert_expired\": {"
			"\"endpoint\": \"warmcat.com\","
			"\"port\": 446,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/\","
			"\"tls\": true,"
			"\"retry\": \"default\","
			"\"timeout_ms\": 3000,"
			"\"tls_trust_store\": \"le_via_isrg\""
		"}},{"
		    "\"badcert_selfsigned\": {"
			"\"endpoint\": \"invalidca.badcert.warmcat.com\","
			"\"port\": 443,"
			"\"protocol\": \"h1\","
			"\"http_method\": \"GET\","
			"\"http_url\": \"/\","
			"\"tls\": true,"
			"\"nghttp2_quirk_end_stream\": true,"
			"\"h2q_oflow_txcr\": true,"
			"\"timeout_ms\": 5000,"
			"\"retry\": \"default\","
			"\"tls_trust_store\": \"le_via_isrg\""
                "}}"
	"]}"
;

#endif

/*
 * This is the sequence of test streams we are going to create, the ss timeout,
 * and a description of what we want to see to understand the test passed, or
 * failed.  If the test hits destruction without making a explicit pass or fail
 * decision before, that's a fail.  Or, depending on what state we put in
 * .must_see, we can count a state like UNREACHABLE as a pass.
 */

struct tests_seq {
	const char		*name;
	const char		*streamtype;
	uint64_t		timeout_us;
	lws_ss_constate_t	must_see;
	unsigned int		mask_unexpected;
	size_t			eom_pass;
} tests_seq[] = {

	/*
	 * We just get a 200 from httpbin.org as a sanity check first
	 */

	{
		"h1:80 just get 200",
		"t_h1", 15 * LWS_US_PER_SEC, LWSSSCS_QOS_ACK_REMOTE,
		(1 << LWSSSCS_TIMEOUT) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
					 (1 << LWSSSCS_ALL_RETRIES_FAILED),
		0
	},
	{
		"h1:443 just get 200",
		"t_h1_tls", 15 * LWS_US_PER_SEC, LWSSSCS_QOS_ACK_REMOTE,
		(1 << LWSSSCS_TIMEOUT) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
					 (1 << LWSSSCS_ALL_RETRIES_FAILED),
		0
	},
	{
		"h2:443 just get 200",
		"t_h2_tls", 15 * LWS_US_PER_SEC, LWSSSCS_QOS_ACK_REMOTE,
		(1 << LWSSSCS_TIMEOUT) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
					 (1 << LWSSSCS_ALL_RETRIES_FAILED),
		0
	},

	/*
	 * We arranged that the server will delay 10s before sending the
	 * response, but set our ss timeout for 5s.  So we expect to see
	 * our timeout and not an ACK / 200.
	 */

	{
		"h1:80 timeout after connection",
		"d_h1", 3 * LWS_US_PER_SEC, LWSSSCS_TIMEOUT,
		(1 << LWSSSCS_QOS_ACK_REMOTE) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
					 (1 << LWSSSCS_ALL_RETRIES_FAILED),
		0
	},
	{
		"h1:443 timeout after connection",
		"d_h1_tls", 3 * LWS_US_PER_SEC, LWSSSCS_TIMEOUT,
		(1 << LWSSSCS_QOS_ACK_REMOTE) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
					 (1 << LWSSSCS_ALL_RETRIES_FAILED),
		0
	},
	{
		"h2:443 timeout after connection",
		"d_h2_tls", 3 * LWS_US_PER_SEC, LWSSSCS_TIMEOUT,
		(1 << LWSSSCS_QOS_ACK_REMOTE) | (1 << LWSSSCS_QOS_NACK_REMOTE),
		0
	},

	/*
	 * We are talking to a nonexistant dns address "bogus.nope".  We expect
	 * in each case to hear that is unreachable, before any ss timeout.
	 */

	{
		"h1:80 NXDOMAIN",
		"nxd_h1", 35 * LWS_US_PER_SEC, LWSSSCS_UNREACHABLE,
		(1 << LWSSSCS_QOS_ACK_REMOTE) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
		(1 << LWSSSCS_TIMEOUT) | (1 << LWSSSCS_ALL_RETRIES_FAILED),
		0
	},
	{
		"h1:443 NXDOMAIN",
		"nxd_h1_tls", 35 * LWS_US_PER_SEC, LWSSSCS_UNREACHABLE,
		(1 << LWSSSCS_QOS_ACK_REMOTE) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
		(1 << LWSSSCS_TIMEOUT) | (1 << LWSSSCS_ALL_RETRIES_FAILED),
		0
	},
	{
		"h2:443 NXDOMAIN",
		"nxd_h2_tls", 35 * LWS_US_PER_SEC, LWSSSCS_UNREACHABLE,
		(1 << LWSSSCS_QOS_ACK_REMOTE) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
		(1 << LWSSSCS_TIMEOUT) | (1 << LWSSSCS_ALL_RETRIES_FAILED),
		0
	},

	/*
	 * We are talking to a nonexistant dns address "bogus.nope".  We expect
	 * that if we stick around longer, retries will also end up all failing.
	 * We might see the timeout depending on blocking getaddrinfo
	 * behaviour.
	 */

	{
		"h1:80 NXDOMAIN exhaust retries",
		"nxd_h1", 35 * LWS_US_PER_SEC, LWSSSCS_ALL_RETRIES_FAILED,
		(1 << LWSSSCS_QOS_ACK_REMOTE) | (1 << LWSSSCS_QOS_NACK_REMOTE),
		0
	},
	{
		"h1:443 NXDOMAIN exhaust retries",
		"nxd_h1_tls", 35 * LWS_US_PER_SEC, LWSSSCS_ALL_RETRIES_FAILED,
		(1 << LWSSSCS_QOS_ACK_REMOTE) | (1 << LWSSSCS_QOS_NACK_REMOTE),
		0
	},
	{
		"h2:443 NXDOMAIN exhaust retries",
		"nxd_h2_tls", 25 * LWS_US_PER_SEC, LWSSSCS_ALL_RETRIES_FAILED,
		(1 << LWSSSCS_QOS_ACK_REMOTE) | (1 << LWSSSCS_QOS_NACK_REMOTE),
		0
	},

	/*
	 * Let's request some bulk data from httpbin.org
	 */

	{
		"h1:80 read bulk",
		"bulk_h1", 5 * LWS_US_PER_SEC, LWSSSCS_QOS_ACK_REMOTE,
		(1 << LWSSSCS_TIMEOUT) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
		(1 << LWSSSCS_ALL_RETRIES_FAILED),
		12345
	},
	{
		"h1:443 read bulk",
		"bulk_h1_tls", 5 * LWS_US_PER_SEC, LWSSSCS_QOS_ACK_REMOTE,
		(1 << LWSSSCS_TIMEOUT) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
		(1 << LWSSSCS_ALL_RETRIES_FAILED),
		12345
	},
	{
		"h2:443 read bulk",
		"bulk_h2_tls", 5 * LWS_US_PER_SEC, LWSSSCS_QOS_ACK_REMOTE,
		(1 << LWSSSCS_TIMEOUT) | (1 << LWSSSCS_QOS_NACK_REMOTE) |
		(1 << LWSSSCS_ALL_RETRIES_FAILED),
		12345
	},

	/*
	 * Let's fail at the tls negotiation various ways
	 */

	{
		"h1:badcert_hostname",
		"badcert_hostname", 35 * LWS_US_PER_SEC, LWSSSCS_ALL_RETRIES_FAILED,
		(1 << LWSSSCS_QOS_NACK_REMOTE),
		0
	},
	{
		"h1:badcert_expired",
		"badcert_expired", 35 * LWS_US_PER_SEC, LWSSSCS_ALL_RETRIES_FAILED,
		(1 << LWSSSCS_QOS_NACK_REMOTE),
		0
	},
	{
		"h1:badcert_selfsigned",
		"badcert_selfsigned", 35 * LWS_US_PER_SEC, LWSSSCS_ALL_RETRIES_FAILED,
		(1 << LWSSSCS_QOS_NACK_REMOTE),
		0
	},

};

typedef struct myss {
	struct lws_ss_handle 		*ss;
	void				*opaque_data;

	size_t				rx_seen;
	lws_usec_t			start_us;
	char				result_reported;
} myss_t;


/* secure streams payload interface */

static lws_ss_state_return_t
myss_rx(void *userobj, const uint8_t *buf, size_t len, int flags)
{
	myss_t *m = (myss_t *)userobj;

	m->rx_seen += len;

	if (flags & LWSSS_FLAG_EOM)
		lwsl_notice("%s: %s len %d, fl %d, received %u bytes\n",
				__func__, lws_ss_tag(m->ss), (int)len, flags,
				(unsigned int)m->rx_seen);

	return 0;
}

static lws_ss_state_return_t
myss_tx(void *userobj, lws_ss_tx_ordinal_t ord, uint8_t *buf, size_t *len,
	int *flags)
{
	//myss_t *m = (myss_t *)userobj;

	/* in this example, we don't send stuff */

	return LWSSSSRET_TX_DONT_SEND;
}

static lws_ss_state_return_t
myss_state(void *userobj, void *sh, lws_ss_constate_t state,
	   lws_ss_tx_ordinal_t ack)
{
	myss_t *m = (myss_t *)userobj;
	struct tests_seq *curr_test = (	struct tests_seq *)m->opaque_data;
	char buf[8];
	size_t sl;

	lwsl_info("%s: %s: %s, ord 0x%x\n", __func__, lws_ss_tag(m->ss),
		  lws_ss_state_name(state), (unsigned int)ack);

	if (curr_test->mask_unexpected & (1u << state)) {

		/*
		 * We have definitively failed on an unexpected state received
		 */

		lwsl_warn("%s: ======= FAILING ON UNEXPECTED STATE %s\n",
				__func__, lws_ss_state_name(state));

		m->result_reported = 1;
		tests_fail++;
		/* we'll start the next test next time around the event loop */
		lws_sul_schedule(context, 0, &sul_next_test, tests_start_next, 1);

		h = NULL;
		return LWSSSSRET_DESTROY_ME;
	}

	if (state == curr_test->must_see) {

		if (curr_test->eom_pass != m->rx_seen) {
			lwsl_notice("%s: failing on rx %d, expected %d\n",
				    __func__, (int)m->rx_seen,
				    (int)curr_test->eom_pass);
			m->result_reported = 1;
			tests_fail++;
			lws_sul_schedule(context, 0, &sul_next_test, tests_start_next, 1);
			h = NULL;
			return LWSSSSRET_DESTROY_ME;
		}

		lwsl_warn("%s: ++++++++ saw expected state %s\n",
				__func__, lws_ss_state_name(state));
		m->result_reported = 1;
		tests_pass++;
		/* we'll start the next test next time around the event loop */
		lws_sul_schedule(context, 0, &sul_next_test, tests_start_next, 1);

		if (state == LWSSSCS_TIMEOUT ||
		    state == LWSSSCS_ALL_RETRIES_FAILED) {
			h = NULL;
			return LWSSSSRET_DESTROY_ME;
		}

		return LWSSSSRET_OK;
	}

	switch (state) {
	case LWSSSCS_CONNECTED:
		lwsl_notice("%s: CONNECTED\n", __func__);
		{
			lws_usec_t used = lws_now_usecs() - m->start_us;
			unsigned int remaining;

			if (used > (lws_usec_t)curr_test->timeout_us) {
				if (curr_test->must_see == LWSSSCS_TIMEOUT ||
				    (curr_test->must_see == LWSSSCS_ALL_RETRIES_FAILED)) {
					lwsl_notice("%s: ++++++++ saw expected state %s (manual)\n", __func__, lws_ss_state_name(curr_test->must_see));
					tests_pass++;
				} else {
					lwsl_notice("%s: timeout exceeded (must scan %d)\n", __func__, (int)curr_test->must_see);
					tests_fail++;
				}
				m->result_reported = 1;
				lws_sul_schedule(context, 0, &sul_next_test, tests_start_next, 1);
				h = NULL;
				return LWSSSSRET_DESTROY_ME;
			}

			remaining = (unsigned int)(((lws_usec_t)curr_test->timeout_us - used) / LWS_US_PER_MS);
			if (!remaining)
				remaining = 1;

			lws_ss_start_timeout(m->ss, remaining);
		}
		break;
	case LWSSSCS_CONNECTING:
	case LWSSSCS_CREATING:
		if (state == LWSSSCS_CREATING) {
			if (!m->start_us)
				m->start_us = lws_now_usecs();
			lws_ss_start_timeout(m->ss,
				(unsigned int)(curr_test->timeout_us / LWS_US_PER_MS));
		} else {
			lws_usec_t used = lws_now_usecs() - m->start_us;
			unsigned int remaining;

			if (used > (lws_usec_t)curr_test->timeout_us) {
				if (curr_test->must_see == LWSSSCS_TIMEOUT ||
				    (curr_test->must_see == LWSSSCS_ALL_RETRIES_FAILED)) {
					lwsl_notice("%s: ++++++++ saw expected state %s (manual)\n", __func__, lws_ss_state_name(curr_test->must_see));
					tests_pass++;
				} else {
					lwsl_notice("%s: timeout exceeded (must scan %d)\n", __func__, (int)curr_test->must_see);
					tests_fail++;
				}
				m->result_reported = 1;
				lws_sul_schedule(context, 0, &sul_next_test, tests_start_next, 1);
				h = NULL;
				return LWSSSSRET_DESTROY_ME;
			}

			remaining = (unsigned int)(((lws_usec_t)curr_test->timeout_us - used) / LWS_US_PER_MS);
			if (!remaining)
				remaining = 1;

			lws_ss_start_timeout(m->ss, remaining);
		}

		if (curr_test->eom_pass) {
			sl = (size_t)lws_snprintf(buf, sizeof(buf), "%u",
					(unsigned int)curr_test->eom_pass);
			if (lws_ss_set_metadata(m->ss, "amount", buf, sl))
				return LWSSSSRET_DISCONNECT_ME;
		}
		if (state == LWSSSCS_CREATING)
			return lws_ss_client_connect(m->ss);
		break;

	case LWSSSCS_DESTROYING:
		lwsl_notice("%s: DESTROYING, res_rep %d, retry %d\n", __func__, m->result_reported, doing_a_retry);
		if (!m->result_reported && !doing_a_retry) {
			lwsl_notice("%s: failing on unexpected destruction\n",
					__func__);

			tests_fail++;
			/* we'll start the next test next time around the event loop */
			lws_sul_schedule(context, 0, &sul_next_test, tests_start_next, 1);
		}
		break;

	default:
		break;
	}

	if (state == LWSSSCS_TIMEOUT)
		return LWSSSSRET_DISCONNECT_ME;

	return LWSSSSRET_OK;
}

static void
tests_start_next(lws_sorted_usec_list_t *sul)
{
	struct tests_seq *ts;
	lws_ss_info_t ssi;

	/* destroy the old one */

	if (h) {
		lwsl_info("%s: destroying previous stream\n", __func__);
		lws_ss_destroy(&h);
	}

	doing_a_retry = 0;

	if ((unsigned int)tests >= LWS_ARRAY_SIZE(tests_seq)) {
		lwsl_notice("Completed all tests\n");
		interrupted = 1;
		return;
	}

	ts = &tests_seq[tests++];

	/* Create the next test stream */

	memset(&ssi, 0, sizeof(ssi));
	ssi.handle_offset = offsetof(myss_t, ss);
	ssi.opaque_user_data_offset = offsetof(myss_t, opaque_data);
	ssi.rx = myss_rx;
	ssi.tx = myss_tx;
	ssi.state = myss_state;
	ssi.user_alloc = sizeof(myss_t);
	ssi.streamtype = ts->streamtype;

	lwsl_user("%s: %d: %s\n", __func__, tests, ts->name);

	if (lws_ss_create(context, 0, &ssi, ts, &h, NULL, NULL)) {
		lwsl_err("%s: failed to create secure stream\n",
			 __func__);
		tests_fail++;
		interrupted = 1;
		return;
	}
}

static int
app_system_state_nf(lws_state_manager_t *mgr, lws_state_notify_link_t *link,
		    int current, int target)
{
	switch (target) {

	case LWS_SYSTATE_OPERATIONAL:
		if (current == LWS_SYSTATE_OPERATIONAL)
			/* we'll start the next test next time around the event loop */
			lws_sul_schedule(context, 0, &sul_next_test, tests_start_next, 1);
		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)
{
	interrupted = 1;
}

int
main(int argc, const char **argv)
{
	struct lws_context_creation_info info;
	const char *pp;
	(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;
	}


	signal(SIGINT, sigint_handler);

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

	if ((pp = lws_cmdline_option(argc, argv, switches[LWS_SW_AMOUNT].sw)))
		amount = (size_t)atoi(pp);

	/* set the expected payload for the bulk-related tests to amount */

	tests_seq[12].eom_pass = tests_seq[13].eom_pass =
					tests_seq[14].eom_pass = amount;
#if !defined(LWS_SS_USE_SSPC)
	if ((pp = lws_cmdline_option(argc, argv, switches[LWS_SW_C].sw))) {
		info.pss_policies_json = pp;
	} else {
		info.pss_policies_json = default_ss_policy;
	}
#endif

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

	info.fd_limit_per_thread = 1 + 16 + 1;
	info.port = CONTEXT_PORT_NO_LISTEN;
	info.connect_timeout_secs = 15;
	info.timeout_secs = 10;
#if defined(LWS_SS_USE_SSPC)
	info.protocols = lws_sspc_protocols;
	{
		const char *p;

		/* connect to ssproxy via UDS by default, else via
		 * tcp connection to 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;
				}
				info.ss_proxy_port = (uint16_t)__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)))
			info.ss_proxy_bind = p;

		/* if -p given, -a specifies the proxy address to connect to */
		if ((p = lws_cmdline_option(argc, argv, switches[LWS_SW_A].sw)))
			info.ss_proxy_address = p;
	}
#else
	info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
		       LWS_SERVER_OPTION_H2_JUST_FIX_WINDOW_UPDATE_OVERFLOW |
		       LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
#endif

	/* 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;

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

	/* create the context */

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

	/* the event loop */

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

	lws_context_destroy(context);

	lwsl_user("Completed: %s (pass %d, fail %d)\n",
		  tests_pass == tests && !tests_fail ? "OK" : "failed",
				  tests_pass, tests_fail);

	return !(tests_pass == tests && !tests_fail);
}
