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
|
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2021, Gunnar Beutner <gbeutner@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Format.h>
#include <fcntl.h>
#include <pty.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
int openpty(int* amaster, int* aslave, char* name, const struct termios* termp, const struct winsize* winp)
{
*amaster = posix_openpt(O_RDWR);
if (*amaster < 0) {
return -1;
}
if (grantpt(*amaster) < 0) {
int error = errno;
close(*amaster);
errno = error;
return -1;
}
if (unlockpt(*amaster) < 0) {
int error = errno;
close(*amaster);
errno = error;
return -1;
}
const char* tty_name = ptsname(*amaster);
if (!tty_name) {
int error = errno;
close(*amaster);
errno = error;
return -1;
}
if (name) {
/* The spec doesn't say how large name has to be. Good luck. */
[[maybe_unused]] auto rc = strlcpy(name, tty_name, 128);
}
*aslave = open(tty_name, O_RDWR | O_NOCTTY);
if (*aslave < 0) {
int error = errno;
close(*amaster);
errno = error;
return -1;
}
if (termp) {
// FIXME: error handling
tcsetattr(*aslave, TCSAFLUSH, termp);
}
if (winp) {
// FIXME: error handling
ioctl(*aslave, TIOCGWINSZ, winp);
}
dbgln("openpty, master={}, slave={}, tty_name={}", *amaster, *aslave, tty_name);
return 0;
}
pid_t forkpty(int* amaster, int* aslave, char* name, const struct termios* termp, const struct winsize* winp)
{
int rc = openpty(amaster, aslave, name, termp, winp);
if (rc < 0)
return rc;
rc = fork();
if (rc < 0) {
close(*amaster);
close(*aslave);
return -1;
}
if (rc == 0)
rc = login_tty(*aslave);
return rc;
}
int login_tty(int fd)
{
setsid();
close(0);
close(1);
close(2);
int rc = dup2(fd, 0);
if (rc < 0)
return rc;
rc = dup2(fd, 1);
if (rc < 0)
return -1;
rc = dup2(fd, 2);
if (rc < 0)
return rc;
rc = close(fd);
if (rc < 0)
return rc;
rc = ioctl(0, TIOCSCTTY);
if (rc < 0)
return rc;
return 0;
}
|