xref: /netbsd/libexec/telnetd/telnetd.c (revision ebb3c6c1)
1 /*	$NetBSD: telnetd.c,v 1.58 2022/08/26 19:30:44 dholland Exp $	*/
2 
3 /*
4  * Copyright (C) 1997 and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 1989, 1993
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  */
60 
61 #include <sys/cdefs.h>
62 #ifndef lint
63 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\
64  The Regents of the University of California.  All rights reserved.");
65 #if 0
66 static char sccsid[] = "@(#)telnetd.c	8.4 (Berkeley) 5/30/95";
67 #else
68 __RCSID("$NetBSD: telnetd.c,v 1.58 2022/08/26 19:30:44 dholland Exp $");
69 #endif
70 #endif /* not lint */
71 
72 #include "telnetd.h"
73 #include "pathnames.h"
74 
75 #include <arpa/inet.h>
76 
77 #include <err.h>
78 #include <termcap.h>
79 
80 #include <limits.h>
81 
82 #ifdef KRB5
83 #define	Authenticator	k5_Authenticator
84 #include <krb5.h>
85 #undef	Authenticator
86 #include <krb5/com_err.h>
87 #endif
88 
89 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
90 #include <libtelnet/misc.h>
91 #endif
92 
93 extern int require_hwpreauth;
94 #ifdef KRB5
95 extern krb5_context telnet_context;
96 #endif
97 int	registerd_host_only = 0;
98 
99 
100 /*
101  * I/O data buffers,
102  * pointers, and counters.
103  */
104 char	ptyibuf[BUFSIZ], *ptyip = ptyibuf;
105 char	ptyibuf2[BUFSIZ];
106 
107 
108 int	hostinfo = 1;			/* do we print login banner? */
109 
110 
111 static int debug = 0;
112 int keepalive = 1;
113 const char *gettyname = "default";
114 char *progname;
115 
116 void usage(void) __dead;
117 int getterminaltype(char *, size_t);
118 int getent(char *, const char *);
119 static void doit(struct sockaddr *) __dead;
120 void _gettermname(void);
121 int terminaltypeok(char *);
122 char *getstr(const char *, char **);
123 
124 /*
125  * The string to pass to getopt().  We do it this way so
126  * that only the actual options that we support will be
127  * passed off to getopt().
128  */
129 char valid_opts[] = {
130 	'd', ':', 'g', ':', 'h', 'k', 'n', 'S', ':', 'u', ':', 'U',
131 	'4', '6',
132 #ifdef	AUTHENTICATION
133 	'a', ':', 'X', ':',
134 #endif
135 #ifdef	ENCRYPTION
136 	'e', ':',
137 #endif
138 #ifdef DIAGNOSTICS
139 	'D', ':',
140 #endif
141 #ifdef	LINEMODE
142 	'l',
143 #endif
144 #ifdef	SECURELOGIN
145 	's',
146 #endif
147 #ifdef	KRB5
148 	'R', ':', 'H',
149 #endif
150 	'\0'
151 };
152 
153 int family = AF_INET;
154 struct sockaddr_storage from;
155 
156 int
main(int argc,char * argv[])157 main(int argc, char *argv[])
158 {
159 	static char Xline[] = NULL16STR;
160 
161 	socklen_t fromlen;
162 	int on = 1;
163 	int ch;
164 #if	defined(IPPROTO_IP) && defined(IP_TOS)
165 	int tos = -1;
166 #endif
167 
168 	line = Xline;
169 
170 	pfrontp = pbackp = ptyobuf;
171 	netip = netibuf;
172 	nfrontp = nbackp = netobuf;
173 #ifdef	ENCRYPTION
174 	nclearto = 0;
175 #endif	/* ENCRYPTION */
176 
177 	progname = *argv;
178 
179 
180 	while ((ch = getopt(argc, argv, valid_opts)) != -1) {
181 		switch (ch) {
182 
183 #ifdef	AUTHENTICATION
184 		case 'a':
185 			/*
186 			 * Check for required authentication level
187 			 */
188 			if (strcmp(optarg, "debug") == 0) {
189 				auth_debug_mode = 1;
190 			} else if (strcasecmp(optarg, "none") == 0) {
191 				auth_level = 0;
192 			} else if (strcasecmp(optarg, "other") == 0) {
193 				auth_level = AUTH_OTHER;
194 			} else if (strcasecmp(optarg, "user") == 0) {
195 				auth_level = AUTH_USER;
196 			} else if (strcasecmp(optarg, "valid") == 0) {
197 				auth_level = AUTH_VALID;
198 			} else if (strcasecmp(optarg, "off") == 0) {
199 				/*
200 				 * This hack turns off authentication
201 				 */
202 				auth_level = -1;
203 			} else {
204 				fprintf(stderr,
205 			    "telnetd: unknown authorization level for -a\n");
206 			}
207 			break;
208 #endif	/* AUTHENTICATION */
209 
210 
211 		case 'd':
212 			if (strcmp(optarg, "ebug") == 0) {
213 				debug++;
214 				break;
215 			}
216 			usage();
217 			/* NOTREACHED */
218 			break;
219 
220 #ifdef DIAGNOSTICS
221 		case 'D':
222 			/*
223 			 * Check for desired diagnostics capabilities.
224 			 */
225 			if (!strcmp(optarg, "report")) {
226 				diagnostic |= TD_REPORT|TD_OPTIONS;
227 			} else if (!strcmp(optarg, "exercise")) {
228 				diagnostic |= TD_EXERCISE;
229 			} else if (!strcmp(optarg, "netdata")) {
230 				diagnostic |= TD_NETDATA;
231 			} else if (!strcmp(optarg, "ptydata")) {
232 				diagnostic |= TD_PTYDATA;
233 			} else if (!strcmp(optarg, "options")) {
234 				diagnostic |= TD_OPTIONS;
235 			} else {
236 				usage();
237 				/* NOT REACHED */
238 			}
239 			break;
240 #endif /* DIAGNOSTICS */
241 
242 #ifdef	ENCRYPTION
243 		case 'e':
244 			if (strcmp(optarg, "debug") == 0) {
245 				encrypt_debug_mode = 1;
246 				break;
247 			}
248 			usage();
249 			/* NOTREACHED */
250 			break;
251 #endif	/* ENCRYPTION */
252 
253 		case 'g':
254 			gettyname = optarg;
255 			break;
256 
257 		case 'h':
258 			hostinfo = 0;
259 			break;
260 
261 #ifdef	KRB5
262 		case 'H':
263 		    {
264 			require_hwpreauth = 1;
265 			break;
266 		    }
267 #endif	/* KRB5 */
268 
269 
270 #ifdef	LINEMODE
271 		case 'l':
272 			alwayslinemode = 1;
273 			break;
274 #endif	/* LINEMODE */
275 
276 		case 'k':
277 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
278 			lmodetype = NO_AUTOKLUDGE;
279 #else
280 			/* ignore -k option if built without kludge linemode */
281 #endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
282 			break;
283 
284 		case 'n':
285 			keepalive = 0;
286 			break;
287 
288 
289 #ifdef	KRB5
290 		case 'R':
291 		    {
292 			krb5_error_code retval;
293 
294 			if (telnet_context == 0) {
295 				retval = krb5_init_context(&telnet_context);
296 				if (retval) {
297 					com_err("telnetd", retval,
298 					    "while initializing krb5");
299 					exit(1);
300 				}
301 			}
302 			krb5_set_default_realm(telnet_context, optarg);
303 			break;
304 		    }
305 #endif	/* KRB5 */
306 
307 #ifdef	SECURELOGIN
308 		case 's':
309 			/* Secure login required */
310 			require_secure_login = 1;
311 			break;
312 #endif	/* SECURELOGIN */
313 		case 'S':
314 			fprintf(stderr, "%s%s\n", "TOS option unavailable; ",
315 						"-S flag not supported\n");
316 			break;
317 
318 		case 'u':
319 			fprintf(stderr, "telnetd: -u option unneeded\n");
320 			break;
321 
322 		case 'U':
323 			registerd_host_only = 1;
324 			break;
325 
326 #ifdef	AUTHENTICATION
327 		case 'X':
328 			/*
329 			 * Check for invalid authentication types
330 			 */
331 			auth_disable_name(optarg);
332 			break;
333 #endif	/* AUTHENTICATION */
334 
335 		case '4':
336 			family = AF_INET;
337 			break;
338 
339 		case '6':
340 			family = AF_INET6;
341 			break;
342 
343 		default:
344 			fprintf(stderr, "telnetd: %c: unknown option\n", ch);
345 			/* FALLTHROUGH */
346 		case '?':
347 			usage();
348 			/* NOTREACHED */
349 		}
350 	}
351 
352 	argc -= optind;
353 	argv += optind;
354 
355 	if (debug) {
356 	    int s, ns, error;
357 	    socklen_t foo;
358 	    const char *service = "telnet";
359 	    struct addrinfo hints, *res;
360 
361 	    if (argc > 1) {
362 		usage();
363 		/* NOT REACHED */
364 	    } else if (argc == 1)
365 		service = *argv;
366 
367 	    memset(&hints, 0, sizeof(hints));
368 	    hints.ai_flags = AI_PASSIVE;
369 	    hints.ai_family = family;
370 	    hints.ai_socktype = SOCK_STREAM;
371 	    hints.ai_protocol = 0;
372 	    error = getaddrinfo(NULL, service, &hints, &res);
373 
374 	    if (error) {
375 		fprintf(stderr, "tcp/%s: %s\n", service, gai_strerror(error));
376 		exit(1);
377 	    }
378 
379 	    s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
380 	    if (s < 0) {
381 		perror("telnetd: socket");
382 		exit(1);
383 	    }
384 	    (void) setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
385 				(char *)&on, sizeof(on));
386 	    if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
387 		perror("bind");
388 		exit(1);
389 	    }
390 	    if (listen(s, 1) < 0) {
391 		perror("listen");
392 		exit(1);
393 	    }
394 	    foo = res->ai_addrlen;
395 	    ns = accept(s, res->ai_addr, &foo);
396 	    if (ns < 0) {
397 		perror("accept");
398 		exit(1);
399 	    }
400 	    (void) dup2(ns, 0);
401 	    (void) close(ns);
402 	    (void) close(s);
403 	} else if (argc > 0) {
404 		usage();
405 		/* NOT REACHED */
406 	}
407 
408 	openlog("telnetd", LOG_PID, LOG_DAEMON);
409 	fromlen = sizeof (from);
410 	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
411 		fprintf(stderr, "%s: ", progname);
412 		perror("getpeername");
413 		_exit(1);
414 	}
415 	if (keepalive &&
416 	    setsockopt(0, SOL_SOCKET, SO_KEEPALIVE,
417 			(char *)&on, sizeof (on)) < 0) {
418 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
419 	}
420 
421 #if	defined(IPPROTO_IP) && defined(IP_TOS)
422 	if (((struct sockaddr *)&from)->sa_family == AF_INET) {
423 		if (tos < 0)
424 			tos = 020;	/* Low Delay bit */
425 		if (tos
426 		   && (setsockopt(0, IPPROTO_IP, IP_TOS,
427 				  (char *)&tos, sizeof(tos)) < 0)
428 		   && (errno != ENOPROTOOPT) )
429 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
430 	}
431 #endif	/* defined(IPPROTO_IP) && defined(IP_TOS) */
432 
433 	net = 0;
434 	doit((struct sockaddr *)&from);
435 	/* NOTREACHED */
436 #ifdef __GNUC__
437 	exit(0);
438 #endif
439 }  /* end of main */
440 
441 void
usage(void)442 usage(void)
443 {
444 	fprintf(stderr, "Usage: telnetd");
445 #ifdef	AUTHENTICATION
446 	fprintf(stderr, " [-a (debug|other|user|valid|off|none)]\n\t");
447 #endif
448 	fprintf(stderr, " [-debug]");
449 #ifdef DIAGNOSTICS
450 	fprintf(stderr, " [-D (options|report|exercise|netdata|ptydata)]\n\t");
451 #endif
452 #ifdef	ENCRYPTION
453 	fprintf(stderr, " [-edebug]");
454 #endif
455 	fprintf(stderr, " [-h]");
456 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
457 	fprintf(stderr, " [-k]");
458 #endif
459 #ifdef LINEMODE
460 	fprintf(stderr, " [-l]");
461 #endif
462 	fprintf(stderr, " [-n]");
463 	fprintf(stderr, "\n\t");
464 #ifdef	SECURELOGIN
465 	fprintf(stderr, " [-s]");
466 #endif
467 #ifdef	AUTHENTICATION
468 	fprintf(stderr, " [-X auth-type]");
469 #endif
470 	fprintf(stderr, " [-u utmp_hostname_length] [-U]");
471 	fprintf(stderr, " [port]\n");
472 	exit(1);
473 }
474 
475 /*
476  * getterminaltype
477  *
478  *	Ask the other end to send along its terminal type and speed.
479  * Output is the variable terminaltype filled in.
480  */
481 static unsigned char ttytype_sbbuf[] = {
482 	IAC, SB, TELOPT_TTYPE, TELQUAL_SEND, IAC, SE
483 };
484 
485 int
getterminaltype(char * name,size_t l)486 getterminaltype(char *name, size_t l)
487 {
488     int retval = -1;
489 
490     settimer(baseline);
491 #ifdef AUTHENTICATION
492     /*
493      * Handle the Authentication option before we do anything else.
494      */
495     send_do(TELOPT_AUTHENTICATION, 1);
496     while (his_will_wont_is_changing(TELOPT_AUTHENTICATION))
497 	ttloop();
498     if (his_state_is_will(TELOPT_AUTHENTICATION)) {
499 	retval = auth_wait(name, l);
500     }
501 #endif
502 
503 #ifdef	ENCRYPTION
504     send_will(TELOPT_ENCRYPT, 1);
505 #endif	/* ENCRYPTION */
506     send_do(TELOPT_TTYPE, 1);
507     send_do(TELOPT_TSPEED, 1);
508     send_do(TELOPT_XDISPLOC, 1);
509     send_do(TELOPT_NEW_ENVIRON, 1);
510     send_do(TELOPT_OLD_ENVIRON, 1);
511     while (
512 #ifdef	ENCRYPTION
513 	   his_do_dont_is_changing(TELOPT_ENCRYPT) ||
514 #endif	/* ENCRYPTION */
515 	   his_will_wont_is_changing(TELOPT_TTYPE) ||
516 	   his_will_wont_is_changing(TELOPT_TSPEED) ||
517 	   his_will_wont_is_changing(TELOPT_XDISPLOC) ||
518 	   his_will_wont_is_changing(TELOPT_NEW_ENVIRON) ||
519 	   his_will_wont_is_changing(TELOPT_OLD_ENVIRON)) {
520 	ttloop();
521     }
522     if (his_state_is_will(TELOPT_TSPEED)) {
523 	static unsigned char sb[] =
524 			{ IAC, SB, TELOPT_TSPEED, TELQUAL_SEND, IAC, SE };
525 
526 	output_datalen((const char *)sb, sizeof sb);
527 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
528     }
529 #ifdef	ENCRYPTION
530     /*
531      * Wait for the negotiation of what type of encryption we can
532      * send with.  If autoencrypt is not set, this will just return.
533      */
534     if (his_state_is_will(TELOPT_ENCRYPT)) {
535 	encrypt_wait();
536     }
537 #endif	/* ENCRYPTION */
538     if (his_state_is_will(TELOPT_XDISPLOC)) {
539 	static unsigned char sb[] =
540 			{ IAC, SB, TELOPT_XDISPLOC, TELQUAL_SEND, IAC, SE };
541 
542 	output_datalen((const char *)sb, sizeof sb);
543 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
544     }
545     if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
546 	static unsigned char sb[] =
547 			{ IAC, SB, TELOPT_NEW_ENVIRON, TELQUAL_SEND, IAC, SE };
548 
549 	output_datalen((const char *)sb, sizeof sb);
550 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
551     }
552     else if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
553 	static unsigned char sb[] =
554 			{ IAC, SB, TELOPT_OLD_ENVIRON, TELQUAL_SEND, IAC, SE };
555 
556 	output_datalen((const char *)sb, sizeof sb);
557 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
558     }
559     if (his_state_is_will(TELOPT_TTYPE)) {
560 
561 	output_datalen((const char *)ttytype_sbbuf, sizeof ttytype_sbbuf);
562 	DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
563 					sizeof ttytype_sbbuf - 2););
564     }
565     if (his_state_is_will(TELOPT_TSPEED)) {
566 	while (sequenceIs(tspeedsubopt, baseline))
567 	    ttloop();
568     }
569     if (his_state_is_will(TELOPT_XDISPLOC)) {
570 	while (sequenceIs(xdisplocsubopt, baseline))
571 	    ttloop();
572     }
573     if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
574 	while (sequenceIs(environsubopt, baseline))
575 	    ttloop();
576     }
577     if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
578 	while (sequenceIs(oenvironsubopt, baseline))
579 	    ttloop();
580     }
581     if (his_state_is_will(TELOPT_TTYPE)) {
582 	char first[256], last[256];
583 
584 	while (sequenceIs(ttypesubopt, baseline))
585 	    ttloop();
586 
587 	/*
588 	 * If the other side has already disabled the option, then
589 	 * we have to just go with what we (might) have already gotten.
590 	 */
591 	if (his_state_is_will(TELOPT_TTYPE) && !terminaltypeok(terminaltype)) {
592 	    (void) strlcpy(first, terminaltype, sizeof(first));
593 	    for(;;) {
594 		/*
595 		 * Save the unknown name, and request the next name.
596 		 */
597 		(void) strlcpy(last, terminaltype, sizeof(last));
598 		_gettermname();
599 		if (terminaltypeok(terminaltype))
600 		    break;
601 		if ((strncmp(last, terminaltype, sizeof(last)) == 0) ||
602 		    his_state_is_wont(TELOPT_TTYPE)) {
603 		    /*
604 		     * We've hit the end.  If this is the same as
605 		     * the first name, just go with it.
606 		     */
607 		    if (strncmp(first, terminaltype, sizeof(first)) == 0)
608 			break;
609 		    /*
610 		     * Get the terminal name one more time, so that
611 		     * RFC1091 compliant telnets will cycle back to
612 		     * the start of the list.
613 		     */
614 		     _gettermname();
615 		    if (strncmp(first, terminaltype, sizeof(first)) != 0) {
616 			(void) strlcpy(terminaltype, first, sizeof(terminaltype));
617 		    }
618 		    break;
619 		}
620 	    }
621 	}
622     }
623     return(retval);
624 }  /* end of getterminaltype */
625 
626 void
_gettermname(void)627 _gettermname(void)
628 {
629     /*
630      * If the client turned off the option,
631      * we can't send another request, so we
632      * just return.
633      */
634     if (his_state_is_wont(TELOPT_TTYPE))
635 	return;
636     settimer(baseline);
637     output_datalen((const char *)ttytype_sbbuf, sizeof ttytype_sbbuf);
638     DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
639 					sizeof ttytype_sbbuf - 2););
640     while (sequenceIs(ttypesubopt, baseline))
641 	ttloop();
642 }
643 
644 int
terminaltypeok(char * s)645 terminaltypeok(char *s)
646 {
647     char buf[1024];
648 
649     /*
650      * tgetent() will return 1 if the type is known, and
651      * 0 if it is not known.  If it returns -1, it couldn't
652      * open the database.  But if we can't open the database,
653      * it won't help to say we failed, because we won't be
654      * able to verify anything else.  So, we treat -1 like 1.
655      */
656     if (tgetent(buf, s) == 0)
657 	return(0);
658     return(1);
659 }
660 
661 char *hostname;
662 char host_name[MAXHOSTNAMELEN + 1];
663 char remote_host_name[MAXHOSTNAMELEN + 1];
664 
665 static void telnet(int, int) __dead;
666 
667 /*
668  * Get a pty, scan input lines.
669  */
670 static void
doit(struct sockaddr * who)671 doit(struct sockaddr *who)
672 {
673 	char *host;
674 	int error;
675 	int level;
676 	int ptynum;
677 	int flags;
678 	char user_name[256];
679 
680 	/*
681 	 * Initialize the slc mapping table.
682 	 */
683 	get_slc_defaults();
684 
685 	/*
686 	 * Find an available pty to use.
687 	 */
688 	pty = getpty(&ptynum);
689 	if (pty < 0)
690 		fatal(net, "All network ports in use");
691 
692 	flags = registerd_host_only ? NI_NAMEREQD : 0;
693 
694 	/* get name of connected client */
695 	error = getnameinfo(who, who->sa_len, remote_host_name,
696 	    sizeof(remote_host_name), NULL, 0, flags);
697 
698 	if (error) {
699 		fatal(net, "Couldn't resolve your address into a host name.\r\n\
700 	 Please contact your net administrator");
701 #ifdef __GNUC__
702 		host = NULL;	/* XXX gcc */
703 #endif
704 	}
705 
706 	remote_host_name[sizeof(remote_host_name)-1] = 0;
707 	host = remote_host_name;
708 
709 	(void)gethostname(host_name, sizeof(host_name));
710 	host_name[sizeof(host_name) - 1] = '\0';
711 	hostname = host_name;
712 
713 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
714 	auth_encrypt_init(hostname, host, "TELNETD", 1);
715 #endif
716 
717 	init_env();
718 	/*
719 	 * get terminal type.
720 	 */
721 	*user_name = 0;
722 	level = getterminaltype(user_name, sizeof(user_name));
723 	setenv("TERM", terminaltype[0] ? terminaltype : "network", 1);
724 
725 	/*
726 	 * Start up the login process on the slave side of the terminal
727 	 */
728 	startslave(host, level, user_name);
729 
730 	telnet(net, pty);  /* begin server processing */
731 	/*NOTREACHED*/
732 }  /* end of doit */
733 
734 
735 /*
736  * Main loop.  Select from pty and network, and
737  * hand data to telnet receiver finite state machine.
738  */
739 static void
telnet(int f,int p)740 telnet(int f, int p)
741 {
742 	int on = 1;
743 #define	TABBUFSIZ	512
744 	char	defent[TABBUFSIZ];
745 	char	defstrs[TABBUFSIZ];
746 #undef	TABBUFSIZ
747 	char *HE, *HN, *IF, *ptyibuf2ptr;
748 	const char *IM;
749 	struct pollfd set[2];
750 
751 	/*
752 	 * Do some tests where it is desirable to wait for a response.
753 	 * Rather than doing them slowly, one at a time, do them all
754 	 * at once.
755 	 */
756 	if (my_state_is_wont(TELOPT_SGA))
757 		send_will(TELOPT_SGA, 1);
758 	/*
759 	 * Is the client side a 4.2 (NOT 4.3) system?  We need to know this
760 	 * because 4.2 clients are unable to deal with TCP urgent data.
761 	 *
762 	 * To find out, we send out a "DO ECHO".  If the remote system
763 	 * answers "WILL ECHO" it is probably a 4.2 client, and we note
764 	 * that fact ("WILL ECHO" ==> that the client will echo what
765 	 * WE, the server, sends it; it does NOT mean that the client will
766 	 * echo the terminal input).
767 	 */
768 	send_do(TELOPT_ECHO, 1);
769 
770 #ifdef	LINEMODE
771 	if (his_state_is_wont(TELOPT_LINEMODE)) {
772 		/* Query the peer for linemode support by trying to negotiate
773 		 * the linemode option.
774 		 */
775 		linemode = 0;
776 		editmode = 0;
777 		send_do(TELOPT_LINEMODE, 1);  /* send do linemode */
778 	}
779 #endif	/* LINEMODE */
780 
781 	/*
782 	 * Send along a couple of other options that we wish to negotiate.
783 	 */
784 	send_do(TELOPT_NAWS, 1);
785 	send_will(TELOPT_STATUS, 1);
786 	flowmode = 1;		/* default flow control state */
787 	restartany = -1;	/* uninitialized... */
788 	send_do(TELOPT_LFLOW, 1);
789 
790 	/*
791 	 * Spin, waiting for a response from the DO ECHO.  However,
792 	 * some REALLY DUMB telnets out there might not respond
793 	 * to the DO ECHO.  So, we spin looking for NAWS, (most dumb
794 	 * telnets so far seem to respond with WONT for a DO that
795 	 * they don't understand...) because by the time we get the
796 	 * response, it will already have processed the DO ECHO.
797 	 * Kludge upon kludge.
798 	 */
799 	while (his_will_wont_is_changing(TELOPT_NAWS))
800 		ttloop();
801 
802 	/*
803 	 * But...
804 	 * The client might have sent a WILL NAWS as part of its
805 	 * startup code; if so, we'll be here before we get the
806 	 * response to the DO ECHO.  We'll make the assumption
807 	 * that any implementation that understands about NAWS
808 	 * is a modern enough implementation that it will respond
809 	 * to our DO ECHO request; hence we'll do another spin
810 	 * waiting for the ECHO option to settle down, which is
811 	 * what we wanted to do in the first place...
812 	 */
813 	if (his_want_state_is_will(TELOPT_ECHO) &&
814 	    his_state_is_will(TELOPT_NAWS)) {
815 		while (his_will_wont_is_changing(TELOPT_ECHO))
816 			ttloop();
817 	}
818 	/*
819 	 * On the off chance that the telnet client is broken and does not
820 	 * respond to the DO ECHO we sent, (after all, we did send the
821 	 * DO NAWS negotiation after the DO ECHO, and we won't get here
822 	 * until a response to the DO NAWS comes back) simulate the
823 	 * receipt of a will echo.  This will also send a WONT ECHO
824 	 * to the client, since we assume that the client failed to
825 	 * respond because it believes that it is already in DO ECHO
826 	 * mode, which we do not want.
827 	 */
828 	if (his_want_state_is_will(TELOPT_ECHO)) {
829 		DIAG(TD_OPTIONS,
830 			{output_data("td: simulating recv\r\n");});
831 		willoption(TELOPT_ECHO);
832 	}
833 
834 	/*
835 	 * Finally, to clean things up, we turn on our echo.  This
836 	 * will break stupid 4.2 telnets out of local terminal echo.
837 	 */
838 
839 	if (my_state_is_wont(TELOPT_ECHO))
840 		send_will(TELOPT_ECHO, 1);
841 
842 	/*
843 	 * Turn on packet mode
844 	 */
845 	(void) ioctl(p, TIOCPKT, (char *)&on);
846 
847 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
848 	/*
849 	 * Continuing line mode support.  If client does not support
850 	 * real linemode, attempt to negotiate kludge linemode by sending
851 	 * the do timing mark sequence.
852 	 */
853 	if (lmodetype < REAL_LINEMODE)
854 		send_do(TELOPT_TM, 1);
855 #endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
856 
857 	/*
858 	 * Call telrcv() once to pick up anything received during
859 	 * terminal type negotiation, 4.2/4.3 determination, and
860 	 * linemode negotiation.
861 	 */
862 	telrcv();
863 
864 	(void) ioctl(f, FIONBIO, (char *)&on);
865 	(void) ioctl(p, FIONBIO, (char *)&on);
866 
867 	(void) setsockopt(f, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof on);
868 
869 	(void) signal(SIGTSTP, SIG_IGN);
870 	/*
871 	 * Ignoring SIGTTOU keeps the kernel from blocking us
872 	 * in ttioct() in /sys/tty.c.
873 	 */
874 	(void) signal(SIGTTOU, SIG_IGN);
875 
876 	(void) signal(SIGCHLD, cleanup);
877 
878 
879 	{
880 		int t;
881 		t = open(_PATH_TTY, O_RDWR);
882 		if (t >= 0) {
883 			(void) ioctl(t, TIOCNOTTY, (char *)0);
884 			(void) close(t);
885 		}
886 	}
887 
888 
889 	/*
890 	 * Show banner that getty never gave.
891 	 *
892 	 * We put the banner in the pty input buffer.  This way, it
893 	 * gets carriage return null processing, etc., just like all
894 	 * other pty --> client data.
895 	 */
896 
897 	if (getent(defent, gettyname) == 1) {
898 		char *cp=defstrs;
899 
900 		HE = getstr("he", &cp);
901 		HN = getstr("hn", &cp);
902 		IM = getstr("im", &cp);
903 		IF = getstr("if", &cp);
904 		if (HN && *HN)
905 			(void)strlcpy(host_name, HN, sizeof(host_name));
906 		if (IM == 0)
907 			IM = "";
908 	} else {
909 		IM = DEFAULT_IM;
910 		HE = 0;
911 		IF = NULL;
912 	}
913 	edithost(HE, host_name);
914 	ptyibuf2ptr = ptyibuf2;
915 	if (hostinfo) {
916 		if (IF)	{
917 			char buf[_POSIX2_LINE_MAX];
918 			FILE *fd;
919 
920 			if ((fd = fopen(IF, "r")) != NULL) {
921 				while (fgets(buf, sizeof(buf) - 1, fd) != NULL)
922 					ptyibuf2ptr = putf(buf, ptyibuf2ptr);
923 				fclose(fd);
924 			}
925 		}
926 		if (*IM)
927 			ptyibuf2ptr = putf(IM, ptyibuf2ptr);
928 	}
929 
930 	if (pcc)
931 		strncpy(ptyibuf2ptr, ptyip, pcc+1);
932 	ptyip = ptyibuf2;
933 	pcc = strlen(ptyip);
934 #ifdef	LINEMODE
935 	/*
936 	 * Last check to make sure all our states are correct.
937 	 */
938 	init_termbuf();
939 	localstat();
940 #endif	/* LINEMODE */
941 
942 	DIAG(TD_REPORT,
943 		{output_data("td: Entering processing loop\r\n");});
944 
945 
946 	set[0].fd = f;
947 	set[1].fd = p;
948 	for (;;) {
949 		int c;
950 
951 		if (ncc < 0 && pcc < 0)
952 			break;
953 
954 		/*
955 		 * Never look for input if there's still
956 		 * stuff in the corresponding output buffer
957 		 */
958 		set[0].events = 0;
959 		set[1].events = 0;
960 		if (nfrontp - nbackp || pcc > 0)
961 			set[0].events |= POLLOUT;
962 		else
963 			set[1].events |= POLLIN;
964 		if (pfrontp - pbackp || ncc > 0)
965 			set[1].events |= POLLOUT;
966 		else
967 			set[0].events |= POLLIN;
968 		if (!SYNCHing)
969 			set[0].events |= POLLPRI;
970 
971 		if ((c = poll(set, 2, INFTIM)) < 1) {
972 			if (c == -1) {
973 				if (errno == EINTR) {
974 					continue;
975 				}
976 			}
977 			sleep(5);
978 			continue;
979 		}
980 
981 		/*
982 		 * Any urgent data?
983 		 */
984 		if (set[0].revents & POLLPRI) {
985 		    SYNCHing = 1;
986 		}
987 
988 		/*
989 		 * Something to read from the network...
990 		 */
991 		if (set[0].revents & POLLIN) {
992 		    ncc = read(f, netibuf, sizeof (netibuf));
993 		    if (ncc < 0 && errno == EWOULDBLOCK)
994 			ncc = 0;
995 		    else {
996 			if (ncc <= 0) {
997 			    break;
998 			}
999 			netip = netibuf;
1000 		    }
1001 		    DIAG((TD_REPORT | TD_NETDATA),
1002 			    {output_data("td: netread %d chars\r\n", ncc);});
1003 		    DIAG(TD_NETDATA, printdata("nd", netip, ncc));
1004 		}
1005 
1006 		/*
1007 		 * Something to read from the pty...
1008 		 */
1009 		if (set[1].revents & POLLIN) {
1010 			pcc = read(p, ptyibuf, BUFSIZ);
1011 			/*
1012 			 * On some systems, if we try to read something
1013 			 * off the master side before the slave side is
1014 			 * opened, we get EIO.
1015 			 */
1016 			if (pcc < 0 && (errno == EWOULDBLOCK ||
1017 					errno == EAGAIN ||
1018 					errno == EIO)) {
1019 				pcc = 0;
1020 			} else {
1021 				if (pcc <= 0)
1022 					break;
1023 #ifdef	LINEMODE
1024 				/*
1025 				 * If ioctl from pty, pass it through net
1026 				 */
1027 				if (ptyibuf[0] & TIOCPKT_IOCTL) {
1028 					copy_termbuf(ptyibuf+1, pcc-1);
1029 					localstat();
1030 					pcc = 1;
1031 				}
1032 #endif	/* LINEMODE */
1033 				if (ptyibuf[0] & TIOCPKT_FLUSHWRITE) {
1034 					netclear();	/* clear buffer back */
1035 					/*
1036 					 * There are client telnets on some
1037 					 * operating systems get screwed up
1038 					 * royally if we send them urgent
1039 					 * mode data.
1040 					 */
1041 					output_data("%c%c", IAC, DM);
1042 					neturg = nfrontp - 1; /* off by one XXX */
1043 					DIAG(TD_OPTIONS,
1044 					    printoption("td: send IAC", DM));
1045 				}
1046 				if (his_state_is_will(TELOPT_LFLOW) &&
1047 				    (ptyibuf[0] &
1048 				     (TIOCPKT_NOSTOP|TIOCPKT_DOSTOP))) {
1049 					int newflow =
1050 					    ptyibuf[0] & TIOCPKT_DOSTOP ? 1 : 0;
1051 					if (newflow != flowmode) {
1052 						flowmode = newflow;
1053 						(void) output_data(
1054 							"%c%c%c%c%c%c",
1055 							IAC, SB, TELOPT_LFLOW,
1056 							flowmode ? LFLOW_ON
1057 								 : LFLOW_OFF,
1058 							IAC, SE);
1059 						DIAG(TD_OPTIONS, printsub('>',
1060 						    (unsigned char *)nfrontp - 4,
1061 						    4););
1062 					}
1063 				}
1064 				pcc--;
1065 				ptyip = ptyibuf+1;
1066 			}
1067 		}
1068 
1069 		while (pcc > 0) {
1070 			if ((&netobuf[BUFSIZ] - nfrontp) < 2)
1071 				break;
1072 			c = *ptyip++ & 0377, pcc--;
1073 			if (c == IAC)
1074 				output_data("%c", c);
1075 			output_data("%c", c);
1076 			if ((c == '\r') && (my_state_is_wont(TELOPT_BINARY))) {
1077 				if (pcc > 0 && ((*ptyip & 0377) == '\n')) {
1078 					output_data("%c", *ptyip++ & 0377);
1079 					pcc--;
1080 				} else
1081 					output_datalen("\0", 1);
1082 			}
1083 		}
1084 
1085 		if ((set[0].revents & POLLOUT) && (nfrontp - nbackp) > 0)
1086 			netflush();
1087 		if (ncc > 0)
1088 			telrcv();
1089 		if ((set[1].revents & POLLOUT) && (pfrontp - pbackp) > 0)
1090 			ptyflush();
1091 	}
1092 	cleanup(0);
1093 }  /* end of telnet */
1094 
1095 /*
1096  * Send interrupt to process on other side of pty.
1097  * If it is in raw mode, just write NULL;
1098  * otherwise, write intr char.
1099  */
1100 void
interrupt(void)1101 interrupt(void)
1102 {
1103 	ptyflush();	/* half-hearted */
1104 
1105 	(void) ioctl(pty, TIOCSIG, (char *)SIGINT);
1106 }
1107 
1108 /*
1109  * Send quit to process on other side of pty.
1110  * If it is in raw mode, just write NULL;
1111  * otherwise, write quit char.
1112  */
1113 void
sendbrk(void)1114 sendbrk(void)
1115 {
1116 	ptyflush();	/* half-hearted */
1117 	(void) ioctl(pty, TIOCSIG, (char *)SIGQUIT);
1118 }
1119 
1120 void
sendsusp(void)1121 sendsusp(void)
1122 {
1123 	ptyflush();	/* half-hearted */
1124 	(void) ioctl(pty, TIOCSIG, (char *)SIGTSTP);
1125 }
1126 
1127 /*
1128  * When we get an AYT, if ^T is enabled, use that.  Otherwise,
1129  * just send back "[Yes]".
1130  */
1131 void
recv_ayt(void)1132 recv_ayt(void)
1133 {
1134 	if (slctab[SLC_AYT].sptr && *slctab[SLC_AYT].sptr != _POSIX_VDISABLE) {
1135 		(void) ioctl(pty, TIOCSIG, (char *)SIGINFO);
1136 		return;
1137 	}
1138 	(void) output_data("\r\n[Yes]\r\n");
1139 }
1140 
1141 void
doeof(void)1142 doeof(void)
1143 {
1144 	init_termbuf();
1145 
1146 #if	defined(LINEMODE) && (VEOF == VMIN)
1147 	if (!tty_isediting()) {
1148 		extern char oldeofc;
1149 		*pfrontp++ = oldeofc;
1150 		return;
1151 	}
1152 #endif
1153 	*pfrontp++ = slctab[SLC_EOF].sptr ?
1154 			(unsigned char)*slctab[SLC_EOF].sptr : '\004';
1155 }
1156