1 /* vi: set sw=4 ts=4: */
2 /* Based on agetty - another getty program for Linux. By W. Z. Venema 1989
3 * Ported to Linux by Peter Orbaek <poe@daimi.aau.dk>
4 * This program is freely distributable.
6 * option added by Eric Rasmussen <ear@usfirst.org> - 12/28/95
8 * 1999-02-22 Arkadiusz Mickiewicz <misiek@misiek.eu.org>
9 * - added Native Language Support
11 * 1999-05-05 Thorsten Kranzkowski <dl8bcu@gmx.net>
12 * - enable hardware flow control before displaying /etc/issue
14 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 #if ENABLE_FEATURE_UTMP
21 # include <utmp.h> /* LOGIN_PROCESS */
29 * Some heuristics to find out what environment we are in: if it is not
30 * System V, assume it is SunOS 4.
32 #ifdef LOGIN_PROCESS /* defined in System V utmp.h */
33 # include <sys/utsname.h>
34 #else /* if !sysV style, wtmp/utmp code is off */
35 # undef ENABLE_FEATURE_UTMP
36 # undef ENABLE_FEATURE_WTMP
37 # define ENABLE_FEATURE_UTMP 0
38 # define ENABLE_FEATURE_WTMP 0
39 #endif /* LOGIN_PROCESS */
42 /* The following is used for understandable diagnostics. */
45 # define DEBUGTERM "/dev/ttyp0"
46 # define debug(...) do { fprintf(dbf, __VA_ARGS__); fflush(dbf); } while (0)
48 # define debug(...) ((void)0)
53 * Things you may want to modify.
55 * You may disagree with the default line-editing etc. characters defined
56 * below. Note, however, that DEL cannot be used for interrupt generation
57 * and for line editing at the same time.
60 /* I doubt there are systems which still... */
61 /* ...have only uppercase: */
63 /* ...use # and @ for backspace and line erase: */
64 #undef ANCIENT_BS_KILL_CHARS
65 /* It actually makes sense (tries to guess parity by looking at 7th bit)
66 * but it's broken, and interferes with non-ASCII login names
67 * (yes, I did receive complains from real users):
69 #undef BROKEN_PARITY_DETECTION_CODE
72 #define _PATH_LOGIN "/bin/login"
74 /* Displayed before the login prompt.
75 * If ISSUE is not defined, getty will never display the contents of the
76 * /etc/issue file. You will not want to spit out large "issue" files at the
79 #define ISSUE "/etc/issue"
81 /* Some shorthands for control characters. */
82 #define CTL(x) ((x) ^ 0100) /* Assumes ASCII dialect */
83 #define CR CTL('M') /* carriage return */
84 #define NL CTL('J') /* line feed */
85 #define BS CTL('H') /* back space */
86 #define DEL CTL('?') /* delete */
88 /* Defaults for line-editing etc. characters; you may want to change this. */
89 #define DEF_ERASE DEL /* default erase character */
90 #define DEF_INTR CTL('C') /* default interrupt character */
91 #define DEF_QUIT CTL('\\') /* default quit char */
92 #define DEF_KILL CTL('U') /* default kill char */
93 #define DEF_EOF CTL('D') /* default EOF char */
95 #define DEF_SWITCH 0 /* default switch char */
98 * When multiple baud rates are specified on the command line, the first one
99 * we will try is the first one specified.
101 #define MAX_SPEED 10 /* max. nr. of baud rates */
103 /* Storage for command-line options. */
105 unsigned timeout; /* time-out period */
106 const char *login; /* login program */
107 const char *tty; /* name of tty */
108 const char *initstring; /* modem init string */
109 const char *issue; /* alternative issue file */
110 int numspeed; /* number of baud rates to try */
111 int speeds[MAX_SPEED]; /* baud rates to be tried */
114 /* Storage for things detected while the login name was read. */
116 unsigned char erase; /* erase character */
117 #ifdef ANCIENT_BS_KILL_CHARS
118 unsigned char kill; /* kill character */
120 unsigned char eol; /* end-of-line character */
121 #ifdef BROKEN_PARITY_DETECTION_CODE
122 unsigned char parity; /* what parity did we see */
123 /* (parity & 1): saw odd parity char with 7th bit set */
124 /* (parity & 2): saw even parity char with 7th bit set */
125 /* parity == 0: probably 7-bit, space parity? */
126 /* parity == 1: probably 7-bit, odd parity? */
127 /* parity == 2: probably 7-bit, even parity? */
128 /* parity == 3: definitely 8 bit, no parity! */
129 /* Hmm... with any value of parity "8 bit, no parity" is possible */
131 #ifdef HANDLE_ALLCAPS
132 unsigned char capslock; /* upper case without lower case */
136 /* Initial values for the above. */
137 static const struct chardata init_chardata = {
138 DEF_ERASE, /* default erase character */
139 #ifdef ANCIENT_BS_KILL_CHARS
140 DEF_KILL, /* default kill character */
142 13, /* default eol char */
143 #ifdef BROKEN_PARITY_DETECTION_CODE
144 0, /* space parity */
146 #ifdef HANDLE_ALLCAPS
151 #define line_buf bb_common_bufsiz1
153 //usage:#define getty_trivial_usage
154 //usage: "[OPTIONS] BAUD_RATE[,BAUD_RATE]... TTY [TERMTYPE]"
155 //usage:#define getty_full_usage "\n\n"
156 //usage: "Open a tty, prompt for a login name, then invoke /bin/login\n"
157 //usage: "\nOptions:"
158 //usage: "\n -h Enable hardware (RTS/CTS) flow control"
159 //usage: "\n -i Don't display /etc/issue"
160 //usage: "\n -L Local line, set CLOCAL on it"
161 //usage: "\n -m Get baud rate from modem's CONNECT status message"
162 //usage: "\n -w Wait for CR or LF before sending /etc/issue"
163 //usage: "\n -n Don't prompt for a login name"
164 //usage: "\n -f ISSUE_FILE Display ISSUE_FILE instead of /etc/issue"
165 //usage: "\n -l LOGIN Invoke LOGIN instead of /bin/login"
166 //usage: "\n -t SEC Terminate after SEC if no username is read"
167 //usage: "\n -I INITSTR Send INITSTR before anything else"
168 //usage: "\n -H HOST Log HOST into the utmp file as the hostname"
170 //usage: "\nBAUD_RATE of 0 leaves it unchanged"
172 static const char opt_string[] ALIGN1 = "I:LH:f:hil:mt:wn";
173 #define F_INITSTRING (1 << 0) /* -I */
174 #define F_LOCAL (1 << 1) /* -L */
175 #define F_FAKEHOST (1 << 2) /* -H */
176 #define F_CUSTISSUE (1 << 3) /* -f */
177 #define F_RTSCTS (1 << 4) /* -h */
178 #define F_NOISSUE (1 << 5) /* -i */
179 #define F_LOGIN (1 << 6) /* -l */
180 #define F_PARSE (1 << 7) /* -m */
181 #define F_TIMEOUT (1 << 8) /* -t */
182 #define F_WAITCRLF (1 << 9) /* -w */
183 #define F_NOPROMPT (1 << 10) /* -n */
186 /* convert speed string to speed code; return <= 0 on failure */
187 static int bcode(const char *s)
189 int value = bb_strtou(s, NULL, 10); /* yes, int is intended! */
190 if (value < 0) /* bad terminating char, overflow, etc */
192 return tty_value_to_baud(value);
195 /* parse alternate baud rates */
196 static void parse_speeds(struct options *op, char *arg)
200 /* NB: at least one iteration is always done */
201 debug("entered parse_speeds\n");
202 while ((cp = strsep(&arg, ",")) != NULL) {
203 op->speeds[op->numspeed] = bcode(cp);
204 if (op->speeds[op->numspeed] < 0)
205 bb_error_msg_and_die("bad speed: %s", cp);
206 /* note: arg "0" turns into speed B0 */
208 if (op->numspeed > MAX_SPEED)
209 bb_error_msg_and_die("too many alternate speeds");
211 debug("exiting parse_speeds\n");
214 /* parse command-line arguments */
215 static void parse_args(char **argv, struct options *op, char **fakehost_p)
220 opt_complementary = "-2:t+"; /* at least 2 args; -t N */
221 flags = getopt32(argv, opt_string,
222 &(op->initstring), fakehost_p, &(op->issue),
223 &(op->login), &op->timeout);
224 if (flags & F_INITSTRING) {
225 op->initstring = xstrdup(op->initstring);
226 /* decode \ddd octal codes into chars */
227 strcpy_and_process_escape_sequences((char*)op->initstring, op->initstring);
230 debug("after getopt\n");
232 /* we loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
233 op->tty = argv[0]; /* tty name */
234 ts = argv[1]; /* baud rate(s) */
235 if (isdigit(argv[0][0])) {
236 /* a number first, assume it's a speed (BSD style) */
237 op->tty = ts; /* tty name is in argv[1] */
238 ts = argv[0]; /* baud rate(s) */
240 parse_speeds(op, ts);
241 applet_name = xasprintf("getty: %s", op->tty);
244 xsetenv("TERM", argv[2]);
246 debug("exiting parse_args\n");
249 /* set up tty as standard input, output, error */
250 static void open_tty(const char *tty)
252 /* Set up new standard input, unless we are given an already opened port. */
253 if (NOT_LONE_DASH(tty)) {
255 tty = xasprintf("/dev/%s", tty); /* will leak it */
257 /* Open the tty as standard input. */
260 /*fd =*/ xopen(tty, O_RDWR | O_NONBLOCK); /* uses fd 0 */
262 /* Set proper protections and ownership. */
263 fchown(0, 0, 0); /* 0:0 */
264 fchmod(0, 0620); /* crw--w---- */
267 * Standard input should already be connected to an open port. Make
268 * sure it is open for read/write.
270 if ((fcntl(0, F_GETFL) & (O_RDWR|O_RDONLY|O_WRONLY)) != O_RDWR)
271 bb_error_msg_and_die("stdin is not open for read/write");
275 /* initialize termios settings */
276 static void termios_init(struct termios *tp, int speed)
278 /* Flush input and output queues, important for modems!
279 * Users report losing previously queued output chars, and I hesitate
280 * to use tcdrain here instead of tcflush - I imagine it can block.
281 * Using small sleep instead.
283 usleep(100*1000); /* 0.1 sec */
284 tcflush(STDIN_FILENO, TCIOFLUSH);
286 /* Set speed if it wasn't specified as "0" on command line. */
288 cfsetspeed(tp, speed);
291 * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
292 * Special characters are set after we have read the login name; all
293 * reads will be done in raw mode anyway. Errors will be dealt with
296 tp->c_cflag = CS8 | HUPCL | CREAD;
297 if (option_mask32 & F_LOCAL)
298 tp->c_cflag |= CLOCAL;
301 tp->c_oflag = OPOST | ONLCR;
308 /* Optionally enable hardware flow control */
310 if (option_mask32 & F_RTSCTS)
311 tp->c_cflag |= CRTSCTS;
314 tcsetattr_stdin_TCSANOW(tp);
316 debug("term_io 2\n");
319 /* extract baud rate from modem status message */
320 static void auto_baud(char *buf, unsigned size_buf, struct termios *tp)
329 * This works only if the modem produces its status code AFTER raising
330 * the DCD line, and if the computer is fast enough to set the proper
331 * baud rate before the message has gone by. We expect a message of the
334 * <junk><number><junk>
336 * The number is interpreted as the baud rate of the incoming call. If the
337 * modem does not tell us the baud rate within one second, we will keep
338 * using the current baud rate. It is advisable to enable BREAK
339 * processing (comma-separated list of baud rates) if the processing of
340 * modem status messages is enabled.
344 * Use 7-bit characters, don't block if input queue is empty. Errors will
345 * be dealt with later on.
348 tp->c_iflag |= ISTRIP; /* enable 8th-bit stripping */
349 vmin = tp->c_cc[VMIN];
350 tp->c_cc[VMIN] = 0; /* don't block if queue empty */
351 tcsetattr_stdin_TCSANOW(tp);
354 * Wait for a while, then read everything the modem has said so far and
355 * try to extract the speed of the dial-in call.
358 nread = safe_read(STDIN_FILENO, buf, size_buf - 1);
361 for (bp = buf; bp < buf + nread; bp++) {
365 cfsetspeed(tp, speed);
371 /* Restore terminal settings. Errors will be dealt with later on. */
373 tp->c_cc[VMIN] = vmin;
374 tcsetattr_stdin_TCSANOW(tp);
377 #ifdef HANDLE_ALLCAPS
378 /* does string contain upper case without lower case? */
379 static int all_is_upcase(const char *s)
388 /* get user name, establish parity, speed, erase, kill, eol;
389 * return NULL on BREAK, logname on success */
390 static char *get_logname(char *logname, unsigned size_logname,
391 struct options *op, struct chardata *cp)
394 char c; /* input character, full eight bits */
395 char ascval; /* low 7 bits of input character */
396 #ifdef BROKEN_PARITY_DETECTION_CODE
397 static const char erase[][3] = {/* backspace-space-backspace */
398 "\010\040\010", /* space parity */
399 "\010\040\010", /* odd parity */
400 "\210\240\210", /* even parity */
401 "\010\040\010", /* 8 bit no parity */
405 /* NB: *cp is pre-initialized with init_chardata */
407 /* Flush pending input (esp. after parsing or switching the baud rate). */
408 usleep(100*1000); /* 0.1 sec */
409 tcflush(STDIN_FILENO, TCIOFLUSH);
411 /* Prompt for and read a login name. */
413 while (!logname[0]) {
414 /* Write issue file and prompt. */
416 if (!(option_mask32 & F_NOISSUE))
417 print_login_issue(op->issue, op->tty);
419 print_login_prompt();
421 /* Read name, watch for break, parity, erase, kill, end-of-line. */
425 /* Do not report trivial EINTR/EIO errors. */
426 errno = EINTR; /* make read of 0 bytes be silent too */
427 if (read(STDIN_FILENO, &c, 1) < 1) {
428 if (errno == EINTR || errno == EIO)
430 bb_perror_msg_and_die(bb_msg_read_error);
433 /* BREAK. If we have speeds to try,
434 * return NULL (will switch speeds and return here) */
435 if (c == '\0' && op->numspeed > 1)
438 #ifdef BROKEN_PARITY_DETECTION_CODE
439 /* Do parity bit handling. */
440 if (!(option_mask32 & F_LOCAL) && (c & 0x80)) { /* "parity" bit on? */
443 while (mask & 0x7f) {
445 bits++; /* count "1" bits */
448 /* ... |= 2 - even, 1 - odd */
449 cp->parity |= 2 - (bits & 1);
456 /* Do erase, kill and end-of-line processing. */
460 *bp = '\0'; /* terminate logname */
461 cp->eol = ascval; /* set end-of-line char */
465 #ifdef ANCIENT_BS_KILL_CHARS
468 cp->erase = ascval; /* set erase character */
470 #ifdef BROKEN_PARITY_DETECTION_CODE
471 full_write(STDOUT_FILENO, erase[cp->parity], 3);
473 full_write(STDOUT_FILENO, "\010 \010", 3);
479 #ifdef ANCIENT_BS_KILL_CHARS
481 cp->kill = ascval; /* set kill character */
483 while (bp > logname) {
484 #ifdef BROKEN_PARITY_DETECTION_CODE
485 full_write(STDOUT_FILENO, erase[cp->parity], 3);
487 full_write(STDOUT_FILENO, "\010 \010", 3);
496 /* ignore garbage characters */
497 } else if ((int)(bp - logname) < size_logname - 1) {
498 full_write(STDOUT_FILENO, &c, 1); /* echo the character */
499 *bp++ = ascval; /* and store it */
503 } /* end of get char loop */
505 } /* while logname is empty */
507 #ifdef HANDLE_ALLCAPS
508 /* Handle names with upper case and no lower case. */
509 cp->capslock = all_is_upcase(logname);
511 for (bp = logname; *bp; bp++)
513 *bp = tolower(*bp); /* map name to lower case */
519 /* set the final tty mode bits */
520 static void termios_final(struct termios *tp, struct chardata *cp)
522 /* General terminal-independent stuff. */
523 tp->c_iflag |= IXON | IXOFF; /* 2-way flow control */
524 tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
525 /* no longer| ECHOCTL | ECHOPRT */
526 tp->c_oflag |= OPOST;
527 /* tp->c_cflag = 0; */
528 tp->c_cc[VINTR] = DEF_INTR; /* default interrupt */
529 tp->c_cc[VQUIT] = DEF_QUIT; /* default quit */
530 tp->c_cc[VEOF] = DEF_EOF; /* default EOF character */
531 tp->c_cc[VEOL] = DEF_EOL;
533 tp->c_cc[VSWTC] = DEF_SWITCH; /* default switch character */
536 /* Account for special characters seen in input. */
538 tp->c_iflag |= ICRNL; /* map CR in input to NL */
539 tp->c_oflag |= ONLCR; /* map NL in output to CR-NL */
541 tp->c_cc[VERASE] = cp->erase; /* set erase character */
542 #ifdef ANCIENT_BS_KILL_CHARS
543 tp->c_cc[VKILL] = cp->kill; /* set kill character */
545 tp->c_cc[VKILL] = DEF_KILL; /* set kill character */
548 #ifdef BROKEN_PARITY_DETECTION_CODE
549 /* Account for the presence or absence of parity bits in input. */
550 switch (cp->parity) {
551 case 0: /* space (always 0) parity */
552 // I bet most people go here - they use only 7-bit chars in usernames....
554 case 1: /* odd parity */
555 tp->c_cflag |= PARODD;
557 case 2: /* even parity */
558 tp->c_cflag |= PARENB;
559 tp->c_iflag |= INPCK | ISTRIP;
561 case (1 | 2): /* no parity bit */
562 tp->c_cflag &= ~CSIZE;
564 // FIXME: wtf? case 3: we saw both even and odd 8-bit bytes -
565 // it's probably some umlauts etc, but definitely NOT 7-bit!!!
566 // Entire parity detection madness here just begs for deletion...
571 #ifdef HANDLE_ALLCAPS
572 /* Account for upper case without lower case. */
574 tp->c_iflag |= IUCLC;
575 tp->c_lflag |= XCASE;
576 tp->c_oflag |= OLCUC;
581 /* Optionally enable hardware flow control */
582 if (option_mask32 & F_RTSCTS)
583 tp->c_cflag |= CRTSCTS;
586 /* Finally, make the new settings effective */
587 if (tcsetattr_stdin_TCSANOW(tp) < 0)
588 bb_perror_msg_and_die("tcsetattr");
591 int getty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
592 int getty_main(int argc UNUSED_PARAM, char **argv)
596 char *fakehost = NULL; /* Fake hostname for ut_host */
597 char *logname; /* login name, given to /bin/login */
598 /* Merging these into "struct local" may _seem_ to reduce
599 * parameter passing, but today's gcc will inline
600 * statics which are called once anyway, so don't do that */
601 struct chardata chardata; /* set by get_logname() */
602 struct termios termios; /* terminal mode bits */
603 struct options options;
605 chardata = init_chardata;
607 memset(&options, 0, sizeof(options));
608 options.login = _PATH_LOGIN; /* default login program */
609 options.tty = "tty1"; /* default tty line */
610 options.initstring = ""; /* modem init string */
612 options.issue = ISSUE; /* default issue file */
615 /* Parse command-line arguments. */
616 parse_args(argv, &options, &fakehost);
618 logmode = LOGMODE_NONE;
620 /* Create new session, lose controlling tty, if any */
621 /* docs/ctty.htm says:
622 * "This is allowed only when the current process
623 * is not a process group leader" - is this a problem? */
625 /* close stdio, and stray descriptors, just in case */
626 n = xopen(bb_dev_null, O_RDWR);
627 /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
633 /* Logging. We want special flavor of error_msg_and_die */
636 /* most likely will internally use fd #3 in CLOEXEC mode: */
637 openlog(applet_name, LOG_PID, LOG_AUTH);
638 logmode = LOGMODE_BOTH;
641 dbf = xfopen_for_write(DEBUGTERM);
642 for (n = 1; argv[n]; n++) {
648 /* Open the tty as standard input, if it is not "-" */
649 /* If it's not "-" and not taken yet, it will become our ctty */
650 debug("calling open_tty\n");
651 open_tty(options.tty);
658 * The following ioctl will fail if stdin is not a tty, but also when
659 * there is noise on the modem control lines. In the latter case, the
660 * common course of action is (1) fix your cables (2) give the modem more
661 * time to properly reset after hanging up. SunOS users can achieve (2)
662 * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
663 * 5 seconds seems to be a good value.
665 if (tcgetattr(STDIN_FILENO, &termios) < 0)
666 bb_perror_msg_and_die("tcgetattr");
670 // FIXME: do we need this? Otherwise "-" case seems to be broken...
671 // /* Forcibly make fd 0 our controlling tty, even if another session
672 // * has it as a ctty. (Another session loses ctty). */
673 // ioctl(STDIN_FILENO, TIOCSCTTY, (void*)1);
674 /* Make ourself a foreground process group within our session */
675 tcsetpgrp(STDIN_FILENO, pid);
678 /* Update the utmp file. This tty is ours now! */
679 update_utmp(pid, LOGIN_PROCESS, options.tty, "LOGIN", fakehost);
681 /* Initialize the termios settings (raw mode, eight-bit, blocking i/o). */
682 debug("calling termios_init\n");
683 termios_init(&termios, options.speeds[0]);
685 /* Write the modem init string and DON'T flush the buffers */
686 if (option_mask32 & F_INITSTRING) {
687 debug("writing init string\n");
688 full_write1_str(options.initstring);
691 /* Optionally detect the baud rate from the modem status message */
692 debug("before autobaud\n");
693 if (option_mask32 & F_PARSE)
694 auto_baud(line_buf, sizeof(line_buf), &termios);
696 /* Set the optional timer */
697 alarm(options.timeout); /* if 0, alarm is not set */
699 /* Optionally wait for CR or LF before writing /etc/issue */
700 if (option_mask32 & F_WAITCRLF) {
703 debug("waiting for cr-lf\n");
704 while (safe_read(STDIN_FILENO, &ch, 1) == 1) {
705 debug("read %x\n", (unsigned char)ch);
706 ch &= 0x7f; /* strip "parity bit" */
707 if (ch == '\n' || ch == '\r')
713 if (!(option_mask32 & F_NOPROMPT)) {
714 /* NB: termios_init already set line speed
715 * to options.speeds[0] */
719 /* Read the login name. */
720 debug("reading login name\n");
721 logname = get_logname(line_buf, sizeof(line_buf),
722 &options, &chardata);
725 /* we are here only if options.numspeed > 1 */
726 baud_index = (baud_index + 1) % options.numspeed;
727 cfsetspeed(&termios, options.speeds[baud_index]);
728 tcsetattr_stdin_TCSANOW(&termios);
735 /* Finalize the termios settings. */
736 termios_final(&termios, &chardata);
738 /* Now the newline character should be properly written. */
739 full_write(STDOUT_FILENO, "\n", 1);
741 /* Let the login program take care of password validation. */
742 /* We use PATH because we trust that root doesn't set "bad" PATH,
743 * and getty is not suid-root applet. */
744 /* With -n, logname == NULL, and login will ask for username instead */
745 BB_EXECLP(options.login, options.login, "--", logname, NULL);
746 bb_error_msg_and_die("can't execute '%s'", options.login);