refactor out WIN32 tests from code
[platform/upstream/libwebsockets.git] / lib / lws-plat-unix.c
1 /*
2  * included from libwebsockets.c for unix builds
3  */
4
5 static unsigned long long time_in_microseconds(void)
6 {
7         struct timeval tv;
8         gettimeofday(&tv, NULL);
9         return (tv.tv_sec * 1000000) + tv.tv_usec;
10 }
11
12 LWS_VISIBLE int libwebsockets_get_random(struct libwebsocket_context *context,
13                                                              void *buf, int len)
14 {
15         return read(context->fd_random, (char *)buf, len);
16 }
17
18 LWS_VISIBLE int lws_send_pipe_choked(struct libwebsocket *wsi)
19 {
20         struct libwebsocket_pollfd fds;
21
22         /* treat the fact we got a truncated send pending as if we're choked */
23         if (wsi->truncated_send_len)
24                 return 1;
25
26         fds.fd = wsi->sock;
27         fds.events = POLLOUT;
28         fds.revents = 0;
29
30         if (poll(&fds, 1, 0) != 1)
31                 return 1;
32
33         if ((fds.revents & POLLOUT) == 0)
34                 return 1;
35
36         /* okay to send another packet without blocking */
37
38         return 0;
39 }
40
41 static int lws_poll_listen_fd(struct libwebsocket_pollfd *fd)
42 {
43         return poll(fd, 1, 0);
44 }
45
46
47 #ifdef LWS_USE_LIBEV
48 LWS_VISIBLE void 
49 libwebsocket_accept_cb(struct ev_loop *loop, struct ev_io *watcher, int revents)
50 {
51         struct libwebsocket_pollfd eventfd;
52         struct lws_io_watcher *lws_io = (struct lws_io_watcher*)watcher;
53         struct libwebsocket_context *context = lws_io->context;
54
55         if (revents & EV_ERROR)
56                 return;
57
58         eventfd.fd = watcher->fd;
59         eventfd.revents = EV_NONE;
60         if (revents & EV_READ)
61                 eventfd.revents |= LWS_POLLIN;
62
63         if (revents & EV_WRITE)
64                 eventfd.revents |= LWS_POLLOUT;
65
66         libwebsocket_service_fd(context,&eventfd);
67 }
68
69 LWS_VISIBLE void
70 libwebsocket_sigint_cb(
71     struct ev_loop *loop, struct ev_signal* watcher, int revents)
72 {
73     ev_break(loop, EVBREAK_ALL);
74 }
75
76 LWS_VISIBLE int
77 libwebsocket_initloop(
78         struct libwebsocket_context *context,
79         struct ev_loop *loop)
80 {
81         int status = 0;
82         int backend;
83         const char * backend_name;
84         struct ev_io *w_accept = (ev_io *)&context->w_accept;
85         struct ev_signal *w_sigint = (ev_signal *)&context->w_sigint;
86
87         if (!loop)
88                 loop = ev_default_loop(0);
89
90         context->io_loop = loop;
91    
92         /*
93          * Initialize the accept w_accept with the listening socket
94          * and register a callback for read operations:
95          */
96         ev_io_init(w_accept, libwebsocket_accept_cb,
97                                         context->listen_service_fd, EV_READ);
98         ev_io_start(context->io_loop,w_accept);
99         ev_signal_init(w_sigint, libwebsocket_sigint_cb, SIGINT);
100         ev_signal_start(context->io_loop,w_sigint);
101         backend = ev_backend(loop);
102
103         switch (backend) {
104         case EVBACKEND_SELECT:
105                 backend_name = "select";
106                 break;
107         case EVBACKEND_POLL:
108                 backend_name = "poll";
109                 break;
110         case EVBACKEND_EPOLL:
111                 backend_name = "epoll";
112                 break;
113         case EVBACKEND_KQUEUE:
114                 backend_name = "kqueue";
115                 break;
116         case EVBACKEND_DEVPOLL:
117                 backend_name = "/dev/poll";
118                 break;
119         case EVBACKEND_PORT:
120                 backend_name = "Solaris 10 \"port\"";
121                 break;
122         default:
123                 backend_name = "Unknown libev backend";
124                 break;
125         };
126
127         lwsl_notice(" libev backend: %s\n", backend_name);
128
129         return status;
130 }
131
132 #endif /* LWS_USE_LIBEV */
133
134 /**
135  * libwebsocket_cancel_service() - Cancel servicing of pending websocket activity
136  * @context:    Websocket context
137  *
138  *      This function let a call to libwebsocket_service() waiting for a timeout
139  *      immediately return.
140  */
141 LWS_VISIBLE void
142 libwebsocket_cancel_service(struct libwebsocket_context *context)
143 {
144         char buf = 0;
145
146         if (write(context->dummy_pipe_fds[1], &buf, sizeof(buf)) != 1)
147                 lwsl_err("Cannot write to dummy pipe");
148 }
149
150 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
151 {
152         int syslog_level = LOG_DEBUG;
153
154         switch (level) {
155         case LLL_ERR:
156                 syslog_level = LOG_ERR;
157                 break;
158         case LLL_WARN:
159                 syslog_level = LOG_WARNING;
160                 break;
161         case LLL_NOTICE:
162                 syslog_level = LOG_NOTICE;
163                 break;
164         case LLL_INFO:
165                 syslog_level = LOG_INFO;
166                 break;
167         }
168         syslog(syslog_level, "%s", line);
169 }
170
171 LWS_VISIBLE int
172 lws_plat_service(struct libwebsocket_context *context, int timeout_ms)
173 {
174         int n;
175         int m;
176         char buf;
177
178         /* stay dead once we are dead */
179
180         if (context == NULL)
181                 return 1;
182
183 #ifdef LWS_USE_LIBEV
184         if (context->io_loop && LWS_LIBEV_ENABLED(context))
185                 ev_run(context->io_loop, 0);
186 #endif /* LWS_USE_LIBEV */
187         context->service_tid = context->protocols[0].callback(context, NULL,
188                                      LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
189
190         n = poll(context->fds, context->fds_count, timeout_ms);
191         context->service_tid = 0;
192
193         if (n == 0) /* poll timeout */ {
194                 libwebsocket_service_fd(context, NULL);
195                 return 0;
196         }
197
198         if (n < 0) {
199                 if (LWS_ERRNO != LWS_EINTR)
200                         return -1;
201                 return 0;
202         }
203
204         /* any socket with events to service? */
205
206         for (n = 0; n < context->fds_count; n++) {
207                 if (!context->fds[n].revents)
208                         continue;
209
210                 if (context->fds[n].fd == context->dummy_pipe_fds[0]) {
211                         if (read(context->fds[n].fd, &buf, 1) != 1)
212                                 lwsl_err("Cannot read from dummy pipe.");
213                         continue;
214                 }
215
216                 m = libwebsocket_service_fd(context, &context->fds[n]);
217                 if (m < 0)
218                         return -1;
219                 /* if something closed, retry this slot */
220                 if (m)
221                         n--;
222         }
223
224         return 0;
225 }
226
227 int lws_plat_set_socket_options(struct libwebsocket_context *context, int fd)
228 {
229         int optval = 1;
230         socklen_t optlen = sizeof(optval);
231
232 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
233         struct protoent *tcp_proto;
234 #endif
235
236         if (context->ka_time) {
237                 /* enable keepalive on this socket */
238                 optval = 1;
239                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
240                                              (const void *)&optval, optlen) < 0)
241                         return 1;
242
243 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__CYGWIN__)
244
245                 /*
246                  * didn't find a way to set these per-socket, need to
247                  * tune kernel systemwide values
248                  */
249 #else
250                 /* set the keepalive conditions we want on it too */
251                 optval = context->ka_time;
252                 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPIDLE,
253                                              (const void *)&optval, optlen) < 0)
254                         return 1;
255
256                 optval = context->ka_interval;
257                 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPINTVL,
258                                              (const void *)&optval, optlen) < 0)
259                         return 1;
260
261                 optval = context->ka_probes;
262                 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPCNT,
263                                              (const void *)&optval, optlen) < 0)
264                         return 1;
265 #endif
266         }
267
268         /* Disable Nagle */
269         optval = 1;
270 #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
271         setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen);
272 #else
273         tcp_proto = getprotobyname("TCP");
274         setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen);
275 #endif
276
277         /* We are nonblocking... */
278         fcntl(fd, F_SETFL, O_NONBLOCK);
279
280         return 0;
281 }
282
283 static void lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
284 {
285         if (info->gid != -1)
286                 if (setgid(info->gid))
287                         lwsl_warn("setgid: %s\n", strerror(LWS_ERRNO));
288         if (info->uid != -1)
289                 if (setuid(info->uid))
290                         lwsl_warn("setuid: %s\n", strerror(LWS_ERRNO)); 
291 }
292
293 static int lws_plat_init_fd_tables(struct libwebsocket_context *context)
294 {
295 #ifdef LWS_USE_LIBEV
296         if (LWS_LIBEV_ENABLED(context)) {
297                 context->w_accept.context = context;
298                 context->w_sigint.context = context;
299                 return 0;
300         }
301 #endif
302         if (pipe(context->dummy_pipe_fds)) {
303                 lwsl_err("Unable to create pipe\n");
304                 return 1;
305         }
306
307         /* use the read end of pipe as first item */
308         context->fds[0].fd = context->dummy_pipe_fds[0];
309         context->fds[0].events = LWS_POLLIN;
310         context->fds[0].revents = 0;
311         context->fds_count = 1;
312         
313         context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
314         if (context->fd_random < 0) {
315                 lwsl_err("Unable to open random device %s %d\n",
316                                     SYSTEM_RANDOM_FILEPATH, context->fd_random);
317                 return 1;
318         }
319
320         return 0;
321 }
322
323 static void sigpipe_handler(int x)
324 {
325 }
326
327
328 static int lws_plat_context_early_init(void)
329 {
330         sigset_t mask;
331
332         signal(SIGUSR2, lws_sigusr2);
333         sigemptyset(&mask);
334         sigaddset(&mask, SIGUSR2);
335
336         sigprocmask(SIG_BLOCK, &mask, NULL);
337         
338         signal(SIGPIPE, sigpipe_handler);
339
340         return 0;
341 }
342
343 static void lws_plat_context_early_destroy(struct libwebsocket_context *context)
344 {
345 }
346
347 static void lws_plat_context_late_destroy(struct libwebsocket_context *context)
348 {
349         close(context->dummy_pipe_fds[0]);
350         close(context->dummy_pipe_fds[1]);
351         close(context->fd_random);
352 }
353
354 /* cast a struct sockaddr_in6 * into addr for ipv6 */
355
356 int
357 interface_to_sa(struct libwebsocket_context *context,
358                 const char *ifname, struct sockaddr_in *addr, size_t addrlen)
359 {
360         int rc = -1;
361
362         struct ifaddrs *ifr;
363         struct ifaddrs *ifc;
364 #ifdef LWS_USE_IPV6
365         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
366 #endif
367
368         getifaddrs(&ifr);
369         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
370                 if (!ifc->ifa_addr)
371                         continue;
372
373                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
374
375                 if (strcmp(ifc->ifa_name, ifname))
376                         continue;
377
378                 switch (ifc->ifa_addr->sa_family) {
379                 case AF_INET:
380 #ifdef LWS_USE_IPV6
381                         if (LWS_IPV6_ENABLED(context)) {
382                                 /* map IPv4 to IPv6 */
383                                 bzero((char *)&addr6->sin6_addr,
384                                                 sizeof(struct in6_addr));
385                                 addr6->sin6_addr.s6_addr[10] = 0xff;
386                                 addr6->sin6_addr.s6_addr[11] = 0xff;
387                                 memcpy(&addr6->sin6_addr.s6_addr[12],
388                                         &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
389                                                         sizeof(struct in_addr));
390                         } else
391 #endif
392                                 memcpy(addr,
393                                         (struct sockaddr_in *)ifc->ifa_addr,
394                                                     sizeof(struct sockaddr_in));
395                         break;
396 #ifdef LWS_USE_IPV6
397                 case AF_INET6:
398                         if (rc >= 0)
399                                 break;
400                         memcpy(&addr6->sin6_addr,
401                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
402                                                        sizeof(struct in6_addr));
403                         break;
404 #endif
405                 default:
406                         continue;
407                 }
408                 rc = 0;
409         }
410
411         freeifaddrs(ifr);
412         
413         return rc;
414 }
415
416 void lws_plat_insert_socket_into_fds(struct libwebsocket_context *context,
417                                                        struct libwebsocket *wsi)
418 {
419 #ifdef LWS_USE_LIBEV
420         if (context && context->io_loop && LWS_LIBEV_ENABLED(context))
421                 ev_io_start(context->io_loop, (struct ev_io *)&wsi->w_read);
422 #endif /* LWS_USE_LIBEV */
423         context->fds[context->fds_count++].revents = 0;
424 }
425
426 void lws_plat_delete_socket_from_fds(struct libwebsocket_context *context,
427                                                 struct libwebsocket *wsi, int m)
428 {
429 }
430
431 static void lws_plat_service_periodic(struct libwebsocket_context *context)
432 {
433         /* if our parent went down, don't linger around */
434         if (context->started_with_parent &&
435                               kill(context->started_with_parent, 0) < 0)
436                 kill(getpid(), SIGTERM);
437 }
438
439 static int lws_plat_change_pollfd(struct libwebsocket_context *context,
440                       struct libwebsocket *wsi, struct libwebsocket_pollfd *pfd)
441 {
442         return 0;
443 }
444
445 int lws_plat_open_file(const char* filename, unsigned long* filelen)
446 {
447         struct stat stat_buf;
448         int ret = open(filename, O_RDONLY);
449
450         if (ret < 0)
451                 return LWS_INVALID_FILE;
452
453         fstat(ret, &stat_buf);
454         *filelen = stat_buf.st_size;
455         return ret;
456 }