1 /*
2 * Copyright (c) 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#if 0
35#ifndef lint
36static const char sccsid[] = "@(#)sys_term.c	8.4+1 (Berkeley) 5/30/95";
37#endif
38#endif
39#include <sys/cdefs.h>
40__FBSDID("$FreeBSD: src/contrib/telnet/telnetd/sys_term.c,v 1.18 2003/05/04 02:54:49 obrien Exp $");
41
42#include <sys/types.h>
43#include <libutil.h>
44#include <stdlib.h>
45#if (!defined(__BEOS__) && !defined(__HAIKU__))
46# include <sys/tty.h>
47# include <utmp.h>
48#endif
49
50#include "telnetd.h"
51#include "pathnames.h"
52
53#ifdef	AUTHENTICATION
54#include <libtelnet/auth.h>
55#endif
56
57int cleanopen(char *);
58void scrub_env(void);
59
60#if (!defined(__BEOS__) && !defined(__HAIKU__))
61
62struct	utmp wtmp;
63
64# ifdef _PATH_WTMP
65char    wtmpf[] = _PATH_WTMP;
66# else
67char	wtmpf[]	= "/var/log/wtmp";
68# endif
69# ifdef _PATH_UTMP
70char    utmpf[] = _PATH_UTMP;
71# else
72char	utmpf[] = "/var/run/utmp";
73# endif
74#endif
75
76char	*envinit[3];
77extern char **environ;
78
79#define SCPYN(a, b)	(void) strncpy(a, b, sizeof(a))
80#define SCMPN(a, b)	strncmp(a, b, sizeof(a))
81
82#ifdef	t_erase
83#undef	t_erase
84#undef	t_kill
85#undef	t_intrc
86#undef	t_quitc
87#undef	t_startc
88#undef	t_stopc
89#undef	t_eofc
90#undef	t_brkc
91#undef	t_suspc
92#undef	t_dsuspc
93#undef	t_rprntc
94#undef	t_flushc
95#undef	t_werasc
96#undef	t_lnextc
97#endif
98
99#ifndef	USE_TERMIO
100struct termbuf {
101	struct sgttyb sg;
102	struct tchars tc;
103	struct ltchars ltc;
104	int state;
105	int lflags;
106} termbuf, termbuf2;
107# define	cfsetospeed(tp, val)	(tp)->sg.sg_ospeed = (val)
108# define	cfsetispeed(tp, val)	(tp)->sg.sg_ispeed = (val)
109# define	cfgetospeed(tp)		(tp)->sg.sg_ospeed
110# define	cfgetispeed(tp)		(tp)->sg.sg_ispeed
111#else	/* USE_TERMIO */
112# ifndef	TCSANOW
113#  ifdef TCSETS
114#   define	TCSANOW		TCSETS
115#   define	TCSADRAIN	TCSETSW
116#   define	tcgetattr(f, t)	ioctl(f, TCGETS, (char *)t)
117#  else
118#   ifdef TCSETA
119#    define	TCSANOW		TCSETA
120#    define	TCSADRAIN	TCSETAW
121#    define	tcgetattr(f, t)	ioctl(f, TCGETA, (char *)t)
122#   else
123#    define	TCSANOW		TIOCSETA
124#    define	TCSADRAIN	TIOCSETAW
125#    define	tcgetattr(f, t)	ioctl(f, TIOCGETA, (char *)t)
126#   endif
127#  endif
128#  define	tcsetattr(f, a, t)	ioctl(f, a, t)
129#  define	cfsetospeed(tp, val)	(tp)->c_cflag &= ~CBAUD; \
130					(tp)->c_cflag |= (val)
131#  define	cfgetospeed(tp)		((tp)->c_cflag & CBAUD)
132#  ifdef CIBAUD
133#   define	cfsetispeed(tp, val)	(tp)->c_cflag &= ~CIBAUD; \
134					(tp)->c_cflag |= ((val)<<IBSHIFT)
135#   define	cfgetispeed(tp)		(((tp)->c_cflag & CIBAUD)>>IBSHIFT)
136#  else
137#   define	cfsetispeed(tp, val)	(tp)->c_cflag &= ~CBAUD; \
138					(tp)->c_cflag |= (val)
139#   define	cfgetispeed(tp)		((tp)->c_cflag & CBAUD)
140#  endif
141# endif /* TCSANOW */
142struct termios termbuf, termbuf2;	/* pty control structure */
143#endif	/* USE_TERMIO */
144
145#include <sys/types.h>
146#include <libutil.h>
147
148int cleanopen(char *);
149void scrub_env(void);
150static char **addarg(char **, const char *);
151
152/*
153 * init_termbuf()
154 * copy_termbuf(cp)
155 * set_termbuf()
156 *
157 * These three routines are used to get and set the "termbuf" structure
158 * to and from the kernel.  init_termbuf() gets the current settings.
159 * copy_termbuf() hands in a new "termbuf" to write to the kernel, and
160 * set_termbuf() writes the structure into the kernel.
161 */
162
163void
164init_termbuf(void)
165{
166#ifndef	USE_TERMIO
167	(void) ioctl(pty, TIOCGETP, (char *)&termbuf.sg);
168	(void) ioctl(pty, TIOCGETC, (char *)&termbuf.tc);
169	(void) ioctl(pty, TIOCGLTC, (char *)&termbuf.ltc);
170# ifdef	TIOCGSTATE
171	(void) ioctl(pty, TIOCGSTATE, (char *)&termbuf.state);
172# endif
173#else
174	(void) tcgetattr(pty, &termbuf);
175#endif
176	termbuf2 = termbuf;
177}
178
179#if	defined(LINEMODE) && defined(TIOCPKT_IOCTL)
180void
181copy_termbuf(char *cp, size_t len)
182{
183	if (len > sizeof(termbuf))
184		len = sizeof(termbuf);
185	memmove((char *)&termbuf, cp, len);
186	termbuf2 = termbuf;
187}
188#endif	/* defined(LINEMODE) && defined(TIOCPKT_IOCTL) */
189
190void
191set_termbuf(void)
192{
193	/*
194	 * Only make the necessary changes.
195	 */
196#ifndef	USE_TERMIO
197	if (memcmp((char *)&termbuf.sg, (char *)&termbuf2.sg,
198							sizeof(termbuf.sg)))
199		(void) ioctl(pty, TIOCSETN, (char *)&termbuf.sg);
200	if (memcmp((char *)&termbuf.tc, (char *)&termbuf2.tc,
201							sizeof(termbuf.tc)))
202		(void) ioctl(pty, TIOCSETC, (char *)&termbuf.tc);
203	if (memcmp((char *)&termbuf.ltc, (char *)&termbuf2.ltc,
204							sizeof(termbuf.ltc)))
205		(void) ioctl(pty, TIOCSLTC, (char *)&termbuf.ltc);
206	if (termbuf.lflags != termbuf2.lflags)
207		(void) ioctl(pty, TIOCLSET, (char *)&termbuf.lflags);
208#else	/* USE_TERMIO */
209	if (memcmp((char *)&termbuf, (char *)&termbuf2, sizeof(termbuf)))
210		(void) tcsetattr(pty, TCSANOW, &termbuf);
211#endif	/* USE_TERMIO */
212}
213
214
215/*
216 * spcset(func, valp, valpp)
217 *
218 * This function takes various special characters (func), and
219 * sets *valp to the current value of that character, and
220 * *valpp to point to where in the "termbuf" structure that
221 * value is kept.
222 *
223 * It returns the SLC_ level of support for this function.
224 */
225
226#ifndef	USE_TERMIO
227int
228spcset(int func, cc_t *valp, cc_t **valpp)
229{
230	switch(func) {
231	case SLC_EOF:
232		*valp = termbuf.tc.t_eofc;
233		*valpp = (cc_t *)&termbuf.tc.t_eofc;
234		return(SLC_VARIABLE);
235	case SLC_EC:
236		*valp = termbuf.sg.sg_erase;
237		*valpp = (cc_t *)&termbuf.sg.sg_erase;
238		return(SLC_VARIABLE);
239	case SLC_EL:
240		*valp = termbuf.sg.sg_kill;
241		*valpp = (cc_t *)&termbuf.sg.sg_kill;
242		return(SLC_VARIABLE);
243	case SLC_IP:
244		*valp = termbuf.tc.t_intrc;
245		*valpp = (cc_t *)&termbuf.tc.t_intrc;
246		return(SLC_VARIABLE|SLC_FLUSHIN|SLC_FLUSHOUT);
247	case SLC_ABORT:
248		*valp = termbuf.tc.t_quitc;
249		*valpp = (cc_t *)&termbuf.tc.t_quitc;
250		return(SLC_VARIABLE|SLC_FLUSHIN|SLC_FLUSHOUT);
251	case SLC_XON:
252		*valp = termbuf.tc.t_startc;
253		*valpp = (cc_t *)&termbuf.tc.t_startc;
254		return(SLC_VARIABLE);
255	case SLC_XOFF:
256		*valp = termbuf.tc.t_stopc;
257		*valpp = (cc_t *)&termbuf.tc.t_stopc;
258		return(SLC_VARIABLE);
259	case SLC_AO:
260		*valp = termbuf.ltc.t_flushc;
261		*valpp = (cc_t *)&termbuf.ltc.t_flushc;
262		return(SLC_VARIABLE);
263	case SLC_SUSP:
264		*valp = termbuf.ltc.t_suspc;
265		*valpp = (cc_t *)&termbuf.ltc.t_suspc;
266		return(SLC_VARIABLE);
267	case SLC_EW:
268		*valp = termbuf.ltc.t_werasc;
269		*valpp = (cc_t *)&termbuf.ltc.t_werasc;
270		return(SLC_VARIABLE);
271	case SLC_RP:
272		*valp = termbuf.ltc.t_rprntc;
273		*valpp = (cc_t *)&termbuf.ltc.t_rprntc;
274		return(SLC_VARIABLE);
275	case SLC_LNEXT:
276		*valp = termbuf.ltc.t_lnextc;
277		*valpp = (cc_t *)&termbuf.ltc.t_lnextc;
278		return(SLC_VARIABLE);
279	case SLC_FORW1:
280		*valp = termbuf.tc.t_brkc;
281		*valpp = (cc_t *)&termbuf.ltc.t_lnextc;
282		return(SLC_VARIABLE);
283	case SLC_BRK:
284	case SLC_SYNCH:
285	case SLC_AYT:
286	case SLC_EOR:
287		*valp = (cc_t)0;
288		*valpp = (cc_t *)0;
289		return(SLC_DEFAULT);
290	default:
291		*valp = (cc_t)0;
292		*valpp = (cc_t *)0;
293		return(SLC_NOSUPPORT);
294	}
295}
296
297#else	/* USE_TERMIO */
298
299
300#define	setval(a, b)	*valp = termbuf.c_cc[a]; \
301			*valpp = &termbuf.c_cc[a]; \
302			return(b);
303#define	defval(a) *valp = ((cc_t)a); *valpp = (cc_t *)0; return(SLC_DEFAULT);
304
305int
306spcset(int func, cc_t *valp, cc_t **valpp)
307{
308	switch(func) {
309	case SLC_EOF:
310		setval(VEOF, SLC_VARIABLE);
311	case SLC_EC:
312		setval(VERASE, SLC_VARIABLE);
313	case SLC_EL:
314		setval(VKILL, SLC_VARIABLE);
315	case SLC_IP:
316		setval(VINTR, SLC_VARIABLE|SLC_FLUSHIN|SLC_FLUSHOUT);
317	case SLC_ABORT:
318		setval(VQUIT, SLC_VARIABLE|SLC_FLUSHIN|SLC_FLUSHOUT);
319	case SLC_XON:
320#ifdef	VSTART
321		setval(VSTART, SLC_VARIABLE);
322#else
323		defval(0x13);
324#endif
325	case SLC_XOFF:
326#ifdef	VSTOP
327		setval(VSTOP, SLC_VARIABLE);
328#else
329		defval(0x11);
330#endif
331	case SLC_EW:
332#ifdef	VWERASE
333		setval(VWERASE, SLC_VARIABLE);
334#else
335		defval(0);
336#endif
337	case SLC_RP:
338#ifdef	VREPRINT
339		setval(VREPRINT, SLC_VARIABLE);
340#else
341		defval(0);
342#endif
343	case SLC_LNEXT:
344#ifdef	VLNEXT
345		setval(VLNEXT, SLC_VARIABLE);
346#else
347		defval(0);
348#endif
349	case SLC_AO:
350#if	!defined(VDISCARD) && defined(VFLUSHO)
351# define VDISCARD VFLUSHO
352#endif
353#ifdef	VDISCARD
354		setval(VDISCARD, SLC_VARIABLE|SLC_FLUSHOUT);
355#else
356		defval(0);
357#endif
358	case SLC_SUSP:
359#ifdef	VSUSP
360		setval(VSUSP, SLC_VARIABLE|SLC_FLUSHIN);
361#else
362		defval(0);
363#endif
364#ifdef	VEOL
365	case SLC_FORW1:
366		setval(VEOL, SLC_VARIABLE);
367#endif
368#ifdef	VEOL2
369	case SLC_FORW2:
370		setval(VEOL2, SLC_VARIABLE);
371#endif
372	case SLC_AYT:
373#ifdef	VSTATUS
374		setval(VSTATUS, SLC_VARIABLE);
375#else
376		defval(0);
377#endif
378
379	case SLC_BRK:
380	case SLC_SYNCH:
381	case SLC_EOR:
382		defval(0);
383
384	default:
385		*valp = 0;
386		*valpp = 0;
387		return(SLC_NOSUPPORT);
388	}
389}
390#endif	/* USE_TERMIO */
391
392/*
393 * getpty()
394 *
395 * Allocate a pty.  As a side effect, the external character
396 * array "line" contains the name of the slave side.
397 *
398 * Returns the file descriptor of the opened pty.
399 */
400char alpha[] = "0123456789abcdefghijklmnopqrstuv";
401
402int
403getpty(int *ptynum __unused)
404{
405	int p;
406	const char *cp;
407	char *p1, *p2;
408	int i;
409
410#if (defined(__BEOS__) || defined(__HAIKU__))
411	(void) strcpy(line, "/dev/pt/XX");
412#else
413	(void) strcpy(line, _PATH_DEV);
414	(void) strcat(line, "ptyXX");
415#endif
416	p1 = &line[8];
417	p2 = &line[9];
418
419	for (cp = "pqrsPQRS"; *cp; cp++) {
420		struct stat stb;
421
422		*p1 = *cp;
423		*p2 = '0';
424		/*
425		 * This stat() check is just to keep us from
426		 * looping through all 256 combinations if there
427		 * aren't that many ptys available.
428		 */
429		if (stat(line, &stb) < 0)
430			break;
431		for (i = 0; i < 32; i++) {
432			*p2 = alpha[i];
433			p = open(line, 2);
434			if (p > 0) {
435				line[5] = 't';
436				chown(line, 0, 0);
437				chmod(line, 0600);
438					return(p);
439			}
440		}
441	}
442	return(-1);
443}
444
445#ifdef	LINEMODE
446/*
447 * tty_flowmode()	Find out if flow control is enabled or disabled.
448 * tty_linemode()	Find out if linemode (external processing) is enabled.
449 * tty_setlinemod(on)	Turn on/off linemode.
450 * tty_isecho()		Find out if echoing is turned on.
451 * tty_setecho(on)	Enable/disable character echoing.
452 * tty_israw()		Find out if terminal is in RAW mode.
453 * tty_binaryin(on)	Turn on/off BINARY on input.
454 * tty_binaryout(on)	Turn on/off BINARY on output.
455 * tty_isediting()	Find out if line editing is enabled.
456 * tty_istrapsig()	Find out if signal trapping is enabled.
457 * tty_setedit(on)	Turn on/off line editing.
458 * tty_setsig(on)	Turn on/off signal trapping.
459 * tty_issofttab()	Find out if tab expansion is enabled.
460 * tty_setsofttab(on)	Turn on/off soft tab expansion.
461 * tty_islitecho()	Find out if typed control chars are echoed literally
462 * tty_setlitecho()	Turn on/off literal echo of control chars
463 * tty_tspeed(val)	Set transmit speed to val.
464 * tty_rspeed(val)	Set receive speed to val.
465 */
466
467
468int
469tty_linemode(void)
470{
471#ifndef	USE_TERMIO
472	return(termbuf.state & TS_EXTPROC);
473#else
474	return(termbuf.c_lflag & EXTPROC);
475#endif
476}
477
478void
479tty_setlinemode(int on)
480{
481#ifdef	TIOCEXT
482	set_termbuf();
483	(void) ioctl(pty, TIOCEXT, (char *)&on);
484	init_termbuf();
485#else	/* !TIOCEXT */
486# ifdef	EXTPROC
487	if (on)
488		termbuf.c_lflag |= EXTPROC;
489	else
490		termbuf.c_lflag &= ~EXTPROC;
491# endif
492#endif	/* TIOCEXT */
493}
494#endif	/* LINEMODE */
495
496int
497tty_isecho(void)
498{
499#ifndef USE_TERMIO
500	return (termbuf.sg.sg_flags & ECHO);
501#else
502	return (termbuf.c_lflag & ECHO);
503#endif
504}
505
506int
507tty_flowmode(void)
508{
509#ifndef USE_TERMIO
510	return(((termbuf.tc.t_startc) > 0 && (termbuf.tc.t_stopc) > 0) ? 1 : 0);
511#else
512	return((termbuf.c_iflag & IXON) ? 1 : 0);
513#endif
514}
515
516int
517tty_restartany(void)
518{
519#ifndef USE_TERMIO
520# ifdef	DECCTQ
521	return((termbuf.lflags & DECCTQ) ? 0 : 1);
522# else
523	return(-1);
524# endif
525#else
526	return((termbuf.c_iflag & IXANY) ? 1 : 0);
527#endif
528}
529
530void
531tty_setecho(int on)
532{
533#ifndef	USE_TERMIO
534	if (on)
535		termbuf.sg.sg_flags |= ECHO|CRMOD;
536	else
537		termbuf.sg.sg_flags &= ~(ECHO|CRMOD);
538#else
539	if (on)
540		termbuf.c_lflag |= ECHO;
541	else
542		termbuf.c_lflag &= ~ECHO;
543#endif
544}
545
546int
547tty_israw(void)
548{
549#ifndef USE_TERMIO
550	return(termbuf.sg.sg_flags & RAW);
551#else
552	return(!(termbuf.c_lflag & ICANON));
553#endif
554}
555
556#ifdef	AUTHENTICATION
557#if	defined(NO_LOGIN_F) && defined(LOGIN_R)
558int
559tty_setraw(int on)
560{
561#  ifndef USE_TERMIO
562	if (on)
563		termbuf.sg.sg_flags |= RAW;
564	else
565		termbuf.sg.sg_flags &= ~RAW;
566#  else
567	if (on)
568		termbuf.c_lflag &= ~ICANON;
569	else
570		termbuf.c_lflag |= ICANON;
571#  endif
572}
573#endif
574#endif /* AUTHENTICATION */
575
576void
577tty_binaryin(int on)
578{
579#ifndef	USE_TERMIO
580	if (on)
581		termbuf.lflags |= LPASS8;
582	else
583		termbuf.lflags &= ~LPASS8;
584#else
585	if (on) {
586		termbuf.c_iflag &= ~ISTRIP;
587	} else {
588		termbuf.c_iflag |= ISTRIP;
589	}
590#endif
591}
592
593void
594tty_binaryout(int on)
595{
596#ifndef	USE_TERMIO
597	if (on)
598		termbuf.lflags |= LLITOUT;
599	else
600		termbuf.lflags &= ~LLITOUT;
601#else
602	if (on) {
603		termbuf.c_cflag &= ~(CSIZE|PARENB);
604		termbuf.c_cflag |= CS8;
605		termbuf.c_oflag &= ~OPOST;
606	} else {
607		termbuf.c_cflag &= ~CSIZE;
608		termbuf.c_cflag |= CS7|PARENB;
609		termbuf.c_oflag |= OPOST;
610	}
611#endif
612}
613
614int
615tty_isbinaryin(void)
616{
617#ifndef	USE_TERMIO
618	return(termbuf.lflags & LPASS8);
619#else
620	return(!(termbuf.c_iflag & ISTRIP));
621#endif
622}
623
624int
625tty_isbinaryout(void)
626{
627#ifndef	USE_TERMIO
628	return(termbuf.lflags & LLITOUT);
629#else
630	return(!(termbuf.c_oflag&OPOST));
631#endif
632}
633
634#ifdef	LINEMODE
635int
636tty_isediting(void)
637{
638#ifndef USE_TERMIO
639	return(!(termbuf.sg.sg_flags & (CBREAK|RAW)));
640#else
641	return(termbuf.c_lflag & ICANON);
642#endif
643}
644
645int
646tty_istrapsig(void)
647{
648#ifndef USE_TERMIO
649	return(!(termbuf.sg.sg_flags&RAW));
650#else
651	return(termbuf.c_lflag & ISIG);
652#endif
653}
654
655void
656tty_setedit(int on)
657{
658#ifndef USE_TERMIO
659	if (on)
660		termbuf.sg.sg_flags &= ~CBREAK;
661	else
662		termbuf.sg.sg_flags |= CBREAK;
663#else
664	if (on)
665		termbuf.c_lflag |= ICANON;
666	else
667		termbuf.c_lflag &= ~ICANON;
668#endif
669}
670
671void
672tty_setsig(int on)
673{
674#ifndef	USE_TERMIO
675	if (on)
676		;
677#else
678	if (on)
679		termbuf.c_lflag |= ISIG;
680	else
681		termbuf.c_lflag &= ~ISIG;
682#endif
683}
684#endif	/* LINEMODE */
685
686int
687tty_issofttab(void)
688{
689#ifndef	USE_TERMIO
690	return (termbuf.sg.sg_flags & XTABS);
691#else
692# ifdef	OXTABS
693	return (termbuf.c_oflag & OXTABS);
694# endif
695# ifdef	TABDLY
696	return ((termbuf.c_oflag & TABDLY) == TAB3);
697# endif
698#endif
699}
700
701void
702tty_setsofttab(int on)
703{
704#ifndef	USE_TERMIO
705	if (on)
706		termbuf.sg.sg_flags |= XTABS;
707	else
708		termbuf.sg.sg_flags &= ~XTABS;
709#else
710	if (on) {
711# ifdef	OXTABS
712		termbuf.c_oflag |= OXTABS;
713# endif
714# ifdef	TABDLY
715		termbuf.c_oflag &= ~TABDLY;
716		termbuf.c_oflag |= TAB3;
717# endif
718	} else {
719# ifdef	OXTABS
720		termbuf.c_oflag &= ~OXTABS;
721# endif
722# ifdef	TABDLY
723		termbuf.c_oflag &= ~TABDLY;
724		termbuf.c_oflag |= TAB0;
725# endif
726	}
727#endif
728}
729
730int
731tty_islitecho(void)
732{
733#ifndef	USE_TERMIO
734	return (!(termbuf.lflags & LCTLECH));
735#else
736# ifdef	ECHOCTL
737	return (!(termbuf.c_lflag & ECHOCTL));
738# endif
739# ifdef	TCTLECH
740	return (!(termbuf.c_lflag & TCTLECH));
741# endif
742# if	!defined(ECHOCTL) && !defined(TCTLECH)
743	return (0);	/* assumes ctl chars are echoed '^x' */
744# endif
745#endif
746}
747
748void
749tty_setlitecho(int on)
750{
751#ifndef	USE_TERMIO
752	if (on)
753		termbuf.lflags &= ~LCTLECH;
754	else
755		termbuf.lflags |= LCTLECH;
756#else
757# ifdef	ECHOCTL
758	if (on)
759		termbuf.c_lflag &= ~ECHOCTL;
760	else
761		termbuf.c_lflag |= ECHOCTL;
762# endif
763# ifdef	TCTLECH
764	if (on)
765		termbuf.c_lflag &= ~TCTLECH;
766	else
767		termbuf.c_lflag |= TCTLECH;
768# endif
769#endif
770}
771
772int
773tty_iscrnl(void)
774{
775#ifndef	USE_TERMIO
776	return (termbuf.sg.sg_flags & CRMOD);
777#else
778	return (termbuf.c_iflag & ICRNL);
779#endif
780}
781
782/*
783 * Try to guess whether speeds are "encoded" (4.2BSD) or just numeric (4.4BSD).
784 */
785#if B4800 != 4800
786#define	DECODE_BAUD
787#endif
788
789#ifdef	DECODE_BAUD
790
791/*
792 * A table of available terminal speeds
793 */
794struct termspeeds {
795	int	speed;
796	int	value;
797} termspeeds[] = {
798	{ 0,      B0 },      { 50,    B50 },    { 75,     B75 },
799	{ 110,    B110 },    { 134,   B134 },   { 150,    B150 },
800	{ 200,    B200 },    { 300,   B300 },   { 600,    B600 },
801	{ 1200,   B1200 },   { 1800,  B1800 },  { 2400,   B2400 },
802	{ 4800,   B4800 },
803#ifdef	B7200
804	{ 7200,  B7200 },
805#endif
806	{ 9600,   B9600 },
807#ifdef	B14400
808	{ 14400,  B14400 },
809#endif
810#ifdef	B19200
811	{ 19200,  B19200 },
812#endif
813#ifdef	B28800
814	{ 28800,  B28800 },
815#endif
816#ifdef	B38400
817	{ 38400,  B38400 },
818#endif
819#ifdef	B57600
820	{ 57600,  B57600 },
821#endif
822#ifdef	B115200
823	{ 115200, B115200 },
824#endif
825#ifdef	B230400
826	{ 230400, B230400 },
827#endif
828	{ -1,     0 }
829};
830#endif	/* DECODE_BAUD */
831
832void
833tty_tspeed(int val)
834{
835#ifdef	DECODE_BAUD
836	struct termspeeds *tp;
837
838	for (tp = termspeeds; (tp->speed != -1) && (val > tp->speed); tp++)
839		;
840	if (tp->speed == -1)	/* back up to last valid value */
841		--tp;
842	cfsetospeed(&termbuf, tp->value);
843#else	/* DECODE_BAUD */
844	cfsetospeed(&termbuf, val);
845#endif	/* DECODE_BAUD */
846}
847
848void
849tty_rspeed(int val)
850{
851#ifdef	DECODE_BAUD
852	struct termspeeds *tp;
853
854	for (tp = termspeeds; (tp->speed != -1) && (val > tp->speed); tp++)
855		;
856	if (tp->speed == -1)	/* back up to last valid value */
857		--tp;
858	cfsetispeed(&termbuf, tp->value);
859#else	/* DECODE_BAUD */
860	cfsetispeed(&termbuf, val);
861#endif	/* DECODE_BAUD */
862}
863
864/*
865 * getptyslave()
866 *
867 * Open the slave side of the pty, and do any initialization
868 * that is necessary.
869 */
870static void
871getptyslave(void)
872{
873	int t = -1;
874	char erase;
875
876# ifdef	LINEMODE
877	int waslm;
878# endif
879# ifdef	TIOCGWINSZ
880	struct winsize ws;
881	extern int def_row, def_col;
882# endif
883	extern int def_tspeed, def_rspeed;
884	/*
885	 * Opening the slave side may cause initilization of the
886	 * kernel tty structure.  We need remember the state of
887	 * 	if linemode was turned on
888	 *	terminal window size
889	 *	terminal speed
890	 *	erase character
891	 * so that we can re-set them if we need to.
892	 */
893# ifdef	LINEMODE
894	waslm = tty_linemode();
895# endif
896	erase = termbuf.c_cc[VERASE];
897
898	/*
899	 * Make sure that we don't have a controlling tty, and
900	 * that we are the session (process group) leader.
901	 */
902# ifdef	TIOCNOTTY
903	t = open(_PATH_TTY, O_RDWR);
904	if (t >= 0) {
905		(void) ioctl(t, TIOCNOTTY, (char *)0);
906		(void) close(t);
907	}
908# endif
909
910	t = cleanopen(line);
911	if (t < 0)
912		fatalperror(net, line);
913
914
915	/*
916	 * set up the tty modes as we like them to be.
917	 */
918	init_termbuf();
919# ifdef	TIOCGWINSZ
920	if (def_row || def_col) {
921		memset((char *)&ws, 0, sizeof(ws));
922		ws.ws_col = def_col;
923		ws.ws_row = def_row;
924		(void)ioctl(t, TIOCSWINSZ, (char *)&ws);
925	}
926# endif
927
928	/*
929	 * Settings for sgtty based systems
930	 */
931# ifndef	USE_TERMIO
932	termbuf.sg.sg_flags |= CRMOD|ANYP|ECHO|XTABS;
933# endif	/* USE_TERMIO */
934
935	/*
936	 * Settings for all other termios/termio based
937	 * systems, other than 4.4BSD.  In 4.4BSD the
938	 * kernel does the initial terminal setup.
939	 */
940	tty_rspeed((def_rspeed > 0) ? def_rspeed : 9600);
941	tty_tspeed((def_tspeed > 0) ? def_tspeed : 9600);
942	if (erase)
943		termbuf.c_cc[VERASE] = erase;
944# ifdef	LINEMODE
945	if (waslm)
946		tty_setlinemode(1);
947# endif	/* LINEMODE */
948
949	/*
950	 * Set the tty modes, and make this our controlling tty.
951	 */
952	set_termbuf();
953	if (login_tty(t) == -1)
954		fatalperror(net, "login_tty");
955	if (net > 2)
956		(void) close(net);
957#ifdef	AUTHENTICATION
958#if	defined(NO_LOGIN_F) && defined(LOGIN_R)
959	/*
960	 * Leave the pty open so that we can write out the rlogin
961	 * protocol for /bin/login, if the authentication works.
962	 */
963#else
964	if (pty > 2) {
965		(void) close(pty);
966		pty = -1;
967	}
968#endif
969#endif /* AUTHENTICATION */
970}
971
972#ifndef	O_NOCTTY
973#define	O_NOCTTY	0
974#endif
975/*
976 * Open the specified slave side of the pty,
977 * making sure that we have a clean tty.
978 */
979int
980cleanopen(char *li)
981{
982	int t;
983
984	/*
985	 * Make sure that other people can't open the
986	 * slave side of the connection.
987	 */
988	(void) chown(li, 0, 0);
989	(void) chmod(li, 0600);
990
991#if (!defined(__BEOS__) && !defined(__HAIKU__))
992	(void) revoke(li);
993#endif
994
995	t = open(line, O_RDWR|O_NOCTTY);
996
997	if (t < 0)
998		return(-1);
999
1000	return(t);
1001}
1002
1003
1004#if (defined(__BEOS__) || defined(__HAIKU__))
1005/* taken from DragonFly's telnetd */
1006int
1007login_tty(int t)
1008{
1009	if (setsid() < 0) {
1010		fatalperror(net, "setsid()");
1011	}
1012
1013	/*
1014	 * We get our controlling tty assigned as a side-effect
1015	 * of opening up a tty device.  But on BSD based systems,
1016	 * this only happens if our process group is zero.  The
1017	 * setsid() call above may have set our pgrp, so clear
1018	 * it out before opening the tty...
1019	 */
1020	setpgid(0, 0);
1021	close(open(line, O_RDWR));
1022
1023	setenv("TTY", line, 1);
1024
1025	if (t != 0)
1026		(void) dup2(t, 0);
1027	if (t != 1)
1028		(void) dup2(t, 1);
1029	if (t != 2)
1030		(void) dup2(t, 2);
1031	if (t > 2)
1032		close(t);
1033	return(0);
1034}
1035#endif	/* __BEOS__ */
1036
1037/*
1038 * startslave(host)
1039 *
1040 * Given a hostname, do whatever
1041 * is necessary to startup the login process on the slave side of the pty.
1042 */
1043
1044/* ARGSUSED */
1045void
1046startslave(char *host, int autologin, char *autoname)
1047{
1048	int i;
1049
1050#ifdef	AUTHENTICATION
1051	if (!autoname || !autoname[0])
1052		autologin = 0;
1053
1054	if (autologin < auth_level) {
1055		fatal(net, "Authorization failed");
1056		exit(1);
1057	}
1058#endif
1059
1060
1061	if ((i = fork()) < 0)
1062		fatalperror(net, "fork");
1063	if (i) {
1064	} else {
1065		getptyslave();
1066		start_login(host, autologin, autoname);
1067		/*NOTREACHED*/
1068	}
1069}
1070
1071void
1072init_env(void)
1073{
1074	char **envp;
1075
1076	envp = envinit;
1077	if ((*envp = getenv("TZ")))
1078		*envp++ -= 3;
1079	*envp = 0;
1080	environ = envinit;
1081}
1082
1083
1084/*
1085 * start_login(host)
1086 *
1087 * Assuming that we are now running as a child processes, this
1088 * function will turn us into the login process.
1089 */
1090
1091#ifndef AUTHENTICATION
1092#define undef1 __unused
1093#else
1094#define undef1
1095#endif
1096
1097void
1098start_login(char *host undef1, int autologin undef1, char *name undef1)
1099{
1100	char **argv;
1101
1102	scrub_env();
1103
1104	/*
1105	 * -h : pass on name of host.
1106	 *		WARNING:  -h is accepted by login if and only if
1107	 *			getuid() == 0.
1108	 * -p : don't clobber the environment (so terminal type stays set).
1109	 *
1110	 * -f : force this login, he has already been authenticated
1111	 */
1112	argv = addarg(0, "login");
1113
1114#if	!defined(NO_LOGIN_H)
1115#ifdef	AUTHENTICATION
1116# if	defined(NO_LOGIN_F) && defined(LOGIN_R)
1117	/*
1118	 * Don't add the "-h host" option if we are going
1119	 * to be adding the "-r host" option down below...
1120	 */
1121	if ((auth_level < 0) || (autologin != AUTH_VALID))
1122# endif
1123	{
1124		argv = addarg(argv, "-h");
1125		argv = addarg(argv, host);
1126	}
1127#endif /* AUTHENTICATION */
1128#endif
1129#if	!defined(NO_LOGIN_P)
1130	argv = addarg(argv, "-p");
1131#endif
1132#ifdef	LINEMODE
1133	/*
1134	 * Set the environment variable "LINEMODE" to either
1135	 * "real" or "kludge" if we are operating in either
1136	 * real or kludge linemode.
1137	 */
1138	if (lmodetype == REAL_LINEMODE)
1139		setenv("LINEMODE", "real", 1);
1140# ifdef KLUDGELINEMODE
1141	else if (lmodetype == KLUDGE_LINEMODE || lmodetype == KLUDGE_OK)
1142		setenv("LINEMODE", "kludge", 1);
1143# endif
1144#endif
1145#ifdef	BFTPDAEMON
1146	/*
1147	 * Are we working as the bftp daemon?  If so, then ask login
1148	 * to start bftp instead of shell.
1149	 */
1150	if (bftpd) {
1151		argv = addarg(argv, "-e");
1152		argv = addarg(argv, BFTPPATH);
1153	} else
1154#endif
1155#ifdef	AUTHENTICATION
1156	if (auth_level >= 0 && autologin == AUTH_VALID) {
1157# if	!defined(NO_LOGIN_F)
1158		argv = addarg(argv, "-f");
1159		argv = addarg(argv, "--");
1160		argv = addarg(argv, name);
1161# else
1162#  if defined(LOGIN_R)
1163		/*
1164		 * We don't have support for "login -f", but we
1165		 * can fool /bin/login into thinking that we are
1166		 * rlogind, and allow us to log in without a
1167		 * password.  The rlogin protocol expects
1168		 *	local-user\0remote-user\0term/speed\0
1169		 */
1170
1171		if (pty > 2) {
1172			char *cp;
1173			char speed[128];
1174			int isecho, israw, xpty, len;
1175			extern int def_rspeed;
1176#  ifndef LOGIN_HOST
1177			/*
1178			 * Tell login that we are coming from "localhost".
1179			 * If we passed in the real host name, then the
1180			 * user would have to allow .rhost access from
1181			 * every machine that they want authenticated
1182			 * access to work from, which sort of defeats
1183			 * the purpose of an authenticated login...
1184			 * So, we tell login that the session is coming
1185			 * from "localhost", and the user will only have
1186			 * to have "localhost" in their .rhost file.
1187			 */
1188#			define LOGIN_HOST "localhost"
1189#  endif
1190			argv = addarg(argv, "-r");
1191			argv = addarg(argv, LOGIN_HOST);
1192
1193			xpty = pty;
1194			pty = 0;
1195			init_termbuf();
1196			isecho = tty_isecho();
1197			israw = tty_israw();
1198			if (isecho || !israw) {
1199				tty_setecho(0);		/* Turn off echo */
1200				tty_setraw(1);		/* Turn on raw */
1201				set_termbuf();
1202			}
1203			len = strlen(name)+1;
1204			write(xpty, name, len);
1205			write(xpty, name, len);
1206			snprintf(speed, sizeof(speed),
1207				"%s/%d", (cp = getenv("TERM")) ? cp : "",
1208				(def_rspeed > 0) ? def_rspeed : 9600);
1209			len = strlen(speed)+1;
1210			write(xpty, speed, len);
1211
1212			if (isecho || !israw) {
1213				init_termbuf();
1214				tty_setecho(isecho);
1215				tty_setraw(israw);
1216				set_termbuf();
1217				if (!israw) {
1218					/*
1219					 * Write a newline to ensure
1220					 * that login will be able to
1221					 * read the line...
1222					 */
1223					write(xpty, "\n", 1);
1224				}
1225			}
1226			pty = xpty;
1227		}
1228#  else
1229		argv = addarg(argv, "--");
1230		argv = addarg(argv, name);
1231#  endif
1232# endif
1233	} else
1234#endif
1235	if (getenv("USER")) {
1236 		argv = addarg(argv, "--");
1237		argv = addarg(argv, getenv("USER"));
1238#if	defined(LOGIN_ARGS) && defined(NO_LOGIN_P)
1239		{
1240			char **cpp;
1241			for (cpp = environ; *cpp; cpp++)
1242				argv = addarg(argv, *cpp);
1243		}
1244#endif
1245		/*
1246		 * Assume that login will set the USER variable
1247		 * correctly.  For SysV systems, this means that
1248		 * USER will no longer be set, just LOGNAME by
1249		 * login.  (The problem is that if the auto-login
1250		 * fails, and the user then specifies a different
1251		 * account name, he can get logged in with both
1252		 * LOGNAME and USER in his environment, but the
1253		 * USER value will be wrong.
1254		 */
1255		unsetenv("USER");
1256	}
1257#ifdef	AUTHENTICATION
1258#if	defined(NO_LOGIN_F) && defined(LOGIN_R)
1259	if (pty > 2)
1260		close(pty);
1261#endif
1262#endif /* AUTHENTICATION */
1263	closelog();
1264
1265	if (altlogin == NULL) {
1266		altlogin = _PATH_LOGIN;
1267	}
1268	execv(altlogin, argv);
1269
1270	syslog(LOG_ERR, "%s: %m", altlogin);
1271	fatalperror(net, altlogin);
1272	/*NOTREACHED*/
1273}
1274
1275static char **
1276addarg(char **argv, const char *val)
1277{
1278	char **cpp;
1279
1280	if (argv == NULL) {
1281		/*
1282		 * 10 entries, a leading length, and a null
1283		 */
1284		argv = (char **)malloc(sizeof(*argv) * 12);
1285		if (argv == NULL)
1286			return(NULL);
1287		*argv++ = (char *)10;
1288		*argv = (char *)0;
1289	}
1290	for (cpp = argv; *cpp; cpp++)
1291		;
1292	if (cpp == &argv[(long)argv[-1]]) {
1293		--argv;
1294		*argv = (char *)((long)(*argv) + 10);
1295		argv = (char **)realloc(argv, sizeof(*argv)*((long)(*argv) + 2));
1296		if (argv == NULL)
1297			return(NULL);
1298		argv++;
1299		cpp = &argv[(long)argv[-1] - 10];
1300	}
1301	*cpp++ = strdup(val);
1302	*cpp = 0;
1303	return(argv);
1304}
1305
1306/*
1307 * scrub_env()
1308 *
1309 * We only accept the environment variables listed below.
1310 */
1311void
1312scrub_env(void)
1313{
1314	static const char *rej[] = {
1315		"TERMCAP=/",
1316		NULL
1317	};
1318
1319	static const char *acc[] = {
1320		"XAUTH=", "XAUTHORITY=", "DISPLAY=",
1321		"TERM=",
1322		"EDITOR=",
1323		"PAGER=",
1324		"LOGNAME=",
1325		"POSIXLY_CORRECT=",
1326		"PRINTER=",
1327		NULL
1328	};
1329
1330	char **cpp, **cpp2;
1331	const char **p;
1332
1333 	for (cpp2 = cpp = environ; *cpp; cpp++) {
1334		int reject_it = 0;
1335
1336		for(p = rej; *p; p++)
1337			if(strncmp(*cpp, *p, strlen(*p)) == 0) {
1338				reject_it = 1;
1339				break;
1340			}
1341		if (reject_it)
1342			continue;
1343
1344		for(p = acc; *p; p++)
1345			if(strncmp(*cpp, *p, strlen(*p)) == 0)
1346				break;
1347		if(*p != NULL)
1348 			*cpp2++ = *cpp;
1349 	}
1350	*cpp2 = NULL;
1351}
1352
1353/*
1354 * cleanup()
1355 *
1356 * This is the routine to call when we are all through, to
1357 * clean up anything that needs to be cleaned up.
1358 */
1359/* ARGSUSED */
1360void
1361cleanup(int sig __unused)
1362{
1363	char *p;
1364	sigset_t mask;
1365
1366	p = line + sizeof(_PATH_DEV) - 1;
1367	/*
1368	 * Block all signals before clearing the utmp entry.  We don't want to
1369	 * be called again after calling logout() and then not add the wtmp
1370	 * entry because of not finding the corresponding entry in utmp.
1371	 */
1372	sigfillset(&mask);
1373	sigprocmask(SIG_SETMASK, &mask, NULL);
1374#if (!defined(__BEOS__) && !defined(__HAIKU__))
1375	if (logout(p))
1376		logwtmp(p, "", "");
1377	(void)chmod(line, 0666);
1378	(void)chown(line, 0, 0);
1379	*p = 'p';
1380	(void)chmod(line, 0666);
1381	(void)chown(line, 0, 0);
1382#endif
1383	(void) shutdown(net, 2);
1384	_exit(1);
1385}
1386