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