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.
21 #ifdef CONFIG_FEATURE_UTMP
25 #define _PATH_LOGIN "/bin/login"
27 /* If USE_SYSLOG is undefined all diagnostics go directly to /dev/console. */
29 #include <sys/param.h>
35 * Some heuristics to find out what environment we are in: if it is not
36 * System V, assume it is SunOS 4.
39 #ifdef LOGIN_PROCESS /* defined in System V utmp.h */
40 #define SYSV_STYLE /* select System V style getty */
41 #ifdef CONFIG_FEATURE_WTMP
42 extern void updwtmp(const char *filename, const struct utmp *ut);
44 #endif /* LOGIN_PROCESS */
47 * Things you may want to modify.
49 * You may disagree with the default line-editing etc. characters defined
50 * below. Note, however, that DEL cannot be used for interrupt generation
51 * and for line editing at the same time.
55 #include <sys/utsname.h>
59 /* If ISSUE is not defined, agetty will never display the contents of the
60 * /etc/issue file. You will not want to spit out large "issue" files at the
63 #define ISSUE "/etc/issue" /* displayed before the login prompt */
65 /* Some shorthands for control characters. */
67 #define CTL(x) (x ^ 0100) /* Assumes ASCII dialect */
68 #define CR CTL('M') /* carriage return */
69 #define NL CTL('J') /* line feed */
70 #define BS CTL('H') /* back space */
71 #define DEL CTL('?') /* delete */
73 /* Defaults for line-editing etc. characters; you may want to change this. */
75 #define DEF_ERASE DEL /* default erase character */
76 #define DEF_INTR CTL('C') /* default interrupt character */
77 #define DEF_QUIT CTL('\\') /* default quit char */
78 #define DEF_KILL CTL('U') /* default kill char */
79 #define DEF_EOF CTL('D') /* default EOF char */
81 #define DEF_SWITCH 0 /* default switch char */
84 * SunOS 4.1.1 termio is broken. We must use the termios stuff instead,
85 * because the termio -> termios translation does not clear the termios
86 * CIBAUD bits. Therefore, the tty driver would sometimes report that input
87 * baud rate != output baud rate. I did not notice that problem with SunOS
88 * 4.1. We will use termios where available, and termio otherwise.
91 /* linux 0.12 termio is broken too, if we use it c_cc[VERASE] isn't set
92 properly, but all is well if we use termios?! */
98 #define termio termios
100 #define TCSETA TCSETS
101 #define TCSETAW TCSETSW
105 * When multiple baud rates are specified on the command line, the first one
106 * we will try is the first one specified.
109 #define FIRST_SPEED 0
111 /* Storage for command-line options. */
113 #define MAX_SPEED 10 /* max. nr. of baud rates */
116 int flags; /* toggle switches, see below */
117 int timeout; /* time-out period */
118 char *login; /* login program */
119 char *tty; /* name of tty */
120 char *initstring; /* modem init string */
121 char *issue; /* alternative issue file */
122 int numspeed; /* number of baud rates to try */
123 int speeds[MAX_SPEED]; /* baud rates to be tried */
126 static const char opt_string[] = "I:LH:f:hil:mt:wn";
127 #define F_INITSTRING (1<<0) /* initstring is set */
128 #define F_LOCAL (1<<1) /* force local */
129 #define F_FAKEHOST (1<<2) /* force fakehost */
130 #define F_CUSTISSUE (1<<3) /* give alternative issue file */
131 #define F_RTSCTS (1<<4) /* enable RTS/CTS flow control */
132 #define F_ISSUE (1<<5) /* display /etc/issue */
133 #define F_LOGIN (1<<6) /* non-default login program */
134 #define F_PARSE (1<<7) /* process modem status messages */
135 #define F_TIMEOUT (1<<8) /* time out */
136 #define F_WAITCRLF (1<<9) /* wait for CR or LF */
137 #define F_NOPROMPT (1<<10) /* don't ask for login name! */
139 /* Storage for things detected while the login name was read. */
142 int erase; /* erase character */
143 int kill; /* kill character */
144 int eol; /* end-of-line character */
145 int parity; /* what parity did we see */
146 int capslock; /* upper case without lower case */
149 /* Initial values for the above. */
151 static struct chardata init_chardata = {
152 DEF_ERASE, /* default erase character */
153 DEF_KILL, /* default kill character */
154 13, /* default eol char */
155 0, /* space parity */
165 static struct Speedtab speedtab[] = {
206 #ifdef CONFIG_FEATURE_UTMP
207 static void update_utmp(char *line);
211 /* The following is used for understandable diagnostics. */
213 /* Fake hostname for ut_host specified on command line. */
214 static char *fakehost = NULL;
218 #define debug(s) fprintf(dbf,s); fflush(dbf)
219 #define DEBUGTERM "/dev/ttyp0"
222 #define debug(s) /* nothing */
227 * output error messages
229 static void error(const char *fmt, ...) ATTRIBUTE_NORETURN;
230 static void error(const char *fmt, ...)
235 #ifdef CONFIG_SYSLOGD
236 va_start(va_alist, fmt);
237 vsnprintf(buf, sizeof(buf), fmt, va_alist);
238 openlog(bb_applet_name, 0, LOG_AUTH);
239 syslog(LOG_ERR, "%s", buf);
245 snprintf(buf, sizeof(buf), "%s: ", bb_applet_name);
247 va_start(va_alist, fmt);
248 vsnprintf(buf + l, sizeof(buf) - l, fmt, va_alist);
250 /* truncate if need */
251 if((l + 3) > sizeof(buf))
253 /* add \r\n always */
257 if ((fd = open("/dev/console", 1)) >= 0) {
265 (void) sleep((unsigned) 10); /* be kind to init(8) */
271 /* bcode - convert speed string to speed code; return 0 on failure */
272 static int bcode(const char *s)
276 if (safe_strtoul((char *)s, &value)) {
279 if ((r = tty_value_to_baud(value)) > 0) {
286 /* parse_speeds - parse alternate baud rates */
287 static void parse_speeds(struct options *op, char *arg)
291 debug("entered parse_speeds\n");
292 for (cp = strtok(arg, ","); cp != 0; cp = strtok((char *) 0, ",")) {
293 if ((op->speeds[op->numspeed++] = bcode(cp)) <= 0)
294 error("bad speed: %s", cp);
295 if (op->numspeed > MAX_SPEED)
296 error("too many alternate speeds");
298 debug("exiting parsespeeds\n");
302 /* parse-args - parse command-line arguments */
303 static void parse_args(int argc, char **argv, struct options *op)
307 op->flags = bb_getopt_ulflags(argc, argv, opt_string,
308 &(op->initstring), &fakehost, &(op->issue),
310 if(op->flags & F_INITSTRING) {
311 const char *p = op->initstring;
314 q = op->initstring = xstrdup(op->initstring);
315 /* copy optarg into op->initstring decoding \ddd
316 octal codes into chars */
320 *q++ = bb_process_escape_sequence(&p);
327 op->flags ^= F_ISSUE; /* revert flag show /etc/issue */
328 if(op->flags & F_TIMEOUT) {
329 if ((op->timeout = atoi(ts)) <= 0)
330 error("bad timeout value: %s", ts);
332 debug("after getopt loop\n");
333 if (argc < optind + 2) /* check parameter count */
336 /* we loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
337 if ('0' <= argv[optind][0] && argv[optind][0] <= '9') {
338 /* a number first, assume it's a speed (BSD style) */
339 parse_speeds(op, argv[optind++]); /* baud rate(s) */
340 op->tty = argv[optind]; /* tty name */
342 op->tty = argv[optind++]; /* tty name */
343 parse_speeds(op, argv[optind]); /* baud rate(s) */
347 if (argc > optind && argv[optind])
348 setenv("TERM", argv[optind], 1);
350 debug("exiting parseargs\n");
353 /* open_tty - set up tty as standard { input, output, error } */
354 static void open_tty(char *tty, struct termio *tp, int local)
356 int chdir_to_root = 0;
358 /* Set up new standard input, unless we are given an already opened port. */
360 if (strcmp(tty, "-")) {
364 /* Sanity checks... */
367 error("/dev: chdir() failed: %m");
369 if (stat(tty, &st) < 0)
370 error("/dev/%s: %m", tty);
371 if ((st.st_mode & S_IFMT) != S_IFCHR)
372 error("/dev/%s: not a character device", tty);
374 /* Open the tty as standard input. */
378 fd = open(tty, O_RDWR | O_NONBLOCK, 0);
380 error("/dev/%s: cannot open as standard input: %m", tty);
384 * Standard input should already be connected to an open port. Make
385 * sure it is open for read/write.
388 if ((fcntl(0, F_GETFL, 0) & O_RDWR) != O_RDWR)
389 error("%s: not open for read/write", tty);
392 /* Replace current standard output/error fd's with new ones */
394 if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1 ||
395 dup2(STDIN_FILENO, STDERR_FILENO) == -1)
396 error("%s: dup problem: %m", tty); /* we have a problem */
399 * The following ioctl will fail if stdin is not a tty, but also when
400 * there is noise on the modem control lines. In the latter case, the
401 * common course of action is (1) fix your cables (2) give the modem more
402 * time to properly reset after hanging up. SunOS users can achieve (2)
403 * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
404 * 5 seconds seems to be a good value.
407 if (ioctl(0, TCGETA, tp) < 0)
408 error("%s: ioctl: %m", tty);
411 * It seems to be a terminal. Set proper protections and ownership. Mode
412 * 0622 is suitable for SYSV <4 because /bin/login does not change
413 * protections. SunOS 4 login will change the protections to 0620 (write
414 * access for group tty) after the login has succeeded.
419 /* tty to root.dialout 660 */
423 id = (gr = getgrnam("dialout")) ? gr->gr_gid : 0;
427 /* vcs,vcsa to root.sys 600 */
428 if (!strncmp(tty, "tty", 3) && isdigit(tty[3])) {
431 if (!(vcs = strdup(tty)))
432 error("Can't malloc for vcs");
433 if (!(vcsa = malloc(strlen(tty) + 2)))
434 error("Can't malloc for vcsa");
436 strcpy(vcs + 3, tty + 3);
437 strcpy(vcsa, "vcsa");
438 strcpy(vcsa + 4, tty + 3);
440 id = (gr = getgrnam("sys")) ? gr->gr_gid : 0;
451 (void) chown(tty, 0, 0); /* root, sys */
452 (void) chmod(tty, 0622); /* crw--w--w- */
454 if(chdir_to_root && chdir("/"))
455 error("chdir to / failed: %m");
458 /* termio_init - initialize termio settings */
459 static void termio_init(struct termio *tp, int speed, struct options *op)
462 * Initial termio settings: 8-bit characters, raw-mode, blocking i/o.
463 * Special characters are set after we have read the login name; all
464 * reads will be done in raw mode anyway. Errors will be dealt with
468 /* flush input and output queues, important for modems! */
469 (void) ioctl(0, TCFLSH, TCIOFLUSH);
472 tp->c_cflag = CS8 | HUPCL | CREAD | speed;
473 if (op->flags & F_LOCAL) {
474 tp->c_cflag |= CLOCAL;
477 tp->c_iflag = tp->c_lflag = tp->c_oflag = tp->c_line = 0;
481 /* Optionally enable hardware flow control */
484 if (op->flags & F_RTSCTS)
485 tp->c_cflag |= CRTSCTS;
488 (void) ioctl(0, TCSETA, tp);
490 /* go to blocking input even in local mode */
491 fcntl(0, F_SETFL, fcntl(0, F_GETFL, 0) & ~O_NONBLOCK);
493 debug("term_io 2\n");
496 /* auto_baud - extract baud rate from modem status message */
497 static void auto_baud(struct termio *tp)
507 * This works only if the modem produces its status code AFTER raising
508 * the DCD line, and if the computer is fast enough to set the proper
509 * baud rate before the message has gone by. We expect a message of the
512 * <junk><number><junk>
514 * The number is interpreted as the baud rate of the incoming call. If the
515 * modem does not tell us the baud rate within one second, we will keep
516 * using the current baud rate. It is advisable to enable BREAK
517 * processing (comma-separated list of baud rates) if the processing of
518 * modem status messages is enabled.
522 * Use 7-bit characters, don't block if input queue is empty. Errors will
523 * be dealt with lateron.
527 tp->c_iflag |= ISTRIP; /* enable 8th-bit stripping */
528 vmin = tp->c_cc[VMIN];
529 tp->c_cc[VMIN] = 0; /* don't block if queue empty */
530 (void) ioctl(0, TCSETA, tp);
533 * Wait for a while, then read everything the modem has said so far and
534 * try to extract the speed of the dial-in call.
538 if ((nread = read(0, buf, sizeof(buf) - 1)) > 0) {
540 for (bp = buf; bp < buf + nread; bp++) {
541 if (isascii(*bp) && isdigit(*bp)) {
542 if ((speed = bcode(bp))) {
543 tp->c_cflag &= ~CBAUD;
544 tp->c_cflag |= speed;
550 /* Restore terminal settings. Errors will be dealt with lateron. */
553 tp->c_cc[VMIN] = vmin;
554 (void) ioctl(0, TCSETA, tp);
557 /* next_speed - select next baud rate */
558 static void next_speed(struct termio *tp, struct options *op)
560 static int baud_index = FIRST_SPEED; /* current speed index */
562 baud_index = (baud_index + 1) % op->numspeed;
563 tp->c_cflag &= ~CBAUD;
564 tp->c_cflag |= op->speeds[baud_index];
565 (void) ioctl(0, TCSETA, tp);
569 /* do_prompt - show login prompt, optionally preceded by /etc/issue contents */
570 static void do_prompt(struct options *op, struct termio *tp)
572 #ifdef ISSUE /* optional: show /etc/issue */
573 print_login_issue(op->issue, op->tty);
575 print_login_prompt();
578 /* caps_lock - string contains upper case without lower case */
579 /* returns 1 if true, 0 if false */
580 static int caps_lock(const char *s)
584 for (capslock = 0; *s; s++) {
588 capslock = isupper(*s);
593 #define logname bb_common_bufsiz1
594 /* get_logname - get user name, establish parity, speed, erase, kill, eol */
595 /* return NULL on failure, logname on success */
596 static char *get_logname(struct options *op, struct chardata *cp, struct termio *tp)
599 char c; /* input character, full eight bits */
600 char ascval; /* low 7 bits of input character */
601 int bits; /* # of "1" bits per character */
602 int mask; /* mask with 1 bit up */
603 static char *erase[] = { /* backspace-space-backspace */
604 "\010\040\010", /* space parity */
605 "\010\040\010", /* odd parity */
606 "\210\240\210", /* even parity */
607 "\210\240\210", /* no parity */
610 /* Initialize kill, erase, parity etc. (also after switching speeds). */
614 /* Flush pending input (esp. after parsing or switching the baud rate). */
617 (void) ioctl(0, TCFLSH, TCIFLUSH);
619 /* Prompt for and read a login name. */
621 for (*logname = 0; *logname == 0; /* void */ ) {
623 /* Write issue file and prompt, with "parity" bit == 0. */
627 /* Read name, watch for break, parity, erase, kill, end-of-line. */
629 for (bp = logname, cp->eol = 0; cp->eol == 0; /* void */ ) {
631 /* Do not report trivial EINTR/EIO errors. */
633 if (read(0, &c, 1) < 1) {
634 if (errno == EINTR || errno == EIO)
636 error("%s: read: %m", op->tty);
638 /* Do BREAK handling elsewhere. */
640 if ((c == 0) && op->numspeed > 1)
644 /* Do parity bit handling. */
646 if (c != (ascval = (c & 0177))) { /* "parity" bit on ? */
647 for (bits = 1, mask = 1; mask & 0177; mask <<= 1)
649 bits++; /* count "1" bits */
650 cp->parity |= ((bits & 1) ? 1 : 2);
652 /* Do erase, kill and end-of-line processing. */
657 *bp = 0; /* terminate logname */
658 cp->eol = ascval; /* set end-of-line char */
663 cp->erase = ascval; /* set erase character */
665 (void) write(1, erase[cp->parity], 3);
671 cp->kill = ascval; /* set kill character */
672 while (bp > logname) {
673 (void) write(1, erase[cp->parity], 3);
680 if (!isascii(ascval) || !isprint(ascval)) {
681 /* ignore garbage characters */ ;
682 } else if (bp - logname >= sizeof(logname) - 1) {
683 error("%s: input overrun", op->tty);
685 (void) write(1, &c, 1); /* echo the character */
686 *bp++ = ascval; /* and store it */
692 /* Handle names with upper case and no lower case. */
694 if ((cp->capslock = caps_lock(logname))) {
695 for (bp = logname; *bp; bp++)
697 *bp = tolower(*bp); /* map name to lower case */
702 /* termio_final - set the final tty mode bits */
703 static void termio_final(struct options *op, struct termio *tp, struct chardata *cp)
705 /* General terminal-independent stuff. */
707 tp->c_iflag |= IXON | IXOFF; /* 2-way flow control */
708 tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
709 /* no longer| ECHOCTL | ECHOPRT */
710 tp->c_oflag |= OPOST;
711 /* tp->c_cflag = 0; */
712 tp->c_cc[VINTR] = DEF_INTR; /* default interrupt */
713 tp->c_cc[VQUIT] = DEF_QUIT; /* default quit */
714 tp->c_cc[VEOF] = DEF_EOF; /* default EOF character */
715 tp->c_cc[VEOL] = DEF_EOL;
716 tp->c_cc[VSWTC] = DEF_SWITCH; /* default switch character */
718 /* Account for special characters seen in input. */
721 tp->c_iflag |= ICRNL; /* map CR in input to NL */
722 tp->c_oflag |= ONLCR; /* map NL in output to CR-NL */
724 tp->c_cc[VERASE] = cp->erase; /* set erase character */
725 tp->c_cc[VKILL] = cp->kill; /* set kill character */
727 /* Account for the presence or absence of parity bits in input. */
729 switch (cp->parity) {
730 case 0: /* space (always 0) parity */
732 case 1: /* odd parity */
733 tp->c_cflag |= PARODD;
735 case 2: /* even parity */
736 tp->c_cflag |= PARENB;
737 tp->c_iflag |= INPCK | ISTRIP;
739 case (1 | 2): /* no parity bit */
740 tp->c_cflag &= ~CSIZE;
744 /* Account for upper case without lower case. */
747 tp->c_iflag |= IUCLC;
748 tp->c_lflag |= XCASE;
749 tp->c_oflag |= OLCUC;
751 /* Optionally enable hardware flow control */
754 if (op->flags & F_RTSCTS)
755 tp->c_cflag |= CRTSCTS;
758 /* Finally, make the new settings effective */
760 if (ioctl(0, TCSETA, tp) < 0)
761 error("%s: ioctl: TCSETA: %m", op->tty);
766 #ifdef CONFIG_FEATURE_UTMP
767 /* update_utmp - update our utmp entry */
768 static void update_utmp(char *line)
773 int mypid = getpid();
774 #if ! (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1))
779 * The utmp file holds miscellaneous information about things started by
780 * /sbin/init and other system-related events. Our purpose is to update
781 * the utmp entry for the current process, in particular the process type
782 * and the tty line we are listening to. Return successfully only if the
783 * utmp file can be opened for update, and if we are able to find our
784 * entry in the utmp file.
786 if (access(_PATH_UTMP, R_OK|W_OK) == -1) {
787 close(creat(_PATH_UTMP, 0664));
789 utmpname(_PATH_UTMP);
791 while ((utp = getutent())
792 && !(utp->ut_type == INIT_PROCESS && utp->ut_pid == mypid)) /* nothing */
796 memcpy(&ut, utp, sizeof(ut));
798 /* some inits don't initialize utmp... */
799 memset(&ut, 0, sizeof(ut));
800 safe_strncpy(ut.ut_id, line + 3, sizeof(ut.ut_id));
804 strcpy(ut.ut_user, "LOGIN");
805 safe_strncpy(ut.ut_line, line, sizeof(ut.ut_line));
807 safe_strncpy(ut.ut_host, fakehost, sizeof(ut.ut_host));
810 ut.ut_type = LOGIN_PROCESS;
816 #ifdef CONFIG_FEATURE_WTMP
817 if (access(bb_path_wtmp_file, R_OK|W_OK) == -1)
818 close(creat(bb_path_wtmp_file, 0664));
819 updwtmp(bb_path_wtmp_file, &ut);
823 #endif /* CONFIG_FEATURE_UTMP */
824 #endif /* SYSV_STYLE */
828 int getty_main(int argc, char **argv)
830 char *logname = NULL; /* login name, given to /bin/login */
831 struct chardata chardata; /* set by get_logname() */
832 struct termio termio; /* terminal mode bits */
833 static struct options options = {
834 0, /* show /etc/issue (SYSV_STYLE) */
836 _PATH_LOGIN, /* default login program */
837 "tty1", /* default tty line */
838 "", /* modem init string */
840 ISSUE, /* default issue file */
844 0, /* no baud rates known yet */
848 dbf = xfopen(DEBUGTERM, "w");
853 for (i = 1; i < argc; i++) {
860 /* Parse command-line arguments. */
862 parse_args(argc, argv, &options);
868 /* Update the utmp file. */
872 #ifdef CONFIG_FEATURE_UTMP
873 update_utmp(options.tty);
877 debug("calling open_tty\n");
878 /* Open the tty as standard { input, output, error }. */
879 open_tty(options.tty, &termio, options.flags & F_LOCAL);
886 ioctl(0, TIOCSPGRP, &iv);
889 /* Initialize the termio settings (raw mode, eight-bit, blocking i/o). */
890 debug("calling termio_init\n");
891 termio_init(&termio, options.speeds[FIRST_SPEED], &options);
893 /* write the modem init string and DON'T flush the buffers */
894 if (options.flags & F_INITSTRING) {
895 debug("writing init string\n");
896 write(1, options.initstring, strlen(options.initstring));
899 if (!(options.flags & F_LOCAL)) {
900 /* go to blocking write mode unless -L is specified */
901 fcntl(1, F_SETFL, fcntl(1, F_GETFL, 0) & ~O_NONBLOCK);
904 /* Optionally detect the baud rate from the modem status message. */
905 debug("before autobaud\n");
906 if (options.flags & F_PARSE)
909 /* Set the optional timer. */
911 (void) alarm((unsigned) options.timeout);
913 /* optionally wait for CR or LF before writing /etc/issue */
914 if (options.flags & F_WAITCRLF) {
917 debug("waiting for cr-lf\n");
918 while (read(0, &ch, 1) == 1) {
919 ch &= 0x7f; /* strip "parity bit" */
921 fprintf(dbf, "read %c\n", ch);
923 if (ch == '\n' || ch == '\r')
928 chardata = init_chardata;
929 if (!(options.flags & F_NOPROMPT)) {
930 /* Read the login name. */
931 debug("reading login name\n");
932 /* while ((logname = get_logname(&options, &chardata, &termio)) == 0) */
933 while ((logname = get_logname(&options, &chardata, &termio)) ==
934 NULL) next_speed(&termio, &options);
942 /* Finalize the termio settings. */
944 termio_final(&options, &termio, &chardata);
946 /* Now the newline character should be properly written. */
948 (void) write(1, "\n", 1);
950 /* Let the login program take care of password validation. */
952 (void) execl(options.login, options.login, "--", logname, (char *) 0);
953 error("%s: can't exec %s: %m", options.tty, options.login);