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