1/*
2 * lws-minimal-http-client-h2-rxflow
3 *
4 * Written in 2010-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 * This demonstrates the a minimal http client using lws.
10 *
11 * It visits https://warmcat.com/ and receives the html page there.  You
12 * can dump the page data by changing the #if 0 below.
13 */
14
15#include <libwebsockets.h>
16#include <string.h>
17#include <signal.h>
18
19static int interrupted, bad = 1, status, each = 1024;
20static struct lws *client_wsi;
21
22static const lws_retry_bo_t retry = {
23	.secs_since_valid_ping = 3,
24	.secs_since_valid_hangup = 10,
25};
26
27struct pss {
28	lws_sorted_usec_list_t sul;
29	struct lws *wsi;
30};
31
32/*
33 * Once we're established, we ask the server for another 1KB every 250ms
34 * until we have it all.
35 */
36
37static void
38drain_cb(lws_sorted_usec_list_t *sul)
39{
40	struct pss *pss = lws_container_of(sul, struct pss, sul);
41
42	lws_wsi_tx_credit(pss->wsi, LWSTXCR_PEER_TO_US, each);
43
44	lws_sul_schedule(lws_get_context(pss->wsi), 0, &pss->sul, drain_cb,
45			 250 * LWS_US_PER_MS);
46}
47
48
49static int
50callback_http(struct lws *wsi, enum lws_callback_reasons reason,
51	      void *user, void *in, size_t len)
52{
53	struct pss *pss = (struct pss *)user;
54
55	switch (reason) {
56
57	/* because we are protocols[0] ... */
58	case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
59		lwsl_err("CLIENT_CONNECTION_ERROR: %s\n",
60			 in ? (char *)in : "(null)");
61		interrupted = 1;
62		break;
63
64	case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP:
65		{
66			char buf[128];
67
68			lws_get_peer_simple(wsi, buf, sizeof(buf));
69			status = (int)lws_http_client_http_response(wsi);
70
71			lwsl_user("Connected to %s, http response: %d\n",
72					buf, status);
73		}
74		pss->wsi = wsi;
75		lws_sul_schedule(lws_get_context(wsi), 0, &pss->sul, drain_cb,
76				 250 * LWS_US_PER_MS);
77		break;
78
79	/* chunks of chunked content, with header removed */
80	case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
81		lwsl_user("RECEIVE_CLIENT_HTTP_READ: read %d\n", (int)len);
82
83#if 0  /* enable to dump the html */
84		{
85			const char *p = in;
86
87			while (len--)
88				if (*p < 0x7f)
89					putchar(*p++);
90				else
91					putchar('.');
92		}
93#endif
94		return 0; /* don't passthru */
95
96	/* uninterpreted http content */
97	case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
98		{
99			char buffer[1024 + LWS_PRE];
100			char *px = buffer + LWS_PRE;
101			int lenx = sizeof(buffer) - LWS_PRE;
102
103			if (lws_http_client_read(wsi, &px, &lenx) < 0)
104				return -1;
105		}
106		return 0; /* don't passthru */
107
108	case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
109		lwsl_user("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
110		interrupted = 1;
111		bad = status != 200;
112		lws_cancel_service(lws_get_context(wsi)); /* abort poll wait */
113		break;
114
115	case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
116		interrupted = 1;
117		bad = status != 200;
118		lws_sul_cancel(&pss->sul);
119		lws_cancel_service(lws_get_context(wsi)); /* abort poll wait */
120		break;
121
122	default:
123		break;
124	}
125
126	return lws_callback_http_dummy(wsi, reason, user, in, len);
127}
128
129static const struct lws_protocols protocols[] = {
130	{
131		"http",
132		callback_http,
133		sizeof(struct pss),
134		0, 0, NULL, 0
135	},
136	LWS_PROTOCOL_LIST_TERM
137};
138
139static void
140sigint_handler(int sig)
141{
142	interrupted = 1;
143}
144
145struct args {
146	int argc;
147	const char **argv;
148};
149
150static int
151system_notify_cb(lws_state_manager_t *mgr, lws_state_notify_link_t *link,
152		   int current, int target)
153{
154	struct lws_context *context = mgr->parent;
155	struct lws_client_connect_info i;
156	struct args *a = lws_context_user(context);
157	const char *p;
158
159	if (current != LWS_SYSTATE_OPERATIONAL || target != LWS_SYSTATE_OPERATIONAL)
160		return 0;
161
162	lwsl_info("%s: operational\n", __func__);
163
164	memset(&i, 0, sizeof i); /* otherwise uninitialized garbage */
165	i.context = context;
166	if (!lws_cmdline_option(a->argc, a->argv, "-n"))
167		i.ssl_connection = LCCSCF_USE_SSL;
168
169	if (lws_cmdline_option(a->argc, a->argv, "-l")) {
170		i.port = 7681;
171		i.address = "localhost";
172		i.ssl_connection |= LCCSCF_ALLOW_SELFSIGNED;
173	} else {
174		i.port = 443;
175		i.address = "warmcat.com";
176	}
177
178	if (lws_cmdline_option(a->argc, a->argv, "--nossl"))
179		i.ssl_connection = 0;
180
181	i.ssl_connection |= LCCSCF_H2_QUIRK_OVERFLOWS_TXCR |
182			    LCCSCF_H2_QUIRK_NGHTTP2_END_STREAM;
183
184	i.alpn = "h2";
185	if (lws_cmdline_option(a->argc, a->argv, "--h1"))
186		i.alpn = "http/1.1";
187
188	if ((p = lws_cmdline_option(a->argc, a->argv, "-p")))
189		i.port = atoi(p);
190
191	if (lws_cmdline_option(a->argc, a->argv, "-j"))
192		i.ssl_connection |= LCCSCF_ALLOW_SELFSIGNED;
193
194	if (lws_cmdline_option(a->argc, a->argv, "-k"))
195		i.ssl_connection |= LCCSCF_ALLOW_INSECURE;
196
197	if (lws_cmdline_option(a->argc, a->argv, "-m"))
198		i.ssl_connection |= LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;
199
200	if (lws_cmdline_option(a->argc, a->argv, "-e"))
201		i.ssl_connection |= LCCSCF_ALLOW_EXPIRED;
202
203	if ((p = lws_cmdline_option(a->argc, a->argv, "-f"))) {
204		i.ssl_connection |= LCCSCF_H2_MANUAL_RXFLOW;
205		i.manual_initial_tx_credit = atoi(p);
206		lwsl_notice("%s: manual peer tx credit %d\n", __func__,
207				i.manual_initial_tx_credit);
208	}
209
210	if ((p = lws_cmdline_option(a->argc, a->argv, "--each")))
211		each = atoi(p);
212
213	/* the default validity check is 5m / 5m10s... -v = 3s / 10s */
214
215	if (lws_cmdline_option(a->argc, a->argv, "-v"))
216		i.retry_and_idle_policy = &retry;
217
218	if ((p = lws_cmdline_option(a->argc, a->argv, "--server")))
219		i.address = p;
220
221	if ((p = lws_cmdline_option(a->argc, a->argv, "--path")))
222		i.path = p;
223	else
224		i.path = "/";
225
226	i.host = i.address;
227	i.origin = i.address;
228	i.method = "GET";
229
230	i.protocol = protocols[0].name;
231	i.pwsi = &client_wsi;
232
233	return !lws_client_connect_via_info(&i);
234}
235
236int main(int argc, const char **argv)
237{
238	lws_state_notify_link_t notifier = { { NULL, NULL, NULL },
239						system_notify_cb, "app" };
240	lws_state_notify_link_t *na[] = { &notifier, NULL };
241	struct lws_context_creation_info info;
242	struct lws_context *context;
243	struct args args;
244	int n = 0;
245	// uint8_t memcert[4096];
246
247	args.argc = argc;
248	args.argv = argv;
249
250	signal(SIGINT, sigint_handler);
251
252	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
253	lws_cmdline_option_handle_builtin(argc, argv, &info);
254
255	lwsl_user("LWS minimal http client [-d<verbosity>] [-l] [--h1]\n");
256
257	info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
258	info.port = CONTEXT_PORT_NO_LISTEN; /* we do not run any server */
259	info.protocols = protocols;
260	info.user = &args;
261	info.register_notifier_list = na;
262	info.timeout_secs = 10;
263	info.connect_timeout_secs = 30;
264
265	/*
266	 * since we know this lws context is only ever going to be used with
267	 * one client wsis / fds / sockets at a time, let lws know it doesn't
268	 * have to use the default allocations for fd tables up to ulimit -n.
269	 * It will just allocate for 1 internal and 1 (+ 1 http2 nwsi) that we
270	 * will use.
271	 */
272	info.fd_limit_per_thread = 1 + 1 + 1;
273
274#if defined(LWS_WITH_MBEDTLS) || defined(USE_WOLFSSL)
275	/*
276	 * OpenSSL uses the system trust store.  mbedTLS has to be told which
277	 * CA to trust explicitly.
278	 */
279	info.client_ssl_ca_filepath = "./warmcat.com.cer";
280#endif
281#if 0
282	n = open("./warmcat.com.cer", O_RDONLY);
283	if (n >= 0) {
284		info.client_ssl_ca_mem_len = read(n, memcert, sizeof(memcert));
285		info.client_ssl_ca_mem = memcert;
286		close(n);
287		n = 0;
288		memcert[info.client_ssl_ca_mem_len++] = '\0';
289	}
290#endif
291	context = lws_create_context(&info);
292	if (!context) {
293		lwsl_err("lws init failed\n");
294		return 1;
295	}
296
297	while (n >= 0 && !interrupted)
298		n = lws_service(context, 0);
299
300	lws_context_destroy(context);
301	lwsl_user("Completed: %s\n", bad ? "failed" : "OK");
302
303	return bad;
304}
305