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