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