Home | History | Annotate | Line # | Download | only in telnetd
telnetd.c revision 1.54
      1 /*	$NetBSD: telnetd.c,v 1.54 2012/01/10 23:39:11 joerg 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.54 2012/01/10 23:39:11 joerg 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 #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 const char *gettyname = "default";
    122 char *progname;
    123 
    124 void usage(void) __dead;
    125 int getterminaltype(char *, size_t);
    126 int getent(char *, const char *);
    127 static void doit(struct sockaddr *) __dead;
    128 void _gettermname(void);
    129 int terminaltypeok(char *);
    130 char *getstr(const char *, char **);
    131 
    132 /*
    133  * The string to pass to getopt().  We do it this way so
    134  * that only the actual options that we support will be
    135  * passed off to getopt().
    136  */
    137 char valid_opts[] = {
    138 	'd', ':', 'g', ':', 'h', 'k', 'n', 'S', ':', 'u', ':', 'U',
    139 	'4', '6',
    140 #ifdef	AUTHENTICATION
    141 	'a', ':', 'X', ':',
    142 #endif
    143 #ifdef	ENCRYPTION
    144 	'e', ':',
    145 #endif
    146 #ifdef DIAGNOSTICS
    147 	'D', ':',
    148 #endif
    149 #ifdef	LINEMODE
    150 	'l',
    151 #endif
    152 #ifdef	SECURELOGIN
    153 	's',
    154 #endif
    155 #ifdef	KRB5
    156 	'R', ':', 'H',
    157 #endif
    158 	'\0'
    159 };
    160 
    161 int family = AF_INET;
    162 struct sockaddr_storage from;
    163 
    164 int
    165 main(int argc, char *argv[])
    166 {
    167 	socklen_t fromlen;
    168 	int on = 1;
    169 	int ch;
    170 #if	defined(IPPROTO_IP) && defined(IP_TOS)
    171 	int tos = -1;
    172 #endif
    173 
    174 	pfrontp = pbackp = ptyobuf;
    175 	netip = netibuf;
    176 	nfrontp = nbackp = netobuf;
    177 #ifdef	ENCRYPTION
    178 	nclearto = 0;
    179 #endif	/* ENCRYPTION */
    180 
    181 	progname = *argv;
    182 
    183 
    184 	while ((ch = getopt(argc, argv, valid_opts)) != -1) {
    185 		switch (ch) {
    186 
    187 #ifdef	AUTHENTICATION
    188 		case 'a':
    189 			/*
    190 			 * Check for required authentication level
    191 			 */
    192 			if (strcmp(optarg, "debug") == 0) {
    193 				auth_debug_mode = 1;
    194 			} else if (strcasecmp(optarg, "none") == 0) {
    195 				auth_level = 0;
    196 			} else if (strcasecmp(optarg, "other") == 0) {
    197 				auth_level = AUTH_OTHER;
    198 			} else if (strcasecmp(optarg, "user") == 0) {
    199 				auth_level = AUTH_USER;
    200 			} else if (strcasecmp(optarg, "valid") == 0) {
    201 				auth_level = AUTH_VALID;
    202 			} else if (strcasecmp(optarg, "off") == 0) {
    203 				/*
    204 				 * This hack turns off authentication
    205 				 */
    206 				auth_level = -1;
    207 			} else {
    208 				fprintf(stderr,
    209 			    "telnetd: unknown authorization level for -a\n");
    210 			}
    211 			break;
    212 #endif	/* AUTHENTICATION */
    213 
    214 
    215 		case 'd':
    216 			if (strcmp(optarg, "ebug") == 0) {
    217 				debug++;
    218 				break;
    219 			}
    220 			usage();
    221 			/* NOTREACHED */
    222 			break;
    223 
    224 #ifdef DIAGNOSTICS
    225 		case 'D':
    226 			/*
    227 			 * Check for desired diagnostics capabilities.
    228 			 */
    229 			if (!strcmp(optarg, "report")) {
    230 				diagnostic |= TD_REPORT|TD_OPTIONS;
    231 			} else if (!strcmp(optarg, "exercise")) {
    232 				diagnostic |= TD_EXERCISE;
    233 			} else if (!strcmp(optarg, "netdata")) {
    234 				diagnostic |= TD_NETDATA;
    235 			} else if (!strcmp(optarg, "ptydata")) {
    236 				diagnostic |= TD_PTYDATA;
    237 			} else if (!strcmp(optarg, "options")) {
    238 				diagnostic |= TD_OPTIONS;
    239 			} else {
    240 				usage();
    241 				/* NOT REACHED */
    242 			}
    243 			break;
    244 #endif /* DIAGNOSTICS */
    245 
    246 #ifdef	ENCRYPTION
    247 		case 'e':
    248 			if (strcmp(optarg, "debug") == 0) {
    249 				encrypt_debug_mode = 1;
    250 				break;
    251 			}
    252 			usage();
    253 			/* NOTREACHED */
    254 			break;
    255 #endif	/* ENCRYPTION */
    256 
    257 		case 'g':
    258 			gettyname = optarg;
    259 			break;
    260 
    261 		case 'h':
    262 			hostinfo = 0;
    263 			break;
    264 
    265 #ifdef	KRB5
    266 		case 'H':
    267 		    {
    268 			require_hwpreauth = 1;
    269 			break;
    270 		    }
    271 #endif	/* KRB5 */
    272 
    273 
    274 #ifdef	LINEMODE
    275 		case 'l':
    276 			alwayslinemode = 1;
    277 			break;
    278 #endif	/* LINEMODE */
    279 
    280 		case 'k':
    281 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
    282 			lmodetype = NO_AUTOKLUDGE;
    283 #else
    284 			/* ignore -k option if built without kludge linemode */
    285 #endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
    286 			break;
    287 
    288 		case 'n':
    289 			keepalive = 0;
    290 			break;
    291 
    292 
    293 #ifdef	KRB5
    294 		case 'R':
    295 		    {
    296 			krb5_error_code retval;
    297 
    298 			if (telnet_context == 0) {
    299 				retval = krb5_init_context(&telnet_context);
    300 				if (retval) {
    301 					com_err("telnetd", retval,
    302 					    "while initializing krb5");
    303 					exit(1);
    304 				}
    305 			}
    306 			krb5_set_default_realm(telnet_context, optarg);
    307 			break;
    308 		    }
    309 #endif	/* KRB5 */
    310 
    311 #ifdef	SECURELOGIN
    312 		case 's':
    313 			/* Secure login required */
    314 			require_secure_login = 1;
    315 			break;
    316 #endif	/* SECURELOGIN */
    317 		case 'S':
    318 			fprintf(stderr, "%s%s\n", "TOS option unavailable; ",
    319 						"-S flag not supported\n");
    320 			break;
    321 
    322 		case 'u':
    323 			fprintf(stderr, "telnetd: -u option unneeded\n");
    324 			break;
    325 
    326 		case 'U':
    327 			registerd_host_only = 1;
    328 			break;
    329 
    330 #ifdef	AUTHENTICATION
    331 		case 'X':
    332 			/*
    333 			 * Check for invalid authentication types
    334 			 */
    335 			auth_disable_name(optarg);
    336 			break;
    337 #endif	/* AUTHENTICATION */
    338 
    339 		case '4':
    340 			family = AF_INET;
    341 			break;
    342 
    343 		case '6':
    344 			family = AF_INET6;
    345 			break;
    346 
    347 		default:
    348 			fprintf(stderr, "telnetd: %c: unknown option\n", ch);
    349 			/* FALLTHROUGH */
    350 		case '?':
    351 			usage();
    352 			/* NOTREACHED */
    353 		}
    354 	}
    355 
    356 	argc -= optind;
    357 	argv += optind;
    358 
    359 	if (debug) {
    360 	    int s, ns, error;
    361 	    socklen_t foo;
    362 	    const char *service = "telnet";
    363 	    struct addrinfo hints, *res;
    364 
    365 	    if (argc > 1) {
    366 		usage();
    367 		/* NOT REACHED */
    368 	    } else if (argc == 1)
    369 		service = *argv;
    370 
    371 	    memset(&hints, 0, sizeof(hints));
    372 	    hints.ai_flags = AI_PASSIVE;
    373 	    hints.ai_family = family;
    374 	    hints.ai_socktype = SOCK_STREAM;
    375 	    hints.ai_protocol = 0;
    376 	    error = getaddrinfo(NULL, service, &hints, &res);
    377 
    378 	    if (error) {
    379 		fprintf(stderr, "tcp/%s: %s\n", service, gai_strerror(error));
    380 		exit(1);
    381 	    }
    382 
    383 	    s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    384 	    if (s < 0) {
    385 		perror("telnetd: socket");
    386 		exit(1);
    387 	    }
    388 	    (void) setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
    389 				(char *)&on, sizeof(on));
    390 	    if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
    391 		perror("bind");
    392 		exit(1);
    393 	    }
    394 	    if (listen(s, 1) < 0) {
    395 		perror("listen");
    396 		exit(1);
    397 	    }
    398 	    foo = res->ai_addrlen;
    399 	    ns = accept(s, res->ai_addr, &foo);
    400 	    if (ns < 0) {
    401 		perror("accept");
    402 		exit(1);
    403 	    }
    404 	    (void) dup2(ns, 0);
    405 	    (void) close(ns);
    406 	    (void) close(s);
    407 	} else if (argc > 0) {
    408 		usage();
    409 		/* NOT REACHED */
    410 	}
    411 
    412 	openlog("telnetd", LOG_PID, LOG_DAEMON);
    413 	fromlen = sizeof (from);
    414 	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
    415 		fprintf(stderr, "%s: ", progname);
    416 		perror("getpeername");
    417 		_exit(1);
    418 	}
    419 	if (keepalive &&
    420 	    setsockopt(0, SOL_SOCKET, SO_KEEPALIVE,
    421 			(char *)&on, sizeof (on)) < 0) {
    422 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
    423 	}
    424 
    425 #if	defined(IPPROTO_IP) && defined(IP_TOS)
    426 	if (((struct sockaddr *)&from)->sa_family == AF_INET) {
    427 		if (tos < 0)
    428 			tos = 020;	/* Low Delay bit */
    429 		if (tos
    430 		   && (setsockopt(0, IPPROTO_IP, IP_TOS,
    431 				  (char *)&tos, sizeof(tos)) < 0)
    432 		   && (errno != ENOPROTOOPT) )
    433 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
    434 	}
    435 #endif	/* defined(IPPROTO_IP) && defined(IP_TOS) */
    436 
    437 	net = 0;
    438 	doit((struct sockaddr *)&from);
    439 	/* NOTREACHED */
    440 #ifdef __GNUC__
    441 	exit(0);
    442 #endif
    443 }  /* end of main */
    444 
    445 void
    446 usage(void)
    447 {
    448 	fprintf(stderr, "Usage: telnetd");
    449 #ifdef	AUTHENTICATION
    450 	fprintf(stderr, " [-a (debug|other|user|valid|off|none)]\n\t");
    451 #endif
    452 	fprintf(stderr, " [-debug]");
    453 #ifdef DIAGNOSTICS
    454 	fprintf(stderr, " [-D (options|report|exercise|netdata|ptydata)]\n\t");
    455 #endif
    456 #ifdef	ENCRYPTION
    457 	fprintf(stderr, " [-edebug]");
    458 #endif
    459 	fprintf(stderr, " [-h]");
    460 #if	defined(LINEMODE) && defined(KLUDGELINEMODE)
    461 	fprintf(stderr, " [-k]");
    462 #endif
    463 #ifdef LINEMODE
    464 	fprintf(stderr, " [-l]");
    465 #endif
    466 	fprintf(stderr, " [-n]");
    467 	fprintf(stderr, "\n\t");
    468 #ifdef	SECURELOGIN
    469 	fprintf(stderr, " [-s]");
    470 #endif
    471 #ifdef	AUTHENTICATION
    472 	fprintf(stderr, " [-X auth-type]");
    473 #endif
    474 	fprintf(stderr, " [-u utmp_hostname_length] [-U]");
    475 	fprintf(stderr, " [port]\n");
    476 	exit(1);
    477 }
    478 
    479 /*
    480  * getterminaltype
    481  *
    482  *	Ask the other end to send along its terminal type and speed.
    483  * Output is the variable terminaltype filled in.
    484  */
    485 static unsigned char ttytype_sbbuf[] = {
    486 	IAC, SB, TELOPT_TTYPE, TELQUAL_SEND, IAC, SE
    487 };
    488 
    489 int
    490 getterminaltype(char *name, size_t l)
    491 {
    492     int retval = -1;
    493 
    494     settimer(baseline);
    495 #ifdef AUTHENTICATION
    496     /*
    497      * Handle the Authentication option before we do anything else.
    498      */
    499     send_do(TELOPT_AUTHENTICATION, 1);
    500     while (his_will_wont_is_changing(TELOPT_AUTHENTICATION))
    501 	ttloop();
    502     if (his_state_is_will(TELOPT_AUTHENTICATION)) {
    503 	retval = auth_wait(name, l);
    504     }
    505 #endif
    506 
    507 #ifdef	ENCRYPTION
    508     send_will(TELOPT_ENCRYPT, 1);
    509 #endif	/* ENCRYPTION */
    510     send_do(TELOPT_TTYPE, 1);
    511     send_do(TELOPT_TSPEED, 1);
    512     send_do(TELOPT_XDISPLOC, 1);
    513     send_do(TELOPT_NEW_ENVIRON, 1);
    514     send_do(TELOPT_OLD_ENVIRON, 1);
    515     while (
    516 #ifdef	ENCRYPTION
    517 	   his_do_dont_is_changing(TELOPT_ENCRYPT) ||
    518 #endif	/* ENCRYPTION */
    519 	   his_will_wont_is_changing(TELOPT_TTYPE) ||
    520 	   his_will_wont_is_changing(TELOPT_TSPEED) ||
    521 	   his_will_wont_is_changing(TELOPT_XDISPLOC) ||
    522 	   his_will_wont_is_changing(TELOPT_NEW_ENVIRON) ||
    523 	   his_will_wont_is_changing(TELOPT_OLD_ENVIRON)) {
    524 	ttloop();
    525     }
    526     if (his_state_is_will(TELOPT_TSPEED)) {
    527 	static unsigned char sb[] =
    528 			{ IAC, SB, TELOPT_TSPEED, TELQUAL_SEND, IAC, SE };
    529 
    530 	output_datalen((const char *)sb, sizeof sb);
    531 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
    532     }
    533 #ifdef	ENCRYPTION
    534     /*
    535      * Wait for the negotiation of what type of encryption we can
    536      * send with.  If autoencrypt is not set, this will just return.
    537      */
    538     if (his_state_is_will(TELOPT_ENCRYPT)) {
    539 	encrypt_wait();
    540     }
    541 #endif	/* ENCRYPTION */
    542     if (his_state_is_will(TELOPT_XDISPLOC)) {
    543 	static unsigned char sb[] =
    544 			{ IAC, SB, TELOPT_XDISPLOC, TELQUAL_SEND, IAC, SE };
    545 
    546 	output_datalen((const char *)sb, sizeof sb);
    547 	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
    548     }
    549     if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
    550 	static unsigned char sb[] =
    551 			{ IAC, SB, TELOPT_NEW_ENVIRON, 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     else if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
    557 	static unsigned char sb[] =
    558 			{ IAC, SB, TELOPT_OLD_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     if (his_state_is_will(TELOPT_TTYPE)) {
    564 
    565 	output_datalen((const char *)ttytype_sbbuf, sizeof ttytype_sbbuf);
    566 	DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
    567 					sizeof ttytype_sbbuf - 2););
    568     }
    569     if (his_state_is_will(TELOPT_TSPEED)) {
    570 	while (sequenceIs(tspeedsubopt, baseline))
    571 	    ttloop();
    572     }
    573     if (his_state_is_will(TELOPT_XDISPLOC)) {
    574 	while (sequenceIs(xdisplocsubopt, baseline))
    575 	    ttloop();
    576     }
    577     if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
    578 	while (sequenceIs(environsubopt, baseline))
    579 	    ttloop();
    580     }
    581     if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
    582 	while (sequenceIs(oenvironsubopt, baseline))
    583 	    ttloop();
    584     }
    585     if (his_state_is_will(TELOPT_TTYPE)) {
    586 	char first[256], last[256];
    587 
    588 	while (sequenceIs(ttypesubopt, baseline))
    589 	    ttloop();
    590 
    591 	/*
    592 	 * If the other side has already disabled the option, then
    593 	 * we have to just go with what we (might) have already gotten.
    594 	 */
    595 	if (his_state_is_will(TELOPT_TTYPE) && !terminaltypeok(terminaltype)) {
    596 	    (void) strlcpy(first, terminaltype, sizeof(first));
    597 	    for(;;) {
    598 		/*
    599 		 * Save the unknown name, and request the next name.
    600 		 */
    601 		(void) strlcpy(last, terminaltype, sizeof(last));
    602 		_gettermname();
    603 		if (terminaltypeok(terminaltype))
    604 		    break;
    605 		if ((strncmp(last, terminaltype, sizeof(last)) == 0) ||
    606 		    his_state_is_wont(TELOPT_TTYPE)) {
    607 		    /*
    608 		     * We've hit the end.  If this is the same as
    609 		     * the first name, just go with it.
    610 		     */
    611 		    if (strncmp(first, terminaltype, sizeof(first)) == 0)
    612 			break;
    613 		    /*
    614 		     * Get the terminal name one more time, so that
    615 		     * RFC1091 compliant telnets will cycle back to
    616 		     * the start of the list.
    617 		     */
    618 		     _gettermname();
    619 		    if (strncmp(first, terminaltype, sizeof(first)) != 0) {
    620 			(void) strlcpy(terminaltype, first, sizeof(terminaltype));
    621 		    }
    622 		    break;
    623 		}
    624 	    }
    625 	}
    626     }
    627     return(retval);
    628 }  /* end of getterminaltype */
    629 
    630 void
    631 _gettermname(void)
    632 {
    633     /*
    634      * If the client turned off the option,
    635      * we can't send another request, so we
    636      * just return.
    637      */
    638     if (his_state_is_wont(TELOPT_TTYPE))
    639 	return;
    640     settimer(baseline);
    641     output_datalen((const char *)ttytype_sbbuf, sizeof ttytype_sbbuf);
    642     DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
    643 					sizeof ttytype_sbbuf - 2););
    644     while (sequenceIs(ttypesubopt, baseline))
    645 	ttloop();
    646 }
    647 
    648 int
    649 terminaltypeok(char *s)
    650 {
    651     char buf[1024];
    652 
    653     if (terminaltype == NULL)
    654 	return(1);
    655 
    656     /*
    657      * tgetent() will return 1 if the type is known, and
    658      * 0 if it is not known.  If it returns -1, it couldn't
    659      * open the database.  But if we can't open the database,
    660      * it won't help to say we failed, because we won't be
    661      * able to verify anything else.  So, we treat -1 like 1.
    662      */
    663     if (tgetent(buf, s) == 0)
    664 	return(0);
    665     return(1);
    666 }
    667 
    668 char *hostname;
    669 char host_name[MAXHOSTNAMELEN + 1];
    670 char remote_host_name[MAXHOSTNAMELEN + 1];
    671 
    672 static void telnet(int, int) __dead;
    673 
    674 /*
    675  * Get a pty, scan input lines.
    676  */
    677 static void
    678 doit(struct sockaddr *who)
    679 {
    680 	char *host;
    681 	int error;
    682 	int level;
    683 	int ptynum;
    684 	int flags;
    685 	char user_name[256];
    686 
    687 	/*
    688 	 * Find an available pty to use.
    689 	 */
    690 	pty = getpty(&ptynum);
    691 	if (pty < 0)
    692 		fatal(net, "All network ports in use");
    693 
    694 	flags = registerd_host_only ? NI_NAMEREQD : 0;
    695 
    696 	/* get name of connected client */
    697 	error = getnameinfo(who, who->sa_len, remote_host_name,
    698 	    sizeof(remote_host_name), NULL, 0, flags);
    699 
    700 	if (error) {
    701 		fatal(net, "Couldn't resolve your address into a host name.\r\n\
    702 	 Please contact your net administrator");
    703 #ifdef __GNUC__
    704 		host = NULL;	/* XXX gcc */
    705 #endif
    706 	}
    707 
    708 	remote_host_name[sizeof(remote_host_name)-1] = 0;
    709 	host = remote_host_name;
    710 
    711 	(void)gethostname(host_name, sizeof(host_name));
    712 	host_name[sizeof(host_name) - 1] = '\0';
    713 	hostname = host_name;
    714 
    715 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
    716 	auth_encrypt_init(hostname, host, "TELNETD", 1);
    717 #endif
    718 
    719 	init_env();
    720 	/*
    721 	 * get terminal type.
    722 	 */
    723 	*user_name = 0;
    724 	level = getterminaltype(user_name, sizeof(user_name));
    725 	setenv("TERM", terminaltype[0] ? terminaltype : "network", 1);
    726 
    727 	/*
    728 	 * Start up the login process on the slave side of the terminal
    729 	 */
    730 	startslave(host, level, user_name);
    731 
    732 	telnet(net, pty);  /* begin server processing */
    733 	/*NOTREACHED*/
    734 }  /* end of doit */
    735 
    736 
    737 /*
    738  * Main loop.  Select from pty and network, and
    739  * hand data to telnet receiver finite state machine.
    740  */
    741 static void
    742 telnet(int f, int p)
    743 {
    744 	int on = 1;
    745 #define	TABBUFSIZ	512
    746 	char	defent[TABBUFSIZ];
    747 	char	defstrs[TABBUFSIZ];
    748 #undef	TABBUFSIZ
    749 	char *HE, *HN, *IF, *ptyibuf2ptr;
    750 	const char *IM;
    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