Initial public busybox upstream commit
[busybox4maemo] / libbb / getpty.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini getpty implementation for busybox
4  * Bjorn Wesen, Axis Communications AB (bjornw@axis.com)
5  *
6  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
7  */
8
9 #include "libbb.h"
10
11 #define DEBUG 0
12
13 int getpty(char *line)
14 {
15         int p;
16 #if ENABLE_FEATURE_DEVPTS
17         p = open("/dev/ptmx", O_RDWR);
18         if (p > 0) {
19                 const char *name;
20                 grantpt(p);
21                 unlockpt(p);
22                 name = ptsname(p);
23                 if (!name) {
24                         bb_perror_msg("ptsname error (is /dev/pts mounted?)");
25                         return -1;
26                 }
27                 safe_strncpy(line, name, GETPTY_BUFSIZE);
28                 return p;
29         }
30 #else
31         struct stat stb;
32         int i;
33         int j;
34
35         strcpy(line, "/dev/ptyXX");
36
37         for (i = 0; i < 16; i++) {
38                 line[8] = "pqrstuvwxyzabcde"[i];
39                 line[9] = '0';
40                 if (stat(line, &stb) < 0) {
41                         continue;
42                 }
43                 for (j = 0; j < 16; j++) {
44                         line[9] = j < 10 ? j + '0' : j - 10 + 'a';
45                         if (DEBUG)
46                                 fprintf(stderr, "Trying to open device: %s\n", line);
47                         p = open(line, O_RDWR | O_NOCTTY);
48                         if (p >= 0) {
49                                 line[5] = 't';
50                                 return p;
51                         }
52                 }
53         }
54 #endif /* FEATURE_DEVPTS */
55         return -1;
56 }
57
58