uv: Upgrade to v0.11.17
[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(const 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_loop_alive(const uv_loop_t* loop) {
259     return uv__loop_alive(loop);
260 }
261
262
263 int uv_run(uv_loop_t* loop, uv_run_mode mode) {
264   int timeout;
265   int r;
266
267   r = uv__loop_alive(loop);
268   if (!r)
269     uv__update_time(loop);
270
271   while (r != 0 && loop->stop_flag == 0) {
272     UV_TICK_START(loop, mode);
273
274     uv__update_time(loop);
275     uv__run_timers(loop);
276     uv__run_idle(loop);
277     uv__run_prepare(loop);
278     uv__run_pending(loop);
279
280     timeout = 0;
281     if ((mode & UV_RUN_NOWAIT) == 0)
282       timeout = uv_backend_timeout(loop);
283
284     uv__io_poll(loop, timeout);
285     uv__run_check(loop);
286     uv__run_closing_handles(loop);
287
288     if (mode == UV_RUN_ONCE) {
289       /* UV_RUN_ONCE implies forward progess: at least one callback must have
290        * been invoked when it returns. uv__io_poll() can return without doing
291        * I/O (meaning: no callbacks) when its timeout expires - which means we
292        * have pending timers that satisfy the forward progress constraint.
293        *
294        * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
295        * the check.
296        */
297       uv__update_time(loop);
298       uv__run_timers(loop);
299     }
300
301     r = uv__loop_alive(loop);
302     UV_TICK_STOP(loop, mode);
303
304     if (mode & (UV_RUN_ONCE | UV_RUN_NOWAIT))
305       break;
306   }
307
308   /* The if statement lets gcc compile it to a conditional store. Avoids
309    * dirtying a cache line.
310    */
311   if (loop->stop_flag != 0)
312     loop->stop_flag = 0;
313
314   return r;
315 }
316
317
318 void uv_update_time(uv_loop_t* loop) {
319   uv__update_time(loop);
320 }
321
322
323 int uv_is_active(const uv_handle_t* handle) {
324   return uv__is_active(handle);
325 }
326
327
328 /* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
329 int uv__socket(int domain, int type, int protocol) {
330   int sockfd;
331   int err;
332
333 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
334   sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
335   if (sockfd != -1)
336     return sockfd;
337
338   if (errno != EINVAL)
339     return -errno;
340 #endif
341
342   sockfd = socket(domain, type, protocol);
343   if (sockfd == -1)
344     return -errno;
345
346   err = uv__nonblock(sockfd, 1);
347   if (err == 0)
348     err = uv__cloexec(sockfd, 1);
349
350   if (err) {
351     uv__close(sockfd);
352     return err;
353   }
354
355 #if defined(SO_NOSIGPIPE)
356   {
357     int on = 1;
358     setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
359   }
360 #endif
361
362   return sockfd;
363 }
364
365
366 int uv__accept(int sockfd) {
367   int peerfd;
368   int err;
369
370   assert(sockfd >= 0);
371
372   while (1) {
373 #if defined(__linux__)
374     static int no_accept4;
375
376     if (no_accept4)
377       goto skip;
378
379     peerfd = uv__accept4(sockfd,
380                          NULL,
381                          NULL,
382                          UV__SOCK_NONBLOCK|UV__SOCK_CLOEXEC);
383     if (peerfd != -1)
384       return peerfd;
385
386     if (errno == EINTR)
387       continue;
388
389     if (errno != ENOSYS)
390       return -errno;
391
392     no_accept4 = 1;
393 skip:
394 #endif
395
396     peerfd = accept(sockfd, NULL, NULL);
397     if (peerfd == -1) {
398       if (errno == EINTR)
399         continue;
400       return -errno;
401     }
402
403     err = uv__cloexec(peerfd, 1);
404     if (err == 0)
405       err = uv__nonblock(peerfd, 1);
406
407     if (err) {
408       uv__close(peerfd);
409       return err;
410     }
411
412     return peerfd;
413   }
414 }
415
416
417 int uv__close(int fd) {
418   int saved_errno;
419   int rc;
420
421   assert(fd > -1);  /* Catch uninitialized io_watcher.fd bugs. */
422   assert(fd > STDERR_FILENO);  /* Catch stdio close bugs. */
423
424   saved_errno = errno;
425   rc = close(fd);
426   if (rc == -1) {
427     rc = -errno;
428     if (rc == -EINTR)
429       rc = -EINPROGRESS;  /* For platform/libc consistency. */
430     errno = saved_errno;
431   }
432
433   return rc;
434 }
435
436
437 #if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
438
439 int uv__nonblock(int fd, int set) {
440   int r;
441
442   do
443     r = ioctl(fd, FIONBIO, &set);
444   while (r == -1 && errno == EINTR);
445
446   if (r)
447     return -errno;
448
449   return 0;
450 }
451
452
453 int uv__cloexec(int fd, int set) {
454   int r;
455
456   do
457     r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
458   while (r == -1 && errno == EINTR);
459
460   if (r)
461     return -errno;
462
463   return 0;
464 }
465
466 #else /* !(defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)) */
467
468 int uv__nonblock(int fd, int set) {
469   int flags;
470   int r;
471
472   do
473     r = fcntl(fd, F_GETFL);
474   while (r == -1 && errno == EINTR);
475
476   if (r == -1)
477     return -errno;
478
479   /* Bail out now if already set/clear. */
480   if (!!(r & O_NONBLOCK) == !!set)
481     return 0;
482
483   if (set)
484     flags = r | O_NONBLOCK;
485   else
486     flags = r & ~O_NONBLOCK;
487
488   do
489     r = fcntl(fd, F_SETFL, flags);
490   while (r == -1 && errno == EINTR);
491
492   if (r)
493     return -errno;
494
495   return 0;
496 }
497
498
499 int uv__cloexec(int fd, int set) {
500   int flags;
501   int r;
502
503   do
504     r = fcntl(fd, F_GETFD);
505   while (r == -1 && errno == EINTR);
506
507   if (r == -1)
508     return -errno;
509
510   /* Bail out now if already set/clear. */
511   if (!!(r & FD_CLOEXEC) == !!set)
512     return 0;
513
514   if (set)
515     flags = r | FD_CLOEXEC;
516   else
517     flags = r & ~FD_CLOEXEC;
518
519   do
520     r = fcntl(fd, F_SETFD, flags);
521   while (r == -1 && errno == EINTR);
522
523   if (r)
524     return -errno;
525
526   return 0;
527 }
528
529 #endif /* defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) */
530
531
532 /* This function is not execve-safe, there is a race window
533  * between the call to dup() and fcntl(FD_CLOEXEC).
534  */
535 int uv__dup(int fd) {
536   int err;
537
538   fd = dup(fd);
539
540   if (fd == -1)
541     return -errno;
542
543   err = uv__cloexec(fd, 1);
544   if (err) {
545     uv__close(fd);
546     return err;
547   }
548
549   return fd;
550 }
551
552
553 ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) {
554   struct cmsghdr* cmsg;
555   ssize_t rc;
556   int* pfd;
557   int* end;
558 #if defined(__linux__)
559   static int no_msg_cmsg_cloexec;
560   if (no_msg_cmsg_cloexec == 0) {
561     rc = recvmsg(fd, msg, flags | 0x40000000);  /* MSG_CMSG_CLOEXEC */
562     if (rc != -1)
563       return rc;
564     if (errno != EINVAL)
565       return -errno;
566     rc = recvmsg(fd, msg, flags);
567     if (rc == -1)
568       return -errno;
569     no_msg_cmsg_cloexec = 1;
570   } else {
571     rc = recvmsg(fd, msg, flags);
572   }
573 #else
574   rc = recvmsg(fd, msg, flags);
575 #endif
576   if (rc == -1)
577     return -errno;
578   if (msg->msg_controllen == 0)
579     return rc;
580   for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg))
581     if (cmsg->cmsg_type == SCM_RIGHTS)
582       for (pfd = (int*) CMSG_DATA(cmsg),
583            end = (int*) ((char*) cmsg + cmsg->cmsg_len);
584            pfd < end;
585            pfd += 1)
586         uv__cloexec(*pfd, 1);
587   return rc;
588 }
589
590
591 int uv_cwd(char* buffer, size_t size) {
592   if (buffer == NULL)
593     return -EINVAL;
594
595   if (size == 0)
596     return -EINVAL;
597
598   if (getcwd(buffer, size) == NULL)
599     return -errno;
600
601   return 0;
602 }
603
604
605 int uv_chdir(const char* dir) {
606   if (chdir(dir))
607     return -errno;
608
609   return 0;
610 }
611
612
613 void uv_disable_stdio_inheritance(void) {
614   int fd;
615
616   /* Set the CLOEXEC flag on all open descriptors. Unconditionally try the
617    * first 16 file descriptors. After that, bail out after the first error.
618    */
619   for (fd = 0; ; fd++)
620     if (uv__cloexec(fd, 1) && fd > 15)
621       break;
622 }
623
624
625 static void uv__run_pending(uv_loop_t* loop) {
626   QUEUE* q;
627   uv__io_t* w;
628
629   while (!QUEUE_EMPTY(&loop->pending_queue)) {
630     q = QUEUE_HEAD(&loop->pending_queue);
631     QUEUE_REMOVE(q);
632     QUEUE_INIT(q);
633
634     w = QUEUE_DATA(q, uv__io_t, pending_queue);
635     w->cb(loop, w, UV__POLLOUT);
636   }
637 }
638
639
640 static unsigned int next_power_of_two(unsigned int val) {
641   val -= 1;
642   val |= val >> 1;
643   val |= val >> 2;
644   val |= val >> 4;
645   val |= val >> 8;
646   val |= val >> 16;
647   val += 1;
648   return val;
649 }
650
651 static void maybe_resize(uv_loop_t* loop, unsigned int len) {
652   uv__io_t** watchers;
653   void* fake_watcher_list;
654   void* fake_watcher_count;
655   unsigned int nwatchers;
656   unsigned int i;
657
658   if (len <= loop->nwatchers)
659     return;
660
661   /* Preserve fake watcher list and count at the end of the watchers */
662   if (loop->watchers != NULL) {
663     fake_watcher_list = loop->watchers[loop->nwatchers];
664     fake_watcher_count = loop->watchers[loop->nwatchers + 1];
665   } else {
666     fake_watcher_list = NULL;
667     fake_watcher_count = NULL;
668   }
669
670   nwatchers = next_power_of_two(len + 2) - 2;
671   watchers = realloc(loop->watchers,
672                      (nwatchers + 2) * sizeof(loop->watchers[0]));
673
674   if (watchers == NULL)
675     abort();
676   for (i = loop->nwatchers; i < nwatchers; i++)
677     watchers[i] = NULL;
678   watchers[nwatchers] = fake_watcher_list;
679   watchers[nwatchers + 1] = fake_watcher_count;
680
681   loop->watchers = watchers;
682   loop->nwatchers = nwatchers;
683 }
684
685
686 void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
687   assert(cb != NULL);
688   assert(fd >= -1);
689   QUEUE_INIT(&w->pending_queue);
690   QUEUE_INIT(&w->watcher_queue);
691   w->cb = cb;
692   w->fd = fd;
693   w->events = 0;
694   w->pevents = 0;
695
696 #if defined(UV_HAVE_KQUEUE)
697   w->rcount = 0;
698   w->wcount = 0;
699 #endif /* defined(UV_HAVE_KQUEUE) */
700 }
701
702
703 void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
704   assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
705   assert(0 != events);
706   assert(w->fd >= 0);
707   assert(w->fd < INT_MAX);
708
709   w->pevents |= events;
710   maybe_resize(loop, w->fd + 1);
711
712 #if !defined(__sun)
713   /* The event ports backend needs to rearm all file descriptors on each and
714    * every tick of the event loop but the other backends allow us to
715    * short-circuit here if the event mask is unchanged.
716    */
717   if (w->events == w->pevents) {
718     if (w->events == 0 && !QUEUE_EMPTY(&w->watcher_queue)) {
719       QUEUE_REMOVE(&w->watcher_queue);
720       QUEUE_INIT(&w->watcher_queue);
721     }
722     return;
723   }
724 #endif
725
726   if (QUEUE_EMPTY(&w->watcher_queue))
727     QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
728
729   if (loop->watchers[w->fd] == NULL) {
730     loop->watchers[w->fd] = w;
731     loop->nfds++;
732   }
733 }
734
735
736 void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
737   assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
738   assert(0 != events);
739
740   if (w->fd == -1)
741     return;
742
743   assert(w->fd >= 0);
744
745   /* Happens when uv__io_stop() is called on a handle that was never started. */
746   if ((unsigned) w->fd >= loop->nwatchers)
747     return;
748
749   w->pevents &= ~events;
750
751   if (w->pevents == 0) {
752     QUEUE_REMOVE(&w->watcher_queue);
753     QUEUE_INIT(&w->watcher_queue);
754
755     if (loop->watchers[w->fd] != NULL) {
756       assert(loop->watchers[w->fd] == w);
757       assert(loop->nfds > 0);
758       loop->watchers[w->fd] = NULL;
759       loop->nfds--;
760       w->events = 0;
761     }
762   }
763   else if (QUEUE_EMPTY(&w->watcher_queue))
764     QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
765 }
766
767
768 void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
769   uv__io_stop(loop, w, UV__POLLIN | UV__POLLOUT);
770   QUEUE_REMOVE(&w->pending_queue);
771
772   /* Remove stale events for this file descriptor */
773   uv__platform_invalidate_fd(loop, w->fd);
774 }
775
776
777 void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
778   if (QUEUE_EMPTY(&w->pending_queue))
779     QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue);
780 }
781
782
783 int uv__io_active(const uv__io_t* w, unsigned int events) {
784   assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
785   assert(0 != events);
786   return 0 != (w->pevents & events);
787 }