lws-meta
[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_5 = {
230         NULL,
231         NULL,
232         "lws-meta",
233         "" /* ignored, just matches the protocol name above */
234 };
235
236 static const struct lws_protocol_vhost_options pvo_4 = {
237         &pvo_5,
238         &pvo_opt4, /* set us as the protocol who gets raw connections */
239         "protocol-lws-raw-test",
240         "" /* ignored, just matches the protocol name above */
241 };
242
243 static const struct lws_protocol_vhost_options pvo_3 = {
244         &pvo_4,
245         NULL,
246         "protocol-post-demo",
247         "" /* ignored, just matches the protocol name above */
248 };
249
250 static const struct lws_protocol_vhost_options pvo_2 = {
251         &pvo_3,
252         NULL,
253         "lws-status",
254         "" /* ignored, just matches the protocol name above */
255 };
256
257 static const struct lws_protocol_vhost_options pvo_1 = {
258         &pvo_2,
259         NULL,
260         "lws-mirror-protocol",
261         ""
262 };
263
264 static const struct lws_protocol_vhost_options pvo = {
265         &pvo_1,
266         NULL, // &pvo_opt,
267         "dumb-increment-protocol",
268         ""
269 };
270
271 static void signal_cb(uv_signal_t *watcher, int signum)
272 {
273         lwsl_err("Signal %d caught, exiting...\n", watcher->signum);
274         switch (watcher->signum) {
275         case SIGTERM:
276         case SIGINT:
277                 break;
278         default:
279                 signal(SIGABRT, SIG_DFL);
280                 abort();
281                 break;
282         }
283         lws_libuv_stop(context);
284 }
285
286 static const struct option options[] = {
287         { "help",       no_argument,            NULL, 'h' },
288         { "debug",      required_argument,      NULL, 'd' },
289         { "port",       required_argument,      NULL, 'p' },
290         { "ssl",        no_argument,            NULL, 's' },
291         { "ssl-alerts", no_argument,            NULL, 'S' },
292         { "allow-non-ssl",      no_argument,    NULL, 'a' },
293         { "interface",  required_argument,      NULL, 'i' },
294         { "ssl-cert",  required_argument,       NULL, 'C' },
295         { "ssl-key",  required_argument,        NULL, 'K' },
296         { "ssl-ca",  required_argument,         NULL, 'A' },
297 #if defined(LWS_OPENSSL_SUPPORT)
298         { "ssl-verify-client",  no_argument,            NULL, 'v' },
299 #if defined(LWS_HAVE_SSL_CTX_set1_param)
300         { "ssl-crl",  required_argument,                NULL, 'R' },
301 #endif
302 #endif
303 #ifndef LWS_NO_DAEMONIZE
304         { "daemonize",  no_argument,            NULL, 'D' },
305 #endif
306         { "resource_path", required_argument,   NULL, 'r' },
307         { NULL, 0, 0, 0 }
308 };
309
310 static const char * const plugin_dirs[] = {
311                 INSTALL_DATADIR"/libwebsockets-test-server/plugins/",
312                 NULL
313 };
314
315 int main(int argc, char **argv)
316 {
317         struct lws_vhost *vhost;
318         char interface_name[128] = "";
319         const char *iface = NULL;
320         char cert_path[1024] = "";
321         char key_path[1024] = "";
322         char ca_path[1024] = "";
323         int uid = -1, gid = -1;
324         int use_ssl = 0;
325         int opts = 0;
326         int n = 0;
327 #ifndef _WIN32
328         int syslog_options = LOG_PID | LOG_PERROR;
329 #endif
330 #ifndef LWS_NO_DAEMONIZE
331         int daemonize = 0;
332 #endif
333
334         /*
335          * take care to zero down the info struct, he contains random garbaage
336          * from the stack otherwise
337          */
338         memset(&info, 0, sizeof info);
339         info.port = 7681;
340
341         while (n >= 0) {
342                 n = getopt_long(argc, argv, "i:hsap:d:Dr:C:K:A:R:vu:g:S",
343                                 (struct option *)options, NULL);
344                 if (n < 0)
345                         continue;
346                 switch (n) {
347 #ifndef LWS_NO_DAEMONIZE
348                 case 'D':
349                         daemonize = 1;
350                         #ifndef _WIN32
351                         syslog_options &= ~LOG_PERROR;
352                         #endif
353                         break;
354 #endif
355                 case 'u':
356                         uid = atoi(optarg);
357                         break;
358                 case 'g':
359                         gid = atoi(optarg);
360                         break;
361                 case 'd':
362                         debug_level = atoi(optarg);
363                         break;
364                 case 's':
365                         use_ssl = 1;
366                         break;
367                 case 'S':
368 #if defined(LWS_OPENSSL_SUPPORT)
369                         info.ssl_info_event_mask |= SSL_CB_ALERT;
370 #endif
371                         break;
372                 case 'a':
373                         opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
374                         break;
375                 case 'p':
376                         info.port = atoi(optarg);
377                         break;
378                 case 'i':
379                         strncpy(interface_name, optarg, sizeof interface_name);
380                         interface_name[(sizeof interface_name) - 1] = '\0';
381                         iface = interface_name;
382                         break;
383                 case 'r':
384                         resource_path = optarg;
385                         printf("Setting resource path to \"%s\"\n", resource_path);
386                         break;
387                 case 'C':
388                         strncpy(cert_path, optarg, sizeof(cert_path) - 1);
389                         cert_path[sizeof(cert_path) - 1] = '\0';
390                         break;
391                 case 'K':
392                         strncpy(key_path, optarg, sizeof(key_path) - 1);
393                         key_path[sizeof(key_path) - 1] = '\0';
394                         break;
395                 case 'A':
396                         strncpy(ca_path, optarg, sizeof(ca_path) - 1);
397                         ca_path[sizeof(ca_path) - 1] = '\0';
398                         break;
399 #if defined(LWS_OPENSSL_SUPPORT)
400                 case 'v':
401                         use_ssl = 1;
402                         opts |= LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT;
403                         break;
404
405 #if defined(LWS_HAVE_SSL_CTX_set1_param)
406                 case 'R':
407                         strncpy(crl_path, optarg, sizeof(crl_path) - 1);
408                         crl_path[sizeof(crl_path) - 1] = '\0';
409                         break;
410 #endif
411 #endif
412                 case 'h':
413                         fprintf(stderr, "Usage: test-server "
414                                         "[--port=<p>] [--ssl] "
415                                         "[-d <log bitfield>] "
416                                         "[--resource_path <path>]\n");
417                         exit(1);
418                 }
419         }
420
421 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
422         /*
423          * normally lock path would be /var/lock/lwsts or similar, to
424          * simplify getting started without having to take care about
425          * permissions or running as root, set to /tmp/.lwsts-lock
426          */
427         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
428                 fprintf(stderr, "Failed to daemonize\n");
429                 return 10;
430         }
431 #endif
432
433         signal(SIGINT, sighandler);
434 #if defined(TEST_DYNAMIC_VHOST)
435         signal(SIGUSR1, sighandler_USR1);
436 #endif
437
438 #ifndef _WIN32
439         /* we will only try to log things according to our debug_level */
440         setlogmask(LOG_UPTO (LOG_DEBUG));
441         openlog("lwsts", syslog_options, LOG_DAEMON);
442 #endif
443
444         /* tell the library what debug level to emit and to send it to syslog */
445         lws_set_log_level(debug_level, lwsl_emit_syslog);
446
447         lwsl_notice("libwebsockets test server - license LGPL2.1+SLE\n");
448         lwsl_notice("(C) Copyright 2010-2017 Andy Green <andy@warmcat.com>\n");
449
450         lwsl_notice(" Using resource path \"%s\"\n", resource_path);
451
452         info.iface = iface;
453         info.protocols = NULL; /* all protocols from lib / plugins */
454         info.ssl_cert_filepath = NULL;
455         info.ssl_private_key_filepath = NULL;
456         info.gid = gid;
457         info.uid = uid;
458         info.max_http_header_pool = 16;
459         info.options = opts | LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
460                         LWS_SERVER_OPTION_FALLBACK_TO_RAW |
461                         LWS_SERVER_OPTION_VALIDATE_UTF8 |
462                         LWS_SERVER_OPTION_LIBUV; /* plugins require this */
463
464         if (use_ssl) {
465                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
466                         lwsl_err("resource path too long\n");
467                         return -1;
468                 }
469                 if (!cert_path[0])
470                         sprintf(cert_path, "%s/libwebsockets-test-server.pem",
471                                 resource_path);
472                 if (strlen(resource_path) > sizeof(key_path) - 32) {
473                         lwsl_err("resource path too long\n");
474                         return -1;
475                 }
476                 if (!key_path[0])
477                         sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
478                                 resource_path);
479
480                 info.ssl_cert_filepath = cert_path;
481                 info.ssl_private_key_filepath = key_path;
482                 if (ca_path[0])
483                         info.ssl_ca_filepath = ca_path;
484
485                 /* redirect guys coming on http */
486                 info.options |= LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS;
487         }
488
489         info.extensions = exts;
490         info.timeout_secs = 5;
491         info.ssl_cipher_list = "ECDHE-ECDSA-AES256-GCM-SHA384:"
492                                "ECDHE-RSA-AES256-GCM-SHA384:"
493                                "DHE-RSA-AES256-GCM-SHA384:"
494                                "ECDHE-RSA-AES256-SHA384:"
495                                "HIGH:!aNULL:!eNULL:!EXPORT:"
496                                "!DES:!MD5:!PSK:!RC4:!HMAC_SHA1:"
497                                "!SHA1:!DHE-RSA-AES128-GCM-SHA256:"
498                                "!DHE-RSA-AES128-SHA256:"
499                                "!AES128-GCM-SHA256:"
500                                "!AES128-SHA256:"
501                                "!DHE-RSA-AES256-SHA256:"
502                                "!AES256-GCM-SHA384:"
503                                "!AES256-SHA256";
504
505         /* tell lws to look for protocol plugins here */
506         info.plugin_dirs = plugin_dirs;
507
508         /* tell lws about our mount we want */
509         info.mounts = &mount;
510         /*
511          * give it our linked-list of Per-Vhost Options, these control
512          * which protocols (from plugins) are allowed to be enabled on
513          * our vhost
514          */
515         info.pvo = &pvo;
516
517         /*
518          * Since we used LWS_SERVER_OPTION_EXPLICIT_VHOSTS, this only creates
519          * the context.  We can modify info and create as many vhosts as we
520          * like subsequently.
521          */
522         context = lws_create_context(&info);
523         if (context == NULL) {
524                 lwsl_err("libwebsocket init failed\n");
525                 return -1;
526         }
527
528         /*
529          *  normally we would adapt at least info.name to reflect the
530          * external hostname for this server.
531          */
532         vhost = lws_create_vhost(context, &info);
533         if (!vhost) {
534                 lwsl_err("vhost creation failed\n");
535                 return -1;
536         }
537
538 #if defined(TEST_DYNAMIC_VHOST)
539         /* our dynamic vhost is on port + 1 */
540         info.port++;
541 #endif
542
543         /* libuv event loop */
544         lws_uv_sigint_cfg(context, 1, signal_cb);
545         if (lws_uv_initloop(context, NULL, 0)) {
546                 lwsl_err("lws_uv_initloop failed\n");
547                 goto bail;
548         }
549
550 #if defined(TEST_DYNAMIC_VHOST)
551         uv_timer_init(lws_uv_getloop(context, 0), &timeout_watcher);
552 #endif
553         lws_libuv_run(context, 0);
554
555 #if defined(TEST_DYNAMIC_VHOST)
556         uv_timer_stop(&timeout_watcher);
557         uv_close((uv_handle_t *)&timeout_watcher, NULL);
558 #endif
559
560 bail:
561         /* when we decided to exit the event loop */
562         lws_context_destroy(context);
563         lws_context_destroy2(context);
564         lwsl_notice("libwebsockets-test-server exited cleanly\n");
565
566 #ifndef _WIN32
567         closelog();
568 #endif
569
570         return 0;
571 }