Imported Upstream version 3.2.0
[platform/upstream/libwebsockets.git] / test-apps / test-server.c
1 /*
2  * libwebsockets-test-server - libwebsockets test implementation
3  *
4  * Written in 2010-2019 by 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 <stdio.h>
23 #include <stdlib.h>
24 #if defined(LWS_HAS_GETOPT_LONG) || defined(WIN32)
25 #include <getopt.h>
26 #endif
27 #include <signal.h>
28
29 #if defined(WIN32) || defined(_WIN32)
30 #else
31 #include <unistd.h>
32 #endif
33
34 int close_testing;
35 int max_poll_elements;
36 int debug_level = LLL_USER | 7;
37
38 #if defined(LWS_WITH_EXTERNAL_POLL)
39 struct lws_pollfd *pollfds;
40 int *fd_lookup;
41 int count_pollfds;
42 #endif
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;
48
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] = "";
54 #endif
55
56 /*
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).
60  *
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.
63  *
64  * Please consider using test-server-v2.0.c instead of this: it has the
65  * same functionality but
66  *
67  * 1) uses lws built-in http handling so you don't need to deal with it in
68  * your callback
69  *
70  * 2) Links with libuv and uses the plugins at runtime
71  *
72  * 3) Uses advanced lws features like mounts to bind parts of the filesystem
73  * to the served URL space
74  *
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.
78  */
79
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"
86 #endif
87
88 static int
89 lws_callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
90                   void *in, size_t len)
91 {
92         const unsigned char *c;
93         char buf[1024];
94         int n = 0, hlen;
95
96         switch (reason) {
97         case LWS_CALLBACK_HTTP:
98
99                 /* non-mount-handled accesses will turn up here */
100
101                 /* dump the headers */
102
103                 do {
104                         c = lws_token_to_string(n);
105                         if (!c) {
106                                 n++;
107                                 continue;
108                         }
109
110                         hlen = lws_hdr_total_length(wsi, n);
111                         if (!hlen || hlen > (int)sizeof(buf) - 1) {
112                                 n++;
113                                 continue;
114                         }
115
116                         if (lws_hdr_copy(wsi, buf, sizeof buf, n) < 0)
117                                 fprintf(stderr, "    %s (too big)\n", (char *)c);
118                         else {
119                                 buf[sizeof(buf) - 1] = '\0';
120
121                                 fprintf(stderr, "    %s = %s\n", (char *)c, buf);
122                         }
123                         n++;
124                 } while (c);
125
126                 /* dump the individual URI Arg parameters */
127
128                 n = 0;
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);
132                 }
133
134                 if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL))
135                         return -1;
136
137                 if (lws_http_transaction_completed(wsi))
138                         return -1;
139
140                 return 0;
141         default:
142                 break;
143         }
144
145         return lws_callback_http_dummy(wsi, reason, user, in, len);
146 }
147
148 /* list of supported protocols and callbacks */
149
150 static struct lws_protocols protocols[] = {
151         /* first protocol must always be HTTP handler */
152
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,
159 #endif
160         { NULL, NULL, 0, 0 } /* terminator */
161 };
162
163
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)
167  */
168 static lws_fop_fd_t
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)
172 {
173         lws_fop_fd_t fop_fd;
174
175         /* call through to original platform implementation */
176         fop_fd = fops_plat.open(fops, vfs_path, vpath, flags);
177
178         if (fop_fd)
179                 lwsl_info("%s: opening %s, ret %p, len %lu\n", __func__,
180                                 vfs_path, fop_fd,
181                                 (long)lws_vfs_get_length(fop_fd));
182         else
183                 lwsl_info("%s: open %s failed\n", __func__, vfs_path);
184
185         return fop_fd;
186 }
187
188 void sighandler(int sig)
189 {
190 #if !defined(WIN32) && !defined(_WIN32)
191         /* because windows is too dumb to have SIGUSR1... */
192         if (sig == SIGUSR1) {
193                 /*
194                  * For testing, you can fire a SIGUSR1 at the test server
195                  * to toggle the existence of an identical server on
196                  * port + 1
197                  */
198                 dynamic_vhost_enable ^= 1;
199                 lws_cancel_service(context);
200                 lwsl_notice("SIGUSR1: dynamic_vhost_enable: %d\n",
201                                 dynamic_vhost_enable);
202                 return;
203         }
204 #endif
205         force_exit = 1;
206         lws_cancel_service(context);
207 }
208
209 static const struct lws_extension exts[] = {
210         {
211                 "permessage-deflate",
212                 lws_extension_callback_pm_deflate,
213                 "permessage-deflate"
214         },
215         { NULL, NULL, NULL /* terminator */ }
216 };
217
218 /*
219  * mount handlers for sections of the URL space
220  */
221
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 */
227         NULL,
228         NULL,
229         NULL,
230         NULL,
231         0,
232         0,
233         0,
234         0,
235         0,
236         0,
237         LWSMPRO_FILE,   /* origin points to a callback */
238         8,                      /* strlen("/ziptest"), ie length of the mountpoint */
239         NULL,
240
241         { NULL, NULL } // sentinel
242 };
243
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 */
249         NULL,
250         NULL,
251         NULL,
252         NULL,
253         0,
254         0,
255         0,
256         0,
257         0,
258         0,
259         LWSMPRO_CALLBACK,       /* origin points to a callback */
260         9,                      /* strlen("/formtest"), ie length of the mountpoint */
261         NULL,
262
263         { NULL, NULL } // sentinel
264 };
265
266 /*
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
270  */
271
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 */
277         NULL,
278         NULL,
279         NULL,
280         NULL,
281         0,
282         0,
283         0,
284         0,
285         0,
286         0,
287         LWSMPRO_FILE,   /* mount type is a directory in a filesystem */
288         1,              /* strlen("/"), ie length of the mountpoint */
289         NULL,
290
291         { NULL, NULL } // sentinel
292 };
293
294 static const struct lws_protocol_vhost_options pvo_options = {
295         NULL,
296         NULL,
297         "options",              /* pvo name */
298         (void *)&test_options   /* pvo value */
299 };
300
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 */
305         ""                              /* ignored */
306 };
307
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' },
324 #endif
325 #endif
326         { "libev",  no_argument,                NULL, 'e' },
327         { "unix-socket",  required_argument,    NULL, 'U' },
328 #ifndef LWS_NO_DAEMONIZE
329         { "daemonize",  no_argument,            NULL, 'D' },
330 #endif
331         { "pingpong-secs", required_argument,   NULL, 'P' },
332         { NULL, 0, 0, 0 }
333 };
334 #endif
335
336 int main(int argc, char **argv)
337 {
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;
346         int use_ssl = 0;
347         int pp_secs = 0;
348         int opts = 0;
349         int n = 0;
350 #ifndef LWS_NO_DAEMONIZE
351         int daemonize = 0;
352 #endif
353
354         /*
355          * take care to zero down the info struct, he contains random garbaage
356          * from the stack otherwise
357          */
358         memset(&info, 0, sizeof info);
359         info.port = 7681;
360
361         while (n >= 0) {
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);
364 #else
365                 n = getopt(argc, argv, "eci:hsap:d:DC:K:A:R:vu:g:P:kU:n");
366 #endif
367                 if (n < 0)
368                         continue;
369                 switch (n) {
370                 case 'e':
371                         opts |= LWS_SERVER_OPTION_LIBEV;
372                         break;
373 #ifndef LWS_NO_DAEMONIZE
374                 case 'D':
375                         daemonize = 1;
376                         break;
377 #endif
378                 case 'u':
379                         uid = atoi(optarg);
380                         break;
381                 case 'g':
382                         gid = atoi(optarg);
383                         break;
384                 case 'd':
385                         debug_level = atoi(optarg);
386                         break;
387                 case 'n':
388                         /* no dumb increment send */
389                         test_options |= 1;
390                         break;
391                 case 's':
392                         use_ssl = 1;
393                         opts |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
394                         break;
395                 case 'a':
396                         opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
397                         break;
398                 case 'p':
399                         info.port = atoi(optarg);
400                         break;
401                 case 'i':
402                         lws_strncpy(interface_name, optarg, sizeof interface_name);
403                         iface = interface_name;
404                         break;
405                 case 'U':
406                         lws_strncpy(interface_name, optarg, sizeof interface_name);
407                         iface = interface_name;
408                         opts |= LWS_SERVER_OPTION_UNIX_SOCK;
409                         break;
410                 case 'k':
411                         info.bind_iface = 1;
412 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
413                         info.caps[0] = CAP_NET_RAW;
414                         info.count_caps = 1;
415 #endif
416                         break;
417                 case 'c':
418                         close_testing = 1;
419                         fprintf(stderr, " Close testing mode -- closes on "
420                                            "client after 50 dumb increments"
421                                            "and suppresses lws_mirror spam\n");
422                         break;
423                 case 'C':
424                         lws_strncpy(cert_path, optarg, sizeof(cert_path));
425                         break;
426                 case 'K':
427                         lws_strncpy(key_path, optarg, sizeof(key_path));
428                         break;
429                 case 'A':
430                         lws_strncpy(ca_path, optarg, sizeof(ca_path));
431                         break;
432                 case 'P':
433                         pp_secs = atoi(optarg);
434                         lwsl_notice("Setting pingpong interval to %d\n", pp_secs);
435                         break;
436 #if defined(LWS_WITH_TLS)
437                 case 'v':
438                         use_ssl = 1;
439                         opts |= LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT;
440                         break;
441
442 #if defined(LWS_HAVE_SSL_CTX_set1_param)
443                 case 'R':
444                         lws_strncpy(crl_path, optarg, sizeof(crl_path));
445                         break;
446 #endif
447 #endif
448                 case 'h':
449                         fprintf(stderr, "Usage: test-server "
450                                         "[--port=<p>] [--ssl] "
451                                         "[-d <log bitfield>]\n");
452                         exit(1);
453                 }
454         }
455
456 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
457         /*
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
461          */
462         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
463                 fprintf(stderr, "Failed to daemonize\n");
464                 return 10;
465         }
466 #endif
467
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);
473 #endif
474
475         /* tell the library what debug level to emit and to send it to stderr */
476         lws_set_log_level(debug_level, NULL);
477
478         lwsl_notice("libwebsockets test server - license LGPL2.1+SLE\n");
479         lwsl_notice("(C) Copyright 2010-2018 Andy Green <andy@warmcat.com>\n");
480
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();
485 #else
486         max_poll_elements = sysconf(_SC_OPEN_MAX);
487 #endif
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);
492                 return -1;
493         }
494 #endif
495
496         info.iface = iface;
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;
501
502         if (use_ssl) {
503                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
504                         lwsl_err("resource path too long\n");
505                         return -1;
506                 }
507                 if (!cert_path[0])
508                         sprintf(cert_path, "%s/libwebsockets-test-server.pem",
509                                                                 resource_path);
510                 if (strlen(resource_path) > sizeof(key_path) - 32) {
511                         lwsl_err("resource path too long\n");
512                         return -1;
513                 }
514                 if (!key_path[0])
515                         sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
516                                                                 resource_path);
517
518                 info.ssl_cert_filepath = cert_path;
519                 info.ssl_private_key_filepath = key_path;
520                 if (ca_path[0])
521                         info.ssl_ca_filepath = ca_path;
522         }
523         info.gid = gid;
524         info.uid = uid;
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:"
537                                "!AES128-SHA256:"
538                                "!DHE-RSA-AES256-SHA256:"
539                                "!AES256-GCM-SHA384:"
540                                "!AES256-SHA256";
541         info.mounts = &mount;
542         info.ip_limit_ah = 24; /* for testing */
543         info.ip_limit_wsi = 400; /* for testing */
544
545         if (use_ssl)
546                 /* redirect guys coming on http */
547                 info.options |= LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS;
548
549         context = lws_create_context(&info);
550         if (context == NULL) {
551                 lwsl_err("libwebsocket init failed\n");
552                 return -1;
553         }
554
555         info.pvo = &pvo;
556
557         vhost = lws_create_vhost(context, &info);
558         if (!vhost) {
559                 lwsl_err("vhost creation failed\n");
560                 return -1;
561         }
562
563         /*
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
567          */
568
569         info.port++;
570
571 #if !defined(LWS_NO_CLIENT) && defined(LWS_WITH_TLS)
572         lws_init_vhost_client_ssl(&info, vhost);
573 #endif
574
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)
578          */
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;
583
584         n = 0;
585         while (n >= 0 && !force_exit) {
586                 struct timeval tv;
587
588                 gettimeofday(&tv, NULL);
589
590                 /*
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)
594                  */
595
596 #if defined(LWS_WITH_EXTERNAL_POLL)
597                 /*
598                  * this represents an existing server's single poll action
599                  * which also includes libwebsocket sockets
600                  */
601                 n = poll(pollfds, count_pollfds, 50);
602                 if (n < 0)
603                         continue;
604
605                 if (n) {
606                         for (n = 0; n < count_pollfds; n++)
607                                 if (pollfds[n].revents)
608                                         /*
609                                         * returns immediately if the fd does not
610                                         * match anything under libwebsockets
611                                         * control
612                                         */
613                                         if (lws_service_fd(context,
614                                                                   &pollfds[n]) < 0)
615                                                 goto done;
616
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);
621                         }
622                 }
623 #else
624                 /*
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.
628                  */
629
630                 n = lws_service(context, 0);
631 #endif
632
633                 if (dynamic_vhost_enable && !dynamic_vhost) {
634                         lwsl_notice("creating dynamic vhost...\n");
635                         dynamic_vhost = lws_create_vhost(context, &info);
636                 } else
637                         if (!dynamic_vhost_enable && dynamic_vhost) {
638                                 lwsl_notice("destroying dynamic vhost...\n");
639                                 lws_vhost_destroy(dynamic_vhost);
640                                 dynamic_vhost = NULL;
641                         }
642
643         }
644
645 #if defined(LWS_WITH_EXTERNAL_POLL)
646 done:
647 #endif
648
649         lws_context_destroy(context);
650
651         lwsl_notice("libwebsockets-test-server exited cleanly\n");
652
653         return 0;
654 }