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