de5cf93fe85c75e54dd76db0e11d01a5346cd57c
[oweals/busybox.git] / console-tools / openvt.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  *  openvt.c - open a vt to run a command.
4  *
5  *  busyboxed by Quy Tonthat <quy@signal3.com>
6  *  hacked by Tito <farmatito@tiscali.it>
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9  */
10
11 //usage:#define openvt_trivial_usage
12 //usage:       "[-c N] [-sw] [PROG ARGS]"
13 //usage:#define openvt_full_usage "\n\n"
14 //usage:       "Start PROG on a new virtual terminal\n"
15 //usage:     "\nOptions:"
16 //usage:     "\n        -c N    Use specified VT"
17 //usage:     "\n        -s      Switch to the VT"
18 /* //usage:     "\n     -l      Run PROG as login shell (by prepending '-')" */
19 //usage:     "\n        -w      Wait for PROG to exit"
20 //usage:
21 //usage:#define openvt_example_usage
22 //usage:       "openvt 2 /bin/ash\n"
23
24 #include <linux/vt.h>
25 #include "libbb.h"
26
27 /* "Standard" openvt's man page (we do not support all of this):
28
29 openvt [-c NUM] [-fsulv] [--] [command [args]]
30
31 Find the first available VT, and run command on it. Stdio is directed
32 to that VT. If no command is specified then $SHELL is used.
33
34 -c NUM
35     Use the given VT number, not the first free one.
36 -f
37     Force opening a VT: don't try to check if VT is already in use.
38 -s
39     Switch to the new VT when starting the command.
40     The VT of the new command will be made the new current VT.
41 -u
42     Figure out the owner of the current VT, and run login as that user.
43     Suitable to be called by init. Shouldn't be used with -c or -l.
44 -l
45     Make the command a login shell: a "-" is prepended to the argv[0]
46     when command is executed.
47 -v
48     Verbose.
49 -w
50     Wait for command to complete. If -w and -s are used together,
51     switch back to the controlling terminal when the command completes.
52
53 bbox:
54 -u: not implemented
55 -f: always in effect
56 -l: not implemented, ignored
57 -v: ignored
58 -ws: does NOT switch back
59 */
60
61 /* Helper: does this fd understand VT_xxx? */
62 static int not_vt_fd(int fd)
63 {
64         struct vt_stat vtstat;
65         return ioctl(fd, VT_GETSTATE, &vtstat); /* !0: error, it's not VT fd */
66 }
67
68 /* Helper: get a fd suitable for VT_xxx */
69 static int get_vt_fd(void)
70 {
71         int fd;
72
73         /* Do we, by chance, already have it? */
74         for (fd = 0; fd < 3; fd++)
75                 if (!not_vt_fd(fd))
76                         return fd;
77         fd = open(DEV_CONSOLE, O_RDONLY | O_NONBLOCK);
78         if (fd >= 0 && !not_vt_fd(fd))
79                 return fd;
80         bb_error_msg_and_die("can't find open VT");
81 }
82
83 static int find_free_vtno(void)
84 {
85         int vtno;
86         int fd = get_vt_fd();
87
88         errno = 0;
89         /*xfunc_error_retval = 3; - do we need compat? */
90         if (ioctl(fd, VT_OPENQRY, &vtno) != 0 || vtno <= 0)
91                 bb_perror_msg_and_die("can't find open VT");
92 // Not really needed, grep for DAEMON_ONLY_SANITIZE
93 //      if (fd > 2)
94 //              close(fd);
95         return vtno;
96 }
97
98 /* vfork scares gcc, it generates bigger code.
99  * Keep it away from main program.
100  * TODO: move to libbb; or adapt existing libbb's spawn().
101  */
102 static NOINLINE void vfork_child(char **argv)
103 {
104         if (vfork() == 0) {
105                 /* CHILD */
106                 /* Try to make this VT our controlling tty */
107                 setsid(); /* lose old ctty */
108                 ioctl(STDIN_FILENO, TIOCSCTTY, 0 /* 0: don't forcibly steal */);
109                 //bb_error_msg("our sid %d", getsid(0));
110                 //bb_error_msg("our pgrp %d", getpgrp());
111                 //bb_error_msg("VT's sid %d", tcgetsid(0));
112                 //bb_error_msg("VT's pgrp %d", tcgetpgrp(0));
113                 BB_EXECVP_or_die(argv);
114         }
115 }
116
117 int openvt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
118 int openvt_main(int argc UNUSED_PARAM, char **argv)
119 {
120         char vtname[sizeof(VC_FORMAT) + sizeof(int)*3];
121         struct vt_stat vtstat;
122         char *str_c;
123         int vtno;
124         int flags;
125         enum {
126                 OPT_c = (1 << 0),
127                 OPT_w = (1 << 1),
128                 OPT_s = (1 << 2),
129                 OPT_l = (1 << 3),
130                 OPT_f = (1 << 4),
131                 OPT_v = (1 << 5),
132         };
133
134         /* "+" - stop on first non-option */
135         flags = getopt32(argv, "+c:wslfv", &str_c);
136         argv += optind;
137
138         if (flags & OPT_c) {
139                 /* Check for illegal vt number: < 1 or > 63 */
140                 vtno = xatou_range(str_c, 1, 63);
141         } else {
142                 vtno = find_free_vtno();
143         }
144
145         /* Grab new VT */
146         sprintf(vtname, VC_FORMAT, vtno);
147         /* (Try to) clean up stray open fds above fd 2 */
148         bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS | DAEMON_ONLY_SANITIZE, NULL);
149         close(STDIN_FILENO);
150         /*setsid(); - BAD IDEA: after we exit, child is SIGHUPed... */
151         xopen(vtname, O_RDWR);
152         xioctl(STDIN_FILENO, VT_GETSTATE, &vtstat);
153
154         if (flags & OPT_s) {
155                 console_make_active(STDIN_FILENO, vtno);
156         }
157
158         if (!argv[0]) {
159                 argv--;
160                 argv[0] = (char *) get_shell_name();
161                 /*argv[1] = NULL; - already is */
162         }
163
164         xdup2(STDIN_FILENO, STDOUT_FILENO);
165         xdup2(STDIN_FILENO, STDERR_FILENO);
166
167 #ifdef BLOAT
168         {
169         /* Handle -l (login shell) option */
170         const char *prog = argv[0];
171         if (flags & OPT_l)
172                 argv[0] = xasprintf("-%s", argv[0]);
173         }
174 #endif
175
176         vfork_child(argv);
177         if (flags & OPT_w) {
178                 /* We have only one child, wait for it */
179                 safe_waitpid(-1, NULL, 0); /* loops on EINTR */
180                 if (flags & OPT_s) {
181                         console_make_active(STDIN_FILENO, vtstat.v_active);
182                         // Compat: even with -c N (try to) disallocate:
183                         // # /usr/app/kbd-1.12/bin/openvt -f -c 9 -ws sleep 5
184                         // openvt: could not deallocate console 9
185                         xioctl(STDIN_FILENO, VT_DISALLOCATE, (void*)(ptrdiff_t)vtno);
186                 }
187         }
188         return EXIT_SUCCESS;
189 }