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 -f 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
21 #include <sys/ioctl.h>
32 #ifdef CONFIG_FEATURE_UTMP
36 #define _PATH_LOGIN "/bin/login"
38 /* If USE_SYSLOG is undefined all diagnostics go directly to /dev/console. */
40 #include <sys/param.h>
46 * Some heuristics to find out what environment we are in: if it is not
47 * System V, assume it is SunOS 4.
50 #ifdef LOGIN_PROCESS /* defined in System V utmp.h */
51 #define SYSV_STYLE /* select System V style getty */
52 #ifdef CONFIG_FEATURE_WTMP
53 extern void updwtmp(const char *filename, const struct utmp *ut);
55 #endif /* LOGIN_PROCESS */
58 * Things you may want to modify.
60 * You may disagree with the default line-editing etc. characters defined
61 * below. Note, however, that DEL cannot be used for interrupt generation
62 * and for line editing at the same time.
66 #include <sys/utsname.h>
70 /* If ISSUE is not defined, agetty will never display the contents of the
71 * /etc/issue file. You will not want to spit out large "issue" files at the
74 #define ISSUE "/etc/issue" /* displayed before the login prompt */
76 /* Some shorthands for control characters. */
78 #define CTL(x) (x ^ 0100) /* Assumes ASCII dialect */
79 #define CR CTL('M') /* carriage return */
80 #define NL CTL('J') /* line feed */
81 #define BS CTL('H') /* back space */
82 #define DEL CTL('?') /* delete */
84 /* Defaults for line-editing etc. characters; you may want to change this. */
86 #define DEF_ERASE DEL /* default erase character */
87 #define DEF_INTR CTL('C') /* default interrupt character */
88 #define DEF_QUIT CTL('\\') /* default quit char */
89 #define DEF_KILL CTL('U') /* default kill char */
90 #define DEF_EOF CTL('D') /* default EOF char */
92 #define DEF_SWITCH 0 /* default switch char */
95 * SunOS 4.1.1 termio is broken. We must use the termios stuff instead,
96 * because the termio -> termios translation does not clear the termios
97 * CIBAUD bits. Therefore, the tty driver would sometimes report that input
98 * baud rate != output baud rate. I did not notice that problem with SunOS
99 * 4.1. We will use termios where available, and termio otherwise.
102 /* linux 0.12 termio is broken too, if we use it c_cc[VERASE] isn't set
103 properly, but all is well if we use termios?! */
109 #define termio termios
110 #define TCGETA TCGETS
111 #define TCSETA TCSETS
112 #define TCSETAW TCSETSW
116 * When multiple baud rates are specified on the command line, the first one
117 * we will try is the first one specified.
120 #define FIRST_SPEED 0
122 /* Storage for command-line options. */
124 #define MAX_SPEED 10 /* max. nr. of baud rates */
127 int flags; /* toggle switches, see below */
128 int timeout; /* time-out period */
129 char *login; /* login program */
130 char *tty; /* name of tty */
131 char *initstring; /* modem init string */
132 char *issue; /* alternative issue file */
133 int numspeed; /* number of baud rates to try */
134 int speeds[MAX_SPEED]; /* baud rates to be tried */
137 static const char opt_string[] = "I:LH:f:hil:mt:wn";
138 #define F_INITSTRING (1<<0) /* initstring is set */
139 #define F_LOCAL (1<<1) /* force local */
140 #define F_FAKEHOST (1<<2) /* force fakehost */
141 #define F_CUSTISSUE (1<<3) /* give alternative issue file */
142 #define F_RTSCTS (1<<4) /* enable RTS/CTS flow control */
143 #define F_ISSUE (1<<5) /* display /etc/issue */
144 #define F_LOGIN (1<<6) /* non-default login program */
145 #define F_PARSE (1<<7) /* process modem status messages */
146 #define F_TIMEOUT (1<<8) /* time out */
147 #define F_WAITCRLF (1<<9) /* wait for CR or LF */
148 #define F_NOPROMPT (1<<10) /* don't ask for login name! */
150 /* Storage for things detected while the login name was read. */
153 int erase; /* erase character */
154 int kill; /* kill character */
155 int eol; /* end-of-line character */
156 int parity; /* what parity did we see */
157 int capslock; /* upper case without lower case */
160 /* Initial values for the above. */
162 static struct chardata init_chardata = {
163 DEF_ERASE, /* default erase character */
164 DEF_KILL, /* default kill character */
165 13, /* default eol char */
166 0, /* space parity */
176 static struct Speedtab speedtab[] = {
217 #ifdef CONFIG_FEATURE_UTMP
218 static void update_utmp(char *line);
222 /* The following is used for understandable diagnostics. */
224 /* Fake hostname for ut_host specified on command line. */
225 static char *fakehost = NULL;
229 #define debug(s) fprintf(dbf,s); fflush(dbf)
230 #define DEBUGTERM "/dev/ttyp0"
233 #define debug(s) /* nothing */
238 * output error messages
240 static void error(const char *fmt, ...) ATTRIBUTE_NORETURN;
241 static void error(const char *fmt, ...)
246 #ifdef CONFIG_SYSLOGD
247 va_start(va_alist, fmt);
248 vsnprintf(buf, sizeof(buf), fmt, va_alist);
249 openlog(bb_applet_name, 0, LOG_AUTH);
250 syslog(LOG_ERR, "%s", buf);
256 snprintf(buf, sizeof(buf), "%s: ", bb_applet_name);
258 va_start(va_alist, fmt);
259 vsnprintf(buf + l, sizeof(buf) - l, fmt, va_alist);
261 /* truncate if need */
262 if((l + 3) > sizeof(buf))
264 /* add \r\n always */
268 if ((fd = open("/dev/console", 1)) >= 0) {
276 (void) sleep((unsigned) 10); /* be kind to init(8) */
282 /* bcode - convert speed string to speed code; return 0 on failure */
283 static int bcode(const char *s)
287 if (safe_strtoul((char *)s, &value)) {
290 if ((r = tty_value_to_baud(value)) > 0) {
297 /* parse_speeds - parse alternate baud rates */
298 static void parse_speeds(struct options *op, char *arg)
302 debug("entered parse_speeds\n");
303 for (cp = strtok(arg, ","); cp != 0; cp = strtok((char *) 0, ",")) {
304 if ((op->speeds[op->numspeed++] = bcode(cp)) <= 0)
305 error("bad speed: %s", cp);
306 if (op->numspeed > MAX_SPEED)
307 error("too many alternate speeds");
309 debug("exiting parsespeeds\n");
313 /* parse-args - parse command-line arguments */
314 static void parse_args(int argc, char **argv, struct options *op)
318 op->flags = bb_getopt_ulflags(argc, argv, opt_string,
319 &(op->initstring), &fakehost, &(op->issue),
321 if(op->flags & F_INITSTRING) {
322 const char *p = op->initstring;
325 q = op->initstring = bb_xstrdup(op->initstring);
326 /* copy optarg into op->initstring decoding \ddd
327 octal codes into chars */
331 *q++ = bb_process_escape_sequence(&p);
338 op->flags ^= F_ISSUE; /* revert flag show /etc/issue */
339 if(op->flags & F_TIMEOUT) {
340 if ((op->timeout = atoi(ts)) <= 0)
341 error("bad timeout value: %s", ts);
343 debug("after getopt loop\n");
344 if (argc < optind + 2) /* check parameter count */
347 /* we loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
348 if ('0' <= argv[optind][0] && argv[optind][0] <= '9') {
349 /* a number first, assume it's a speed (BSD style) */
350 parse_speeds(op, argv[optind++]); /* baud rate(s) */
351 op->tty = argv[optind]; /* tty name */
353 op->tty = argv[optind++]; /* tty name */
354 parse_speeds(op, argv[optind]); /* baud rate(s) */
358 if (argc > optind && argv[optind])
359 setenv("TERM", argv[optind], 1);
361 debug("exiting parseargs\n");
364 /* open_tty - set up tty as standard { input, output, error } */
365 static void open_tty(char *tty, struct termio *tp, int local)
367 int chdir_to_root = 0;
369 /* Set up new standard input, unless we are given an already opened port. */
371 if (strcmp(tty, "-")) {
375 /* Sanity checks... */
378 error("/dev: chdir() failed: %m");
380 if (stat(tty, &st) < 0)
381 error("/dev/%s: %m", tty);
382 if ((st.st_mode & S_IFMT) != S_IFCHR)
383 error("/dev/%s: not a character device", tty);
385 /* Open the tty as standard input. */
389 fd = open(tty, O_RDWR | O_NONBLOCK, 0);
391 error("/dev/%s: cannot open as standard input: %m", tty);
395 * Standard input should already be connected to an open port. Make
396 * sure it is open for read/write.
399 if ((fcntl(0, F_GETFL, 0) & O_RDWR) != O_RDWR)
400 error("%s: not open for read/write", tty);
403 /* Replace current standard output/error fd's with new ones */
405 if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1 ||
406 dup2(STDIN_FILENO, STDERR_FILENO) == -1)
407 error("%s: dup problem: %m", tty); /* we have a problem */
410 * The following ioctl will fail if stdin is not a tty, but also when
411 * there is noise on the modem control lines. In the latter case, the
412 * common course of action is (1) fix your cables (2) give the modem more
413 * time to properly reset after hanging up. SunOS users can achieve (2)
414 * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
415 * 5 seconds seems to be a good value.
418 if (ioctl(0, TCGETA, tp) < 0)
419 error("%s: ioctl: %m", tty);
422 * It seems to be a terminal. Set proper protections and ownership. Mode
423 * 0622 is suitable for SYSV <4 because /bin/login does not change
424 * protections. SunOS 4 login will change the protections to 0620 (write
425 * access for group tty) after the login has succeeded.
430 /* tty to root.dialout 660 */
434 id = (gr = getgrnam("dialout")) ? gr->gr_gid : 0;
438 /* vcs,vcsa to root.sys 600 */
439 if (!strncmp(tty, "tty", 3) && isdigit(tty[3])) {
442 if (!(vcs = strdup(tty)))
443 error("Can't malloc for vcs");
444 if (!(vcsa = malloc(strlen(tty) + 2)))
445 error("Can't malloc for vcsa");
447 strcpy(vcs + 3, tty + 3);
448 strcpy(vcsa, "vcsa");
449 strcpy(vcsa + 4, tty + 3);
451 id = (gr = getgrnam("sys")) ? gr->gr_gid : 0;
462 (void) chown(tty, 0, 0); /* root, sys */
463 (void) chmod(tty, 0622); /* crw--w--w- */
465 if(chdir_to_root && chdir("/"))
466 error("chdir to / failed: %m");
469 /* termio_init - initialize termio settings */
470 static void termio_init(struct termio *tp, int speed, struct options *op)
473 * Initial termio settings: 8-bit characters, raw-mode, blocking i/o.
474 * Special characters are set after we have read the login name; all
475 * reads will be done in raw mode anyway. Errors will be dealt with
479 /* flush input and output queues, important for modems! */
480 (void) ioctl(0, TCFLSH, TCIOFLUSH);
483 tp->c_cflag = CS8 | HUPCL | CREAD | speed;
484 if (op->flags & F_LOCAL) {
485 tp->c_cflag |= CLOCAL;
488 tp->c_iflag = tp->c_lflag = tp->c_oflag = tp->c_line = 0;
492 /* Optionally enable hardware flow control */
495 if (op->flags & F_RTSCTS)
496 tp->c_cflag |= CRTSCTS;
499 (void) ioctl(0, TCSETA, tp);
501 /* go to blocking input even in local mode */
502 fcntl(0, F_SETFL, fcntl(0, F_GETFL, 0) & ~O_NONBLOCK);
504 debug("term_io 2\n");
507 /* auto_baud - extract baud rate from modem status message */
508 static void auto_baud(struct termio *tp)
518 * This works only if the modem produces its status code AFTER raising
519 * the DCD line, and if the computer is fast enough to set the proper
520 * baud rate before the message has gone by. We expect a message of the
523 * <junk><number><junk>
525 * The number is interpreted as the baud rate of the incoming call. If the
526 * modem does not tell us the baud rate within one second, we will keep
527 * using the current baud rate. It is advisable to enable BREAK
528 * processing (comma-separated list of baud rates) if the processing of
529 * modem status messages is enabled.
533 * Use 7-bit characters, don't block if input queue is empty. Errors will
534 * be dealt with lateron.
538 tp->c_iflag |= ISTRIP; /* enable 8th-bit stripping */
539 vmin = tp->c_cc[VMIN];
540 tp->c_cc[VMIN] = 0; /* don't block if queue empty */
541 (void) ioctl(0, TCSETA, tp);
544 * Wait for a while, then read everything the modem has said so far and
545 * try to extract the speed of the dial-in call.
549 if ((nread = read(0, buf, sizeof(buf) - 1)) > 0) {
551 for (bp = buf; bp < buf + nread; bp++) {
552 if (isascii(*bp) && isdigit(*bp)) {
553 if ((speed = bcode(bp))) {
554 tp->c_cflag &= ~CBAUD;
555 tp->c_cflag |= speed;
561 /* Restore terminal settings. Errors will be dealt with lateron. */
564 tp->c_cc[VMIN] = vmin;
565 (void) ioctl(0, TCSETA, tp);
568 /* next_speed - select next baud rate */
569 static void next_speed(struct termio *tp, struct options *op)
571 static int baud_index = FIRST_SPEED; /* current speed index */
573 baud_index = (baud_index + 1) % op->numspeed;
574 tp->c_cflag &= ~CBAUD;
575 tp->c_cflag |= op->speeds[baud_index];
576 (void) ioctl(0, TCSETA, tp);
580 /* do_prompt - show login prompt, optionally preceded by /etc/issue contents */
581 static void do_prompt(struct options *op, struct termio *tp)
583 #ifdef ISSUE /* optional: show /etc/issue */
584 print_login_issue(op->issue, op->tty);
586 print_login_prompt();
589 /* caps_lock - string contains upper case without lower case */
590 /* returns 1 if true, 0 if false */
591 static int caps_lock(const char *s)
595 for (capslock = 0; *s; s++) {
599 capslock = isupper(*s);
604 #define logname bb_common_bufsiz1
605 /* get_logname - get user name, establish parity, speed, erase, kill, eol */
606 /* return NULL on failure, logname on success */
607 static char *get_logname(struct options *op, struct chardata *cp, struct termio *tp)
610 char c; /* input character, full eight bits */
611 char ascval; /* low 7 bits of input character */
612 int bits; /* # of "1" bits per character */
613 int mask; /* mask with 1 bit up */
614 static char *erase[] = { /* backspace-space-backspace */
615 "\010\040\010", /* space parity */
616 "\010\040\010", /* odd parity */
617 "\210\240\210", /* even parity */
618 "\210\240\210", /* no parity */
621 /* Initialize kill, erase, parity etc. (also after switching speeds). */
625 /* Flush pending input (esp. after parsing or switching the baud rate). */
628 (void) ioctl(0, TCFLSH, TCIFLUSH);
630 /* Prompt for and read a login name. */
632 for (*logname = 0; *logname == 0; /* void */ ) {
634 /* Write issue file and prompt, with "parity" bit == 0. */
638 /* Read name, watch for break, parity, erase, kill, end-of-line. */
640 for (bp = logname, cp->eol = 0; cp->eol == 0; /* void */ ) {
642 /* Do not report trivial EINTR/EIO errors. */
644 if (read(0, &c, 1) < 1) {
645 if (errno == EINTR || errno == EIO)
647 error("%s: read: %m", op->tty);
649 /* Do BREAK handling elsewhere. */
651 if ((c == 0) && op->numspeed > 1)
655 /* Do parity bit handling. */
657 if (c != (ascval = (c & 0177))) { /* "parity" bit on ? */
658 for (bits = 1, mask = 1; mask & 0177; mask <<= 1)
660 bits++; /* count "1" bits */
661 cp->parity |= ((bits & 1) ? 1 : 2);
663 /* Do erase, kill and end-of-line processing. */
668 *bp = 0; /* terminate logname */
669 cp->eol = ascval; /* set end-of-line char */
674 cp->erase = ascval; /* set erase character */
676 (void) write(1, erase[cp->parity], 3);
682 cp->kill = ascval; /* set kill character */
683 while (bp > logname) {
684 (void) write(1, erase[cp->parity], 3);
691 if (!isascii(ascval) || !isprint(ascval)) {
692 /* ignore garbage characters */ ;
693 } else if (bp - logname >= sizeof(logname) - 1) {
694 error("%s: input overrun", op->tty);
696 (void) write(1, &c, 1); /* echo the character */
697 *bp++ = ascval; /* and store it */
703 /* Handle names with upper case and no lower case. */
705 if ((cp->capslock = caps_lock(logname))) {
706 for (bp = logname; *bp; bp++)
708 *bp = tolower(*bp); /* map name to lower case */
713 /* termio_final - set the final tty mode bits */
714 static void termio_final(struct options *op, struct termio *tp, struct chardata *cp)
716 /* General terminal-independent stuff. */
718 tp->c_iflag |= IXON | IXOFF; /* 2-way flow control */
719 tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
720 /* no longer| ECHOCTL | ECHOPRT */
721 tp->c_oflag |= OPOST;
722 /* tp->c_cflag = 0; */
723 tp->c_cc[VINTR] = DEF_INTR; /* default interrupt */
724 tp->c_cc[VQUIT] = DEF_QUIT; /* default quit */
725 tp->c_cc[VEOF] = DEF_EOF; /* default EOF character */
726 tp->c_cc[VEOL] = DEF_EOL;
727 tp->c_cc[VSWTC] = DEF_SWITCH; /* default switch character */
729 /* Account for special characters seen in input. */
732 tp->c_iflag |= ICRNL; /* map CR in input to NL */
733 tp->c_oflag |= ONLCR; /* map NL in output to CR-NL */
735 tp->c_cc[VERASE] = cp->erase; /* set erase character */
736 tp->c_cc[VKILL] = cp->kill; /* set kill character */
738 /* Account for the presence or absence of parity bits in input. */
740 switch (cp->parity) {
741 case 0: /* space (always 0) parity */
743 case 1: /* odd parity */
744 tp->c_cflag |= PARODD;
746 case 2: /* even parity */
747 tp->c_cflag |= PARENB;
748 tp->c_iflag |= INPCK | ISTRIP;
750 case (1 | 2): /* no parity bit */
751 tp->c_cflag &= ~CSIZE;
755 /* Account for upper case without lower case. */
758 tp->c_iflag |= IUCLC;
759 tp->c_lflag |= XCASE;
760 tp->c_oflag |= OLCUC;
762 /* Optionally enable hardware flow control */
765 if (op->flags & F_RTSCTS)
766 tp->c_cflag |= CRTSCTS;
769 /* Finally, make the new settings effective */
771 if (ioctl(0, TCSETA, tp) < 0)
772 error("%s: ioctl: TCSETA: %m", op->tty);
777 #ifdef CONFIG_FEATURE_UTMP
778 /* update_utmp - update our utmp entry */
779 static void update_utmp(char *line)
784 int mypid = getpid();
785 #if ! (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1))
790 * The utmp file holds miscellaneous information about things started by
791 * /sbin/init and other system-related events. Our purpose is to update
792 * the utmp entry for the current process, in particular the process type
793 * and the tty line we are listening to. Return successfully only if the
794 * utmp file can be opened for update, and if we are able to find our
795 * entry in the utmp file.
797 if (access(_PATH_UTMP, R_OK|W_OK) == -1) {
798 close(creat(_PATH_UTMP, 0664));
800 utmpname(_PATH_UTMP);
802 while ((utp = getutent())
803 && !(utp->ut_type == INIT_PROCESS && utp->ut_pid == mypid)) /* nothing */
807 memcpy(&ut, utp, sizeof(ut));
809 /* some inits don't initialize utmp... */
810 memset(&ut, 0, sizeof(ut));
811 strncpy(ut.ut_id, line + 3, sizeof(ut.ut_id));
815 strncpy(ut.ut_user, "LOGIN", sizeof(ut.ut_user));
816 strncpy(ut.ut_line, line, sizeof(ut.ut_line));
818 strncpy(ut.ut_host, fakehost, sizeof(ut.ut_host));
821 ut.ut_type = LOGIN_PROCESS;
827 #ifdef CONFIG_FEATURE_WTMP
828 if (access(bb_path_wtmp_file, R_OK|W_OK) == -1)
829 close(creat(bb_path_wtmp_file, 0664));
830 updwtmp(bb_path_wtmp_file, &ut);
834 #endif /* CONFIG_FEATURE_UTMP */
835 #endif /* SYSV_STYLE */
839 int getty_main(int argc, char **argv)
841 char *logname = NULL; /* login name, given to /bin/login */
842 struct chardata chardata; /* set by get_logname() */
843 struct termio termio; /* terminal mode bits */
844 static struct options options = {
845 0, /* show /etc/issue (SYSV_STYLE) */
847 _PATH_LOGIN, /* default login program */
848 "tty1", /* default tty line */
849 "", /* modem init string */
851 ISSUE, /* default issue file */
855 0, /* no baud rates known yet */
859 dbf = bb_xfopen(DEBUGTERM, "w");
864 for (i = 1; i < argc; i++) {
871 /* Parse command-line arguments. */
873 parse_args(argc, argv, &options);
879 /* Update the utmp file. */
883 #ifdef CONFIG_FEATURE_UTMP
884 update_utmp(options.tty);
888 debug("calling open_tty\n");
889 /* Open the tty as standard { input, output, error }. */
890 open_tty(options.tty, &termio, options.flags & F_LOCAL);
897 ioctl(0, TIOCSPGRP, &iv);
900 /* Initialize the termio settings (raw mode, eight-bit, blocking i/o). */
901 debug("calling termio_init\n");
902 termio_init(&termio, options.speeds[FIRST_SPEED], &options);
904 /* write the modem init string and DON'T flush the buffers */
905 if (options.flags & F_INITSTRING) {
906 debug("writing init string\n");
907 write(1, options.initstring, strlen(options.initstring));
910 if (!(options.flags & F_LOCAL)) {
911 /* go to blocking write mode unless -L is specified */
912 fcntl(1, F_SETFL, fcntl(1, F_GETFL, 0) & ~O_NONBLOCK);
915 /* Optionally detect the baud rate from the modem status message. */
916 debug("before autobaud\n");
917 if (options.flags & F_PARSE)
920 /* Set the optional timer. */
922 (void) alarm((unsigned) options.timeout);
924 /* optionally wait for CR or LF before writing /etc/issue */
925 if (options.flags & F_WAITCRLF) {
928 debug("waiting for cr-lf\n");
929 while (read(0, &ch, 1) == 1) {
930 ch &= 0x7f; /* strip "parity bit" */
932 fprintf(dbf, "read %c\n", ch);
934 if (ch == '\n' || ch == '\r')
939 chardata = init_chardata;
940 if (!(options.flags & F_NOPROMPT)) {
941 /* Read the login name. */
942 debug("reading login name\n");
943 /* while ((logname = get_logname(&options, &chardata, &termio)) == 0) */
944 while ((logname = get_logname(&options, &chardata, &termio)) ==
945 NULL) next_speed(&termio, &options);
953 /* Finalize the termio settings. */
955 termio_final(&options, &termio, &chardata);
957 /* Now the newline character should be properly written. */
959 (void) write(1, "\n", 1);
961 /* Let the login program take care of password validation. */
963 (void) execl(options.login, options.login, "--", logname, (char *) 0);
964 error("%s: can't exec %s: %m", options.tty, options.login);