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.
23 #include <sys/ioctl.h>
34 #ifdef CONFIG_FEATURE_UTMP
38 #define _PATH_LOGIN "/bin/login"
40 /* If USE_SYSLOG is undefined all diagnostics go directly to /dev/console. */
42 #include <sys/param.h>
48 * Some heuristics to find out what environment we are in: if it is not
49 * System V, assume it is SunOS 4.
52 #ifdef LOGIN_PROCESS /* defined in System V utmp.h */
53 #define SYSV_STYLE /* select System V style getty */
54 #ifdef CONFIG_FEATURE_WTMP
55 extern void updwtmp(const char *filename, const struct utmp *ut);
57 #endif /* LOGIN_PROCESS */
60 * Things you may want to modify.
62 * You may disagree with the default line-editing etc. characters defined
63 * below. Note, however, that DEL cannot be used for interrupt generation
64 * and for line editing at the same time.
68 #include <sys/utsname.h>
72 /* If ISSUE is not defined, agetty will never display the contents of the
73 * /etc/issue file. You will not want to spit out large "issue" files at the
76 #define ISSUE "/etc/issue" /* displayed before the login prompt */
78 /* Some shorthands for control characters. */
80 #define CTL(x) (x ^ 0100) /* Assumes ASCII dialect */
81 #define CR CTL('M') /* carriage return */
82 #define NL CTL('J') /* line feed */
83 #define BS CTL('H') /* back space */
84 #define DEL CTL('?') /* delete */
86 /* Defaults for line-editing etc. characters; you may want to change this. */
88 #define DEF_ERASE DEL /* default erase character */
89 #define DEF_INTR CTL('C') /* default interrupt character */
90 #define DEF_QUIT CTL('\\') /* default quit char */
91 #define DEF_KILL CTL('U') /* default kill char */
92 #define DEF_EOF CTL('D') /* default EOF char */
94 #define DEF_SWITCH 0 /* default switch char */
97 * SunOS 4.1.1 termio is broken. We must use the termios stuff instead,
98 * because the termio -> termios translation does not clear the termios
99 * CIBAUD bits. Therefore, the tty driver would sometimes report that input
100 * baud rate != output baud rate. I did not notice that problem with SunOS
101 * 4.1. We will use termios where available, and termio otherwise.
104 /* linux 0.12 termio is broken too, if we use it c_cc[VERASE] isn't set
105 properly, but all is well if we use termios?! */
111 #define termio termios
112 #define TCGETA TCGETS
113 #define TCSETA TCSETS
114 #define TCSETAW TCSETSW
118 * When multiple baud rates are specified on the command line, the first one
119 * we will try is the first one specified.
122 #define FIRST_SPEED 0
124 /* Storage for command-line options. */
126 #define MAX_SPEED 10 /* max. nr. of baud rates */
129 int flags; /* toggle switches, see below */
130 int timeout; /* time-out period */
131 char *login; /* login program */
132 char *tty; /* name of tty */
133 char *initstring; /* modem init string */
134 char *issue; /* alternative issue file */
135 int numspeed; /* number of baud rates to try */
136 int speeds[MAX_SPEED]; /* baud rates to be tried */
139 static const char opt_string[] = "I:LH:f:hil:mt:wn";
140 #define F_INITSTRING (1<<0) /* initstring is set */
141 #define F_LOCAL (1<<1) /* force local */
142 #define F_FAKEHOST (1<<2) /* force fakehost */
143 #define F_CUSTISSUE (1<<3) /* give alternative issue file */
144 #define F_RTSCTS (1<<4) /* enable RTS/CTS flow control */
145 #define F_ISSUE (1<<5) /* display /etc/issue */
146 #define F_LOGIN (1<<6) /* non-default login program */
147 #define F_PARSE (1<<7) /* process modem status messages */
148 #define F_TIMEOUT (1<<8) /* time out */
149 #define F_WAITCRLF (1<<9) /* wait for CR or LF */
150 #define F_NOPROMPT (1<<10) /* don't ask for login name! */
152 /* Storage for things detected while the login name was read. */
155 int erase; /* erase character */
156 int kill; /* kill character */
157 int eol; /* end-of-line character */
158 int parity; /* what parity did we see */
159 int capslock; /* upper case without lower case */
162 /* Initial values for the above. */
164 static struct chardata init_chardata = {
165 DEF_ERASE, /* default erase character */
166 DEF_KILL, /* default kill character */
167 13, /* default eol char */
168 0, /* space parity */
178 static struct Speedtab speedtab[] = {
219 #ifdef CONFIG_FEATURE_UTMP
220 static void update_utmp(char *line);
224 /* The following is used for understandable diagnostics. */
226 /* Fake hostname for ut_host specified on command line. */
227 static char *fakehost = NULL;
231 #define debug(s) fprintf(dbf,s); fflush(dbf)
232 #define DEBUGTERM "/dev/ttyp0"
235 #define debug(s) /* nothing */
240 * output error messages
242 static void error(const char *fmt, ...) ATTRIBUTE_NORETURN;
243 static void error(const char *fmt, ...)
248 #ifdef CONFIG_SYSLOGD
249 va_start(va_alist, fmt);
250 vsnprintf(buf, sizeof(buf), fmt, va_alist);
251 openlog(bb_applet_name, 0, LOG_AUTH);
252 syslog(LOG_ERR, "%s", buf);
258 snprintf(buf, sizeof(buf), "%s: ", bb_applet_name);
260 va_start(va_alist, fmt);
261 vsnprintf(buf + l, sizeof(buf) - l, fmt, va_alist);
263 /* truncate if need */
264 if((l + 3) > sizeof(buf))
266 /* add \r\n always */
270 if ((fd = open("/dev/console", 1)) >= 0) {
278 (void) sleep((unsigned) 10); /* be kind to init(8) */
284 /* bcode - convert speed string to speed code; return 0 on failure */
285 static int bcode(const char *s)
289 if (safe_strtoul((char *)s, &value)) {
292 if ((r = tty_value_to_baud(value)) > 0) {
299 /* parse_speeds - parse alternate baud rates */
300 static void parse_speeds(struct options *op, char *arg)
304 debug("entered parse_speeds\n");
305 for (cp = strtok(arg, ","); cp != 0; cp = strtok((char *) 0, ",")) {
306 if ((op->speeds[op->numspeed++] = bcode(cp)) <= 0)
307 error("bad speed: %s", cp);
308 if (op->numspeed > MAX_SPEED)
309 error("too many alternate speeds");
311 debug("exiting parsespeeds\n");
315 /* parse-args - parse command-line arguments */
316 static void parse_args(int argc, char **argv, struct options *op)
320 op->flags = bb_getopt_ulflags(argc, argv, opt_string,
321 &(op->initstring), &fakehost, &(op->issue),
323 if(op->flags & F_INITSTRING) {
324 const char *p = op->initstring;
327 q = op->initstring = bb_xstrdup(op->initstring);
328 /* copy optarg into op->initstring decoding \ddd
329 octal codes into chars */
333 *q++ = bb_process_escape_sequence(&p);
340 op->flags ^= F_ISSUE; /* revert flag show /etc/issue */
341 if(op->flags & F_TIMEOUT) {
342 if ((op->timeout = atoi(ts)) <= 0)
343 error("bad timeout value: %s", ts);
345 debug("after getopt loop\n");
346 if (argc < optind + 2) /* check parameter count */
349 /* we loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
350 if ('0' <= argv[optind][0] && argv[optind][0] <= '9') {
351 /* a number first, assume it's a speed (BSD style) */
352 parse_speeds(op, argv[optind++]); /* baud rate(s) */
353 op->tty = argv[optind]; /* tty name */
355 op->tty = argv[optind++]; /* tty name */
356 parse_speeds(op, argv[optind]); /* baud rate(s) */
360 if (argc > optind && argv[optind])
361 setenv("TERM", argv[optind], 1);
363 debug("exiting parseargs\n");
366 /* open_tty - set up tty as standard { input, output, error } */
367 static void open_tty(char *tty, struct termio *tp, int local)
369 int chdir_to_root = 0;
371 /* Set up new standard input, unless we are given an already opened port. */
373 if (strcmp(tty, "-")) {
377 /* Sanity checks... */
380 error("/dev: chdir() failed: %m");
382 if (stat(tty, &st) < 0)
383 error("/dev/%s: %m", tty);
384 if ((st.st_mode & S_IFMT) != S_IFCHR)
385 error("/dev/%s: not a character device", tty);
387 /* Open the tty as standard input. */
391 fd = open(tty, O_RDWR | O_NONBLOCK, 0);
393 error("/dev/%s: cannot open as standard input: %m", tty);
397 * Standard input should already be connected to an open port. Make
398 * sure it is open for read/write.
401 if ((fcntl(0, F_GETFL, 0) & O_RDWR) != O_RDWR)
402 error("%s: not open for read/write", tty);
405 /* Replace current standard output/error fd's with new ones */
407 if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1 ||
408 dup2(STDIN_FILENO, STDERR_FILENO) == -1)
409 error("%s: dup problem: %m", tty); /* we have a problem */
412 * The following ioctl will fail if stdin is not a tty, but also when
413 * there is noise on the modem control lines. In the latter case, the
414 * common course of action is (1) fix your cables (2) give the modem more
415 * time to properly reset after hanging up. SunOS users can achieve (2)
416 * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
417 * 5 seconds seems to be a good value.
420 if (ioctl(0, TCGETA, tp) < 0)
421 error("%s: ioctl: %m", tty);
424 * It seems to be a terminal. Set proper protections and ownership. Mode
425 * 0622 is suitable for SYSV <4 because /bin/login does not change
426 * protections. SunOS 4 login will change the protections to 0620 (write
427 * access for group tty) after the login has succeeded.
432 /* tty to root.dialout 660 */
436 id = (gr = getgrnam("dialout")) ? gr->gr_gid : 0;
440 /* vcs,vcsa to root.sys 600 */
441 if (!strncmp(tty, "tty", 3) && isdigit(tty[3])) {
444 if (!(vcs = strdup(tty)))
445 error("Can't malloc for vcs");
446 if (!(vcsa = malloc(strlen(tty) + 2)))
447 error("Can't malloc for vcsa");
449 strcpy(vcs + 3, tty + 3);
450 strcpy(vcsa, "vcsa");
451 strcpy(vcsa + 4, tty + 3);
453 id = (gr = getgrnam("sys")) ? gr->gr_gid : 0;
464 (void) chown(tty, 0, 0); /* root, sys */
465 (void) chmod(tty, 0622); /* crw--w--w- */
467 if(chdir_to_root && chdir("/"))
468 error("chdir to / failed: %m");
471 /* termio_init - initialize termio settings */
472 static void termio_init(struct termio *tp, int speed, struct options *op)
475 * Initial termio settings: 8-bit characters, raw-mode, blocking i/o.
476 * Special characters are set after we have read the login name; all
477 * reads will be done in raw mode anyway. Errors will be dealt with
481 /* flush input and output queues, important for modems! */
482 (void) ioctl(0, TCFLSH, TCIOFLUSH);
485 tp->c_cflag = CS8 | HUPCL | CREAD | speed;
486 if (op->flags & F_LOCAL) {
487 tp->c_cflag |= CLOCAL;
490 tp->c_iflag = tp->c_lflag = tp->c_oflag = tp->c_line = 0;
494 /* Optionally enable hardware flow control */
497 if (op->flags & F_RTSCTS)
498 tp->c_cflag |= CRTSCTS;
501 (void) ioctl(0, TCSETA, tp);
503 /* go to blocking input even in local mode */
504 fcntl(0, F_SETFL, fcntl(0, F_GETFL, 0) & ~O_NONBLOCK);
506 debug("term_io 2\n");
509 /* auto_baud - extract baud rate from modem status message */
510 static void auto_baud(struct termio *tp)
520 * This works only if the modem produces its status code AFTER raising
521 * the DCD line, and if the computer is fast enough to set the proper
522 * baud rate before the message has gone by. We expect a message of the
525 * <junk><number><junk>
527 * The number is interpreted as the baud rate of the incoming call. If the
528 * modem does not tell us the baud rate within one second, we will keep
529 * using the current baud rate. It is advisable to enable BREAK
530 * processing (comma-separated list of baud rates) if the processing of
531 * modem status messages is enabled.
535 * Use 7-bit characters, don't block if input queue is empty. Errors will
536 * be dealt with lateron.
540 tp->c_iflag |= ISTRIP; /* enable 8th-bit stripping */
541 vmin = tp->c_cc[VMIN];
542 tp->c_cc[VMIN] = 0; /* don't block if queue empty */
543 (void) ioctl(0, TCSETA, tp);
546 * Wait for a while, then read everything the modem has said so far and
547 * try to extract the speed of the dial-in call.
551 if ((nread = read(0, buf, sizeof(buf) - 1)) > 0) {
553 for (bp = buf; bp < buf + nread; bp++) {
554 if (isascii(*bp) && isdigit(*bp)) {
555 if ((speed = bcode(bp))) {
556 tp->c_cflag &= ~CBAUD;
557 tp->c_cflag |= speed;
563 /* Restore terminal settings. Errors will be dealt with lateron. */
566 tp->c_cc[VMIN] = vmin;
567 (void) ioctl(0, TCSETA, tp);
570 /* next_speed - select next baud rate */
571 static void next_speed(struct termio *tp, struct options *op)
573 static int baud_index = FIRST_SPEED; /* current speed index */
575 baud_index = (baud_index + 1) % op->numspeed;
576 tp->c_cflag &= ~CBAUD;
577 tp->c_cflag |= op->speeds[baud_index];
578 (void) ioctl(0, TCSETA, tp);
582 /* do_prompt - show login prompt, optionally preceded by /etc/issue contents */
583 static void do_prompt(struct options *op, struct termio *tp)
585 #ifdef ISSUE /* optional: show /etc/issue */
586 print_login_issue(op->issue, op->tty);
588 print_login_prompt();
591 /* caps_lock - string contains upper case without lower case */
592 /* returns 1 if true, 0 if false */
593 static int caps_lock(const char *s)
597 for (capslock = 0; *s; s++) {
601 capslock = isupper(*s);
606 #define logname bb_common_bufsiz1
607 /* get_logname - get user name, establish parity, speed, erase, kill, eol */
608 /* return NULL on failure, logname on success */
609 static char *get_logname(struct options *op, struct chardata *cp, struct termio *tp)
612 char c; /* input character, full eight bits */
613 char ascval; /* low 7 bits of input character */
614 int bits; /* # of "1" bits per character */
615 int mask; /* mask with 1 bit up */
616 static char *erase[] = { /* backspace-space-backspace */
617 "\010\040\010", /* space parity */
618 "\010\040\010", /* odd parity */
619 "\210\240\210", /* even parity */
620 "\210\240\210", /* no parity */
623 /* Initialize kill, erase, parity etc. (also after switching speeds). */
627 /* Flush pending input (esp. after parsing or switching the baud rate). */
630 (void) ioctl(0, TCFLSH, TCIFLUSH);
632 /* Prompt for and read a login name. */
634 for (*logname = 0; *logname == 0; /* void */ ) {
636 /* Write issue file and prompt, with "parity" bit == 0. */
640 /* Read name, watch for break, parity, erase, kill, end-of-line. */
642 for (bp = logname, cp->eol = 0; cp->eol == 0; /* void */ ) {
644 /* Do not report trivial EINTR/EIO errors. */
646 if (read(0, &c, 1) < 1) {
647 if (errno == EINTR || errno == EIO)
649 error("%s: read: %m", op->tty);
651 /* Do BREAK handling elsewhere. */
653 if ((c == 0) && op->numspeed > 1)
657 /* Do parity bit handling. */
659 if (c != (ascval = (c & 0177))) { /* "parity" bit on ? */
660 for (bits = 1, mask = 1; mask & 0177; mask <<= 1)
662 bits++; /* count "1" bits */
663 cp->parity |= ((bits & 1) ? 1 : 2);
665 /* Do erase, kill and end-of-line processing. */
670 *bp = 0; /* terminate logname */
671 cp->eol = ascval; /* set end-of-line char */
676 cp->erase = ascval; /* set erase character */
678 (void) write(1, erase[cp->parity], 3);
684 cp->kill = ascval; /* set kill character */
685 while (bp > logname) {
686 (void) write(1, erase[cp->parity], 3);
693 if (!isascii(ascval) || !isprint(ascval)) {
694 /* ignore garbage characters */ ;
695 } else if (bp - logname >= sizeof(logname) - 1) {
696 error("%s: input overrun", op->tty);
698 (void) write(1, &c, 1); /* echo the character */
699 *bp++ = ascval; /* and store it */
705 /* Handle names with upper case and no lower case. */
707 if ((cp->capslock = caps_lock(logname))) {
708 for (bp = logname; *bp; bp++)
710 *bp = tolower(*bp); /* map name to lower case */
715 /* termio_final - set the final tty mode bits */
716 static void termio_final(struct options *op, struct termio *tp, struct chardata *cp)
718 /* General terminal-independent stuff. */
720 tp->c_iflag |= IXON | IXOFF; /* 2-way flow control */
721 tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
722 /* no longer| ECHOCTL | ECHOPRT */
723 tp->c_oflag |= OPOST;
724 /* tp->c_cflag = 0; */
725 tp->c_cc[VINTR] = DEF_INTR; /* default interrupt */
726 tp->c_cc[VQUIT] = DEF_QUIT; /* default quit */
727 tp->c_cc[VEOF] = DEF_EOF; /* default EOF character */
728 tp->c_cc[VEOL] = DEF_EOL;
729 tp->c_cc[VSWTC] = DEF_SWITCH; /* default switch character */
731 /* Account for special characters seen in input. */
734 tp->c_iflag |= ICRNL; /* map CR in input to NL */
735 tp->c_oflag |= ONLCR; /* map NL in output to CR-NL */
737 tp->c_cc[VERASE] = cp->erase; /* set erase character */
738 tp->c_cc[VKILL] = cp->kill; /* set kill character */
740 /* Account for the presence or absence of parity bits in input. */
742 switch (cp->parity) {
743 case 0: /* space (always 0) parity */
745 case 1: /* odd parity */
746 tp->c_cflag |= PARODD;
748 case 2: /* even parity */
749 tp->c_cflag |= PARENB;
750 tp->c_iflag |= INPCK | ISTRIP;
752 case (1 | 2): /* no parity bit */
753 tp->c_cflag &= ~CSIZE;
757 /* Account for upper case without lower case. */
760 tp->c_iflag |= IUCLC;
761 tp->c_lflag |= XCASE;
762 tp->c_oflag |= OLCUC;
764 /* Optionally enable hardware flow control */
767 if (op->flags & F_RTSCTS)
768 tp->c_cflag |= CRTSCTS;
771 /* Finally, make the new settings effective */
773 if (ioctl(0, TCSETA, tp) < 0)
774 error("%s: ioctl: TCSETA: %m", op->tty);
779 #ifdef CONFIG_FEATURE_UTMP
780 /* update_utmp - update our utmp entry */
781 static void update_utmp(char *line)
786 int mypid = getpid();
787 #if ! (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1))
792 * The utmp file holds miscellaneous information about things started by
793 * /sbin/init and other system-related events. Our purpose is to update
794 * the utmp entry for the current process, in particular the process type
795 * and the tty line we are listening to. Return successfully only if the
796 * utmp file can be opened for update, and if we are able to find our
797 * entry in the utmp file.
799 if (access(_PATH_UTMP, R_OK|W_OK) == -1) {
800 close(creat(_PATH_UTMP, 0664));
802 utmpname(_PATH_UTMP);
804 while ((utp = getutent())
805 && !(utp->ut_type == INIT_PROCESS && utp->ut_pid == mypid)) /* nothing */
809 memcpy(&ut, utp, sizeof(ut));
811 /* some inits don't initialize utmp... */
812 memset(&ut, 0, sizeof(ut));
813 safe_strncpy(ut.ut_id, line + 3, sizeof(ut.ut_id));
817 strcpy(ut.ut_user, "LOGIN");
818 safe_strncpy(ut.ut_line, line, sizeof(ut.ut_line));
820 safe_strncpy(ut.ut_host, fakehost, sizeof(ut.ut_host));
823 ut.ut_type = LOGIN_PROCESS;
829 #ifdef CONFIG_FEATURE_WTMP
830 if (access(bb_path_wtmp_file, R_OK|W_OK) == -1)
831 close(creat(bb_path_wtmp_file, 0664));
832 updwtmp(bb_path_wtmp_file, &ut);
836 #endif /* CONFIG_FEATURE_UTMP */
837 #endif /* SYSV_STYLE */
841 int getty_main(int argc, char **argv)
843 char *logname = NULL; /* login name, given to /bin/login */
844 struct chardata chardata; /* set by get_logname() */
845 struct termio termio; /* terminal mode bits */
846 static struct options options = {
847 0, /* show /etc/issue (SYSV_STYLE) */
849 _PATH_LOGIN, /* default login program */
850 "tty1", /* default tty line */
851 "", /* modem init string */
853 ISSUE, /* default issue file */
857 0, /* no baud rates known yet */
861 dbf = bb_xfopen(DEBUGTERM, "w");
866 for (i = 1; i < argc; i++) {
873 /* Parse command-line arguments. */
875 parse_args(argc, argv, &options);
881 /* Update the utmp file. */
885 #ifdef CONFIG_FEATURE_UTMP
886 update_utmp(options.tty);
890 debug("calling open_tty\n");
891 /* Open the tty as standard { input, output, error }. */
892 open_tty(options.tty, &termio, options.flags & F_LOCAL);
899 ioctl(0, TIOCSPGRP, &iv);
902 /* Initialize the termio settings (raw mode, eight-bit, blocking i/o). */
903 debug("calling termio_init\n");
904 termio_init(&termio, options.speeds[FIRST_SPEED], &options);
906 /* write the modem init string and DON'T flush the buffers */
907 if (options.flags & F_INITSTRING) {
908 debug("writing init string\n");
909 write(1, options.initstring, strlen(options.initstring));
912 if (!(options.flags & F_LOCAL)) {
913 /* go to blocking write mode unless -L is specified */
914 fcntl(1, F_SETFL, fcntl(1, F_GETFL, 0) & ~O_NONBLOCK);
917 /* Optionally detect the baud rate from the modem status message. */
918 debug("before autobaud\n");
919 if (options.flags & F_PARSE)
922 /* Set the optional timer. */
924 (void) alarm((unsigned) options.timeout);
926 /* optionally wait for CR or LF before writing /etc/issue */
927 if (options.flags & F_WAITCRLF) {
930 debug("waiting for cr-lf\n");
931 while (read(0, &ch, 1) == 1) {
932 ch &= 0x7f; /* strip "parity bit" */
934 fprintf(dbf, "read %c\n", ch);
936 if (ch == '\n' || ch == '\r')
941 chardata = init_chardata;
942 if (!(options.flags & F_NOPROMPT)) {
943 /* Read the login name. */
944 debug("reading login name\n");
945 /* while ((logname = get_logname(&options, &chardata, &termio)) == 0) */
946 while ((logname = get_logname(&options, &chardata, &termio)) ==
947 NULL) next_speed(&termio, &options);
955 /* Finalize the termio settings. */
957 termio_final(&options, &termio, &chardata);
959 /* Now the newline character should be properly written. */
961 (void) write(1, "\n", 1);
963 /* Let the login program take care of password validation. */
965 (void) execl(options.login, options.login, "--", logname, (char *) 0);
966 error("%s: can't exec %s: %m", options.tty, options.login);