license clarification and test apps CC zero
[platform/upstream/libwebsockets.git] / test-server / test-server.c
1 /*
2  * libwebsockets-test-servet - 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
40 /* singlethreaded version --> no locks */
41
42 void test_server_lock(int care)
43 {
44 }
45 void test_server_unlock(int care)
46 {
47 }
48
49 /*
50  * This demo server shows how to use libwebsockets for one or more
51  * websocket protocols in the same server
52  *
53  * It defines the following websocket protocols:
54  *
55  *  dumb-increment-protocol:  once the socket is opened, an incrementing
56  *                              ascii string is sent down it every 50ms.
57  *                              If you send "reset\n" on the websocket, then
58  *                              the incrementing number is reset to 0.
59  *
60  *  lws-mirror-protocol: copies any received packet to every connection also
61  *                              using this protocol, including the sender
62  */
63
64 enum demo_protocols {
65         /* always first */
66         PROTOCOL_HTTP = 0,
67
68         PROTOCOL_DUMB_INCREMENT,
69         PROTOCOL_LWS_MIRROR,
70         PROTOCOL_LWS_ECHOGEN,
71
72         /* always last */
73         DEMO_PROTOCOL_COUNT
74 };
75
76 /* list of supported protocols and callbacks */
77
78 static struct lws_protocols protocols[] = {
79         /* first protocol must always be HTTP handler */
80
81         {
82                 "http-only",            /* name */
83                 callback_http,          /* callback */
84                 sizeof (struct per_session_data__http), /* per_session_data_size */
85                 0,                      /* max frame size / rx buffer */
86         },
87         {
88                 "dumb-increment-protocol",
89                 callback_dumb_increment,
90                 sizeof(struct per_session_data__dumb_increment),
91                 10,
92         },
93         {
94                 "lws-mirror-protocol",
95                 callback_lws_mirror,
96                 sizeof(struct per_session_data__lws_mirror),
97                 128,
98         },
99         {
100                 "lws-echogen",
101                 callback_lws_echogen,
102                 sizeof(struct per_session_data__echogen),
103                 128,
104         },
105         { NULL, NULL, 0, 0 } /* terminator */
106 };
107
108
109 /* this shows how to override the lws file operations.  You don't need
110  * to do any of this unless you have a reason (eg, want to serve
111  * compressed files without decompressing the whole archive)
112  */
113 static lws_filefd_type
114 test_server_fops_open(struct lws *wsi, const char *filename,
115                       unsigned long *filelen, int flags)
116 {
117         lws_filefd_type n;
118
119         /* call through to original platform implementation */
120         n = fops_plat.open(wsi, filename, filelen, flags);
121
122         lwsl_notice("%s: opening %s, ret %ld, len %lu\n", __func__, filename,
123                         (long)n, *filelen);
124
125         return n;
126 }
127
128 void sighandler(int sig)
129 {
130         force_exit = 1;
131         lws_cancel_service(context);
132 }
133
134 static const struct lws_extension exts[] = {
135         {
136                 "permessage-deflate",
137                 lws_extension_callback_pm_deflate,
138                 "permessage-deflate"
139         },
140         {
141                 "deflate-frame",
142                 lws_extension_callback_pm_deflate,
143                 "deflate_frame"
144         },
145         { NULL, NULL, NULL /* terminator */ }
146 };
147
148
149
150 static struct option options[] = {
151         { "help",       no_argument,            NULL, 'h' },
152         { "debug",      required_argument,      NULL, 'd' },
153         { "port",       required_argument,      NULL, 'p' },
154         { "ssl",        no_argument,            NULL, 's' },
155         { "allow-non-ssl",      no_argument,    NULL, 'a' },
156         { "interface",  required_argument,      NULL, 'i' },
157         { "closetest",  no_argument,            NULL, 'c' },
158         { "libev",  no_argument,                NULL, 'e' },
159 #ifndef LWS_NO_DAEMONIZE
160         { "daemonize",  no_argument,            NULL, 'D' },
161 #endif
162         { "resource_path", required_argument,   NULL, 'r' },
163         { NULL, 0, 0, 0 }
164 };
165
166 int main(int argc, char **argv)
167 {
168         struct lws_context_creation_info info;
169         char interface_name[128] = "";
170         unsigned int ms, oldms = 0;
171         const char *iface = NULL;
172         char cert_path[1024];
173         char key_path[1024];
174         int use_ssl = 0;
175         int opts = 0;
176         int n = 0;
177 #ifndef _WIN32
178         int syslog_options = LOG_PID | LOG_PERROR;
179 #endif
180 #ifndef LWS_NO_DAEMONIZE
181         int daemonize = 0;
182 #endif
183
184         /*
185          * take care to zero down the info struct, he contains random garbaage
186          * from the stack otherwise
187          */
188         memset(&info, 0, sizeof info);
189         info.port = 7681;
190
191         while (n >= 0) {
192                 n = getopt_long(argc, argv, "eci:hsap:d:Dr:", options, NULL);
193                 if (n < 0)
194                         continue;
195                 switch (n) {
196                 case 'e':
197                         opts |= LWS_SERVER_OPTION_LIBEV;
198                         break;
199 #ifndef LWS_NO_DAEMONIZE
200                 case 'D':
201                         daemonize = 1;
202                         #ifndef _WIN32
203                         syslog_options &= ~LOG_PERROR;
204                         #endif
205                         break;
206 #endif
207                 case 'd':
208                         debug_level = atoi(optarg);
209                         break;
210                 case 's':
211                         use_ssl = 1;
212                         break;
213                 case 'a':
214                         opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
215                         break;
216                 case 'p':
217                         info.port = atoi(optarg);
218                         break;
219                 case 'i':
220                         strncpy(interface_name, optarg, sizeof interface_name);
221                         interface_name[(sizeof interface_name) - 1] = '\0';
222                         iface = interface_name;
223                         break;
224                 case 'c':
225                         close_testing = 1;
226                         fprintf(stderr, " Close testing mode -- closes on "
227                                            "client after 50 dumb increments"
228                                            "and suppresses lws_mirror spam\n");
229                         break;
230                 case 'r':
231                         resource_path = optarg;
232                         printf("Setting resource path to \"%s\"\n", resource_path);
233                         break;
234                 case 'h':
235                         fprintf(stderr, "Usage: test-server "
236                                         "[--port=<p>] [--ssl] "
237                                         "[-d <log bitfield>] "
238                                         "[--resource_path <path>]\n");
239                         exit(1);
240                 }
241         }
242
243 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
244         /*
245          * normally lock path would be /var/lock/lwsts or similar, to
246          * simplify getting started without having to take care about
247          * permissions or running as root, set to /tmp/.lwsts-lock
248          */
249         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
250                 fprintf(stderr, "Failed to daemonize\n");
251                 return 1;
252         }
253 #endif
254
255         signal(SIGINT, sighandler);
256
257 #ifndef _WIN32
258         /* we will only try to log things according to our debug_level */
259         setlogmask(LOG_UPTO (LOG_DEBUG));
260         openlog("lwsts", syslog_options, LOG_DAEMON);
261 #endif
262
263         /* tell the library what debug level to emit and to send it to syslog */
264         lws_set_log_level(debug_level, lwsl_emit_syslog);
265
266         lwsl_notice("libwebsockets test server - license LGPL2.1+SLE\n");
267         lwsl_notice("(C) Copyright 2010-2016 Andy Green <andy@warmcat.com>\n");
268
269         printf("Using resource path \"%s\"\n", resource_path);
270 #ifdef EXTERNAL_POLL
271         max_poll_elements = getdtablesize();
272         pollfds = malloc(max_poll_elements * sizeof (struct lws_pollfd));
273         fd_lookup = malloc(max_poll_elements * sizeof (int));
274         if (pollfds == NULL || fd_lookup == NULL) {
275                 lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
276                 return -1;
277         }
278 #endif
279
280         info.iface = iface;
281         info.protocols = protocols;
282         info.ssl_cert_filepath = NULL;
283         info.ssl_private_key_filepath = NULL;
284
285         if (use_ssl) {
286                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
287                         lwsl_err("resource path too long\n");
288                         return -1;
289                 }
290                 sprintf(cert_path, "%s/libwebsockets-test-server.pem",
291                                                                 resource_path);
292                 if (strlen(resource_path) > sizeof(key_path) - 32) {
293                         lwsl_err("resource path too long\n");
294                         return -1;
295                 }
296                 sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
297                                                                 resource_path);
298
299                 info.ssl_cert_filepath = cert_path;
300                 info.ssl_private_key_filepath = key_path;
301         }
302         info.gid = -1;
303         info.uid = -1;
304         info.max_http_header_pool = 1;
305         info.options = opts | LWS_SERVER_OPTION_VALIDATE_UTF8;
306         info.extensions = exts;
307         context = lws_create_context(&info);
308         if (context == NULL) {
309                 lwsl_err("libwebsocket init failed\n");
310                 return -1;
311         }
312
313         /* this shows how to override the lws file operations.  You don't need
314          * to do any of this unless you have a reason (eg, want to serve
315          * compressed files without decompressing the whole archive)
316          */
317         /* stash original platform fops */
318         fops_plat = *(lws_get_fops(context));
319         /* override the active fops */
320         lws_get_fops(context)->open = test_server_fops_open;
321
322         n = 0;
323         while (n >= 0 && !force_exit) {
324                 struct timeval tv;
325
326                 gettimeofday(&tv, NULL);
327
328                 /*
329                  * This provokes the LWS_CALLBACK_SERVER_WRITEABLE for every
330                  * live websocket connection using the DUMB_INCREMENT protocol,
331                  * as soon as it can take more packets (usually immediately)
332                  */
333
334                 ms = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
335                 if ((ms - oldms) > 50) {
336                         lws_callback_on_writable_all_protocol(context,
337                                 &protocols[PROTOCOL_DUMB_INCREMENT]);
338                         oldms = ms;
339                 }
340
341 #ifdef EXTERNAL_POLL
342                 /*
343                  * this represents an existing server's single poll action
344                  * which also includes libwebsocket sockets
345                  */
346
347                 n = poll(pollfds, count_pollfds, 50);
348                 if (n < 0)
349                         continue;
350
351                 if (n)
352                         for (n = 0; n < count_pollfds; n++)
353                                 if (pollfds[n].revents)
354                                         /*
355                                         * returns immediately if the fd does not
356                                         * match anything under libwebsockets
357                                         * control
358                                         */
359                                         if (lws_service_fd(context,
360                                                                   &pollfds[n]) < 0)
361                                                 goto done;
362 #else
363                 /*
364                  * If libwebsockets sockets are all we care about,
365                  * you can use this api which takes care of the poll()
366                  * and looping through finding who needed service.
367                  *
368                  * If no socket needs service, it'll return anyway after
369                  * the number of ms in the second argument.
370                  */
371
372                 n = lws_service(context, 50);
373 #endif
374         }
375
376 #ifdef EXTERNAL_POLL
377 done:
378 #endif
379
380         lws_context_destroy(context);
381
382         lwsl_notice("libwebsockets-test-server exited cleanly\n");
383
384 #ifndef _WIN32
385         closelog();
386 #endif
387
388         return 0;
389 }