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