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