summaryrefslogtreecommitdiffstats
path: root/tsak/main.cpp
blob: 646a9d45d6977ca6cb69db41786c76fb99a0317e (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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
/*
Copyright 2010 Adam Marchetti
Copyright 2011-2013 Timothy Pearson <[email protected]>

This file is part of tsak, the TDE Secure Attention Key daemon

tsak is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

tsak is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public
License along with tsak. If not, see http://www.gnu.org/licenses/.

*/

#include <stdio.h>
#include <stdlib.h>
#include <exception>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <dirent.h>
#include <linux/input.h>
#include <linux/uinput.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/time.h>
#include <termios.h>
#include <signal.h>
extern "C" {
#include <libudev.h>
}
#include <libgen.h>

using namespace std;

#define FIFO_DIR "/tmp/tdesocket-global"
#define FIFO_FILE_OUT "/tmp/tdesocket-global/tsak"
#define FIFO_LOCKFILE_OUT "/tmp/tdesocket-global/tsak.lock"

// WARNING
// MAX_KEYBOARDS must be greater than or equal to MAX_INPUT_NODE
#define MAX_KEYBOARDS 128
#define MAX_INPUT_NODE 128

#define TestBit(bit, array) (array[(bit) / 8] & (1 << ((bit) % 8)))

typedef unsigned char byte;

bool        mPipeOpen_out = false;
int         mPipe_fd_out = -1;

int         mPipe_lockfd_out = -1;

char filename[32];
char key_bitmask[(KEY_MAX + 7) / 8];

struct sigaction usr_action;
sigset_t block_mask;

int keyboard_fd_num;
int keyboard_fds[MAX_KEYBOARDS];
int child_pids[MAX_KEYBOARDS];
int child_led_pids[MAX_KEYBOARDS];

const char *keycode[256] =
{
	"", "<esc>", "1", "2", "3", "4", "5", "6", "7", "8",
	"9", "0", "−", "=", "<backspace>", "<tab>", "q", "w", "e", "r",
	"t", "y", "u", "i", "o", "p", "[", "]", "\n", "<control>",
	"a", "s", "d", "f", "g", "h", "j", "k", "l", ";",
	"'", "", "<shift>", "\\", "z", "x", "c", "v", "b", "n",
	"m", ",", ".", "/", "<shift>", "", "<alt>", " ", "<capslock>",
	"<f1>", "<f2>", "<f3>", "<f4>", "<f5>", "<f6>", "<f7>", "<f8>", "<f9>", "<f10>",
	"<numlock>", "<scrolllock>", "", "", "", "", "", "", "", "",
	"", "", "\\", "f11", "f12", "", "", "", "", "",
	"", "", "", "<control>", "", "<sysrq>", "", "", "<control>", "", "",
	"<alt>", "", "", "", "", "", "", "", "", "",
	"", "<del>", "", "", "", "", "", "", "", "",
	"", "", "", "", "", "", "", "", "", "",
	"", "", "", "", "", "", "", "", "", "",
	"", "", "", "", "", "", "", "", "", "",
	"", "", "", "", "", "", "", "", "", "",
	"", "", "", "", "", "", "", "", "", "",
	"", "", "", "", "", "", "", "", "", "",
	"", "", "", "", "", "", "", "", "", "",
	"", "", "", "", "", "", "", "", "", ""
};

/* returns 1 if bit number i is set, otherwise returns 0 */
int bit_set(size_t i, const byte* a)
{
  return a[i/CHAR_BIT] & (1 << i%CHAR_BIT);
}

/* exception handling */
struct exit_exception {
	int c;
	exit_exception(int c):c(c) { }
};

/* signal handler */
void signal_callback_handler(int signum)
{
	// Terminate program
	throw exit_exception(signum);
}

/*  termination handler */
void tsak_friendly_termination() {
	int i;

	// Close down all child processes
	for (i=0; i<MAX_KEYBOARDS; i++) {
		if (child_pids[i] != 0) {
			kill(child_pids[i], SIGTERM);
		}
		if (child_led_pids[i] != 0) {
			kill(child_led_pids[i], SIGTERM);
		}
	}

	// Wait for process termination
	sleep(1);

	fprintf(stderr, "[tsak] tsak terminated by external request\n");
	exit(17);
}

// --------------------------------------------------------------------------------------
// Useful function from Stack Overflow
// http://stackoverflow.com/questions/874134/find-if-string-endswith-another-string-in-c
// --------------------------------------------------------------------------------------
/*  returns 1 iff str ends with suffix  */
int str_ends_with(const char * str, const char * suffix) {

  if( str == NULL || suffix == NULL )
    return 0;

  size_t str_len = strlen(str);
  size_t suffix_len = strlen(suffix);

  if(suffix_len > str_len)
    return 0;

  return 0 == strncmp( str + str_len - suffix_len, suffix, suffix_len );
}
// --------------------------------------------------------------------------------------

/*
 * Set a file descriptor to blocking or non-blocking mode.
 *
 * @param fd The file descriptor
 * @param blocking 0:non-blocking mode, 1:blocking mode
 *
 * @return 1:success, 0:failure.
 */
int fd_set_blocking(int fd, int blocking)
{
	/* Save the current flags */
	int flags = fcntl(fd, F_GETFL, 0);
	if (flags == -1) {
		return 0;
	}
	
	if (blocking) {
		flags &= ~O_NONBLOCK;
	}
	else {
		flags |= O_NONBLOCK;
	}
	return fcntl(fd, F_SETFL, flags) != -1;
}

/* Assign features (supported axes and keys) of the physical input device (devin)
 * to the virtual input device (devout) */
static void copy_features(int devin, int devout)
{
	byte evtypes[EV_MAX/CHAR_BIT + 1] = {0};
	byte codes[KEY_MAX/CHAR_BIT + 1];
	unsigned i,code;
	int op;
	if (ioctl(devin, EVIOCGBIT(0, sizeof(evtypes)), evtypes) < 0) return;
	for(i=0;i<EV_MAX;++i) {
		if (bit_set(i, evtypes)) {
			switch(i) {
				case EV_KEY: op = UI_SET_KEYBIT; break;
				case EV_REL: op = UI_SET_RELBIT; break;
				case EV_ABS: op = UI_SET_ABSBIT; break;
				case EV_MSC: op = UI_SET_MSCBIT; break;
				case EV_LED: op = UI_SET_LEDBIT; break;
				case EV_SND: op = UI_SET_SNDBIT; break;
				case EV_SW: op = UI_SET_SWBIT; break;
				default: op = -1;
			}
		}
		if (op == -1) continue;
		ioctl(devout, UI_SET_EVBIT, i);
		memset(codes,0,sizeof(codes));
		if (ioctl(devin, EVIOCGBIT(i, sizeof(codes)), codes) >= 0) {
			for(code=0;code<KEY_MAX;code++) {
				if (bit_set(code, codes)) ioctl(devout, op, code);
			}
		}
	}
}

int find_keyboards() {
	int i, j;
	int fd;
	char name[256] = "Unknown";

	keyboard_fd_num = 0;
	for (i=0; i<MAX_KEYBOARDS; i++) {
		keyboard_fds[i] = 0;
	}

	for (i=0; i<MAX_INPUT_NODE; i++) {
		snprintf(filename, sizeof(filename), "/dev/input/event%d", i);

		fd = open(filename, O_RDWR|O_SYNC);
		if (fd >= 0) {
			ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bitmask)), key_bitmask);
	
			// Ensure that we do not detect our own tsak faked keyboards
			ioctl (fd, EVIOCGNAME(sizeof(name)), name);
			if (str_ends_with(name, "+tsak") == 0) {
				/* We assume that anything that has an alphabetic key in the
					QWERTYUIOP range in it is the main keyboard. */
				for (j = KEY_Q; j <= KEY_P; j++) {
					if (TestBit(j, key_bitmask)) {
						keyboard_fds[keyboard_fd_num] = fd;
					}
				}
			}
	
			if (keyboard_fds[keyboard_fd_num] == 0) {
				close(fd);
			}
			else {
				keyboard_fd_num++;
			}
		}
	}
	return 0;
}

