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/ioctl.h>
33 #if defined(__MVS__) && !defined(IMAXBEL)
38 /* On IBM i PASE, for better compatibility with running interactive programs in
39 * a 5250 environment, isatty() will return true for the stdin/stdout/stderr
40 * streams created by QSH/QP2TERM.
42 * For more, see docs on PASE_STDIO_ISATTY in
43 * https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_74/apis/pase_environ.htm
45 * This behavior causes problems for Node as it expects that if isatty() returns
46 * true that TTY ioctls will be supported by that fd (which is not an
47 * unreasonable expectation) and when they don't it crashes with assertion
50 * Here, we create our own version of isatty() that uses ioctl() to identify
51 * whether the fd is *really* a TTY or not.
53 static int isreallyatty(int file) {
56 rc = !ioctl(file, TXISATTY + 0x81, NULL);
57 if (!rc && errno != EBADF)
62 #define isatty(fd) isreallyatty(fd)
65 #if !defined(CMAKE_BOOTSTRAP)
67 static int orig_termios_fd = -1;
68 static struct termios orig_termios;
69 static uv_spinlock_t termios_spinlock = UV_SPINLOCK_INITIALIZER;
71 int uv__tcsetattr(int fd, int how, const struct termios *term) {
75 rc = tcsetattr(fd, how, term);
76 while (rc == -1 && errno == EINTR);
79 return UV__ERR(errno);
84 static int uv__tty_is_slave(const int fd) {
86 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
89 result = ioctl(fd, TIOCGPTN, &dummy) != 0;
90 #elif defined(__APPLE__)
93 result = ioctl(fd, TIOCPTYGNAME, &dummy) != 0;
94 #elif defined(__NetBSD__)
96 * NetBSD as an extension returns with ptsname(3) and ptsname_r(3) the slave
97 * device name for both descriptors, the master one and slave one.
99 * Implement function to compare major device number with pts devices.
101 * The major numbers are machine-dependent, on NetBSD/amd64 they are
103 * - master tty: ptc - major 6
104 * - slave tty: pts - major 5
108 /* Lookup device's major for the pts driver and cache it. */
109 static devmajor_t pts = NODEVMAJOR;
111 if (pts == NODEVMAJOR) {
112 pts = getdevmajor("pts", S_IFCHR);
113 if (pts == NODEVMAJOR)
117 /* Lookup stat structure behind the file descriptor. */
118 if (fstat(fd, &sb) != 0)
121 /* Assert character device. */
122 if (!S_ISCHR(sb.st_mode))
125 /* Assert valid major. */
126 if (major(sb.st_rdev) == NODEVMAJOR)
129 result = (pts == major(sb.st_rdev));
131 /* Fallback to ptsname
133 result = ptsname(fd) == NULL;
138 int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, int fd, int unused) {
146 (void)unused; /* deprecated parameter is no longer needed */
148 /* File descriptors that refer to files cannot be monitored with epoll.
149 * That restriction also applies to character devices like /dev/random
150 * (but obviously not /dev/tty.)
152 type = uv_guess_handle(fd);
153 if (type == UV_FILE || type == UV_UNKNOWN_HANDLE)
156 /* Save the fd flags in case we need to restore them due to an error. */
158 saved_flags = fcntl(fd, F_GETFL);
159 while (saved_flags == -1 && errno == EINTR);
161 if (saved_flags == -1)
162 return UV__ERR(errno);
163 mode = saved_flags & O_ACCMODE;
165 /* Reopen the file descriptor when it refers to a tty. This lets us put the
166 * tty in non-blocking mode without affecting other processes that share it
169 * Example: `node | cat` - if we put our fd 0 in non-blocking mode, it also
170 * affects fd 1 of `cat` because both file descriptors refer to the same
171 * struct file in the kernel. When we reopen our fd 0, it points to a
172 * different struct file, hence changing its properties doesn't affect
175 if (type == UV_TTY) {
176 /* Reopening a pty in master mode won't work either because the reopened
177 * pty will be in slave mode (*BSD) or reopening will allocate a new
178 * master/slave pair (Linux). Therefore check if the fd points to a
181 if (uv__tty_is_slave(fd) && ttyname_r(fd, path, sizeof(path)) == 0)
182 r = uv__open_cloexec(path, mode | O_NOCTTY);
187 /* fallback to using blocking writes */
188 if (mode != O_RDONLY)
189 flags |= UV_HANDLE_BLOCKING_WRITES;
195 r = uv__dup2_cloexec(newfd, fd);
196 if (r < 0 && r != UV_EINVAL) {
197 /* EINVAL means newfd == fd which could conceivably happen if another
198 * thread called close(fd) between our calls to isatty() and open().
199 * That's a rather unlikely event but let's handle it anyway.
209 uv__stream_init(loop, (uv_stream_t*) tty, UV_TTY);
211 /* If anything fails beyond this point we need to remove the handle from
212 * the handle queue, since it was added by uv__handle_init in uv_stream_init.
215 if (!(flags & UV_HANDLE_BLOCKING_WRITES))
218 #if defined(__APPLE__)
219 r = uv__stream_try_select((uv_stream_t*) tty, &fd);
224 QUEUE_REMOVE(&tty->handle_queue);
226 r = fcntl(fd, F_SETFL, saved_flags);
227 while (r == -1 && errno == EINTR);
232 if (mode != O_WRONLY)
233 flags |= UV_HANDLE_READABLE;
234 if (mode != O_RDONLY)
235 flags |= UV_HANDLE_WRITABLE;
237 uv__stream_open((uv_stream_t*) tty, fd, flags);
238 tty->mode = UV_TTY_MODE_NORMAL;
243 static void uv__tty_make_raw(struct termios* tio) {
246 #if defined __sun || defined __MVS__ || defined __hpux
248 * This implementation of cfmakeraw for Solaris and derivatives is taken from
249 * http://www.perkin.org.uk/posts/solaris-portability-cfmakeraw.html.
251 tio->c_iflag &= ~(IMAXBEL | IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR |
252 IGNCR | ICRNL | IXON);
253 tio->c_oflag &= ~OPOST;
254 tio->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
255 tio->c_cflag &= ~(CSIZE | PARENB);
259 * By default, most software expects a pending read to block until at
260 * least one byte becomes available. As per termio(7I), this requires
261 * setting the MIN and TIME parameters appropriately.
263 * As a somewhat unfortunate artifact of history, the MIN and TIME slots
264 * in the control character array overlap with the EOF and EOL slots used
265 * for canonical mode processing. Because the EOF character needs to be
266 * the ASCII EOT value (aka Control-D), it has the byte value 4. When
267 * switching to raw mode, this is interpreted as a MIN value of 4; i.e.,
268 * reads will block until at least four bytes have been input.
270 * Other platforms with a distinct MIN slot like Linux and FreeBSD appear
271 * to default to a MIN value of 1, so we'll force that value here:
274 tio->c_cc[VTIME] = 0;
277 #endif /* #ifdef __sun */
280 int uv_tty_set_mode(uv_tty_t* tty, uv_tty_mode_t mode) {
285 if (tty->mode == (int) mode)
288 fd = uv__stream_fd(tty);
289 if (tty->mode == UV_TTY_MODE_NORMAL && mode != UV_TTY_MODE_NORMAL) {
291 rc = tcgetattr(fd, &tty->orig_termios);
292 while (rc == -1 && errno == EINTR);
295 return UV__ERR(errno);
297 /* This is used for uv_tty_reset_mode() */
298 uv_spinlock_lock(&termios_spinlock);
299 if (orig_termios_fd == -1) {
300 orig_termios = tty->orig_termios;
301 orig_termios_fd = fd;
303 uv_spinlock_unlock(&termios_spinlock);
306 tmp = tty->orig_termios;
308 case UV_TTY_MODE_NORMAL:
310 case UV_TTY_MODE_RAW:
311 tmp.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
312 tmp.c_oflag |= (ONLCR);
313 tmp.c_cflag |= (CS8);
314 tmp.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
319 uv__tty_make_raw(&tmp);
323 /* Apply changes after draining */
324 rc = uv__tcsetattr(fd, TCSADRAIN, &tmp);
332 int uv_tty_get_winsize(uv_tty_t* tty, int* width, int* height) {
337 err = ioctl(uv__stream_fd(tty), TIOCGWINSZ, &ws);
338 while (err == -1 && errno == EINTR);
341 return UV__ERR(errno);
351 uv_handle_type uv_guess_handle(uv_file file) {
352 struct sockaddr_storage ss;
358 return UV_UNKNOWN_HANDLE;
363 if (fstat(file, &s)) {
364 #if defined(__PASE__)
365 /* On ibmi receiving RST from TCP instead of FIN immediately puts fd into
366 * an error state. fstat will return EINVAL, getsockname will also return
367 * EINVAL, even if sockaddr_storage is valid. (If file does not refer to a
368 * socket, ENOTSOCK is returned instead.)
369 * In such cases, we will permit the user to open the connection as uv_tcp
370 * still, so that the user can get immediately notified of the error in
371 * their read callback and close this fd.
374 if (getsockname(file, (struct sockaddr*) &ss, &len)) {
379 return UV_UNKNOWN_HANDLE;
382 if (S_ISREG(s.st_mode))
385 if (S_ISCHR(s.st_mode))
386 return UV_FILE; /* XXX UV_NAMED_PIPE? */
388 if (S_ISFIFO(s.st_mode))
389 return UV_NAMED_PIPE;
391 if (!S_ISSOCK(s.st_mode))
392 return UV_UNKNOWN_HANDLE;
395 if (getsockname(file, (struct sockaddr*) &ss, &len)) {
397 /* On aix receiving RST from TCP instead of FIN immediately puts fd into
398 * an error state. In such case getsockname will return EINVAL, even if
399 * sockaddr_storage is valid.
400 * In such cases, we will permit the user to open the connection as uv_tcp
401 * still, so that the user can get immediately notified of the error in
402 * their read callback and close this fd.
404 if (errno == EINVAL) {
408 return UV_UNKNOWN_HANDLE;
412 if (getsockopt(file, SOL_SOCKET, SO_TYPE, &type, &len))
413 return UV_UNKNOWN_HANDLE;
415 if (type == SOCK_DGRAM)
416 if (ss.ss_family == AF_INET || ss.ss_family == AF_INET6)
419 if (type == SOCK_STREAM) {
420 #if defined(_AIX) || defined(__DragonFly__)
421 /* on AIX/DragonFly the getsockname call returns an empty sa structure
422 * for sockets of type AF_UNIX. For all other types it will
423 * return a properly filled in structure.
426 return UV_NAMED_PIPE;
427 #endif /* defined(_AIX) || defined(__DragonFly__) */
429 if (ss.ss_family == AF_INET || ss.ss_family == AF_INET6)
431 if (ss.ss_family == AF_UNIX)
432 return UV_NAMED_PIPE;
435 return UV_UNKNOWN_HANDLE;
438 #if !defined(CMAKE_BOOTSTRAP)
440 /* This function is async signal-safe, meaning that it's safe to call from
441 * inside a signal handler _unless_ execution was inside uv_tty_set_mode()'s
442 * critical section when the signal was raised.
444 int uv_tty_reset_mode(void) {
449 if (!uv_spinlock_trylock(&termios_spinlock))
450 return UV_EBUSY; /* In uv_tty_set_mode(). */
453 if (orig_termios_fd != -1)
454 err = uv__tcsetattr(orig_termios_fd, TCSANOW, &orig_termios);
456 uv_spinlock_unlock(&termios_spinlock);
462 void uv_tty_set_vterm_state(uv_tty_vtermstate_t state) {
465 int uv_tty_get_vterm_state(uv_tty_vtermstate_t* state) {