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