2 * libwebsockets-test-server - libwebsockets test implementation
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 * The person who associated a work with this deed has dedicated
10 * the work to the public domain by waiving all of his or her rights
11 * to the work worldwide under copyright law, including all related
12 * and neighboring rights, to the extent allowed by law. You can copy,
13 * modify, distribute and perform the work, even for commercial purposes,
14 * all without asking permission.
16 * The test apps are intended to be adapted for use in your code, which
17 * may be proprietary. So unlike the library itself, they are licensed
21 #include <libwebsockets.h>
24 #if defined(LWS_HAS_GETOPT_LONG) || defined(WIN32)
29 #if defined(WIN32) || defined(_WIN32)
35 int max_poll_elements;
36 int debug_level = LLL_USER | 7;
38 #if defined(LWS_WITH_EXTERNAL_POLL)
39 struct lws_pollfd *pollfds;
43 volatile int force_exit = 0, dynamic_vhost_enable = 0;
44 struct lws_vhost *dynamic_vhost;
45 struct lws_context *context;
46 struct lws_plat_file_ops fops_plat;
47 static int test_options;
49 /* http server gets files from this path */
50 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
51 char *resource_path = LOCAL_RESOURCE_PATH;
52 #if defined(LWS_WITH_TLS) && defined(LWS_HAVE_SSL_CTX_set1_param)
53 char crl_path[1024] = "";
57 * This demonstrates how to use the clean protocol service separation of
58 * plugins, but with static inclusion instead of runtime dynamic loading
59 * (which requires libuv).
61 * dumb-increment doesn't use the plugin, both to demonstrate how to
62 * do the protocols directly, and because it wants libuv for a timer.
64 * Please consider using test-server-v2.0.c instead of this: it has the
65 * same functionality but
67 * 1) uses lws built-in http handling so you don't need to deal with it in
70 * 2) Links with libuv and uses the plugins at runtime
72 * 3) Uses advanced lws features like mounts to bind parts of the filesystem
73 * to the served URL space
75 * Another option is lwsws, this operates like test-server-v2,0.c but is
76 * configured using JSON, do you do not need to provide any code for the
77 * serving action at all, just implement your protocols in plugins.
80 #define LWS_PLUGIN_STATIC
81 #if defined(LWS_ROLE_WS)
82 #include "../plugins/protocol_lws_mirror.c"
83 #include "../plugins/protocol_lws_status.c"
84 #include "../plugins/protocol_dumb_increment.c"
85 #include "../plugins/protocol_post_demo.c"
89 lws_callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
92 const unsigned char *c;
97 case LWS_CALLBACK_HTTP:
99 /* non-mount-handled accesses will turn up here */
101 /* dump the headers */
104 c = lws_token_to_string(n);
110 hlen = lws_hdr_total_length(wsi, n);
111 if (!hlen || hlen > (int)sizeof(buf) - 1) {
116 if (lws_hdr_copy(wsi, buf, sizeof buf, n) < 0)
117 fprintf(stderr, " %s (too big)\n", (char *)c);
119 buf[sizeof(buf) - 1] = '\0';
121 fprintf(stderr, " %s = %s\n", (char *)c, buf);
126 /* dump the individual URI Arg parameters */
129 while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
130 WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
131 lwsl_notice("URI Arg %d: %s\n", ++n, buf);
134 if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL))
137 if (lws_http_transaction_completed(wsi))
145 return lws_callback_http_dummy(wsi, reason, user, in, len);
148 /* list of supported protocols and callbacks */
150 static struct lws_protocols protocols[] = {
151 /* first protocol must always be HTTP handler */
153 { "http-only", lws_callback_http, 0, 0, },
154 #if defined(LWS_ROLE_WS)
155 LWS_PLUGIN_PROTOCOL_DUMB_INCREMENT,
156 LWS_PLUGIN_PROTOCOL_MIRROR,
157 LWS_PLUGIN_PROTOCOL_LWS_STATUS,
158 LWS_PLUGIN_PROTOCOL_POST_DEMO,
160 { NULL, NULL, 0, 0 } /* terminator */
164 /* this shows how to override the lws file operations. You don't need
165 * to do any of this unless you have a reason (eg, want to serve
166 * compressed files without decompressing the whole archive)
169 test_server_fops_open(const struct lws_plat_file_ops *fops,
170 const char *vfs_path, const char *vpath,
171 lws_fop_flags_t *flags)
175 /* call through to original platform implementation */
176 fop_fd = fops_plat.open(fops, vfs_path, vpath, flags);
179 lwsl_info("%s: opening %s, ret %p, len %lu\n", __func__,
181 (long)lws_vfs_get_length(fop_fd));
183 lwsl_info("%s: open %s failed\n", __func__, vfs_path);
188 void sighandler(int sig)
190 #if !defined(WIN32) && !defined(_WIN32)
191 /* because windows is too dumb to have SIGUSR1... */
192 if (sig == SIGUSR1) {
194 * For testing, you can fire a SIGUSR1 at the test server
195 * to toggle the existence of an identical server on
198 dynamic_vhost_enable ^= 1;
199 lws_cancel_service(context);
200 lwsl_notice("SIGUSR1: dynamic_vhost_enable: %d\n",
201 dynamic_vhost_enable);
206 lws_cancel_service(context);
209 static const struct lws_extension exts[] = {
211 "permessage-deflate",
212 lws_extension_callback_pm_deflate,
215 { NULL, NULL, NULL /* terminator */ }
219 * mount handlers for sections of the URL space
222 static const struct lws_http_mount mount_ziptest = {
223 NULL, /* linked-list pointer to next*/
224 "/ziptest", /* mountpoint in URL namespace on this vhost */
225 LOCAL_RESOURCE_PATH"/candide.zip", /* handler */
226 NULL, /* default filename if none given */
237 LWSMPRO_FILE, /* origin points to a callback */
238 8, /* strlen("/ziptest"), ie length of the mountpoint */
241 { NULL, NULL } // sentinel
244 static const struct lws_http_mount mount_post = {
245 (struct lws_http_mount *)&mount_ziptest, /* linked-list pointer to next*/
246 "/formtest", /* mountpoint in URL namespace on this vhost */
247 "protocol-post-demo", /* handler */
248 NULL, /* default filename if none given */
259 LWSMPRO_CALLBACK, /* origin points to a callback */
260 9, /* strlen("/formtest"), ie length of the mountpoint */
263 { NULL, NULL } // sentinel
267 * mount a filesystem directory into the URL space at /
268 * point it to our /usr/share directory with our assets in
269 * stuff from here is autoserved by the library
272 static const struct lws_http_mount mount = {
273 (struct lws_http_mount *)&mount_post, /* linked-list pointer to next*/
274 "/", /* mountpoint in URL namespace on this vhost */
275 LOCAL_RESOURCE_PATH, /* where to go on the filesystem for that */
276 "test.html", /* default filename if none given */
287 LWSMPRO_FILE, /* mount type is a directory in a filesystem */
288 1, /* strlen("/"), ie length of the mountpoint */
291 { NULL, NULL } // sentinel
294 static const struct lws_protocol_vhost_options pvo_options = {
297 "options", /* pvo name */
298 (void *)&test_options /* pvo value */
301 static const struct lws_protocol_vhost_options pvo = {
302 NULL, /* "next" pvo linked-list */
303 &pvo_options, /* "child" pvo linked-list */
304 "dumb-increment-protocol", /* protocol name we belong to on this vhost */
308 #if defined(LWS_HAS_GETOPT_LONG) || defined(WIN32)
309 static struct option options[] = {
310 { "help", no_argument, NULL, 'h' },
311 { "debug", required_argument, NULL, 'd' },
312 { "port", required_argument, NULL, 'p' },
313 { "ssl", no_argument, NULL, 's' },
314 { "allow-non-ssl", no_argument, NULL, 'a' },
315 { "interface", required_argument, NULL, 'i' },
316 { "closetest", no_argument, NULL, 'c' },
317 { "ssl-cert", required_argument, NULL, 'C' },
318 { "ssl-key", required_argument, NULL, 'K' },
319 { "ssl-ca", required_argument, NULL, 'A' },
320 #if defined(LWS_WITH_TLS)
321 { "ssl-verify-client", no_argument, NULL, 'v' },
322 #if defined(LWS_HAVE_SSL_CTX_set1_param)
323 { "ssl-crl", required_argument, NULL, 'R' },
326 { "libev", no_argument, NULL, 'e' },
327 { "unix-socket", required_argument, NULL, 'U' },
328 #ifndef LWS_NO_DAEMONIZE
329 { "daemonize", no_argument, NULL, 'D' },
331 { "pingpong-secs", required_argument, NULL, 'P' },
336 int main(int argc, char **argv)
338 struct lws_context_creation_info info;
339 struct lws_vhost *vhost;
340 char interface_name[128] = "";
341 const char *iface = NULL;
342 char cert_path[1024] = "";
343 char key_path[1024] = "";
344 char ca_path[1024] = "";
345 int uid = -1, gid = -1;
350 #ifndef LWS_NO_DAEMONIZE
355 * take care to zero down the info struct, he contains random garbaage
356 * from the stack otherwise
358 memset(&info, 0, sizeof info);
362 #if defined(LWS_HAS_GETOPT_LONG) || defined(WIN32)
363 n = getopt_long(argc, argv, "eci:hsap:d:DC:K:A:R:vu:g:P:kU:n", options, NULL);
365 n = getopt(argc, argv, "eci:hsap:d:DC:K:A:R:vu:g:P:kU:n");
371 opts |= LWS_SERVER_OPTION_LIBEV;
373 #ifndef LWS_NO_DAEMONIZE
385 debug_level = atoi(optarg);
388 /* no dumb increment send */
393 opts |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
396 opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
399 info.port = atoi(optarg);
402 lws_strncpy(interface_name, optarg, sizeof interface_name);
403 iface = interface_name;
406 lws_strncpy(interface_name, optarg, sizeof interface_name);
407 iface = interface_name;
408 opts |= LWS_SERVER_OPTION_UNIX_SOCK;
412 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
413 info.caps[0] = CAP_NET_RAW;
419 fprintf(stderr, " Close testing mode -- closes on "
420 "client after 50 dumb increments"
421 "and suppresses lws_mirror spam\n");
424 lws_strncpy(cert_path, optarg, sizeof(cert_path));
427 lws_strncpy(key_path, optarg, sizeof(key_path));
430 lws_strncpy(ca_path, optarg, sizeof(ca_path));
433 pp_secs = atoi(optarg);
434 lwsl_notice("Setting pingpong interval to %d\n", pp_secs);
436 #if defined(LWS_WITH_TLS)
439 opts |= LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT;
442 #if defined(LWS_HAVE_SSL_CTX_set1_param)
444 lws_strncpy(crl_path, optarg, sizeof(crl_path));
449 fprintf(stderr, "Usage: test-server "
450 "[--port=<p>] [--ssl] "
451 "[-d <log bitfield>]\n");
456 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
458 * normally lock path would be /var/lock/lwsts or similar, to
459 * simplify getting started without having to take care about
460 * permissions or running as root, set to /tmp/.lwsts-lock
462 if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
463 fprintf(stderr, "Failed to daemonize\n");
468 signal(SIGINT, sighandler);
469 #if !defined(WIN32) && !defined(_WIN32)
470 /* because windows is too dumb to have SIGUSR1... */
471 /* dynamic vhost create / destroy toggle (on port + 1) */
472 signal(SIGUSR1, sighandler);
475 /* tell the library what debug level to emit and to send it to stderr */
476 lws_set_log_level(debug_level, NULL);
478 lwsl_notice("libwebsockets test server - license LGPL2.1+SLE\n");
479 lwsl_notice("(C) Copyright 2010-2018 Andy Green <andy@warmcat.com>\n");
481 printf("Using resource path \"%s\"\n", resource_path);
482 #if defined(LWS_WITH_EXTERNAL_POLL)
483 #if !defined(WIN32) && !defined(_WIN32) && !defined(__ANDROID__)
484 max_poll_elements = getdtablesize();
486 max_poll_elements = sysconf(_SC_OPEN_MAX);
488 pollfds = malloc(max_poll_elements * sizeof (struct lws_pollfd));
489 fd_lookup = malloc(max_poll_elements * sizeof (int));
490 if (pollfds == NULL || fd_lookup == NULL) {
491 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
497 info.protocols = protocols;
498 info.ssl_cert_filepath = NULL;
499 info.ssl_private_key_filepath = NULL;
500 info.ws_ping_pong_interval = pp_secs;
503 if (strlen(resource_path) > sizeof(cert_path) - 32) {
504 lwsl_err("resource path too long\n");
508 sprintf(cert_path, "%s/libwebsockets-test-server.pem",
510 if (strlen(resource_path) > sizeof(key_path) - 32) {
511 lwsl_err("resource path too long\n");
515 sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
518 info.ssl_cert_filepath = cert_path;
519 info.ssl_private_key_filepath = key_path;
521 info.ssl_ca_filepath = ca_path;
525 info.options = opts | LWS_SERVER_OPTION_VALIDATE_UTF8 | LWS_SERVER_OPTION_EXPLICIT_VHOSTS;
526 info.extensions = exts;
527 info.timeout_secs = 5;
528 info.ssl_cipher_list = "ECDHE-ECDSA-AES256-GCM-SHA384:"
529 "ECDHE-RSA-AES256-GCM-SHA384:"
530 "DHE-RSA-AES256-GCM-SHA384:"
531 "ECDHE-RSA-AES256-SHA384:"
532 "HIGH:!aNULL:!eNULL:!EXPORT:"
533 "!DES:!MD5:!PSK:!RC4:!HMAC_SHA1:"
534 "!SHA1:!DHE-RSA-AES128-GCM-SHA256:"
535 "!DHE-RSA-AES128-SHA256:"
536 "!AES128-GCM-SHA256:"
538 "!DHE-RSA-AES256-SHA256:"
539 "!AES256-GCM-SHA384:"
541 info.mounts = &mount;
542 info.ip_limit_ah = 24; /* for testing */
543 info.ip_limit_wsi = 400; /* for testing */
546 /* redirect guys coming on http */
547 info.options |= LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS;
549 context = lws_create_context(&info);
550 if (context == NULL) {
551 lwsl_err("libwebsocket init failed\n");
557 vhost = lws_create_vhost(context, &info);
559 lwsl_err("vhost creation failed\n");
564 * For testing dynamic vhost create / destroy later, we use port + 1
565 * Normally if you were creating more vhosts, you would set info.name
566 * for each to be the hostname external clients use to reach it
571 #if !defined(LWS_NO_CLIENT) && defined(LWS_WITH_TLS)
572 lws_init_vhost_client_ssl(&info, vhost);
575 /* this shows how to override the lws file operations. You don't need
576 * to do any of this unless you have a reason (eg, want to serve
577 * compressed files without decompressing the whole archive)
579 /* stash original platform fops */
580 fops_plat = *(lws_get_fops(context));
581 /* override the active fops */
582 lws_get_fops(context)->open = test_server_fops_open;
585 while (n >= 0 && !force_exit) {
588 gettimeofday(&tv, NULL);
591 * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
592 * live websocket connection using the DUMB_INCREMENT protocol,
593 * as soon as it can take more packets (usually immediately)
596 #if defined(LWS_WITH_EXTERNAL_POLL)
598 * this represents an existing server's single poll action
599 * which also includes libwebsocket sockets
601 n = poll(pollfds, count_pollfds, 50);
606 for (n = 0; n < count_pollfds; n++)
607 if (pollfds[n].revents)
609 * returns immediately if the fd does not
610 * match anything under libwebsockets
613 if (lws_service_fd(context,
617 /* if needed, force-service wsis that may not have read all input */
618 while (!lws_service_adjust_timeout(context, 1, 0)) {
619 lwsl_notice("extpoll doing forced service!\n");
620 lws_service_tsi(context, -1, 0);
625 * If libwebsockets sockets are all we care about,
626 * you can use this api which takes care of the poll()
627 * and looping through finding who needed service.
630 n = lws_service(context, 0);
633 if (dynamic_vhost_enable && !dynamic_vhost) {
634 lwsl_notice("creating dynamic vhost...\n");
635 dynamic_vhost = lws_create_vhost(context, &info);
637 if (!dynamic_vhost_enable && dynamic_vhost) {
638 lwsl_notice("destroying dynamic vhost...\n");
639 lws_vhost_destroy(dynamic_vhost);
640 dynamic_vhost = NULL;
645 #if defined(LWS_WITH_EXTERNAL_POLL)
649 lws_context_destroy(context);
651 lwsl_notice("libwebsockets-test-server exited cleanly\n");