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