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