xref: /openbmc/obmc-console/console-server.c (revision d972ab558efb5d23790c4638a3012de6c06a7fad)
1 /**
2  * Console server process for OpenBMC
3  *
4  * Copyright © 2016 IBM Corporation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 #include <assert.h>
20 #include <errno.h>
21 #include <signal.h>
22 #include <stdint.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <string.h>
30 #include <getopt.h>
31 #include <glob.h>
32 #include <limits.h>
33 #include <time.h>
34 #include <termios.h>
35 
36 #include <sys/types.h>
37 #include <sys/time.h>
38 #include <sys/socket.h>
39 #include <poll.h>
40 
41 #include "console-mux.h"
42 
43 #include "console-server.h"
44 #include "config.h"
45 
46 #define DEV_PTS_PATH "/dev/pts"
47 
48 /* default size of the shared backlog ringbuffer */
49 const size_t default_buffer_size = 128ul * 1024ul;
50 
51 /* state shared with the signal handler */
52 static volatile sig_atomic_t sigint;
53 
usage(const char * progname)54 static void usage(const char *progname)
55 {
56 	fprintf(stderr,
57 		"usage: %s [options] <DEVICE>\n"
58 		"\n"
59 		"Options:\n"
60 		"  --config <FILE>\tUse FILE for configuration\n"
61 		"  --console-id <NAME>\tUse NAME in the UNIX domain socket address\n"
62 		"",
63 		progname);
64 }
65 
console_server_pollfd_reclaimable(struct pollfd * p)66 static bool console_server_pollfd_reclaimable(struct pollfd *p)
67 {
68 	return p->fd == -1 && p->events == 0 && p->revents == ~0;
69 }
70 
71 static ssize_t
console_server_find_released_pollfd(struct console_server * server)72 console_server_find_released_pollfd(struct console_server *server)
73 {
74 	for (size_t i = 0; i < server->capacity_pollfds; i++) {
75 		struct pollfd *p = &server->pollfds[i];
76 		if (console_server_pollfd_reclaimable(p)) {
77 			return (ssize_t)i;
78 		}
79 	}
80 	return -1;
81 }
82 
83 // returns the index of that pollfd in server->pollfds
84 // we cannot return a pointer because 'realloc' may move server->pollfds
console_server_request_pollfd(struct console_server * server,int fd,short int events)85 ssize_t console_server_request_pollfd(struct console_server *server, int fd,
86 				      short int events)
87 {
88 	ssize_t index;
89 	struct pollfd *pollfd;
90 
91 	index = console_server_find_released_pollfd(server);
92 
93 	if (index < 0) {
94 		const size_t newcap = server->capacity_pollfds + 1;
95 
96 		struct pollfd *newarr = reallocarray(server->pollfds, newcap,
97 						     sizeof(struct pollfd));
98 		if (newarr == NULL) {
99 			return -1;
100 		}
101 		server->pollfds = newarr;
102 
103 		index = (ssize_t)server->capacity_pollfds;
104 
105 		server->capacity_pollfds = newcap;
106 	}
107 
108 	pollfd = &server->pollfds[index];
109 	pollfd->fd = fd;
110 	pollfd->events = events;
111 	pollfd->revents = 0;
112 
113 	return index;
114 }
115 
console_server_release_pollfd(struct console_server * server,size_t pollfd_index)116 int console_server_release_pollfd(struct console_server *server,
117 				  size_t pollfd_index)
118 {
119 	if (pollfd_index >= server->capacity_pollfds) {
120 		return -1;
121 	}
122 
123 	struct pollfd *pfd = &server->pollfds[pollfd_index];
124 
125 	// mark pollfd as reclaimable
126 
127 	// ignore this file descriptor when calling 'poll'
128 	// https://www.man7.org/linux/man-pages/man2/poll.2.html
129 	pfd->fd = -1;
130 	pfd->events = 0;
131 	pfd->revents = ~0;
132 
133 	return 0;
134 }
135 
136 /* populates server->tty.dev and server->tty.sysfs_devnode, using the tty kernel name */
tty_find_device(struct console_server * server)137 static int tty_find_device(struct console_server *server)
138 {
139 	char *tty_class_device_link = NULL;
140 	char *tty_path_input_real = NULL;
141 	char *tty_device_tty_dir = NULL;
142 	char *tty_vuart_lpc_addr = NULL;
143 	char *tty_device_reldir = NULL;
144 	char *tty_sysfs_devnode = NULL;
145 	char *tty_kname_real = NULL;
146 	char *tty_path_input = NULL;
147 	int rc;
148 
149 	server->tty.type = TTY_DEVICE_UNDEFINED;
150 
151 	assert(server->tty.kname);
152 	if (!strlen(server->tty.kname)) {
153 		warnx("TTY kname must not be empty");
154 		rc = -1;
155 		goto out_free;
156 	}
157 
158 	if (server->tty.kname[0] == '/') {
159 		tty_path_input = strdup(server->tty.kname);
160 		if (!tty_path_input) {
161 			rc = -1;
162 			goto out_free;
163 		}
164 	} else {
165 		rc = asprintf(&tty_path_input, "/dev/%s", server->tty.kname);
166 		if (rc < 0) {
167 			goto out_free;
168 		}
169 	}
170 
171 	/* udev may rename the tty name with a symbol link, try to resolve */
172 	tty_path_input_real = realpath(tty_path_input, NULL);
173 	if (!tty_path_input_real) {
174 		warn("Can't find realpath for %s", tty_path_input);
175 		rc = -1;
176 		goto out_free;
177 	}
178 
179 	/*
180 	 * Allow hooking obmc-console-server up to PTYs for testing
181 	 *
182 	 * https://amboar.github.io/notes/2023/05/02/testing-obmc-console-with-socat.html
183 	 */
184 	if (!strncmp(DEV_PTS_PATH, tty_path_input_real, strlen(DEV_PTS_PATH))) {
185 		server->tty.type = TTY_DEVICE_PTY;
186 		server->tty.dev = strdup(server->tty.kname);
187 		rc = server->tty.dev ? 0 : -1;
188 		goto out_free;
189 	}
190 
191 	tty_kname_real = basename(tty_path_input_real);
192 	if (!tty_kname_real) {
193 		warn("Can't find real name for %s", server->tty.kname);
194 		rc = -1;
195 		goto out_free;
196 	}
197 
198 	rc = asprintf(&tty_class_device_link, "/sys/class/tty/%s",
199 		      tty_kname_real);
200 	if (rc < 0) {
201 		goto out_free;
202 	}
203 
204 	tty_device_tty_dir = realpath(tty_class_device_link, NULL);
205 	if (!tty_device_tty_dir) {
206 		warn("Can't query sysfs for device %s", tty_kname_real);
207 		rc = -1;
208 		goto out_free;
209 	}
210 
211 	rc = asprintf(&server->tty.dev, "/dev/%s", tty_kname_real);
212 	if (rc < 0) {
213 		goto out_free;
214 	}
215 
216 	// Default to non-VUART
217 	server->tty.type = TTY_DEVICE_UART;
218 
219 	/* Prior to 6.8, we have the tty device directly under the platform
220 	 * device:
221 	 *
222 	 *  1e787000.serial/lpc_address
223 	 *  1e787000.serial/tty/ttySx/
224 	 *
225 	 * As of 6.8, those serial devices now use the port/serdev (:m.n)
226 	 * layout reflected in the sysfs structure:
227 	 *
228 	 *  1e787000.serial/lpc_address
229 	 *  1e787000.serial/1e787000.serial:0/1e787000.serial:0.0/tty/ttySx/
230 	 *
231 	 * - so we need to check for both
232 	 */
233 	const char *rel_dirs[] = {
234 		"../../../../",
235 		"../../",
236 	};
237 
238 	for (unsigned int i = 0; i < (sizeof(rel_dirs) / sizeof(rel_dirs[0]));
239 	     i++) {
240 		const char *rel_dir = rel_dirs[i];
241 
242 		free(tty_device_reldir);
243 		free(tty_sysfs_devnode);
244 
245 		rc = asprintf(&tty_device_reldir, "%s/%s", tty_device_tty_dir,
246 			      rel_dir);
247 		if (rc < 0) {
248 			goto out_free;
249 		}
250 
251 		tty_sysfs_devnode = realpath(tty_device_reldir, NULL);
252 		/* not really an error, but it'd be unusual if we cannot
253 		 * resolve two parent dirs...
254 		 */
255 		if (!tty_sysfs_devnode) {
256 			warn("Can't find parent device for %s", tty_kname_real);
257 			rc = 0;
258 			goto out_free;
259 		}
260 
261 		/* Arbitrarily pick an attribute to determine UART vs VUART */
262 		rc = asprintf(&tty_vuart_lpc_addr, "%s/lpc_address",
263 			      tty_sysfs_devnode);
264 		if (rc < 0) {
265 			goto out_free;
266 		}
267 
268 		rc = access(tty_vuart_lpc_addr, F_OK);
269 		if (!rc) {
270 			server->tty.type = TTY_DEVICE_VUART;
271 			server->tty.vuart.sysfs_devnode =
272 				strdup(tty_sysfs_devnode);
273 			break;
274 		}
275 	}
276 
277 	rc = 0;
278 
279 out_free:
280 	free(tty_vuart_lpc_addr);
281 	free(tty_class_device_link);
282 	free(tty_sysfs_devnode);
283 	free(tty_device_tty_dir);
284 	free(tty_device_reldir);
285 	free(tty_path_input);
286 	free(tty_path_input_real);
287 	return rc;
288 }
289 
tty_set_sysfs_attr(struct console_server * server,const char * name,int value)290 static int tty_set_sysfs_attr(struct console_server *server, const char *name,
291 			      int value)
292 {
293 	char *path;
294 	FILE *fp;
295 	int rc;
296 
297 	assert(server->tty.type == TTY_DEVICE_VUART);
298 
299 	if (!server->tty.vuart.sysfs_devnode) {
300 		return -1;
301 	}
302 
303 	rc = asprintf(&path, "%s/%s", server->tty.vuart.sysfs_devnode, name);
304 	if (rc < 0) {
305 		return -1;
306 	}
307 
308 	fp = fopen(path, "w");
309 	if (!fp) {
310 		warn("Can't access attribute %s on device %s", name,
311 		     server->tty.kname);
312 		rc = -1;
313 		goto out_free;
314 	}
315 	setvbuf(fp, NULL, _IONBF, 0);
316 
317 	rc = fprintf(fp, "0x%x", value);
318 	if (rc < 0) {
319 		warn("Error writing to %s attribute of device %s", name,
320 		     server->tty.kname);
321 	}
322 	fclose(fp);
323 
324 out_free:
325 	free(path);
326 	return rc;
327 }
328 
329 /**
330  * Set termios attributes on the console tty.
331  */
tty_init_termios(struct console_server * server)332 void tty_init_termios(struct console_server *server)
333 {
334 	struct termios termios;
335 	int rc;
336 
337 	rc = tcgetattr(server->tty.fd, &termios);
338 	if (rc) {
339 		warn("Can't read tty termios");
340 		return;
341 	}
342 
343 	if (server->tty.type == TTY_DEVICE_UART && server->tty.uart.baud) {
344 		if (cfsetspeed(&termios, server->tty.uart.baud) < 0) {
345 			warn("Couldn't set speeds for %s", server->tty.kname);
346 		}
347 	}
348 
349 	/* Set console to raw mode: we don't want any processing to occur on
350 	 * the underlying terminal input/output.
351 	 */
352 	cfmakeraw(&termios);
353 
354 	rc = tcsetattr(server->tty.fd, TCSANOW, &termios);
355 	if (rc) {
356 		warn("Can't set terminal options for %s", server->tty.kname);
357 	}
358 }
359 
360 /**
361  * Open and initialise the serial device
362  */
tty_init_vuart_io(struct console_server * server)363 static void tty_init_vuart_io(struct console_server *server)
364 {
365 	assert(server->tty.type == TTY_DEVICE_VUART);
366 
367 	if (server->tty.vuart.sirq) {
368 		tty_set_sysfs_attr(server, "sirq", server->tty.vuart.sirq);
369 	}
370 
371 	if (server->tty.vuart.lpc_addr) {
372 		tty_set_sysfs_attr(server, "lpc_address",
373 				   server->tty.vuart.lpc_addr);
374 	}
375 }
376 
tty_init_io(struct console_server * server)377 static int tty_init_io(struct console_server *server)
378 {
379 	server->tty.fd = open(server->tty.dev, O_RDWR);
380 	if (server->tty.fd <= 0) {
381 		warn("Can't open tty %s", server->tty.dev);
382 		return -1;
383 	}
384 
385 	/* Disable character delay. We may want to later enable this when
386 	 * we detect larger amounts of data
387 	 */
388 	fcntl(server->tty.fd, F_SETFL, FNDELAY);
389 
390 	tty_init_termios(server);
391 
392 	ssize_t index =
393 		console_server_request_pollfd(server, server->tty.fd, POLLIN);
394 
395 	if (index < 0) {
396 		return -1;
397 	}
398 
399 	server->tty_pollfd_index = (size_t)index;
400 
401 	return 0;
402 }
403 
tty_init_vuart(struct console_server * server,struct config * config)404 static int tty_init_vuart(struct console_server *server, struct config *config)
405 {
406 	unsigned long parsed;
407 	const char *val;
408 	char *endp;
409 
410 	assert(server->tty.type == TTY_DEVICE_VUART);
411 
412 	val = config_get_value(config, "lpc-address");
413 	if (val) {
414 		errno = 0;
415 		parsed = strtoul(val, &endp, 0);
416 		if (parsed == ULONG_MAX && errno == ERANGE) {
417 			warn("Cannot interpret 'lpc-address' value as an unsigned long: '%s'",
418 			     val);
419 			return -1;
420 		}
421 
422 		if (parsed > UINT16_MAX) {
423 			warn("Invalid LPC address '%s'", val);
424 			return -1;
425 		}
426 
427 		server->tty.vuart.lpc_addr = (uint16_t)parsed;
428 		if (endp == optarg) {
429 			warn("Invalid LPC address: '%s'", val);
430 			return -1;
431 		}
432 	}
433 
434 	val = config_get_value(config, "sirq");
435 	if (val) {
436 		errno = 0;
437 		parsed = strtoul(val, &endp, 0);
438 		if (parsed == ULONG_MAX && errno == ERANGE) {
439 			warn("Cannot interpret 'sirq' value as an unsigned long: '%s'",
440 			     val);
441 		}
442 
443 		if (parsed > 16) {
444 			warn("Invalid LPC SERIRQ: '%s'", val);
445 		}
446 
447 		server->tty.vuart.sirq = (int)parsed;
448 		if (endp == optarg) {
449 			warn("Invalid sirq: '%s'", val);
450 		}
451 	}
452 
453 	return 0;
454 }
455 
tty_init(struct console_server * server,struct config * config,const char * tty_arg)456 static int tty_init(struct console_server *server, struct config *config,
457 		    const char *tty_arg)
458 {
459 	const char *val;
460 	int rc;
461 
462 	if (tty_arg) {
463 		server->tty.kname = tty_arg;
464 	} else if ((val = config_get_value(config, "upstream-tty"))) {
465 		server->tty.kname = val;
466 	} else {
467 		warnx("Error: No TTY device specified");
468 		return -1;
469 	}
470 
471 	rc = tty_find_device(server);
472 	if (rc) {
473 		return rc;
474 	}
475 
476 	switch (server->tty.type) {
477 	case TTY_DEVICE_VUART:
478 		rc = tty_init_vuart(server, config);
479 		if (rc) {
480 			return rc;
481 		}
482 
483 		tty_init_vuart_io(server);
484 		break;
485 	case TTY_DEVICE_UART:
486 		val = config_get_value(config, "baud");
487 		if (val) {
488 			if (config_parse_baud(&server->tty.uart.baud, val)) {
489 				warnx("Invalid baud rate: '%s'", val);
490 			}
491 		}
492 		break;
493 	case TTY_DEVICE_PTY:
494 		break;
495 	case TTY_DEVICE_UNDEFINED:
496 	default:
497 		warnx("Cannot configure unrecognised TTY device");
498 		return -1;
499 	}
500 
501 	return tty_init_io(server);
502 }
503 
tty_fini(struct console_server * server)504 static void tty_fini(struct console_server *server)
505 {
506 	if (server->tty_pollfd_index < server->capacity_pollfds) {
507 		console_server_release_pollfd(server, server->tty_pollfd_index);
508 		server->tty_pollfd_index = SIZE_MAX;
509 	}
510 
511 	if (server->tty.type == TTY_DEVICE_VUART) {
512 		free(server->tty.vuart.sysfs_devnode);
513 	}
514 
515 	free(server->tty.dev);
516 }
517 
write_to_path(const char * path,const char * data)518 static int write_to_path(const char *path, const char *data)
519 {
520 	int rc = 0;
521 	FILE *f = fopen(path, "w");
522 	if (!f) {
523 		return -1;
524 	}
525 
526 	if (fprintf(f, "%s", data) < 0) {
527 		rc = -1;
528 	}
529 
530 	if (fclose(f)) {
531 		rc = -1;
532 	}
533 
534 	return rc;
535 }
536 
537 #define ASPEED_UART_ROUTING_PATTERN                                            \
538 	"/sys/bus/platform/drivers/aspeed-uart-routing/*.uart-routing"
539 
uart_routing_init(struct config * config)540 static void uart_routing_init(struct config *config)
541 {
542 	const char *muxcfg;
543 	const char *p;
544 	size_t buflen;
545 	char *sink;
546 	char *source;
547 	char *muxdir;
548 	char *path;
549 	glob_t globbuf;
550 
551 	muxcfg = config_get_value(config, "aspeed-uart-routing");
552 	if (!muxcfg) {
553 		return;
554 	}
555 
556 	/* Find the driver's sysfs directory */
557 	if (glob(ASPEED_UART_ROUTING_PATTERN, GLOB_ERR | GLOB_NOSORT, NULL,
558 		 &globbuf) != 0) {
559 		warn("Couldn't find uart-routing driver directory, cannot apply config");
560 		return;
561 	}
562 	if (globbuf.gl_pathc != 1) {
563 		warnx("Found %zd uart-routing driver directories, cannot apply config",
564 		      globbuf.gl_pathc);
565 		goto out_free_glob;
566 	}
567 	muxdir = globbuf.gl_pathv[0];
568 
569 	/*
570 	 * Rather than faff about tracking a bunch of separate buffer sizes,
571 	 * just use one (worst-case) size for all of them -- +2 for a trailing
572 	 * NUL and a '/' separator to construct the sysfs file path.
573 	 */
574 	buflen = strlen(muxdir) + strlen(muxcfg) + 2;
575 
576 	sink = malloc(buflen);
577 	source = malloc(buflen);
578 	path = malloc(buflen);
579 	if (!path || !sink || !source) {
580 		warnx("Out of memory applying uart routing config");
581 		goto out_free_bufs;
582 	}
583 
584 	p = muxcfg;
585 	while (*p) {
586 		ssize_t bytes_scanned;
587 
588 		if (sscanf(p, " %[^:/ \t]:%[^: \t] %zn", sink, source,
589 			   &bytes_scanned) != 2) {
590 			warnx("Invalid syntax in aspeed uart config: '%s' not applied",
591 			      p);
592 			break;
593 		}
594 		p += bytes_scanned;
595 
596 		/*
597 		 * Check that the sink name looks reasonable before proceeding
598 		 * (there are other writable files in the same directory that
599 		 * we shouldn't be touching, such as 'driver_override' and
600 		 * 'uevent').
601 		 */
602 		if (strncmp(sink, "io", strlen("io")) != 0 &&
603 		    strncmp(sink, "uart", strlen("uart")) != 0) {
604 			warnx("Skipping invalid uart routing name '%s' (must be ioN or uartN)",
605 			      sink);
606 			continue;
607 		}
608 
609 		snprintf(path, buflen, "%s/%s", muxdir, sink);
610 		if (write_to_path(path, source)) {
611 			warn("Failed to apply uart-routing config '%s:%s'",
612 			     sink, source);
613 		}
614 	}
615 
616 out_free_bufs:
617 	free(path);
618 	free(source);
619 	free(sink);
620 out_free_glob:
621 	globfree(&globbuf);
622 }
623 
console_data_out(struct console * console,const uint8_t * data,size_t len)624 int console_data_out(struct console *console, const uint8_t *data, size_t len)
625 {
626 	return write_buf_to_fd(console->server->tty.fd, data, len);
627 }
628 
629 /* Prepare a socket name */
set_socket_info(struct console * console,struct config * config,const char * console_id)630 static int set_socket_info(struct console *console, struct config *config,
631 			   const char *console_id)
632 {
633 	ssize_t len;
634 
635 	/* Get console id */
636 	console->console_id = config_resolve_console_id(config, console_id);
637 
638 	/* Get the socket name/path */
639 	len = console_socket_path(console->socket_name, console->console_id);
640 	if (len < 0) {
641 		warn("Failed to set socket path: %s", strerror(errno));
642 		return EXIT_FAILURE;
643 	}
644 
645 	/* Socket name is not a null terminated string hence save the length */
646 	console->socket_name_len = len;
647 
648 	return 0;
649 }
650 
handlers_init(struct console * console,struct config * config)651 static void handlers_init(struct console *console, struct config *config)
652 {
653 	/* NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) */
654 	extern const struct handler_type *const __start_handlers[];
655 	extern const struct handler_type *const __stop_handlers[];
656 	/* NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) */
657 	size_t n_types;
658 	int j = 0;
659 	size_t i;
660 
661 	n_types = __stop_handlers - __start_handlers;
662 	console->handlers = calloc(n_types, sizeof(struct handler *));
663 	if (!console->handlers) {
664 		err(EXIT_FAILURE, "malloc(handlers)");
665 	}
666 
667 	printf("%zu handler type%s\n", n_types, n_types == 1 ? "" : "s");
668 
669 	for (i = 0; i < n_types; i++) {
670 		const struct handler_type *type = __start_handlers[i];
671 		struct handler *handler;
672 
673 		/* Should be picked up at build time by
674 		 * console_handler_register, but check anyway
675 		 */
676 		if (!type->init || !type->fini) {
677 			errx(EXIT_FAILURE,
678 			     "invalid handler type %s: no init() / fini()",
679 			     type->name);
680 		}
681 
682 		handler = type->init(type, console, config);
683 
684 		printf("  console '%s': handler %s [%sactive]\n",
685 		       console->console_id, type->name, handler ? "" : "in");
686 
687 		if (handler) {
688 			handler->type = type;
689 			console->handlers[j++] = handler;
690 		}
691 	}
692 
693 	console->n_handlers = j;
694 }
695 
handlers_fini(struct console * console)696 static void handlers_fini(struct console *console)
697 {
698 	struct handler *handler;
699 	int i;
700 
701 	for (i = 0; i < console->n_handlers; i++) {
702 		handler = console->handlers[i];
703 		handler->type->fini(handler);
704 	}
705 
706 	free(console->handlers);
707 	console->handlers = NULL;
708 	console->n_handlers = 0;
709 }
710 
get_current_time(struct timeval * tv)711 static int get_current_time(struct timeval *tv)
712 {
713 	struct timespec t;
714 	int rc;
715 
716 	/*
717 	 * We use clock_gettime(CLOCK_MONOTONIC) so we're immune to
718 	 * local time changes. However, a struct timeval is more
719 	 * convenient for calculations, so convert to that.
720 	 */
721 	rc = clock_gettime(CLOCK_MONOTONIC, &t);
722 	if (rc) {
723 		return rc;
724 	}
725 
726 	tv->tv_sec = t.tv_sec;
727 	tv->tv_usec = t.tv_nsec / 1000;
728 
729 	return 0;
730 }
731 
732 struct ringbuffer_consumer *
console_ringbuffer_consumer_register(struct console * console,ringbuffer_poll_fn_t poll_fn,void * data)733 console_ringbuffer_consumer_register(struct console *console,
734 				     ringbuffer_poll_fn_t poll_fn, void *data)
735 {
736 	return ringbuffer_consumer_register(console->rb, poll_fn, data);
737 }
738 
console_poller_register(struct console * console,struct handler * handler,poller_event_fn_t poller_fn,poller_timeout_fn_t timeout_fn,int fd,int events,void * data)739 struct poller *console_poller_register(struct console *console,
740 				       struct handler *handler,
741 				       poller_event_fn_t poller_fn,
742 				       poller_timeout_fn_t timeout_fn, int fd,
743 				       int events, void *data)
744 {
745 	struct poller *poller;
746 	long n;
747 
748 	const ssize_t index = console_server_request_pollfd(
749 		console->server, fd, (short)(events & 0x7fff));
750 	if (index < 0) {
751 		fprintf(stderr, "Error requesting pollfd\n");
752 		return NULL;
753 	}
754 
755 	poller = malloc(sizeof(*poller));
756 	// TODO: check for error case of malloc here and release previously requested pollfd
757 	poller->remove = false;
758 	poller->handler = handler;
759 	poller->event_fn = poller_fn;
760 	poller->timeout_fn = timeout_fn;
761 	timerclear(&poller->timeout);
762 	poller->data = data;
763 	poller->pollfd_index = index;
764 
765 	/* add one to our pollers array */
766 	n = console->n_pollers++;
767 	/*
768 	 * We're managing an array of pointers to aggregates, so don't warn about sizeof() on a
769 	 * pointer type.
770 	 */
771 	/* NOLINTBEGIN(bugprone-sizeof-expression) */
772 	console->pollers = reallocarray(console->pollers, console->n_pollers,
773 					sizeof(*console->pollers));
774 	// TODO: check for the error case of reallocarray and release previously requested pollfd
775 	/* NOLINTEND(bugprone-sizeof-expression) */
776 
777 	console->pollers[n] = poller;
778 
779 	return poller;
780 }
781 
console_poller_unregister(struct console * console,struct poller * poller)782 void console_poller_unregister(struct console *console, struct poller *poller)
783 {
784 	int i;
785 
786 	/* find the entry in our pollers array */
787 	for (i = 0; i < console->n_pollers; i++) {
788 		if (console->pollers[i] == poller) {
789 			break;
790 		}
791 	}
792 
793 	assert(i < console->n_pollers);
794 
795 	console->n_pollers--;
796 
797 	/*
798 	 * Remove the item from the pollers array...
799 	 *
800 	 * We're managing an array of pointers to aggregates, so don't warn about sizeof() on a
801 	 * pointer type.
802 	 */
803 	/* NOLINTBEGIN(bugprone-sizeof-expression) */
804 	memmove(&console->pollers[i], &console->pollers[i + 1],
805 		sizeof(*console->pollers) * (console->n_pollers - i));
806 
807 	if (console->n_pollers == 0) {
808 		free(console->pollers);
809 		console->pollers = NULL;
810 	} else {
811 		console->pollers = reallocarray(console->pollers,
812 						console->n_pollers,
813 						sizeof(*console->pollers));
814 	}
815 	/* NOLINTEND(bugprone-sizeof-expression) */
816 
817 	console_server_release_pollfd(console->server, poller->pollfd_index);
818 
819 	free(poller);
820 }
821 
console_poller_set_events(struct console * console,struct poller * poller,int events)822 void console_poller_set_events(struct console *console, struct poller *poller,
823 			       int events)
824 {
825 	console->server->pollfds[poller->pollfd_index].events =
826 		(short)(events & 0x7fff);
827 }
828 
console_poller_set_timeout(struct console * console,struct poller * poller,const struct timeval * tv)829 void console_poller_set_timeout(struct console *console __attribute__((unused)),
830 				struct poller *poller, const struct timeval *tv)
831 {
832 	struct timeval now;
833 	int rc;
834 
835 	rc = get_current_time(&now);
836 	if (rc) {
837 		return;
838 	}
839 
840 	timeradd(&now, tv, &poller->timeout);
841 }
842 
get_poll_timeout(struct console * console,struct timeval * cur_time)843 static long get_poll_timeout(struct console *console, struct timeval *cur_time)
844 {
845 	struct timeval *earliest;
846 	struct timeval interval;
847 	struct poller *poller;
848 	int i;
849 
850 	earliest = NULL;
851 
852 	for (i = 0; i < console->n_pollers; i++) {
853 		poller = console->pollers[i];
854 
855 		if (poller->timeout_fn && timerisset(&poller->timeout) &&
856 		    (!earliest ||
857 		     (earliest && timercmp(&poller->timeout, earliest, <)))) {
858 			// poller is buffering data and needs the poll
859 			// function to timeout.
860 			earliest = &poller->timeout;
861 		}
862 	}
863 
864 	if (earliest) {
865 		if (timercmp(earliest, cur_time, >)) {
866 			/* recalculate the timeout period, time period has
867 			 * not elapsed */
868 			timersub(earliest, cur_time, &interval);
869 			return ((interval.tv_sec * 1000) +
870 				(interval.tv_usec / 1000));
871 		} /* return from poll immediately */
872 		return 0;
873 
874 	} /* poll indefinitely */
875 	return -1;
876 }
877 
call_pollers(struct console * console,struct timeval * cur_time)878 static int call_pollers(struct console *console, struct timeval *cur_time)
879 {
880 	struct poller *poller;
881 	struct pollfd *pollfd;
882 	enum poller_ret prc;
883 	int i;
884 	int rc;
885 
886 	rc = 0;
887 
888 	/*
889 	 * Process poll events by iterating through the pollers and pollfds
890 	 * in-step, calling any pollers that we've found revents for.
891 	 */
892 	for (i = 0; i < console->n_pollers; i++) {
893 		poller = console->pollers[i];
894 		pollfd = &console->server->pollfds[poller->pollfd_index];
895 		if (pollfd->fd < 0) {
896 			// pollfd has already been released
897 			continue;
898 		}
899 
900 		prc = POLLER_OK;
901 
902 		/* process pending events... */
903 		if (pollfd->revents) {
904 			prc = poller->event_fn(poller->handler, pollfd->revents,
905 					       poller->data);
906 			if (prc == POLLER_EXIT) {
907 				rc = -1;
908 			} else if (prc == POLLER_REMOVE) {
909 				poller->remove = true;
910 			}
911 		}
912 
913 		if ((prc == POLLER_OK) && poller->timeout_fn &&
914 		    timerisset(&poller->timeout) &&
915 		    timercmp(&poller->timeout, cur_time, <=)) {
916 			/* One of the ringbuffer consumers is buffering the
917 			data stream. The amount of idle time the consumer
918 			desired has expired.  Process the buffered data for
919 			transmission. */
920 			timerclear(&poller->timeout);
921 			prc = poller->timeout_fn(poller->handler, poller->data);
922 			if (prc == POLLER_EXIT) {
923 				rc = -1;
924 			} else if (prc == POLLER_REMOVE) {
925 				poller->remove = true;
926 			}
927 		}
928 	}
929 
930 	/**
931 	 * Process deferred removals; restarting each time we unregister, as
932 	 * the array will have changed
933 	 */
934 	for (;;) {
935 		bool removed = false;
936 
937 		for (i = 0; i < console->n_pollers; i++) {
938 			poller = console->pollers[i];
939 			if (poller->remove) {
940 				console_poller_unregister(console, poller);
941 				removed = true;
942 				break;
943 			}
944 		}
945 		if (!removed) {
946 			break;
947 		}
948 	}
949 
950 	return rc;
951 }
952 
sighandler(int signal)953 static void sighandler(int signal)
954 {
955 	if (signal == SIGINT) {
956 		sigint = 1;
957 	}
958 }
959 
run_console_per_console(struct console * console,size_t buf_size,struct timeval * tv)960 static int run_console_per_console(struct console *console, size_t buf_size,
961 				   struct timeval *tv)
962 {
963 	int rc;
964 
965 	if (console->rb->size < buf_size) {
966 		fprintf(stderr, "Ringbuffer size should be greater than %zuB\n",
967 			buf_size);
968 		return -1;
969 	}
970 
971 	if (sigint) {
972 		warnx("Received interrupt, exiting\n");
973 		return -1;
974 	}
975 
976 	/* ... and then the pollers */
977 	rc = call_pollers(console, tv);
978 	if (rc) {
979 		return -1;
980 	}
981 
982 	return 0;
983 }
984 
run_console_iteration(struct console_server * server)985 static int run_console_iteration(struct console_server *server)
986 {
987 	struct timeval tv;
988 	uint8_t buf[4096];
989 	long timeout;
990 	ssize_t rc;
991 
992 	rc = get_current_time(&tv);
993 	if (rc) {
994 		warn("Failed to read current time");
995 		return -1;
996 	}
997 
998 	timeout = get_poll_timeout(server->active, &tv);
999 
1000 	rc = poll(server->pollfds, server->capacity_pollfds, (int)timeout);
1001 
1002 	if (sigint) {
1003 		warnx("Received interrupt, exiting\n");
1004 		return -1;
1005 	}
1006 
1007 	if (rc < 0) {
1008 		if (errno == EINTR) {
1009 			return 0;
1010 		}
1011 		warn("poll error");
1012 		return -1;
1013 	}
1014 
1015 	/* process internal fd first */
1016 	if (server->pollfds[server->tty_pollfd_index].revents) {
1017 		rc = read(server->tty.fd, buf, sizeof(buf));
1018 		if (rc <= 0) {
1019 			warn("Error reading from tty device");
1020 			return -1;
1021 		}
1022 
1023 		rc = ringbuffer_queue(server->active->rb, buf, rc);
1024 		if (rc) {
1025 			return -1;
1026 		}
1027 	}
1028 
1029 	// process dbus
1030 	struct pollfd *dbus_pollfd =
1031 		&(server->pollfds[server->dbus_pollfd_index]);
1032 	if (dbus_pollfd->revents) {
1033 		sd_bus_process(server->bus, NULL);
1034 	}
1035 
1036 	for (size_t i = 0; i < server->n_consoles; i++) {
1037 		struct console *console = server->consoles[i];
1038 
1039 		rc = run_console_per_console(console, sizeof(buf), &tv);
1040 		if (rc != 0) {
1041 			return -1;
1042 		}
1043 	}
1044 
1045 	return 0;
1046 }
1047 
run_server(struct console_server * server)1048 int run_server(struct console_server *server)
1049 {
1050 	sighandler_t sighandler_save;
1051 	ssize_t rc = 0;
1052 
1053 	if (server->n_consoles == 0) {
1054 		warnx("no console configured for this server");
1055 		return -1;
1056 	}
1057 
1058 	sighandler_save = signal(SIGINT, sighandler);
1059 	for (;;) {
1060 		rc = run_console_iteration(server);
1061 		if (rc) {
1062 			break;
1063 		}
1064 	}
1065 	signal(SIGINT, sighandler_save);
1066 
1067 	return rc ? -1 : 0;
1068 }
1069 
1070 static const struct option options[] = {
1071 	{ "config", required_argument, 0, 'c' },
1072 	{ "console-id", required_argument, 0, 'i' },
1073 	{ 0, 0, 0, 0 },
1074 };
1075 
console_init(struct console_server * server,struct config * config,const char * console_id)1076 static struct console *console_init(struct console_server *server,
1077 				    struct config *config,
1078 				    const char *console_id)
1079 {
1080 	size_t buffer_size = default_buffer_size;
1081 	const char *buffer_size_str = NULL;
1082 	int rc;
1083 
1084 	struct console *console = calloc(1, sizeof(struct console));
1085 	if (console == NULL) {
1086 		return NULL;
1087 	}
1088 
1089 	console->server = server;
1090 	console->console_id = console_id;
1091 
1092 	buffer_size_str =
1093 		config_get_section_value(config, console_id, "ringbuffer-size");
1094 
1095 	if (!buffer_size_str) {
1096 		buffer_size_str = config_get_value(config, "ringbuffer-size");
1097 	}
1098 
1099 	if (buffer_size_str) {
1100 		rc = config_parse_bytesize(buffer_size_str, &buffer_size);
1101 		if (rc) {
1102 			warn("Invalid ringbuffer-size. Default to %zukB",
1103 			     buffer_size >> 10);
1104 		}
1105 	}
1106 
1107 	console->rb = ringbuffer_init(buffer_size);
1108 	if (!console->rb) {
1109 		goto cleanup_console;
1110 	}
1111 
1112 	rc = console_mux_init(console, config);
1113 	if (rc) {
1114 		warnx("could not set mux gpios from config, exiting");
1115 		goto cleanup_rb;
1116 	}
1117 
1118 	if (set_socket_info(console, config, console_id)) {
1119 		warnx("set_socket_info failed");
1120 		goto cleanup_rb;
1121 	}
1122 
1123 	rc = dbus_init(console, config);
1124 	if (rc != 0) {
1125 		goto cleanup_rb;
1126 	}
1127 
1128 	handlers_init(console, config);
1129 
1130 	return console;
1131 
1132 cleanup_rb:
1133 	free(console->rb);
1134 cleanup_console:
1135 	free(console);
1136 
1137 	return NULL;
1138 }
1139 
console_fini(struct console * console)1140 static void console_fini(struct console *console)
1141 {
1142 	handlers_fini(console);
1143 	ringbuffer_fini(console->rb);
1144 	free(console->pollers);
1145 	free(console);
1146 }
1147 
1148 // 'opt_console_id' may be NULL
console_server_add_console(struct console_server * server,struct config * config,const char * opt_console_id)1149 static int console_server_add_console(struct console_server *server,
1150 				      struct config *config,
1151 				      const char *opt_console_id)
1152 {
1153 	const char *console_id;
1154 	struct console *console;
1155 
1156 	console_id = config_resolve_console_id(config, opt_console_id);
1157 
1158 	struct console **tmp = reallocarray(server->consoles,
1159 					    server->n_consoles + 1,
1160 					    sizeof(struct console *));
1161 	if (tmp == NULL) {
1162 		warnx("could not realloc server->consoles");
1163 		return -1;
1164 	}
1165 	server->consoles = tmp;
1166 
1167 	console = console_init(server, config, console_id);
1168 	if (console == NULL) {
1169 		warnx("console_init failed");
1170 		return -1;
1171 	}
1172 
1173 	server->consoles[server->n_consoles++] = console;
1174 
1175 	return 0;
1176 }
1177 
1178 // returns NULL on error
1179 static struct console *
console_server_add_consoles(struct console_server * server,const char * arg_console_id)1180 console_server_add_consoles(struct console_server *server,
1181 			    const char *arg_console_id)
1182 {
1183 	int rc;
1184 
1185 	const int nsections = config_count_sections(server->config);
1186 	if (nsections < 0) {
1187 		return NULL;
1188 	}
1189 
1190 	if (nsections == 0) {
1191 		const char *console_id = arg_console_id;
1192 
1193 		rc = console_server_add_console(server, server->config,
1194 						console_id);
1195 		if (rc != 0) {
1196 			return NULL;
1197 		}
1198 	}
1199 
1200 	for (int i = 0; i < nsections; i++) {
1201 		const char *console_id =
1202 			config_get_section_name(server->config, i);
1203 
1204 		if (console_id == NULL) {
1205 			warnx("no console id provided\n");
1206 			return NULL;
1207 		}
1208 
1209 		rc = console_server_add_console(server, server->config,
1210 						console_id);
1211 		if (rc != 0) {
1212 			return NULL;
1213 		}
1214 	}
1215 
1216 	const char *initially_active =
1217 		config_get_value(server->config, "active-console");
1218 	if (!initially_active) {
1219 		return server->consoles[0];
1220 	}
1221 
1222 	printf("setting console-id '%s' as the initially active console\n",
1223 	       initially_active);
1224 
1225 	for (size_t i = 0; i < server->n_consoles; i++) {
1226 		struct console *console = server->consoles[i];
1227 
1228 		if (strcmp(console->console_id, initially_active) == 0) {
1229 			return console;
1230 		}
1231 	}
1232 
1233 	warnx("'active-console' '%s' not found among console ids\n",
1234 	      initially_active);
1235 
1236 	return NULL;
1237 }
1238 
console_server_init(struct console_server * server,const char * config_filename,const char * config_tty_kname,const char * console_id)1239 int console_server_init(struct console_server *server,
1240 			const char *config_filename,
1241 			const char *config_tty_kname, const char *console_id)
1242 {
1243 	int rc;
1244 	memset(server, 0, sizeof(struct console_server));
1245 
1246 	server->tty_pollfd_index = -1;
1247 
1248 	server->config = config_init(config_filename);
1249 	if (server->config == NULL) {
1250 		return -1;
1251 	}
1252 
1253 	rc = console_server_mux_init(server);
1254 	if (rc != 0) {
1255 		return -1;
1256 	}
1257 
1258 	uart_routing_init(server->config);
1259 
1260 	rc = tty_init(server, server->config, config_tty_kname);
1261 	if (rc != 0) {
1262 		warnx("error during tty_init, exiting.\n");
1263 		return -1;
1264 	}
1265 
1266 	rc = dbus_server_init(server);
1267 	if (rc != 0) {
1268 		warnx("error during dbus init for console server");
1269 		return -1;
1270 	}
1271 
1272 	struct console *initial_active =
1273 		console_server_add_consoles(server, console_id);
1274 	if (initial_active == NULL) {
1275 		return -1;
1276 	}
1277 
1278 	rc = console_mux_activate(initial_active);
1279 	if (rc != 0) {
1280 		return -1;
1281 	}
1282 
1283 	return 0;
1284 }
1285 
console_server_fini(struct console_server * server)1286 void console_server_fini(struct console_server *server)
1287 {
1288 	for (size_t i = 0; i < server->n_consoles; i++) {
1289 		console_fini(server->consoles[i]);
1290 	}
1291 
1292 	free(server->consoles);
1293 	dbus_server_fini(server);
1294 	tty_fini(server);
1295 	free(server->pollfds);
1296 	console_server_mux_fini(server);
1297 	config_fini(server->config);
1298 }
1299 
main(int argc,char ** argv)1300 int main(int argc, char **argv)
1301 {
1302 	const char *config_filename = NULL;
1303 	const char *config_tty_kname = NULL;
1304 	const char *console_id = NULL;
1305 	struct console_server server = { 0 };
1306 	int rc = 0;
1307 
1308 	for (;;) {
1309 		int c;
1310 		int idx;
1311 
1312 		c = getopt_long(argc, argv, "c:i:", options, &idx);
1313 		if (c == -1) {
1314 			break;
1315 		}
1316 
1317 		switch (c) {
1318 		case 'c':
1319 			config_filename = optarg;
1320 			break;
1321 		case 'i':
1322 			console_id = optarg;
1323 			break;
1324 		case 'h':
1325 		case '?':
1326 			usage(argv[0]);
1327 			return EXIT_SUCCESS;
1328 		}
1329 	}
1330 
1331 	if (optind < argc) {
1332 		config_tty_kname = argv[optind];
1333 	} else {
1334 		errx(EXIT_FAILURE, "no tty device path has been provided\n");
1335 	}
1336 
1337 	rc = console_server_init(&server, config_filename, config_tty_kname,
1338 				 console_id);
1339 
1340 	if (rc == 0) {
1341 		rc = run_server(&server);
1342 	}
1343 
1344 	console_server_fini(&server);
1345 
1346 	return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1347 }
1348