Home | History | Annotate | Line # | Download | only in telnetd
telnetd.c revision 1.23
      1 /*	$NetBSD: telnetd.c,v 1.23 2000/11/19 20:17:39 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 1997 and 1998 WIDE Project.
      5  * 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. Neither the name of the project nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1989, 1993
     34  *	The Regents of the University of California.  All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. All advertising materials mentioning features or use of this software
     45  *    must display the following acknowledgement:
     46  *	This product includes software developed by the University of
     47  *	California, Berkeley and its contributors.
     48  * 4. Neither the name of the University nor the names of its contributors
     49  *    may be used to endorse or promote products derived from this software
     50  *    without specific prior written permission.
     51  *
     52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     62  * SUCH DAMAGE.
     63  */
     64 
     65 #include <sys/cdefs.h>
     66 #ifndef lint
     67 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\n\
     68 	The Regents of the University of California.  All rights reserved.\n");
     69 #if 0
     70 static char sccsid[] = "@(#)telnetd.c	8.4 (Berkeley) 5/30/95";
     71 #else
     72 __RCSID("$NetBSD: telnetd.c,v 1.23 2000/11/19 20:17:39 christos Exp $");
     73 #endif
     74 #endif /* not lint */
     75 
     76 #include "telnetd.h"
     77 #include "pathnames.h"
     78 
     79 #include <arpa/inet.h>
     80 
     81 #include <err.h>
     82 #include <termcap.h>
     83 
     84 #include <limits.h>
     85 
     86 #define P __P
     87 
     88 #if	defined(_SC_CRAY_SECURE_SYS) && !defined(SCM_SECURITY)
     89 /*
     90  * UNICOS 6.0/6.1 do not have SCM_SECURITY defined, so we can
     91  * use it to tell us to turn off all the socket security code,
     92  * since that is only used in UNICOS 7.0 and later.
     93  */
     94 # undef _SC_CRAY_SECURE_SYS
     95 #endif
     96 
     97 #if	defined(_SC_CRAY_SECURE_SYS)
     98 #include <sys/sysv.h>
     99 #include <sys/secdev.h>
    100 # ifdef SO_SEC_MULTI		/* 8.0 code */
    101 #include <sys/secparm.h>
    102 #include <sys/usrv.h>
    103 # endif /* SO_SEC_MULTI */
    104 int	secflag;
    105 char	tty_dev[16];
    106 struct	secdev dv;
    107 struct	sysv sysv;
    108 # ifdef SO_SEC_MULTI		/* 8.0 code */
    109 struct	socksec ss;
    110 # else /* SO_SEC_MULTI */	/* 7.0 code */
    111 struct	socket_security ss;
    112 # endif /* SO_SEC_MULTI */
    113 #endif	/* _SC_CRAY_SECURE_SYS */
    114 
    115 #if	defined(KRB5)
    116 #define	Authenticator	k5_Authenticator
    117 #include <krb5.h>
    118 #undef	Authenticator
    119 #include <com_err.h>
    120 #endif
    121 
    122 #if	defined(AUTHENTICATION)
    123 #include <libtelnet/auth.h>
    124 int	auth_level = 0;
    125 #endif
    126 
    127 #if defined(ENCRYPTION)
    128 #include <libtelnet/encrypt.h>
    129 #endif
    130 
    131 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
    132 #include <libtelnet/misc.h>
    133 #endif
    134 
    135 #if	defined(SECURELOGIN)
    136 int	require_secure_login = 0;
    137 #endif
    138 
    139 extern	int utmp_len;
    140 int	registerd_host_only = 0;
    141 
    142 #ifdef	STREAMSPTY
    143 # include <stropts.h>
    144 # include <termio.h>
    145 /* make sure we don't get the bsd version */
    146 # include "/usr/include/sys/tty.h"
    147 # include <sys/ptyvar.h>
    148 
    149 /*
    150  * Because of the way ptyibuf is used with streams messages, we need
    151  * ptyibuf+1 to be on a full-word boundary.  The following wierdness
    152  * is simply to make that happen.
    153  */
    154 long	ptyibufbuf[BUFSIZ/sizeof(long)+1];
    155 char	*ptyibuf = ((char *)&ptyibufbuf[1])-1;
    156 char	*ptyip = ((char *)&ptyibufbuf[1])-1;
    157 char	ptyibuf2[BUFSIZ*4];
    158 unsigned char ctlbuf[BUFSIZ];
    159 struct	strbuf strbufc, strbufd;
    160 
    161 int readstream();
    162 
    163 #else	/* ! STREAMPTY */
    164 
    165 /*
    166  * I/O data buffers,
    167  * pointers, and counters.
    168  */
    169 char	ptyibuf[BUFSIZ], *ptyip = ptyibuf;
    170 char	ptyibuf2[BUFSIZ];
    171 
    172 #endif /* ! STREAMPTY */
    173 
    174 int	hostinfo = 1;			/* do we print login banner? */
    175 
    176 #ifdef	CRAY
    177 extern int      newmap; /* nonzero if \n maps to ^M^J */
    178 int	lowpty = 0, highpty;	/* low, high pty numbers */
    179 #endif /* CRAY */
    180 
    181 int debug = 0;
    182 int keepalive = 1;
    183 char *gettyname = "default";
    184 char *progname;
    185 
    186 extern void usage P((void));
    187 int main __P((int, char *[]));
    188 void usage __P((void));
    189 int getterminaltype __P((char *));
    190 int getent __P((char *, char *));
    191 void doit __P((struct sockaddr *));
    192 void _gettermname __P((void));
    193 int terminaltypeok __P((char *));
    194 char *getstr __P((char *, char **));
    195 
    196 /*
    197  * The string to pass to getopt().  We do it this way so
    198  * that only the actual options that we support will be
    199  * passed off to getopt().
    200  */
    201 char valid_opts[] = {
    202 	'd', ':', 'g', ':', 'h', 'k', 'n', 'S', ':', 'u', ':', 'U',
    203 	'4', '6',
    204 #ifdef	AUTHENTICATION
    205 	'a', ':', 'X', ':',
    206 #endif
    207 #ifdef BFTPDAEMON
    208 	'B',
    209 #endif
    210 #ifdef	ENCRYPTION
    211 	'e', ':',
    212 #endif
    213 #ifdef DIAGNOSTICS
    214 	'D', ':',
    215 #endif
    216 #if	defined(CRAY) && defined(NEWINIT)
    217 	'I', ':',
    218 #endif
    219 #ifdef	LINEMODE
    220 	'l',
    221 #endif
    222 #ifdef CRAY
    223 	'r', ':',
    224 #endif
    225 #ifdef	SECURELOGIN
    226 	's',
    227 #endif
    228 #ifdef	KRB5
    229 	'R', ':', 'H',
    230 #endif
    231 	'\0'
    232 };
    233 
    234 int family = AF_INET;
    235 
    236 int
    237 main(argc, argv)
    238 	int argc;
    239 	char *argv[];
    240 {
    241 	struct sockaddr_storage from;
    242 	int on = 1, fromlen;
    243 	register int ch;
    244 #if	defined(IPPROTO_IP) && defined(IP_TOS)
    245 	int tos = -1;
    246 #endif
    247 
    248 	pfrontp = pbackp = ptyobuf;
    249 	netip = netibuf;
    250 	nfrontp = nbackp = netobuf;
    251 #ifdef	ENCRYPTION
    252 	nclearto = 0;
    253 #endif	/* ENCRYPTION */
    254 
    255 	progname = *argv;
    256 
    257 #ifdef CRAY
    258 	/*
    259 	 * Get number of pty's before trying to process options,
    260 	 * which may include changing pty range.
    261 	 */
    262 	highpty = getnpty();
    263 #endif /* CRAY */
    264 
    265 	while ((ch = getopt(argc, argv, valid_opts)) != -1) {
    266 		switch (ch) {
    267 
    268 #ifdef	AUTHENTICATION
    269 		case 'a':
    270 			/*
    271 			 * Check for required authentication level
    272 			 */
    273 			if (strcmp(optarg, "debug") == 0) {
    274 				extern int auth_debug_mode;
    275 				auth_debug_mode = 1;
    276 			} else if (strcasecmp(optarg, "none") == 0) {
    277 				auth_level = 0;
    278 			} else if (strcasecmp(optarg, "other") == 0) {
    279 				auth_level = AUTH_OTHER;
    280 			} else if (strcasecmp(optarg, "user") == 0) {
    281 				auth_level = AUTH_USER;
    282 			} else if (strcasecmp(optarg, "valid") == 0) {
    283 				auth_level = AUTH_VALID;
    284 			} else if (strcasecmp(optarg, "off") == 0) {
    285 				/*
    286 				 * This hack turns off authentication
    287 				 */
    288 				auth_level = -1;
    289 			} else {
    290 				fprintf(stderr,
    291 			    "telnetd: unknown authorization level for -a\n");
    292 			}
    293 			break;
    294 #endif	/* AUTHENTICATION */
    295 
    296 #ifdef BFTPDAEMON
    297 		case 'B':
    298 			bftpd++;
    299 			break;
    300 #endif /* BFTPDAEMON */
    301 
    302 		case 'd':
    303 			if (strcmp(optarg, "ebug") == 0) {
    304 				debug++;
    305 				break;
    306 			}
    307 			usage();
    308 			/* NOTREACHED */
    309 			break;
    310 
    311 #ifdef DIAGNOSTICS
    312 		case 'D':
    313 			/*
    314 			 * Check for desired diagnostics capabilities.
    315 			 */
    316 			if (!strcmp(optarg, "report")) {
    317 				diagnostic |= TD_REPORT|TD_OPTIONS;
    318 			} else if (!strcmp(optarg, "exercise")) {
    319 				diagnostic |= TD_EXERCISE;
    320 			} else if (!strcmp(optarg, "netdata")) {
    321 				diagnostic |= TD_NETDATA;
    322 			} else if (!strcmp(optarg, "ptydata")) {
    323 				diagnostic |= TD_PTYDATA;
    324 			} else if (!strcmp(optarg, "options")) {
    325 				diagnostic |= TD_OPTIONS;
    326 			} else {
    327 				usage();
    328 				/* NOT REACHED */
    329 			}
    330 			break;
    331 #endif /* DIAGNOSTICS */
    332 
    333 #ifdef	ENCRYPTION
    334 		case 'e':
    335 			if (strcmp(optarg, "debug") == 0) {
    336 				extern int encrypt_debug_mode;
    337 				encrypt_debug_mode = 1;
    338 				break;
    339 			}
    340 			usage();
    341 			/* NOTREACHED */
    342 			break;
    343 #endif	/* ENCRYPTION */
    344 
    345 		case 'g':
    346 			gettyname = optarg;
    347 			break;
    348 
    349 		case 'h':
    350 			hostinfo = 0;
    351 			break;
    352 
    353 #ifdef	KRB5
    354 		case 'H':
    355 		    {
    356 			extern int require_hwpreauth;
    357 			require_hwpreauth = 1;
    358 			break;
    359 		    }
    360 #endif	/* KRB5 */
    361 
    362 #if	defined(CRAY) && defined(NEWINIT)
    363 		case 'I':
    364 		    {
    365 			extern char *gen_id;
    366 			gen_id = optarg;
    367 			break;
    368 		    }
    369 #endif	/* defined(CRAY) && defined(NEWINIT) */
    370 
    371 #ifdef	LINEMODE
    372 		case 'l':
    373 			alwayslinemode = 1;
    374 			break;
    375 #endif	/* LINEMODE */
    376 
    377 		case 'k':
    378 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
    379 			lmodetype = NO_AUTOKLUDGE;
    380 #else
    381 			/* ignore -k option if built without kludge linemode */
    382 #endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
    383 			break;
    384 
    385 		case 'n':
    386 			keepalive = 0;
    387 			break;
    388 
    389 #ifdef CRAY
    390 		case 'r':
    391 		    {
    392 			char *strchr();
    393 			char *c;
    394 
    395 			/*
    396 			 * Allow the specification of alterations
    397 			 * to the pty search range.  It is legal to
    398 			 * specify only one, and not change the
    399 			 * other from its default.
    400 			 */
    401 			c = strchr(optarg, '-');
    402 			if (c) {
    403 				*c++ = '\0';
    404 				highpty = atoi(c);
    405 			}
    406 			if (*optarg != '\0')
    407 				lowpty = atoi(optarg);
    408 			if ((lowpty > highpty) || (lowpty < 0) ||
    409 							(highpty > 32767)) {
    410 				usage();
    411 				/* NOT REACHED */
    412 			}
    413 			break;
    414 		    }
    415 #endif	/* CRAY */
    416 
    417 #ifdef	KRB5
    418 		case 'R':
    419 		    {
    420 			extern krb5_context telnet_context;
    421 			krb5_error_code retval;
    422 
    423 			if (telnet_context == 0) {
    424 				retval = krb5_init_context(&telnet_context);
    425 				if (retval) {
    426 					com_err("telnetd", retval,
    427 					    "while initializing krb5");
    428 					exit(1);
    429 				}
    430 			}
    431 			krb5_set_default_realm(telnet_context, optarg);
    432 			break;
    433 		    }
    434 #endif	/* KRB5 */
    435 
    436 #ifdef	SECURELOGIN
    437 		case 's':
    438 			/* Secure login required */
    439 			require_secure_login = 1;
    440 			break;
    441 #endif	/* SECURELOGIN */
    442 		case 'S':
    443 #ifdef	HAS_GETTOS
    444 			if ((tos = parsetos(optarg, "tcp")) < 0)
    445 				fprintf(stderr, "%s%s%s\n",
    446 					"telnetd: Bad TOS argument '", optarg,
    447 					"'; will try to use default TOS");
    448 #else
    449 			fprintf(stderr, "%s%s\n", "TOS option unavailable; ",
    450 						"-S flag not supported\n");
    451 #endif
    452 			break;
    453 
    454 		case 'u':
    455 			utmp_len = atoi(optarg);
    456 			break;
    457 
    458 		case 'U':
    459 			registerd_host_only = 1;
    460 			break;
    461 
    462 #ifdef	AUTHENTICATION
    463 		case 'X':
    464 			/*
    465 			 * Check for invalid authentication types
    466 			 */
    467 			auth_disable_name(optarg);
    468 			break;
    469 #endif	/* AUTHENTICATION */
    470 
    471 		case '4':
    472 			family = AF_INET;
    473 			break;
    474 
    475 		case '6':
    476 			family = AF_INET6;
    477 			break;
    478 
    479 		default:
    480 			fprintf(stderr, "telnetd: %c: unknown option\n", ch);
    481 			/* FALLTHROUGH */
    482 		case '?':
    483 			usage();
    484 			/* NOTREACHED */
    485 		}
    486 	}
    487 
    488 	argc -= optind;
    489 	argv += optind;
    490 
    491 	if (debug) {
    492 	    int s, ns, foo, error;
    493 	    char *service = "telnet";
    494 	    struct addrinfo hints, *res;
    495 
    496 	    if (argc > 1) {
    497 		usage();
    498 		/* NOT REACHED */
    499 	    } else if (argc == 1)
    500 		service = *argv;
    501 
    502 	    memset(&hints, 0, sizeof(hints));
    503 	    hints.ai_flags = AI_PASSIVE;
    504 	    hints.ai_family = family;
    505 	    hints.ai_socktype = SOCK_STREAM;
    506 	    hints.ai_protocol = 0;
    507 	    error = getaddrinfo(NULL, service, &hints, &res);
    508 
    509 	    if (error) {
    510 		fprintf(stderr, "tcp/%s: %s\n", service, gai_strerror(error));
    511 		exit(1);
    512 	    }
    513 
    514 	    s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    515 	    if (s < 0) {
    516 		perror("telnetd: socket");;
    517 		exit(1);
    518 	    }
    519 	    (void) setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
    520 				(char *)&on, sizeof(on));
    521 	    if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
    522 		perror("bind");
    523 		exit(1);
    524 	    }
    525 	    if (listen(s, 1) < 0) {
    526 		perror("listen");
    527 		exit(1);
    528 	    }
    529 	    foo = res->ai_addrlen;
    530 	    ns = accept(s, res->ai_addr, &foo);
    531 	    if (ns < 0) {
    532 		perror("accept");
    533 		exit(1);
    534 	    }
    535 	    (void) dup2(ns, 0);
    536 	    (void) close(ns);
    537 	    (void) close(s);
    538 #ifdef convex
    539 	} else if (argc == 1) {
    540 		; /* VOID*/		/* Just ignore the host/port name */
    541 #endif
    542 	} else if (argc > 0) {
    543 		usage();
    544 		/* NOT REACHED */
    545 	}
    546 
    547 #if	defined(_SC_CRAY_SECURE_SYS)
    548 	secflag = sysconf(_SC_CRAY_SECURE_SYS);
    549 
    550 	/*
    551 	 *	Get socket's security label
    552 	 */
    553 	if (secflag)  {
    554 		int szss = sizeof(ss);
    555 #ifdef SO_SEC_MULTI			/* 8.0 code */
    556 		int sock_multi;
    557 		int szi = sizeof(int);
    558 #endif /* SO_SEC_MULTI */
    559 
    560 		memset((char *)&dv, 0, sizeof(dv));
    561 
    562 		if (getsysv(&sysv, sizeof(struct sysv)) != 0) {
    563 			perror("getsysv");
    564 			exit(1);
    565 		}
    566 
    567 		/*
    568 		 *	Get socket security label and set device values
    569 		 *	   {security label to be set on ttyp device}
    570 		 */
    571 #ifdef SO_SEC_MULTI			/* 8.0 code */
    572 		if ((getsockopt(0, SOL_SOCKET, SO_SECURITY,
    573 			       (char *)&ss, &szss) < 0) ||
    574 		    (getsockopt(0, SOL_SOCKET, SO_SEC_MULTI,
    575 				(char *)&sock_multi, &szi) < 0)) {
    576 			perror("getsockopt");
    577 			exit(1);
    578 		} else {
    579 			dv.dv_actlvl = ss.ss_actlabel.lt_level;
    580 			dv.dv_actcmp = ss.ss_actlabel.lt_compart;
    581 			if (!sock_multi) {
    582 				dv.dv_minlvl = dv.dv_maxlvl = dv.dv_actlvl;
    583 				dv.dv_valcmp = dv.dv_actcmp;
    584 			} else {
    585 				dv.dv_minlvl = ss.ss_minlabel.lt_level;
    586 				dv.dv_maxlvl = ss.ss_maxlabel.lt_level;
    587 				dv.dv_valcmp = ss.ss_maxlabel.lt_compart;
    588 			}
    589 			dv.dv_devflg = 0;
    590 		}
    591 #else /* SO_SEC_MULTI */		/* 7.0 code */
    592 		if (getsockopt(0, SOL_SOCKET, SO_SECURITY,
    593 				(char *)&ss, &szss) >= 0) {
    594 			dv.dv_actlvl = ss.ss_slevel;
    595 			dv.dv_actcmp = ss.ss_compart;
    596 			dv.dv_minlvl = ss.ss_minlvl;
    597 			dv.dv_maxlvl = ss.ss_maxlvl;
    598 			dv.dv_valcmp = ss.ss_maxcmp;
    599 		}
    600 #endif /* SO_SEC_MULTI */
    601 	}
    602 #endif	/* _SC_CRAY_SECURE_SYS */
    603 
    604 	openlog("telnetd", LOG_PID | LOG_ODELAY, LOG_DAEMON);
    605 	fromlen = sizeof (from);
    606 	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
    607 		fprintf(stderr, "%s: ", progname);
    608 		perror("getpeername");
    609 		_exit(1);
    610 	}
    611 	if (keepalive &&
    612 	    setsockopt(0, SOL_SOCKET, SO_KEEPALIVE,
    613 			(char *)&on, sizeof (on)) < 0) {
    614 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
    615 	}
    616 
    617 #if	defined(IPPROTO_IP) && defined(IP_TOS)
    618 	if (((struct sockaddr *)&from)->sa_family == AF_INET) {
    619 # if	defined(HAS_GETTOS)
    620 		struct tosent *tp;
    621 		if (tos < 0 && (tp = gettosbyname("telnet", "tcp")))
    622 			tos = tp->t_tos;
    623 # endif
    624 		if (tos < 0)
    625 			tos = 020;	/* Low Delay bit */
    626 		if (tos
    627 		   && (setsockopt(0, IPPROTO_IP, IP_TOS,
    628 				  (char *)&tos, sizeof(tos)) < 0)
    629 		   && (errno != ENOPROTOOPT) )
    630 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
    631 	}
    632 #endif	/* defined(IPPROTO_IP) && defined(IP_TOS) */
    633 
    634 	net = 0;
    635 	doit((struct sockaddr *)&from);
    636 	/* NOTREACHED */
    637 #ifdef __GNUC__
    638 	exit(0);
    639 #endif
    640 }  /* end of main */
    641 
    642 	void
    643 usage()
    644 {
    645 	fprintf(stderr, "Usage: telnetd");
    646 #ifdef	AUTHENTICATION
    647 	fprintf(stderr, " [-a (debug|other|user|valid|off|none)]\n\t");
    648 #endif
    649 #ifdef BFTPDAEMON
    650 	fprintf(stderr, " [-B]");
    651 #endif
    652 	fprintf(stderr, " [-debug]");
    653 #ifdef DIAGNOSTICS
    654 	fprintf(stderr, " [-D (options|report|exercise|netdata|ptydata)]\n\t");
    655 #endif
    656 #ifdef	AUTHENTICATION
    657 	fprintf(stderr, " [-edebug]");
    658 #endif
    659 	fprintf(stderr, " [-h]");
    660 #if	defined(CRAY) && defined(NEWINIT)
    661 	fprintf(stderr, " [-Iinitid]");
    662 #endif
    663 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
    664 	fprintf(stderr, " [-k]");
    665 #endif
    666 #ifdef LINEMODE
    667 	fprintf(stderr, " [-l]");
    668 #endif
    669 	fprintf(stderr, " [-n]");
    670 #ifdef	CRAY
    671 	fprintf(stderr, " [-r[lowpty]-[highpty]]");
    672 #endif
    673 	fprintf(stderr, "\n\t");
    674 #ifdef	SECURELOGIN
    675 	fprintf(stderr, " [-s]");
    676 #endif
    677 #ifdef	HAS_GETTOS
    678 	fprintf(stderr, " [-S tos]");
    679 #endif
    680 #ifdef	AUTHENTICATION
    681 	fprintf(stderr, " [-X auth-type]");
    682 #endif
    683 	fprintf(stderr, " [-u utmp_hostname_length] [-U]");
    684 	fprintf(stderr, " [port]\n");
    685 	exit(1);
    686 }
    687 
    688 /*
    689  * getterminaltype
    690  *
    691  *	Ask the other end to send along its terminal type and speed.
    692  * Output is the variable terminaltype filled in.
    693  */
    694 static unsigned char ttytype_sbbuf[] = {
    695 	IAC, SB, TELOPT_TTYPE, TELQUAL_SEND, IAC, SE
    696 };
    697 
    698     int
    699 getterminaltype(name)
    700     char *name;
    701 {
    702     int retval = -1;
    703 
    704     settimer(baseline);
    705 #if	defined(AUTHENTICATION)
    706     /*
    707      * Handle the Authentication option before we do anything else.
    708      */
    709     send_do(TELOPT_AUTHENTICATION, 1);
    710     while (his_will_wont_is_changing(TELOPT_AUTHENTICATION))
    711 	ttloop();
    712     if (his_state_is_will(TELOPT_AUTHENTICATION)) {
    713 	retval = auth_wait(name);
    714     }
    715 #endif
    716 
    717 #ifdef	ENCRYPTION
    718     send_will(TELOPT_ENCRYPT, 1);
    719 #endif	/* ENCRYPTION */
    720     send_do(TELOPT_TTYPE, 1);
    721     send_do(TELOPT_TSPEED, 1);
    722     send_do(TELOPT_XDISPLOC, 1);
    723     send_do(TELOPT_NEW_ENVIRON, 1);
    724     send_do(TELOPT_OLD_ENVIRON, 1);
    725     while (
    726 #ifdef	ENCRYPTION
    727 	   his_do_dont_is_changing(TELOPT_ENCRYPT) ||
    728 #endif	/* ENCRYPTION */
    729 	   his_will_wont_is_changing(TELOPT_TTYPE) ||
    730 	   his_will_wont_is_changing(TELOPT_TSPEED) ||
    731 	   his_will_wont_is_changing(TELOPT_XDISPLOC) ||
    732 	   his_will_wont_is_changing(TELOPT_NEW_ENVIRON) ||
    733 	   his_will_wont_is_changing(TELOPT_OLD_ENVIRON)) {
    734 	ttloop();
    735     }
    736     if (his_state_is_will(TELOPT_TSPEED)) {
    737 	static unsigned char sb[] =
    738 			{ IAC, SB, TELOPT_TSPEED, TELQUAL_SEND, IAC, SE };
    739 
    740 	memmove(nfrontp, sb, sizeof sb);
    741 	nfrontp += sizeof sb;
    742 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
    743     }
    744 #ifdef	ENCRYPTION
    745     /*
    746      * Wait for the negotiation of what type of encryption we can
    747      * send with.  If autoencrypt is not set, this will just return.
    748      */
    749     if (his_state_is_will(TELOPT_ENCRYPT)) {
    750 	encrypt_wait();
    751     }
    752 #endif	/* ENCRYPTION */
    753     if (his_state_is_will(TELOPT_XDISPLOC)) {
    754 	static unsigned char sb[] =
    755 			{ IAC, SB, TELOPT_XDISPLOC, TELQUAL_SEND, IAC, SE };
    756 
    757 	memmove(nfrontp, sb, sizeof sb);
    758 	nfrontp += sizeof sb;
    759 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
    760     }
    761     if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
    762 	static unsigned char sb[] =
    763 			{ IAC, SB, TELOPT_NEW_ENVIRON, TELQUAL_SEND, IAC, SE };
    764 
    765 	memmove(nfrontp, sb, sizeof sb);
    766 	nfrontp += sizeof sb;
    767 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
    768     }
    769     else if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
    770 	static unsigned char sb[] =
    771 			{ IAC, SB, TELOPT_OLD_ENVIRON, TELQUAL_SEND, IAC, SE };
    772 
    773 	memmove(nfrontp, sb, sizeof sb);
    774 	nfrontp += sizeof sb;
    775 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
    776     }
    777     if (his_state_is_will(TELOPT_TTYPE)) {
    778 
    779 	memmove(nfrontp, ttytype_sbbuf, sizeof ttytype_sbbuf);
    780 	nfrontp += sizeof ttytype_sbbuf;
    781 	DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
    782 					sizeof ttytype_sbbuf - 2););
    783     }
    784     if (his_state_is_will(TELOPT_TSPEED)) {
    785 	while (sequenceIs(tspeedsubopt, baseline))
    786 	    ttloop();
    787     }
    788     if (his_state_is_will(TELOPT_XDISPLOC)) {
    789 	while (sequenceIs(xdisplocsubopt, baseline))
    790 	    ttloop();
    791     }
    792     if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
    793 	while (sequenceIs(environsubopt, baseline))
    794 	    ttloop();
    795     }
    796     if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
    797 	while (sequenceIs(oenvironsubopt, baseline))
    798 	    ttloop();
    799     }
    800     if (his_state_is_will(TELOPT_TTYPE)) {
    801 	char first[256], last[256];
    802 
    803 	while (sequenceIs(ttypesubopt, baseline))
    804 	    ttloop();
    805 
    806 	/*
    807 	 * If the other side has already disabled the option, then
    808 	 * we have to just go with what we (might) have already gotten.
    809 	 */
    810 	if (his_state_is_will(TELOPT_TTYPE) && !terminaltypeok(terminaltype)) {
    811 	    (void) strncpy(first, terminaltype, sizeof(first) - 1);
    812 	    first[sizeof(first) - 1] = '\0';
    813 	    for(;;) {
    814 		/*
    815 		 * Save the unknown name, and request the next name.
    816 		 */
    817 		(void) strncpy(last, terminaltype, sizeof(last) - 1);
    818 		last[sizeof(last) - 1] = '\0';
    819 		_gettermname();
    820 		if (terminaltypeok(terminaltype))
    821 		    break;
    822 		if ((strncmp(last, terminaltype, sizeof(last)) == 0) ||
    823 		    his_state_is_wont(TELOPT_TTYPE)) {
    824 		    /*
    825 		     * We've hit the end.  If this is the same as
    826 		     * the first name, just go with it.
    827 		     */
    828 		    if (strncmp(first, terminaltype, sizeof(first)) == 0)
    829 			break;
    830 		    /*
    831 		     * Get the terminal name one more time, so that
    832 		     * RFC1091 compliant telnets will cycle back to
    833 		     * the start of the list.
    834 		     */
    835 		     _gettermname();
    836 		    if (strncmp(first, terminaltype, sizeof(first)) != 0) {
    837 			(void) strncpy(terminaltype, first, sizeof(first) - 1);
    838 			terminaltype[sizeof(terminaltype) - 1] = '\0';
    839 		    }
    840 		    break;
    841 		}
    842 	    }
    843 	}
    844     }
    845     return(retval);
    846 }  /* end of getterminaltype */
    847 
    848     void
    849 _gettermname()
    850 {
    851     /*
    852      * If the client turned off the option,
    853      * we can't send another request, so we
    854      * just return.
    855      */
    856     if (his_state_is_wont(TELOPT_TTYPE))
    857 	return;
    858     settimer(baseline);
    859     memmove(nfrontp, ttytype_sbbuf, sizeof ttytype_sbbuf);
    860     nfrontp += sizeof ttytype_sbbuf;
    861     DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
    862 					sizeof ttytype_sbbuf - 2););
    863     while (sequenceIs(ttypesubopt, baseline))
    864 	ttloop();
    865 }
    866 
    867     int
    868 terminaltypeok(s)
    869     char *s;
    870 {
    871     char buf[1024];
    872 
    873     if (terminaltype == NULL)
    874 	return(1);
    875 
    876     /*
    877      * tgetent() will return 1 if the type is known, and
    878      * 0 if it is not known.  If it returns -1, it couldn't
    879      * open the database.  But if we can't open the database,
    880      * it won't help to say we failed, because we won't be
    881      * able to verify anything else.  So, we treat -1 like 1.
    882      */
    883     if (tgetent(buf, s) == 0)
    884 	return(0);
    885     return(1);
    886 }
    887 
    888 #ifndef	MAXHOSTNAMELEN
    889 #define	MAXHOSTNAMELEN 64
    890 #endif	/* MAXHOSTNAMELEN */
    891 
    892 char *hostname;
    893 char host_name[MAXHOSTNAMELEN + 1];
    894 char remote_host_name[MAXHOSTNAMELEN + 1];
    895 
    896 #ifndef	convex
    897 extern void telnet P((int, int));
    898 #else
    899 extern void telnet P((int, int, char *));
    900 #endif
    901 
    902 /*
    903  * Get a pty, scan input lines.
    904  */
    905 void
    906 doit(who)
    907 	struct sockaddr *who;
    908 {
    909 	char *host;
    910 	int error;
    911 	int level;
    912 	int ptynum;
    913 	char user_name[256];
    914 
    915 	/*
    916 	 * Find an available pty to use.
    917 	 */
    918 #ifndef	convex
    919 	pty = getpty(&ptynum);
    920 	if (pty < 0)
    921 		fatal(net, "All network ports in use");
    922 #else
    923 	for (;;) {
    924 		char *lp;
    925 
    926 		if ((lp = getpty()) == NULL)
    927 			fatal(net, "Out of ptys");
    928 
    929 		if ((pty = open(lp, 2)) >= 0) {
    930 			(void)strlcpy(line, lp, sizeof(NULL16STR));
    931 			line[5] = 't';
    932 			break;
    933 		}
    934 	}
    935 #endif
    936 
    937 #if	defined(_SC_CRAY_SECURE_SYS)
    938 	/*
    939 	 *	set ttyp line security label
    940 	 */
    941 	if (secflag) {
    942 		char slave_dev[16];
    943 
    944 		sprintf(tty_dev, "/dev/pty/%03d", ptynum);
    945 		if (setdevs(tty_dev, &dv) < 0)
    946 		 	fatal(net, "cannot set pty security");
    947 		sprintf(slave_dev, "/dev/ttyp%03d", ptynum);
    948 		if (setdevs(slave_dev, &dv) < 0)
    949 		 	fatal(net, "cannot set tty security");
    950 	}
    951 #endif	/* _SC_CRAY_SECURE_SYS */
    952 
    953 	/* get name of connected client */
    954 	error = getnameinfo(who, who->sa_len, remote_host_name,
    955 			    sizeof(remote_host_name), NULL, 0, 0);
    956 
    957 	if (error) {
    958 		fatal(net, "Couldn't resolve your address into a host name.\r\n\
    959 	 Please contact your net administrator");
    960 #ifdef __GNUC__
    961 		host = NULL;	/* XXX gcc */
    962 #endif
    963 	}
    964 
    965 	remote_host_name[sizeof(remote_host_name)-1] = 0;
    966 	host = remote_host_name;
    967 
    968 	(void)gethostname(host_name, sizeof (host_name));
    969 	host_name[sizeof(host_name) - 1] = '\0';
    970 	hostname = host_name;
    971 
    972 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
    973 	auth_encrypt_init(hostname, host, "TELNETD", 1);
    974 #endif
    975 
    976 	init_env();
    977 	/*
    978 	 * get terminal type.
    979 	 */
    980 	*user_name = 0;
    981 	level = getterminaltype(user_name);
    982 	setenv("TERM", terminaltype ? terminaltype : "network", 1);
    983 
    984 	/*
    985 	 * Start up the login process on the slave side of the terminal
    986 	 */
    987 #ifndef	convex
    988 	startslave(host, level, user_name);
    989 
    990 #if	defined(_SC_CRAY_SECURE_SYS)
    991 	if (secflag) {
    992 		if (setulvl(dv.dv_actlvl) < 0)
    993 			fatal(net,"cannot setulvl()");
    994 		if (setucmp(dv.dv_actcmp) < 0)
    995 			fatal(net, "cannot setucmp()");
    996 	}
    997 #endif	/* _SC_CRAY_SECURE_SYS */
    998 
    999 	telnet(net, pty);  /* begin server processing */
   1000 #else
   1001 	telnet(net, pty, host);
   1002 #endif
   1003 	/*NOTREACHED*/
   1004 }  /* end of doit */
   1005 
   1006 #if	defined(CRAY2) && defined(UNICOS5) && defined(UNICOS50)
   1007 	int
   1008 Xterm_output(ibufp, obuf, icountp, ocount)
   1009 	char **ibufp, *obuf;
   1010 	int *icountp, ocount;
   1011 {
   1012 	int ret;
   1013 	ret = term_output(*ibufp, obuf, *icountp, ocount);
   1014 	*ibufp += *icountp;
   1015 	*icountp = 0;
   1016 	return(ret);
   1017 }
   1018 #define	term_output	Xterm_output
   1019 #endif	/* defined(CRAY2) && defined(UNICOS5) && defined(UNICOS50) */
   1020 
   1021 /*
   1022  * Main loop.  Select from pty and network, and
   1023  * hand data to telnet receiver finite state machine.
   1024  */
   1025 	void
   1026 #ifndef	convex
   1027 telnet(f, p)
   1028 #else
   1029 telnet(f, p, host)
   1030 #endif
   1031 	int f, p;
   1032 #ifdef convex
   1033 	char *host;
   1034 #endif
   1035 {
   1036 	int on = 1;
   1037 #define	TABBUFSIZ	512
   1038 	char	defent[TABBUFSIZ];
   1039 	char	defstrs[TABBUFSIZ];
   1040 #undef	TABBUFSIZ
   1041 	char *HE, *HN, *IM, *IF, *ptyibuf2ptr;
   1042 	int nfd;
   1043 
   1044 	/*
   1045 	 * Initialize the slc mapping table.
   1046 	 */
   1047 	get_slc_defaults();
   1048 
   1049 	/*
   1050 	 * Do some tests where it is desireable to wait for a response.
   1051 	 * Rather than doing them slowly, one at a time, do them all
   1052 	 * at once.
   1053 	 */
   1054 	if (my_state_is_wont(TELOPT_SGA))
   1055 		send_will(TELOPT_SGA, 1);
   1056 	/*
   1057 	 * Is the client side a 4.2 (NOT 4.3) system?  We need to know this
   1058 	 * because 4.2 clients are unable to deal with TCP urgent data.
   1059 	 *
   1060 	 * To find out, we send out a "DO ECHO".  If the remote system
   1061 	 * answers "WILL ECHO" it is probably a 4.2 client, and we note
   1062 	 * that fact ("WILL ECHO" ==> that the client will echo what
   1063 	 * WE, the server, sends it; it does NOT mean that the client will
   1064 	 * echo the terminal input).
   1065 	 */
   1066 	send_do(TELOPT_ECHO, 1);
   1067 
   1068 #ifdef	LINEMODE
   1069 	if (his_state_is_wont(TELOPT_LINEMODE)) {
   1070 		/* Query the peer for linemode support by trying to negotiate
   1071 		 * the linemode option.
   1072 		 */
   1073 		linemode = 0;
   1074 		editmode = 0;
   1075 		send_do(TELOPT_LINEMODE, 1);  /* send do linemode */
   1076 	}
   1077 #endif	/* LINEMODE */
   1078 
   1079 	/*
   1080 	 * Send along a couple of other options that we wish to negotiate.
   1081 	 */
   1082 	send_do(TELOPT_NAWS, 1);
   1083 	send_will(TELOPT_STATUS, 1);
   1084 	flowmode = 1;		/* default flow control state */
   1085 	restartany = -1;	/* uninitialized... */
   1086 	send_do(TELOPT_LFLOW, 1);
   1087 
   1088 	/*
   1089 	 * Spin, waiting for a response from the DO ECHO.  However,
   1090 	 * some REALLY DUMB telnets out there might not respond
   1091 	 * to the DO ECHO.  So, we spin looking for NAWS, (most dumb
   1092 	 * telnets so far seem to respond with WONT for a DO that
   1093 	 * they don't understand...) because by the time we get the
   1094 	 * response, it will already have processed the DO ECHO.
   1095 	 * Kludge upon kludge.
   1096 	 */
   1097 	while (his_will_wont_is_changing(TELOPT_NAWS))
   1098 		ttloop();
   1099 
   1100 	/*
   1101 	 * But...
   1102 	 * The client might have sent a WILL NAWS as part of its
   1103 	 * startup code; if so, we'll be here before we get the
   1104 	 * response to the DO ECHO.  We'll make the assumption
   1105 	 * that any implementation that understands about NAWS
   1106 	 * is a modern enough implementation that it will respond
   1107 	 * to our DO ECHO request; hence we'll do another spin
   1108 	 * waiting for the ECHO option to settle down, which is
   1109 	 * what we wanted to do in the first place...
   1110 	 */
   1111 	if (his_want_state_is_will(TELOPT_ECHO) &&
   1112 	    his_state_is_will(TELOPT_NAWS)) {
   1113 		while (his_will_wont_is_changing(TELOPT_ECHO))
   1114 			ttloop();
   1115 	}
   1116 	/*
   1117 	 * On the off chance that the telnet client is broken and does not
   1118 	 * respond to the DO ECHO we sent, (after all, we did send the
   1119 	 * DO NAWS negotiation after the DO ECHO, and we won't get here
   1120 	 * until a response to the DO NAWS comes back) simulate the
   1121 	 * receipt of a will echo.  This will also send a WONT ECHO
   1122 	 * to the client, since we assume that the client failed to
   1123 	 * respond because it believes that it is already in DO ECHO
   1124 	 * mode, which we do not want.
   1125 	 */
   1126 	if (his_want_state_is_will(TELOPT_ECHO)) {
   1127 		DIAG(TD_OPTIONS,
   1128 			{sprintf(nfrontp, "td: simulating recv\r\n");
   1129 			 nfrontp += strlen(nfrontp);});
   1130 		willoption(TELOPT_ECHO);
   1131 	}
   1132 
   1133 	/*
   1134 	 * Finally, to clean things up, we turn on our echo.  This
   1135 	 * will break stupid 4.2 telnets out of local terminal echo.
   1136 	 */
   1137 
   1138 	if (my_state_is_wont(TELOPT_ECHO))
   1139 		send_will(TELOPT_ECHO, 1);
   1140 
   1141 #ifndef	STREAMSPTY
   1142 	/*
   1143 	 * Turn on packet mode
   1144 	 */
   1145 	(void) ioctl(p, TIOCPKT, (char *)&on);
   1146 #endif
   1147 
   1148 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
   1149 	/*
   1150 	 * Continuing line mode support.  If client does not support
   1151 	 * real linemode, attempt to negotiate kludge linemode by sending
   1152 	 * the do timing mark sequence.
   1153 	 */
   1154 	if (lmodetype < REAL_LINEMODE)
   1155 		send_do(TELOPT_TM, 1);
   1156 #endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
   1157 
   1158 	/*
   1159 	 * Call telrcv() once to pick up anything received during
   1160 	 * terminal type negotiation, 4.2/4.3 determination, and
   1161 	 * linemode negotiation.
   1162 	 */
   1163 	telrcv();
   1164 
   1165 	(void) ioctl(f, FIONBIO, (char *)&on);
   1166 	(void) ioctl(p, FIONBIO, (char *)&on);
   1167 #if	defined(CRAY2) && defined(UNICOS5)
   1168 	init_termdriver(f, p, interrupt, sendbrk);
   1169 #endif
   1170 
   1171 #if	defined(SO_OOBINLINE)
   1172 	(void) setsockopt(net, SOL_SOCKET, SO_OOBINLINE,
   1173 				(char *)&on, sizeof on);
   1174 #endif	/* defined(SO_OOBINLINE) */
   1175 
   1176 #ifdef	SIGTSTP
   1177 	(void) signal(SIGTSTP, SIG_IGN);
   1178 #endif
   1179 #ifdef	SIGTTOU
   1180 	/*
   1181 	 * Ignoring SIGTTOU keeps the kernel from blocking us
   1182 	 * in ttioct() in /sys/tty.c.
   1183 	 */
   1184 	(void) signal(SIGTTOU, SIG_IGN);
   1185 #endif
   1186 
   1187 	(void) signal(SIGCHLD, cleanup);
   1188 
   1189 #if	defined(CRAY2) && defined(UNICOS5)
   1190 	/*
   1191 	 * Cray-2 will send a signal when pty modes are changed by slave
   1192 	 * side.  Set up signal handler now.
   1193 	 */
   1194 	if ((int)signal(SIGUSR1, termstat) < 0)
   1195 		perror("signal");
   1196 	else if (ioctl(p, TCSIGME, (char *)SIGUSR1) < 0)
   1197 		perror("ioctl:TCSIGME");
   1198 	/*
   1199 	 * Make processing loop check terminal characteristics early on.
   1200 	 */
   1201 	termstat();
   1202 #endif
   1203 
   1204 #ifdef  TIOCNOTTY
   1205 	{
   1206 		register int t;
   1207 		t = open(_PATH_TTY, O_RDWR);
   1208 		if (t >= 0) {
   1209 			(void) ioctl(t, TIOCNOTTY, (char *)0);
   1210 			(void) close(t);
   1211 		}
   1212 	}
   1213 #endif
   1214 
   1215 #if	defined(CRAY) && defined(NEWINIT) && defined(TIOCSCTTY)
   1216 	(void) setsid();
   1217 	ioctl(p, TIOCSCTTY, 0);
   1218 #endif
   1219 
   1220 	/*
   1221 	 * Show banner that getty never gave.
   1222 	 *
   1223 	 * We put the banner in the pty input buffer.  This way, it
   1224 	 * gets carriage return null processing, etc., just like all
   1225 	 * other pty --> client data.
   1226 	 */
   1227 
   1228 #if	!defined(CRAY) || !defined(NEWINIT)
   1229 	if (getenv("USER"))
   1230 		hostinfo = 0;
   1231 #endif
   1232 
   1233 	if (getent(defent, gettyname) == 1) {
   1234 		char *cp=defstrs;
   1235 
   1236 		HE = getstr("he", &cp);
   1237 		HN = getstr("hn", &cp);
   1238 		IM = getstr("im", &cp);
   1239 		IF = getstr("if", &cp);
   1240 		if (HN && *HN)
   1241 			(void)strlcpy(host_name, HN, sizeof(host_name));
   1242 		if (IM == 0)
   1243 			IM = "";
   1244 	} else {
   1245 		IM = DEFAULT_IM;
   1246 		HE = 0;
   1247 	}
   1248 	edithost(HE, host_name);
   1249 	ptyibuf2ptr = ptyibuf2;
   1250 	if (hostinfo) {
   1251 		if (IF)	{
   1252 			char buf[_POSIX2_LINE_MAX];
   1253 			FILE *fd;
   1254 
   1255 			if ((fd = fopen(IF, "r")) != NULL) {
   1256 				while (fgets(buf, sizeof(buf) - 1, fd) != NULL)
   1257 					ptyibuf2ptr = putf(buf, ptyibuf2ptr);
   1258 				fclose(fd);
   1259 			}
   1260 		}
   1261 		if (*IM)
   1262 			ptyibuf2ptr = putf(IM, ptyibuf2ptr);
   1263 	}
   1264 
   1265 	if (pcc)
   1266 		strncpy(ptyibuf2ptr, ptyip, pcc+1);
   1267 	ptyip = ptyibuf2;
   1268 	pcc = strlen(ptyip);
   1269 #ifdef	LINEMODE
   1270 	/*
   1271 	 * Last check to make sure all our states are correct.
   1272 	 */
   1273 	init_termbuf();
   1274 	localstat();
   1275 #endif	/* LINEMODE */
   1276 
   1277 	DIAG(TD_REPORT,
   1278 		{sprintf(nfrontp, "td: Entering processing loop\r\n");
   1279 		 nfrontp += strlen(nfrontp);});
   1280 
   1281 #ifdef	convex
   1282 	startslave(host);
   1283 #endif
   1284 
   1285 	nfd = ((f > p) ? f : p) + 1;
   1286 	for (;;) {
   1287 		fd_set ibits, obits, xbits;
   1288 		register int c;
   1289 
   1290 		if (ncc < 0 && pcc < 0)
   1291 			break;
   1292 
   1293 #if	defined(CRAY2) && defined(UNICOS5)
   1294 		if (needtermstat)
   1295 			_termstat();
   1296 #endif	/* defined(CRAY2) && defined(UNICOS5) */
   1297 		FD_ZERO(&ibits);
   1298 		FD_ZERO(&obits);
   1299 		FD_ZERO(&xbits);
   1300 		/*
   1301 		 * Never look for input if there's still
   1302 		 * stuff in the corresponding output buffer
   1303 		 */
   1304 		if (nfrontp - nbackp || pcc > 0) {
   1305 			FD_SET(f, &obits);
   1306 		} else {
   1307 			FD_SET(p, &ibits);
   1308 		}
   1309 		if (pfrontp - pbackp || ncc > 0) {
   1310 			FD_SET(p, &obits);
   1311 		} else {
   1312 			FD_SET(f, &ibits);
   1313 		}
   1314 		if (!SYNCHing) {
   1315 			FD_SET(f, &xbits);
   1316 		}
   1317 		if ((c = select(nfd, &ibits, &obits, &xbits,
   1318 						(struct timeval *)0)) < 1) {
   1319 			if (c == -1) {
   1320 				if (errno == EINTR) {
   1321 					continue;
   1322 				}
   1323 			}
   1324 			sleep(5);
   1325 			continue;
   1326 		}
   1327 
   1328 		/*
   1329 		 * Any urgent data?
   1330 		 */
   1331 		if (FD_ISSET(net, &xbits)) {
   1332 		    SYNCHing = 1;
   1333 		}
   1334 
   1335 		/*
   1336 		 * Something to read from the network...
   1337 		 */
   1338 		if (FD_ISSET(net, &ibits)) {
   1339 #if	!defined(SO_OOBINLINE)
   1340 			/*
   1341 			 * In 4.2 (and 4.3 beta) systems, the
   1342 			 * OOB indication and data handling in the kernel
   1343 			 * is such that if two separate TCP Urgent requests
   1344 			 * come in, one byte of TCP data will be overlaid.
   1345 			 * This is fatal for Telnet, but we try to live
   1346 			 * with it.
   1347 			 *
   1348 			 * In addition, in 4.2 (and...), a special protocol
   1349 			 * is needed to pick up the TCP Urgent data in
   1350 			 * the correct sequence.
   1351 			 *
   1352 			 * What we do is:  if we think we are in urgent
   1353 			 * mode, we look to see if we are "at the mark".
   1354 			 * If we are, we do an OOB receive.  If we run
   1355 			 * this twice, we will do the OOB receive twice,
   1356 			 * but the second will fail, since the second
   1357 			 * time we were "at the mark", but there wasn't
   1358 			 * any data there (the kernel doesn't reset
   1359 			 * "at the mark" until we do a normal read).
   1360 			 * Once we've read the OOB data, we go ahead
   1361 			 * and do normal reads.
   1362 			 *
   1363 			 * There is also another problem, which is that
   1364 			 * since the OOB byte we read doesn't put us
   1365 			 * out of OOB state, and since that byte is most
   1366 			 * likely the TELNET DM (data mark), we would
   1367 			 * stay in the TELNET SYNCH (SYNCHing) state.
   1368 			 * So, clocks to the rescue.  If we've "just"
   1369 			 * received a DM, then we test for the
   1370 			 * presence of OOB data when the receive OOB
   1371 			 * fails (and AFTER we did the normal mode read
   1372 			 * to clear "at the mark").
   1373 			 */
   1374 		    if (SYNCHing) {
   1375 			int atmark;
   1376 
   1377 			(void) ioctl(net, SIOCATMARK, (char *)&atmark);
   1378 			if (atmark) {
   1379 			    ncc = recv(net, netibuf, sizeof (netibuf), MSG_OOB);
   1380 			    if ((ncc == -1) && (errno == EINVAL)) {
   1381 				ncc = read(net, netibuf, sizeof (netibuf));
   1382 				if (sequenceIs(didnetreceive, gotDM)) {
   1383 				    SYNCHing = stilloob(net);
   1384 				}
   1385 			    }
   1386 			} else {
   1387 			    ncc = read(net, netibuf, sizeof (netibuf));
   1388 			}
   1389 		    } else {
   1390 			ncc = read(net, netibuf, sizeof (netibuf));
   1391 		    }
   1392 		    settimer(didnetreceive);
   1393 #else	/* !defined(SO_OOBINLINE)) */
   1394 		    ncc = read(net, netibuf, sizeof (netibuf));
   1395 #endif	/* !defined(SO_OOBINLINE)) */
   1396 		    if (ncc < 0 && errno == EWOULDBLOCK)
   1397 			ncc = 0;
   1398 		    else {
   1399 			if (ncc <= 0) {
   1400 			    break;
   1401 			}
   1402 			netip = netibuf;
   1403 		    }
   1404 		    DIAG((TD_REPORT | TD_NETDATA),
   1405 			    {sprintf(nfrontp, "td: netread %d chars\r\n", ncc);
   1406 			     nfrontp += strlen(nfrontp);});
   1407 		    DIAG(TD_NETDATA, printdata("nd", netip, ncc));
   1408 		}
   1409 
   1410 		/*
   1411 		 * Something to read from the pty...
   1412 		 */
   1413 		if (FD_ISSET(p, &ibits)) {
   1414 #ifndef	STREAMSPTY
   1415 			pcc = read(p, ptyibuf, BUFSIZ);
   1416 #else
   1417 			pcc = readstream(p, ptyibuf, BUFSIZ);
   1418 #endif
   1419 			/*
   1420 			 * On some systems, if we try to read something
   1421 			 * off the master side before the slave side is
   1422 			 * opened, we get EIO.
   1423 			 */
   1424 			if (pcc < 0 && (errno == EWOULDBLOCK ||
   1425 #ifdef	EAGAIN
   1426 					errno == EAGAIN ||
   1427 #endif
   1428 					errno == EIO)) {
   1429 				pcc = 0;
   1430 			} else {
   1431 				if (pcc <= 0)
   1432 					break;
   1433 #if	!defined(CRAY2) || !defined(UNICOS5)
   1434 #ifdef	LINEMODE
   1435 				/*
   1436 				 * If ioctl from pty, pass it through net
   1437 				 */
   1438 				if (ptyibuf[0] & TIOCPKT_IOCTL) {
   1439 					copy_termbuf(ptyibuf+1, pcc-1);
   1440 					localstat();
   1441 					pcc = 1;
   1442 				}
   1443 #endif	/* LINEMODE */
   1444 				if (ptyibuf[0] & TIOCPKT_FLUSHWRITE) {
   1445 					netclear();	/* clear buffer back */
   1446 #ifndef	NO_URGENT
   1447 					/*
   1448 					 * There are client telnets on some
   1449 					 * operating systems get screwed up
   1450 					 * royally if we send them urgent
   1451 					 * mode data.
   1452 					 */
   1453 					*nfrontp++ = IAC;
   1454 					*nfrontp++ = DM;
   1455 					neturg = nfrontp-1; /* off by one XXX */
   1456 					DIAG(TD_OPTIONS,
   1457 					    printoption("td: send IAC", DM));
   1458 
   1459 #endif
   1460 				}
   1461 				if (his_state_is_will(TELOPT_LFLOW) &&
   1462 				    (ptyibuf[0] &
   1463 				     (TIOCPKT_NOSTOP|TIOCPKT_DOSTOP))) {
   1464 					int newflow =
   1465 					    ptyibuf[0] & TIOCPKT_DOSTOP ? 1 : 0;
   1466 					if (newflow != flowmode) {
   1467 						flowmode = newflow;
   1468 						(void) sprintf(nfrontp,
   1469 							"%c%c%c%c%c%c",
   1470 							IAC, SB, TELOPT_LFLOW,
   1471 							flowmode ? LFLOW_ON
   1472 								 : LFLOW_OFF,
   1473 							IAC, SE);
   1474 						nfrontp += 6;
   1475 						DIAG(TD_OPTIONS, printsub('>',
   1476 						    (unsigned char *)nfrontp-4,
   1477 						    4););
   1478 					}
   1479 				}
   1480 				pcc--;
   1481 				ptyip = ptyibuf+1;
   1482 #else	/* defined(CRAY2) && defined(UNICOS5) */
   1483 				if (!uselinemode) {
   1484 					unpcc = pcc;
   1485 					unptyip = ptyibuf;
   1486 					pcc = term_output(&unptyip, ptyibuf2,
   1487 								&unpcc, BUFSIZ);
   1488 					ptyip = ptyibuf2;
   1489 				} else
   1490 					ptyip = ptyibuf;
   1491 #endif	/* defined(CRAY2) && defined(UNICOS5) */
   1492 			}
   1493 		}
   1494 
   1495 		while (pcc > 0) {
   1496 			if ((&netobuf[BUFSIZ] - nfrontp) < 2)
   1497 				break;
   1498 			c = *ptyip++ & 0377, pcc--;
   1499 			if (c == IAC)
   1500 				*nfrontp++ = c;
   1501 #if	defined(CRAY2) && defined(UNICOS5)
   1502 			else if (c == '\n' &&
   1503 				     my_state_is_wont(TELOPT_BINARY) && newmap)
   1504 				*nfrontp++ = '\r';
   1505 #endif	/* defined(CRAY2) && defined(UNICOS5) */
   1506 			*nfrontp++ = c;
   1507 			if ((c == '\r') && (my_state_is_wont(TELOPT_BINARY))) {
   1508 				if (pcc > 0 && ((*ptyip & 0377) == '\n')) {
   1509 					*nfrontp++ = *ptyip++ & 0377;
   1510 					pcc--;
   1511 				} else
   1512 					*nfrontp++ = '\0';
   1513 			}
   1514 		}
   1515 #if	defined(CRAY2) && defined(UNICOS5)
   1516 		/*
   1517 		 * If chars were left over from the terminal driver,
   1518 		 * note their existence.
   1519 		 */
   1520 		if (!uselinemode && unpcc) {
   1521 			pcc = unpcc;
   1522 			unpcc = 0;
   1523 			ptyip = unptyip;
   1524 		}
   1525 #endif	/* defined(CRAY2) && defined(UNICOS5) */
   1526 
   1527 		if (FD_ISSET(f, &obits) && (nfrontp - nbackp) > 0)
   1528 			netflush();
   1529 		if (ncc > 0)
   1530 			telrcv();
   1531 		if (FD_ISSET(p, &obits) && (pfrontp - pbackp) > 0)
   1532 			ptyflush();
   1533 	}
   1534 	cleanup(0);
   1535 }  /* end of telnet */
   1536 
   1537 #ifndef	TCSIG
   1538 # ifdef	TIOCSIG
   1539 #  define TCSIG TIOCSIG
   1540 # endif
   1541 #endif
   1542 
   1543 #ifdef	STREAMSPTY
   1544 
   1545 int flowison = -1;  /* current state of flow: -1 is unknown */
   1546 
   1547 int readstream(p, ibuf, bufsize)
   1548 	int p;
   1549 	char *ibuf;
   1550 	int bufsize;
   1551 {
   1552 	int flags = 0;
   1553 	int ret = 0;
   1554 	struct termios *tsp;
   1555 	struct termio *tp;
   1556 	struct iocblk *ip;
   1557 	char vstop, vstart;
   1558 	int ixon;
   1559 	int newflow;
   1560 
   1561 	strbufc.maxlen = BUFSIZ;
   1562 	strbufc.buf = (char *)ctlbuf;
   1563 	strbufd.maxlen = bufsize-1;
   1564 	strbufd.len = 0;
   1565 	strbufd.buf = ibuf+1;
   1566 	ibuf[0] = 0;
   1567 
   1568 	ret = getmsg(p, &strbufc, &strbufd, &flags);
   1569 	if (ret < 0)  /* error of some sort -- probably EAGAIN */
   1570 		return(-1);
   1571 
   1572 	if (strbufc.len <= 0 || ctlbuf[0] == M_DATA) {
   1573 		/* data message */
   1574 		if (strbufd.len > 0) {			/* real data */
   1575 			return(strbufd.len + 1);	/* count header char */
   1576 		} else {
   1577 			/* nothing there */
   1578 			errno = EAGAIN;
   1579 			return(-1);
   1580 		}
   1581 	}
   1582 
   1583 	/*
   1584 	 * It's a control message.  Return 1, to look at the flag we set
   1585 	 */
   1586 
   1587 	switch (ctlbuf[0]) {
   1588 	case M_FLUSH:
   1589 		if (ibuf[1] & FLUSHW)
   1590 			ibuf[0] = TIOCPKT_FLUSHWRITE;
   1591 		return(1);
   1592 
   1593 	case M_IOCTL:
   1594 		ip = (struct iocblk *) (ibuf+1);
   1595 
   1596 		switch (ip->ioc_cmd) {
   1597 		case TCSETS:
   1598 		case TCSETSW:
   1599 		case TCSETSF:
   1600 			tsp = (struct termios *)
   1601 					(ibuf+1 + sizeof(struct iocblk));
   1602 			vstop = tsp->c_cc[VSTOP];
   1603 			vstart = tsp->c_cc[VSTART];
   1604 			ixon = tsp->c_iflag & IXON;
   1605 			break;
   1606 		case TCSETA:
   1607 		case TCSETAW:
   1608 		case TCSETAF:
   1609 			tp = (struct termio *) (ibuf+1 + sizeof(struct iocblk));
   1610 			vstop = tp->c_cc[VSTOP];
   1611 			vstart = tp->c_cc[VSTART];
   1612 			ixon = tp->c_iflag & IXON;
   1613 			break;
   1614 		default:
   1615 			errno = EAGAIN;
   1616 			return(-1);
   1617 		}
   1618 
   1619 		newflow =  (ixon && (vstart == 021) && (vstop == 023)) ? 1 : 0;
   1620 		if (newflow != flowison) {  /* it's a change */
   1621 			flowison = newflow;
   1622 			ibuf[0] = newflow ? TIOCPKT_DOSTOP : TIOCPKT_NOSTOP;
   1623 			return(1);
   1624 		}
   1625 	}
   1626 
   1627 	/* nothing worth doing anything about */
   1628 	errno = EAGAIN;
   1629 	return(-1);
   1630 }
   1631 #endif /* STREAMSPTY */
   1632 
   1633 /*
   1634  * Send interrupt to process on other side of pty.
   1635  * If it is in raw mode, just write NULL;
   1636  * otherwise, write intr char.
   1637  */
   1638 	void
   1639 interrupt()
   1640 {
   1641 	ptyflush();	/* half-hearted */
   1642 
   1643 #if defined(STREAMSPTY) && defined(TIOCSIGNAL)
   1644 	/* Streams PTY style ioctl to post a signal */
   1645 	{
   1646 		int sig = SIGINT;
   1647 		(void) ioctl(pty, TIOCSIGNAL, &sig);
   1648 		(void) ioctl(pty, I_FLUSH, FLUSHR);
   1649 	}
   1650 #else
   1651 #ifdef	TCSIG
   1652 	(void) ioctl(pty, TCSIG, (char *)SIGINT);
   1653 #else	/* TCSIG */
   1654 	init_termbuf();
   1655 	*pfrontp++ = slctab[SLC_IP].sptr ?
   1656 			(unsigned char)*slctab[SLC_IP].sptr : '\177';
   1657 #endif	/* TCSIG */
   1658 #endif
   1659 }
   1660 
   1661 /*
   1662  * Send quit to process on other side of pty.
   1663  * If it is in raw mode, just write NULL;
   1664  * otherwise, write quit char.
   1665  */
   1666 	void
   1667 sendbrk()
   1668 {
   1669 	ptyflush();	/* half-hearted */
   1670 #ifdef	TCSIG
   1671 	(void) ioctl(pty, TCSIG, (char *)SIGQUIT);
   1672 #else	/* TCSIG */
   1673 	init_termbuf();
   1674 	*pfrontp++ = slctab[SLC_ABORT].sptr ?
   1675 			(unsigned char)*slctab[SLC_ABORT].sptr : '\034';
   1676 #endif	/* TCSIG */
   1677 }
   1678 
   1679 	void
   1680 sendsusp()
   1681 {
   1682 #ifdef	SIGTSTP
   1683 	ptyflush();	/* half-hearted */
   1684 # ifdef	TCSIG
   1685 	(void) ioctl(pty, TCSIG, (char *)SIGTSTP);
   1686 # else	/* TCSIG */
   1687 	*pfrontp++ = slctab[SLC_SUSP].sptr ?
   1688 			(unsigned char)*slctab[SLC_SUSP].sptr : '\032';
   1689 # endif	/* TCSIG */
   1690 #endif	/* SIGTSTP */
   1691 }
   1692 
   1693 /*
   1694  * When we get an AYT, if ^T is enabled, use that.  Otherwise,
   1695  * just send back "[Yes]".
   1696  */
   1697 	void
   1698 recv_ayt()
   1699 {
   1700 #if	defined(SIGINFO) && defined(TCSIG)
   1701 	if (slctab[SLC_AYT].sptr && *slctab[SLC_AYT].sptr != _POSIX_VDISABLE) {
   1702 		(void) ioctl(pty, TCSIG, (char *)SIGINFO);
   1703 		return;
   1704 	}
   1705 #endif
   1706 	(void) strcpy(nfrontp, "\r\n[Yes]\r\n");
   1707 	nfrontp += 9;
   1708 }
   1709 
   1710 	void
   1711 doeof()
   1712 {
   1713 	init_termbuf();
   1714 
   1715 #if	defined(LINEMODE) && defined(USE_TERMIO) && (VEOF == VMIN)
   1716 	if (!tty_isediting()) {
   1717 		extern char oldeofc;
   1718 		*pfrontp++ = oldeofc;
   1719 		return;
   1720 	}
   1721 #endif
   1722 	*pfrontp++ = slctab[SLC_EOF].sptr ?
   1723 			(unsigned char)*slctab[SLC_EOF].sptr : '\004';
   1724 }
   1725