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