xref: /freebsd/usr.sbin/watch/watch.c (revision 271c3a9060f2ee55607ebe146523f888e1db2654)
1 /*
2  * Copyright (c) 1995 Ugen J.S.Antsilevich
3  *
4  * Redistribution and use in source forms, with and without modification,
5  * are permitted provided that this entire comment appears intact.
6  *
7  * Redistribution in binary form may occur without any restrictions.
8  * Obviously, it would be nice if you gave credit where credit is due
9  * but requiring it would be too onerous.
10  *
11  * This software is provided ``AS IS'' without any warranties of any kind.
12  *
13  * Snoop stuff.
14  */
15 
16 #include <sys/cdefs.h>
17 __FBSDID("$FreeBSD$");
18 
19 #include <sys/param.h>
20 #include <sys/fcntl.h>
21 #include <sys/filio.h>
22 #include <sys/snoop.h>
23 #include <sys/stat.h>
24 #include <sys/linker.h>
25 #include <sys/module.h>
26 
27 #include <err.h>
28 #include <errno.h>
29 #include <locale.h>
30 #include <paths.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sysexits.h>
36 #include <termcap.h>
37 #include <termios.h>
38 #include <time.h>
39 #include <unistd.h>
40 
41 #define MSG_INIT	"Snoop started."
42 #define MSG_OFLOW	"Snoop stopped due to overflow. Reconnecting."
43 #define MSG_CLOSED	"Snoop stopped due to tty close. Reconnecting."
44 #define MSG_CHANGE	"Snoop device change by user request."
45 #define MSG_NOWRITE	"Snoop device change due to write failure."
46 
47 
48 #define DEV_NAME_LEN	1024	/* for /dev/ttyXX++ */
49 #define MIN_SIZE	256
50 
51 #define CHR_SWITCH	24	/* Ctrl+X	 */
52 #define CHR_CLEAR	23	/* Ctrl+V	 */
53 
54 static void	clear(void);
55 static void	timestamp(const char *);
56 static void	set_tty(void);
57 static void	unset_tty(void);
58 static void	fatal(int, const char *);
59 static int	open_snp(void);
60 static void	cleanup(int);
61 static void	usage(void) __dead2;
62 static void	setup_scr(void);
63 static void	attach_snp(void);
64 static void	detach_snp(void);
65 static void	set_dev(const char *);
66 static void	ask_dev(char *, const char *);
67 
68 int             opt_reconn_close = 0;
69 int             opt_reconn_oflow = 0;
70 int             opt_interactive = 1;
71 int             opt_timestamp = 0;
72 int		opt_write = 0;
73 int		opt_no_switch = 0;
74 const char	*opt_snpdev;
75 
76 char            dev_name[DEV_NAME_LEN];
77 int             snp_io;
78 int             std_in = 0, std_out = 1;
79 
80 
81 int             clear_ok = 0;
82 struct termios  otty;
83 char            tbuf[1024], gbuf[1024];
84 
85 
86 static void
87 clear(void)
88 {
89 	if (clear_ok)
90 		tputs(gbuf, 1, putchar);
91 	fflush(stdout);
92 }
93 
94 static void
95 timestamp(const char *buf)
96 {
97 	time_t          t;
98 	char            btmp[1024];
99 	clear();
100 	printf("\n---------------------------------------------\n");
101 	t = time(NULL);
102 	strftime(btmp, 1024, "Time: %d %b %H:%M", localtime(&t));
103 	printf("%s\n", btmp);
104 	printf("%s\n", buf);
105 	printf("---------------------------------------------\n");
106 	fflush(stdout);
107 }
108 
109 static void
110 set_tty(void)
111 {
112 	struct termios  ntty;
113 
114 	tcgetattr (std_in, &otty);
115 	ntty = otty;
116 	ntty.c_lflag &= ~ICANON;    /* disable canonical operation  */
117 	ntty.c_lflag &= ~ECHO;
118 #ifdef FLUSHO
119 	ntty.c_lflag &= ~FLUSHO;
120 #endif
121 #ifdef PENDIN
122 	ntty.c_lflag &= ~PENDIN;
123 #endif
124 #ifdef IEXTEN
125 	ntty.c_lflag &= ~IEXTEN;
126 #endif
127 	ntty.c_cc[VMIN] = 1;        /* minimum of one character */
128 	ntty.c_cc[VTIME] = 0;       /* timeout value        */
129 
130 	ntty.c_cc[VINTR] = 07;   /* ^G */
131 	ntty.c_cc[VQUIT] = 07;   /* ^G */
132 	tcsetattr (std_in, TCSANOW, &ntty);
133 }
134 
135 static void
136 unset_tty(void)
137 {
138 	tcsetattr (std_in, TCSANOW, &otty);
139 }
140 
141 
142 static void
143 fatal(int error, const char *buf)
144 {
145 	unset_tty();
146 	if (buf)
147 		errx(error, "fatal: %s", buf);
148 	else
149 		exit(error);
150 }
151 
152 static int
153 open_snp(void)
154 {
155 	int		f, mode;
156 
157 	if (opt_write)
158 		mode = O_RDWR;
159 	else
160 		mode = O_RDONLY;
161 
162 	if (opt_snpdev == NULL)
163 		f = open(_PATH_DEV "snp", mode);
164 	else
165 		f = open(opt_snpdev, mode);
166 	if (f == -1)
167 		fatal(EX_OSFILE, "cannot open snoop device");
168 
169 	return (f);
170 }
171 
172 
173 static void
174 cleanup(int signo __unused)
175 {
176 	if (opt_timestamp)
177 		timestamp("Logging Exited.");
178 	close(snp_io);
179 	unset_tty();
180 	exit(EX_OK);
181 }
182 
183 
184 static void
185 usage(void)
186 {
187 	fprintf(stderr, "usage: watch [-ciotnW] [tty name]\n");
188 	exit(EX_USAGE);
189 }
190 
191 static void
192 setup_scr(void)
193 {
194 	char           *cbuf = gbuf, *term;
195 	if (!opt_interactive)
196 		return;
197 	if ((term = getenv("TERM")))
198 		if (tgetent(tbuf, term) == 1)
199 			if (tgetstr("cl", &cbuf))
200 				clear_ok = 1;
201 	set_tty();
202 	clear();
203 }
204 
205 static void
206 detach_snp(void)
207 {
208 	int		fd;
209 
210 	fd = -1;
211 	ioctl(snp_io, SNPSTTY, &fd);
212 }
213 
214 static void
215 attach_snp(void)
216 {
217 	int		snp_tty;
218 
219 	snp_tty = open(dev_name, O_RDONLY | O_NONBLOCK);
220 	if (snp_tty < 0)
221 		fatal(EX_DATAERR, "can't open device");
222 	if (ioctl(snp_io, SNPSTTY, &snp_tty) != 0)
223 		fatal(EX_UNAVAILABLE, "cannot attach to tty");
224 	close(snp_tty);
225 	if (opt_timestamp)
226 		timestamp("Logging Started.");
227 }
228 
229 
230 static void
231 set_dev(const char *name)
232 {
233 	char            buf[DEV_NAME_LEN];
234 	struct stat	sb;
235 
236 	if (strlen(name) > 5 && !strncmp(name, _PATH_DEV, sizeof _PATH_DEV - 1)) {
237 		snprintf(buf, sizeof buf, "%s", name);
238 	} else {
239 		if (strlen(name) == 2)
240 			sprintf(buf, "%s%s", _PATH_TTY, name);
241 		else
242 			sprintf(buf, "%s%s", _PATH_DEV, name);
243 	}
244 
245 	if (*name == '\0' || stat(buf, &sb) < 0)
246 		fatal(EX_DATAERR, "bad device name");
247 
248 	if ((sb.st_mode & S_IFMT) != S_IFCHR)
249 		fatal(EX_DATAERR, "must be a character device");
250 
251 	strncpy(dev_name, buf, DEV_NAME_LEN);
252 
253 	attach_snp();
254 }
255 
256 void
257 ask_dev(char *dbuf, const char *msg)
258 {
259 	char            buf[DEV_NAME_LEN];
260 	int             len;
261 
262 	clear();
263 	unset_tty();
264 
265 	if (msg)
266 		printf("%s\n", msg);
267 	if (dbuf)
268 		printf("Enter device name [%s]:", dbuf);
269 	else
270 		printf("Enter device name:");
271 
272 	if (fgets(buf, DEV_NAME_LEN - 1, stdin)) {
273 		len = strlen(buf);
274 		if (buf[len - 1] == '\n')
275 			buf[len - 1] = '\0';
276 		if (buf[0] != '\0' && buf[0] != ' ')
277 			strcpy(dbuf, buf);
278 	}
279 	set_tty();
280 }
281 
282 #define READB_LEN	5
283 
284 int
285 main(int ac, char *av[])
286 {
287 	int             ch, res, rv, nread;
288 	size_t		b_size = MIN_SIZE;
289 	char            *buf, chb[READB_LEN];
290 	fd_set          fd_s;
291 
292 	(void) setlocale(LC_TIME, "");
293 
294 	if (isatty(std_out))
295 		opt_interactive = 1;
296 	else
297 		opt_interactive = 0;
298 
299 
300 	while ((ch = getopt(ac, av, "Wciotnf:")) != -1)
301 		switch (ch) {
302 		case 'W':
303 			opt_write = 1;
304 			break;
305 		case 'c':
306 			opt_reconn_close = 1;
307 			break;
308 		case 'i':
309 			opt_interactive = 1;
310 			break;
311 		case 'o':
312 			opt_reconn_oflow = 1;
313 			break;
314 		case 't':
315 			opt_timestamp = 1;
316 			break;
317 		case 'n':
318 			opt_no_switch = 1;
319 			break;
320 		case 'f':
321 			opt_snpdev = optarg;
322 			break;
323 		case '?':
324 		default:
325 			usage();
326 		}
327 
328 	if (modfind("snp") == -1)
329 		if (kldload("snp") == -1 || modfind("snp") == -1)
330 			warn("snp module not available");
331 
332 	signal(SIGINT, cleanup);
333 
334 	snp_io = open_snp();
335 	setup_scr();
336 
337 	if (*(av += optind) == NULL) {
338 		if (opt_interactive && !opt_no_switch)
339 			ask_dev(dev_name, MSG_INIT);
340 		else
341 			fatal(EX_DATAERR, "no device name given");
342 	} else
343 		strncpy(dev_name, *av, DEV_NAME_LEN);
344 
345 	set_dev(dev_name);
346 
347 	if (!(buf = (char *) malloc(b_size)))
348 		fatal(EX_UNAVAILABLE, "malloc failed");
349 
350 	FD_ZERO(&fd_s);
351 
352 	while (1) {
353 		if (opt_interactive)
354 			FD_SET(std_in, &fd_s);
355 		FD_SET(snp_io, &fd_s);
356 		res = select(snp_io + 1, &fd_s, NULL, NULL, NULL);
357 		if (opt_interactive && FD_ISSET(std_in, &fd_s)) {
358 
359 			if ((res = ioctl(std_in, FIONREAD, &nread)) != 0)
360 				fatal(EX_OSERR, "ioctl(FIONREAD)");
361 			if (nread > READB_LEN)
362 				nread = READB_LEN;
363 			rv = read(std_in, chb, nread);
364 			if (rv == -1 || rv != nread)
365 				fatal(EX_IOERR, "read (stdin) failed");
366 
367 			switch (chb[0]) {
368 			case CHR_CLEAR:
369 				clear();
370 				break;
371 			case CHR_SWITCH:
372 				if (!opt_no_switch) {
373 					detach_snp();
374 					ask_dev(dev_name, MSG_CHANGE);
375 					set_dev(dev_name);
376 					break;
377 				}
378 			default:
379 				if (opt_write) {
380 					rv = write(snp_io, chb, nread);
381 					if (rv == -1 || rv != nread) {
382 						detach_snp();
383 						if (opt_no_switch)
384 							fatal(EX_IOERR,
385 							  "write failed");
386 						ask_dev(dev_name, MSG_NOWRITE);
387 						set_dev(dev_name);
388 					}
389 				}
390 
391 			}
392 		}
393 		if (!FD_ISSET(snp_io, &fd_s))
394 			continue;
395 
396 		if ((res = ioctl(snp_io, FIONREAD, &nread)) != 0)
397 			fatal(EX_OSERR, "ioctl(FIONREAD)");
398 
399 		switch (nread) {
400 		case SNP_OFLOW:
401 			if (opt_reconn_oflow)
402 				attach_snp();
403 			else if (opt_interactive && !opt_no_switch) {
404 				ask_dev(dev_name, MSG_OFLOW);
405 				set_dev(dev_name);
406 			} else
407 				cleanup(-1);
408 			break;
409 		case SNP_DETACH:
410 		case SNP_TTYCLOSE:
411 			if (opt_reconn_close)
412 				attach_snp();
413 			else if (opt_interactive && !opt_no_switch) {
414 				ask_dev(dev_name, MSG_CLOSED);
415 				set_dev(dev_name);
416 			} else
417 				cleanup(-1);
418 			break;
419 		default:
420 			if (nread < (b_size / 2) && (b_size / 2) > MIN_SIZE) {
421 				free(buf);
422 				if (!(buf = (char *) malloc(b_size / 2)))
423 					fatal(EX_UNAVAILABLE, "malloc failed");
424 				b_size = b_size / 2;
425 			}
426 			if (nread > b_size) {
427 				b_size = (nread % 2) ? (nread + 1) : (nread);
428 				free(buf);
429 				if (!(buf = (char *) malloc(b_size)))
430 					fatal(EX_UNAVAILABLE, "malloc failed");
431 			}
432 			rv = read(snp_io, buf, nread);
433 			if (rv == -1 || rv != nread)
434 				fatal(EX_IOERR, "read failed");
435 			rv = write(std_out, buf, nread);
436 			if (rv == -1 || rv != nread)
437 				fatal(EX_IOERR, "write failed");
438 		}
439 	}			/* While */
440 	return(0);
441 }
442 
443