void tearDownPipe()
{
	if (mPipeOpen_out == true) {
		mPipeOpen_out = false;
		close(mPipe_fd_out);
		unlink(FIFO_FILE_OUT);
	}
}

void tearDownLockingPipe()
{
	close(mPipe_lockfd_out);
	unlink(FIFO_LOCKFILE_OUT);
}

bool setFileLock(int fd, bool close_on_failure)
{
	struct flock fl;

	fl.l_type = F_WRLCK;
	fl.l_whence = SEEK_SET;
	fl.l_start = 0;
	fl.l_len = 1;

	// Set the exclusive file lock
	if (fcntl(fd, F_SETLK, &fl) == -1) {
		close(fd);
		return false;
	}

	return true;
}

bool checkFileLock()
{
	struct flock fl;

	fl.l_type    = F_WRLCK;   /* Test for any lock on any part of file. */
	fl.l_start   = 0;
	fl.l_whence  = SEEK_SET;
	fl.l_len     = 0;

	int fd = open(FIFO_LOCKFILE_OUT, O_RDWR | O_NONBLOCK);
	fcntl(fd, F_GETLK, &fl);  /* Overwrites lock structure with preventors. */

	if (fd > -1) {
		if (fl.l_type == F_WRLCK) {
			return false;
		}
		return true;
	}

	return true;
}

