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