1 /* Copyright (C) 1998-2023 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
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.
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.
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/>. */
26 #include <sys/types.h>
27 #include <shlib-compat.h>
29 /* Return the result of ptsname_r in the buffer pointed to by PTS,
30 which should be of length BUF_LEN. If it is too long to fit in
31 this buffer, a sufficiently long buffer is allocated using malloc,
32 and returned in PTS. 0 is returned upon success, -1 otherwise. */
34 pts_name (int fd
, char **pts
, size_t buf_len
)
45 rv
= __ptsname_r (fd
, buf
, buf_len
);
47 if (rv
!= 0 || memchr (buf
, '\0', buf_len
))
48 /* We either got an error, or we succeeded and the
49 returned name fit in the buffer. */
52 /* Try again with a longer buffer. */
53 buf_len
+= buf_len
; /* Double it */
56 /* No initial buffer; start out by mallocing one. */
57 buf_len
= 128; /* First time guess. */
60 /* We've already malloced another buffer at least once. */
61 new_buf
= realloc (buf
, buf_len
);
63 new_buf
= malloc (buf_len
);
74 *pts
= buf
; /* Return buffer to the user. */
76 free (buf
); /* Free what we malloced when returning an error. */
81 /* Create pseudo tty multiplexer/terminal pair and set terminal attributes
82 according to TERMP and WINP. Return handles for both ends in
83 *PPTMX and *PTERMINAL, and return the name of the terminal end in NAME. */
85 __openpty (int *pptmx
, int *pterminal
, char *name
,
86 const struct termios
*termp
, const struct winsize
*winp
)
94 int ptmx
, ret
= -1, terminal
= -1;
109 /* Try to allocate terminal fd solely based on PTMX fd first. */
110 terminal
= __ioctl (ptmx
, TIOCGPTPEER
, O_RDWR
| O_NOCTTY
);
114 /* Fallback to path-based terminal fd allocation in case kernel doesn't
115 * support TIOCGPTPEER.
117 if (pts_name (ptmx
, &buf
, sizeof (_buf
)))
120 terminal
= __open64 (buf
, O_RDWR
| O_NOCTTY
);
125 /* XXX Should we ignore errors here? */
127 tcsetattr (terminal
, TCSAFLUSH
, termp
);
130 __ioctl (terminal
, TIOCSWINSZ
, winp
);
134 *pterminal
= terminal
;
138 if (pts_name (ptmx
, &buf
, sizeof (_buf
)))
159 versioned_symbol (libc
, __openpty
, openpty
, GLIBC_2_34
);
160 libc_hidden_ver (__openpty
, openpty
)
162 #if OTHER_SHLIB_COMPAT (libutil, GLIBC_2_0, GLIBC_2_34)
163 compat_symbol (libutil
, __openpty
, openpty
, GLIBC_2_0
);