aboutsummaryrefslogtreecommitdiff
path: root/slowbaud.c
blob: 63a8a3b833ba4cce6f38bb832dc9001b5bafbcce (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
/* Simulate low bitrate serial connection, like a 1980s modem.
   Author: B. Watson. License: WTFPL. */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <time.h>
#include <string.h>

/* portability stuff only tested on Linux and OSX. Hope it's OK. */
#if defined(__FreeBSD__) || defined(HAVE_LIBUTIL_H)
	#include <libutil.h>
#elif defined (__OpenBSD__) || defined (__NetBSD__) || defined (__APPLE__) || defined(HAVE_UTIL_H)
	#include <util.h>
#else
	#include <pty.h>
#endif

#define DEFAULT_BPS 2400
#define MIN_BPS 1
#define MAX_BPS 500000

const char *self;
unsigned int bps;
unsigned long interval, starttime, outbytes = 0;

int debug = 0;

int timer;
struct timeval tv;
struct itimerval itv, itv_disarm;
sigset_t sigmask;

#define NOW_USEC() ( (gettimeofday(&tv, NULL)), tv.tv_sec * 1000000L + tv.tv_usec )

void die(const char *msg) {
	if(errno) {
		fprintf(stderr, "%s: %s: %s\n", self, strerror(errno), msg);
	} else {
		fprintf(stderr, "%s: %s\n", self, msg);
	}
	exit(1);
}

void setup_timer(void) {
	itv_disarm.it_interval.tv_sec =
	itv_disarm.it_interval.tv_usec =
	itv_disarm.it_value.tv_sec =
	itv_disarm.it_value.tv_usec = 0;

	itv = itv_disarm;
	itv.it_interval.tv_usec = interval;
	itv.it_value.tv_usec = interval;

	sigemptyset(&sigmask);
	sigaddset(&sigmask, SIGALRM);
	sigprocmask(SIG_BLOCK, &sigmask, NULL);
}

/* on both Linux and OSX, using setitimer() and sigwait() gives better
   timing accuracy than usleep() or nanosleep(). */
void slow_write(int outfd, char c) {
	int j;
	unsigned long now, target, overslept;

	setitimer(ITIMER_REAL, &itv, NULL);

	target = NOW_USEC() + interval;

	write(outfd, &c, 1);
	outbytes++;
	sigwait(&sigmask, &j);
	setitimer(ITIMER_REAL, &itv_disarm, NULL);

	now = NOW_USEC();
	if(now > target) {
		overslept = now - target;
		if(overslept < interval) {
			itv.it_interval.tv_usec -= overslept;
			itv.it_value.tv_usec = itv.it_interval.tv_usec;
		}
	} else {
		while(NOW_USEC() < target)
			/* NOP */ ;
	}
}

void debug_stats(void) {
	if(outbytes) {
		unsigned long elapsed_us = NOW_USEC() - starttime;
		double elapsed_sec = ((double)elapsed_us/1000000.0L);
		double finterval = (1000000.0L / ((double)bps / 10.0L));
		double actual = ((double)outbytes * 10.0L) / elapsed_sec;
		double offby = 100.0L * (((double)bps / actual) - 1.0L);
		fprintf(stderr,
				"outbytes %lu, elapsed_us %lu, tv_usec %lu, requested bps %d (%.2fms), "
				"actual %.2f, accuracy %.2f%%\n",
				outbytes, elapsed_us, itv.it_value.tv_usec, bps, finterval, actual, 100.0 - offby);
	}
}

void slowcat(int infd) {
	int c;

	outbytes = 0;
	starttime = NOW_USEC();

	while(read(infd, &c, 1) == 1) {
		slow_write(1, c);
	}

	if(debug) debug_stats();
}

void slowtty(char **args) {
	char *dflt_args[] = { NULL, NULL };
	pid_t kidpid;
	int master, status;
	struct termios term, oldterm;
	struct winsize winsz;
	char c;

	if(!*args) {
		args = dflt_args;
		args[0] = getenv("SHELL");
		if(!*args) args[0] = "/bin/sh";
	}
	if(debug) {
		char **a = args;
		fprintf(stderr, "executing cmd '%s', argv[]: ", a[0]);
		while(*a) {
			fprintf(stderr, "%s ", *a++);
		}
		fprintf(stderr, "\n");
	}

	if( (tcgetattr(0, &term)) ) die("tcgetattr");

	if( (ioctl(0, TIOCGWINSZ, &winsz)) ) die("ioctl(TIOCGWINSZ)");

	kidpid = forkpty(&master, NULL, &term, &winsz);
	if(kidpid < 0) die("forkpty");

	if(kidpid == 0) {
		/* we are the child, do childish things */
		execvp(args[0], args);
		perror("execvp"); /* don't use die() */
		exit(127);
	}

	/* we are the parent, watch the child */
	oldterm = term; /* so we can restore it later */
	cfmakeraw(&term);
	tcsetattr(0, TCSANOW, &term);

	while(1) {
		ssize_t nbytes;
		fd_set readfds;

		FD_ZERO(&readfds);
		FD_SET(0, &readfds);
		FD_SET(master, &readfds);

		if(select(master + 1, &readfds, NULL, NULL, NULL) < 0) {
			if(errno == EINTR) continue;
			break;
		}

      if(FD_ISSET(0, &readfds)) {
			nbytes = read(0, &c, 1);
			if(nbytes < 1) break;
			write(master, &c, 1);
		}

      if(FD_ISSET(master, &readfds)) {
			nbytes = read(master, &c, 1);
			if(nbytes < 1) break;
			slow_write(1, c);
		}
	}

	close(master);
	while (waitpid(kidpid, &status, 0) < 0 && errno == EINTR) /* NOP */ ;

	tcsetattr(STDIN_FILENO, TCSANOW, &oldterm);
	tcsetattr(STDOUT_FILENO, TCSANOW, &oldterm);
	tcsetattr(STDERR_FILENO, TCSANOW, &oldterm);

	exit(WIFEXITED(status) ? WEXITSTATUS(status) : 127);
}

void echo_args(char **args) {
	starttime = NOW_USEC();
	while(*args) {
		char *a = *args;
		while(*a) slow_write(1, *a++);
		args++;
		if(*args) slow_write(1, ' ');
	}

	slow_write(1, '\n');

	if(debug) debug_stats();
	exit(0);
}

void benchmark(char **args) {
	int bytes = 0, devnull;

	if(*args) bytes = atoi(*args);
	if(bytes < 1) bytes = 4096;
	fprintf(stderr, "benchmarking with %d bytes\n", bytes);

	devnull = open("/dev/null", O_RDONLY);
	if(devnull < 1) die("/dev/null");

	starttime = NOW_USEC();
	while(bytes--)
		slow_write(devnull, 0);
	close(devnull);

	debug_stats();
	exit(0);
}

void usage(int exitstat) {
	printf("Usage: %s [<bits-per-sec>] [<file> [<file> ...]]\n", self);
	printf("       With no filenames, reads stdin.\n");
	printf("or:    %s [<bits-per-sec>] -c [<command> [<arg> ...]]\n", self);
	printf("       With no command, spawns a shell.\n");
	printf("or:    %s [<bits-per-sec>] -e <string> [<string> ...]\n", self);
	printf("or:    %s [<bits-per-sec>] -b [<bytes>]\n", self);
	printf("With no <bits-per-sec>, default rate is %d\n", DEFAULT_BPS);
	exit(exitstat);
}

int main(int argc, char **argv) {
	int infd;
	const char *p, *env_bps;

	if(getenv("SLOWBAUD_DEBUG")) debug = 1;

	/* for usage message, we want "slowbaud", not "/path/to/slowbaud" */
	self = argv[0];
	for(p = argv[0]; *p; p++) {
		if(*p == '/') self = p + 1;
	}
	argv++, argc--;

	/* set bps. command line option overrides env, env overrides builtin */
	bps = DEFAULT_BPS;

	if( (env_bps = getenv("SLOWBAUD_BPS")) )
		bps = atoi(env_bps);

	if(*argv && (**argv > '0' && **argv <= '9')) {
		char *e;
		long b = strtol(*argv, &e, 0);
		if(!*e) {
			bps = (int)b;
			argv++, argc--;
		}
	}

	if(bps < MIN_BPS || bps > MAX_BPS) {
		fprintf(stderr, "%s: invalid bps, range %d - %d\n", self, MIN_BPS, MAX_BPS);
		exit(1);
	}

	/* if we used only integer math here, we couldn't support bps not
      a multiple of 10 (e.g. 75 would be taken as 70).
      We still have a rounding problem: 115200bps is 86.81ms/char, but
      it gets rounded down to 86 here. Which would be around 116279bps,
      or almost 1% too fast. We never reach 100% speed anyway, so the
      loss from overhead actually offsets the extra bit of speed.
	 */
	interval = (unsigned long)(1000000.0L / ((double)bps / 10.0L));
	if(debug) fprintf(stderr, "interval %ld us\n", interval);

	if(*argv && argv[0][0] == '-' && argv[0][1] == '-' && !argv[0][2]) {
		if(debug) fprintf(stderr, "skipping -- argument\n");
		argv++, argc--;
	}

	setup_timer();

	if(!argc) {
		if(debug) fprintf(stderr, "no args, reading stdin\n");
		slowcat(0);
	} else if(**argv == '-') {
		switch(argv[0][1]) {
			case 'c':
				if(debug) fprintf(stderr, "-c given, creating a pty\n");
				slowtty(++argv);
				break;
			case 'e':
				if(argc < 2) die("-e requires at least one argument");
				if(debug) fprintf(stderr, "-e given, echoing args\n");
				echo_args(++argv);
				break;
			case 'b':
				benchmark(++argv);
				break;
			case 'h':
			case '?':
				usage(0);
				break;
			default:
				die("invalid option, try -h for help");
				break;
		}
	} else {
		while(*argv) {
			if(debug) fprintf(stderr, "opening file %s for reading\n", *argv);
			if( (infd = open(*argv, O_RDONLY)) < 0) {
				die(*argv);
			}
			slowcat(infd);
			close(infd);
			argv++;
		}
	}
	exit(0);
}