xref: /haiku/src/bin/consoled/consoled.cpp (revision 97901ec593ec4dd50ac115c1c35a6d72f6e489a5)
1 /*
2  * Copyright 2004-2010, Haiku. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Copyright 2002, Travis Geiselbrecht. All rights reserved.
6  * Distributed under the terms of the NewOS License.
7  */
8 
9 
10 #include <ctype.h>
11 #include <dirent.h>
12 #include <errno.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <termios.h>
17 #include <unistd.h>
18 
19 #include <FindDirectory.h>
20 #include <image.h>
21 #include <InterfaceDefs.h>
22 #include <OS.h>
23 
24 #include <keyboard_mouse_driver.h>
25 #include <Keymap.h>
26 
27 
28 struct console;
29 
30 struct keyboard {
31 	struct keyboard*	next;
32 	int					device;
33 	int					target;
34 	thread_id			thread;
35 };
36 
37 struct console {
38 	int					console_fd;
39 	thread_id			console_writer;
40 
41 	struct keyboard*	keyboards;
42 
43 	int					tty_master_fd;
44 	int					tty_slave_fd;
45 	int					tty_num;
46 };
47 
48 
49 struct console gConsole;
50 
51 
52 void
53 error(const char* message, ...)
54 {
55 	char buffer[2048];
56 
57 	va_list args;
58 	va_start(args, message);
59 
60 	vsnprintf(buffer, sizeof(buffer), message, args);
61 
62 	va_end(args);
63 
64 	// put it out on stderr as well as to serial/syslog
65 	fputs(buffer, stderr);
66 	debug_printf("%s", buffer);
67 }
68 
69 
70 void
71 update_leds(int fd, uint32 modifiers)
72 {
73 	char lockIO[3] = {0, 0, 0};
74 
75 	if ((modifiers & B_NUM_LOCK) != 0)
76 		lockIO[0] = 1;
77 	if ((modifiers & B_CAPS_LOCK) != 0)
78 		lockIO[1] = 1;
79 	if ((modifiers & B_SCROLL_LOCK) != 0)
80 		lockIO[2] = 1;
81 
82 	ioctl(fd, KB_SET_LEDS, &lockIO);
83 }
84 
85 
86 static int32
87 keyboard_reader(void* arg)
88 {
89 	struct keyboard* keyboard = (struct keyboard*)arg;
90 	uint8 activeDeadKey = 0;
91 	uint32 modifiers = 0;
92 
93 	BKeymap keymap;
94 	// Load current keymap from disk (we can't talk to the input server)
95 	// TODO: find a better way (we shouldn't have to care about the on-disk
96 	// location)
97 	char path[PATH_MAX];
98 	status_t status = find_directory(B_USER_SETTINGS_DIRECTORY, -1, false,
99 		path, sizeof(path));
100 	if (status == B_OK) {
101 		strlcat(path, "/Key_map", sizeof(path));
102 		status = keymap.SetTo(path);
103 	}
104 	if (status != B_OK)
105 		keymap.SetToDefault();
106 
107 	for (;;) {
108 		raw_key_info rawKeyInfo;
109 		if (ioctl(keyboard->device, KB_READ, &rawKeyInfo) != 0)
110 			break;
111 
112 		uint32 keycode = rawKeyInfo.keycode;
113 		bool isKeyDown = rawKeyInfo.is_keydown;
114 
115 		if (keycode == 0)
116 			continue;
117 
118 		uint32 changedModifiers = keymap.Modifier(keycode);
119 		bool isLock = (changedModifiers
120 			& (B_CAPS_LOCK | B_NUM_LOCK | B_SCROLL_LOCK)) != 0;
121 		if (changedModifiers != 0 && (!isLock || isKeyDown)) {
122 			uint32 oldModifiers = modifiers;
123 
124 			if ((isKeyDown && !isLock)
125 				|| (isKeyDown && !(modifiers & changedModifiers)))
126 				modifiers |= changedModifiers;
127 			else {
128 				modifiers &= ~changedModifiers;
129 
130 				// ensure that we don't clear a combined B_*_KEY when still
131 				// one of the individual B_{LEFT|RIGHT}_*_KEY is pressed
132 				if (modifiers & (B_LEFT_SHIFT_KEY | B_RIGHT_SHIFT_KEY))
133 					modifiers |= B_SHIFT_KEY;
134 				if (modifiers & (B_LEFT_COMMAND_KEY | B_RIGHT_COMMAND_KEY))
135 					modifiers |= B_COMMAND_KEY;
136 				if (modifiers & (B_LEFT_CONTROL_KEY | B_RIGHT_CONTROL_KEY))
137 					modifiers |= B_CONTROL_KEY;
138 				if (modifiers & (B_LEFT_OPTION_KEY | B_RIGHT_OPTION_KEY))
139 					modifiers |= B_OPTION_KEY;
140 			}
141 
142 			if (modifiers != oldModifiers) {
143 				if (isLock)
144 					update_leds(keyboard->device, modifiers);
145 			}
146 		}
147 
148 		uint8 newDeadKey = 0;
149 		if (activeDeadKey == 0 || !isKeyDown)
150 			newDeadKey = keymap.ActiveDeadKey(keycode, modifiers);
151 
152 		char* string = NULL;
153 		int32 numBytes = 0;
154 		if (newDeadKey == 0 && isKeyDown) {
155 			keymap.GetChars(keycode, modifiers, activeDeadKey, &string,
156 				&numBytes);
157 			if (numBytes > 0)
158 				write(keyboard->target, string, numBytes);
159 
160 			delete[] string;
161 		}
162 
163 		if (newDeadKey == 0) {
164 			if (isKeyDown && !modifiers && activeDeadKey != 0) {
165 				// a dead key was completed
166 				activeDeadKey = 0;
167 			}
168 		} else if (isKeyDown) {
169 			// start of a dead key
170 			char* string = NULL;
171 			int32 numBytes = 0;
172 			keymap.GetChars(keycode, modifiers, 0, &string, &numBytes);
173 
174 			activeDeadKey = newDeadKey;
175 		}
176 	}
177 
178 	return 0;
179 }
180 
181 
182 static int32
183 console_writer(void* arg)
184 {
185 	struct console* con = (struct console*)arg;
186 
187 	for (;;) {
188 		char buffer[1024];
189 		ssize_t length = read(con->tty_master_fd, buffer, sizeof(buffer));
190 		if (length < 0)
191 			break;
192 
193 		write(con->console_fd, buffer, length);
194 	}
195 
196 	return 0;
197 }
198 
199 
200 static void
201 stop_keyboards(struct console* con)
202 {
203 	// close devices
204 
205 	for (struct keyboard* keyboard = con->keyboards; keyboard != NULL;
206 			keyboard = keyboard->next) {
207 		close(keyboard->device);
208 	}
209 
210 	// wait for the threads
211 
212 	for (struct keyboard* keyboard = con->keyboards; keyboard != NULL;) {
213 		struct keyboard* next = keyboard->next;
214 		wait_for_thread(keyboard->thread, NULL);
215 
216 		delete keyboard;
217 		keyboard = next;
218 	}
219 
220 	con->keyboards = NULL;
221 }
222 
223 
224 /*!	Opens the all keyboard drivers it finds starting from the given
225 	location \a start that support the debugger extension.
226 */
227 static struct keyboard*
228 open_keyboards(int target, const char* start, struct keyboard* previous)
229 {
230 	DIR* dir = opendir(start);
231 	if (dir == NULL)
232 		return NULL;
233 
234 	struct keyboard* keyboard = previous;
235 
236 	while (true) {
237 		dirent* entry = readdir(dir);
238 		if (entry == NULL)
239 			break;
240 		if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
241 			continue;
242 
243 		char path[PATH_MAX];
244 		strlcpy(path, start, sizeof(path));
245 		strlcat(path, "/", sizeof(path));
246 		strlcat(path, entry->d_name, sizeof(path));
247 
248 		struct stat stat;
249 		if (::stat(path, &stat) != 0)
250 			continue;
251 
252 		if (S_ISDIR(stat.st_mode)) {
253 			keyboard = open_keyboards(target, path, keyboard);
254 			continue;
255 		}
256 
257 		// Try to open it as a device
258 		int fd = open(path, O_RDONLY);
259 		if (fd >= 0) {
260 			// Turn on debugger mode
261 			if (ioctl(fd, KB_SET_DEBUG_READER, NULL, 0) == 0) {
262 				keyboard = new ::keyboard();
263 				keyboard->device = fd;
264 				keyboard->target = target;
265 				keyboard->thread = spawn_thread(&keyboard_reader, path,
266 					B_URGENT_DISPLAY_PRIORITY, keyboard);
267 				if (keyboard->thread < 0) {
268 					close(fd);
269 					return NULL;
270 				}
271 
272 				if (previous != NULL)
273 					previous->next = keyboard;
274 
275 				resume_thread(keyboard->thread);
276 			} else
277 				close(fd);
278 		}
279 	}
280 
281 	closedir(dir);
282 	return keyboard;
283 }
284 
285 
286 static int
287 start_console(struct console* con)
288 {
289 	memset(con, 0, sizeof(struct console));
290 	con->console_fd = -1;
291 	con->tty_master_fd = -1;
292 	con->tty_slave_fd = -1;
293 	con->console_writer = -1;
294 
295 	con->console_fd = open("/dev/console", O_WRONLY);
296 	if (con->console_fd < 0)
297 		return -2;
298 
299 	DIR* dir = opendir("/dev/pt");
300 	if (dir != NULL) {
301 		struct dirent* entry;
302 		char name[64];
303 
304 		while ((entry = readdir(dir)) != NULL) {
305 			if (entry->d_name[0] == '.')
306 				continue;
307 
308 			snprintf(name, sizeof(name), "/dev/pt/%s", entry->d_name);
309 
310 			con->tty_master_fd = open(name, O_RDWR);
311 			if (con->tty_master_fd >= 0) {
312 				snprintf(name, sizeof(name), "/dev/tt/%s", entry->d_name);
313 
314 				con->tty_slave_fd = open(name, O_RDWR);
315 				if (con->tty_slave_fd < 0) {
316 					error("Could not open tty %s: %s!\n", name,
317 						strerror(errno));
318 					close(con->tty_master_fd);
319 				} else {
320 					// set default mode
321 					struct termios termios;
322 					struct winsize size;
323 
324 					if (tcgetattr(con->tty_slave_fd, &termios) == 0) {
325 						termios.c_iflag = ICRNL;
326 						termios.c_oflag = OPOST | ONLCR;
327 						termios.c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHONL;
328 
329 						tcsetattr(con->tty_slave_fd, TCSANOW, &termios);
330 					}
331 
332 					if (ioctl(con->console_fd, TIOCGWINSZ, &size,
333 							sizeof(struct winsize)) == 0) {
334 						// we got the window size from the console
335 						ioctl(con->tty_slave_fd, TIOCSWINSZ, &size,
336 							sizeof(struct winsize));
337 					}
338 				}
339 				break;
340 			}
341 		}
342 
343 		setenv("TTY", name, true);
344 	}
345 
346 	if (con->tty_master_fd < 0 || con->tty_slave_fd < 0)
347 		return -3;
348 
349 	con->keyboards
350 		= open_keyboards(con->tty_master_fd, "/dev/input/keyboard", NULL);
351 	if (con->keyboards == NULL)
352 		return -4;
353 
354 	con->console_writer = spawn_thread(&console_writer, "console writer",
355 		B_URGENT_DISPLAY_PRIORITY, con);
356 	if (con->console_writer < 0)
357 		return -5;
358 
359 	resume_thread(con->console_writer);
360 	setenv("TERM", "xterm", true);
361 
362 	return 0;
363 }
364 
365 
366 static void
367 stop_console(struct console* con)
368 {
369 	// close TTY FDs; this will also unblock the threads
370 	close(con->tty_master_fd);
371 	close(con->tty_slave_fd);
372 
373 	// close console and keyboards
374 	close(con->console_fd);
375 	wait_for_thread(con->console_writer, NULL);
376 
377 	stop_keyboards(con);
378 }
379 
380 
381 static pid_t
382 start_process(int argc, const char** argv, struct console* con)
383 {
384 	int savedInput = dup(0);
385 	int savedOutput = dup(1);
386 	int savedError = dup(2);
387 
388 	dup2(con->tty_slave_fd, 0);
389 	dup2(con->tty_slave_fd, 1);
390 	dup2(con->tty_slave_fd, 2);
391 
392 	pid_t pid = load_image(argc, argv, (const char**)environ);
393 	resume_thread(pid);
394 	setpgid(pid, 0);
395 	tcsetpgrp(con->tty_slave_fd, pid);
396 
397 	dup2(savedInput, 0);
398 	dup2(savedOutput, 1);
399 	dup2(savedError, 2);
400 	close(savedInput);
401 	close(savedOutput);
402 	close(savedError);
403 
404 	return pid;
405 }
406 
407 
408 int
409 main(int argc, char** argv)
410 {
411 	// we're a session leader
412 	setsid();
413 
414 	int err = start_console(&gConsole);
415 	if (err < 0) {
416 		error("consoled: error %d starting console.\n", err);
417 		return err;
418 	}
419 
420 	// move our stdin and stdout to the console
421 	dup2(gConsole.tty_slave_fd, 0);
422 	dup2(gConsole.tty_slave_fd, 1);
423 	dup2(gConsole.tty_slave_fd, 2);
424 
425 	if (argc > 1) {
426 		// a command was given: we run it only once
427 
428 		// get the command argument vector
429 		int commandArgc = argc - 1;
430 		const char** commandArgv = new const char*[commandArgc + 1];
431 		for (int i = 0; i < commandArgc; i++)
432 			commandArgv[i] = argv[i + 1];
433 
434 		commandArgv[commandArgc] = NULL;
435 
436 		// start the process
437 		pid_t process = start_process(commandArgc, commandArgv, &gConsole);
438 
439 		status_t returnCode;
440 		wait_for_thread(process, &returnCode);
441 	} else {
442 		// no command given: start a shell in an endless loop
443 		for (;;) {
444 			pid_t shellProcess;
445 			status_t returnCode;
446 			const char* shellArgv[] = { "/bin/sh", "--login", NULL };
447 
448 			shellProcess = start_process(2, shellArgv, &gConsole);
449 
450 			wait_for_thread(shellProcess, &returnCode);
451 
452 			puts("Restart shell");
453 		}
454 	}
455 
456 	stop_console(&gConsole);
457 
458 	return 0;
459 }
460 
461