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