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