blob: 52ae3d21516cb426cd57953068bf8f936277c878 [file] [log] [blame]
Eric Andersenaad1a882001-03-16 22:47:14 +00001/* vi: set sw=4 ts=4: */
2/*
3 * Utility routines.
4 *
Glenn L McGrath005f83a2003-09-01 08:53:32 +00005 * Copyright (C) many different people. If you wrote this, please
6 * acknowledge your work.
Eric Andersenaad1a882001-03-16 22:47:14 +00007 *
Bernhard Reutner-Fischerb1629b12006-05-19 19:29:19 +00008 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
Eric Andersenaad1a882001-03-16 22:47:14 +00009 */
10
11#include <stdio.h>
12#include <errno.h>
13#include <fcntl.h>
14#include <unistd.h>
15#include <sys/ioctl.h>
16#include "libbb.h"
17
18
19
Eric Andersenc7bda1c2004-03-15 08:29:22 +000020/* From <linux/kd.h> */
Rob Landleybc68cd12006-03-10 19:22:06 +000021enum { KDGKBTYPE = 0x4B33 }; /* get keyboard type */
Eric Andersenaad1a882001-03-16 22:47:14 +000022
Eric Andersenaad1a882001-03-16 22:47:14 +000023
Glenn L McGrath005f83a2003-09-01 08:53:32 +000024static int open_a_console(const char *fnam)
Eric Andersenaad1a882001-03-16 22:47:14 +000025{
26 int fd;
27
Glenn L McGrath005f83a2003-09-01 08:53:32 +000028 /* try read-write */
Eric Andersenaad1a882001-03-16 22:47:14 +000029 fd = open(fnam, O_RDWR);
30
31 /* if failed, try read-only */
32 if (fd < 0 && errno == EACCES)
33 fd = open(fnam, O_RDONLY);
34
35 /* if failed, try write-only */
36 if (fd < 0 && errno == EACCES)
37 fd = open(fnam, O_WRONLY);
38
Eric Andersenaad1a882001-03-16 22:47:14 +000039 return fd;
40}
41
42/*
43 * Get an fd for use with kbd/console ioctls.
44 * We try several things because opening /dev/console will fail
45 * if someone else used X (which does a chown on /dev/console).
Eric Andersenaad1a882001-03-16 22:47:14 +000046 */
47
Eric Andersenc38678d2002-09-16 06:22:25 +000048int get_console_fd(void)
Eric Andersenaad1a882001-03-16 22:47:14 +000049{
50 int fd;
51
Glenn L McGrath005f83a2003-09-01 08:53:32 +000052 static const char * const choise_console_names[] = {
53 CONSOLE_DEV, CURRENT_VC, CURRENT_TTY
54 };
Eric Andersenaad1a882001-03-16 22:47:14 +000055
Glenn L McGrath005f83a2003-09-01 08:53:32 +000056 for (fd = 2; fd >= 0; fd--) {
57 int fd4name;
58 int choise_fd;
59 char arg;
Eric Andersenaad1a882001-03-16 22:47:14 +000060
Glenn L McGrath005f83a2003-09-01 08:53:32 +000061 fd4name = open_a_console(choise_console_names[fd]);
62 chk_std:
63 choise_fd = fd4name >= 0 ? fd4name : fd;
Eric Andersenaad1a882001-03-16 22:47:14 +000064
Glenn L McGrath005f83a2003-09-01 08:53:32 +000065 arg = 0;
66 if (ioctl(choise_fd, KDGKBTYPE, &arg) == 0)
67 return choise_fd;
68 if(fd4name >= 0) {
69 close(fd4name);
70 fd4name = -1;
71 goto chk_std;
72 }
73 }
Eric Andersenaad1a882001-03-16 22:47:14 +000074
Denis Vlasenkoa9595882006-09-29 21:30:43 +000075 bb_error_msg("cannot get file descriptor referring to console");
Glenn L McGrath005f83a2003-09-01 08:53:32 +000076 return fd; /* total failure */
Eric Andersenaad1a882001-03-16 22:47:14 +000077}