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 #if ENABLE_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.
30 #ifdef LOGIN_PROCESS /* defined in System V utmp.h */
31 #include <sys/utsname.h>
33 #if ENABLE_FEATURE_WTMP
34 extern void updwtmp(const char *filename, const struct utmp *ut);
36 #else /* if !sysV style, wtmp/utmp code is off */
37 #undef ENABLE_FEATURE_UTMP
38 #undef ENABLE_FEATURE_WTMP
39 #define ENABLE_FEATURE_UTMP 0
40 #define ENABLE_FEATURE_WTMP 0
41 #endif /* LOGIN_PROCESS */
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 */
53 #undef ANCIENT_BS_KILL_CHARS
55 #define _PATH_LOGIN "/bin/login"
57 /* If ISSUE is not defined, getty will never display the contents of the
58 * /etc/issue file. You will not want to spit out large "issue" files at the
61 #define ISSUE "/etc/issue" /* displayed before the login prompt */
63 /* 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. */
71 #define DEF_ERASE DEL /* default erase character */
72 #define DEF_INTR CTL('C') /* default interrupt character */
73 #define DEF_QUIT CTL('\\') /* default quit char */
74 #define DEF_KILL CTL('U') /* default kill char */
75 #define DEF_EOF CTL('D') /* default EOF char */
77 #define DEF_SWITCH 0 /* default switch char */
80 * When multiple baud rates are specified on the command line, the first one
81 * we will try is the first one specified.
83 #define MAX_SPEED 10 /* max. nr. of baud rates */
85 /* Storage for command-line options. */
87 int flags; /* toggle switches, see below */
88 unsigned timeout; /* time-out period */
89 const char *login; /* login program */
90 const char *tty; /* name of tty */
91 const char *initstring; /* modem init string */
92 const char *issue; /* alternative issue file */
93 int numspeed; /* number of baud rates to try */
94 int speeds[MAX_SPEED]; /* baud rates to be tried */
97 /* Storage for things detected while the login name was read. */
99 unsigned char erase; /* erase character */
100 unsigned char kill; /* kill character */
101 unsigned char eol; /* end-of-line character */
102 unsigned char parity; /* what parity did we see */
103 /* (parity & 1): saw odd parity char with 7th bit set */
104 /* (parity & 2): saw even parity char with 7th bit set */
105 /* parity == 0: probably 7-bit, space parity? */
106 /* parity == 1: probably 7-bit, odd parity? */
107 /* parity == 2: probably 7-bit, even parity? */
108 /* parity == 3: definitely 8 bit, no parity! */
109 /* Hmm... with any value of "parity" 8 bit, no parity is possible */
110 #ifdef HANDLE_ALLCAPS
111 unsigned char capslock; /* upper case without lower case */
116 /* Initial values for the above. */
117 static const struct chardata init_chardata = {
118 DEF_ERASE, /* default erase character */
119 DEF_KILL, /* default kill character */
120 13, /* default eol char */
121 0, /* space parity */
122 #ifdef HANDLE_ALLCAPS
127 static const char opt_string[] ALIGN1 = "I:LH:f:hil:mt:wn";
128 #define F_INITSTRING (1 << 0) /* -I initstring is set */
129 #define F_LOCAL (1 << 1) /* -L force local */
130 #define F_FAKEHOST (1 << 2) /* -H fake hostname */
131 #define F_CUSTISSUE (1 << 3) /* -f give alternative issue file */
132 #define F_RTSCTS (1 << 4) /* -h enable RTS/CTS flow control */
133 #define F_ISSUE (1 << 5) /* -i display /etc/issue */
134 #define F_LOGIN (1 << 6) /* -l non-default login program */
135 #define F_PARSE (1 << 7) /* -m process modem status messages */
136 #define F_TIMEOUT (1 << 8) /* -t time out */
137 #define F_WAITCRLF (1 << 9) /* -w wait for CR or LF */
138 #define F_NOPROMPT (1 << 10) /* -n don't ask for login name */
141 #define line_buf bb_common_bufsiz1
143 /* The following is used for understandable diagnostics. */
146 #define DEBUGTERM "/dev/ttyp0"
147 #define debug(...) do { fprintf(dbf, __VA_ARGS__); fflush(dbf); } while (0)
149 #define debug(...) ((void)0)
153 /* bcode - convert speed string to speed code; return <= 0 on failure */
154 static int bcode(const char *s)
156 int value = bb_strtou(s, NULL, 10); /* yes, int is intended! */
157 if (value < 0) /* bad terminating char, overflow, etc */
159 return tty_value_to_baud(value);
162 /* parse_speeds - parse alternate baud rates */
163 static void parse_speeds(struct options *op, char *arg)
167 /* NB: at least one iteration is always done */
168 debug("entered parse_speeds\n");
169 while ((cp = strsep(&arg, ",")) != NULL) {
170 op->speeds[op->numspeed] = bcode(cp);
171 if (op->speeds[op->numspeed] <= 0)
172 bb_error_msg_and_die("bad speed: %s", cp);
174 if (op->numspeed > MAX_SPEED)
175 bb_error_msg_and_die("too many alternate speeds");
177 debug("exiting parse_speeds\n");
180 /* parse_args - parse command-line arguments */
181 static void parse_args(char **argv, struct options *op, char **fakehost_p)
185 opt_complementary = "-2:t+"; /* at least 2 args; -t N */
186 op->flags = getopt32(argv, opt_string,
187 &(op->initstring), fakehost_p, &(op->issue),
188 &(op->login), &op->timeout);
190 if (op->flags & F_INITSTRING) {
191 const char *p = op->initstring;
194 op->initstring = q = xstrdup(p);
195 /* copy optarg into op->initstring decoding \ddd
196 octal codes into chars */
200 *q++ = bb_process_escape_sequence(&p);
207 op->flags ^= F_ISSUE; /* invert flag "show /etc/issue" */
208 debug("after getopt\n");
210 /* we loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
211 op->tty = argv[0]; /* tty name */
212 ts = argv[1]; /* baud rate(s) */
213 if (isdigit(argv[0][0])) {
214 /* a number first, assume it's a speed (BSD style) */
215 op->tty = ts; /* tty name is in argv[1] */
216 ts = argv[0]; /* baud rate(s) */
218 parse_speeds(op, ts);
220 // TODO: if applet_name is set to "getty: TTY", bb_error_msg's get simpler!
224 xsetenv("TERM", argv[2]);
226 debug("exiting parse_args\n");
229 /* open_tty - set up tty as standard { input, output, error } */
230 static void open_tty(const char *tty)
232 /* Set up new standard input, unless we are given an already opened port. */
233 if (NOT_LONE_DASH(tty)) {
238 /* Sanity checks... */
239 // cur_dir_fd = xopen(".", O_DIRECTORY | O_NONBLOCK);
242 // if ((st.st_mode & S_IFMT) != S_IFCHR)
243 // bb_error_msg_and_die("%s: not a character device", tty);
246 tty = xasprintf("/dev/%s", tty); /* will leak it */
248 /* Open the tty as standard input. */
251 /*fd =*/ xopen(tty, O_RDWR | O_NONBLOCK); /* uses fd 0 */
253 // /* Restore current directory */
254 // fchdir(cur_dir_fd);
256 /* Open the tty as standard input, continued */
258 // /* fd is >= cur_dir_fd, and cur_dir_fd gets closed too here: */
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_RDWR)
271 bb_error_msg_and_die("stdin is not open for read/write");
275 /* termios_init - initialize termios settings */
276 static void termios_init(struct termios *tp, int speed, struct options *op)
279 * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
280 * Special characters are set after we have read the login name; all
281 * reads will be done in raw mode anyway. Errors will be dealt with
285 /* flush input and output queues, important for modems! */
286 ioctl(0, TCFLSH, TCIOFLUSH);
289 tp->c_cflag = CS8 | HUPCL | CREAD | speed;
290 if (op->flags & F_LOCAL)
291 tp->c_cflag |= CLOCAL;
293 tp->c_iflag = tp->c_lflag = tp->c_line = 0;
294 tp->c_oflag = OPOST | ONLCR;
298 /* Optionally enable hardware flow control */
300 if (op->flags & F_RTSCTS)
301 tp->c_cflag |= CRTSCTS;
304 ioctl(0, TCSETS, tp);
306 debug("term_io 2\n");
309 /* auto_baud - extract baud rate from modem status message */
310 static void auto_baud(char *buf, unsigned size_buf, struct termios *tp)
319 * This works only if the modem produces its status code AFTER raising
320 * the DCD line, and if the computer is fast enough to set the proper
321 * baud rate before the message has gone by. We expect a message of the
324 * <junk><number><junk>
326 * The number is interpreted as the baud rate of the incoming call. If the
327 * modem does not tell us the baud rate within one second, we will keep
328 * using the current baud rate. It is advisable to enable BREAK
329 * processing (comma-separated list of baud rates) if the processing of
330 * modem status messages is enabled.
334 * Use 7-bit characters, don't block if input queue is empty. Errors will
335 * be dealt with later on.
338 tp->c_iflag |= ISTRIP; /* enable 8th-bit stripping */
339 vmin = tp->c_cc[VMIN];
340 tp->c_cc[VMIN] = 0; /* don't block if queue empty */
341 ioctl(0, TCSETS, tp);
344 * Wait for a while, then read everything the modem has said so far and
345 * try to extract the speed of the dial-in call.
348 nread = safe_read(0, buf, size_buf - 1);
351 for (bp = buf; bp < buf + nread; bp++) {
355 tp->c_cflag &= ~CBAUD;
356 tp->c_cflag |= speed;
363 /* Restore terminal settings. Errors will be dealt with later on. */
365 tp->c_cc[VMIN] = vmin;
366 ioctl(0, TCSETS, tp);
369 /* do_prompt - show login prompt, optionally preceded by /etc/issue contents */
370 static void do_prompt(struct options *op)
373 print_login_issue(op->issue, op->tty);
375 print_login_prompt();
378 #ifdef HANDLE_ALLCAPS
379 /* all_is_upcase - string contains upper case without lower case */
380 /* returns 1 if true, 0 if false */
381 static int all_is_upcase(const char *s)
390 /* get_logname - get user name, establish parity, speed, erase, kill, eol;
391 * return NULL on BREAK, logname on success */
392 static char *get_logname(char *logname, unsigned size_logname,
393 struct options *op, struct chardata *cp)
396 char c; /* input character, full eight bits */
397 char ascval; /* low 7 bits of input character */
398 int bits; /* # of "1" bits per character */
399 int mask; /* mask with 1 bit up */
400 static const char erase[][3] = {/* backspace-space-backspace */
401 "\010\040\010", /* space parity */
402 "\010\040\010", /* odd parity */
403 "\210\240\210", /* even parity */
404 "\010\040\010", /* 8 bit no parity */
407 /* NB: *cp is pre-initialized with init_chardata */
409 /* Flush pending input (esp. after parsing or switching the baud rate). */
411 ioctl(0, TCFLSH, TCIFLUSH);
413 /* Prompt for and read a login name. */
415 while (!logname[0]) {
416 /* Write issue file and prompt, with "parity" bit == 0. */
419 /* Read name, watch for break, parity, erase, kill, end-of-line. */
422 while (cp->eol == '\0') {
424 /* Do not report trivial EINTR/EIO errors. */
425 if (read(0, &c, 1) < 1) {
426 if (errno == EINTR || errno == EIO)
428 bb_perror_msg_and_die("%s: read", op->tty);
431 /* BREAK. If we have speeds to try,
432 * return NULL (will switch speeds and return here) */
433 if (c == '\0' && op->numspeed > 1)
436 /* Do parity bit handling. */
437 if (!(op->flags & F_LOCAL) && (c & 0x80)) { /* "parity" bit on? */
440 while (mask & 0x7f) {
442 bits++; /* count "1" bits */
445 /* ... |= 2 - even, 1 - odd */
446 cp->parity |= 2 - (bits & 1);
449 /* Do erase, kill and end-of-line processing. */
454 *bp = '\0'; /* terminate logname */
455 cp->eol = ascval; /* set end-of-line char */
459 #ifdef ANCIENT_BS_KILL_CHARS
462 cp->erase = ascval; /* set erase character */
464 full_write(1, erase[cp->parity], 3);
469 #ifdef ANCIENT_BS_KILL_CHARS
472 cp->kill = ascval; /* set kill character */
473 while (bp > logname) {
474 full_write(1, erase[cp->parity], 3);
481 if (!isascii(ascval) || !isprint(ascval)) {
482 /* ignore garbage characters */
483 } else if (bp - logname >= size_logname - 1) {
484 bb_error_msg_and_die("%s: input overrun", op->tty);
486 full_write(1, &c, 1); /* echo the character */
487 *bp++ = ascval; /* and store it */
493 /* Handle names with upper case and no lower case. */
495 #ifdef HANDLE_ALLCAPS
496 cp->capslock = all_is_upcase(logname);
498 for (bp = logname; *bp; bp++)
500 *bp = tolower(*bp); /* map name to lower case */
506 /* termios_final - set the final tty mode bits */
507 static void termios_final(struct options *op, struct termios *tp, struct chardata *cp)
509 /* General terminal-independent stuff. */
510 tp->c_iflag |= IXON | IXOFF; /* 2-way flow control */
511 tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
512 /* no longer| ECHOCTL | ECHOPRT */
513 tp->c_oflag |= OPOST;
514 /* tp->c_cflag = 0; */
515 tp->c_cc[VINTR] = DEF_INTR; /* default interrupt */
516 tp->c_cc[VQUIT] = DEF_QUIT; /* default quit */
517 tp->c_cc[VEOF] = DEF_EOF; /* default EOF character */
518 tp->c_cc[VEOL] = DEF_EOL;
519 tp->c_cc[VSWTC] = DEF_SWITCH; /* default switch character */
521 /* Account for special characters seen in input. */
523 tp->c_iflag |= ICRNL; /* map CR in input to NL */
524 tp->c_oflag |= ONLCR; /* map NL in output to CR-NL */
526 tp->c_cc[VERASE] = cp->erase; /* set erase character */
527 tp->c_cc[VKILL] = cp->kill; /* set kill character */
529 /* Account for the presence or absence of parity bits in input. */
530 switch (cp->parity) {
531 case 0: /* space (always 0) parity */
532 // I bet most people go here - they use only 7-bit chars in usernames....
534 case 1: /* odd parity */
535 tp->c_cflag |= PARODD;
537 case 2: /* even parity */
538 tp->c_cflag |= PARENB;
539 tp->c_iflag |= INPCK | ISTRIP;
541 case (1 | 2): /* no parity bit */
542 tp->c_cflag &= ~CSIZE;
544 // FIXME: wtf? case 3: we saw both even and odd 8-bit bytes -
545 // it's probably some umlauts etc, but definitely NOT 7-bit!!!
546 // Entire parity detection madness here just begs for deletion...
550 /* Account for upper case without lower case. */
551 #ifdef HANDLE_ALLCAPS
553 tp->c_iflag |= IUCLC;
554 tp->c_lflag |= XCASE;
555 tp->c_oflag |= OLCUC;
558 /* Optionally enable hardware flow control */
560 if (op->flags & F_RTSCTS)
561 tp->c_cflag |= CRTSCTS;
564 /* Finally, make the new settings effective */
565 ioctl_or_perror_and_die(0, TCSETS, tp, "%s: TCSETS", op->tty);
568 #if ENABLE_FEATURE_UTMP
569 static void touch(const char *filename)
571 if (access(filename, R_OK | W_OK) == -1)
572 close(open(filename, O_WRONLY | O_CREAT, 0664));
575 /* update_utmp - update our utmp entry */
576 static void update_utmp(const char *line, char *fakehost)
580 int mypid = getpid();
582 /* In case we won't find an entry below... */
583 memset(&ut, 0, sizeof(ut));
584 safe_strncpy(ut.ut_id, line + 3, sizeof(ut.ut_id));
587 * The utmp file holds miscellaneous information about things started by
588 * /sbin/init and other system-related events. Our purpose is to update
589 * the utmp entry for the current process, in particular the process type
590 * and the tty line we are listening to. Return successfully only if the
591 * utmp file can be opened for update, and if we are able to find our
592 * entry in the utmp file.
596 utmpname(_PATH_UTMP);
598 while ((utp = getutent()) != NULL) {
599 if (utp->ut_type == INIT_PROCESS && utp->ut_pid == mypid) {
600 memcpy(&ut, utp, sizeof(ut));
605 strcpy(ut.ut_user, "LOGIN");
606 safe_strncpy(ut.ut_line, line, sizeof(ut.ut_line));
608 safe_strncpy(ut.ut_host, fakehost, sizeof(ut.ut_host));
609 ut.ut_time = time(NULL);
610 ut.ut_type = LOGIN_PROCESS;
616 #if ENABLE_FEATURE_WTMP
617 touch(bb_path_wtmp_file);
618 updwtmp(bb_path_wtmp_file, &ut);
621 #endif /* CONFIG_FEATURE_UTMP */
623 int getty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
624 int getty_main(int argc ATTRIBUTE_UNUSED, char **argv)
627 char *fakehost = NULL; /* Fake hostname for ut_host */
628 char *logname; /* login name, given to /bin/login */
629 /* Merging these into "struct local" may _seem_ to reduce
630 * parameter passing, but today's gcc will inline
631 * statics which are called once anyway, so don't do that */
632 struct chardata chardata; /* set by get_logname() */
633 struct termios termios; /* terminal mode bits */
634 struct options options;
636 chardata = init_chardata;
638 memset(&options, 0, sizeof(options));
639 options.login = _PATH_LOGIN; /* default login program */
640 options.tty = "tty1"; /* default tty line */
641 options.initstring = ""; /* modem init string */
643 options.issue = ISSUE; /* default issue file */
646 /* Parse command-line arguments. */
647 parse_args(argv, &options, &fakehost);
649 logmode = LOGMODE_NONE;
651 /* Create new session, lose controlling tty, if any */
652 /* docs/ctty.htm says:
653 * "This is allowed only when the current process
654 * is not a process group leader" - is this a problem? */
656 /* close stdio, and stray descriptors, just in case */
657 n = xopen(bb_dev_null, O_RDWR);
658 /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
664 /* Logging. We want special flavor of error_msg_and_die */
667 /* most likely will internally use fd #3 in CLOEXEC mode: */
668 openlog(applet_name, LOG_PID, LOG_AUTH);
669 logmode = LOGMODE_BOTH;
672 dbf = xfopen(DEBUGTERM, "w");
673 for (n = 1; argv[n]; n++) {
679 /* Open the tty as standard input, if it is not "-" */
680 /* If it's not "-" and not taken yet, it will become our ctty */
681 debug("calling open_tty\n");
682 open_tty(options.tty);
689 * The following ioctl will fail if stdin is not a tty, but also when
690 * there is noise on the modem control lines. In the latter case, the
691 * common course of action is (1) fix your cables (2) give the modem more
692 * time to properly reset after hanging up. SunOS users can achieve (2)
693 * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
694 * 5 seconds seems to be a good value.
696 ioctl_or_perror_and_die(0, TCGETS, &termios, "%s: TCGETS", options.tty);
699 // FIXME: do we need this? Otherwise "-" case seems to be broken...
700 // /* Forcibly make fd 0 our controlling tty, even if another session
701 // * has it as a ctty. (Another session loses ctty). */
702 // ioctl(0, TIOCSCTTY, (void*)1);
703 /* Make ourself a foreground process group within our session */
704 tcsetpgrp(0, getpid());
707 #if ENABLE_FEATURE_UTMP
708 /* Update the utmp file. This tty is ours now! */
709 update_utmp(options.tty, fakehost);
712 /* Initialize the termios settings (raw mode, eight-bit, blocking i/o). */
713 debug("calling termios_init\n");
714 termios_init(&termios, options.speeds[0], &options);
716 /* Write the modem init string and DON'T flush the buffers */
717 if (options.flags & F_INITSTRING) {
718 debug("writing init string\n");
719 full_write(1, options.initstring, strlen(options.initstring));
722 /* Optionally detect the baud rate from the modem status message */
723 debug("before autobaud\n");
724 if (options.flags & F_PARSE)
725 auto_baud(line_buf, sizeof(line_buf), &termios);
727 /* Set the optional timer */
728 alarm(options.timeout); /* if 0, alarm is not set */
730 /* Optionally wait for CR or LF before writing /etc/issue */
731 if (options.flags & F_WAITCRLF) {
734 debug("waiting for cr-lf\n");
735 while (safe_read(0, &ch, 1) == 1) {
736 debug("read %x\n", (unsigned char)ch);
737 ch &= 0x7f; /* strip "parity bit" */
738 if (ch == '\n' || ch == '\r')
744 if (!(options.flags & F_NOPROMPT)) {
745 /* NB:termios_init already set line speed
746 * to options.speeds[0] */
750 /* Read the login name. */
751 debug("reading login name\n");
752 logname = get_logname(line_buf, sizeof(line_buf),
753 &options, &chardata);
756 /* we are here only if options.numspeed > 1 */
757 baud_index = (baud_index + 1) % options.numspeed;
758 termios.c_cflag &= ~CBAUD;
759 termios.c_cflag |= options.speeds[baud_index];
760 ioctl(0, TCSETS, &termios);
767 /* Finalize the termios settings. */
768 termios_final(&options, &termios, &chardata);
770 /* Now the newline character should be properly written. */
771 full_write(1, "\n", 1);
773 /* Let the login program take care of password validation. */
774 /* We use PATH because we trust that root doesn't set "bad" PATH,
775 * and getty is not suid-root applet. */
776 /* With -n, logname == NULL, and login will ask for username instead */
777 BB_EXECLP(options.login, options.login, "--", logname, NULL);
778 bb_error_msg_and_die("%s: can't exec %s", options.tty, options.login);