89ee69025d04f802405bfc2a04a57ef2f2f729ca
[platform/upstream/libwebsockets.git] / lib / libuv.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2016 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 "private-libwebsockets.h"
23
24 void
25 lws_feature_status_libuv(struct lws_context_creation_info *info)
26 {
27         if (lws_check_opt(info->options, LWS_SERVER_OPTION_LIBUV))
28                 lwsl_notice("libuv support compiled in and enabled\n");
29         else
30                 lwsl_notice("libuv support compiled in but disabled\n");
31 }
32
33 static void
34 lws_uv_idle(uv_idle_t *handle
35 #if UV_VERSION_MAJOR == 0
36                 , int status
37 #endif
38 )
39 {
40         struct lws_context_per_thread *pt = lws_container_of(handle,
41                                         struct lws_context_per_thread, uv_idle);
42
43         lwsl_debug("%s\n", __func__);
44
45         /*
46          * is there anybody with pending stuff that needs service forcing?
47          */
48         if (!lws_service_adjust_timeout(pt->context, 1, pt->tid)) {
49                 /* -1 timeout means just do forced service */
50                 lws_plat_service_tsi(pt->context, -1, pt->tid);
51                 /* still somebody left who wants forced service? */
52                 if (!lws_service_adjust_timeout(pt->context, 1, pt->tid))
53                         /* yes... come back again later */
54                         return;
55         }
56
57         /* there is nobody who needs service forcing, shut down idle */
58         uv_idle_stop(handle);
59 }
60
61 static void
62 lws_io_cb(uv_poll_t *watcher, int status, int revents)
63 {
64         struct lws_io_watcher *lws_io = lws_container_of(watcher,
65                                         struct lws_io_watcher, uv_watcher);
66         struct lws *wsi = lws_container_of(lws_io, struct lws, w_read);
67         struct lws_context *context = lws_io->context;
68         struct lws_pollfd eventfd;
69
70 #if defined(WIN32) || defined(_WIN32)
71         eventfd.fd = watcher->socket;
72 #else
73         eventfd.fd = watcher->io_watcher.fd;
74 #endif
75         eventfd.events = 0;
76         eventfd.revents = 0;
77
78         if (status < 0) {
79                 /* at this point status will be an UV error, like UV_EBADF,
80                 we treat all errors as LWS_POLLHUP */
81
82                 /* you might want to return; instead of servicing the fd in some cases */
83                 if (status == UV_EAGAIN)
84                         return;
85
86                 eventfd.events |= LWS_POLLHUP;
87                 eventfd.revents |= LWS_POLLHUP;
88         } else {
89                 if (revents & UV_READABLE) {
90                         eventfd.events |= LWS_POLLIN;
91                         eventfd.revents |= LWS_POLLIN;
92                 }
93                 if (revents & UV_WRITABLE) {
94                         eventfd.events |= LWS_POLLOUT;
95                         eventfd.revents |= LWS_POLLOUT;
96                 }
97         }
98         lws_service_fd(context, &eventfd);
99
100         uv_idle_start(&context->pt[(int)wsi->tsi].uv_idle, lws_uv_idle);
101 }
102
103 LWS_VISIBLE void
104 lws_uv_sigint_cb(uv_signal_t *watcher, int signum)
105 {
106         lwsl_info("internal signal handler caught signal %d\n", signum);
107         lws_libuv_stop(watcher->data);
108 }
109
110 LWS_VISIBLE int
111 lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
112                   uv_signal_cb cb)
113 {
114         context->use_ev_sigint = use_uv_sigint;
115         if (cb)
116                 context->lws_uv_sigint_cb = cb;
117         else
118                 context->lws_uv_sigint_cb = &lws_uv_sigint_cb;
119
120         return 0;
121 }
122
123 static void
124 lws_uv_timeout_cb(uv_timer_t *timer
125 #if UV_VERSION_MAJOR == 0
126                 , int status
127 #endif
128 )
129 {
130         struct lws_context_per_thread *pt = lws_container_of(timer,
131                         struct lws_context_per_thread, uv_timeout_watcher);
132
133         lwsl_debug("%s\n", __func__);
134
135         lws_service_fd_tsi(pt->context, NULL, pt->tid);
136 }
137
138 static const int sigs[] = { SIGINT, SIGTERM, SIGSEGV, SIGFPE };
139
140 LWS_VISIBLE int
141 lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi)
142 {
143         struct lws_context_per_thread *pt = &context->pt[tsi];
144         struct lws_vhost *vh = context->vhost_list;
145         int status = 0, n;
146
147         if (!loop) {
148                 loop = lws_malloc(sizeof(*loop));
149 #if UV_VERSION_MAJOR > 0
150                 uv_loop_init(loop);
151 #else
152                 lwsl_err("This libuv is too old to work...\n");
153                 return 1;
154 #endif
155                 pt->ev_loop_foreign = 0;
156         } else
157                 pt->ev_loop_foreign = 1;
158
159         pt->io_loop_uv = loop;
160         uv_idle_init(loop, &pt->uv_idle);
161
162         if (pt->context->use_ev_sigint) {
163                 assert(ARRAY_SIZE(sigs) <= ARRAY_SIZE(pt->signals));
164                 for (n = 0; n < ARRAY_SIZE(sigs); n++) {
165                         uv_signal_init(loop, &pt->signals[n]);
166                         pt->signals[n].data = pt->context;
167                         uv_signal_start(&pt->signals[n],
168                                         context->lws_uv_sigint_cb, sigs[n]);
169                 }
170         }
171
172         /*
173          * Initialize the accept wsi read watcher with all the listening sockets
174          * and register a callback for read operations
175          *
176          * We have to do it here because the uv loop(s) are not
177          * initialized until after context creation.
178          */
179         while (vh) {
180                 if (vh->lserv_wsi) {
181                         vh->lserv_wsi->w_read.context = context;
182                         n = uv_poll_init_socket(pt->io_loop_uv,
183                                      &vh->lserv_wsi->w_read.uv_watcher,
184                                      vh->lserv_wsi->sock);
185                         if (n) {
186                                 lwsl_err("uv_poll_init failed %d, sockfd=%p\n",
187                                         n, (void *)(long)vh->lserv_wsi->sock);
188
189                                 return -1;
190                         }
191                         uv_poll_start(&vh->lserv_wsi->w_read.uv_watcher,
192                                       UV_READABLE, lws_io_cb);
193                 }
194                 vh = vh->vhost_next;
195         }
196
197         uv_timer_init(pt->io_loop_uv, &pt->uv_timeout_watcher);
198         uv_timer_start(&pt->uv_timeout_watcher, lws_uv_timeout_cb, 1000, 1000);
199
200         return status;
201 }
202
203 void lws_uv_close_cb(uv_handle_t *handle)
204 {
205
206 }
207
208 void lws_uv_walk_cb(uv_handle_t *handle, void *arg)
209 {
210         uv_close(handle, lws_uv_close_cb);
211 }
212
213 void
214 lws_libuv_destroyloop(struct lws_context *context, int tsi)
215 {
216         struct lws_context_per_thread *pt = &context->pt[tsi];
217         int m;
218
219         if (!lws_check_opt(context->options, LWS_SERVER_OPTION_LIBUV))
220                 return;
221
222         if (!pt->io_loop_uv)
223                 return;
224
225         if (context->use_ev_sigint)
226                 uv_signal_stop(&pt->w_sigint.uv_watcher);
227         for (m = 0; m < ARRAY_SIZE(sigs); m++)
228                 uv_signal_stop(&pt->signals[m]);
229         if (!pt->ev_loop_foreign) {
230                 uv_stop(pt->io_loop_uv);
231                 uv_walk(pt->io_loop_uv, lws_uv_walk_cb, NULL);
232                 while (uv_run(pt->io_loop_uv, UV_RUN_NOWAIT));
233 #if UV_VERSION_MAJOR > 0
234                 m = uv_loop_close(pt->io_loop_uv);
235                 if (m == UV_EBUSY)
236                         lwsl_debug("%s: uv_loop_close: UV_EBUSY\n", __func__);
237 #endif
238                 lws_free(pt->io_loop_uv);
239         }
240 }
241
242 void
243 lws_libuv_accept(struct lws *wsi, int accept_fd)
244 {
245         struct lws_context *context = lws_get_context(wsi);
246         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
247
248         if (!LWS_LIBUV_ENABLED(context))
249                 return;
250
251         lwsl_debug("%s: new wsi %p\n", __func__, wsi);
252
253         wsi->w_read.context = context;
254
255         uv_poll_init(pt->io_loop_uv, &wsi->w_read.uv_watcher, accept_fd);
256 }
257
258 void
259 lws_libuv_io(struct lws *wsi, int flags)
260 {
261         struct lws_context *context = lws_get_context(wsi);
262         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
263 #if defined(WIN32) || defined(_WIN32)
264         int current_events = wsi->w_read.uv_watcher.events &
265                              (UV_READABLE | UV_WRITABLE);
266 #else
267         int current_events = wsi->w_read.uv_watcher.io_watcher.pevents &
268                              (UV_READABLE | UV_WRITABLE);
269 #endif
270         struct lws_io_watcher *w = &wsi->w_read;
271
272         if (!LWS_LIBUV_ENABLED(context))
273                 return;
274
275         lwsl_debug("%s: wsi: %p, flags:%d\n", __func__, wsi, flags);
276
277         if (!pt->io_loop_uv) {
278                 lwsl_info("%s: no io loop yet\n", __func__);
279                 return;
280         }
281
282         assert((flags & (LWS_EV_START | LWS_EV_STOP)) &&
283                (flags & (LWS_EV_READ | LWS_EV_WRITE)));
284
285         if (flags & LWS_EV_START) {
286                 if (flags & LWS_EV_WRITE)
287                         current_events |= UV_WRITABLE;
288
289                 if (flags & LWS_EV_READ)
290                         current_events |= UV_READABLE;
291
292                 uv_poll_start(&w->uv_watcher, current_events, lws_io_cb);
293         } else {
294                 if (flags & LWS_EV_WRITE)
295                         current_events &= ~UV_WRITABLE;
296
297                 if (flags & LWS_EV_READ)
298                         current_events &= ~UV_READABLE;
299
300                 if (!(current_events & (UV_READABLE | UV_WRITABLE)))
301                         uv_poll_stop(&w->uv_watcher);
302                 else
303                         uv_poll_start(&w->uv_watcher, current_events,
304                                       lws_io_cb);
305         }
306 }
307
308 int
309 lws_libuv_init_fd_table(struct lws_context *context)
310 {
311         int n;
312
313         if (!LWS_LIBUV_ENABLED(context))
314                 return 0;
315
316         for (n = 0; n < context->count_threads; n++)
317                 context->pt[n].w_sigint.context = context;
318
319         return 1;
320 }
321
322 LWS_VISIBLE void
323 lws_libuv_run(const struct lws_context *context, int tsi)
324 {
325         if (context->pt[tsi].io_loop_uv && LWS_LIBUV_ENABLED(context))
326                 uv_run(context->pt[tsi].io_loop_uv, 0);
327 }
328
329 static void
330 lws_libuv_kill(const struct lws_context *context)
331 {
332         int n;
333
334         for (n = 0; n < context->count_threads; n++)
335                 if (context->pt[n].io_loop_uv && LWS_LIBUV_ENABLED(context))
336                         uv_stop(context->pt[n].io_loop_uv);
337         // TODO uv_stop check foreign loop? or not?
338 }
339
340 /*
341  * This does not actually stop the event loop.  The reason is we have to pass
342  * libuv handle closures through its event loop.  So this tries to close all
343  * wsi, and set a flag; when all the wsi closures are finalized then we
344  * actually stop the libuv event loops.
345  */
346
347 LWS_VISIBLE void
348 lws_libuv_stop(struct lws_context *context)
349 {
350         struct lws_context_per_thread *pt;
351         int n, m;
352
353         context->requested_kill = 1;
354
355         m = context->count_threads;
356         context->being_destroyed = 1;
357
358         while (m--) {
359                 pt = &context->pt[m];
360
361                 for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {
362                         struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);
363                         if (!wsi)
364                                 continue;
365
366                         lws_close_free_wsi(wsi,
367                                 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY
368                                 /* no protocol close */);
369                         n--;
370                 }
371         }
372
373         if (context->count_wsi_allocated == 0)
374                 lws_libuv_kill(context);
375 }
376
377 LWS_VISIBLE uv_loop_t *
378 lws_uv_getloop(struct lws_context *context, int tsi)
379 {
380         if (context->pt[tsi].io_loop_uv && LWS_LIBUV_ENABLED(context))
381                 return context->pt[tsi].io_loop_uv;
382
383         return NULL;
384 }
385
386 static void
387 lws_libuv_closewsi(uv_handle_t* handle)
388 {
389         struct lws *n = NULL, *wsi = (struct lws *)(((char *)handle) -
390                           (char *)(&n->w_read.uv_watcher));
391         struct lws_context *context = lws_get_context(wsi);
392
393         lws_close_free_wsi_final(wsi);
394
395         if (context->requested_kill && context->count_wsi_allocated == 0)
396                 lws_libuv_kill(context);
397 }
398
399 void
400 lws_libuv_closehandle(struct lws *wsi)
401 {
402         struct lws_context *context = lws_get_context(wsi);
403
404         /* required to defer actual deletion until libuv has processed it */
405
406         uv_close((uv_handle_t*)&wsi->w_read.uv_watcher, lws_libuv_closewsi);
407
408         if (context->requested_kill && context->count_wsi_allocated == 0)
409                 lws_libuv_kill(context);
410 }
411
412 #if defined(LWS_WITH_PLUGINS) && (UV_VERSION_MAJOR > 0)
413
414 LWS_VISIBLE int
415 lws_plat_plugins_init(struct lws_context * context, const char *d)
416 {
417         struct lws_plugin_capability lcaps;
418         struct lws_plugin *plugin;
419         lws_plugin_init_func initfunc;
420         int m, ret = 0;
421         void *v;
422         uv_dirent_t dent;
423         uv_fs_t req;
424         char path[256];
425         uv_loop_t loop;
426         uv_lib_t lib;
427
428         lib.errmsg = NULL;
429         lib.handle = NULL;
430
431         uv_loop_init(&loop);
432
433         if (!uv_fs_scandir(&loop, &req, d, 0, NULL)) {
434                 lwsl_err("Scandir on %s failed\n", d);
435                 return 1;
436         }
437
438         lwsl_notice("  Plugins:\n");
439
440         while (uv_fs_scandir_next(&req, &dent) != UV_EOF) {
441                 if (strlen(dent.name) < 7)
442                         continue;
443
444                 lwsl_notice("   %s\n", dent.name);
445
446                 snprintf(path, sizeof(path) - 1, "%s/%s", d, dent.name);
447                 if (uv_dlopen(path, &lib)) {
448                         uv_dlerror(&lib);
449                         lwsl_err("Error loading DSO: %s\n", lib.errmsg);
450                         goto bail;
451                 }
452                 /* we could open it, can we get his init function? */
453                 m = snprintf(path, sizeof(path) - 1, "init_%s",
454                              dent.name + 3 /* snip lib... */);
455                 path[m - 3] = '\0'; /* snip the .so */
456                 if (uv_dlsym(&lib, path, &v)) {
457                         uv_dlerror(&lib);
458                         lwsl_err("Failed to get init on %s: %s",
459                                         dent.name, lib.errmsg);
460                         goto bail;
461                 }
462                 initfunc = (lws_plugin_init_func)v;
463                 lcaps.api_magic = LWS_PLUGIN_API_MAGIC;
464                 m = initfunc(context, &lcaps);
465                 if (m) {
466                         lwsl_err("Initializing %s failed %d\n", dent.name, m);
467                         goto skip;
468                 }
469
470                 plugin = lws_malloc(sizeof(*plugin));
471                 if (!plugin) {
472                         lwsl_err("OOM\n");
473                         goto bail;
474                 }
475                 plugin->list = context->plugin_list;
476                 context->plugin_list = plugin;
477                 strncpy(plugin->name, dent.name, sizeof(plugin->name) - 1);
478                 plugin->name[sizeof(plugin->name) - 1] = '\0';
479                 plugin->lib = lib;
480                 plugin->caps = lcaps;
481                 context->plugin_protocol_count += lcaps.count_protocols;
482                 context->plugin_extension_count += lcaps.count_extensions;
483
484                 continue;
485
486 skip:
487                 uv_dlclose(&lib);
488         }
489
490 bail:
491         uv_fs_req_cleanup(&req);
492         uv_loop_close(&loop);
493
494         return ret;
495
496 }
497
498 LWS_VISIBLE int
499 lws_plat_plugins_destroy(struct lws_context * context)
500 {
501         struct lws_plugin *plugin = context->plugin_list, *p;
502         lws_plugin_destroy_func func;
503         char path[256];
504         void *v;
505         int m;
506
507         if (!plugin)
508                 return 0;
509
510         lwsl_notice("%s\n", __func__);
511
512         while (plugin) {
513                 p = plugin;
514                 m = snprintf(path, sizeof(path) - 1, "destroy_%s", plugin->name + 3);
515                 path[m - 3] = '\0';
516
517                 if (uv_dlsym(&plugin->lib, path, &v)) {
518                         uv_dlerror(&plugin->lib);
519                         lwsl_err("Failed to get init on %s: %s",
520                                         plugin->name, plugin->lib.errmsg);
521                 } else {
522                         func = (lws_plugin_destroy_func)v;
523                         m = func(context);
524                         if (m)
525                                 lwsl_err("Destroying %s failed %d\n",
526                                                 plugin->name, m);
527                 }
528
529                 uv_dlclose(&p->lib);
530                 plugin = p->list;
531                 p->list = NULL;
532                 free(p);
533         }
534
535         context->plugin_list = NULL;
536
537         return 0;
538 }
539
540 #endif
541