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