re-mark 1.29b-2 as not yet uploaded (merge madness!)
[debian/tar] / gnu / ttyname_r.c
1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* Determine name of a terminal.
4
5    Copyright (C) 2010-2014 Free Software Foundation, Inc.
6
7    This program is free software: you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* Written by Bruno Haible <bruno@clisp.org>, 2010.  */
21
22 #include <config.h>
23
24 #include <unistd.h>
25
26 #include <errno.h>
27 #include <limits.h>
28 #include <string.h>
29
30 int
31 ttyname_r (int fd, char *buf, size_t buflen)
32 #undef ttyname_r
33 {
34   /* When ttyname_r exists, use it.  */
35 #if HAVE_TTYNAME_R
36   /* This code is multithread-safe.  */
37   /* On Solaris, ttyname_r always fails if buflen < 128.  On OSF/1 5.1,
38      ttyname_r ignores the buffer size and assumes the buffer is large enough.
39      So provide a buffer that is large enough.  */
40   char largerbuf[512];
41 # if HAVE_POSIXDECL_TTYNAME_R
42   int err =
43     (buflen < sizeof (largerbuf)
44      ? ttyname_r (fd, largerbuf, sizeof (largerbuf))
45      : ttyname_r (fd, buf, buflen <= INT_MAX ? buflen : INT_MAX));
46   if (err != 0)
47     return err;
48   if (buflen < sizeof (largerbuf))
49     {
50       size_t namelen = strlen (largerbuf) + 1;
51       if (namelen > buflen)
52         return ERANGE;
53       memcpy (buf, largerbuf, namelen);
54     }
55 # else
56   char *name =
57     (buflen < sizeof (largerbuf)
58      ? ttyname_r (fd, largerbuf, sizeof (largerbuf))
59      : ttyname_r (fd, buf, buflen <= INT_MAX ? buflen : INT_MAX));
60   if (name == NULL)
61     return errno;
62   if (name != buf)
63     {
64       size_t namelen = strlen (name) + 1;
65       if (namelen > buflen)
66         return ERANGE;
67       memmove (buf, name, namelen);
68     }
69 # endif
70   return 0;
71 #elif HAVE_TTYNAME
72   /* Note: This is not multithread-safe.  */
73   char *name;
74   size_t namelen;
75
76   name = ttyname (fd);
77   if (name == NULL)
78     return errno;
79   namelen = strlen (name) + 1;
80   if (namelen > buflen)
81     return ERANGE;
82   memcpy (buf, name, namelen);
83   return 0;
84 #else
85   /* Platforms like mingw: no ttys exist at all.  */
86   return ENOTTY;
87 #endif
88 }