1 /* vi: set sw=4 ts=4: */
2 /* agetty.c - 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. The entire man-page used to
5 * be here. Now read the real man-page agetty.8 instead.
7 * option added by Eric Rasmussen <ear@usfirst.org> - 12/28/95
9 * 1999-02-22 Arkadiusz Mi¶kiewicz <misiek@misiek.eu.org>
10 * - added Native Language Support
12 * 1999-05-05 Thorsten Kranzkowski <dl8bcu@gmx.net>
13 * - enable hardware flow control before displaying /etc/issue
15 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
22 #ifdef CONFIG_FEATURE_UTMP
27 * Some heuristics to find out what environment we are in: if it is not
28 * System V, assume it is SunOS 4.
31 #ifdef LOGIN_PROCESS /* defined in System V utmp.h */
32 #define SYSV_STYLE /* select System V style getty */
33 #ifdef CONFIG_FEATURE_WTMP
34 extern void updwtmp(const char *filename, const struct utmp *ut);
36 #endif /* LOGIN_PROCESS */
39 #include <sys/utsname.h>
44 * Things you may want to modify.
46 * You may disagree with the default line-editing etc. characters defined
47 * below. Note, however, that DEL cannot be used for interrupt generation
48 * and for line editing at the same time.
51 /* I doubt there are systems which still need this */
54 #define _PATH_LOGIN "/bin/login"
56 /* If ISSUE is not defined, agetty will never display the contents of the
57 * /etc/issue file. You will not want to spit out large "issue" files at the
60 #define ISSUE "/etc/issue" /* displayed before the login prompt */
62 /* Some shorthands for control characters. */
64 #define CTL(x) (x ^ 0100) /* Assumes ASCII dialect */
65 #define CR CTL('M') /* carriage return */
66 #define NL CTL('J') /* line feed */
67 #define BS CTL('H') /* back space */
68 #define DEL CTL('?') /* delete */
70 /* Defaults for line-editing etc. characters; you may want to change this. */
72 #define DEF_ERASE DEL /* default erase character */
73 #define DEF_INTR CTL('C') /* default interrupt character */
74 #define DEF_QUIT CTL('\\') /* default quit char */
75 #define DEF_KILL CTL('U') /* default kill char */
76 #define DEF_EOF CTL('D') /* default EOF char */
78 #define DEF_SWITCH 0 /* default switch char */
81 * SunOS 4.1.1 termio is broken. We must use the termios stuff instead,
82 * because the termio -> termios translation does not clear the termios
83 * CIBAUD bits. Therefore, the tty driver would sometimes report that input
84 * baud rate != output baud rate. I did not notice that problem with SunOS
85 * 4.1. We will use termios where available, and termio otherwise.
88 /* linux 0.12 termio is broken too, if we use it c_cc[VERASE] isn't set
89 properly, but all is well if we use termios?! */
95 #define termio termios
98 #define TCSETAW TCSETSW
102 * When multiple baud rates are specified on the command line, the first one
103 * we will try is the first one specified.
106 #define FIRST_SPEED 0
108 /* Storage for command-line options. */
110 #define MAX_SPEED 10 /* max. nr. of baud rates */
113 int flags; /* toggle switches, see below */
114 unsigned timeout; /* time-out period */
115 char *login; /* login program */
116 char *tty; /* name of tty */
117 char *initstring; /* modem init string */
118 char *issue; /* alternative issue file */
119 int numspeed; /* number of baud rates to try */
120 int speeds[MAX_SPEED]; /* baud rates to be tried */
123 static const char opt_string[] = "I:LH:f:hil:mt:wn";
124 #define F_INITSTRING (1<<0) /* initstring is set */
125 #define F_LOCAL (1<<1) /* force local */
126 #define F_FAKEHOST (1<<2) /* force fakehost */
127 #define F_CUSTISSUE (1<<3) /* give alternative issue file */
128 #define F_RTSCTS (1<<4) /* enable RTS/CTS flow control */
129 #define F_ISSUE (1<<5) /* display /etc/issue */
130 #define F_LOGIN (1<<6) /* non-default login program */
131 #define F_PARSE (1<<7) /* process modem status messages */
132 #define F_TIMEOUT (1<<8) /* time out */
133 #define F_WAITCRLF (1<<9) /* wait for CR or LF */
134 #define F_NOPROMPT (1<<10) /* don't ask for login name! */
136 /* Storage for things detected while the login name was read. */
139 unsigned char erase; /* erase character */
140 unsigned char kill; /* kill character */
141 unsigned char eol; /* end-of-line character */
142 unsigned char parity; /* what parity did we see */
143 #ifdef HANDLE_ALLCAPS
144 unsigned char capslock; /* upper case without lower case */
148 /* Initial values for the above. */
150 static const struct chardata init_chardata = {
151 DEF_ERASE, /* default erase character */
152 DEF_KILL, /* default kill character */
153 13, /* default eol char */
154 0, /* space parity */
155 #ifdef HANDLE_ALLCAPS
161 #ifdef CONFIG_FEATURE_UTMP
162 static void update_utmp(char *line);
166 /* The following is used for understandable diagnostics. */
168 /* Fake hostname for ut_host specified on command line. */
169 static char *fakehost = NULL;
173 #define debug(s) fprintf(dbf,s); fflush(dbf)
174 #define DEBUGTERM "/dev/ttyp0"
177 #define debug(s) /* nothing */
181 /* bcode - convert speed string to speed code; return 0 on failure */
182 static int bcode(const char *s)
186 if (safe_strtou((char *)s, &value)) {
189 r = tty_value_to_baud(value);
197 /* parse_speeds - parse alternate baud rates */
198 static void parse_speeds(struct options *op, char *arg)
202 debug("entered parse_speeds\n");
203 for (cp = strtok(arg, ","); cp != 0; cp = strtok((char *) 0, ",")) {
204 if ((op->speeds[op->numspeed++] = bcode(cp)) <= 0)
205 bb_error_msg_and_die("bad speed: %s", cp);
206 if (op->numspeed > MAX_SPEED)
207 bb_error_msg_and_die("too many alternate speeds");
209 debug("exiting parsespeeds\n");
213 /* parse_args - parse command-line arguments */
214 static void parse_args(int argc, char **argv, struct options *op)
218 op->flags = getopt32(argc, argv, opt_string,
219 &(op->initstring), &fakehost, &(op->issue),
221 if (op->flags & F_INITSTRING) {
222 const char *p = op->initstring;
225 q = op->initstring = xstrdup(op->initstring);
226 /* copy optarg into op->initstring decoding \ddd
227 octal codes into chars */
231 *q++ = bb_process_escape_sequence(&p);
238 op->flags ^= F_ISSUE; /* revert flag show /etc/issue */
239 if (op->flags & F_TIMEOUT) {
240 op->timeout = xatoul_range(ts, 1, INT_MAX);
244 debug("after getopt loop\n");
245 if (argc < 2) /* check parameter count */
248 /* we loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
249 if ('0' <= argv[0][0] && argv[0][0] <= '9') {
250 /* a number first, assume it's a speed (BSD style) */
251 parse_speeds(op, argv[0]); /* baud rate(s) */
252 op->tty = argv[1]; /* tty name */
254 op->tty = argv[0]; /* tty name */
255 parse_speeds(op, argv[1]); /* baud rate(s) */
259 setenv("TERM", argv[2], 1);
261 debug("exiting parseargs\n");
264 static void xdup2(int srcfd, int dstfd, const char *tty)
266 if (dup2(srcfd, dstfd) == -1)
267 bb_perror_msg_and_die("%s: dup", tty);
270 /* open_tty - set up tty as standard { input, output, error } */
271 static void open_tty(char *tty, struct termio *tp, int local)
273 int chdir_to_root = 0;
275 /* Set up new standard input, unless we are given an already opened port. */
277 if (strcmp(tty, "-")) {
281 /* Sanity checks... */
286 if ((st.st_mode & S_IFMT) != S_IFCHR)
287 bb_error_msg_and_die("%s: not a character device", tty);
289 /* Open the tty as standard input. */
292 fd = xopen(tty, O_RDWR | O_NONBLOCK);
299 * Standard input should already be connected to an open port. Make
300 * sure it is open for read/write.
303 if ((fcntl(0, F_GETFL, 0) & O_RDWR) != O_RDWR)
304 bb_error_msg_and_die("%s: not open for read/write", tty);
307 /* Replace current standard output/error fd's with new ones */
313 * The following ioctl will fail if stdin is not a tty, but also when
314 * there is noise on the modem control lines. In the latter case, the
315 * common course of action is (1) fix your cables (2) give the modem more
316 * time to properly reset after hanging up. SunOS users can achieve (2)
317 * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
318 * 5 seconds seems to be a good value.
321 if (ioctl(0, TCGETA, tp) < 0)
322 bb_perror_msg_and_die("%s: ioctl(TCGETA)", tty);
325 * It seems to be a terminal. Set proper protections and ownership. Mode
326 * 0622 is suitable for SYSV <4 because /bin/login does not change
327 * protections. SunOS 4 login will change the protections to 0620 (write
328 * access for group tty) after the login has succeeded.
332 #warning Debian /dev/vcs[a]NN hack is deprecated and will be removed
334 /* tty to root.dialout 660 */
338 gr = getgrnam("dialout");
339 id = gr ? gr->gr_gid : 0;
343 /* vcs,vcsa to root.sys 600 */
344 if (!strncmp(tty, "tty", 3) && isdigit(tty[3])) {
348 vcsa = xmalloc(strlen(tty) + 2);
350 strcpy(vcs + 3, tty + 3);
351 strcpy(vcsa, "vcsa");
352 strcpy(vcsa + 4, tty + 3);
354 id = (gr = getgrnam("sys")) ? gr->gr_gid : 0;
365 chown(tty, 0, 0); /* root, sys */
366 chmod(tty, 0622); /* crw--w--w- */
372 /* termio_init - initialize termio settings */
373 static void termio_init(struct termio *tp, int speed, struct options *op)
376 * Initial termio settings: 8-bit characters, raw-mode, blocking i/o.
377 * Special characters are set after we have read the login name; all
378 * reads will be done in raw mode anyway. Errors will be dealt with
382 /* flush input and output queues, important for modems! */
383 ioctl(0, TCFLSH, TCIOFLUSH);
386 tp->c_cflag = CS8 | HUPCL | CREAD | speed;
387 if (op->flags & F_LOCAL) {
388 tp->c_cflag |= CLOCAL;
391 tp->c_iflag = tp->c_lflag = tp->c_line = 0;
392 tp->c_oflag = OPOST | ONLCR;
396 /* Optionally enable hardware flow control */
399 if (op->flags & F_RTSCTS)
400 tp->c_cflag |= CRTSCTS;
403 ioctl(0, TCSETA, tp);
405 /* go to blocking input even in local mode */
406 fcntl(0, F_SETFL, fcntl(0, F_GETFL, 0) & ~O_NONBLOCK);
408 debug("term_io 2\n");
411 /* auto_baud - extract baud rate from modem status message */
412 static void auto_baud(char *buf, unsigned size_buf, struct termio *tp)
421 * This works only if the modem produces its status code AFTER raising
422 * the DCD line, and if the computer is fast enough to set the proper
423 * baud rate before the message has gone by. We expect a message of the
426 * <junk><number><junk>
428 * The number is interpreted as the baud rate of the incoming call. If the
429 * modem does not tell us the baud rate within one second, we will keep
430 * using the current baud rate. It is advisable to enable BREAK
431 * processing (comma-separated list of baud rates) if the processing of
432 * modem status messages is enabled.
436 * Use 7-bit characters, don't block if input queue is empty. Errors will
437 * be dealt with later on.
441 tp->c_iflag |= ISTRIP; /* enable 8th-bit stripping */
442 vmin = tp->c_cc[VMIN];
443 tp->c_cc[VMIN] = 0; /* don't block if queue empty */
444 ioctl(0, TCSETA, tp);
447 * Wait for a while, then read everything the modem has said so far and
448 * try to extract the speed of the dial-in call.
452 nread = read(0, buf, size_buf - 1);
455 for (bp = buf; bp < buf + nread; bp++) {
456 if (isascii(*bp) && isdigit(*bp)) {
459 tp->c_cflag &= ~CBAUD;
460 tp->c_cflag |= speed;
466 /* Restore terminal settings. Errors will be dealt with later on. */
469 tp->c_cc[VMIN] = vmin;
470 ioctl(0, TCSETA, tp);
473 /* next_speed - select next baud rate */
474 static void next_speed(struct termio *tp, struct options *op)
476 static int baud_index = FIRST_SPEED; /* current speed index */
478 baud_index = (baud_index + 1) % op->numspeed;
479 tp->c_cflag &= ~CBAUD;
480 tp->c_cflag |= op->speeds[baud_index];
481 ioctl(0, TCSETA, tp);
485 /* do_prompt - show login prompt, optionally preceded by /etc/issue contents */
486 static void do_prompt(struct options *op, struct termio *tp)
489 print_login_issue(op->issue, op->tty);
491 print_login_prompt();
494 #ifdef HANDLE_ALLCAPS
495 /* caps_lock - string contains upper case without lower case */
496 /* returns 1 if true, 0 if false */
497 static int caps_lock(const char *s)
506 /* get_logname - get user name, establish parity, speed, erase, kill, eol */
507 /* return NULL on failure, logname on success */
508 static char *get_logname(char *logname, unsigned size_logname,
509 struct options *op, struct chardata *cp, struct termio *tp)
512 char c; /* input character, full eight bits */
513 char ascval; /* low 7 bits of input character */
514 int bits; /* # of "1" bits per character */
515 int mask; /* mask with 1 bit up */
516 static const char erase[][3] = { /* backspace-space-backspace */
517 "\010\040\010", /* space parity */
518 "\010\040\010", /* odd parity */
519 "\210\240\210", /* even parity */
520 "\210\240\210", /* no parity */
523 /* Initialize kill, erase, parity etc. (also after switching speeds). */
527 /* Flush pending input (esp. after parsing or switching the baud rate). */
530 ioctl(0, TCFLSH, TCIFLUSH);
532 /* Prompt for and read a login name. */
535 while (!logname[0]) {
537 /* Write issue file and prompt, with "parity" bit == 0. */
541 /* Read name, watch for break, parity, erase, kill, end-of-line. */
545 while (cp->eol == '\0') {
547 /* Do not report trivial EINTR/EIO errors. */
548 if (read(0, &c, 1) < 1) {
549 if (errno == EINTR || errno == EIO)
551 bb_perror_msg_and_die("%s: read", op->tty);
554 /* Do BREAK handling elsewhere. */
555 if (c == '\0' && op->numspeed > 1)
558 /* Do parity bit handling. */
560 if (c != ascval) { /* "parity" bit on ? */
563 while (mask & 0177) {
565 bits++; /* count "1" bits */
568 /* ... |= 2 - even, 1 - odd */
569 cp->parity |= 2 - (bits & 1);
572 /* Do erase, kill and end-of-line processing. */
576 *bp = '\0'; /* terminate logname */
577 cp->eol = ascval; /* set end-of-line char */
582 cp->erase = ascval; /* set erase character */
584 write(1, erase[cp->parity], 3);
590 cp->kill = ascval; /* set kill character */
591 while (bp > logname) {
592 write(1, erase[cp->parity], 3);
599 if (!isascii(ascval) || !isprint(ascval)) {
600 /* ignore garbage characters */
601 } else if (bp - logname >= size_logname - 1) {
602 bb_error_msg_and_die("%s: input overrun", op->tty);
604 write(1, &c, 1); /* echo the character */
605 *bp++ = ascval; /* and store it */
611 /* Handle names with upper case and no lower case. */
613 #ifdef HANDLE_ALLCAPS
614 cp->capslock = caps_lock(logname);
616 for (bp = logname; *bp; bp++)
618 *bp = tolower(*bp); /* map name to lower case */
624 /* termio_final - set the final tty mode bits */
625 static void termio_final(struct options *op, struct termio *tp, struct chardata *cp)
627 /* General terminal-independent stuff. */
629 tp->c_iflag |= IXON | IXOFF; /* 2-way flow control */
630 tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
631 /* no longer| ECHOCTL | ECHOPRT */
632 tp->c_oflag |= OPOST;
633 /* tp->c_cflag = 0; */
634 tp->c_cc[VINTR] = DEF_INTR; /* default interrupt */
635 tp->c_cc[VQUIT] = DEF_QUIT; /* default quit */
636 tp->c_cc[VEOF] = DEF_EOF; /* default EOF character */
637 tp->c_cc[VEOL] = DEF_EOL;
638 tp->c_cc[VSWTC] = DEF_SWITCH; /* default switch character */
640 /* Account for special characters seen in input. */
643 tp->c_iflag |= ICRNL; /* map CR in input to NL */
644 tp->c_oflag |= ONLCR; /* map NL in output to CR-NL */
646 tp->c_cc[VERASE] = cp->erase; /* set erase character */
647 tp->c_cc[VKILL] = cp->kill; /* set kill character */
649 /* Account for the presence or absence of parity bits in input. */
651 switch (cp->parity) {
652 case 0: /* space (always 0) parity */
654 case 1: /* odd parity */
655 tp->c_cflag |= PARODD;
657 case 2: /* even parity */
658 tp->c_cflag |= PARENB;
659 tp->c_iflag |= INPCK | ISTRIP;
661 case (1 | 2): /* no parity bit */
662 tp->c_cflag &= ~CSIZE;
666 /* Account for upper case without lower case. */
668 #ifdef HANDLE_ALLCAPS
670 tp->c_iflag |= IUCLC;
671 tp->c_lflag |= XCASE;
672 tp->c_oflag |= OLCUC;
675 /* Optionally enable hardware flow control */
678 if (op->flags & F_RTSCTS)
679 tp->c_cflag |= CRTSCTS;
682 /* Finally, make the new settings effective */
684 if (ioctl(0, TCSETA, tp) < 0)
685 bb_perror_msg_and_die("%s: ioctl(TCSETA)", op->tty);
690 #ifdef CONFIG_FEATURE_UTMP
691 /* update_utmp - update our utmp entry */
692 static void update_utmp(char *line)
697 int mypid = getpid();
698 #if ! (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1))
703 * The utmp file holds miscellaneous information about things started by
704 * /sbin/init and other system-related events. Our purpose is to update
705 * the utmp entry for the current process, in particular the process type
706 * and the tty line we are listening to. Return successfully only if the
707 * utmp file can be opened for update, and if we are able to find our
708 * entry in the utmp file.
710 if (access(_PATH_UTMP, R_OK|W_OK) == -1) {
711 close(creat(_PATH_UTMP, 0664));
713 utmpname(_PATH_UTMP);
715 while ((utp = getutent())
716 && !(utp->ut_type == INIT_PROCESS && utp->ut_pid == mypid))
720 memcpy(&ut, utp, sizeof(ut));
722 /* some inits don't initialize utmp... */
723 memset(&ut, 0, sizeof(ut));
724 safe_strncpy(ut.ut_id, line + 3, sizeof(ut.ut_id));
728 strcpy(ut.ut_user, "LOGIN");
729 safe_strncpy(ut.ut_line, line, sizeof(ut.ut_line));
731 safe_strncpy(ut.ut_host, fakehost, sizeof(ut.ut_host));
734 ut.ut_type = LOGIN_PROCESS;
740 #ifdef CONFIG_FEATURE_WTMP
741 if (access(bb_path_wtmp_file, R_OK|W_OK) == -1)
742 close(creat(bb_path_wtmp_file, 0664));
743 updwtmp(bb_path_wtmp_file, &ut);
747 #endif /* CONFIG_FEATURE_UTMP */
748 #endif /* SYSV_STYLE */
751 int getty_main(int argc, char **argv)
754 char *logname = NULL; /* login name, given to /bin/login */
755 // TODO: we can merge these into "struct local"
756 // (will reduce parameter passing)
757 struct chardata chardata; /* set by get_logname() */
758 struct termio termio; /* terminal mode bits */
759 struct options options = {
760 0, /* show /etc/issue (SYSV_STYLE) */
762 _PATH_LOGIN, /* default login program */
763 "tty1", /* default tty line */
764 "", /* modem init string */
766 ISSUE, /* default issue file */
770 0, /* no baud rates known yet */
773 /* Already too late because of theoretical
774 * possibility of getty --help somehow triggered
775 * inadvertently before we reach this. Oh well. */
779 logmode = LOGMODE_NONE;
783 /* Was "/dev/console". Why should we spam *system console*
784 * if there is a problem with getty on /dev/ttyS15?... */
785 nullfd = xopen(bb_dev_null, O_RDWR);
791 /* We want special flavor of error_msg_and_die */
794 openlog(applet_name, LOG_PID, LOG_AUTH);
795 logmode = LOGMODE_BOTH;
798 dbf = xfopen(DEBUGTERM, "w");
803 for (i = 1; i < argc; i++) {
810 /* Parse command-line arguments. */
811 parse_args(argc, argv, &options);
814 #ifdef CONFIG_FEATURE_UTMP
815 /* Update the utmp file. */
816 update_utmp(options.tty);
820 debug("calling open_tty\n");
821 /* Open the tty as standard { input, output, error }. */
822 open_tty(options.tty, &termio, options.flags & F_LOCAL);
829 ioctl(0, TIOCSPGRP, &iv);
832 /* Initialize the termio settings (raw mode, eight-bit, blocking i/o). */
833 debug("calling termio_init\n");
834 termio_init(&termio, options.speeds[FIRST_SPEED], &options);
836 /* write the modem init string and DON'T flush the buffers */
837 if (options.flags & F_INITSTRING) {
838 debug("writing init string\n");
839 write(1, options.initstring, strlen(options.initstring));
842 if (!(options.flags & F_LOCAL)) {
843 /* go to blocking write mode unless -L is specified */
844 fcntl(1, F_SETFL, fcntl(1, F_GETFL, 0) & ~O_NONBLOCK);
847 /* Optionally detect the baud rate from the modem status message. */
848 debug("before autobaud\n");
849 if (options.flags & F_PARSE)
850 auto_baud(bb_common_bufsiz1, sizeof(bb_common_bufsiz1), &termio);
852 /* Set the optional timer. */
854 alarm(options.timeout);
856 /* optionally wait for CR or LF before writing /etc/issue */
857 if (options.flags & F_WAITCRLF) {
860 debug("waiting for cr-lf\n");
861 while (read(0, &ch, 1) == 1) {
862 ch &= 0x7f; /* strip "parity bit" */
864 fprintf(dbf, "read %c\n", ch);
866 if (ch == '\n' || ch == '\r')
871 chardata = init_chardata;
872 if (!(options.flags & F_NOPROMPT)) {
873 /* Read the login name. */
874 debug("reading login name\n");
875 logname = get_logname(bb_common_bufsiz1, sizeof(bb_common_bufsiz1),
876 &options, &chardata, &termio);
877 while (logname == NULL)
878 next_speed(&termio, &options);
886 /* Finalize the termio settings. */
888 termio_final(&options, &termio, &chardata);
890 /* Now the newline character should be properly written. */
894 /* Let the login program take care of password validation. */
896 execl(options.login, options.login, "--", logname, (char *) 0);
897 bb_error_msg_and_die("%s: can't exec %s", options.tty, options.login);