aboutsummaryrefslogtreecommitdiffstats
path: root/etc/ttytap.c
blob: 6914e6a81342a7156c5801c89350c9d0ff188898 (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
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <ctype.h>
#include <linux/ttytap.h>
#include <linux/kdev_t.h>

static void usage(void) {
	fprintf(stderr, "usage: ttytap -q|<ttyDevice>\n");
	exit(1);
}

int main(int argc, char **argv) {
	int fd;
	tapheader th;
	int i;
	int r;
	int major;
	int minor;
	int lastdir = -1;
	struct stat stbuf;
	char tbuf[256];
	unsigned char buf[4096];


	if (argc != 2)
		usage();
	if (strcmp(argv[1], "-q")) {
		if (stat(argv[1], &stbuf)) {
			perror(argv[1]);
			exit(-1);
		}
		if (!S_ISCHR(stbuf.st_mode)) {
			fprintf(stderr, "%s is not a char device\n", argv[1]);
			exit(1);
		}
		major = MAJOR(stbuf.st_rdev);
		minor = MINOR(stbuf.st_rdev);
	} else {
		minor = 0;
		major = 0;
	}
	fd = open("/proc/ttytap", O_RDONLY);
	if (fd == -1) {
		perror("/proc/ttytap");
		exit(-1);
	}
	if (ioctl(fd, TTYTAP_SETDEV, (major << 8) | minor)) {
		perror("ioctl /proc/ttytap");
		exit(-1);
	}
	if ((minor == 0) && (major == 0)) {
		printf("Serial tapping switched off\n");
		exit(0);
	}
	if (ioctl(fd, TTYTAP_GETQLEN, &i)) {
		perror("ioctl /proc/ttytap");
		exit(-1);
	}
	fprintf(stderr, "Queue length is %d\n", i);
	while (1) {
		r = read(fd, &th, sizeof(th));
		if (r != sizeof(th)) {
			perror("read /proc/ttytap");
			exit(-1);
		}
		strftime(tbuf, 255, "%H:%M:%S", localtime(&th.stamp.tv_sec));
		printf("%s.%06ld %c (%04d) ", tbuf,
			(unsigned long)th.stamp.tv_usec,
			(th.io) ? '<' : '>', th.len);
		r = read(fd, buf, th.len);
		if (r != th.len) {
			perror("read /proc/ttytap");
			exit(-1);
		}
		for (i = 0; i < th.len; i++)
			printf("%02x ", buf[i] & 255);
		for (i = 0; i < th.len; i++)
			printf("%c", isprint(buf[i]) ? buf[i] : '.');
		printf("\n"); fflush(stdout);
	}
	return 0;
}