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