2 * lws-minimal-http-client-post
4 * Written in 2010-2019 by Andy Green <andy@warmcat.com>
6 * This file is made available under the Creative Commons CC0 1.0
7 * Universal Public Domain Dedication.
9 * This demonstrates the a minimal http client using lws and POST.
11 * It POSTs both form data and a file to the form at
12 * https://libwebsockets.org/testserver/formtest and dumps
13 * the html page received generated by the POST handler.
16 #include <libwebsockets.h>
20 static int interrupted, bad = 0, status, count_clients = 1, completed;
21 static struct lws *client_wsi[4];
29 callback_http(struct lws *wsi, enum lws_callback_reasons reason,
30 void *user, void *in, size_t len)
32 struct pss *pss = (struct pss *)user;
33 char buf[LWS_PRE + 1024], *start = &buf[LWS_PRE], *p = start,
34 *end = &buf[sizeof(buf) - 1];
41 /* because we are protocols[0] ... */
42 case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
43 lwsl_err("CLIENT_CONNECTION_ERROR: %s\n",
44 in ? (char *)in : "(null)");
46 if (++completed == count_clients)
47 lws_cancel_service(lws_get_context(wsi));
50 case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
51 for (n = 0; n < count_clients; n++)
52 if (client_wsi[n] == wsi) {
55 if (++completed == count_clients)
57 lws_cancel_service(lws_get_context(wsi));
61 /* ...callbacks related to receiving the result... */
63 case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP:
64 status = lws_http_client_http_response(wsi);
65 lwsl_user("Connected with server response: %d\n", status);
68 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
69 lwsl_user("RECEIVE_CLIENT_HTTP_READ: read %d\n", (int)len);
70 lwsl_hexdump_notice(in, len);
71 return 0; /* don't passthru */
73 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
74 n = sizeof(buf) - LWS_PRE;
75 if (lws_http_client_read(wsi, &p, &n) < 0)
78 return 0; /* don't passthru */
80 case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
81 lwsl_user("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
84 * Do this to mark us as having processed the completion
85 * so close doesn't duplicate (with pipelining, completion !=
88 for (n = 0; n < count_clients; n++)
89 if (client_wsi[n] == wsi)
91 if (++completed == count_clients)
93 lws_cancel_service(lws_get_context(wsi));
96 /* ...callbacks related to generating the POST... */
98 case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
99 lwsl_user("LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER\n");
101 uend = *up + len - 1;
103 /* generate a random boundary string */
105 lws_get_random(lws_get_context(wsi), &r, sizeof(r));
106 lws_snprintf(pss->boundary, sizeof(pss->boundary) - 1,
107 "---boundary-%08x", r);
109 n = lws_snprintf(buf, sizeof(buf) - 1,
110 "multipart/form-data; boundary=%s", pss->boundary);
111 if (lws_add_http_header_by_token(wsi,
112 WSI_TOKEN_HTTP_CONTENT_TYPE,
113 (uint8_t *)buf, n, up, uend))
116 * Notice because we are sending multipart/form-data we can
117 * usually rely on the server to understand where the form
118 * payload ends without having to give it an overall
119 * content-length (which can be troublesome to compute ahead
120 * of generating the data to send).
122 * Tell lws we are going to send the body next...
124 lws_client_http_body_pending(wsi, 1);
125 lws_callback_on_writable(wsi);
128 case LWS_CALLBACK_CLIENT_HTTP_WRITEABLE:
129 lwsl_user("LWS_CALLBACK_CLIENT_HTTP_WRITEABLE\n");
133 * For a small body like this, we could prepare it in memory and
134 * send it all at once. But to show how to handle, eg,
135 * arbitrary-sized file payloads, or huge form-data fields, the
136 * sending is done in multiple passes through the event loop.
139 switch (pss->body_part++) {
141 /* notice every usage of the boundary starts with -- */
142 p += lws_snprintf(p, end - p, "--%s\xd\xa"
143 "content-disposition: "
144 "form-data; name=\"text\"\xd\xa"
147 "\xd\xa", pss->boundary);
150 p += lws_snprintf(p, end - p,
152 "content-disposition: form-data; name=\"file\";"
153 "filename=\"myfile.txt\"\xd\xa"
154 "content-type: text/plain\xd\xa"
156 "This is the contents of the "
157 "uploaded file.\xd\xa"
158 "\xd\xa", pss->boundary);
161 p += lws_snprintf(p, end - p, "--%s--\xd\xa",
163 lws_client_http_body_pending(wsi, 0);
164 /* necessary to support H2, it means we will write no
165 * more on this stream */
166 n = LWS_WRITE_HTTP_FINAL;
171 * We can get extra callbacks here, if nothing to do,
177 if (lws_write(wsi, (uint8_t *)start, lws_ptr_diff(p, start), n)
178 != lws_ptr_diff(p, start))
181 if (n != LWS_WRITE_HTTP_FINAL)
182 lws_callback_on_writable(wsi);
190 return lws_callback_http_dummy(wsi, reason, user, in, len);
193 static const struct lws_protocols protocols[] = {
204 sigint_handler(int sig)
209 int main(int argc, const char **argv)
211 struct lws_context_creation_info info;
212 struct lws_client_connect_info i;
213 struct lws_context *context;
215 int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE
217 * For LLL_ verbosity above NOTICE to be built into lws,
218 * lws must have been configured and built with
219 * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE
221 * | LLL_INFO | LLL_PARSER | LLL_HEADER | LLL_EXT |
222 * LLL_CLIENT | LLL_LATENCY | LLL_DEBUG
225 signal(SIGINT, sigint_handler);
227 if ((p = lws_cmdline_option(argc, argv, "-d")))
230 lws_set_log_level(logs, NULL);
231 lwsl_user("LWS minimal http client - POST [-d<verbosity>] [-l] [--h1]\n");
233 if (lws_cmdline_option(argc, argv, "-m"))
234 count_clients = LWS_ARRAY_SIZE(client_wsi);
236 memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
237 info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
238 info.port = CONTEXT_PORT_NO_LISTEN; /* we do not run any server */
239 info.protocols = protocols;
241 * since we know this lws context is only ever going to be used with
242 * one client wsis / fds / sockets at a time, let lws know it doesn't
243 * have to use the default allocations for fd tables up to ulimit -n.
244 * It will just allocate for 1 internal and 1 (+ 1 http2 nwsi) that we
247 info.fd_limit_per_thread = 1 + count_clients + 1;
249 #if defined(LWS_WITH_MBEDTLS)
251 * OpenSSL uses the system trust store. mbedTLS has to be told which
252 * CA to trust explicitly.
254 if (!lws_cmdline_option(argc, argv, "-l"))
255 info.client_ssl_ca_filepath = "./libwebsockets.org.cer";
258 context = lws_create_context(&info);
260 lwsl_err("lws init failed\n");
264 memset(&i, 0, sizeof i); /* otherwise uninitialized garbage */
266 i.ssl_connection = LCCSCF_USE_SSL;
268 if (lws_cmdline_option(argc, argv, "-l")) {
270 i.address = "localhost";
271 i.ssl_connection |= LCCSCF_ALLOW_SELFSIGNED;
272 i.path = "/formtest";
275 i.address = "libwebsockets.org";
276 i.path = "/testserver/formtest";
280 i.origin = i.address;
283 /* force h1 even if h2 available */
284 if (lws_cmdline_option(argc, argv, "--h1"))
287 i.protocol = protocols[0].name;
289 for (n = 0; n < count_clients; n++) {
290 i.pwsi = &client_wsi[n];
291 if (!lws_client_connect_via_info(&i))
295 while (n >= 0 && completed != count_clients && !interrupted)
296 n = lws_service(context, 0);
298 lws_context_destroy(context);
299 lwsl_user("Completed: %s\n", bad ? "failed" : "OK");