force service properly when unconsumed rxbuf in ah
[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, m, c;
126         char buf;
127
128         /* stay dead once we are dead */
129
130         if (!context)
131                 return 1;
132
133         lws_libev_run(context, tsi);
134         lws_libuv_run(context, tsi);
135
136         if (!context->service_tid_detected) {
137                 struct lws _lws;
138
139                 memset(&_lws, 0, sizeof(_lws));
140                 _lws.context = context;
141
142                 context->service_tid_detected = context->protocols[0].callback(
143                         &_lws, LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
144         }
145         context->service_tid = context->service_tid_detected;
146
147         timeout_ms = lws_service_adjust_timeout(context, timeout_ms, tsi);
148
149         n = poll(pt->fds, pt->fds_count, timeout_ms);
150
151 #ifdef LWS_OPENSSL_SUPPORT
152         if (!pt->rx_draining_ext_list &&
153             !lws_ssl_anybody_has_buffered_read_tsi(context, tsi) && !n) {
154 #else
155         if (!pt->rx_draining_ext_list && !n) /* poll timeout */ {
156 #endif
157                 lws_service_fd_tsi(context, NULL, tsi);
158                 return 0;
159         }
160
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_context *context, 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 (context->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 = context->ka_time;
234                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE,
235                                (const void *)&optval, optlen) < 0)
236                         return 1;
237
238                 optval = context->ka_interval;
239                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,
240                                (const void *)&optval, optlen) < 0)
241                         return 1;
242
243                 optval = context->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 static void
293 sigpipe_handler(int x)
294 {
295 }
296
297 LWS_VISIBLE int
298 lws_plat_context_early_init(void)
299 {
300         sigset_t mask;
301
302         signal(SIGUSR2, lws_sigusr2);
303         sigemptyset(&mask);
304         sigaddset(&mask, SIGUSR2);
305
306         sigprocmask(SIG_BLOCK, &mask, NULL);
307
308         signal(SIGPIPE, sigpipe_handler);
309
310         return 0;
311 }
312
313 LWS_VISIBLE void
314 lws_plat_context_early_destroy(struct lws_context *context)
315 {
316 }
317
318 LWS_VISIBLE void
319 lws_plat_context_late_destroy(struct lws_context *context)
320 {
321         struct lws_context_per_thread *pt = &context->pt[0];
322         int m = context->count_threads;
323
324         if (context->lws_lookup)
325                 lws_free(context->lws_lookup);
326
327         while (m--) {
328                 close(pt->dummy_pipe_fds[0]);
329                 close(pt->dummy_pipe_fds[1]);
330                 pt++;
331         }
332         close(context->fd_random);
333 }
334
335 /* cast a struct sockaddr_in6 * into addr for ipv6 */
336
337 LWS_VISIBLE int
338 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
339                     size_t addrlen)
340 {
341         int rc = -1;
342
343         struct ifaddrs *ifr;
344         struct ifaddrs *ifc;
345 #ifdef LWS_USE_IPV6
346         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
347 #endif
348
349         getifaddrs(&ifr);
350         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
351                 if (!ifc->ifa_addr)
352                         continue;
353
354                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
355
356                 if (strcmp(ifc->ifa_name, ifname))
357                         continue;
358
359                 switch (ifc->ifa_addr->sa_family) {
360                 case AF_INET:
361 #ifdef LWS_USE_IPV6
362                         if (ipv6) {
363                                 /* map IPv4 to IPv6 */
364                                 bzero((char *)&addr6->sin6_addr,
365                                                 sizeof(struct in6_addr));
366                                 addr6->sin6_addr.s6_addr[10] = 0xff;
367                                 addr6->sin6_addr.s6_addr[11] = 0xff;
368                                 memcpy(&addr6->sin6_addr.s6_addr[12],
369                                         &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
370                                                         sizeof(struct in_addr));
371                         } else
372 #endif
373                                 memcpy(addr,
374                                         (struct sockaddr_in *)ifc->ifa_addr,
375                                                     sizeof(struct sockaddr_in));
376                         break;
377 #ifdef LWS_USE_IPV6
378                 case AF_INET6:
379                         memcpy(&addr6->sin6_addr,
380                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
381                                                        sizeof(struct in6_addr));
382                         break;
383 #endif
384                 default:
385                         continue;
386                 }
387                 rc = 0;
388         }
389
390         freeifaddrs(ifr);
391
392         if (rc == -1) {
393                 /* check if bind to IP adddress */
394 #ifdef LWS_USE_IPV6
395                 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
396                         rc = 0;
397                 else
398 #endif
399                 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
400                         rc = 0;
401         }
402
403         return rc;
404 }
405
406 LWS_VISIBLE void
407 lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)
408 {
409         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
410
411         lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ);
412         lws_libuv_io(wsi, LWS_EV_START | LWS_EV_READ);
413
414         pt->fds[pt->fds_count++].revents = 0;
415 }
416
417 LWS_VISIBLE void
418 lws_plat_delete_socket_from_fds(struct lws_context *context,
419                                                 struct lws *wsi, int m)
420 {
421         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
422         pt->fds_count--;
423 }
424
425 LWS_VISIBLE void
426 lws_plat_service_periodic(struct lws_context *context)
427 {
428         /* if our parent went down, don't linger around */
429         if (context->started_with_parent &&
430             kill(context->started_with_parent, 0) < 0)
431                 kill(getpid(), SIGTERM);
432 }
433
434 LWS_VISIBLE int
435 lws_plat_change_pollfd(struct lws_context *context,
436                       struct lws *wsi, struct lws_pollfd *pfd)
437 {
438         return 0;
439 }
440
441 LWS_VISIBLE const char *
442 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
443 {
444         return inet_ntop(af, src, dst, cnt);
445 }
446
447 static lws_filefd_type
448 _lws_plat_file_open(struct lws *wsi, const char *filename,
449                     unsigned long *filelen, int flags)
450 {
451         struct stat stat_buf;
452         int ret = open(filename, flags, 0664);
453
454         if (ret < 0)
455                 return LWS_INVALID_FILE;
456
457         if (fstat(ret, &stat_buf) < 0) {
458                 close(ret);
459                 return LWS_INVALID_FILE;
460         }
461         *filelen = stat_buf.st_size;
462         return ret;
463 }
464
465 static int
466 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
467 {
468         return close(fd);
469 }
470
471 unsigned long
472 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
473 {
474         return lseek(fd, offset, SEEK_CUR);
475 }
476
477 static int
478 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
479                     unsigned char *buf, unsigned long len)
480 {
481         long n;
482
483         n = read((int)fd, buf, len);
484         if (n == -1) {
485                 *amount = 0;
486                 return -1;
487         }
488
489         *amount = n;
490
491         return 0;
492 }
493
494 static int
495 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
496                      unsigned char *buf, unsigned long len)
497 {
498         long n;
499
500         n = write((int)fd, buf, len);
501         if (n == -1) {
502                 *amount = 0;
503                 return -1;
504         }
505
506         *amount = n;
507
508         return 0;
509 }
510
511 LWS_VISIBLE int
512 lws_plat_init(struct lws_context *context,
513               struct lws_context_creation_info *info)
514 {
515         struct lws_context_per_thread *pt = &context->pt[0];
516         int n = context->count_threads, fd;
517
518         /* master context has the global fd lookup array */
519         context->lws_lookup = lws_zalloc(sizeof(struct lws *) *
520                                          context->max_fds);
521         if (context->lws_lookup == NULL) {
522                 lwsl_err("OOM on lws_lookup array for %d connections\n",
523                          context->max_fds);
524                 return 1;
525         }
526
527         lwsl_notice(" mem: platform fd map: %5u bytes\n",
528                     sizeof(struct lws *) * context->max_fds);
529         fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
530
531         context->fd_random = fd;
532         if (context->fd_random < 0) {
533                 lwsl_err("Unable to open random device %s %d\n",
534                          SYSTEM_RANDOM_FILEPATH, context->fd_random);
535                 return 1;
536         }
537
538         if (!lws_libev_init_fd_table(context) &&
539             !lws_libuv_init_fd_table(context)) {
540                 /* otherwise libev handled it instead */
541
542                 while (n--) {
543                         if (pipe(pt->dummy_pipe_fds)) {
544                                 lwsl_err("Unable to create pipe\n");
545                                 return 1;
546                         }
547
548                         /* use the read end of pipe as first item */
549                         pt->fds[0].fd = pt->dummy_pipe_fds[0];
550                         pt->fds[0].events = LWS_POLLIN;
551                         pt->fds[0].revents = 0;
552                         pt->fds_count = 1;
553                         pt++;
554                 }
555         }
556
557         context->fops.open      = _lws_plat_file_open;
558         context->fops.close     = _lws_plat_file_close;
559         context->fops.seek_cur  = _lws_plat_file_seek_cur;
560         context->fops.read      = _lws_plat_file_read;
561         context->fops.write     = _lws_plat_file_write;
562
563         return 0;
564 }