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