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