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