summaryrefslogtreecommitdiff
path: root/usr.bin/cu/cu.c
blob: efa2f4f05d7a08b0c00482b9575ce41e90848e1d (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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/* $OpenBSD: cu.c,v 1.24 2015/10/16 07:01:53 deraadt Exp $ */

/*
 * Copyright (c) 2012 Nicholas Marriott <nicm@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/ioctl.h>

#include <ctype.h>
#include <err.h>
#include <event.h>
#include <fcntl.h>
#include <getopt.h>
#include <paths.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <limits.h>

#include "cu.h"

extern char		*__progname;

FILE			*record_file;
struct termios		 saved_tio;
struct bufferevent	*input_ev;
struct bufferevent	*output_ev;
int			 is_direct = -1;
const char		*line_path = NULL;
int			 line_speed = -1;
int			 line_fd;
struct termios		 line_tio;
struct bufferevent	*line_ev;
struct event		 sigterm_ev;
struct event		 sighup_ev;
enum {
	STATE_NONE,
	STATE_NEWLINE,
	STATE_TILDE
} last_state = STATE_NEWLINE;

__dead void	usage(void);
void		signal_event(int, short, void *);
void		stream_read(struct bufferevent *, void *);
void		stream_error(struct bufferevent *, short, void *);
void		line_read(struct bufferevent *, void *);
void		line_error(struct bufferevent *, short, void *);
void		try_remote(const char *, const char *, const char *);

__dead void
usage(void)
{
	fprintf(stderr, "usage: %s [-d] [-l line] [-s speed | -speed]\n",
	    __progname);
	fprintf(stderr, "       %s [host]\n", __progname);
	exit(1);
}

int
main(int argc, char **argv)
{
	const char	*errstr;
	char		*tmp, *s, *host;
	int		 opt, i, flags;

	if (pledge("stdio rpath wpath cpath getpw proc exec tty",
	    NULL) == -1)
		err(1, "pledge");

	if (isatty(STDIN_FILENO) && tcgetattr(STDIN_FILENO, &saved_tio) != 0)
		err(1, "tcgetattr");

	/*
	 * Convert obsolescent -### speed to modern -s### syntax which getopt()
	 * can handle.
	 */
	for (i = 1; i < argc; i++) {
		if (strcmp("--", argv[i]) == 0)
			break;
		if (argv[i][0] != '-' || !isdigit((unsigned char)argv[i][1]))
			continue;

		if (asprintf(&argv[i], "-s%s", &argv[i][1]) == -1)
			errx(1, "speed asprintf");
	}

	while ((opt = getopt(argc, argv, "dl:s:")) != -1) {
		switch (opt) {
		case 'd':
			is_direct = 1;
			break;
		case 'l':
			line_path = optarg;
			break;
		case 's':
			line_speed = strtonum(optarg, 0, INT_MAX, &errstr);
			if (errstr != NULL)
				errx(1, "speed is %s: %s", errstr, optarg);
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 0 && argc != 1)
		usage();

	if (line_path != NULL || line_speed != -1 || is_direct != -1) {
		if (argc != 0)
			usage();
	} else {
		if (argc == 1)
			host = argv[0];
		else
			host = getenv("HOST");
		if (host != NULL && *host != '\0') {
			if (*host == '/')
				line_path = host;
			else {
				s = getenv("REMOTE");
				if (s != NULL && *s == '/')
					try_remote(host, s, NULL);
				else
					try_remote(host, NULL, s);
			}
		}
	}

	if (line_path == NULL)
		line_path = "/dev/cua00";
	if (line_speed == -1)
		line_speed = 9600;
	if (is_direct == -1)
		is_direct = 0;

	if (strchr(line_path, '/') == NULL) {
		if (asprintf(&tmp, "%s%s", _PATH_DEV, line_path) == -1)
			err(1, "asprintf");
		line_path = tmp;
	}

	flags = O_RDWR;
	if (is_direct)
		flags |= O_NONBLOCK;
	line_fd = open(line_path, flags);
	if (line_fd < 0)
		err(1, "open(\"%s\")", line_path);
	if (ioctl(line_fd, TIOCEXCL) != 0)
		err(1, "ioctl(TIOCEXCL)");
	if (tcgetattr(line_fd, &line_tio) != 0)
		err(1, "tcgetattr");
	if (set_line(line_speed) != 0)
		err(1, "tcsetattr");

	event_init();

	signal_set(&sigterm_ev, SIGTERM, signal_event, NULL);
	signal_add(&sigterm_ev, NULL);
	signal_set(&sighup_ev, SIGHUP, signal_event, NULL);
	signal_add(&sighup_ev, NULL);
	if (signal(SIGINT, SIG_IGN) == SIG_ERR)
		err(1, "signal");
	if (signal(SIGQUIT, SIG_IGN) == SIG_ERR)
		err(1, "signal");

	set_termios(); /* after this use cu_err and friends */

	/* stdin and stdout get separate events */
	input_ev = bufferevent_new(STDIN_FILENO, stream_read, NULL,
	    stream_error, NULL);
	bufferevent_enable(input_ev, EV_READ);
	output_ev = bufferevent_new(STDOUT_FILENO, NULL, NULL, stream_error,
	    NULL);
	bufferevent_enable(output_ev, EV_WRITE);

	set_blocking(line_fd, 0);
	line_ev = bufferevent_new(line_fd, line_read, NULL, line_error,
	    NULL);
	bufferevent_enable(line_ev, EV_READ|EV_WRITE);

	printf("Connected to %s (speed %d)\r\n", line_path, line_speed);
	event_dispatch();

	restore_termios();
	printf("\r\n[EOT]\n");

	exit(0);
}

void
signal_event(int fd, short events, void *data)
{
	restore_termios();
	printf("\r\n[SIG%s]\n", sys_signame[fd]);

	exit(0);
}

void
set_blocking(int fd, int state)
{
	int mode;

	state = state ? 0 : O_NONBLOCK;
	if ((mode = fcntl(fd, F_GETFL)) == -1)
		cu_err(1, "fcntl");
	if ((mode & O_NONBLOCK) != state) {
		mode = (mode & ~O_NONBLOCK) | state;
		if (fcntl(fd, F_SETFL, mode) == -1)
			cu_err(1, "fcntl");
	}
}

void
set_termios(void)
{
	struct termios tio;

	if (!isatty(STDIN_FILENO))
		return;

	memcpy(&tio, &saved_tio, sizeof(tio));
	tio.c_lflag &= ~(ICANON|IEXTEN|ECHO);
	tio.c_iflag &= ~(INPCK|ICRNL);
	tio.c_oflag &= ~OPOST;
	tio.c_cc[VMIN] = 1;
	tio.c_cc[VTIME] = 0;
	tio.c_cc[VDISCARD] = _POSIX_VDISABLE;
	tio.c_cc[VDSUSP] = _POSIX_VDISABLE;
	tio.c_cc[VINTR] = _POSIX_VDISABLE;
	tio.c_cc[VLNEXT] = _POSIX_VDISABLE;
	tio.c_cc[VQUIT] = _POSIX_VDISABLE;
	tio.c_cc[VSUSP] = _POSIX_VDISABLE;
	if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio) != 0)
		cu_err(1, "tcsetattr");
}

