1 /* vi: set sw=4 ts=4: */
2 /*
3 * Based on agetty - another getty program for Linux. By W. Z. Venema 1989
4 * Ported to Linux by Peter Orbaek <poe@daimi.aau.dk>
5 * This program is freely distributable.
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 * - Enabled hardware flow control before displaying /etc/issue
14 *
15 * 2011-01 Venys Vlasenko
16 * - Removed parity detection code. It can't work reliably:
17 * if all chars received have bit 7 cleared and odd (or even) parity,
18 * it is impossible to determine whether other side is 8-bit,no-parity
19 * or 7-bit,odd(even)-parity. It also interferes with non-ASCII usernames.
20 * - From now on, we assume that parity is correctly set.
21 *
22 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
23 */
24 //config:config GETTY
25 //config: bool "getty (10 kb)"
26 //config: default y
27 //config: select FEATURE_SYSLOG
28 //config: help
29 //config: getty lets you log in on a tty. It is normally invoked by init.
30 //config:
31 //config: Note that you can save a few bytes by disabling it and
32 //config: using login applet directly.
33 //config: If you need to reset tty attributes before calling login,
34 //config: this script approximates getty:
35 //config:
36 //config: exec </dev/$1 >/dev/$1 2>&1 || exit 1
37 //config: reset
38 //config: stty sane; stty ispeed 38400; stty ospeed 38400
39 //config: printf "%s login: " "`hostname`"
40 //config: read -r login
41 //config: exec /bin/login "$login"
42
43 //applet:IF_GETTY(APPLET(getty, BB_DIR_SBIN, BB_SUID_DROP))
44
45 //kbuild:lib-$(CONFIG_GETTY) += getty.o
46
47 #include "libbb.h"
48 #include <syslog.h>
49 #ifndef IUCLC
50 # define IUCLC 0
51 #endif
52
53 #ifndef LOGIN_PROCESS
54 # undef ENABLE_FEATURE_UTMP
55 # undef ENABLE_FEATURE_WTMP
56 # define ENABLE_FEATURE_UTMP 0
57 # define ENABLE_FEATURE_WTMP 0
58 #endif
59
60
61 /* The following is used for understandable diagnostics */
62 #ifdef DEBUGGING
63 static FILE *dbf;
64 # define DEBUGTERM "/dev/ttyp0"
65 # define debug(...) do { fprintf(dbf, __VA_ARGS__); fflush(dbf); } while (0)
66 #else
67 # define debug(...) ((void)0)
68 #endif
69
70
71 /*
72 * Things you may want to modify.
73 *
74 * You may disagree with the default line-editing etc. characters defined
75 * below. Note, however, that DEL cannot be used for interrupt generation
76 * and for line editing at the same time.
77 */
78 #undef _PATH_LOGIN
79 #define _PATH_LOGIN "/bin/login"
80
81 /* Displayed before the login prompt.
82 * If ISSUE is not defined, getty will never display the contents of the
83 * /etc/issue file. You will not want to spit out large "issue" files at the
84 * wrong baud rate.
85 */
86 #define ISSUE "/etc/issue"
87
88 /* Macro to build Ctrl-LETTER. Assumes ASCII dialect */
89 #define CTL(x) ((x) ^ 0100)
90
91 /*
92 * When multiple baud rates are specified on the command line,
93 * the first one we will try is the first one specified.
94 */
95 #define MAX_SPEED 10 /* max. nr. of baud rates */
96
97 struct globals {
98 unsigned timeout;
99 const char *login; /* login program */
100 const char *fakehost;
101 const char *tty_name;
102 char *initstring; /* modem init string */
103 const char *issue; /* alternative issue file */
104 int numspeed; /* number of baud rates to try */
105 int speeds[MAX_SPEED]; /* baud rates to be tried */
106 unsigned char eol; /* end-of-line char seen (CR or NL) */
107 struct termios tty_attrs;
108 char line_buf[128];
109 };
110
111 #define G (*ptr_to_globals)
112 #define INIT_G() do { \
113 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
114 } while (0)
115
116 //usage:#define getty_trivial_usage
117 //usage: "[OPTIONS] BAUD_RATE[,BAUD_RATE]... TTY [TERMTYPE]"
118 //usage:#define getty_full_usage "\n\n"
119 //usage: "Open TTY, prompt for login name, then invoke /bin/login\n"
120 //usage: "\n -h Enable hardware RTS/CTS flow control"
121 //usage: "\n -L Set CLOCAL (ignore Carrier Detect state)"
122 //usage: "\n -m Get baud rate from modem's CONNECT status message"
123 //usage: "\n -n Don't prompt for login name"
124 //usage: "\n -w Wait for CR or LF before sending /etc/issue"
125 //usage: "\n -i Don't display /etc/issue"
126 //usage: "\n -f ISSUE_FILE Display ISSUE_FILE instead of /etc/issue"
127 //usage: "\n -l LOGIN Invoke LOGIN instead of /bin/login"
128 //usage: "\n -t SEC Terminate after SEC if no login name is read"
129 //usage: "\n -I INITSTR Send INITSTR before anything else"
130 //usage: "\n -H HOST Log HOST into the utmp file as the hostname"
131 //usage: "\n"
132 //usage: "\nBAUD_RATE of 0 leaves it unchanged"
133
134 #define OPT_STR "I:LH:f:hil:mt:+wn"
135 #define F_INITSTRING (1 << 0) /* -I */
136 #define F_LOCAL (1 << 1) /* -L */
137 #define F_FAKEHOST (1 << 2) /* -H */
138 #define F_CUSTISSUE (1 << 3) /* -f */
139 #define F_RTSCTS (1 << 4) /* -h */
140 #define F_NOISSUE (1 << 5) /* -i */
141 #define F_LOGIN (1 << 6) /* -l */
142 #define F_PARSE (1 << 7) /* -m */
143 #define F_TIMEOUT (1 << 8) /* -t */
144 #define F_WAITCRLF (1 << 9) /* -w */
145 #define F_NOPROMPT (1 << 10) /* -n */
146
147
148 /* convert speed string to speed code; return <= 0 on failure */
bcode(const char * s)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 alternate baud rates */
parse_speeds(char * arg)158 static void parse_speeds(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 G.speeds[G.numspeed] = bcode(cp);
166 if (G.speeds[G.numspeed] < 0)
167 bb_error_msg_and_die("bad speed: %s", cp);
168 /* note: arg "0" turns into speed B0 */
169 G.numspeed++;
170 if (G.numspeed > MAX_SPEED)
171 bb_simple_error_msg_and_die("too many alternate speeds");
172 }
173 debug("exiting parse_speeds\n");
174 }
175
176 /* parse command-line arguments */
parse_args(char ** argv)177 static void parse_args(char **argv)
178 {
179 char *ts;
180 int flags;
181
182 flags = getopt32(argv, "^" OPT_STR "\0" "-2"/* at least 2 args*/,
183 &G.initstring, &G.fakehost, &G.issue,
184 &G.login, &G.timeout
185 );
186 if (flags & F_INITSTRING) {
187 G.initstring = xstrdup(G.initstring);
188 /* decode \ddd octal codes into chars */
189 strcpy_and_process_escape_sequences(G.initstring, G.initstring);
190 }
191 argv += optind;
192 debug("after getopt\n");
193
194 /* We loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
195 G.tty_name = argv[0];
196 ts = argv[1]; /* baud rate(s) */
197 if (isdigit(argv[0][0])) {
198 /* A number first, assume it's a speed (BSD style) */
199 G.tty_name = ts; /* tty name is in argv[1] */
200 ts = argv[0]; /* baud rate(s) */
201 }
202 parse_speeds(ts);
203
204 if (argv[2])
205 xsetenv("TERM", argv[2]);
206
207 debug("exiting parse_args\n");
208 }
209
210 /* set up tty as standard input, output, error */
open_tty(void)211 static void open_tty(void)
212 {
213 /* Set up new standard input, unless we are given an already opened port */
214 if (NOT_LONE_DASH(G.tty_name)) {
215 if (G.tty_name[0] != '/')
216 G.tty_name = xasprintf("/dev/%s", G.tty_name); /* will leak it */
217
218 /* Open the tty as standard input */
219 debug("open(2)\n");
220 close(0);
221 xopen(G.tty_name, O_RDWR | O_NONBLOCK); /* uses fd 0 */
222
223 /* Set proper protections and ownership */
224 fchown(0, 0, 0); /* 0:0 */
225 fchmod(0, 0620); /* crw--w---- */
226 } else {
227 char *n;
228 /*
229 * Standard input should already be connected to an open port.
230 * Make sure it is open for read/write.
231 */
232 if ((fcntl(0, F_GETFL) & (O_RDWR|O_RDONLY|O_WRONLY)) != O_RDWR)
233 bb_simple_error_msg_and_die("stdin is not open for read/write");
234
235 /* Try to get real tty name instead of "-" */
236 n = xmalloc_ttyname(0);
237 if (n)
238 G.tty_name = n;
239 }
240 applet_name = xasprintf("getty: %s", skip_dev_pfx(G.tty_name));
241 }
242
set_tty_attrs(void)243 static void set_tty_attrs(void)
244 {
245 if (tcsetattr_stdin_TCSANOW(&G.tty_attrs) < 0)
246 bb_simple_perror_msg_and_die("tcsetattr");
247 }
248
249 /* We manipulate tty_attrs this way:
250 * - first, we read existing tty_attrs
251 * - init_tty_attrs modifies some parts and sets it
252 * - auto_baud and/or BREAK processing can set different speed and set tty attrs
253 * - finalize_tty_attrs again modifies some parts and sets tty attrs before
254 * execing login
255 */
init_tty_attrs(int speed)256 static void init_tty_attrs(int speed)
257 {
258 /* Try to drain output buffer, with 5 sec timeout.
259 * Added on request from users of ~600 baud serial interface
260 * with biggish buffer on a 90MHz CPU.
261 * They were losing hundreds of bytes of buffered output
262 * on tcflush.
263 */
264 signal_no_SA_RESTART_empty_mask(SIGALRM, record_signo);
265 alarm(5);
266 tcdrain(STDIN_FILENO);
267 alarm(0);
268
269 /* Flush input and output queues, important for modems! */
270 tcflush(STDIN_FILENO, TCIOFLUSH);
271
272 /* Set speed if it wasn't specified as "0" on command line */
273 if (speed != B0)
274 cfsetspeed(&G.tty_attrs, speed);
275
276 /* Initial 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.
279 */
280 /* Clear all bits except: */
281 G.tty_attrs.c_cflag &= (0
282 /* 2 stop bits (1 otherwise)
283 * Enable parity bit (both on input and output)
284 * Odd parity (else even)
285 */
286 | CSTOPB | PARENB | PARODD
287 #ifdef CMSPAR
288 | CMSPAR /* mark or space parity */
289 #endif
290 #ifdef CBAUD
291 | CBAUD /* (output) baud rate */
292 #endif
293 #ifdef CBAUDEX
294 | CBAUDEX /* (output) baud rate */
295 #endif
296 #ifdef CIBAUD
297 | CIBAUD /* input baud rate */
298 #endif
299 );
300 /* Set: 8 bits; hang up (drop DTR) on last close; enable receive */
301 G.tty_attrs.c_cflag |= CS8 | HUPCL | CREAD;
302 if (option_mask32 & F_LOCAL) {
303 /* ignore Carrier Detect pin:
304 * opens don't block when CD is low,
305 * losing CD doesn't hang up processes whose ctty is this tty
306 */
307 G.tty_attrs.c_cflag |= CLOCAL;
308 }
309 #ifdef CRTSCTS
310 if (option_mask32 & F_RTSCTS)
311 G.tty_attrs.c_cflag |= CRTSCTS; /* flow control using RTS/CTS pins */
312 #endif
313 G.tty_attrs.c_iflag = 0;
314 G.tty_attrs.c_lflag = 0;
315 /* non-raw output; add CR to each NL */
316 G.tty_attrs.c_oflag = OPOST | ONLCR;
317
318 /* reads will block only if < 1 char is available */
319 G.tty_attrs.c_cc[VMIN] = 1;
320 /* no timeout (reads block forever) */
321 G.tty_attrs.c_cc[VTIME] = 0;
322 #ifdef __linux__
323 G.tty_attrs.c_line = 0;
324 #endif
325
326 set_tty_attrs();
327
328 debug("term_io 2\n");
329 }
330
finalize_tty_attrs(void)331 static void finalize_tty_attrs(void)
332 {
333 /* software flow control on output (stop sending if XOFF is recvd);
334 * and on input (send XOFF when buffer is full)
335 */
336 G.tty_attrs.c_iflag |= IXON | IXOFF;
337 if (G.eol == '\r') {
338 G.tty_attrs.c_iflag |= ICRNL; /* map CR on input to NL */
339 }
340 /* Other bits in c_iflag:
341 * IXANY Any recvd char enables output (any char is also a XON)
342 * INPCK Enable parity check
343 * IGNPAR Ignore parity errors (drop bad bytes)
344 * PARMRK Mark parity errors with 0xff, 0x00 prefix
345 * (else bad byte is received as 0x00)
346 * ISTRIP Strip parity bit
347 * IGNBRK Ignore break condition
348 * BRKINT Send SIGINT on break - maybe set this?
349 * INLCR Map NL to CR
350 * IGNCR Ignore CR
351 * ICRNL Map CR to NL
352 * IUCLC Map uppercase to lowercase
353 * IMAXBEL Echo BEL on input line too long
354 * IUTF8 Appears to affect tty's idea of char widths,
355 * observed to improve backspacing through Unicode chars
356 */
357
358 /* ICANON line buffered input (NL or EOL or EOF chars end a line);
359 * ISIG recognize INT/QUIT/SUSP chars;
360 * ECHO echo input chars;
361 * ECHOE echo BS-SP-BS on erase character;
362 * ECHOK echo kill char specially, not as ^c (ECHOKE controls how exactly);
363 * ECHOKE erase all input via BS-SP-BS on kill char (else go to next line)
364 * ECHOCTL Echo ctrl chars as ^c (else echo verbatim:
365 * e.g. up arrow emits "ESC-something" and thus moves cursor up!)
366 */
367 G.tty_attrs.c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE | ECHOCTL;
368 /* Other bits in c_lflag:
369 * XCASE Map uppercase to \lowercase [tried, doesn't work]
370 * ECHONL Echo NL even if ECHO is not set
371 * ECHOPRT On erase, echo erased chars
372 * [qwe<BS><BS><BS> input looks like "qwe\ewq/" on screen]
373 * NOFLSH Don't flush input buffer after interrupt or quit chars
374 * IEXTEN Enable extended functions (??)
375 * [glibc says it enables c_cc[LNEXT] "enter literal char"
376 * and c_cc[VDISCARD] "toggle discard buffered output" chars]
377 * FLUSHO Output being flushed (c_cc[VDISCARD] is in effect)
378 * PENDIN Retype pending input at next read or input char
379 * (c_cc[VREPRINT] is being processed)
380 * TOSTOP Send SIGTTOU for background output
381 * (why "stty sane" unsets this bit?)
382 */
383
384 G.tty_attrs.c_cc[VINTR] = CTL('C');
385 G.tty_attrs.c_cc[VQUIT] = CTL('\\');
386 G.tty_attrs.c_cc[VEOF] = CTL('D');
387 G.tty_attrs.c_cc[VEOL] = '\n';
388 #ifdef VSWTC
389 G.tty_attrs.c_cc[VSWTC] = 0;
390 #endif
391 #ifdef VSWTCH
392 G.tty_attrs.c_cc[VSWTCH] = 0;
393 #endif
394 G.tty_attrs.c_cc[VKILL] = CTL('U');
395 /* Other control chars:
396 * VEOL2
397 * VERASE, VWERASE - (word) erase. we may set VERASE in get_logname
398 * VREPRINT - reprint current input buffer
399 * VLNEXT, VDISCARD, VSTATUS
400 * VSUSP, VDSUSP - send (delayed) SIGTSTP
401 * VSTART, VSTOP - chars used for IXON/IXOFF
402 */
403
404 set_tty_attrs();
405
406 /* Now the newline character should be properly written */
407 full_write1_str("\n");
408 }
409
410 /* extract baud rate from modem status message */
auto_baud(void)411 static void auto_baud(void)
412 {
413 int nread;
414
415 /*
416 * This works only if the modem produces its status code AFTER raising
417 * the DCD line, and if the computer is fast enough to set the proper
418 * baud rate before the message has gone by. We expect a message of the
419 * following format:
420 *
421 * <junk><number><junk>
422 *
423 * The number is interpreted as the baud rate of the incoming call. If the
424 * modem does not tell us the baud rate within one second, we will keep
425 * using the current baud rate. It is advisable to enable BREAK
426 * processing (comma-separated list of baud rates) if the processing of
427 * modem status messages is enabled.
428 */
429
430 G.tty_attrs.c_cc[VMIN] = 0; /* don't block reads (min read is 0 chars) */
431 set_tty_attrs();
432
433 /*
434 * Wait for a while, then read everything the modem has said so far and
435 * try to extract the speed of the dial-in call.
436 */
437 sleep1();
438 nread = safe_read(STDIN_FILENO, G.line_buf, sizeof(G.line_buf) - 1);
439 if (nread > 0) {
440 int speed;
441 char *bp;
442 G.line_buf[nread] = '\0';
443 for (bp = G.line_buf; bp < G.line_buf + nread; bp++) {
444 if (isdigit(*bp)) {
445 speed = bcode(bp);
446 if (speed > 0)
447 cfsetspeed(&G.tty_attrs, speed);
448 break;
449 }
450 }
451 }
452
453 /* Restore terminal settings */
454 G.tty_attrs.c_cc[VMIN] = 1; /* restore to value set by init_tty_attrs */
455 set_tty_attrs();
456 }
457
458 /* get user name, establish parity, speed, erase, kill, eol;
459 * return NULL on BREAK, logname on success
460 */
get_logname(void)461 static char *get_logname(void)
462 {
463 char *bp;
464 char c;
465
466 /* Flush pending input (esp. after parsing or switching the baud rate) */
467 usleep(100*1000); /* 0.1 sec */
468 tcflush(STDIN_FILENO, TCIFLUSH);
469
470 /* Prompt for and read a login name */
471 do {
472 /* Write issue file and prompt */
473 #ifdef ISSUE
474 if (!(option_mask32 & F_NOISSUE))
475 print_login_issue(G.issue, G.tty_name);
476 #endif
477 print_login_prompt();
478
479 /* Read name, watch for break, erase, kill, end-of-line */
480 bp = G.line_buf;
481 while (1) {
482 /* Do not report trivial EINTR/EIO errors */
483 errno = EINTR; /* make read of 0 bytes be silent too */
484 if (read(STDIN_FILENO, &c, 1) < 1) {
485 finalize_tty_attrs();
486 if (errno == EINTR || errno == EIO)
487 exit(EXIT_SUCCESS);
488 bb_simple_perror_msg_and_die(bb_msg_read_error);
489 }
490
491 switch (c) {
492 case '\r':
493 case '\n':
494 *bp = '\0';
495 G.eol = c;
496 goto got_logname;
497 case CTL('H'):
498 case 0x7f:
499 G.tty_attrs.c_cc[VERASE] = c;
500 if (bp > G.line_buf) {
501 full_write1_str("\010 \010");
502 bp--;
503 }
504 break;
505 case CTL('U'):
506 while (bp > G.line_buf) {
507 full_write1_str("\010 \010");
508 bp--;
509 }
510 break;
511 case CTL('C'):
512 case CTL('D'):
513 finalize_tty_attrs();
514 exit(EXIT_SUCCESS);
515 case '\0':
516 /* BREAK. If we have speeds to try,
517 * return NULL (will switch speeds and return here) */
518 if (G.numspeed > 1)
519 return NULL;
520 /* fall through and ignore it */
521 default:
522 if ((unsigned char)c < ' ') {
523 /* ignore garbage characters */
524 } else if ((int)(bp - G.line_buf) < sizeof(G.line_buf) - 1) {
525 /* echo and store the character */
526 full_write(STDOUT_FILENO, &c, 1);
527 *bp++ = c;
528 }
529 break;
530 }
531 } /* end of get char loop */
532 got_logname: ;
533 } while (G.line_buf[0] == '\0'); /* while logname is empty */
534
535 return G.line_buf;
536 }
537
alarm_handler(int sig UNUSED_PARAM)538 static void alarm_handler(int sig UNUSED_PARAM)
539 {
540 finalize_tty_attrs();
541 _exit(EXIT_SUCCESS);
542 }
543
sleep10(void)544 static void sleep10(void)
545 {
546 sleep(10);
547 }
548
549 int getty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
getty_main(int argc UNUSED_PARAM,char ** argv)550 int getty_main(int argc UNUSED_PARAM, char **argv)
551 {
552 int n;
553 pid_t pid, tsid;
554 char *logname;
555
556 INIT_G();
557 G.login = _PATH_LOGIN; /* default login program */
558 #ifdef ISSUE
559 G.issue = ISSUE; /* default issue file */
560 #endif
561 G.eol = '\r';
562
563 /* Parse command-line arguments */
564 parse_args(argv);
565
566 /* Create new session and pgrp, lose controlling tty */
567 pid = setsid(); /* this also gives us our pid :) */
568 if (pid < 0) {
569 int fd;
570 /* :(
571 * docs/ctty.htm says:
572 * "This is allowed only when the current process
573 * is not a process group leader".
574 * Thus, setsid() will fail if we _already_ are
575 * a session leader - which is quite possible for getty!
576 */
577 pid = getpid();
578 if (getsid(0) != pid) {
579 //for debugging:
580 //bb_perror_msg_and_die("setsid failed:"
581 // " pid %d ppid %d"
582 // " sid %d pgid %d",
583 // pid, getppid(),
584 // getsid(0), getpgid(0));
585 bb_simple_perror_msg_and_die("setsid");
586 /*
587 * When we can end up here?
588 * Example: setsid() fails when run alone in interactive shell:
589 * # getty 115200 /dev/tty2
590 * because shell's child (getty) is put in a new process group.
591 * But doesn't fail if shell is not interactive
592 * (and therefore doesn't create process groups for pipes),
593 * or if getty is not the first process in the process group:
594 * # true | getty 115200 /dev/tty2
595 */
596 }
597 /* Looks like we are already a session leader.
598 * In this case (setsid failed) we may still have ctty,
599 * and it may be different from tty we need to control!
600 * If we still have ctty, on Linux ioctl(TIOCSCTTY)
601 * (which we are going to use a bit later) always fails -
602 * even if we try to take ctty which is already ours!
603 * Try to drop old ctty now to prevent that.
604 * Use O_NONBLOCK: old ctty may be a serial line.
605 */
606 fd = open("/dev/tty", O_RDWR | O_NONBLOCK);
607 if (fd >= 0) {
608 /* TIOCNOTTY sends SIGHUP to the foreground
609 * process group - which may include us!
610 * Make sure to not die on it:
611 */
612 sighandler_t old = signal(SIGHUP, SIG_IGN);
613 ioctl(fd, TIOCNOTTY);
614 close(fd);
615 signal(SIGHUP, old);
616 }
617 }
618
619 /* Close stdio, and stray descriptors, just in case */
620 n = xopen(bb_dev_null, O_RDWR);
621 /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
622 xdup2(n, 1);
623 xdup2(n, 2);
624 while (n > 2)
625 close(n--);
626
627 /* Logging. We want special flavor of error_msg_and_die */
628 die_func = sleep10;
629 msg_eol = "\r\n";
630 /* most likely will internally use fd #3 in CLOEXEC mode: */
631 openlog(applet_name, LOG_PID, LOG_AUTH);
632 logmode = LOGMODE_BOTH;
633
634 #ifdef DEBUGGING
635 dbf = xfopen_for_write(DEBUGTERM);
636 for (n = 1; argv[n]; n++) {
637 debug(argv[n]);
638 debug("\n");
639 }
640 #endif
641
642 /* Open the tty as standard input, if it is not "-" */
643 debug("calling open_tty\n");
644 open_tty();
645 ndelay_off(STDIN_FILENO);
646 debug("duping\n");
647 xdup2(STDIN_FILENO, 1);
648 xdup2(STDIN_FILENO, 2);
649
650 /* Steal ctty if we don't have it yet */
651 tsid = tcgetsid(STDIN_FILENO);
652 if (tsid < 0 || pid != tsid) {
653 if (ioctl(STDIN_FILENO, TIOCSCTTY, /*force:*/ (long)1) < 0)
654 bb_simple_perror_msg_and_die("TIOCSCTTY");
655 }
656
657 #ifdef __linux__
658 /* Make ourself a foreground process group within our session */
659 if (tcsetpgrp(STDIN_FILENO, pid) < 0)
660 bb_simple_perror_msg_and_die("tcsetpgrp");
661 #endif
662
663 /*
664 * The following ioctl will fail if stdin is not a tty, but also when
665 * there is noise on the modem control lines. In the latter case, the
666 * common course of action is (1) fix your cables (2) give the modem more
667 * time to properly reset after hanging up. SunOS users can achieve (2)
668 * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
669 * 5 seconds seems to be a good value.
670 */
671 if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0)
672 bb_simple_perror_msg_and_die("tcgetattr");
673
674 /* Update the utmp file. This tty is ours now! */
675 update_utmp(pid, LOGIN_PROCESS, G.tty_name, "LOGIN", G.fakehost);
676
677 /* Initialize tty attrs (raw mode, eight-bit, blocking i/o) */
678 debug("calling init_tty_attrs\n");
679 init_tty_attrs(G.speeds[0]);
680
681 /* Write the modem init string and DON'T flush the buffers */
682 if (option_mask32 & F_INITSTRING) {
683 debug("writing init string\n");
684 full_write1_str(G.initstring);
685 }
686
687 /* Optionally detect the baud rate from the modem status message */
688 debug("before autobaud\n");
689 if (option_mask32 & F_PARSE)
690 auto_baud();
691
692 /* Set the optional timer */
693 signal(SIGALRM, alarm_handler);
694 alarm(G.timeout); /* if 0, alarm is not set */
695
696 /* Optionally wait for CR or LF before writing /etc/issue */
697 if (option_mask32 & F_WAITCRLF) {
698 char ch;
699 debug("waiting for cr-lf\n");
700 while (safe_read(STDIN_FILENO, &ch, 1) == 1) {
701 debug("read %x\n", (unsigned char)ch);
702 if (ch == '\n' || ch == '\r')
703 break;
704 }
705 }
706
707 logname = NULL;
708 if (!(option_mask32 & F_NOPROMPT)) {
709 /* NB: init_tty_attrs already set line speed
710 * to G.speeds[0] */
711 int baud_index = 0;
712
713 while (1) {
714 /* Read the login name */
715 debug("reading login name\n");
716 logname = get_logname();
717 if (logname)
718 break;
719 /* We are here only if G.numspeed > 1 */
720 baud_index = (baud_index + 1) % G.numspeed;
721 cfsetspeed(&G.tty_attrs, G.speeds[baud_index]);
722 set_tty_attrs();
723 }
724 }
725
726 /* Disable timer */
727 alarm(0);
728
729 finalize_tty_attrs();
730
731 /* Let the login program take care of password validation */
732 /* We use PATH because we trust that root doesn't set "bad" PATH,
733 * and getty is not suid-root applet */
734 /* With -n, logname == NULL, and login will ask for username instead */
735 BB_EXECLP(G.login, G.login, "--", logname, (char *)0);
736 bb_error_msg_and_die("can't execute '%s'", G.login);
737 }
738