1 /* vi: set sw=4 ts=4: */
3 * Based on agetty - another getty program for Linux. By W. Z. Venema 1989
4 * Ported to Linux by Peter Orbaek <poe@daimi.aau.dk>
5 * This program is freely distributable.
7 * option added by Eric Rasmussen <ear@usfirst.org> - 12/28/95
9 * 1999-02-22 Arkadiusz Mickiewicz <misiek@misiek.eu.org>
10 * - Added Native Language Support
12 * 1999-05-05 Thorsten Kranzkowski <dl8bcu@gmx.net>
13 * - Enabled hardware flow control before displaying /etc/issue
15 * 2011-01 Venys Vlasenko
16 * - Removed parity detection code. It can't work reliably:
17 * if all chars received have bit 7 cleared and odd (or even) parity,
18 * it is impossible to determine whether other side is 8-bit,no-parity
19 * or 7-bit,odd(even)-parity. It also interferes with non-ASCII usernames.
20 * - From now on, we assume that parity is correctly set.
22 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
32 # undef ENABLE_FEATURE_UTMP
33 # undef ENABLE_FEATURE_WTMP
34 # define ENABLE_FEATURE_UTMP 0
35 # define ENABLE_FEATURE_WTMP 0
39 /* The following is used for understandable diagnostics */
42 # define DEBUGTERM "/dev/ttyp0"
43 # define debug(...) do { fprintf(dbf, __VA_ARGS__); fflush(dbf); } while (0)
45 # define debug(...) ((void)0)
50 * Things you may want to modify.
52 * You may disagree with the default line-editing etc. characters defined
53 * below. Note, however, that DEL cannot be used for interrupt generation
54 * and for line editing at the same time.
57 #define _PATH_LOGIN "/bin/login"
59 /* Displayed before the login prompt.
60 * If ISSUE is not defined, getty will never display the contents of the
61 * /etc/issue file. You will not want to spit out large "issue" files at the
64 #define ISSUE "/etc/issue"
66 /* Macro to build Ctrl-LETTER. Assumes ASCII dialect */
67 #define CTL(x) ((x) ^ 0100)
70 * When multiple baud rates are specified on the command line,
71 * the first one we will try is the first one specified.
73 #define MAX_SPEED 10 /* max. nr. of baud rates */
77 const char *login
; /* login program */
80 char *initstring
; /* modem init string */
81 const char *issue
; /* alternative issue file */
82 int numspeed
; /* number of baud rates to try */
83 int speeds
[MAX_SPEED
]; /* baud rates to be tried */
84 unsigned char eol
; /* end-of-line char seen (CR or NL) */
85 struct termios tty_attrs
;
89 #define G (*ptr_to_globals)
90 #define INIT_G() do { \
91 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
94 //usage:#define getty_trivial_usage
95 //usage: "[OPTIONS] BAUD_RATE[,BAUD_RATE]... TTY [TERMTYPE]"
96 //usage:#define getty_full_usage "\n\n"
97 //usage: "Open TTY, prompt for login name, then invoke /bin/login\n"
98 //usage: "\n -h Enable hardware RTS/CTS flow control"
99 //usage: "\n -L Set CLOCAL (ignore Carrier Detect state)"
100 //usage: "\n -m Get baud rate from modem's CONNECT status message"
101 //usage: "\n -n Don't prompt for login name"
102 //usage: "\n -w Wait for CR or LF before sending /etc/issue"
103 //usage: "\n -i Don't display /etc/issue"
104 //usage: "\n -f ISSUE_FILE Display ISSUE_FILE instead of /etc/issue"
105 //usage: "\n -l LOGIN Invoke LOGIN instead of /bin/login"
106 //usage: "\n -t SEC Terminate after SEC if no login name is read"
107 //usage: "\n -I INITSTR Send INITSTR before anything else"
108 //usage: "\n -H HOST Log HOST into the utmp file as the hostname"
110 //usage: "\nBAUD_RATE of 0 leaves it unchanged"
112 static const char opt_string
[] ALIGN1
= "I:LH:f:hil:mt:wn";
113 #define F_INITSTRING (1 << 0) /* -I */
114 #define F_LOCAL (1 << 1) /* -L */
115 #define F_FAKEHOST (1 << 2) /* -H */
116 #define F_CUSTISSUE (1 << 3) /* -f */
117 #define F_RTSCTS (1 << 4) /* -h */
118 #define F_NOISSUE (1 << 5) /* -i */
119 #define F_LOGIN (1 << 6) /* -l */
120 #define F_PARSE (1 << 7) /* -m */
121 #define F_TIMEOUT (1 << 8) /* -t */
122 #define F_WAITCRLF (1 << 9) /* -w */
123 #define F_NOPROMPT (1 << 10) /* -n */
126 /* convert speed string to speed code; return <= 0 on failure */
127 static int bcode(const char *s
)
129 int value
= bb_strtou(s
, NULL
, 10); /* yes, int is intended! */
130 if (value
< 0) /* bad terminating char, overflow, etc */
132 return tty_value_to_baud(value
);
135 /* parse alternate baud rates */
136 static void parse_speeds(char *arg
)
140 /* NB: at least one iteration is always done */
141 debug("entered parse_speeds\n");
142 while ((cp
= strsep(&arg
, ",")) != NULL
) {
143 G
.speeds
[G
.numspeed
] = bcode(cp
);
144 if (G
.speeds
[G
.numspeed
] < 0)
145 bb_error_msg_and_die("bad speed: %s", cp
);
146 /* note: arg "0" turns into speed B0 */
148 if (G
.numspeed
> MAX_SPEED
)
149 bb_error_msg_and_die("too many alternate speeds");
151 debug("exiting parse_speeds\n");
154 /* parse command-line arguments */
155 static void parse_args(char **argv
)
160 opt_complementary
= "-2:t+"; /* at least 2 args; -t N */
161 flags
= getopt32(argv
, opt_string
,
162 &G
.initstring
, &G
.fakehost
, &G
.issue
,
165 if (flags
& F_INITSTRING
) {
166 G
.initstring
= xstrdup(G
.initstring
);
167 /* decode \ddd octal codes into chars */
168 strcpy_and_process_escape_sequences(G
.initstring
, G
.initstring
);
171 debug("after getopt\n");
173 /* We loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
174 G
.tty_name
= argv
[0];
175 ts
= argv
[1]; /* baud rate(s) */
176 if (isdigit(argv
[0][0])) {
177 /* A number first, assume it's a speed (BSD style) */
178 G
.tty_name
= ts
; /* tty name is in argv[1] */
179 ts
= argv
[0]; /* baud rate(s) */
184 xsetenv("TERM", argv
[2]);
186 debug("exiting parse_args\n");
189 /* set up tty as standard input, output, error */
190 static void open_tty(void)
192 /* Set up new standard input, unless we are given an already opened port */
193 if (NOT_LONE_DASH(G
.tty_name
)) {
194 if (G
.tty_name
[0] != '/')
195 G
.tty_name
= xasprintf("/dev/%s", G
.tty_name
); /* will leak it */
197 /* Open the tty as standard input */
200 xopen(G
.tty_name
, O_RDWR
| O_NONBLOCK
); /* uses fd 0 */
202 /* Set proper protections and ownership */
203 fchown(0, 0, 0); /* 0:0 */
204 fchmod(0, 0620); /* crw--w---- */
208 * Standard input should already be connected to an open port.
209 * Make sure it is open for read/write.
211 if ((fcntl(0, F_GETFL
) & (O_RDWR
|O_RDONLY
|O_WRONLY
)) != O_RDWR
)
212 bb_error_msg_and_die("stdin is not open for read/write");
214 /* Try to get real tty name instead of "-" */
215 n
= xmalloc_ttyname(0);
219 applet_name
= xasprintf("getty: %s", skip_dev_pfx(G
.tty_name
));
222 static void set_tty_attrs(void)
224 if (tcsetattr_stdin_TCSANOW(&G
.tty_attrs
) < 0)
225 bb_perror_msg_and_die("tcsetattr");
228 /* We manipulate tty_attrs this way:
229 * - first, we read existing tty_attrs
230 * - init_tty_attrs modifies some parts and sets it
231 * - auto_baud and/or BREAK processing can set different speed and set tty attrs
232 * - finalize_tty_attrs again modifies some parts and sets tty attrs before
235 static void init_tty_attrs(int speed
)
237 /* Try to drain output buffer, with 5 sec timeout.
238 * Added on request from users of ~600 baud serial interface
239 * with biggish buffer on a 90MHz CPU.
240 * They were losing hundreds of bytes of buffered output
243 signal_no_SA_RESTART_empty_mask(SIGALRM
, record_signo
);
245 tcdrain(STDIN_FILENO
);
248 /* Flush input and output queues, important for modems! */
249 tcflush(STDIN_FILENO
, TCIOFLUSH
);
251 /* Set speed if it wasn't specified as "0" on command line */
253 cfsetspeed(&G
.tty_attrs
, speed
);
255 /* Initial settings: 8-bit characters, raw mode, blocking i/o.
256 * Special characters are set after we have read the login name; all
257 * reads will be done in raw mode anyway.
259 /* Clear all bits except: */
260 G
.tty_attrs
.c_cflag
&= (0
261 /* 2 stop bits (1 otherwise)
262 * Enable parity bit (both on input and output)
263 * Odd parity (else even)
265 | CSTOPB
| PARENB
| PARODD
267 | CMSPAR
/* mark or space parity */
270 | CBAUD
/* (output) baud rate */
273 | CBAUDEX
/* (output) baud rate */
276 | CIBAUD
/* input baud rate */
279 /* Set: 8 bits; hang up (drop DTR) on last close; enable receive */
280 G
.tty_attrs
.c_cflag
|= CS8
| HUPCL
| CREAD
;
281 if (option_mask32
& F_LOCAL
) {
282 /* ignore Carrier Detect pin:
283 * opens don't block when CD is low,
284 * losing CD doesn't hang up processes whose ctty is this tty
286 G
.tty_attrs
.c_cflag
|= CLOCAL
;
289 if (option_mask32
& F_RTSCTS
)
290 G
.tty_attrs
.c_cflag
|= CRTSCTS
; /* flow control using RTS/CTS pins */
292 G
.tty_attrs
.c_iflag
= 0;
293 G
.tty_attrs
.c_lflag
= 0;
294 /* non-raw output; add CR to each NL */
295 G
.tty_attrs
.c_oflag
= OPOST
| ONLCR
;
297 /* reads would block only if < 1 char is available */
298 G
.tty_attrs
.c_cc
[VMIN
] = 1;
299 /* no timeout (reads block forever) */
300 G
.tty_attrs
.c_cc
[VTIME
] = 0;
302 G
.tty_attrs
.c_line
= 0;
307 debug("term_io 2\n");
310 static void finalize_tty_attrs(void)
312 /* software flow control on output (stop sending if XOFF is recvd);
313 * and on input (send XOFF when buffer is full)
315 G
.tty_attrs
.c_iflag
|= IXON
| IXOFF
;
317 G
.tty_attrs
.c_iflag
|= ICRNL
; /* map CR on input to NL */
319 /* Other bits in c_iflag:
320 * IXANY Any recvd char enables output (any char is also a XON)
321 * INPCK Enable parity check
322 * IGNPAR Ignore parity errors (drop bad bytes)
323 * PARMRK Mark parity errors with 0xff, 0x00 prefix
324 * (else bad byte is received as 0x00)
325 * ISTRIP Strip parity bit
326 * IGNBRK Ignore break condition
327 * BRKINT Send SIGINT on break - maybe set this?
331 * IUCLC Map uppercase to lowercase
332 * IMAXBEL Echo BEL on input line too long
333 * IUTF8 Appears to affect tty's idea of char widths,
334 * observed to improve backspacing through Unicode chars
337 /* line buffered input (NL or EOL or EOF chars end a line);
338 * recognize INT/QUIT/SUSP chars;
340 * echo BS-SP-BS on erase character;
341 * echo kill char specially, not as ^c (ECHOKE controls how exactly);
342 * erase all input via BS-SP-BS on kill char (else go to next line)
344 G
.tty_attrs
.c_lflag
|= ICANON
| ISIG
| ECHO
| ECHOE
| ECHOK
| ECHOKE
;
345 /* Other bits in c_lflag:
346 * XCASE Map uppercase to \lowercase [tried, doesn't work]
347 * ECHONL Echo NL even if ECHO is not set
348 * ECHOCTL Echo ctrl chars as ^c (else don't echo) - maybe set this?
349 * ECHOPRT On erase, echo erased chars
350 * [qwe<BS><BS><BS> input looks like "qwe\ewq/" on screen]
351 * NOFLSH Don't flush input buffer after interrupt or quit chars
352 * IEXTEN Enable extended functions (??)
353 * [glibc says it enables c_cc[LNEXT] "enter literal char"
354 * and c_cc[VDISCARD] "toggle discard buffered output" chars]
355 * FLUSHO Output being flushed (c_cc[VDISCARD] is in effect)
356 * PENDIN Retype pending input at next read or input char
357 * (c_cc[VREPRINT] is being processed)
358 * TOSTOP Send SIGTTOU for background output
359 * (why "stty sane" unsets this bit?)
362 G
.tty_attrs
.c_cc
[VINTR
] = CTL('C');
363 G
.tty_attrs
.c_cc
[VQUIT
] = CTL('\\');
364 G
.tty_attrs
.c_cc
[VEOF
] = CTL('D');
365 G
.tty_attrs
.c_cc
[VEOL
] = '\n';
367 G
.tty_attrs
.c_cc
[VSWTC
] = 0;
370 G
.tty_attrs
.c_cc
[VSWTCH
] = 0;
372 G
.tty_attrs
.c_cc
[VKILL
] = CTL('U');
373 /* Other control chars:
375 * VERASE, VWERASE - (word) erase. we may set VERASE in get_logname
376 * VREPRINT - reprint current input buffer
377 * VLNEXT, VDISCARD, VSTATUS
378 * VSUSP, VDSUSP - send (delayed) SIGTSTP
379 * VSTART, VSTOP - chars used for IXON/IXOFF
384 /* Now the newline character should be properly written */
385 full_write(STDOUT_FILENO
, "\n", 1);
388 /* extract baud rate from modem status message */
389 static void auto_baud(void)
394 * This works only if the modem produces its status code AFTER raising
395 * the DCD line, and if the computer is fast enough to set the proper
396 * baud rate before the message has gone by. We expect a message of the
399 * <junk><number><junk>
401 * The number is interpreted as the baud rate of the incoming call. If the
402 * modem does not tell us the baud rate within one second, we will keep
403 * using the current baud rate. It is advisable to enable BREAK
404 * processing (comma-separated list of baud rates) if the processing of
405 * modem status messages is enabled.
408 G
.tty_attrs
.c_cc
[VMIN
] = 0; /* don't block reads (min read is 0 chars) */
412 * Wait for a while, then read everything the modem has said so far and
413 * try to extract the speed of the dial-in call.
416 nread
= safe_read(STDIN_FILENO
, G
.line_buf
, sizeof(G
.line_buf
) - 1);
420 G
.line_buf
[nread
] = '\0';
421 for (bp
= G
.line_buf
; bp
< G
.line_buf
+ nread
; bp
++) {
425 cfsetspeed(&G
.tty_attrs
, speed
);
431 /* Restore terminal settings */
432 G
.tty_attrs
.c_cc
[VMIN
] = 1; /* restore to value set by init_tty_attrs */
436 /* get user name, establish parity, speed, erase, kill, eol;
437 * return NULL on BREAK, logname on success
439 static char *get_logname(void)
444 /* Flush pending input (esp. after parsing or switching the baud rate) */
445 usleep(100*1000); /* 0.1 sec */
446 tcflush(STDIN_FILENO
, TCIFLUSH
);
448 /* Prompt for and read a login name */
450 /* Write issue file and prompt */
452 if (!(option_mask32
& F_NOISSUE
))
453 print_login_issue(G
.issue
, G
.tty_name
);
455 print_login_prompt();
457 /* Read name, watch for break, erase, kill, end-of-line */
460 /* Do not report trivial EINTR/EIO errors */
461 errno
= EINTR
; /* make read of 0 bytes be silent too */
462 if (read(STDIN_FILENO
, &c
, 1) < 1) {
463 finalize_tty_attrs();
464 if (errno
== EINTR
|| errno
== EIO
)
466 bb_perror_msg_and_die(bb_msg_read_error
);
477 G
.tty_attrs
.c_cc
[VERASE
] = c
;
478 if (bp
> G
.line_buf
) {
479 full_write(STDOUT_FILENO
, "\010 \010", 3);
484 while (bp
> G
.line_buf
) {
485 full_write(STDOUT_FILENO
, "\010 \010", 3);
491 finalize_tty_attrs();
494 /* BREAK. If we have speeds to try,
495 * return NULL (will switch speeds and return here) */
498 /* fall through and ignore it */
500 if ((unsigned char)c
< ' ') {
501 /* ignore garbage characters */
502 } else if ((int)(bp
- G
.line_buf
) < sizeof(G
.line_buf
) - 1) {
503 /* echo and store the character */
504 full_write(STDOUT_FILENO
, &c
, 1);
509 } /* end of get char loop */
511 } while (G
.line_buf
[0] == '\0'); /* while logname is empty */
516 static void alarm_handler(int sig UNUSED_PARAM
)
518 finalize_tty_attrs();
522 int getty_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
523 int getty_main(int argc UNUSED_PARAM
, char **argv
)
530 G
.login
= _PATH_LOGIN
; /* default login program */
532 G
.issue
= ISSUE
; /* default issue file */
536 /* Parse command-line arguments */
539 /* Create new session and pgrp, lose controlling tty */
540 pid
= setsid(); /* this also gives us our pid :) */
544 * docs/ctty.htm says:
545 * "This is allowed only when the current process
546 * is not a process group leader".
547 * Thus, setsid() will fail if we _already_ are
548 * a session leader - which is quite possible for getty!
551 if (getsid(0) != pid
)
552 bb_perror_msg_and_die("setsid");
553 /* Looks like we are already a session leader.
554 * In this case (setsid failed) we may still have ctty,
555 * and it may be different from tty we need to control!
556 * If we still have ctty, on Linux ioctl(TIOCSCTTY)
557 * (which we are going to use a bit later) always fails -
558 * even if we try to take ctty which is already ours!
559 * Try to drop old ctty now to prevent that.
560 * Use O_NONBLOCK: old ctty may be a serial line.
562 fd
= open("/dev/tty", O_RDWR
| O_NONBLOCK
);
564 /* TIOCNOTTY sends SIGHUP to the foreground
565 * process group - which may include us!
566 * Make sure to not die on it:
568 sighandler_t old
= signal(SIGHUP
, SIG_IGN
);
569 ioctl(fd
, TIOCNOTTY
);
575 /* Close stdio, and stray descriptors, just in case */
576 n
= xopen(bb_dev_null
, O_RDWR
);
577 /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
583 /* Logging. We want special flavor of error_msg_and_die */
586 /* most likely will internally use fd #3 in CLOEXEC mode: */
587 openlog(applet_name
, LOG_PID
, LOG_AUTH
);
588 logmode
= LOGMODE_BOTH
;
591 dbf
= xfopen_for_write(DEBUGTERM
);
592 for (n
= 1; argv
[n
]; n
++) {
598 /* Open the tty as standard input, if it is not "-" */
599 debug("calling open_tty\n");
601 ndelay_off(STDIN_FILENO
);
603 xdup2(STDIN_FILENO
, 1);
604 xdup2(STDIN_FILENO
, 2);
606 /* Steal ctty if we don't have it yet */
607 tsid
= tcgetsid(STDIN_FILENO
);
608 if (tsid
< 0 || pid
!= tsid
) {
609 if (ioctl(STDIN_FILENO
, TIOCSCTTY
, /*force:*/ (long)1) < 0)
610 bb_perror_msg_and_die("TIOCSCTTY");
614 /* Make ourself a foreground process group within our session */
615 if (tcsetpgrp(STDIN_FILENO
, pid
) < 0)
616 bb_perror_msg_and_die("tcsetpgrp");
620 * The following ioctl will fail if stdin is not a tty, but also when
621 * there is noise on the modem control lines. In the latter case, the
622 * common course of action is (1) fix your cables (2) give the modem more
623 * time to properly reset after hanging up. SunOS users can achieve (2)
624 * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
625 * 5 seconds seems to be a good value.
627 if (tcgetattr(STDIN_FILENO
, &G
.tty_attrs
) < 0)
628 bb_perror_msg_and_die("tcgetattr");
630 /* Update the utmp file. This tty is ours now! */
631 update_utmp(pid
, LOGIN_PROCESS
, G
.tty_name
, "LOGIN", G
.fakehost
);
633 /* Initialize tty attrs (raw mode, eight-bit, blocking i/o) */
634 debug("calling init_tty_attrs\n");
635 init_tty_attrs(G
.speeds
[0]);
637 /* Write the modem init string and DON'T flush the buffers */
638 if (option_mask32
& F_INITSTRING
) {
639 debug("writing init string\n");
640 full_write1_str(G
.initstring
);
643 /* Optionally detect the baud rate from the modem status message */
644 debug("before autobaud\n");
645 if (option_mask32
& F_PARSE
)
648 /* Set the optional timer */
649 signal(SIGALRM
, alarm_handler
);
650 alarm(G
.timeout
); /* if 0, alarm is not set */
652 /* Optionally wait for CR or LF before writing /etc/issue */
653 if (option_mask32
& F_WAITCRLF
) {
655 debug("waiting for cr-lf\n");
656 while (safe_read(STDIN_FILENO
, &ch
, 1) == 1) {
657 debug("read %x\n", (unsigned char)ch
);
658 if (ch
== '\n' || ch
== '\r')
664 if (!(option_mask32
& F_NOPROMPT
)) {
665 /* NB: init_tty_attrs already set line speed
670 /* Read the login name */
671 debug("reading login name\n");
672 logname
= get_logname();
675 /* We are here only if G.numspeed > 1 */
676 baud_index
= (baud_index
+ 1) % G
.numspeed
;
677 cfsetspeed(&G
.tty_attrs
, G
.speeds
[baud_index
]);
685 finalize_tty_attrs();
687 /* Let the login program take care of password validation */
688 /* We use PATH because we trust that root doesn't set "bad" PATH,
689 * and getty is not suid-root applet */
690 /* With -n, logname == NULL, and login will ask for username instead */
691 BB_EXECLP(G
.login
, G
.login
, "--", logname
, NULL
);
692 bb_error_msg_and_die("can't execute '%s'", G
.login
);