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