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