dlfcn h only if plugins
[platform/upstream/libwebsockets.git] / lib / lws-plat-unix.c
1 #include "private-libwebsockets.h"
2
3 #include <pwd.h>
4 #include <grp.h>
5
6 #ifdef LWS_WITH_PLUGINS
7 #include <dlfcn.h>
8 #endif
9 #include <dirent.h>
10
11
12 /*
13  * included from libwebsockets.c for unix builds
14  */
15
16 unsigned long long time_in_microseconds(void)
17 {
18         struct timeval tv;
19         gettimeofday(&tv, NULL);
20         return ((unsigned long long)tv.tv_sec * 1000000LL) + tv.tv_usec;
21 }
22
23 LWS_VISIBLE int
24 lws_get_random(struct lws_context *context, void *buf, int len)
25 {
26         return read(context->fd_random, (char *)buf, len);
27 }
28
29 LWS_VISIBLE int
30 lws_send_pipe_choked(struct lws *wsi)
31 {
32         struct lws_pollfd fds;
33
34         /* treat the fact we got a truncated send pending as if we're choked */
35         if (wsi->trunc_len)
36                 return 1;
37
38         fds.fd = wsi->sock;
39         fds.events = POLLOUT;
40         fds.revents = 0;
41
42         if (poll(&fds, 1, 0) != 1)
43                 return 1;
44
45         if ((fds.revents & POLLOUT) == 0)
46                 return 1;
47
48         /* okay to send another packet without blocking */
49
50         return 0;
51 }
52
53 LWS_VISIBLE int
54 lws_poll_listen_fd(struct lws_pollfd *fd)
55 {
56         return poll(fd, 1, 0);
57 }
58
59 LWS_VISIBLE void
60 lws_cancel_service_pt(struct lws *wsi)
61 {
62         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
63         char buf = 0;
64
65         if (write(pt->dummy_pipe_fds[1], &buf, sizeof(buf)) != 1)
66                 lwsl_err("Cannot write to dummy pipe");
67 }
68
69 LWS_VISIBLE void
70 lws_cancel_service(struct lws_context *context)
71 {
72         struct lws_context_per_thread *pt = &context->pt[0];
73         char buf = 0, m = context->count_threads;
74
75         while (m--) {
76                 if (write(pt->dummy_pipe_fds[1], &buf, sizeof(buf)) != 1)
77                         lwsl_err("Cannot write to dummy pipe");
78                 pt++;
79         }
80 }
81
82 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
83 {
84         int syslog_level = LOG_DEBUG;
85
86         switch (level) {
87         case LLL_ERR:
88                 syslog_level = LOG_ERR;
89                 break;
90         case LLL_WARN:
91                 syslog_level = LOG_WARNING;
92                 break;
93         case LLL_NOTICE:
94                 syslog_level = LOG_NOTICE;
95                 break;
96         case LLL_INFO:
97                 syslog_level = LOG_INFO;
98                 break;
99         }
100         syslog(syslog_level, "%s", line);
101 }
102
103 LWS_VISIBLE int
104 lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi)
105 {
106         struct lws_context_per_thread *pt = &context->pt[tsi];
107         int n = -1, m, c;
108         char buf;
109
110         /* stay dead once we are dead */
111
112         if (!context || !context->vhost_list)
113                 return 1;
114
115         if (timeout_ms < 0)
116                 goto faked_service;
117
118         lws_libev_run(context, tsi);
119         lws_libuv_run(context, tsi);
120
121         if (!context->service_tid_detected) {
122                 struct lws _lws;
123
124                 memset(&_lws, 0, sizeof(_lws));
125                 _lws.context = context;
126
127                 context->service_tid_detected =
128                         context->vhost_list->protocols[0].callback(
129                         &_lws, LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
130         }
131         context->service_tid = context->service_tid_detected;
132
133         timeout_ms = lws_service_adjust_timeout(context, timeout_ms, tsi);
134
135         n = poll(pt->fds, pt->fds_count, timeout_ms);
136
137 #ifdef LWS_OPENSSL_SUPPORT
138         if (!pt->rx_draining_ext_list &&
139             !lws_ssl_anybody_has_buffered_read_tsi(context, tsi) && !n) {
140 #else
141         if (!pt->rx_draining_ext_list && !n) /* poll timeout */ {
142 #endif
143                 lws_service_fd_tsi(context, NULL, tsi);
144                 return 0;
145         }
146
147 faked_service:
148         m = lws_service_flag_pending(context, tsi);
149         if (m)
150                 c = -1; /* unknown limit */
151         else
152                 if (n < 0) {
153                         if (LWS_ERRNO != LWS_EINTR)
154                                 return -1;
155                         return 0;
156                 } else
157                         c = n;
158
159         /* any socket with events to service? */
160         for (n = 0; n < pt->fds_count && c; n++) {
161                 if (!pt->fds[n].revents)
162                         continue;
163
164                 c--;
165
166                 if (pt->fds[n].fd == pt->dummy_pipe_fds[0]) {
167                         if (read(pt->fds[n].fd, &buf, 1) != 1)
168                                 lwsl_err("Cannot read from dummy pipe.");
169                         continue;
170                 }
171
172                 m = lws_service_fd_tsi(context, &pt->fds[n], tsi);
173                 if (m < 0)
174                         return -1;
175                 /* if something closed, retry this slot */
176                 if (m)
177                         n--;
178         }
179
180         return 0;
181 }
182
183 LWS_VISIBLE int
184 lws_plat_service(struct lws_context *context, int timeout_ms)
185 {
186         return lws_plat_service_tsi(context, timeout_ms, 0);
187 }
188
189 LWS_VISIBLE int
190 lws_plat_set_socket_options(struct lws_vhost *vhost, int fd)
191 {
192         int optval = 1;
193         socklen_t optlen = sizeof(optval);
194
195 #if defined(__APPLE__) || \
196     defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
197     defined(__NetBSD__) || \
198     defined(__OpenBSD__)
199         struct protoent *tcp_proto;
200 #endif
201
202         if (vhost->ka_time) {
203                 /* enable keepalive on this socket */
204                 optval = 1;
205                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
206                                (const void *)&optval, optlen) < 0)
207                         return 1;
208
209 #if defined(__APPLE__) || \
210     defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
211     defined(__NetBSD__) || \
212         defined(__CYGWIN__) || defined(__OpenBSD__)
213
214                 /*
215                  * didn't find a way to set these per-socket, need to
216                  * tune kernel systemwide values
217                  */
218 #else
219                 /* set the keepalive conditions we want on it too */
220                 optval = vhost->ka_time;
221                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE,
222                                (const void *)&optval, optlen) < 0)
223                         return 1;
224
225                 optval = vhost->ka_interval;
226                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,
227                                (const void *)&optval, optlen) < 0)
228                         return 1;
229
230                 optval = vhost->ka_probes;
231                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT,
232                                (const void *)&optval, optlen) < 0)
233                         return 1;
234 #endif
235         }
236
237         /* Disable Nagle */
238         optval = 1;
239 #if !defined(__APPLE__) && \
240     !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__) && \
241     !defined(__NetBSD__) && \
242     !defined(__OpenBSD__)
243         if (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)
244                 return 1;
245 #else
246         tcp_proto = getprotobyname("TCP");
247         if (setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen) < 0)
248                 return 1;
249 #endif
250
251         /* We are nonblocking... */
252         if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
253                 return 1;
254
255         return 0;
256 }
257
258 LWS_VISIBLE void
259 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
260 {
261         if (info->gid != -1)
262                 if (setgid(info->gid))
263                         lwsl_warn("setgid: %s\n", strerror(LWS_ERRNO));
264
265         if (info->uid != -1) {
266                 struct passwd *p = getpwuid(info->uid);
267
268                 if (p) {
269                         initgroups(p->pw_name, info->gid);
270                         if (setuid(info->uid))
271                                 lwsl_warn("setuid: %s\n", strerror(LWS_ERRNO));
272                         else
273                                 lwsl_notice("Set privs to user '%s'\n", p->pw_name);
274                 } else
275                         lwsl_warn("getpwuid: unable to find uid %d", info->uid);
276         }
277 }
278
279 #ifdef LWS_WITH_PLUGINS
280
281 #if defined(LWS_USE_LIBUV) && UV_VERSION_MAJOR > 0
282
283 /* libuv.c implements these in a cross-platform way */
284
285 #else
286
287 static int filter(const struct dirent *ent)
288 {
289         if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
290                 return 0;
291
292         return 1;
293 }
294
295 LWS_VISIBLE int
296 lws_plat_plugins_init(struct lws_context * context, const char * const *d)
297 {
298         struct lws_plugin_capability lcaps;
299         struct lws_plugin *plugin;
300         lws_plugin_init_func initfunc;
301         struct dirent **namelist;
302         int n, i, m, ret = 0;
303         char path[256];
304         void *l;
305
306         lwsl_notice("  Plugins:\n");
307
308         while (d && *d) {
309                 n = scandir(*d, &namelist, filter, alphasort);
310                 if (n < 0) {
311                         lwsl_err("Scandir on %s failed\n", *d);
312                         return 1;
313                 }
314
315                 for (i = 0; i < n; i++) {
316                         if (strlen(namelist[i]->d_name) < 7)
317                                 goto inval;
318
319                         lwsl_notice("   %s\n", namelist[i]->d_name);
320
321                         snprintf(path, sizeof(path) - 1, "%s/%s", *d,
322                                  namelist[i]->d_name);
323                         l = dlopen(path, RTLD_NOW);
324                         if (!l) {
325                                 lwsl_err("Error loading DSO: %s\n", dlerror());
326                                 while (i++ < n)
327                                         free(namelist[i]);
328                                 goto bail;
329                         }
330                         /* we could open it, can we get his init function? */
331                         m = snprintf(path, sizeof(path) - 1, "init_%s",
332                                      namelist[i]->d_name + 3 /* snip lib... */);
333                         path[m - 3] = '\0'; /* snip the .so */
334                         initfunc = dlsym(l, path);
335                         if (!initfunc) {
336                                 lwsl_err("Failed to get init on %s: %s",
337                                                 namelist[i]->d_name, dlerror());
338                                 dlclose(l);
339                         }
340                         lcaps.api_magic = LWS_PLUGIN_API_MAGIC;
341                         m = initfunc(context, &lcaps);
342                         if (m) {
343                                 lwsl_err("Initializing %s failed %d\n",
344                                         namelist[i]->d_name, m);
345                                 dlclose(l);
346                                 goto skip;
347                         }
348
349                         plugin = lws_malloc(sizeof(*plugin));
350                         if (!plugin) {
351                                 lwsl_err("OOM\n");
352                                 goto bail;
353                         }
354                         plugin->list = context->plugin_list;
355                         context->plugin_list = plugin;
356                         strncpy(plugin->name, namelist[i]->d_name, sizeof(plugin->name) - 1);
357                         plugin->name[sizeof(plugin->name) - 1] = '\0';
358                         plugin->l = l;
359                         plugin->caps = lcaps;
360                         context->plugin_protocol_count += lcaps.count_protocols;
361                         context->plugin_extension_count += lcaps.count_extensions;
362
363                         free(namelist[i]);
364                         continue;
365
366         skip:
367                         dlclose(l);
368         inval:
369                         free(namelist[i]);
370                 }
371                 free(namelist);
372                 d++;
373         }
374
375 bail:
376         free(namelist);
377
378         return ret;
379 }
380
381 LWS_VISIBLE int
382 lws_plat_plugins_destroy(struct lws_context * context)
383 {
384         struct lws_plugin *plugin = context->plugin_list, *p;
385         lws_plugin_destroy_func func;
386         char path[256];
387         int m;
388
389         if (!plugin)
390                 return 0;
391
392         lwsl_notice("%s\n", __func__);
393
394         while (plugin) {
395                 p = plugin;
396                 m = snprintf(path, sizeof(path) - 1, "destroy_%s", plugin->name + 3);
397                 path[m - 3] = '\0';
398                 func = dlsym(plugin->l, path);
399                 if (!func) {
400                         lwsl_err("Failed to get destroy on %s: %s",
401                                         plugin->name, dlerror());
402                         goto next;
403                 }
404                 m = func(context);
405                 if (m)
406                         lwsl_err("Initializing %s failed %d\n",
407                                 plugin->name, m);
408 next:
409                 dlclose(p->l);
410                 plugin = p->list;
411                 p->list = NULL;
412                 free(p);
413         }
414
415         context->plugin_list = NULL;
416
417         return 0;
418 }
419
420 #endif
421 #endif
422
423
424 #if 0
425 static void
426 sigabrt_handler(int x)
427 {
428         printf("%s\n", __func__);
429         //*(char *)0 = 0;
430 }
431 #endif
432
433 LWS_VISIBLE int
434 lws_plat_context_early_init(void)
435 {
436         signal(SIGPIPE, SIG_IGN);
437
438 //      signal(SIGABRT, sigabrt_handler);
439
440         return 0;
441 }
442
443 LWS_VISIBLE void
444 lws_plat_context_early_destroy(struct lws_context *context)
445 {
446 }
447
448 LWS_VISIBLE void
449 lws_plat_context_late_destroy(struct lws_context *context)
450 {
451         struct lws_context_per_thread *pt = &context->pt[0];
452         int m = context->count_threads;
453
454 #ifdef LWS_WITH_PLUGINS
455         if (context->plugin_list)
456                 lws_plat_plugins_destroy(context);
457 #endif
458
459         if (context->lws_lookup)
460                 lws_free(context->lws_lookup);
461
462         while (m--) {
463                 close(pt->dummy_pipe_fds[0]);
464                 close(pt->dummy_pipe_fds[1]);
465                 pt++;
466         }
467         close(context->fd_random);
468 }
469
470 /* cast a struct sockaddr_in6 * into addr for ipv6 */
471
472 LWS_VISIBLE int
473 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
474                     size_t addrlen)
475 {
476         int rc = -1;
477
478         struct ifaddrs *ifr;
479         struct ifaddrs *ifc;
480 #ifdef LWS_USE_IPV6
481         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
482 #endif
483
484         getifaddrs(&ifr);
485         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
486                 if (!ifc->ifa_addr)
487                         continue;
488
489                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
490
491                 if (strcmp(ifc->ifa_name, ifname))
492                         continue;
493
494                 switch (ifc->ifa_addr->sa_family) {
495                 case AF_INET:
496 #ifdef LWS_USE_IPV6
497                         if (ipv6) {
498                                 /* map IPv4 to IPv6 */
499                                 bzero((char *)&addr6->sin6_addr,
500                                                 sizeof(struct in6_addr));
501                                 addr6->sin6_addr.s6_addr[10] = 0xff;
502                                 addr6->sin6_addr.s6_addr[11] = 0xff;
503                                 memcpy(&addr6->sin6_addr.s6_addr[12],
504                                         &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
505                                                         sizeof(struct in_addr));
506                         } else
507 #endif
508                                 memcpy(addr,
509                                         (struct sockaddr_in *)ifc->ifa_addr,
510                                                     sizeof(struct sockaddr_in));
511                         break;
512 #ifdef LWS_USE_IPV6
513                 case AF_INET6:
514                         memcpy(&addr6->sin6_addr,
515                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
516                                                        sizeof(struct in6_addr));
517                         break;
518 #endif
519                 default:
520                         continue;
521                 }
522                 rc = 0;
523         }
524
525         freeifaddrs(ifr);
526
527         if (rc == -1) {
528                 /* check if bind to IP adddress */
529 #ifdef LWS_USE_IPV6
530                 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
531                         rc = 0;
532                 else
533 #endif
534                 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
535                         rc = 0;
536         }
537
538         return rc;
539 }
540
541 LWS_VISIBLE void
542 lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)
543 {
544         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
545
546         lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ);
547         lws_libuv_io(wsi, LWS_EV_START | LWS_EV_READ);
548
549         pt->fds[pt->fds_count++].revents = 0;
550 }
551
552 LWS_VISIBLE void
553 lws_plat_delete_socket_from_fds(struct lws_context *context,
554                                                 struct lws *wsi, int m)
555 {
556         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
557
558         lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE);
559         lws_libuv_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE);
560
561         pt->fds_count--;
562 }
563
564 LWS_VISIBLE void
565 lws_plat_service_periodic(struct lws_context *context)
566 {
567         /* if our parent went down, don't linger around */
568         if (context->started_with_parent &&
569             kill(context->started_with_parent, 0) < 0)
570                 kill(getpid(), SIGTERM);
571 }
572
573 LWS_VISIBLE int
574 lws_plat_change_pollfd(struct lws_context *context,
575                       struct lws *wsi, struct lws_pollfd *pfd)
576 {
577         return 0;
578 }
579
580 LWS_VISIBLE const char *
581 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
582 {
583         return inet_ntop(af, src, dst, cnt);
584 }
585
586 static lws_filefd_type
587 _lws_plat_file_open(struct lws *wsi, const char *filename,
588                     unsigned long *filelen, int flags)
589 {
590         struct stat stat_buf;
591         int ret = open(filename, flags, 0664);
592
593         if (ret < 0)
594                 return LWS_INVALID_FILE;
595
596         if (fstat(ret, &stat_buf) < 0) {
597                 close(ret);
598                 return LWS_INVALID_FILE;
599         }
600         *filelen = stat_buf.st_size;
601         return ret;
602 }
603
604 static int
605 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
606 {
607         return close(fd);
608 }
609
610 unsigned long
611 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
612 {
613         return lseek(fd, offset, SEEK_CUR);
614 }
615
616 static int
617 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
618                     unsigned char *buf, unsigned long len)
619 {
620         long n;
621
622         n = read((int)fd, buf, len);
623         if (n == -1) {
624                 *amount = 0;
625                 return -1;
626         }
627
628         *amount = n;
629
630         return 0;
631 }
632
633 static int
634 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
635                      unsigned char *buf, unsigned long len)
636 {
637         long n;
638
639         n = write((int)fd, buf, len);
640         if (n == -1) {
641                 *amount = 0;
642                 return -1;
643         }
644
645         *amount = n;
646
647         return 0;
648 }
649
650
651 LWS_VISIBLE int
652 lws_plat_init(struct lws_context *context,
653               struct lws_context_creation_info *info)
654 {
655         struct lws_context_per_thread *pt = &context->pt[0];
656         int n = context->count_threads, fd;
657
658         /* master context has the global fd lookup array */
659         context->lws_lookup = lws_zalloc(sizeof(struct lws *) *
660                                          context->max_fds);
661         if (context->lws_lookup == NULL) {
662                 lwsl_err("OOM on lws_lookup array for %d connections\n",
663                          context->max_fds);
664                 return 1;
665         }
666
667         lwsl_notice(" mem: platform fd map: %5u bytes\n",
668                     sizeof(struct lws *) * context->max_fds);
669         fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
670
671         context->fd_random = fd;
672         if (context->fd_random < 0) {
673                 lwsl_err("Unable to open random device %s %d\n",
674                          SYSTEM_RANDOM_FILEPATH, context->fd_random);
675                 return 1;
676         }
677
678         if (!lws_libev_init_fd_table(context) &&
679             !lws_libuv_init_fd_table(context)) {
680                 /* otherwise libev handled it instead */
681
682                 while (n--) {
683                         if (pipe(pt->dummy_pipe_fds)) {
684                                 lwsl_err("Unable to create pipe\n");
685                                 return 1;
686                         }
687
688                         /* use the read end of pipe as first item */
689                         pt->fds[0].fd = pt->dummy_pipe_fds[0];
690                         pt->fds[0].events = LWS_POLLIN;
691                         pt->fds[0].revents = 0;
692                         pt->fds_count = 1;
693                         pt++;
694                 }
695         }
696
697         context->fops.open      = _lws_plat_file_open;
698         context->fops.close     = _lws_plat_file_close;
699         context->fops.seek_cur  = _lws_plat_file_seek_cur;
700         context->fops.read      = _lws_plat_file_read;
701         context->fops.write     = _lws_plat_file_write;
702
703 #ifdef LWS_WITH_PLUGINS
704         if (info->plugin_dirs)
705                 lws_plat_plugins_init(context, info->plugin_dirs);
706 #endif
707
708         return 0;
709 }