2 * libwebsockets-test-server - libwebsockets test implementation
4 * Copyright (C) 2010-2016 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 "test-server.h"
24 int max_poll_elements;
28 struct lws_pollfd *pollfds;
32 volatile int force_exit = 0, dynamic_vhost_enable = 0;
33 struct lws_vhost *dynamic_vhost;
34 struct lws_context *context;
35 struct lws_plat_file_ops fops_plat;
37 /* http server gets files from this path */
38 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
39 char *resource_path = LOCAL_RESOURCE_PATH;
40 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
41 char crl_path[1024] = "";
45 * This demonstrates how to use the clean protocol service separation of
46 * plugins, but with static inclusion instead of runtime dynamic loading
47 * (which requires libuv).
49 * dumb-increment doesn't use the plugin, both to demonstrate how to
50 * do the protocols directly, and because it wants libuv for a timer.
52 * Please consider using test-server-v2.0.c instead of this: it has the
53 * same functionality but
55 * 1) uses lws built-in http handling so you don't need to deal with it in
58 * 2) Links with libuv and uses the plugins at runtime
60 * 3) Uses advanced lws features like mounts to bind parts of the filesystem
61 * to the served URL space
63 * Another option is lwsws, this operates like test-server-v2,0.c but is
64 * configured using JSON, do you do not need to provide any code for the
65 * serving action at all, just implement your protocols in plugins.
68 #define LWS_PLUGIN_STATIC
69 #include "../plugins/protocol_lws_mirror.c"
70 #include "../plugins/protocol_lws_status.c"
72 /* singlethreaded version --> no locks */
74 void test_server_lock(int care)
77 void test_server_unlock(int care)
82 * This demo server shows how to use libwebsockets for one or more
83 * websocket protocols in the same server
85 * It defines the following websocket protocols:
87 * dumb-increment-protocol: once the socket is opened, an incrementing
88 * ascii string is sent down it every 50ms.
89 * If you send "reset\n" on the websocket, then
90 * the incrementing number is reset to 0.
92 * lws-mirror-protocol: copies any received packet to every connection also
93 * using this protocol, including the sender
95 * lws-status: informs connected browsers of who else is
103 PROTOCOL_DUMB_INCREMENT,
111 /* list of supported protocols and callbacks */
113 static struct lws_protocols protocols[] = {
114 /* first protocol must always be HTTP handler */
117 "http-only", /* name */
118 callback_http, /* callback */
119 sizeof (struct per_session_data__http), /* per_session_data_size */
120 0, /* max frame size / rx buffer */
123 "dumb-increment-protocol",
124 callback_dumb_increment,
125 sizeof(struct per_session_data__dumb_increment),
126 10, /* rx buf size must be >= permessage-deflate rx size
127 * dumb-increment only sends very small packets, so we set
128 * this accordingly. If your protocol will send bigger
129 * things, adjust this to match */
131 LWS_PLUGIN_PROTOCOL_MIRROR,
132 LWS_PLUGIN_PROTOCOL_LWS_STATUS,
133 { NULL, NULL, 0, 0 } /* terminator */
137 /* this shows how to override the lws file operations. You don't need
138 * to do any of this unless you have a reason (eg, want to serve
139 * compressed files without decompressing the whole archive)
142 test_server_fops_open(const struct lws_plat_file_ops *fops,
143 const char *vfs_path, const char *vpath,
144 lws_fop_flags_t *flags)
148 /* call through to original platform implementation */
149 fop_fd = fops_plat.open(fops, vfs_path, vpath, flags);
152 lwsl_info("%s: opening %s, ret %p, len %lu\n", __func__,
154 (long)lws_vfs_get_length(fop_fd));
156 lwsl_info("%s: open %s failed\n", __func__, vfs_path);
161 void sighandler(int sig)
163 #if !defined(WIN32) && !defined(_WIN32)
164 /* because windows is too dumb to have SIGUSR1... */
165 if (sig == SIGUSR1) {
167 * For testing, you can fire a SIGUSR1 at the test server
168 * to toggle the existence of an identical server on
171 dynamic_vhost_enable ^= 1;
172 lwsl_notice("SIGUSR1: dynamic_vhost_enable: %d\n",
173 dynamic_vhost_enable);
178 lws_cancel_service(context);
181 static const struct lws_extension exts[] = {
183 "permessage-deflate",
184 lws_extension_callback_pm_deflate,
189 lws_extension_callback_pm_deflate,
192 { NULL, NULL, NULL /* terminator */ }
197 static struct option options[] = {
198 { "help", no_argument, NULL, 'h' },
199 { "debug", required_argument, NULL, 'd' },
200 { "port", required_argument, NULL, 'p' },
201 { "ssl", no_argument, NULL, 's' },
202 { "allow-non-ssl", no_argument, NULL, 'a' },
203 { "interface", required_argument, NULL, 'i' },
204 { "closetest", no_argument, NULL, 'c' },
205 { "ssl-cert", required_argument, NULL, 'C' },
206 { "ssl-key", required_argument, NULL, 'K' },
207 { "ssl-ca", required_argument, NULL, 'A' },
208 #if defined(LWS_OPENSSL_SUPPORT)
209 { "ssl-verify-client", no_argument, NULL, 'v' },
210 #if defined(LWS_HAVE_SSL_CTX_set1_param)
211 { "ssl-crl", required_argument, NULL, 'R' },
214 { "libev", no_argument, NULL, 'e' },
215 #ifndef LWS_NO_DAEMONIZE
216 { "daemonize", no_argument, NULL, 'D' },
218 { "resource_path", required_argument, NULL, 'r' },
219 { "pingpong-secs", required_argument, NULL, 'P' },
223 int main(int argc, char **argv)
225 struct lws_context_creation_info info;
226 struct lws_vhost *vhost;
227 char interface_name[128] = "";
228 unsigned int ms, oldms = 0;
229 const char *iface = NULL;
230 char cert_path[1024] = "";
231 char key_path[1024] = "";
232 char ca_path[1024] = "";
233 int uid = -1, gid = -1;
239 /* LOG_PERROR is not POSIX standard, and may not be portable */
241 int syslog_options = LOG_PID;
243 int syslog_options = LOG_PID | LOG_PERROR;
246 #ifndef LWS_NO_DAEMONIZE
251 * take care to zero down the info struct, he contains random garbaage
252 * from the stack otherwise
254 memset(&info, 0, sizeof info);
258 n = getopt_long(argc, argv, "eci:hsap:d:Dr:C:K:A:R:vu:g:P:k", options, NULL);
263 opts |= LWS_SERVER_OPTION_LIBEV;
265 #ifndef LWS_NO_DAEMONIZE
268 #if !defined(_WIN32) && !defined(__sun)
269 syslog_options &= ~LOG_PERROR;
280 debug_level = atoi(optarg);
284 opts |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
287 opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
290 info.port = atoi(optarg);
293 strncpy(interface_name, optarg, sizeof interface_name);
294 interface_name[(sizeof interface_name) - 1] = '\0';
295 iface = interface_name;
299 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
300 info.caps[0] = CAP_NET_RAW;
306 fprintf(stderr, " Close testing mode -- closes on "
307 "client after 50 dumb increments"
308 "and suppresses lws_mirror spam\n");
311 resource_path = optarg;
312 printf("Setting resource path to \"%s\"\n", resource_path);
315 strncpy(cert_path, optarg, sizeof(cert_path) - 1);
316 cert_path[sizeof(cert_path) - 1] = '\0';
319 strncpy(key_path, optarg, sizeof(key_path) - 1);
320 key_path[sizeof(key_path) - 1] = '\0';
323 strncpy(ca_path, optarg, sizeof(ca_path) - 1);
324 ca_path[sizeof(ca_path) - 1] = '\0';
327 pp_secs = atoi(optarg);
328 lwsl_notice("Setting pingpong interval to %d\n", pp_secs);
330 #if defined(LWS_OPENSSL_SUPPORT)
333 opts |= LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT;
336 #if defined(LWS_HAVE_SSL_CTX_set1_param)
338 strncpy(crl_path, optarg, sizeof(crl_path) - 1);
339 crl_path[sizeof(crl_path) - 1] = '\0';
344 fprintf(stderr, "Usage: test-server "
345 "[--port=<p>] [--ssl] "
346 "[-d <log bitfield>] "
347 "[--resource_path <path>]\n");
352 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
354 * normally lock path would be /var/lock/lwsts or similar, to
355 * simplify getting started without having to take care about
356 * permissions or running as root, set to /tmp/.lwsts-lock
358 if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
359 fprintf(stderr, "Failed to daemonize\n");
364 signal(SIGINT, sighandler);
365 #if !defined(WIN32) && !defined(_WIN32)
366 /* because windows is too dumb to have SIGUSR1... */
367 /* dynamic vhost create / destroy toggle (on port + 1) */
368 signal(SIGUSR1, sighandler);
372 /* we will only try to log things according to our debug_level */
373 setlogmask(LOG_UPTO (LOG_DEBUG));
374 openlog("lwsts", syslog_options, LOG_DAEMON);
377 /* tell the library what debug level to emit and to send it to syslog */
378 lws_set_log_level(debug_level, lwsl_emit_syslog);
380 lwsl_notice("libwebsockets test server - license LGPL2.1+SLE\n");
381 lwsl_notice("(C) Copyright 2010-2016 Andy Green <andy@warmcat.com>\n");
383 printf("Using resource path \"%s\"\n", resource_path);
385 max_poll_elements = getdtablesize();
386 pollfds = malloc(max_poll_elements * sizeof (struct lws_pollfd));
387 fd_lookup = malloc(max_poll_elements * sizeof (int));
388 if (pollfds == NULL || fd_lookup == NULL) {
389 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
395 info.protocols = protocols;
396 info.ssl_cert_filepath = NULL;
397 info.ssl_private_key_filepath = NULL;
398 info.ws_ping_pong_interval = pp_secs;
401 if (strlen(resource_path) > sizeof(cert_path) - 32) {
402 lwsl_err("resource path too long\n");
406 sprintf(cert_path, "%s/libwebsockets-test-server.pem",
408 if (strlen(resource_path) > sizeof(key_path) - 32) {
409 lwsl_err("resource path too long\n");
413 sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
416 info.ssl_cert_filepath = cert_path;
417 info.ssl_private_key_filepath = key_path;
419 info.ssl_ca_filepath = ca_path;
423 info.max_http_header_pool = 16;
424 info.options = opts | LWS_SERVER_OPTION_VALIDATE_UTF8 | LWS_SERVER_OPTION_EXPLICIT_VHOSTS;
425 info.extensions = exts;
426 info.timeout_secs = 5;
427 info.ssl_cipher_list = "ECDHE-ECDSA-AES256-GCM-SHA384:"
428 "ECDHE-RSA-AES256-GCM-SHA384:"
429 "DHE-RSA-AES256-GCM-SHA384:"
430 "ECDHE-RSA-AES256-SHA384:"
431 "HIGH:!aNULL:!eNULL:!EXPORT:"
432 "!DES:!MD5:!PSK:!RC4:!HMAC_SHA1:"
433 "!SHA1:!DHE-RSA-AES128-GCM-SHA256:"
434 "!DHE-RSA-AES128-SHA256:"
435 "!AES128-GCM-SHA256:"
437 "!DHE-RSA-AES256-SHA256:"
438 "!AES256-GCM-SHA384:"
442 /* redirect guys coming on http */
443 info.options |= LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS;
445 context = lws_create_context(&info);
446 if (context == NULL) {
447 lwsl_err("libwebsocket init failed\n");
451 vhost = lws_create_vhost(context, &info);
453 lwsl_err("vhost creation failed\n");
458 * For testing dynamic vhost create / destroy later, we use port + 1
459 * Normally if you were creating more vhosts, you would set info.name
460 * for each to be the hostname external clients use to reach it
465 #if !defined(LWS_NO_CLIENT) && defined(LWS_OPENSSL_SUPPORT)
466 lws_init_vhost_client_ssl(&info, vhost);
469 /* this shows how to override the lws file operations. You don't need
470 * to do any of this unless you have a reason (eg, want to serve
471 * compressed files without decompressing the whole archive)
473 /* stash original platform fops */
474 fops_plat = *(lws_get_fops(context));
475 /* override the active fops */
476 lws_get_fops(context)->open = test_server_fops_open;
482 while (n >= 0 && !force_exit) {
485 gettimeofday(&tv, NULL);
488 * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
489 * live websocket connection using the DUMB_INCREMENT protocol,
490 * as soon as it can take more packets (usually immediately)
493 ms = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
494 if ((ms - oldms) > 50) {
495 lws_callback_on_writable_all_protocol(context,
496 &protocols[PROTOCOL_DUMB_INCREMENT]);
502 * this represents an existing server's single poll action
503 * which also includes libwebsocket sockets
506 n = poll(pollfds, count_pollfds, 50);
511 for (n = 0; n < count_pollfds; n++)
512 if (pollfds[n].revents)
514 * returns immediately if the fd does not
515 * match anything under libwebsockets
518 if (lws_service_fd(context,
522 /* if needed, force-service wsis that may not have read all input */
523 while (!lws_service_adjust_timeout(context, 1, 0)) {
524 lwsl_notice("extpoll doing forced service!\n");
525 lws_service_tsi(context, -1, 0);
528 /* no revents, but before polling again, make lws check for any timeouts */
529 if (ms - ms_1sec > 1000) {
530 lwsl_notice("1 per sec\n");
531 lws_service_fd(context, NULL);
537 * If libwebsockets sockets are all we care about,
538 * you can use this api which takes care of the poll()
539 * and looping through finding who needed service.
541 * If no socket needs service, it'll return anyway after
542 * the number of ms in the second argument.
545 n = lws_service(context, 50);
548 if (dynamic_vhost_enable && !dynamic_vhost) {
549 lwsl_notice("creating dynamic vhost...\n");
550 dynamic_vhost = lws_create_vhost(context, &info);
552 if (!dynamic_vhost_enable && dynamic_vhost) {
553 lwsl_notice("destroying dynamic vhost...\n");
554 lws_vhost_destroy(dynamic_vhost);
555 dynamic_vhost = NULL;
564 lws_context_destroy(context);
566 lwsl_notice("libwebsockets-test-server exited cleanly\n");