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