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