-
Notifications
You must be signed in to change notification settings - Fork 1
/
ptytty.c
144 lines (124 loc) · 2.87 KB
/
ptytty.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#define _GNU_SOURCE /* grantpt, ptsname, unlockpt */
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
static int
retryeintr_open(char const *const path, int const flags)
{
int const fd = open(path, flags);
if (fd != -1 || errno != EINTR)
return fd;
return retryeintr_open(path, flags);
}
static int
retryeintr_dup2(int const oldfd, int const newfd)
{
int const ret = dup2(oldfd, newfd);
if (ret != -1 || errno != EINTR)
return ret;
return retryeintr_dup2(oldfd, newfd);
}
static int
retryeintr_close(int const fd)
{
int const ret = close(fd);
if (ret != -1 || errno != EINTR)
return ret;
return retryeintr_close(fd);
}
static int
opentofd(int const fd, char const *const path, int const flags)
{
int thefd = retryeintr_open(path, flags);
if (thefd == -1) {
perror("open");
return -1;
}
if (thefd == fd)
return fd;
if (retryeintr_dup2(thefd, fd) == -1) {
perror("dup2");
return -1;
}
if (retryeintr_close(thefd) == -1) {
perror("close");
return -1;
}
return fd;
}
static int
str2fd(char const *const str)
{
char *endptr;
errno = 0;
long const num = strtol(str, &endptr, 10);
if (errno) {
perror("strtol");
return -1;
}
if (endptr == str || num < 0 || num > INT_MAX || *endptr) {
if (fputs("Invalid fd.\n", stderr) == EOF)
perror("fputs");
return -1;
}
return (int)num;
}
static void
usage(void)
{
static char const msg[] =
"Usage: ptytty [-N] ptyfd ttyfd cmd [args...]\n";
if (fputs(msg, stderr) == EOF)
perror("fputs");
}
int
main(int const argc, char *const *const argv)
{
int ptflags = O_RDWR;
for (int opt; opt = getopt(argc, argv, "+N"), opt != -1;) {
switch (opt) {
case 'N':
ptflags |= O_NOCTTY;
break;
default:
usage();
return 2;
}
}
if (argc - optind < 3) {
usage();
return 2;
}
char const *const ptyfdstr = argv[optind];
char const *const ttyfdstr = argv[optind + 1];
char *const *const cmd = &argv[optind + 2];
int const ptyfd = str2fd(ptyfdstr);
if (ptyfd == -1)
return 2;
int const ttyfd = str2fd(ttyfdstr);
if (ttyfd == -1)
return 2;
if (opentofd(ptyfd, "/dev/ptmx", ptflags) == -1)
return 2;
if (grantpt(ptyfd) == -1) {
perror("grantpt");
return 2;
}
if (unlockpt(ptyfd) == -1) {
perror("unlockpt");
return 2;
}
char const *const ttypath = ptsname(ptyfd);
if (!ttypath) {
perror("ptsname");
return 2;
}
if (opentofd(ttyfd, ttypath, O_RDWR) == -1)
return 2;
(void)execvp(*cmd, cmd);
perror("execvp");
return 2;
}