eb2f76234415335394b426b4e025f0452a9cac56
[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 #if defined(LWS_USE_LIBUV) && UV_VERSION_MAJOR > 0
304
305 /* libuv.c implements these in a cross-platform way */
306
307 #else
308
309 static int filter(const struct dirent *ent)
310 {
311         if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
312                 return 0;
313
314         return 1;
315 }
316
317 LWS_VISIBLE int
318 lws_plat_plugins_init(struct lws_context * context, const char *d)
319 {
320         struct lws_plugin_capability lcaps;
321         struct lws_plugin *plugin;
322         lws_plugin_init_func initfunc;
323         struct dirent **namelist;
324         int n, i, m, ret = 0;
325         char path[256];
326         void *l;
327
328
329         n = scandir(d, &namelist, filter, alphasort);
330         if (n < 0) {
331                 lwsl_err("Scandir on %s failed\n", d);
332                 return 1;
333         }
334
335         lwsl_notice("  Plugins:\n");
336
337         for (i = 0; i < n; i++) {
338                 if (strlen(namelist[i]->d_name) < 7)
339                         goto inval;
340
341                 lwsl_notice("   %s\n", namelist[i]->d_name);
342
343                 snprintf(path, sizeof(path) - 1, "%s/%s", d,
344                          namelist[i]->d_name);
345                 l = dlopen(path, RTLD_NOW);
346                 if (!l) {
347                         lwsl_err("Error loading DSO: %s\n", dlerror());
348                         while (i++ < n)
349                                 free(namelist[i]);
350                         goto bail;
351                 }
352                 /* we could open it, can we get his init function? */
353                 m = snprintf(path, sizeof(path) - 1, "init_%s",
354                              namelist[i]->d_name + 3 /* snip lib... */);
355                 path[m - 3] = '\0'; /* snip the .so */
356                 initfunc = dlsym(l, path);
357                 if (!initfunc) {
358                         lwsl_err("Failed to get init on %s: %s",
359                                         namelist[i]->d_name, dlerror());
360                         dlclose(l);
361                 }
362                 lcaps.api_magic = LWS_PLUGIN_API_MAGIC;
363                 m = initfunc(context, &lcaps);
364                 if (m) {
365                         lwsl_err("Initializing %s failed %d\n",
366                                 namelist[i]->d_name, m);
367                         dlclose(l);
368                         goto skip;
369                 }
370
371                 plugin = lws_malloc(sizeof(*plugin));
372                 if (!plugin) {
373                         lwsl_err("OOM\n");
374                         goto bail;
375                 }
376                 plugin->list = context->plugin_list;
377                 context->plugin_list = plugin;
378                 strncpy(plugin->name, namelist[i]->d_name, sizeof(plugin->name) - 1);
379                 plugin->name[sizeof(plugin->name) - 1] = '\0';
380                 plugin->l = l;
381                 plugin->caps = lcaps;
382                 context->plugin_protocol_count += lcaps.count_protocols;
383                 context->plugin_extension_count += lcaps.count_extensions;
384
385                 free(namelist[i]);
386                 continue;
387
388 skip:
389                 dlclose(l);
390 inval:
391                 free(namelist[i]);
392         }
393
394 bail:
395         free(namelist);
396
397         return ret;
398 }
399
400 LWS_VISIBLE int
401 lws_plat_plugins_destroy(struct lws_context * context)
402 {
403         struct lws_plugin *plugin = context->plugin_list, *p;
404         lws_plugin_destroy_func func;
405         char path[256];
406         int m;
407
408         if (!plugin)
409                 return 0;
410
411         lwsl_notice("%s\n", __func__);
412
413         while (plugin) {
414                 p = plugin;
415                 m = snprintf(path, sizeof(path) - 1, "destroy_%s", plugin->name + 3);
416                 path[m - 3] = '\0';
417                 func = dlsym(plugin->l, path);
418                 if (!func) {
419                         lwsl_err("Failed to get destroy on %s: %s",
420                                         plugin->name, dlerror());
421                         goto next;
422                 }
423                 m = func(context);
424                 if (m)
425                         lwsl_err("Initializing %s failed %d\n",
426                                 plugin->name, m);
427 next:
428                 dlclose(p->l);
429                 plugin = p->list;
430                 p->list = NULL;
431                 free(p);
432         }
433
434         context->plugin_list = NULL;
435
436         return 0;
437 }
438
439 #endif
440 #endif
441
442
443 static void
444 sigpipe_handler(int x)
445 {
446 }
447
448 LWS_VISIBLE int
449 lws_plat_context_early_init(void)
450 {
451         sigset_t mask;
452
453         signal(SIGUSR2, lws_sigusr2);
454         sigemptyset(&mask);
455         sigaddset(&mask, SIGUSR2);
456
457         sigprocmask(SIG_BLOCK, &mask, NULL);
458
459         signal(SIGPIPE, sigpipe_handler);
460
461         return 0;
462 }
463
464 LWS_VISIBLE void
465 lws_plat_context_early_destroy(struct lws_context *context)
466 {
467 }
468
469 LWS_VISIBLE void
470 lws_plat_context_late_destroy(struct lws_context *context)
471 {
472         struct lws_context_per_thread *pt = &context->pt[0];
473         int m = context->count_threads;
474
475 #ifdef LWS_WITH_PLUGINS
476         if (context->plugin_list)
477                 lws_plat_plugins_destroy(context);
478 #endif
479
480         if (context->lws_lookup)
481                 lws_free(context->lws_lookup);
482
483         while (m--) {
484                 close(pt->dummy_pipe_fds[0]);
485                 close(pt->dummy_pipe_fds[1]);
486                 pt++;
487         }
488         close(context->fd_random);
489 }
490
491 /* cast a struct sockaddr_in6 * into addr for ipv6 */
492
493 LWS_VISIBLE int
494 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
495                     size_t addrlen)
496 {
497         int rc = -1;
498
499         struct ifaddrs *ifr;
500         struct ifaddrs *ifc;
501 #ifdef LWS_USE_IPV6
502         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
503 #endif
504
505         getifaddrs(&ifr);
506         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
507                 if (!ifc->ifa_addr)
508                         continue;
509
510                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
511
512                 if (strcmp(ifc->ifa_name, ifname))
513                         continue;
514
515                 switch (ifc->ifa_addr->sa_family) {
516                 case AF_INET:
517 #ifdef LWS_USE_IPV6
518                         if (ipv6) {
519                                 /* map IPv4 to IPv6 */
520                                 bzero((char *)&addr6->sin6_addr,
521                                                 sizeof(struct in6_addr));
522                                 addr6->sin6_addr.s6_addr[10] = 0xff;
523                                 addr6->sin6_addr.s6_addr[11] = 0xff;
524                                 memcpy(&addr6->sin6_addr.s6_addr[12],
525                                         &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
526                                                         sizeof(struct in_addr));
527                         } else
528 #endif
529                                 memcpy(addr,
530                                         (struct sockaddr_in *)ifc->ifa_addr,
531                                                     sizeof(struct sockaddr_in));
532                         break;
533 #ifdef LWS_USE_IPV6
534                 case AF_INET6:
535                         memcpy(&addr6->sin6_addr,
536                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
537                                                        sizeof(struct in6_addr));
538                         break;
539 #endif
540                 default:
541                         continue;
542                 }
543                 rc = 0;
544         }
545
546         freeifaddrs(ifr);
547
548         if (rc == -1) {
549                 /* check if bind to IP adddress */
550 #ifdef LWS_USE_IPV6
551                 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
552                         rc = 0;
553                 else
554 #endif
555                 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
556                         rc = 0;
557         }
558
559         return rc;
560 }
561
562 LWS_VISIBLE void
563 lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)
564 {
565         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
566
567         lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ);
568         lws_libuv_io(wsi, LWS_EV_START | LWS_EV_READ);
569
570         pt->fds[pt->fds_count++].revents = 0;
571 }
572
573 LWS_VISIBLE void
574 lws_plat_delete_socket_from_fds(struct lws_context *context,
575                                                 struct lws *wsi, int m)
576 {
577         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
578         pt->fds_count--;
579 }
580
581 LWS_VISIBLE void
582 lws_plat_service_periodic(struct lws_context *context)
583 {
584         /* if our parent went down, don't linger around */
585         if (context->started_with_parent &&
586             kill(context->started_with_parent, 0) < 0)
587                 kill(getpid(), SIGTERM);
588 }
589
590 LWS_VISIBLE int
591 lws_plat_change_pollfd(struct lws_context *context,
592                       struct lws *wsi, struct lws_pollfd *pfd)
593 {
594         return 0;
595 }
596
597 LWS_VISIBLE const char *
598 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
599 {
600         return inet_ntop(af, src, dst, cnt);
601 }
602
603 static lws_filefd_type
604 _lws_plat_file_open(struct lws *wsi, const char *filename,
605                     unsigned long *filelen, int flags)
606 {
607         struct stat stat_buf;
608         int ret = open(filename, flags, 0664);
609
610         if (ret < 0)
611                 return LWS_INVALID_FILE;
612
613         if (fstat(ret, &stat_buf) < 0) {
614                 close(ret);
615                 return LWS_INVALID_FILE;
616         }
617         *filelen = stat_buf.st_size;
618         return ret;
619 }
620
621 static int
622 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
623 {
624         return close(fd);
625 }
626
627 unsigned long
628 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
629 {
630         return lseek(fd, offset, SEEK_CUR);
631 }
632
633 static int
634 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
635                     unsigned char *buf, unsigned long len)
636 {
637         long n;
638
639         n = read((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 static int
651 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
652                      unsigned char *buf, unsigned long len)
653 {
654         long n;
655
656         n = write((int)fd, buf, len);
657         if (n == -1) {
658                 *amount = 0;
659                 return -1;
660         }
661
662         *amount = n;
663
664         return 0;
665 }
666
667
668 LWS_VISIBLE int
669 lws_plat_init(struct lws_context *context,
670               struct lws_context_creation_info *info)
671 {
672         struct lws_context_per_thread *pt = &context->pt[0];
673         int n = context->count_threads, fd;
674
675         /* master context has the global fd lookup array */
676         context->lws_lookup = lws_zalloc(sizeof(struct lws *) *
677                                          context->max_fds);
678         if (context->lws_lookup == NULL) {
679                 lwsl_err("OOM on lws_lookup array for %d connections\n",
680                          context->max_fds);
681                 return 1;
682         }
683
684         lwsl_notice(" mem: platform fd map: %5u bytes\n",
685                     sizeof(struct lws *) * context->max_fds);
686         fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
687
688         context->fd_random = fd;
689         if (context->fd_random < 0) {
690                 lwsl_err("Unable to open random device %s %d\n",
691                          SYSTEM_RANDOM_FILEPATH, context->fd_random);
692                 return 1;
693         }
694
695         if (!lws_libev_init_fd_table(context) &&
696             !lws_libuv_init_fd_table(context)) {
697                 /* otherwise libev handled it instead */
698
699                 while (n--) {
700                         if (pipe(pt->dummy_pipe_fds)) {
701                                 lwsl_err("Unable to create pipe\n");
702                                 return 1;
703                         }
704
705                         /* use the read end of pipe as first item */
706                         pt->fds[0].fd = pt->dummy_pipe_fds[0];
707                         pt->fds[0].events = LWS_POLLIN;
708                         pt->fds[0].revents = 0;
709                         pt->fds_count = 1;
710                         pt++;
711                 }
712         }
713
714         context->fops.open      = _lws_plat_file_open;
715         context->fops.close     = _lws_plat_file_close;
716         context->fops.seek_cur  = _lws_plat_file_seek_cur;
717         context->fops.read      = _lws_plat_file_read;
718         context->fops.write     = _lws_plat_file_write;
719
720 #ifdef LWS_WITH_PLUGINS
721         if (info->plugins_dir)
722                 lws_plat_plugins_init(context, info->plugins_dir);
723 #endif
724
725         return 0;
726 }