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