source: branches/3.2/mindi-busybox/loginutils/getty.c @ 3232

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