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