5656928085da4ea72ba534967aa472ab5cf4c27f
[platform/upstream/libwebsockets.git] / test-server / test-server.c
1 /*
2  * libwebsockets-test-server - 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 "test-server.h"
22
23 int close_testing;
24 int max_poll_elements;
25 int debug_level = 7;
26
27 #ifdef EXTERNAL_POLL
28 struct lws_pollfd *pollfds;
29 int *fd_lookup;
30 int count_pollfds;
31 #endif
32 volatile int force_exit = 0;
33 struct lws_context *context;
34 struct lws_plat_file_ops fops_plat;
35
36 /* http server gets files from this path */
37 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
38 char *resource_path = LOCAL_RESOURCE_PATH;
39 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
40 char crl_path[1024] = "";
41 #endif
42
43 /*
44  * This demonstrates how to use the clean protocol service separation of
45  * plugins, but with static inclusion instead of runtime dynamic loading
46  * (which requires libuv).
47  *
48  * dumb-increment doesn't use the plugin, both to demonstrate how to
49  * do the protocols directly, and because it wants libuv for a timer.
50  *
51  * Please consider using test-server-v2.0.c instead of this: it has the
52  * same functionality but
53  *
54  * 1) uses lws built-in http handling so you don't need to deal with it in
55  * your callback
56  *
57  * 2) Links with libuv and uses the plugins at runtime
58  *
59  * 3) Uses advanced lws features like mounts to bind parts of the filesystem
60  * to the served URL space
61  *
62  * Another option is lwsws, this operates like test-server-v2,0.c but is
63  * configured using JSON, do you do not need to provide any code for the
64  * serving action at all, just implement your protocols in plugins.
65  */
66
67 #define LWS_PLUGIN_STATIC
68 #include "../plugins/protocol_lws_mirror.c"
69 #include "../plugins/protocol_lws_status.c"
70
71 /* singlethreaded version --> no locks */
72
73 void test_server_lock(int care)
74 {
75 }
76 void test_server_unlock(int care)
77 {
78 }
79
80 /*
81  * This demo server shows how to use libwebsockets for one or more
82  * websocket protocols in the same server
83  *
84  * It defines the following websocket protocols:
85  *
86  *  dumb-increment-protocol:  once the socket is opened, an incrementing
87  *                              ascii string is sent down it every 50ms.
88  *                              If you send "reset\n" on the websocket, then
89  *                              the incrementing number is reset to 0.
90  *
91  *  lws-mirror-protocol: copies any received packet to every connection also
92  *                              using this protocol, including the sender
93  *
94  *  lws-status:                 informs connected browsers of who else is
95  *                              connected.
96  */
97
98 enum demo_protocols {
99         /* always first */
100         PROTOCOL_HTTP = 0,
101
102         PROTOCOL_DUMB_INCREMENT,
103         PROTOCOL_LWS_MIRROR,
104         PROTOCOL_LWS_STATUS,
105
106         /* always last */
107         DEMO_PROTOCOL_COUNT
108 };
109
110 /* list of supported protocols and callbacks */
111
112 static struct lws_protocols protocols[] = {
113         /* first protocol must always be HTTP handler */
114
115         {
116                 "http-only",            /* name */
117                 callback_http,          /* callback */
118                 sizeof (struct per_session_data__http), /* per_session_data_size */
119                 0,                      /* max frame size / rx buffer */
120         },
121         {
122                 "dumb-increment-protocol",
123                 callback_dumb_increment,
124                 sizeof(struct per_session_data__dumb_increment),
125                 10, /* rx buf size must be >= permessage-deflate rx size
126                      * dumb-increment only sends very small packets, so we set
127                      * this accordingly.  If your protocol will send bigger
128                      * things, adjust this to match */
129         },
130         LWS_PLUGIN_PROTOCOL_MIRROR,
131         LWS_PLUGIN_PROTOCOL_LWS_STATUS,
132         { NULL, NULL, 0, 0 } /* terminator */
133 };
134
135
136 /* this shows how to override the lws file operations.  You don't need
137  * to do any of this unless you have a reason (eg, want to serve
138  * compressed files without decompressing the whole archive)
139  */
140 static lws_fop_fd_t
141 test_server_fops_open(const struct lws_plat_file_ops *fops,
142                      const char *vfs_path, const char *vpath,
143                      lws_fop_flags_t *flags)
144 {
145         lws_fop_fd_t fop_fd;
146
147         /* call through to original platform implementation */
148         fop_fd = fops_plat.open(fops, vfs_path, vpath, flags);
149
150         if (fop_fd)
151                 lwsl_info("%s: opening %s, ret %p, len %lu\n", __func__,
152                                 vfs_path, fop_fd,
153                                 (long)lws_vfs_get_length(fop_fd));
154         else
155                 lwsl_info("%s: open %s failed\n", __func__, vfs_path);
156
157         return fop_fd;
158 }
159
160 void sighandler(int sig)
161 {
162         force_exit = 1;
163         lws_cancel_service(context);
164 }
165
166 static const struct lws_extension exts[] = {
167         {
168                 "permessage-deflate",
169                 lws_extension_callback_pm_deflate,
170                 "permessage-deflate"
171         },
172         {
173                 "deflate-frame",
174                 lws_extension_callback_pm_deflate,
175                 "deflate_frame"
176         },
177         { NULL, NULL, NULL /* terminator */ }
178 };
179
180
181
182 static struct option options[] = {
183         { "help",       no_argument,            NULL, 'h' },
184         { "debug",      required_argument,      NULL, 'd' },
185         { "port",       required_argument,      NULL, 'p' },
186         { "ssl",        no_argument,            NULL, 's' },
187         { "allow-non-ssl",      no_argument,    NULL, 'a' },
188         { "interface",  required_argument,      NULL, 'i' },
189         { "closetest",  no_argument,            NULL, 'c' },
190         { "ssl-cert",  required_argument,       NULL, 'C' },
191         { "ssl-key",  required_argument,        NULL, 'K' },
192         { "ssl-ca",  required_argument,         NULL, 'A' },
193 #if defined(LWS_OPENSSL_SUPPORT)
194         { "ssl-verify-client",  no_argument,            NULL, 'v' },
195 #if defined(LWS_HAVE_SSL_CTX_set1_param)
196         { "ssl-crl",  required_argument,                NULL, 'R' },
197 #endif
198 #endif
199         { "libev",  no_argument,                NULL, 'e' },
200 #ifndef LWS_NO_DAEMONIZE
201         { "daemonize",  no_argument,            NULL, 'D' },
202 #endif
203         { "resource_path", required_argument,   NULL, 'r' },
204         { "pingpong-secs", required_argument,   NULL, 'P' },
205         { NULL, 0, 0, 0 }
206 };
207
208 int main(int argc, char **argv)
209 {
210         struct lws_context_creation_info info;
211         struct lws_vhost *vhost;
212         char interface_name[128] = "";
213         unsigned int ms, oldms = 0;
214         const char *iface = NULL;
215         char cert_path[1024] = "";
216         char key_path[1024] = "";
217         char ca_path[1024] = "";
218         int uid = -1, gid = -1;
219         int use_ssl = 0;
220         int pp_secs = 0;
221         int opts = 0;
222         int n = 0;
223 #ifndef _WIN32
224 /* LOG_PERROR is not POSIX standard, and may not be portable */
225 #ifdef __sun
226         int syslog_options = LOG_PID;
227 #else        
228         int syslog_options = LOG_PID | LOG_PERROR;
229 #endif
230 #endif
231 #ifndef LWS_NO_DAEMONIZE
232         int daemonize = 0;
233 #endif
234
235         /*
236          * take care to zero down the info struct, he contains random garbaage
237          * from the stack otherwise
238          */
239         memset(&info, 0, sizeof info);
240         info.port = 7681;
241
242         while (n >= 0) {
243                 n = getopt_long(argc, argv, "eci:hsap:d:Dr:C:K:A:R:vu:g:P:k", options, NULL);
244                 if (n < 0)
245                         continue;
246                 switch (n) {
247                 case 'e':
248                         opts |= LWS_SERVER_OPTION_LIBEV;
249                         break;
250 #ifndef LWS_NO_DAEMONIZE
251                 case 'D':
252                         daemonize = 1;
253                         #if !defined(_WIN32) && !defined(__sun)
254                         syslog_options &= ~LOG_PERROR;
255                         #endif
256                         break;
257 #endif
258                 case 'u':
259                         uid = atoi(optarg);
260                         break;
261                 case 'g':
262                         gid = atoi(optarg);
263                         break;
264                 case 'd':
265                         debug_level = atoi(optarg);
266                         break;
267                 case 's':
268                         use_ssl = 1;
269                         opts |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
270                         break;
271                 case 'a':
272                         opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
273                         break;
274                 case 'p':
275                         info.port = atoi(optarg);
276                         break;
277                 case 'i':
278                         strncpy(interface_name, optarg, sizeof interface_name);
279                         interface_name[(sizeof interface_name) - 1] = '\0';
280                         iface = interface_name;
281                         break;
282                 case 'k':
283                         info.bind_iface = 1;
284 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
285                         info.caps[0] = CAP_NET_RAW;
286                         info.count_caps = 1;
287 #endif
288                         break;
289                 case 'c':
290                         close_testing = 1;
291                         fprintf(stderr, " Close testing mode -- closes on "
292                                            "client after 50 dumb increments"
293                                            "and suppresses lws_mirror spam\n");
294                         break;
295                 case 'r':
296                         resource_path = optarg;
297                         printf("Setting resource path to \"%s\"\n", resource_path);
298                         break;
299                 case 'C':
300                         strncpy(cert_path, optarg, sizeof(cert_path) - 1);
301                         cert_path[sizeof(cert_path) - 1] = '\0';
302                         break;
303                 case 'K':
304                         strncpy(key_path, optarg, sizeof(key_path) - 1);
305                         key_path[sizeof(key_path) - 1] = '\0';
306                         break;
307                 case 'A':
308                         strncpy(ca_path, optarg, sizeof(ca_path) - 1);
309                         ca_path[sizeof(ca_path) - 1] = '\0';
310                         break;
311                 case 'P':
312                         pp_secs = atoi(optarg);
313                         lwsl_notice("Setting pingpong interval to %d\n", pp_secs);
314                         break;
315 #if defined(LWS_OPENSSL_SUPPORT)
316                 case 'v':
317                         use_ssl = 1;
318                         opts |= LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT;
319                         break;
320
321 #if defined(LWS_HAVE_SSL_CTX_set1_param)
322                 case 'R':
323                         strncpy(crl_path, optarg, sizeof(crl_path) - 1);
324                         crl_path[sizeof(crl_path) - 1] = '\0';
325                         break;
326 #endif
327 #endif
328                 case 'h':
329                         fprintf(stderr, "Usage: test-server "
330                                         "[--port=<p>] [--ssl] "
331                                         "[-d <log bitfield>] "
332                                         "[--resource_path <path>]\n");
333                         exit(1);
334                 }
335         }
336
337 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
338         /*
339          * normally lock path would be /var/lock/lwsts or similar, to
340          * simplify getting started without having to take care about
341          * permissions or running as root, set to /tmp/.lwsts-lock
342          */
343         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
344                 fprintf(stderr, "Failed to daemonize\n");
345                 return 10;
346         }
347 #endif
348
349         signal(SIGINT, sighandler);
350
351 #ifndef _WIN32
352         /* we will only try to log things according to our debug_level */
353         setlogmask(LOG_UPTO (LOG_DEBUG));
354         openlog("lwsts", syslog_options, LOG_DAEMON);
355 #endif
356
357         /* tell the library what debug level to emit and to send it to syslog */
358         lws_set_log_level(debug_level, lwsl_emit_syslog);
359
360         lwsl_notice("libwebsockets test server - license LGPL2.1+SLE\n");
361         lwsl_notice("(C) Copyright 2010-2016 Andy Green <andy@warmcat.com>\n");
362
363         printf("Using resource path \"%s\"\n", resource_path);
364 #ifdef EXTERNAL_POLL
365         max_poll_elements = getdtablesize();
366         pollfds = malloc(max_poll_elements * sizeof (struct lws_pollfd));
367         fd_lookup = malloc(max_poll_elements * sizeof (int));
368         if (pollfds == NULL || fd_lookup == NULL) {
369                 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
370                 return -1;
371         }
372 #endif
373
374         info.iface = iface;
375         info.protocols = protocols;
376         info.ssl_cert_filepath = NULL;
377         info.ssl_private_key_filepath = NULL;
378         info.ws_ping_pong_interval = pp_secs;
379
380         if (use_ssl) {
381                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
382                         lwsl_err("resource path too long\n");
383                         return -1;
384                 }
385                 if (!cert_path[0])
386                         sprintf(cert_path, "%s/libwebsockets-test-server.pem",
387                                                                 resource_path);
388                 if (strlen(resource_path) > sizeof(key_path) - 32) {
389                         lwsl_err("resource path too long\n");
390                         return -1;
391                 }
392                 if (!key_path[0])
393                         sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
394                                                                 resource_path);
395
396                 info.ssl_cert_filepath = cert_path;
397                 info.ssl_private_key_filepath = key_path;
398                 if (ca_path[0])
399                         info.ssl_ca_filepath = ca_path;
400         }
401         info.gid = gid;
402         info.uid = uid;
403         info.max_http_header_pool = 16;
404         info.options = opts | LWS_SERVER_OPTION_VALIDATE_UTF8 | LWS_SERVER_OPTION_EXPLICIT_VHOSTS;
405         info.extensions = exts;
406         info.timeout_secs = 5;
407         info.ssl_cipher_list = "ECDHE-ECDSA-AES256-GCM-SHA384:"
408                                "ECDHE-RSA-AES256-GCM-SHA384:"
409                                "DHE-RSA-AES256-GCM-SHA384:"
410                                "ECDHE-RSA-AES256-SHA384:"
411                                "HIGH:!aNULL:!eNULL:!EXPORT:"
412                                "!DES:!MD5:!PSK:!RC4:!HMAC_SHA1:"
413                                "!SHA1:!DHE-RSA-AES128-GCM-SHA256:"
414                                "!DHE-RSA-AES128-SHA256:"
415                                "!AES128-GCM-SHA256:"
416                                "!AES128-SHA256:"
417                                "!DHE-RSA-AES256-SHA256:"
418                                "!AES256-GCM-SHA384:"
419                                "!AES256-SHA256";
420
421         if (use_ssl)
422                 /* redirect guys coming on http */
423                 info.options |= LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS;
424
425         context = lws_create_context(&info);
426         if (context == NULL) {
427                 lwsl_err("libwebsocket init failed\n");
428                 return -1;
429         }
430
431         vhost = lws_create_vhost(context, &info);
432         if (!vhost) {
433                 lwsl_err("vhost creation failed\n");
434                 return -1;
435         }
436
437 #if !defined(LWS_NO_CLIENT) && defined(LWS_OPENSSL_SUPPORT)
438         lws_init_vhost_client_ssl(&info, vhost);
439 #endif
440
441         /* this shows how to override the lws file operations.  You don't need
442          * to do any of this unless you have a reason (eg, want to serve
443          * compressed files without decompressing the whole archive)
444          */
445         /* stash original platform fops */
446         fops_plat = *(lws_get_fops(context));
447         /* override the active fops */
448         lws_get_fops(context)->open = test_server_fops_open;
449
450         n = 0;
451 #ifdef EXTERNAL_POLL
452         int ms_1sec = 0;
453 #endif
454         while (n >= 0 && !force_exit) {
455                 struct timeval tv;
456
457                 gettimeofday(&tv, NULL);
458
459                 /*
460                  * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
461                  * live websocket connection using the DUMB_INCREMENT protocol,
462                  * as soon as it can take more packets (usually immediately)
463                  */
464
465                 ms = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
466                 if ((ms - oldms) > 50) {
467                         lws_callback_on_writable_all_protocol(context,
468                                 &protocols[PROTOCOL_DUMB_INCREMENT]);
469                         oldms = ms;
470                 }
471
472 #ifdef EXTERNAL_POLL
473                 /*
474                  * this represents an existing server's single poll action
475                  * which also includes libwebsocket sockets
476                  */
477
478                 n = poll(pollfds, count_pollfds, 50);
479                 if (n < 0)
480                         continue;
481
482                 if (n) {
483                         for (n = 0; n < count_pollfds; n++)
484                                 if (pollfds[n].revents)
485                                         /*
486                                         * returns immediately if the fd does not
487                                         * match anything under libwebsockets
488                                         * control
489                                         */
490                                         if (lws_service_fd(context,
491                                                                   &pollfds[n]) < 0)
492                                                 goto done;
493
494                         /* if needed, force-service wsis that may not have read all input */
495                         while (!lws_service_adjust_timeout(context, 1, 0)) {
496                                 lwsl_notice("extpoll doing forced service!\n");
497                                 lws_service_tsi(context, -1, 0);
498                         }
499                 } else {
500                         /* no revents, but before polling again, make lws check for any timeouts */
501                         if (ms - ms_1sec > 1000) {
502                                 lwsl_notice("1 per sec\n");
503                                 lws_service_fd(context, NULL);
504                                 ms_1sec = ms;
505                         }
506                 }
507 #else
508                 /*
509                  * If libwebsockets sockets are all we care about,
510                  * you can use this api which takes care of the poll()
511                  * and looping through finding who needed service.
512                  *
513                  * If no socket needs service, it'll return anyway after
514                  * the number of ms in the second argument.
515                  */
516
517                 n = lws_service(context, 50);
518 #endif
519         }
520
521 #ifdef EXTERNAL_POLL
522 done:
523 #endif
524
525         lws_context_destroy(context);
526
527         lwsl_notice("libwebsockets-test-server exited cleanly\n");
528
529 #ifndef _WIN32
530         closelog();
531 #endif
532
533         return 0;
534 }