void
restore_termios(void)
{
	if (isatty(STDIN_FILENO))
		tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_tio);
}

int
set_line(int speed)
{
	struct termios	 tio;

	memcpy(&tio, &line_tio, sizeof(tio));
	tio.c_iflag &= ~(ISTRIP|ICRNL);
	tio.c_oflag &= ~OPOST;
	tio.c_lflag &= ~(ICANON|ISIG|IEXTEN|ECHO);
	tio.c_cflag &= ~(CSIZE|PARENB);
	tio.c_cflag |= CREAD|CS8|CLOCAL;
	tio.c_cc[VMIN] = 1;
	tio.c_cc[VTIME] = 0;
	cfsetspeed(&tio, speed);
	if (tcsetattr(line_fd, TCSAFLUSH, &tio) != 0)
		return (-1);
	return (0);
}

void
stream_read(struct bufferevent *bufev, void *data)
{
	char	*new_data, *ptr;
	size_t	 new_size;
	int	 state_change;

	new_data = EVBUFFER_DATA(input_ev->input);
	new_size = EVBUFFER_LENGTH(input_ev->input);
	if (new_size == 0)
		return;

	state_change = isatty(STDIN_FILENO);
	for (ptr = new_data; ptr < new_data + new_size; ptr++) {
		switch (last_state) {
		case STATE_NONE:
			if (state_change && *ptr == '\r')
				last_state = STATE_NEWLINE;
			break;
		case STATE_NEWLINE:
			if (state_change && *ptr == '~') {
				last_state = STATE_TILDE;
				continue;
			}
			if (*ptr != '\r')
				last_state = STATE_NONE;
			break;
		case STATE_TILDE:
			do_command(*ptr);
			last_state = STATE_NEWLINE;
			continue;
		}

		bufferevent_write(line_ev, ptr, 1);
	}

	evbuffer_drain(input_ev->input, new_size);
}

