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