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