No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / dist / heimdal / appl / telnet / telnetd / telnetd.c
bloba1ce4f8e00d204a4a7ebbd1a02d6778bd5bbca3b
1 /*
2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
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.
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.
34 #include "telnetd.h"
36 __RCSID("$Heimdal: telnetd.c 21748 2007-07-31 18:57:20Z lha $"
37 "$NetBSD$");
39 #ifdef _SC_CRAY_SECURE_SYS
40 #include <sys/sysv.h>
41 #include <sys/secdev.h>
42 #include <sys/secparm.h>
43 #include <sys/usrv.h>
44 int secflag;
45 char tty_dev[16];
46 struct secdev dv;
47 struct sysv sysv;
48 struct socksec ss;
49 #endif /* _SC_CRAY_SECURE_SYS */
51 #ifdef AUTHENTICATION
52 int auth_level = 0;
53 #endif
55 #ifdef KRB5
56 #define Authenticator k5_Authenticator
57 #include <krb5.h>
58 #undef Authenticator
59 #endif
61 extern int utmp_len;
62 int registerd_host_only = 0;
63 #ifdef ENCRYPTION
64 int require_encryption = 0;
65 #endif
67 #ifdef STREAMSPTY
69 #ifdef _AIX
70 #include <sys/termio.h>
71 #endif
72 # ifdef HAVE_SYS_STRTTY_H
73 # include <sys/strtty.h>
74 # endif
75 # ifdef HAVE_SYS_STR_TTY_H
76 # include <sys/str_tty.h>
77 # endif
78 /* make sure we don't get the bsd version */
79 /* what is this here for? solaris? /joda */
80 # ifdef HAVE_SYS_TTY_H
81 # include "/usr/include/sys/tty.h"
82 # endif
83 # ifdef HAVE_SYS_PTYVAR_H
84 # include <sys/ptyvar.h>
85 # endif
88 * Because of the way ptyibuf is used with streams messages, we need
89 * ptyibuf+1 to be on a full-word boundary. The following wierdness
90 * is simply to make that happen.
92 long ptyibufbuf[BUFSIZ/sizeof(long)+1];
93 char *ptyibuf = ((char *)&ptyibufbuf[1])-1;
94 char *ptyip = ((char *)&ptyibufbuf[1])-1;
95 char ptyibuf2[BUFSIZ];
96 unsigned char ctlbuf[BUFSIZ];
97 struct strbuf strbufc, strbufd;
99 int readstream(int, char*, int);
101 #else /* ! STREAMPTY */
104 * I/O data buffers,
105 * pointers, and counters.
107 char ptyibuf[BUFSIZ], *ptyip = ptyibuf;
108 char ptyibuf2[BUFSIZ];
110 #endif /* ! STREAMPTY */
112 int hostinfo = 1; /* do we print login banner? */
114 #ifdef _CRAY
115 extern int newmap; /* nonzero if \n maps to ^M^J */
116 int lowpty = 0, highpty; /* low, high pty numbers */
117 #endif /* CRAY */
119 int debug = 0;
120 int keepalive = 1;
121 char *progname;
123 static void usage (int error_code);
126 * The string to pass to getopt(). We do it this way so
127 * that only the actual options that we support will be
128 * passed off to getopt().
130 char valid_opts[] = "Bd:hklnS:u:UL:y"
131 #ifdef AUTHENTICATION
132 "a:X:z"
133 #endif
134 #ifdef ENCRYPTION
136 #endif
137 #ifdef DIAGNOSTICS
138 "D:"
139 #endif
140 #ifdef _CRAY
141 "r:"
142 #endif
145 static void doit(struct sockaddr*, int);
148 main(int argc, char **argv)
150 struct sockaddr_storage __ss;
151 struct sockaddr *sa = (struct sockaddr *)&__ss;
152 int on = 1;
153 socklen_t sa_size;
154 int ch;
155 #if defined(IPPROTO_IP) && defined(IP_TOS)
156 int tos = -1;
157 #endif
158 pfrontp = pbackp = ptyobuf;
159 netip = netibuf;
160 nfrontp = nbackp = netobuf;
162 setprogname(argv[0]);
164 progname = *argv;
165 #ifdef ENCRYPTION
166 nclearto = 0;
167 #endif
169 #ifdef _CRAY
171 * Get number of pty's before trying to process options,
172 * which may include changing pty range.
174 highpty = getnpty();
175 #endif /* CRAY */
177 if (argc == 2 && strcmp(argv[1], "--version") == 0) {
178 print_version(NULL);
179 exit(0);
181 if (argc == 2 && strcmp(argv[1], "--help") == 0)
182 usage(0);
184 while ((ch = getopt(argc, argv, valid_opts)) != -1) {
185 switch(ch) {
187 #ifdef AUTHENTICATION
188 case 'a':
190 * Check for required authentication level
192 if (strcmp(optarg, "debug") == 0) {
193 auth_debug_mode = 1;
194 } else if (strcasecmp(optarg, "none") == 0) {
195 auth_level = 0;
196 } else if (strcasecmp(optarg, "otp") == 0) {
197 auth_level = 0;
198 require_otp = 1;
199 } else if (strcasecmp(optarg, "other") == 0) {
200 auth_level = AUTH_OTHER;
201 } else if (strcasecmp(optarg, "user") == 0) {
202 auth_level = AUTH_USER;
203 } else if (strcasecmp(optarg, "valid") == 0) {
204 auth_level = AUTH_VALID;
205 } else if (strcasecmp(optarg, "off") == 0) {
207 * This hack turns off authentication
209 auth_level = -1;
210 } else {
211 fprintf(stderr,
212 "telnetd: unknown authorization level for -a\n");
214 break;
215 #endif /* AUTHENTICATION */
217 case 'B': /* BFTP mode is not supported any more */
218 break;
219 case 'd':
220 if (strcmp(optarg, "ebug") == 0) {
221 debug++;
222 break;
224 usage(1);
225 /* NOTREACHED */
226 break;
228 #ifdef DIAGNOSTICS
229 case 'D':
231 * Check for desired diagnostics capabilities.
233 if (!strcmp(optarg, "report")) {
234 diagnostic |= TD_REPORT|TD_OPTIONS;
235 } else if (!strcmp(optarg, "exercise")) {
236 diagnostic |= TD_EXERCISE;
237 } else if (!strcmp(optarg, "netdata")) {
238 diagnostic |= TD_NETDATA;
239 } else if (!strcmp(optarg, "ptydata")) {
240 diagnostic |= TD_PTYDATA;
241 } else if (!strcmp(optarg, "options")) {
242 diagnostic |= TD_OPTIONS;
243 } else {
244 usage(1);
245 /* NOT REACHED */
247 break;
248 #endif /* DIAGNOSTICS */
250 #ifdef ENCRYPTION
251 case 'e':
252 require_encryption = 1;
253 break;
254 #endif
256 case 'h':
257 hostinfo = 0;
258 break;
260 case 'k': /* Linemode is not supported any more */
261 case 'l':
262 break;
264 case 'n':
265 keepalive = 0;
266 break;
268 #ifdef _CRAY
269 case 'r':
271 char *strchr();
272 char *c;
275 * Allow the specification of alterations
276 * to the pty search range. It is legal to
277 * specify only one, and not change the
278 * other from its default.
280 c = strchr(optarg, '-');
281 if (c) {
282 *c++ = '\0';
283 highpty = atoi(c);
285 if (*optarg != '\0')
286 lowpty = atoi(optarg);
287 if ((lowpty > highpty) || (lowpty < 0) ||
288 (highpty > 32767)) {
289 usage(1);
290 /* NOT REACHED */
292 break;
294 #endif /* CRAY */
296 case 'S':
297 #ifdef HAVE_PARSETOS
298 if ((tos = parsetos(optarg, "tcp")) < 0)
299 fprintf(stderr, "%s%s%s\n",
300 "telnetd: Bad TOS argument '", optarg,
301 "'; will try to use default TOS");
302 #else
303 fprintf(stderr, "%s%s\n", "TOS option unavailable; ",
304 "-S flag not supported\n");
305 #endif
306 break;
308 case 'u': {
309 char *eptr;
311 utmp_len = strtol(optarg, &eptr, 0);
312 if (optarg == eptr)
313 fprintf(stderr, "telnetd: unknown utmp len (%s)\n", optarg);
314 break;
317 case 'U':
318 registerd_host_only = 1;
319 break;
321 #ifdef AUTHENTICATION
322 case 'X':
324 * Check for invalid authentication types
326 auth_disable_name(optarg);
327 break;
328 #endif
329 case 'y':
330 no_warn = 1;
331 break;
332 #ifdef AUTHENTICATION
333 case 'z':
334 log_unauth = 1;
335 break;
337 #endif /* AUTHENTICATION */
339 case 'L':
340 new_login = optarg;
341 break;
343 default:
344 fprintf(stderr, "telnetd: %c: unknown option\n", ch);
345 /* FALLTHROUGH */
346 case '?':
347 usage(0);
348 /* NOTREACHED */
352 argc -= optind;
353 argv += optind;
355 if (debug) {
356 int port = 0;
357 struct servent *sp;
359 if (argc > 1) {
360 usage (1);
361 } else if (argc == 1) {
362 sp = roken_getservbyname (*argv, "tcp");
363 if (sp)
364 port = sp->s_port;
365 else
366 port = htons(atoi(*argv));
367 } else {
368 #ifdef KRB5
369 port = krb5_getportbyname (NULL, "telnet", "tcp", 23);
370 #else
371 port = k_getportbyname("telnet", "tcp", htons(23));
372 #endif
374 mini_inetd (port);
375 } else if (argc > 0) {
376 usage(1);
377 /* NOT REACHED */
380 #ifdef _SC_CRAY_SECURE_SYS
381 secflag = sysconf(_SC_CRAY_SECURE_SYS);
384 * Get socket's security label
386 if (secflag) {
387 socklen_t szss = sizeof(ss);
388 int sock_multi;
389 socklen_t szi = sizeof(int);
391 memset(&dv, 0, sizeof(dv));
393 if (getsysv(&sysv, sizeof(struct sysv)) != 0)
394 fatalperror(net, "getsysv");
397 * Get socket security label and set device values
398 * {security label to be set on ttyp device}
400 #ifdef SO_SEC_MULTI /* 8.0 code */
401 if ((getsockopt(0, SOL_SOCKET, SO_SECURITY,
402 (void *)&ss, &szss) < 0) ||
403 (getsockopt(0, SOL_SOCKET, SO_SEC_MULTI,
404 (void *)&sock_multi, &szi) < 0))
405 fatalperror(net, "getsockopt");
406 else {
407 dv.dv_actlvl = ss.ss_actlabel.lt_level;
408 dv.dv_actcmp = ss.ss_actlabel.lt_compart;
409 if (!sock_multi) {
410 dv.dv_minlvl = dv.dv_maxlvl = dv.dv_actlvl;
411 dv.dv_valcmp = dv.dv_actcmp;
412 } else {
413 dv.dv_minlvl = ss.ss_minlabel.lt_level;
414 dv.dv_maxlvl = ss.ss_maxlabel.lt_level;
415 dv.dv_valcmp = ss.ss_maxlabel.lt_compart;
417 dv.dv_devflg = 0;
419 #else /* SO_SEC_MULTI */ /* 7.0 code */
420 if (getsockopt(0, SOL_SOCKET, SO_SECURITY,
421 (void *)&ss, &szss) >= 0) {
422 dv.dv_actlvl = ss.ss_slevel;
423 dv.dv_actcmp = ss.ss_compart;
424 dv.dv_minlvl = ss.ss_minlvl;
425 dv.dv_maxlvl = ss.ss_maxlvl;
426 dv.dv_valcmp = ss.ss_maxcmp;
428 #endif /* SO_SEC_MULTI */
430 #endif /* _SC_CRAY_SECURE_SYS */
432 roken_openlog("telnetd", LOG_PID | LOG_ODELAY, LOG_DAEMON);
433 sa_size = sizeof (__ss);
434 if (getpeername(STDIN_FILENO, sa, &sa_size) < 0) {
435 fprintf(stderr, "%s: ", progname);
436 perror("getpeername");
437 _exit(1);
439 if (keepalive &&
440 setsockopt(STDIN_FILENO, SOL_SOCKET, SO_KEEPALIVE,
441 (void *)&on, sizeof (on)) < 0) {
442 syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
445 #if defined(IPPROTO_IP) && defined(IP_TOS) && defined(HAVE_SETSOCKOPT)
447 # ifdef HAVE_GETTOSBYNAME
448 struct tosent *tp;
449 if (tos < 0 && (tp = gettosbyname("telnet", "tcp")))
450 tos = tp->t_tos;
451 # endif
452 if (tos < 0)
453 tos = 020; /* Low Delay bit */
454 if (tos
455 && sa->sa_family == AF_INET
456 && (setsockopt(STDIN_FILENO, IPPROTO_IP, IP_TOS,
457 (void *)&tos, sizeof(tos)) < 0)
458 && (errno != ENOPROTOOPT) )
459 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
461 #endif /* defined(IPPROTO_IP) && defined(IP_TOS) */
462 net = STDIN_FILENO;
463 doit(sa, sa_size);
464 /* NOTREACHED */
465 return 0;
466 } /* end of main */
468 static void
469 usage(int exit_code)
471 fprintf(stderr, "Usage: telnetd");
472 fprintf(stderr, " [--help]");
473 fprintf(stderr, " [--version]");
474 #ifdef AUTHENTICATION
475 fprintf(stderr, " [-a (debug|other|otp|user|valid|off|none)]\n\t");
476 #endif
477 fprintf(stderr, " [-debug]");
478 #ifdef DIAGNOSTICS
479 fprintf(stderr, " [-D (options|report|exercise|netdata|ptydata)]\n\t");
480 #endif
481 #ifdef AUTHENTICATION
482 fprintf(stderr, " [-edebug]");
483 #endif
484 fprintf(stderr, " [-h]");
485 fprintf(stderr, " [-L login]");
486 fprintf(stderr, " [-n]");
487 #ifdef _CRAY
488 fprintf(stderr, " [-r[lowpty]-[highpty]]");
489 #endif
490 fprintf(stderr, "\n\t");
491 #ifdef HAVE_GETTOSBYNAME
492 fprintf(stderr, " [-S tos]");
493 #endif
494 #ifdef AUTHENTICATION
495 fprintf(stderr, " [-X auth-type] [-y] [-z]");
496 #endif
497 fprintf(stderr, " [-u utmp_hostname_length] [-U]");
498 fprintf(stderr, " [port]\n");
499 exit(exit_code);
503 * getterminaltype
505 * Ask the other end to send along its terminal type and speed.
506 * Output is the variable terminaltype filled in.
508 static unsigned char ttytype_sbbuf[] = {
509 IAC, SB, TELOPT_TTYPE, TELQUAL_SEND, IAC, SE
513 getterminaltype(char *name, size_t name_sz)
515 int retval = -1;
517 settimer(baseline);
518 #ifdef AUTHENTICATION
520 * Handle the Authentication option before we do anything else.
522 send_do(TELOPT_AUTHENTICATION, 1);
523 while (his_will_wont_is_changing(TELOPT_AUTHENTICATION))
524 ttloop();
525 if (his_state_is_will(TELOPT_AUTHENTICATION)) {
526 retval = auth_wait(name, name_sz);
528 #endif
530 #ifdef ENCRYPTION
531 send_will(TELOPT_ENCRYPT, 1);
532 send_do(TELOPT_ENCRYPT, 1); /* esc@magic.fi */
533 #endif
534 send_do(TELOPT_TTYPE, 1);
535 send_do(TELOPT_TSPEED, 1);
536 send_do(TELOPT_XDISPLOC, 1);
537 send_do(TELOPT_NEW_ENVIRON, 1);
538 send_do(TELOPT_OLD_ENVIRON, 1);
539 while (
540 #ifdef ENCRYPTION
541 his_do_dont_is_changing(TELOPT_ENCRYPT) ||
542 #endif
543 his_will_wont_is_changing(TELOPT_TTYPE) ||
544 his_will_wont_is_changing(TELOPT_TSPEED) ||
545 his_will_wont_is_changing(TELOPT_XDISPLOC) ||
546 his_will_wont_is_changing(TELOPT_NEW_ENVIRON) ||
547 his_will_wont_is_changing(TELOPT_OLD_ENVIRON)) {
548 ttloop();
550 #ifdef ENCRYPTION
552 * Wait for the negotiation of what type of encryption we can
553 * send with. If autoencrypt is not set, this will just return.
555 if (his_state_is_will(TELOPT_ENCRYPT)) {
556 encrypt_wait();
558 if (require_encryption) {
560 while (encrypt_delay())
561 if (telnet_spin())
562 fatal(net, "Failed while waiting for encryption");
564 if (!encrypt_is_encrypting())
565 fatal(net, "Encryption required but not turned on by client");
567 #endif
568 if (his_state_is_will(TELOPT_TSPEED)) {
569 static unsigned char sb[] =
570 { IAC, SB, TELOPT_TSPEED, TELQUAL_SEND, IAC, SE };
572 telnet_net_write (sb, sizeof sb);
573 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
575 if (his_state_is_will(TELOPT_XDISPLOC)) {
576 static unsigned char sb[] =
577 { IAC, SB, TELOPT_XDISPLOC, TELQUAL_SEND, IAC, SE };
579 telnet_net_write (sb, sizeof sb);
580 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
582 if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
583 static unsigned char sb[] =
584 { IAC, SB, TELOPT_NEW_ENVIRON, TELQUAL_SEND, IAC, SE };
586 telnet_net_write (sb, sizeof sb);
587 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
589 else if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
590 static unsigned char sb[] =
591 { IAC, SB, TELOPT_OLD_ENVIRON, TELQUAL_SEND, IAC, SE };
593 telnet_net_write (sb, sizeof sb);
594 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
596 if (his_state_is_will(TELOPT_TTYPE)) {
598 telnet_net_write (ttytype_sbbuf, sizeof ttytype_sbbuf);
599 DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
600 sizeof ttytype_sbbuf - 2););
602 if (his_state_is_will(TELOPT_TSPEED)) {
603 while (sequenceIs(tspeedsubopt, baseline))
604 ttloop();
606 if (his_state_is_will(TELOPT_XDISPLOC)) {
607 while (sequenceIs(xdisplocsubopt, baseline))
608 ttloop();
610 if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
611 while (sequenceIs(environsubopt, baseline))
612 ttloop();
614 if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
615 while (sequenceIs(oenvironsubopt, baseline))
616 ttloop();
618 if (his_state_is_will(TELOPT_TTYPE)) {
619 char first[256], last[256];
621 while (sequenceIs(ttypesubopt, baseline))
622 ttloop();
625 * If the other side has already disabled the option, then
626 * we have to just go with what we (might) have already gotten.
628 if (his_state_is_will(TELOPT_TTYPE) && !terminaltypeok(terminaltype)) {
629 strlcpy(first, terminaltype, sizeof(first));
630 for(;;) {
632 * Save the unknown name, and request the next name.
634 strlcpy(last, terminaltype, sizeof(last));
635 _gettermname();
636 if (terminaltypeok(terminaltype))
637 break;
638 if ((strncmp(last, terminaltype, sizeof(last)) == 0) ||
639 his_state_is_wont(TELOPT_TTYPE)) {
641 * We've hit the end. If this is the same as
642 * the first name, just go with it.
644 if (strncmp(first, terminaltype, sizeof(first)) == 0)
645 break;
647 * Get the terminal name one more time, so that
648 * RFC1091 compliant telnets will cycle back to
649 * the start of the list.
651 _gettermname();
652 if (strncmp(first, terminaltype, sizeof(first)) != 0)
653 strlcpy(terminaltype, first, sizeof(terminaltype));
654 break;
659 return(retval);
660 } /* end of getterminaltype */
662 void
663 _gettermname(void)
666 * If the client turned off the option,
667 * we can't send another request, so we
668 * just return.
670 if (his_state_is_wont(TELOPT_TTYPE))
671 return;
672 settimer(baseline);
673 telnet_net_write (ttytype_sbbuf, sizeof ttytype_sbbuf);
674 DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
675 sizeof ttytype_sbbuf - 2););
676 while (sequenceIs(ttypesubopt, baseline))
677 ttloop();
681 terminaltypeok(char *s)
683 return 1;
687 char host_name[MaxHostNameLen];
688 char remote_host_name[MaxHostNameLen];
689 char remote_utmp_name[MaxHostNameLen];
692 * Get a pty, scan input lines.
694 static void
695 doit(struct sockaddr *who, int who_len)
697 int level;
698 int ptynum;
699 char user_name[256];
700 int error;
703 * Find an available pty to use.
705 ourpty = getpty(&ptynum);
706 if (ourpty < 0)
707 fatal(net, "All network ports in use");
709 #ifdef _SC_CRAY_SECURE_SYS
711 * set ttyp line security label
713 if (secflag) {
714 char slave_dev[16];
716 snprintf(tty_dev, sizeof(tty_dev), "/dev/pty/%03d", ptynum);
717 if (setdevs(tty_dev, &dv) < 0)
718 fatal(net, "cannot set pty security");
719 snprintf(slave_dev, sizeof(slave_dev), "/dev/ttyp%03d", ptynum);
720 if (setdevs(slave_dev, &dv) < 0)
721 fatal(net, "cannot set tty security");
723 #endif /* _SC_CRAY_SECURE_SYS */
725 error = getnameinfo_verified (who, who_len,
726 remote_host_name,
727 sizeof(remote_host_name),
728 NULL, 0,
729 registerd_host_only ? NI_NAMEREQD : 0);
730 if (error)
731 fatal(net, "Couldn't resolve your address into a host name.\r\n\
732 Please contact your net administrator");
734 gethostname(host_name, sizeof (host_name));
736 strlcpy (remote_utmp_name, remote_host_name, sizeof(remote_utmp_name));
738 /* Only trim if too long (and possible) */
739 if (strlen(remote_utmp_name) > utmp_len) {
740 char *domain = strchr(host_name, '.');
741 char *p = strchr(remote_utmp_name, '.');
742 if (domain != NULL && p != NULL && (strcmp(p, domain) == 0))
743 *p = '\0'; /* remove domain part */
747 * If hostname still doesn't fit utmp, use ipaddr.
749 if (strlen(remote_utmp_name) > utmp_len) {
750 error = getnameinfo (who, who_len,
751 remote_utmp_name,
752 sizeof(remote_utmp_name),
753 NULL, 0,
754 NI_NUMERICHOST);
755 if (error)
756 fatal(net, "Couldn't get numeric address\r\n");
759 #ifdef AUTHENTICATION
760 auth_encrypt_init(host_name, remote_host_name, "TELNETD", 1);
761 #endif
763 init_env();
765 /* begin server processing */
768 * Initialize the slc mapping table.
771 get_slc_defaults();
774 * get terminal type.
776 *user_name = 0;
777 level = getterminaltype(user_name, sizeof(user_name));
778 esetenv("TERM", terminaltype[0] ? terminaltype : "network", 1);
780 #ifdef _SC_CRAY_SECURE_SYS
781 if (secflag) {
782 if (setulvl(dv.dv_actlvl) < 0)
783 fatal(net,"cannot setulvl()");
784 if (setucmp(dv.dv_actcmp) < 0)
785 fatal(net, "cannot setucmp()");
787 #endif /* _SC_CRAY_SECURE_SYS */
789 my_telnet(net, ourpty, remote_host_name, remote_utmp_name,
790 level, user_name);
791 /*NOTREACHED*/
792 } /* end of doit */
794 /* output contents of /etc/issue.net, or /etc/issue */
795 static void
796 show_issue(void)
798 FILE *f;
799 char buf[128];
800 f = fopen(SYSCONFDIR "/issue.net", "r");
801 if(f == NULL)
802 f = fopen(SYSCONFDIR "/issue", "r");
803 if(f){
804 while(fgets(buf, sizeof(buf), f) != NULL) {
805 size_t len = strcspn(buf, "\r\n");
806 if(len == strlen(buf)) {
807 /* there's no newline */
808 writenet(buf, len);
809 } else {
810 /* replace newline with \r\n */
811 buf[len] = '\0';
812 writenet(buf, len);
813 writenet("\r\n", 2);
816 fclose(f);
821 * Main loop. Select from pty and network, and
822 * hand data to telnet receiver finite state machine.
824 void
825 my_telnet(int f, int p, const char *host, const char *utmp_host,
826 int level, char *autoname)
828 int on = 1;
829 char *he;
830 char *IM;
831 int nfd;
832 int startslave_called = 0;
833 time_t timeout;
836 * Do some tests where it is desireable to wait for a response.
837 * Rather than doing them slowly, one at a time, do them all
838 * at once.
840 if (my_state_is_wont(TELOPT_SGA))
841 send_will(TELOPT_SGA, 1);
843 * Is the client side a 4.2 (NOT 4.3) system? We need to know this
844 * because 4.2 clients are unable to deal with TCP urgent data.
846 * To find out, we send out a "DO ECHO". If the remote system
847 * answers "WILL ECHO" it is probably a 4.2 client, and we note
848 * that fact ("WILL ECHO" ==> that the client will echo what
849 * WE, the server, sends it; it does NOT mean that the client will
850 * echo the terminal input).
852 send_do(TELOPT_ECHO, 1);
855 * Send along a couple of other options that we wish to negotiate.
857 send_do(TELOPT_NAWS, 1);
858 send_will(TELOPT_STATUS, 1);
859 flowmode = 1; /* default flow control state */
860 restartany = -1; /* uninitialized... */
861 send_do(TELOPT_LFLOW, 1);
864 * Spin, waiting for a response from the DO ECHO. However,
865 * some REALLY DUMB telnets out there might not respond
866 * to the DO ECHO. So, we spin looking for NAWS, (most dumb
867 * telnets so far seem to respond with WONT for a DO that
868 * they don't understand...) because by the time we get the
869 * response, it will already have processed the DO ECHO.
870 * Kludge upon kludge.
872 while (his_will_wont_is_changing(TELOPT_NAWS))
873 ttloop();
876 * But...
877 * The client might have sent a WILL NAWS as part of its
878 * startup code; if so, we'll be here before we get the
879 * response to the DO ECHO. We'll make the assumption
880 * that any implementation that understands about NAWS
881 * is a modern enough implementation that it will respond
882 * to our DO ECHO request; hence we'll do another spin
883 * waiting for the ECHO option to settle down, which is
884 * what we wanted to do in the first place...
886 if (his_want_state_is_will(TELOPT_ECHO) &&
887 his_state_is_will(TELOPT_NAWS)) {
888 while (his_will_wont_is_changing(TELOPT_ECHO))
889 ttloop();
892 * On the off chance that the telnet client is broken and does not
893 * respond to the DO ECHO we sent, (after all, we did send the
894 * DO NAWS negotiation after the DO ECHO, and we won't get here
895 * until a response to the DO NAWS comes back) simulate the
896 * receipt of a will echo. This will also send a WONT ECHO
897 * to the client, since we assume that the client failed to
898 * respond because it believes that it is already in DO ECHO
899 * mode, which we do not want.
901 if (his_want_state_is_will(TELOPT_ECHO)) {
902 DIAG(TD_OPTIONS,
903 {output_data("td: simulating recv\r\n");
905 willoption(TELOPT_ECHO);
909 * Finally, to clean things up, we turn on our echo. This
910 * will break stupid 4.2 telnets out of local terminal echo.
913 if (my_state_is_wont(TELOPT_ECHO))
914 send_will(TELOPT_ECHO, 1);
916 #ifdef TIOCPKT
917 #ifdef STREAMSPTY
918 if (!really_stream)
919 #endif
921 * Turn on packet mode
923 ioctl(p, TIOCPKT, (char *)&on);
924 #endif
928 * Call telrcv() once to pick up anything received during
929 * terminal type negotiation, 4.2/4.3 determination, and
930 * linemode negotiation.
932 telrcv();
934 ioctl(f, FIONBIO, (char *)&on);
935 ioctl(p, FIONBIO, (char *)&on);
937 #if defined(SO_OOBINLINE) && defined(HAVE_SETSOCKOPT)
938 setsockopt(net, SOL_SOCKET, SO_OOBINLINE,
939 (void *)&on, sizeof on);
940 #endif /* defined(SO_OOBINLINE) */
942 #ifdef SIGTSTP
943 signal(SIGTSTP, SIG_IGN);
944 #endif
945 #ifdef SIGTTOU
947 * Ignoring SIGTTOU keeps the kernel from blocking us
948 * in ttioct() in /sys/tty.c.
950 signal(SIGTTOU, SIG_IGN);
951 #endif
953 signal(SIGCHLD, cleanup);
955 #ifdef TIOCNOTTY
957 int t;
958 t = open(_PATH_TTY, O_RDWR);
959 if (t >= 0) {
960 ioctl(t, TIOCNOTTY, (char *)0);
961 close(t);
964 #endif
966 show_issue();
968 * Show banner that getty never gave.
970 * We put the banner in the pty input buffer. This way, it
971 * gets carriage return null processing, etc., just like all
972 * other pty --> client data.
975 if (getenv("USER"))
976 hostinfo = 0;
978 IM = DEFAULT_IM;
979 he = 0;
980 edithost(he, host_name);
981 if (hostinfo && *IM)
982 putf(IM, ptyibuf2);
984 if (pcc)
985 strncat(ptyibuf2, ptyip, pcc+1);
986 ptyip = ptyibuf2;
987 pcc = strlen(ptyip);
989 DIAG(TD_REPORT, {
990 output_data("td: Entering processing loop\r\n");
994 nfd = ((f > p) ? f : p) + 1;
995 timeout = time(NULL) + 5;
996 for (;;) {
997 fd_set ibits, obits, xbits;
998 int c;
1000 /* wait for encryption to be turned on, but don't wait
1001 indefinitely */
1002 if(!startslave_called && (!encrypt_delay() || timeout > time(NULL))){
1003 startslave_called = 1;
1004 startslave(host, utmp_host, level, autoname);
1007 if (ncc < 0 && pcc < 0)
1008 break;
1010 FD_ZERO(&ibits);
1011 FD_ZERO(&obits);
1012 FD_ZERO(&xbits);
1014 if (f >= FD_SETSIZE
1015 || p >= FD_SETSIZE)
1016 fatal(net, "fd too large");
1019 * Never look for input if there's still
1020 * stuff in the corresponding output buffer
1022 if (nfrontp - nbackp || pcc > 0) {
1023 FD_SET(f, &obits);
1024 } else {
1025 FD_SET(p, &ibits);
1027 if (pfrontp - pbackp || ncc > 0) {
1028 FD_SET(p, &obits);
1029 } else {
1030 FD_SET(f, &ibits);
1032 if (!SYNCHing) {
1033 FD_SET(f, &xbits);
1035 if ((c = select(nfd, &ibits, &obits, &xbits,
1036 (struct timeval *)0)) < 1) {
1037 if (c == -1) {
1038 if (errno == EINTR) {
1039 continue;
1042 sleep(5);
1043 continue;
1047 * Any urgent data?
1049 if (FD_ISSET(net, &xbits)) {
1050 SYNCHing = 1;
1054 * Something to read from the network...
1056 if (FD_ISSET(net, &ibits)) {
1057 #ifndef SO_OOBINLINE
1059 * In 4.2 (and 4.3 beta) systems, the
1060 * OOB indication and data handling in the kernel
1061 * is such that if two separate TCP Urgent requests
1062 * come in, one byte of TCP data will be overlaid.
1063 * This is fatal for Telnet, but we try to live
1064 * with it.
1066 * In addition, in 4.2 (and...), a special protocol
1067 * is needed to pick up the TCP Urgent data in
1068 * the correct sequence.
1070 * What we do is: if we think we are in urgent
1071 * mode, we look to see if we are "at the mark".
1072 * If we are, we do an OOB receive. If we run
1073 * this twice, we will do the OOB receive twice,
1074 * but the second will fail, since the second
1075 * time we were "at the mark", but there wasn't
1076 * any data there (the kernel doesn't reset
1077 * "at the mark" until we do a normal read).
1078 * Once we've read the OOB data, we go ahead
1079 * and do normal reads.
1081 * There is also another problem, which is that
1082 * since the OOB byte we read doesn't put us
1083 * out of OOB state, and since that byte is most
1084 * likely the TELNET DM (data mark), we would
1085 * stay in the TELNET SYNCH (SYNCHing) state.
1086 * So, clocks to the rescue. If we've "just"
1087 * received a DM, then we test for the
1088 * presence of OOB data when the receive OOB
1089 * fails (and AFTER we did the normal mode read
1090 * to clear "at the mark").
1092 if (SYNCHing) {
1093 int atmark;
1095 ioctl(net, SIOCATMARK, (char *)&atmark);
1096 if (atmark) {
1097 ncc = recv(net, netibuf, sizeof (netibuf), MSG_OOB);
1098 if ((ncc == -1) && (errno == EINVAL)) {
1099 ncc = read(net, netibuf, sizeof (netibuf));
1100 if (sequenceIs(didnetreceive, gotDM)) {
1101 SYNCHing = stilloob(net);
1104 } else {
1105 ncc = read(net, netibuf, sizeof (netibuf));
1107 } else {
1108 ncc = read(net, netibuf, sizeof (netibuf));
1110 settimer(didnetreceive);
1111 #else /* !defined(SO_OOBINLINE)) */
1112 ncc = read(net, netibuf, sizeof (netibuf));
1113 #endif /* !defined(SO_OOBINLINE)) */
1114 if (ncc < 0 && errno == EWOULDBLOCK)
1115 ncc = 0;
1116 else {
1117 if (ncc <= 0) {
1118 break;
1120 netip = netibuf;
1122 DIAG((TD_REPORT | TD_NETDATA), {
1123 output_data("td: netread %d chars\r\n", ncc);
1125 DIAG(TD_NETDATA, printdata("nd", netip, ncc));
1129 * Something to read from the pty...
1131 if (FD_ISSET(p, &ibits)) {
1132 #ifdef STREAMSPTY
1133 if (really_stream)
1134 pcc = readstream(p, ptyibuf, BUFSIZ);
1135 else
1136 #endif
1137 pcc = read(p, ptyibuf, BUFSIZ);
1140 * On some systems, if we try to read something
1141 * off the master side before the slave side is
1142 * opened, we get EIO.
1144 if (pcc < 0 && (errno == EWOULDBLOCK ||
1145 #ifdef EAGAIN
1146 errno == EAGAIN ||
1147 #endif
1148 errno == EIO)) {
1149 pcc = 0;
1150 } else {
1151 if (pcc <= 0)
1152 break;
1153 if (ptyibuf[0] & TIOCPKT_FLUSHWRITE) {
1154 netclear(); /* clear buffer back */
1155 #ifndef NO_URGENT
1157 * There are client telnets on some
1158 * operating systems get screwed up
1159 * royally if we send them urgent
1160 * mode data.
1162 output_data ("%c%c", IAC, DM);
1164 neturg = nfrontp-1; /* off by one XXX */
1165 DIAG(TD_OPTIONS,
1166 printoption("td: send IAC", DM));
1168 #endif
1170 if (his_state_is_will(TELOPT_LFLOW) &&
1171 (ptyibuf[0] &
1172 (TIOCPKT_NOSTOP|TIOCPKT_DOSTOP))) {
1173 int newflow =
1174 ptyibuf[0] & TIOCPKT_DOSTOP ? 1 : 0;
1175 if (newflow != flowmode) {
1176 flowmode = newflow;
1177 output_data("%c%c%c%c%c%c",
1178 IAC, SB, TELOPT_LFLOW,
1179 flowmode ? LFLOW_ON
1180 : LFLOW_OFF,
1181 IAC, SE);
1182 DIAG(TD_OPTIONS, printsub('>',
1183 (unsigned char *)nfrontp-4,
1184 4););
1187 pcc--;
1188 ptyip = ptyibuf+1;
1192 while (pcc > 0) {
1193 if ((&netobuf[BUFSIZ] - nfrontp) < 3)
1194 break;
1195 c = *ptyip++ & 0377, pcc--;
1196 if (c == IAC)
1197 *nfrontp++ = c;
1198 *nfrontp++ = c;
1199 if ((c == '\r') && (my_state_is_wont(TELOPT_BINARY))) {
1200 if (pcc > 0 && ((*ptyip & 0377) == '\n')) {
1201 *nfrontp++ = *ptyip++ & 0377;
1202 pcc--;
1203 } else
1204 *nfrontp++ = '\0';
1208 if (FD_ISSET(f, &obits) && (nfrontp - nbackp) > 0)
1209 netflush();
1210 if (ncc > 0)
1211 telrcv();
1212 if (FD_ISSET(p, &obits) && (pfrontp - pbackp) > 0)
1213 ptyflush();
1215 cleanup(0);
1218 #ifndef TCSIG
1219 # ifdef TIOCSIG
1220 # define TCSIG TIOCSIG
1221 # endif
1222 #endif
1224 #ifdef STREAMSPTY
1226 int flowison = -1; /* current state of flow: -1 is unknown */
1229 readstream(int p, char *ibuf, int bufsize)
1231 int flags = 0;
1232 int ret = 0;
1233 struct termios *tsp;
1234 #if 0
1235 struct termio *tp;
1236 #endif
1237 struct iocblk *ip;
1238 char vstop, vstart;
1239 int ixon;
1240 int newflow;
1242 strbufc.maxlen = BUFSIZ;
1243 strbufc.buf = (char *)ctlbuf;
1244 strbufd.maxlen = bufsize-1;
1245 strbufd.len = 0;
1246 strbufd.buf = ibuf+1;
1247 ibuf[0] = 0;
1249 ret = getmsg(p, &strbufc, &strbufd, &flags);
1250 if (ret < 0) /* error of some sort -- probably EAGAIN */
1251 return(-1);
1253 if (strbufc.len <= 0 || ctlbuf[0] == M_DATA) {
1254 /* data message */
1255 if (strbufd.len > 0) { /* real data */
1256 return(strbufd.len + 1); /* count header char */
1257 } else {
1258 /* nothing there */
1259 errno = EAGAIN;
1260 return(-1);
1265 * It's a control message. Return 1, to look at the flag we set
1268 switch (ctlbuf[0]) {
1269 case M_FLUSH:
1270 if (ibuf[1] & FLUSHW)
1271 ibuf[0] = TIOCPKT_FLUSHWRITE;
1272 return(1);
1274 case M_IOCTL:
1275 ip = (struct iocblk *) (ibuf+1);
1277 switch (ip->ioc_cmd) {
1278 #ifdef TCSETS
1279 case TCSETS:
1280 case TCSETSW:
1281 case TCSETSF:
1282 tsp = (struct termios *)
1283 (ibuf+1 + sizeof(struct iocblk));
1284 vstop = tsp->c_cc[VSTOP];
1285 vstart = tsp->c_cc[VSTART];
1286 ixon = tsp->c_iflag & IXON;
1287 break;
1288 #endif
1289 #if 0
1290 case TCSETA:
1291 case TCSETAW:
1292 case TCSETAF:
1293 tp = (struct termio *) (ibuf+1 + sizeof(struct iocblk));
1294 vstop = tp->c_cc[VSTOP];
1295 vstart = tp->c_cc[VSTART];
1296 ixon = tp->c_iflag & IXON;
1297 break;
1298 #endif
1299 default:
1300 errno = EAGAIN;
1301 return(-1);
1304 newflow = (ixon && (vstart == 021) && (vstop == 023)) ? 1 : 0;
1305 if (newflow != flowison) { /* it's a change */
1306 flowison = newflow;
1307 ibuf[0] = newflow ? TIOCPKT_DOSTOP : TIOCPKT_NOSTOP;
1308 return(1);
1312 /* nothing worth doing anything about */
1313 errno = EAGAIN;
1314 return(-1);
1316 #endif /* STREAMSPTY */
1319 * Send interrupt to process on other side of pty.
1320 * If it is in raw mode, just write NULL;
1321 * otherwise, write intr char.
1323 void
1324 interrupt()
1326 ptyflush(); /* half-hearted */
1328 #if defined(STREAMSPTY) && defined(TIOCSIGNAL)
1329 /* Streams PTY style ioctl to post a signal */
1330 if (really_stream)
1332 int sig = SIGINT;
1333 ioctl(ourpty, TIOCSIGNAL, &sig);
1334 ioctl(ourpty, I_FLUSH, FLUSHR);
1336 #else
1337 #ifdef TCSIG
1338 ioctl(ourpty, TCSIG, (char *)SIGINT);
1339 #else /* TCSIG */
1340 init_termbuf();
1341 *pfrontp++ = slctab[SLC_IP].sptr ?
1342 (unsigned char)*slctab[SLC_IP].sptr : '\177';
1343 #endif /* TCSIG */
1344 #endif
1348 * Send quit to process on other side of pty.
1349 * If it is in raw mode, just write NULL;
1350 * otherwise, write quit char.
1352 void
1353 sendbrk()
1355 ptyflush(); /* half-hearted */
1356 #ifdef TCSIG
1357 ioctl(ourpty, TCSIG, (char *)SIGQUIT);
1358 #else /* TCSIG */
1359 init_termbuf();
1360 *pfrontp++ = slctab[SLC_ABORT].sptr ?
1361 (unsigned char)*slctab[SLC_ABORT].sptr : '\034';
1362 #endif /* TCSIG */
1365 void
1366 sendsusp()
1368 #ifdef SIGTSTP
1369 ptyflush(); /* half-hearted */
1370 # ifdef TCSIG
1371 ioctl(ourpty, TCSIG, (char *)SIGTSTP);
1372 # else /* TCSIG */
1373 *pfrontp++ = slctab[SLC_SUSP].sptr ?
1374 (unsigned char)*slctab[SLC_SUSP].sptr : '\032';
1375 # endif /* TCSIG */
1376 #endif /* SIGTSTP */
1380 * When we get an AYT, if ^T is enabled, use that. Otherwise,
1381 * just send back "[Yes]".
1383 void
1384 recv_ayt()
1386 #if defined(SIGINFO) && defined(TCSIG)
1387 if (slctab[SLC_AYT].sptr && *slctab[SLC_AYT].sptr != _POSIX_VDISABLE) {
1388 ioctl(ourpty, TCSIG, (char *)SIGINFO);
1389 return;
1391 #endif
1392 output_data("\r\n[Yes]\r\n");
1395 void
1396 doeof()
1398 init_termbuf();
1400 *pfrontp++ = slctab[SLC_EOF].sptr ?
1401 (unsigned char)*slctab[SLC_EOF].sptr : '\004';