libev complete unix plat context init
[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 lws_sigusr2(int sig)
58 {
59 }
60
61 /**
62  * lws_cancel_service() - Cancel servicing of pending websocket activity
63  * @context:    Websocket context
64  *
65  *      This function let a call to lws_service() waiting for a timeout
66  *      immediately return.
67  */
68 LWS_VISIBLE void
69 lws_cancel_service(struct lws_context *context)
70 {
71         char buf = 0;
72
73         if (write(context->dummy_pipe_fds[1], &buf, sizeof(buf)) != 1)
74                 lwsl_err("Cannot write to dummy pipe");
75 }
76
77 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
78 {
79         int syslog_level = LOG_DEBUG;
80
81         switch (level) {
82         case LLL_ERR:
83                 syslog_level = LOG_ERR;
84                 break;
85         case LLL_WARN:
86                 syslog_level = LOG_WARNING;
87                 break;
88         case LLL_NOTICE:
89                 syslog_level = LOG_NOTICE;
90                 break;
91         case LLL_INFO:
92                 syslog_level = LOG_INFO;
93                 break;
94         }
95         syslog(syslog_level, "%s", line);
96 }
97
98 LWS_VISIBLE int
99 lws_plat_service(struct lws_context *context, int timeout_ms)
100 {
101         int n;
102         int m;
103         char buf;
104 #ifdef LWS_OPENSSL_SUPPORT
105         struct lws *wsi, *wsi_next;
106 #endif
107
108         /* stay dead once we are dead */
109
110         if (!context)
111                 return 1;
112
113         lws_libev_run(context);
114
115         context->service_tid = context->protocols[0].callback(NULL,
116                                      LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
117
118 #ifdef LWS_OPENSSL_SUPPORT
119         /* if we know we have non-network pending data, do not wait in poll */
120         if (lws_ssl_anybody_has_buffered_read(context))
121                 timeout_ms = 0;
122 #endif
123         n = poll(context->fds, context->fds_count, timeout_ms);
124         context->service_tid = 0;
125
126 #ifdef LWS_OPENSSL_SUPPORT
127         if (!lws_ssl_anybody_has_buffered_read(context) && n == 0) {
128 #else
129         if (n == 0) /* poll timeout */ {
130 #endif
131                 lws_service_fd(context, NULL);
132                 return 0;
133         }
134
135         if (n < 0) {
136                 if (LWS_ERRNO != LWS_EINTR)
137                         return -1;
138                 return 0;
139         }
140
141 #ifdef LWS_OPENSSL_SUPPORT
142         /*
143          * For all guys with buffered SSL read data already saved up, if they
144          * are not flowcontrolled, fake their POLLIN status so they'll get
145          * service to use up the buffered incoming data, even though their
146          * network socket may have nothing
147          */
148
149         wsi = context->pending_read_list;
150         while (wsi) {
151                 wsi_next = wsi->pending_read_list_next;
152                 context->fds[wsi->position_in_fds_table].revents |=
153                         context->fds[wsi->position_in_fds_table].events & POLLIN;
154                 if (context->fds[wsi->position_in_fds_table].revents & POLLIN)
155                         /*
156                          * he's going to get serviced now, take him off the
157                          * list of guys with buffered SSL.  If he still has some
158                          * at the end of the service, he'll get put back on the
159                          * list then.
160                          */
161                         lws_ssl_remove_wsi_from_buffered_list(wsi);
162
163                 wsi = wsi_next;
164         }
165 #endif
166
167         /* any socket with events to service? */
168
169         for (n = 0; n < context->fds_count; n++) {
170                 if (!context->fds[n].revents)
171                         continue;
172
173                 if (context->fds[n].fd == context->dummy_pipe_fds[0]) {
174                         if (read(context->fds[n].fd, &buf, 1) != 1)
175                                 lwsl_err("Cannot read from dummy pipe.");
176                         continue;
177                 }
178
179                 m = lws_service_fd(context, &context->fds[n]);
180                 if (m < 0)
181                         return -1;
182                 /* if something closed, retry this slot */
183                 if (m)
184                         n--;
185         }
186
187         return 0;
188 }
189
190 LWS_VISIBLE int
191 lws_plat_set_socket_options(struct lws_context *context, int fd)
192 {
193         int optval = 1;
194         socklen_t optlen = sizeof(optval);
195
196 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
197     defined(__OpenBSD__)
198         struct protoent *tcp_proto;
199 #endif
200
201         if (context->ka_time) {
202                 /* enable keepalive on this socket */
203                 optval = 1;
204                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
205                                (const void *)&optval, optlen) < 0)
206                         return 1;
207
208 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
209         defined(__CYGWIN__) || defined(__OpenBSD__)
210
211                 /*
212                  * didn't find a way to set these per-socket, need to
213                  * tune kernel systemwide values
214                  */
215 #else
216                 /* set the keepalive conditions we want on it too */
217                 optval = context->ka_time;
218                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE,
219                                (const void *)&optval, optlen) < 0)
220                         return 1;
221
222                 optval = context->ka_interval;
223                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,
224                                (const void *)&optval, optlen) < 0)
225                         return 1;
226
227                 optval = context->ka_probes;
228                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT,
229                                (const void *)&optval, optlen) < 0)
230                         return 1;
231 #endif
232         }
233
234         /* Disable Nagle */
235         optval = 1;
236 #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && \
237     !defined(__OpenBSD__)
238         if (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)
239                 return 1;
240 #else
241         tcp_proto = getprotobyname("TCP");
242         if (setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen) < 0)
243                 return 1;
244 #endif
245
246         /* We are nonblocking... */
247         if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
248                 return 1;
249
250         return 0;
251 }
252
253 LWS_VISIBLE void
254 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
255 {
256         if (info->uid != -1) {
257                 struct passwd *p = getpwuid(info->uid);
258
259                 if (p) {
260                         initgroups(p->pw_name, info->gid);
261                         if (setuid(info->uid))
262                                 lwsl_warn("setuid: %s\n", strerror(LWS_ERRNO));
263                         else
264                                 lwsl_notice(" Set privs to user '%s'\n", p->pw_name);
265                 } else
266                         lwsl_warn("getpwuid: unable to find uid %d", info->uid);
267         }
268         if (info->gid != -1)
269                 if (setgid(info->gid))
270                         lwsl_warn("setgid: %s\n", strerror(LWS_ERRNO));
271
272 }
273
274 static void sigpipe_handler(int x)
275 {
276 }
277
278 LWS_VISIBLE int
279 lws_plat_context_early_init(void)
280 {
281         sigset_t mask;
282
283         signal(SIGUSR2, lws_sigusr2);
284         sigemptyset(&mask);
285         sigaddset(&mask, SIGUSR2);
286
287         sigprocmask(SIG_BLOCK, &mask, NULL);
288
289         signal(SIGPIPE, sigpipe_handler);
290
291         return 0;
292 }
293
294 LWS_VISIBLE void
295 lws_plat_context_early_destroy(struct lws_context *context)
296 {
297 }
298
299 LWS_VISIBLE void
300 lws_plat_context_late_destroy(struct lws_context *context)
301 {
302         if (context->lws_lookup)
303                 lws_free(context->lws_lookup);
304
305         close(context->dummy_pipe_fds[0]);
306         close(context->dummy_pipe_fds[1]);
307         close(context->fd_random);
308 }
309
310 /* cast a struct sockaddr_in6 * into addr for ipv6 */
311
312 LWS_VISIBLE int
313 interface_to_sa(struct lws_context *context,
314                 const char *ifname, struct sockaddr_in *addr, size_t addrlen)
315 {
316         int rc = -1;
317
318         struct ifaddrs *ifr;
319         struct ifaddrs *ifc;
320 #ifdef LWS_USE_IPV6
321         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
322 #endif
323
324         getifaddrs(&ifr);
325         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
326                 if (!ifc->ifa_addr)
327                         continue;
328
329                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
330
331                 if (strcmp(ifc->ifa_name, ifname))
332                         continue;
333
334                 switch (ifc->ifa_addr->sa_family) {
335                 case AF_INET:
336 #ifdef LWS_USE_IPV6
337                         if (LWS_IPV6_ENABLED(context)) {
338                                 /* map IPv4 to IPv6 */
339                                 bzero((char *)&addr6->sin6_addr,
340                                                 sizeof(struct in6_addr));
341                                 addr6->sin6_addr.s6_addr[10] = 0xff;
342                                 addr6->sin6_addr.s6_addr[11] = 0xff;
343                                 memcpy(&addr6->sin6_addr.s6_addr[12],
344                                         &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
345                                                         sizeof(struct in_addr));
346                         } else
347 #endif
348                                 memcpy(addr,
349                                         (struct sockaddr_in *)ifc->ifa_addr,
350                                                     sizeof(struct sockaddr_in));
351                         break;
352 #ifdef LWS_USE_IPV6
353                 case AF_INET6:
354                         memcpy(&addr6->sin6_addr,
355                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
356                                                        sizeof(struct in6_addr));
357                         break;
358 #endif
359                 default:
360                         continue;
361                 }
362                 rc = 0;
363         }
364
365         freeifaddrs(ifr);
366
367         if (rc == -1) {
368                 /* check if bind to IP adddress */
369 #ifdef LWS_USE_IPV6
370                 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
371                         rc = 0;
372                 else
373 #endif
374                 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
375                         rc = 0;
376         }
377
378         return rc;
379 }
380
381 LWS_VISIBLE void
382 lws_plat_insert_socket_into_fds(struct lws_context *context,
383                                                        struct lws *wsi)
384 {
385         lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ);
386         context->fds[context->fds_count++].revents = 0;
387 }
388
389 LWS_VISIBLE void
390 lws_plat_delete_socket_from_fds(struct lws_context *context,
391                                                 struct lws *wsi, int m)
392 {
393 }
394
395 LWS_VISIBLE void
396 lws_plat_service_periodic(struct lws_context *context)
397 {
398         /* if our parent went down, don't linger around */
399         if (context->started_with_parent &&
400             kill(context->started_with_parent, 0) < 0)
401                 kill(getpid(), SIGTERM);
402 }
403
404 LWS_VISIBLE int
405 lws_plat_change_pollfd(struct lws_context *context,
406                       struct lws *wsi, struct lws_pollfd *pfd)
407 {
408         return 0;
409 }
410
411 LWS_VISIBLE const char *
412 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
413 {
414         return inet_ntop(af, src, dst, cnt);
415 }
416
417 static lws_filefd_type
418 _lws_plat_file_open(struct lws *wsi, const char *filename,
419                     unsigned long *filelen, int flags)
420 {
421         struct stat stat_buf;
422         int ret = open(filename, flags, 0664);
423
424         if (ret < 0)
425                 return LWS_INVALID_FILE;
426
427         if (fstat(ret, &stat_buf) < 0) {
428                 close(ret);
429                 return LWS_INVALID_FILE;
430         }
431         *filelen = stat_buf.st_size;
432         return ret;
433 }
434
435 static int
436 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
437 {
438         return close(fd);
439 }
440
441 unsigned long
442 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
443 {
444         return lseek(fd, offset, SEEK_CUR);
445 }
446
447 static int
448 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
449                     unsigned char *buf, unsigned long len)
450 {
451         long n;
452
453         n = read((int)fd, buf, len);
454         if (n == -1) {
455                 *amount = 0;
456                 return -1;
457         }
458
459         *amount = n;
460
461         return 0;
462 }
463
464 static int
465 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
466                      unsigned char *buf, unsigned long len)
467 {
468         long n;
469
470         n = write((int)fd, buf, len);
471         if (n == -1) {
472                 *amount = 0;
473                 return -1;
474         }
475
476         *amount = n;
477
478         return 0;
479 }
480
481 LWS_VISIBLE int
482 lws_plat_init(struct lws_context *context,
483               struct lws_context_creation_info *info)
484 {
485         context->lws_lookup = lws_zalloc(sizeof(struct lws *) * context->max_fds);
486         if (context->lws_lookup == NULL) {
487                 lwsl_err(
488                   "Unable to allocate lws_lookup array for %d connections\n",
489                                                               context->max_fds);
490                 return 1;
491         }
492
493         context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
494         if (context->fd_random < 0) {
495                 lwsl_err("Unable to open random device %s %d\n",
496                                     SYSTEM_RANDOM_FILEPATH, context->fd_random);
497                 return 1;
498         }
499
500         if (!lws_libev_init_fd_table(context)) {
501                 /* otherwise libev handled it instead */
502
503                 if (pipe(context->dummy_pipe_fds)) {
504                         lwsl_err("Unable to create pipe\n");
505                         return 1;
506                 }
507         }
508
509         /* use the read end of pipe as first item */
510         context->fds[0].fd = context->dummy_pipe_fds[0];
511         context->fds[0].events = LWS_POLLIN;
512         context->fds[0].revents = 0;
513         context->fds_count = 1;
514
515         context->fops.open      = _lws_plat_file_open;
516         context->fops.close     = _lws_plat_file_close;
517         context->fops.seek_cur  = _lws_plat_file_seek_cur;
518         context->fops.read      = _lws_plat_file_read;
519         context->fops.write     = _lws_plat_file_write;
520
521         return 0;
522 }