1/*
2 * Copyright (c) 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#if 0
35#ifndef lint
36static const char sccsid[] = "@(#)telnetd.c	8.4 (Berkeley) 5/30/95";
37#endif
38#endif
39#include <sys/cdefs.h>
40__FBSDID("$FreeBSD: src/contrib/telnet/telnetd/telnetd.c,v 1.29 2006/09/26 21:46:11 ru Exp $");
41
42#include "telnetd.h"
43#include "pathnames.h"
44
45#include <sys/mman.h>
46#include <err.h>
47#ifndef __APPLE__
48#include <libutil.h>
49#endif
50#include <paths.h>
51#include <termcap.h>
52#ifndef __APPLE__
53#include <utmp.h>
54#endif
55
56#include <arpa/inet.h>
57
58#ifdef	AUTHENTICATION
59#include <libtelnet/auth.h>
60int	auth_level = 0;
61#endif
62#ifdef	ENCRYPTION
63#include <libtelnet/encrypt.h>
64#endif
65#include <libtelnet/misc.h>
66
67char	remote_hostname[MAXHOSTNAMELEN];
68size_t	utmp_len = sizeof(remote_hostname) - 1;
69int	registerd_host_only = 0;
70
71
72/*
73 * I/O data buffers,
74 * pointers, and counters.
75 */
76char	ptyibuf[BUFSIZ], *ptyip = ptyibuf;
77char	ptyibuf2[BUFSIZ];
78
79int readstream(int, char *, int);
80void doit(struct sockaddr *);
81int terminaltypeok(char *);
82
83int	hostinfo = 1;			/* do we print login banner? */
84
85static int debug = 0;
86int keepalive = 1;
87const char *altlogin;
88
89void doit(struct sockaddr *);
90int terminaltypeok(char *);
91void startslave(char *, int, char *);
92extern void usage(void);
93static void _gettermname(void);
94
95/*
96 * The string to pass to getopt().  We do it this way so
97 * that only the actual options that we support will be
98 * passed off to getopt().
99 */
100char valid_opts[] = {
101	'd', ':', 'h', 'k', 'n', 'p', ':', 'S', ':', 'u', ':', 'U',
102	'4', '6',
103#ifdef	AUTHENTICATION
104	'a', ':', 'X', ':',
105#endif
106#ifdef BFTPDAEMON
107	'B',
108#endif
109#ifdef DIAGNOSTICS
110	'D', ':',
111#endif
112#ifdef	ENCRYPTION
113	'e', ':',
114#endif
115#ifdef	LINEMODE
116	'l',
117#endif
118	'\0'
119};
120
121int family = AF_INET;
122
123#ifndef	MAXHOSTNAMELEN
124#define	MAXHOSTNAMELEN 256
125#endif	/* MAXHOSTNAMELEN */
126
127char *hostname;
128char host_name[MAXHOSTNAMELEN];
129
130extern void telnet(int, int, char *);
131
132int level;
133char user_name[256];
134
135int
136main(int argc, char *argv[])
137{
138	u_long ultmp;
139	struct sockaddr_storage from;
140#ifdef __APPLE__
141	int on = 1;
142	socklen_t fromlen;
143#else
144	int on = 1, fromlen;
145#endif
146	int ch;
147#if	defined(IPPROTO_IP) && defined(IP_TOS)
148	int tos = -1;
149#endif
150	char *ep;
151
152	// radar:17828581
153	(void)signal(SIGTERM, SIG_DFL);
154
155	pfrontp = pbackp = ptyobuf;
156	netip = netibuf;
157	nfrontp = nbackp = netobuf;
158#ifdef	ENCRYPTION
159	nclearto = 0;
160#endif	/* ENCRYPTION */
161
162	/*
163	 * This initialization causes linemode to default to a configuration
164	 * that works on all telnet clients, including the FreeBSD client.
165	 * This is not quite the same as the telnet client issuing a "mode
166	 * character" command, but has most of the same benefits, and is
167	 * preferable since some clients (like usofts) don't have the
168	 * mode character command anyway and linemode breaks things.
169	 * The most notable symptom of fix is that csh "set filec" operations
170	 * like <ESC> (filename completion) and ^D (choices) keys now work
171	 * in telnet sessions and can be used more than once on the same line.
172	 * CR/LF handling is also corrected in some termio modes.  This
173	 * change resolves problem reports bin/771 and bin/1037.
174	 */
175
176	linemode=1;	/*Default to mode that works on bulk of clients*/
177
178	while ((ch = getopt(argc, argv, valid_opts)) != -1) {
179		switch(ch) {
180
181#ifdef	AUTHENTICATION
182		case 'a':
183			/*
184			 * Check for required authentication level
185			 */
186			if (strcmp(optarg, "debug") == 0) {
187				extern int auth_debug_mode;
188				auth_debug_mode = 1;
189			} else if (strcasecmp(optarg, "none") == 0) {
190				auth_level = 0;
191			} else if (strcasecmp(optarg, "other") == 0) {
192				auth_level = AUTH_OTHER;
193			} else if (strcasecmp(optarg, "user") == 0) {
194				auth_level = AUTH_USER;
195			} else if (strcasecmp(optarg, "valid") == 0) {
196				auth_level = AUTH_VALID;
197			} else if (strcasecmp(optarg, "off") == 0) {
198				/*
199				 * This hack turns off authentication
200				 */
201				auth_level = -1;
202			} else {
203				warnx("unknown authorization level for -a");
204			}
205			break;
206#endif	/* AUTHENTICATION */
207
208#ifdef BFTPDAEMON
209		case 'B':
210			bftpd++;
211			break;
212#endif /* BFTPDAEMON */
213
214		case 'd':
215			if (strcmp(optarg, "ebug") == 0) {
216				debug++;
217				break;
218			}
219			usage();
220			/* NOTREACHED */
221			break;
222
223#ifdef DIAGNOSTICS
224		case 'D':
225			/*
226			 * Check for desired diagnostics capabilities.
227			 */
228			if (!strcmp(optarg, "report")) {
229				diagnostic |= TD_REPORT|TD_OPTIONS;
230			} else if (!strcmp(optarg, "exercise")) {
231				diagnostic |= TD_EXERCISE;
232			} else if (!strcmp(optarg, "netdata")) {
233				diagnostic |= TD_NETDATA;
234			} else if (!strcmp(optarg, "ptydata")) {
235				diagnostic |= TD_PTYDATA;
236			} else if (!strcmp(optarg, "options")) {
237				diagnostic |= TD_OPTIONS;
238			} else {
239				usage();
240				/* NOT REACHED */
241			}
242			break;
243#endif /* DIAGNOSTICS */
244
245#ifdef	ENCRYPTION
246		case 'e':
247			if (strcmp(optarg, "debug") == 0) {
248				extern int encrypt_debug_mode;
249				encrypt_debug_mode = 1;
250				break;
251			}
252			usage();
253			/* NOTREACHED */
254			break;
255#endif	/* ENCRYPTION */
256
257		case 'h':
258			hostinfo = 0;
259			break;
260
261#ifdef	LINEMODE
262		case 'l':
263			alwayslinemode = 1;
264			break;
265#endif	/* LINEMODE */
266
267		case 'k':
268#if	defined(LINEMODE) && defined(KLUDGELINEMODE)
269			lmodetype = NO_AUTOKLUDGE;
270#else
271			/* ignore -k option if built without kludge linemode */
272#endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
273			break;
274
275		case 'n':
276			keepalive = 0;
277			break;
278
279		case 'p':
280			altlogin = optarg;
281			break;
282
283		case 'S':
284#ifdef	HAS_GETTOS
285			if ((tos = parsetos(optarg, "tcp")) < 0)
286				warnx("%s%s%s",
287					"bad TOS argument '", optarg,
288					"'; will try to use default TOS");
289#else
290#define	MAXTOS	255
291			ultmp = strtoul(optarg, &ep, 0);
292			if (*ep || ep == optarg || ultmp > MAXTOS)
293				warnx("%s%s%s",
294					"bad TOS argument '", optarg,
295					"'; will try to use default TOS");
296			else
297				tos = ultmp;
298#endif
299			break;
300
301		case 'u':
302			utmp_len = (size_t)atoi(optarg);
303			if (utmp_len >= sizeof(remote_hostname))
304				utmp_len = sizeof(remote_hostname) - 1;
305			break;
306
307		case 'U':
308			registerd_host_only = 1;
309			break;
310
311#ifdef	AUTHENTICATION
312		case 'X':
313			/*
314			 * Check for invalid authentication types
315			 */
316			auth_disable_name(optarg);
317			break;
318#endif	/* AUTHENTICATION */
319
320		case '4':
321			family = AF_INET;
322			break;
323
324#ifdef INET6
325		case '6':
326			family = AF_INET6;
327			break;
328#endif
329
330		default:
331			warnx("%c: unknown option", ch);
332			/* FALLTHROUGH */
333		case '?':
334			usage();
335			/* NOTREACHED */
336		}
337	}
338
339	argc -= optind;
340	argv += optind;
341
342	if (debug) {
343#ifdef __APPLE__
344		int s, ns, error;
345		socklen_t foo;
346#else
347	    int s, ns, foo, error;
348#endif
349	    const char *service = "telnet";
350	    struct addrinfo hints, *res;
351
352	    if (argc > 1) {
353		usage();
354		/* NOT REACHED */
355	    } else if (argc == 1)
356		service = *argv;
357
358	    memset(&hints, 0, sizeof(hints));
359	    hints.ai_flags = AI_PASSIVE;
360	    hints.ai_family = family;
361	    hints.ai_socktype = SOCK_STREAM;
362	    hints.ai_protocol = 0;
363	    error = getaddrinfo(NULL, service, &hints, &res);
364
365	    if (error) {
366		errx(1, "tcp/%s: %s\n", service, gai_strerror(error));
367		if (error == EAI_SYSTEM)
368		    errx(1, "tcp/%s: %s\n", service, strerror(errno));
369		usage();
370	    }
371
372	    s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
373	    if (s < 0)
374		    err(1, "socket");
375	    (void) setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
376				(char *)&on, sizeof(on));
377	    if (debug > 1)
378	        (void) setsockopt(s, SOL_SOCKET, SO_DEBUG,
379				(char *)&on, sizeof(on));
380	    if (bind(s, res->ai_addr, res->ai_addrlen) < 0)
381		err(1, "bind");
382	    if (listen(s, 1) < 0)
383		err(1, "listen");
384	    foo = res->ai_addrlen;
385	    ns = accept(s, res->ai_addr, &foo);
386	    if (ns < 0)
387		err(1, "accept");
388	    (void) setsockopt(ns, SOL_SOCKET, SO_DEBUG,
389				(char *)&on, sizeof(on));
390	    (void) dup2(ns, 0);
391	    (void) close(ns);
392	    (void) close(s);
393#ifdef convex
394	} else if (argc == 1) {
395		; /* VOID*/		/* Just ignore the host/port name */
396#endif
397	} else if (argc > 0) {
398		usage();
399		/* NOT REACHED */
400	}
401
402	openlog("telnetd", LOG_PID | LOG_ODELAY, LOG_DAEMON);
403	fromlen = sizeof (from);
404	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
405		warn("getpeername");
406		_exit(1);
407	}
408	if (keepalive &&
409	    setsockopt(0, SOL_SOCKET, SO_KEEPALIVE,
410			(char *)&on, sizeof (on)) < 0) {
411		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
412	}
413
414#if	defined(IPPROTO_IP) && defined(IP_TOS)
415	if (from.ss_family == AF_INET) {
416# if	defined(HAS_GETTOS)
417		struct tosent *tp;
418		if (tos < 0 && (tp = gettosbyname("telnet", "tcp")))
419			tos = tp->t_tos;
420# endif
421		if (tos < 0)
422			tos = 020;	/* Low Delay bit */
423		if (tos
424		   && (setsockopt(0, IPPROTO_IP, IP_TOS,
425				  (char *)&tos, sizeof(tos)) < 0)
426		   && (errno != ENOPROTOOPT) )
427			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
428	}
429#endif	/* defined(IPPROTO_IP) && defined(IP_TOS) */
430	net = 0;
431	doit((struct sockaddr *)&from);
432	/* NOTREACHED */
433	return(0);
434}  /* end of main */
435
436	void
437usage()
438{
439	fprintf(stderr, "usage: telnetd");
440#ifdef	AUTHENTICATION
441	fprintf(stderr,
442	    " [-4] [-6] [-a (debug|other|user|valid|off|none)]\n\t");
443#endif
444#ifdef BFTPDAEMON
445	fprintf(stderr, " [-B]");
446#endif
447	fprintf(stderr, " [-debug]");
448#ifdef DIAGNOSTICS
449	fprintf(stderr, " [-D (options|report|exercise|netdata|ptydata)]\n\t");
450#endif
451#ifdef	AUTHENTICATION
452	fprintf(stderr, " [-edebug]");
453#endif
454	fprintf(stderr, " [-h]");
455#if	defined(LINEMODE) && defined(KLUDGELINEMODE)
456	fprintf(stderr, " [-k]");
457#endif
458#ifdef LINEMODE
459	fprintf(stderr, " [-l]");
460#endif
461	fprintf(stderr, " [-n]");
462	fprintf(stderr, "\n\t");
463#ifdef	HAS_GETTOS
464	fprintf(stderr, " [-S tos]");
465#endif
466#ifdef	AUTHENTICATION
467	fprintf(stderr, " [-X auth-type]");
468#endif
469	fprintf(stderr, " [-u utmp_hostname_length] [-U]");
470	fprintf(stderr, " [port]\n");
471	exit(1);
472}
473
474/*
475 * getterminaltype
476 *
477 *	Ask the other end to send along its terminal type and speed.
478 * Output is the variable terminaltype filled in.
479 */
480static unsigned char ttytype_sbbuf[] = {
481	IAC, SB, TELOPT_TTYPE, TELQUAL_SEND, IAC, SE
482};
483
484
485#ifndef	AUTHENTICATION
486#define undef2 __unused
487#else
488#define undef2
489#endif
490
491static int
492getterminaltype(char *name undef2)
493{
494    int retval = -1;
495
496    settimer(baseline);
497#ifdef	AUTHENTICATION
498    /*
499     * Handle the Authentication option before we do anything else.
500     */
501    send_do(TELOPT_AUTHENTICATION, 1);
502    while (his_will_wont_is_changing(TELOPT_AUTHENTICATION))
503	ttloop();
504    if (his_state_is_will(TELOPT_AUTHENTICATION)) {
505	retval = auth_wait(name);
506    }
507#endif
508
509#ifdef	ENCRYPTION
510    send_will(TELOPT_ENCRYPT, 1);
511#endif	/* ENCRYPTION */
512    send_do(TELOPT_TTYPE, 1);
513    send_do(TELOPT_TSPEED, 1);
514    send_do(TELOPT_XDISPLOC, 1);
515    send_do(TELOPT_NEW_ENVIRON, 1);
516    send_do(TELOPT_OLD_ENVIRON, 1);
517    while (
518#ifdef	ENCRYPTION
519	   his_do_dont_is_changing(TELOPT_ENCRYPT) ||
520#endif	/* ENCRYPTION */
521	   his_will_wont_is_changing(TELOPT_TTYPE) ||
522	   his_will_wont_is_changing(TELOPT_TSPEED) ||
523	   his_will_wont_is_changing(TELOPT_XDISPLOC) ||
524	   his_will_wont_is_changing(TELOPT_NEW_ENVIRON) ||
525	   his_will_wont_is_changing(TELOPT_OLD_ENVIRON)) {
526	ttloop();
527    }
528#ifdef	ENCRYPTION
529    /*
530     * Wait for the negotiation of what type of encryption we can
531     * send with.  If autoencrypt is not set, this will just return.
532     */
533    if (his_state_is_will(TELOPT_ENCRYPT)) {
534	encrypt_wait();
535    }
536#endif	/* ENCRYPTION */
537    if (his_state_is_will(TELOPT_TSPEED)) {
538	static unsigned char sb[] =
539			{ IAC, SB, TELOPT_TSPEED, TELQUAL_SEND, IAC, SE };
540
541	output_datalen((char*)sb, sizeof sb);
542	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
543    }
544    if (his_state_is_will(TELOPT_XDISPLOC)) {
545	static unsigned char sb[] =
546			{ IAC, SB, TELOPT_XDISPLOC, TELQUAL_SEND, IAC, SE };
547
548	output_datalen((char*)sb, sizeof sb);
549	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
550    }
551    if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
552	static unsigned char sb[] =
553			{ IAC, SB, TELOPT_NEW_ENVIRON, TELQUAL_SEND, IAC, SE };
554
555	output_datalen((char*)sb, sizeof sb);
556	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
557    }
558    else if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
559	static unsigned char sb[] =
560			{ IAC, SB, TELOPT_OLD_ENVIRON, TELQUAL_SEND, IAC, SE };
561
562	output_datalen((char*)sb, sizeof sb);
563	DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
564    }
565    if (his_state_is_will(TELOPT_TTYPE)) {
566
567	output_datalen((char*)ttytype_sbbuf, sizeof ttytype_sbbuf);
568	DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
569					sizeof ttytype_sbbuf - 2););
570    }
571    if (his_state_is_will(TELOPT_TSPEED)) {
572	while (sequenceIs(tspeedsubopt, baseline))
573	    ttloop();
574    }
575    if (his_state_is_will(TELOPT_XDISPLOC)) {
576	while (sequenceIs(xdisplocsubopt, baseline))
577	    ttloop();
578    }
579    if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
580	while (sequenceIs(environsubopt, baseline))
581	    ttloop();
582    }
583    if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
584	while (sequenceIs(oenvironsubopt, baseline))
585	    ttloop();
586    }
587    if (his_state_is_will(TELOPT_TTYPE)) {
588	char first[256], last[256];
589
590	while (sequenceIs(ttypesubopt, baseline))
591	    ttloop();
592
593	/*
594	 * If the other side has already disabled the option, then
595	 * we have to just go with what we (might) have already gotten.
596	 */
597	if (his_state_is_will(TELOPT_TTYPE) && !terminaltypeok(terminaltype)) {
598	    (void) strncpy(first, terminaltype, sizeof(first)-1);
599	    first[sizeof(first)-1] = '\0';
600	    for(;;) {
601		/*
602		 * Save the unknown name, and request the next name.
603		 */
604		(void) strncpy(last, terminaltype, sizeof(last)-1);
605		last[sizeof(last)-1] = '\0';
606		_gettermname();
607		if (terminaltypeok(terminaltype))
608		    break;
609		if ((strncmp(last, terminaltype, sizeof(last)) == 0) ||
610		    his_state_is_wont(TELOPT_TTYPE)) {
611		    /*
612		     * We've hit the end.  If this is the same as
613		     * the first name, just go with it.
614		     */
615		    if (strncmp(first, terminaltype, sizeof(first)) == 0)
616			break;
617		    /*
618		     * Get the terminal name one more time, so that
619		     * RFC1091 compliant telnets will cycle back to
620		     * the start of the list.
621		     */
622		     _gettermname();
623		    if (strncmp(first, terminaltype, sizeof(first)) != 0) {
624			(void) strncpy(terminaltype, first, sizeof(terminaltype)-1);
625			terminaltype[sizeof(terminaltype)-1] = '\0';
626		    }
627		    break;
628		}
629	    }
630	}
631    }
632    return(retval);
633}  /* end of getterminaltype */
634
635static void
636_gettermname(void)
637{
638    /*
639     * If the client turned off the option,
640     * we can't send another request, so we
641     * just return.
642     */
643    if (his_state_is_wont(TELOPT_TTYPE))
644	return;
645    settimer(baseline);
646    output_datalen((char*)ttytype_sbbuf, sizeof ttytype_sbbuf);
647    DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
648					sizeof ttytype_sbbuf - 2););
649    while (sequenceIs(ttypesubopt, baseline))
650	ttloop();
651}
652
653int
654terminaltypeok(char *s)
655{
656    char buf[1024];
657
658    if (terminaltype == NULL)
659	return(1);
660
661    /*
662     * tgetent() will return 1 if the type is known, and
663     * 0 if it is not known.  If it returns -1, it couldn't
664     * open the database.  But if we can't open the database,
665     * it won't help to say we failed, because we won't be
666     * able to verify anything else.  So, we treat -1 like 1.
667     */
668    if (tgetent(buf, s) == 0)
669	return(0);
670    return(1);
671}
672
673#ifdef __APPLE__
674#ifndef	MAXHOSTNAMELEN
675#define	MAXHOSTNAMELEN 256
676#endif	/* MAXHOSTNAMELEN */
677
678char *hostname;
679char host_name[MAXHOSTNAMELEN];
680
681int level;
682char user_name[256];
683#endif /* __APPLE__ */
684
685/*
686 * Get a pty, scan input lines.
687 */
688void
689doit(struct sockaddr *who)
690{
691#ifndef __APPLE__
692	int err_; /* XXX */
693#else
694	char *host = NULL;
695	struct hostent *hp;
696#endif
697	int ptynum;
698
699	/*
700	 * Find an available pty to use.
701	 */
702#ifndef	convex
703	spty = -1;
704	mpty = getpty(&ptynum, &spty);
705	if (mpty < 0)
706		fatal(net, "All network ports in use");
707#else
708	for (;;) {
709		char *lp;
710
711		if ((lp = getpty()) == NULL)
712			fatal(net, "Out of ptys");
713
714		if ((pty = open(lp, 2)) >= 0) {
715			strlcpy(line,lp,sizeof(line));
716			line[5] = 't';
717			break;
718		}
719	}
720#endif
721
722#ifdef __APPLE__
723        /* get name of connected client */
724        hp = gethostbyaddr((char *)&((struct sockaddr_in *)who)->sin_addr, sizeof (struct in_addr),
725                ((struct sockaddr_in *)who)->sin_family);
726
727        if (hp == NULL && registerd_host_only) {
728                fatal(net, "Couldn't resolve your address into a host name.\r\n\
729         Please contact your net administrator");
730        } else if (hp &&
731            (strlen(hp->h_name) <= utmp_len)) {
732                host = hp->h_name;
733        } else {
734                host = inet_ntoa(((struct sockaddr_in *)who)->sin_addr);
735        }
736        /*
737         * We must make a copy because Kerberos is probably going
738         * to also do a gethost* and overwrite the static data...
739         */
740        strncpy(remote_hostname, host, sizeof(remote_hostname)-1);
741        remote_hostname[sizeof(remote_hostname)-1] = 0;
742        host = remote_hostname;
743
744	(void) gethostname(host_name, sizeof(host_name) - 1);
745	host_name[sizeof(host_name) - 1] = '\0';
746	hostname = host_name;
747#else /* __APPLE__ */
748	/* get name of connected client */
749	if (realhostname_sa(remote_hostname, sizeof(remote_hostname) - 1,
750	    who, who->sa_len) == HOSTNAME_INVALIDADDR && registerd_host_only)
751		fatal(net, "Couldn't resolve your address into a host name.\r\n\
752	Please contact your net administrator");
753	remote_hostname[sizeof(remote_hostname) - 1] = '\0';
754
755	trimdomain(remote_hostname, UT_HOSTSIZE);
756	if (!isdigit(remote_hostname[0]) && strlen(remote_hostname) > utmp_len)
757		err_ = getnameinfo(who, who->sa_len, remote_hostname,
758				  sizeof(remote_hostname), NULL, 0,
759				  NI_NUMERICHOST);
760		/* XXX: do 'err_' check */
761
762	(void) gethostname(host_name, sizeof(host_name) - 1);
763	host_name[sizeof(host_name) - 1] = '\0';
764	hostname = host_name;
765#endif /* __APPLE__ */
766
767#ifdef	AUTHENTICATION
768#ifdef	ENCRYPTION
769/* The above #ifdefs should actually be "or"'ed, not "and"'ed.
770 * This is a byproduct of needing "#ifdef" and not "#if defined()"
771 * for unifdef. XXX MarkM
772 */
773	auth_encrypt_init(hostname, remote_hostname, "TELNETD", 1);
774#endif
775#endif
776
777	init_env();
778	/*
779	 * get terminal type.
780	 */
781	*user_name = 0;
782	level = getterminaltype(user_name);
783	setenv("TERM", terminaltype ? terminaltype : "network", 1);
784
785	telnet(net, mpty, remote_hostname);	/* begin server process */
786
787	/*NOTREACHED*/
788}  /* end of doit */
789
790/*
791 * Main loop.  Select from pty and network, and
792 * hand data to telnet receiver finite state machine.
793 */
794void
795telnet(int f, int p, char *host)
796{
797	int on = 1;
798#define	TABBUFSIZ	512
799	char	defent[TABBUFSIZ];
800	char	defstrs[TABBUFSIZ];
801#undef	TABBUFSIZ
802	char *HE;
803	char *HN;
804	char *IM;
805#ifdef __APPLE__
806	char *IF = NULL;
807	int if_fd = -1;
808	char *if_buf;
809	struct stat statbuf;
810#endif
811	int nfd;
812
813	/*
814	 * Initialize the slc mapping table.
815	 */
816	get_slc_defaults();
817
818	/*
819	 * Do some tests where it is desireable to wait for a response.
820	 * Rather than doing them slowly, one at a time, do them all
821	 * at once.
822	 */
823	if (my_state_is_wont(TELOPT_SGA))
824		send_will(TELOPT_SGA, 1);
825	/*
826	 * Is the client side a 4.2 (NOT 4.3) system?  We need to know this
827	 * because 4.2 clients are unable to deal with TCP urgent data.
828	 *
829	 * To find out, we send out a "DO ECHO".  If the remote system
830	 * answers "WILL ECHO" it is probably a 4.2 client, and we note
831	 * that fact ("WILL ECHO" ==> that the client will echo what
832	 * WE, the server, sends it; it does NOT mean that the client will
833	 * echo the terminal input).
834	 */
835	send_do(TELOPT_ECHO, 1);
836
837#ifdef	LINEMODE
838	if (his_state_is_wont(TELOPT_LINEMODE)) {
839		/* Query the peer for linemode support by trying to negotiate
840		 * the linemode option.
841		 */
842		linemode = 0;
843		editmode = 0;
844		send_do(TELOPT_LINEMODE, 1);  /* send do linemode */
845	}
846#endif	/* LINEMODE */
847
848	/*
849	 * Send along a couple of other options that we wish to negotiate.
850	 */
851	send_do(TELOPT_NAWS, 1);
852	send_will(TELOPT_STATUS, 1);
853	flowmode = 1;		/* default flow control state */
854	restartany = -1;	/* uninitialized... */
855	send_do(TELOPT_LFLOW, 1);
856
857	/*
858	 * Spin, waiting for a response from the DO ECHO.  However,
859	 * some REALLY DUMB telnets out there might not respond
860	 * to the DO ECHO.  So, we spin looking for NAWS, (most dumb
861	 * telnets so far seem to respond with WONT for a DO that
862	 * they don't understand...) because by the time we get the
863	 * response, it will already have processed the DO ECHO.
864	 * Kludge upon kludge.
865	 */
866	while (his_will_wont_is_changing(TELOPT_NAWS))
867		ttloop();
868
869	/*
870	 * But...
871	 * The client might have sent a WILL NAWS as part of its
872	 * startup code; if so, we'll be here before we get the
873	 * response to the DO ECHO.  We'll make the assumption
874	 * that any implementation that understands about NAWS
875	 * is a modern enough implementation that it will respond
876	 * to our DO ECHO request; hence we'll do another spin
877	 * waiting for the ECHO option to settle down, which is
878	 * what we wanted to do in the first place...
879	 */
880	if (his_want_state_is_will(TELOPT_ECHO) &&
881	    his_state_is_will(TELOPT_NAWS)) {
882		while (his_will_wont_is_changing(TELOPT_ECHO))
883			ttloop();
884	}
885	/*
886	 * On the off chance that the telnet client is broken and does not
887	 * respond to the DO ECHO we sent, (after all, we did send the
888	 * DO NAWS negotiation after the DO ECHO, and we won't get here
889	 * until a response to the DO NAWS comes back) simulate the
890	 * receipt of a will echo.  This will also send a WONT ECHO
891	 * to the client, since we assume that the client failed to
892	 * respond because it believes that it is already in DO ECHO
893	 * mode, which we do not want.
894	 */
895	if (his_want_state_is_will(TELOPT_ECHO)) {
896		DIAG(TD_OPTIONS, output_data("td: simulating recv\r\n"));
897		willoption(TELOPT_ECHO);
898	}
899
900	/*
901	 * Finally, to clean things up, we turn on our echo.  This
902	 * will break stupid 4.2 telnets out of local terminal echo.
903	 */
904
905	if (my_state_is_wont(TELOPT_ECHO))
906		send_will(TELOPT_ECHO, 1);
907
908	/*
909	 * Turn on packet mode
910	 */
911	(void) ioctl(p, TIOCPKT, (char *)&on);
912
913#if	defined(LINEMODE) && defined(KLUDGELINEMODE)
914	/*
915	 * Continuing line mode support.  If client does not support
916	 * real linemode, attempt to negotiate kludge linemode by sending
917	 * the do timing mark sequence.
918	 */
919	if (lmodetype < REAL_LINEMODE)
920		send_do(TELOPT_TM, 1);
921#endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
922
923	/*
924	 * Call telrcv() once to pick up anything received during
925	 * terminal type negotiation, 4.2/4.3 determination, and
926	 * linemode negotiation.
927	 */
928	telrcv();
929
930	(void) ioctl(f, FIONBIO, (char *)&on);
931	(void) ioctl(p, FIONBIO, (char *)&on);
932
933#if	defined(SO_OOBINLINE)
934	(void) setsockopt(net, SOL_SOCKET, SO_OOBINLINE,
935				(char *)&on, sizeof on);
936#endif	/* defined(SO_OOBINLINE) */
937
938#ifdef	SIGTSTP
939	(void) signal(SIGTSTP, SIG_IGN);
940#endif
941#ifdef	SIGTTOU
942	/*
943	 * Ignoring SIGTTOU keeps the kernel from blocking us
944	 * in ttioct() in /sys/tty.c.
945	 */
946	(void) signal(SIGTTOU, SIG_IGN);
947#endif
948
949	(void) signal(SIGCHLD, cleanup);
950
951#ifdef  TIOCNOTTY
952	{
953		int t;
954		t = open(_PATH_TTY, O_RDWR);
955		if (t >= 0) {
956			(void) ioctl(t, TIOCNOTTY, (char *)0);
957			(void) close(t);
958		}
959	}
960#endif
961
962	/*
963	 * Show banner that getty never gave.
964	 *
965	 * We put the banner in the pty input buffer.  This way, it
966	 * gets carriage return null processing, etc., just like all
967	 * other pty --> client data.
968	 */
969
970#ifdef __APPLE__
971	if (getenv("USER"))
972		hostinfo = 0;
973#endif
974	if (getent(defent, "default") == 1) {
975		char *cp=defstrs;
976
977		HE = Getstr("he", &cp);
978		HN = Getstr("hn", &cp);
979		IM = Getstr("im", &cp);
980#ifdef __APPLE__
981		IF = Getstr("if", &cp);
982#endif
983		if (HN && *HN)
984			(void) strlcpy(host_name, HN, sizeof(host_name));
985#ifdef __APPLE__
986		if (IF && (if_fd = open(IF, O_RDONLY, 000)) != -1)
987			IM = 0;
988#endif
989		if (IM == 0)
990			IM = strdup("");
991	} else {
992		IM = strdup(DEFAULT_IM);
993		HE = 0;
994	}
995	edithost(HE, host_name);
996	if (hostinfo && *IM)
997		putf(IM, ptyibuf2);
998#ifdef __APPLE__
999	else if (IF && if_fd != -1) {
1000		fstat (if_fd, &statbuf);
1001		if_buf = (char *) mmap (0, statbuf.st_size, PROT_READ,
1002		    0, if_fd, 0);
1003		putf(if_buf, ptyibuf2);
1004		munmap (if_buf, statbuf.st_size);
1005		close (if_fd);
1006	}
1007#endif
1008
1009	if (pcc)
1010		(void) strncat(ptyibuf2, ptyip, pcc+1);
1011	ptyip = ptyibuf2;
1012	pcc = strlen(ptyip);
1013#ifdef	LINEMODE
1014	/*
1015	 * Last check to make sure all our states are correct.
1016	 */
1017	init_termbuf();
1018	localstat();
1019#endif	/* LINEMODE */
1020
1021	DIAG(TD_REPORT, output_data("td: Entering processing loop\r\n"));
1022
1023	/*
1024	 * Startup the login process on the slave side of the terminal
1025	 * now.  We delay this until here to insure option negotiation
1026	 * is complete.
1027	 */
1028	startslave(host, level, user_name);
1029
1030	nfd = ((f > p) ? f : p) + 1;
1031	for (;;) {
1032		fd_set ibits, obits, xbits;
1033		int c;
1034
1035		if (ncc < 0 && pcc < 0)
1036			break;
1037
1038		FD_ZERO(&ibits);
1039		FD_ZERO(&obits);
1040		FD_ZERO(&xbits);
1041		/*
1042		 * Never look for input if there's still
1043		 * stuff in the corresponding output buffer
1044		 */
1045		if (nfrontp - nbackp || pcc > 0) {
1046			FD_SET(f, &obits);
1047		} else {
1048			FD_SET(p, &ibits);
1049		}
1050		if (pfrontp - pbackp || ncc > 0) {
1051			FD_SET(p, &obits);
1052		} else {
1053			FD_SET(f, &ibits);
1054		}
1055		if (!SYNCHing) {
1056			FD_SET(f, &xbits);
1057		}
1058		if ((c = select(nfd, &ibits, &obits, &xbits,
1059						(struct timeval *)0)) < 1) {
1060			if (c == -1) {
1061				if (errno == EINTR) {
1062					continue;
1063				}
1064			}
1065			sleep(5);
1066			continue;
1067		}
1068
1069		/*
1070		 * Any urgent data?
1071		 */
1072		if (FD_ISSET(net, &xbits)) {
1073		    SYNCHing = 1;
1074		}
1075
1076		/*
1077		 * Something to read from the network...
1078		 */
1079		if (FD_ISSET(net, &ibits)) {
1080#if	!defined(SO_OOBINLINE)
1081			/*
1082			 * In 4.2 (and 4.3 beta) systems, the
1083			 * OOB indication and data handling in the kernel
1084			 * is such that if two separate TCP Urgent requests
1085			 * come in, one byte of TCP data will be overlaid.
1086			 * This is fatal for Telnet, but we try to live
1087			 * with it.
1088			 *
1089			 * In addition, in 4.2 (and...), a special protocol
1090			 * is needed to pick up the TCP Urgent data in
1091			 * the correct sequence.
1092			 *
1093			 * What we do is:  if we think we are in urgent
1094			 * mode, we look to see if we are "at the mark".
1095			 * If we are, we do an OOB receive.  If we run
1096			 * this twice, we will do the OOB receive twice,
1097			 * but the second will fail, since the second
1098			 * time we were "at the mark", but there wasn't
1099			 * any data there (the kernel doesn't reset
1100			 * "at the mark" until we do a normal read).
1101			 * Once we've read the OOB data, we go ahead
1102			 * and do normal reads.
1103			 *
1104			 * There is also another problem, which is that
1105			 * since the OOB byte we read doesn't put us
1106			 * out of OOB state, and since that byte is most
1107			 * likely the TELNET DM (data mark), we would
1108			 * stay in the TELNET SYNCH (SYNCHing) state.
1109			 * So, clocks to the rescue.  If we've "just"
1110			 * received a DM, then we test for the
1111			 * presence of OOB data when the receive OOB
1112			 * fails (and AFTER we did the normal mode read
1113			 * to clear "at the mark").
1114			 */
1115		    if (SYNCHing) {
1116			int atmark;
1117
1118			(void) ioctl(net, SIOCATMARK, (char *)&atmark);
1119			if (atmark) {
1120			    ncc = recv(net, netibuf, sizeof (netibuf), MSG_OOB);
1121			    if ((ncc == -1) && (errno == EINVAL)) {
1122				ncc = read(net, netibuf, sizeof (netibuf));
1123				if (sequenceIs(didnetreceive, gotDM)) {
1124				    SYNCHing = stilloob(net);
1125				}
1126			    }
1127			} else {
1128			    ncc = read(net, netibuf, sizeof (netibuf));
1129			}
1130		    } else {
1131			ncc = read(net, netibuf, sizeof (netibuf));
1132		    }
1133		    settimer(didnetreceive);
1134#else	/* !defined(SO_OOBINLINE)) */
1135		    ncc = read(net, netibuf, sizeof (netibuf));
1136#endif	/* !defined(SO_OOBINLINE)) */
1137		    if (ncc < 0 && errno == EWOULDBLOCK)
1138			ncc = 0;
1139		    else {
1140			if (ncc <= 0) {
1141			    break;
1142			}
1143			netip = netibuf;
1144		    }
1145		    DIAG((TD_REPORT | TD_NETDATA),
1146			output_data("td: netread %d chars\r\n", ncc));
1147		    DIAG(TD_NETDATA, printdata("nd", netip, ncc));
1148		}
1149
1150		/*
1151		 * Something to read from the pty...
1152		 */
1153		if (FD_ISSET(p, &ibits)) {
1154			pcc = read(p, ptyibuf, BUFSIZ);
1155			/*
1156			 * On some systems, if we try to read something
1157			 * off the master side before the slave side is
1158			 * opened, we get EIO.
1159			 */
1160			if (pcc < 0 && (errno == EWOULDBLOCK ||
1161#ifdef	EAGAIN
1162					errno == EAGAIN ||
1163#endif
1164					errno == EIO)) {
1165				pcc = 0;
1166			} else {
1167				if (pcc <= 0)
1168					break;
1169#ifdef	LINEMODE
1170				/*
1171				 * If ioctl from pty, pass it through net
1172				 */
1173				if (ptyibuf[0] & TIOCPKT_IOCTL) {
1174					copy_termbuf(ptyibuf+1, pcc-1);
1175					localstat();
1176					pcc = 1;
1177				}
1178#endif	/* LINEMODE */
1179				if (ptyibuf[0] & TIOCPKT_FLUSHWRITE) {
1180					netclear();	/* clear buffer back */
1181#ifndef	NO_URGENT
1182					/*
1183					 * There are client telnets on some
1184					 * operating systems get screwed up
1185					 * royally if we send them urgent
1186					 * mode data.
1187					 */
1188					output_data("%c%c", IAC, DM);
1189					neturg = nfrontp-1; /* off by one XXX */
1190					DIAG(TD_OPTIONS,
1191					    printoption("td: send IAC", DM));
1192
1193#endif
1194				}
1195				if (his_state_is_will(TELOPT_LFLOW) &&
1196				    (ptyibuf[0] &
1197				     (TIOCPKT_NOSTOP|TIOCPKT_DOSTOP))) {
1198					int newflow =
1199					    ptyibuf[0] & TIOCPKT_DOSTOP ? 1 : 0;
1200					if (newflow != flowmode) {
1201						flowmode = newflow;
1202						output_data("%c%c%c%c%c%c",
1203							IAC, SB, TELOPT_LFLOW,
1204							flowmode ? LFLOW_ON
1205								 : LFLOW_OFF,
1206							IAC, SE);
1207						DIAG(TD_OPTIONS, printsub('>',
1208						    (unsigned char *)nfrontp-4,
1209						    4););
1210					}
1211				}
1212				pcc--;
1213				ptyip = ptyibuf+1;
1214			}
1215		}
1216
1217		while (pcc > 0) {
1218			if ((&netobuf[BUFSIZ] - nfrontp) < 2)
1219				break;
1220			c = *ptyip++ & 0377, pcc--;
1221			if (c == IAC)
1222				output_data("%c", c);
1223			output_data("%c", c);
1224			if ((c == '\r') && (my_state_is_wont(TELOPT_BINARY))) {
1225				if (pcc > 0 && ((*ptyip & 0377) == '\n')) {
1226					output_data("%c", *ptyip++ & 0377);
1227					pcc--;
1228				} else
1229					output_data("%c", '\0');
1230			}
1231		}
1232
1233		if (FD_ISSET(f, &obits) && (nfrontp - nbackp) > 0)
1234			netflush();
1235		if (ncc > 0)
1236			telrcv();
1237		if (FD_ISSET(p, &obits) && (pfrontp - pbackp) > 0)
1238			ptyflush();
1239	}
1240	cleanup(0);
1241}  /* end of telnet */
1242
1243#ifndef	TCSIG
1244# ifdef	TIOCSIG
1245#  define TCSIG TIOCSIG
1246# endif
1247#endif
1248
1249/*
1250 * Send interrupt to process on other side of pty.
1251 * If it is in raw mode, just write NULL;
1252 * otherwise, write intr char.
1253 */
1254void
1255interrupt(void)
1256{
1257	ptyflush();	/* half-hearted */
1258
1259#ifdef	TCSIG
1260	(void) ioctl(mpty, TCSIG, (char *)SIGINT);
1261#else	/* TCSIG */
1262	init_termbuf();
1263	*pfrontp++ = slctab[SLC_IP].sptr ?
1264			(unsigned char)*slctab[SLC_IP].sptr : '\177';
1265#endif	/* TCSIG */
1266}
1267
1268/*
1269 * Send quit to process on other side of pty.
1270 * If it is in raw mode, just write NULL;
1271 * otherwise, write quit char.
1272 */
1273void
1274sendbrk(void)
1275{
1276	ptyflush();	/* half-hearted */
1277#ifdef	TCSIG
1278	(void) ioctl(mpty, TCSIG, (char *)SIGQUIT);
1279#else	/* TCSIG */
1280	init_termbuf();
1281	*pfrontp++ = slctab[SLC_ABORT].sptr ?
1282			(unsigned char)*slctab[SLC_ABORT].sptr : '\034';
1283#endif	/* TCSIG */
1284}
1285
1286void
1287sendsusp(void)
1288{
1289#ifdef	SIGTSTP
1290	ptyflush();	/* half-hearted */
1291# ifdef	TCSIG
1292	(void) ioctl(mpty, TCSIG, (char *)SIGTSTP);
1293# else	/* TCSIG */
1294	*pfrontp++ = slctab[SLC_SUSP].sptr ?
1295			(unsigned char)*slctab[SLC_SUSP].sptr : '\032';
1296# endif	/* TCSIG */
1297#endif	/* SIGTSTP */
1298}
1299
1300/*
1301 * When we get an AYT, if ^T is enabled, use that.  Otherwise,
1302 * just send back "[Yes]".
1303 */
1304void
1305recv_ayt(void)
1306{
1307#if	defined(SIGINFO) && defined(TCSIG)
1308	if (slctab[SLC_AYT].sptr && *slctab[SLC_AYT].sptr != _POSIX_VDISABLE) {
1309		(void) ioctl(spty, TCSIG, (char *)SIGINFO);
1310		return;
1311	}
1312#endif
1313	output_data("\r\n[Yes]\r\n");
1314}
1315
1316void
1317doeof(void)
1318{
1319	init_termbuf();
1320
1321#if	defined(LINEMODE) && defined(USE_TERMIO) && (VEOF == VMIN)
1322	if (!tty_isediting()) {
1323		extern char oldeofc;
1324		*pfrontp++ = oldeofc;
1325		return;
1326	}
1327#endif
1328	*pfrontp++ = slctab[SLC_EOF].sptr ?
1329			(unsigned char)*slctab[SLC_EOF].sptr : '\004';
1330}
1331