1 | /* Copyright (C) 1998-2021 Free Software Foundation, Inc. |
2 | This file is part of the GNU C Library. |
3 | Contributed by Zack Weinberg <zack@rabi.phys.columbia.edu>, 1998. |
4 | |
5 | The GNU C Library is free software; you can redistribute it and/or |
6 | modify it under the terms of the GNU Lesser General Public |
7 | License as published by the Free Software Foundation; either |
8 | version 2.1 of the License, or (at your option) any later version. |
9 | |
10 | The GNU C Library is distributed in the hope that it will be useful, |
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
13 | Lesser General Public License for more details. |
14 | |
15 | You should have received a copy of the GNU Lesser General Public |
16 | License along with the GNU C Library; if not, see |
17 | <https://www.gnu.org/licenses/>. */ |
18 | |
19 | #include <errno.h> |
20 | #include <paths.h> |
21 | #include <stdlib.h> |
22 | #include <string.h> |
23 | #include <sys/ioctl.h> |
24 | #include <termios.h> |
25 | #include <unistd.h> |
26 | |
27 | #include <_itoa.h> |
28 | |
29 | /* Directory where we can find the slave pty nodes. */ |
30 | #define _PATH_DEVPTS "/dev/pts/" |
31 | |
32 | /* Static buffer for `ptsname'. */ |
33 | static char buffer[sizeof (_PATH_DEVPTS) + 20]; |
34 | |
35 | |
36 | /* Return the pathname of the pseudo terminal slave associated with |
37 | the master FD is open on, or NULL on errors. |
38 | The returned storage is good until the next call to this function. */ |
39 | char * |
40 | ptsname (int fd) |
41 | { |
42 | return __ptsname_r (fd, buffer, sizeof (buffer)) != 0 ? NULL : buffer; |
43 | } |
44 | |
45 | |
46 | /* Store at most BUFLEN characters of the pathname of the slave pseudo |
47 | terminal associated with the master FD is open on in BUF. |
48 | Return 0 on success, otherwise an error number. */ |
49 | int |
50 | __ptsname_r (int fd, char *buf, size_t buflen) |
51 | { |
52 | int save_errno = errno; |
53 | unsigned int ptyno; |
54 | |
55 | if (__ioctl (fd, TIOCGPTN, &ptyno) == 0) |
56 | { |
57 | /* Buffer we use to print the number in. For a maximum size for |
58 | `int' of 8 bytes we never need more than 20 digits. */ |
59 | char numbuf[21]; |
60 | const char *devpts = _PATH_DEVPTS; |
61 | const size_t devptslen = strlen (_PATH_DEVPTS); |
62 | char *p; |
63 | |
64 | numbuf[sizeof (numbuf) - 1] = '\0'; |
65 | p = _itoa_word (ptyno, &numbuf[sizeof (numbuf) - 1], 10, 0); |
66 | |
67 | if (buflen < devptslen + (&numbuf[sizeof (numbuf)] - p)) |
68 | { |
69 | __set_errno (ERANGE); |
70 | return ERANGE; |
71 | } |
72 | |
73 | memcpy (__stpcpy (buf, devpts), p, &numbuf[sizeof (numbuf)] - p); |
74 | } |
75 | else |
76 | /* Bad file descriptor, or not a ptmx descriptor. */ |
77 | return errno; |
78 | |
79 | __set_errno (save_errno); |
80 | return 0; |
81 | } |
82 | libc_hidden_def (__ptsname_r) |
83 | weak_alias (__ptsname_r, ptsname_r) |
84 | |