6bb2057351e9fd2193e8ebb2b2a6e0e1db0bf95d
[platform/upstream/nodejs.git] / deps / uv / src / unix / core.c
1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
2  * Permission is hereby granted, free of charge, to any person obtaining a copy
3  * of this software and associated documentation files (the "Software"), to
4  * deal in the Software without restriction, including without limitation the
5  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
6  * sell copies of the Software, and to permit persons to whom the Software is
7  * furnished to do so, subject to the following conditions:
8  *
9  * The above copyright notice and this permission notice shall be included in
10  * all copies or substantial portions of the Software.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
17  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
18  * IN THE SOFTWARE.
19  */
20
21 #include "uv.h"
22 #include "internal.h"
23
24 #include <stddef.h> /* NULL */
25 #include <stdio.h> /* printf */
26 #include <stdlib.h>
27 #include <string.h> /* strerror */
28 #include <errno.h>
29 #include <assert.h>
30 #include <unistd.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <sys/socket.h>
35 #include <sys/un.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include <limits.h> /* INT_MAX, PATH_MAX */
39 #include <sys/uio.h> /* writev */
40
41 #ifdef __linux__
42 # include <sys/ioctl.h>
43 #endif
44
45 #ifdef __sun
46 # include <sys/types.h>
47 # include <sys/wait.h>
48 #endif
49
50 #ifdef __APPLE__
51 # include <mach-o/dyld.h> /* _NSGetExecutablePath */
52 # include <sys/filio.h>
53 # include <sys/ioctl.h>
54 #endif
55
56 #ifdef __FreeBSD__
57 # include <sys/sysctl.h>
58 # include <sys/filio.h>
59 # include <sys/ioctl.h>
60 # include <sys/wait.h>
61 #endif
62
63 static void uv__run_pending(uv_loop_t* loop);
64
65 /* Verify that uv_buf_t is ABI-compatible with struct iovec. */
66 STATIC_ASSERT(sizeof(uv_buf_t) == sizeof(struct iovec));
67 STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->base) ==
68               sizeof(((struct iovec*) 0)->iov_base));
69 STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->len) ==
70               sizeof(((struct iovec*) 0)->iov_len));
71 STATIC_ASSERT(offsetof(uv_buf_t, base) == offsetof(struct iovec, iov_base));
72 STATIC_ASSERT(offsetof(uv_buf_t, len) == offsetof(struct iovec, iov_len));
73
74
75 uint64_t uv_hrtime(void) {
76   return uv__hrtime(UV_CLOCK_PRECISE);
77 }
78
79
80 void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
81   assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));
82
83   handle->flags |= UV_CLOSING;
84   handle->close_cb = close_cb;
85
86   switch (handle->type) {
87   case UV_NAMED_PIPE:
88     uv__pipe_close((uv_pipe_t*)handle);
89     break;
90
91   case UV_TTY:
92     uv__stream_close((uv_stream_t*)handle);
93     break;
94
95   case UV_TCP:
96     uv__tcp_close((uv_tcp_t*)handle);
97     break;
98
99   case UV_UDP:
100     uv__udp_close((uv_udp_t*)handle);
101     break;
102
103   case UV_PREPARE:
104     uv__prepare_close((uv_prepare_t*)handle);
105     break;
106
107   case UV_CHECK:
108     uv__check_close((uv_check_t*)handle);
109     break;
110
111   case UV_IDLE:
112     uv__idle_close((uv_idle_t*)handle);
113     break;
114
115   case UV_ASYNC:
116     uv__async_close((uv_async_t*)handle);
117     break;
118
119   case UV_TIMER:
120     uv__timer_close((uv_timer_t*)handle);
121     break;
122
123   case UV_PROCESS:
124     uv__process_close((uv_process_t*)handle);
125     break;
126
127   case UV_FS_EVENT:
128     uv__fs_event_close((uv_fs_event_t*)handle);
129     break;
130
131   case UV_POLL:
132     uv__poll_close((uv_poll_t*)handle);
133     break;
134
135   case UV_FS_POLL:
136     uv__fs_poll_close((uv_fs_poll_t*)handle);
137     break;
138
139   case UV_SIGNAL:
140     uv__signal_close((uv_signal_t*) handle);
141     /* Signal handles may not be closed immediately. The signal code will */
142     /* itself close uv__make_close_pending whenever appropriate. */
143     return;
144
145   default:
146     assert(0);
147   }
148
149   uv__make_close_pending(handle);
150 }
151
152
153 void uv__make_close_pending(uv_handle_t* handle) {
154   assert(handle->flags & UV_CLOSING);
155   assert(!(handle->flags & UV_CLOSED));
156   handle->next_closing = handle->loop->closing_handles;
157   handle->loop->closing_handles = handle;
158 }
159
160
161 static void uv__finish_close(uv_handle_t* handle) {
162   /* Note: while the handle is in the UV_CLOSING state now, it's still possible
163    * for it to be active in the sense that uv__is_active() returns true.
164    * A good example is when the user calls uv_shutdown(), immediately followed
165    * by uv_close(). The handle is considered active at this point because the
166    * completion of the shutdown req is still pending.
167    */
168   assert(handle->flags & UV_CLOSING);
169   assert(!(handle->flags & UV_CLOSED));
170   handle->flags |= UV_CLOSED;
171
172   switch (handle->type) {
173     case UV_PREPARE:
174     case UV_CHECK:
175     case UV_IDLE:
176     case UV_ASYNC:
177     case UV_TIMER:
178     case UV_PROCESS:
179     case UV_FS_EVENT:
180     case UV_FS_POLL:
181     case UV_POLL:
182     case UV_SIGNAL:
183       break;
184
185     case UV_NAMED_PIPE:
186     case UV_TCP:
187     case UV_TTY:
188       uv__stream_destroy((uv_stream_t*)handle);
189       break;
190
191     case UV_UDP:
192       uv__udp_finish_close((uv_udp_t*)handle);
193       break;
194
195     default:
196       assert(0);
197       break;
198   }
199
200   uv__handle_unref(handle);
201   QUEUE_REMOVE(&handle->handle_queue);
202
203   if (handle->close_cb) {
204     handle->close_cb(handle);
205   }
206 }
207
208
209 static void uv__run_closing_handles(uv_loop_t* loop) {
210   uv_handle_t* p;
211   uv_handle_t* q;
212
213   p = loop->closing_handles;
214   loop->closing_handles = NULL;
215
216   while (p) {
217     q = p->next_closing;
218     uv__finish_close(p);
219     p = q;
220   }
221 }
222
223
224 int uv_is_closing(const uv_handle_t* handle) {
225   return uv__is_closing(handle);
226 }
227
228
229 int uv_backend_fd(const uv_loop_t* loop) {
230   return loop->backend_fd;
231 }
232
233
234 int uv_backend_timeout(const uv_loop_t* loop) {
235   if (loop->stop_flag != 0)
236     return 0;
237
238   if (!uv__has_active_handles(loop) && !uv__has_active_reqs(loop))
239     return 0;
240
241   if (!QUEUE_EMPTY(&loop->idle_handles))
242     return 0;
243
244   if (loop->closing_handles)
245     return 0;
246
247   return uv__next_timeout(loop);
248 }
249
250
251 static int uv__loop_alive(uv_loop_t* loop) {
252   return uv__has_active_handles(loop) ||
253          uv__has_active_reqs(loop) ||
254          loop->closing_handles != NULL;
255 }
256
257
258 int uv_run(uv_loop_t* loop, uv_run_mode mode) {
259   int timeout;
260   int r;
261
262   r = uv__loop_alive(loop);
263   if (!r)
264     uv__update_time(loop);
265
266   while (r != 0 && loop->stop_flag == 0) {
267     UV_TICK_START(loop, mode);
268
269     uv__update_time(loop);
270     uv__run_timers(loop);
271     uv__run_idle(loop);
272     uv__run_prepare(loop);
273     uv__run_pending(loop);
274
275     timeout = 0;
276     if ((mode & UV_RUN_NOWAIT) == 0)
277       timeout = uv_backend_timeout(loop);
278
279     uv__io_poll(loop, timeout);
280     uv__run_check(loop);
281     uv__run_closing_handles(loop);
282
283     if (mode == UV_RUN_ONCE) {
284       /* UV_RUN_ONCE implies forward progess: at least one callback must have
285        * been invoked when it returns. uv__io_poll() can return without doing
286        * I/O (meaning: no callbacks) when its timeout expires - which means we
287        * have pending timers that satisfy the forward progress constraint.
288        *
289        * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
290        * the check.
291        */
292       uv__update_time(loop);
293       uv__run_timers(loop);
294     }
295
296     r = uv__loop_alive(loop);
297     UV_TICK_STOP(loop, mode);
298
299     if (mode & (UV_RUN_ONCE | UV_RUN_NOWAIT))
300       break;
301   }
302
303   /* The if statement lets gcc compile it to a conditional store. Avoids
304    * dirtying a cache line.
305    */
306   if (loop->stop_flag != 0)
307     loop->stop_flag = 0;
308
309   return r;
310 }
311
312
313 void uv_update_time(uv_loop_t* loop) {
314   uv__update_time(loop);
315 }
316
317
318 int uv_is_active(const uv_handle_t* handle) {
319   return uv__is_active(handle);
320 }
321
322
323 /* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
324 int uv__socket(int domain, int type, int protocol) {
325   int sockfd;
326   int err;
327
328 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
329   sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
330   if (sockfd != -1)
331     return sockfd;
332
333   if (errno != EINVAL)
334     return -errno;
335 #endif
336
337   sockfd = socket(domain, type, protocol);
338   if (sockfd == -1)
339     return -errno;
340
341   err = uv__nonblock(sockfd, 1);
342   if (err == 0)
343     err = uv__cloexec(sockfd, 1);
344
345   if (err) {
346     uv__close(sockfd);
347     return err;
348   }
349
350 #if defined(SO_NOSIGPIPE)
351   {
352     int on = 1;
353     setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
354   }
355 #endif
356
357   return sockfd;
358 }
359
360
361 int uv__accept(int sockfd) {
362   int peerfd;
363   int err;
364
365   assert(sockfd >= 0);
366
367   while (1) {
368 #if defined(__linux__)
369     static int no_accept4;
370
371     if (no_accept4)
372       goto skip;
373
374     peerfd = uv__accept4(sockfd,
375                          NULL,
376                          NULL,
377                          UV__SOCK_NONBLOCK|UV__SOCK_CLOEXEC);
378     if (peerfd != -1)
379       return peerfd;
380
381     if (errno == EINTR)
382       continue;
383
384     if (errno != ENOSYS)
385       return -errno;
386
387     no_accept4 = 1;
388 skip:
389 #endif
390
391     peerfd = accept(sockfd, NULL, NULL);
392     if (peerfd == -1) {
393       if (errno == EINTR)
394         continue;
395       return -errno;
396     }
397
398     err = uv__cloexec(peerfd, 1);
399     if (err == 0)
400       err = uv__nonblock(peerfd, 1);
401
402     if (err) {
403       uv__close(peerfd);
404       return err;
405     }
406
407     return peerfd;
408   }
409 }
410
411
412 int uv__close(int fd) {
413   int saved_errno;
414   int rc;
415
416   assert(fd > -1);  /* Catch uninitialized io_watcher.fd bugs. */
417   assert(fd > STDERR_FILENO);  /* Catch stdio close bugs. */
418
419   saved_errno = errno;
420   rc = close(fd);
421   if (rc == -1) {
422     rc = -errno;
423     if (rc == -EINTR)
424       rc = -EINPROGRESS;  /* For platform/libc consistency. */
425     errno = saved_errno;
426   }
427
428   return rc;
429 }
430
431
432 #if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
433
434 int uv__nonblock(int fd, int set) {
435   int r;
436
437   do
438     r = ioctl(fd, FIONBIO, &set);
439   while (r == -1 && errno == EINTR);
440
441   if (r)
442     return -errno;
443
444   return 0;
445 }
446
447
448 int uv__cloexec(int fd, int set) {
449   int r;
450
451   do
452     r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
453   while (r == -1 && errno == EINTR);
454
455   if (r)
456     return -errno;
457
458   return 0;
459 }
460
461 #else /* !(defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)) */
462
463 int uv__nonblock(int fd, int set) {
464   int flags;
465   int r;
466
467   do
468     r = fcntl(fd, F_GETFL);
469   while (r == -1 && errno == EINTR);
470
471   if (r == -1)
472     return -errno;
473
474   /* Bail out now if already set/clear. */
475   if (!!(r & O_NONBLOCK) == !!set)
476     return 0;
477
478   if (set)
479     flags = r | O_NONBLOCK;
480   else
481     flags = r & ~O_NONBLOCK;
482
483   do
484     r = fcntl(fd, F_SETFL, flags);
485   while (r == -1 && errno == EINTR);
486
487   if (r)
488     return -errno;
489
490   return 0;
491 }
492
493
494 int uv__cloexec(int fd, int set) {
495   int flags;
496   int r;
497
498   do
499     r = fcntl(fd, F_GETFD);
500   while (r == -1 && errno == EINTR);
501
502   if (r == -1)
503     return -errno;
504
505   /* Bail out now if already set/clear. */
506   if (!!(r & FD_CLOEXEC) == !!set)
507     return 0;
508
509   if (set)
510     flags = r | FD_CLOEXEC;
511   else
512     flags = r & ~FD_CLOEXEC;
513
514   do
515     r = fcntl(fd, F_SETFD, flags);
516   while (r == -1 && errno == EINTR);
517
518   if (r)
519     return -errno;
520
521   return 0;
522 }
523
524 #endif /* defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) */
525
526
527 /* This function is not execve-safe, there is a race window
528  * between the call to dup() and fcntl(FD_CLOEXEC).
529  */
530 int uv__dup(int fd) {
531   int err;
532
533   fd = dup(fd);
534
535   if (fd == -1)
536     return -errno;
537
538   err = uv__cloexec(fd, 1);
539   if (err) {
540     uv__close(fd);
541     return err;
542   }
543
544   return fd;
545 }
546
547
548 ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) {
549   struct cmsghdr* cmsg;
550   ssize_t rc;
551   int* pfd;
552   int* end;
553 #if defined(__linux__)
554   static int no_msg_cmsg_cloexec;
555   if (no_msg_cmsg_cloexec == 0) {
556     rc = recvmsg(fd, msg, flags | 0x40000000);  /* MSG_CMSG_CLOEXEC */
557     if (rc != -1)
558       return rc;
559     if (errno != EINVAL)
560       return -errno;
561     rc = recvmsg(fd, msg, flags);
562     if (rc == -1)
563       return -errno;
564     no_msg_cmsg_cloexec = 1;
565   } else {
566     rc = recvmsg(fd, msg, flags);
567   }
568 #else
569   rc = recvmsg(fd, msg, flags);
570 #endif
571   if (rc == -1)
572     return -errno;
573   if (msg->msg_controllen == 0)
574     return rc;
575   for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg))
576     if (cmsg->cmsg_type == SCM_RIGHTS)
577       for (pfd = (int*) CMSG_DATA(cmsg),
578            end = (int*) ((char*) cmsg + cmsg->cmsg_len);
579            pfd < end;
580            pfd += 1)
581         uv__cloexec(*pfd, 1);
582   return rc;
583 }
584
585
586 int uv_cwd(char* buffer, size_t size) {
587   if (buffer == NULL)
588     return -EINVAL;
589
590   if (size == 0)
591     return -EINVAL;
592
593   if (getcwd(buffer, size) == NULL)
594     return -errno;
595
596   return 0;
597 }
598
599
600 int uv_chdir(const char* dir) {
601   if (chdir(dir))
602     return -errno;
603
604   return 0;
605 }
606
607
608 void uv_disable_stdio_inheritance(void) {
609   int fd;
610
611   /* Set the CLOEXEC flag on all open descriptors. Unconditionally try the
612    * first 16 file descriptors. After that, bail out after the first error.
613    */
614   for (fd = 0; ; fd++)
615     if (uv__cloexec(fd, 1) && fd > 15)
616       break;
617 }
618
619
620 static void uv__run_pending(uv_loop_t* loop) {
621   QUEUE* q;
622   uv__io_t* w;
623
624   while (!QUEUE_EMPTY(&loop->pending_queue)) {
625     q = QUEUE_HEAD(&loop->pending_queue);
626     QUEUE_REMOVE(q);
627     QUEUE_INIT(q);
628
629     w = QUEUE_DATA(q, uv__io_t, pending_queue);
630     w->cb(loop, w, UV__POLLOUT);
631   }
632 }
633
634
635 static unsigned int next_power_of_two(unsigned int val) {
636   val -= 1;
637   val |= val >> 1;
638   val |= val >> 2;
639   val |= val >> 4;
640   val |= val >> 8;
641   val |= val >> 16;
642   val += 1;
643   return val;
644 }
645
646 static void maybe_resize(uv_loop_t* loop, unsigned int len) {
647   uv__io_t** watchers;
648   void* fake_watcher_list;
649   void* fake_watcher_count;
650   unsigned int nwatchers;
651   unsigned int i;
652
653   if (len <= loop->nwatchers)
654     return;
655
656   /* Preserve fake watcher list and count at the end of the watchers */
657   if (loop->watchers != NULL) {
658     fake_watcher_list = loop->watchers[loop->nwatchers];
659     fake_watcher_count = loop->watchers[loop->nwatchers + 1];
660   } else {
661     fake_watcher_list = NULL;
662     fake_watcher_count = NULL;
663   }
664
665   nwatchers = next_power_of_two(len + 2) - 2;
666   watchers = realloc(loop->watchers,
667                      (nwatchers + 2) * sizeof(loop->watchers[0]));
668
669   if (watchers == NULL)
670     abort();
671   for (i = loop->nwatchers; i < nwatchers; i++)
672     watchers[i] = NULL;
673   watchers[nwatchers] = fake_watcher_list;
674   watchers[nwatchers + 1] = fake_watcher_count;
675
676   loop->watchers = watchers;
677   loop->nwatchers = nwatchers;
678 }
679
680
681 void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
682   assert(cb != NULL);
683   assert(fd >= -1);
684   QUEUE_INIT(&w->pending_queue);
685   QUEUE_INIT(&w->watcher_queue);
686   w->cb = cb;
687   w->fd = fd;
688   w->events = 0;
689   w->pevents = 0;
690
691 #if defined(UV_HAVE_KQUEUE)
692   w->rcount = 0;
693   w->wcount = 0;
694 #endif /* defined(UV_HAVE_KQUEUE) */
695 }
696
697
698 void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
699   assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
700   assert(0 != events);
701   assert(w->fd >= 0);
702   assert(w->fd < INT_MAX);
703
704   w->pevents |= events;
705   maybe_resize(loop, w->fd + 1);
706
707 #if !defined(__sun)
708   /* The event ports backend needs to rearm all file descriptors on each and
709    * every tick of the event loop but the other backends allow us to
710    * short-circuit here if the event mask is unchanged.
711    */
712   if (w->events == w->pevents) {
713     if (w->events == 0 && !QUEUE_EMPTY(&w->watcher_queue)) {
714       QUEUE_REMOVE(&w->watcher_queue);
715       QUEUE_INIT(&w->watcher_queue);
716     }
717     return;
718   }
719 #endif
720
721   if (QUEUE_EMPTY(&w->watcher_queue))
722     QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
723
724   if (loop->watchers[w->fd] == NULL) {
725     loop->watchers[w->fd] = w;
726     loop->nfds++;
727   }
728 }
729
730
731 void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
732   assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
733   assert(0 != events);
734
735   if (w->fd == -1)
736     return;
737
738   assert(w->fd >= 0);
739
740   /* Happens when uv__io_stop() is called on a handle that was never started. */
741   if ((unsigned) w->fd >= loop->nwatchers)
742     return;
743
744   w->pevents &= ~events;
745
746   if (w->pevents == 0) {
747     QUEUE_REMOVE(&w->watcher_queue);
748     QUEUE_INIT(&w->watcher_queue);
749
750     if (loop->watchers[w->fd] != NULL) {
751       assert(loop->watchers[w->fd] == w);
752       assert(loop->nfds > 0);
753       loop->watchers[w->fd] = NULL;
754       loop->nfds--;
755       w->events = 0;
756     }
757   }
758   else if (QUEUE_EMPTY(&w->watcher_queue))
759     QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
760 }
761
762
763 void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
764   uv__io_stop(loop, w, UV__POLLIN | UV__POLLOUT);
765   QUEUE_REMOVE(&w->pending_queue);
766
767   /* Remove stale events for this file descriptor */
768   uv__platform_invalidate_fd(loop, w->fd);
769 }
770
771
772 void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
773   if (QUEUE_EMPTY(&w->pending_queue))
774     QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue);
775 }
776
777
778 int uv__io_active(const uv__io_t* w, unsigned int events) {
779   assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
780   assert(0 != events);
781   return 0 != (w->pevents & events);
782 }