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