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