aboutsummaryrefslogtreecommitdiff
path: root/jsmond.c
blob: b0d6d6d3811e79ebbbbfee3a93259a97a200e554 (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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
/* need this, or else we don't get a prototype for strdup() from string.h */
#define _XOPEN_SOURCE 500

#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include <errno.h>

#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/extensions/XTest.h>

#include <linux/joystick.h>
#include <sys/inotify.h>

/* microseconds to wait between sending a keypresss
   or mouse click event and its release */
#define EVENT_DELAY 100000

/* if we can't find an unused keycode in the X keymap, use this one */
#define FALLBACK_KEYCODE 255

/* min/max allowed keycodes. really this should be queried from
   the X server, but for Xorg this value is good enough for
   argument checking. the max is 0xff as keycodes are 8 bit unsigned. */
#define MIN_KEYCODE 8
#define MAX_KEYCODE 255

/* same as above, for mouse buttons. */
#define MIN_BUTTON 1
#define MAX_BUTTON 10

typedef enum {
	fm_auto_keycode, fm_keycode, fm_button, fm_motion
} fake_mode_t;

/* user options */
int interval = 250;              /* -i */
int debug = 0;                   /* -D */
int keycode = -1;                /* -k */
int button = -1;                 /* -b */
char *event_dir = EVENTDIR;      /* -d */
char *js_node_name = JSNODE;     /* -j */
int autodiscover = 1; /* cleared if user supplies joydev args */
fake_mode_t fake_mode = fm_auto_keycode;  /* -b, -m */

/* joystick stuff */
char *joynames[MAX_STICKS + 1];
int last_joyname = 0;
int joyfds[MAX_STICKS + 1];

const char *self;

/* X stuff */
Display *xdisp;

/* inotify stuff */
int inotify_fd, watch_fd;
char inotify_buf[sizeof(struct inotify_event) + NAME_MAX + 1];
struct inotify_event *inotify_ev = (struct inotify_event *)inotify_buf;

void usage(void) {
	printf("jsmond v" VERSION " by B. Watson, WTFPL\n");
	printf("Usage: %s [-i interval] [-b button | -k keycode] [-j name]\n", self);
	printf("              [-d dir] [-D] [joystick [...]]\n");
	printf("Built-in defaults: MAX_STICKS=%d, -d " EVENTDIR ", -j " JSNODE "\n", MAX_STICKS);
	printf("See man page for details\n");
	exit(0);
}

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

/* make some trivial Xlib call that will result in Xlib killing
   this process if it fails. XNoOp looks like it was meant for
   exactly this, but it keeps returning 1 even if the X server is killed. */
void ping_x_server(void) {
	(void)XPending(xdisp);
	if(debug) fprintf(stderr, "X server is still alive\n");
}

void send_fake_key(void) {
	if(debug) fprintf(stderr, "sending keycode %d\n", keycode);

	/* press... */
	XTestFakeKeyEvent(xdisp, keycode, 1, 0L);
	XSync(xdisp, 0);

	/* ...wait 1/10 sec... */
	usleep(EVENT_DELAY);

	/* ...release */
	XTestFakeKeyEvent(xdisp, keycode, 0, 0L);
	XSync(xdisp, 0);
}

void send_fake_click(void) {
	if(debug) fprintf(stderr, "sending button %d click\n", button);

	/* press... */
	XTestFakeButtonEvent(xdisp, button, 1, 0L);
	XSync(xdisp, 0);

	/* ...wait 1/10 sec... */
	usleep(EVENT_DELAY);

	/* ...release */
	XTestFakeButtonEvent(xdisp, button, 0, 0L);
	XSync(xdisp, 0);
}

/* XXX: the man page documents XTestFakeRelativeMotionEvent()
   as taking 5 arguments (2nd one is screen_number), but Xtst.h
	only has 4 (with no screen_number arg). */
void send_fake_motion(void) {
	int oldx, oldy, ignoreme;
	Window win_ignoreme;

	if(debug) fprintf(stderr, "sending mouse motion\n");

	XQueryPointer(
			xdisp,
			DefaultRootWindow(xdisp),
			&win_ignoreme,
			&win_ignoreme,
			&oldx,
			&oldy,
			&ignoreme,
			&ignoreme,
			(unsigned int *)&ignoreme);

	if(debug) fprintf(stderr, "oldx %d, oldy %d\n", oldx, oldy);

	/* move... */
	XTestFakeRelativeMotionEvent(xdisp, 10, 10, 0L);
	XSync(xdisp, 0);

	/* ...wait 1/10 sec... */
	usleep(EVENT_DELAY);

	/* ...move back */
	XTestFakeRelativeMotionEvent(xdisp, -10, -10, 0L);
	XSync(xdisp, 0);

	/* we've moved all 4 directions now. but if were were too close
	   to an edge of the screen, the mouse pointer isn't where it
	   started. so: */
	XWarpPointer(
			xdisp,
			None,
			DefaultRootWindow(xdisp),
			0,
			0,
			0,
			0,
			oldx, oldy);
	XSync(xdisp, 0);
}

void send_fake_x_event(void) {
	switch(fake_mode) {
		case fm_keycode:
			send_fake_key();
			break;
		case fm_button:
			send_fake_click();
			break;
		case fm_motion:
			send_fake_motion();
			break;
		default: /* This Never Happens(tm) */
			fprintf(stderr, "%s: BUG: fake_mode %d isn't a valid fake_mode_t!\n",
					self, fake_mode);
			exit(1);
			break;
	}
}

void open_joysticks(void) {
	int fdcount, i;
	struct js_event e;

	fdcount = 0;
	for(i = 0; i < last_joyname; i++) {
		int synthev = 0;
		if(joyfds[i] > -1) close(joyfds[i]);
		joyfds[i] = open(joynames[i], O_RDONLY | O_NONBLOCK);
		if(joyfds[i] > -1) {
			fdcount++;
			while( (read(joyfds[i], &e, sizeof(e)) > 0) && (e.type & JS_EVENT_INIT) )
				synthev++;
			if(debug)
				fprintf(stderr, "opened %s, fd %d, skipped %d synthetic events\n",
						joynames[i], joyfds[i], synthev);
		}
	}
	if(debug) fprintf(stderr, "opened %d devices\n", fdcount);
}

void init_joysticks(void) {
	int i;

	for(i = 0; i < MAX_STICKS; i++)
		joyfds[i] = -1;

	open_joysticks();
}

void check_inotify() {
	int res;

	res = read(inotify_fd, inotify_buf, sizeof(inotify_buf) + NAME_MAX + 1);

	if(res > 0) {
		if(debug) {
			fprintf(stderr, "read %d bytes from inotify_fd\n", res);
			if(!inotify_ev->len) {
				fprintf(stderr, "got event with no name: %x\n", inotify_ev->mask);
			} else {
				fprintf(stderr, "got event with name %s: %x\n", inotify_ev->name, inotify_ev->mask);
			}
		}
		usleep(EVENT_DELAY); /* might not need, be paranoid */
		open_joysticks();
	} else {
		if(errno != EAGAIN) {
			fprintf(stderr, "%s: failed to read from inotify_fd: %s\n",
					self, strerror(errno));
			exit(1);
		}
	}
}

/* this is the point of no return. the only way out of main_loop()
   is process death. */
void main_loop(void) {
	struct js_event e;
	int i, active, sleep_us;

	fprintf(stderr, "entering main_loop()\n");

	sleep_us = interval * 1000;
	while(1) {
		/* Xlib will obligingly kill us, if X goes away */
		ping_x_server();

		/* check_inotify() will close & reopen the joystick fds as needed */
		check_inotify();

		/* let the fds gather events as we slumber */
		if(debug) fprintf(stderr, "sleeping %dms...\n", interval);
		usleep(sleep_us);

		/* now see if any of them got any events while we took a nap */
		active = 0;
		for(i = 0; i < last_joyname; i++) {
			if(joyfds[i] < 0) continue;

			if(debug) fprintf(stderr, "reading device %d, fd %d\n", i, joyfds[i]);

			/* count events. any we get here *should* be real, but it doesn't
			   hurt to mask out synthetic ones again */
			while(read(joyfds[i], &e, sizeof(e)) > 0) {
				if(!(e.type & JS_EVENT_INIT)) active++;
			}

			/* EAGAIN just means there are no more events to read.
			   anything else is a problem, though not fatal */
			if(errno != EAGAIN) {
				if(debug) fprintf(stderr, "got error on device %d: %s\n", i, strerror(errno));
			}
		}

		/* if we got any activity on any of the fds, do our thing */
		if(active) {
			if(debug) fprintf(stderr, "*** got activity!\n");
			send_fake_x_event();
		} else if(debug) fprintf(stderr, "no activity\n");
	}
}

/* make self point to our executable name without any directory */
void set_exe_name(const char *argv0) {
	const char *p;
	self = argv0;
	for(p = self; *p; p++)
		if(p[0] == '/' && p[1]) self = p + 1;
}

char *make_joystick_name(int js) {
	static char buf[PATH_MAX + 1];
	sprintf(buf, "%s/%s%d", event_dir, js_node_name, js);
	return buf;
}

/* add a joystick by pathname or number. note this only gets
   called once, at startup: the list never gets modified after that. */
void add_joystick_name(const char *name) {
	if(last_joyname >= MAX_STICKS) {
		fprintf(stderr,
				"%s: too many device names, monitoring only the first %d\n",
				self,
				last_joyname);
		return;
	}

	if(*name >= '0' && *name <= '9') {
		add_joystick_name(make_joystick_name(atoi(name)));
		return;
	}

	if( !(joynames[last_joyname] = strdup(name)) )
		die(strerror(errno));

	if(debug)
		fprintf(stderr, "added device name %d: %s\n", last_joyname, name);

	last_joyname++;
}

void populate_joynames(void) {
	int i;

	for(i = 0; i < MAX_STICKS; i++) {
		add_joystick_name(make_joystick_name(i));
	}
}

void set_fake_mode(fake_mode_t newmode) {
	if(fake_mode != fm_auto_keycode)
		die("use only one of the -k -b -m options");
	else
		fake_mode = newmode;
}

void parse_args(int argc, char **argv) {
	char *nextarg;

	if(argc > 1 && strcmp(argv[1], "--help") == 0) usage();

	while(++argv, --argc) {
		if(argv[0][0] == '-') {
			if(argv[0][1] && argv[0][2])
				die("spaces required between options and arguments, please");
			nextarg = argv[1];
			switch(argv[0][1]) {
				case 'm':
					set_fake_mode(fm_motion);
					break;
				case 'k':
					if(nextarg &&
							(keycode = atoi(nextarg)) &&
							(keycode >= MIN_KEYCODE) &&
							(keycode <= MAX_KEYCODE) )
					{
						set_fake_mode(fm_keycode);
						argv++, argc--;
					} else {
						fprintf(stderr, "%s: -k requires a keycode argument, %d-%d\n",
								self, MIN_KEYCODE, MAX_KEYCODE);
						exit(1);
					}
					break;
				case 'b':
					if(nextarg) button = atoi(nextarg);
					if ( (button >= MIN_BUTTON) && (button <= MAX_BUTTON) ) {
						set_fake_mode(fm_button);
						argv++, argc--;
					} else {
						fprintf(stderr, "%s: -b requires a mouse button argument, %d-%d\n",
								self, MIN_BUTTON, MAX_BUTTON);
						exit(1);
					}
					break;
				case 'i':
					if(nextarg && (interval = atoi(nextarg)) > 0)
						argv++, argc--;
					else
						die("-i requires a positive integer argument in milliseconds");
					break;
				case 'd':
					if(nextarg) {
						event_dir = nextarg;
						argv++, argc--;
					} else {
						die("-d requires a directory argument");
					}
					break;
				case 'j':
					if(nextarg) {
						js_node_name = nextarg;
						argv++, argc--;
					} else {
						die("-j requires a string argument");
					}
					break;
				case 'D':
					debug = 1;
					break;
				default:
					die("unrecognized argument, try --help");
					break;
			}
		} else {
			add_joystick_name(*argv);
			autodiscover = 0;
		}
	}
}

/* make ourselves a daemon, double-fork technique.
   verbose comments are not here because I think you need them, they're
   here for me so I don't forget what this gibberish is for... */
void daemonize(void) {
	pid_t pid;

	if((pid = fork()) < 0) {
		/* in parent, fork failed */
		fprintf(stderr, "%s: %s\n", self, strerror(errno));
		die("failed to daemonize");
	} else if(pid) {
		/* in parent, fork succeeded */
		exit(0);
	}

	/* now we're in the child, aka the 2nd generation parent.
      the only reason for the first fork() was because setsid() can't
	   be run in the parent process */
	if( (setsid() < 0) ) {
		fprintf(stderr, "%s: %s\n", self, strerror(errno));
		die("failed to daemonize");
	}

	/* go on, do it again */
	if((pid = fork()) < 0) {
		/* in 2nd gen parent, fork failed */
		fprintf(stderr, "%s: %s\n", self, strerror(errno));
		die("failed to daemonize");
	} else if(pid) {
		/* in 2nd gen parent, fork succeeded */
		fprintf(stderr, "%s: daemonized, PID %u\n", self, pid);
		exit(0);
	}

	/* now we're in the grandchild, and we no longer need stdin/out/err */
	close(0);
	close(1);
	close(2);

	/* do this so we don't keep a filesystem from being umounted because
		it's still busy (as our cwd) */
	chdir("/");
}

void init_inotify(void) {
	inotify_fd = inotify_init1(IN_NONBLOCK);
	if(inotify_fd < 0) {
		fprintf(stderr, "%s: inotify_init1() failed: %s",
				self, strerror(errno));
		exit(1);
	}

	if(debug) fprintf(stderr, "inotify_init1() returned %d\n", inotify_fd);

	watch_fd = inotify_add_watch(inotify_fd, event_dir, IN_CREATE | IN_DELETE);
	if(watch_fd < 0) {
		fprintf(stderr, "%s: inotify_add_watch() failed: %s",
				self, strerror(errno));
		exit(1);
	}

	if(debug) fprintf(stderr, "inotify_add_watch() on %s returned %d\n", event_dir, inotify_fd);
}

void connect_to_x(void) {
	int ignoreme;

	if(debug) fprintf(stderr, "connecting to X server...\n");

	xdisp = XOpenDisplay(getenv("DISPLAY"));

	if(!xdisp) die("can't connect to X server");
	if(debug) fprintf(stderr, "connected to X server\n");

	if(XTestQueryExtension(xdisp, &ignoreme, &ignoreme, &ignoreme, &ignoreme)) {
		if(debug) fprintf(stderr, "X server supports XTest extension, good\n");
	} else {
		die("X server doesn't support XTest extension\n");
	}
}

/* XXX: XKeycodeToKeysym() is deprecated. I must learn XKB. */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
KeySym get_keysym(int i) {
	return XKeycodeToKeysym(xdisp, i, 0);
}
#pragma GCC diagnostic pop

/* the goggles, they do nothing! */
void find_keycode() {
	int i, min_code = 0, max_code = 0;
	
	/* man page doesn't document the return value */
	(void)XDisplayKeycodes(xdisp, &min_code, &max_code);

	if(debug) fprintf(stderr, "XDisplayKeycodes min %d, max %d\n", min_code, max_code);

	for(i = min_code; i <= max_code; i++) {
		if(get_keysym(i) == NoSymbol) {
			keycode = i;
			if(debug) fprintf(stderr, "using keycode %d\n", keycode);
			break;
		}
	}

	if(keycode < 0) {
		fprintf(stderr,
				"%s: can't find a free keycode in the keymap, using %d\n",
				self, FALLBACK_KEYCODE);
		keycode = FALLBACK_KEYCODE;
	}
}

void init_x(void) {
	connect_to_x();

	if(fake_mode == fm_auto_keycode) {
		find_keycode();
		fake_mode = fm_keycode;
	}

	/* do this now, before daemonizing. if something's wrong, Xlib
	   will kill us. we'd better let that happen while we still have a
	   stderr, so the user can see what happened. */
	send_fake_x_event();
}

int main(int argc, char **argv) {
	set_exe_name(argv[0]);

	parse_args(argc, argv);

	if(autodiscover) populate_joynames();

	init_joysticks();

	init_inotify();

	init_x();

	if(!debug) daemonize();

	main_loop();

	return 0;
}