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