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