windows detect client connection error
[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 #ifdef LWS_WITH_PLUGINS
7 #include <dlfcn.h>
8 #endif
9 #include <dirent.h>
10
11
12 /*
13  * included from libwebsockets.c for unix builds
14  */
15
16 unsigned long long time_in_microseconds(void)
17 {
18         struct timeval tv;
19         gettimeofday(&tv, NULL);
20         return ((unsigned long long)tv.tv_sec * 1000000LL) + tv.tv_usec;
21 }
22
23 LWS_VISIBLE int
24 lws_get_random(struct lws_context *context, void *buf, int len)
25 {
26         return read(context->fd_random, (char *)buf, len);
27 }
28
29 LWS_VISIBLE int
30 lws_send_pipe_choked(struct lws *wsi)
31 {
32         struct lws_pollfd fds;
33
34         /* treat the fact we got a truncated send pending as if we're choked */
35         if (wsi->trunc_len)
36                 return 1;
37
38         fds.fd = wsi->sock;
39         fds.events = POLLOUT;
40         fds.revents = 0;
41
42         if (poll(&fds, 1, 0) != 1)
43                 return 1;
44
45         if ((fds.revents & POLLOUT) == 0)
46                 return 1;
47
48         /* okay to send another packet without blocking */
49
50         return 0;
51 }
52
53 LWS_VISIBLE int
54 lws_poll_listen_fd(struct lws_pollfd *fd)
55 {
56         return poll(fd, 1, 0);
57 }
58
59 LWS_VISIBLE void
60 lws_cancel_service_pt(struct lws *wsi)
61 {
62         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
63         char buf = 0;
64
65         if (write(pt->dummy_pipe_fds[1], &buf, sizeof(buf)) != 1)
66                 lwsl_err("Cannot write to dummy pipe");
67 }
68
69 LWS_VISIBLE void
70 lws_cancel_service(struct lws_context *context)
71 {
72         struct lws_context_per_thread *pt = &context->pt[0];
73         char buf = 0, m = context->count_threads;
74
75         while (m--) {
76                 if (write(pt->dummy_pipe_fds[1], &buf, sizeof(buf)) != 1)
77                         lwsl_err("Cannot write to dummy pipe");
78                 pt++;
79         }
80 }
81
82 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
83 {
84         int syslog_level = LOG_DEBUG;
85
86         switch (level) {
87         case LLL_ERR:
88                 syslog_level = LOG_ERR;
89                 break;
90         case LLL_WARN:
91                 syslog_level = LOG_WARNING;
92                 break;
93         case LLL_NOTICE:
94                 syslog_level = LOG_NOTICE;
95                 break;
96         case LLL_INFO:
97                 syslog_level = LOG_INFO;
98                 break;
99         }
100         syslog(syslog_level, "%s", line);
101 }
102
103 LWS_VISIBLE int
104 lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi)
105 {
106         struct lws_context_per_thread *pt = &context->pt[tsi];
107         int n = -1, m, c;
108         char buf;
109
110         /* stay dead once we are dead */
111
112         if (!context || !context->vhost_list)
113                 return 1;
114
115         if (timeout_ms < 0)
116                 goto faked_service;
117
118         lws_libev_run(context, tsi);
119         lws_libuv_run(context, tsi);
120
121         if (!context->service_tid_detected) {
122                 struct lws _lws;
123
124                 memset(&_lws, 0, sizeof(_lws));
125                 _lws.context = context;
126
127                 context->service_tid_detected =
128                         context->vhost_list->protocols[0].callback(
129                         &_lws, LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
130         }
131         context->service_tid = context->service_tid_detected;
132
133         timeout_ms = lws_service_adjust_timeout(context, timeout_ms, tsi);
134
135         n = poll(pt->fds, pt->fds_count, timeout_ms);
136
137 #ifdef LWS_OPENSSL_SUPPORT
138         if (!pt->rx_draining_ext_list &&
139             !lws_ssl_anybody_has_buffered_read_tsi(context, tsi) && !n) {
140 #else
141         if (!pt->rx_draining_ext_list && !n) /* poll timeout */ {
142 #endif
143                 lws_service_fd_tsi(context, NULL, tsi);
144                 return 0;
145         }
146
147 faked_service:
148         m = lws_service_flag_pending(context, tsi);
149         if (m)
150                 c = -1; /* unknown limit */
151         else
152                 if (n < 0) {
153                         if (LWS_ERRNO != LWS_EINTR)
154                                 return -1;
155                         return 0;
156                 } else
157                         c = n;
158
159         /* any socket with events to service? */
160         for (n = 0; n < pt->fds_count && c; n++) {
161                 if (!pt->fds[n].revents)
162                         continue;
163
164                 c--;
165
166                 if (pt->fds[n].fd == pt->dummy_pipe_fds[0]) {
167                         if (read(pt->fds[n].fd, &buf, 1) != 1)
168                                 lwsl_err("Cannot read from dummy pipe.");
169                         continue;
170                 }
171
172                 m = lws_service_fd_tsi(context, &pt->fds[n], tsi);
173                 if (m < 0)
174                         return -1;
175                 /* if something closed, retry this slot */
176                 if (m)
177                         n--;
178         }
179
180         return 0;
181 }
182
183 LWS_VISIBLE int
184 lws_plat_check_connection_error(struct lws *wsi)
185 {
186         return 0;
187 }
188
189 LWS_VISIBLE int
190 lws_plat_service(struct lws_context *context, int timeout_ms)
191 {
192         return lws_plat_service_tsi(context, timeout_ms, 0);
193 }
194
195 LWS_VISIBLE int
196 lws_plat_set_socket_options(struct lws_vhost *vhost, int fd)
197 {
198         int optval = 1;
199         socklen_t optlen = sizeof(optval);
200
201 #if defined(__APPLE__) || \
202     defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
203     defined(__NetBSD__) || \
204     defined(__OpenBSD__)
205         struct protoent *tcp_proto;
206 #endif
207
208         if (vhost->ka_time) {
209                 /* enable keepalive on this socket */
210                 optval = 1;
211                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
212                                (const void *)&optval, optlen) < 0)
213                         return 1;
214
215 #if defined(__APPLE__) || \
216     defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
217     defined(__NetBSD__) || \
218         defined(__CYGWIN__) || defined(__OpenBSD__)
219
220                 /*
221                  * didn't find a way to set these per-socket, need to
222                  * tune kernel systemwide values
223                  */
224 #else
225                 /* set the keepalive conditions we want on it too */
226                 optval = vhost->ka_time;
227                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE,
228                                (const void *)&optval, optlen) < 0)
229                         return 1;
230
231                 optval = vhost->ka_interval;
232                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,
233                                (const void *)&optval, optlen) < 0)
234                         return 1;
235
236                 optval = vhost->ka_probes;
237                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT,
238                                (const void *)&optval, optlen) < 0)
239                         return 1;
240 #endif
241         }
242
243         /* Disable Nagle */
244         optval = 1;
245 #if !defined(__APPLE__) && \
246     !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__) && \
247     !defined(__NetBSD__) && \
248     !defined(__OpenBSD__)
249         if (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)
250                 return 1;
251 #else
252         tcp_proto = getprotobyname("TCP");
253         if (setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen) < 0)
254                 return 1;
255 #endif
256
257         /* We are nonblocking... */
258         if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
259                 return 1;
260
261         return 0;
262 }
263
264 LWS_VISIBLE void
265 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
266 {
267         if (info->gid != -1)
268                 if (setgid(info->gid))
269                         lwsl_warn("setgid: %s\n", strerror(LWS_ERRNO));
270
271         if (info->uid != -1) {
272                 struct passwd *p = getpwuid(info->uid);
273
274                 if (p) {
275                         initgroups(p->pw_name, info->gid);
276                         if (setuid(info->uid))
277                                 lwsl_warn("setuid: %s\n", strerror(LWS_ERRNO));
278                         else
279                                 lwsl_notice("Set privs to user '%s'\n", p->pw_name);
280                 } else
281                         lwsl_warn("getpwuid: unable to find uid %d", info->uid);
282         }
283 }
284
285 #ifdef LWS_WITH_PLUGINS
286
287 #if defined(LWS_USE_LIBUV) && UV_VERSION_MAJOR > 0
288
289 /* libuv.c implements these in a cross-platform way */
290
291 #else
292
293 static int filter(const struct dirent *ent)
294 {
295         if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
296                 return 0;
297
298         return 1;
299 }
300
301 LWS_VISIBLE int
302 lws_plat_plugins_init(struct lws_context * context, const char * const *d)
303 {
304         struct lws_plugin_capability lcaps;
305         struct lws_plugin *plugin;
306         lws_plugin_init_func initfunc;
307         struct dirent **namelist;
308         int n, i, m, ret = 0;
309         char path[256];
310         void *l;
311
312         lwsl_notice("  Plugins:\n");
313
314         while (d && *d) {
315                 n = scandir(*d, &namelist, filter, alphasort);
316                 if (n < 0) {
317                         lwsl_err("Scandir on %s failed\n", *d);
318                         return 1;
319                 }
320
321                 for (i = 0; i < n; i++) {
322                         if (strlen(namelist[i]->d_name) < 7)
323                                 goto inval;
324
325                         lwsl_notice("   %s\n", namelist[i]->d_name);
326
327                         snprintf(path, sizeof(path) - 1, "%s/%s", *d,
328                                  namelist[i]->d_name);
329                         l = dlopen(path, RTLD_NOW);
330                         if (!l) {
331                                 lwsl_err("Error loading DSO: %s\n", dlerror());
332                                 while (i++ < n)
333                                         free(namelist[i]);
334                                 goto bail;
335                         }
336                         /* we could open it, can we get his init function? */
337                         m = snprintf(path, sizeof(path) - 1, "init_%s",
338                                      namelist[i]->d_name + 3 /* snip lib... */);
339                         path[m - 3] = '\0'; /* snip the .so */
340                         initfunc = dlsym(l, path);
341                         if (!initfunc) {
342                                 lwsl_err("Failed to get init on %s: %s",
343                                                 namelist[i]->d_name, dlerror());
344                                 dlclose(l);
345                         }
346                         lcaps.api_magic = LWS_PLUGIN_API_MAGIC;
347                         m = initfunc(context, &lcaps);
348                         if (m) {
349                                 lwsl_err("Initializing %s failed %d\n",
350                                         namelist[i]->d_name, m);
351                                 dlclose(l);
352                                 goto skip;
353                         }
354
355                         plugin = lws_malloc(sizeof(*plugin));
356                         if (!plugin) {
357                                 lwsl_err("OOM\n");
358                                 goto bail;
359                         }
360                         plugin->list = context->plugin_list;
361                         context->plugin_list = plugin;
362                         strncpy(plugin->name, namelist[i]->d_name, sizeof(plugin->name) - 1);
363                         plugin->name[sizeof(plugin->name) - 1] = '\0';
364                         plugin->l = l;
365                         plugin->caps = lcaps;
366                         context->plugin_protocol_count += lcaps.count_protocols;
367                         context->plugin_extension_count += lcaps.count_extensions;
368
369                         free(namelist[i]);
370                         continue;
371
372         skip:
373                         dlclose(l);
374         inval:
375                         free(namelist[i]);
376                 }
377                 free(namelist);
378                 d++;
379         }
380
381 bail:
382         free(namelist);
383
384         return ret;
385 }
386
387 LWS_VISIBLE int
388 lws_plat_plugins_destroy(struct lws_context * context)
389 {
390         struct lws_plugin *plugin = context->plugin_list, *p;
391         lws_plugin_destroy_func func;
392         char path[256];
393         int m;
394
395         if (!plugin)
396                 return 0;
397
398         lwsl_notice("%s\n", __func__);
399
400         while (plugin) {
401                 p = plugin;
402                 m = snprintf(path, sizeof(path) - 1, "destroy_%s", plugin->name + 3);
403                 path[m - 3] = '\0';
404                 func = dlsym(plugin->l, path);
405                 if (!func) {
406                         lwsl_err("Failed to get destroy on %s: %s",
407                                         plugin->name, dlerror());
408                         goto next;
409                 }
410                 m = func(context);
411                 if (m)
412                         lwsl_err("Initializing %s failed %d\n",
413                                 plugin->name, m);
414 next:
415                 dlclose(p->l);
416                 plugin = p->list;
417                 p->list = NULL;
418                 free(p);
419         }
420
421         context->plugin_list = NULL;
422
423         return 0;
424 }
425
426 #endif
427 #endif
428
429
430 #if 0
431 static void
432 sigabrt_handler(int x)
433 {
434         printf("%s\n", __func__);
435         //*(char *)0 = 0;
436 }
437 #endif
438
439 LWS_VISIBLE int
440 lws_plat_context_early_init(void)
441 {
442         signal(SIGPIPE, SIG_IGN);
443
444 //      signal(SIGABRT, sigabrt_handler);
445
446         return 0;
447 }
448
449 LWS_VISIBLE void
450 lws_plat_context_early_destroy(struct lws_context *context)
451 {
452 }
453
454 LWS_VISIBLE void
455 lws_plat_context_late_destroy(struct lws_context *context)
456 {
457         struct lws_context_per_thread *pt = &context->pt[0];
458         int m = context->count_threads;
459
460 #ifdef LWS_WITH_PLUGINS
461         if (context->plugin_list)
462                 lws_plat_plugins_destroy(context);
463 #endif
464
465         if (context->lws_lookup)
466                 lws_free(context->lws_lookup);
467
468         while (m--) {
469                 close(pt->dummy_pipe_fds[0]);
470                 close(pt->dummy_pipe_fds[1]);
471                 pt++;
472         }
473         close(context->fd_random);
474 }
475
476 /* cast a struct sockaddr_in6 * into addr for ipv6 */
477
478 LWS_VISIBLE int
479 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
480                     size_t addrlen)
481 {
482         int rc = -1;
483
484         struct ifaddrs *ifr;
485         struct ifaddrs *ifc;
486 #ifdef LWS_USE_IPV6
487         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
488 #endif
489
490         getifaddrs(&ifr);
491         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
492                 if (!ifc->ifa_addr)
493                         continue;
494
495                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
496
497                 if (strcmp(ifc->ifa_name, ifname))
498                         continue;
499
500                 switch (ifc->ifa_addr->sa_family) {
501                 case AF_INET:
502 #ifdef LWS_USE_IPV6
503                         if (ipv6) {
504                                 /* map IPv4 to IPv6 */
505                                 bzero((char *)&addr6->sin6_addr,
506                                                 sizeof(struct in6_addr));
507                                 addr6->sin6_addr.s6_addr[10] = 0xff;
508                                 addr6->sin6_addr.s6_addr[11] = 0xff;
509                                 memcpy(&addr6->sin6_addr.s6_addr[12],
510                                         &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
511                                                         sizeof(struct in_addr));
512                         } else
513 #endif
514                                 memcpy(addr,
515                                         (struct sockaddr_in *)ifc->ifa_addr,
516                                                     sizeof(struct sockaddr_in));
517                         break;
518 #ifdef LWS_USE_IPV6
519                 case AF_INET6:
520                         memcpy(&addr6->sin6_addr,
521                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
522                                                        sizeof(struct in6_addr));
523                         break;
524 #endif
525                 default:
526                         continue;
527                 }
528                 rc = 0;
529         }
530
531         freeifaddrs(ifr);
532
533         if (rc == -1) {
534                 /* check if bind to IP adddress */
535 #ifdef LWS_USE_IPV6
536                 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
537                         rc = 0;
538                 else
539 #endif
540                 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
541                         rc = 0;
542         }
543
544         return rc;
545 }
546
547 LWS_VISIBLE void
548 lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)
549 {
550         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
551
552         lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ);
553         lws_libuv_io(wsi, LWS_EV_START | LWS_EV_READ);
554
555         pt->fds[pt->fds_count++].revents = 0;
556 }
557
558 LWS_VISIBLE void
559 lws_plat_delete_socket_from_fds(struct lws_context *context,
560                                                 struct lws *wsi, int m)
561 {
562         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
563
564         lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE);
565         lws_libuv_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE);
566
567         pt->fds_count--;
568 }
569
570 LWS_VISIBLE void
571 lws_plat_service_periodic(struct lws_context *context)
572 {
573         /* if our parent went down, don't linger around */
574         if (context->started_with_parent &&
575             kill(context->started_with_parent, 0) < 0)
576                 kill(getpid(), SIGTERM);
577 }
578
579 LWS_VISIBLE int
580 lws_plat_change_pollfd(struct lws_context *context,
581                       struct lws *wsi, struct lws_pollfd *pfd)
582 {
583         return 0;
584 }
585
586 LWS_VISIBLE const char *
587 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
588 {
589         return inet_ntop(af, src, dst, cnt);
590 }
591
592 static lws_filefd_type
593 _lws_plat_file_open(struct lws *wsi, const char *filename,
594                     unsigned long *filelen, int flags)
595 {
596         struct stat stat_buf;
597         int ret = open(filename, flags, 0664);
598
599         if (ret < 0)
600                 return LWS_INVALID_FILE;
601
602         if (fstat(ret, &stat_buf) < 0) {
603                 close(ret);
604                 return LWS_INVALID_FILE;
605         }
606         *filelen = stat_buf.st_size;
607         return ret;
608 }
609
610 static int
611 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
612 {
613         return close(fd);
614 }
615
616 unsigned long
617 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
618 {
619         return lseek(fd, offset, SEEK_CUR);
620 }
621
622 static int
623 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
624                     unsigned char *buf, unsigned long len)
625 {
626         long n;
627
628         n = read((int)fd, buf, len);
629         if (n == -1) {
630                 *amount = 0;
631                 return -1;
632         }
633
634         *amount = n;
635
636         return 0;
637 }
638
639 static int
640 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
641                      unsigned char *buf, unsigned long len)
642 {
643         long n;
644
645         n = write((int)fd, buf, len);
646         if (n == -1) {
647                 *amount = 0;
648                 return -1;
649         }
650
651         *amount = n;
652
653         return 0;
654 }
655
656
657 LWS_VISIBLE int
658 lws_plat_init(struct lws_context *context,
659               struct lws_context_creation_info *info)
660 {
661         struct lws_context_per_thread *pt = &context->pt[0];
662         int n = context->count_threads, fd;
663
664         /* master context has the global fd lookup array */
665         context->lws_lookup = lws_zalloc(sizeof(struct lws *) *
666                                          context->max_fds);
667         if (context->lws_lookup == NULL) {
668                 lwsl_err("OOM on lws_lookup array for %d connections\n",
669                          context->max_fds);
670                 return 1;
671         }
672
673         lwsl_notice(" mem: platform fd map: %5u bytes\n",
674                     sizeof(struct lws *) * context->max_fds);
675         fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
676
677         context->fd_random = fd;
678         if (context->fd_random < 0) {
679                 lwsl_err("Unable to open random device %s %d\n",
680                          SYSTEM_RANDOM_FILEPATH, context->fd_random);
681                 return 1;
682         }
683
684         if (!lws_libev_init_fd_table(context) &&
685             !lws_libuv_init_fd_table(context)) {
686                 /* otherwise libev handled it instead */
687
688                 while (n--) {
689                         if (pipe(pt->dummy_pipe_fds)) {
690                                 lwsl_err("Unable to create pipe\n");
691                                 return 1;
692                         }
693
694                         /* use the read end of pipe as first item */
695                         pt->fds[0].fd = pt->dummy_pipe_fds[0];
696                         pt->fds[0].events = LWS_POLLIN;
697                         pt->fds[0].revents = 0;
698                         pt->fds_count = 1;
699                         pt++;
700                 }
701         }
702
703         context->fops.open      = _lws_plat_file_open;
704         context->fops.close     = _lws_plat_file_close;
705         context->fops.seek_cur  = _lws_plat_file_seek_cur;
706         context->fops.read      = _lws_plat_file_read;
707         context->fops.write     = _lws_plat_file_write;
708
709 #ifdef LWS_WITH_PLUGINS
710         if (info->plugin_dirs)
711                 lws_plat_plugins_init(context, info->plugin_dirs);
712 #endif
713
714         return 0;
715 }