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