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