libuv integration
[platform/upstream/libwebsockets.git] / test-server / test-server-libev.c
1 /*
2  * libwebsockets-test-server - libwebsockets test implementation
3  *
4  * Copyright (C) 2011-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 #include "test-server.h"
21
22 int close_testing;
23 int max_poll_elements;
24 int debug_level = 7;
25 volatile int force_exit = 0;
26 struct lws_context *context;
27 struct lws_plat_file_ops fops_plat;
28
29 /* http server gets files from this path */
30 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
31 char *resource_path = LOCAL_RESOURCE_PATH;
32
33 /*
34  * libev dumps their hygeine problems on their users blaming compiler
35  * http://lists.schmorp.de/pipermail/libev/2008q4/000442.html
36  */
37
38 #if EV_MINPRI == EV_MAXPRI
39 # define _ev_set_priority(ev, pri) ((ev), (pri))
40 #else
41 # define _ev_set_priority(ev, pri) { \
42         ev_watcher *evw = (ev_watcher *)(void *)ev; \
43         evw->priority = pri; \
44 }
45 #endif
46
47 #define _ev_init(ev,cb_) {  \
48         ev_watcher *evw = (ev_watcher *)(void *)ev; \
49 \
50         evw->active = evw->pending = 0; \
51         _ev_set_priority((ev), 0); \
52         ev_set_cb((ev), cb_); \
53 }
54
55 #define _ev_timer_init(ev, cb, after, _repeat) { \
56         ev_watcher_time *evwt = (ev_watcher_time *)(void *)ev; \
57 \
58         _ev_init(ev, cb); \
59         evwt->at = after; \
60         (ev)->repeat = _repeat; \
61 }
62
63 /* singlethreaded version --> no locks */
64
65 void test_server_lock(int care)
66 {
67 }
68 void test_server_unlock(int care)
69 {
70 }
71
72 /*
73  * This demo server shows how to use libwebsockets for one or more
74  * websocket protocols in the same server
75  *
76  * It defines the following websocket protocols:
77  *
78  *  dumb-increment-protocol:  once the socket is opened, an incrementing
79  *                              ascii string is sent down it every 50ms.
80  *                              If you send "reset\n" on the websocket, then
81  *                              the incrementing number is reset to 0.
82  *
83  *  lws-mirror-protocol: copies any received packet to every connection also
84  *                              using this protocol, including the sender
85  */
86
87 enum demo_protocols {
88         /* always first */
89         PROTOCOL_HTTP = 0,
90
91         PROTOCOL_DUMB_INCREMENT,
92         PROTOCOL_LWS_MIRROR,
93
94         /* always last */
95         DEMO_PROTOCOL_COUNT
96 };
97
98 /* list of supported protocols and callbacks */
99
100 static struct lws_protocols protocols[] = {
101         /* first protocol must always be HTTP handler */
102
103         {
104                 "http-only",            /* name */
105                 callback_http,          /* callback */
106                 sizeof (struct per_session_data__http), /* per_session_data_size */
107                 0,                      /* max frame size / rx buffer */
108         },
109         {
110                 "dumb-increment-protocol",
111                 callback_dumb_increment,
112                 sizeof(struct per_session_data__dumb_increment),
113                 10,
114         },
115         {
116                 "lws-mirror-protocol",
117                 callback_lws_mirror,
118                 sizeof(struct per_session_data__lws_mirror),
119                 128,
120         },
121         { NULL, NULL, 0, 0 } /* terminator */
122 };
123
124 static const struct lws_extension exts[] = {
125         {
126                 "permessage-deflate",
127                 lws_extension_callback_pm_deflate,
128                 "permessage-deflate; client_no_context_takeover; client_max_window_bits"
129         },
130         {
131                 "deflate-frame",
132                 lws_extension_callback_pm_deflate,
133                 "deflate_frame"
134         },
135         { NULL, NULL, NULL /* terminator */ }
136 };
137
138 /* this shows how to override the lws file operations.  You don't need
139  * to do any of this unless you have a reason (eg, want to serve
140  * compressed files without decompressing the whole archive)
141  */
142 static lws_filefd_type
143 test_server_fops_open(struct lws *wsi, const char *filename,
144                       unsigned long *filelen, int flags)
145 {
146         lws_filefd_type n;
147
148         /* call through to original platform implementation */
149         n = fops_plat.open(wsi, filename, filelen, flags);
150
151         lwsl_notice("%s: opening %s, ret %ld, len %lu\n", __func__, filename,
152                         (long)n, *filelen);
153
154         return n;
155 }
156
157 void signal_cb(struct ev_loop *loop, struct ev_signal* watcher, int revents)
158 {
159         lwsl_notice("Signal caught, exiting...\n");
160         force_exit = 1;
161         switch (watcher->signum) {
162         case SIGTERM:
163         case SIGINT:
164                 ev_break(loop, EVBREAK_ALL);
165                 break;
166         default:
167                 signal(SIGABRT, SIG_DFL);
168                 abort();
169                 break;
170         }
171 }
172
173 static void
174 ev_timeout_cb (EV_P_ ev_timer *w, int revents)
175 {
176         lws_callback_on_writable_all_protocol(context,
177                                         &protocols[PROTOCOL_DUMB_INCREMENT]);
178 }
179
180 static struct option options[] = {
181         { "help",       no_argument,            NULL, 'h' },
182         { "debug",      required_argument,      NULL, 'd' },
183         { "port",       required_argument,      NULL, 'p' },
184         { "ssl",        no_argument,            NULL, 's' },
185         { "allow-non-ssl",      no_argument,    NULL, 'a' },
186         { "interface",  required_argument,      NULL, 'i' },
187         { "closetest",  no_argument,            NULL, 'c' },
188         { "libev",  no_argument,                NULL, 'e' },
189 #ifndef LWS_NO_DAEMONIZE
190         { "daemonize",  no_argument,            NULL, 'D' },
191 #endif
192         { "resource_path", required_argument,   NULL, 'r' },
193         { NULL, 0, 0, 0 }
194 };
195
196 int main(int argc, char **argv)
197 {
198         int sigs[] = { SIGINT, SIGKILL, SIGTERM, SIGSEGV, SIGFPE };
199         struct ev_signal signals[ARRAY_SIZE(sigs)];
200         struct ev_loop *loop = ev_default_loop(0);
201         struct lws_context_creation_info info;
202         char interface_name[128] = "";
203         const char *iface = NULL;
204         ev_timer timeout_watcher;
205         char cert_path[1024];
206         char key_path[1024];
207         int use_ssl = 0;
208         int opts = 0;
209         int n = 0;
210 #ifndef _WIN32
211         int syslog_options = LOG_PID | LOG_PERROR;
212 #endif
213 #ifndef LWS_NO_DAEMONIZE
214         int daemonize = 0;
215 #endif
216
217         /*
218          * take care to zero down the info struct, he contains random garbaage
219          * from the stack otherwise
220          */
221         memset(&info, 0, sizeof info);
222         info.port = 7681;
223
224         while (n >= 0) {
225                 n = getopt_long(argc, argv, "eci:hsap:d:Dr:", options, NULL);
226                 if (n < 0)
227                         continue;
228                 switch (n) {
229                 case 'e':
230                         opts |= LWS_SERVER_OPTION_LIBEV;
231                         break;
232 #ifndef LWS_NO_DAEMONIZE
233                 case 'D':
234                         daemonize = 1;
235                         #ifndef _WIN32
236                         syslog_options &= ~LOG_PERROR;
237                         #endif
238                         break;
239 #endif
240                 case 'd':
241                         debug_level = atoi(optarg);
242                         break;
243                 case 's':
244                         use_ssl = 1;
245                         break;
246                 case 'a':
247                         opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
248                         break;
249                 case 'p':
250                         info.port = atoi(optarg);
251                         break;
252                 case 'i':
253                         strncpy(interface_name, optarg, sizeof interface_name);
254                         interface_name[(sizeof interface_name) - 1] = '\0';
255                         iface = interface_name;
256                         break;
257                 case 'c':
258                         close_testing = 1;
259                         fprintf(stderr, " Close testing mode -- closes on "
260                                            "client after 50 dumb increments"
261                                            "and suppresses lws_mirror spam\n");
262                         break;
263                 case 'r':
264                         resource_path = optarg;
265                         printf("Setting resource path to \"%s\"\n", resource_path);
266                         break;
267                 case 'h':
268                         fprintf(stderr, "Usage: test-server "
269                                         "[--port=<p>] [--ssl] "
270                                         "[-d <log bitfield>] "
271                                         "[--resource_path <path>]\n");
272                         exit(1);
273                 }
274         }
275
276 #if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
277         /*
278          * normally lock path would be /var/lock/lwsts or similar, to
279          * simplify getting started without having to take care about
280          * permissions or running as root, set to /tmp/.lwsts-lock
281          */
282         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
283                 fprintf(stderr, "Failed to daemonize\n");
284                 return 1;
285         }
286 #endif
287
288         for (n = 0; n < ARRAY_SIZE(sigs); n++) {
289                 _ev_init(&signals[n], signal_cb);
290                 ev_signal_set(&signals[n], sigs[n]);
291                 ev_signal_start(loop, &signals[n]);
292         }
293
294 #ifndef _WIN32
295         /* we will only try to log things according to our debug_level */
296         setlogmask(LOG_UPTO (LOG_DEBUG));
297         openlog("lwsts", syslog_options, LOG_DAEMON);
298 #endif
299
300         /* tell the library what debug level to emit and to send it to syslog */
301         lws_set_log_level(debug_level, lwsl_emit_syslog);
302
303         lwsl_notice("libwebsockets test server libev - license LGPL2.1+SLE\n");
304         lwsl_notice("(C) Copyright 2010-2016 Andy Green <andy@warmcat.com>\n");
305
306         printf("Using resource path \"%s\"\n", resource_path);
307
308         info.iface = iface;
309         info.protocols = protocols;
310         info.extensions = exts;
311
312         info.ssl_cert_filepath = NULL;
313         info.ssl_private_key_filepath = NULL;
314
315         if (use_ssl) {
316                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
317                         lwsl_err("resource path too long\n");
318                         return -1;
319                 }
320                 sprintf(cert_path, "%s/libwebsockets-test-server.pem",
321                                                                 resource_path);
322                 if (strlen(resource_path) > sizeof(key_path) - 32) {
323                         lwsl_err("resource path too long\n");
324                         return -1;
325                 }
326                 sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
327                                                                 resource_path);
328
329                 info.ssl_cert_filepath = cert_path;
330                 info.ssl_private_key_filepath = key_path;
331         }
332         info.gid = -1;
333         info.uid = -1;
334         info.max_http_header_pool = 1;
335         info.options = opts | LWS_SERVER_OPTION_LIBEV;
336
337         context = lws_create_context(&info);
338         if (context == NULL) {
339                 lwsl_err("libwebsocket init failed\n");
340                 return -1;
341         }
342
343         /*
344          * this shows how to override the lws file operations.  You don't need
345          * to do any of this unless you have a reason (eg, want to serve
346          * compressed files without decompressing the whole archive)
347          */
348         /* stash original platform fops */
349         fops_plat = *(lws_get_fops(context));
350         /* override the active fops */
351         lws_get_fops(context)->open = test_server_fops_open;
352
353         lws_ev_initloop(context, loop, 0);
354
355         _ev_timer_init(&timeout_watcher, ev_timeout_cb, 0.05, 0.05);
356         ev_timer_start(loop, &timeout_watcher);
357         ev_run(loop, 0);
358
359         lws_context_destroy(context);
360         lwsl_notice("libwebsockets-test-server exited cleanly\n");
361
362 #ifndef _WIN32
363         closelog();
364 #endif
365
366         return 0;
367 }