Merge commit 'b572c3a256e7bf1e4eecc8c36448c08093240a6a' into stable
[gnulib.git] / lib / ptsname_r.c
1 /* Determine name of the slave side of a pseudo-terminal.
2    Copyright (C) 1998, 2002, 2010-2011 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program 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
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18
19 #include <stdlib.h>
20
21 #include <errno.h>
22 #include <string.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25
26 #ifdef _LIBC
27 # include <paths.h>
28 #else
29 # ifndef _PATH_TTY
30 #  define _PATH_TTY "/dev/tty"
31 # endif
32 # ifndef _PATH_DEV
33 #  define _PATH_DEV "/dev/"
34 # endif
35
36 # define __set_errno(e) errno = (e)
37 # define __isatty isatty
38 # define __stat stat
39 # define __ttyname_r ttyname_r
40 # define __ptsname_r ptsname_r
41
42 #endif
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
49 __ptsname_r (int fd, char *buf, size_t buflen)
50 {
51   int save_errno = errno;
52   int err;
53   struct stat st;
54
55   if (buf == NULL)
56     {
57       __set_errno (EINVAL);
58       return EINVAL;
59     }
60
61   if (!__isatty (fd))
62     /* We rely on isatty to set errno properly (i.e. EBADF or ENOTTY).  */
63     return errno;
64
65   if (buflen < strlen (_PATH_TTY) + 3)
66     {
67       __set_errno (ERANGE);
68       return ERANGE;
69     }
70
71   err = __ttyname_r (fd, buf, buflen);
72   if (err != 0)
73     {
74       __set_errno (err);
75       return errno;
76     }
77
78   buf[sizeof (_PATH_DEV) - 1] = 't';
79
80   if (__stat (buf, &st) < 0)
81     return errno;
82
83   __set_errno (save_errno);
84   return 0;
85 }