1
0

tty.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
  2. *
  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:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  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
  19. * IN THE SOFTWARE.
  20. */
  21. #include "uv.h"
  22. #include "internal.h"
  23. #include "spinlock.h"
  24. #include <stdlib.h>
  25. #include <assert.h>
  26. #include <unistd.h>
  27. #include <termios.h>
  28. #include <errno.h>
  29. #include <sys/ioctl.h>
  30. #if defined(__MVS__) && !defined(IMAXBEL)
  31. #define IMAXBEL 0
  32. #endif
  33. #if defined(__PASE__)
  34. /* On IBM i PASE, for better compatibility with running interactive programs in
  35. * a 5250 environment, isatty() will return true for the stdin/stdout/stderr
  36. * streams created by QSH/QP2TERM.
  37. *
  38. * For more, see docs on PASE_STDIO_ISATTY in
  39. * https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_74/apis/pase_environ.htm
  40. *
  41. * This behavior causes problems for Node as it expects that if isatty() returns
  42. * true that TTY ioctls will be supported by that fd (which is not an
  43. * unreasonable expectation) and when they don't it crashes with assertion
  44. * errors.
  45. *
  46. * Here, we create our own version of isatty() that uses ioctl() to identify
  47. * whether the fd is *really* a TTY or not.
  48. */
  49. static int isreallyatty(int file) {
  50. int rc;
  51. rc = !ioctl(file, TXISATTY + 0x81, NULL);
  52. if (!rc && errno != EBADF)
  53. errno = ENOTTY;
  54. return rc;
  55. }
  56. #define isatty(fd) isreallyatty(fd)
  57. #endif
  58. static int orig_termios_fd = -1;
  59. static struct termios orig_termios;
  60. static uv_spinlock_t termios_spinlock = UV_SPINLOCK_INITIALIZER;
  61. static int uv__tty_is_slave(const int fd) {
  62. int result;
  63. #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
  64. int dummy;
  65. result = ioctl(fd, TIOCGPTN, &dummy) != 0;
  66. #elif defined(__APPLE__)
  67. char dummy[256];
  68. result = ioctl(fd, TIOCPTYGNAME, &dummy) != 0;
  69. #elif defined(__NetBSD__)
  70. /*
  71. * NetBSD as an extension returns with ptsname(3) and ptsname_r(3) the slave
  72. * device name for both descriptors, the master one and slave one.
  73. *
  74. * Implement function to compare major device number with pts devices.
  75. *
  76. * The major numbers are machine-dependent, on NetBSD/amd64 they are
  77. * respectively:
  78. * - master tty: ptc - major 6
  79. * - slave tty: pts - major 5
  80. */
  81. struct stat sb;
  82. /* Lookup device's major for the pts driver and cache it. */
  83. static devmajor_t pts = NODEVMAJOR;
  84. if (pts == NODEVMAJOR) {
  85. pts = getdevmajor("pts", S_IFCHR);
  86. if (pts == NODEVMAJOR)
  87. abort();
  88. }
  89. /* Lookup stat structure behind the file descriptor. */
  90. if (fstat(fd, &sb) != 0)
  91. abort();
  92. /* Assert character device. */
  93. if (!S_ISCHR(sb.st_mode))
  94. abort();
  95. /* Assert valid major. */
  96. if (major(sb.st_rdev) == NODEVMAJOR)
  97. abort();
  98. result = (pts == major(sb.st_rdev));
  99. #else
  100. /* Fallback to ptsname
  101. */
  102. result = ptsname(fd) == NULL;
  103. #endif
  104. return result;
  105. }
  106. int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, int fd, int unused) {
  107. uv_handle_type type;
  108. int flags;
  109. int newfd;
  110. int r;
  111. int saved_flags;
  112. int mode;
  113. char path[256];
  114. (void)unused; /* deprecated parameter is no longer needed */
  115. /* File descriptors that refer to files cannot be monitored with epoll.
  116. * That restriction also applies to character devices like /dev/random
  117. * (but obviously not /dev/tty.)
  118. */
  119. type = uv_guess_handle(fd);
  120. if (type == UV_FILE || type == UV_UNKNOWN_HANDLE)
  121. return UV_EINVAL;
  122. flags = 0;
  123. newfd = -1;
  124. /* Save the fd flags in case we need to restore them due to an error. */
  125. do
  126. saved_flags = fcntl(fd, F_GETFL);
  127. while (saved_flags == -1 && errno == EINTR);
  128. if (saved_flags == -1)
  129. return UV__ERR(errno);
  130. mode = saved_flags & O_ACCMODE;
  131. /* Reopen the file descriptor when it refers to a tty. This lets us put the
  132. * tty in non-blocking mode without affecting other processes that share it
  133. * with us.
  134. *
  135. * Example: `node | cat` - if we put our fd 0 in non-blocking mode, it also
  136. * affects fd 1 of `cat` because both file descriptors refer to the same
  137. * struct file in the kernel. When we reopen our fd 0, it points to a
  138. * different struct file, hence changing its properties doesn't affect
  139. * other processes.
  140. */
  141. if (type == UV_TTY) {
  142. /* Reopening a pty in master mode won't work either because the reopened
  143. * pty will be in slave mode (*BSD) or reopening will allocate a new
  144. * master/slave pair (Linux). Therefore check if the fd points to a
  145. * slave device.
  146. */
  147. if (uv__tty_is_slave(fd) && ttyname_r(fd, path, sizeof(path)) == 0)
  148. r = uv__open_cloexec(path, mode | O_NOCTTY);
  149. else
  150. r = -1;
  151. if (r < 0) {
  152. /* fallback to using blocking writes */
  153. if (mode != O_RDONLY)
  154. flags |= UV_HANDLE_BLOCKING_WRITES;
  155. goto skip;
  156. }
  157. newfd = r;
  158. r = uv__dup2_cloexec(newfd, fd);
  159. if (r < 0 && r != UV_EINVAL) {
  160. /* EINVAL means newfd == fd which could conceivably happen if another
  161. * thread called close(fd) between our calls to isatty() and open().
  162. * That's a rather unlikely event but let's handle it anyway.
  163. */
  164. uv__close(newfd);
  165. return r;
  166. }
  167. fd = newfd;
  168. }
  169. skip:
  170. uv__stream_init(loop, (uv_stream_t*) tty, UV_TTY);
  171. /* If anything fails beyond this point we need to remove the handle from
  172. * the handle queue, since it was added by uv__handle_init in uv_stream_init.
  173. */
  174. if (!(flags & UV_HANDLE_BLOCKING_WRITES))
  175. uv__nonblock(fd, 1);
  176. #if defined(__APPLE__)
  177. r = uv__stream_try_select((uv_stream_t*) tty, &fd);
  178. if (r) {
  179. int rc = r;
  180. if (newfd != -1)
  181. uv__close(newfd);
  182. QUEUE_REMOVE(&tty->handle_queue);
  183. do
  184. r = fcntl(fd, F_SETFL, saved_flags);
  185. while (r == -1 && errno == EINTR);
  186. return rc;
  187. }
  188. #endif
  189. if (mode != O_WRONLY)
  190. flags |= UV_HANDLE_READABLE;
  191. if (mode != O_RDONLY)
  192. flags |= UV_HANDLE_WRITABLE;
  193. uv__stream_open((uv_stream_t*) tty, fd, flags);
  194. tty->mode = UV_TTY_MODE_NORMAL;
  195. return 0;
  196. }
  197. static void uv__tty_make_raw(struct termios* tio) {
  198. assert(tio != NULL);
  199. #if defined __sun || defined __MVS__
  200. /*
  201. * This implementation of cfmakeraw for Solaris and derivatives is taken from
  202. * http://www.perkin.org.uk/posts/solaris-portability-cfmakeraw.html.
  203. */
  204. tio->c_iflag &= ~(IMAXBEL | IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR |
  205. IGNCR | ICRNL | IXON);
  206. tio->c_oflag &= ~OPOST;
  207. tio->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  208. tio->c_cflag &= ~(CSIZE | PARENB);
  209. tio->c_cflag |= CS8;
  210. #else
  211. cfmakeraw(tio);
  212. #endif /* #ifdef __sun */
  213. }
  214. int uv_tty_set_mode(uv_tty_t* tty, uv_tty_mode_t mode) {
  215. struct termios tmp;
  216. int fd;
  217. if (tty->mode == (int) mode)
  218. return 0;
  219. fd = uv__stream_fd(tty);
  220. if (tty->mode == UV_TTY_MODE_NORMAL && mode != UV_TTY_MODE_NORMAL) {
  221. if (tcgetattr(fd, &tty->orig_termios))
  222. return UV__ERR(errno);
  223. /* This is used for uv_tty_reset_mode() */
  224. uv_spinlock_lock(&termios_spinlock);
  225. if (orig_termios_fd == -1) {
  226. orig_termios = tty->orig_termios;
  227. orig_termios_fd = fd;
  228. }
  229. uv_spinlock_unlock(&termios_spinlock);
  230. }
  231. tmp = tty->orig_termios;
  232. switch (mode) {
  233. case UV_TTY_MODE_NORMAL:
  234. break;
  235. case UV_TTY_MODE_RAW:
  236. tmp.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  237. tmp.c_oflag |= (ONLCR);
  238. tmp.c_cflag |= (CS8);
  239. tmp.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
  240. tmp.c_cc[VMIN] = 1;
  241. tmp.c_cc[VTIME] = 0;
  242. break;
  243. case UV_TTY_MODE_IO:
  244. uv__tty_make_raw(&tmp);
  245. break;
  246. }
  247. /* Apply changes after draining */
  248. if (tcsetattr(fd, TCSADRAIN, &tmp))
  249. return UV__ERR(errno);
  250. tty->mode = mode;
  251. return 0;
  252. }
  253. int uv_tty_get_winsize(uv_tty_t* tty, int* width, int* height) {
  254. struct winsize ws;
  255. int err;
  256. do
  257. err = ioctl(uv__stream_fd(tty), TIOCGWINSZ, &ws);
  258. while (err == -1 && errno == EINTR);
  259. if (err == -1)
  260. return UV__ERR(errno);
  261. *width = ws.ws_col;
  262. *height = ws.ws_row;
  263. return 0;
  264. }
  265. uv_handle_type uv_guess_handle(uv_file file) {
  266. struct sockaddr sa;
  267. struct stat s;
  268. socklen_t len;
  269. int type;
  270. if (file < 0)
  271. return UV_UNKNOWN_HANDLE;
  272. if (isatty(file))
  273. return UV_TTY;
  274. if (fstat(file, &s))
  275. return UV_UNKNOWN_HANDLE;
  276. if (S_ISREG(s.st_mode))
  277. return UV_FILE;
  278. if (S_ISCHR(s.st_mode))
  279. return UV_FILE; /* XXX UV_NAMED_PIPE? */
  280. if (S_ISFIFO(s.st_mode))
  281. return UV_NAMED_PIPE;
  282. if (!S_ISSOCK(s.st_mode))
  283. return UV_UNKNOWN_HANDLE;
  284. len = sizeof(type);
  285. if (getsockopt(file, SOL_SOCKET, SO_TYPE, &type, &len))
  286. return UV_UNKNOWN_HANDLE;
  287. len = sizeof(sa);
  288. if (getsockname(file, &sa, &len))
  289. return UV_UNKNOWN_HANDLE;
  290. if (type == SOCK_DGRAM)
  291. if (sa.sa_family == AF_INET || sa.sa_family == AF_INET6)
  292. return UV_UDP;
  293. if (type == SOCK_STREAM) {
  294. #if defined(_AIX) || defined(__DragonFly__)
  295. /* on AIX/DragonFly the getsockname call returns an empty sa structure
  296. * for sockets of type AF_UNIX. For all other types it will
  297. * return a properly filled in structure.
  298. */
  299. if (len == 0)
  300. return UV_NAMED_PIPE;
  301. #endif /* defined(_AIX) || defined(__DragonFly__) */
  302. if (sa.sa_family == AF_INET || sa.sa_family == AF_INET6)
  303. return UV_TCP;
  304. if (sa.sa_family == AF_UNIX)
  305. return UV_NAMED_PIPE;
  306. }
  307. return UV_UNKNOWN_HANDLE;
  308. }
  309. /* This function is async signal-safe, meaning that it's safe to call from
  310. * inside a signal handler _unless_ execution was inside uv_tty_set_mode()'s
  311. * critical section when the signal was raised.
  312. */
  313. int uv_tty_reset_mode(void) {
  314. int saved_errno;
  315. int err;
  316. saved_errno = errno;
  317. if (!uv_spinlock_trylock(&termios_spinlock))
  318. return UV_EBUSY; /* In uv_tty_set_mode(). */
  319. err = 0;
  320. if (orig_termios_fd != -1)
  321. if (tcsetattr(orig_termios_fd, TCSANOW, &orig_termios))
  322. err = UV__ERR(errno);
  323. uv_spinlock_unlock(&termios_spinlock);
  324. errno = saved_errno;
  325. return err;
  326. }
  327. void uv_tty_set_vterm_state(uv_tty_vtermstate_t state) {
  328. }
  329. int uv_tty_get_vterm_state(uv_tty_vtermstate_t* state) {
  330. return UV_ENOTSUP;
  331. }