1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
3 * Permission is hereby granted, free of charge, to any person obtaining a copy
4 * of this software and associated documentation files (the "Software"), to
5 * deal in the Software without restriction, including without limitation the
6 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 * sell copies of the Software, and to permit persons to whom the Software is
8 * furnished to do so, subject to the following conditions:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
31 #include <sys/types.h>
32 #include <sys/socket.h>
36 #include <limits.h> /* IOV_MAX */
38 #if defined(__APPLE__)
39 # include <sys/event.h>
40 # include <sys/time.h>
41 # include <sys/select.h>
43 /* Forward declaration */
44 typedef struct uv__stream_select_s uv__stream_select_t;
46 struct uv__stream_select_s {
61 #endif /* defined(__APPLE__) */
63 static void uv__stream_connect(uv_stream_t*);
64 static void uv__write(uv_stream_t* stream);
65 static void uv__read(uv_stream_t* stream);
66 static void uv__stream_io(uv_loop_t* loop, uv__io_t* w, unsigned int events);
67 static void uv__write_callbacks(uv_stream_t* stream);
68 static size_t uv__write_req_size(uv_write_t* req);
69 static void uv__drain(uv_stream_t* stream);
72 void uv__stream_init(uv_loop_t* loop,
74 uv_handle_type type) {
77 uv__handle_init(loop, (uv_handle_t*)stream, type);
78 stream->read_cb = NULL;
79 stream->alloc_cb = NULL;
80 stream->close_cb = NULL;
81 stream->connection_cb = NULL;
82 stream->connect_req = NULL;
83 stream->shutdown_req = NULL;
84 stream->accepted_fd = -1;
85 stream->queued_fds = NULL;
86 stream->delayed_error = 0;
87 QUEUE_INIT(&stream->write_queue);
88 QUEUE_INIT(&stream->write_completed_queue);
89 stream->write_queue_size = 0;
91 if (loop->emfile_fd == -1) {
92 err = uv__open_cloexec("/dev/null", O_RDONLY);
94 /* In the rare case that "/dev/null" isn't mounted open "/"
97 err = uv__open_cloexec("/", O_RDONLY);
99 loop->emfile_fd = err;
102 #if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
103 stream->select = NULL;
104 #endif /* defined(__APPLE_) */
106 uv__io_init(&stream->io_watcher, uv__stream_io, -1);
110 static void uv__stream_osx_interrupt_select(uv_stream_t* stream) {
111 #if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
112 /* Notify select() thread about state change */
113 uv__stream_select_t* s;
120 /* Interrupt select() loop
121 * NOTE: fake_fd and int_fd are socketpair(), thus writing to one will
122 * emit read event on other side
125 r = write(s->fake_fd, "x", 1);
126 while (r == -1 && errno == EINTR);
129 #else /* !defined(__APPLE__) */
130 /* No-op on any other platform */
131 #endif /* !defined(__APPLE__) */
135 #if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
136 static void uv__stream_osx_select(void* arg) {
138 uv__stream_select_t* s;
155 /* Terminate on semaphore */
156 if (uv_sem_trywait(&s->close_sem) == 0)
159 /* Watch fd using select(2) */
160 memset(s->sread, 0, s->sread_sz);
161 memset(s->swrite, 0, s->swrite_sz);
163 if (uv__io_active(&stream->io_watcher, POLLIN))
164 FD_SET(fd, s->sread);
165 if (uv__io_active(&stream->io_watcher, POLLOUT))
166 FD_SET(fd, s->swrite);
167 FD_SET(s->int_fd, s->sread);
169 /* Wait indefinitely for fd events */
170 r = select(max_fd + 1, s->sread, s->swrite, NULL, NULL);
175 /* XXX: Possible?! */
179 /* Ignore timeouts */
183 /* Empty socketpair's buffer in case of interruption */
184 if (FD_ISSET(s->int_fd, s->sread))
186 r = read(s->int_fd, buf, sizeof(buf));
188 if (r == sizeof(buf))
194 if (errno == EAGAIN || errno == EWOULDBLOCK)
205 if (FD_ISSET(fd, s->sread))
207 if (FD_ISSET(fd, s->swrite))
210 assert(events != 0 || FD_ISSET(s->int_fd, s->sread));
212 ACCESS_ONCE(int, s->events) = events;
214 uv_async_send(&s->async);
215 uv_sem_wait(&s->async_sem);
217 /* Should be processed at this stage */
218 assert((s->events == 0) || (stream->flags & UV_HANDLE_CLOSING));
224 static void uv__stream_osx_select_cb(uv_async_t* handle) {
225 uv__stream_select_t* s;
229 s = container_of(handle, uv__stream_select_t, async);
232 /* Get and reset stream's events */
234 ACCESS_ONCE(int, s->events) = 0;
237 assert(events == (events & (POLLIN | POLLOUT)));
239 /* Invoke callback on event-loop */
240 if ((events & POLLIN) && uv__io_active(&stream->io_watcher, POLLIN))
241 uv__stream_io(stream->loop, &stream->io_watcher, POLLIN);
243 if ((events & POLLOUT) && uv__io_active(&stream->io_watcher, POLLOUT))
244 uv__stream_io(stream->loop, &stream->io_watcher, POLLOUT);
246 if (stream->flags & UV_HANDLE_CLOSING)
249 /* NOTE: It is important to do it here, otherwise `select()` might be called
250 * before the actual `uv__read()`, leading to the blocking syscall
252 uv_sem_post(&s->async_sem);
256 static void uv__stream_osx_cb_close(uv_handle_t* async) {
257 uv__stream_select_t* s;
259 s = container_of(async, uv__stream_select_t, async);
264 int uv__stream_try_select(uv_stream_t* stream, int* fd) {
266 * kqueue doesn't work with some files from /dev mount on osx.
267 * select(2) in separate thread for those fds
270 struct kevent filter[1];
271 struct kevent events[1];
272 struct timespec timeout;
273 uv__stream_select_t* s;
285 perror("(libuv) kqueue()");
286 return UV__ERR(errno);
289 EV_SET(&filter[0], *fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, 0);
291 /* Use small timeout, because we only want to capture EINVALs */
296 ret = kevent(kq, filter, 1, events, 1, &timeout);
297 while (ret == -1 && errno == EINTR);
302 return UV__ERR(errno);
304 if (ret == 0 || (events[0].flags & EV_ERROR) == 0 || events[0].data != EINVAL)
307 /* At this point we definitely know that this fd won't work with kqueue */
310 * Create fds for io watcher and to interrupt the select() loop.
311 * NOTE: do it ahead of malloc below to allocate enough space for fd_sets
313 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds))
314 return UV__ERR(errno);
320 sread_sz = ROUND_UP(max_fd + 1, sizeof(uint32_t) * NBBY) / NBBY;
321 swrite_sz = sread_sz;
323 s = uv__malloc(sizeof(*s) + sread_sz + swrite_sz);
331 s->sread = (fd_set*) ((char*) s + sizeof(*s));
332 s->sread_sz = sread_sz;
333 s->swrite = (fd_set*) ((char*) s->sread + sread_sz);
334 s->swrite_sz = swrite_sz;
336 err = uv_async_init(stream->loop, &s->async, uv__stream_osx_select_cb);
338 goto failed_async_init;
340 s->async.flags |= UV_HANDLE_INTERNAL;
341 uv__handle_unref(&s->async);
343 err = uv_sem_init(&s->close_sem, 0);
345 goto failed_close_sem_init;
347 err = uv_sem_init(&s->async_sem, 0);
349 goto failed_async_sem_init;
359 err = uv_thread_create(&s->thread, uv__stream_osx_select, stream);
361 goto failed_thread_create;
365 failed_thread_create:
367 stream->select = NULL;
370 uv_sem_destroy(&s->async_sem);
372 failed_async_sem_init:
373 uv_sem_destroy(&s->close_sem);
375 failed_close_sem_init:
378 uv_close((uv_handle_t*) &s->async, uv__stream_osx_cb_close);
390 #endif /* defined(__APPLE__) */
393 int uv__stream_open(uv_stream_t* stream, int fd, int flags) {
394 #if defined(__APPLE__)
398 if (!(stream->io_watcher.fd == -1 || stream->io_watcher.fd == fd))
402 stream->flags |= flags;
404 if (stream->type == UV_TCP) {
405 if ((stream->flags & UV_HANDLE_TCP_NODELAY) && uv__tcp_nodelay(fd, 1))
406 return UV__ERR(errno);
408 /* TODO Use delay the user passed in. */
409 if ((stream->flags & UV_HANDLE_TCP_KEEPALIVE) &&
410 uv__tcp_keepalive(fd, 1, 60)) {
411 return UV__ERR(errno);
415 #if defined(__APPLE__)
417 if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &enable, sizeof(enable)) &&
420 return UV__ERR(errno);
424 stream->io_watcher.fd = fd;
430 void uv__stream_flush_write_queue(uv_stream_t* stream, int error) {
433 while (!QUEUE_EMPTY(&stream->write_queue)) {
434 q = QUEUE_HEAD(&stream->write_queue);
437 req = QUEUE_DATA(q, uv_write_t, queue);
440 QUEUE_INSERT_TAIL(&stream->write_completed_queue, &req->queue);
445 void uv__stream_destroy(uv_stream_t* stream) {
446 assert(!uv__io_active(&stream->io_watcher, POLLIN | POLLOUT));
447 assert(stream->flags & UV_HANDLE_CLOSED);
449 if (stream->connect_req) {
450 uv__req_unregister(stream->loop, stream->connect_req);
451 stream->connect_req->cb(stream->connect_req, UV_ECANCELED);
452 stream->connect_req = NULL;
455 uv__stream_flush_write_queue(stream, UV_ECANCELED);
456 uv__write_callbacks(stream);
459 assert(stream->write_queue_size == 0);
463 /* Implements a best effort approach to mitigating accept() EMFILE errors.
464 * We have a spare file descriptor stashed away that we close to get below
465 * the EMFILE limit. Next, we accept all pending connections and close them
466 * immediately to signal the clients that we're overloaded - and we are, but
467 * we still keep on trucking.
469 * There is one caveat: it's not reliable in a multi-threaded environment.
470 * The file descriptor limit is per process. Our party trick fails if another
471 * thread opens a file or creates a socket in the time window between us
472 * calling close() and accept().
474 static int uv__emfile_trick(uv_loop_t* loop, int accept_fd) {
478 if (loop->emfile_fd == -1)
481 uv__close(loop->emfile_fd);
482 loop->emfile_fd = -1;
485 err = uv__accept(accept_fd);
488 } while (err >= 0 || err == UV_EINTR);
490 emfile_fd = uv__open_cloexec("/", O_RDONLY);
492 loop->emfile_fd = emfile_fd;
498 #if defined(UV_HAVE_KQUEUE)
499 # define UV_DEC_BACKLOG(w) w->rcount--;
501 # define UV_DEC_BACKLOG(w) /* no-op */
502 #endif /* defined(UV_HAVE_KQUEUE) */
505 void uv__server_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
509 stream = container_of(w, uv_stream_t, io_watcher);
510 assert(events & POLLIN);
511 assert(stream->accepted_fd == -1);
512 assert(!(stream->flags & UV_HANDLE_CLOSING));
514 uv__io_start(stream->loop, &stream->io_watcher, POLLIN);
516 /* connection_cb can close the server socket while we're
517 * in the loop so check it on each iteration.
519 while (uv__stream_fd(stream) != -1) {
520 assert(stream->accepted_fd == -1);
522 #if defined(UV_HAVE_KQUEUE)
525 #endif /* defined(UV_HAVE_KQUEUE) */
527 err = uv__accept(uv__stream_fd(stream));
529 if (err == UV_EAGAIN || err == UV__ERR(EWOULDBLOCK))
530 return; /* Not an error. */
532 if (err == UV_ECONNABORTED)
533 continue; /* Ignore. Nothing we can do about that. */
535 if (err == UV_EMFILE || err == UV_ENFILE) {
536 err = uv__emfile_trick(loop, uv__stream_fd(stream));
537 if (err == UV_EAGAIN || err == UV__ERR(EWOULDBLOCK))
541 stream->connection_cb(stream, err);
546 stream->accepted_fd = err;
547 stream->connection_cb(stream, 0);
549 if (stream->accepted_fd != -1) {
550 /* The user hasn't yet accepted called uv_accept() */
551 uv__io_stop(loop, &stream->io_watcher, POLLIN);
555 if (stream->type == UV_TCP &&
556 (stream->flags & UV_HANDLE_TCP_SINGLE_ACCEPT)) {
557 /* Give other processes a chance to accept connections. */
558 struct timespec timeout = { 0, 1 };
559 nanosleep(&timeout, NULL);
565 #undef UV_DEC_BACKLOG
568 int uv_accept(uv_stream_t* server, uv_stream_t* client) {
571 assert(server->loop == client->loop);
573 if (server->accepted_fd == -1)
576 switch (client->type) {
579 err = uv__stream_open(client,
581 UV_HANDLE_READABLE | UV_HANDLE_WRITABLE);
583 /* TODO handle error */
584 uv__close(server->accepted_fd);
590 err = uv_udp_open((uv_udp_t*) client, server->accepted_fd);
592 uv__close(server->accepted_fd);
601 client->flags |= UV_HANDLE_BOUND;
604 /* Process queued fds */
605 if (server->queued_fds != NULL) {
606 uv__stream_queued_fds_t* queued_fds;
608 queued_fds = server->queued_fds;
611 server->accepted_fd = queued_fds->fds[0];
614 assert(queued_fds->offset > 0);
615 if (--queued_fds->offset == 0) {
616 uv__free(queued_fds);
617 server->queued_fds = NULL;
620 memmove(queued_fds->fds,
622 queued_fds->offset * sizeof(*queued_fds->fds));
625 server->accepted_fd = -1;
627 uv__io_start(server->loop, &server->io_watcher, POLLIN);
633 int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb) {
635 if (uv__is_closing(stream)) {
638 switch (stream->type) {
640 err = uv__tcp_listen((uv_tcp_t*)stream, backlog, cb);
644 err = uv__pipe_listen((uv_pipe_t*)stream, backlog, cb);
652 uv__handle_start(stream);
658 static void uv__drain(uv_stream_t* stream) {
662 assert(QUEUE_EMPTY(&stream->write_queue));
663 if (!(stream->flags & UV_HANDLE_CLOSING)) {
664 uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
665 uv__stream_osx_interrupt_select(stream);
668 if (!(stream->flags & UV_HANDLE_SHUTTING))
671 req = stream->shutdown_req;
674 if ((stream->flags & UV_HANDLE_CLOSING) ||
675 !(stream->flags & UV_HANDLE_SHUT)) {
676 stream->shutdown_req = NULL;
677 stream->flags &= ~UV_HANDLE_SHUTTING;
678 uv__req_unregister(stream->loop, req);
681 if (stream->flags & UV_HANDLE_CLOSING)
682 /* The user destroyed the stream before we got to do the shutdown. */
684 else if (shutdown(uv__stream_fd(stream), SHUT_WR))
685 err = UV__ERR(errno);
687 stream->flags |= UV_HANDLE_SHUT;
695 static ssize_t uv__writev(int fd, struct iovec* vec, size_t n) {
697 return write(fd, vec->iov_base, vec->iov_len);
699 return writev(fd, vec, n);
703 static size_t uv__write_req_size(uv_write_t* req) {
706 assert(req->bufs != NULL);
707 size = uv__count_bufs(req->bufs + req->write_index,
708 req->nbufs - req->write_index);
709 assert(req->handle->write_queue_size >= size);
715 /* Returns 1 if all write request data has been written, or 0 if there is still
716 * more data to write.
718 * Note: the return value only says something about the *current* request.
719 * There may still be other write requests sitting in the queue.
721 static int uv__write_req_update(uv_stream_t* stream,
727 assert(n <= stream->write_queue_size);
728 stream->write_queue_size -= n;
730 buf = req->bufs + req->write_index;
733 len = n < buf->len ? n : buf->len;
736 buf += (buf->len == 0); /* Advance to next buffer if this one is empty. */
740 req->write_index = buf - req->bufs;
742 return req->write_index == req->nbufs;
746 static void uv__write_req_finish(uv_write_t* req) {
747 uv_stream_t* stream = req->handle;
749 /* Pop the req off tcp->write_queue. */
750 QUEUE_REMOVE(&req->queue);
752 /* Only free when there was no error. On error, we touch up write_queue_size
753 * right before making the callback. The reason we don't do that right away
754 * is that a write_queue_size > 0 is our only way to signal to the user that
755 * they should stop writing - which they should if we got an error. Something
756 * to revisit in future revisions of the libuv API.
758 if (req->error == 0) {
759 if (req->bufs != req->bufsml)
764 /* Add it to the write_completed_queue where it will have its
765 * callback called in the near future.
767 QUEUE_INSERT_TAIL(&stream->write_completed_queue, &req->queue);
768 uv__io_feed(stream->loop, &stream->io_watcher);
772 static int uv__handle_fd(uv_handle_t* handle) {
773 switch (handle->type) {
776 return ((uv_stream_t*) handle)->io_watcher.fd;
779 return ((uv_udp_t*) handle)->io_watcher.fd;
786 static int uv__try_write(uv_stream_t* stream,
787 const uv_buf_t bufs[],
789 uv_stream_t* send_handle) {
796 * Cast to iovec. We had to have our own uv_buf_t instead of iovec
797 * because Windows's WSABUF is not an iovec.
799 iov = (struct iovec*) bufs;
802 iovmax = uv__getiovmax();
804 /* Limit iov count to avoid EINVALs from writev() */
809 * Now do the actual writev. Note that we've been updating the pointers
810 * inside the iov each time we write. So there is no need to offset it.
812 if (send_handle != NULL) {
815 struct cmsghdr *cmsg;
818 struct cmsghdr alias;
821 if (uv__is_closing(send_handle))
824 fd_to_send = uv__handle_fd((uv_handle_t*) send_handle);
826 memset(&scratch, 0, sizeof(scratch));
828 assert(fd_to_send >= 0);
833 msg.msg_iovlen = iovcnt;
836 msg.msg_control = &scratch.alias;
837 msg.msg_controllen = CMSG_SPACE(sizeof(fd_to_send));
839 cmsg = CMSG_FIRSTHDR(&msg);
840 cmsg->cmsg_level = SOL_SOCKET;
841 cmsg->cmsg_type = SCM_RIGHTS;
842 cmsg->cmsg_len = CMSG_LEN(sizeof(fd_to_send));
844 /* silence aliasing warning */
846 void* pv = CMSG_DATA(cmsg);
852 n = sendmsg(uv__stream_fd(stream), &msg, 0);
853 while (n == -1 && errno == EINTR);
856 n = uv__writev(uv__stream_fd(stream), iov, iovcnt);
857 while (n == -1 && errno == EINTR);
863 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == ENOBUFS)
867 /* macOS versions 10.10 and 10.15 - and presumbaly 10.11 to 10.14, too -
868 * have a bug where a race condition causes the kernel to return EPROTOTYPE
869 * because the socket isn't fully constructed. It's probably the result of
870 * the peer closing the connection and that is why libuv translates it to
871 * ECONNRESET. Previously, libuv retried until the EPROTOTYPE error went
872 * away but some VPN software causes the same behavior except the error is
873 * permanent, not transient, turning the retry mechanism into an infinite
874 * loop. See https://github.com/libuv/libuv/pull/482.
876 if (errno == EPROTOTYPE)
877 return UV_ECONNRESET;
878 #endif /* __APPLE__ */
880 return UV__ERR(errno);
883 static void uv__write(uv_stream_t* stream) {
888 assert(uv__stream_fd(stream) >= 0);
891 if (QUEUE_EMPTY(&stream->write_queue))
894 q = QUEUE_HEAD(&stream->write_queue);
895 req = QUEUE_DATA(q, uv_write_t, queue);
896 assert(req->handle == stream);
898 n = uv__try_write(stream,
899 &(req->bufs[req->write_index]),
900 req->nbufs - req->write_index,
903 /* Ensure the handle isn't sent again in case this is a partial write. */
905 req->send_handle = NULL;
906 if (uv__write_req_update(stream, req, n)) {
907 uv__write_req_finish(req);
908 return; /* TODO(bnoordhuis) Start trying to write the next request. */
910 } else if (n != UV_EAGAIN)
913 /* If this is a blocking stream, try again. */
914 if (stream->flags & UV_HANDLE_BLOCKING_WRITES)
917 /* We're not done. */
918 uv__io_start(stream->loop, &stream->io_watcher, POLLOUT);
920 /* Notify select() thread about state change */
921 uv__stream_osx_interrupt_select(stream);
927 uv__write_req_finish(req);
928 uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
929 uv__stream_osx_interrupt_select(stream);
933 static void uv__write_callbacks(uv_stream_t* stream) {
938 if (QUEUE_EMPTY(&stream->write_completed_queue))
941 QUEUE_MOVE(&stream->write_completed_queue, &pq);
943 while (!QUEUE_EMPTY(&pq)) {
944 /* Pop a req off write_completed_queue. */
946 req = QUEUE_DATA(q, uv_write_t, queue);
948 uv__req_unregister(stream->loop, req);
950 if (req->bufs != NULL) {
951 stream->write_queue_size -= uv__write_req_size(req);
952 if (req->bufs != req->bufsml)
957 /* NOTE: call callback AFTER freeing the request data. */
959 req->cb(req, req->error);
964 static void uv__stream_eof(uv_stream_t* stream, const uv_buf_t* buf) {
965 stream->flags |= UV_HANDLE_READ_EOF;
966 stream->flags &= ~UV_HANDLE_READING;
967 uv__io_stop(stream->loop, &stream->io_watcher, POLLIN);
968 uv__handle_stop(stream);
969 uv__stream_osx_interrupt_select(stream);
970 stream->read_cb(stream, UV_EOF, buf);
974 static int uv__stream_queue_fd(uv_stream_t* stream, int fd) {
975 uv__stream_queued_fds_t* queued_fds;
976 unsigned int queue_size;
978 queued_fds = stream->queued_fds;
979 if (queued_fds == NULL) {
981 queued_fds = uv__malloc((queue_size - 1) * sizeof(*queued_fds->fds) +
982 sizeof(*queued_fds));
983 if (queued_fds == NULL)
985 queued_fds->size = queue_size;
986 queued_fds->offset = 0;
987 stream->queued_fds = queued_fds;
990 } else if (queued_fds->size == queued_fds->offset) {
991 queue_size = queued_fds->size + 8;
992 queued_fds = uv__realloc(queued_fds,
993 (queue_size - 1) * sizeof(*queued_fds->fds) +
994 sizeof(*queued_fds));
997 * Allocation failure, report back.
998 * NOTE: if it is fatal - sockets will be closed in uv__stream_close
1000 if (queued_fds == NULL)
1002 queued_fds->size = queue_size;
1003 stream->queued_fds = queued_fds;
1006 /* Put fd in a queue */
1007 queued_fds->fds[queued_fds->offset++] = fd;
1013 #if defined(__PASE__)
1014 /* on IBMi PASE the control message length can not exceed 256. */
1015 # define UV__CMSG_FD_COUNT 60
1017 # define UV__CMSG_FD_COUNT 64
1019 #define UV__CMSG_FD_SIZE (UV__CMSG_FD_COUNT * sizeof(int))
1022 static int uv__stream_recv_cmsg(uv_stream_t* stream, struct msghdr* msg) {
1023 struct cmsghdr* cmsg;
1025 for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg)) {
1034 if (cmsg->cmsg_type != SCM_RIGHTS) {
1035 fprintf(stderr, "ignoring non-SCM_RIGHTS ancillary data: %d\n",
1040 /* silence aliasing warning */
1041 pv = CMSG_DATA(cmsg);
1044 /* Count available fds */
1045 start = (char*) cmsg;
1046 end = (char*) cmsg + cmsg->cmsg_len;
1048 while (start + CMSG_LEN(count * sizeof(*pi)) < end)
1050 assert(start + CMSG_LEN(count * sizeof(*pi)) == end);
1052 for (i = 0; i < count; i++) {
1053 /* Already has accepted fd, queue now */
1054 if (stream->accepted_fd != -1) {
1055 err = uv__stream_queue_fd(stream, pi[i]);
1058 for (; i < count; i++)
1063 stream->accepted_fd = pi[i];
1073 # pragma clang diagnostic push
1074 # pragma clang diagnostic ignored "-Wgnu-folding-constant"
1075 # pragma clang diagnostic ignored "-Wvla-extension"
1078 static void uv__read(uv_stream_t* stream) {
1082 char cmsg_space[CMSG_SPACE(UV__CMSG_FD_SIZE)];
1087 stream->flags &= ~UV_HANDLE_READ_PARTIAL;
1089 /* Prevent loop starvation when the data comes in as fast as (or faster than)
1090 * we can read it. XXX Need to rearm fd if we switch to edge-triggered I/O.
1094 is_ipc = stream->type == UV_NAMED_PIPE && ((uv_pipe_t*) stream)->ipc;
1096 /* XXX: Maybe instead of having UV_HANDLE_READING we just test if
1097 * tcp->read_cb is NULL or not?
1099 while (stream->read_cb
1100 && (stream->flags & UV_HANDLE_READING)
1102 assert(stream->alloc_cb != NULL);
1104 buf = uv_buf_init(NULL, 0);
1105 stream->alloc_cb((uv_handle_t*)stream, 64 * 1024, &buf);
1106 if (buf.base == NULL || buf.len == 0) {
1107 /* User indicates it can't or won't handle the read. */
1108 stream->read_cb(stream, UV_ENOBUFS, &buf);
1112 assert(buf.base != NULL);
1113 assert(uv__stream_fd(stream) >= 0);
1117 nread = read(uv__stream_fd(stream), buf.base, buf.len);
1119 while (nread < 0 && errno == EINTR);
1121 /* ipc uses recvmsg */
1123 msg.msg_iov = (struct iovec*) &buf;
1125 msg.msg_name = NULL;
1126 msg.msg_namelen = 0;
1127 /* Set up to receive a descriptor even if one isn't in the message */
1128 msg.msg_controllen = sizeof(cmsg_space);
1129 msg.msg_control = cmsg_space;
1132 nread = uv__recvmsg(uv__stream_fd(stream), &msg, 0);
1134 while (nread < 0 && errno == EINTR);
1139 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1140 /* Wait for the next one. */
1141 if (stream->flags & UV_HANDLE_READING) {
1142 uv__io_start(stream->loop, &stream->io_watcher, POLLIN);
1143 uv__stream_osx_interrupt_select(stream);
1145 stream->read_cb(stream, 0, &buf);
1146 #if defined(__CYGWIN__) || defined(__MSYS__)
1147 } else if (errno == ECONNRESET && stream->type == UV_NAMED_PIPE) {
1148 uv__stream_eof(stream, &buf);
1152 /* Error. User should call uv_close(). */
1153 stream->flags &= ~(UV_HANDLE_READABLE | UV_HANDLE_WRITABLE);
1154 stream->read_cb(stream, UV__ERR(errno), &buf);
1155 if (stream->flags & UV_HANDLE_READING) {
1156 stream->flags &= ~UV_HANDLE_READING;
1157 uv__io_stop(stream->loop, &stream->io_watcher, POLLIN);
1158 uv__handle_stop(stream);
1159 uv__stream_osx_interrupt_select(stream);
1163 } else if (nread == 0) {
1164 uv__stream_eof(stream, &buf);
1167 /* Successful read */
1168 ssize_t buflen = buf.len;
1171 err = uv__stream_recv_cmsg(stream, &msg);
1173 stream->read_cb(stream, err, &buf);
1178 #if defined(__MVS__)
1179 if (is_ipc && msg.msg_controllen > 0) {
1187 msg.msg_iov = (struct iovec*) &blankbuf;
1190 nread = uv__recvmsg(uv__stream_fd(stream), &msg, 0);
1191 err = uv__stream_recv_cmsg(stream, &msg);
1193 stream->read_cb(stream, err, &buf);
1197 } while (nread == 0 && msg.msg_controllen > 0);
1201 stream->read_cb(stream, nread, &buf);
1203 /* Return if we didn't fill the buffer, there is no more data to read. */
1204 if (nread < buflen) {
1205 stream->flags |= UV_HANDLE_READ_PARTIAL;
1214 # pragma clang diagnostic pop
1217 #undef UV__CMSG_FD_COUNT
1218 #undef UV__CMSG_FD_SIZE
1221 int uv_shutdown(uv_shutdown_t* req, uv_stream_t* stream, uv_shutdown_cb cb) {
1222 assert(stream->type == UV_TCP ||
1223 stream->type == UV_TTY ||
1224 stream->type == UV_NAMED_PIPE);
1226 if (!(stream->flags & UV_HANDLE_WRITABLE) ||
1227 stream->flags & UV_HANDLE_SHUT ||
1228 stream->flags & UV_HANDLE_SHUTTING ||
1229 uv__is_closing(stream)) {
1233 assert(uv__stream_fd(stream) >= 0);
1235 /* Initialize request. The `shutdown(2)` call will always be deferred until
1236 * `uv__drain`, just before the callback is run. */
1237 uv__req_init(stream->loop, req, UV_SHUTDOWN);
1238 req->handle = stream;
1240 stream->shutdown_req = req;
1241 stream->flags |= UV_HANDLE_SHUTTING;
1242 stream->flags &= ~UV_HANDLE_WRITABLE;
1244 if (QUEUE_EMPTY(&stream->write_queue))
1245 uv__io_feed(stream->loop, &stream->io_watcher);
1251 static void uv__stream_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
1252 uv_stream_t* stream;
1254 stream = container_of(w, uv_stream_t, io_watcher);
1256 assert(stream->type == UV_TCP ||
1257 stream->type == UV_NAMED_PIPE ||
1258 stream->type == UV_TTY);
1259 assert(!(stream->flags & UV_HANDLE_CLOSING));
1261 if (stream->connect_req) {
1262 uv__stream_connect(stream);
1266 assert(uv__stream_fd(stream) >= 0);
1268 /* Ignore POLLHUP here. Even if it's set, there may still be data to read. */
1269 if (events & (POLLIN | POLLERR | POLLHUP))
1272 if (uv__stream_fd(stream) == -1)
1273 return; /* read_cb closed stream. */
1275 /* Short-circuit iff POLLHUP is set, the user is still interested in read
1276 * events and uv__read() reported a partial read but not EOF. If the EOF
1277 * flag is set, uv__read() called read_cb with err=UV_EOF and we don't
1278 * have to do anything. If the partial read flag is not set, we can't
1279 * report the EOF yet because there is still data to read.
1281 if ((events & POLLHUP) &&
1282 (stream->flags & UV_HANDLE_READING) &&
1283 (stream->flags & UV_HANDLE_READ_PARTIAL) &&
1284 !(stream->flags & UV_HANDLE_READ_EOF)) {
1285 uv_buf_t buf = { NULL, 0 };
1286 uv__stream_eof(stream, &buf);
1289 if (uv__stream_fd(stream) == -1)
1290 return; /* read_cb closed stream. */
1292 if (events & (POLLOUT | POLLERR | POLLHUP)) {
1294 uv__write_callbacks(stream);
1296 /* Write queue drained. */
1297 if (QUEUE_EMPTY(&stream->write_queue))
1304 * We get called here from directly following a call to connect(2).
1305 * In order to determine if we've errored out or succeeded must call
1308 static void uv__stream_connect(uv_stream_t* stream) {
1310 uv_connect_t* req = stream->connect_req;
1311 socklen_t errorsize = sizeof(int);
1313 assert(stream->type == UV_TCP || stream->type == UV_NAMED_PIPE);
1316 if (stream->delayed_error) {
1317 /* To smooth over the differences between unixes errors that
1318 * were reported synchronously on the first connect can be delayed
1319 * until the next tick--which is now.
1321 error = stream->delayed_error;
1322 stream->delayed_error = 0;
1324 /* Normal situation: we need to get the socket error from the kernel. */
1325 assert(uv__stream_fd(stream) >= 0);
1326 getsockopt(uv__stream_fd(stream),
1331 error = UV__ERR(error);
1334 if (error == UV__ERR(EINPROGRESS))
1337 stream->connect_req = NULL;
1338 uv__req_unregister(stream->loop, req);
1340 if (error < 0 || QUEUE_EMPTY(&stream->write_queue)) {
1341 uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
1345 req->cb(req, error);
1347 if (uv__stream_fd(stream) == -1)
1351 uv__stream_flush_write_queue(stream, UV_ECANCELED);
1352 uv__write_callbacks(stream);
1357 static int uv__check_before_write(uv_stream_t* stream,
1359 uv_stream_t* send_handle) {
1361 assert((stream->type == UV_TCP ||
1362 stream->type == UV_NAMED_PIPE ||
1363 stream->type == UV_TTY) &&
1364 "uv_write (unix) does not yet support other types of streams");
1366 if (uv__stream_fd(stream) < 0)
1369 if (!(stream->flags & UV_HANDLE_WRITABLE))
1372 if (send_handle != NULL) {
1373 if (stream->type != UV_NAMED_PIPE || !((uv_pipe_t*)stream)->ipc)
1376 /* XXX We abuse uv_write2() to send over UDP handles to child processes.
1377 * Don't call uv__stream_fd() on those handles, it's a macro that on OS X
1378 * evaluates to a function that operates on a uv_stream_t with a couple of
1379 * OS X specific fields. On other Unices it does (handle)->io_watcher.fd,
1380 * which works but only by accident.
1382 if (uv__handle_fd((uv_handle_t*) send_handle) < 0)
1385 #if defined(__CYGWIN__) || defined(__MSYS__)
1386 /* Cygwin recvmsg always sets msg_controllen to zero, so we cannot send it.
1387 See https://github.com/mirror/newlib-cygwin/blob/86fc4bf0/winsup/cygwin/fhandler_socket.cc#L1736-L1743 */
1395 int uv_write2(uv_write_t* req,
1396 uv_stream_t* stream,
1397 const uv_buf_t bufs[],
1399 uv_stream_t* send_handle,
1404 err = uv__check_before_write(stream, nbufs, send_handle);
1408 /* It's legal for write_queue_size > 0 even when the write_queue is empty;
1409 * it means there are error-state requests in the write_completed_queue that
1410 * will touch up write_queue_size later, see also uv__write_req_finish().
1411 * We could check that write_queue is empty instead but that implies making
1412 * a write() syscall when we know that the handle is in error mode.
1414 empty_queue = (stream->write_queue_size == 0);
1416 /* Initialize the req */
1417 uv__req_init(stream->loop, req, UV_WRITE);
1419 req->handle = stream;
1421 req->send_handle = send_handle;
1422 QUEUE_INIT(&req->queue);
1424 req->bufs = req->bufsml;
1425 if (nbufs > ARRAY_SIZE(req->bufsml))
1426 req->bufs = uv__malloc(nbufs * sizeof(bufs[0]));
1428 if (req->bufs == NULL)
1431 memcpy(req->bufs, bufs, nbufs * sizeof(bufs[0]));
1433 req->write_index = 0;
1434 stream->write_queue_size += uv__count_bufs(bufs, nbufs);
1436 /* Append the request to write_queue. */
1437 QUEUE_INSERT_TAIL(&stream->write_queue, &req->queue);
1439 /* If the queue was empty when this function began, we should attempt to
1440 * do the write immediately. Otherwise start the write_watcher and wait
1441 * for the fd to become writable.
1443 if (stream->connect_req) {
1444 /* Still connecting, do nothing. */
1446 else if (empty_queue) {
1451 * blocking streams should never have anything in the queue.
1452 * if this assert fires then somehow the blocking stream isn't being
1453 * sufficiently flushed in uv__write.
1455 assert(!(stream->flags & UV_HANDLE_BLOCKING_WRITES));
1456 uv__io_start(stream->loop, &stream->io_watcher, POLLOUT);
1457 uv__stream_osx_interrupt_select(stream);
1464 /* The buffers to be written must remain valid until the callback is called.
1465 * This is not required for the uv_buf_t array.
1467 int uv_write(uv_write_t* req,
1468 uv_stream_t* handle,
1469 const uv_buf_t bufs[],
1472 return uv_write2(req, handle, bufs, nbufs, NULL, cb);
1476 int uv_try_write(uv_stream_t* stream,
1477 const uv_buf_t bufs[],
1478 unsigned int nbufs) {
1479 return uv_try_write2(stream, bufs, nbufs, NULL);
1483 int uv_try_write2(uv_stream_t* stream,
1484 const uv_buf_t bufs[],
1486 uv_stream_t* send_handle) {
1489 /* Connecting or already writing some data */
1490 if (stream->connect_req != NULL || stream->write_queue_size != 0)
1493 err = uv__check_before_write(stream, nbufs, NULL);
1497 return uv__try_write(stream, bufs, nbufs, send_handle);
1501 int uv__read_start(uv_stream_t* stream,
1502 uv_alloc_cb alloc_cb,
1503 uv_read_cb read_cb) {
1504 assert(stream->type == UV_TCP || stream->type == UV_NAMED_PIPE ||
1505 stream->type == UV_TTY);
1507 /* The UV_HANDLE_READING flag is irrelevant of the state of the stream - it
1508 * just expresses the desired state of the user. */
1509 stream->flags |= UV_HANDLE_READING;
1510 stream->flags &= ~UV_HANDLE_READ_EOF;
1512 /* TODO: try to do the read inline? */
1513 assert(uv__stream_fd(stream) >= 0);
1516 stream->read_cb = read_cb;
1517 stream->alloc_cb = alloc_cb;
1519 uv__io_start(stream->loop, &stream->io_watcher, POLLIN);
1520 uv__handle_start(stream);
1521 uv__stream_osx_interrupt_select(stream);
1527 int uv_read_stop(uv_stream_t* stream) {
1528 if (!(stream->flags & UV_HANDLE_READING))
1531 stream->flags &= ~UV_HANDLE_READING;
1532 uv__io_stop(stream->loop, &stream->io_watcher, POLLIN);
1533 uv__handle_stop(stream);
1534 uv__stream_osx_interrupt_select(stream);
1536 stream->read_cb = NULL;
1537 stream->alloc_cb = NULL;
1542 int uv_is_readable(const uv_stream_t* stream) {
1543 return !!(stream->flags & UV_HANDLE_READABLE);
1547 int uv_is_writable(const uv_stream_t* stream) {
1548 return !!(stream->flags & UV_HANDLE_WRITABLE);
1552 #if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
1553 int uv___stream_fd(const uv_stream_t* handle) {
1554 const uv__stream_select_t* s;
1556 assert(handle->type == UV_TCP ||
1557 handle->type == UV_TTY ||
1558 handle->type == UV_NAMED_PIPE);
1564 return handle->io_watcher.fd;
1566 #endif /* defined(__APPLE__) */
1569 void uv__stream_close(uv_stream_t* handle) {
1571 uv__stream_queued_fds_t* queued_fds;
1573 #if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
1574 /* Terminate select loop first */
1575 if (handle->select != NULL) {
1576 uv__stream_select_t* s;
1580 uv_sem_post(&s->close_sem);
1581 uv_sem_post(&s->async_sem);
1582 uv__stream_osx_interrupt_select(handle);
1583 uv_thread_join(&s->thread);
1584 uv_sem_destroy(&s->close_sem);
1585 uv_sem_destroy(&s->async_sem);
1586 uv__close(s->fake_fd);
1587 uv__close(s->int_fd);
1588 uv_close((uv_handle_t*) &s->async, uv__stream_osx_cb_close);
1590 handle->select = NULL;
1592 #endif /* defined(__APPLE__) */
1594 uv__io_close(handle->loop, &handle->io_watcher);
1595 uv_read_stop(handle);
1596 uv__handle_stop(handle);
1597 handle->flags &= ~(UV_HANDLE_READABLE | UV_HANDLE_WRITABLE);
1599 if (handle->io_watcher.fd != -1) {
1600 /* Don't close stdio file descriptors. Nothing good comes from it. */
1601 if (handle->io_watcher.fd > STDERR_FILENO)
1602 uv__close(handle->io_watcher.fd);
1603 handle->io_watcher.fd = -1;
1606 if (handle->accepted_fd != -1) {
1607 uv__close(handle->accepted_fd);
1608 handle->accepted_fd = -1;
1611 /* Close all queued fds */
1612 if (handle->queued_fds != NULL) {
1613 queued_fds = handle->queued_fds;
1614 for (i = 0; i < queued_fds->offset; i++)
1615 uv__close(queued_fds->fds[i]);
1616 uv__free(handle->queued_fds);
1617 handle->queued_fds = NULL;
1620 assert(!uv__io_active(&handle->io_watcher, POLLIN | POLLOUT));
1624 int uv_stream_set_blocking(uv_stream_t* handle, int blocking) {
1625 /* Don't need to check the file descriptor, uv__nonblock()
1626 * will fail with EBADF if it's not valid.
1628 return uv__nonblock(uv__stream_fd(handle), !blocking);