• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * lws-minimal-secure-streams
3  *
4  * Written in 2010-2021 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  *
10  * This demonstrates a minimal http client using secure streams api.
11  *
12  * It visits https://warmcat.com/ and receives the html page there.
13  *
14  * This example is built two different ways from the same source... one includes
15  * the policy everything needed to fulfil the stream directly.  The other -client
16  * variant has no policy itself and some other minor init changes, and connects
17  * to the -proxy example to actually get the connection done.
18  *
19  * In the -client build case, the example does not even init the tls libraries
20  * since the proxy part will take care of all that.
21  */
22 
23 #include <libwebsockets.h>
24 #include <string.h>
25 #include <signal.h>
26 
27 // #define FORCE_OS_TRUST_STORE
28 
29 /*
30  * uncomment to force network traffic through 127.0.0.1:1080
31  *
32  * On your local machine, you can run a SOCKS5 proxy like this
33  *
34  * $ ssh -N -D 0.0.0.0:1080 localhost -v
35  *
36  * If enabled, this also fetches a remote policy that also
37  * specifies that all traffic should go through the remote
38  * proxy.
39  */
40 // #define VIA_LOCALHOST_SOCKS
41 
42 static int interrupted, bad = 1, force_cpd_fail_portal,
43 	   force_cpd_fail_no_internet, test_respmap, test_ots, test_local;
44 static unsigned int timeout_ms = 3000;
45 static lws_state_notify_link_t nl;
46 
47 /*
48  * If the -proxy app is fulfilling our connection, then we don't need to have
49  * the policy in the client.
50  *
51  * When we build with LWS_SS_USE_SSPC, the apis hook up to a proxy process over
52  * a Unix Domain Socket.  To test that, you need to separately run the
53  * ./lws-minimal-secure-streams-proxy test app on the same machine.
54  */
55 
56 #if !defined(LWS_SS_USE_SSPC)
57 static const char * const default_ss_policy =
58 	"{"
59 	  "\"release\":"			"\"01234567\","
60 	  "\"product\":"			"\"myproduct\","
61 	  "\"schema-version\":"			"1,"
62 #if defined(VIA_LOCALHOST_SOCKS)
63 	  "\"via-socks5\":"                     "\"127.0.0.1:1080\","
64 #endif
65 
66 	  "\"retry\": ["	/* named backoff / retry strategies */
67 		"{\"default\": {"
68 			"\"backoff\": ["	 "1000,"
69 						 "2000,"
70 						 "3000,"
71 						 "5000,"
72 						"10000"
73 				"],"
74 			"\"conceal\":"		"5,"
75 			"\"jitterpc\":"		"20,"
76 			"\"svalidping\":"	"30,"
77 			"\"svalidhup\":"	"35"
78 		"}}"
79 	  "],"
80 	  "\"certs\": [" /* named individual certificates in BASE64 DER */
81 		/*
82 		 * Let's Encrypt certs for warmcat.com / libwebsockets.org
83 		 *
84 		 * We fetch the real policy from there using SS and switch to
85 		 * using that.
86 		 */
87 #if !defined(FORCE_OS_TRUST_STORE)
88 	  		"{\"isrg_root_x1\": \""
89 	"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw"
90 	"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh"
91 	"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4"
92 	"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu"
93 	"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY"
94 	"MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc"
95 	"h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+"
96 	"0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U"
97 	"A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW"
98 	"T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH"
99 	"B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC"
100 	"B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv"
101 	"KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn"
102 	"OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn"
103 	"jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw"
104 	"qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI"
105 	"rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV"
106 	"HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq"
107 	"hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL"
108 	"ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ"
109 	"3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK"
110 	"NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5"
111 	"ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur"
112 	"TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC"
113 	"jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc"
114 	"oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq"
115 	"4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA"
116 	"mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d"
117 	"emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc="
118 		"\"}"
119 #endif
120 	  "],"
121 	  "\"trust_stores\": [" /* named cert chains */
122 #if !defined(FORCE_OS_TRUST_STORE)
123 		"{"
124 			"\"name\": \"le_via_isrg\","
125 			"\"stack\": ["
126 				"\"isrg_root_x1\""
127 			"]"
128 		"}"
129 #endif
130 	  "],"
131 	  "\"s\": ["
132 #if !defined(LWS_WITH_SS_DIRECT_PROTOCOL_STR)
133 		/*
134 		 * "fetch_policy" decides from where the real policy
135 		 * will be fetched, if present.  Otherwise the initial
136 		 * policy is treated as the whole, hardcoded, policy.
137 		 */
138 		"{\"fetch_policy\": {"
139 			"\"endpoint\":"		"\"warmcat.com\","
140 			"\"port\":"		"443,"
141 			"\"protocol\":"		"\"h1\","
142 			"\"http_method\":"	"\"GET\","
143 #if defined(VIA_LOCALHOST_SOCKS)
144 			"\"http_url\":"		"\"policy/minimal-proxy-socks.json\","
145 #else
146 			"\"http_url\":"		"\"policy/minimal-proxy-v4.2-v2.json\","
147 #endif
148 			"\"tls\":"		"true,"
149 			"\"opportunistic\":"	"true,"
150 #if !defined(FORCE_OS_TRUST_STORE)
151 			"\"tls_trust_store\":"	"\"le_via_isrg\","
152 #endif
153 			"\"retry\":"		"\"default\""
154 #else
155 	"{\"mintest\": {"
156 			"\"endpoint\":  \"warmcat.com\","
157 			"\"port\": 443,"
158 			"\"protocol\": \"h1\","
159 			"\"http_method\": \"GET\","
160 			"\"http_url\": \"index.html?uptag=${uptag}\","
161 			"\"metadata\": [{"
162 			"	\"uptag\": \"X-Upload-Tag:\""
163 			"}, {"
164 			"	\"xctype\": \"X-Content-Type:\""
165 			"}],"
166 			"\"tls\": true,"
167 			"\"opportunistic\": true,"
168 			"\"retry\": \"default\","
169 			"\"timeout_ms\": 2000,"
170 			"\"direct_proto_str\": true,"
171 			"\"tls_trust_store\": \"le_via_dst\""
172 		"}},"
173 	"{\"mintest_local\": {"
174 			"\"endpoint\":  \"localhost\","
175 			"\"port\": 8000,"
176 			"\"protocol\": \"h1\","
177 			"\"http_method\": \"GET\","
178 			"\"tls\": false,"
179 			"\"opportunistic\": true,"
180 			"\"retry\": \"default\","
181 			"\"timeout_ms\": 2000,"
182 			"\"direct_proto_str\": true"
183 #endif
184 		"}},{"
185 			/*
186 			 * "captive_portal_detect" describes
187 			 * what to do in order to check if the path to
188 			 * the Internet is being interrupted by a
189 			 * captive portal.  If there's a larger policy
190 			 * fetched from elsewhere, it should also include
191 			 * this since it needs to be done at least after
192 			 * every DHCP acquisition
193 			 */
194 		    "\"captive_portal_detect\": {"
195                         "\"endpoint\": \"connectivitycheck.android.com\","
196 			"\"http_url\": \"generate_204\","
197 			"\"port\": 80,"
198                         "\"protocol\": \"h1\","
199                         "\"http_method\": \"GET\","
200                         "\"opportunistic\": true,"
201                         "\"http_expect\": 204,"
202 			"\"http_fail_redirect\": true"
203                 "}}"
204 	"]}"
205 ;
206 
207 #endif
208 
209 typedef struct myss {
210 	struct lws_ss_handle		*ss;
211 	void				*opaque_data;
212 	/* ... application specific state ... */
213 	lws_sorted_usec_list_t		sul;
214 	size_t				amt;
215 
216 	struct lws_genhash_ctx		hash_ctx;
217 } myss_t;
218 
219 #if !defined(LWS_SS_USE_SSPC)
220 
221 static const char *canned_root_token_payload =
222 	"grant_type=refresh_token"
223 	"&refresh_token=Atzr|IwEBIJedGXjDqsU_vMxykqOMg"
224 	"SHfYe3CPcedueWEMWSDMaDnEmiW8RlR1Kns7Cb4B-TOSnqp7ifVsY4BMY2B8tpHfO39XP"
225 	"zfu9HapGjTR458IyHX44FE71pWJkGZ79uVBpljP4sazJuk8XS3Oe_yLnm_DIO6fU1nU3Y"
226 	"0flYmsOiOAQE_gRk_pdlmEtHnpMA-9rLw3mkY5L89Ty9kUygBsiFaYatouROhbsTn8-jW"
227 	"k1zZLUDpT6ICtBXSnrCIg0pUbZevPFhTwdXd6eX-u4rq0W-XaDvPWFO7au-iPb4Zk5eZE"
228 	"iX6sissYrtNmuEXc2uHu7MnQO1hHCaTdIO2CANVumf-PHSD8xseamyh04sLV5JgFzY45S"
229 	"KvKMajiUZuLkMokOx86rjC2Hdkx5DO7G-dbG1ufBDG-N79pFMSs7Ck5pc283IdLoJkCQc"
230 	"AGvTX8o8I29QqkcGou-9TKhOJmpX8As94T61ok0UqqEKPJ7RhfQHHYdCtsdwxgvfVr9qI"
231 	"xL_hDCcTho8opCVX-6QhJHl6SQFlTw13"
232 	"&client_id="
233 		"amzn1.application-oa2-client.4823334c434b4190a2b5a42c07938a2d";
234 
235 #endif
236 
237 /* secure streams payload interface */
238 
239 static lws_ss_state_return_t
myss_rx(void * userobj,const uint8_t * buf,size_t len,int flags)240 myss_rx(void *userobj, const uint8_t *buf, size_t len, int flags)
241 {
242 
243 	if (flags & LWSSS_FLAG_PERF_JSON)
244 		return LWSSSSRET_OK;
245 
246 #if !defined(LWS_WITH_SS_DIRECT_PROTOCOL_STR)
247 	myss_t *m = (myss_t *)userobj;
248 	const char *md_srv = "not set", *md_test = "not set";
249 	size_t md_srv_len = 7, md_test_len = 7;
250 
251 	lws_ss_get_metadata(m->ss, "srv", (const void **)&md_srv, &md_srv_len);
252 	lws_ss_get_metadata(m->ss, "test", (const void **)&md_test, &md_test_len);
253 	lwsl_user("%s: len %d, flags: %d, srv: %.*s, test: %.*s\n", __func__,
254 		  (int)len, flags, (int)md_srv_len, md_srv,
255 		  (int)md_test_len, md_test);
256 
257 	lwsl_hexdump_info(buf, len);
258 #endif
259 
260 	/*
261 	 * If we received the whole message, for our example it means
262 	 * we are done.
263 	 */
264 	if (flags & LWSSS_FLAG_EOM) {
265 		bad = 0;
266 		interrupted = 1;
267 	}
268 
269 	return LWSSSSRET_OK;
270 }
271 
272 static lws_ss_state_return_t
myss_tx(void * userobj,lws_ss_tx_ordinal_t ord,uint8_t * buf,size_t * len,int * flags)273 myss_tx(void *userobj, lws_ss_tx_ordinal_t ord, uint8_t *buf, size_t *len,
274 	int *flags)
275 {
276 	//myss_t *m = (myss_t *)userobj;
277 
278 	/* in this example, we don't send stuff */
279 
280 	return LWSSSSRET_TX_DONT_SEND;
281 }
282 
283 #if defined(LWS_WITH_SS_DIRECT_PROTOCOL_STR)
284 static const char * long_token_str = "{xxx:AWlKJMMISWJBQpAFqU0UqKNsnSY5usx2YtjOZJUQALNtapRxu/9VJqMk5IFVhxrNvMTj+RCGN6B5OlUK80lbbC8fAmQi7SoFB8DHN9UCRHkENriC62FjMNiBVfgkjMWx+60GioZy4bI2kCcyisd2CujQuSVllUmQFXhVq291cJhFfcKR4c3CUCuhouUfK2e1BY5InDMnzUXozOh+vhjJSeBIfp4HRUAgMpV7FXlHy8D5tgbmPbHs9X81MEsHTcERd3pG10B5fu1PzH+dJbr5F2WTK+VFWZI99B89ijEZWsPg447IK3F+0HHGseZfpRjKw2bY94id/TmncTxS0cqchDJlYg+Jt33U4HkUPqLdRiGIfJb6wSATx4S9ZKUumeJAgXpC6ytlUeqPpxzgnD7Tle5CDVb+eVzRk2FJfjiZdjbYxXhWYntPusLP/PGrorkqLw0ZKw+OJ+fhbkwF+0SCUelWEc8WPtfxCDAIdEQ7X5P4vUlBNEfuHprgHbZry680syFetY2q3ZtCmWemLHhqdDGu4lFgcQPCbb9b8eOE8oAbUQPm9AeV84RXSLevBG44JST/W2JuYguOk8SFlsRkfHb3dvxfB15Lg+mtH0tGRoumSMT0CFJL4ClTiKdpJo1LPgEd2/f13GcukEWirjqDRxpepJYWaVAMbxbaPBNfRHw9S8Fn8qU9/9eAxmbEqOopep5I/Zd99CT2PdE0Qyami1p05/BEc5dgvjg3SNDmAc/8kWC0AcvoSfApXI1TaVzbNh68b79h6IaIvXXorY5274u0lVB357JIRiYo29QbJgNn4bDbIr5ScM8GnFHQdKy29/TZoq4zbGMPX2X2t41vXRVeoZteu7vNWsMQD6eIomVq9qFWnoEEaR30woGF+8ZSIEu9JH5LKVZVFx46lipnjE8CDt5qrYCjwiGIswdLLMmIltxRmDt4aefTFpre7lhgUChv7ndJARvsn8rvtg2Hg1qKyfCAHa/LBblM29cRjLFqp7tWLJO7N27SWiqEhai6pmSmSYzqoPL+rnLS69rkdIuUwkA==}{yyy:jG8akvr66AXK+W1KSUyGIN3Yk4WNRLSIZHWTu8rsvQAuKwv9a/ZxrxIa+R1xW7cwmPSgINcJ4Jo7kGK9n7aDnsSDt3uMSHsu2iNg+UtIaJcO0XO6fPaLmOPLpOIU5AfG9HnbWUjeniNRrUGN8+26JH/9EB1h/X++Ow61CCHm8mKrgR1lXsKuNyqDYIrjoI3KCCVKZkdWygyFAXQ6l0sr+pUyNpv6H5w1xlC8dtI88091b/njuRlHsnoCa1zRtgqH0L4igLNu0zzOkH/ATsVS3Pyn4nsoRiGVFgzJZ0e2jT2McmDTxNeEHcafQSxeN7pztDFHT3ukUU9QFFtFDdzlug==}{vvv:VGbzgaVrLrJ+92ACJ0TEtQ==}{eeee:QURQVG9rZW6FbmNyeXB0aW6uS2v5}{sssss:mG+}";
285 #endif
286 
287 static lws_ss_state_return_t
myss_state(void * userobj,void * sh,lws_ss_constate_t state,lws_ss_tx_ordinal_t ack)288 myss_state(void *userobj, void *sh, lws_ss_constate_t state,
289 	   lws_ss_tx_ordinal_t ack)
290 {
291 	myss_t *m = (myss_t *)userobj;
292 #if defined(LWS_WITH_SS_DIRECT_PROTOCOL_STR)
293 	const char *md_test = "not set";
294 	size_t md_test_len = 7;
295 	int i;
296 	static const char * imd_test_keys[8] = {
297 		"server:",
298 		"content-security-policy:",
299 		"strict-transport-security:",
300 		"test-custom-header:",
301 		"x-xss-protection:",
302 		"x-content-type-options:",
303 		"x-frame-options:",
304 		"x-non-exist:",
305 		};
306 #endif
307 
308 	lwsl_user("%s: %s (%d), ord 0x%x\n", __func__,
309 		  lws_ss_state_name((int)state), state, (unsigned int)ack);
310 
311 	switch (state) {
312 	case LWSSSCS_CREATING:
313 		return lws_ss_client_connect(m->ss);
314 
315 	case LWSSSCS_CONNECTING:
316 		lws_ss_start_timeout(m->ss, timeout_ms);
317 
318 		if (lws_ss_set_metadata(m->ss, "uptag", "myuptag123", 10))
319 			/* can fail, eg due to OOM, retry later if so */
320 			return LWSSSSRET_DISCONNECT_ME;
321 #if !defined(LWS_WITH_SS_DIRECT_PROTOCOL_STR)
322 		if (lws_ss_set_metadata(m->ss, "ctype", "myctype", 7))
323 			/* can fail, eg due to OOM, retry later if so */
324 			return LWSSSSRET_DISCONNECT_ME;
325 #else
326 		if (lws_ss_set_metadata(m->ss, "X-Test-Type1:", "myctype1", 8))
327 			/* can fail, eg due to OOM, retry later if so */
328 			return LWSSSSRET_DISCONNECT_ME;
329 		if (lws_ss_set_metadata(m->ss, "X-Test-Type2:", "myctype2", 8))
330 			/* can fail, eg due to OOM, retry later if so */
331 			return LWSSSSRET_DISCONNECT_ME;
332 		if (lws_ss_set_metadata(m->ss, "Content-Type:", "myctype", 7))
333 			/* can fail, eg due to OOM, retry later if so */
334 			return LWSSSSRET_DISCONNECT_ME;
335 		if (lws_ss_set_metadata(m->ss, "X-ADP-Authentication-Token:",
336 					long_token_str, strlen(long_token_str)))
337 			/* can fail, eg due to OOM, retry later if so */
338 			return LWSSSSRET_DISCONNECT_ME;
339 
340 #endif
341 		break;
342 
343 	case LWSSSCS_ALL_RETRIES_FAILED:
344 		/* if we're out of retries, we want to close the app and FAIL */
345 		interrupted = 1;
346 		bad = 2;
347 		break;
348 	case LWSSSCS_CONNECTED:
349 #if defined(LWS_WITH_SS_DIRECT_PROTOCOL_STR)
350 	lwsl_user("%s: get direct metadata\n", __func__);
351 	for (i = 0; i < 8; i++) {
352 		md_test = "not set";
353 		lws_ss_get_metadata(m->ss, imd_test_keys[i], (const void **)&md_test, &md_test_len);
354 		lwsl_user("%s test key:[%s], got [%s]\n", __func__, imd_test_keys[i], md_test);
355 	}
356 #endif
357 		break;
358 
359 	case LWSSSCS_QOS_ACK_REMOTE:
360 		lwsl_notice("%s: LWSSSCS_QOS_ACK_REMOTE\n", __func__);
361 		break;
362 
363 	case LWSSSCS_TIMEOUT:
364 		lwsl_notice("%s: LWSSSCS_TIMEOUT\n", __func__);
365 		/* if we're out of time */
366 		interrupted = 1;
367 		bad = 3;
368 		break;
369 
370 	case LWSSSCS_USER_BASE:
371 		lwsl_notice("%s: LWSSSCS_USER_BASE\n", __func__);
372 		break;
373 
374 	default:
375 		break;
376 	}
377 
378 	return LWSSSSRET_OK;
379 }
380 
381 #if defined(LWS_WITH_SECURE_STREAMS_BUFFER_DUMP)
382 static void
myss_headers_dump(void * userobj,const uint8_t * buf,size_t len,int done)383 myss_headers_dump(void *userobj, const uint8_t *buf, size_t len, int done)
384 {
385 	lwsl_user("%s: %lu done: %s\n", __func__, len, done?"true":"false");
386 
387 	lwsl_hexdump_err(buf, len);
388 }
389 #endif
390 static int
app_system_state_nf(lws_state_manager_t * mgr,lws_state_notify_link_t * link,int current,int target)391 app_system_state_nf(lws_state_manager_t *mgr, lws_state_notify_link_t *link,
392 		    int current, int target)
393 {
394 	struct lws_context *context = lws_system_context_from_system_mgr(mgr);
395 #if !defined(LWS_SS_USE_SSPC)
396 
397 	lws_system_blob_t *ab = lws_system_get_blob(context,
398 				LWS_SYSBLOB_TYPE_AUTH, 1 /* AUTH_IDX_ROOT */);
399 	size_t size;
400 #endif
401 
402 	/*
403 	 * For the things we care about, let's notice if we are trying to get
404 	 * past them when we haven't solved them yet, and make the system
405 	 * state wait while we trigger the dependent action.
406 	 */
407 	switch (target) {
408 
409 #if !defined(LWS_SS_USE_SSPC)
410 
411 	/*
412 	 * The proxy takes responsibility for this stuff if we get things
413 	 * done through that
414 	 */
415 
416 	case LWS_SYSTATE_INITIALIZED: /* overlay on the hardcoded policy */
417 	case LWS_SYSTATE_POLICY_VALID: /* overlay on the loaded policy */
418 
419 		if (target != current)
420 			break;
421 
422 		if (force_cpd_fail_portal)
423 
424 			/* this makes it look like we're behind a captive portal
425 			 * because the overriden address does a redirect */
426 
427 			lws_ss_policy_overlay(context,
428 				      "{\"s\": [{\"captive_portal_detect\": {"
429 				         "\"endpoint\": \"google.com\","
430 					 "\"http_url\": \"/\","
431 					 "\"port\": 80"
432 				      "}}]}");
433 
434 		if (force_cpd_fail_no_internet)
435 
436 			/* this looks like no internet, because the overridden
437 			 * port doesn't have anything that will connect to us */
438 
439 			lws_ss_policy_overlay(context,
440 				      "{\"s\": [{\"captive_portal_detect\": {"
441 					 "\"endpoint\": \"warmcat.com\","
442 					 "\"http_url\": \"/\","
443 					 "\"port\": 999"
444 				      "}}]}");
445 		break;
446 
447 	case LWS_SYSTATE_REGISTERED:
448 		size = lws_system_blob_get_size(ab);
449 		if (size)
450 			break;
451 
452 		/* let's register our canned root token so auth can use it */
453 		lws_system_blob_direct_set(ab,
454 				(const uint8_t *)canned_root_token_payload,
455 				strlen(canned_root_token_payload));
456 		break;
457 
458 #endif
459 
460 	case LWS_SYSTATE_OPERATIONAL:
461 		if (current == LWS_SYSTATE_OPERATIONAL) {
462 			lws_ss_info_t ssi;
463 
464 			/* We're making an outgoing secure stream ourselves */
465 
466 			memset(&ssi, 0, sizeof(ssi));
467 			ssi.handle_offset = offsetof(myss_t, ss);
468 			ssi.opaque_user_data_offset = offsetof(myss_t,
469 							       opaque_data);
470 			ssi.rx = myss_rx;
471 			ssi.tx = myss_tx;
472 			ssi.state = myss_state;
473 #if defined(LWS_WITH_SECURE_STREAMS_BUFFER_DUMP)
474 			ssi.dump = myss_headers_dump;
475 #endif
476 			ssi.user_alloc = sizeof(myss_t);
477 			ssi.streamtype = test_ots ? "mintest-ots" :
478 					 (test_respmap ? "respmap" :
479 					  (test_local ? "mintest_local" :
480 					  "mintest"));
481 
482 			if (lws_ss_create(context, 0, &ssi, NULL, NULL,
483 					  NULL, NULL)) {
484 				lwsl_err("%s: failed to create secure stream\n",
485 					 __func__);
486 				interrupted = 1;
487 				lws_cancel_service(context);
488 				return -1;
489 			}
490 		}
491 		break;
492 	}
493 
494 	return 0;
495 }
496 
497 static lws_state_notify_link_t * const app_notifier_list[] = {
498 	&nl, NULL
499 };
500 
501 #if defined(LWS_WITH_SYS_METRICS)
502 
503 static int
my_metric_report(lws_metric_pub_t * mp)504 my_metric_report(lws_metric_pub_t *mp)
505 {
506 	lws_metric_bucket_t *sub = mp->u.hist.head;
507 	char buf[192];
508 
509 	do {
510 		if (lws_metrics_format(mp, &sub, buf, sizeof(buf)))
511 			lwsl_user("%s: %s\n", __func__, buf);
512 	} while ((mp->flags & LWSMTFL_REPORT_HIST) && sub);
513 
514 	/* 0 = leave metric to accumulate, 1 = reset the metric */
515 
516 	return 1;
517 }
518 
519 static const lws_system_ops_t system_ops = {
520 	.metric_report = my_metric_report,
521 };
522 
523 #endif
524 
525 static void
sigint_handler(int sig)526 sigint_handler(int sig)
527 {
528 	interrupted = 1;
529 }
530 
main(int argc,const char ** argv)531 int main(int argc, const char **argv)
532 {
533 	struct lws_context_creation_info info;
534 	struct lws_context *context;
535 	int n = 0, expected = 0;
536 	const char *p;
537 
538 	signal(SIGINT, sigint_handler);
539 
540 	memset(&info, 0, sizeof info);
541 	lws_cmdline_option_handle_builtin(argc, argv, &info);
542 
543 	//lws_set_log_level(LLL_USER | LLL_ERR | LLL_DEBUG | LLL_NOTICE | LLL_INFO, NULL);
544 
545 	lwsl_user("LWS secure streams test client [-d<verb>]\n");
546 
547 	/* these options are mutually exclusive if given */
548 
549 	if (lws_cmdline_option(argc, argv, "--force-portal"))
550 		force_cpd_fail_portal = 1;
551 
552 	if (lws_cmdline_option(argc, argv, "--force-no-internet"))
553 		force_cpd_fail_no_internet = 1;
554 
555 	if (lws_cmdline_option(argc, argv, "--respmap"))
556 		test_respmap = 1;
557 
558 	if (lws_cmdline_option(argc, argv, "--ots"))
559 		/*
560 		 * Use a streamtype that relies on the OS trust store for
561 		 * validation
562 		 */
563 		test_ots = 1;
564 
565 	if (lws_cmdline_option(argc, argv, "--local"))
566 		test_local = 1;
567 
568 	if ((p = lws_cmdline_option(argc, argv, "--timeout_ms")))
569 		timeout_ms = (unsigned int)atoi(p);
570 
571 	info.fd_limit_per_thread = 1 + 6 + 1;
572 	info.port = CONTEXT_PORT_NO_LISTEN;
573 #if defined(LWS_SS_USE_SSPC)
574 	info.protocols = lws_sspc_protocols;
575 	{
576 		const char *p;
577 
578 		/* connect to ssproxy via UDS by default, else via
579 		 * tcp connection to this port */
580 		if ((p = lws_cmdline_option(argc, argv, "-p")))
581 			info.ss_proxy_port = (uint16_t)atoi(p);
582 
583 		/* UDS "proxy.ss.lws" in abstract namespace, else this socket
584 		 * path; when -p given this can specify the network interface
585 		 * to bind to */
586 		if ((p = lws_cmdline_option(argc, argv, "-i")))
587 			info.ss_proxy_bind = p;
588 
589 		/* if -p given, -a specifies the proxy address to connect to */
590 		if ((p = lws_cmdline_option(argc, argv, "-a")))
591 			info.ss_proxy_address = p;
592 	}
593 #else
594 	info.pss_policies_json = default_ss_policy;
595 	info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
596 		       LWS_SERVER_OPTION_H2_JUST_FIX_WINDOW_UPDATE_OVERFLOW |
597 		       LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
598 #endif
599 
600 #if defined(LWS_WITH_MBEDTLS)
601 
602 	/* uncomment to force mbedtls to load a system trust store like
603 	 * openssl does
604 	 *
605 	 * info.mbedtls_client_preload_filepath =
606 	 *		"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem";
607 	 */
608 #endif
609 
610 	/* integrate us with lws system state management when context created */
611 
612 	nl.name = "app";
613 	nl.notify_cb = app_system_state_nf;
614 	info.register_notifier_list = app_notifier_list;
615 
616 
617 #if defined(LWS_WITH_SYS_METRICS)
618 	info.system_ops = &system_ops;
619 	info.metrics_prefix = "ssmex";
620 #endif
621 
622 	/* create the context */
623 
624 	context = lws_create_context(&info);
625 	if (!context) {
626 		lwsl_err("lws init failed\n");
627 		goto bail;
628 	}
629 
630 #if !defined(LWS_SS_USE_SSPC)
631 	/*
632 	 * If we're being a proxied client, the proxy does all this
633 	 */
634 
635 	/*
636 	 * Set the related lws_system blobs
637 	 *
638 	 * ...direct_set() sets a pointer, so the thing pointed to has to have
639 	 * a suitable lifetime, eg, something that already exists on the heap or
640 	 * a const string in .rodata like this
641 	 */
642 
643 	lws_system_blob_direct_set(lws_system_get_blob(context,
644 				   LWS_SYSBLOB_TYPE_DEVICE_SERIAL, 0),
645 				   (const uint8_t *)"SN12345678", 10);
646 	lws_system_blob_direct_set(lws_system_get_blob(context,
647 				   LWS_SYSBLOB_TYPE_DEVICE_FW_VERSION, 0),
648 				   (const uint8_t *)"v0.01", 5);
649 
650 	/*
651 	 * ..._heap_append() appends to a buflist kind of arrangement on heap,
652 	 * just one block is fine, otherwise it will concatenate the fragments
653 	 * in the order they were appended (and take care of freeing them at
654 	 * context destroy time). ..._heap_empty() is also available to remove
655 	 * everything that was already allocated.
656 	 *
657 	 * Here we use _heap_append() just so it's tested as well as direct set.
658 	 */
659 
660 	lws_system_blob_heap_append(lws_system_get_blob(context,
661 				    LWS_SYSBLOB_TYPE_DEVICE_TYPE, 0),
662 				   (const uint8_t *)"spacerocket", 11);
663 #endif
664 
665 	/* the event loop */
666 
667 	while (n >= 0 && !interrupted)
668 		n = lws_service(context, 0);
669 
670 	lws_context_destroy(context);
671 
672 bail:
673 	if ((p = lws_cmdline_option(argc, argv, "--expected-exit")))
674 		expected = atoi(p);
675 
676 	if (bad == expected) {
677 		lwsl_user("Completed: OK (seen expected %d)\n", expected);
678 		return 0;
679 	} else
680 		lwsl_err("Completed: failed: exit %d, expected %d\n", bad, expected);
681 
682 	return 1;
683 }
684