summaryrefslogtreecommitdiff
path: root/loginutils/getty.c (plain)
blob: e5a2533c09c69b97c4cac21f919cc37dbd6aa984
1/* vi: set sw=4 ts=4: */
2/*
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.
6 *
7 * option added by Eric Rasmussen <ear@usfirst.org> - 12/28/95
8 *
9 * 1999-02-22 Arkadiusz Mickiewicz <misiek@misiek.eu.org>
10 * - Added Native Language Support
11 *
12 * 1999-05-05 Thorsten Kranzkowski <dl8bcu@gmx.net>
13 * - Enabled hardware flow control before displaying /etc/issue
14 *
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.
21 *
22 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
23 */
24//config:config GETTY
25//config: bool "getty"
26//config: default y
27//config: select FEATURE_SYSLOG
28//config: help
29//config: getty lets you log in on a tty. It is normally invoked by init.
30//config:
31//config: Note that you can save a few bytes by disabling it and
32//config: using login applet directly.
33//config: If you need to reset tty attributes before calling login,
34//config: this script approximates getty:
35//config:
36//config: exec </dev/$1 >/dev/$1 2>&1 || exit 1
37//config: reset
38//config: stty sane; stty ispeed 38400; stty ospeed 38400
39//config: printf "%s login: " "`hostname`"
40//config: read -r login
41//config: exec /bin/login "$login"
42
43//applet:IF_GETTY(APPLET(getty, BB_DIR_SBIN, BB_SUID_DROP))
44
45//kbuild:lib-$(CONFIG_GETTY) += getty.o
46
47#include "libbb.h"
48#include <syslog.h>
49#ifndef IUCLC
50# define IUCLC 0
51#endif
52
53#ifndef LOGIN_PROCESS
54# undef ENABLE_FEATURE_UTMP
55# undef ENABLE_FEATURE_WTMP
56# define ENABLE_FEATURE_UTMP 0
57# define ENABLE_FEATURE_WTMP 0
58#endif
59
60
61/* The following is used for understandable diagnostics */
62#ifdef DEBUGGING
63static FILE *dbf;
64# define DEBUGTERM "/dev/ttyp0"
65# define debug(...) do { fprintf(dbf, __VA_ARGS__); fflush(dbf); } while (0)
66#else
67# define debug(...) ((void)0)
68#endif
69
70
71/*
72 * Things you may want to modify.
73 *
74 * You may disagree with the default line-editing etc. characters defined
75 * below. Note, however, that DEL cannot be used for interrupt generation
76 * and for line editing at the same time.
77 */
78#undef _PATH_LOGIN
79#ifdef __BIONIC__
80#define cfsetspeed(t,s) cfsetispeed(t,s)
81#define _PATH_LOGIN "/system/xbin/login"
82#else
83#define _PATH_LOGIN "/bin/login"
84#endif
85
86/* Displayed before the login prompt.
87 * If ISSUE is not defined, getty will never display the contents of the
88 * /etc/issue file. You will not want to spit out large "issue" files at the
89 * wrong baud rate.
90 */
91#define ISSUE "/etc/issue"
92
93/* Macro to build Ctrl-LETTER. Assumes ASCII dialect */
94#define CTL(x) ((x) ^ 0100)
95
96/*
97 * When multiple baud rates are specified on the command line,
98 * the first one we will try is the first one specified.
99 */
100#define MAX_SPEED 10 /* max. nr. of baud rates */
101
102struct globals {
103 unsigned timeout;
104 const char *login; /* login program */
105 const char *fakehost;
106 const char *tty_name;
107 char *initstring; /* modem init string */
108 const char *issue; /* alternative issue file */
109 int numspeed; /* number of baud rates to try */
110 int speeds[MAX_SPEED]; /* baud rates to be tried */
111 unsigned char eol; /* end-of-line char seen (CR or NL) */
112 struct termios tty_attrs;
113 char line_buf[128];
114};
115
116#define G (*ptr_to_globals)
117#define INIT_G() do { \
118 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
119} while (0)
120
121//usage:#define getty_trivial_usage
122//usage: "[OPTIONS] BAUD_RATE[,BAUD_RATE]... TTY [TERMTYPE]"
123//usage:#define getty_full_usage "\n\n"
124//usage: "Open TTY, prompt for login name, then invoke /system/xbin/login\n"
125//usage: "\n -h Enable hardware RTS/CTS flow control"
126//usage: "\n -L Set CLOCAL (ignore Carrier Detect state)"
127//usage: "\n -m Get baud rate from modem's CONNECT status message"
128//usage: "\n -n Don't prompt for login name"
129//usage: "\n -w Wait for CR or LF before sending /etc/issue"
130//usage: "\n -i Don't display /etc/issue"
131//usage: "\n -f ISSUE_FILE Display ISSUE_FILE instead of /etc/issue"
132//usage: "\n -l LOGIN Invoke LOGIN instead of /system/xbin/login"
133//usage: "\n -t SEC Terminate after SEC if no login name is read"
134//usage: "\n -I INITSTR Send INITSTR before anything else"
135//usage: "\n -H HOST Log HOST into the utmp file as the hostname"
136//usage: "\n"
137//usage: "\nBAUD_RATE of 0 leaves it unchanged"
138
139static const char opt_string[] ALIGN1 = "I:LH:f:hil:mt:+wn";
140#define F_INITSTRING (1 << 0) /* -I */
141#define F_LOCAL (1 << 1) /* -L */
142#define F_FAKEHOST (1 << 2) /* -H */
143#define F_CUSTISSUE (1 << 3) /* -f */
144#define F_RTSCTS (1 << 4) /* -h */
145#define F_NOISSUE (1 << 5) /* -i */
146#define F_LOGIN (1 << 6) /* -l */
147#define F_PARSE (1 << 7) /* -m */
148#define F_TIMEOUT (1 << 8) /* -t */
149#define F_WAITCRLF (1 << 9) /* -w */
150#define F_NOPROMPT (1 << 10) /* -n */
151
152
153/* convert speed string to speed code; return <= 0 on failure */
154static int bcode(const char *s)
155{
156 int value = bb_strtou(s, NULL, 10); /* yes, int is intended! */
157 if (value < 0) /* bad terminating char, overflow, etc */
158 return value;
159 return tty_value_to_baud(value);
160}
161
162/* parse alternate baud rates */
163static void parse_speeds(char *arg)
164{
165 char *cp;
166
167 /* NB: at least one iteration is always done */
168 debug("entered parse_speeds\n");
169 while ((cp = strsep(&arg, ",")) != NULL) {
170 G.speeds[G.numspeed] = bcode(cp);
171 if (G.speeds[G.numspeed] < 0)
172 bb_error_msg_and_die("bad speed: %s", cp);
173 /* note: arg "0" turns into speed B0 */
174 G.numspeed++;
175 if (G.numspeed > MAX_SPEED)
176 bb_error_msg_and_die("too many alternate speeds");
177 }
178 debug("exiting parse_speeds\n");
179}
180
181/* parse command-line arguments */
182static void parse_args(char **argv)
183{
184 char *ts;
185 int flags;
186
187 opt_complementary = "-2"; /* at least 2 args; -t N */
188 flags = getopt32(argv, opt_string,
189 &G.initstring, &G.fakehost, &G.issue,
190 &G.login, &G.timeout
191 );
192 if (flags & F_INITSTRING) {
193 G.initstring = xstrdup(G.initstring);
194 /* decode \ddd octal codes into chars */
195 strcpy_and_process_escape_sequences(G.initstring, G.initstring);
196 }
197 argv += optind;
198 debug("after getopt\n");
199
200 /* We loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
201 G.tty_name = argv[0];
202 ts = argv[1]; /* baud rate(s) */
203 if (isdigit(argv[0][0])) {
204 /* A number first, assume it's a speed (BSD style) */
205 G.tty_name = ts; /* tty name is in argv[1] */
206 ts = argv[0]; /* baud rate(s) */
207 }
208 parse_speeds(ts);
209
210 if (argv[2])
211 xsetenv("TERM", argv[2]);
212
213 debug("exiting parse_args\n");
214}
215
216/* set up tty as standard input, output, error */
217static void open_tty(void)
218{
219 /* Set up new standard input, unless we are given an already opened port */
220 if (NOT_LONE_DASH(G.tty_name)) {
221 if (G.tty_name[0] != '/')
222 G.tty_name = xasprintf("/dev/%s", G.tty_name); /* will leak it */
223
224 /* Open the tty as standard input */
225 debug("open(2)\n");
226 close(0);
227 xopen(G.tty_name, O_RDWR | O_NONBLOCK); /* uses fd 0 */
228
229 /* Set proper protections and ownership */
230 fchown(0, 0, 0); /* 0:0 */
231 fchmod(0, 0620); /* crw--w---- */
232 } else {
233 char *n;
234 /*
235 * Standard input should already be connected to an open port.
236 * Make sure it is open for read/write.
237 */
238 if ((fcntl(0, F_GETFL) & (O_RDWR|O_RDONLY|O_WRONLY)) != O_RDWR)
239 bb_error_msg_and_die("stdin is not open for read/write");
240
241 /* Try to get real tty name instead of "-" */
242 n = xmalloc_ttyname(0);
243 if (n)
244 G.tty_name = n;
245 }
246 applet_name = xasprintf("getty: %s", skip_dev_pfx(G.tty_name));
247}
248
249static void set_tty_attrs(void)
250{
251 if (tcsetattr_stdin_TCSANOW(&G.tty_attrs) < 0)
252 bb_perror_msg_and_die("tcsetattr");
253}
254
255/* We manipulate tty_attrs this way:
256 * - first, we read existing tty_attrs
257 * - init_tty_attrs modifies some parts and sets it
258 * - auto_baud and/or BREAK processing can set different speed and set tty attrs
259 * - finalize_tty_attrs again modifies some parts and sets tty attrs before
260 * execing login
261 */
262static void init_tty_attrs(int speed)
263{
264 /* Try to drain output buffer, with 5 sec timeout.
265 * Added on request from users of ~600 baud serial interface
266 * with biggish buffer on a 90MHz CPU.
267 * They were losing hundreds of bytes of buffered output
268 * on tcflush.
269 */
270 signal_no_SA_RESTART_empty_mask(SIGALRM, record_signo);
271 alarm(5);
272 tcdrain(STDIN_FILENO);
273 alarm(0);
274
275 /* Flush input and output queues, important for modems! */
276 tcflush(STDIN_FILENO, TCIOFLUSH);
277
278 /* Set speed if it wasn't specified as "0" on command line */
279 if (speed != B0)
280 cfsetspeed(&G.tty_attrs, speed);
281
282 /* Initial settings: 8-bit characters, raw mode, blocking i/o.
283 * Special characters are set after we have read the login name; all
284 * reads will be done in raw mode anyway.
285 */
286 /* Clear all bits except: */
287 G.tty_attrs.c_cflag &= (0
288 /* 2 stop bits (1 otherwise)
289 * Enable parity bit (both on input and output)
290 * Odd parity (else even)
291 */
292 | CSTOPB | PARENB | PARODD
293#ifdef CMSPAR
294 | CMSPAR /* mark or space parity */
295#endif
296#ifdef CBAUD
297 | CBAUD /* (output) baud rate */
298#endif
299#ifdef CBAUDEX
300 | CBAUDEX /* (output) baud rate */
301#endif
302#ifdef CIBAUD
303 | CIBAUD /* input baud rate */
304#endif
305 );
306 /* Set: 8 bits; hang up (drop DTR) on last close; enable receive */
307 G.tty_attrs.c_cflag |= CS8 | HUPCL | CREAD;
308 if (option_mask32 & F_LOCAL) {
309 /* ignore Carrier Detect pin:
310 * opens don't block when CD is low,
311 * losing CD doesn't hang up processes whose ctty is this tty
312 */
313 G.tty_attrs.c_cflag |= CLOCAL;
314 }
315#ifdef CRTSCTS
316 if (option_mask32 & F_RTSCTS)
317 G.tty_attrs.c_cflag |= CRTSCTS; /* flow control using RTS/CTS pins */
318#endif
319 G.tty_attrs.c_iflag = 0;
320 G.tty_attrs.c_lflag = 0;
321 /* non-raw output; add CR to each NL */
322 G.tty_attrs.c_oflag = OPOST | ONLCR;
323
324 /* reads would block only if < 1 char is available */
325 G.tty_attrs.c_cc[VMIN] = 1;
326 /* no timeout (reads block forever) */
327 G.tty_attrs.c_cc[VTIME] = 0;
328#ifdef __linux__
329 G.tty_attrs.c_line = 0;
330#endif
331
332 set_tty_attrs();
333
334 debug("term_io 2\n");
335}
336
337static void finalize_tty_attrs(void)
338{
339 /* software flow control on output (stop sending if XOFF is recvd);
340 * and on input (send XOFF when buffer is full)
341 */
342 G.tty_attrs.c_iflag |= IXON | IXOFF;
343 if (G.eol == '\r') {
344 G.tty_attrs.c_iflag |= ICRNL; /* map CR on input to NL */
345 }
346 /* Other bits in c_iflag:
347 * IXANY Any recvd char enables output (any char is also a XON)
348 * INPCK Enable parity check
349 * IGNPAR Ignore parity errors (drop bad bytes)
350 * PARMRK Mark parity errors with 0xff, 0x00 prefix
351 * (else bad byte is received as 0x00)
352 * ISTRIP Strip parity bit
353 * IGNBRK Ignore break condition
354 * BRKINT Send SIGINT on break - maybe set this?
355 * INLCR Map NL to CR
356 * IGNCR Ignore CR
357 * ICRNL Map CR to NL
358 * IUCLC Map uppercase to lowercase
359 * IMAXBEL Echo BEL on input line too long
360 * IUTF8 Appears to affect tty's idea of char widths,
361 * observed to improve backspacing through Unicode chars
362 */
363
364 /* ICANON line buffered input (NL or EOL or EOF chars end a line);
365 * ISIG recognize INT/QUIT/SUSP chars;
366 * ECHO echo input chars;
367 * ECHOE echo BS-SP-BS on erase character;
368 * ECHOK echo kill char specially, not as ^c (ECHOKE controls how exactly);
369 * ECHOKE erase all input via BS-SP-BS on kill char (else go to next line)
370 * ECHOCTL Echo ctrl chars as ^c (else echo verbatim:
371 * e.g. up arrow emits "ESC-something" and thus moves cursor up!)
372 */
373 G.tty_attrs.c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE | ECHOCTL;
374 /* Other bits in c_lflag:
375 * XCASE Map uppercase to \lowercase [tried, doesn't work]
376 * ECHONL Echo NL even if ECHO is not set
377 * ECHOPRT On erase, echo erased chars
378 * [qwe<BS><BS><BS> input looks like "qwe\ewq/" on screen]
379 * NOFLSH Don't flush input buffer after interrupt or quit chars
380 * IEXTEN Enable extended functions (??)
381 * [glibc says it enables c_cc[LNEXT] "enter literal char"
382 * and c_cc[VDISCARD] "toggle discard buffered output" chars]
383 * FLUSHO Output being flushed (c_cc[VDISCARD] is in effect)
384 * PENDIN Retype pending input at next read or input char
385 * (c_cc[VREPRINT] is being processed)
386 * TOSTOP Send SIGTTOU for background output
387 * (why "stty sane" unsets this bit?)
388 */
389
390 G.tty_attrs.c_cc[VINTR] = CTL('C');
391 G.tty_attrs.c_cc[VQUIT] = CTL('\\');
392 G.tty_attrs.c_cc[VEOF] = CTL('D');
393 G.tty_attrs.c_cc[VEOL] = '\n';
394#ifdef VSWTC
395 G.tty_attrs.c_cc[VSWTC] = 0;
396#endif
397#ifdef VSWTCH
398 G.tty_attrs.c_cc[VSWTCH] = 0;
399#endif
400 G.tty_attrs.c_cc[VKILL] = CTL('U');
401 /* Other control chars:
402 * VEOL2
403 * VERASE, VWERASE - (word) erase. we may set VERASE in get_logname
404 * VREPRINT - reprint current input buffer
405 * VLNEXT, VDISCARD, VSTATUS
406 * VSUSP, VDSUSP - send (delayed) SIGTSTP
407 * VSTART, VSTOP - chars used for IXON/IXOFF
408 */
409
410 set_tty_attrs();
411
412 /* Now the newline character should be properly written */
413 full_write(STDOUT_FILENO, "\n", 1);
414}
415
416/* extract baud rate from modem status message */
417static void auto_baud(void)
418{
419 int nread;
420
421 /*
422 * This works only if the modem produces its status code AFTER raising
423 * the DCD line, and if the computer is fast enough to set the proper
424 * baud rate before the message has gone by. We expect a message of the
425 * following format:
426 *
427 * <junk><number><junk>
428 *
429 * The number is interpreted as the baud rate of the incoming call. If the
430 * modem does not tell us the baud rate within one second, we will keep
431 * using the current baud rate. It is advisable to enable BREAK
432 * processing (comma-separated list of baud rates) if the processing of
433 * modem status messages is enabled.
434 */
435
436 G.tty_attrs.c_cc[VMIN] = 0; /* don't block reads (min read is 0 chars) */
437 set_tty_attrs();
438
439 /*
440 * Wait for a while, then read everything the modem has said so far and
441 * try to extract the speed of the dial-in call.
442 */
443 sleep(1);
444 nread = safe_read(STDIN_FILENO, G.line_buf, sizeof(G.line_buf) - 1);
445 if (nread > 0) {
446 int speed;
447 char *bp;
448 G.line_buf[nread] = '\0';
449 for (bp = G.line_buf; bp < G.line_buf + nread; bp++) {
450 if (isdigit(*bp)) {
451 speed = bcode(bp);
452 if (speed > 0)
453 cfsetspeed(&G.tty_attrs, speed);
454 break;
455 }
456 }
457 }
458
459 /* Restore terminal settings */
460 G.tty_attrs.c_cc[VMIN] = 1; /* restore to value set by init_tty_attrs */
461 set_tty_attrs();
462}
463
464/* get user name, establish parity, speed, erase, kill, eol;
465 * return NULL on BREAK, logname on success
466 */
467static char *get_logname(void)
468{
469 char *bp;
470 char c;
471
472 /* Flush pending input (esp. after parsing or switching the baud rate) */
473 usleep(100*1000); /* 0.1 sec */
474 tcflush(STDIN_FILENO, TCIFLUSH);
475
476 /* Prompt for and read a login name */
477 do {
478 /* Write issue file and prompt */
479#ifdef ISSUE
480 if (!(option_mask32 & F_NOISSUE))
481 print_login_issue(G.issue, G.tty_name);
482#endif
483 print_login_prompt();
484
485 /* Read name, watch for break, erase, kill, end-of-line */
486 bp = G.line_buf;
487 while (1) {
488 /* Do not report trivial EINTR/EIO errors */
489 errno = EINTR; /* make read of 0 bytes be silent too */
490 if (read(STDIN_FILENO, &c, 1) < 1) {
491 finalize_tty_attrs();
492 if (errno == EINTR || errno == EIO)
493 exit(EXIT_SUCCESS);
494 bb_perror_msg_and_die(bb_msg_read_error);
495 }
496
497 switch (c) {
498 case '\r':
499 case '\n':
500 *bp = '\0';
501 G.eol = c;
502 goto got_logname;
503 case CTL('H'):
504 case 0x7f:
505 G.tty_attrs.c_cc[VERASE] = c;
506 if (bp > G.line_buf) {
507 full_write(STDOUT_FILENO, "\010 \010", 3);
508 bp--;
509 }
510 break;
511 case CTL('U'):
512 while (bp > G.line_buf) {
513 full_write(STDOUT_FILENO, "\010 \010", 3);
514 bp--;
515 }
516 break;
517 case CTL('C'):
518 case CTL('D'):
519 finalize_tty_attrs();
520 exit(EXIT_SUCCESS);
521 case '\0':
522 /* BREAK. If we have speeds to try,
523 * return NULL (will switch speeds and return here) */
524 if (G.numspeed > 1)
525 return NULL;
526 /* fall through and ignore it */
527 default:
528 if ((unsigned char)c < ' ') {
529 /* ignore garbage characters */
530 } else if ((int)(bp - G.line_buf) < (int)sizeof(G.line_buf) - 1) {
531 /* echo and store the character */
532 full_write(STDOUT_FILENO, &c, 1);
533 *bp++ = c;
534 }
535 break;
536 }
537 } /* end of get char loop */
538 got_logname: ;
539 } while (G.line_buf[0] == '\0'); /* while logname is empty */
540
541 return G.line_buf;
542}
543
544static void alarm_handler(int sig UNUSED_PARAM)
545{
546 finalize_tty_attrs();
547 _exit(EXIT_SUCCESS);
548}
549
550static void sleep10(void)
551{
552 sleep(10);
553}
554
555int getty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
556int getty_main(int argc UNUSED_PARAM, char **argv)
557{
558 int n;
559 pid_t pid, tsid;
560 char *logname;
561
562 INIT_G();
563 G.login = _PATH_LOGIN; /* default login program */
564#ifdef ISSUE
565 G.issue = ISSUE; /* default issue file */
566#endif
567 G.eol = '\r';
568
569 /* Parse command-line arguments */
570 parse_args(argv);
571
572 /* Create new session and pgrp, lose controlling tty */
573 pid = setsid(); /* this also gives us our pid :) */
574 if (pid < 0) {
575 int fd;
576 /* :(
577 * docs/ctty.htm says:
578 * "This is allowed only when the current process
579 * is not a process group leader".
580 * Thus, setsid() will fail if we _already_ are
581 * a session leader - which is quite possible for getty!
582 */
583 pid = getpid();
584 if (getsid(0) != pid) {
585 //for debugging:
586 //bb_perror_msg_and_die("setsid failed:"
587 // " pid %d ppid %d"
588 // " sid %d pgid %d",
589 // pid, getppid(),
590 // getsid(0), getpgid(0));
591 bb_perror_msg_and_die("setsid");
592 /*
593 * When we can end up here?
594 * Example: setsid() fails when run alone in interactive shell:
595 * # getty 115200 /dev/tty2
596 * because shell's child (getty) is put in a new process group.
597 * But doesn't fail if shell is not interactive
598 * (and therefore doesn't create process groups for pipes),
599 * or if getty is not the first process in the process group:
600 * # true | getty 115200 /dev/tty2
601 */
602 }
603 /* Looks like we are already a session leader.
604 * In this case (setsid failed) we may still have ctty,
605 * and it may be different from tty we need to control!
606 * If we still have ctty, on Linux ioctl(TIOCSCTTY)
607 * (which we are going to use a bit later) always fails -
608 * even if we try to take ctty which is already ours!
609 * Try to drop old ctty now to prevent that.
610 * Use O_NONBLOCK: old ctty may be a serial line.
611 */
612 fd = open("/dev/tty", O_RDWR | O_NONBLOCK);
613 if (fd >= 0) {
614 /* TIOCNOTTY sends SIGHUP to the foreground
615 * process group - which may include us!
616 * Make sure to not die on it:
617 */
618 sighandler_t old = signal(SIGHUP, SIG_IGN);
619 ioctl(fd, TIOCNOTTY);
620 close(fd);
621 signal(SIGHUP, old);
622 }
623 }
624
625 /* Close stdio, and stray descriptors, just in case */
626 n = xopen(bb_dev_null, O_RDWR);
627 /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
628 xdup2(n, 1);
629 xdup2(n, 2);
630 while (n > 2)
631 close(n--);
632
633 /* Logging. We want special flavor of error_msg_and_die */
634 die_func = sleep10;
635 msg_eol = "\r\n";
636 /* most likely will internally use fd #3 in CLOEXEC mode: */
637 openlog(applet_name, LOG_PID, LOG_AUTH);
638 logmode = LOGMODE_BOTH;
639
640#ifdef DEBUGGING
641 dbf = xfopen_for_write(DEBUGTERM);
642 for (n = 1; argv[n]; n++) {
643 debug(argv[n]);
644 debug("\n");
645 }
646#endif
647
648 /* Open the tty as standard input, if it is not "-" */
649 debug("calling open_tty\n");
650 open_tty();
651 ndelay_off(STDIN_FILENO);
652 debug("duping\n");
653 xdup2(STDIN_FILENO, 1);
654 xdup2(STDIN_FILENO, 2);
655
656 /* Steal ctty if we don't have it yet */
657 tsid = tcgetsid(STDIN_FILENO);
658 if (tsid < 0 || pid != tsid) {
659 if (ioctl(STDIN_FILENO, TIOCSCTTY, /*force:*/ (long)1) < 0)
660 bb_perror_msg_and_die("TIOCSCTTY");
661 }
662
663#ifdef __linux__
664 /* Make ourself a foreground process group within our session */
665 if (tcsetpgrp(STDIN_FILENO, pid) < 0)
666 bb_perror_msg_and_die("tcsetpgrp");
667#endif
668
669 /*
670 * The following ioctl will fail if stdin is not a tty, but also when
671 * there is noise on the modem control lines. In the latter case, the
672 * common course of action is (1) fix your cables (2) give the modem more
673 * time to properly reset after hanging up. SunOS users can achieve (2)
674 * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
675 * 5 seconds seems to be a good value.
676 */
677 if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0)
678 bb_perror_msg_and_die("tcgetattr");
679
680 /* Update the utmp file. This tty is ours now! */
681 update_utmp(pid, LOGIN_PROCESS, G.tty_name, "LOGIN", G.fakehost);
682
683 /* Initialize tty attrs (raw mode, eight-bit, blocking i/o) */
684 debug("calling init_tty_attrs\n");
685 init_tty_attrs(G.speeds[0]);
686
687 /* Write the modem init string and DON'T flush the buffers */
688 if (option_mask32 & F_INITSTRING) {
689 debug("writing init string\n");
690 full_write1_str(G.initstring);
691 }
692
693 /* Optionally detect the baud rate from the modem status message */
694 debug("before autobaud\n");
695 if (option_mask32 & F_PARSE)
696 auto_baud();
697
698 /* Set the optional timer */
699 signal(SIGALRM, alarm_handler);
700 alarm(G.timeout); /* if 0, alarm is not set */
701
702 /* Optionally wait for CR or LF before writing /etc/issue */
703 if (option_mask32 & F_WAITCRLF) {
704 char ch;
705 debug("waiting for cr-lf\n");
706 while (safe_read(STDIN_FILENO, &ch, 1) == 1) {
707 debug("read %x\n", (unsigned char)ch);
708 if (ch == '\n' || ch == '\r')
709 break;
710 }
711 }
712
713 logname = NULL;
714 if (!(option_mask32 & F_NOPROMPT)) {
715 /* NB: init_tty_attrs already set line speed
716 * to G.speeds[0] */
717 int baud_index = 0;
718
719 while (1) {
720 /* Read the login name */
721 debug("reading login name\n");
722 logname = get_logname();
723 if (logname)
724 break;
725 /* We are here only if G.numspeed > 1 */
726 baud_index = (baud_index + 1) % G.numspeed;
727 cfsetspeed(&G.tty_attrs, G.speeds[baud_index]);
728 set_tty_attrs();
729 }
730 }
731
732 /* Disable timer */
733 alarm(0);
734
735 finalize_tty_attrs();
736
737 /* Let the login program take care of password validation */
738 /* We use PATH because we trust that root doesn't set "bad" PATH,
739 * and getty is not suid-root applet */
740 /* With -n, logname == NULL, and login will ask for username instead */
741 BB_EXECLP(G.login, G.login, "--", logname, (char *)0);
742 bb_error_msg_and_die("can't execute '%s'", G.login);
743}
744