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> /* O_CLOEXEC */
34 #include <sys/ioctl.h>
35 #include <sys/socket.h>
36 #include <sys/un.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39 #include <limits.h> /* INT_MAX, PATH_MAX, IOV_MAX */
40 #include <sys/uio.h> /* writev */
41 #include <sys/resource.h> /* getrusage */
42 #include <pwd.h>
43 #include <sched.h>
44 #include <sys/utsname.h>
45 #include <sys/time.h>
46
47 #ifdef __sun
48 # include <sys/filio.h>
49 # include <sys/types.h>
50 # include <sys/wait.h>
51 #endif
52
53 #if defined(__APPLE__)
54 # include <sys/filio.h>
55 # endif /* defined(__APPLE__) */
56
57
58 #if defined(__APPLE__) && !TARGET_OS_IPHONE
59 # include <crt_externs.h>
60 # include <mach-o/dyld.h> /* _NSGetExecutablePath */
61 # define environ (*_NSGetEnviron())
62 #else /* defined(__APPLE__) && !TARGET_OS_IPHONE */
63 extern char** environ;
64 #endif /* !(defined(__APPLE__) && !TARGET_OS_IPHONE) */
65
66
67 #if defined(__DragonFly__) || \
68 defined(__FreeBSD__) || \
69 defined(__FreeBSD_kernel__) || \
70 defined(__NetBSD__) || \
71 defined(__OpenBSD__)
72 # include <sys/sysctl.h>
73 # include <sys/filio.h>
74 # include <sys/wait.h>
75 # if defined(__FreeBSD__)
76 # define uv__accept4 accept4
77 # endif
78 # if defined(__NetBSD__)
79 # define uv__accept4(a, b, c, d) paccept((a), (b), (c), NULL, (d))
80 # endif
81 #endif
82
83 #if defined(__FreeBSD__)
84 # include <sys/param.h>
85 # include <sys/cpuset.h>
86 #endif
87
88 #if defined(__MVS__)
89 #include <sys/ioctl.h>
90 #endif
91
92 #if defined(__linux__)
93 # include <sys/syscall.h>
94 # define uv__accept4 accept4
95 #endif
96
97 static int uv__run_pending(uv_loop_t* loop);
98
99 /* Verify that uv_buf_t is ABI-compatible with struct iovec. */
100 STATIC_ASSERT(sizeof(uv_buf_t) == sizeof(struct iovec));
101 STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->base) ==
102 sizeof(((struct iovec*) 0)->iov_base));
103 STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->len) ==
104 sizeof(((struct iovec*) 0)->iov_len));
105 STATIC_ASSERT(offsetof(uv_buf_t, base) == offsetof(struct iovec, iov_base));
106 STATIC_ASSERT(offsetof(uv_buf_t, len) == offsetof(struct iovec, iov_len));
107
108
uv_hrtime(void)109 uint64_t uv_hrtime(void) {
110 return uv__hrtime(UV_CLOCK_PRECISE);
111 }
112
113
uv_close(uv_handle_t * handle,uv_close_cb close_cb)114 void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
115 assert(!uv__is_closing(handle));
116
117 handle->flags |= UV_HANDLE_CLOSING;
118 handle->close_cb = close_cb;
119
120 switch (handle->type) {
121 case UV_NAMED_PIPE:
122 uv__pipe_close((uv_pipe_t*)handle);
123 break;
124
125 case UV_TTY:
126 uv__stream_close((uv_stream_t*)handle);
127 break;
128
129 case UV_TCP:
130 uv__tcp_close((uv_tcp_t*)handle);
131 break;
132
133 case UV_UDP:
134 uv__udp_close((uv_udp_t*)handle);
135 break;
136
137 case UV_PREPARE:
138 uv__prepare_close((uv_prepare_t*)handle);
139 break;
140
141 case UV_CHECK:
142 uv__check_close((uv_check_t*)handle);
143 break;
144
145 case UV_IDLE:
146 uv__idle_close((uv_idle_t*)handle);
147 break;
148
149 case UV_ASYNC:
150 uv__async_close((uv_async_t*)handle);
151 break;
152
153 case UV_TIMER:
154 uv__timer_close((uv_timer_t*)handle);
155 break;
156
157 case UV_PROCESS:
158 uv__process_close((uv_process_t*)handle);
159 break;
160
161 case UV_FS_EVENT:
162 uv__fs_event_close((uv_fs_event_t*)handle);
163 break;
164
165 case UV_POLL:
166 uv__poll_close((uv_poll_t*)handle);
167 break;
168
169 case UV_FS_POLL:
170 uv__fs_poll_close((uv_fs_poll_t*)handle);
171 /* Poll handles use file system requests, and one of them may still be
172 * running. The poll code will call uv__make_close_pending() for us. */
173 return;
174
175 case UV_SIGNAL:
176 uv__signal_close((uv_signal_t*) handle);
177 break;
178
179 default:
180 assert(0);
181 }
182
183 uv__make_close_pending(handle);
184 }
185
uv__socket_sockopt(uv_handle_t * handle,int optname,int * value)186 int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value) {
187 int r;
188 int fd;
189 socklen_t len;
190
191 if (handle == NULL || value == NULL)
192 return UV_EINVAL;
193
194 if (handle->type == UV_TCP || handle->type == UV_NAMED_PIPE)
195 fd = uv__stream_fd((uv_stream_t*) handle);
196 else if (handle->type == UV_UDP)
197 fd = ((uv_udp_t *) handle)->io_watcher.fd;
198 else
199 return UV_ENOTSUP;
200
201 len = sizeof(*value);
202
203 if (*value == 0)
204 r = getsockopt(fd, SOL_SOCKET, optname, value, &len);
205 else
206 r = setsockopt(fd, SOL_SOCKET, optname, (const void*) value, len);
207
208 if (r < 0)
209 return UV__ERR(errno);
210
211 return 0;
212 }
213
uv__make_close_pending(uv_handle_t * handle)214 void uv__make_close_pending(uv_handle_t* handle) {
215 assert(handle->flags & UV_HANDLE_CLOSING);
216 assert(!(handle->flags & UV_HANDLE_CLOSED));
217 handle->next_closing = handle->loop->closing_handles;
218 handle->loop->closing_handles = handle;
219 }
220
uv__getiovmax(void)221 int uv__getiovmax(void) {
222 #if defined(IOV_MAX)
223 return IOV_MAX;
224 #elif defined(_SC_IOV_MAX)
225 static int iovmax_cached = -1;
226 int iovmax;
227
228 iovmax = uv__load_relaxed(&iovmax_cached);
229 if (iovmax != -1)
230 return iovmax;
231
232 /* On some embedded devices (arm-linux-uclibc based ip camera),
233 * sysconf(_SC_IOV_MAX) can not get the correct value. The return
234 * value is -1 and the errno is EINPROGRESS. Degrade the value to 1.
235 */
236 iovmax = sysconf(_SC_IOV_MAX);
237 if (iovmax == -1)
238 iovmax = 1;
239
240 uv__store_relaxed(&iovmax_cached, iovmax);
241
242 return iovmax;
243 #else
244 return 1024;
245 #endif
246 }
247
248
uv__finish_close(uv_handle_t * handle)249 static void uv__finish_close(uv_handle_t* handle) {
250 uv_signal_t* sh;
251
252 /* Note: while the handle is in the UV_HANDLE_CLOSING state now, it's still
253 * possible for it to be active in the sense that uv__is_active() returns
254 * true.
255 *
256 * A good example is when the user calls uv_shutdown(), immediately followed
257 * by uv_close(). The handle is considered active at this point because the
258 * completion of the shutdown req is still pending.
259 */
260 assert(handle->flags & UV_HANDLE_CLOSING);
261 assert(!(handle->flags & UV_HANDLE_CLOSED));
262 handle->flags |= UV_HANDLE_CLOSED;
263
264 switch (handle->type) {
265 case UV_PREPARE:
266 case UV_CHECK:
267 case UV_IDLE:
268 case UV_ASYNC:
269 case UV_TIMER:
270 case UV_PROCESS:
271 case UV_FS_EVENT:
272 case UV_FS_POLL:
273 case UV_POLL:
274 break;
275
276 case UV_SIGNAL:
277 /* If there are any caught signals "trapped" in the signal pipe,
278 * we can't call the close callback yet. Reinserting the handle
279 * into the closing queue makes the event loop spin but that's
280 * okay because we only need to deliver the pending events.
281 */
282 sh = (uv_signal_t*) handle;
283 if (sh->caught_signals > sh->dispatched_signals) {
284 handle->flags ^= UV_HANDLE_CLOSED;
285 uv__make_close_pending(handle); /* Back into the queue. */
286 return;
287 }
288 break;
289
290 case UV_NAMED_PIPE:
291 case UV_TCP:
292 case UV_TTY:
293 uv__stream_destroy((uv_stream_t*)handle);
294 break;
295
296 case UV_UDP:
297 uv__udp_finish_close((uv_udp_t*)handle);
298 break;
299
300 default:
301 assert(0);
302 break;
303 }
304
305 uv__handle_unref(handle);
306 QUEUE_REMOVE(&handle->handle_queue);
307
308 if (handle->close_cb) {
309 handle->close_cb(handle);
310 }
311 }
312
313
uv__run_closing_handles(uv_loop_t * loop)314 static void uv__run_closing_handles(uv_loop_t* loop) {
315 uv_handle_t* p;
316 uv_handle_t* q;
317
318 p = loop->closing_handles;
319 loop->closing_handles = NULL;
320
321 while (p) {
322 q = p->next_closing;
323 uv__finish_close(p);
324 p = q;
325 }
326 }
327
328
uv_is_closing(const uv_handle_t * handle)329 int uv_is_closing(const uv_handle_t* handle) {
330 return uv__is_closing(handle);
331 }
332
333
uv_backend_fd(const uv_loop_t * loop)334 int uv_backend_fd(const uv_loop_t* loop) {
335 return loop->backend_fd;
336 }
337
338
uv_backend_timeout(const uv_loop_t * loop)339 int uv_backend_timeout(const uv_loop_t* loop) {
340 if (loop->stop_flag != 0)
341 return 0;
342
343 if (!uv__has_active_handles(loop) && !uv__has_active_reqs(loop))
344 return 0;
345
346 if (!QUEUE_EMPTY(&loop->idle_handles))
347 return 0;
348
349 if (!QUEUE_EMPTY(&loop->pending_queue))
350 return 0;
351
352 if (loop->closing_handles)
353 return 0;
354
355 return uv__next_timeout(loop);
356 }
357
358
uv__loop_alive(const uv_loop_t * loop)359 static int uv__loop_alive(const uv_loop_t* loop) {
360 return uv__has_active_handles(loop) ||
361 uv__has_active_reqs(loop) ||
362 loop->closing_handles != NULL;
363 }
364
365
uv_loop_alive(const uv_loop_t * loop)366 int uv_loop_alive(const uv_loop_t* loop) {
367 return uv__loop_alive(loop);
368 }
369
370
uv_run(uv_loop_t * loop,uv_run_mode mode)371 int uv_run(uv_loop_t* loop, uv_run_mode mode) {
372 int timeout;
373 int r;
374 int ran_pending;
375
376 r = uv__loop_alive(loop);
377 if (!r)
378 uv__update_time(loop);
379
380 while (r != 0 && loop->stop_flag == 0) {
381 uv__update_time(loop);
382 uv__run_timers(loop);
383 ran_pending = uv__run_pending(loop);
384 uv__run_idle(loop);
385 uv__run_prepare(loop);
386
387 timeout = 0;
388 if ((mode == UV_RUN_ONCE && !ran_pending) || mode == UV_RUN_DEFAULT)
389 timeout = uv_backend_timeout(loop);
390
391 uv__io_poll(loop, timeout);
392
393 /* Run one final update on the provider_idle_time in case uv__io_poll
394 * returned because the timeout expired, but no events were received. This
395 * call will be ignored if the provider_entry_time was either never set (if
396 * the timeout == 0) or was already updated b/c an event was received.
397 */
398 uv__metrics_update_idle_time(loop);
399
400 uv__run_check(loop);
401 uv__run_closing_handles(loop);
402
403 if (mode == UV_RUN_ONCE) {
404 /* UV_RUN_ONCE implies forward progress: at least one callback must have
405 * been invoked when it returns. uv__io_poll() can return without doing
406 * I/O (meaning: no callbacks) when its timeout expires - which means we
407 * have pending timers that satisfy the forward progress constraint.
408 *
409 * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
410 * the check.
411 */
412 uv__update_time(loop);
413 uv__run_timers(loop);
414 }
415
416 r = uv__loop_alive(loop);
417 if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
418 break;
419 }
420
421 /* The if statement lets gcc compile it to a conditional store. Avoids
422 * dirtying a cache line.
423 */
424 if (loop->stop_flag != 0)
425 loop->stop_flag = 0;
426
427 return r;
428 }
429
430
uv_update_time(uv_loop_t * loop)431 void uv_update_time(uv_loop_t* loop) {
432 uv__update_time(loop);
433 }
434
435
uv_is_active(const uv_handle_t * handle)436 int uv_is_active(const uv_handle_t* handle) {
437 return uv__is_active(handle);
438 }
439
440
441 /* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
uv__socket(int domain,int type,int protocol)442 int uv__socket(int domain, int type, int protocol) {
443 int sockfd;
444 int err;
445
446 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
447 sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
448 if (sockfd != -1)
449 return sockfd;
450
451 if (errno != EINVAL)
452 return UV__ERR(errno);
453 #endif
454
455 sockfd = socket(domain, type, protocol);
456 if (sockfd == -1)
457 return UV__ERR(errno);
458
459 err = uv__nonblock(sockfd, 1);
460 if (err == 0)
461 err = uv__cloexec(sockfd, 1);
462
463 if (err) {
464 uv__close(sockfd);
465 return err;
466 }
467
468 #if defined(SO_NOSIGPIPE)
469 {
470 int on = 1;
471 setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
472 }
473 #endif
474
475 return sockfd;
476 }
477
478 /* get a file pointer to a file in read-only and close-on-exec mode */
uv__open_file(const char * path)479 FILE* uv__open_file(const char* path) {
480 int fd;
481 FILE* fp;
482
483 fd = uv__open_cloexec(path, O_RDONLY);
484 if (fd < 0)
485 return NULL;
486
487 fp = fdopen(fd, "r");
488 if (fp == NULL)
489 uv__close(fd);
490
491 return fp;
492 }
493
494
uv__accept(int sockfd)495 int uv__accept(int sockfd) {
496 int peerfd;
497 int err;
498
499 (void) &err;
500 assert(sockfd >= 0);
501
502 do
503 #ifdef uv__accept4
504 peerfd = uv__accept4(sockfd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
505 #else
506 peerfd = accept(sockfd, NULL, NULL);
507 #endif
508 while (peerfd == -1 && errno == EINTR);
509
510 if (peerfd == -1)
511 return UV__ERR(errno);
512
513 #ifndef uv__accept4
514 err = uv__cloexec(peerfd, 1);
515 if (err == 0)
516 err = uv__nonblock(peerfd, 1);
517
518 if (err != 0) {
519 uv__close(peerfd);
520 return err;
521 }
522 #endif
523
524 return peerfd;
525 }
526
527
528 /* close() on macos has the "interesting" quirk that it fails with EINTR
529 * without closing the file descriptor when a thread is in the cancel state.
530 * That's why libuv calls close$NOCANCEL() instead.
531 *
532 * glibc on linux has a similar issue: close() is a cancellation point and
533 * will unwind the thread when it's in the cancel state. Work around that
534 * by making the system call directly. Musl libc is unaffected.
535 */
uv__close_nocancel(int fd)536 int uv__close_nocancel(int fd) {
537 #if defined(__APPLE__)
538 #pragma GCC diagnostic push
539 #pragma GCC diagnostic ignored "-Wdollar-in-identifier-extension"
540 #if defined(__LP64__) || TARGET_OS_IPHONE
541 extern int close$NOCANCEL(int);
542 return close$NOCANCEL(fd);
543 #else
544 extern int close$NOCANCEL$UNIX2003(int);
545 return close$NOCANCEL$UNIX2003(fd);
546 #endif
547 #pragma GCC diagnostic pop
548 #elif defined(__linux__)
549 return syscall(SYS_close, fd);
550 #else
551 return close(fd);
552 #endif
553 }
554
555
uv__close_nocheckstdio(int fd)556 int uv__close_nocheckstdio(int fd) {
557 int saved_errno;
558 int rc;
559
560 assert(fd > -1); /* Catch uninitialized io_watcher.fd bugs. */
561
562 saved_errno = errno;
563 rc = uv__close_nocancel(fd);
564 if (rc == -1) {
565 rc = UV__ERR(errno);
566 if (rc == UV_EINTR || rc == UV__ERR(EINPROGRESS))
567 rc = 0; /* The close is in progress, not an error. */
568 errno = saved_errno;
569 }
570
571 return rc;
572 }
573
574
uv__close(int fd)575 int uv__close(int fd) {
576 assert(fd > STDERR_FILENO); /* Catch stdio close bugs. */
577 #if defined(__MVS__)
578 SAVE_ERRNO(epoll_file_close(fd));
579 #endif
580 return uv__close_nocheckstdio(fd);
581 }
582
583
uv__nonblock_ioctl(int fd,int set)584 int uv__nonblock_ioctl(int fd, int set) {
585 int r;
586
587 do
588 r = ioctl(fd, FIONBIO, &set);
589 while (r == -1 && errno == EINTR);
590
591 if (r)
592 return UV__ERR(errno);
593
594 return 0;
595 }
596
597
598 #if !defined(__hpux) && !defined(__CYGWIN__) && !defined(__MSYS__) && !defined(__HAIKU__)
uv__cloexec_ioctl(int fd,int set)599 int uv__cloexec_ioctl(int fd, int set) {
600 int r;
601
602 do
603 r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
604 while (r == -1 && errno == EINTR);
605
606 if (r)
607 return UV__ERR(errno);
608
609 return 0;
610 }
611 #endif
612
613
uv__nonblock_fcntl(int fd,int set)614 int uv__nonblock_fcntl(int fd, int set) {
615 int flags;
616 int r;
617
618 do
619 r = fcntl(fd, F_GETFL);
620 while (r == -1 && errno == EINTR);
621
622 if (r == -1)
623 return UV__ERR(errno);
624
625 /* Bail out now if already set/clear. */
626 if (!!(r & O_NONBLOCK) == !!set)
627 return 0;
628
629 if (set)
630 flags = r | O_NONBLOCK;
631 else
632 flags = r & ~O_NONBLOCK;
633
634 do
635 r = fcntl(fd, F_SETFL, flags);
636 while (r == -1 && errno == EINTR);
637
638 if (r)
639 return UV__ERR(errno);
640
641 return 0;
642 }
643
644
uv__cloexec_fcntl(int fd,int set)645 int uv__cloexec_fcntl(int fd, int set) {
646 int flags;
647 int r;
648
649 do
650 r = fcntl(fd, F_GETFD);
651 while (r == -1 && errno == EINTR);
652
653 if (r == -1)
654 return UV__ERR(errno);
655
656 /* Bail out now if already set/clear. */
657 if (!!(r & FD_CLOEXEC) == !!set)
658 return 0;
659
660 if (set)
661 flags = r | FD_CLOEXEC;
662 else
663 flags = r & ~FD_CLOEXEC;
664
665 do
666 r = fcntl(fd, F_SETFD, flags);
667 while (r == -1 && errno == EINTR);
668
669 if (r)
670 return UV__ERR(errno);
671
672 return 0;
673 }
674
675
uv__recvmsg(int fd,struct msghdr * msg,int flags)676 ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) {
677 struct cmsghdr* cmsg;
678 ssize_t rc;
679 int* pfd;
680 int* end;
681 #if defined(__linux__)
682 static int no_msg_cmsg_cloexec;
683 if (0 == uv__load_relaxed(&no_msg_cmsg_cloexec)) {
684 rc = recvmsg(fd, msg, flags | 0x40000000); /* MSG_CMSG_CLOEXEC */
685 if (rc != -1)
686 return rc;
687 if (errno != EINVAL)
688 return UV__ERR(errno);
689 rc = recvmsg(fd, msg, flags);
690 if (rc == -1)
691 return UV__ERR(errno);
692 uv__store_relaxed(&no_msg_cmsg_cloexec, 1);
693 } else {
694 rc = recvmsg(fd, msg, flags);
695 }
696 #else
697 rc = recvmsg(fd, msg, flags);
698 #endif
699 if (rc == -1)
700 return UV__ERR(errno);
701 if (msg->msg_controllen == 0)
702 return rc;
703 for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg))
704 if (cmsg->cmsg_type == SCM_RIGHTS)
705 for (pfd = (int*) CMSG_DATA(cmsg),
706 end = (int*) ((char*) cmsg + cmsg->cmsg_len);
707 pfd < end;
708 pfd += 1)
709 uv__cloexec(*pfd, 1);
710 return rc;
711 }
712
713
uv_cwd(char * buffer,size_t * size)714 int uv_cwd(char* buffer, size_t* size) {
715 char scratch[1 + UV__PATH_MAX];
716
717 if (buffer == NULL || size == NULL)
718 return UV_EINVAL;
719
720 /* Try to read directly into the user's buffer first... */
721 if (getcwd(buffer, *size) != NULL)
722 goto fixup;
723
724 if (errno != ERANGE)
725 return UV__ERR(errno);
726
727 /* ...or into scratch space if the user's buffer is too small
728 * so we can report how much space to provide on the next try.
729 */
730 if (getcwd(scratch, sizeof(scratch)) == NULL)
731 return UV__ERR(errno);
732
733 buffer = scratch;
734
735 fixup:
736
737 *size = strlen(buffer);
738
739 if (*size > 1 && buffer[*size - 1] == '/') {
740 *size -= 1;
741 buffer[*size] = '\0';
742 }
743
744 if (buffer == scratch) {
745 *size += 1;
746 return UV_ENOBUFS;
747 }
748
749 return 0;
750 }
751
752
uv_chdir(const char * dir)753 int uv_chdir(const char* dir) {
754 if (chdir(dir))
755 return UV__ERR(errno);
756
757 return 0;
758 }
759
760
uv_disable_stdio_inheritance(void)761 void uv_disable_stdio_inheritance(void) {
762 int fd;
763
764 /* Set the CLOEXEC flag on all open descriptors. Unconditionally try the
765 * first 16 file descriptors. After that, bail out after the first error.
766 */
767 for (fd = 0; ; fd++)
768 if (uv__cloexec(fd, 1) && fd > 15)
769 break;
770 }
771
772
uv_fileno(const uv_handle_t * handle,uv_os_fd_t * fd)773 int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd) {
774 int fd_out;
775
776 switch (handle->type) {
777 case UV_TCP:
778 case UV_NAMED_PIPE:
779 case UV_TTY:
780 fd_out = uv__stream_fd((uv_stream_t*) handle);
781 break;
782
783 case UV_UDP:
784 fd_out = ((uv_udp_t *) handle)->io_watcher.fd;
785 break;
786
787 case UV_POLL:
788 fd_out = ((uv_poll_t *) handle)->io_watcher.fd;
789 break;
790
791 default:
792 return UV_EINVAL;
793 }
794
795 if (uv__is_closing(handle) || fd_out == -1)
796 return UV_EBADF;
797
798 *fd = fd_out;
799 return 0;
800 }
801
802
uv__run_pending(uv_loop_t * loop)803 static int uv__run_pending(uv_loop_t* loop) {
804 QUEUE* q;
805 QUEUE pq;
806 uv__io_t* w;
807
808 if (QUEUE_EMPTY(&loop->pending_queue))
809 return 0;
810
811 QUEUE_MOVE(&loop->pending_queue, &pq);
812
813 while (!QUEUE_EMPTY(&pq)) {
814 q = QUEUE_HEAD(&pq);
815 QUEUE_REMOVE(q);
816 QUEUE_INIT(q);
817 w = QUEUE_DATA(q, uv__io_t, pending_queue);
818 w->cb(loop, w, POLLOUT);
819 }
820
821 return 1;
822 }
823
824
next_power_of_two(unsigned int val)825 static unsigned int next_power_of_two(unsigned int val) {
826 val -= 1;
827 val |= val >> 1;
828 val |= val >> 2;
829 val |= val >> 4;
830 val |= val >> 8;
831 val |= val >> 16;
832 val += 1;
833 return val;
834 }
835
maybe_resize(uv_loop_t * loop,unsigned int len)836 static void maybe_resize(uv_loop_t* loop, unsigned int len) {
837 uv__io_t** watchers;
838 void* fake_watcher_list;
839 void* fake_watcher_count;
840 unsigned int nwatchers;
841 unsigned int i;
842
843 if (len <= loop->nwatchers)
844 return;
845
846 /* Preserve fake watcher list and count at the end of the watchers */
847 if (loop->watchers != NULL) {
848 fake_watcher_list = loop->watchers[loop->nwatchers];
849 fake_watcher_count = loop->watchers[loop->nwatchers + 1];
850 } else {
851 fake_watcher_list = NULL;
852 fake_watcher_count = NULL;
853 }
854
855 nwatchers = next_power_of_two(len + 2) - 2;
856 watchers = uv__reallocf(loop->watchers,
857 (nwatchers + 2) * sizeof(loop->watchers[0]));
858
859 if (watchers == NULL)
860 abort();
861 for (i = loop->nwatchers; i < nwatchers; i++)
862 watchers[i] = NULL;
863 watchers[nwatchers] = fake_watcher_list;
864 watchers[nwatchers + 1] = fake_watcher_count;
865
866 loop->watchers = watchers;
867 loop->nwatchers = nwatchers;
868 }
869
870
uv__io_init(uv__io_t * w,uv__io_cb cb,int fd)871 void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
872 assert(cb != NULL);
873 assert(fd >= -1);
874 QUEUE_INIT(&w->pending_queue);
875 QUEUE_INIT(&w->watcher_queue);
876 w->cb = cb;
877 w->fd = fd;
878 w->events = 0;
879 w->pevents = 0;
880
881 #if defined(UV_HAVE_KQUEUE)
882 w->rcount = 0;
883 w->wcount = 0;
884 #endif /* defined(UV_HAVE_KQUEUE) */
885 }
886
887
uv__io_start(uv_loop_t * loop,uv__io_t * w,unsigned int events)888 void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
889 assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI)));
890 assert(0 != events);
891 assert(w->fd >= 0);
892 assert(w->fd < INT_MAX);
893
894 w->pevents |= events;
895 maybe_resize(loop, w->fd + 1);
896
897 #if !defined(__sun)
898 /* The event ports backend needs to rearm all file descriptors on each and
899 * every tick of the event loop but the other backends allow us to
900 * short-circuit here if the event mask is unchanged.
901 */
902 if (w->events == w->pevents)
903 return;
904 #endif
905
906 if (QUEUE_EMPTY(&w->watcher_queue))
907 QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
908
909 if (loop->watchers[w->fd] == NULL) {
910 loop->watchers[w->fd] = w;
911 loop->nfds++;
912 }
913 }
914
915
uv__io_stop(uv_loop_t * loop,uv__io_t * w,unsigned int events)916 void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
917 assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI)));
918 assert(0 != events);
919
920 if (w->fd == -1)
921 return;
922
923 assert(w->fd >= 0);
924
925 /* Happens when uv__io_stop() is called on a handle that was never started. */
926 if ((unsigned) w->fd >= loop->nwatchers)
927 return;
928
929 w->pevents &= ~events;
930
931 if (w->pevents == 0) {
932 QUEUE_REMOVE(&w->watcher_queue);
933 QUEUE_INIT(&w->watcher_queue);
934
935 if (loop->watchers[w->fd] != NULL) {
936 assert(loop->watchers[w->fd] == w);
937 assert(loop->nfds > 0);
938 loop->watchers[w->fd] = NULL;
939 loop->nfds--;
940 w->events = 0;
941 }
942 }
943 else if (QUEUE_EMPTY(&w->watcher_queue))
944 QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
945 }
946
947
uv__io_close(uv_loop_t * loop,uv__io_t * w)948 void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
949 uv__io_stop(loop, w, POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI);
950 QUEUE_REMOVE(&w->pending_queue);
951
952 /* Remove stale events for this file descriptor */
953 if (w->fd != -1)
954 uv__platform_invalidate_fd(loop, w->fd);
955 }
956
957
uv__io_feed(uv_loop_t * loop,uv__io_t * w)958 void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
959 if (QUEUE_EMPTY(&w->pending_queue))
960 QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue);
961 }
962
963
uv__io_active(const uv__io_t * w,unsigned int events)964 int uv__io_active(const uv__io_t* w, unsigned int events) {
965 assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI)));
966 assert(0 != events);
967 return 0 != (w->pevents & events);
968 }
969
970
uv__fd_exists(uv_loop_t * loop,int fd)971 int uv__fd_exists(uv_loop_t* loop, int fd) {
972 return (unsigned) fd < loop->nwatchers && loop->watchers[fd] != NULL;
973 }
974
975
uv_getrusage(uv_rusage_t * rusage)976 int uv_getrusage(uv_rusage_t* rusage) {
977 struct rusage usage;
978
979 if (getrusage(RUSAGE_SELF, &usage))
980 return UV__ERR(errno);
981
982 rusage->ru_utime.tv_sec = usage.ru_utime.tv_sec;
983 rusage->ru_utime.tv_usec = usage.ru_utime.tv_usec;
984
985 rusage->ru_stime.tv_sec = usage.ru_stime.tv_sec;
986 rusage->ru_stime.tv_usec = usage.ru_stime.tv_usec;
987
988 #if !defined(__MVS__) && !defined(__HAIKU__)
989 rusage->ru_maxrss = usage.ru_maxrss;
990 rusage->ru_ixrss = usage.ru_ixrss;
991 rusage->ru_idrss = usage.ru_idrss;
992 rusage->ru_isrss = usage.ru_isrss;
993 rusage->ru_minflt = usage.ru_minflt;
994 rusage->ru_majflt = usage.ru_majflt;
995 rusage->ru_nswap = usage.ru_nswap;
996 rusage->ru_inblock = usage.ru_inblock;
997 rusage->ru_oublock = usage.ru_oublock;
998 rusage->ru_msgsnd = usage.ru_msgsnd;
999 rusage->ru_msgrcv = usage.ru_msgrcv;
1000 rusage->ru_nsignals = usage.ru_nsignals;
1001 rusage->ru_nvcsw = usage.ru_nvcsw;
1002 rusage->ru_nivcsw = usage.ru_nivcsw;
1003 #endif
1004
1005 return 0;
1006 }
1007
1008
uv__open_cloexec(const char * path,int flags)1009 int uv__open_cloexec(const char* path, int flags) {
1010 #if defined(O_CLOEXEC)
1011 int fd;
1012
1013 fd = open(path, flags | O_CLOEXEC);
1014 if (fd == -1)
1015 return UV__ERR(errno);
1016
1017 return fd;
1018 #else /* O_CLOEXEC */
1019 int err;
1020 int fd;
1021
1022 fd = open(path, flags);
1023 if (fd == -1)
1024 return UV__ERR(errno);
1025
1026 err = uv__cloexec(fd, 1);
1027 if (err) {
1028 uv__close(fd);
1029 return err;
1030 }
1031
1032 return fd;
1033 #endif /* O_CLOEXEC */
1034 }
1035
1036
uv__dup2_cloexec(int oldfd,int newfd)1037 int uv__dup2_cloexec(int oldfd, int newfd) {
1038 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__linux__)
1039 int r;
1040
1041 r = dup3(oldfd, newfd, O_CLOEXEC);
1042 if (r == -1)
1043 return UV__ERR(errno);
1044
1045 return r;
1046 #else
1047 int err;
1048 int r;
1049
1050 r = dup2(oldfd, newfd); /* Never retry. */
1051 if (r == -1)
1052 return UV__ERR(errno);
1053
1054 err = uv__cloexec(newfd, 1);
1055 if (err != 0) {
1056 uv__close(newfd);
1057 return err;
1058 }
1059
1060 return r;
1061 #endif
1062 }
1063
1064
uv_os_homedir(char * buffer,size_t * size)1065 int uv_os_homedir(char* buffer, size_t* size) {
1066 uv_passwd_t pwd;
1067 size_t len;
1068 int r;
1069
1070 /* Check if the HOME environment variable is set first. The task of
1071 performing input validation on buffer and size is taken care of by
1072 uv_os_getenv(). */
1073 r = uv_os_getenv("HOME", buffer, size);
1074
1075 if (r != UV_ENOENT)
1076 return r;
1077
1078 /* HOME is not set, so call uv__getpwuid_r() */
1079 r = uv__getpwuid_r(&pwd);
1080
1081 if (r != 0) {
1082 return r;
1083 }
1084
1085 len = strlen(pwd.homedir);
1086
1087 if (len >= *size) {
1088 *size = len + 1;
1089 uv_os_free_passwd(&pwd);
1090 return UV_ENOBUFS;
1091 }
1092
1093 memcpy(buffer, pwd.homedir, len + 1);
1094 *size = len;
1095 uv_os_free_passwd(&pwd);
1096
1097 return 0;
1098 }
1099
1100
uv_os_tmpdir(char * buffer,size_t * size)1101 int uv_os_tmpdir(char* buffer, size_t* size) {
1102 const char* buf;
1103 size_t len;
1104
1105 if (buffer == NULL || size == NULL || *size == 0)
1106 return UV_EINVAL;
1107
1108 #define CHECK_ENV_VAR(name) \
1109 do { \
1110 buf = getenv(name); \
1111 if (buf != NULL) \
1112 goto return_buffer; \
1113 } \
1114 while (0)
1115
1116 /* Check the TMPDIR, TMP, TEMP, and TEMPDIR environment variables in order */
1117 CHECK_ENV_VAR("TMPDIR");
1118 CHECK_ENV_VAR("TMP");
1119 CHECK_ENV_VAR("TEMP");
1120 CHECK_ENV_VAR("TEMPDIR");
1121
1122 #undef CHECK_ENV_VAR
1123
1124 /* No temp environment variables defined */
1125 #if defined(__ANDROID__)
1126 buf = "/data/local/tmp";
1127 #else
1128 buf = "/tmp";
1129 #endif
1130
1131 return_buffer:
1132 len = strlen(buf);
1133
1134 if (len >= *size) {
1135 *size = len + 1;
1136 return UV_ENOBUFS;
1137 }
1138
1139 /* The returned directory should not have a trailing slash. */
1140 if (len > 1 && buf[len - 1] == '/') {
1141 len--;
1142 }
1143
1144 memcpy(buffer, buf, len + 1);
1145 buffer[len] = '\0';
1146 *size = len;
1147
1148 return 0;
1149 }
1150
1151
uv__getpwuid_r(uv_passwd_t * pwd)1152 int uv__getpwuid_r(uv_passwd_t* pwd) {
1153 struct passwd pw;
1154 struct passwd* result;
1155 char* buf;
1156 uid_t uid;
1157 size_t bufsize;
1158 size_t name_size;
1159 size_t homedir_size;
1160 size_t shell_size;
1161 long initsize;
1162 int r;
1163
1164 if (pwd == NULL)
1165 return UV_EINVAL;
1166
1167 initsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1168
1169 if (initsize <= 0)
1170 bufsize = 4096;
1171 else
1172 bufsize = (size_t) initsize;
1173
1174 uid = geteuid();
1175 buf = NULL;
1176
1177 for (;;) {
1178 uv__free(buf);
1179 buf = uv__malloc(bufsize);
1180
1181 if (buf == NULL)
1182 return UV_ENOMEM;
1183
1184 r = getpwuid_r(uid, &pw, buf, bufsize, &result);
1185
1186 if (r != ERANGE)
1187 break;
1188
1189 bufsize *= 2;
1190 }
1191
1192 if (r != 0) {
1193 uv__free(buf);
1194 return -r;
1195 }
1196
1197 if (result == NULL) {
1198 uv__free(buf);
1199 return UV_ENOENT;
1200 }
1201
1202 /* Allocate memory for the username, shell, and home directory */
1203 name_size = strlen(pw.pw_name) + 1;
1204 homedir_size = strlen(pw.pw_dir) + 1;
1205 shell_size = strlen(pw.pw_shell) + 1;
1206 pwd->username = uv__malloc(name_size + homedir_size + shell_size);
1207
1208 if (pwd->username == NULL) {
1209 uv__free(buf);
1210 return UV_ENOMEM;
1211 }
1212
1213 /* Copy the username */
1214 memcpy(pwd->username, pw.pw_name, name_size);
1215
1216 /* Copy the home directory */
1217 pwd->homedir = pwd->username + name_size;
1218 memcpy(pwd->homedir, pw.pw_dir, homedir_size);
1219
1220 /* Copy the shell */
1221 pwd->shell = pwd->homedir + homedir_size;
1222 memcpy(pwd->shell, pw.pw_shell, shell_size);
1223
1224 /* Copy the uid and gid */
1225 pwd->uid = pw.pw_uid;
1226 pwd->gid = pw.pw_gid;
1227
1228 uv__free(buf);
1229
1230 return 0;
1231 }
1232
1233
uv_os_free_passwd(uv_passwd_t * pwd)1234 void uv_os_free_passwd(uv_passwd_t* pwd) {
1235 if (pwd == NULL)
1236 return;
1237
1238 /*
1239 The memory for name, shell, and homedir are allocated in a single
1240 uv__malloc() call. The base of the pointer is stored in pwd->username, so
1241 that is the field that needs to be freed.
1242 */
1243 uv__free(pwd->username);
1244 pwd->username = NULL;
1245 pwd->shell = NULL;
1246 pwd->homedir = NULL;
1247 }
1248
1249
uv_os_get_passwd(uv_passwd_t * pwd)1250 int uv_os_get_passwd(uv_passwd_t* pwd) {
1251 return uv__getpwuid_r(pwd);
1252 }
1253
1254
uv_translate_sys_error(int sys_errno)1255 int uv_translate_sys_error(int sys_errno) {
1256 /* If < 0 then it's already a libuv error. */
1257 return sys_errno <= 0 ? sys_errno : -sys_errno;
1258 }
1259
1260
uv_os_environ(uv_env_item_t ** envitems,int * count)1261 int uv_os_environ(uv_env_item_t** envitems, int* count) {
1262 int i, j, cnt;
1263 uv_env_item_t* envitem;
1264
1265 *envitems = NULL;
1266 *count = 0;
1267
1268 for (i = 0; environ[i] != NULL; i++);
1269
1270 *envitems = uv__calloc(i, sizeof(**envitems));
1271
1272 if (*envitems == NULL)
1273 return UV_ENOMEM;
1274
1275 for (j = 0, cnt = 0; j < i; j++) {
1276 char* buf;
1277 char* ptr;
1278
1279 if (environ[j] == NULL)
1280 break;
1281
1282 buf = uv__strdup(environ[j]);
1283 if (buf == NULL)
1284 goto fail;
1285
1286 ptr = strchr(buf, '=');
1287 if (ptr == NULL) {
1288 uv__free(buf);
1289 continue;
1290 }
1291
1292 *ptr = '\0';
1293
1294 envitem = &(*envitems)[cnt];
1295 envitem->name = buf;
1296 envitem->value = ptr + 1;
1297
1298 cnt++;
1299 }
1300
1301 *count = cnt;
1302 return 0;
1303
1304 fail:
1305 for (i = 0; i < cnt; i++) {
1306 envitem = &(*envitems)[cnt];
1307 uv__free(envitem->name);
1308 }
1309 uv__free(*envitems);
1310
1311 *envitems = NULL;
1312 *count = 0;
1313 return UV_ENOMEM;
1314 }
1315
1316
uv_os_getenv(const char * name,char * buffer,size_t * size)1317 int uv_os_getenv(const char* name, char* buffer, size_t* size) {
1318 char* var;
1319 size_t len;
1320
1321 if (name == NULL || buffer == NULL || size == NULL || *size == 0)
1322 return UV_EINVAL;
1323
1324 var = getenv(name);
1325
1326 if (var == NULL)
1327 return UV_ENOENT;
1328
1329 len = strlen(var);
1330
1331 if (len >= *size) {
1332 *size = len + 1;
1333 return UV_ENOBUFS;
1334 }
1335
1336 memcpy(buffer, var, len + 1);
1337 *size = len;
1338
1339 return 0;
1340 }
1341
1342
uv_os_setenv(const char * name,const char * value)1343 int uv_os_setenv(const char* name, const char* value) {
1344 if (name == NULL || value == NULL)
1345 return UV_EINVAL;
1346
1347 if (setenv(name, value, 1) != 0)
1348 return UV__ERR(errno);
1349
1350 return 0;
1351 }
1352
1353
uv_os_unsetenv(const char * name)1354 int uv_os_unsetenv(const char* name) {
1355 if (name == NULL)
1356 return UV_EINVAL;
1357
1358 if (unsetenv(name) != 0)
1359 return UV__ERR(errno);
1360
1361 return 0;
1362 }
1363
1364
uv_os_gethostname(char * buffer,size_t * size)1365 int uv_os_gethostname(char* buffer, size_t* size) {
1366 /*
1367 On some platforms, if the input buffer is not large enough, gethostname()
1368 succeeds, but truncates the result. libuv can detect this and return ENOBUFS
1369 instead by creating a large enough buffer and comparing the hostname length
1370 to the size input.
1371 */
1372 char buf[UV_MAXHOSTNAMESIZE];
1373 size_t len;
1374
1375 if (buffer == NULL || size == NULL || *size == 0)
1376 return UV_EINVAL;
1377
1378 if (gethostname(buf, sizeof(buf)) != 0)
1379 return UV__ERR(errno);
1380
1381 buf[sizeof(buf) - 1] = '\0'; /* Null terminate, just to be safe. */
1382 len = strlen(buf);
1383
1384 if (len >= *size) {
1385 *size = len + 1;
1386 return UV_ENOBUFS;
1387 }
1388
1389 memcpy(buffer, buf, len + 1);
1390 *size = len;
1391 return 0;
1392 }
1393
1394
uv_cpumask_size(void)1395 int uv_cpumask_size(void) {
1396 #if defined(__linux__) || defined(__FreeBSD__)
1397 return CPU_SETSIZE;
1398 #else
1399 return UV_ENOTSUP;
1400 #endif
1401 }
1402
1403
uv_get_osfhandle(int fd)1404 uv_os_fd_t uv_get_osfhandle(int fd) {
1405 return fd;
1406 }
1407
uv_open_osfhandle(uv_os_fd_t os_fd)1408 int uv_open_osfhandle(uv_os_fd_t os_fd) {
1409 return os_fd;
1410 }
1411
uv_os_getpid(void)1412 uv_pid_t uv_os_getpid(void) {
1413 return getpid();
1414 }
1415
1416
uv_os_getppid(void)1417 uv_pid_t uv_os_getppid(void) {
1418 return getppid();
1419 }
1420
1421
uv_os_getpriority(uv_pid_t pid,int * priority)1422 int uv_os_getpriority(uv_pid_t pid, int* priority) {
1423 int r;
1424
1425 if (priority == NULL)
1426 return UV_EINVAL;
1427
1428 errno = 0;
1429 r = getpriority(PRIO_PROCESS, (int) pid);
1430
1431 if (r == -1 && errno != 0)
1432 return UV__ERR(errno);
1433
1434 *priority = r;
1435 return 0;
1436 }
1437
1438
uv_os_setpriority(uv_pid_t pid,int priority)1439 int uv_os_setpriority(uv_pid_t pid, int priority) {
1440 if (priority < UV_PRIORITY_HIGHEST || priority > UV_PRIORITY_LOW)
1441 return UV_EINVAL;
1442
1443 if (setpriority(PRIO_PROCESS, (int) pid, priority) != 0)
1444 return UV__ERR(errno);
1445
1446 return 0;
1447 }
1448
1449
uv_os_uname(uv_utsname_t * buffer)1450 int uv_os_uname(uv_utsname_t* buffer) {
1451 struct utsname buf;
1452 int r;
1453
1454 if (buffer == NULL)
1455 return UV_EINVAL;
1456
1457 if (uname(&buf) == -1) {
1458 r = UV__ERR(errno);
1459 goto error;
1460 }
1461
1462 r = uv__strscpy(buffer->sysname, buf.sysname, sizeof(buffer->sysname));
1463 if (r == UV_E2BIG)
1464 goto error;
1465
1466 #ifdef _AIX
1467 r = snprintf(buffer->release,
1468 sizeof(buffer->release),
1469 "%s.%s",
1470 buf.version,
1471 buf.release);
1472 if (r >= sizeof(buffer->release)) {
1473 r = UV_E2BIG;
1474 goto error;
1475 }
1476 #else
1477 r = uv__strscpy(buffer->release, buf.release, sizeof(buffer->release));
1478 if (r == UV_E2BIG)
1479 goto error;
1480 #endif
1481
1482 r = uv__strscpy(buffer->version, buf.version, sizeof(buffer->version));
1483 if (r == UV_E2BIG)
1484 goto error;
1485
1486 #if defined(_AIX) || defined(__PASE__)
1487 r = uv__strscpy(buffer->machine, "ppc64", sizeof(buffer->machine));
1488 #else
1489 r = uv__strscpy(buffer->machine, buf.machine, sizeof(buffer->machine));
1490 #endif
1491
1492 if (r == UV_E2BIG)
1493 goto error;
1494
1495 return 0;
1496
1497 error:
1498 buffer->sysname[0] = '\0';
1499 buffer->release[0] = '\0';
1500 buffer->version[0] = '\0';
1501 buffer->machine[0] = '\0';
1502 return r;
1503 }
1504
uv__getsockpeername(const uv_handle_t * handle,uv__peersockfunc func,struct sockaddr * name,int * namelen)1505 int uv__getsockpeername(const uv_handle_t* handle,
1506 uv__peersockfunc func,
1507 struct sockaddr* name,
1508 int* namelen) {
1509 socklen_t socklen;
1510 uv_os_fd_t fd;
1511 int r;
1512
1513 r = uv_fileno(handle, &fd);
1514 if (r < 0)
1515 return r;
1516
1517 /* sizeof(socklen_t) != sizeof(int) on some systems. */
1518 socklen = (socklen_t) *namelen;
1519
1520 if (func(fd, name, &socklen))
1521 return UV__ERR(errno);
1522
1523 *namelen = (int) socklen;
1524 return 0;
1525 }
1526
uv_gettimeofday(uv_timeval64_t * tv)1527 int uv_gettimeofday(uv_timeval64_t* tv) {
1528 struct timeval time;
1529
1530 if (tv == NULL)
1531 return UV_EINVAL;
1532
1533 if (gettimeofday(&time, NULL) != 0)
1534 return UV__ERR(errno);
1535
1536 tv->tv_sec = (int64_t) time.tv_sec;
1537 tv->tv_usec = (int32_t) time.tv_usec;
1538 return 0;
1539 }
1540
uv_sleep(unsigned int msec)1541 void uv_sleep(unsigned int msec) {
1542 struct timespec timeout;
1543 int rc;
1544
1545 timeout.tv_sec = msec / 1000;
1546 timeout.tv_nsec = (msec % 1000) * 1000 * 1000;
1547
1548 do
1549 rc = nanosleep(&timeout, &timeout);
1550 while (rc == -1 && errno == EINTR);
1551
1552 assert(rc == 0);
1553 }
1554
uv__search_path(const char * prog,char * buf,size_t * buflen)1555 int uv__search_path(const char* prog, char* buf, size_t* buflen) {
1556 char abspath[UV__PATH_MAX];
1557 size_t abspath_size;
1558 char trypath[UV__PATH_MAX];
1559 char* cloned_path;
1560 char* path_env;
1561 char* token;
1562
1563 if (buf == NULL || buflen == NULL || *buflen == 0)
1564 return UV_EINVAL;
1565
1566 /*
1567 * Possibilities for prog:
1568 * i) an absolute path such as: /home/user/myprojects/nodejs/node
1569 * ii) a relative path such as: ./node or ../myprojects/nodejs/node
1570 * iii) a bare filename such as "node", after exporting PATH variable
1571 * to its location.
1572 */
1573
1574 /* Case i) and ii) absolute or relative paths */
1575 if (strchr(prog, '/') != NULL) {
1576 if (realpath(prog, abspath) != abspath)
1577 return UV__ERR(errno);
1578
1579 abspath_size = strlen(abspath);
1580
1581 *buflen -= 1;
1582 if (*buflen > abspath_size)
1583 *buflen = abspath_size;
1584
1585 memcpy(buf, abspath, *buflen);
1586 buf[*buflen] = '\0';
1587
1588 return 0;
1589 }
1590
1591 /* Case iii). Search PATH environment variable */
1592 cloned_path = NULL;
1593 token = NULL;
1594 path_env = getenv("PATH");
1595
1596 if (path_env == NULL)
1597 return UV_EINVAL;
1598
1599 cloned_path = uv__strdup(path_env);
1600 if (cloned_path == NULL)
1601 return UV_ENOMEM;
1602
1603 token = strtok(cloned_path, ":");
1604 while (token != NULL) {
1605 snprintf(trypath, sizeof(trypath) - 1, "%s/%s", token, prog);
1606 if (realpath(trypath, abspath) == abspath) {
1607 /* Check the match is executable */
1608 if (access(abspath, X_OK) == 0) {
1609 abspath_size = strlen(abspath);
1610
1611 *buflen -= 1;
1612 if (*buflen > abspath_size)
1613 *buflen = abspath_size;
1614
1615 memcpy(buf, abspath, *buflen);
1616 buf[*buflen] = '\0';
1617
1618 uv__free(cloned_path);
1619 return 0;
1620 }
1621 }
1622 token = strtok(NULL, ":");
1623 }
1624 uv__free(cloned_path);
1625
1626 /* Out of tokens (path entries), and no match found */
1627 return UV_EINVAL;
1628 }
1629