neuswc

patched neuswc library (tracked)
git clone https://git.daat.foo/neuswc.git
Log | Files | Refs | README | LICENSE

launch.c (22664B)


      1 /* swc: launch/launch.c
      2  *
      3  * Copyright (c) 2013, 2014, 2016 Michael Forney
      4  *
      5  * Based in part upon weston-launch.c from weston which is:
      6  *
      7  *     Copyright © 2012 Benjamin Franzke
      8  *
      9  * Permission is hereby granted, free of charge, to any person obtaining a copy
     10  * of this software and associated documentation files (the "Software"), to deal
     11  * in the Software without restriction, including without limitation the rights
     12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     13  * copies of the Software, and to permit persons to whom the Software is
     14  * furnished to do so, subject to the following conditions:
     15  *
     16  * The above copyright notice and this permission notice shall be included in
     17  * all copies or substantial portions of the Software.
     18  *
     19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     25  * SOFTWARE.
     26  */
     27 
     28 #include "devmajor.h"
     29 #include "protocol.h"
     30 
     31 #include <errno.h>
     32 #include <fcntl.h>
     33 #include <limits.h>
     34 #include <poll.h>
     35 #include <signal.h>
     36 #include <spawn.h>
     37 #include <stdarg.h>
     38 #include <stdbool.h>
     39 #include <stdio.h>
     40 #include <stdlib.h>
     41 #include <stdnoreturn.h>
     42 #include <string.h>
     43 #include <unistd.h>
     44 
     45 #include <sys/ioctl.h>
     46 #include <sys/socket.h>
     47 #include <sys/stat.h>
     48 #include <sys/types.h>
     49 #include <sys/wait.h>
     50 #include <dirent.h>
     51 #include <time.h>
     52 #ifdef __linux__
     53 #include <sys/sysmacros.h>
     54 #endif
     55 
     56 #if defined(__FreeBSD__)
     57 #include <sys/consio.h>
     58 #include <sys/kbio.h>
     59 #include <dev/evdev/input.h> /* needed for eviocgrab */
     60 #elif defined(__NetBSD__)
     61 #include <dev/wscons/wsdisplay_usl_io.h>
     62 
     63 #elif defined(__OpenBSD__)
     64 #include <dev/wscons/wsdisplay_usl_io.h>
     65 
     66 #elif defined(__linux__)
     67 #include <linux/input.h>
     68 #include <linux/kd.h>
     69 #include <linux/vt.h>
     70 
     71 #else
     72 #include <dev/wscons/wsdisplay_usl_io.h>
     73 #endif
     74 
     75 #ifdef ENABLE_DRM
     76 #include <xf86drm.h>
     77 #endif
     78 
     79 #ifdef __OpenBSD__
     80 /* required by the runtime for setuid executables */
     81 __attribute__((visibility("default")))
     82 mode_t _permit_setugid = S_ISUID;
     83 #endif
     84 
     85 #define ARRAY_LENGTH(array) (sizeof(array) / sizeof(array)[0])
     86 #ifdef __linux__
     87 #define ESCAPE_KEYBOARDS_MAX 32
     88 #else
     89 #define ESCAPE_KEYBOARDS_MAX 0
     90 #endif
     91 
     92 static void
     93 activate(void);
     94 static void
     95 deactivate(void);
     96 
     97 static bool nflag;
     98 static int sigfd[2], sock[2];
     99 static int input_fds[128], num_input_fds;
    100 #ifdef ENABLE_DRM
    101 static int drm_fds[16], num_drm_fds;
    102 #endif
    103 static int tty_fd;
    104 static bool active;
    105 static pid_t child_pid = -1;
    106 
    107 /* with -e, read the keyboards here so a wedged server cant block these:
    108  *   ctrl+alt+f1..f12        switch vt
    109  *   ctrl+alt+backspace x2   end the session */
    110 #ifdef __linux__
    111 #define ESCAPE_KEYBOARDS ESCAPE_KEYBOARDS_MAX
    112 #define ESCAPE_WINDOW 3000
    113 #define ESCAPE_RESCAN 3000
    114 static struct {
    115 	int fd;
    116 	dev_t rdev;
    117 } keyboards[ESCAPE_KEYBOARDS];
    118 static int num_keyboards;
    119 static bool escape_enabled;
    120 static bool ctrl_l, ctrl_r, alt_l, alt_r;
    121 static long long last_zap;
    122 #endif
    123 
    124 static struct {
    125 	bool altered;
    126 	int vt;
    127 	long kb_mode;
    128 	long console_mode;
    129 } original_vt_state;
    130 
    131 static void
    132 cleanup(void);
    133 
    134 static noreturn void
    135 usage(const char *name)
    136 {
    137 	fprintf(stderr, "usage: %s [-ne] [-t tty] [--] server [args...]\n", name);
    138 	exit(2);
    139 }
    140 
    141 static noreturn void __attribute__((format(printf, 1, 2)))
    142 die(const char *format, ...)
    143 {
    144 	va_list args;
    145 
    146 	va_start(args, format);
    147 	vfprintf(stderr, format, args);
    148 	va_end(args);
    149 
    150 	if (format[0] && format[strlen(format) - 1] == ':') {
    151 		fprintf(stderr, " %s", strerror(errno));
    152 	}
    153 	fputc('\n', stderr);
    154 
    155 	cleanup();
    156 	exit(EXIT_FAILURE);
    157 }
    158 
    159 static void
    160 start_devices(void)
    161 {
    162 #ifdef ENABLE_DRM
    163 	int i;
    164 
    165 	for (i = 0; i < num_drm_fds; ++i) {
    166 		if (drmSetMaster(drm_fds[i]) < 0) {
    167 			die("failed to set DRM master");
    168 		}
    169 	}
    170 #endif
    171 }
    172 
    173 static void
    174 stop_devices(bool fatal)
    175 {
    176 	int i;
    177 
    178 #ifdef ENABLE_DRM
    179 	for (i = 0; i < num_drm_fds; ++i) {
    180 		if (drmDropMaster(drm_fds[i]) < 0 && fatal) {
    181 			die("drmDropMaster:");
    182 		}
    183 	}
    184 #endif
    185 	for (i = 0; i < num_input_fds; ++i) {
    186 #ifdef EVIOCREVOKE
    187 		if (ioctl(input_fds[i], EVIOCREVOKE, 0) < 0 && errno != ENODEV &&
    188 		    fatal) {
    189 			die("ioctl EVIOCREVOKE:");
    190 		}
    191 #endif
    192 		close(input_fds[i]);
    193 	}
    194 	num_input_fds = 0;
    195 }
    196 
    197 static void
    198 cleanup(void)
    199 {
    200 	struct vt_mode mode = {.mode = VT_AUTO};
    201 
    202 	if (!original_vt_state.altered) {
    203 		return;
    204 	}
    205 
    206 	/* Stop devices before switching the VT to make sure we have released the
    207 	 * DRM device before the next session tries to claim it. */
    208 	stop_devices(false);
    209 
    210 	/* stop VT signal delivery before restoring tty */
    211 	ioctl(tty_fd, VT_SETMODE, &mode);
    212 #ifndef __OpenBSD__
    213 	ioctl(tty_fd, KDSKBMODE, original_vt_state.kb_mode);
    214 #endif
    215 	ioctl(tty_fd, KDSETMODE, original_vt_state.console_mode);
    216 	ioctl(tty_fd, VT_ACTIVATE, original_vt_state.vt);
    217 	original_vt_state.altered = false;
    218 	if (child_pid > 0)
    219 		kill(child_pid, SIGTERM);
    220 }
    221 
    222 /* async-signal-safe: console back to text, keyboard back on */
    223 static void
    224 restore_vt_raw(void)
    225 {
    226 	struct vt_mode mode = {.mode = VT_AUTO};
    227 
    228 	if (!original_vt_state.altered)
    229 		return;
    230 	ioctl(tty_fd, VT_SETMODE, &mode);
    231 #ifndef __OpenBSD__
    232 	ioctl(tty_fd, KDSKBMODE, original_vt_state.kb_mode);
    233 #endif
    234 	ioctl(tty_fd, KDSETMODE, original_vt_state.console_mode);
    235 }
    236 
    237 static void
    238 handle_fatal(int sig)
    239 {
    240 	restore_vt_raw();
    241 	if (child_pid > 0)
    242 		kill(child_pid, SIGKILL);
    243 	signal(sig, SIG_DFL);
    244 	raise(sig);
    245 }
    246 
    247 static long long
    248 now_ms(void)
    249 {
    250 	struct timespec ts;
    251 
    252 	clock_gettime(CLOCK_MONOTONIC, &ts);
    253 	return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
    254 }
    255 
    256 /* restore the console, ask the session to end, kill it after 3s */
    257 static noreturn void
    258 end_session(int code)
    259 {
    260 	long long until;
    261 	int status;
    262 	pid_t pid;
    263 
    264 	cleanup();
    265 	until = now_ms() + 3000;
    266 	while (child_pid > 0) {
    267 		pid = waitpid(child_pid, &status, WNOHANG);
    268 		if (pid == child_pid || (pid < 0 && errno == ECHILD))
    269 			break;
    270 		if (now_ms() >= until) {
    271 			kill(child_pid, SIGKILL);
    272 			waitpid(child_pid, &status, 0);
    273 			break;
    274 		}
    275 		nanosleep(&(struct timespec){0, 50000000}, NULL);
    276 	}
    277 	exit(code);
    278 }
    279 
    280 static void
    281 activate(void)
    282 {
    283 	struct swc_launch_event event = {.type = SWC_LAUNCH_EVENT_ACTIVATE};
    284 
    285 	start_devices();
    286 	/* a hung server must not hold the vt */
    287 	send(sock[0], &event, sizeof(event), MSG_DONTWAIT | MSG_NOSIGNAL);
    288 	active = true;
    289 #ifdef __linux__
    290 	ctrl_l = ctrl_r = alt_l = alt_r = false;
    291 	last_zap = 0;
    292 #endif
    293 }
    294 
    295 static void
    296 deactivate(void)
    297 {
    298 	struct swc_launch_event event = {.type = SWC_LAUNCH_EVENT_DEACTIVATE};
    299 
    300 	send(sock[0], &event, sizeof(event), MSG_DONTWAIT | MSG_NOSIGNAL);
    301 	stop_devices(true);
    302 	active = false;
    303 }
    304 
    305 static void
    306 handle_signal(int sig)
    307 {
    308 	write(sigfd[1], (char[]){sig}, 1);
    309 }
    310 
    311 static void
    312 handle_socket_data(int socket)
    313 {
    314 	struct swc_launch_request request;
    315 	struct swc_launch_event response;
    316 	char path[PATH_MAX];
    317 	struct iovec request_iov[2] = {
    318 	    {.iov_base = &request, .iov_len = sizeof(request)},
    319 	    {.iov_base = path, .iov_len = sizeof(path)},
    320 	};
    321 	struct iovec response_iov[1] = {
    322 	    {.iov_base = &response, .iov_len = sizeof(response)},
    323 	};
    324 	int fd = -1;
    325 	struct stat st;
    326 	ssize_t size;
    327 
    328 	size = receive_fd(socket, &fd, request_iov, 2);
    329 	if (size == -1 || size == 0 || size < sizeof(request)) {
    330 		return;
    331 	}
    332 	size -= sizeof(request);
    333 
    334 	response.type = SWC_LAUNCH_EVENT_RESPONSE;
    335 	response.serial = request.serial;
    336 
    337 	switch (request.type) {
    338 	case SWC_LAUNCH_REQUEST_OPEN_DEVICE:
    339 		if (size == 0 || path[size - 1] != '\0') {
    340 			fprintf(stderr, "path is not NULL terminated\n");
    341 			goto fail;
    342 		}
    343 		if ((request.flags & (O_ACCMODE | O_NONBLOCK | O_CLOEXEC)) !=
    344 		    request.flags) {
    345 			fprintf(stderr, "invalid open flags\n");
    346 			goto fail;
    347 		}
    348 
    349 		fd = open(path, request.flags | O_CLOEXEC);
    350 		if (fd == -1) {
    351 			fprintf(stderr, "open %s: %s\n", path, strerror(errno));
    352 			goto fail;
    353 		}
    354 		if (fstat(fd, &st) == -1) {
    355 			fprintf(stderr, "stat %s: %s\n", path, strerror(errno));
    356 			goto fail;
    357 		}
    358 
    359 		if (device_is_input(st.st_rdev)) {
    360 			if (!active) {
    361 				goto fail;
    362 			}
    363 			/* the same device again means a restarted server: drop the stale fd */
    364 			for (int i = 0; i < num_input_fds; ++i) {
    365 				struct stat old;
    366 
    367 				if (fstat(input_fds[i], &old) == 0 && old.st_rdev == st.st_rdev) {
    368 #ifdef EVIOCREVOKE
    369 					ioctl(input_fds[i], EVIOCREVOKE, 0);
    370 #endif
    371 					close(input_fds[i]);
    372 					input_fds[i--] = input_fds[--num_input_fds];
    373 				}
    374 			}
    375 			if (num_input_fds == ARRAY_LENGTH(input_fds)) {
    376 				fprintf(stderr, "too many input devices opened\n");
    377 				goto fail;
    378 			}
    379 			#ifdef __FreeBSD__
    380 			/* this (EVIOCGRAB) is the only way to
    381 			 * prevent the TTY from recieving
    382 			 * input from the neuswc session.
    383 			 */
    384 			if (ioctl(fd, EVIOCGRAB, (void*)1) == -1)
    385 			  {
    386 			    fprintf(stderr, "EVIOCGRAB %s: %s", path, strerror(errno));
    387 			    goto fail;
    388 			  }
    389 			#endif
    390 			input_fds[num_input_fds++] = fd;
    391 		} else if (device_is_drm(st.st_rdev)) {
    392 #ifdef ENABLE_DRM
    393 			/* the stale fd is still master and would keep the new server from drawing */
    394 			for (int i = 0; i < num_drm_fds; ++i) {
    395 				struct stat old;
    396 
    397 				if (fstat(drm_fds[i], &old) == 0 && old.st_rdev == st.st_rdev) {
    398 					drmDropMaster(drm_fds[i]);
    399 					close(drm_fds[i]);
    400 					drm_fds[i--] = drm_fds[--num_drm_fds];
    401 				}
    402 			}
    403 			if (num_drm_fds == ARRAY_LENGTH(drm_fds)) {
    404 				fprintf(stderr, "too many DRM devices opened\n");
    405 				goto fail;
    406 			}
    407 			drm_fds[num_drm_fds++] = fd;
    408 			if (active && drmSetMaster(fd) < 0)
    409 				fprintf(stderr, "drmSetMaster %s: %s\n", path, strerror(errno));
    410 #else
    411 			fprintf(stderr, "DRM device requested by non-DRM backend\n");
    412 			goto fail;
    413 #endif
    414 #ifdef ENABLE_FBDEV
    415 		} else if (device_is_fbdev(st.st_rdev)) {
    416 			if (!active) {
    417 				goto fail;
    418 			}
    419 #endif
    420 #ifdef ENABLE_WSDISPLAY
    421 		} else if (device_is_tty(st.st_rdev)) {
    422 			if (!active) {
    423 				goto fail;
    424 			}
    425 #endif
    426 		} else {
    427 			fprintf(stderr, "requested fd is not a video or input device\n");
    428 			goto fail;
    429 		}
    430 		break;
    431 	case SWC_LAUNCH_REQUEST_ACTIVATE_VT:
    432 		if (!active) {
    433 			goto fail;
    434 		}
    435 
    436 		if (ioctl(tty_fd, VT_ACTIVATE, request.vt) == -1) {
    437 			fprintf(stderr, "failed to activate VT %d: %s\n", request.vt,
    438 			        strerror(errno));
    439 		}
    440 		break;
    441 	default:
    442 		fprintf(stderr, "unknown request %u\n", request.type);
    443 		goto fail;
    444 	}
    445 
    446 	response.success = true;
    447 	goto done;
    448 
    449 fail:
    450 	response.success = false;
    451 	if (fd != -1) {
    452 		close(fd);
    453 	}
    454 	fd = -1;
    455 done:
    456 	send_fd(socket, fd, response_iov, 1);
    457 }
    458 
    459 static void
    460 find_vt(char *vt, size_t size)
    461 {
    462 #if defined(__NetBSD__)
    463 	if (snprintf(vt, size, "/dev/ttyE1") >= size) {
    464 		die("VT number is too large");
    465 	}
    466 #elif defined(__OpenBSD__)
    467 	const char *tty;
    468 	tty = ttyname(STDIN_FILENO);
    469 	if (!tty || strncmp(tty, "/dev/ttyC", 8) != 0) {
    470 		die("must be run from wscons VT (/dev/ttyC*)");
    471 	}
    472 	if (snprintf(vt, size, "%s", tty) >= size) {
    473 		die("VT number is too large");
    474 	}
    475 #else
    476 	char *vtnr;
    477 	int tty0_fd, vt_num;
    478 
    479 	/* If we are running from an existing X or wayland session, always open a
    480 	 * new VT instead of using the current one. */
    481 	if (getenv("DISPLAY") || getenv("WAYLAND_DISPLAY") ||
    482 	    !(vtnr = getenv("XDG_VTNR"))) {
    483 #if defined(__FreeBSD__)
    484 	  tty0_fd=open("/dev/ttyv0", O_RDWR | O_CLOEXEC);
    485 	  #else
    486 		tty0_fd = open("/dev/tty0", O_RDWR | O_CLOEXEC);
    487 		#endif
    488 		if (tty0_fd == -1) {
    489 			die("open /dev/tty0:");
    490 		}
    491 		if (ioctl(tty0_fd, VT_OPENQRY, &vt_num) != 0) {
    492 			die("VT open query failed:");
    493 		}
    494 		close(tty0_fd);
    495 #if defined(__FreeBSD__)
    496 		if (snprintf(vt, size, "/dev/ttyv%d", vt_num - 1) >= size) {
    497 		#else
    498 		if (snprintf(vt, size, "/dev/tty%d", vt_num) >= size) {
    499 		
    500 		#endif
    501 		  			die("VT number is too large");
    502 		}
    503 	} else {
    504 #if defined(__FreeBSD__)
    505 		  int n=atoi(vtnr);
    506 		  if (snprintf(vt, size, "/dev/ttyv%d", n - 1) >= size) {
    507 		  #else
    508 		if (snprintf(vt, size, "/dev/tty%s", vtnr) >= size) {
    509 		  #endif
    510 			die("XDG_VTNR is too long");
    511 		}
    512 	}
    513 #endif
    514 }
    515 
    516 static int
    517 open_tty(const char *tty_name)
    518 {
    519 	char *stdin_tty;
    520 	int fd;
    521 
    522 	/* Check if we are already running on the desired VT */
    523 	if ((stdin_tty = ttyname(STDIN_FILENO)) &&
    524 	    strcmp(tty_name, stdin_tty) == 0) {
    525 		return STDIN_FILENO;
    526 	}
    527 
    528 	fd = open(tty_name, O_RDWR | O_NOCTTY | O_CLOEXEC);
    529 	if (fd < 0) {
    530 		die("open %s:", tty_name);
    531 	}
    532 
    533 	return fd;
    534 }
    535 
    536 static void
    537 setup_tty(int fd)
    538 {
    539 	struct stat st;
    540 	int vt;
    541 #if !defined(__FreeBSD__)
    542 	struct vt_stat state;
    543 #endif
    544 	struct vt_mode mode = {
    545 	    .mode = VT_PROCESS, .relsig = SIGUSR1, .acqsig = SIGUSR2,
    546 #ifdef __OpenBSD__
    547 	    /* wsdisplay validates frsig but is unused */
    548 	    .frsig = SIGUSR1,
    549 #endif
    550 	};
    551 
    552 	if (fstat(fd, &st) == -1) {
    553 		die("failed to stat TTY fd:");
    554 	}
    555 	vt = minor(st.st_rdev);
    556 
    557 #ifdef __OpenBSD__
    558 	if (!device_is_tty(st.st_rdev)) {
    559 		die("not a valid VT");
    560 	}
    561 #else
    562 	if (!device_is_tty(st.st_rdev) || vt == 0) {
    563 		die("not a valid VT");
    564 	}
    565 #endif
    566 
    567 #if defined(__FreeBSD__)
    568 	{
    569 	  int vt_num;
    570 	  if (ioctl(fd, VT_GETACTIVE, &vt_num) == -1)
    571 	    {
    572 	      die("failed to get current VT state:");
    573 	    }
    574 	  original_vt_state.vt=vt_num;
    575 	}
    576 #else
    577 	if (ioctl(fd, VT_GETSTATE, &state) == -1) {
    578 		die("failed to get the current VT state:");
    579 	}
    580 #endif
    581 
    582 #if !defined(__FreeBSD__)
    583 	original_vt_state.vt = state.v_active;
    584 #endif
    585 #ifdef __OpenBSD__
    586 	/* VT ioctl api expects it to start from 1 */
    587 	++vt;
    588 #endif
    589 
    590 #ifdef KDGETMODE
    591 	if (ioctl(fd, KDGKBMODE, &original_vt_state.kb_mode)) {
    592 		die("failed to get keyboard mode:");
    593 	}
    594 	if (ioctl(fd, KDGETMODE, &original_vt_state.console_mode)) {
    595 		die("failed to get console mode:");
    596 	}
    597 #else
    598 	original_vt_state.kb_mode = K_XLATE;
    599 	original_vt_state.console_mode = KD_TEXT;
    600 #endif
    601 
    602 #ifdef K_OFF
    603 	if (ioctl(fd, KDSKBMODE, K_OFF) == -1) {
    604 		die("failed to set keyboard mode to K_OFF:");
    605 	}
    606 #elif defined(__FreeBSD__)
    607 	if (ioctl(fd, KDSKBMODE, K_CODE) == -1) {
    608 	  	 die("failed to set keyboard mode to K_RAW:");
    609 	}
    610 #endif
    611 	if (ioctl(fd, KDSETMODE, KD_GRAPHICS) == -1) {
    612 		perror("KDSETMODE KD_GRAPHICS");
    613 		goto error0;
    614 	}
    615 
    616 #ifndef __FreeBSD__
    617 	if (ioctl(fd, VT_SETMODE, &mode) == -1) {
    618 		perror("failed to set VT mode");
    619 		goto error1;
    620 	}
    621 #endif
    622 
    623 #ifdef __OpenBSD__
    624 	if (vt != original_vt_state.vt) {
    625 		fprintf(stderr, "OpenBSD: start on the active ttyC console\n");
    626 		goto error2;
    627 	}
    628 	activate();
    629 #else
    630 	if (vt == original_vt_state.vt) {
    631 		activate();
    632 	} else if (!nflag) {
    633 		if (ioctl(fd, VT_ACTIVATE, vt) == -1) {
    634 			perror("failed to activate VT");
    635 			goto error2;
    636 		}
    637 
    638 		if (ioctl(fd, VT_WAITACTIVE, vt) == -1) {
    639 			perror("failed to wait for VT to become active");
    640 			goto error2;
    641 		}
    642 	}
    643 #endif
    644 	original_vt_state.altered = true;
    645 
    646 	return;
    647 
    648 #ifndef __FreeBSD__
    649 error2:
    650 	mode = (struct vt_mode){.mode = VT_AUTO};
    651 	ioctl(fd, VT_SETMODE, &mode);
    652 error1:
    653 #endif
    654 #ifndef __OpenBSD__
    655 	ioctl(fd, KDSKBMODE, original_vt_state.kb_mode);
    656 #endif
    657 error0:
    658 	ioctl(fd, KDSETMODE, original_vt_state.console_mode);
    659 	exit(EXIT_FAILURE);
    660 }
    661 
    662 #ifdef __linux__
    663 #define TEST_BIT(bits, n) ((bits)[(n) / (8 * sizeof(long))] >> ((n) % (8 * sizeof(long))) & 1)
    664 
    665 /* open every keyboard not already open */
    666 static void
    667 scan_keyboards(void)
    668 {
    669 	DIR *dir;
    670 	struct dirent *entry;
    671 	char path[PATH_MAX];
    672 	unsigned long keys[KEY_MAX / (8 * sizeof(long)) + 1];
    673 	struct stat st;
    674 	int fd, i;
    675 
    676 	if (!(dir = opendir("/dev/input")))
    677 		return;
    678 	while ((entry = readdir(dir)) && num_keyboards < ESCAPE_KEYBOARDS) {
    679 		if (strncmp(entry->d_name, "event", 5) != 0)
    680 			continue;
    681 		snprintf(path, sizeof(path), "/dev/input/%s", entry->d_name);
    682 		if (stat(path, &st) < 0 || !device_is_input(st.st_rdev))
    683 			continue;
    684 		for (i = 0; i < num_keyboards && keyboards[i].rdev != st.st_rdev; ++i)
    685 			;
    686 		if (i < num_keyboards)
    687 			continue;
    688 		if ((fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC)) < 0)
    689 			continue;
    690 		memset(keys, 0, sizeof(keys));
    691 		if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keys)), keys) < 0 ||
    692 		    !TEST_BIT(keys, KEY_BACKSPACE) || !TEST_BIT(keys, KEY_LEFTCTRL)) {
    693 			close(fd);
    694 			continue;
    695 		}
    696 		keyboards[num_keyboards].fd = fd;
    697 		keyboards[num_keyboards].rdev = st.st_rdev;
    698 		++num_keyboards;
    699 	}
    700 	closedir(dir);
    701 }
    702 
    703 static void
    704 drop_keyboard(int i)
    705 {
    706 	close(keyboards[i].fd);
    707 	keyboards[i] = keyboards[--num_keyboards];
    708 }
    709 
    710 static void
    711 handle_keyboard(int i)
    712 {
    713 	struct input_event ev[64];
    714 	ssize_t n;
    715 	size_t k;
    716 
    717 	while ((n = read(keyboards[i].fd, ev, sizeof(ev))) > 0) {
    718 		for (k = 0; k < (size_t)n / sizeof(ev[0]); ++k) {
    719 			bool down = ev[k].value != 0;
    720 
    721 			if (ev[k].type != EV_KEY)
    722 				continue;
    723 			switch (ev[k].code) {
    724 			case KEY_LEFTCTRL: ctrl_l = down; continue;
    725 			case KEY_RIGHTCTRL: ctrl_r = down; continue;
    726 			case KEY_LEFTALT: alt_l = down; continue;
    727 			case KEY_RIGHTALT: alt_r = down; continue;
    728 			}
    729 			/* presses with ctrl+alt held, on our vt only */
    730 			if (ev[k].value != 1 || !active || !(ctrl_l || ctrl_r) || !(alt_l || alt_r))
    731 				continue;
    732 			if (ev[k].code == KEY_BACKSPACE) {
    733 				long long now = now_ms();
    734 
    735 				if (last_zap && now - last_zap <= ESCAPE_WINDOW) {
    736 					fprintf(stderr, "swc-launch: Ctrl+Alt+Backspace twice, ending the session\n");
    737 					end_session(EXIT_FAILURE);
    738 				}
    739 				last_zap = now;
    740 				fprintf(stderr, "swc-launch: Ctrl+Alt+Backspace; again within 3s ends the session\n");
    741 			} else if (ev[k].code >= KEY_F1 && ev[k].code <= KEY_F10) {
    742 				ioctl(tty_fd, VT_ACTIVATE, ev[k].code - KEY_F1 + 1);
    743 			} else if (ev[k].code == KEY_F11 || ev[k].code == KEY_F12) {
    744 				ioctl(tty_fd, VT_ACTIVATE, ev[k].code == KEY_F11 ? 11 : 12);
    745 			}
    746 		}
    747 	}
    748 	if (n < 0 && errno != EAGAIN && errno != EINTR)
    749 		drop_keyboard(i); /* unplugged */
    750 }
    751 #endif
    752 
    753 static void
    754 run(int fd)
    755 {
    756 	struct pollfd fds[2 + ESCAPE_KEYBOARDS_MAX];
    757 	int status, nfds, i;
    758 	long long next_scan = 0;
    759 	pid_t pid;
    760 	char sig;
    761 
    762 	for (;;) {
    763 		nfds = 0;
    764 		fds[nfds++] = (struct pollfd){.fd = fd, .events = POLLIN};
    765 		fds[nfds++] = (struct pollfd){.fd = sigfd[0], .events = POLLIN};
    766 #ifdef __linux__
    767 		if (escape_enabled && now_ms() >= next_scan) {
    768 			scan_keyboards();
    769 			next_scan = now_ms() + ESCAPE_RESCAN;
    770 		}
    771 		for (i = 0; i < num_keyboards; ++i)
    772 			fds[nfds++] = (struct pollfd){.fd = keyboards[i].fd, .events = POLLIN};
    773 #endif
    774 		if (poll(fds, nfds, escape_enabled ? ESCAPE_RESCAN : -1) < 0) {
    775 			if (errno == EINTR) {
    776 				continue;
    777 			}
    778 			die("poll:");
    779 		}
    780 		if (fds[0].revents & POLLIN) {
    781 			handle_socket_data(fd);
    782 		} else if (fds[0].revents & (POLLHUP | POLLERR)) {
    783 			/* server gone: stop polling its socket, sigchld ends the session */
    784 			fds[0].fd = -1;
    785 			fd = -1;
    786 		}
    787 #ifdef __linux__
    788 		for (i = nfds - 1; i >= 2; --i) {
    789 			if (fds[i].revents)
    790 				handle_keyboard(i - 2);
    791 		}
    792 #endif
    793 		if (fds[1].revents) {
    794 			if (read(sigfd[0], &sig, 1) <= 0) {
    795 				continue;
    796 			}
    797 			switch (sig) {
    798 			case SIGCHLD:
    799 				while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
    800 					if (pid == child_pid) {
    801 						child_pid = -1;
    802 						cleanup();
    803 						exit(WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status));
    804 					}
    805 				}
    806 				break;
    807 			case SIGTERM:
    808 			case SIGINT:
    809 			case SIGHUP:
    810 			case SIGQUIT:
    811 				fprintf(stderr, "swc-launch: signal %d, ending the session\n", sig);
    812 				end_session(128 + sig);
    813 			case SIGUSR1:
    814 				deactivate();
    815 				ioctl(tty_fd, VT_RELDISP, 1);
    816 				break;
    817 			case SIGUSR2:
    818 				ioctl(tty_fd, VT_RELDISP, VT_ACKACQ);
    819 				activate();
    820 				break;
    821 			}
    822 		}
    823 	}
    824 }
    825 
    826 int
    827 main(int argc, char *argv[])
    828 {
    829 	extern char **environ;
    830 	int option;
    831 	char *vt = NULL, buf[64];
    832 	struct sigaction action = {
    833 	    .sa_handler = handle_signal,
    834 	    .sa_flags = SA_RESTART,
    835 	};
    836 	sigset_t set;
    837 	pid_t pid;
    838 	posix_spawnattr_t attr;
    839 
    840 	while ((option = getopt(argc, argv, "net:")) != -1) {
    841 		switch (option) {
    842 		case 'n':
    843 			nflag = true;
    844 			break;
    845 		case 'e':
    846 #ifdef __linux__
    847 			escape_enabled = true;
    848 #endif
    849 			break;
    850 		case 't':
    851 			vt = optarg;
    852 			break;
    853 		default:
    854 			usage(argv[0]);
    855 		}
    856 	}
    857 
    858 	if (argc - optind < 1) {
    859 		usage(argv[0]);
    860 	}
    861 
    862 	
    863 	if (socketpair(AF_LOCAL,
    864 		       #ifdef __linux__
    865 		       SOCK_SEQPACKET,
    866 		       #else
    867 		       SOCK_STREAM,
    868 		       #endif
    869 		       0, sock) == -1) {
    870 		die("socketpair:");
    871 	}
    872 	if (fcntl(sock[0], F_SETFD, FD_CLOEXEC) == -1) {
    873 		die("failed set CLOEXEC on socket:");
    874 	}
    875 
    876 	if (pipe2(sigfd, O_CLOEXEC) == -1) {
    877 		die("pipe:");
    878 	}
    879 	if (sigaction(SIGCHLD, &action, NULL) == -1) {
    880 		die("sigaction SIGCHLD:");
    881 	}
    882 	if (sigaction(SIGUSR1, &action, NULL) == -1) {
    883 		die("sigaction SIGUSR1:");
    884 	}
    885 	if (sigaction(SIGUSR2, &action, NULL) == -1) {
    886 		die("sigaction SIGUSR2:");
    887 	}
    888 	/* end the session, console first */
    889 	if (sigaction(SIGTERM, &action, NULL) == -1 ||
    890 	    sigaction(SIGINT, &action, NULL) == -1 ||
    891 	    sigaction(SIGHUP, &action, NULL) == -1 ||
    892 	    sigaction(SIGQUIT, &action, NULL) == -1) {
    893 		die("sigaction:");
    894 	}
    895 	{
    896 		/* restore the console on our own crash */
    897 		struct sigaction fatal = {.sa_handler = handle_fatal, .sa_flags = SA_RESETHAND};
    898 		int sigs[] = {SIGSEGV, SIGBUS, SIGABRT, SIGFPE, SIGILL};
    899 
    900 		for (size_t i = 0; i < ARRAY_LENGTH(sigs); ++i)
    901 			sigaction(sigs[i], &fatal, NULL);
    902 	}
    903 	sigfillset(&set);
    904 	sigdelset(&set, SIGCHLD);
    905 	sigdelset(&set, SIGUSR1);
    906 	sigdelset(&set, SIGUSR2);
    907 	sigdelset(&set, SIGTERM);
    908 	sigdelset(&set, SIGINT);
    909 	sigdelset(&set, SIGHUP);
    910 	sigdelset(&set, SIGQUIT);
    911 	sigdelset(&set, SIGSEGV);
    912 	sigdelset(&set, SIGBUS);
    913 	sigdelset(&set, SIGABRT);
    914 	sigdelset(&set, SIGFPE);
    915 	sigdelset(&set, SIGILL);
    916 	sigprocmask(SIG_SETMASK, &set, NULL);
    917 
    918 	if (!vt) {
    919 		find_vt(buf, sizeof(buf));
    920 		vt = buf;
    921 	}
    922 
    923 	fprintf(stderr, "running on %s\n", vt);
    924 	tty_fd = open_tty(vt);
    925 	setup_tty(tty_fd);
    926 	if (setenv(SWC_LAUNCH_TTY_ENV, vt, 1) == -1) {
    927 		die("setenv %s:", SWC_LAUNCH_TTY_ENV);
    928 	}
    929 
    930 	snprintf(buf, sizeof(buf), "%d", sock[1]);
    931 	setenv(SWC_LAUNCH_SOCKET_ENV, buf, 1);
    932 
    933 	/* make sure XDG_RUNTIME_DIR is set */
    934 	if (!getenv("XDG_RUNTIME_DIR")) {
    935 		uid_t uid = getuid();
    936 		snprintf(buf, sizeof(buf), "/tmp/XDG_RUNTIME_DIR_%d", uid);
    937 		if (mkdir(buf, 0700) == -1 && errno != EEXIST) {
    938 			die("mkdir %s:", buf);
    939 		}
    940 		setenv("XDG_RUNTIME_DIR", buf, 1);
    941 		fprintf(stderr, "set XDG_RUNTIME_DIR=%s\n", buf);
    942 	}
    943 
    944 	if ((errno = posix_spawnattr_init(&attr))) {
    945 		die("posix_spawnattr_init:");
    946 	}
    947 	if ((errno = posix_spawnattr_setflags(&attr, POSIX_SPAWN_RESETIDS |
    948 	                                                 POSIX_SPAWN_SETSIGMASK))) {
    949 		die("posix_spawnattr_setflags:");
    950 	}
    951 	sigemptyset(&set);
    952 	if ((errno = posix_spawnattr_setsigmask(&attr, &set))) {
    953 		die("posix_spawnattr_setsigmask:");
    954 	}
    955 	if ((errno = posix_spawnp(&pid, argv[optind], NULL, &attr, argv + optind,
    956 	                          environ))) {
    957 		die("posix_spawnp %s:", argv[optind]);
    958 	}
    959 	child_pid = pid;
    960 	posix_spawnattr_destroy(&attr);
    961 
    962 	close(sock[1]);
    963 	run(sock[0]);
    964 
    965 	return EXIT_SUCCESS;
    966 }