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