context deprecation
[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 LWS_EXTERN 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         /*
134          * is there anybody with pending stuff that needs service forcing?
135          */
136         if (!lws_service_adjust_timeout(context, 1, tsi)) {
137                 /* -1 timeout means just do forced service */
138                 _lws_plat_service_tsi(context, -1, pt->tid);
139                 /* still somebody left who wants forced service? */
140                 if (!lws_service_adjust_timeout(context, 1, pt->tid))
141                         /* yes... come back again quickly */
142                         timeout_ms = 0;
143         }
144
145         n = poll(pt->fds, pt->fds_count, timeout_ms);
146
147 #ifdef LWS_OPENSSL_SUPPORT
148         if (!pt->rx_draining_ext_list &&
149             !lws_ssl_anybody_has_buffered_read_tsi(context, tsi) && !n) {
150 #else
151         if (!pt->rx_draining_ext_list && !n) /* poll timeout */ {
152 #endif
153                 lws_service_fd_tsi(context, NULL, tsi);
154                 return 0;
155         }
156
157 faked_service:
158         m = lws_service_flag_pending(context, tsi);
159         if (m)
160                 c = -1; /* unknown limit */
161         else
162                 if (n < 0) {
163                         if (LWS_ERRNO != LWS_EINTR)
164                                 return -1;
165                         return 0;
166                 } else
167                         c = n;
168
169         /* any socket with events to service? */
170         for (n = 0; n < pt->fds_count && c; n++) {
171                 if (!pt->fds[n].revents)
172                         continue;
173
174                 c--;
175
176                 if (pt->fds[n].fd == pt->dummy_pipe_fds[0]) {
177                         if (read(pt->fds[n].fd, &buf, 1) != 1)
178                                 lwsl_err("Cannot read from dummy pipe.");
179                         continue;
180                 }
181
182                 m = lws_service_fd_tsi(context, &pt->fds[n], tsi);
183                 if (m < 0)
184                         return -1;
185                 /* if something closed, retry this slot */
186                 if (m)
187                         n--;
188         }
189
190         return 0;
191 }
192
193 LWS_VISIBLE int
194 lws_plat_check_connection_error(struct lws *wsi)
195 {
196         return 0;
197 }
198
199 LWS_VISIBLE int
200 lws_plat_service(struct lws_context *context, int timeout_ms)
201 {
202         return _lws_plat_service_tsi(context, timeout_ms, 0);
203 }
204
205 LWS_VISIBLE int
206 lws_plat_set_socket_options(struct lws_vhost *vhost, int fd)
207 {
208         int optval = 1;
209         socklen_t optlen = sizeof(optval);
210
211 #if defined(__APPLE__) || \
212     defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
213     defined(__NetBSD__) || \
214     defined(__OpenBSD__)
215         struct protoent *tcp_proto;
216 #endif
217
218         if (vhost->ka_time) {
219                 /* enable keepalive on this socket */
220                 optval = 1;
221                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
222                                (const void *)&optval, optlen) < 0)
223                         return 1;
224
225 #if defined(__APPLE__) || \
226     defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
227     defined(__NetBSD__) || \
228         defined(__CYGWIN__) || defined(__OpenBSD__) || defined (__sun)
229
230                 /*
231                  * didn't find a way to set these per-socket, need to
232                  * tune kernel systemwide values
233                  */
234 #else
235                 /* set the keepalive conditions we want on it too */
236                 optval = vhost->ka_time;
237                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE,
238                                (const void *)&optval, optlen) < 0)
239                         return 1;
240
241                 optval = vhost->ka_interval;
242                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,
243                                (const void *)&optval, optlen) < 0)
244                         return 1;
245
246                 optval = vhost->ka_probes;
247                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT,
248                                (const void *)&optval, optlen) < 0)
249                         return 1;
250 #endif
251         }
252
253         /* Disable Nagle */
254         optval = 1;
255 #if defined (__sun)
256         if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)
257                 return 1;
258 #elif !defined(__APPLE__) && \
259       !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__) &&        \
260       !defined(__NetBSD__) && \
261       !defined(__OpenBSD__)
262         if (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)
263                 return 1;
264 #else
265         tcp_proto = getprotobyname("TCP");
266         if (setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen) < 0)
267                 return 1;
268 #endif
269
270         /* We are nonblocking... */
271         if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
272                 return 1;
273
274         return 0;
275 }
276
277 LWS_VISIBLE void
278 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
279 {
280         if (info->gid != -1)
281                 if (setgid(info->gid))
282                         lwsl_warn("setgid: %s\n", strerror(LWS_ERRNO));
283
284         if (info->uid != -1) {
285                 struct passwd *p = getpwuid(info->uid);
286
287                 if (p) {
288                         initgroups(p->pw_name, info->gid);
289                         if (setuid(info->uid))
290                                 lwsl_warn("setuid: %s\n", strerror(LWS_ERRNO));
291                         else
292                                 lwsl_notice("Set privs to user '%s'\n", p->pw_name);
293                 } else
294                         lwsl_warn("getpwuid: unable to find uid %d", info->uid);
295         }
296 }
297
298 #ifdef LWS_WITH_PLUGINS
299
300 #if defined(LWS_USE_LIBUV) && UV_VERSION_MAJOR > 0
301
302 /* libuv.c implements these in a cross-platform way */
303
304 #else
305
306 static int filter(const struct dirent *ent)
307 {
308         if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
309                 return 0;
310
311         return 1;
312 }
313
314 LWS_VISIBLE int
315 lws_plat_plugins_init(struct lws_context * context, const char * const *d)
316 {
317         struct lws_plugin_capability lcaps;
318         struct lws_plugin *plugin;
319         lws_plugin_init_func initfunc;
320         struct dirent **namelist;
321         int n, i, m, ret = 0;
322         char path[256];
323         void *l;
324
325         lwsl_notice("  Plugins:\n");
326
327         while (d && *d) {
328                 n = scandir(*d, &namelist, filter, alphasort);
329                 if (n < 0) {
330                         lwsl_err("Scandir on %s failed\n", *d);
331                         return 1;
332                 }
333
334                 for (i = 0; i < n; i++) {
335                         if (strlen(namelist[i]->d_name) < 7)
336                                 goto inval;
337
338                         lwsl_notice("   %s\n", namelist[i]->d_name);
339
340                         lws_snprintf(path, sizeof(path) - 1, "%s/%s", *d,
341                                  namelist[i]->d_name);
342                         l = dlopen(path, RTLD_NOW);
343                         if (!l) {
344                                 lwsl_err("Error loading DSO: %s\n", dlerror());
345                                 while (i++ < n)
346                                         free(namelist[i]);
347                                 goto bail;
348                         }
349                         /* we could open it, can we get his init function? */
350                         m = lws_snprintf(path, sizeof(path) - 1, "init_%s",
351                                      namelist[i]->d_name + 3 /* snip lib... */);
352                         path[m - 3] = '\0'; /* snip the .so */
353                         initfunc = dlsym(l, path);
354                         if (!initfunc) {
355                                 lwsl_err("Failed to get init on %s: %s",
356                                                 namelist[i]->d_name, dlerror());
357                                 dlclose(l);
358                         }
359                         lcaps.api_magic = LWS_PLUGIN_API_MAGIC;
360                         m = initfunc(context, &lcaps);
361                         if (m) {
362                                 lwsl_err("Initializing %s failed %d\n",
363                                         namelist[i]->d_name, m);
364                                 dlclose(l);
365                                 goto skip;
366                         }
367
368                         plugin = lws_malloc(sizeof(*plugin));
369                         if (!plugin) {
370                                 lwsl_err("OOM\n");
371                                 goto bail;
372                         }
373                         plugin->list = context->plugin_list;
374                         context->plugin_list = plugin;
375                         strncpy(plugin->name, namelist[i]->d_name, sizeof(plugin->name) - 1);
376                         plugin->name[sizeof(plugin->name) - 1] = '\0';
377                         plugin->l = l;
378                         plugin->caps = lcaps;
379                         context->plugin_protocol_count += lcaps.count_protocols;
380                         context->plugin_extension_count += lcaps.count_extensions;
381
382                         free(namelist[i]);
383                         continue;
384
385         skip:
386                         dlclose(l);
387         inval:
388                         free(namelist[i]);
389                 }
390                 free(namelist);
391                 d++;
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 = lws_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 #if 0
444 static void
445 sigabrt_handler(int x)
446 {
447         printf("%s\n", __func__);
448         //*(char *)0 = 0;
449 }
450 #endif
451
452 LWS_VISIBLE int
453 lws_plat_context_early_init(void)
454 {
455         signal(SIGPIPE, SIG_IGN);
456
457 //      signal(SIGABRT, sigabrt_handler);
458
459         return 0;
460 }
461
462 LWS_VISIBLE void
463 lws_plat_context_early_destroy(struct lws_context *context)
464 {
465 }
466
467 LWS_VISIBLE void
468 lws_plat_context_late_destroy(struct lws_context *context)
469 {
470         struct lws_context_per_thread *pt = &context->pt[0];
471         int m = context->count_threads;
472
473 #ifdef LWS_WITH_PLUGINS
474         if (context->plugin_list)
475                 lws_plat_plugins_destroy(context);
476 #endif
477
478         if (context->lws_lookup)
479                 lws_free(context->lws_lookup);
480
481         while (m--) {
482                 if (pt->dummy_pipe_fds[0])
483                         close(pt->dummy_pipe_fds[0]);
484                 if (pt->dummy_pipe_fds[1])
485                         close(pt->dummy_pipe_fds[1]);
486                 pt++;
487         }
488         if (!context->fd_random)
489                 lwsl_err("ZERO RANDOM FD\n");
490         if (context->fd_random != LWS_INVALID_FILE)
491                 close(context->fd_random);
492 }
493
494 /* cast a struct sockaddr_in6 * into addr for ipv6 */
495
496 LWS_VISIBLE int
497 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
498                     size_t addrlen)
499 {
500         int rc = -1;
501
502         struct ifaddrs *ifr;
503         struct ifaddrs *ifc;
504 #ifdef LWS_USE_IPV6
505         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
506 #endif
507
508         getifaddrs(&ifr);
509         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
510                 if (!ifc->ifa_addr)
511                         continue;
512
513                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
514
515                 if (strcmp(ifc->ifa_name, ifname))
516                         continue;
517
518                 switch (ifc->ifa_addr->sa_family) {
519                 case AF_INET:
520 #ifdef LWS_USE_IPV6
521                         if (ipv6) {
522                                 /* map IPv4 to IPv6 */
523                                 bzero((char *)&addr6->sin6_addr,
524                                                 sizeof(struct in6_addr));
525                                 addr6->sin6_addr.s6_addr[10] = 0xff;
526                                 addr6->sin6_addr.s6_addr[11] = 0xff;
527                                 memcpy(&addr6->sin6_addr.s6_addr[12],
528                                         &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
529                                                         sizeof(struct in_addr));
530                         } else
531 #endif
532                                 memcpy(addr,
533                                         (struct sockaddr_in *)ifc->ifa_addr,
534                                                     sizeof(struct sockaddr_in));
535                         break;
536 #ifdef LWS_USE_IPV6
537                 case AF_INET6:
538                         memcpy(&addr6->sin6_addr,
539                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
540                                                        sizeof(struct in6_addr));
541                         break;
542 #endif
543                 default:
544                         continue;
545                 }
546                 rc = 0;
547         }
548
549         freeifaddrs(ifr);
550
551         if (rc == -1) {
552                 /* check if bind to IP address */
553 #ifdef LWS_USE_IPV6
554                 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
555                         rc = 0;
556                 else
557 #endif
558                 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
559                         rc = 0;
560         }
561
562         return rc;
563 }
564
565 LWS_VISIBLE void
566 lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)
567 {
568         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
569
570         lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ);
571         lws_libuv_io(wsi, LWS_EV_START | LWS_EV_READ);
572
573         pt->fds[pt->fds_count++].revents = 0;
574 }
575
576 LWS_VISIBLE void
577 lws_plat_delete_socket_from_fds(struct lws_context *context,
578                                                 struct lws *wsi, int m)
579 {
580         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
581
582         lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE);
583         lws_libuv_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE);
584
585         pt->fds_count--;
586 }
587
588 LWS_VISIBLE void
589 lws_plat_service_periodic(struct lws_context *context)
590 {
591         /* if our parent went down, don't linger around */
592         if (context->started_with_parent &&
593             kill(context->started_with_parent, 0) < 0)
594                 kill(getpid(), SIGTERM);
595 }
596
597 LWS_VISIBLE int
598 lws_plat_change_pollfd(struct lws_context *context,
599                       struct lws *wsi, struct lws_pollfd *pfd)
600 {
601         return 0;
602 }
603
604 LWS_VISIBLE const char *
605 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
606 {
607         return inet_ntop(af, src, dst, cnt);
608 }
609
610 static lws_filefd_type
611 _lws_plat_file_open(struct lws *wsi, const char *filename,
612                     unsigned long *filelen, int flags)
613 {
614         struct stat stat_buf;
615         int ret = open(filename, flags, 0664);
616
617         if (ret < 0)
618                 return LWS_INVALID_FILE;
619
620         if (fstat(ret, &stat_buf) < 0) {
621                 close(ret);
622                 return LWS_INVALID_FILE;
623         }
624         *filelen = stat_buf.st_size;
625         return ret;
626 }
627
628 static int
629 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
630 {
631         return close(fd);
632 }
633
634 unsigned long
635 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
636 {
637         return lseek(fd, offset, SEEK_CUR);
638 }
639
640 static int
641 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
642                     unsigned char *buf, unsigned long len)
643 {
644         long n;
645
646         n = read((int)fd, buf, len);
647         if (n == -1) {
648                 *amount = 0;
649                 return -1;
650         }
651
652         *amount = n;
653
654         return 0;
655 }
656
657 static int
658 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
659                      unsigned char *buf, unsigned long len)
660 {
661         long n;
662
663         n = write((int)fd, buf, len);
664         if (n == -1) {
665                 *amount = 0;
666                 return -1;
667         }
668
669         *amount = n;
670
671         return 0;
672 }
673
674
675 LWS_VISIBLE int
676 lws_plat_init(struct lws_context *context,
677               struct lws_context_creation_info *info)
678 {
679         struct lws_context_per_thread *pt = &context->pt[0];
680         int n = context->count_threads, fd;
681
682         /* master context has the global fd lookup array */
683         context->lws_lookup = lws_zalloc(sizeof(struct lws *) *
684                                          context->max_fds);
685         if (context->lws_lookup == NULL) {
686                 lwsl_err("OOM on lws_lookup array for %d connections\n",
687                          context->max_fds);
688                 return 1;
689         }
690
691         lwsl_notice(" mem: platform fd map: %5u bytes\n",
692                     sizeof(struct lws *) * context->max_fds);
693         fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
694
695         context->fd_random = fd;
696         if (context->fd_random < 0) {
697                 lwsl_err("Unable to open random device %s %d\n",
698                          SYSTEM_RANDOM_FILEPATH, context->fd_random);
699                 return 1;
700         }
701
702         if (!lws_libev_init_fd_table(context) &&
703             !lws_libuv_init_fd_table(context)) {
704                 /* otherwise libev handled it instead */
705
706                 while (n--) {
707                         if (pipe(pt->dummy_pipe_fds)) {
708                                 lwsl_err("Unable to create pipe\n");
709                                 return 1;
710                         }
711
712                         /* use the read end of pipe as first item */
713                         pt->fds[0].fd = pt->dummy_pipe_fds[0];
714                         pt->fds[0].events = LWS_POLLIN;
715                         pt->fds[0].revents = 0;
716                         pt->fds_count = 1;
717                         pt++;
718                 }
719         }
720
721         context->fops.open      = _lws_plat_file_open;
722         context->fops.close     = _lws_plat_file_close;
723         context->fops.seek_cur  = _lws_plat_file_seek_cur;
724         context->fops.read      = _lws_plat_file_read;
725         context->fops.write     = _lws_plat_file_write;
726
727 #ifdef LWS_WITH_PLUGINS
728         if (info->plugin_dirs)
729                 lws_plat_plugins_init(context, info->plugin_dirs);
730 #endif
731
732         return 0;
733 }