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