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