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