remove a few superfluous includes
[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  * option added by Eric Rasmussen <ear@usfirst.org> - 12/28/95
8  *
9  * 1999-02-22 Arkadiusz Mickiewicz <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  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
16  */
17
18 #include "libbb.h"
19 #include <syslog.h>
20
21 #if ENABLE_FEATURE_UTMP
22 #include <utmp.h> /* updwtmp() */
23 #endif
24
25 /*
26  * Some heuristics to find out what environment we are in: if it is not
27  * System V, assume it is SunOS 4.
28  */
29 #ifdef LOGIN_PROCESS                    /* defined in System V utmp.h */
30 #include <sys/utsname.h>
31 #else /* if !sysV style, wtmp/utmp code is off */
32 #undef ENABLE_FEATURE_UTMP
33 #undef ENABLE_FEATURE_WTMP
34 #define ENABLE_FEATURE_UTMP 0
35 #define ENABLE_FEATURE_WTMP 0
36 #endif  /* LOGIN_PROCESS */
37
38 /*
39  * Things you may want to modify.
40  *
41  * You may disagree with the default line-editing etc. characters defined
42  * below. Note, however, that DEL cannot be used for interrupt generation
43  * and for line editing at the same time.
44  */
45
46 /* I doubt there are systems which still need this */
47 #undef HANDLE_ALLCAPS
48 #undef ANCIENT_BS_KILL_CHARS
49
50 #define _PATH_LOGIN "/bin/login"
51
52 /* If ISSUE is not defined, getty will never display the contents of the
53  * /etc/issue file. You will not want to spit out large "issue" files at the
54  * wrong baud rate.
55  */
56 #define ISSUE "/etc/issue"              /* displayed before the login prompt */
57
58 /* Some shorthands for control characters. */
59 #define CTL(x)          ((x) ^ 0100)    /* Assumes ASCII dialect */
60 #define CR              CTL('M')        /* carriage return */
61 #define NL              CTL('J')        /* line feed */
62 #define BS              CTL('H')        /* back space */
63 #define DEL             CTL('?')        /* delete */
64
65 /* Defaults for line-editing etc. characters; you may want to change this. */
66 #define DEF_ERASE       DEL             /* default erase character */
67 #define DEF_INTR        CTL('C')        /* default interrupt character */
68 #define DEF_QUIT        CTL('\\')       /* default quit char */
69 #define DEF_KILL        CTL('U')        /* default kill char */
70 #define DEF_EOF         CTL('D')        /* default EOF char */
71 #define DEF_EOL         '\n'
72 #define DEF_SWITCH      0               /* default switch char */
73
74 /*
75  * When multiple baud rates are specified on the command line, the first one
76  * we will try is the first one specified.
77  */
78 #define MAX_SPEED       10              /* max. nr. of baud rates */
79
80 /* Storage for command-line options. */
81 struct options {
82         int flags;                      /* toggle switches, see below */
83         unsigned timeout;               /* time-out period */
84         const char *login;              /* login program */
85         const char *tty;                /* name of tty */
86         const char *initstring;         /* modem init string */
87         const char *issue;              /* alternative issue file */
88         int numspeed;                   /* number of baud rates to try */
89         int speeds[MAX_SPEED];          /* baud rates to be tried */
90 };
91
92 /* Storage for things detected while the login name was read. */
93 struct chardata {
94         unsigned char erase;    /* erase character */
95         unsigned char kill;     /* kill character */
96         unsigned char eol;      /* end-of-line character */
97         unsigned char parity;   /* what parity did we see */
98         /* (parity & 1): saw odd parity char with 7th bit set */
99         /* (parity & 2): saw even parity char with 7th bit set */
100         /* parity == 0: probably 7-bit, space parity? */
101         /* parity == 1: probably 7-bit, odd parity? */
102         /* parity == 2: probably 7-bit, even parity? */
103         /* parity == 3: definitely 8 bit, no parity! */
104         /* Hmm... with any value of "parity" 8 bit, no parity is possible */
105 #ifdef HANDLE_ALLCAPS
106         unsigned char capslock; /* upper case without lower case */
107 #endif
108 };
109
110
111 /* Initial values for the above. */
112 static const struct chardata init_chardata = {
113         DEF_ERASE,                              /* default erase character */
114         DEF_KILL,                               /* default kill character */
115         13,                                     /* default eol char */
116         0,                                      /* space parity */
117 #ifdef HANDLE_ALLCAPS
118         0,                                      /* no capslock */
119 #endif
120 };
121
122 static const char opt_string[] ALIGN1 = "I:LH:f:hil:mt:wn";
123 #define F_INITSTRING    (1 << 0)        /* -I initstring is set */
124 #define F_LOCAL         (1 << 1)        /* -L force local */
125 #define F_FAKEHOST      (1 << 2)        /* -H fake hostname */
126 #define F_CUSTISSUE     (1 << 3)        /* -f give alternative issue file */
127 #define F_RTSCTS        (1 << 4)        /* -h enable RTS/CTS flow control */
128 #define F_ISSUE         (1 << 5)        /* -i display /etc/issue */
129 #define F_LOGIN         (1 << 6)        /* -l non-default login program */
130 #define F_PARSE         (1 << 7)        /* -m process modem status messages */
131 #define F_TIMEOUT       (1 << 8)        /* -t time out */
132 #define F_WAITCRLF      (1 << 9)        /* -w wait for CR or LF */
133 #define F_NOPROMPT      (1 << 10)       /* -n don't ask for login name */
134
135
136 #define line_buf bb_common_bufsiz1
137
138 /* The following is used for understandable diagnostics. */
139 #ifdef DEBUGGING
140 static FILE *dbf;
141 #define DEBUGTERM "/dev/ttyp0"
142 #define debug(...) do { fprintf(dbf, __VA_ARGS__); fflush(dbf); } while (0)
143 #else
144 #define debug(...) ((void)0)
145 #endif
146
147
148 /* bcode - convert speed string to speed code; return <= 0 on failure */
149 static int bcode(const char *s)
150 {
151         int value = bb_strtou(s, NULL, 10); /* yes, int is intended! */
152         if (value < 0) /* bad terminating char, overflow, etc */
153                 return value;
154         return tty_value_to_baud(value);
155 }
156
157 /* parse_speeds - parse alternate baud rates */
158 static void parse_speeds(struct options *op, char *arg)
159 {
160         char *cp;
161
162         /* NB: at least one iteration is always done */
163         debug("entered parse_speeds\n");
164         while ((cp = strsep(&arg, ",")) != NULL) {
165                 op->speeds[op->numspeed] = bcode(cp);
166                 if (op->speeds[op->numspeed] <= 0)
167                         bb_error_msg_and_die("bad speed: %s", cp);
168                 op->numspeed++;
169                 if (op->numspeed > MAX_SPEED)
170                         bb_error_msg_and_die("too many alternate speeds");
171         }
172         debug("exiting parse_speeds\n");
173 }
174
175 /* parse_args - parse command-line arguments */
176 static void parse_args(char **argv, struct options *op, char **fakehost_p)
177 {
178         char *ts;
179
180         opt_complementary = "-2:t+"; /* at least 2 args; -t N */
181         op->flags = getopt32(argv, opt_string,
182                 &(op->initstring), fakehost_p, &(op->issue),
183                 &(op->login), &op->timeout);
184         argv += optind;
185         if (op->flags & F_INITSTRING) {
186                 const char *p = op->initstring;
187                 char *q;
188
189                 op->initstring = q = xstrdup(p);
190                 /* copy optarg into op->initstring decoding \ddd
191                    octal codes into chars */
192                 while (*p) {
193                         if (*p == '\\') {
194                                 p++;
195                                 *q++ = bb_process_escape_sequence(&p);
196                         } else {
197                                 *q++ = *p++;
198                         }
199                 }
200                 *q = '\0';
201         }
202         op->flags ^= F_ISSUE;           /* invert flag "show /etc/issue" */
203         debug("after getopt\n");
204
205         /* we loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
206         op->tty = argv[0];      /* tty name */
207         ts = argv[1];           /* baud rate(s) */
208         if (isdigit(argv[0][0])) {
209                 /* a number first, assume it's a speed (BSD style) */
210                 op->tty = ts;   /* tty name is in argv[1] */
211                 ts = argv[0];   /* baud rate(s) */
212         }
213         parse_speeds(op, ts);
214
215 // TODO: if applet_name is set to "getty: TTY", bb_error_msg's get simpler!
216 // grep for "%s:"
217
218         if (argv[2])
219                 xsetenv("TERM", argv[2]);
220
221         debug("exiting parse_args\n");
222 }
223
224 /* open_tty - set up tty as standard { input, output, error } */
225 static void open_tty(const char *tty)
226 {
227         /* Set up new standard input, unless we are given an already opened port. */
228         if (NOT_LONE_DASH(tty)) {
229 //              struct stat st;
230 //              int cur_dir_fd;
231 //              int fd;
232
233                 /* Sanity checks... */
234 //              cur_dir_fd = xopen(".", O_DIRECTORY | O_NONBLOCK);
235 //              xchdir("/dev");
236 //              xstat(tty, &st);
237 //              if ((st.st_mode & S_IFMT) != S_IFCHR)
238 //                      bb_error_msg_and_die("%s: not a character device", tty);
239
240                 if (tty[0] != '/')
241                         tty = xasprintf("/dev/%s", tty); /* will leak it */
242
243                 /* Open the tty as standard input. */
244                 debug("open(2)\n");
245                 close(0);
246                 /*fd =*/ xopen(tty, O_RDWR | O_NONBLOCK); /* uses fd 0 */
247
248 //              /* Restore current directory */
249 //              fchdir(cur_dir_fd);
250
251                 /* Open the tty as standard input, continued */
252 //              xmove_fd(fd, 0);
253 //              /* fd is >= cur_dir_fd, and cur_dir_fd gets closed too here: */
254 //              while (fd > 2)
255 //                      close(fd--);
256
257                 /* Set proper protections and ownership. */
258                 fchown(0, 0, 0);        /* 0:0 */
259                 fchmod(0, 0620);        /* crw--w---- */
260         } else {
261                 /*
262                  * Standard input should already be connected to an open port. Make
263                  * sure it is open for read/write.
264                  */
265                 if ((fcntl(0, F_GETFL) & O_RDWR) != O_RDWR)
266                         bb_error_msg_and_die("stdin is not open for read/write");
267         }
268 }
269
270 /* termios_init - initialize termios settings */
271 static void termios_init(struct termios *tp, int speed, struct options *op)
272 {
273         /*
274          * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
275          * Special characters are set after we have read the login name; all
276          * reads will be done in raw mode anyway. Errors will be dealt with
277          * later on.
278          */
279 #ifdef __linux__
280         /* flush input and output queues, important for modems! */
281         ioctl(0, TCFLSH, TCIOFLUSH); /* tcflush(0, TCIOFLUSH)? - same */
282 #endif
283
284         tp->c_cflag = CS8 | HUPCL | CREAD | speed;
285         if (op->flags & F_LOCAL)
286                 tp->c_cflag |= CLOCAL;
287
288         tp->c_iflag = tp->c_lflag = tp->c_line = 0;
289         tp->c_oflag = OPOST | ONLCR;
290         tp->c_cc[VMIN] = 1;
291         tp->c_cc[VTIME] = 0;
292
293         /* Optionally enable hardware flow control */
294 #ifdef CRTSCTS
295         if (op->flags & F_RTSCTS)
296                 tp->c_cflag |= CRTSCTS;
297 #endif
298
299         tcsetattr_stdin_TCSANOW(tp);
300
301         debug("term_io 2\n");
302 }
303
304 /* auto_baud - extract baud rate from modem status message */
305 static void auto_baud(char *buf, unsigned size_buf, struct termios *tp)
306 {
307         int speed;
308         int vmin;
309         unsigned iflag;
310         char *bp;
311         int nread;
312
313         /*
314          * This works only if the modem produces its status code AFTER raising
315          * the DCD line, and if the computer is fast enough to set the proper
316          * baud rate before the message has gone by. We expect a message of the
317          * following format:
318          *
319          * <junk><number><junk>
320          *
321          * The number is interpreted as the baud rate of the incoming call. If the
322          * modem does not tell us the baud rate within one second, we will keep
323          * using the current baud rate. It is advisable to enable BREAK
324          * processing (comma-separated list of baud rates) if the processing of
325          * modem status messages is enabled.
326          */
327
328         /*
329          * Use 7-bit characters, don't block if input queue is empty. Errors will
330          * be dealt with later on.
331          */
332         iflag = tp->c_iflag;
333         tp->c_iflag |= ISTRIP;          /* enable 8th-bit stripping */
334         vmin = tp->c_cc[VMIN];
335         tp->c_cc[VMIN] = 0;             /* don't block if queue empty */
336         tcsetattr_stdin_TCSANOW(tp);
337
338         /*
339          * Wait for a while, then read everything the modem has said so far and
340          * try to extract the speed of the dial-in call.
341          */
342         sleep(1);
343         nread = safe_read(STDIN_FILENO, buf, size_buf - 1);
344         if (nread > 0) {
345                 buf[nread] = '\0';
346                 for (bp = buf; bp < buf + nread; bp++) {
347                         if (isdigit(*bp)) {
348                                 speed = bcode(bp);
349                                 if (speed > 0) {
350                                         tp->c_cflag &= ~CBAUD;
351                                         tp->c_cflag |= speed;
352                                 }
353                                 break;
354                         }
355                 }
356         }
357
358         /* Restore terminal settings. Errors will be dealt with later on. */
359         tp->c_iflag = iflag;
360         tp->c_cc[VMIN] = vmin;
361         tcsetattr_stdin_TCSANOW(tp);
362 }
363
364 /* do_prompt - show login prompt, optionally preceded by /etc/issue contents */
365 static void do_prompt(struct options *op)
366 {
367 #ifdef ISSUE
368         print_login_issue(op->issue, op->tty);
369 #endif
370         print_login_prompt();
371 }
372
373 #ifdef HANDLE_ALLCAPS
374 /* all_is_upcase - string contains upper case without lower case */
375 /* returns 1 if true, 0 if false */
376 static int all_is_upcase(const char *s)
377 {
378         while (*s)
379                 if (islower(*s++))
380                         return 0;
381         return 1;
382 }
383 #endif
384
385 /* get_logname - get user name, establish parity, speed, erase, kill, eol;
386  * return NULL on BREAK, logname on success */
387 static char *get_logname(char *logname, unsigned size_logname,
388                 struct options *op, struct chardata *cp)
389 {
390         char *bp;
391         char c;                         /* input character, full eight bits */
392         char ascval;                    /* low 7 bits of input character */
393         int bits;                       /* # of "1" bits per character */
394         int mask;                       /* mask with 1 bit up */
395         static const char erase[][3] = {/* backspace-space-backspace */
396                 "\010\040\010",                 /* space parity */
397                 "\010\040\010",                 /* odd parity */
398                 "\210\240\210",                 /* even parity */
399                 "\010\040\010",                 /* 8 bit no parity */
400         };
401
402         /* NB: *cp is pre-initialized with init_chardata */
403
404         /* Flush pending input (esp. after parsing or switching the baud rate). */
405         sleep(1);
406         ioctl(0, TCFLSH, TCIFLUSH); /* tcflush(0, TCIOFLUSH)? - same */
407
408         /* Prompt for and read a login name. */
409         logname[0] = '\0';
410         while (!logname[0]) {
411                 /* Write issue file and prompt, with "parity" bit == 0. */
412                 do_prompt(op);
413
414                 /* Read name, watch for break, parity, erase, kill, end-of-line. */
415                 bp = logname;
416                 cp->eol = '\0';
417                 while (cp->eol == '\0') {
418
419                         /* Do not report trivial EINTR/EIO errors. */
420                         if (read(STDIN_FILENO, &c, 1) < 1) {
421                                 if (errno == EINTR || errno == EIO)
422                                         exit(EXIT_SUCCESS);
423                                 bb_perror_msg_and_die("%s: read", op->tty);
424                         }
425
426                         /* BREAK. If we have speeds to try,
427                          * return NULL (will switch speeds and return here) */
428                         if (c == '\0' && op->numspeed > 1)
429                                 return NULL;
430
431                         /* Do parity bit handling. */
432                         if (!(op->flags & F_LOCAL) && (c & 0x80)) {       /* "parity" bit on? */
433                                 bits = 1;
434                                 mask = 1;
435                                 while (mask & 0x7f) {
436                                         if (mask & c)
437                                                 bits++; /* count "1" bits */
438                                         mask <<= 1;
439                                 }
440                                 /* ... |= 2 - even, 1 - odd */
441                                 cp->parity |= 2 - (bits & 1);
442                         }
443
444                         /* Do erase, kill and end-of-line processing. */
445                         ascval = c & 0x7f;
446                         switch (ascval) {
447                         case CR:
448                         case NL:
449                                 *bp = '\0';             /* terminate logname */
450                                 cp->eol = ascval;       /* set end-of-line char */
451                                 break;
452                         case BS:
453                         case DEL:
454 #ifdef ANCIENT_BS_KILL_CHARS
455                         case '#':
456 #endif
457                                 cp->erase = ascval;     /* set erase character */
458                                 if (bp > logname) {
459                                         full_write(STDOUT_FILENO, erase[cp->parity], 3);
460                                         bp--;
461                                 }
462                                 break;
463                         case CTL('U'):
464 #ifdef ANCIENT_BS_KILL_CHARS
465                         case '@':
466 #endif
467                                 cp->kill = ascval;      /* set kill character */
468                                 while (bp > logname) {
469                                         full_write(STDOUT_FILENO, erase[cp->parity], 3);
470                                         bp--;
471                                 }
472                                 break;
473                         case CTL('D'):
474                                 exit(EXIT_SUCCESS);
475                         default:
476                                 if (!isascii(ascval) || !isprint(ascval)) {
477                                         /* ignore garbage characters */
478                                 } else if ((int)(bp - logname) >= size_logname - 1) {
479                                         bb_error_msg_and_die("%s: input overrun", op->tty);
480                                 } else {
481                                         full_write(STDOUT_FILENO, &c, 1); /* echo the character */
482                                         *bp++ = ascval; /* and store it */
483                                 }
484                                 break;
485                         }
486                 }
487         }
488         /* Handle names with upper case and no lower case. */
489
490 #ifdef HANDLE_ALLCAPS
491         cp->capslock = all_is_upcase(logname);
492         if (cp->capslock) {
493                 for (bp = logname; *bp; bp++)
494                         if (isupper(*bp))
495                                 *bp = tolower(*bp);     /* map name to lower case */
496         }
497 #endif
498         return logname;
499 }
500
501 /* termios_final - set the final tty mode bits */
502 static void termios_final(struct options *op, struct termios *tp, struct chardata *cp)
503 {
504         /* General terminal-independent stuff. */
505         tp->c_iflag |= IXON | IXOFF;    /* 2-way flow control */
506         tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
507         /* no longer| ECHOCTL | ECHOPRT */
508         tp->c_oflag |= OPOST;
509         /* tp->c_cflag = 0; */
510         tp->c_cc[VINTR] = DEF_INTR;     /* default interrupt */
511         tp->c_cc[VQUIT] = DEF_QUIT;     /* default quit */
512         tp->c_cc[VEOF] = DEF_EOF;       /* default EOF character */
513         tp->c_cc[VEOL] = DEF_EOL;
514         tp->c_cc[VSWTC] = DEF_SWITCH;   /* default switch character */
515
516         /* Account for special characters seen in input. */
517         if (cp->eol == CR) {
518                 tp->c_iflag |= ICRNL;   /* map CR in input to NL */
519                 tp->c_oflag |= ONLCR;   /* map NL in output to CR-NL */
520         }
521         tp->c_cc[VERASE] = cp->erase;   /* set erase character */
522         tp->c_cc[VKILL] = cp->kill;     /* set kill character */
523
524         /* Account for the presence or absence of parity bits in input. */
525         switch (cp->parity) {
526         case 0:                                 /* space (always 0) parity */
527 // I bet most people go here - they use only 7-bit chars in usernames....
528                 break;
529         case 1:                                 /* odd parity */
530                 tp->c_cflag |= PARODD;
531                 /* FALLTHROUGH */
532         case 2:                                 /* even parity */
533                 tp->c_cflag |= PARENB;
534                 tp->c_iflag |= INPCK | ISTRIP;
535                 /* FALLTHROUGH */
536         case (1 | 2):                           /* no parity bit */
537                 tp->c_cflag &= ~CSIZE;
538                 tp->c_cflag |= CS7;
539 // FIXME: wtf? case 3: we saw both even and odd 8-bit bytes -
540 // it's probably some umlauts etc, but definitely NOT 7-bit!!!
541 // Entire parity detection madness here just begs for deletion...
542                 break;
543         }
544
545         /* Account for upper case without lower case. */
546 #ifdef HANDLE_ALLCAPS
547         if (cp->capslock) {
548                 tp->c_iflag |= IUCLC;
549                 tp->c_lflag |= XCASE;
550                 tp->c_oflag |= OLCUC;
551         }
552 #endif
553         /* Optionally enable hardware flow control */
554 #ifdef CRTSCTS
555         if (op->flags & F_RTSCTS)
556                 tp->c_cflag |= CRTSCTS;
557 #endif
558
559         /* Finally, make the new settings effective */
560         /* It's tcsetattr_stdin_TCSANOW() + error check */
561         ioctl_or_perror_and_die(0, TCSETS, tp, "%s: TCSETS", op->tty);
562 }
563
564 #if ENABLE_FEATURE_UTMP
565 static void touch(const char *filename)
566 {
567         if (access(filename, R_OK | W_OK) == -1)
568                 close(open(filename, O_WRONLY | O_CREAT, 0664));
569 }
570
571 /* update_utmp - update our utmp entry */
572 static void update_utmp(const char *line, char *fakehost)
573 {
574         struct utmp ut;
575         struct utmp *utp;
576         int mypid = getpid();
577
578         /* In case we won't find an entry below... */
579         memset(&ut, 0, sizeof(ut));
580         safe_strncpy(ut.ut_id, line + 3, sizeof(ut.ut_id));
581
582         /*
583          * The utmp file holds miscellaneous information about things started by
584          * /sbin/init and other system-related events. Our purpose is to update
585          * the utmp entry for the current process, in particular the process type
586          * and the tty line we are listening to. Return successfully only if the
587          * utmp file can be opened for update, and if we are able to find our
588          * entry in the utmp file.
589          */
590         touch(_PATH_UTMP);
591
592         utmpname(_PATH_UTMP);
593         setutent();
594         while ((utp = getutent()) != NULL) {
595                 if (utp->ut_type == INIT_PROCESS && utp->ut_pid == mypid) {
596                         memcpy(&ut, utp, sizeof(ut));
597                         break;
598                 }
599         }
600
601         strcpy(ut.ut_user, "LOGIN");
602         safe_strncpy(ut.ut_line, line, sizeof(ut.ut_line));
603         if (fakehost)
604                 safe_strncpy(ut.ut_host, fakehost, sizeof(ut.ut_host));
605         ut.ut_tv.tv_sec = time(NULL);
606         ut.ut_type = LOGIN_PROCESS;
607         ut.ut_pid = mypid;
608
609         pututline(&ut);
610         endutent();
611
612 #if ENABLE_FEATURE_WTMP
613         touch(bb_path_wtmp_file);
614         updwtmp(bb_path_wtmp_file, &ut);
615 #endif
616 }
617 #endif /* CONFIG_FEATURE_UTMP */
618
619 int getty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
620 int getty_main(int argc UNUSED_PARAM, char **argv)
621 {
622         int n;
623         char *fakehost = NULL;          /* Fake hostname for ut_host */
624         char *logname;                  /* login name, given to /bin/login */
625         /* Merging these into "struct local" may _seem_ to reduce
626          * parameter passing, but today's gcc will inline
627          * statics which are called once anyway, so don't do that */
628         struct chardata chardata;       /* set by get_logname() */
629         struct termios termios;         /* terminal mode bits */
630         struct options options;
631
632         chardata = init_chardata;
633
634         memset(&options, 0, sizeof(options));
635         options.login = _PATH_LOGIN;    /* default login program */
636         options.tty = "tty1";           /* default tty line */
637         options.initstring = "";        /* modem init string */
638 #ifdef ISSUE
639         options.issue = ISSUE;          /* default issue file */
640 #endif
641
642         /* Parse command-line arguments. */
643         parse_args(argv, &options, &fakehost);
644
645         logmode = LOGMODE_NONE;
646
647         /* Create new session, lose controlling tty, if any */
648         /* docs/ctty.htm says:
649          * "This is allowed only when the current process
650          *  is not a process group leader" - is this a problem? */
651         setsid();
652         /* close stdio, and stray descriptors, just in case */
653         n = xopen(bb_dev_null, O_RDWR);
654         /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
655         xdup2(n, 1);
656         xdup2(n, 2);
657         while (n > 2)
658                 close(n--);
659
660         /* Logging. We want special flavor of error_msg_and_die */
661         die_sleep = 10;
662         msg_eol = "\r\n";
663         /* most likely will internally use fd #3 in CLOEXEC mode: */
664         openlog(applet_name, LOG_PID, LOG_AUTH);
665         logmode = LOGMODE_BOTH;
666
667 #ifdef DEBUGGING
668         dbf = xfopen_for_write(DEBUGTERM);
669         for (n = 1; argv[n]; n++) {
670                 debug(argv[n]);
671                 debug("\n");
672         }
673 #endif
674
675         /* Open the tty as standard input, if it is not "-" */
676         /* If it's not "-" and not taken yet, it will become our ctty */
677         debug("calling open_tty\n");
678         open_tty(options.tty);
679         ndelay_off(0);
680         debug("duping\n");
681         xdup2(0, 1);
682         xdup2(0, 2);
683
684         /*
685          * The following ioctl will fail if stdin is not a tty, but also when
686          * there is noise on the modem control lines. In the latter case, the
687          * common course of action is (1) fix your cables (2) give the modem more
688          * time to properly reset after hanging up. SunOS users can achieve (2)
689          * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
690          * 5 seconds seems to be a good value.
691          */
692         /* tcgetattr() + error check */
693         ioctl_or_perror_and_die(0, TCGETS, &termios, "%s: TCGETS", options.tty);
694
695 #ifdef __linux__
696 // FIXME: do we need this? Otherwise "-" case seems to be broken...
697         // /* Forcibly make fd 0 our controlling tty, even if another session
698         //  * has it as a ctty. (Another session loses ctty). */
699         // ioctl(0, TIOCSCTTY, (void*)1);
700         /* Make ourself a foreground process group within our session */
701         tcsetpgrp(0, getpid());
702 #endif
703
704 #if ENABLE_FEATURE_UTMP
705         /* Update the utmp file. This tty is ours now! */
706         update_utmp(options.tty, fakehost);
707 #endif
708
709         /* Initialize the termios settings (raw mode, eight-bit, blocking i/o). */
710         debug("calling termios_init\n");
711         termios_init(&termios, options.speeds[0], &options);
712
713         /* Write the modem init string and DON'T flush the buffers */
714         if (options.flags & F_INITSTRING) {
715                 debug("writing init string\n");
716                 full_write(STDOUT_FILENO, options.initstring, strlen(options.initstring));
717         }
718
719         /* Optionally detect the baud rate from the modem status message */
720         debug("before autobaud\n");
721         if (options.flags & F_PARSE)
722                 auto_baud(line_buf, sizeof(line_buf), &termios);
723
724         /* Set the optional timer */
725         alarm(options.timeout); /* if 0, alarm is not set */
726
727         /* Optionally wait for CR or LF before writing /etc/issue */
728         if (options.flags & F_WAITCRLF) {
729                 char ch;
730
731                 debug("waiting for cr-lf\n");
732                 while (safe_read(STDIN_FILENO, &ch, 1) == 1) {
733                         debug("read %x\n", (unsigned char)ch);
734                         ch &= 0x7f;                     /* strip "parity bit" */
735                         if (ch == '\n' || ch == '\r')
736                                 break;
737                 }
738         }
739
740         logname = NULL;
741         if (!(options.flags & F_NOPROMPT)) {
742                 /* NB:termios_init already set line speed
743                  * to options.speeds[0] */
744                 int baud_index = 0;
745
746                 while (1) {
747                         /* Read the login name. */
748                         debug("reading login name\n");
749                         logname = get_logname(line_buf, sizeof(line_buf),
750                                         &options, &chardata);
751                         if (logname)
752                                 break;
753                         /* we are here only if options.numspeed > 1 */
754                         baud_index = (baud_index + 1) % options.numspeed;
755                         termios.c_cflag &= ~CBAUD;
756                         termios.c_cflag |= options.speeds[baud_index];
757                         tcsetattr_stdin_TCSANOW(&termios);
758                 }
759         }
760
761         /* Disable timer. */
762         alarm(0);
763
764         /* Finalize the termios settings. */
765         termios_final(&options, &termios, &chardata);
766
767         /* Now the newline character should be properly written. */
768         full_write(STDOUT_FILENO, "\n", 1);
769
770         /* Let the login program take care of password validation. */
771         /* We use PATH because we trust that root doesn't set "bad" PATH,
772          * and getty is not suid-root applet. */
773         /* With -n, logname == NULL, and login will ask for username instead */
774         BB_EXECLP(options.login, options.login, "--", logname, NULL);
775         bb_error_msg_and_die("%s: can't exec %s", options.tty, options.login);
776 }