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