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