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