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