1 /* vi: set sw=4 ts=4: */
3 * Based on agetty - another getty program for Linux. By W. Z. Venema 1989
4 * Ported to Linux by Peter Orbaek <poe@daimi.aau.dk>
5 * This program is freely distributable.
7 * option added by Eric Rasmussen <ear@usfirst.org> - 12/28/95
9 * 1999-02-22 Arkadiusz Mickiewicz <misiek@misiek.eu.org>
10 * - Added Native Language Support
12 * 1999-05-05 Thorsten Kranzkowski <dl8bcu@gmx.net>
13 * - Enabled hardware flow control before displaying /etc/issue
15 * 2011-01 Venys Vlasenko
16 * - Removed parity detection code. It can't work reliably:
17 * if all chars received have bit 7 cleared and odd (or even) parity,
18 * it is impossible to determine whether other side is 8-bit,no-parity
19 * or 7-bit,odd(even)-parity. It also interferes with non-ASCII usernames.
20 * - From now on, we assume that parity is correctly set.
22 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
32 # undef ENABLE_FEATURE_UTMP
33 # undef ENABLE_FEATURE_WTMP
34 # define ENABLE_FEATURE_UTMP 0
35 # define ENABLE_FEATURE_WTMP 0
39 /* The following is used for understandable diagnostics */
42 # define DEBUGTERM "/dev/ttyp0"
43 # define debug(...) do { fprintf(dbf, __VA_ARGS__); fflush(dbf); } while (0)
45 # define debug(...) ((void)0)
50 * Things you may want to modify.
52 * You may disagree with the default line-editing etc. characters defined
53 * below. Note, however, that DEL cannot be used for interrupt generation
54 * and for line editing at the same time.
57 #define _PATH_LOGIN "/bin/login"
59 /* Displayed before the login prompt.
60 * If ISSUE is not defined, getty will never display the contents of the
61 * /etc/issue file. You will not want to spit out large "issue" files at the
64 #define ISSUE "/etc/issue"
66 /* Some shorthands for control characters */
67 #define CTL(x) ((x) ^ 0100) /* Assumes ASCII dialect */
68 #define BS CTL('H') /* back space */
69 #define DEL CTL('?') /* delete */
71 /* Defaults for line-editing etc. characters; you may want to change this */
72 #define DEF_INTR CTL('C') /* default interrupt character */
73 #define DEF_QUIT CTL('\\') /* default quit char */
74 #define DEF_KILL CTL('U') /* default kill char */
75 #define DEF_EOF CTL('D') /* default EOF char */
77 #define DEF_SWITCH 0 /* default switch char (none) */
80 * When multiple baud rates are specified on the command line,
81 * the first one we will try is the first one specified.
83 #define MAX_SPEED 10 /* max. nr. of baud rates */
86 unsigned timeout; /* time-out period */
87 const char *login; /* login program */
89 const char *tty; /* name of tty */
90 const char *initstring; /* modem init string */
91 const char *issue; /* alternative issue file */
92 int numspeed; /* number of baud rates to try */
93 int speeds[MAX_SPEED]; /* baud rates to be tried */
94 unsigned char eol; /* end-of-line char seen (CR or NL) */
95 struct termios termios; /* terminal mode bits */
99 #define G (*ptr_to_globals)
100 #define INIT_G() do { \
101 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
104 //usage:#define getty_trivial_usage
105 //usage: "[OPTIONS] BAUD_RATE[,BAUD_RATE]... TTY [TERMTYPE]"
106 //usage:#define getty_full_usage "\n\n"
107 //usage: "Open a tty, prompt for a login name, then invoke /bin/login\n"
108 //usage: "\nOptions:"
109 //usage: "\n -h Enable hardware RTS/CTS flow control"
110 //usage: "\n -L Set CLOCAL (ignore Carrier Detect state)"
111 //usage: "\n -m Get baud rate from modem's CONNECT status message"
112 //usage: "\n -n Don't prompt for login name"
113 //usage: "\n -w Wait for CR or LF before sending /etc/issue"
114 //usage: "\n -i Don't display /etc/issue"
115 //usage: "\n -f ISSUE_FILE Display ISSUE_FILE instead of /etc/issue"
116 //usage: "\n -l LOGIN Invoke LOGIN instead of /bin/login"
117 //usage: "\n -t SEC Terminate after SEC if no login name is read"
118 //usage: "\n -I INITSTR Send INITSTR before anything else"
119 //usage: "\n -H HOST Log HOST into the utmp file as the hostname"
121 //usage: "\nBAUD_RATE of 0 leaves it unchanged"
123 static const char opt_string[] ALIGN1 = "I:LH:f:hil:mt:wn";
124 #define F_INITSTRING (1 << 0) /* -I */
125 #define F_LOCAL (1 << 1) /* -L */
126 #define F_FAKEHOST (1 << 2) /* -H */
127 #define F_CUSTISSUE (1 << 3) /* -f */
128 #define F_RTSCTS (1 << 4) /* -h */
129 #define F_NOISSUE (1 << 5) /* -i */
130 #define F_LOGIN (1 << 6) /* -l */
131 #define F_PARSE (1 << 7) /* -m */
132 #define F_TIMEOUT (1 << 8) /* -t */
133 #define F_WAITCRLF (1 << 9) /* -w */
134 #define F_NOPROMPT (1 << 10) /* -n */
137 /* convert speed string to speed code; return <= 0 on failure */
138 static int bcode(const char *s)
140 int value = bb_strtou(s, NULL, 10); /* yes, int is intended! */
141 if (value < 0) /* bad terminating char, overflow, etc */
143 return tty_value_to_baud(value);
146 /* parse alternate baud rates */
147 static void parse_speeds(char *arg)
151 /* NB: at least one iteration is always done */
152 debug("entered parse_speeds\n");
153 while ((cp = strsep(&arg, ",")) != NULL) {
154 G.speeds[G.numspeed] = bcode(cp);
155 if (G.speeds[G.numspeed] < 0)
156 bb_error_msg_and_die("bad speed: %s", cp);
157 /* note: arg "0" turns into speed B0 */
159 if (G.numspeed > MAX_SPEED)
160 bb_error_msg_and_die("too many alternate speeds");
162 debug("exiting parse_speeds\n");
165 /* parse command-line arguments */
166 static void parse_args(char **argv)
171 opt_complementary = "-2:t+"; /* at least 2 args; -t N */
172 flags = getopt32(argv, opt_string,
173 &G.initstring, &G.fakehost, &G.issue,
176 if (flags & F_INITSTRING) {
177 G.initstring = xstrdup(G.initstring);
178 /* decode \ddd octal codes into chars */
179 strcpy_and_process_escape_sequences((char*)G.initstring, G.initstring);
182 debug("after getopt\n");
184 /* We loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
185 G.tty = argv[0]; /* tty name */
186 ts = argv[1]; /* baud rate(s) */
187 if (isdigit(argv[0][0])) {
188 /* A number first, assume it's a speed (BSD style) */
189 G.tty = ts; /* tty name is in argv[1] */
190 ts = argv[0]; /* baud rate(s) */
193 applet_name = xasprintf("getty: %s", G.tty);
196 xsetenv("TERM", argv[2]);
198 debug("exiting parse_args\n");
201 /* set up tty as standard input, output, error */
202 static void open_tty(void)
204 /* Set up new standard input, unless we are given an already opened port */
205 if (NOT_LONE_DASH(G.tty)) {
207 G.tty = xasprintf("/dev/%s", G.tty); /* will leak it */
209 /* Open the tty as standard input */
212 xopen(G.tty, O_RDWR | O_NONBLOCK); /* uses fd 0 */
214 /* Set proper protections and ownership */
215 fchown(0, 0, 0); /* 0:0 */
216 fchmod(0, 0620); /* crw--w---- */
219 * Standard input should already be connected to an open port. Make
220 * sure it is open for read/write.
222 if ((fcntl(0, F_GETFL) & (O_RDWR|O_RDONLY|O_WRONLY)) != O_RDWR)
223 bb_error_msg_and_die("stdin is not open for read/write");
227 /* We manipulate termios this way:
228 * - first, we read existing termios settings
229 * - termios_init modifies some parts and sets it
230 * - auto_baud and/or BREAK processing can set different speed and set termios
231 * - termios_final again modifies some parts and sets termios before
234 static void termios_init(int speed)
236 /* Flush input and output queues, important for modems!
237 * Users report losing previously queued output chars, and I hesitate
238 * to use tcdrain here instead of tcflush - I imagine it can block.
239 * Using small sleep instead.
241 usleep(100*1000); /* 0.1 sec */
242 tcflush(STDIN_FILENO, TCIOFLUSH);
244 /* Set speed if it wasn't specified as "0" on command line */
246 cfsetspeed(&G.termios, speed);
249 * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
250 * Special characters are set after we have read the login name; all
251 * reads will be done in raw mode anyway. Errors will be dealt with
254 /* 8 bits; hangup (drop DTR) on last close; enable receive */
255 G.termios.c_cflag = CS8 | HUPCL | CREAD;
256 if (option_mask32 & F_LOCAL) {
257 /* ignore Carrier Detect pin:
258 * opens don't block when CD is low,
259 * losing CD doesn't hang up processes whose ctty is this tty
261 G.termios.c_cflag |= CLOCAL;
264 if (option_mask32 & F_RTSCTS)
265 G.termios.c_cflag |= CRTSCTS; /* flow control using RTS/CTS pins */
267 /* Other bits in c_cflag:
268 * CSTOPB 2 stop bits (1 otherwise)
269 * PARENB Enable parity bit
270 * PARODD Use odd parity (else even)
271 * LOBLK Block job control output (??)
273 G.termios.c_iflag = 0;
274 G.termios.c_lflag = 0;
275 /* non-raw output; add CR to each NL */
276 G.termios.c_oflag = OPOST | ONLCR;
278 G.termios.c_cc[VMIN] = 1; /* block reads if < 1 char is available */
279 G.termios.c_cc[VTIME] = 0; /* no timeout (reads block forever) */
281 G.termios.c_line = 0;
284 tcsetattr_stdin_TCSANOW(&G.termios);
286 debug("term_io 2\n");
289 static void termios_final(void)
291 /* software flow control on output (stop sending if XOFF is recvd);
292 * and on input (send XOFF when buffer is full)
294 G.termios.c_iflag |= IXON | IXOFF;
296 G.termios.c_iflag |= ICRNL; /* map CR on input to NL */
298 /* Other bits in c_iflag:
299 * IXANY Any recvd char enables output (any char is also a XON)
300 * INPCK Enable parity check
301 * IGNPAR Ignore parity errors (drop bad bytes)
302 * PARMRK Mark parity errors with 0xff, 0x00 prefix
303 * (else bad byte is received as 0x00)
304 * ISTRIP Strip parity bit
305 * IGNBRK Ignore break condition
306 * BRKINT Send SIGINT on break - maybe set this?
310 * IUCLC Map uppercase to lowercase
311 * IMAXBEL Echo BEL on input line too long
312 * IUTF8 [Appears to affect tty's idea of char widths,
313 * observed to improve backspacing through Unicode chars]
316 /* line buffered input (NL or EOL or EOF chars end a line);
317 * recognize INT/QUIT/SUSP chars;
319 * echo BS-SP-BS on erase character;
320 * echo kill char specially, not as ^c (ECHOKE controls how exactly);
321 * erase all input via BS-SP-BS on kill char (else go to next line)
323 G.termios.c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
324 /* Other bits in c_lflag:
325 * XCASE Map uppercase to \lowercase [tried, doesn't work]
326 * ECHONL Echo NL even if ECHO is not set
327 * NOFLSH Don't flush input buffer after interrupt or quit chars
328 * IEXTEN Enable extended functions (??)
329 * [glibc says it enables c_cc[LNEXT] "enter literal char"
330 * and c_cc[VDISCARD] "toggle discard buffered output" chars]
331 * ECHOCTL Echo ctrl chars as ^c (else don't echo) - maybe set this?
332 * ECHOPRT On erase, echo erased chars
333 * [qwe<BS><BS><BS> input looks like "qwe\ewq/" on screen]
334 * FLUSHO Output being flushed (c_cc[VDISCARD] is in effect)
335 * PENDIN Retype pending input at next read or input char
336 * (c_cc[VREPRINT] is being processes)
337 * TOSTOP Send SIGTTOU for background output
338 * (why "stty sane" unsets this bit?)
341 G.termios.c_cc[VINTR] = DEF_INTR;
342 G.termios.c_cc[VQUIT] = DEF_QUIT;
343 G.termios.c_cc[VEOF] = DEF_EOF;
344 G.termios.c_cc[VEOL] = DEF_EOL;
346 G.termios.c_cc[VSWTC] = DEF_SWITCH;
349 G.termios.c_cc[VSWTCH] = DEF_SWITCH;
351 G.termios.c_cc[VKILL] = DEF_KILL;
352 /* Other control chars:
354 * VERASE, VWERASE - (word) erase. we may set VERASE in get_logname
355 * VREPRINT - reprint current input buffer
356 * VLNEXT, VDISCARD, VSTATUS
357 * VSUSP, VDSUSP - send (delayed) SIGTSTP
358 * VSTART, VSTOP - chars used for IXON/IXOFF
361 if (tcsetattr_stdin_TCSANOW(&G.termios) < 0)
362 bb_perror_msg_and_die("tcsetattr");
365 /* extract baud rate from modem status message */
366 static void auto_baud(void)
371 * This works only if the modem produces its status code AFTER raising
372 * the DCD line, and if the computer is fast enough to set the proper
373 * baud rate before the message has gone by. We expect a message of the
376 * <junk><number><junk>
378 * The number is interpreted as the baud rate of the incoming call. If the
379 * modem does not tell us the baud rate within one second, we will keep
380 * using the current baud rate. It is advisable to enable BREAK
381 * processing (comma-separated list of baud rates) if the processing of
382 * modem status messages is enabled.
385 G.termios.c_cc[VMIN] = 0; /* don't block reads (min read is 0 chars) */
386 tcsetattr_stdin_TCSANOW(&G.termios);
389 * Wait for a while, then read everything the modem has said so far and
390 * try to extract the speed of the dial-in call.
393 nread = safe_read(STDIN_FILENO, G.line_buf, sizeof(G.line_buf) - 1);
397 G.line_buf[nread] = '\0';
398 for (bp = G.line_buf; bp < G.line_buf + nread; bp++) {
402 cfsetspeed(&G.termios, speed);
408 /* Restore terminal settings. Errors will be dealt with later on */
409 G.termios.c_cc[VMIN] = 1; /* restore to value set by termios_init */
410 tcsetattr_stdin_TCSANOW(&G.termios);
413 /* get user name, establish parity, speed, erase, kill, eol;
414 * return NULL on BREAK, logname on success
416 static char *get_logname(void)
421 /* Flush pending input (esp. after parsing or switching the baud rate) */
422 usleep(100*1000); /* 0.1 sec */
423 tcflush(STDIN_FILENO, TCIFLUSH);
425 /* Prompt for and read a login name */
426 G.line_buf[0] = '\0';
427 while (!G.line_buf[0]) {
428 /* Write issue file and prompt */
430 if (!(option_mask32 & F_NOISSUE))
431 print_login_issue(G.issue, G.tty);
433 print_login_prompt();
435 /* Read name, watch for break, parity, erase, kill, end-of-line */
439 /* Do not report trivial EINTR/EIO errors */
440 errno = EINTR; /* make read of 0 bytes be silent too */
441 if (read(STDIN_FILENO, &c, 1) < 1) {
442 if (errno == EINTR || errno == EIO)
444 bb_perror_msg_and_die(bb_msg_read_error);
447 /* BREAK. If we have speeds to try,
448 * return NULL (will switch speeds and return here) */
449 if (c == '\0' && G.numspeed > 1)
452 /* Do erase, kill and end-of-line processing */
461 G.termios.c_cc[VERASE] = c;
462 if (bp > G.line_buf) {
463 full_write(STDOUT_FILENO, "\010 \010", 3);
468 while (bp > G.line_buf) {
469 full_write(STDOUT_FILENO, "\010 \010", 3);
476 if ((unsigned char)c < ' ') {
477 /* ignore garbage characters */
478 } else if ((int)(bp - G.line_buf) < sizeof(G.line_buf) - 1) {
479 /* echo and store the character */
480 full_write(STDOUT_FILENO, &c, 1);
485 } /* end of get char loop */
487 } /* while logname is empty */
492 int getty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
493 int getty_main(int argc UNUSED_PARAM, char **argv)
500 G.login = _PATH_LOGIN; /* default login program */
502 G.issue = ISSUE; /* default issue file */
506 /* Parse command-line arguments */
509 logmode = LOGMODE_NONE;
511 /* Create new session, lose controlling tty, if any */
512 /* docs/ctty.htm says:
513 * "This is allowed only when the current process
514 * is not a process group leader" - is this a problem? */
516 /* close stdio, and stray descriptors, just in case */
517 n = xopen(bb_dev_null, O_RDWR);
518 /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
524 /* Logging. We want special flavor of error_msg_and_die */
527 /* most likely will internally use fd #3 in CLOEXEC mode: */
528 openlog(applet_name, LOG_PID, LOG_AUTH);
529 logmode = LOGMODE_BOTH;
532 dbf = xfopen_for_write(DEBUGTERM);
533 for (n = 1; argv[n]; n++) {
539 /* Open the tty as standard input, if it is not "-" */
540 /* If it's not "-" and not taken yet, it will become our ctty */
541 debug("calling open_tty\n");
549 * The following ioctl will fail if stdin is not a tty, but also when
550 * there is noise on the modem control lines. In the latter case, the
551 * common course of action is (1) fix your cables (2) give the modem more
552 * time to properly reset after hanging up. SunOS users can achieve (2)
553 * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
554 * 5 seconds seems to be a good value.
556 if (tcgetattr(STDIN_FILENO, &G.termios) < 0)
557 bb_perror_msg_and_die("tcgetattr");
561 // FIXME: do we need this? Otherwise "-" case seems to be broken...
562 // /* Forcibly make fd 0 our controlling tty, even if another session
563 // * has it as a ctty. (Another session loses ctty). */
564 // ioctl(STDIN_FILENO, TIOCSCTTY, (void*)1);
565 /* Make ourself a foreground process group within our session */
566 tcsetpgrp(STDIN_FILENO, pid);
569 /* Update the utmp file. This tty is ours now! */
570 update_utmp(pid, LOGIN_PROCESS, G.tty, "LOGIN", G.fakehost);
572 /* Initialize the termios settings (raw mode, eight-bit, blocking i/o) */
573 debug("calling termios_init\n");
574 termios_init(G.speeds[0]);
576 /* Write the modem init string and DON'T flush the buffers */
577 if (option_mask32 & F_INITSTRING) {
578 debug("writing init string\n");
579 full_write1_str(G.initstring);
582 /* Optionally detect the baud rate from the modem status message */
583 debug("before autobaud\n");
584 if (option_mask32 & F_PARSE)
587 /* Set the optional timer */
588 alarm(G.timeout); /* if 0, alarm is not set */
589 //BUG: death by signal won't restore termios
591 /* Optionally wait for CR or LF before writing /etc/issue */
592 if (option_mask32 & F_WAITCRLF) {
594 debug("waiting for cr-lf\n");
595 while (safe_read(STDIN_FILENO, &ch, 1) == 1) {
596 debug("read %x\n", (unsigned char)ch);
597 if (ch == '\n' || ch == '\r')
603 if (!(option_mask32 & F_NOPROMPT)) {
604 /* NB: termios_init already set line speed
609 /* Read the login name */
610 debug("reading login name\n");
611 logname = get_logname();
614 /* We are here only if G.numspeed > 1 */
615 baud_index = (baud_index + 1) % G.numspeed;
616 cfsetspeed(&G.termios, G.speeds[baud_index]);
617 tcsetattr_stdin_TCSANOW(&G.termios);
624 /* Finalize the termios settings */
627 /* Now the newline character should be properly written */
628 full_write(STDOUT_FILENO, "\n", 1);
630 /* Let the login program take care of password validation */
631 /* We use PATH because we trust that root doesn't set "bad" PATH,
632 * and getty is not suid-root applet */
633 /* With -n, logname == NULL, and login will ask for username instead */
634 BB_EXECLP(G.login, G.login, "--", logname, NULL);
635 bb_error_msg_and_die("can't execute '%s'", G.login);