Home | History | Annotate | Line # | Download | only in telnetd
telnetd.c revision 1.59
      1 /*	$NetBSD: telnetd.c,v 1.59 2023/09/21 14:00:34 shm 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.59 2023/09/21 14:00:34 shm 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
    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 	    freeaddrinfo(res);
    404 	} else if (argc > 0) {
    405 		usage();
    406 		/* NOT REACHED */
    407 	}
    408 
    409 	openlog("telnetd", LOG_PID, LOG_DAEMON);
    410 	fromlen = sizeof (from);
    411 	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
    412 		fprintf(stderr, "%s: ", progname);
    413 		perror("getpeername");
    414 		_exit(1);
    415 	}
    416 	if (keepalive &&
    417 	    setsockopt(0, SOL_SOCKET, SO_KEEPALIVE,
    418 			(char *)&on, sizeof (on)) < 0) {
    419 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
    420 	}
    421 
    422 #if	defined(IPPROTO_IP) && defined(IP_TOS)
    423 	if (((struct sockaddr *)&from)->sa_family == AF_INET) {
    424 		if (tos < 0)
    425 			tos = 020;	/* Low Delay bit */
    426 		if (tos
    427 		   && (setsockopt(0, IPPROTO_IP, IP_TOS,
    428 				  (char *)&tos, sizeof(tos)) < 0)
    429 		   && (errno != ENOPROTOOPT) )
    430 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
    431 	}
    432 #endif	/* defined(IPPROTO_IP) && defined(IP_TOS) */
    433 
    434 	net = 0;
    435 	doit((struct sockaddr *)&from);
    436 	/* NOTREACHED */
    437 #ifdef __GNUC__
    438 	exit(0);
    439 #endif
    440 }  /* end of main */
    441 
    442 void
    443 usage(void)
    444 {
    445 	fprintf(stderr, "Usage: telnetd");
    446 #ifdef	AUTHENTICATION
    447 	fprintf(stderr, " [-a (debug|other|user|valid|off|none)]\n\t");
    448 #endif
    449 	fprintf(stderr, " [-debug]");
    450 #ifdef DIAGNOSTICS
    451 	fprintf(stderr, " [-D (options|report|exercise|netdata|ptydata)]\n\t");
    452 #endif
    453 #ifdef	ENCRYPTION
    454 	fprintf(stderr, " [-edebug]");
    455 #endif
    456 	fprintf(stderr, " [-h]");
    457 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
    458 	fprintf(stderr, " [-k]");
    459 #endif
    460 #ifdef LINEMODE
    461 	fprintf(stderr, " [-l]");
    462 #endif
    463 	fprintf(stderr, " [-n]");
    464 	fprintf(stderr, "\n\t");
    465 #ifdef	SECURELOGIN
    466 	fprintf(stderr, " [-s]");
    467 #endif
    468 #ifdef	AUTHENTICATION
    469 	fprintf(stderr, " [-X auth-type]");
    470 #endif
    471 	fprintf(stderr, " [-u utmp_hostname_length] [-U]");
    472 	fprintf(stderr, " [port]\n");
    473 	exit(1);
    474 }
    475 
    476 /*
    477  * getterminaltype
    478  *
    479  *	Ask the other end to send along its terminal type and speed.
    480  * Output is the variable terminaltype filled in.
    481  */
    482 static unsigned char ttytype_sbbuf[] = {
    483 	IAC, SB, TELOPT_TTYPE, TELQUAL_SEND, IAC, SE
    484 };
    485 
    486 int
    487 getterminaltype(char *name, size_t l)
    488 {
    489     int retval = -1;
    490 
    491     settimer(baseline);
    492 #ifdef AUTHENTICATION
    493     /*
    494      * Handle the Authentication option before we do anything else.
    495      */
    496     send_do(TELOPT_AUTHENTICATION, 1);
    497     while (his_will_wont_is_changing(TELOPT_AUTHENTICATION))
    498 	ttloop();
    499     if (his_state_is_will(TELOPT_AUTHENTICATION)) {
    500 	retval = auth_wait(name, l);
    501     }
    502 #endif
    503 
    504 #ifdef	ENCRYPTION
    505     send_will(TELOPT_ENCRYPT, 1);
    506 #endif	/* ENCRYPTION */
    507     send_do(TELOPT_TTYPE, 1);
    508     send_do(TELOPT_TSPEED, 1);
    509     send_do(TELOPT_XDISPLOC, 1);
    510     send_do(TELOPT_NEW_ENVIRON, 1);
    511     send_do(TELOPT_OLD_ENVIRON, 1);
    512     while (
    513 #ifdef	ENCRYPTION
    514 	   his_do_dont_is_changing(TELOPT_ENCRYPT) ||
    515 #endif	/* ENCRYPTION */
    516 	   his_will_wont_is_changing(TELOPT_TTYPE) ||
    517 	   his_will_wont_is_changing(TELOPT_TSPEED) ||
    518 	   his_will_wont_is_changing(TELOPT_XDISPLOC) ||
    519 	   his_will_wont_is_changing(TELOPT_NEW_ENVIRON) ||
    520 	   his_will_wont_is_changing(TELOPT_OLD_ENVIRON)) {
    521 	ttloop();
    522     }
    523     if (his_state_is_will(TELOPT_TSPEED)) {
    524 	static unsigned char sb[] =
    525 			{ IAC, SB, TELOPT_TSPEED, TELQUAL_SEND, IAC, SE };
    526 
    527 	output_datalen((const char *)sb, sizeof sb);
    528 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
    529     }
    530 #ifdef	ENCRYPTION
    531     /*
    532      * Wait for the negotiation of what type of encryption we can
    533      * send with.  If autoencrypt is not set, this will just return.
    534      */
    535     if (his_state_is_will(TELOPT_ENCRYPT)) {
    536 	encrypt_wait();
    537     }
    538 #endif	/* ENCRYPTION */
    539     if (his_state_is_will(TELOPT_XDISPLOC)) {
    540 	static unsigned char sb[] =
    541 			{ IAC, SB, TELOPT_XDISPLOC, TELQUAL_SEND, IAC, SE };
    542 
    543 	output_datalen((const char *)sb, sizeof sb);
    544 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
    545     }
    546     if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
    547 	static unsigned char sb[] =
    548 			{ IAC, SB, TELOPT_NEW_ENVIRON, TELQUAL_SEND, IAC, SE };
    549 
    550 	output_datalen((const char *)sb, sizeof sb);
    551 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
    552     }
    553     else if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
    554 	static unsigned char sb[] =
    555 			{ IAC, SB, TELOPT_OLD_ENVIRON, TELQUAL_SEND, IAC, SE };
    556 
    557 	output_datalen((const char *)sb, sizeof sb);
    558 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
    559     }
    560     if (his_state_is_will(TELOPT_TTYPE)) {
    561 
    562 	output_datalen((const char *)ttytype_sbbuf, sizeof ttytype_sbbuf);
    563 	DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
    564 					sizeof ttytype_sbbuf - 2););
    565     }
    566     if (his_state_is_will(TELOPT_TSPEED)) {
    567 	while (sequenceIs(tspeedsubopt, baseline))
    568 	    ttloop();
    569     }
    570     if (his_state_is_will(TELOPT_XDISPLOC)) {
    571 	while (sequenceIs(xdisplocsubopt, baseline))
    572 	    ttloop();
    573     }
    574     if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
    575 	while (sequenceIs(environsubopt, baseline))
    576 	    ttloop();
    577     }
    578     if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
    579 	while (sequenceIs(oenvironsubopt, baseline))
    580 	    ttloop();
    581     }
    582     if (his_state_is_will(TELOPT_TTYPE)) {
    583 	char first[256], last[256];
    584 
    585 	while (sequenceIs(ttypesubopt, baseline))
    586 	    ttloop();
    587 
    588 	/*
    589 	 * If the other side has already disabled the option, then
    590 	 * we have to just go with what we (might) have already gotten.
    591 	 */
    592 	if (his_state_is_will(TELOPT_TTYPE) && !terminaltypeok(terminaltype)) {
    593 	    (void) strlcpy(first, terminaltype, sizeof(first));
    594 	    for(;;) {
    595 		/*
    596 		 * Save the unknown name, and request the next name.
    597 		 */
    598 		(void) strlcpy(last, terminaltype, sizeof(last));
    599 		_gettermname();
    600 		if (terminaltypeok(terminaltype))
    601 		    break;
    602 		if ((strncmp(last, terminaltype, sizeof(last)) == 0) ||
    603 		    his_state_is_wont(TELOPT_TTYPE)) {
    604 		    /*
    605 		     * We've hit the end.  If this is the same as
    606 		     * the first name, just go with it.
    607 		     */
    608 		    if (strncmp(first, terminaltype, sizeof(first)) == 0)
    609 			break;
    610 		    /*
    611 		     * Get the terminal name one more time, so that
    612 		     * RFC1091 compliant telnets will cycle back to
    613 		     * the start of the list.
    614 		     */
    615 		     _gettermname();
    616 		    if (strncmp(first, terminaltype, sizeof(first)) != 0) {
    617 			(void) strlcpy(terminaltype, first, sizeof(terminaltype));
    618 		    }
    619 		    break;
    620 		}
    621 	    }
    622 	}
    623     }
    624     return(retval);
    625 }  /* end of getterminaltype */
    626 
    627 void
    628 _gettermname(void)
    629 {
    630     /*
    631      * If the client turned off the option,
    632      * we can't send another request, so we
    633      * just return.
    634      */
    635     if (his_state_is_wont(TELOPT_TTYPE))
    636 	return;
    637     settimer(baseline);
    638     output_datalen((const char *)ttytype_sbbuf, sizeof ttytype_sbbuf);
    639     DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
    640 					sizeof ttytype_sbbuf - 2););
    641     while (sequenceIs(ttypesubopt, baseline))
    642 	ttloop();
    643 }
    644 
    645 int
    646 terminaltypeok(char *s)
    647 {
    648     char buf[1024];
    649 
    650     /*
    651      * tgetent() will return 1 if the type is known, and
    652      * 0 if it is not known.  If it returns -1, it couldn't
    653      * open the database.  But if we can't open the database,
    654      * it won't help to say we failed, because we won't be
    655      * able to verify anything else.  So, we treat -1 like 1.
    656      */
    657     if (tgetent(buf, s) == 0)
    658 	return(0);
    659     return(1);
    660 }
    661 
    662 char *hostname;
    663 char host_name[MAXHOSTNAMELEN + 1];
    664 char remote_host_name[MAXHOSTNAMELEN + 1];
    665 
    666 static void telnet(int, int) __dead;
    667 
    668 /*
    669  * Get a pty, scan input lines.
    670  */
    671 static void
    672 doit(struct sockaddr *who)
    673 {
    674 	char *host;
    675 	int error;
    676 	int level;
    677 	int ptynum;
    678 	int flags;
    679 	char user_name[256];
    680 
    681 	/*
    682 	 * Initialize the slc mapping table.
    683 	 */
    684 	get_slc_defaults();
    685 
    686 	/*
    687 	 * Find an available pty to use.
    688 	 */
    689 	pty = getpty(&ptynum);
    690 	if (pty < 0)
    691 		fatal(net, "All network ports in use");
    692 
    693 	flags = registerd_host_only ? NI_NAMEREQD : 0;
    694 
    695 	/* get name of connected client */
    696 	error = getnameinfo(who, who->sa_len, remote_host_name,
    697 	    sizeof(remote_host_name), NULL, 0, flags);
    698 
    699 	if (error) {
    700 		fatal(net, "Couldn't resolve your address into a host name.\r\n\
    701 	 Please contact your net administrator");
    702 #ifdef __GNUC__
    703 		host = NULL;	/* XXX gcc */
    704 #endif
    705 	}
    706 
    707 	remote_host_name[sizeof(remote_host_name)-1] = 0;
    708 	host = remote_host_name;
    709 
    710 	(void)gethostname(host_name, sizeof(host_name));
    711 	host_name[sizeof(host_name) - 1] = '\0';
    712 	hostname = host_name;
    713 
    714 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
    715 	auth_encrypt_init(hostname, host, "TELNETD", 1);
    716 #endif
    717 
    718 	init_env();
    719 	/*
    720 	 * get terminal type.
    721 	 */
    722 	*user_name = 0;
    723 	level = getterminaltype(user_name, sizeof(user_name));
    724 	setenv("TERM", terminaltype[0] ? terminaltype : "network", 1);
    725 
    726 	/*
    727 	 * Start up the login process on the slave side of the terminal
    728 	 */
    729 	startslave(host, level, user_name);
    730 
    731 	telnet(net, pty);  /* begin server processing */
    732 	/*NOTREACHED*/
    733 }  /* end of doit */
    734 
    735 
    736 /*
    737  * Main loop.  Select from pty and network, and
    738  * hand data to telnet receiver finite state machine.
    739  */
    740 static void
    741 telnet(int f, int p)
    742 {
    743 	int on = 1;
    744 #define	TABBUFSIZ	512
    745 	char	defent[TABBUFSIZ];
    746 	char	defstrs[TABBUFSIZ];
    747 #undef	TABBUFSIZ
    748 	char *HE, *HN, *IF, *ptyibuf2ptr;
    749 	const char *IM;
    750 	struct pollfd set[2];
    751 
    752 	/*
    753 	 * Do some tests where it is desirable to wait for a response.
    754 	 * Rather than doing them slowly, one at a time, do them all
    755 	 * at once.
    756 	 */
    757 	if (my_state_is_wont(TELOPT_SGA))
    758 		send_will(TELOPT_SGA, 1);
    759 	/*
    760 	 * Is the client side a 4.2 (NOT 4.3) system?  We need to know this
    761 	 * because 4.2 clients are unable to deal with TCP urgent data.
    762 	 *
    763 	 * To find out, we send out a "DO ECHO".  If the remote system
    764 	 * answers "WILL ECHO" it is probably a 4.2 client, and we note
    765 	 * that fact ("WILL ECHO" ==> that the client will echo what
    766 	 * WE, the server, sends it; it does NOT mean that the client will
    767 	 * echo the terminal input).
    768 	 */
    769 	send_do(TELOPT_ECHO, 1);
    770 
    771 #ifdef	LINEMODE
    772 	if (his_state_is_wont(TELOPT_LINEMODE)) {
    773 		/* Query the peer for linemode support by trying to negotiate
    774 		 * the linemode option.
    775 		 */
    776 		linemode = 0;
    777 		editmode = 0;
    778 		send_do(TELOPT_LINEMODE, 1);  /* send do linemode */
    779 	}
    780 #endif	/* LINEMODE */
    781 
    782 	/*
    783 	 * Send along a couple of other options that we wish to negotiate.
    784 	 */
    785 	send_do(TELOPT_NAWS, 1);
    786 	send_will(TELOPT_STATUS, 1);
    787 	flowmode = 1;		/* default flow control state */
    788 	restartany = -1;	/* uninitialized... */
    789 	send_do(TELOPT_LFLOW, 1);
    790 
    791 	/*
    792 	 * Spin, waiting for a response from the DO ECHO.  However,
    793 	 * some REALLY DUMB telnets out there might not respond
    794 	 * to the DO ECHO.  So, we spin looking for NAWS, (most dumb
    795 	 * telnets so far seem to respond with WONT for a DO that
    796 	 * they don't understand...) because by the time we get the
    797 	 * response, it will already have processed the DO ECHO.
    798 	 * Kludge upon kludge.
    799 	 */
    800 	while (his_will_wont_is_changing(TELOPT_NAWS))
    801 		ttloop();
    802 
    803 	/*
    804 	 * But...
    805 	 * The client might have sent a WILL NAWS as part of its
    806 	 * startup code; if so, we'll be here before we get the
    807 	 * response to the DO ECHO.  We'll make the assumption
    808 	 * that any implementation that understands about NAWS
    809 	 * is a modern enough implementation that it will respond
    810 	 * to our DO ECHO request; hence we'll do another spin
    811 	 * waiting for the ECHO option to settle down, which is
    812 	 * what we wanted to do in the first place...
    813 	 */
    814 	if (his_want_state_is_will(TELOPT_ECHO) &&
    815 	    his_state_is_will(TELOPT_NAWS)) {
    816 		while (his_will_wont_is_changing(TELOPT_ECHO))
    817 			ttloop();
    818 	}
    819 	/*
    820 	 * On the off chance that the telnet client is broken and does not
    821 	 * respond to the DO ECHO we sent, (after all, we did send the
    822 	 * DO NAWS negotiation after the DO ECHO, and we won't get here
    823 	 * until a response to the DO NAWS comes back) simulate the
    824 	 * receipt of a will echo.  This will also send a WONT ECHO
    825 	 * to the client, since we assume that the client failed to
    826 	 * respond because it believes that it is already in DO ECHO
    827 	 * mode, which we do not want.
    828 	 */
    829 	if (his_want_state_is_will(TELOPT_ECHO)) {
    830 		DIAG(TD_OPTIONS,
    831 			{output_data("td: simulating recv\r\n");});
    832 		willoption(TELOPT_ECHO);
    833 	}
    834 
    835 	/*
    836 	 * Finally, to clean things up, we turn on our echo.  This
    837 	 * will break stupid 4.2 telnets out of local terminal echo.
    838 	 */
    839 
    840 	if (my_state_is_wont(TELOPT_ECHO))
    841 		send_will(TELOPT_ECHO, 1);
    842 
    843 	/*
    844 	 * Turn on packet mode
    845 	 */
    846 	(void) ioctl(p, TIOCPKT, (char *)&on);
    847 
    848 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
    849 	/*
    850 	 * Continuing line mode support.  If client does not support
    851 	 * real linemode, attempt to negotiate kludge linemode by sending
    852 	 * the do timing mark sequence.
    853 	 */
    854 	if (lmodetype < REAL_LINEMODE)
    855 		send_do(TELOPT_TM, 1);
    856 #endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
    857 
    858 	/*
    859 	 * Call telrcv() once to pick up anything received during
    860 	 * terminal type negotiation, 4.2/4.3 determination, and
    861 	 * linemode negotiation.
    862 	 */
    863 	telrcv();
    864 
    865 	(void) ioctl(f, FIONBIO, (char *)&on);
    866 	(void) ioctl(p, FIONBIO, (char *)&on);
    867 
    868 	(void) setsockopt(f, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof on);
    869 
    870 	(void) signal(SIGTSTP, SIG_IGN);
    871 	/*
    872 	 * Ignoring SIGTTOU keeps the kernel from blocking us
    873 	 * in ttioct() in /sys/tty.c.
    874 	 */
    875 	(void) signal(SIGTTOU, SIG_IGN);
    876 
    877 	(void) signal(SIGCHLD, cleanup);
    878 
    879 
    880 	{
    881 		int t;
    882 		t = open(_PATH_TTY, O_RDWR);
    883 		if (t >= 0) {
    884 			(void) ioctl(t, TIOCNOTTY, (char *)0);
    885 			(void) close(t);
    886 		}
    887 	}
    888 
    889 
    890 	/*
    891 	 * Show banner that getty never gave.
    892 	 *
    893 	 * We put the banner in the pty input buffer.  This way, it
    894 	 * gets carriage return null processing, etc., just like all
    895 	 * other pty --> client data.
    896 	 */
    897 
    898 	if (getent(defent, gettyname) == 1) {
    899 		char *cp=defstrs;
    900 
    901 		HE = getstr("he", &cp);
    902 		HN = getstr("hn", &cp);
    903 		IM = getstr("im", &cp);
    904 		IF = getstr("if", &cp);
    905 		if (HN && *HN)
    906 			(void)strlcpy(host_name, HN, sizeof(host_name));
    907 		if (IM == 0)
    908 			IM = "";
    909 	} else {
    910 		IM = DEFAULT_IM;
    911 		HE = 0;
    912 		IF = NULL;
    913 	}
    914 	edithost(HE, host_name);
    915 	ptyibuf2ptr = ptyibuf2;
    916 	if (hostinfo) {
    917 		if (IF)	{
    918 			char buf[_POSIX2_LINE_MAX];
    919 			FILE *fd;
    920 
    921 			if ((fd = fopen(IF, "r")) != NULL) {
    922 				while (fgets(buf, sizeof(buf) - 1, fd) != NULL)
    923 					ptyibuf2ptr = putf(buf, ptyibuf2ptr);
    924 				fclose(fd);
    925 			}
    926 		}
    927 		if (*IM)
    928 			ptyibuf2ptr = putf(IM, ptyibuf2ptr);
    929 	}
    930 
    931 	if (pcc)
    932 		strncpy(ptyibuf2ptr, ptyip, pcc+1);
    933 	ptyip = ptyibuf2;
    934 	pcc = strlen(ptyip);
    935 #ifdef	LINEMODE
    936 	/*
    937 	 * Last check to make sure all our states are correct.
    938 	 */
    939 	init_termbuf();
    940 	localstat();
    941 #endif	/* LINEMODE */
    942 
    943 	DIAG(TD_REPORT,
    944 		{output_data("td: Entering processing loop\r\n");});
    945 
    946 
    947 	set[0].fd = f;
    948 	set[1].fd = p;
    949 	for (;;) {
    950 		int c;
    951 
    952 		if (ncc < 0 && pcc < 0)
    953 			break;
    954 
    955 		/*
    956 		 * Never look for input if there's still
    957 		 * stuff in the corresponding output buffer
    958 		 */
    959 		set[0].events = 0;
    960 		set[1].events = 0;
    961 		if (nfrontp - nbackp || pcc > 0)
    962 			set[0].events |= POLLOUT;
    963 		else
    964 			set[1].events |= POLLIN;
    965 		if (pfrontp - pbackp || ncc > 0)
    966 			set[1].events |= POLLOUT;
    967 		else
    968 			set[0].events |= POLLIN;
    969 		if (!SYNCHing)
    970 			set[0].events |= POLLPRI;
    971 
    972 		if ((c = poll(set, 2, INFTIM)) < 1) {
    973 			if (c == -1) {
    974 				if (errno == EINTR) {
    975 					continue;
    976 				}
    977 			}
    978 			sleep(5);
    979 			continue;
    980 		}
    981 
    982 		/*
    983 		 * Any urgent data?
    984 		 */
    985 		if (set[0].revents & POLLPRI) {
    986 		    SYNCHing = 1;
    987 		}
    988 
    989 		/*
    990 		 * Something to read from the network...
    991 		 */
    992 		if (set[0].revents & POLLIN) {
    993 		    ncc = read(f, netibuf, sizeof (netibuf));
    994 		    if (ncc < 0 && errno == EWOULDBLOCK)
    995 			ncc = 0;
    996 		    else {
    997 			if (ncc <= 0) {
    998 			    break;
    999 			}
   1000 			netip = netibuf;
   1001 		    }
   1002 		    DIAG((TD_REPORT | TD_NETDATA),
   1003 			    {output_data("td: netread %d chars\r\n", ncc);});
   1004 		    DIAG(TD_NETDATA, printdata("nd", netip, ncc));
   1005 		}
   1006 
   1007 		/*
   1008 		 * Something to read from the pty...
   1009 		 */
   1010 		if (set[1].revents & POLLIN) {
   1011 			pcc = read(p, ptyibuf, BUFSIZ);
   1012 			/*
   1013 			 * On some systems, if we try to read something
   1014 			 * off the master side before the slave side is
   1015 			 * opened, we get EIO.
   1016 			 */
   1017 			if (pcc < 0 && (errno == EWOULDBLOCK ||
   1018 					errno == EAGAIN ||
   1019 					errno == EIO)) {
   1020 				pcc = 0;
   1021 			} else {
   1022 				if (pcc <= 0)
   1023 					break;
   1024 #ifdef	LINEMODE
   1025 				/*
   1026 				 * If ioctl from pty, pass it through net
   1027 				 */
   1028 				if (ptyibuf[0] & TIOCPKT_IOCTL) {
   1029 					copy_termbuf(ptyibuf+1, pcc-1);
   1030 					localstat();
   1031 					pcc = 1;
   1032 				}
   1033 #endif	/* LINEMODE */
   1034 				if (ptyibuf[0] & TIOCPKT_FLUSHWRITE) {
   1035 					netclear();	/* clear buffer back */
   1036 					/*
   1037 					 * There are client telnets on some
   1038 					 * operating systems get screwed up
   1039 					 * royally if we send them urgent
   1040 					 * mode data.
   1041 					 */
   1042 					output_data("%c%c", IAC, DM);
   1043 					neturg = nfrontp - 1; /* off by one XXX */
   1044 					DIAG(TD_OPTIONS,
   1045 					    printoption("td: send IAC", DM));
   1046 				}
   1047 				if (his_state_is_will(TELOPT_LFLOW) &&
   1048 				    (ptyibuf[0] &
   1049 				     (TIOCPKT_NOSTOP|TIOCPKT_DOSTOP))) {
   1050 					int newflow =
   1051 					    ptyibuf[0] & TIOCPKT_DOSTOP ? 1 : 0;
   1052 					if (newflow != flowmode) {
   1053 						flowmode = newflow;
   1054 						(void) output_data(
   1055 							"%c%c%c%c%c%c",
   1056 							IAC, SB, TELOPT_LFLOW,
   1057 							flowmode ? LFLOW_ON
   1058 								 : LFLOW_OFF,
   1059 							IAC, SE);
   1060 						DIAG(TD_OPTIONS, printsub('>',
   1061 						    (unsigned char *)nfrontp - 4,
   1062 						    4););
   1063 					}
   1064 				}
   1065 				pcc--;
   1066 				ptyip = ptyibuf+1;
   1067 			}
   1068 		}
   1069 
   1070 		while (pcc > 0) {
   1071 			if ((&netobuf[BUFSIZ] - nfrontp) < 2)
   1072 				break;
   1073 			c = *ptyip++ & 0377, pcc--;
   1074 			if (c == IAC)
   1075 				output_data("%c", c);
   1076 			output_data("%c", c);
   1077 			if ((c == '\r') && (my_state_is_wont(TELOPT_BINARY))) {
   1078 				if (pcc > 0 && ((*ptyip & 0377) == '\n')) {
   1079 					output_data("%c", *ptyip++ & 0377);
   1080 					pcc--;
   1081 				} else
   1082 					output_datalen("\0", 1);
   1083 			}
   1084 		}
   1085 
   1086 		if ((set[0].revents & POLLOUT) && (nfrontp - nbackp) > 0)
   1087 			netflush();
   1088 		if (ncc > 0)
   1089 			telrcv();
   1090 		if ((set[1].revents & POLLOUT) && (pfrontp - pbackp) > 0)
   1091 			ptyflush();
   1092 	}
   1093 	cleanup(0);
   1094 }  /* end of telnet */
   1095 
   1096 /*
   1097  * Send interrupt to process on other side of pty.
   1098  * If it is in raw mode, just write NULL;
   1099  * otherwise, write intr char.
   1100  */
   1101 void
   1102 interrupt(void)
   1103 {
   1104 	ptyflush();	/* half-hearted */
   1105 
   1106 	(void) ioctl(pty, TIOCSIG, (char *)SIGINT);
   1107 }
   1108 
   1109 /*
   1110  * Send quit to process on other side of pty.
   1111  * If it is in raw mode, just write NULL;
   1112  * otherwise, write quit char.
   1113  */
   1114 void
   1115 sendbrk(void)
   1116 {
   1117 	ptyflush();	/* half-hearted */
   1118 	(void) ioctl(pty, TIOCSIG, (char *)SIGQUIT);
   1119 }
   1120 
   1121 void
   1122 sendsusp(void)
   1123 {
   1124 	ptyflush();	/* half-hearted */
   1125 	(void) ioctl(pty, TIOCSIG, (char *)SIGTSTP);
   1126 }
   1127 
   1128 /*
   1129  * When we get an AYT, if ^T is enabled, use that.  Otherwise,
   1130  * just send back "[Yes]".
   1131  */
   1132 void
   1133 recv_ayt(void)
   1134 {
   1135 	if (slctab[SLC_AYT].sptr && *slctab[SLC_AYT].sptr != _POSIX_VDISABLE) {
   1136 		(void) ioctl(pty, TIOCSIG, (char *)SIGINFO);
   1137 		return;
   1138 	}
   1139 	(void) output_data("\r\n[Yes]\r\n");
   1140 }
   1141 
   1142 void
   1143 doeof(void)
   1144 {
   1145 	init_termbuf();
   1146 
   1147 #if	defined(LINEMODE) && (VEOF == VMIN)
   1148 	if (!tty_isediting()) {
   1149 		extern char oldeofc;
   1150 		*pfrontp++ = oldeofc;
   1151 		return;
   1152 	}
   1153 #endif
   1154 	*pfrontp++ = slctab[SLC_EOF].sptr ?
   1155 			(unsigned char)*slctab[SLC_EOF].sptr : '\004';
   1156 }
   1157