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