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