getty: add ECHOE explanation
[oweals/busybox.git] / loginutils / getty.c
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
25 #include "libbb.h"
26 #include <syslog.h>
27 #ifndef IUCLC
28 # define IUCLC 0
29 #endif
30
31 #ifndef LOGIN_PROCESS
32 # undef ENABLE_FEATURE_UTMP
33 # undef ENABLE_FEATURE_WTMP
34 # define ENABLE_FEATURE_UTMP 0
35 # define ENABLE_FEATURE_WTMP 0
36 #endif
37
38
39 /* The following is used for understandable diagnostics */
40 #ifdef DEBUGGING
41 static FILE *dbf;
42 # define DEBUGTERM "/dev/ttyp0"
43 # define debug(...) do { fprintf(dbf, __VA_ARGS__); fflush(dbf); } while (0)
44 #else
45 # define debug(...) ((void)0)
46 #endif
47
48
49 /*
50  * Things you may want to modify.
51  *
52  * You may disagree with the default line-editing etc. characters defined
53  * below. Note, however, that DEL cannot be used for interrupt generation
54  * and for line editing at the same time.
55  */
56 #undef  _PATH_LOGIN
57 #define _PATH_LOGIN "/bin/login"
58
59 /* Displayed before the login prompt.
60  * If ISSUE is not defined, getty will never display the contents of the
61  * /etc/issue file. You will not want to spit out large "issue" files at the
62  * wrong baud rate.
63  */
64 #define ISSUE "/etc/issue"
65
66 /* Some shorthands for control characters */
67 #define CTL(x)          ((x) ^ 0100)    /* Assumes ASCII dialect */
68 #define BS              CTL('H')        /* back space */
69 #define DEL             CTL('?')        /* delete */
70
71 /* Defaults for line-editing etc. characters; you may want to change this */
72 #define DEF_INTR        CTL('C')        /* default interrupt character */
73 #define DEF_QUIT        CTL('\\')       /* default quit char */
74 #define DEF_KILL        CTL('U')        /* default kill char */
75 #define DEF_EOF         CTL('D')        /* default EOF char */
76 #define DEF_EOL         '\n'
77 #define DEF_SWITCH      0               /* default switch char (none) */
78
79 /*
80  * When multiple baud rates are specified on the command line,
81  * the first one we will try is the first one specified.
82  */
83 #define MAX_SPEED       10              /* max. nr. of baud rates */
84
85 struct globals {
86         unsigned timeout;               /* time-out period */
87         const char *login;              /* login program */
88         const char *fakehost;
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         unsigned char eol;              /* end-of-line char seen (CR or NL) */
95         struct termios termios;         /* terminal mode bits */
96         char line_buf[128];
97 };
98
99 #define G (*ptr_to_globals)
100 #define INIT_G() do { \
101         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
102 } while (0)
103
104 //usage:#define getty_trivial_usage
105 //usage:       "[OPTIONS] BAUD_RATE[,BAUD_RATE]... TTY [TERMTYPE]"
106 //usage:#define getty_full_usage "\n\n"
107 //usage:       "Open a tty, prompt for a login name, then invoke /bin/login\n"
108 //usage:     "\nOptions:"
109 //usage:     "\n        -h              Enable hardware RTS/CTS flow control"
110 //usage:     "\n        -L              Set CLOCAL (ignore Carrier Detect state)"
111 //usage:     "\n        -m              Get baud rate from modem's CONNECT status message"
112 //usage:     "\n        -n              Don't prompt for login name"
113 //usage:     "\n        -w              Wait for CR or LF before sending /etc/issue"
114 //usage:     "\n        -i              Don't display /etc/issue"
115 //usage:     "\n        -f ISSUE_FILE   Display ISSUE_FILE instead of /etc/issue"
116 //usage:     "\n        -l LOGIN        Invoke LOGIN instead of /bin/login"
117 //usage:     "\n        -t SEC          Terminate after SEC if no login name is read"
118 //usage:     "\n        -I INITSTR      Send INITSTR before anything else"
119 //usage:     "\n        -H HOST         Log HOST into the utmp file as the hostname"
120 //usage:     "\n"
121 //usage:     "\nBAUD_RATE of 0 leaves it unchanged"
122
123 static const char opt_string[] ALIGN1 = "I:LH:f:hil:mt:wn";
124 #define F_INITSTRING    (1 << 0)   /* -I */
125 #define F_LOCAL         (1 << 1)   /* -L */
126 #define F_FAKEHOST      (1 << 2)   /* -H */
127 #define F_CUSTISSUE     (1 << 3)   /* -f */
128 #define F_RTSCTS        (1 << 4)   /* -h */
129 #define F_NOISSUE       (1 << 5)   /* -i */
130 #define F_LOGIN         (1 << 6)   /* -l */
131 #define F_PARSE         (1 << 7)   /* -m */
132 #define F_TIMEOUT       (1 << 8)   /* -t */
133 #define F_WAITCRLF      (1 << 9)   /* -w */
134 #define F_NOPROMPT      (1 << 10)  /* -n */
135
136
137 /* convert speed string to speed code; return <= 0 on failure */
138 static int bcode(const char *s)
139 {
140         int value = bb_strtou(s, NULL, 10); /* yes, int is intended! */
141         if (value < 0) /* bad terminating char, overflow, etc */
142                 return value;
143         return tty_value_to_baud(value);
144 }
145
146 /* parse alternate baud rates */
147 static void parse_speeds(char *arg)
148 {
149         char *cp;
150
151         /* NB: at least one iteration is always done */
152         debug("entered parse_speeds\n");
153         while ((cp = strsep(&arg, ",")) != NULL) {
154                 G.speeds[G.numspeed] = bcode(cp);
155                 if (G.speeds[G.numspeed] < 0)
156                         bb_error_msg_and_die("bad speed: %s", cp);
157                 /* note: arg "0" turns into speed B0 */
158                 G.numspeed++;
159                 if (G.numspeed > MAX_SPEED)
160                         bb_error_msg_and_die("too many alternate speeds");
161         }
162         debug("exiting parse_speeds\n");
163 }
164
165 /* parse command-line arguments */
166 static void parse_args(char **argv)
167 {
168         char *ts;
169         int flags;
170
171         opt_complementary = "-2:t+"; /* at least 2 args; -t N */
172         flags = getopt32(argv, opt_string,
173                 &G.initstring, &G.fakehost, &G.issue,
174                 &G.login, &G.timeout
175         );
176         if (flags & F_INITSTRING) {
177                 G.initstring = xstrdup(G.initstring);
178                 /* decode \ddd octal codes into chars */
179                 strcpy_and_process_escape_sequences((char*)G.initstring, G.initstring);
180         }
181         argv += optind;
182         debug("after getopt\n");
183
184         /* We loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
185         G.tty = argv[0];        /* tty name */
186         ts = argv[1];           /* baud rate(s) */
187         if (isdigit(argv[0][0])) {
188                 /* A number first, assume it's a speed (BSD style) */
189                 G.tty = ts;     /* tty name is in argv[1] */
190                 ts = argv[0];   /* baud rate(s) */
191         }
192         parse_speeds(ts);
193         applet_name = xasprintf("getty: %s", G.tty);
194
195         if (argv[2])
196                 xsetenv("TERM", argv[2]);
197
198         debug("exiting parse_args\n");
199 }
200
201 /* set up tty as standard input, output, error */
202 static void open_tty(void)
203 {
204         /* Set up new standard input, unless we are given an already opened port */
205         if (NOT_LONE_DASH(G.tty)) {
206                 if (G.tty[0] != '/')
207                         G.tty = xasprintf("/dev/%s", G.tty); /* will leak it */
208
209                 /* Open the tty as standard input */
210                 debug("open(2)\n");
211                 close(0);
212                 xopen(G.tty, O_RDWR | O_NONBLOCK); /* uses fd 0 */
213
214                 /* Set proper protections and ownership */
215                 fchown(0, 0, 0);        /* 0:0 */
216                 fchmod(0, 0620);        /* crw--w---- */
217         } else {
218                 /*
219                  * Standard input should already be connected to an open port. Make
220                  * sure it is open for read/write.
221                  */
222                 if ((fcntl(0, F_GETFL) & (O_RDWR|O_RDONLY|O_WRONLY)) != O_RDWR)
223                         bb_error_msg_and_die("stdin is not open for read/write");
224         }
225 }
226
227 /* We manipulate termios this way:
228  * - first, we read existing termios settings
229  * - termios_init modifies some parts and sets it
230  * - auto_baud and/or BREAK processing can set different speed and set termios
231  * - termios_final again modifies some parts and sets termios before
232  *   execing login
233  */
234 static void termios_init(int speed)
235 {
236         /* Flush input and output queues, important for modems!
237          * Users report losing previously queued output chars, and I hesitate
238          * to use tcdrain here instead of tcflush - I imagine it can block.
239          * Using small sleep instead.
240          */
241         usleep(100*1000); /* 0.1 sec */
242         tcflush(STDIN_FILENO, TCIOFLUSH);
243
244         /* Set speed if it wasn't specified as "0" on command line */
245         if (speed != B0)
246                 cfsetspeed(&G.termios, speed);
247
248         /*
249          * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
250          * Special characters are set after we have read the login name; all
251          * reads will be done in raw mode anyway. Errors will be dealt with
252          * later on.
253          */
254         /* 8 bits; hangup (drop DTR) on last close; enable receive */
255         G.termios.c_cflag = CS8 | HUPCL | CREAD;
256         if (option_mask32 & F_LOCAL) {
257                 /* ignore Carrier Detect pin:
258                  * opens don't block when CD is low,
259                  * losing CD doesn't hang up processes whose ctty is this tty
260                  */
261                 G.termios.c_cflag |= CLOCAL;
262         }
263 #ifdef CRTSCTS
264         if (option_mask32 & F_RTSCTS)
265                 G.termios.c_cflag |= CRTSCTS; /* flow control using RTS/CTS pins */
266 #endif
267         G.termios.c_iflag = 0;
268         G.termios.c_lflag = 0;
269         /* non-raw output; add CR to each NL */
270         G.termios.c_oflag = OPOST | ONLCR;
271         G.termios.c_cc[VMIN] = 1; /* block reads if < 1 char is available */
272         G.termios.c_cc[VTIME] = 0; /* no timeout (reads block forever) */
273 #ifdef __linux__
274         G.termios.c_line = 0;
275 #endif
276
277         tcsetattr_stdin_TCSANOW(&G.termios);
278
279         debug("term_io 2\n");
280 }
281
282 static void termios_final(void)
283 {
284         /* software flow control on output; and on input */
285         G.termios.c_iflag |= IXON | IXOFF;
286         if (G.eol == '\r') {
287                 G.termios.c_iflag |= ICRNL; /* map CR on input to NL */
288         }
289         /* non-raw input; enable SIGINT/QUIT/etc sigs; echo;
290          * echo erase character as BS-space-BS;
291          * echo NL on kill char;
292          * erase entire line via BS-space-BS on kill char */
293         G.termios.c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
294         /* echo ctrl chars as ^c; (what is ECHOPRT?) */
295         /* no longer in c_lflag: | ECHOCTL | ECHOPRT */
296
297         G.termios.c_cc[VINTR] = DEF_INTR;
298         G.termios.c_cc[VQUIT] = DEF_QUIT;
299         G.termios.c_cc[VEOF] = DEF_EOF;
300         G.termios.c_cc[VEOL] = DEF_EOL;
301 #ifdef VSWTC
302         G.termios.c_cc[VSWTC] = DEF_SWITCH;
303 #endif
304 #ifdef VSWTCH
305         G.termios.c_cc[VSWTCH] = DEF_SWITCH;
306 #endif
307         G.termios.c_cc[VKILL] = DEF_KILL;
308
309         if (tcsetattr_stdin_TCSANOW(&G.termios) < 0)
310                 bb_perror_msg_and_die("tcsetattr");
311 }
312
313 /* extract baud rate from modem status message */
314 static void auto_baud(void)
315 {
316         int nread;
317
318         /*
319          * This works only if the modem produces its status code AFTER raising
320          * the DCD line, and if the computer is fast enough to set the proper
321          * baud rate before the message has gone by. We expect a message of the
322          * following format:
323          *
324          * <junk><number><junk>
325          *
326          * The number is interpreted as the baud rate of the incoming call. If the
327          * modem does not tell us the baud rate within one second, we will keep
328          * using the current baud rate. It is advisable to enable BREAK
329          * processing (comma-separated list of baud rates) if the processing of
330          * modem status messages is enabled.
331          */
332
333         G.termios.c_cc[VMIN] = 0; /* don't block reads (min read is 0 chars) */
334         tcsetattr_stdin_TCSANOW(&G.termios);
335
336         /*
337          * Wait for a while, then read everything the modem has said so far and
338          * try to extract the speed of the dial-in call.
339          */
340         sleep(1);
341         nread = safe_read(STDIN_FILENO, G.line_buf, sizeof(G.line_buf) - 1);
342         if (nread > 0) {
343                 int speed;
344                 char *bp;
345                 G.line_buf[nread] = '\0';
346                 for (bp = G.line_buf; bp < G.line_buf + nread; bp++) {
347                         if (isdigit(*bp)) {
348                                 speed = bcode(bp);
349                                 if (speed > 0)
350                                         cfsetspeed(&G.termios, speed);
351                                 break;
352                         }
353                 }
354         }
355
356         /* Restore terminal settings. Errors will be dealt with later on */
357         G.termios.c_cc[VMIN] = 1; /* restore to value set by termios_init */
358         tcsetattr_stdin_TCSANOW(&G.termios);
359 }
360
361 /* get user name, establish parity, speed, erase, kill, eol;
362  * return NULL on BREAK, logname on success
363  */
364 static char *get_logname(void)
365 {
366         char *bp;
367         char c;
368
369         /* Flush pending input (esp. after parsing or switching the baud rate) */
370         usleep(100*1000); /* 0.1 sec */
371         tcflush(STDIN_FILENO, TCIFLUSH);
372
373         /* Prompt for and read a login name */
374         G.line_buf[0] = '\0';
375         while (!G.line_buf[0]) {
376                 /* Write issue file and prompt */
377 #ifdef ISSUE
378                 if (!(option_mask32 & F_NOISSUE))
379                         print_login_issue(G.issue, G.tty);
380 #endif
381                 print_login_prompt();
382
383                 /* Read name, watch for break, parity, erase, kill, end-of-line */
384                 bp = G.line_buf;
385                 G.eol = '\0';
386                 while (1) {
387                         /* Do not report trivial EINTR/EIO errors */
388                         errno = EINTR; /* make read of 0 bytes be silent too */
389                         if (read(STDIN_FILENO, &c, 1) < 1) {
390                                 if (errno == EINTR || errno == EIO)
391                                         exit(EXIT_SUCCESS);
392                                 bb_perror_msg_and_die(bb_msg_read_error);
393                         }
394
395                         /* BREAK. If we have speeds to try,
396                          * return NULL (will switch speeds and return here) */
397                         if (c == '\0' && G.numspeed > 1)
398                                 return NULL;
399
400                         /* Do erase, kill and end-of-line processing */
401                         switch (c) {
402                         case '\r':
403                         case '\n':
404                                 *bp = '\0';
405                                 G.eol = c;
406                                 goto got_logname;
407                         case BS:
408                         case DEL:
409                                 G.termios.c_cc[VERASE] = c;
410                                 if (bp > G.line_buf) {
411                                         full_write(STDOUT_FILENO, "\010 \010", 3);
412                                         bp--;
413                                 }
414                                 break;
415                         case CTL('U'):
416                                 while (bp > G.line_buf) {
417                                         full_write(STDOUT_FILENO, "\010 \010", 3);
418                                         bp--;
419                                 }
420                                 break;
421                         case CTL('D'):
422                                 exit(EXIT_SUCCESS);
423                         default:
424                                 if ((unsigned char)c < ' ') {
425                                         /* ignore garbage characters */
426                                 } else if ((int)(bp - G.line_buf) < sizeof(G.line_buf) - 1) {
427                                         /* echo and store the character */
428                                         full_write(STDOUT_FILENO, &c, 1);
429                                         *bp++ = c;
430                                 }
431                                 break;
432                         }
433                 } /* end of get char loop */
434  got_logname: ;
435         } /* while logname is empty */
436
437         return G.line_buf;
438 }
439
440 int getty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
441 int getty_main(int argc UNUSED_PARAM, char **argv)
442 {
443         int n;
444         pid_t pid;
445         char *logname;
446
447         INIT_G();
448         G.login = _PATH_LOGIN;    /* default login program */
449 #ifdef ISSUE
450         G.issue = ISSUE;          /* default issue file */
451 #endif
452         G.eol = '\r';
453
454         /* Parse command-line arguments */
455         parse_args(argv);
456
457         logmode = LOGMODE_NONE;
458
459         /* Create new session, lose controlling tty, if any */
460         /* docs/ctty.htm says:
461          * "This is allowed only when the current process
462          *  is not a process group leader" - is this a problem? */
463         setsid();
464         /* close stdio, and stray descriptors, just in case */
465         n = xopen(bb_dev_null, O_RDWR);
466         /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
467         xdup2(n, 1);
468         xdup2(n, 2);
469         while (n > 2)
470                 close(n--);
471
472         /* Logging. We want special flavor of error_msg_and_die */
473         die_sleep = 10;
474         msg_eol = "\r\n";
475         /* most likely will internally use fd #3 in CLOEXEC mode: */
476         openlog(applet_name, LOG_PID, LOG_AUTH);
477         logmode = LOGMODE_BOTH;
478
479 #ifdef DEBUGGING
480         dbf = xfopen_for_write(DEBUGTERM);
481         for (n = 1; argv[n]; n++) {
482                 debug(argv[n]);
483                 debug("\n");
484         }
485 #endif
486
487         /* Open the tty as standard input, if it is not "-" */
488         /* If it's not "-" and not taken yet, it will become our ctty */
489         debug("calling open_tty\n");
490         open_tty();
491         ndelay_off(0);
492         debug("duping\n");
493         xdup2(0, 1);
494         xdup2(0, 2);
495
496         /*
497          * The following ioctl will fail if stdin is not a tty, but also when
498          * there is noise on the modem control lines. In the latter case, the
499          * common course of action is (1) fix your cables (2) give the modem more
500          * time to properly reset after hanging up. SunOS users can achieve (2)
501          * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
502          * 5 seconds seems to be a good value.
503          */
504         if (tcgetattr(STDIN_FILENO, &G.termios) < 0)
505                 bb_perror_msg_and_die("tcgetattr");
506
507         pid = getpid();
508 #ifdef __linux__
509 // FIXME: do we need this? Otherwise "-" case seems to be broken...
510         // /* Forcibly make fd 0 our controlling tty, even if another session
511         //  * has it as a ctty. (Another session loses ctty). */
512         // ioctl(STDIN_FILENO, TIOCSCTTY, (void*)1);
513         /* Make ourself a foreground process group within our session */
514         tcsetpgrp(STDIN_FILENO, pid);
515 #endif
516
517         /* Update the utmp file. This tty is ours now! */
518         update_utmp(pid, LOGIN_PROCESS, G.tty, "LOGIN", G.fakehost);
519
520         /* Initialize the termios settings (raw mode, eight-bit, blocking i/o) */
521         debug("calling termios_init\n");
522         termios_init(G.speeds[0]);
523
524         /* Write the modem init string and DON'T flush the buffers */
525         if (option_mask32 & F_INITSTRING) {
526                 debug("writing init string\n");
527                 full_write1_str(G.initstring);
528         }
529
530         /* Optionally detect the baud rate from the modem status message */
531         debug("before autobaud\n");
532         if (option_mask32 & F_PARSE)
533                 auto_baud();
534
535         /* Set the optional timer */
536         alarm(G.timeout); /* if 0, alarm is not set */
537 //BUG: death by signal won't restore termios
538
539         /* Optionally wait for CR or LF before writing /etc/issue */
540         if (option_mask32 & F_WAITCRLF) {
541                 char ch;
542                 debug("waiting for cr-lf\n");
543                 while (safe_read(STDIN_FILENO, &ch, 1) == 1) {
544                         debug("read %x\n", (unsigned char)ch);
545                         if (ch == '\n' || ch == '\r')
546                                 break;
547                 }
548         }
549
550         logname = NULL;
551         if (!(option_mask32 & F_NOPROMPT)) {
552                 /* NB: termios_init already set line speed
553                  * to G.speeds[0] */
554                 int baud_index = 0;
555
556                 while (1) {
557                         /* Read the login name */
558                         debug("reading login name\n");
559                         logname = get_logname();
560                         if (logname)
561                                 break;
562                         /* We are here only if G.numspeed > 1 */
563                         baud_index = (baud_index + 1) % G.numspeed;
564                         cfsetspeed(&G.termios, G.speeds[baud_index]);
565                         tcsetattr_stdin_TCSANOW(&G.termios);
566                 }
567         }
568
569         /* Disable timer */
570         alarm(0);
571
572         /* Finalize the termios settings */
573         termios_final();
574
575         /* Now the newline character should be properly written */
576         full_write(STDOUT_FILENO, "\n", 1);
577
578         /* Let the login program take care of password validation */
579         /* We use PATH because we trust that root doesn't set "bad" PATH,
580          * and getty is not suid-root applet */
581         /* With -n, logname == NULL, and login will ask for username instead */
582         BB_EXECLP(G.login, G.login, "--", logname, NULL);
583         bb_error_msg_and_die("can't execute '%s'", G.login);
584 }