blob: 391d729f2232653e9d67f2a0e72cae5a2bcedde4 [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 */
8
9#include "libbb.h"
10
Paul Foxb4a50872008-03-05 22:01:45 +000011#define DEBUG 0
12
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +000013int FAST_FUNC xgetpty(char *line)
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +000014{
15 int p;
Denis Vlasenkoeb084772008-08-17 12:47:19 +000016
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +000017#if ENABLE_FEATURE_DEVPTS
18 p = open("/dev/ptmx", O_RDWR);
Denys Vlasenko438b4ac2014-03-16 12:34:53 +010019 if (p >= 0) {
Denis Vlasenkoeb084772008-08-17 12:47:19 +000020 grantpt(p); /* chmod+chown corresponding slave pty */
21 unlockpt(p); /* (what does this do?) */
Denys Vlasenko24915112011-08-28 05:31:49 +020022# ifndef HAVE_PTSNAME_R
23 {
24 const char *name;
25 name = ptsname(p); /* find out the name of slave pty */
26 if (!name) {
27 bb_perror_msg_and_die("ptsname error (is /dev/pts mounted?)");
28 }
29 safe_strncpy(line, name, GETPTY_BUFSIZE);
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +000030 }
Denys Vlasenko24915112011-08-28 05:31:49 +020031# else
Denis Vlasenkoeb084772008-08-17 12:47:19 +000032 /* find out the name of slave pty */
33 if (ptsname_r(p, line, GETPTY_BUFSIZE-1) != 0) {
34 bb_perror_msg_and_die("ptsname error (is /dev/pts mounted?)");
35 }
36 line[GETPTY_BUFSIZE-1] = '\0';
Denys Vlasenko24915112011-08-28 05:31:49 +020037# endif
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +000038 return p;
39 }
40#else
41 struct stat stb;
42 int i;
43 int j;
44
45 strcpy(line, "/dev/ptyXX");
46
47 for (i = 0; i < 16; i++) {
48 line[8] = "pqrstuvwxyzabcde"[i];
49 line[9] = '0';
50 if (stat(line, &stb) < 0) {
51 continue;
52 }
53 for (j = 0; j < 16; j++) {
54 line[9] = j < 10 ? j + '0' : j - 10 + 'a';
55 if (DEBUG)
56 fprintf(stderr, "Trying to open device: %s\n", line);
57 p = open(line, O_RDWR | O_NOCTTY);
58 if (p >= 0) {
59 line[5] = 't';
60 return p;
61 }
62 }
63 }
64#endif /* FEATURE_DEVPTS */
Denis Vlasenkoeb084772008-08-17 12:47:19 +000065 bb_error_msg_and_die("can't find free pty");
Denis Vlasenkoc8f2f742008-02-27 14:33:28 +000066}