Antti Seppala (with dots over the last two a's) wants our getty to initialize
[platform/upstream/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_line = 0;
478         tp->c_oflag = OPOST | ONLCR;
479         tp->c_cc[VMIN] = 1;
480         tp->c_cc[VTIME] = 0;
481
482         /* Optionally enable hardware flow control */
483
484 #ifdef  CRTSCTS
485         if (op->flags & F_RTSCTS)
486                 tp->c_cflag |= CRTSCTS;
487 #endif
488
489         (void) ioctl(0, TCSETA, tp);
490
491         /* go to blocking input even in local mode */
492         fcntl(0, F_SETFL, fcntl(0, F_GETFL, 0) & ~O_NONBLOCK);
493
494         debug("term_io 2\n");
495 }
496
497 /* auto_baud - extract baud rate from modem status message */
498 static void auto_baud(struct termio *tp)
499 {
500         int speed;
501         int vmin;
502         unsigned iflag;
503         char buf[BUFSIZ];
504         char *bp;
505         int nread;
506
507         /*
508          * This works only if the modem produces its status code AFTER raising
509          * the DCD line, and if the computer is fast enough to set the proper
510          * baud rate before the message has gone by. We expect a message of the
511          * following format:
512          *
513          * <junk><number><junk>
514          *
515          * The number is interpreted as the baud rate of the incoming call. If the
516          * modem does not tell us the baud rate within one second, we will keep
517          * using the current baud rate. It is advisable to enable BREAK
518          * processing (comma-separated list of baud rates) if the processing of
519          * modem status messages is enabled.
520          */
521
522         /*
523          * Use 7-bit characters, don't block if input queue is empty. Errors will
524          * be dealt with lateron.
525          */
526
527         iflag = tp->c_iflag;
528         tp->c_iflag |= ISTRIP;          /* enable 8th-bit stripping */
529         vmin = tp->c_cc[VMIN];
530         tp->c_cc[VMIN] = 0;                     /* don't block if queue empty */
531         (void) ioctl(0, TCSETA, tp);
532
533         /*
534          * Wait for a while, then read everything the modem has said so far and
535          * try to extract the speed of the dial-in call.
536          */
537
538         (void) sleep(1);
539         if ((nread = read(0, buf, sizeof(buf) - 1)) > 0) {
540                 buf[nread] = '\0';
541                 for (bp = buf; bp < buf + nread; bp++) {
542                         if (isascii(*bp) && isdigit(*bp)) {
543                                 if ((speed = bcode(bp))) {
544                                         tp->c_cflag &= ~CBAUD;
545                                         tp->c_cflag |= speed;
546                                 }
547                                 break;
548                         }
549                 }
550         }
551         /* Restore terminal settings. Errors will be dealt with lateron. */
552
553         tp->c_iflag = iflag;
554         tp->c_cc[VMIN] = vmin;
555         (void) ioctl(0, TCSETA, tp);
556 }
557
558 /* next_speed - select next baud rate */
559 static void next_speed(struct termio *tp, struct options *op)
560 {
561         static int baud_index = FIRST_SPEED;    /* current speed index */
562
563         baud_index = (baud_index + 1) % op->numspeed;
564         tp->c_cflag &= ~CBAUD;
565         tp->c_cflag |= op->speeds[baud_index];
566         (void) ioctl(0, TCSETA, tp);
567 }
568
569
570 /* do_prompt - show login prompt, optionally preceded by /etc/issue contents */
571 static void do_prompt(struct options *op, struct termio *tp)
572 {
573 #ifdef  ISSUE                                   /* optional: show /etc/issue */
574         print_login_issue(op->issue, op->tty);
575 #endif
576         print_login_prompt();
577 }
578
579 /* caps_lock - string contains upper case without lower case */
580 /* returns 1 if true, 0 if false */
581 static int caps_lock(const char *s)
582 {
583         int capslock;
584
585         for (capslock = 0; *s; s++) {
586                 if (islower(*s))
587                         return (0);
588                 if (capslock == 0)
589                         capslock = isupper(*s);
590         }
591         return (capslock);
592 }
593
594 #define logname bb_common_bufsiz1
595 /* get_logname - get user name, establish parity, speed, erase, kill, eol */
596 /* return NULL on failure, logname on success */
597 static char *get_logname(struct options *op, struct chardata *cp, struct termio *tp)
598 {
599         char *bp;
600         char c;                         /* input character, full eight bits */
601         char ascval;                    /* low 7 bits of input character */
602         int bits;                       /* # of "1" bits per character */
603         int mask;                       /* mask with 1 bit up */
604         static char *erase[] = {        /* backspace-space-backspace */
605                 "\010\040\010",                 /* space parity */
606                 "\010\040\010",                 /* odd parity */
607                 "\210\240\210",                 /* even parity */
608                 "\210\240\210",                 /* no parity */
609         };
610
611         /* Initialize kill, erase, parity etc. (also after switching speeds). */
612
613         *cp = init_chardata;
614
615         /* Flush pending input (esp. after parsing or switching the baud rate). */
616
617         (void) sleep(1);
618         (void) ioctl(0, TCFLSH, TCIFLUSH);
619
620         /* Prompt for and read a login name. */
621
622         for (*logname = 0; *logname == 0; /* void */ ) {
623
624                 /* Write issue file and prompt, with "parity" bit == 0. */
625
626                 do_prompt(op, tp);
627
628                 /* Read name, watch for break, parity, erase, kill, end-of-line. */
629
630                 for (bp = logname, cp->eol = 0; cp->eol == 0; /* void */ ) {
631
632                         /* Do not report trivial EINTR/EIO errors. */
633
634                         if (read(0, &c, 1) < 1) {
635                                 if (errno == EINTR || errno == EIO)
636                                         exit(0);
637                                 error("%s: read: %m", op->tty);
638                         }
639                         /* Do BREAK handling elsewhere. */
640
641                         if ((c == 0) && op->numspeed > 1)
642                                 /* return (0); */
643                                 return NULL;
644
645                         /* Do parity bit handling. */
646
647                         if (c != (ascval = (c & 0177))) {       /* "parity" bit on ? */
648                                 for (bits = 1, mask = 1; mask & 0177; mask <<= 1)
649                                         if (mask & ascval)
650                                                 bits++; /* count "1" bits */
651                                 cp->parity |= ((bits & 1) ? 1 : 2);
652                         }
653                         /* Do erase, kill and end-of-line processing. */
654
655                         switch (ascval) {
656                         case CR:
657                         case NL:
658                                 *bp = 0;                /* terminate logname */
659                                 cp->eol = ascval;       /* set end-of-line char */
660                                 break;
661                         case BS:
662                         case DEL:
663                         case '#':
664                                 cp->erase = ascval;     /* set erase character */
665                                 if (bp > logname) {
666                                         (void) write(1, erase[cp->parity], 3);
667                                         bp--;
668                                 }
669                                 break;
670                         case CTL('U'):
671                         case '@':
672                                 cp->kill = ascval;      /* set kill character */
673                                 while (bp > logname) {
674                                         (void) write(1, erase[cp->parity], 3);
675                                         bp--;
676                                 }
677                                 break;
678                         case CTL('D'):
679                                 exit(0);
680                         default:
681                                 if (!isascii(ascval) || !isprint(ascval)) {
682                                         /* ignore garbage characters */ ;
683                                 } else if (bp - logname >= sizeof(logname) - 1) {
684                                         error("%s: input overrun", op->tty);
685                                 } else {
686                                         (void) write(1, &c, 1); /* echo the character */
687                                         *bp++ = ascval; /* and store it */
688                                 }
689                                 break;
690                         }
691                 }
692         }
693         /* Handle names with upper case and no lower case. */
694
695         if ((cp->capslock = caps_lock(logname))) {
696                 for (bp = logname; *bp; bp++)
697                         if (isupper(*bp))
698                                 *bp = tolower(*bp);     /* map name to lower case */
699         }
700         return (logname);
701 }
702
703 /* termio_final - set the final tty mode bits */
704 static void termio_final(struct options *op, struct termio *tp, struct chardata *cp)
705 {
706         /* General terminal-independent stuff. */
707
708         tp->c_iflag |= IXON | IXOFF;    /* 2-way flow control */
709         tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
710         /* no longer| ECHOCTL | ECHOPRT */
711         tp->c_oflag |= OPOST;
712         /* tp->c_cflag = 0; */
713         tp->c_cc[VINTR] = DEF_INTR;     /* default interrupt */
714         tp->c_cc[VQUIT] = DEF_QUIT;     /* default quit */
715         tp->c_cc[VEOF] = DEF_EOF;       /* default EOF character */
716         tp->c_cc[VEOL] = DEF_EOL;
717         tp->c_cc[VSWTC] = DEF_SWITCH;   /* default switch character */
718
719         /* Account for special characters seen in input. */
720
721         if (cp->eol == CR) {
722                 tp->c_iflag |= ICRNL;   /* map CR in input to NL */
723                 tp->c_oflag |= ONLCR;   /* map NL in output to CR-NL */
724         }
725         tp->c_cc[VERASE] = cp->erase;   /* set erase character */
726         tp->c_cc[VKILL] = cp->kill;     /* set kill character */
727
728         /* Account for the presence or absence of parity bits in input. */
729
730         switch (cp->parity) {
731         case 0:                                 /* space (always 0) parity */
732                 break;
733         case 1:                                 /* odd parity */
734                 tp->c_cflag |= PARODD;
735                 /* FALLTHROUGH */
736         case 2:                                 /* even parity */
737                 tp->c_cflag |= PARENB;
738                 tp->c_iflag |= INPCK | ISTRIP;
739                 /* FALLTHROUGH */
740         case (1 | 2):                           /* no parity bit */
741                 tp->c_cflag &= ~CSIZE;
742                 tp->c_cflag |= CS7;
743                 break;
744         }
745         /* Account for upper case without lower case. */
746
747         if (cp->capslock) {
748                 tp->c_iflag |= IUCLC;
749                 tp->c_lflag |= XCASE;
750                 tp->c_oflag |= OLCUC;
751         }
752         /* Optionally enable hardware flow control */
753
754 #ifdef  CRTSCTS
755         if (op->flags & F_RTSCTS)
756                 tp->c_cflag |= CRTSCTS;
757 #endif
758
759         /* Finally, make the new settings effective */
760
761         if (ioctl(0, TCSETA, tp) < 0)
762                 error("%s: ioctl: TCSETA: %m", op->tty);
763 }
764
765
766 #ifdef  SYSV_STYLE
767 #ifdef CONFIG_FEATURE_UTMP
768 /* update_utmp - update our utmp entry */
769 static void update_utmp(char *line)
770 {
771         struct utmp ut;
772         struct utmp *utp;
773         time_t t;
774         int mypid = getpid();
775 #if ! (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1))
776         struct flock lock;
777 #endif
778
779         /*
780          * The utmp file holds miscellaneous information about things started by
781          * /sbin/init and other system-related events. Our purpose is to update
782          * the utmp entry for the current process, in particular the process type
783          * and the tty line we are listening to. Return successfully only if the
784          * utmp file can be opened for update, and if we are able to find our
785          * entry in the utmp file.
786          */
787         if (access(_PATH_UTMP, R_OK|W_OK) == -1) {
788                 close(creat(_PATH_UTMP, 0664));
789         }
790         utmpname(_PATH_UTMP);
791         setutent();
792         while ((utp = getutent())
793                    && !(utp->ut_type == INIT_PROCESS && utp->ut_pid == mypid))  /* nothing */
794                 ;
795
796         if (utp) {
797                 memcpy(&ut, utp, sizeof(ut));
798         } else {
799                 /* some inits don't initialize utmp... */
800                 memset(&ut, 0, sizeof(ut));
801                 safe_strncpy(ut.ut_id, line + 3, sizeof(ut.ut_id));
802         }
803         /*endutent(); */
804
805         strcpy(ut.ut_user, "LOGIN");
806         safe_strncpy(ut.ut_line, line, sizeof(ut.ut_line));
807         if (fakehost)
808                 safe_strncpy(ut.ut_host, fakehost, sizeof(ut.ut_host));
809         time(&t);
810         ut.ut_time = t;
811         ut.ut_type = LOGIN_PROCESS;
812         ut.ut_pid = mypid;
813
814         pututline(&ut);
815         endutent();
816
817 #ifdef CONFIG_FEATURE_WTMP
818         if (access(bb_path_wtmp_file, R_OK|W_OK) == -1)
819                 close(creat(bb_path_wtmp_file, 0664));
820         updwtmp(bb_path_wtmp_file, &ut);
821 #endif
822 }
823
824 #endif /* CONFIG_FEATURE_UTMP */
825 #endif /* SYSV_STYLE */
826
827
828 #undef logname
829 int getty_main(int argc, char **argv)
830 {
831         char *logname = NULL;           /* login name, given to /bin/login */
832         struct chardata chardata;       /* set by get_logname() */
833         struct termio termio;           /* terminal mode bits */
834         static struct options options = {
835                 0,                      /* show /etc/issue (SYSV_STYLE) */
836                 0,                      /* no timeout */
837                 _PATH_LOGIN,            /* default login program */
838                 "tty1",                 /* default tty line */
839                 "",                     /* modem init string */
840 #ifdef ISSUE
841                 ISSUE,                  /* default issue file */
842 #else
843                 NULL,
844 #endif
845                 0,                      /* no baud rates known yet */
846         };
847
848 #ifdef DEBUGGING
849         dbf = xfopen(DEBUGTERM, "w");
850
851         {
852                 int i;
853
854                 for (i = 1; i < argc; i++) {
855                         debug(argv[i]);
856                         debug("\n");
857                 }
858         }
859 #endif
860
861         /* Parse command-line arguments. */
862
863         parse_args(argc, argv, &options);
864
865 #ifdef __linux__
866         setsid();
867 #endif
868
869         /* Update the utmp file. */
870
871
872 #ifdef  SYSV_STYLE
873 #ifdef CONFIG_FEATURE_UTMP
874         update_utmp(options.tty);
875 #endif
876 #endif
877
878         debug("calling open_tty\n");
879         /* Open the tty as standard { input, output, error }. */
880         open_tty(options.tty, &termio, options.flags & F_LOCAL);
881
882 #ifdef __linux__
883         {
884                 int iv;
885
886                 iv = getpid();
887                 ioctl(0, TIOCSPGRP, &iv);
888         }
889 #endif
890         /* Initialize the termio settings (raw mode, eight-bit, blocking i/o). */
891         debug("calling termio_init\n");
892         termio_init(&termio, options.speeds[FIRST_SPEED], &options);
893
894         /* write the modem init string and DON'T flush the buffers */
895         if (options.flags & F_INITSTRING) {
896                 debug("writing init string\n");
897                 write(1, options.initstring, strlen(options.initstring));
898         }
899
900         if (!(options.flags & F_LOCAL)) {
901                 /* go to blocking write mode unless -L is specified */
902                 fcntl(1, F_SETFL, fcntl(1, F_GETFL, 0) & ~O_NONBLOCK);
903         }
904
905         /* Optionally detect the baud rate from the modem status message. */
906         debug("before autobaud\n");
907         if (options.flags & F_PARSE)
908                 auto_baud(&termio);
909
910         /* Set the optional timer. */
911         if (options.timeout)
912                 (void) alarm((unsigned) options.timeout);
913
914         /* optionally wait for CR or LF before writing /etc/issue */
915         if (options.flags & F_WAITCRLF) {
916                 char ch;
917
918                 debug("waiting for cr-lf\n");
919                 while (read(0, &ch, 1) == 1) {
920                         ch &= 0x7f;                     /* strip "parity bit" */
921 #ifdef DEBUGGING
922                         fprintf(dbf, "read %c\n", ch);
923 #endif
924                         if (ch == '\n' || ch == '\r')
925                                 break;
926                 }
927         }
928
929         chardata = init_chardata;
930         if (!(options.flags & F_NOPROMPT)) {
931                 /* Read the login name. */
932                 debug("reading login name\n");
933                 /* while ((logname = get_logname(&options, &chardata, &termio)) == 0) */
934                 while ((logname = get_logname(&options, &chardata, &termio)) ==
935                            NULL) next_speed(&termio, &options);
936         }
937
938         /* Disable timer. */
939
940         if (options.timeout)
941                 (void) alarm(0);
942
943         /* Finalize the termio settings. */
944
945         termio_final(&options, &termio, &chardata);
946
947         /* Now the newline character should be properly written. */
948
949         (void) write(1, "\n", 1);
950
951         /* Let the login program take care of password validation. */
952
953         (void) execl(options.login, options.login, "--", logname, (char *) 0);
954         error("%s: can't exec %s: %m", options.tty, options.login);
955 }
956