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