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