1/*
2 * lws-api-test-dhcpc
3 *
4 * Written in 2019 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#include <libwebsockets.h>
11#include <signal.h>
12
13static int interrupted, ok, fail, exp = 1;
14struct lws_context *context;
15const char *nif;
16
17static const char * const sa46_names[] = {
18	"LWSDH_SA46_IP",
19	"LWSDH_SA46_DNS_SRV_1",
20	"LWSDH_SA46_DNS_SRV_2",
21	"LWSDH_SA46_DNS_SRV_3",
22	"LWSDH_SA46_DNS_SRV_4",
23	"LWSDH_SA46_IPV4_ROUTER",
24	"LWSDH_SA46_NTP_SERVER",
25	"LWSDH_SA46_DHCP_SERVER",
26};
27
28static int
29lws_dhcpc_cb(void *opaque, lws_dhcpc_ifstate_t *is)
30{
31	unsigned int n;
32	char buf[64];
33
34	lwsl_user("%s: dhcp set OK\n", __func__);
35
36	for (n = 0; n < LWS_ARRAY_SIZE(sa46_names); n++) {
37		lws_sa46_write_numeric_address(&is->sa46[n], buf, sizeof(buf));
38		lwsl_notice("%s: %s: %s\n", __func__, sa46_names[n], buf);
39	}
40
41	ok = 1;
42	interrupted = 1;
43	return 0;
44}
45
46void sigint_handler(int sig)
47{
48	interrupted = 1;
49}
50
51int
52main(int argc, const char **argv)
53{
54	struct lws_context_creation_info info;
55#if !defined(__COVERITY__)
56	const char *p;
57#endif
58	int n = 1;
59
60	signal(SIGINT, sigint_handler);
61
62	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
63	lws_cmdline_option_handle_builtin(argc, argv, &info);
64	lwsl_user("LWS API selftest: DHCP Client\n");
65
66	info.port = CONTEXT_PORT_NO_LISTEN;
67	info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
68
69#if !defined(__COVERITY__)
70	if ((p = lws_cmdline_option(argc, argv, "-i")))
71		nif = p;
72#endif
73
74	context = lws_create_context(&info);
75	if (!context) {
76		lwsl_err("lws init failed\n");
77		return 1;
78	}
79
80	if (nif) {
81		lwsl_user("%s: requesting DHCP for %s\n", __func__, nif);
82		lws_dhcpc_request(context, nif, AF_INET, lws_dhcpc_cb, NULL);
83	} else {
84		lwsl_err("%s: use -i <network-interface> to select if\n", __func__);
85		interrupted = 1;
86	}
87
88	/* the usual lws event loop */
89
90	n = 1;
91	while (n >= 0 && !interrupted)
92		n = lws_service(context, 0);
93
94	lws_context_destroy(context);
95
96	if (fail || ok != exp)
97		lwsl_user("Completed: PASS: %d / %d, FAIL: %d\n", ok, exp,
98				fail);
99	else
100		lwsl_user("Completed: ALL PASS: %d / %d\n", ok, exp);
101
102	return !(ok == exp && !fail);
103}
104