bool setupPipe()
{
	/* Create the FIFOs if they do not exist */
	umask(0);
	mkdir(FIFO_DIR,0644);

	mknod(FIFO_FILE_OUT, S_IFIFO|0600, 0);
	chmod(FIFO_FILE_OUT, 0600);

	mPipe_fd_out = open(FIFO_FILE_OUT, O_RDWR | O_NONBLOCK);
	if (mPipe_fd_out > -1) {
		mPipeOpen_out = true;
	}

	// Set the exclusive file lock
	return setFileLock(mPipe_fd_out, true);
}

bool setupLockingPipe(bool writepid)
{
	/* Create the FIFOs if they do not exist */
	umask(0);
	mkdir(FIFO_DIR,0644);

	mknod(FIFO_LOCKFILE_OUT, 0600, 0);
	chmod(FIFO_LOCKFILE_OUT, 0600);

	mPipe_lockfd_out = open(FIFO_LOCKFILE_OUT, O_RDWR | O_NONBLOCK);
	if (mPipe_lockfd_out > -1) {
		if (writepid) {
			// Write my PID to the file
			pid_t tsakpid = getpid();
			char pidstring[1024];
			sprintf(pidstring, "%d", tsakpid);
			write(mPipe_lockfd_out, pidstring, strlen(pidstring));
		}
		// Set the exclusive file lock
		return setFileLock(mPipe_lockfd_out, true);
	}

	return false;
}

void broadcast_sak()
{
	// Let anyone listening to our interface know that an SAK keypress was received
	// I highly doubt there are more than 255 VTs active at once...
	int i;
	for (i=0;i<255;i++) {
		if (write(mPipe_fd_out, "SAK\n\r", 6) < 0) {
			fprintf(stderr, "[tsak] Unable to send SAK signal to clients\n");
		}
	}
}

void restart_tsak()
{
	int i;

	fprintf(stderr, "[tsak] Forcibly terminating...\n");

	// Close down all child processes
	for (i=0; i<MAX_KEYBOARDS; i++) {
		if (child_pids[i] != 0) {
			kill(child_pids[i], SIGKILL);
		}
		if (child_led_pids[i] != 0) {
			kill(child_led_pids[i], SIGKILL);
		}
	}

	// Wait for process termination
	sleep(1);

	// Release all exclusive keyboard locks
	for (int current_keyboard=0;current_keyboard<keyboard_fd_num;current_keyboard++) {
		if(ioctl(keyboard_fds[current_keyboard], EVIOCGRAB, 0) < 0) {
			fprintf(stderr, "[tsak] Failed to release exclusive input device lock");
		}
		close(keyboard_fds[current_keyboard]);
	}

#if 1
	// Restart now
	// Note that the execl function never returns
	char me[2048];
	int chars = readlink("/proc/self/exe", me, sizeof(me));
	me[chars] = 0;
	me[2047] = 0;
	execl(me, basename(me), (char*)NULL);
#else
	_exit(0);
#endif
}

