lws-vhost-destroy
[platform/upstream/libwebsockets.git] / test-server / test-server-v2.0.c
1 /*
2  * libwebsockets-test-server-v2.0 - libwebsockets test implementation
3  *
4  * Copyright (C) 2010-2016 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  * 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.
15  *
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
18  * Public Domain.
19  */
20
21 #include <libwebsockets.h>
22 #include <string.h>
23 #include <getopt.h>
24 #ifndef WIN32
25 #include <syslog.h>
26 #endif
27
28 /* windows has no SIGUSR1 */
29 #if !defined(WIN32) && !defined(_WIN32)
30 #define TEST_DYNAMIC_VHOST
31 #endif
32
33 struct lws_context_creation_info info;
34 int debug_level = 7;
35 struct lws_context *context;
36
37 #if defined(TEST_DYNAMIC_VHOST)
38 volatile int dynamic_vhost_enable = 0;
39 struct lws_vhost *dynamic_vhost;
40 uv_timer_t timeout_watcher;
41 #endif
42
43 /* http server gets files from this path */
44 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
45 char *resource_path = LOCAL_RESOURCE_PATH;
46
47 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
48 char crl_path[1024] = "";
49 #endif
50
51 /*
52  * This test server is ONLY this .c file, it's radically simpler than the
53  * pre-v2.0 test servers.  For example it has no user callback content or
54  * defines any protocols.
55  *
56  * To achieve that, it uses the LWS protocol plugins.  Those in turn
57  * use libuv.  So you must configure with LWS_WITH_PLUGINS (which implies
58  * libuv) to get this to build.
59  *
60  * You can find the individual protocol plugin sources in ../plugins
61  */
62
63 #if defined(TEST_DYNAMIC_VHOST)
64
65 /*
66  *  to test dynamic vhost creation, fire a SIGUSR1 at the test server.
67  * It will toggle the existence of a second identical vhost at port + 1
68  *
69  * To synchronize with the event loop, it uses a libuv timer with 0 delay
70  * to get the business end called as the next event.
71  */
72
73 static void
74 uv_timeout_dynamic_vhost_toggle(uv_timer_t *w
75 #if UV_VERSION_MAJOR == 0
76                 , int status
77 #endif
78 )
79 {
80         if (dynamic_vhost_enable && !dynamic_vhost) {
81                 lwsl_notice("creating dynamic vhost...\n");
82                 dynamic_vhost = lws_create_vhost(context, &info);
83         } else
84                 if (!dynamic_vhost_enable && dynamic_vhost) {
85                         lwsl_notice("destroying dynamic vhost...\n");
86                         lws_vhost_destroy(dynamic_vhost);
87                         dynamic_vhost = NULL;
88                 }
89 }
90
91 void sighandler_USR1(int sig)
92 {
93         dynamic_vhost_enable ^= 1;
94         lwsl_notice("SIGUSR1: dynamic_vhost_enable: %d\n",
95                         dynamic_vhost_enable);
96         uv_timer_start(&timeout_watcher,
97                        uv_timeout_dynamic_vhost_toggle, 0, 0);
98 }
99 #endif
100
101 void sighandler(int sig)
102 {
103         lws_cancel_service(context);
104 }
105
106 static const struct lws_extension exts[] = {
107         {
108                 "permessage-deflate",
109                 lws_extension_callback_pm_deflate,
110                 "permessage-deflate"
111         },
112         {
113                 "deflate-frame",
114                 lws_extension_callback_pm_deflate,
115                 "deflate_frame"
116         },
117         { NULL, NULL, NULL /* terminator */ }
118 };
119
120 /*
121  * mount handlers for sections of the URL space
122  */
123
124 static const struct lws_http_mount mount_ziptest = {
125         NULL,                   /* linked-list pointer to next*/
126         "/ziptest",             /* mountpoint in URL namespace on this vhost */
127         LOCAL_RESOURCE_PATH"/candide.zip",      /* handler */
128         NULL,   /* default filename if none given */
129         NULL,
130         NULL,
131         NULL,
132         NULL,
133         0,
134         0,
135         0,
136         0,
137         0,
138         0,
139         LWSMPRO_FILE,   /* origin points to a callback */
140         8,                      /* strlen("/ziptest"), ie length of the mountpoint */
141         NULL,
142
143         { NULL, NULL } // sentinel
144 };
145
146 static const struct lws_http_mount mount_post = {
147         (struct lws_http_mount *)&mount_ziptest, /* linked-list pointer to next*/
148         "/formtest",            /* mountpoint in URL namespace on this vhost */
149         "protocol-post-demo",   /* handler */
150         NULL,   /* default filename if none given */
151         NULL,
152         NULL,
153         NULL,
154         NULL,
155         0,
156         0,
157         0,
158         0,
159         0,
160         0,
161         LWSMPRO_CALLBACK,       /* origin points to a callback */
162         9,                      /* strlen("/formtest"), ie length of the mountpoint */
163         NULL,
164
165         { NULL, NULL } // sentinel
166 };
167
168 /*
169  * mount a filesystem directory into the URL space at /
170  * point it to our /usr/share directory with our assets in
171  * stuff from here is autoserved by the library
172  */
173
174 static const struct lws_http_mount mount = {
175         (struct lws_http_mount *)&mount_post,   /* linked-list pointer to next*/
176         "/",            /* mountpoint in URL namespace on this vhost */
177         LOCAL_RESOURCE_PATH, /* where to go on the filesystem for that */
178         "test.html",    /* default filename if none given */
179         NULL,
180         NULL,
181         NULL,
182         NULL,
183         0,
184         0,
185         0,
186         0,
187         0,
188         0,
189         LWSMPRO_FILE,   /* mount type is a directory in a filesystem */
190         1,              /* strlen("/"), ie length of the mountpoint */
191         NULL,
192
193         { NULL, NULL } // sentinel
194 };
195
196 /*
197  * this sets a per-vhost, per-protocol option name:value pair
198  * the effect is to set this protocol to be the default one for the vhost,
199  * ie, selected if no Protocol: header is sent with the ws upgrade.
200  */
201 #if 0
202 static const struct lws_protocol_vhost_options pvo_opt = {
203         NULL,
204         NULL,
205         "default",
206         "1"
207 };
208 #endif
209
210 static const struct lws_protocol_vhost_options pvo_opt4a = {
211         NULL,
212         NULL,
213         "raw", /* indicate we are the protocol that gets raw connections */
214         "1"
215 };
216
217 static const struct lws_protocol_vhost_options pvo_opt4 = {
218         &pvo_opt4a,
219         NULL,
220         "fifo-path", /* tell the raw test plugin to open a raw file here */
221         "/tmp/lws-test-raw"
222 };
223
224 /*
225  * We must enable the plugin protocols we want into our vhost with a
226  * linked-list.  We can also give the plugin per-vhost options here.
227  */
228
229 static const struct lws_protocol_vhost_options pvo_4 = {
230         NULL,
231         &pvo_opt4, /* set us as the protocol who gets raw connections */
232         "protocol-lws-raw-test",
233         "" /* ignored, just matches the protocol name above */
234 };
235
236 static const struct lws_protocol_vhost_options pvo_3 = {
237         &pvo_4,
238         NULL,
239         "protocol-post-demo",
240         "" /* ignored, just matches the protocol name above */
241 };
242
243 static const struct lws_protocol_vhost_options pvo_2 = {
244         &pvo_3,
245         NULL,
246         "lws-status",
247         "" /* ignored, just matches the protocol name above */
248 };
249
250 static const struct lws_protocol_vhost_options pvo_1 = {
251         &pvo_2,
252         NULL,
253         "lws-mirror-protocol",
254         ""
255 };
256
257 static const struct lws_protocol_vhost_options pvo = {
258         &pvo_1,
259         NULL, // &pvo_opt,
260         "dumb-increment-protocol",
261         ""
262 };
263
264 static void signal_cb(uv_signal_t *watcher, int signum)
265 {
266         lwsl_err("Signal %d caught, exiting...\n", watcher->signum);
267         switch (watcher->signum) {
268         case SIGTERM:
269         case SIGINT:
270                 break;
271         default:
272                 signal(SIGABRT, SIG_DFL);
273                 abort();
274                 break;
275         }
276         lws_libuv_stop(context);
277 }
278
279 static const struct option options[] = {
280         { "help",       no_argument,            NULL, 'h' },
281         { "debug",      required_argument,      NULL, 'd' },
282         { "port",       required_argument,      NULL, 'p' },
283         { "ssl",        no_argument,            NULL, 's' },
284         { "ssl-alerts", no_argument,            NULL, 'S' },
285         { "allow-non-ssl",      no_argument,    NULL, 'a' },
286         { "interface",  required_argument,      NULL, 'i' },
287         { "ssl-cert",  required_argument,       NULL, 'C' },
288         { "ssl-key",  required_argument,        NULL, 'K' },
289         { "ssl-ca",  required_argument,         NULL, 'A' },
290 #if defined(LWS_OPENSSL_SUPPORT)
291         { "ssl-verify-client",  no_argument,            NULL, 'v' },
292 #if defined(LWS_HAVE_SSL_CTX_set1_param)
293         { "ssl-crl",  required_argument,                NULL, 'R' },
294 #endif
295 #endif
296 #ifndef LWS_NO_DAEMONIZE
297         { "daemonize",  no_argument,            NULL, 'D' },
298 #endif
299         { "resource_path", required_argument,   NULL, 'r' },
300         { NULL, 0, 0, 0 }
301 };
302
303 static const char * const plugin_dirs[] = {
304                 INSTALL_DATADIR"/libwebsockets-test-server/plugins/",
305                 NULL
306 };
307
308 int main(int argc, char **argv)
309 {
310         struct lws_vhost *vhost;
311         char interface_name[128] = "";
312         const char *iface = NULL;
313         char cert_path[1024] = "";
314         char key_path[1024] = "";
315         char ca_path[1024] = "";
316         int uid = -1, gid = -1;
317         int use_ssl = 0;
318         int opts = 0;
319         int n = 0;
320 #ifndef _WIN32
321         int syslog_options = LOG_PID | LOG_PERROR;
322 #endif
323 #ifndef LWS_NO_DAEMONIZE
324         int daemonize = 0;
325 #endif
326
327         /*
328          * take care to zero down the info struct, he contains random garbaage
329          * from the stack otherwise
330          */
331         memset(&info, 0, sizeof info);
332         info.port = 7681;
333
334         while (n >= 0) {
335                 n = getopt_long(argc, argv, "i:hsap:d:Dr:C:K:A:R:vu:g:S",
336                                 (struct option *)options, NULL);
337                 if (n < 0)
338                         continue;
339                 switch (n) {
340 #ifndef LWS_NO_DAEMONIZE
341                 case 'D':
342                         daemonize = 1;
343                         #ifndef _WIN32
344                         syslog_options &= ~LOG_PERROR;
345                         #endif
346                         break;
347 #endif
348                 case 'u':
349                         uid = atoi(optarg);
350                         break;
351                 case 'g':
352                         gid = atoi(optarg);
353                         break;
354                 case 'd':
355                         debug_level = atoi(optarg);
356                         break;
357                 case 's':
358                         use_ssl = 1;
359                         break;
360                 case 'S':
361 #if defined(LWS_OPENSSL_SUPPORT)
362                         info.ssl_info_event_mask |= SSL_CB_ALERT;
363 #endif
364                         break;
365                 case 'a':
366                         opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
367                         break;
368                 case 'p':
369                         info.port = atoi(optarg);
370                         break;
371                 case 'i':
372                         strncpy(interface_name, optarg, sizeof interface_name);
373                         interface_name[(sizeof interface_name) - 1] = '\0';
374                         iface = interface_name;
375                         break;
376                 case 'r':
377                         resource_path = optarg;
378                         printf("Setting resource path to \"%s\"\n", resource_path);
379                         break;
380                 case 'C':
381                         strncpy(cert_path, optarg, sizeof(cert_path) - 1);
382                         cert_path[sizeof(cert_path) - 1] = '\0';
383                         break;
384                 case 'K':
385                         strncpy(key_path, optarg, sizeof(key_path) - 1);
386                         key_path[sizeof(key_path) - 1] = '\0';
387                         break;
388                 case 'A':
389                         strncpy(ca_path, optarg, sizeof(ca_path) - 1);
390                         ca_path[sizeof(ca_path) - 1] = '\0';
391                         break;
392 #if defined(LWS_OPENSSL_SUPPORT)
393                 case 'v':
394                         use_ssl = 1;
395                         opts |= LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT;
396                         break;
397
398 #if defined(LWS_HAVE_SSL_CTX_set1_param)
399                 case 'R':
400                         strncpy(crl_path, optarg, sizeof(crl_path) - 1);
401                         crl_path[sizeof(crl_path) - 1] = '\0';
402                         break;
403 #endif
404 #endif
405                 case 'h':
406                         fprintf(stderr, "Usage: test-server "
407                                         "[--port=<p>] [--ssl] "
408                                         "[-d <log bitfield>] "
409                                         "[--resource_path <path>]\n");
410                         exit(1);
411                 }
412         }
413
414 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
415         /*
416          * normally lock path would be /var/lock/lwsts or similar, to
417          * simplify getting started without having to take care about
418          * permissions or running as root, set to /tmp/.lwsts-lock
419          */
420         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
421                 fprintf(stderr, "Failed to daemonize\n");
422                 return 10;
423         }
424 #endif
425
426         signal(SIGINT, sighandler);
427 #if defined(TEST_DYNAMIC_VHOST)
428         signal(SIGUSR1, sighandler_USR1);
429 #endif
430
431 #ifndef _WIN32
432         /* we will only try to log things according to our debug_level */
433         setlogmask(LOG_UPTO (LOG_DEBUG));
434         openlog("lwsts", syslog_options, LOG_DAEMON);
435 #endif
436
437         /* tell the library what debug level to emit and to send it to syslog */
438         lws_set_log_level(debug_level, lwsl_emit_syslog);
439
440         lwsl_notice("libwebsockets test server - license LGPL2.1+SLE\n");
441         lwsl_notice("(C) Copyright 2010-2017 Andy Green <andy@warmcat.com>\n");
442
443         lwsl_notice(" Using resource path \"%s\"\n", resource_path);
444
445         info.iface = iface;
446         info.protocols = NULL; /* all protocols from lib / plugins */
447         info.ssl_cert_filepath = NULL;
448         info.ssl_private_key_filepath = NULL;
449         info.gid = gid;
450         info.uid = uid;
451         info.max_http_header_pool = 16;
452         info.options = opts | LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
453                         LWS_SERVER_OPTION_FALLBACK_TO_RAW |
454                         LWS_SERVER_OPTION_VALIDATE_UTF8 |
455                         LWS_SERVER_OPTION_LIBUV; /* plugins require this */
456
457         if (use_ssl) {
458                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
459                         lwsl_err("resource path too long\n");
460                         return -1;
461                 }
462                 if (!cert_path[0])
463                         sprintf(cert_path, "%s/libwebsockets-test-server.pem",
464                                 resource_path);
465                 if (strlen(resource_path) > sizeof(key_path) - 32) {
466                         lwsl_err("resource path too long\n");
467                         return -1;
468                 }
469                 if (!key_path[0])
470                         sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
471                                 resource_path);
472
473                 info.ssl_cert_filepath = cert_path;
474                 info.ssl_private_key_filepath = key_path;
475                 if (ca_path[0])
476                         info.ssl_ca_filepath = ca_path;
477
478                 /* redirect guys coming on http */
479                 info.options |= LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS;
480         }
481
482         info.extensions = exts;
483         info.timeout_secs = 5;
484         info.ssl_cipher_list = "ECDHE-ECDSA-AES256-GCM-SHA384:"
485                                "ECDHE-RSA-AES256-GCM-SHA384:"
486                                "DHE-RSA-AES256-GCM-SHA384:"
487                                "ECDHE-RSA-AES256-SHA384:"
488                                "HIGH:!aNULL:!eNULL:!EXPORT:"
489                                "!DES:!MD5:!PSK:!RC4:!HMAC_SHA1:"
490                                "!SHA1:!DHE-RSA-AES128-GCM-SHA256:"
491                                "!DHE-RSA-AES128-SHA256:"
492                                "!AES128-GCM-SHA256:"
493                                "!AES128-SHA256:"
494                                "!DHE-RSA-AES256-SHA256:"
495                                "!AES256-GCM-SHA384:"
496                                "!AES256-SHA256";
497
498         /* tell lws to look for protocol plugins here */
499         info.plugin_dirs = plugin_dirs;
500
501         /* tell lws about our mount we want */
502         info.mounts = &mount;
503         /*
504          * give it our linked-list of Per-Vhost Options, these control
505          * which protocols (from plugins) are allowed to be enabled on
506          * our vhost
507          */
508         info.pvo = &pvo;
509
510         /*
511          * Since we used LWS_SERVER_OPTION_EXPLICIT_VHOSTS, this only creates
512          * the context.  We can modify info and create as many vhosts as we
513          * like subsequently.
514          */
515         context = lws_create_context(&info);
516         if (context == NULL) {
517                 lwsl_err("libwebsocket init failed\n");
518                 return -1;
519         }
520
521         /*
522          *  normally we would adapt at least info.name to reflect the
523          * external hostname for this server.
524          */
525         vhost = lws_create_vhost(context, &info);
526         if (!vhost) {
527                 lwsl_err("vhost creation failed\n");
528                 return -1;
529         }
530
531 #if defined(TEST_DYNAMIC_VHOST)
532         /* our dynamic vhost is on port + 1 */
533         info.port++;
534 #endif
535
536         /* libuv event loop */
537         lws_uv_sigint_cfg(context, 1, signal_cb);
538         if (lws_uv_initloop(context, NULL, 0)) {
539                 lwsl_err("lws_uv_initloop failed\n");
540                 goto bail;
541         }
542
543 #if defined(TEST_DYNAMIC_VHOST)
544         uv_timer_init(lws_uv_getloop(context, 0), &timeout_watcher);
545 #endif
546         lws_libuv_run(context, 0);
547
548 #if defined(TEST_DYNAMIC_VHOST)
549         uv_timer_stop(&timeout_watcher);
550         uv_close((uv_handle_t *)&timeout_watcher, NULL);
551 #endif
552
553 bail:
554         /* when we decided to exit the event loop */
555         lws_context_destroy(context);
556         lws_context_destroy2(context);
557         lwsl_notice("libwebsockets-test-server exited cleanly\n");
558
559 #ifndef _WIN32
560         closelog();
561 #endif
562
563         return 0;
564 }