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