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