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