xref: /netbsd-src/libexec/getty/main.c (revision 06be8101a16cc95f40783b3cb7afd12112103a9a)
1 /*	$NetBSD: main.c,v 1.41 2001/11/10 17:35:54 thorpej Exp $	*/
2 
3 /*-
4  * Copyright (c) 1980, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 
38 #ifndef lint
39 __COPYRIGHT("@(#) Copyright (c) 1980, 1993\n\
40 	The Regents of the University of California.  All rights reserved.\n");
41 #endif /* not lint */
42 
43 #ifndef lint
44 #if 0
45 static char sccsid[] = "from: @(#)main.c	8.1 (Berkeley) 6/20/93";
46 #else
47 __RCSID("$NetBSD: main.c,v 1.41 2001/11/10 17:35:54 thorpej Exp $");
48 #endif
49 #endif /* not lint */
50 
51 #include <sys/param.h>
52 #include <sys/stat.h>
53 #include <termios.h>
54 #include <sys/ioctl.h>
55 #include <sys/resource.h>
56 #include <sys/utsname.h>
57 
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <time.h>
61 #include <ctype.h>
62 #include <fcntl.h>
63 #include <pwd.h>
64 #include <setjmp.h>
65 #include <signal.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <syslog.h>
69 #include <time.h>
70 #include <unistd.h>
71 #include <util.h>
72 #include <limits.h>
73 #include <ttyent.h>
74 #include <termcap.h>
75 
76 #include "gettytab.h"
77 #include "pathnames.h"
78 #include "extern.h"
79 
80 extern char **environ;
81 extern char editedhost[];
82 
83 /*
84  * Set the amount of running time that getty should accumulate
85  * before deciding that something is wrong and exit.
86  */
87 #define GETTY_TIMEOUT	60 /* seconds */
88 
89 /* defines for auto detection of incoming PPP calls (->PAP/CHAP) */
90 
91 #define PPP_FRAME           0x7e  /* PPP Framing character */
92 #define PPP_STATION         0xff  /* "All Station" character */
93 #define PPP_ESCAPE          0x7d  /* Escape Character */
94 #define PPP_CONTROL         0x03  /* PPP Control Field */
95 #define PPP_CONTROL_ESCAPED 0x23  /* PPP Control Field, escaped */
96 #define PPP_LCP_HI          0xc0  /* LCP protocol - high byte */
97 #define PPP_LCP_LOW         0x21  /* LCP protocol - low byte */
98 
99 struct termios tmode, omode;
100 
101 int crmod, digit, lower, upper;
102 
103 char	hostname[MAXHOSTNAMELEN + 1];
104 struct	utsname kerninfo;
105 char	name[LOGIN_NAME_MAX];
106 char	dev[] = _PATH_DEV;
107 char	ttyn[32];
108 char	lockfile[512];
109 uid_t	ttyowner;
110 char	*rawttyn;
111 
112 #define	OBUFSIZ		128
113 #define	TABBUFSIZ	512
114 
115 char	defent[TABBUFSIZ];
116 char	tabent[TABBUFSIZ];
117 
118 char	*env[128];
119 
120 const char partab[] = {
121 	0001,0201,0201,0001,0201,0001,0001,0201,
122 	0202,0004,0003,0205,0005,0206,0201,0001,
123 	0201,0001,0001,0201,0001,0201,0201,0001,
124 	0001,0201,0201,0001,0201,0001,0001,0201,
125 	0200,0000,0000,0200,0000,0200,0200,0000,
126 	0000,0200,0200,0000,0200,0000,0000,0200,
127 	0000,0200,0200,0000,0200,0000,0000,0200,
128 	0200,0000,0000,0200,0000,0200,0200,0000,
129 	0200,0000,0000,0200,0000,0200,0200,0000,
130 	0000,0200,0200,0000,0200,0000,0000,0200,
131 	0000,0200,0200,0000,0200,0000,0000,0200,
132 	0200,0000,0000,0200,0000,0200,0200,0000,
133 	0000,0200,0200,0000,0200,0000,0000,0200,
134 	0200,0000,0000,0200,0000,0200,0200,0000,
135 	0200,0000,0000,0200,0000,0200,0200,0000,
136 	0000,0200,0200,0000,0200,0000,0000,0201
137 };
138 
139 #define	ERASE	tmode.c_cc[VERASE]
140 #define	KILL	tmode.c_cc[VKILL]
141 #define	EOT	tmode.c_cc[VEOF]
142 
143 static void	clearscreen(void);
144 
145 jmp_buf timeout;
146 
147 static void
148 dingdong(int signo)
149 {
150 
151 	alarm(0);
152 	signal(SIGALRM, SIG_DFL);
153 	longjmp(timeout, 1);
154 }
155 
156 jmp_buf	intrupt;
157 
158 static void
159 interrupt(int signo)
160 {
161 
162 	signal(SIGINT, interrupt);
163 	longjmp(intrupt, 1);
164 }
165 
166 /*
167  * Action to take when getty is running too long.
168  */
169 static void
170 timeoverrun(int signo)
171 {
172 
173 	syslog(LOG_ERR, "getty exiting due to excessive running time");
174 	exit(1);
175 }
176 
177 int		main(int, char *[]);
178 static int	getname(void);
179 static void	oflush(void);
180 static void	prompt(void);
181 static void	putchr(int);
182 static void	putf(const char *);
183 static void	putpad(const char *);
184 static void	xputs(const char *);
185 
186 int
187 main(int argc, char *argv[])
188 {
189 	const char *progname;
190 	char *tname;
191 	int repcnt = 0, failopenlogged = 0, uugetty = 0, first_time = 1;
192 	struct rlimit limit;
193 	struct passwd *pw;
194         int rval;
195 
196 #ifdef __GNUC__
197 	(void)&tname;		/* XXX gcc -Wall */
198 #endif
199 
200 	signal(SIGINT, SIG_IGN);
201 /*
202 	signal(SIGQUIT, SIG_DFL);
203 */
204 	openlog("getty", LOG_PID, LOG_AUTH);
205 	gethostname(hostname, sizeof(hostname));
206 	hostname[sizeof(hostname) - 1] = '\0';
207 	if (hostname[0] == '\0')
208 		strcpy(hostname, "Amnesiac");
209 	uname(&kerninfo);
210 
211 	progname = getprogname();
212 	if (progname[0] == 'u' && progname[1] == 'u')
213 		uugetty = 1;
214 
215 	/*
216 	 * Find id of uucp login (if present) so we can chown tty properly.
217 	 */
218 	if (uugetty && (pw = getpwnam("uucp")))
219 		ttyowner = pw->pw_uid;
220 	else
221 		ttyowner = 0;
222 
223 	/*
224 	 * Limit running time to deal with broken or dead lines.
225 	 */
226 	(void)signal(SIGXCPU, timeoverrun);
227 	limit.rlim_max = RLIM_INFINITY;
228 	limit.rlim_cur = GETTY_TIMEOUT;
229 	(void)setrlimit(RLIMIT_CPU, &limit);
230 
231 	/*
232 	 * The following is a work around for vhangup interactions
233 	 * which cause great problems getting window systems started.
234 	 * If the tty line is "-", we do the old style getty presuming
235 	 * that the file descriptors are already set up for us.
236 	 * J. Gettys - MIT Project Athena.
237 	 */
238 	if (argc <= 2 || strcmp(argv[2], "-") == 0) {
239 	    strlcpy(ttyn, ttyname(0), sizeof(ttyn));
240 	}
241 	else {
242 	    int i;
243 
244 	    rawttyn = argv[2];
245 	    strlcpy(ttyn, dev, sizeof(ttyn));
246 	    strlcat(ttyn, argv[2], sizeof(ttyn));
247 
248 	    if (uugetty)  {
249 		chown(ttyn, ttyowner, 0);
250 		strcpy(lockfile, _PATH_LOCK);
251 		strlcat(lockfile, argv[2], sizeof(lockfile));
252 		/* wait for lockfiles to go away before we try to open */
253 		if ( pidlock(lockfile, 0, 0, 0) != 0 )  {
254 		    syslog(LOG_ERR, "%s: can't create lockfile", ttyn);
255 		    exit(1);
256 		}
257 		unlink(lockfile);
258 	    }
259 	    if (strcmp(argv[0], "+") != 0) {
260 		chown(ttyn, ttyowner, 0);
261 		chmod(ttyn, 0600);
262 		revoke(ttyn);
263 		if (ttyaction(ttyn, "getty", "root"))
264 			syslog(LOG_WARNING, "%s: ttyaction failed", ttyn);
265 		/*
266 		 * Delay the open so DTR stays down long enough to be detected.
267 		 */
268 		sleep(2);
269 		while ((i = open(ttyn, O_RDWR)) == -1) {
270 			if ((repcnt % 10 == 0) &&
271 			    (errno != ENXIO || !failopenlogged)) {
272 				syslog(LOG_WARNING, "%s: %m", ttyn);
273 				closelog();
274 				failopenlogged = 1;
275 			}
276 			repcnt++;
277 			sleep(60);
278 		}
279 		if (uugetty && pidlock(lockfile, 0, 0, 0) != 0)  {
280 			syslog(LOG_ERR, "%s: can't create lockfile", ttyn);
281 			exit(1);
282 		}
283 		(void) chown(lockfile, ttyowner, 0);
284 		login_tty(i);
285 	    }
286 	}
287 
288 	/* Start with default tty settings */
289 	if (tcgetattr(0, &tmode) < 0) {
290 		syslog(LOG_ERR, "%s: %m", ttyn);
291 		exit(1);
292 	}
293 	omode = tmode;
294 
295 	gettable("default", defent);
296 	gendefaults();
297 	tname = "default";
298 	if (argc > 1)
299 		tname = argv[1];
300 	for (;;) {
301 		int off;
302 
303 		gettable(tname, tabent);
304 		if (OPset || EPset || APset)
305 			APset++, OPset++, EPset++;
306 		setdefaults();
307 		off = 0;
308 		(void)tcflush(0, TCIOFLUSH);	/* clear out the crap */
309 		ioctl(0, FIONBIO, &off);	/* turn off non-blocking mode */
310 		ioctl(0, FIOASYNC, &off);	/* ditto for async mode */
311 
312 		if (IS)
313 			cfsetispeed(&tmode, IS);
314 		else if (SP)
315 			cfsetispeed(&tmode, SP);
316 		if (OS)
317 			cfsetospeed(&tmode, OS);
318 		else if (SP)
319 			cfsetospeed(&tmode, SP);
320 		setflags(0);
321 		setchars();
322 		if (tcsetattr(0, TCSANOW, &tmode) < 0) {
323 			syslog(LOG_ERR, "%s: %m", ttyn);
324 			exit(1);
325 		}
326 		if (AB) {
327 			tname = autobaud();
328 			continue;
329 		}
330 		if (PS) {
331 			tname = portselector();
332 			continue;
333 		}
334 		if (CS)
335 			clearscreen();
336 		if (CL && *CL)
337 			putpad(CL);
338 		edithost(HE);
339 
340                 /*
341                  * If this is the first time through this, and an
342                  * issue file has been given, then send it.
343                  */
344 		if (first_time != 0 && IF != NULL) {
345 			char buf[_POSIX2_LINE_MAX];
346 			FILE *fd;
347 
348 			if ((fd = fopen(IF, "r")) != NULL) {
349 				while (fgets(buf, sizeof(buf) - 1, fd) != NULL)
350 					putf(buf);
351 				fclose(fd);
352 			}
353 		}
354 		first_time = 0;
355 
356 		if (IM && *IM)
357 			putf(IM);
358 		oflush();
359 		if (setjmp(timeout)) {
360 			tmode.c_ispeed = tmode.c_ospeed = 0;
361 			(void)tcsetattr(0, TCSANOW, &tmode);
362 			exit(1);
363 		}
364 		if (TO) {
365 			signal(SIGALRM, dingdong);
366 			alarm(TO);
367 		}
368 		if (AL) {
369 			const char *p = AL;
370 			char *q = name;
371 
372 			while (*p && q < &name[sizeof name - 1]) {
373 				if (isupper(*p))
374 					upper = 1;
375 				else if (islower(*p))
376 					lower = 1;
377 				else if (isdigit(*p))
378 					digit++;
379 				*q++ = *p++;
380 			}
381 		} else if ((rval = getname()) == 2) {
382 		        execle(PP, "ppplogin", ttyn, (char *) 0, env);
383 		        syslog(LOG_ERR, "%s: %m", PP);
384 		        exit(1);
385 		}
386 
387 		if (rval || AL) {
388 			int i;
389 
390 			oflush();
391 			alarm(0);
392 			signal(SIGALRM, SIG_DFL);
393 			if (name[0] == '-') {
394 				xputs("user names may not start with '-'.");
395 				continue;
396 			}
397 			if (!(upper || lower || digit))
398 				continue;
399 			setflags(2);
400 			if (crmod) {
401 				tmode.c_iflag |= ICRNL;
402 				tmode.c_oflag |= ONLCR;
403 			}
404 #if XXX
405 			if (upper || UC)
406 				tmode.sg_flags |= LCASE;
407 			if (lower || LC)
408 				tmode.sg_flags &= ~LCASE;
409 #endif
410 			if (tcsetattr(0, TCSANOW, &tmode) < 0) {
411 				syslog(LOG_ERR, "%s: %m", ttyn);
412 				exit(1);
413 			}
414 			signal(SIGINT, SIG_DFL);
415 			for (i = 0; environ[i] != (char *)0; i++)
416 				env[i] = environ[i];
417 			makeenv(&env[i]);
418 
419 			limit.rlim_max = RLIM_INFINITY;
420 			limit.rlim_cur = RLIM_INFINITY;
421 			(void)setrlimit(RLIMIT_CPU, &limit);
422 			execle(LO, "login", AL ? "-fp" : "-p", "--", name,
423 			    (char *)0, env);
424 			syslog(LOG_ERR, "%s: %m", LO);
425 			exit(1);
426 		}
427 		alarm(0);
428 		signal(SIGALRM, SIG_DFL);
429 		signal(SIGINT, SIG_IGN);
430 		if (NX && *NX)
431 			tname = NX;
432 		unlink(lockfile);
433 	}
434 }
435 
436 static int
437 getname(void)
438 {
439 	int c;
440 	char *np;
441 	unsigned char cs;
442 	int ppp_state, ppp_connection;
443 
444 	/*
445 	 * Interrupt may happen if we use CBREAK mode
446 	 */
447 	if (setjmp(intrupt)) {
448 		signal(SIGINT, SIG_IGN);
449 		return (0);
450 	}
451 	signal(SIGINT, interrupt);
452 	setflags(1);
453 	prompt();
454 	if (PF > 0) {
455 		oflush();
456 		sleep(PF);
457 		PF = 0;
458 	}
459 	if (tcsetattr(0, TCSANOW, &tmode) < 0) {
460 		syslog(LOG_ERR, "%s: %m", ttyn);
461 		exit(1);
462 	}
463 	crmod = digit = lower = upper = 0;
464         ppp_state = ppp_connection = 0;
465 	np = name;
466 	for (;;) {
467 		oflush();
468 		if (read(STDIN_FILENO, &cs, 1) <= 0)
469 			exit(0);
470 		if ((c = cs&0177) == 0)
471 			return (0);
472 
473 		/*
474 		 * PPP detection state machine..
475 		 * Look for sequences:
476 		 * PPP_FRAME, PPP_STATION, PPP_ESCAPE, PPP_CONTROL_ESCAPED or
477 		 * PPP_FRAME, PPP_STATION, PPP_CONTROL (deviant from RFC)
478 		 * See RFC1662.
479 		 * Derived from code from Michael Hancock <michaelh@cet.co.jp>
480 		 * and Erik 'PPP' Olson <eriko@wrq.com>
481 		 */
482 		if (PP && cs == PPP_FRAME) {
483 			ppp_state = 1;
484 		} else if (ppp_state == 1 && cs == PPP_STATION) {
485 			ppp_state = 2;
486 		} else if (ppp_state == 2 && cs == PPP_ESCAPE) {
487 			ppp_state = 3;
488 		} else if ((ppp_state == 2 && cs == PPP_CONTROL) ||
489 		    (ppp_state == 3 && cs == PPP_CONTROL_ESCAPED)) {
490 			ppp_state = 4;
491 		} else if (ppp_state == 4 && cs == PPP_LCP_HI) {
492 			ppp_state = 5;
493 		} else if (ppp_state == 5 && cs == PPP_LCP_LOW) {
494 			ppp_connection = 1;
495 			break;
496 		} else {
497 			ppp_state = 0;
498 		}
499 
500 		if (c == EOT)
501 			exit(1);
502 		if (c == '\r' || c == '\n' ||
503 		    np >= &name[LOGIN_NAME_MAX - 1]) {
504 			*np = '\0';
505 			putf("\r\n");
506 			break;
507 		}
508 		if (islower(c))
509 			lower = 1;
510 		else if (isupper(c))
511 			upper = 1;
512 		else if (c == ERASE || c == '#' || c == '\b') {
513 			if (np > name) {
514 				np--;
515 				if (cfgetospeed(&tmode) >= 1200)
516 					xputs("\b \b");
517 				else
518 					putchr(cs);
519 			}
520 			continue;
521 		} else if (c == KILL || c == '@') {
522 			putchr(cs);
523 			putchr('\r');
524 			if (cfgetospeed(&tmode) < 1200)
525 				putchr('\n');
526 			/* this is the way they do it down under ... */
527 			else if (np > name)
528 				xputs(
529 				    "                                     \r");
530 			prompt();
531 			np = name;
532 			continue;
533 		} else if (isdigit(c))
534 			digit++;
535 		if (IG && (c <= ' ' || c > 0176))
536 			continue;
537 		*np++ = c;
538 		putchr(cs);
539 	}
540 	signal(SIGINT, SIG_IGN);
541 	*np = 0;
542 	if (c == '\r')
543 		crmod = 1;
544 	if ((upper && !lower && !LC) || UC)
545 		for (np = name; *np; np++)
546 			if (isupper(*np))
547 				*np = tolower(*np);
548 	return (1 + ppp_connection);
549 }
550 
551 static void
552 putpad(const char *s)
553 {
554 	int pad = 0;
555 	speed_t ospeed = cfgetospeed(&tmode);
556 
557 	if (isdigit(*s)) {
558 		while (isdigit(*s)) {
559 			pad *= 10;
560 			pad += *s++ - '0';
561 		}
562 		pad *= 10;
563 		if (*s == '.' && isdigit(s[1])) {
564 			pad += s[1] - '0';
565 			s += 2;
566 		}
567 	}
568 
569 	xputs(s);
570 	/*
571 	 * If no delay needed, or output speed is
572 	 * not comprehensible, then don't try to delay.
573 	 */
574 	if (pad == 0 || ospeed <= 0)
575 		return;
576 
577 	/*
578 	 * Round up by a half a character frame, and then do the delay.
579 	 * Too bad there are no user program accessible programmed delays.
580 	 * Transmitting pad characters slows many terminals down and also
581 	 * loads the system.
582 	 */
583 	pad = (pad * ospeed + 50000) / 100000;
584 	while (pad--)
585 		putchr(*PC);
586 }
587 
588 static void
589 xputs(const char *s)
590 {
591 	while (*s)
592 		putchr(*s++);
593 }
594 
595 char	outbuf[OBUFSIZ];
596 int	obufcnt = 0;
597 
598 static void
599 putchr(int cc)
600 {
601 	char c;
602 
603 	c = cc;
604 	if (!NP) {
605 		c |= partab[c&0177] & 0200;
606 		if (OP)
607 			c ^= 0200;
608 	}
609 	if (!UB) {
610 		outbuf[obufcnt++] = c;
611 		if (obufcnt >= OBUFSIZ)
612 			oflush();
613 	} else
614 		write(STDOUT_FILENO, &c, 1);
615 }
616 
617 static void
618 oflush(void)
619 {
620 	if (obufcnt)
621 		write(STDOUT_FILENO, outbuf, obufcnt);
622 	obufcnt = 0;
623 }
624 
625 static void
626 prompt(void)
627 {
628 
629 	putf(LM);
630 	if (CO)
631 		putchr('\n');
632 }
633 
634 static void
635 putf(const char *cp)
636 {
637 	time_t t;
638 	char *slash, db[100];
639 
640 	while (*cp) {
641 		if (*cp != '%') {
642 			putchr(*cp++);
643 			continue;
644 		}
645 		switch (*++cp) {
646 
647 		case 't':
648 			slash = strrchr(ttyn, '/');
649 			if (slash == NULL)
650 				xputs(ttyn);
651 			else
652 				xputs(&slash[1]);
653 			break;
654 
655 		case 'h':
656 			xputs(editedhost);
657 			break;
658 
659 		case 'd':
660 			(void)time(&t);
661 			(void)strftime(db, sizeof(db),
662 			    /* SCCS eats %M% */
663 			    "%l:%M" "%p on %A, %d %B %Y", localtime(&t));
664 			xputs(db);
665 			break;
666 
667 		case 's':
668 			xputs(kerninfo.sysname);
669 			break;
670 
671 		case 'm':
672 			xputs(kerninfo.machine);
673 			break;
674 
675 		case 'r':
676 			xputs(kerninfo.release);
677 			break;
678 
679 		case 'v':
680 			xputs(kerninfo.version);
681 			break;
682 
683 		case '%':
684 			putchr('%');
685 			break;
686 		}
687 		if (*cp)
688 			cp++;
689 	}
690 }
691 
692 static void
693 clearscreen(void)
694 {
695 	struct ttyent *typ;
696 	struct tinfo *tinfo;
697 	char *cs;
698 
699 	if (rawttyn == NULL)
700 		return;
701 
702 	typ = getttynam(rawttyn);
703 
704 	if ((typ == NULL) || (typ->ty_type == NULL) ||
705 	    (typ->ty_type[0] == 0))
706 		return;
707 
708 	if (t_getent(&tinfo, typ->ty_type) <= 0)
709 		return;
710 
711 	cs = t_agetstr(tinfo, "cl");
712 	if (cs == NULL)
713 		return;
714 
715 	putpad(cs);
716 }
717