-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpty.c
124 lines (109 loc) · 2.59 KB
/
pty.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
/*
* tizian - better chrooting with containers
* Copyright (C) 2017 Salvatore Mesoraca <s.mesoraca16@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <signal.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include "utils.h"
pid_t global_child = -1;
int global_pt = 1;
int prepare_term(struct termios *terms)
{
struct termios terms2;
int ret;
ret = tcgetattr(0, terms);
if (ret)
goto error;
terms2 = *terms;
cfmakeraw(&terms2);
ret = tcsetattr(0, TCSAFLUSH, &terms2);
if (ret)
goto error;
return 0;
error:
print_error("error preparing terminal");
return ret;
}
static void sync_winsize(int src, int dst)
{
struct winsize wsize;
if (ioctl(src, TIOCGWINSZ, &wsize) == 0) {
ioctl(dst, TIOCSWINSZ, &wsize);
if (global_child != -1)
kill(global_child, SIGWINCH);
}
}
void sigwinch(int s)
{
int serrno = errno;
sync_winsize(1, global_pt);
errno = serrno;
}
int pty_manager(struct termios *terms, int pt)
{
int ret = 0;
char input[512];
fd_set fd_in;
sync_winsize(1, pt);
global_pt = pt;
while (1) {
FD_ZERO(&fd_in);
FD_SET(1, &fd_in);
FD_SET(pt, &fd_in);
ret = select(pt + 1, &fd_in, NULL, NULL, NULL);
if (ret == -1 && errno != EINTR) {
print_error("Can't select");
break;
}
if (FD_ISSET(1, &fd_in)) {
ret = read(1, input, sizeof(input));
if (ret > 0) {
if (write(pt, input, ret) != ret) {
print_error("error on stdin");
break;
}
} else if (errno == EIO)
break;
else if (ret < 0) {
print_error("error on stdin");
break;
}
}
if (FD_ISSET(pt, &fd_in)) {
ret = read(pt, input, sizeof(input));
if (ret > 0) {
if (write(0, input, ret) != ret) {
print_error("error on stdin");
break;
}
} else if (errno == EIO)
break;
else if (ret < 0) {
print_error("error on stdout");
break;
}
}
}
if (ret >= 0)
ret = 0;
return ret;
}