detect service tid once and use wsi with valid context to do it
[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__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
205     defined(__OpenBSD__)
206         struct protoent *tcp_proto;
207 #endif
208
209         if (context->ka_time) {
210                 /* enable keepalive on this socket */
211                 optval = 1;
212                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
213                                (const void *)&optval, optlen) < 0)
214                         return 1;
215
216 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
217         defined(__CYGWIN__) || defined(__OpenBSD__)
218
219                 /*
220                  * didn't find a way to set these per-socket, need to
221                  * tune kernel systemwide values
222                  */
223 #else
224                 /* set the keepalive conditions we want on it too */
225                 optval = context->ka_time;
226                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE,
227                                (const void *)&optval, optlen) < 0)
228                         return 1;
229
230                 optval = context->ka_interval;
231                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,
232                                (const void *)&optval, optlen) < 0)
233                         return 1;
234
235                 optval = context->ka_probes;
236                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT,
237                                (const void *)&optval, optlen) < 0)
238                         return 1;
239 #endif
240         }
241
242         /* Disable Nagle */
243         optval = 1;
244 #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && \
245     !defined(__OpenBSD__)
246         if (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)
247                 return 1;
248 #else
249         tcp_proto = getprotobyname("TCP");
250         if (setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen) < 0)
251                 return 1;
252 #endif
253
254         /* We are nonblocking... */
255         if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
256                 return 1;
257
258         return 0;
259 }
260
261 LWS_VISIBLE void
262 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
263 {
264         if (info->uid != -1) {
265                 struct passwd *p = getpwuid(info->uid);
266
267                 if (p) {
268                         initgroups(p->pw_name, info->gid);
269                         if (setuid(info->uid))
270                                 lwsl_warn("setuid: %s\n", strerror(LWS_ERRNO));
271                         else
272                                 lwsl_notice(" Set privs to user '%s'\n", p->pw_name);
273                 } else
274                         lwsl_warn("getpwuid: unable to find uid %d", info->uid);
275         }
276         if (info->gid != -1)
277                 if (setgid(info->gid))
278                         lwsl_warn("setgid: %s\n", strerror(LWS_ERRNO));
279
280 }
281
282 static void sigpipe_handler(int x)
283 {
284 }
285
286 LWS_VISIBLE int
287 lws_plat_context_early_init(void)
288 {
289         sigset_t mask;
290
291         signal(SIGUSR2, lws_sigusr2);
292         sigemptyset(&mask);
293         sigaddset(&mask, SIGUSR2);
294
295         sigprocmask(SIG_BLOCK, &mask, NULL);
296
297         signal(SIGPIPE, sigpipe_handler);
298
299         return 0;
300 }
301
302 LWS_VISIBLE void
303 lws_plat_context_early_destroy(struct lws_context *context)
304 {
305 }
306
307 LWS_VISIBLE void
308 lws_plat_context_late_destroy(struct lws_context *context)
309 {
310         if (context->lws_lookup)
311                 lws_free(context->lws_lookup);
312
313         close(context->dummy_pipe_fds[0]);
314         close(context->dummy_pipe_fds[1]);
315         close(context->fd_random);
316 }
317
318 /* cast a struct sockaddr_in6 * into addr for ipv6 */
319
320 LWS_VISIBLE int
321 interface_to_sa(struct lws_context *context,
322                 const char *ifname, struct sockaddr_in *addr, size_t addrlen)
323 {
324         int rc = -1;
325
326         struct ifaddrs *ifr;
327         struct ifaddrs *ifc;
328 #ifdef LWS_USE_IPV6
329         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
330 #endif
331
332         getifaddrs(&ifr);
333         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
334                 if (!ifc->ifa_addr)
335                         continue;
336
337                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
338
339                 if (strcmp(ifc->ifa_name, ifname))
340                         continue;
341
342                 switch (ifc->ifa_addr->sa_family) {
343                 case AF_INET:
344 #ifdef LWS_USE_IPV6
345                         if (LWS_IPV6_ENABLED(context)) {
346                                 /* map IPv4 to IPv6 */
347                                 bzero((char *)&addr6->sin6_addr,
348                                                 sizeof(struct in6_addr));
349                                 addr6->sin6_addr.s6_addr[10] = 0xff;
350                                 addr6->sin6_addr.s6_addr[11] = 0xff;
351                                 memcpy(&addr6->sin6_addr.s6_addr[12],
352                                         &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
353                                                         sizeof(struct in_addr));
354                         } else
355 #endif
356                                 memcpy(addr,
357                                         (struct sockaddr_in *)ifc->ifa_addr,
358                                                     sizeof(struct sockaddr_in));
359                         break;
360 #ifdef LWS_USE_IPV6
361                 case AF_INET6:
362                         memcpy(&addr6->sin6_addr,
363                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
364                                                        sizeof(struct in6_addr));
365                         break;
366 #endif
367                 default:
368                         continue;
369                 }
370                 rc = 0;
371         }
372
373         freeifaddrs(ifr);
374
375         if (rc == -1) {
376                 /* check if bind to IP adddress */
377 #ifdef LWS_USE_IPV6
378                 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
379                         rc = 0;
380                 else
381 #endif
382                 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
383                         rc = 0;
384         }
385
386         return rc;
387 }
388
389 LWS_VISIBLE void
390 lws_plat_insert_socket_into_fds(struct lws_context *context,
391                                                        struct lws *wsi)
392 {
393         lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ);
394         context->fds[context->fds_count++].revents = 0;
395 }
396
397 LWS_VISIBLE void
398 lws_plat_delete_socket_from_fds(struct lws_context *context,
399                                                 struct lws *wsi, int m)
400 {
401 }
402
403 LWS_VISIBLE void
404 lws_plat_service_periodic(struct lws_context *context)
405 {
406         /* if our parent went down, don't linger around */
407         if (context->started_with_parent &&
408             kill(context->started_with_parent, 0) < 0)
409                 kill(getpid(), SIGTERM);
410 }
411
412 LWS_VISIBLE int
413 lws_plat_change_pollfd(struct lws_context *context,
414                       struct lws *wsi, struct lws_pollfd *pfd)
415 {
416         return 0;
417 }
418
419 LWS_VISIBLE const char *
420 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
421 {
422         return inet_ntop(af, src, dst, cnt);
423 }
424
425 static lws_filefd_type
426 _lws_plat_file_open(struct lws *wsi, const char *filename,
427                     unsigned long *filelen, int flags)
428 {
429         struct stat stat_buf;
430         int ret = open(filename, flags, 0664);
431
432         if (ret < 0)
433                 return LWS_INVALID_FILE;
434
435         if (fstat(ret, &stat_buf) < 0) {
436                 close(ret);
437                 return LWS_INVALID_FILE;
438         }
439         *filelen = stat_buf.st_size;
440         return ret;
441 }
442
443 static int
444 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
445 {
446         return close(fd);
447 }
448
449 unsigned long
450 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
451 {
452         return lseek(fd, offset, SEEK_CUR);
453 }
454
455 static int
456 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
457                     unsigned char *buf, unsigned long len)
458 {
459         long n;
460
461         n = read((int)fd, buf, len);
462         if (n == -1) {
463                 *amount = 0;
464                 return -1;
465         }
466
467         *amount = n;
468
469         return 0;
470 }
471
472 static int
473 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
474                      unsigned char *buf, unsigned long len)
475 {
476         long n;
477
478         n = write((int)fd, buf, len);
479         if (n == -1) {
480                 *amount = 0;
481                 return -1;
482         }
483
484         *amount = n;
485
486         return 0;
487 }
488
489 LWS_VISIBLE int
490 lws_plat_init(struct lws_context *context,
491               struct lws_context_creation_info *info)
492 {
493         context->lws_lookup = lws_zalloc(sizeof(struct lws *) * context->max_fds);
494         if (context->lws_lookup == NULL) {
495                 lwsl_err(
496                   "Unable to allocate lws_lookup array for %d connections\n",
497                                                               context->max_fds);
498                 return 1;
499         }
500
501         context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
502         if (context->fd_random < 0) {
503                 lwsl_err("Unable to open random device %s %d\n",
504                                     SYSTEM_RANDOM_FILEPATH, context->fd_random);
505                 return 1;
506         }
507
508         if (!lws_libev_init_fd_table(context)) {
509                 /* otherwise libev handled it instead */
510
511                 if (pipe(context->dummy_pipe_fds)) {
512                         lwsl_err("Unable to create pipe\n");
513                         return 1;
514                 }
515         }
516
517         /* use the read end of pipe as first item */
518         context->fds[0].fd = context->dummy_pipe_fds[0];
519         context->fds[0].events = LWS_POLLIN;
520         context->fds[0].revents = 0;
521         context->fds_count = 1;
522
523         context->fops.open      = _lws_plat_file_open;
524         context->fops.close     = _lws_plat_file_close;
525         context->fops.seek_cur  = _lws_plat_file_seek_cur;
526         context->fops.read      = _lws_plat_file_read;
527         context->fops.write     = _lws_plat_file_write;
528
529         return 0;
530 }