xref: /original-bsd/libexec/telnetd/telnetd.c (revision de436421)
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.4 (Berkeley) 05/30/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 
main(argc,argv)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 		memset((char *)&dv, 0, 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
usage()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
getterminaltype(name)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 	memmove(nfrontp, sb, sizeof sb);
615 	nfrontp += sizeof sb;
616 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
617     }
618     if (his_state_is_will(TELOPT_XDISPLOC)) {
619 	static unsigned char sb[] =
620 			{ IAC, SB, TELOPT_XDISPLOC, TELQUAL_SEND, IAC, SE };
621 
622 	memmove(nfrontp, sb, sizeof sb);
623 	nfrontp += sizeof sb;
624 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
625     }
626     if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
627 	static unsigned char sb[] =
628 			{ IAC, SB, TELOPT_NEW_ENVIRON, TELQUAL_SEND, IAC, SE };
629 
630 	memmove(nfrontp, sb, sizeof sb);
631 	nfrontp += sizeof sb;
632 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
633     }
634     else if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
635 	static unsigned char sb[] =
636 			{ IAC, SB, TELOPT_OLD_ENVIRON, TELQUAL_SEND, IAC, SE };
637 
638 	memmove(nfrontp, sb, sizeof sb);
639 	nfrontp += sizeof sb;
640 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
641     }
642     if (his_state_is_will(TELOPT_TTYPE)) {
643 
644 	memmove(nfrontp, ttytype_sbbuf, sizeof ttytype_sbbuf);
645 	nfrontp += sizeof ttytype_sbbuf;
646 	DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
647 					sizeof ttytype_sbbuf - 2););
648     }
649     if (his_state_is_will(TELOPT_TSPEED)) {
650 	while (sequenceIs(tspeedsubopt, baseline))
651 	    ttloop();
652     }
653     if (his_state_is_will(TELOPT_XDISPLOC)) {
654 	while (sequenceIs(xdisplocsubopt, baseline))
655 	    ttloop();
656     }
657     if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
658 	while (sequenceIs(environsubopt, baseline))
659 	    ttloop();
660     }
661     if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
662 	while (sequenceIs(oenvironsubopt, baseline))
663 	    ttloop();
664     }
665     if (his_state_is_will(TELOPT_TTYPE)) {
666 	char first[256], last[256];
667 
668 	while (sequenceIs(ttypesubopt, baseline))
669 	    ttloop();
670 
671 	/*
672 	 * If the other side has already disabled the option, then
673 	 * we have to just go with what we (might) have already gotten.
674 	 */
675 	if (his_state_is_will(TELOPT_TTYPE) && !terminaltypeok(terminaltype)) {
676 	    (void) strncpy(first, terminaltype, sizeof(first));
677 	    for(;;) {
678 		/*
679 		 * Save the unknown name, and request the next name.
680 		 */
681 		(void) strncpy(last, terminaltype, sizeof(last));
682 		_gettermname();
683 		if (terminaltypeok(terminaltype))
684 		    break;
685 		if ((strncmp(last, terminaltype, sizeof(last)) == 0) ||
686 		    his_state_is_wont(TELOPT_TTYPE)) {
687 		    /*
688 		     * We've hit the end.  If this is the same as
689 		     * the first name, just go with it.
690 		     */
691 		    if (strncmp(first, terminaltype, sizeof(first)) == 0)
692 			break;
693 		    /*
694 		     * Get the terminal name one more time, so that
695 		     * RFC1091 compliant telnets will cycle back to
696 		     * the start of the list.
697 		     */
698 		     _gettermname();
699 		    if (strncmp(first, terminaltype, sizeof(first)) != 0)
700 			(void) strncpy(terminaltype, first, sizeof(first));
701 		    break;
702 		}
703 	    }
704 	}
705     }
706     return(retval);
707 }  /* end of getterminaltype */
708 
709     void
_gettermname()710 _gettermname()
711 {
712     /*
713      * If the client turned off the option,
714      * we can't send another request, so we
715      * just return.
716      */
717     if (his_state_is_wont(TELOPT_TTYPE))
718 	return;
719     settimer(baseline);
720     memmove(nfrontp, ttytype_sbbuf, sizeof ttytype_sbbuf);
721     nfrontp += sizeof ttytype_sbbuf;
722     DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
723 					sizeof ttytype_sbbuf - 2););
724     while (sequenceIs(ttypesubopt, baseline))
725 	ttloop();
726 }
727 
728     int
terminaltypeok(s)729 terminaltypeok(s)
730     char *s;
731 {
732     char buf[1024];
733 
734     if (terminaltype == NULL)
735 	return(1);
736 
737     /*
738      * tgetent() will return 1 if the type is known, and
739      * 0 if it is not known.  If it returns -1, it couldn't
740      * open the database.  But if we can't open the database,
741      * it won't help to say we failed, because we won't be
742      * able to verify anything else.  So, we treat -1 like 1.
743      */
744     if (tgetent(buf, s) == 0)
745 	return(0);
746     return(1);
747 }
748 
749 #ifndef	MAXHOSTNAMELEN
750 #define	MAXHOSTNAMELEN 64
751 #endif	/* MAXHOSTNAMELEN */
752 
753 char *hostname;
754 char host_name[MAXHOSTNAMELEN];
755 char remote_host_name[MAXHOSTNAMELEN];
756 
757 #ifndef	convex
758 extern void telnet P((int, int));
759 #else
760 extern void telnet P((int, int, char *));
761 #endif
762 
763 /*
764  * Get a pty, scan input lines.
765  */
766 doit(who)
767 	struct sockaddr_in *who;
768 {
769 	char *host, *inet_ntoa();
770 	int t;
771 	struct hostent *hp;
772 	int level;
773 	int ptynum;
774 	char user_name[256];
775 
776 	/*
777 	 * Find an available pty to use.
778 	 */
779 #ifndef	convex
780 	pty = getpty(&ptynum);
781 	if (pty < 0)
782 		fatal(net, "All network ports in use");
783 #else
784 	for (;;) {
785 		char *lp;
786 		extern char *line, *getpty();
787 
788 		if ((lp = getpty()) == NULL)
789 			fatal(net, "Out of ptys");
790 
791 		if ((pty = open(lp, 2)) >= 0) {
792 			strcpy(line,lp);
793 			line[5] = 't';
794 			break;
795 		}
796 	}
797 #endif
798 
799 #if	defined(_SC_CRAY_SECURE_SYS)
800 	/*
801 	 *	set ttyp line security label
802 	 */
803 	if (secflag) {
804 		char slave_dev[16];
805 
806 		sprintf(tty_dev, "/dev/pty/%03d", ptynum);
807 		if (setdevs(tty_dev, &dv) < 0)
808 		 	fatal(net, "cannot set pty security");
809 		sprintf(slave_dev, "/dev/ttyp%03d", ptynum);
810 		if (setdevs(slave_dev, &dv) < 0)
811 		 	fatal(net, "cannot set tty security");
812 	}
813 #endif	/* _SC_CRAY_SECURE_SYS */
814 
815 	/* get name of connected client */
816 	hp = gethostbyaddr((char *)&who->sin_addr, sizeof (struct in_addr),
817 		who->sin_family);
818 
819 	if (hp == NULL && registerd_host_only) {
820 		fatal(net, "Couldn't resolve your address into a host name.\r\n\
821 	 Please contact your net administrator");
822 	} else if (hp &&
823 	    (strlen(hp->h_name) <= (unsigned int)((utmp_len < 0) ? -utmp_len
824 								 : utmp_len))) {
825 		host = hp->h_name;
826 	} else {
827 		host = inet_ntoa(who->sin_addr);
828 	}
829 	/*
830 	 * We must make a copy because Kerberos is probably going
831 	 * to also do a gethost* and overwrite the static data...
832 	 */
833 	strncpy(remote_host_name, host, sizeof(remote_host_name)-1);
834 	remote_host_name[sizeof(remote_host_name)-1] = 0;
835 	host = remote_host_name;
836 
837 	(void) gethostname(host_name, sizeof (host_name));
838 	hostname = host_name;
839 
840 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
841 	auth_encrypt_init(hostname, host, "TELNETD", 1);
842 #endif
843 
844 	init_env();
845 	/*
846 	 * get terminal type.
847 	 */
848 	*user_name = 0;
849 	level = getterminaltype(user_name);
850 	setenv("TERM", terminaltype ? terminaltype : "network", 1);
851 
852 	/*
853 	 * Start up the login process on the slave side of the terminal
854 	 */
855 #ifndef	convex
856 	startslave(host, level, user_name);
857 
858 #if	defined(_SC_CRAY_SECURE_SYS)
859 	if (secflag) {
860 		if (setulvl(dv.dv_actlvl) < 0)
861 			fatal(net,"cannot setulvl()");
862 		if (setucmp(dv.dv_actcmp) < 0)
863 			fatal(net, "cannot setucmp()");
864 	}
865 #endif	/* _SC_CRAY_SECURE_SYS */
866 
867 	telnet(net, pty);  /* begin server processing */
868 #else
869 	telnet(net, pty, host);
870 #endif
871 	/*NOTREACHED*/
872 }  /* end of doit */
873 
874 #if	defined(CRAY2) && defined(UNICOS5) && defined(UNICOS50)
875 	int
Xterm_output(ibufp,obuf,icountp,ocount)876 Xterm_output(ibufp, obuf, icountp, ocount)
877 	char **ibufp, *obuf;
878 	int *icountp, ocount;
879 {
880 	int ret;
881 	ret = term_output(*ibufp, obuf, *icountp, ocount);
882 	*ibufp += *icountp;
883 	*icountp = 0;
884 	return(ret);
885 }
886 #define	term_output	Xterm_output
887 #endif	/* defined(CRAY2) && defined(UNICOS5) && defined(UNICOS50) */
888 
889 /*
890  * Main loop.  Select from pty and network, and
891  * hand data to telnet receiver finite state machine.
892  */
893 	void
894 #ifndef	convex
telnet(f,p)895 telnet(f, p)
896 #else
897 telnet(f, p, host)
898 #endif
899 	int f, p;
900 #ifdef convex
901 	char *host;
902 #endif
903 {
904 	int on = 1;
905 #define	TABBUFSIZ	512
906 	char	defent[TABBUFSIZ];
907 	char	defstrs[TABBUFSIZ];
908 #undef	TABBUFSIZ
909 	char *HE;
910 	char *HN;
911 	char *IM;
912 	void netflush();
913 	int nfd;
914 
915 	/*
916 	 * Initialize the slc mapping table.
917 	 */
918 	get_slc_defaults();
919 
920 	/*
921 	 * Do some tests where it is desireable to wait for a response.
922 	 * Rather than doing them slowly, one at a time, do them all
923 	 * at once.
924 	 */
925 	if (my_state_is_wont(TELOPT_SGA))
926 		send_will(TELOPT_SGA, 1);
927 	/*
928 	 * Is the client side a 4.2 (NOT 4.3) system?  We need to know this
929 	 * because 4.2 clients are unable to deal with TCP urgent data.
930 	 *
931 	 * To find out, we send out a "DO ECHO".  If the remote system
932 	 * answers "WILL ECHO" it is probably a 4.2 client, and we note
933 	 * that fact ("WILL ECHO" ==> that the client will echo what
934 	 * WE, the server, sends it; it does NOT mean that the client will
935 	 * echo the terminal input).
936 	 */
937 	send_do(TELOPT_ECHO, 1);
938 
939 #ifdef	LINEMODE
940 	if (his_state_is_wont(TELOPT_LINEMODE)) {
941 		/* Query the peer for linemode support by trying to negotiate
942 		 * the linemode option.
943 		 */
944 		linemode = 0;
945 		editmode = 0;
946 		send_do(TELOPT_LINEMODE, 1);  /* send do linemode */
947 	}
948 #endif	/* LINEMODE */
949 
950 	/*
951 	 * Send along a couple of other options that we wish to negotiate.
952 	 */
953 	send_do(TELOPT_NAWS, 1);
954 	send_will(TELOPT_STATUS, 1);
955 	flowmode = 1;		/* default flow control state */
956 	restartany = -1;	/* uninitialized... */
957 	send_do(TELOPT_LFLOW, 1);
958 
959 	/*
960 	 * Spin, waiting for a response from the DO ECHO.  However,
961 	 * some REALLY DUMB telnets out there might not respond
962 	 * to the DO ECHO.  So, we spin looking for NAWS, (most dumb
963 	 * telnets so far seem to respond with WONT for a DO that
964 	 * they don't understand...) because by the time we get the
965 	 * response, it will already have processed the DO ECHO.
966 	 * Kludge upon kludge.
967 	 */
968 	while (his_will_wont_is_changing(TELOPT_NAWS))
969 		ttloop();
970 
971 	/*
972 	 * But...
973 	 * The client might have sent a WILL NAWS as part of its
974 	 * startup code; if so, we'll be here before we get the
975 	 * response to the DO ECHO.  We'll make the assumption
976 	 * that any implementation that understands about NAWS
977 	 * is a modern enough implementation that it will respond
978 	 * to our DO ECHO request; hence we'll do another spin
979 	 * waiting for the ECHO option to settle down, which is
980 	 * what we wanted to do in the first place...
981 	 */
982 	if (his_want_state_is_will(TELOPT_ECHO) &&
983 	    his_state_is_will(TELOPT_NAWS)) {
984 		while (his_will_wont_is_changing(TELOPT_ECHO))
985 			ttloop();
986 	}
987 	/*
988 	 * On the off chance that the telnet client is broken and does not
989 	 * respond to the DO ECHO we sent, (after all, we did send the
990 	 * DO NAWS negotiation after the DO ECHO, and we won't get here
991 	 * until a response to the DO NAWS comes back) simulate the
992 	 * receipt of a will echo.  This will also send a WONT ECHO
993 	 * to the client, since we assume that the client failed to
994 	 * respond because it believes that it is already in DO ECHO
995 	 * mode, which we do not want.
996 	 */
997 	if (his_want_state_is_will(TELOPT_ECHO)) {
998 		DIAG(TD_OPTIONS,
999 			{sprintf(nfrontp, "td: simulating recv\r\n");
1000 			 nfrontp += strlen(nfrontp);});
1001 		willoption(TELOPT_ECHO);
1002 	}
1003 
1004 	/*
1005 	 * Finally, to clean things up, we turn on our echo.  This
1006 	 * will break stupid 4.2 telnets out of local terminal echo.
1007 	 */
1008 
1009 	if (my_state_is_wont(TELOPT_ECHO))
1010 		send_will(TELOPT_ECHO, 1);
1011 
1012 #ifndef	STREAMSPTY
1013 	/*
1014 	 * Turn on packet mode
1015 	 */
1016 	(void) ioctl(p, TIOCPKT, (char *)&on);
1017 #endif
1018 
1019 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
1020 	/*
1021 	 * Continuing line mode support.  If client does not support
1022 	 * real linemode, attempt to negotiate kludge linemode by sending
1023 	 * the do timing mark sequence.
1024 	 */
1025 	if (lmodetype < REAL_LINEMODE)
1026 		send_do(TELOPT_TM, 1);
1027 #endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
1028 
1029 	/*
1030 	 * Call telrcv() once to pick up anything received during
1031 	 * terminal type negotiation, 4.2/4.3 determination, and
1032 	 * linemode negotiation.
1033 	 */
1034 	telrcv();
1035 
1036 	(void) ioctl(f, FIONBIO, (char *)&on);
1037 	(void) ioctl(p, FIONBIO, (char *)&on);
1038 #if	defined(CRAY2) && defined(UNICOS5)
1039 	init_termdriver(f, p, interrupt, sendbrk);
1040 #endif
1041 
1042 #if	defined(SO_OOBINLINE)
1043 	(void) setsockopt(net, SOL_SOCKET, SO_OOBINLINE,
1044 				(char *)&on, sizeof on);
1045 #endif	/* defined(SO_OOBINLINE) */
1046 
1047 #ifdef	SIGTSTP
1048 	(void) signal(SIGTSTP, SIG_IGN);
1049 #endif
1050 #ifdef	SIGTTOU
1051 	/*
1052 	 * Ignoring SIGTTOU keeps the kernel from blocking us
1053 	 * in ttioct() in /sys/tty.c.
1054 	 */
1055 	(void) signal(SIGTTOU, SIG_IGN);
1056 #endif
1057 
1058 	(void) signal(SIGCHLD, cleanup);
1059 
1060 #if	defined(CRAY2) && defined(UNICOS5)
1061 	/*
1062 	 * Cray-2 will send a signal when pty modes are changed by slave
1063 	 * side.  Set up signal handler now.
1064 	 */
1065 	if ((int)signal(SIGUSR1, termstat) < 0)
1066 		perror("signal");
1067 	else if (ioctl(p, TCSIGME, (char *)SIGUSR1) < 0)
1068 		perror("ioctl:TCSIGME");
1069 	/*
1070 	 * Make processing loop check terminal characteristics early on.
1071 	 */
1072 	termstat();
1073 #endif
1074 
1075 #ifdef  TIOCNOTTY
1076 	{
1077 		register int t;
1078 		t = open(_PATH_TTY, O_RDWR);
1079 		if (t >= 0) {
1080 			(void) ioctl(t, TIOCNOTTY, (char *)0);
1081 			(void) close(t);
1082 		}
1083 	}
1084 #endif
1085 
1086 #if	defined(CRAY) && defined(NEWINIT) && defined(TIOCSCTTY)
1087 	(void) setsid();
1088 	ioctl(p, TIOCSCTTY, 0);
1089 #endif
1090 
1091 	/*
1092 	 * Show banner that getty never gave.
1093 	 *
1094 	 * We put the banner in the pty input buffer.  This way, it
1095 	 * gets carriage return null processing, etc., just like all
1096 	 * other pty --> client data.
1097 	 */
1098 
1099 #if	!defined(CRAY) || !defined(NEWINIT)
1100 	if (getenv("USER"))
1101 		hostinfo = 0;
1102 #endif
1103 
1104 	if (getent(defent, "default") == 1) {
1105 		char *getstr();
1106 		char *cp=defstrs;
1107 
1108 		HE = getstr("he", &cp);
1109 		HN = getstr("hn", &cp);
1110 		IM = getstr("im", &cp);
1111 		if (HN && *HN)
1112 			(void) strcpy(host_name, HN);
1113 		if (IM == 0)
1114 			IM = "";
1115 	} else {
1116 		IM = DEFAULT_IM;
1117 		HE = 0;
1118 	}
1119 	edithost(HE, host_name);
1120 	if (hostinfo && *IM)
1121 		putf(IM, ptyibuf2);
1122 
1123 	if (pcc)
1124 		(void) strncat(ptyibuf2, ptyip, pcc+1);
1125 	ptyip = ptyibuf2;
1126 	pcc = strlen(ptyip);
1127 #ifdef	LINEMODE
1128 	/*
1129 	 * Last check to make sure all our states are correct.
1130 	 */
1131 	init_termbuf();
1132 	localstat();
1133 #endif	/* LINEMODE */
1134 
1135 	DIAG(TD_REPORT,
1136 		{sprintf(nfrontp, "td: Entering processing loop\r\n");
1137 		 nfrontp += strlen(nfrontp);});
1138 
1139 #ifdef	convex
1140 	startslave(host);
1141 #endif
1142 
1143 	nfd = ((f > p) ? f : p) + 1;
1144 	for (;;) {
1145 		fd_set ibits, obits, xbits;
1146 		register int c;
1147 
1148 		if (ncc < 0 && pcc < 0)
1149 			break;
1150 
1151 #if	defined(CRAY2) && defined(UNICOS5)
1152 		if (needtermstat)
1153 			_termstat();
1154 #endif	/* defined(CRAY2) && defined(UNICOS5) */
1155 		FD_ZERO(&ibits);
1156 		FD_ZERO(&obits);
1157 		FD_ZERO(&xbits);
1158 		/*
1159 		 * Never look for input if there's still
1160 		 * stuff in the corresponding output buffer
1161 		 */
1162 		if (nfrontp - nbackp || pcc > 0) {
1163 			FD_SET(f, &obits);
1164 		} else {
1165 			FD_SET(p, &ibits);
1166 		}
1167 		if (pfrontp - pbackp || ncc > 0) {
1168 			FD_SET(p, &obits);
1169 		} else {
1170 			FD_SET(f, &ibits);
1171 		}
1172 		if (!SYNCHing) {
1173 			FD_SET(f, &xbits);
1174 		}
1175 		if ((c = select(nfd, &ibits, &obits, &xbits,
1176 						(struct timeval *)0)) < 1) {
1177 			if (c == -1) {
1178 				if (errno == EINTR) {
1179 					continue;
1180 				}
1181 			}
1182 			sleep(5);
1183 			continue;
1184 		}
1185 
1186 		/*
1187 		 * Any urgent data?
1188 		 */
1189 		if (FD_ISSET(net, &xbits)) {
1190 		    SYNCHing = 1;
1191 		}
1192 
1193 		/*
1194 		 * Something to read from the network...
1195 		 */
1196 		if (FD_ISSET(net, &ibits)) {
1197 #if	!defined(SO_OOBINLINE)
1198 			/*
1199 			 * In 4.2 (and 4.3 beta) systems, the
1200 			 * OOB indication and data handling in the kernel
1201 			 * is such that if two separate TCP Urgent requests
1202 			 * come in, one byte of TCP data will be overlaid.
1203 			 * This is fatal for Telnet, but we try to live
1204 			 * with it.
1205 			 *
1206 			 * In addition, in 4.2 (and...), a special protocol
1207 			 * is needed to pick up the TCP Urgent data in
1208 			 * the correct sequence.
1209 			 *
1210 			 * What we do is:  if we think we are in urgent
1211 			 * mode, we look to see if we are "at the mark".
1212 			 * If we are, we do an OOB receive.  If we run
1213 			 * this twice, we will do the OOB receive twice,
1214 			 * but the second will fail, since the second
1215 			 * time we were "at the mark", but there wasn't
1216 			 * any data there (the kernel doesn't reset
1217 			 * "at the mark" until we do a normal read).
1218 			 * Once we've read the OOB data, we go ahead
1219 			 * and do normal reads.
1220 			 *
1221 			 * There is also another problem, which is that
1222 			 * since the OOB byte we read doesn't put us
1223 			 * out of OOB state, and since that byte is most
1224 			 * likely the TELNET DM (data mark), we would
1225 			 * stay in the TELNET SYNCH (SYNCHing) state.
1226 			 * So, clocks to the rescue.  If we've "just"
1227 			 * received a DM, then we test for the
1228 			 * presence of OOB data when the receive OOB
1229 			 * fails (and AFTER we did the normal mode read
1230 			 * to clear "at the mark").
1231 			 */
1232 		    if (SYNCHing) {
1233 			int atmark;
1234 
1235 			(void) ioctl(net, SIOCATMARK, (char *)&atmark);
1236 			if (atmark) {
1237 			    ncc = recv(net, netibuf, sizeof (netibuf), MSG_OOB);
1238 			    if ((ncc == -1) && (errno == EINVAL)) {
1239 				ncc = read(net, netibuf, sizeof (netibuf));
1240 				if (sequenceIs(didnetreceive, gotDM)) {
1241 				    SYNCHing = stilloob(net);
1242 				}
1243 			    }
1244 			} else {
1245 			    ncc = read(net, netibuf, sizeof (netibuf));
1246 			}
1247 		    } else {
1248 			ncc = read(net, netibuf, sizeof (netibuf));
1249 		    }
1250 		    settimer(didnetreceive);
1251 #else	/* !defined(SO_OOBINLINE)) */
1252 		    ncc = read(net, netibuf, sizeof (netibuf));
1253 #endif	/* !defined(SO_OOBINLINE)) */
1254 		    if (ncc < 0 && errno == EWOULDBLOCK)
1255 			ncc = 0;
1256 		    else {
1257 			if (ncc <= 0) {
1258 			    break;
1259 			}
1260 			netip = netibuf;
1261 		    }
1262 		    DIAG((TD_REPORT | TD_NETDATA),
1263 			    {sprintf(nfrontp, "td: netread %d chars\r\n", ncc);
1264 			     nfrontp += strlen(nfrontp);});
1265 		    DIAG(TD_NETDATA, printdata("nd", netip, ncc));
1266 		}
1267 
1268 		/*
1269 		 * Something to read from the pty...
1270 		 */
1271 		if (FD_ISSET(p, &ibits)) {
1272 #ifndef	STREAMSPTY
1273 			pcc = read(p, ptyibuf, BUFSIZ);
1274 #else
1275 			pcc = readstream(p, ptyibuf, BUFSIZ);
1276 #endif
1277 			/*
1278 			 * On some systems, if we try to read something
1279 			 * off the master side before the slave side is
1280 			 * opened, we get EIO.
1281 			 */
1282 			if (pcc < 0 && (errno == EWOULDBLOCK ||
1283 #ifdef	EAGAIN
1284 					errno == EAGAIN ||
1285 #endif
1286 					errno == EIO)) {
1287 				pcc = 0;
1288 			} else {
1289 				if (pcc <= 0)
1290 					break;
1291 #if	!defined(CRAY2) || !defined(UNICOS5)
1292 #ifdef	LINEMODE
1293 				/*
1294 				 * If ioctl from pty, pass it through net
1295 				 */
1296 				if (ptyibuf[0] & TIOCPKT_IOCTL) {
1297 					copy_termbuf(ptyibuf+1, pcc-1);
1298 					localstat();
1299 					pcc = 1;
1300 				}
1301 #endif	/* LINEMODE */
1302 				if (ptyibuf[0] & TIOCPKT_FLUSHWRITE) {
1303 					netclear();	/* clear buffer back */
1304 #ifndef	NO_URGENT
1305 					/*
1306 					 * There are client telnets on some
1307 					 * operating systems get screwed up
1308 					 * royally if we send them urgent
1309 					 * mode data.
1310 					 */
1311 					*nfrontp++ = IAC;
1312 					*nfrontp++ = DM;
1313 					neturg = nfrontp-1; /* off by one XXX */
1314 					DIAG(TD_OPTIONS,
1315 					    printoption("td: send IAC", DM));
1316 
1317 #endif
1318 				}
1319 				if (his_state_is_will(TELOPT_LFLOW) &&
1320 				    (ptyibuf[0] &
1321 				     (TIOCPKT_NOSTOP|TIOCPKT_DOSTOP))) {
1322 					int newflow =
1323 					    ptyibuf[0] & TIOCPKT_DOSTOP ? 1 : 0;
1324 					if (newflow != flowmode) {
1325 						flowmode = newflow;
1326 						(void) sprintf(nfrontp,
1327 							"%c%c%c%c%c%c",
1328 							IAC, SB, TELOPT_LFLOW,
1329 							flowmode ? LFLOW_ON
1330 								 : LFLOW_OFF,
1331 							IAC, SE);
1332 						nfrontp += 6;
1333 						DIAG(TD_OPTIONS, printsub('>',
1334 						    (unsigned char *)nfrontp-4,
1335 						    4););
1336 					}
1337 				}
1338 				pcc--;
1339 				ptyip = ptyibuf+1;
1340 #else	/* defined(CRAY2) && defined(UNICOS5) */
1341 				if (!uselinemode) {
1342 					unpcc = pcc;
1343 					unptyip = ptyibuf;
1344 					pcc = term_output(&unptyip, ptyibuf2,
1345 								&unpcc, BUFSIZ);
1346 					ptyip = ptyibuf2;
1347 				} else
1348 					ptyip = ptyibuf;
1349 #endif	/* defined(CRAY2) && defined(UNICOS5) */
1350 			}
1351 		}
1352 
1353 		while (pcc > 0) {
1354 			if ((&netobuf[BUFSIZ] - nfrontp) < 2)
1355 				break;
1356 			c = *ptyip++ & 0377, pcc--;
1357 			if (c == IAC)
1358 				*nfrontp++ = c;
1359 #if	defined(CRAY2) && defined(UNICOS5)
1360 			else if (c == '\n' &&
1361 				     my_state_is_wont(TELOPT_BINARY) && newmap)
1362 				*nfrontp++ = '\r';
1363 #endif	/* defined(CRAY2) && defined(UNICOS5) */
1364 			*nfrontp++ = c;
1365 			if ((c == '\r') && (my_state_is_wont(TELOPT_BINARY))) {
1366 				if (pcc > 0 && ((*ptyip & 0377) == '\n')) {
1367 					*nfrontp++ = *ptyip++ & 0377;
1368 					pcc--;
1369 				} else
1370 					*nfrontp++ = '\0';
1371 			}
1372 		}
1373 #if	defined(CRAY2) && defined(UNICOS5)
1374 		/*
1375 		 * If chars were left over from the terminal driver,
1376 		 * note their existence.
1377 		 */
1378 		if (!uselinemode && unpcc) {
1379 			pcc = unpcc;
1380 			unpcc = 0;
1381 			ptyip = unptyip;
1382 		}
1383 #endif	/* defined(CRAY2) && defined(UNICOS5) */
1384 
1385 		if (FD_ISSET(f, &obits) && (nfrontp - nbackp) > 0)
1386 			netflush();
1387 		if (ncc > 0)
1388 			telrcv();
1389 		if (FD_ISSET(p, &obits) && (pfrontp - pbackp) > 0)
1390 			ptyflush();
1391 	}
1392 	cleanup(0);
1393 }  /* end of telnet */
1394 
1395 #ifndef	TCSIG
1396 # ifdef	TIOCSIG
1397 #  define TCSIG TIOCSIG
1398 # endif
1399 #endif
1400 
1401 #ifdef	STREAMSPTY
1402 
1403 int flowison = -1;  /* current state of flow: -1 is unknown */
1404 
readstream(p,ibuf,bufsize)1405 int readstream(p, ibuf, bufsize)
1406 	int p;
1407 	char *ibuf;
1408 	int bufsize;
1409 {
1410 	int flags = 0;
1411 	int ret = 0;
1412 	struct termios *tsp;
1413 	struct termio *tp;
1414 	struct iocblk *ip;
1415 	char vstop, vstart;
1416 	int ixon;
1417 	int newflow;
1418 
1419 	strbufc.maxlen = BUFSIZ;
1420 	strbufc.buf = (char *)ctlbuf;
1421 	strbufd.maxlen = bufsize-1;
1422 	strbufd.len = 0;
1423 	strbufd.buf = ibuf+1;
1424 	ibuf[0] = 0;
1425 
1426 	ret = getmsg(p, &strbufc, &strbufd, &flags);
1427 	if (ret < 0)  /* error of some sort -- probably EAGAIN */
1428 		return(-1);
1429 
1430 	if (strbufc.len <= 0 || ctlbuf[0] == M_DATA) {
1431 		/* data message */
1432 		if (strbufd.len > 0) {			/* real data */
1433 			return(strbufd.len + 1);	/* count header char */
1434 		} else {
1435 			/* nothing there */
1436 			errno = EAGAIN;
1437 			return(-1);
1438 		}
1439 	}
1440 
1441 	/*
1442 	 * It's a control message.  Return 1, to look at the flag we set
1443 	 */
1444 
1445 	switch (ctlbuf[0]) {
1446 	case M_FLUSH:
1447 		if (ibuf[1] & FLUSHW)
1448 			ibuf[0] = TIOCPKT_FLUSHWRITE;
1449 		return(1);
1450 
1451 	case M_IOCTL:
1452 		ip = (struct iocblk *) (ibuf+1);
1453 
1454 		switch (ip->ioc_cmd) {
1455 		case TCSETS:
1456 		case TCSETSW:
1457 		case TCSETSF:
1458 			tsp = (struct termios *)
1459 					(ibuf+1 + sizeof(struct iocblk));
1460 			vstop = tsp->c_cc[VSTOP];
1461 			vstart = tsp->c_cc[VSTART];
1462 			ixon = tsp->c_iflag & IXON;
1463 			break;
1464 		case TCSETA:
1465 		case TCSETAW:
1466 		case TCSETAF:
1467 			tp = (struct termio *) (ibuf+1 + sizeof(struct iocblk));
1468 			vstop = tp->c_cc[VSTOP];
1469 			vstart = tp->c_cc[VSTART];
1470 			ixon = tp->c_iflag & IXON;
1471 			break;
1472 		default:
1473 			errno = EAGAIN;
1474 			return(-1);
1475 		}
1476 
1477 		newflow =  (ixon && (vstart == 021) && (vstop == 023)) ? 1 : 0;
1478 		if (newflow != flowison) {  /* it's a change */
1479 			flowison = newflow;
1480 			ibuf[0] = newflow ? TIOCPKT_DOSTOP : TIOCPKT_NOSTOP;
1481 			return(1);
1482 		}
1483 	}
1484 
1485 	/* nothing worth doing anything about */
1486 	errno = EAGAIN;
1487 	return(-1);
1488 }
1489 #endif /* STREAMSPTY */
1490 
1491 /*
1492  * Send interrupt to process on other side of pty.
1493  * If it is in raw mode, just write NULL;
1494  * otherwise, write intr char.
1495  */
1496 	void
interrupt()1497 interrupt()
1498 {
1499 	ptyflush();	/* half-hearted */
1500 
1501 #if defined(STREAMSPTY) && defined(TIOCSIGNAL)
1502 	/* Streams PTY style ioctl to post a signal */
1503 	{
1504 		int sig = SIGINT;
1505 		(void) ioctl(pty, TIOCSIGNAL, &sig);
1506 		(void) ioctl(pty, I_FLUSH, FLUSHR);
1507 	}
1508 #else
1509 #ifdef	TCSIG
1510 	(void) ioctl(pty, TCSIG, (char *)SIGINT);
1511 #else	/* TCSIG */
1512 	init_termbuf();
1513 	*pfrontp++ = slctab[SLC_IP].sptr ?
1514 			(unsigned char)*slctab[SLC_IP].sptr : '\177';
1515 #endif	/* TCSIG */
1516 #endif
1517 }
1518 
1519 /*
1520  * Send quit to process on other side of pty.
1521  * If it is in raw mode, just write NULL;
1522  * otherwise, write quit char.
1523  */
1524 	void
sendbrk()1525 sendbrk()
1526 {
1527 	ptyflush();	/* half-hearted */
1528 #ifdef	TCSIG
1529 	(void) ioctl(pty, TCSIG, (char *)SIGQUIT);
1530 #else	/* TCSIG */
1531 	init_termbuf();
1532 	*pfrontp++ = slctab[SLC_ABORT].sptr ?
1533 			(unsigned char)*slctab[SLC_ABORT].sptr : '\034';
1534 #endif	/* TCSIG */
1535 }
1536 
1537 	void
sendsusp()1538 sendsusp()
1539 {
1540 #ifdef	SIGTSTP
1541 	ptyflush();	/* half-hearted */
1542 # ifdef	TCSIG
1543 	(void) ioctl(pty, TCSIG, (char *)SIGTSTP);
1544 # else	/* TCSIG */
1545 	*pfrontp++ = slctab[SLC_SUSP].sptr ?
1546 			(unsigned char)*slctab[SLC_SUSP].sptr : '\032';
1547 # endif	/* TCSIG */
1548 #endif	/* SIGTSTP */
1549 }
1550 
1551 /*
1552  * When we get an AYT, if ^T is enabled, use that.  Otherwise,
1553  * just send back "[Yes]".
1554  */
1555 	void
recv_ayt()1556 recv_ayt()
1557 {
1558 #if	defined(SIGINFO) && defined(TCSIG)
1559 	if (slctab[SLC_AYT].sptr && *slctab[SLC_AYT].sptr != _POSIX_VDISABLE) {
1560 		(void) ioctl(pty, TCSIG, (char *)SIGINFO);
1561 		return;
1562 	}
1563 #endif
1564 	(void) strcpy(nfrontp, "\r\n[Yes]\r\n");
1565 	nfrontp += 9;
1566 }
1567 
1568 	void
doeof()1569 doeof()
1570 {
1571 	init_termbuf();
1572 
1573 #if	defined(LINEMODE) && defined(USE_TERMIO) && (VEOF == VMIN)
1574 	if (!tty_isediting()) {
1575 		extern char oldeofc;
1576 		*pfrontp++ = oldeofc;
1577 		return;
1578 	}
1579 #endif
1580 	*pfrontp++ = slctab[SLC_EOF].sptr ?
1581 			(unsigned char)*slctab[SLC_EOF].sptr : '\004';
1582 }
1583