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