class PipeHandler
{
public:
	PipeHandler();
	~PipeHandler();

	bool active;
};

PipeHandler::PipeHandler()
{
	active = false;
}

PipeHandler::~PipeHandler()
{
	if (active) {
		tearDownPipe();
		tearDownLockingPipe();
	}
}

int main (int argc, char *argv[])
{
	struct input_event ev[64];
	struct input_event event;
	struct input_event revev;
	struct uinput_user_dev devinfo={{0},{0}};
	int devout[MAX_KEYBOARDS], rd, i, size = sizeof (struct input_event);
	char name[256] = "Unknown";
	bool ctrl_down = false;
	bool alt_down = false;
	bool hide_event = false;
	bool established = false;
	bool testrun = false;
	bool depcheck = false;
	int current_keyboard;
	bool can_proceed;

	// Ignore SIGPIPE
	signal(SIGPIPE, SIG_IGN);

	// Register signal handlers
	// Register signal and signal handler
	signal(SIGINT, signal_callback_handler);
	signal(SIGTERM, signal_callback_handler);

	set_terminate(tsak_friendly_termination);

	try {
		for (i=0; i<MAX_KEYBOARDS; i++) {
			child_pids[i] = 0;
			child_led_pids[i] = 0;
		}

		if (argc == 2) {
			if (strcmp(argv[1], "checkactive") == 0) {
				testrun = true;
			}
			if (strcmp(argv[1], "checkdeps") == 0) {
				depcheck = true;
			}
		}

		if (depcheck == false) {
			// Check for existing file locks
			if (!checkFileLock()) {
				fprintf(stderr, "[tsak] Another instance of this program is already running [1]\n");
				return 8;
			}
			if (!setupLockingPipe(true)) {
				fprintf(stderr, "[tsak] Another instance of this program is already running [2]\n");
				return 8;
			}
		}

		// Create the output pipe
		PipeHandler controlpipe;
		if (depcheck == false) {
			if (!setupPipe()) {
				fprintf(stderr, "[tsak] Another instance of this program is already running\n");
				return 8;
			}
		}

		while (1) {
			if (depcheck == false) {
				controlpipe.active = true;
			}

			if ((getuid ()) != 0) {
				printf ("You are not root! This WILL NOT WORK!\nDO NOT attempt to bypass security restrictions, e.g. by changing keyboard permissions or owner, if you want the SAK system to remain secure...\n");
				return 5;
			}

			// Find keyboards
			find_keyboards();
			if (keyboard_fd_num == 0) {
				printf ("Could not find any usable keyboard(s)!\n");
				if (depcheck == true) {
					return 50;
				}
				// Make sure everyone knows we physically can't detect a SAK
				// Before we do this we broadcast one so that active dialogs are updated appropriately
				// Also, we keep watching for a keyboard to be added via a forked child process...
				broadcast_sak();
				if (established)
					sleep(1);
				else {
					int i=fork();
					if (i<0) {
						return 12; // fork failed
					}
					if (i>0) {
						return 4;
					}
					sleep(1);
					restart_tsak();
				}
			}
			else {
				fprintf(stderr, "[tsak] Found %d keyboard(s)\n", keyboard_fd_num);

				can_proceed = true;
				for (current_keyboard=0;current_keyboard<keyboard_fd_num;current_keyboard++) {
					// Print Device Name
					ioctl (keyboard_fds[current_keyboard], EVIOCGNAME (sizeof (name)), name);
					fprintf(stderr, "[tsak] Reading from keyboard: (%s)\n", name);

					// Create filtered virtual output device
					devout[current_keyboard]=open("/dev/misc/uinput",O_RDWR|O_NONBLOCK);
					if (devout[current_keyboard]<0) {
						devout[current_keyboard]=open("/dev/uinput",O_RDWR|O_NONBLOCK);
						if (devout[current_keyboard]<0) {
							perror("open(\"/dev/misc/uinput\")");
						}
					}
					if (devout[current_keyboard]<0) {
						can_proceed = false;
						fprintf(stderr, "[tsak] Unable to open /dev/uinput or /dev/misc/uinput (char device 10:223).\nPossible causes:\n 1) Device node does not exist\n 2) Kernel not compiled with evdev [INPUT_EVDEV] and uinput [INPUT_UINPUT] user level driver support\n 3) Permission denied.\n");
						perror("open(\"/dev/uinput\")");
						if (established)
							sleep(1);
						else
							return 3;
					}
					fd_set_blocking(devout[current_keyboard], true);
				}
				if (depcheck == true) {
					return 0;
				}

				if (can_proceed == true) {
					for (current_keyboard=0;current_keyboard<keyboard_fd_num;current_keyboard++) {
						if(ioctl(keyboard_fds[current_keyboard], EVIOCGRAB, 2) < 0) {
							close(keyboard_fds[current_keyboard]);
							fprintf(stderr, "[tsak] Failed to grab exclusive input device lock");
							if (established) {
								sleep(1);
							}
							else {
								return 1;
							}
						}
						else {
							ioctl(keyboard_fds[current_keyboard], EVIOCGNAME(UINPUT_MAX_NAME_SIZE), devinfo.name);
							strncat(devinfo.name, "+tsak", UINPUT_MAX_NAME_SIZE-1);
							fprintf(stderr, "[tsak] %s\n", devinfo.name);
							ioctl(keyboard_fds[current_keyboard], EVIOCGID, &devinfo.id);

							copy_features(keyboard_fds[current_keyboard], devout[current_keyboard]);
							if (write(devout[current_keyboard],&devinfo,sizeof(devinfo)) < 0) {
								fprintf(stderr, "[tsak] Unable to write to output device\n");
							}
							if (ioctl(devout[current_keyboard],UI_DEV_CREATE)<0) {
								fprintf(stderr, "[tsak] Unable to create input device with UI_DEV_CREATE\n");
								if (established)
									sleep(1);
								else
									return 2;
							}
							else {
								fprintf(stderr, "[tsak] Device created.\n");

								if (established == false) {
									int i=fork();
									if (i<0) return 9; // fork failed
									if (i>0) {
										child_pids[current_keyboard] = i;
										continue;
									}
									setupLockingPipe(false);
								}

								established = true;

								if (testrun == true) {
									return 0;
								}

								int i=fork();
								if (i<0) return 9; // fork failed
								if (i>0) {
									child_led_pids[current_keyboard] = i;
									while (1) {
										// Replicate LED events from the virtual keyboard to the physical keyboard
										int rrd = read(devout[current_keyboard], &revev, size);
										if (rrd >= size) {
											if (revev.type == EV_LED) {
												if (write(keyboard_fds[current_keyboard], &revev, sizeof(revev)) < 0) {
													fprintf(stderr, "[tsak] Unable to replicate LED event\n");
												}
											}
										}
									}
									return 0;
								}

								while (1) {
									if ((rd = read(keyboard_fds[current_keyboard], ev, size)) < size) {
										fprintf(stderr, "[tsak] Read failed.\n");
										break;
									}

									if (ev[0].value == 0 && ev[0].type == 1) { // Read the key release event
										if (keycode[(ev[0].code)]) {
											if (strcmp(keycode[(ev[0].code)], "<control>") == 0) ctrl_down = false;
											if (strcmp(keycode[(ev[0].code)], "<alt>") == 0) alt_down = false;
										}
									}
									if (ev[0].value == 1 && ev[0].type == 1) { // Read the key press event
										if (keycode[(ev[0].code)]) {
											if (strcmp(keycode[(ev[0].code)], "<control>") == 0) ctrl_down = true;
											if (strcmp(keycode[(ev[0].code)], "<alt>") == 0) alt_down = true;
										}
									}

									hide_event = false;
									if (ev[0].value == 1 && ev[0].type == 1) { // Read the key press event
										if (keycode[(ev[0].code)]) {
											if (alt_down && ctrl_down && (strcmp(keycode[(ev[0].code)], "<del>") == 0)) {
												hide_event = true;
											}
										}
									}

									if ((hide_event == false) && (ev[0].type != EV_LED) && (ev[1].type != EV_LED)) {
										// Pass the event on...
										event = ev[0];
										if (write(devout[current_keyboard], &event, sizeof event) < 0) {
											fprintf(stderr, "[tsak] Unable to replicate keyboard event!\n");
										}
									}
									if (hide_event == true) {
										// Let anyone listening to our interface know that an SAK keypress was received
										broadcast_sak();
									}
								}
							}
						}
					}

					// fork udev monitor process
					int i=fork();
					if (i<0) {
						return 10; // fork failed
					}
					if (i>0) {
						// Terminate parent
						controlpipe.active = false;
						return 0;
					}

					// Prevent multiple process instances from starting
					setupLockingPipe(true);

					// Wait a little bit so that udev hotplug can stabilize before we start monitoring
					sleep(1);

					fprintf(stderr, "[tsak] Hotplug monitoring process started\n");

					// Monitor for hotplugged keyboards
					int j;
					int hotplug_fd;
					bool is_new_keyboard;
					struct udev *udev;
					struct udev_device *dev;
					struct udev_monitor *mon;

					// Create the udev object
					udev = udev_new();
					if (!udev) {
						fprintf(stderr, "[tsak] Cannot connect to udev interface\n");
						return 11;
					}

					// Set up a udev monitor to monitor input devices
					mon = udev_monitor_new_from_netlink(udev, "udev");
					udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL);
					udev_monitor_enable_receiving(mon);

					while (1) {
						// Watch for input from the monitoring process
						fd_set readfds;
						FD_ZERO(&readfds);
						FD_SET(udev_monitor_get_fd(mon), &readfds);
						int fdcount = select(udev_monitor_get_fd(mon)+1, &readfds, NULL, NULL, NULL);
						if (fdcount < 0) {
							if (errno == EINTR) {
								fprintf(stderr, "[tsak] Signal caught in hotplug monitoring process; ignoring\n");
							}
							else {
								fprintf(stderr, "[tsak] Select failed on udev file descriptor in hotplug monitoring process\n");
							}
							usleep(1000);
							continue;
						}

						dev = udev_monitor_receive_device(mon);
						if (dev) {
							// If a keyboard was removed we need to restart...
							if (strcmp(udev_device_get_action(dev), "remove") == 0) {
								udev_device_unref(dev);
								udev_unref(udev);
								restart_tsak();
							}

							is_new_keyboard = false;
							snprintf(filename,sizeof(filename), "%s", udev_device_get_devnode(dev));
							udev_device_unref(dev);

							// Print name of keyboard
							hotplug_fd = open(filename, O_RDWR|O_SYNC);
							ioctl(hotplug_fd, EVIOCGBIT(EV_KEY, sizeof(key_bitmask)), key_bitmask);

							/* We assume that anything that has an alphabetic key in the
								QWERTYUIOP range in it is the main keyboard. */
							for (j = KEY_Q; j <= KEY_P; j++) {
								if (TestBit(j, key_bitmask)) {
									is_new_keyboard = true;
								}
							}
							ioctl (hotplug_fd, EVIOCGNAME (sizeof (name)), name);
							close(hotplug_fd);

							// Ensure that we do not detect our own tsak faked keyboards
							if (str_ends_with(name, "+tsak") == 1) {
								is_new_keyboard = false;
							}

							// If a keyboard was added we need to restart...
							if (is_new_keyboard == true) {
								fprintf(stderr, "[tsak] Hotplugged new keyboard: (%s)\n", name);
								udev_unref(udev);
								restart_tsak();
							}
						}
						else {
							fprintf(stderr, "[tsak] No device from receive_device().  A udev error has occurred; terminating hotplug monitoring process.\n");
							return 12;
						}
					}

					udev_unref(udev);

					fprintf(stderr, "[tsak] Hotplug monitoring process terminated\n");
				}
			}
		}
	}
	catch(exit_exception& e) {
		tsak_friendly_termination();
	}

	return 6;
}