libuv add idle processing to force service where needed
[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         int n = -1, m, c;
126         char buf;
127
128         /* stay dead once we are dead */
129
130         if (!context || !context->vhost_list)
131                 return 1;
132
133         if (timeout_ms < 0)
134                 goto faked_service;
135
136         lws_libev_run(context, tsi);
137         lws_libuv_run(context, tsi);
138
139         if (!context->service_tid_detected) {
140                 struct lws _lws;
141
142                 memset(&_lws, 0, sizeof(_lws));
143                 _lws.context = context;
144
145                 context->service_tid_detected =
146                         context->vhost_list->protocols[0].callback(
147                         &_lws, LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
148         }
149         context->service_tid = context->service_tid_detected;
150
151         timeout_ms = lws_service_adjust_timeout(context, timeout_ms, tsi);
152
153         n = poll(pt->fds, pt->fds_count, timeout_ms);
154
155 #ifdef LWS_OPENSSL_SUPPORT
156         if (!pt->rx_draining_ext_list &&
157             !lws_ssl_anybody_has_buffered_read_tsi(context, tsi) && !n) {
158 #else
159         if (!pt->rx_draining_ext_list && !n) /* poll timeout */ {
160 #endif
161                 lws_service_fd_tsi(context, NULL, tsi);
162                 return 0;
163         }
164
165 faked_service:
166         m = lws_service_flag_pending(context, tsi);
167         if (m)
168                 c = -1; /* unknown limit */
169         else
170                 if (n < 0) {
171                         if (LWS_ERRNO != LWS_EINTR)
172                                 return -1;
173                         return 0;
174                 } else
175                         c = n;
176
177         /* any socket with events to service? */
178         for (n = 0; n < pt->fds_count && c; n++) {
179                 if (!pt->fds[n].revents)
180                         continue;
181
182                 c--;
183
184                 if (pt->fds[n].fd == pt->dummy_pipe_fds[0]) {
185                         if (read(pt->fds[n].fd, &buf, 1) != 1)
186                                 lwsl_err("Cannot read from dummy pipe.");
187                         continue;
188                 }
189
190                 m = lws_service_fd_tsi(context, &pt->fds[n], tsi);
191                 if (m < 0)
192                         return -1;
193                 /* if something closed, retry this slot */
194                 if (m)
195                         n--;
196         }
197
198         return 0;
199 }
200
201 LWS_VISIBLE int
202 lws_plat_service(struct lws_context *context, int timeout_ms)
203 {
204         return lws_plat_service_tsi(context, timeout_ms, 0);
205 }
206
207 LWS_VISIBLE int
208 lws_plat_set_socket_options(struct lws_vhost *vhost, int fd)
209 {
210         int optval = 1;
211         socklen_t optlen = sizeof(optval);
212
213 #if defined(__APPLE__) || \
214     defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
215     defined(__NetBSD__) || \
216     defined(__OpenBSD__)
217         struct protoent *tcp_proto;
218 #endif
219
220         if (vhost->ka_time) {
221                 /* enable keepalive on this socket */
222                 optval = 1;
223                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
224                                (const void *)&optval, optlen) < 0)
225                         return 1;
226
227 #if defined(__APPLE__) || \
228     defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
229     defined(__NetBSD__) || \
230         defined(__CYGWIN__) || defined(__OpenBSD__)
231
232                 /*
233                  * didn't find a way to set these per-socket, need to
234                  * tune kernel systemwide values
235                  */
236 #else
237                 /* set the keepalive conditions we want on it too */
238                 optval = vhost->ka_time;
239                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE,
240                                (const void *)&optval, optlen) < 0)
241                         return 1;
242
243                 optval = vhost->ka_interval;
244                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,
245                                (const void *)&optval, optlen) < 0)
246                         return 1;
247
248                 optval = vhost->ka_probes;
249                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT,
250                                (const void *)&optval, optlen) < 0)
251                         return 1;
252 #endif
253         }
254
255         /* Disable Nagle */
256         optval = 1;
257 #if !defined(__APPLE__) && \
258     !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__) && \
259     !defined(__NetBSD__) && \
260     !defined(__OpenBSD__)
261         if (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)
262                 return 1;
263 #else
264         tcp_proto = getprotobyname("TCP");
265         if (setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen) < 0)
266                 return 1;
267 #endif
268
269         /* We are nonblocking... */
270         if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
271                 return 1;
272
273         return 0;
274 }
275
276 LWS_VISIBLE void
277 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
278 {
279         if (info->gid != -1)
280                 if (setgid(info->gid))
281                         lwsl_warn("setgid: %s\n", strerror(LWS_ERRNO));
282
283         if (info->uid != -1) {
284                 struct passwd *p = getpwuid(info->uid);
285
286                 if (p) {
287                         initgroups(p->pw_name, info->gid);
288                         if (setuid(info->uid))
289                                 lwsl_warn("setuid: %s\n", strerror(LWS_ERRNO));
290                         else
291                                 lwsl_notice("Set privs to user '%s'\n", p->pw_name);
292                 } else
293                         lwsl_warn("getpwuid: unable to find uid %d", info->uid);
294         }
295 }
296
297 static void
298 sigpipe_handler(int x)
299 {
300 }
301
302 LWS_VISIBLE int
303 lws_plat_context_early_init(void)
304 {
305         sigset_t mask;
306
307         signal(SIGUSR2, lws_sigusr2);
308         sigemptyset(&mask);
309         sigaddset(&mask, SIGUSR2);
310
311         sigprocmask(SIG_BLOCK, &mask, NULL);
312
313         signal(SIGPIPE, sigpipe_handler);
314
315         return 0;
316 }
317
318 LWS_VISIBLE void
319 lws_plat_context_early_destroy(struct lws_context *context)
320 {
321 }
322
323 LWS_VISIBLE void
324 lws_plat_context_late_destroy(struct lws_context *context)
325 {
326         struct lws_context_per_thread *pt = &context->pt[0];
327         int m = context->count_threads;
328
329         if (context->lws_lookup)
330                 lws_free(context->lws_lookup);
331
332         while (m--) {
333                 close(pt->dummy_pipe_fds[0]);
334                 close(pt->dummy_pipe_fds[1]);
335                 pt++;
336         }
337         close(context->fd_random);
338 }
339
340 /* cast a struct sockaddr_in6 * into addr for ipv6 */
341
342 LWS_VISIBLE int
343 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
344                     size_t addrlen)
345 {
346         int rc = -1;
347
348         struct ifaddrs *ifr;
349         struct ifaddrs *ifc;
350 #ifdef LWS_USE_IPV6
351         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
352 #endif
353
354         getifaddrs(&ifr);
355         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
356                 if (!ifc->ifa_addr)
357                         continue;
358
359                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
360
361                 if (strcmp(ifc->ifa_name, ifname))
362                         continue;
363
364                 switch (ifc->ifa_addr->sa_family) {
365                 case AF_INET:
366 #ifdef LWS_USE_IPV6
367                         if (ipv6) {
368                                 /* map IPv4 to IPv6 */
369                                 bzero((char *)&addr6->sin6_addr,
370                                                 sizeof(struct in6_addr));
371                                 addr6->sin6_addr.s6_addr[10] = 0xff;
372                                 addr6->sin6_addr.s6_addr[11] = 0xff;
373                                 memcpy(&addr6->sin6_addr.s6_addr[12],
374                                         &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
375                                                         sizeof(struct in_addr));
376                         } else
377 #endif
378                                 memcpy(addr,
379                                         (struct sockaddr_in *)ifc->ifa_addr,
380                                                     sizeof(struct sockaddr_in));
381                         break;
382 #ifdef LWS_USE_IPV6
383                 case AF_INET6:
384                         memcpy(&addr6->sin6_addr,
385                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
386                                                        sizeof(struct in6_addr));
387                         break;
388 #endif
389                 default:
390                         continue;
391                 }
392                 rc = 0;
393         }
394
395         freeifaddrs(ifr);
396
397         if (rc == -1) {
398                 /* check if bind to IP adddress */
399 #ifdef LWS_USE_IPV6
400                 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
401                         rc = 0;
402                 else
403 #endif
404                 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
405                         rc = 0;
406         }
407
408         return rc;
409 }
410
411 LWS_VISIBLE void
412 lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)
413 {
414         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
415
416         lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ);
417         lws_libuv_io(wsi, LWS_EV_START | LWS_EV_READ);
418
419         pt->fds[pt->fds_count++].revents = 0;
420 }
421
422 LWS_VISIBLE void
423 lws_plat_delete_socket_from_fds(struct lws_context *context,
424                                                 struct lws *wsi, int m)
425 {
426         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
427         pt->fds_count--;
428 }
429
430 LWS_VISIBLE void
431 lws_plat_service_periodic(struct lws_context *context)
432 {
433         /* if our parent went down, don't linger around */
434         if (context->started_with_parent &&
435             kill(context->started_with_parent, 0) < 0)
436                 kill(getpid(), SIGTERM);
437 }
438
439 LWS_VISIBLE int
440 lws_plat_change_pollfd(struct lws_context *context,
441                       struct lws *wsi, struct lws_pollfd *pfd)
442 {
443         return 0;
444 }
445
446 LWS_VISIBLE const char *
447 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
448 {
449         return inet_ntop(af, src, dst, cnt);
450 }
451
452 static lws_filefd_type
453 _lws_plat_file_open(struct lws *wsi, const char *filename,
454                     unsigned long *filelen, int flags)
455 {
456         struct stat stat_buf;
457         int ret = open(filename, flags, 0664);
458
459         if (ret < 0)
460                 return LWS_INVALID_FILE;
461
462         if (fstat(ret, &stat_buf) < 0) {
463                 close(ret);
464                 return LWS_INVALID_FILE;
465         }
466         *filelen = stat_buf.st_size;
467         return ret;
468 }
469
470 static int
471 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
472 {
473         return close(fd);
474 }
475
476 unsigned long
477 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
478 {
479         return lseek(fd, offset, SEEK_CUR);
480 }
481
482 static int
483 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
484                     unsigned char *buf, unsigned long len)
485 {
486         long n;
487
488         n = read((int)fd, buf, len);
489         if (n == -1) {
490                 *amount = 0;
491                 return -1;
492         }
493
494         *amount = n;
495
496         return 0;
497 }
498
499 static int
500 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
501                      unsigned char *buf, unsigned long len)
502 {
503         long n;
504
505         n = write((int)fd, buf, len);
506         if (n == -1) {
507                 *amount = 0;
508                 return -1;
509         }
510
511         *amount = n;
512
513         return 0;
514 }
515
516 LWS_VISIBLE int
517 lws_plat_init(struct lws_context *context,
518               struct lws_context_creation_info *info)
519 {
520         struct lws_context_per_thread *pt = &context->pt[0];
521         int n = context->count_threads, fd;
522
523         /* master context has the global fd lookup array */
524         context->lws_lookup = lws_zalloc(sizeof(struct lws *) *
525                                          context->max_fds);
526         if (context->lws_lookup == NULL) {
527                 lwsl_err("OOM on lws_lookup array for %d connections\n",
528                          context->max_fds);
529                 return 1;
530         }
531
532         lwsl_notice(" mem: platform fd map: %5u bytes\n",
533                     sizeof(struct lws *) * context->max_fds);
534         fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
535
536         context->fd_random = fd;
537         if (context->fd_random < 0) {
538                 lwsl_err("Unable to open random device %s %d\n",
539                          SYSTEM_RANDOM_FILEPATH, context->fd_random);
540                 return 1;
541         }
542
543         if (!lws_libev_init_fd_table(context) &&
544             !lws_libuv_init_fd_table(context)) {
545                 /* otherwise libev handled it instead */
546
547                 while (n--) {
548                         if (pipe(pt->dummy_pipe_fds)) {
549                                 lwsl_err("Unable to create pipe\n");
550                                 return 1;
551                         }
552
553                         /* use the read end of pipe as first item */
554                         pt->fds[0].fd = pt->dummy_pipe_fds[0];
555                         pt->fds[0].events = LWS_POLLIN;
556                         pt->fds[0].revents = 0;
557                         pt->fds_count = 1;
558                         pt++;
559                 }
560         }
561
562         context->fops.open      = _lws_plat_file_open;
563         context->fops.close     = _lws_plat_file_close;
564         context->fops.seek_cur  = _lws_plat_file_seek_cur;
565         context->fops.read      = _lws_plat_file_read;
566         context->fops.write     = _lws_plat_file_write;
567
568         return 0;
569 }