void
stream_error(struct bufferevent *bufev, short what, void *data)
{
	event_loopexit(NULL);
}

void
line_read(struct bufferevent *bufev, void *data)
{
	char	*new_data;
	size_t	 new_size;

	new_data = EVBUFFER_DATA(line_ev->input);
	new_size = EVBUFFER_LENGTH(line_ev->input);
	if (new_size == 0)
		return;

	if (record_file != NULL)
		fwrite(new_data, 1, new_size, record_file);
	bufferevent_write(output_ev, new_data, new_size);

	evbuffer_drain(line_ev->input, new_size);
}

void
line_error(struct bufferevent *bufev, short what, void *data)
{
	event_loopexit(NULL);
}

void
try_remote(const char *host, const char *path, const char *entry)
{
	const char	*paths[] = { "/etc/remote", NULL, NULL };
	char		*cp, *s;
	long		 l;
	int		 error;

	if (path != NULL) {
		paths[0] = path;
		paths[1] = "/etc/remote";
	}

	if (entry != NULL && cgetset(entry) != 0)
		cu_errx(1, "cgetset failed");
	error = cgetent(&cp, (char **)paths, (char *)host);
	if (error < 0) {
		switch (error) {
		case -1:
			cu_errx(1, "unknown host %s", host);
		case -2:
			cu_errx(1, "can't open remote file");
		case -3:
			cu_errx(1, "loop in remote file");
		default:
			cu_errx(1, "unknown error in remote file");
		}
	}

	if (is_direct == -1 && cgetcap(cp, "dc", ':') != NULL)
		is_direct = 1;

	if (line_path == NULL && cgetstr(cp, "dv", &s) >= 0)
		line_path = s;

	if (line_speed == -1 && cgetnum(cp, "br", &l) >= 0) {
		if (l < 0 || l > INT_MAX)
			cu_errx(1, "speed out of range");
		line_speed = l;
	}
}

/* Expands tildes in the file name. Based on code from ssh/misc.c. */
char *
tilde_expand(const char *filename1)
{
	const char	*filename, *path, *sep;
	char		 user[128], *out;
	struct passwd	*pw;
	u_int		 len, slash;
	int		 rv;

	if (*filename1 != '~')
		goto no_change;
	filename = filename1 + 1;

	path = strchr(filename, '/');
	if (path != NULL && path > filename) {		/* ~user/path */
		slash = path - filename;
		if (slash > sizeof(user) - 1)
			goto no_change;
		memcpy(user, filename, slash);
		user[slash] = '\0';
		if ((pw = getpwnam(user)) == NULL)
			goto no_change;
	} else if ((pw = getpwuid(getuid())) == NULL)	/* ~/path */
		goto no_change;

	/* Make sure directory has a trailing '/' */
	len = strlen(pw->pw_dir);
	if (len == 0 || pw->pw_dir[len - 1] != '/')
		sep = "/";
	else
		sep = "";

	/* Skip leading '/' from specified path */
	if (path != NULL)
		filename = path + 1;

	if ((rv = asprintf(&out, "%s%s%s", pw->pw_dir, sep, filename)) == -1)
		cu_err(1, "asprintf");
	if (rv >= PATH_MAX) {
		free(out);
		goto no_change;
	}

	return (out);

no_change:
	out = strdup(filename1);
	if (out == NULL)
		cu_err(1, "strdup");
	return (out);
}