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