lwsws cgi integration
[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 sigabrt_handler(int x)
445 {
446         printf("%s\n", __func__);
447         //*(char *)0 = 0;
448 }
449
450 LWS_VISIBLE int
451 lws_plat_context_early_init(void)
452 {
453         sigset_t mask;
454
455         signal(SIGUSR2, lws_sigusr2);
456         sigemptyset(&mask);
457         sigaddset(&mask, SIGUSR2);
458
459         sigprocmask(SIG_BLOCK, &mask, NULL);
460
461         signal(SIGPIPE, SIG_IGN);
462
463         signal(SIGABRT, sigabrt_handler);
464
465         return 0;
466 }
467
468 LWS_VISIBLE void
469 lws_plat_context_early_destroy(struct lws_context *context)
470 {
471 }
472
473 LWS_VISIBLE void
474 lws_plat_context_late_destroy(struct lws_context *context)
475 {
476         struct lws_context_per_thread *pt = &context->pt[0];
477         int m = context->count_threads;
478
479 #ifdef LWS_WITH_PLUGINS
480         if (context->plugin_list)
481                 lws_plat_plugins_destroy(context);
482 #endif
483
484         if (context->lws_lookup)
485                 lws_free(context->lws_lookup);
486
487         while (m--) {
488                 close(pt->dummy_pipe_fds[0]);
489                 close(pt->dummy_pipe_fds[1]);
490                 pt++;
491         }
492         close(context->fd_random);
493 }
494
495 /* cast a struct sockaddr_in6 * into addr for ipv6 */
496
497 LWS_VISIBLE int
498 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
499                     size_t addrlen)
500 {
501         int rc = -1;
502
503         struct ifaddrs *ifr;
504         struct ifaddrs *ifc;
505 #ifdef LWS_USE_IPV6
506         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
507 #endif
508
509         getifaddrs(&ifr);
510         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
511                 if (!ifc->ifa_addr)
512                         continue;
513
514                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
515
516                 if (strcmp(ifc->ifa_name, ifname))
517                         continue;
518
519                 switch (ifc->ifa_addr->sa_family) {
520                 case AF_INET:
521 #ifdef LWS_USE_IPV6
522                         if (ipv6) {
523                                 /* map IPv4 to IPv6 */
524                                 bzero((char *)&addr6->sin6_addr,
525                                                 sizeof(struct in6_addr));
526                                 addr6->sin6_addr.s6_addr[10] = 0xff;
527                                 addr6->sin6_addr.s6_addr[11] = 0xff;
528                                 memcpy(&addr6->sin6_addr.s6_addr[12],
529                                         &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
530                                                         sizeof(struct in_addr));
531                         } else
532 #endif
533                                 memcpy(addr,
534                                         (struct sockaddr_in *)ifc->ifa_addr,
535                                                     sizeof(struct sockaddr_in));
536                         break;
537 #ifdef LWS_USE_IPV6
538                 case AF_INET6:
539                         memcpy(&addr6->sin6_addr,
540                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
541                                                        sizeof(struct in6_addr));
542                         break;
543 #endif
544                 default:
545                         continue;
546                 }
547                 rc = 0;
548         }
549
550         freeifaddrs(ifr);
551
552         if (rc == -1) {
553                 /* check if bind to IP adddress */
554 #ifdef LWS_USE_IPV6
555                 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
556                         rc = 0;
557                 else
558 #endif
559                 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
560                         rc = 0;
561         }
562
563         return rc;
564 }
565
566 LWS_VISIBLE void
567 lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)
568 {
569         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
570
571         lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ);
572         lws_libuv_io(wsi, LWS_EV_START | LWS_EV_READ);
573
574         pt->fds[pt->fds_count++].revents = 0;
575 }
576
577 LWS_VISIBLE void
578 lws_plat_delete_socket_from_fds(struct lws_context *context,
579                                                 struct lws *wsi, int m)
580 {
581         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
582         pt->fds_count--;
583 }
584
585 LWS_VISIBLE void
586 lws_plat_service_periodic(struct lws_context *context)
587 {
588         /* if our parent went down, don't linger around */
589         if (context->started_with_parent &&
590             kill(context->started_with_parent, 0) < 0)
591                 kill(getpid(), SIGTERM);
592 }
593
594 LWS_VISIBLE int
595 lws_plat_change_pollfd(struct lws_context *context,
596                       struct lws *wsi, struct lws_pollfd *pfd)
597 {
598         return 0;
599 }
600
601 LWS_VISIBLE const char *
602 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
603 {
604         return inet_ntop(af, src, dst, cnt);
605 }
606
607 static lws_filefd_type
608 _lws_plat_file_open(struct lws *wsi, const char *filename,
609                     unsigned long *filelen, int flags)
610 {
611         struct stat stat_buf;
612         int ret = open(filename, flags, 0664);
613
614         if (ret < 0)
615                 return LWS_INVALID_FILE;
616
617         if (fstat(ret, &stat_buf) < 0) {
618                 close(ret);
619                 return LWS_INVALID_FILE;
620         }
621         *filelen = stat_buf.st_size;
622         return ret;
623 }
624
625 static int
626 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
627 {
628         return close(fd);
629 }
630
631 unsigned long
632 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
633 {
634         return lseek(fd, offset, SEEK_CUR);
635 }
636
637 static int
638 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
639                     unsigned char *buf, unsigned long len)
640 {
641         long n;
642
643         n = read((int)fd, buf, len);
644         if (n == -1) {
645                 *amount = 0;
646                 return -1;
647         }
648
649         *amount = n;
650
651         return 0;
652 }
653
654 static int
655 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
656                      unsigned char *buf, unsigned long len)
657 {
658         long n;
659
660         n = write((int)fd, buf, len);
661         if (n == -1) {
662                 *amount = 0;
663                 return -1;
664         }
665
666         *amount = n;
667
668         return 0;
669 }
670
671
672 LWS_VISIBLE int
673 lws_plat_init(struct lws_context *context,
674               struct lws_context_creation_info *info)
675 {
676         struct lws_context_per_thread *pt = &context->pt[0];
677         int n = context->count_threads, fd;
678
679         /* master context has the global fd lookup array */
680         context->lws_lookup = lws_zalloc(sizeof(struct lws *) *
681                                          context->max_fds);
682         if (context->lws_lookup == NULL) {
683                 lwsl_err("OOM on lws_lookup array for %d connections\n",
684                          context->max_fds);
685                 return 1;
686         }
687
688         lwsl_notice(" mem: platform fd map: %5u bytes\n",
689                     sizeof(struct lws *) * context->max_fds);
690         fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
691
692         context->fd_random = fd;
693         if (context->fd_random < 0) {
694                 lwsl_err("Unable to open random device %s %d\n",
695                          SYSTEM_RANDOM_FILEPATH, context->fd_random);
696                 return 1;
697         }
698
699         if (!lws_libev_init_fd_table(context) &&
700             !lws_libuv_init_fd_table(context)) {
701                 /* otherwise libev handled it instead */
702
703                 while (n--) {
704                         if (pipe(pt->dummy_pipe_fds)) {
705                                 lwsl_err("Unable to create pipe\n");
706                                 return 1;
707                         }
708
709                         /* use the read end of pipe as first item */
710                         pt->fds[0].fd = pt->dummy_pipe_fds[0];
711                         pt->fds[0].events = LWS_POLLIN;
712                         pt->fds[0].revents = 0;
713                         pt->fds_count = 1;
714                         pt++;
715                 }
716         }
717
718         context->fops.open      = _lws_plat_file_open;
719         context->fops.close     = _lws_plat_file_close;
720         context->fops.seek_cur  = _lws_plat_file_seek_cur;
721         context->fops.read      = _lws_plat_file_read;
722         context->fops.write     = _lws_plat_file_write;
723
724 #ifdef LWS_WITH_PLUGINS
725         if (info->plugins_dir)
726                 lws_plat_plugins_init(context, info->plugins_dir);
727 #endif
728
729         return 0;
730 }