Home | History | Annotate | Line # | Download | only in telnetd
telnetd.c revision 1.22
      1 /*	$NetBSD: telnetd.c,v 1.22 2000/08/18 03:25:52 itojun 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.22 2000/08/18 03:25:52 itojun 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 		extern char *line;
    926 
    927 		if ((lp = getpty()) == NULL)
    928 			fatal(net, "Out of ptys");
    929 
    930 		if ((pty = open(lp, 2)) >= 0) {
    931 			strcpy(line,lp);
    932 			line[5] = 't';
    933 			break;
    934 		}
    935 	}
    936 #endif
    937 
    938 #if	defined(_SC_CRAY_SECURE_SYS)
    939 	/*
    940 	 *	set ttyp line security label
    941 	 */
    942 	if (secflag) {
    943 		char slave_dev[16];
    944 
    945 		sprintf(tty_dev, "/dev/pty/%03d", ptynum);
    946 		if (setdevs(tty_dev, &dv) < 0)
    947 		 	fatal(net, "cannot set pty security");
    948 		sprintf(slave_dev, "/dev/ttyp%03d", ptynum);
    949 		if (setdevs(slave_dev, &dv) < 0)
    950 		 	fatal(net, "cannot set tty security");
    951 	}
    952 #endif	/* _SC_CRAY_SECURE_SYS */
    953 
    954 	/* get name of connected client */
    955 	error = getnameinfo(who, who->sa_len, remote_host_name,
    956 			    sizeof(remote_host_name), NULL, 0, 0);
    957 
    958 	if (error) {
    959 		fatal(net, "Couldn't resolve your address into a host name.\r\n\
    960 	 Please contact your net administrator");
    961 #ifdef __GNUC__
    962 		host = NULL;	/* XXX gcc */
    963 #endif
    964 	}
    965 
    966 	remote_host_name[sizeof(remote_host_name)-1] = 0;
    967 	host = remote_host_name;
    968 
    969 	(void)gethostname(host_name, sizeof (host_name));
    970 	host_name[sizeof(host_name) - 1] = '\0';
    971 	hostname = host_name;
    972 
    973 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
    974 	auth_encrypt_init(hostname, host, "TELNETD", 1);
    975 #endif
    976 
    977 	init_env();
    978 	/*
    979 	 * get terminal type.
    980 	 */
    981 	*user_name = 0;
    982 	level = getterminaltype(user_name);
    983 	setenv("TERM", terminaltype ? terminaltype : "network", 1);
    984 
    985 	/*
    986 	 * Start up the login process on the slave side of the terminal
    987 	 */
    988 #ifndef	convex
    989 	startslave(host, level, user_name);
    990 
    991 #if	defined(_SC_CRAY_SECURE_SYS)
    992 	if (secflag) {
    993 		if (setulvl(dv.dv_actlvl) < 0)
    994 			fatal(net,"cannot setulvl()");
    995 		if (setucmp(dv.dv_actcmp) < 0)
    996 			fatal(net, "cannot setucmp()");
    997 	}
    998 #endif	/* _SC_CRAY_SECURE_SYS */
    999 
   1000 	telnet(net, pty);  /* begin server processing */
   1001 #else
   1002 	telnet(net, pty, host);
   1003 #endif
   1004 	/*NOTREACHED*/
   1005 }  /* end of doit */
   1006 
   1007 #if	defined(CRAY2) && defined(UNICOS5) && defined(UNICOS50)
   1008 	int
   1009 Xterm_output(ibufp, obuf, icountp, ocount)
   1010 	char **ibufp, *obuf;
   1011 	int *icountp, ocount;
   1012 {
   1013 	int ret;
   1014 	ret = term_output(*ibufp, obuf, *icountp, ocount);
   1015 	*ibufp += *icountp;
   1016 	*icountp = 0;
   1017 	return(ret);
   1018 }
   1019 #define	term_output	Xterm_output
   1020 #endif	/* defined(CRAY2) && defined(UNICOS5) && defined(UNICOS50) */
   1021 
   1022 /*
   1023  * Main loop.  Select from pty and network, and
   1024  * hand data to telnet receiver finite state machine.
   1025  */
   1026 	void
   1027 #ifndef	convex
   1028 telnet(f, p)
   1029 #else
   1030 telnet(f, p, host)
   1031 #endif
   1032 	int f, p;
   1033 #ifdef convex
   1034 	char *host;
   1035 #endif
   1036 {
   1037 	int on = 1;
   1038 #define	TABBUFSIZ	512
   1039 	char	defent[TABBUFSIZ];
   1040 	char	defstrs[TABBUFSIZ];
   1041 #undef	TABBUFSIZ
   1042 	char *HE, *HN, *IM, *IF, *ptyibuf2ptr;
   1043 	int nfd;
   1044 
   1045 	/*
   1046 	 * Initialize the slc mapping table.
   1047 	 */
   1048 	get_slc_defaults();
   1049 
   1050 	/*
   1051 	 * Do some tests where it is desireable to wait for a response.
   1052 	 * Rather than doing them slowly, one at a time, do them all
   1053 	 * at once.
   1054 	 */
   1055 	if (my_state_is_wont(TELOPT_SGA))
   1056 		send_will(TELOPT_SGA, 1);
   1057 	/*
   1058 	 * Is the client side a 4.2 (NOT 4.3) system?  We need to know this
   1059 	 * because 4.2 clients are unable to deal with TCP urgent data.
   1060 	 *
   1061 	 * To find out, we send out a "DO ECHO".  If the remote system
   1062 	 * answers "WILL ECHO" it is probably a 4.2 client, and we note
   1063 	 * that fact ("WILL ECHO" ==> that the client will echo what
   1064 	 * WE, the server, sends it; it does NOT mean that the client will
   1065 	 * echo the terminal input).
   1066 	 */
   1067 	send_do(TELOPT_ECHO, 1);
   1068 
   1069 #ifdef	LINEMODE
   1070 	if (his_state_is_wont(TELOPT_LINEMODE)) {
   1071 		/* Query the peer for linemode support by trying to negotiate
   1072 		 * the linemode option.
   1073 		 */
   1074 		linemode = 0;
   1075 		editmode = 0;
   1076 		send_do(TELOPT_LINEMODE, 1);  /* send do linemode */
   1077 	}
   1078 #endif	/* LINEMODE */
   1079 
   1080 	/*
   1081 	 * Send along a couple of other options that we wish to negotiate.
   1082 	 */
   1083 	send_do(TELOPT_NAWS, 1);
   1084 	send_will(TELOPT_STATUS, 1);
   1085 	flowmode = 1;		/* default flow control state */
   1086 	restartany = -1;	/* uninitialized... */
   1087 	send_do(TELOPT_LFLOW, 1);
   1088 
   1089 	/*
   1090 	 * Spin, waiting for a response from the DO ECHO.  However,
   1091 	 * some REALLY DUMB telnets out there might not respond
   1092 	 * to the DO ECHO.  So, we spin looking for NAWS, (most dumb
   1093 	 * telnets so far seem to respond with WONT for a DO that
   1094 	 * they don't understand...) because by the time we get the
   1095 	 * response, it will already have processed the DO ECHO.
   1096 	 * Kludge upon kludge.
   1097 	 */
   1098 	while (his_will_wont_is_changing(TELOPT_NAWS))
   1099 		ttloop();
   1100 
   1101 	/*
   1102 	 * But...
   1103 	 * The client might have sent a WILL NAWS as part of its
   1104 	 * startup code; if so, we'll be here before we get the
   1105 	 * response to the DO ECHO.  We'll make the assumption
   1106 	 * that any implementation that understands about NAWS
   1107 	 * is a modern enough implementation that it will respond
   1108 	 * to our DO ECHO request; hence we'll do another spin
   1109 	 * waiting for the ECHO option to settle down, which is
   1110 	 * what we wanted to do in the first place...
   1111 	 */
   1112 	if (his_want_state_is_will(TELOPT_ECHO) &&
   1113 	    his_state_is_will(TELOPT_NAWS)) {
   1114 		while (his_will_wont_is_changing(TELOPT_ECHO))
   1115 			ttloop();
   1116 	}
   1117 	/*
   1118 	 * On the off chance that the telnet client is broken and does not
   1119 	 * respond to the DO ECHO we sent, (after all, we did send the
   1120 	 * DO NAWS negotiation after the DO ECHO, and we won't get here
   1121 	 * until a response to the DO NAWS comes back) simulate the
   1122 	 * receipt of a will echo.  This will also send a WONT ECHO
   1123 	 * to the client, since we assume that the client failed to
   1124 	 * respond because it believes that it is already in DO ECHO
   1125 	 * mode, which we do not want.
   1126 	 */
   1127 	if (his_want_state_is_will(TELOPT_ECHO)) {
   1128 		DIAG(TD_OPTIONS,
   1129 			{sprintf(nfrontp, "td: simulating recv\r\n");
   1130 			 nfrontp += strlen(nfrontp);});
   1131 		willoption(TELOPT_ECHO);
   1132 	}
   1133 
   1134 	/*
   1135 	 * Finally, to clean things up, we turn on our echo.  This
   1136 	 * will break stupid 4.2 telnets out of local terminal echo.
   1137 	 */
   1138 
   1139 	if (my_state_is_wont(TELOPT_ECHO))
   1140 		send_will(TELOPT_ECHO, 1);
   1141 
   1142 #ifndef	STREAMSPTY
   1143 	/*
   1144 	 * Turn on packet mode
   1145 	 */
   1146 	(void) ioctl(p, TIOCPKT, (char *)&on);
   1147 #endif
   1148 
   1149 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
   1150 	/*
   1151 	 * Continuing line mode support.  If client does not support
   1152 	 * real linemode, attempt to negotiate kludge linemode by sending
   1153 	 * the do timing mark sequence.
   1154 	 */
   1155 	if (lmodetype < REAL_LINEMODE)
   1156 		send_do(TELOPT_TM, 1);
   1157 #endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
   1158 
   1159 	/*
   1160 	 * Call telrcv() once to pick up anything received during
   1161 	 * terminal type negotiation, 4.2/4.3 determination, and
   1162 	 * linemode negotiation.
   1163 	 */
   1164 	telrcv();
   1165 
   1166 	(void) ioctl(f, FIONBIO, (char *)&on);
   1167 	(void) ioctl(p, FIONBIO, (char *)&on);
   1168 #if	defined(CRAY2) && defined(UNICOS5)
   1169 	init_termdriver(f, p, interrupt, sendbrk);
   1170 #endif
   1171 
   1172 #if	defined(SO_OOBINLINE)
   1173 	(void) setsockopt(net, SOL_SOCKET, SO_OOBINLINE,
   1174 				(char *)&on, sizeof on);
   1175 #endif	/* defined(SO_OOBINLINE) */
   1176 
   1177 #ifdef	SIGTSTP
   1178 	(void) signal(SIGTSTP, SIG_IGN);
   1179 #endif
   1180 #ifdef	SIGTTOU
   1181 	/*
   1182 	 * Ignoring SIGTTOU keeps the kernel from blocking us
   1183 	 * in ttioct() in /sys/tty.c.
   1184 	 */
   1185 	(void) signal(SIGTTOU, SIG_IGN);
   1186 #endif
   1187 
   1188 	(void) signal(SIGCHLD, cleanup);
   1189 
   1190 #if	defined(CRAY2) && defined(UNICOS5)
   1191 	/*
   1192 	 * Cray-2 will send a signal when pty modes are changed by slave
   1193 	 * side.  Set up signal handler now.
   1194 	 */
   1195 	if ((int)signal(SIGUSR1, termstat) < 0)
   1196 		perror("signal");
   1197 	else if (ioctl(p, TCSIGME, (char *)SIGUSR1) < 0)
   1198 		perror("ioctl:TCSIGME");
   1199 	/*
   1200 	 * Make processing loop check terminal characteristics early on.
   1201 	 */
   1202 	termstat();
   1203 #endif
   1204 
   1205 #ifdef  TIOCNOTTY
   1206 	{
   1207 		register int t;
   1208 		t = open(_PATH_TTY, O_RDWR);
   1209 		if (t >= 0) {
   1210 			(void) ioctl(t, TIOCNOTTY, (char *)0);
   1211 			(void) close(t);
   1212 		}
   1213 	}
   1214 #endif
   1215 
   1216 #if	defined(CRAY) && defined(NEWINIT) && defined(TIOCSCTTY)
   1217 	(void) setsid();
   1218 	ioctl(p, TIOCSCTTY, 0);
   1219 #endif
   1220 
   1221 	/*
   1222 	 * Show banner that getty never gave.
   1223 	 *
   1224 	 * We put the banner in the pty input buffer.  This way, it
   1225 	 * gets carriage return null processing, etc., just like all
   1226 	 * other pty --> client data.
   1227 	 */
   1228 
   1229 #if	!defined(CRAY) || !defined(NEWINIT)
   1230 	if (getenv("USER"))
   1231 		hostinfo = 0;
   1232 #endif
   1233 
   1234 	if (getent(defent, gettyname) == 1) {
   1235 		char *cp=defstrs;
   1236 
   1237 		HE = getstr("he", &cp);
   1238 		HN = getstr("hn", &cp);
   1239 		IM = getstr("im", &cp);
   1240 		IF = getstr("if", &cp);
   1241 		if (HN && *HN)
   1242 			(void) strcpy(host_name, HN);
   1243 		if (IM == 0)
   1244 			IM = "";
   1245 	} else {
   1246 		IM = DEFAULT_IM;
   1247 		HE = 0;
   1248 	}
   1249 	edithost(HE, host_name);
   1250 	ptyibuf2ptr = ptyibuf2;
   1251 	if (hostinfo) {
   1252 		if (IF)	{
   1253 			char buf[_POSIX2_LINE_MAX];
   1254 			FILE *fd;
   1255 
   1256 			if ((fd = fopen(IF, "r")) != NULL) {
   1257 				while (fgets(buf, sizeof(buf) - 1, fd) != NULL)
   1258 					ptyibuf2ptr = putf(buf, ptyibuf2ptr);
   1259 				fclose(fd);
   1260 			}
   1261 		}
   1262 		if (*IM)
   1263 			ptyibuf2ptr = putf(IM, ptyibuf2ptr);
   1264 	}
   1265 
   1266 	if (pcc)
   1267 		strncpy(ptyibuf2ptr, ptyip, pcc+1);
   1268 	ptyip = ptyibuf2;
   1269 	pcc = strlen(ptyip);
   1270 #ifdef	LINEMODE
   1271 	/*
   1272 	 * Last check to make sure all our states are correct.
   1273 	 */
   1274 	init_termbuf();
   1275 	localstat();
   1276 #endif	/* LINEMODE */
   1277 
   1278 	DIAG(TD_REPORT,
   1279 		{sprintf(nfrontp, "td: Entering processing loop\r\n");
   1280 		 nfrontp += strlen(nfrontp);});
   1281 
   1282 #ifdef	convex
   1283 	startslave(host);
   1284 #endif
   1285 
   1286 	nfd = ((f > p) ? f : p) + 1;
   1287 	for (;;) {
   1288 		fd_set ibits, obits, xbits;
   1289 		register int c;
   1290 
   1291 		if (ncc < 0 && pcc < 0)
   1292 			break;
   1293 
   1294 #if	defined(CRAY2) && defined(UNICOS5)
   1295 		if (needtermstat)
   1296 			_termstat();
   1297 #endif	/* defined(CRAY2) && defined(UNICOS5) */
   1298 		FD_ZERO(&ibits);
   1299 		FD_ZERO(&obits);
   1300 		FD_ZERO(&xbits);
   1301 		/*
   1302 		 * Never look for input if there's still
   1303 		 * stuff in the corresponding output buffer
   1304 		 */
   1305 		if (nfrontp - nbackp || pcc > 0) {
   1306 			FD_SET(f, &obits);
   1307 		} else {
   1308 			FD_SET(p, &ibits);
   1309 		}
   1310 		if (pfrontp - pbackp || ncc > 0) {
   1311 			FD_SET(p, &obits);
   1312 		} else {
   1313 			FD_SET(f, &ibits);
   1314 		}
   1315 		if (!SYNCHing) {
   1316 			FD_SET(f, &xbits);
   1317 		}
   1318 		if ((c = select(nfd, &ibits, &obits, &xbits,
   1319 						(struct timeval *)0)) < 1) {
   1320 			if (c == -1) {
   1321 				if (errno == EINTR) {
   1322 					continue;
   1323 				}
   1324 			}
   1325 			sleep(5);
   1326 			continue;
   1327 		}
   1328 
   1329 		/*
   1330 		 * Any urgent data?
   1331 		 */
   1332 		if (FD_ISSET(net, &xbits)) {
   1333 		    SYNCHing = 1;
   1334 		}
   1335 
   1336 		/*
   1337 		 * Something to read from the network...
   1338 		 */
   1339 		if (FD_ISSET(net, &ibits)) {
   1340 #if	!defined(SO_OOBINLINE)
   1341 			/*
   1342 			 * In 4.2 (and 4.3 beta) systems, the
   1343 			 * OOB indication and data handling in the kernel
   1344 			 * is such that if two separate TCP Urgent requests
   1345 			 * come in, one byte of TCP data will be overlaid.
   1346 			 * This is fatal for Telnet, but we try to live
   1347 			 * with it.
   1348 			 *
   1349 			 * In addition, in 4.2 (and...), a special protocol
   1350 			 * is needed to pick up the TCP Urgent data in
   1351 			 * the correct sequence.
   1352 			 *
   1353 			 * What we do is:  if we think we are in urgent
   1354 			 * mode, we look to see if we are "at the mark".
   1355 			 * If we are, we do an OOB receive.  If we run
   1356 			 * this twice, we will do the OOB receive twice,
   1357 			 * but the second will fail, since the second
   1358 			 * time we were "at the mark", but there wasn't
   1359 			 * any data there (the kernel doesn't reset
   1360 			 * "at the mark" until we do a normal read).
   1361 			 * Once we've read the OOB data, we go ahead
   1362 			 * and do normal reads.
   1363 			 *
   1364 			 * There is also another problem, which is that
   1365 			 * since the OOB byte we read doesn't put us
   1366 			 * out of OOB state, and since that byte is most
   1367 			 * likely the TELNET DM (data mark), we would
   1368 			 * stay in the TELNET SYNCH (SYNCHing) state.
   1369 			 * So, clocks to the rescue.  If we've "just"
   1370 			 * received a DM, then we test for the
   1371 			 * presence of OOB data when the receive OOB
   1372 			 * fails (and AFTER we did the normal mode read
   1373 			 * to clear "at the mark").
   1374 			 */
   1375 		    if (SYNCHing) {
   1376 			int atmark;
   1377 
   1378 			(void) ioctl(net, SIOCATMARK, (char *)&atmark);
   1379 			if (atmark) {
   1380 			    ncc = recv(net, netibuf, sizeof (netibuf), MSG_OOB);
   1381 			    if ((ncc == -1) && (errno == EINVAL)) {
   1382 				ncc = read(net, netibuf, sizeof (netibuf));
   1383 				if (sequenceIs(didnetreceive, gotDM)) {
   1384 				    SYNCHing = stilloob(net);
   1385 				}
   1386 			    }
   1387 			} else {
   1388 			    ncc = read(net, netibuf, sizeof (netibuf));
   1389 			}
   1390 		    } else {
   1391 			ncc = read(net, netibuf, sizeof (netibuf));
   1392 		    }
   1393 		    settimer(didnetreceive);
   1394 #else	/* !defined(SO_OOBINLINE)) */
   1395 		    ncc = read(net, netibuf, sizeof (netibuf));
   1396 #endif	/* !defined(SO_OOBINLINE)) */
   1397 		    if (ncc < 0 && errno == EWOULDBLOCK)
   1398 			ncc = 0;
   1399 		    else {
   1400 			if (ncc <= 0) {
   1401 			    break;
   1402 			}
   1403 			netip = netibuf;
   1404 		    }
   1405 		    DIAG((TD_REPORT | TD_NETDATA),
   1406 			    {sprintf(nfrontp, "td: netread %d chars\r\n", ncc);
   1407 			     nfrontp += strlen(nfrontp);});
   1408 		    DIAG(TD_NETDATA, printdata("nd", netip, ncc));
   1409 		}
   1410 
   1411 		/*
   1412 		 * Something to read from the pty...
   1413 		 */
   1414 		if (FD_ISSET(p, &ibits)) {
   1415 #ifndef	STREAMSPTY
   1416 			pcc = read(p, ptyibuf, BUFSIZ);
   1417 #else
   1418 			pcc = readstream(p, ptyibuf, BUFSIZ);
   1419 #endif
   1420 			/*
   1421 			 * On some systems, if we try to read something
   1422 			 * off the master side before the slave side is
   1423 			 * opened, we get EIO.
   1424 			 */
   1425 			if (pcc < 0 && (errno == EWOULDBLOCK ||
   1426 #ifdef	EAGAIN
   1427 					errno == EAGAIN ||
   1428 #endif
   1429 					errno == EIO)) {
   1430 				pcc = 0;
   1431 			} else {
   1432 				if (pcc <= 0)
   1433 					break;
   1434 #if	!defined(CRAY2) || !defined(UNICOS5)
   1435 #ifdef	LINEMODE
   1436 				/*
   1437 				 * If ioctl from pty, pass it through net
   1438 				 */
   1439 				if (ptyibuf[0] & TIOCPKT_IOCTL) {
   1440 					copy_termbuf(ptyibuf+1, pcc-1);
   1441 					localstat();
   1442 					pcc = 1;
   1443 				}
   1444 #endif	/* LINEMODE */
   1445 				if (ptyibuf[0] & TIOCPKT_FLUSHWRITE) {
   1446 					netclear();	/* clear buffer back */
   1447 #ifndef	NO_URGENT
   1448 					/*
   1449 					 * There are client telnets on some
   1450 					 * operating systems get screwed up
   1451 					 * royally if we send them urgent
   1452 					 * mode data.
   1453 					 */
   1454 					*nfrontp++ = IAC;
   1455 					*nfrontp++ = DM;
   1456 					neturg = nfrontp-1; /* off by one XXX */
   1457 					DIAG(TD_OPTIONS,
   1458 					    printoption("td: send IAC", DM));
   1459 
   1460 #endif
   1461 				}
   1462 				if (his_state_is_will(TELOPT_LFLOW) &&
   1463 				    (ptyibuf[0] &
   1464 				     (TIOCPKT_NOSTOP|TIOCPKT_DOSTOP))) {
   1465 					int newflow =
   1466 					    ptyibuf[0] & TIOCPKT_DOSTOP ? 1 : 0;
   1467 					if (newflow != flowmode) {
   1468 						flowmode = newflow;
   1469 						(void) sprintf(nfrontp,
   1470 							"%c%c%c%c%c%c",
   1471 							IAC, SB, TELOPT_LFLOW,
   1472 							flowmode ? LFLOW_ON
   1473 								 : LFLOW_OFF,
   1474 							IAC, SE);
   1475 						nfrontp += 6;
   1476 						DIAG(TD_OPTIONS, printsub('>',
   1477 						    (unsigned char *)nfrontp-4,
   1478 						    4););
   1479 					}
   1480 				}
   1481 				pcc--;
   1482 				ptyip = ptyibuf+1;
   1483 #else	/* defined(CRAY2) && defined(UNICOS5) */
   1484 				if (!uselinemode) {
   1485 					unpcc = pcc;
   1486 					unptyip = ptyibuf;
   1487 					pcc = term_output(&unptyip, ptyibuf2,
   1488 								&unpcc, BUFSIZ);
   1489 					ptyip = ptyibuf2;
   1490 				} else
   1491 					ptyip = ptyibuf;
   1492 #endif	/* defined(CRAY2) && defined(UNICOS5) */
   1493 			}
   1494 		}
   1495 
   1496 		while (pcc > 0) {
   1497 			if ((&netobuf[BUFSIZ] - nfrontp) < 2)
   1498 				break;
   1499 			c = *ptyip++ & 0377, pcc--;
   1500 			if (c == IAC)
   1501 				*nfrontp++ = c;
   1502 #if	defined(CRAY2) && defined(UNICOS5)
   1503 			else if (c == '\n' &&
   1504 				     my_state_is_wont(TELOPT_BINARY) && newmap)
   1505 				*nfrontp++ = '\r';
   1506 #endif	/* defined(CRAY2) && defined(UNICOS5) */
   1507 			*nfrontp++ = c;
   1508 			if ((c == '\r') && (my_state_is_wont(TELOPT_BINARY))) {
   1509 				if (pcc > 0 && ((*ptyip & 0377) == '\n')) {
   1510 					*nfrontp++ = *ptyip++ & 0377;
   1511 					pcc--;
   1512 				} else
   1513 					*nfrontp++ = '\0';
   1514 			}
   1515 		}
   1516 #if	defined(CRAY2) && defined(UNICOS5)
   1517 		/*
   1518 		 * If chars were left over from the terminal driver,
   1519 		 * note their existence.
   1520 		 */
   1521 		if (!uselinemode && unpcc) {
   1522 			pcc = unpcc;
   1523 			unpcc = 0;
   1524 			ptyip = unptyip;
   1525 		}
   1526 #endif	/* defined(CRAY2) && defined(UNICOS5) */
   1527 
   1528 		if (FD_ISSET(f, &obits) && (nfrontp - nbackp) > 0)
   1529 			netflush();
   1530 		if (ncc > 0)
   1531 			telrcv();
   1532 		if (FD_ISSET(p, &obits) && (pfrontp - pbackp) > 0)
   1533 			ptyflush();
   1534 	}
   1535 	cleanup(0);
   1536 }  /* end of telnet */
   1537 
   1538 #ifndef	TCSIG
   1539 # ifdef	TIOCSIG
   1540 #  define TCSIG TIOCSIG
   1541 # endif
   1542 #endif
   1543 
   1544 #ifdef	STREAMSPTY
   1545 
   1546 int flowison = -1;  /* current state of flow: -1 is unknown */
   1547 
   1548 int readstream(p, ibuf, bufsize)
   1549 	int p;
   1550 	char *ibuf;
   1551 	int bufsize;
   1552 {
   1553 	int flags = 0;
   1554 	int ret = 0;
   1555 	struct termios *tsp;
   1556 	struct termio *tp;
   1557 	struct iocblk *ip;
   1558 	char vstop, vstart;
   1559 	int ixon;
   1560 	int newflow;
   1561 
   1562 	strbufc.maxlen = BUFSIZ;
   1563 	strbufc.buf = (char *)ctlbuf;
   1564 	strbufd.maxlen = bufsize-1;
   1565 	strbufd.len = 0;
   1566 	strbufd.buf = ibuf+1;
   1567 	ibuf[0] = 0;
   1568 
   1569 	ret = getmsg(p, &strbufc, &strbufd, &flags);
   1570 	if (ret < 0)  /* error of some sort -- probably EAGAIN */
   1571 		return(-1);
   1572 
   1573 	if (strbufc.len <= 0 || ctlbuf[0] == M_DATA) {
   1574 		/* data message */
   1575 		if (strbufd.len > 0) {			/* real data */
   1576 			return(strbufd.len + 1);	/* count header char */
   1577 		} else {
   1578 			/* nothing there */
   1579 			errno = EAGAIN;
   1580 			return(-1);
   1581 		}
   1582 	}
   1583 
   1584 	/*
   1585 	 * It's a control message.  Return 1, to look at the flag we set
   1586 	 */
   1587 
   1588 	switch (ctlbuf[0]) {
   1589 	case M_FLUSH:
   1590 		if (ibuf[1] & FLUSHW)
   1591 			ibuf[0] = TIOCPKT_FLUSHWRITE;
   1592 		return(1);
   1593 
   1594 	case M_IOCTL:
   1595 		ip = (struct iocblk *) (ibuf+1);
   1596 
   1597 		switch (ip->ioc_cmd) {
   1598 		case TCSETS:
   1599 		case TCSETSW:
   1600 		case TCSETSF:
   1601 			tsp = (struct termios *)
   1602 					(ibuf+1 + sizeof(struct iocblk));
   1603 			vstop = tsp->c_cc[VSTOP];
   1604 			vstart = tsp->c_cc[VSTART];
   1605 			ixon = tsp->c_iflag & IXON;
   1606 			break;
   1607 		case TCSETA:
   1608 		case TCSETAW:
   1609 		case TCSETAF:
   1610 			tp = (struct termio *) (ibuf+1 + sizeof(struct iocblk));
   1611 			vstop = tp->c_cc[VSTOP];
   1612 			vstart = tp->c_cc[VSTART];
   1613 			ixon = tp->c_iflag & IXON;
   1614 			break;
   1615 		default:
   1616 			errno = EAGAIN;
   1617 			return(-1);
   1618 		}
   1619 
   1620 		newflow =  (ixon && (vstart == 021) && (vstop == 023)) ? 1 : 0;
   1621 		if (newflow != flowison) {  /* it's a change */
   1622 			flowison = newflow;
   1623 			ibuf[0] = newflow ? TIOCPKT_DOSTOP : TIOCPKT_NOSTOP;
   1624 			return(1);
   1625 		}
   1626 	}
   1627 
   1628 	/* nothing worth doing anything about */
   1629 	errno = EAGAIN;
   1630 	return(-1);
   1631 }
   1632 #endif /* STREAMSPTY */
   1633 
   1634 /*
   1635  * Send interrupt to process on other side of pty.
   1636  * If it is in raw mode, just write NULL;
   1637  * otherwise, write intr char.
   1638  */
   1639 	void
   1640 interrupt()
   1641 {
   1642 	ptyflush();	/* half-hearted */
   1643 
   1644 #if defined(STREAMSPTY) && defined(TIOCSIGNAL)
   1645 	/* Streams PTY style ioctl to post a signal */
   1646 	{
   1647 		int sig = SIGINT;
   1648 		(void) ioctl(pty, TIOCSIGNAL, &sig);
   1649 		(void) ioctl(pty, I_FLUSH, FLUSHR);
   1650 	}
   1651 #else
   1652 #ifdef	TCSIG
   1653 	(void) ioctl(pty, TCSIG, (char *)SIGINT);
   1654 #else	/* TCSIG */
   1655 	init_termbuf();
   1656 	*pfrontp++ = slctab[SLC_IP].sptr ?
   1657 			(unsigned char)*slctab[SLC_IP].sptr : '\177';
   1658 #endif	/* TCSIG */
   1659 #endif
   1660 }
   1661 
   1662 /*
   1663  * Send quit to process on other side of pty.
   1664  * If it is in raw mode, just write NULL;
   1665  * otherwise, write quit char.
   1666  */
   1667 	void
   1668 sendbrk()
   1669 {
   1670 	ptyflush();	/* half-hearted */
   1671 #ifdef	TCSIG
   1672 	(void) ioctl(pty, TCSIG, (char *)SIGQUIT);
   1673 #else	/* TCSIG */
   1674 	init_termbuf();
   1675 	*pfrontp++ = slctab[SLC_ABORT].sptr ?
   1676 			(unsigned char)*slctab[SLC_ABORT].sptr : '\034';
   1677 #endif	/* TCSIG */
   1678 }
   1679 
   1680 	void
   1681 sendsusp()
   1682 {
   1683 #ifdef	SIGTSTP
   1684 	ptyflush();	/* half-hearted */
   1685 # ifdef	TCSIG
   1686 	(void) ioctl(pty, TCSIG, (char *)SIGTSTP);
   1687 # else	/* TCSIG */
   1688 	*pfrontp++ = slctab[SLC_SUSP].sptr ?
   1689 			(unsigned char)*slctab[SLC_SUSP].sptr : '\032';
   1690 # endif	/* TCSIG */
   1691 #endif	/* SIGTSTP */
   1692 }
   1693 
   1694 /*
   1695  * When we get an AYT, if ^T is enabled, use that.  Otherwise,
   1696  * just send back "[Yes]".
   1697  */
   1698 	void
   1699 recv_ayt()
   1700 {
   1701 #if	defined(SIGINFO) && defined(TCSIG)
   1702 	if (slctab[SLC_AYT].sptr && *slctab[SLC_AYT].sptr != _POSIX_VDISABLE) {
   1703 		(void) ioctl(pty, TCSIG, (char *)SIGINFO);
   1704 		return;
   1705 	}
   1706 #endif
   1707 	(void) strcpy(nfrontp, "\r\n[Yes]\r\n");
   1708 	nfrontp += 9;
   1709 }
   1710 
   1711 	void
   1712 doeof()
   1713 {
   1714 	init_termbuf();
   1715 
   1716 #if	defined(LINEMODE) && defined(USE_TERMIO) && (VEOF == VMIN)
   1717 	if (!tty_isediting()) {
   1718 		extern char oldeofc;
   1719 		*pfrontp++ = oldeofc;
   1720 		return;
   1721 	}
   1722 #endif
   1723 	*pfrontp++ = slctab[SLC_EOF].sptr ?
   1724 			(unsigned char)*slctab[SLC_EOF].sptr : '\004';
   1725 }
   1726