0f5e333a76122030259a05a884a14d4bc41d04f5
[platform/upstream/busybox.git] / loginutils / getty.c
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.
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  * - enable hardware flow control before displaying /etc/issue
14  *
15  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
16  */
17
18 #include "libbb.h"
19 #include <syslog.h>
20
21 #if ENABLE_FEATURE_UTMP
22 # include <utmp.h> /* LOGIN_PROCESS */
23 #endif
24
25 #ifndef IUCLC
26 # define IUCLC 0
27 #endif
28
29 /*
30  * Some heuristics to find out what environment we are in: if it is not
31  * System V, assume it is SunOS 4.
32  */
33 #ifdef LOGIN_PROCESS                    /* defined in System V utmp.h */
34 # include <sys/utsname.h>
35 #else /* if !sysV style, wtmp/utmp code is off */
36 # undef ENABLE_FEATURE_UTMP
37 # undef ENABLE_FEATURE_WTMP
38 # define ENABLE_FEATURE_UTMP 0
39 # define ENABLE_FEATURE_WTMP 0
40 #endif  /* LOGIN_PROCESS */
41
42
43 /* The following is used for understandable diagnostics. */
44 #ifdef DEBUGGING
45 static FILE *dbf;
46 # define DEBUGTERM "/dev/ttyp0"
47 # define debug(...) do { fprintf(dbf, __VA_ARGS__); fflush(dbf); } while (0)
48 #else
49 # define debug(...) ((void)0)
50 #endif
51
52
53 /*
54  * Things you may want to modify.
55  *
56  * You may disagree with the default line-editing etc. characters defined
57  * below. Note, however, that DEL cannot be used for interrupt generation
58  * and for line editing at the same time.
59  */
60
61 /* I doubt there are systems which still need this */
62 #undef HANDLE_ALLCAPS
63 #undef ANCIENT_BS_KILL_CHARS
64
65 #undef  _PATH_LOGIN
66 #define _PATH_LOGIN "/bin/login"
67
68 /* Displayed before the login prompt.
69  * If ISSUE is not defined, getty will never display the contents of the
70  * /etc/issue file. You will not want to spit out large "issue" files at the
71  * wrong baud rate.
72  */
73 #define ISSUE "/etc/issue"
74
75 /* Some shorthands for control characters. */
76 #define CTL(x)          ((x) ^ 0100)    /* Assumes ASCII dialect */
77 #define CR              CTL('M')        /* carriage return */
78 #define NL              CTL('J')        /* line feed */
79 #define BS              CTL('H')        /* back space */
80 #define DEL             CTL('?')        /* delete */
81
82 /* Defaults for line-editing etc. characters; you may want to change this. */
83 #define DEF_ERASE       DEL             /* default erase character */
84 #define DEF_INTR        CTL('C')        /* default interrupt character */
85 #define DEF_QUIT        CTL('\\')       /* default quit char */
86 #define DEF_KILL        CTL('U')        /* default kill char */
87 #define DEF_EOF         CTL('D')        /* default EOF char */
88 #define DEF_EOL         '\n'
89 #define DEF_SWITCH      0               /* default switch char */
90
91 /*
92  * When multiple baud rates are specified on the command line, the first one
93  * we will try is the first one specified.
94  */
95 #define MAX_SPEED       10              /* max. nr. of baud rates */
96
97 /* Storage for command-line options. */
98 struct options {
99         unsigned timeout;               /* time-out period */
100         const char *login;              /* login program */
101         const char *tty;                /* name of tty */
102         const char *initstring;         /* modem init string */
103         const char *issue;              /* alternative issue file */
104         int numspeed;                   /* number of baud rates to try */
105         int speeds[MAX_SPEED];          /* baud rates to be tried */
106 };
107
108 /* Storage for things detected while the login name was read. */
109 struct chardata {
110         unsigned char erase;    /* erase character */
111         unsigned char kill;     /* kill character */
112         unsigned char eol;      /* end-of-line character */
113         unsigned char parity;   /* what parity did we see */
114         /* (parity & 1): saw odd parity char with 7th bit set */
115         /* (parity & 2): saw even parity char with 7th bit set */
116         /* parity == 0: probably 7-bit, space parity? */
117         /* parity == 1: probably 7-bit, odd parity? */
118         /* parity == 2: probably 7-bit, even parity? */
119         /* parity == 3: definitely 8 bit, no parity! */
120         /* Hmm... with any value of "parity" 8 bit, no parity is possible */
121 #ifdef HANDLE_ALLCAPS
122         unsigned char capslock; /* upper case without lower case */
123 #endif
124 };
125
126 /* Initial values for the above. */
127 static const struct chardata init_chardata = {
128         DEF_ERASE,                              /* default erase character */
129         DEF_KILL,                               /* default kill character */
130         13,                                     /* default eol char */
131         0,                                      /* space parity */
132 #ifdef HANDLE_ALLCAPS
133         0,                                      /* no capslock */
134 #endif
135 };
136
137 #define line_buf bb_common_bufsiz1
138
139 //usage:#define getty_trivial_usage
140 //usage:       "[OPTIONS] BAUD_RATE TTY [TERMTYPE]"
141 //usage:#define getty_full_usage "\n\n"
142 //usage:       "Open a tty, prompt for a login name, then invoke /bin/login\n"
143 //usage:     "\nOptions:"
144 //usage:     "\n        -h              Enable hardware (RTS/CTS) flow control"
145 //usage:     "\n        -i              Don't display /etc/issue"
146 //usage:     "\n        -L              Local line, don't do carrier detect"
147 //usage:     "\n        -m              Get baud rate from modem's CONNECT status message"
148 //usage:     "\n        -w              Wait for a CR or LF before sending /etc/issue"
149 //usage:     "\n        -n              Don't prompt the user for a login name"
150 //usage:     "\n        -f ISSUE_FILE   Display ISSUE_FILE instead of /etc/issue"
151 //usage:     "\n        -l LOGIN        Invoke LOGIN instead of /bin/login"
152 //usage:     "\n        -t SEC          Terminate after SEC if no username is read"
153 //usage:     "\n        -I INITSTR      Send INITSTR before anything else"
154 //usage:     "\n        -H HOST         Log HOST into the utmp file as the hostname"
155
156 static const char opt_string[] ALIGN1 = "I:LH:f:hil:mt:wn";
157 #define F_INITSTRING    (1 << 0)   /* -I */
158 #define F_LOCAL         (1 << 1)   /* -L */
159 #define F_FAKEHOST      (1 << 2)   /* -H */
160 #define F_CUSTISSUE     (1 << 3)   /* -f */
161 #define F_RTSCTS        (1 << 4)   /* -h */
162 #define F_NOISSUE       (1 << 5)   /* -i */
163 #define F_LOGIN         (1 << 6)   /* -l */
164 #define F_PARSE         (1 << 7)   /* -m */
165 #define F_TIMEOUT       (1 << 8)   /* -t */
166 #define F_WAITCRLF      (1 << 9)   /* -w */
167 #define F_NOPROMPT      (1 << 10)  /* -n */
168
169
170 /* bcode - convert speed string to speed code; return <= 0 on failure */
171 static int bcode(const char *s)
172 {
173         int value = bb_strtou(s, NULL, 10); /* yes, int is intended! */
174         if (value < 0) /* bad terminating char, overflow, etc */
175                 return value;
176         return tty_value_to_baud(value);
177 }
178
179 /* parse_speeds - parse alternate baud rates */
180 static void parse_speeds(struct options *op, char *arg)
181 {
182         char *cp;
183
184         /* NB: at least one iteration is always done */
185         debug("entered parse_speeds\n");
186         while ((cp = strsep(&arg, ",")) != NULL) {
187                 op->speeds[op->numspeed] = bcode(cp);
188                 if (op->speeds[op->numspeed] < 0)
189                         bb_error_msg_and_die("bad speed: %s", cp);
190                 /* note: arg "0" turns into speed B0 */
191                 op->numspeed++;
192                 if (op->numspeed > MAX_SPEED)
193                         bb_error_msg_and_die("too many alternate speeds");
194         }
195         debug("exiting parse_speeds\n");
196 }
197
198 /* parse_args - parse command-line arguments */
199 static void parse_args(char **argv, struct options *op, char **fakehost_p)
200 {
201         char *ts;
202         int flags;
203
204         opt_complementary = "-2:t+"; /* at least 2 args; -t N */
205         flags = getopt32(argv, opt_string,
206                 &(op->initstring), fakehost_p, &(op->issue),
207                 &(op->login), &op->timeout);
208         if (flags & F_INITSTRING) {
209                 op->initstring = xstrdup(op->initstring);
210                 /* decode \ddd octal codes into chars */
211                 strcpy_and_process_escape_sequences((char*)op->initstring, op->initstring);
212         }
213         argv += optind;
214         debug("after getopt\n");
215
216         /* we loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
217         op->tty = argv[0];      /* tty name */
218         ts = argv[1];           /* baud rate(s) */
219         if (isdigit(argv[0][0])) {
220                 /* a number first, assume it's a speed (BSD style) */
221                 op->tty = ts;   /* tty name is in argv[1] */
222                 ts = argv[0];   /* baud rate(s) */
223         }
224         parse_speeds(op, ts);
225         applet_name = xasprintf("getty: %s", op->tty);
226
227         if (argv[2])
228                 xsetenv("TERM", argv[2]);
229
230         debug("exiting parse_args\n");
231 }
232
233 /* open_tty - set up tty as standard { input, output, error } */
234 static void open_tty(const char *tty)
235 {
236         /* Set up new standard input, unless we are given an already opened port. */
237         if (NOT_LONE_DASH(tty)) {
238                 if (tty[0] != '/')
239                         tty = xasprintf("/dev/%s", tty); /* will leak it */
240
241                 /* Open the tty as standard input. */
242                 debug("open(2)\n");
243                 close(0);
244                 /*fd =*/ xopen(tty, O_RDWR | O_NONBLOCK); /* uses fd 0 */
245
246                 /* Set proper protections and ownership. */
247                 fchown(0, 0, 0);        /* 0:0 */
248                 fchmod(0, 0620);        /* crw--w---- */
249         } else {
250                 /*
251                  * Standard input should already be connected to an open port. Make
252                  * sure it is open for read/write.
253                  */
254                 if ((fcntl(0, F_GETFL) & O_RDWR) != O_RDWR)
255                         bb_error_msg_and_die("stdin is not open for read/write");
256         }
257 }
258
259 /* termios_init - initialize termios settings */
260 static void termios_init(struct termios *tp, int speed)
261 {
262         speed_t ispeed, ospeed;
263         /*
264          * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
265          * Special characters are set after we have read the login name; all
266          * reads will be done in raw mode anyway. Errors will be dealt with
267          * later on.
268          */
269         /* flush input and output queues, important for modems! */
270         tcflush(0, TCIOFLUSH);
271         ispeed = ospeed = speed;
272         if (speed == B0) {
273                 /* Speed was specified as "0" on command line.
274                  * Just leave it unchanged */
275                 ispeed = cfgetispeed(tp);
276                 ospeed = cfgetospeed(tp);
277         }
278         tp->c_cflag = CS8 | HUPCL | CREAD;
279         if (option_mask32 & F_LOCAL)
280                 tp->c_cflag |= CLOCAL;
281         cfsetispeed(tp, ispeed);
282         cfsetospeed(tp, ospeed);
283
284         tp->c_iflag = tp->c_lflag = 0;
285         tp->c_oflag = OPOST | ONLCR;
286         tp->c_cc[VMIN] = 1;
287         tp->c_cc[VTIME] = 0;
288 #ifdef __linux__
289         tp->c_line = 0;
290 #endif
291
292         /* Optionally enable hardware flow control */
293 #ifdef CRTSCTS
294         if (option_mask32 & F_RTSCTS)
295                 tp->c_cflag |= CRTSCTS;
296 #endif
297
298         tcsetattr_stdin_TCSANOW(tp);
299
300         debug("term_io 2\n");
301 }
302
303 /* auto_baud - extract baud rate from modem status message */
304 static void auto_baud(char *buf, unsigned size_buf, struct termios *tp)
305 {
306         int speed;
307         int vmin;
308         unsigned iflag;
309         char *bp;
310         int nread;
311
312         /*
313          * This works only if the modem produces its status code AFTER raising
314          * the DCD line, and if the computer is fast enough to set the proper
315          * baud rate before the message has gone by. We expect a message of the
316          * following format:
317          *
318          * <junk><number><junk>
319          *
320          * The number is interpreted as the baud rate of the incoming call. If the
321          * modem does not tell us the baud rate within one second, we will keep
322          * using the current baud rate. It is advisable to enable BREAK
323          * processing (comma-separated list of baud rates) if the processing of
324          * modem status messages is enabled.
325          */
326
327         /*
328          * Use 7-bit characters, don't block if input queue is empty. Errors will
329          * be dealt with later on.
330          */
331         iflag = tp->c_iflag;
332         tp->c_iflag |= ISTRIP;          /* enable 8th-bit stripping */
333         vmin = tp->c_cc[VMIN];
334         tp->c_cc[VMIN] = 0;             /* don't block if queue empty */
335         tcsetattr_stdin_TCSANOW(tp);
336
337         /*
338          * Wait for a while, then read everything the modem has said so far and
339          * try to extract the speed of the dial-in call.
340          */
341         sleep(1);
342         nread = safe_read(STDIN_FILENO, buf, size_buf - 1);
343         if (nread > 0) {
344                 buf[nread] = '\0';
345                 for (bp = buf; bp < buf + nread; bp++) {
346                         if (isdigit(*bp)) {
347                                 speed = bcode(bp);
348                                 if (speed > 0)
349                                         cfsetspeed(tp, speed);
350                                 break;
351                         }
352                 }
353         }
354
355         /* Restore terminal settings. Errors will be dealt with later on. */
356         tp->c_iflag = iflag;
357         tp->c_cc[VMIN] = vmin;
358         tcsetattr_stdin_TCSANOW(tp);
359 }
360
361 /* do_prompt - show login prompt, optionally preceded by /etc/issue contents */
362 static void do_prompt(struct options *op)
363 {
364 #ifdef ISSUE
365         if (!(option_mask32 & F_NOISSUE))
366                 print_login_issue(op->issue, op->tty);
367 #endif
368         print_login_prompt();
369 }
370
371 #ifdef HANDLE_ALLCAPS
372 /* all_is_upcase - string contains upper case without lower case */
373 /* returns 1 if true, 0 if false */
374 static int all_is_upcase(const char *s)
375 {
376         while (*s)
377                 if (islower(*s++))
378                         return 0;
379         return 1;
380 }
381 #endif
382
383 /* get_logname - get user name, establish parity, speed, erase, kill, eol;
384  * return NULL on BREAK, logname on success */
385 static char *get_logname(char *logname, unsigned size_logname,
386                 struct options *op, struct chardata *cp)
387 {
388         char *bp;
389         char c;                         /* input character, full eight bits */
390         char ascval;                    /* low 7 bits of input character */
391         int bits;                       /* # of "1" bits per character */
392         int mask;                       /* mask with 1 bit up */
393         static const char erase[][3] = {/* backspace-space-backspace */
394                 "\010\040\010",                 /* space parity */
395                 "\010\040\010",                 /* odd parity */
396                 "\210\240\210",                 /* even parity */
397                 "\010\040\010",                 /* 8 bit no parity */
398         };
399
400         /* NB: *cp is pre-initialized with init_chardata */
401
402         /* Flush pending input (esp. after parsing or switching the baud rate). */
403         sleep(1);
404         tcflush(0, TCIOFLUSH);
405
406         /* Prompt for and read a login name. */
407         logname[0] = '\0';
408         while (!logname[0]) {
409                 /* Write issue file and prompt, with "parity" bit == 0. */
410                 do_prompt(op);
411
412                 /* Read name, watch for break, parity, erase, kill, end-of-line. */
413                 bp = logname;
414                 cp->eol = '\0';
415                 while (cp->eol == '\0') {
416
417                         /* Do not report trivial EINTR/EIO errors. */
418                         errno = EINTR; /* make read of 0 bytes be silent too */
419                         if (read(STDIN_FILENO, &c, 1) < 1) {
420                                 if (errno == EINTR || errno == EIO)
421                                         exit(EXIT_SUCCESS);
422                                 bb_perror_msg_and_die(bb_msg_read_error);
423                         }
424
425                         /* BREAK. If we have speeds to try,
426                          * return NULL (will switch speeds and return here) */
427                         if (c == '\0' && op->numspeed > 1)
428                                 return NULL;
429
430                         /* Do parity bit handling. */
431                         if (!(option_mask32 & F_LOCAL) && (c & 0x80)) {       /* "parity" bit on? */
432                                 bits = 1;
433                                 mask = 1;
434                                 while (mask & 0x7f) {
435                                         if (mask & c)
436                                                 bits++; /* count "1" bits */
437                                         mask <<= 1;
438                                 }
439                                 /* ... |= 2 - even, 1 - odd */
440                                 cp->parity |= 2 - (bits & 1);
441                         }
442
443                         /* Do erase, kill and end-of-line processing. */
444                         ascval = c & 0x7f;
445                         switch (ascval) {
446                         case CR:
447                         case NL:
448                                 *bp = '\0';             /* terminate logname */
449                                 cp->eol = ascval;       /* set end-of-line char */
450                                 break;
451                         case BS:
452                         case DEL:
453 #ifdef ANCIENT_BS_KILL_CHARS
454                         case '#':
455 #endif
456                                 cp->erase = ascval;     /* set erase character */
457                                 if (bp > logname) {
458                                         full_write(STDOUT_FILENO, erase[cp->parity], 3);
459                                         bp--;
460                                 }
461                                 break;
462                         case CTL('U'):
463 #ifdef ANCIENT_BS_KILL_CHARS
464                         case '@':
465 #endif
466                                 cp->kill = ascval;      /* set kill character */
467                                 while (bp > logname) {
468                                         full_write(STDOUT_FILENO, erase[cp->parity], 3);
469                                         bp--;
470                                 }
471                                 break;
472                         case CTL('D'):
473                                 exit(EXIT_SUCCESS);
474                         default:
475                                 if (ascval < ' ') {
476                                         /* ignore garbage characters */
477                                 } else if ((int)(bp - logname) >= size_logname - 1) {
478                                         bb_error_msg_and_die("input overrun");
479                                 } else {
480                                         full_write(STDOUT_FILENO, &c, 1); /* echo the character */
481                                         *bp++ = ascval; /* and store it */
482                                 }
483                                 break;
484                         }
485                 }
486         }
487         /* Handle names with upper case and no lower case. */
488
489 #ifdef HANDLE_ALLCAPS
490         cp->capslock = all_is_upcase(logname);
491         if (cp->capslock) {
492                 for (bp = logname; *bp; bp++)
493                         if (isupper(*bp))
494                                 *bp = tolower(*bp);     /* map name to lower case */
495         }
496 #endif
497         return logname;
498 }
499
500 /* termios_final - set the final tty mode bits */
501 static void termios_final(struct termios *tp, struct chardata *cp)
502 {
503         /* General terminal-independent stuff. */
504         tp->c_iflag |= IXON | IXOFF;    /* 2-way flow control */
505         tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
506         /* no longer| ECHOCTL | ECHOPRT */
507         tp->c_oflag |= OPOST;
508         /* tp->c_cflag = 0; */
509         tp->c_cc[VINTR] = DEF_INTR;     /* default interrupt */
510         tp->c_cc[VQUIT] = DEF_QUIT;     /* default quit */
511         tp->c_cc[VEOF] = DEF_EOF;       /* default EOF character */
512         tp->c_cc[VEOL] = DEF_EOL;
513 #ifdef VSWTC
514         tp->c_cc[VSWTC] = DEF_SWITCH;   /* default switch character */
515 #endif
516
517         /* Account for special characters seen in input. */
518         if (cp->eol == CR) {
519                 tp->c_iflag |= ICRNL;   /* map CR in input to NL */
520                 tp->c_oflag |= ONLCR;   /* map NL in output to CR-NL */
521         }
522         tp->c_cc[VERASE] = cp->erase;   /* set erase character */
523         tp->c_cc[VKILL] = cp->kill;     /* set kill character */
524
525         /* Account for the presence or absence of parity bits in input. */
526         switch (cp->parity) {
527         case 0:                                 /* space (always 0) parity */
528 // I bet most people go here - they use only 7-bit chars in usernames....
529                 break;
530         case 1:                                 /* odd parity */
531                 tp->c_cflag |= PARODD;
532                 /* FALLTHROUGH */
533         case 2:                                 /* even parity */
534                 tp->c_cflag |= PARENB;
535                 tp->c_iflag |= INPCK | ISTRIP;
536                 /* FALLTHROUGH */
537         case (1 | 2):                           /* no parity bit */
538                 tp->c_cflag &= ~CSIZE;
539                 tp->c_cflag |= CS7;
540 // FIXME: wtf? case 3: we saw both even and odd 8-bit bytes -
541 // it's probably some umlauts etc, but definitely NOT 7-bit!!!
542 // Entire parity detection madness here just begs for deletion...
543                 break;
544         }
545
546         /* Account for upper case without lower case. */
547 #ifdef HANDLE_ALLCAPS
548         if (cp->capslock) {
549                 tp->c_iflag |= IUCLC;
550                 tp->c_lflag |= XCASE;
551                 tp->c_oflag |= OLCUC;
552         }
553 #endif
554         /* Optionally enable hardware flow control */
555 #ifdef CRTSCTS
556         if (option_mask32 & F_RTSCTS)
557                 tp->c_cflag |= CRTSCTS;
558 #endif
559
560         /* Finally, make the new settings effective */
561         if (tcsetattr_stdin_TCSANOW(tp) < 0)
562                 bb_perror_msg_and_die("tcsetattr");
563 }
564
565 int getty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
566 int getty_main(int argc UNUSED_PARAM, char **argv)
567 {
568         int n;
569         pid_t pid;
570         char *fakehost = NULL;          /* Fake hostname for ut_host */
571         char *logname;                  /* login name, given to /bin/login */
572         /* Merging these into "struct local" may _seem_ to reduce
573          * parameter passing, but today's gcc will inline
574          * statics which are called once anyway, so don't do that */
575         struct chardata chardata;       /* set by get_logname() */
576         struct termios termios;         /* terminal mode bits */
577         struct options options;
578
579         chardata = init_chardata;
580
581         memset(&options, 0, sizeof(options));
582         options.login = _PATH_LOGIN;    /* default login program */
583         options.tty = "tty1";           /* default tty line */
584         options.initstring = "";        /* modem init string */
585 #ifdef ISSUE
586         options.issue = ISSUE;          /* default issue file */
587 #endif
588
589         /* Parse command-line arguments. */
590         parse_args(argv, &options, &fakehost);
591
592         logmode = LOGMODE_NONE;
593
594         /* Create new session, lose controlling tty, if any */
595         /* docs/ctty.htm says:
596          * "This is allowed only when the current process
597          *  is not a process group leader" - is this a problem? */
598         setsid();
599         /* close stdio, and stray descriptors, just in case */
600         n = xopen(bb_dev_null, O_RDWR);
601         /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
602         xdup2(n, 1);
603         xdup2(n, 2);
604         while (n > 2)
605                 close(n--);
606
607         /* Logging. We want special flavor of error_msg_and_die */
608         die_sleep = 10;
609         msg_eol = "\r\n";
610         /* most likely will internally use fd #3 in CLOEXEC mode: */
611         openlog(applet_name, LOG_PID, LOG_AUTH);
612         logmode = LOGMODE_BOTH;
613
614 #ifdef DEBUGGING
615         dbf = xfopen_for_write(DEBUGTERM);
616         for (n = 1; argv[n]; n++) {
617                 debug(argv[n]);
618                 debug("\n");
619         }
620 #endif
621
622         /* Open the tty as standard input, if it is not "-" */
623         /* If it's not "-" and not taken yet, it will become our ctty */
624         debug("calling open_tty\n");
625         open_tty(options.tty);
626         ndelay_off(0);
627         debug("duping\n");
628         xdup2(0, 1);
629         xdup2(0, 2);
630
631         /*
632          * The following ioctl will fail if stdin is not a tty, but also when
633          * there is noise on the modem control lines. In the latter case, the
634          * common course of action is (1) fix your cables (2) give the modem more
635          * time to properly reset after hanging up. SunOS users can achieve (2)
636          * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
637          * 5 seconds seems to be a good value.
638          */
639         if (tcgetattr(0, &termios) < 0)
640                 bb_perror_msg_and_die("tcgetattr");
641
642         pid = getpid();
643 #ifdef __linux__
644 // FIXME: do we need this? Otherwise "-" case seems to be broken...
645         // /* Forcibly make fd 0 our controlling tty, even if another session
646         //  * has it as a ctty. (Another session loses ctty). */
647         // ioctl(0, TIOCSCTTY, (void*)1);
648         /* Make ourself a foreground process group within our session */
649         tcsetpgrp(0, pid);
650 #endif
651
652         /* Update the utmp file. This tty is ours now! */
653         update_utmp(pid, LOGIN_PROCESS, options.tty, "LOGIN", fakehost);
654
655         /* Initialize the termios settings (raw mode, eight-bit, blocking i/o). */
656         debug("calling termios_init\n");
657         termios_init(&termios, options.speeds[0]);
658
659         /* Write the modem init string and DON'T flush the buffers */
660         if (option_mask32 & F_INITSTRING) {
661                 debug("writing init string\n");
662                 full_write1_str(options.initstring);
663         }
664
665         /* Optionally detect the baud rate from the modem status message */
666         debug("before autobaud\n");
667         if (option_mask32 & F_PARSE)
668                 auto_baud(line_buf, sizeof(line_buf), &termios);
669
670         /* Set the optional timer */
671         alarm(options.timeout); /* if 0, alarm is not set */
672
673         /* Optionally wait for CR or LF before writing /etc/issue */
674         if (option_mask32 & F_WAITCRLF) {
675                 char ch;
676
677                 debug("waiting for cr-lf\n");
678                 while (safe_read(STDIN_FILENO, &ch, 1) == 1) {
679                         debug("read %x\n", (unsigned char)ch);
680                         ch &= 0x7f;                     /* strip "parity bit" */
681                         if (ch == '\n' || ch == '\r')
682                                 break;
683                 }
684         }
685
686         logname = NULL;
687         if (!(option_mask32 & F_NOPROMPT)) {
688                 /* NB:termios_init already set line speed
689                  * to options.speeds[0] */
690                 int baud_index = 0;
691
692                 while (1) {
693                         /* Read the login name. */
694                         debug("reading login name\n");
695                         logname = get_logname(line_buf, sizeof(line_buf),
696                                         &options, &chardata);
697                         if (logname)
698                                 break;
699                         /* we are here only if options.numspeed > 1 */
700                         baud_index = (baud_index + 1) % options.numspeed;
701                         cfsetispeed(&termios, options.speeds[baud_index]);
702                         cfsetospeed(&termios, options.speeds[baud_index]);
703                         tcsetattr_stdin_TCSANOW(&termios);
704                 }
705         }
706
707         /* Disable timer. */
708         alarm(0);
709
710         /* Finalize the termios settings. */
711         termios_final(&termios, &chardata);
712
713         /* Now the newline character should be properly written. */
714         full_write(STDOUT_FILENO, "\n", 1);
715
716         /* Let the login program take care of password validation. */
717         /* We use PATH because we trust that root doesn't set "bad" PATH,
718          * and getty is not suid-root applet. */
719         /* With -n, logname == NULL, and login will ask for username instead */
720         BB_EXECLP(options.login, options.login, "--", logname, NULL);
721         bb_error_msg_and_die("can't execute '%s'", options.login);
722 }