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