aboutsummaryrefslogtreecommitdiff
path: root/rtty.c
blob: f5df4ac640e826628d19e58a87c15e9a1f895895 (plain)
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>

#define INIT "export TERM=tty43 EDITOR=ed PAGER=cat\n"
#define IINIT "export EDITOR=ed PAGER=ul\n"

#define MAXBUF 2048
#define MAXEARG 32
#define MAXWD 255

char *getpw(char *);
void killall();
void noop();

int
main(int argc, char *argv[])
{
	char	*address, bufin[MAXBUF], bufout[MAXBUF], dir[30],
		*eargv[MAXEARG], in[30], **nargv, out[30], *p, pw[255], *q,
		wd[MAXWD];
	fd_set	rfds0, rfds1;
	int	child, dumb, escape, fdin, fdout, i, interactive, n, offset,
		s, sshpass;
	struct timeval	tv;

	signal(SIGINT, noop);
	signal(SIGQUIT, killall);
	signal(SIGCHLD, killall);

	/* Create named pipes. */
	sprintf(in, "/var/tmp/rtty.in.%d", getpid());
	sprintf(out, "/var/tmp/rtty.out.%d", getpid());
	if(mkfifo(in, 0644) == -1 || mkfifo(out, 0664) == -1)
		if(errno != EEXIST)
			err(1, "mkfifo");

	/* Process rtty-specific flags. */
	escape = dumb = interactive = sshpass = 0;
	for(;argv[1][0] == '+';){
		if(strchr(argv[1], 'd')) dumb = 1;
		if(strchr(argv[1], 'i')) interactive = 1;
		if(strchr(argv[1], 'x')) escape = 1;
		if(strchr(argv[1], 'p')) sshpass = 1;

		/* Remove flag argument from argv. */
		argv[1] = argv[0];
		argv++; argc--;
	}

	/* Save pointer to address argument. */
	address = NULL;
	for(i = 1; i < argc; i++)
		if(argv[i][0] != '-'){
			address = argv[i];
			break;
		}

	/* If +p is given, immediately ask for password. */
	if(sshpass){
		printf("password: ");
		getpw(pw);
		setenv("SSHPASS", pw, 1);
		sshpass = 1;
	}

	/*
	 * A child ssh process is created, with standard in connected to
	 * the input pipe (fdin) and standard out connected to the output
	 * pipe (fdout).
	 */
	if(fork() == 0){
		if(!(fdin = open(in, O_RDONLY)))
			err(1, "open");
		if(!(fdout = open(out, O_WRONLY)))
			err(1, "open");
		dup2(fdin, 0);
		dup2(fdout, 1);

		/* Create new argument vector. */
		if(!(nargv = malloc(sizeof(char *)*(argc+10))))
			err(1, "malloc");
		offset = -1;
		if(sshpass){
			nargv[++offset] = "sshpass";
			nargv[++offset] = "-ePass";
		}
		nargv[++offset] = "ssh";
		nargv[++offset] = "-tt";
		if(!sshpass)
			nargv[++offset] = "-oBatchMode=yes";
		for(i = 1; i < argc; i++)
			nargv[i+offset] = argv[i];
		nargv[argc+offset] = NULL;

		signal(SIGINT, SIG_IGN);

		/* Exec into ssh. */
		execvp(nargv[0], nargv);
		err(1, "%s", nargv[0]);
	}

	if(!(fdin = open(in, O_WRONLY)))
		err(1, "open");
	if(!(fdout = open(out, O_RDONLY)))
		err(1, "open");

	/* Print initialization command. */
	if(interactive)
		dprintf(fdin, IINIT);
	else
		dprintf(fdin, INIT);

	FD_ZERO(&rfds0);
	FD_ZERO(&rfds1);

	tv.tv_sec = 0;
	tv.tv_usec = 1;

	for(;;){
		/*
		 * User input is read from standard in and copied to the
		 * input pipe. It is saved in bufin for later use.
		 */
		FD_SET(0, &rfds0);
		if(select(0+1, &rfds0, NULL, NULL, &tv) > 0){
			n = read(0, bufin, MAXBUF);
			bufin[n] = 0;

			/*
			 * As +x is given, escaped commands are enabled,
			 * prefixed with !. Escaped commands are run
			 * locally, but operate on remote files. Any
			 * specified remote files will be downloaded and
			 * re-uploaded when the escaped command finishes.
			 * (Escaped commands are recognized only after
			 * shell prompt.)
			 */
			if(!(escape && bufin[0] == '!'
			&& (strcmp(bufout+strlen(bufout)-2, "$ ") == 0
			|| strcmp(bufout+strlen(bufout)-2, "% ") == 0
			|| strcmp(bufout+strlen(bufout)-2, "# ") == 0))){
				dprintf(fdin, "%s", bufin);
				continue;
			}

			/*
			 * The remote server is queried for the current
			 * working directory. The response contains the
			 * query ("pwd\n"), which is skipped, followed by
			 * the working directory ("/some/path\n") and then
			 * a shell prompt, which is skipped.
			 */
			dprintf(fdin, "pwd\n");
			for(i = 0; i < MAXWD-1; i++){
				read(fdout, wd, 1);
				if(*wd == '\n') break;
			}
			n = read(fdout, wd, MAXWD);
			wd[strcspn(wd, "\n\015")] = 0;

			/* Construct corresponding argument vector. */
			bufin[strcspn(bufin, "\n")] = 0;
			p = bufin+1;
			i = 0;
			for(q = strtok(p, " "); q;
			(q = strtok(NULL, " ")), i++)
				if(i < MAXEARG-1)
					eargv[i] = q;
			eargv[i] = NULL;

			for(i = 1; eargv[i]; i++)
				if(eargv[i][0] != '-'
				&& eargv[i][0] != '+')
					goto found;
			fprintf(stderr, "no file specified\n");
			goto done;
found:
			if(eargv[i+1]){
				fprintf(stderr,
					"more than one file given\n");
				goto done;
			}

			/* Create a temporary local directory. */
			strcpy(dir, "/tmp/rtty.XXXXXX");
			if(!mkdtemp(dir)){
				warn("mkdtemp");
				continue;
			}
			chdir(dir);

			/* Construct argument to scp. */
			if(!(p = malloc(strlen(address)-1+strlen(wd)-1
			+strlen(eargv[i])-1+3)))
				err(1, "malloc");
			if(eargv[i][0] == '/'){
				sprintf(p, "%s:%s", address, eargv[i]);
			}else
				sprintf(p, "%s:%s/%s", address, wd, eargv[i]);
			q = strrchr(eargv[i], '/');
			if(q) eargv[i] = q+1;

			/*
			 * During the execution of the external commands,
			 * the SIGCHLD handler is temporarily disabled.
			 */
			signal(SIGCHLD, NULL);

			/* Download file. */
			if((child = fork()) == 0){
				execlp("scp", "scp", p, ".", NULL);
				err(1, "scp");
			}
			waitpid(child, &s, WALLSIG);
			if(WIFEXITED(s) && WEXITSTATUS(s)){
				fprintf(stderr, "scp terminated abnormally\n");
				fprintf(stderr, "file saved in %s\n", dir);
				goto done;
			}

			/* Run escaped command. */
			if((child = fork()) == 0){
				signal(SIGINT, SIG_IGN);
				execvp(eargv[0], eargv);
				err(1, "%s", eargv[0]);
			}
			waitpid(child, &s, WALLSIG);
			if(WIFEXITED(s) && WEXITSTATUS(s)){
				fprintf(stderr, "%s terminated abnormally\n",
					eargv[0]);
				fprintf(stderr, "file saved in %s\n", dir);
				goto done;
			}

			/* Upload file. */
			if((child = fork()) == 0){
				execlp("scp", "scp", eargv[i], p, NULL);
				err(1, "scp");
			}
			waitpid(child, &s, WALLSIG);
			if(WIFEXITED(s) && WEXITSTATUS(s)){
				fprintf(stderr, "scp terminated abnormally\n");
				fprintf(stderr, "file saved in %s\n", dir);
				goto done;
			}

			/* Remove temporary directory. */
			unlink(eargv[i]);
			rmdir(dir);

			/* Clean up. */
done:
			signal(SIGCHLD, killall);
			free(p);

			/*
			 * After an escaped command, an empty line is sent
			 * to the remote server, in order for a new shell
			 * prompt to be triggered.
			 */
			dprintf(fdin, "\n");
		}

		/*
		 * System output is read from the output pipe and copied
		 * to standard out for the user to see.
		 */
		FD_SET(fdout, &rfds1);
		if(select(fdout+1, &rfds1, NULL, NULL, &tv) > 0){
			n = read(fdout, bufout, MAXBUF);
			bufout[n] = 0;

			/*
			 * Bufin and bufout are copied to the temporary
			 * pointers p and q. p is incremented in order to
			 * skip any potential repetition of the command
			 * given by the user on standard in. (It is assumed
			 * that the typed command fits in bufin, i.e. is
			 * not larger than MAXBUF.)
			 */
			p = bufin;
			q = bufout;
			for(;;){
				if(*q == '\n'){
					q++;
					break;
				}
				if(*q == 13){
					q++;
					continue;
				}
				if(*p != *q){
					q = bufout;
					break;
				}
				p++; q++;
			}

			/*
			 * Bo is printed and bufin is cleared, so as not
			 * to perform the skip again, incorrectly.
			 */
			printf("%s", q);
			fflush(stdout);
			bufin[0] = 0;

			/*
			 * Unless the +d flag is given, rtty tries to detect
			 * password prompts and hide the user's input.
			 */
			if(dumb)
				continue;
			if(q[strlen(q)-1] == ':'
			|| strcmp(q+strlen(q)-2, ": ") == 0){
				if(!(q = strrchr(bufout, '\n')))
					q = bufout;
				if(strstr(q, "password")
				|| strstr(q, "Password")
				|| strstr(q, "passphrase")
				|| strstr(q, "Passphrase")
				|| strstr(q, "pass phrase")
				|| strstr(q, "Pass phrase")){
					getpw(pw);
					dprintf(fdin, "%s\n", pw);
				}
			}
		}
	}

}

char *
getpw(char *pw)
{
	struct termios orig, term;

	tcgetattr(0, &orig);
	tcgetattr(0, &term);
	term.c_lflag &= ~ECHO;
	tcsetattr(0, TCSANOW, &term);

	fgets(pw, 255, stdin);
	pw[strcspn(pw, "\n")] = 0;

	printf("\n");
	tcsetattr(0, TCSAFLUSH, &orig);

	return pw;
}

void
noop()
{
}

void
killall(int s)
{
	kill(0, SIGTERM);
	exit(1);
}