blob: 9ec6265ad3648b7e1c920e1a36ba1e2cf4619ccf [file] [log] [blame]
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +00001/* vi: set sw=4 ts=4: */
2/*
3 * Mini getpty implementation for busybox
4 * Bjorn Wesen, Axis Communications AB (bjornw@axis.com)
5 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +02006 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +00007 */
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +00008#include "libbb.h"
9
Paul Foxb4a50872008-03-05 22:01:45 +000010#define DEBUG 0
11
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +000012int FAST_FUNC xgetpty(char *line)
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +000013{
14 int p;
Denis Vlasenkoeb084772008-08-17 12:47:19 +000015
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +000016#if ENABLE_FEATURE_DEVPTS
17 p = open("/dev/ptmx", O_RDWR);
Denys Vlasenko438b4ac2014-03-16 12:34:53 +010018 if (p >= 0) {
Denis Vlasenkoeb084772008-08-17 12:47:19 +000019 grantpt(p); /* chmod+chown corresponding slave pty */
20 unlockpt(p); /* (what does this do?) */
Denys Vlasenko24915112011-08-28 05:31:49 +020021# ifndef HAVE_PTSNAME_R
22 {
23 const char *name;
24 name = ptsname(p); /* find out the name of slave pty */
25 if (!name) {
James Byrne69374872019-07-02 11:35:03 +020026 bb_simple_perror_msg_and_die("ptsname error (is /dev/pts mounted?)");
Denys Vlasenko24915112011-08-28 05:31:49 +020027 }
28 safe_strncpy(line, name, GETPTY_BUFSIZE);
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +000029 }
Denys Vlasenko24915112011-08-28 05:31:49 +020030# else
Denis Vlasenkoeb084772008-08-17 12:47:19 +000031 /* find out the name of slave pty */
32 if (ptsname_r(p, line, GETPTY_BUFSIZE-1) != 0) {
James Byrne69374872019-07-02 11:35:03 +020033 bb_simple_perror_msg_and_die("ptsname error (is /dev/pts mounted?)");
Denis Vlasenkoeb084772008-08-17 12:47:19 +000034 }
35 line[GETPTY_BUFSIZE-1] = '\0';
Denys Vlasenko24915112011-08-28 05:31:49 +020036# endif
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +000037 return p;
38 }
39#else
40 struct stat stb;
41 int i;
42 int j;
43
44 strcpy(line, "/dev/ptyXX");
45
46 for (i = 0; i < 16; i++) {
47 line[8] = "pqrstuvwxyzabcde"[i];
48 line[9] = '0';
49 if (stat(line, &stb) < 0) {
50 continue;
51 }
52 for (j = 0; j < 16; j++) {
53 line[9] = j < 10 ? j + '0' : j - 10 + 'a';
54 if (DEBUG)
55 fprintf(stderr, "Trying to open device: %s\n", line);
56 p = open(line, O_RDWR | O_NOCTTY);
57 if (p >= 0) {
58 line[5] = 't';
59 return p;
60 }
61 }
62 }
63#endif /* FEATURE_DEVPTS */
James Byrne69374872019-07-02 11:35:03 +020064 bb_simple_error_msg_and_die("can't find free pty");
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +000065}