test-server-libuv: also call context_destroy2 when using foreign loop
[platform/upstream/libwebsockets.git] / test-server / test-server-libuv.c
1 /*
2  * libwebsockets-test-server for libev - 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 #define DI_HANDLED_BY_PLUGIN
23 #include "test-server.h"
24 #include <uv.h>
25
26 int close_testing;
27 int max_poll_elements;
28 int debug_level = 7;
29 struct lws_context *context;
30 struct lws_plat_file_ops fops_plat;
31
32 /* http server gets files from this path */
33 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
34 char *resource_path = LOCAL_RESOURCE_PATH;
35
36 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
37 char crl_path[1024] = "";
38 #endif
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 #define LWS_PLUGIN_STATIC
50 #include "../plugins/protocol_dumb_increment.c"
51 #include "../plugins/protocol_lws_mirror.c"
52 #include "../plugins/protocol_lws_status.c"
53
54 /*
55  * This demo server shows how to use libwebsockets for one or more
56  * websocket protocols in the same server
57  *
58  * It defines the following websocket protocols:
59  *
60  *  dumb-increment-protocol:  once the socket is opened, an incrementing
61  *                              ascii string is sent down it every 50ms.
62  *                              If you send "reset\n" on the websocket, then
63  *                              the incrementing number is reset to 0.
64  *
65  *  lws-mirror-protocol: copies any received packet to every connection also
66  *                              using this protocol, including the sender
67  */
68
69 enum demo_protocols {
70         /* always first */
71         PROTOCOL_HTTP = 0,
72
73         PROTOCOL_DUMB_INCREMENT,
74         PROTOCOL_LWS_MIRROR,
75         PROTOCOL_LWS_STATUS,
76
77         /* always last */
78         DEMO_PROTOCOL_COUNT
79 };
80
81 /* list of supported protocols and callbacks */
82
83 static struct lws_protocols protocols[] = {
84         /* first protocol must always be HTTP handler */
85
86         {
87                 "http-only",            /* name */
88                 callback_http,          /* callback */
89                 sizeof (struct per_session_data__http), /* per_session_data_size */
90                 0,                      /* max frame size / rx buffer */
91         },
92         LWS_PLUGIN_PROTOCOL_DUMB_INCREMENT,
93         LWS_PLUGIN_PROTOCOL_MIRROR,
94         LWS_PLUGIN_PROTOCOL_LWS_STATUS,
95         { NULL, NULL, 0, 0 } /* terminator */
96 };
97
98 static const struct lws_extension exts[] = {
99         {
100                 "permessage-deflate",
101                 lws_extension_callback_pm_deflate,
102                 "permessage-deflate; client_no_context_takeover; client_max_window_bits"
103         },
104         {
105                 "deflate-frame",
106                 lws_extension_callback_pm_deflate,
107                 "deflate_frame"
108         },
109         { NULL, NULL, NULL /* terminator */ }
110 };
111
112 void signal_cb(uv_signal_t *watcher, int signum)
113 {
114         lwsl_err("Signal %d caught, exiting...\n", watcher->signum);
115         switch (watcher->signum) {
116         case SIGTERM:
117         case SIGINT:
118                 break;
119         default:
120                 signal(SIGABRT, SIG_DFL);
121                 abort();
122                 break;
123         }
124         lws_libuv_stop(context);
125 }
126
127
128 static struct option options[] = {
129         { "help",       no_argument,            NULL, 'h' },
130         { "debug",      required_argument,      NULL, 'd' },
131         { "port",       required_argument,      NULL, 'p' },
132         { "ssl",        no_argument,            NULL, 's' },
133         { "allow-non-ssl",      no_argument,    NULL, 'a' },
134         { "interface",  required_argument,      NULL, 'i' },
135         { "closetest",  no_argument,            NULL, 'c' },
136         { "libev",  no_argument,                NULL, 'e' },
137         { "foreign",  no_argument,              NULL, 'f' },
138 #ifndef LWS_NO_DAEMONIZE
139         { "daemonize",  no_argument,            NULL, 'D' },
140 #endif
141         { "resource_path", required_argument,   NULL, 'r' },
142         { NULL, 0, 0, 0 }
143 };
144
145 #if UV_VERSION_MAJOR > 0
146 /* ----- this code is only needed for foreign / external libuv tests -----*/
147 struct counter
148 {
149         int cur, lim;
150         int stop_loop;
151 };
152
153 static void timer_cb(uv_timer_t *t)
154 {
155         struct counter *c = t->data;
156
157         lwsl_notice("  timer %p cb, count %d, loop has %d handles\n",
158                     t, c->cur, t->loop->active_handles);
159
160         if (c->cur++ == c->lim) {
161                 lwsl_debug("stop loop from timer\n");
162                 uv_timer_stop(t);
163                 if (c->stop_loop)
164                         uv_stop(t->loop);
165         }
166 }
167
168 static void timer_close_cb(uv_handle_t *h)
169 {
170         lwsl_notice("timer close cb %p, loop has %d handles\n",
171                     h, h->loop->active_handles);
172 }
173
174 void outer_signal_cb(uv_signal_t *s, int signum)
175 {
176         lwsl_notice("Foreign loop got signal %d\n", signum);
177         uv_signal_stop(s);
178         uv_stop(s->loop);
179 }
180
181 static void lws_uv_close_cb(uv_handle_t *handle)
182 {
183         //lwsl_err("%s\n", __func__);
184 }
185
186 static void lws_uv_walk_cb(uv_handle_t *handle, void *arg)
187 {
188         uv_close(handle, lws_uv_close_cb);
189 }
190
191 /* --- end of foreign test code ---- */
192 #endif
193
194 int main(int argc, char **argv)
195 {
196         struct lws_context_creation_info info;
197         char interface_name[128] = "";
198 #if UV_VERSION_MAJOR > 0
199 /* --- only needed for foreign loop test ---> */
200         uv_loop_t loop;
201         uv_signal_t signal_outer;
202         uv_timer_t timer_outer;
203         struct counter ctr;
204         int foreign_libuv_loop = 0;
205 /* <--- only needed for foreign loop test --- */
206 #endif
207         const char *iface = NULL;
208         char cert_path[1024];
209         char key_path[1024];
210         int use_ssl = 0;
211         int opts = 0;
212         int n = 0;
213 #ifndef _WIN32
214         int syslog_options = LOG_PID | LOG_PERROR;
215 #endif
216 #ifndef LWS_NO_DAEMONIZE
217         int daemonize = 0;
218 #endif
219
220         /*
221          * take care to zero down the info struct, he contains random garbaage
222          * from the stack otherwise
223          */
224         memset(&info, 0, sizeof info);
225         info.port = 7681;
226
227         while (n >= 0) {
228                 n = getopt_long(argc, argv, "feci:hsap:d:Dr:", options, NULL);
229                 if (n < 0)
230                         continue;
231                 switch (n) {
232                 case 'f':
233 #if UV_VERSION_MAJOR > 0
234                         foreign_libuv_loop = 1;
235 #endif
236                         break;
237                 case 'e':
238                         opts |= LWS_SERVER_OPTION_LIBEV;
239                         break;
240 #ifndef LWS_NO_DAEMONIZE
241                 case 'D':
242                         daemonize = 1;
243                         #ifndef _WIN32
244                         syslog_options &= ~LOG_PERROR;
245                         #endif
246                         break;
247 #endif
248                 case 'd':
249                         debug_level = atoi(optarg);
250                         break;
251                 case 's':
252                         use_ssl = 1;
253                         break;
254                 case 'a':
255                         opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
256                         break;
257                 case 'p':
258                         info.port = atoi(optarg);
259                         break;
260                 case 'i':
261                         strncpy(interface_name, optarg, sizeof interface_name);
262                         interface_name[(sizeof interface_name) - 1] = '\0';
263                         iface = interface_name;
264                         break;
265                 case 'c':
266                         close_testing = 1;
267                         fprintf(stderr, " Close testing mode -- closes on "
268                                            "client after 50 dumb increments"
269                                            "and suppresses lws_mirror spam\n");
270                         break;
271                 case 'r':
272                         resource_path = optarg;
273                         printf("Setting resource path to \"%s\"\n", resource_path);
274                         break;
275                 case 'h':
276                         fprintf(stderr, "Usage: test-server "
277                                         "[--port=<p>] [--ssl] "
278                                         "[-d <log bitfield>] "
279                                         "[--resource_path <path>]\n");
280                         exit(1);
281                 }
282         }
283
284 #if !defined(WIN32)
285 #if !defined(LWS_NO_DAEMONIZE)
286         /*
287          * normally lock path would be /var/lock/lwsts or similar, to
288          * simplify getting started without having to take care about
289          * permissions or running as root, set to /tmp/.lwsts-lock
290          */
291         if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
292                 fprintf(stderr, "Failed to daemonize\n");
293                 return 1;
294         }
295 #endif
296
297         /* we will only try to log things according to our debug_level */
298         setlogmask(LOG_UPTO (LOG_DEBUG));
299         openlog("lwsts", syslog_options, LOG_DAEMON);
300 #endif
301
302         /* tell the library what debug level to emit and to send it to syslog */
303         lws_set_log_level(debug_level, lwsl_emit_syslog);
304
305         lwsl_notice("libwebsockets test server libuv - license LGPL2.1+SLE\n");
306         lwsl_notice("(C) Copyright 2010-2016 Andy Green <andy@warmcat.com>\n");
307
308         lwsl_info("Using resource path \"%s\"\n", resource_path);
309
310         info.iface = iface;
311         info.protocols = protocols;
312         info.extensions = exts;
313
314         info.ssl_cert_filepath = NULL;
315         info.ssl_private_key_filepath = NULL;
316
317         if (use_ssl) {
318                 if (strlen(resource_path) > sizeof(cert_path) - 32) {
319                         lwsl_err("resource path too long\n");
320                         return -1;
321                 }
322                 sprintf(cert_path, "%s/libwebsockets-test-server.pem",
323                         resource_path);
324                 if (strlen(resource_path) > sizeof(key_path) - 32) {
325                         lwsl_err("resource path too long\n");
326                         return -1;
327                 }
328                 sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
329                         resource_path);
330
331                 info.ssl_cert_filepath = cert_path;
332                 info.ssl_private_key_filepath = key_path;
333                 opts |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
334         }
335         info.gid = -1;
336         info.uid = -1;
337         info.max_http_header_pool = 1;
338         info.timeout_secs = 5;
339         info.options = opts | LWS_SERVER_OPTION_LIBUV;
340
341 #if UV_VERSION_MAJOR > 0
342         if (foreign_libuv_loop) {
343                 /* create the foreign loop */
344                 uv_loop_init(&loop);
345
346                 /* run some timer on that loop just so loop is not 'clean' */
347
348                 uv_signal_init(&loop, &signal_outer);
349                 uv_signal_start(&signal_outer, outer_signal_cb, SIGINT);
350
351                 uv_timer_init(&loop, &timer_outer);
352                 timer_outer.data = &ctr;
353                 ctr.cur = 0;
354                 ctr.lim = ctr.cur + 5;
355                 ctr.stop_loop = 1;
356                 uv_timer_start(&timer_outer, timer_cb, 0, 1000);
357                 lwsl_notice("running loop without libwebsockets for %d s\n", ctr.lim);
358
359                 uv_run(&loop, UV_RUN_DEFAULT);
360
361                 /* timer will stop loop and we will get here */
362         }
363 #endif
364
365         context = lws_create_context(&info);
366         if (context == NULL) {
367                 lwsl_err("libwebsocket init failed\n");
368                 return -1;
369         }
370
371         lws_uv_sigint_cfg(context, 1, signal_cb);
372
373 #if UV_VERSION_MAJOR > 0
374         if (foreign_libuv_loop)
375                 /* we have our own uv loop outside of lws */
376                 lws_uv_initloop(context, &loop, 0);
377         else
378 #endif
379         {
380                 /*
381                  * lws will create his own libuv loop in the context
382                  */
383                 if (lws_uv_initloop(context, NULL, 0)) {
384                         lwsl_err("lws_uv_initloop failed\n");
385
386                         goto bail;
387                 }
388         }
389
390 #if UV_VERSION_MAJOR > 0
391         if (foreign_libuv_loop) {
392                 /*
393                  * prepare inner timer on loop, to run along with lws.
394                  * Will exit after 5s while lws keeps running
395                  */
396                 struct counter ctr_inner = { 0, 3, 0 };
397                 int e;
398                 uv_timer_t timer_inner;
399                 uv_timer_init(&loop, &timer_inner);
400                 timer_inner.data = &ctr_inner;
401                 uv_timer_start(&timer_inner, timer_cb, 200, 1000);
402
403                 /* make this timer long-lived, should keep
404                  * firing after lws exits */
405                 ctr.cur = 0;
406                 ctr.lim = ctr.cur + 1000;
407                 uv_timer_start(&timer_outer, timer_cb, 0, 1000);
408
409                 uv_run(&loop, UV_RUN_DEFAULT);
410
411                 /* we are here either because signal stopped us,
412                  * or outer timer expired */
413
414                 /* close short timer */
415                 uv_timer_stop(&timer_inner);
416                 uv_close((uv_handle_t*)&timer_inner, timer_close_cb);
417
418
419                 lwsl_notice("Destroying lws context\n");
420
421                 /* detach lws */
422                 lws_context_destroy(context);
423
424                 lwsl_notice("Please wait while the outer libuv test continues for 10s\n");
425
426                 ctr.lim = ctr.cur + 10;
427
428                 /* try and run outer timer for 10 more seconds,
429                  * (or sigint outer handler) after lws has left the loop */
430                 uv_run(&loop, UV_RUN_DEFAULT);
431
432                 /* Clean up the foreign loop now */
433
434                 /* PHASE 1: stop and close things we created
435                  *          outside of lws */
436
437                 uv_timer_stop(&timer_outer);
438                 uv_close((uv_handle_t*)&timer_outer, timer_close_cb);
439                 uv_signal_stop(&signal_outer);
440
441                 e = 100;
442                 while (e--)
443                         uv_run(&loop, UV_RUN_NOWAIT);
444
445                 /* PHASE 2: close anything remaining */
446
447                 uv_walk(&loop, lws_uv_walk_cb, NULL);
448
449                 e = 100;
450                 while (e--)
451                         uv_run(&loop, UV_RUN_NOWAIT);
452
453                 /* PHASE 3: close the UV loop itself */
454
455                 e = uv_loop_close(&loop);
456                 lwsl_notice("uv loop close rc %s\n",
457                             e ? uv_strerror(e) : "ok");
458
459                 /* PHASE 4: finalize context destruction */
460
461                 lws_context_destroy2(context);
462         } else
463 #endif
464         {
465                 lws_libuv_run(context, 0);
466
467 bail:
468                 lws_context_destroy(context);
469                 lws_context_destroy2(context);
470         }
471
472         lwsl_notice("libwebsockets-test-server exited cleanly\n");
473
474         context = NULL;
475
476         return 0;
477 }