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
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
35 static const char copyright[] =
36 "@(#) Copyright (c) 1989, 1993\n\
37 The Regents of the University of California. All rights reserved.\n";
42 static const char sccsid[] = "@(#)telnetd.c 8.4 (Berkeley) 5/30/95";
44 static const char rcsid[] =
49 #include "pathnames.h"
51 #if defined(_SC_CRAY_SECURE_SYS) && !defined(SCM_SECURITY)
53 * UNICOS 6.0/6.1 do not have SCM_SECURITY defined, so we can
54 * use it to tell us to turn off all the socket security code,
55 * since that is only used in UNICOS 7.0 and later.
57 # undef _SC_CRAY_SECURE_SYS
61 #include <arpa/inet.h>
66 #if defined(_SC_CRAY_SECURE_SYS)
68 #include <sys/secdev.h>
69 # ifdef SO_SEC_MULTI /* 8.0 code */
70 #include <sys/secparm.h>
72 # endif /* SO_SEC_MULTI */
74 /* wrapper for KAME-special getnameinfo() */
75 #ifndef NI_WITHSCOPEID
76 #define NI_WITHSCOPEID 0
83 # ifdef SO_SEC_MULTI /* 8.0 code */
85 # else /* SO_SEC_MULTI */ /* 7.0 code */
86 struct socket_security ss;
87 # endif /* SO_SEC_MULTI */
88 #endif /* _SC_CRAY_SECURE_SYS */
90 #if defined(AUTHENTICATION)
91 #include <libtelnet/auth.h>
94 #if defined(ENCRYPTION)
95 #include <libtelnet/encrypt.h>
97 #include <libtelnet/misc.h>
99 int require_SecurID = 0;
102 char remote_hostname[MAXHOSTNAMELEN];
103 int utmp_len = sizeof(remote_hostname) - 1;
104 int registerd_host_only = 0;
107 # include <stropts.h>
109 /* make sure we don't get the bsd version */
110 # include "/usr/include/sys/tty.h"
111 # include <sys/ptyvar.h>
114 * Because of the way ptyibuf is used with streams messages, we need
115 * ptyibuf+1 to be on a full-word boundary. The following wierdness
116 * is simply to make that happen.
118 long ptyibufbuf[BUFSIZ/sizeof(long)+1];
119 char *ptyibuf = ((char *)&ptyibufbuf[1])-1;
120 char *ptyip = ((char *)&ptyibufbuf[1])-1;
121 char ptyibuf2[BUFSIZ];
122 unsigned char ctlbuf[BUFSIZ];
123 struct strbuf strbufc, strbufd;
125 #else /* ! STREAMPTY */
129 * pointers, and counters.
131 char ptyibuf[BUFSIZ], *ptyip = ptyibuf;
132 char ptyibuf2[BUFSIZ];
134 # include <termcap.h>
136 int readstream(int p, char *ibuf, int bufsize);
137 void doit(struct sockaddr *who);
138 int terminaltypeok(char *s);
139 void startslave(char *host, int autologin, char *autoname);
141 #endif /* ! STREAMPTY */
143 int hostinfo = 1; /* do we print login banner? */
146 extern int newmap; /* nonzero if \n maps to ^M^J */
147 int lowpty = 0, highpty; /* low, high pty numbers */
154 void doit __P((struct sockaddr *));
155 int terminaltypeok __P((char *));
156 void startslave __P((char *, int, char *));
157 extern void usage P((void));
160 * The string to pass to getopt(). We do it this way so
161 * that only the actual options that we support will be
162 * passed off to getopt().
164 char valid_opts[] = {
165 'd', ':', 'h', 'k', 'n', 'p', ':', 'S', ':', 'u', ':', 'U',
167 #ifdef AUTHENTICATION
179 #if defined(CRAY) && defined(NEWINIT)
194 int family = AF_INET;
200 struct sockaddr_storage from;
203 #if defined(IPPROTO_IP) && defined(IP_TOS)
207 pfrontp = pbackp = ptyobuf;
209 nfrontp = nbackp = netobuf;
212 #endif /* ENCRYPTION */
215 * This initialization causes linemode to default to a configuration
216 * that works on all telnet clients, including the FreeBSD client.
217 * This is not quite the same as the telnet client issuing a "mode
218 * character" command, but has most of the same benefits, and is
219 * preferable since some clients (like usofts) don't have the
220 * mode character command anyway and linemode breaks things.
221 * The most notable symptom of fix is that csh "set filec" operations
222 * like <ESC> (filename completion) and ^D (choices) keys now work
223 * in telnet sessions and can be used more than once on the same line.
224 * CR/LF handling is also corrected in some termio modes. This
225 * change resolves problem reports bin/771 and bin/1037.
228 linemode=1; /*Default to mode that works on bulk of clients*/
232 * Get number of pty's before trying to process options,
233 * which may include changing pty range.
238 while ((ch = getopt(argc, argv, valid_opts)) != -1) {
241 #ifdef AUTHENTICATION
244 * Check for required authentication level
246 if (strcmp(optarg, "debug") == 0) {
247 extern int auth_debug_mode;
249 } else if (strcasecmp(optarg, "none") == 0) {
251 } else if (strcasecmp(optarg, "other") == 0) {
252 auth_level = AUTH_OTHER;
253 } else if (strcasecmp(optarg, "user") == 0) {
254 auth_level = AUTH_USER;
255 } else if (strcasecmp(optarg, "valid") == 0) {
256 auth_level = AUTH_VALID;
257 } else if (strcasecmp(optarg, "off") == 0) {
259 * This hack turns off authentication
263 warnx("unknown authorization level for -a");
266 #endif /* AUTHENTICATION */
272 #endif /* BFTPDAEMON */
275 if (strcmp(optarg, "ebug") == 0) {
286 * Check for desired diagnostics capabilities.
288 if (!strcmp(optarg, "report")) {
289 diagnostic |= TD_REPORT|TD_OPTIONS;
290 } else if (!strcmp(optarg, "exercise")) {
291 diagnostic |= TD_EXERCISE;
292 } else if (!strcmp(optarg, "netdata")) {
293 diagnostic |= TD_NETDATA;
294 } else if (!strcmp(optarg, "ptydata")) {
295 diagnostic |= TD_PTYDATA;
296 } else if (!strcmp(optarg, "options")) {
297 diagnostic |= TD_OPTIONS;
303 #endif /* DIAGNOSTICS */
307 if (strcmp(optarg, "debug") == 0) {
308 extern int encrypt_debug_mode;
309 encrypt_debug_mode = 1;
315 #endif /* ENCRYPTION */
321 #if defined(CRAY) && defined(NEWINIT)
328 #endif /* defined(CRAY) && defined(NEWINIT) */
334 #endif /* LINEMODE */
337 #if defined(LINEMODE) && defined(KLUDGELINEMODE)
338 lmodetype = NO_AUTOKLUDGE;
340 /* ignore -k option if built without kludge linemode */
341 #endif /* defined(LINEMODE) && defined(KLUDGELINEMODE) */
359 * Allow the specification of alterations
360 * to the pty search range. It is legal to
361 * specify only one, and not change the
362 * other from its default.
364 c = strchr(optarg, '-');
370 lowpty = atoi(optarg);
371 if ((lowpty > highpty) || (lowpty < 0) ||
382 /* SecurID required */
388 if ((tos = parsetos(optarg, "tcp")) < 0)
390 "bad TOS argument '", optarg,
391 "'; will try to use default TOS");
393 warnx("TOS option unavailable; -S flag not supported");
398 utmp_len = atoi(optarg);
400 utmp_len = -utmp_len;
401 if (utmp_len >= sizeof(remote_hostname))
402 utmp_len = sizeof(remote_hostname) - 1;
406 registerd_host_only = 1;
409 #ifdef AUTHENTICATION
412 * Check for invalid authentication types
414 auth_disable_name(optarg);
416 #endif /* AUTHENTICATION */
429 warnx("%c: unknown option", ch);
441 int s, ns, foo, error;
442 char *service = "telnet";
443 struct addrinfo hints, *res;
448 } else if (argc == 1)
451 memset(&hints, 0, sizeof(hints));
452 hints.ai_flags = AI_PASSIVE;
453 hints.ai_family = family;
454 hints.ai_socktype = SOCK_STREAM;
455 hints.ai_protocol = 0;
456 error = getaddrinfo(NULL, service, &hints, &res);
459 errx(1, "tcp/%s: %s\n", service, gai_strerror(error));
460 if (error == EAI_SYSTEM)
461 errx(1, "tcp/%s: %s\n", service, strerror(errno));
465 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
468 (void) setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
469 (char *)&on, sizeof(on));
470 if (bind(s, res->ai_addr, res->ai_addrlen) < 0)
472 if (listen(s, 1) < 0)
474 foo = res->ai_addrlen;
475 ns = accept(s, res->ai_addr, &foo);
482 } else if (argc == 1) {
483 ; /* VOID*/ /* Just ignore the host/port name */
485 } else if (argc > 0) {
490 #if defined(_SC_CRAY_SECURE_SYS)
491 secflag = sysconf(_SC_CRAY_SECURE_SYS);
494 * Get socket's security label
497 int szss = sizeof(ss);
498 #ifdef SO_SEC_MULTI /* 8.0 code */
500 int szi = sizeof(int);
501 #endif /* SO_SEC_MULTI */
503 memset((char *)&dv, 0, sizeof(dv));
505 if (getsysv(&sysv, sizeof(struct sysv)) != 0)
509 * Get socket security label and set device values
510 * {security label to be set on ttyp device}
512 #ifdef SO_SEC_MULTI /* 8.0 code */
513 if ((getsockopt(0, SOL_SOCKET, SO_SECURITY,
514 (char *)&ss, &szss) < 0) ||
515 (getsockopt(0, SOL_SOCKET, SO_SEC_MULTI,
516 (char *)&sock_multi, &szi) < 0)) {
517 err(1, "getsockopt");
519 dv.dv_actlvl = ss.ss_actlabel.lt_level;
520 dv.dv_actcmp = ss.ss_actlabel.lt_compart;
522 dv.dv_minlvl = dv.dv_maxlvl = dv.dv_actlvl;
523 dv.dv_valcmp = dv.dv_actcmp;
525 dv.dv_minlvl = ss.ss_minlabel.lt_level;
526 dv.dv_maxlvl = ss.ss_maxlabel.lt_level;
527 dv.dv_valcmp = ss.ss_maxlabel.lt_compart;
531 #else /* SO_SEC_MULTI */ /* 7.0 code */
532 if (getsockopt(0, SOL_SOCKET, SO_SECURITY,
533 (char *)&ss, &szss) >= 0) {
534 dv.dv_actlvl = ss.ss_slevel;
535 dv.dv_actcmp = ss.ss_compart;
536 dv.dv_minlvl = ss.ss_minlvl;
537 dv.dv_maxlvl = ss.ss_maxlvl;
538 dv.dv_valcmp = ss.ss_maxcmp;
540 #endif /* SO_SEC_MULTI */
542 #endif /* _SC_CRAY_SECURE_SYS */
544 openlog("telnetd", LOG_PID | LOG_ODELAY, LOG_DAEMON);
545 fromlen = sizeof (from);
546 if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
551 setsockopt(0, SOL_SOCKET, SO_KEEPALIVE,
552 (char *)&on, sizeof (on)) < 0) {
553 syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
556 #if defined(IPPROTO_IP) && defined(IP_TOS)
557 if (from.ss_family == AF_INET) {
558 # if defined(HAS_GETTOS)
560 if (tos < 0 && (tp = gettosbyname("telnet", "tcp")))
564 tos = 020; /* Low Delay bit */
566 && (setsockopt(0, IPPROTO_IP, IP_TOS,
567 (char *)&tos, sizeof(tos)) < 0)
568 && (errno != ENOPROTOOPT) )
569 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
571 #endif /* defined(IPPROTO_IP) && defined(IP_TOS) */
573 doit((struct sockaddr *)&from);
581 fprintf(stderr, "usage: telnetd");
582 #ifdef AUTHENTICATION
583 fprintf(stderr, " [-a (debug|other|user|valid|off|none)]\n\t");
586 fprintf(stderr, " [-B]");
588 fprintf(stderr, " [-debug]");
590 fprintf(stderr, " [-D (options|report|exercise|netdata|ptydata)]\n\t");
592 #ifdef AUTHENTICATION
593 fprintf(stderr, " [-edebug]");
595 fprintf(stderr, " [-h]");
596 #if defined(CRAY) && defined(NEWINIT)
597 fprintf(stderr, " [-Iinitid]");
599 #if defined(LINEMODE) && defined(KLUDGELINEMODE)
600 fprintf(stderr, " [-k]");
603 fprintf(stderr, " [-l]");
605 fprintf(stderr, " [-n]");
607 fprintf(stderr, " [-r[lowpty]-[highpty]]");
609 fprintf(stderr, "\n\t");
611 fprintf(stderr, " [-s]");
614 fprintf(stderr, " [-S tos]");
616 #ifdef AUTHENTICATION
617 fprintf(stderr, " [-X auth-type]");
619 fprintf(stderr, " [-u utmp_hostname_length] [-U]");
620 fprintf(stderr, " [port]\n");
627 * Ask the other end to send along its terminal type and speed.
628 * Output is the variable terminaltype filled in.
630 static unsigned char ttytype_sbbuf[] = {
631 IAC, SB, TELOPT_TTYPE, TELQUAL_SEND, IAC, SE
635 getterminaltype(name)
642 #if defined(AUTHENTICATION)
644 * Handle the Authentication option before we do anything else.
646 send_do(TELOPT_AUTHENTICATION, 1);
647 while (his_will_wont_is_changing(TELOPT_AUTHENTICATION))
649 if (his_state_is_will(TELOPT_AUTHENTICATION)) {
650 retval = auth_wait(name);
655 send_will(TELOPT_ENCRYPT, 1);
656 #endif /* ENCRYPTION */
657 send_do(TELOPT_TTYPE, 1);
658 send_do(TELOPT_TSPEED, 1);
659 send_do(TELOPT_XDISPLOC, 1);
660 send_do(TELOPT_NEW_ENVIRON, 1);
661 send_do(TELOPT_OLD_ENVIRON, 1);
664 his_do_dont_is_changing(TELOPT_ENCRYPT) ||
665 #endif /* ENCRYPTION */
666 his_will_wont_is_changing(TELOPT_TTYPE) ||
667 his_will_wont_is_changing(TELOPT_TSPEED) ||
668 his_will_wont_is_changing(TELOPT_XDISPLOC) ||
669 his_will_wont_is_changing(TELOPT_NEW_ENVIRON) ||
670 his_will_wont_is_changing(TELOPT_OLD_ENVIRON)) {
675 * Wait for the negotiation of what type of encryption we can
676 * send with. If autoencrypt is not set, this will just return.
678 if (his_state_is_will(TELOPT_ENCRYPT)) {
681 #endif /* ENCRYPTION */
682 if (his_state_is_will(TELOPT_TSPEED)) {
683 static unsigned char sb[] =
684 { IAC, SB, TELOPT_TSPEED, TELQUAL_SEND, IAC, SE };
686 memmove(nfrontp, sb, sizeof sb);
687 nfrontp += sizeof sb;
688 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
690 if (his_state_is_will(TELOPT_XDISPLOC)) {
691 static unsigned char sb[] =
692 { IAC, SB, TELOPT_XDISPLOC, TELQUAL_SEND, IAC, SE };
694 memmove(nfrontp, sb, sizeof sb);
695 nfrontp += sizeof sb;
696 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
698 if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
699 static unsigned char sb[] =
700 { IAC, SB, TELOPT_NEW_ENVIRON, TELQUAL_SEND, IAC, SE };
702 memmove(nfrontp, sb, sizeof sb);
703 nfrontp += sizeof sb;
704 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
706 else if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
707 static unsigned char sb[] =
708 { IAC, SB, TELOPT_OLD_ENVIRON, TELQUAL_SEND, IAC, SE };
710 memmove(nfrontp, sb, sizeof sb);
711 nfrontp += sizeof sb;
712 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
714 if (his_state_is_will(TELOPT_TTYPE)) {
716 memmove(nfrontp, ttytype_sbbuf, sizeof ttytype_sbbuf);
717 nfrontp += sizeof ttytype_sbbuf;
718 DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
719 sizeof ttytype_sbbuf - 2););
721 if (his_state_is_will(TELOPT_TSPEED)) {
722 while (sequenceIs(tspeedsubopt, baseline))
725 if (his_state_is_will(TELOPT_XDISPLOC)) {
726 while (sequenceIs(xdisplocsubopt, baseline))
729 if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
730 while (sequenceIs(environsubopt, baseline))
733 if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
734 while (sequenceIs(oenvironsubopt, baseline))
737 if (his_state_is_will(TELOPT_TTYPE)) {
738 char first[256], last[256];
740 while (sequenceIs(ttypesubopt, baseline))
744 * If the other side has already disabled the option, then
745 * we have to just go with what we (might) have already gotten.
747 if (his_state_is_will(TELOPT_TTYPE) && !terminaltypeok(terminaltype)) {
748 (void) strncpy(first, terminaltype, sizeof(first)-1);
749 first[sizeof(first)-1] = '\0';
752 * Save the unknown name, and request the next name.
754 (void) strncpy(last, terminaltype, sizeof(last)-1);
755 last[sizeof(last)-1] = '\0';
757 if (terminaltypeok(terminaltype))
759 if ((strncmp(last, terminaltype, sizeof(last)) == 0) ||
760 his_state_is_wont(TELOPT_TTYPE)) {
762 * We've hit the end. If this is the same as
763 * the first name, just go with it.
765 if (strncmp(first, terminaltype, sizeof(first)) == 0)
768 * Get the terminal name one more time, so that
769 * RFC1091 compliant telnets will cycle back to
770 * the start of the list.
773 if (strncmp(first, terminaltype, sizeof(first)) != 0) {
774 (void) strncpy(terminaltype, first, sizeof(terminaltype)-1);
775 terminaltype[sizeof(terminaltype)-1] = '\0';
783 } /* end of getterminaltype */
789 * If the client turned off the option,
790 * we can't send another request, so we
793 if (his_state_is_wont(TELOPT_TTYPE))
796 memmove(nfrontp, ttytype_sbbuf, sizeof ttytype_sbbuf);
797 nfrontp += sizeof ttytype_sbbuf;
798 DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
799 sizeof ttytype_sbbuf - 2););
800 while (sequenceIs(ttypesubopt, baseline))
810 if (terminaltype == NULL)
814 * tgetent() will return 1 if the type is known, and
815 * 0 if it is not known. If it returns -1, it couldn't
816 * open the database. But if we can't open the database,
817 * it won't help to say we failed, because we won't be
818 * able to verify anything else. So, we treat -1 like 1.
820 if (tgetent(buf, s) == 0)
825 #ifndef MAXHOSTNAMELEN
826 #define MAXHOSTNAMELEN 64
827 #endif /* MAXHOSTNAMELEN */
830 char host_name[MAXHOSTNAMELEN];
832 extern void telnet P((int, int, char *));
837 * Get a pty, scan input lines.
841 struct sockaddr *who;
847 * Find an available pty to use.
850 pty = getpty(&ptynum);
852 fatal(net, "All network ports in use");
856 extern char *line, *getpty();
858 if ((lp = getpty()) == NULL)
859 fatal(net, "Out of ptys");
861 if ((pty = open(lp, 2)) >= 0) {
869 #if defined(_SC_CRAY_SECURE_SYS)
871 * set ttyp line security label
876 sprintf(tty_dev, "/dev/pty/%03d", ptynum);
877 if (setdevs(tty_dev, &dv) < 0)
878 fatal(net, "cannot set pty security");
879 sprintf(slave_dev, "/dev/ttyp%03d", ptynum);
880 if (setdevs(slave_dev, &dv) < 0)
881 fatal(net, "cannot set tty security");
883 #endif /* _SC_CRAY_SECURE_SYS */
885 /* get name of connected client */
886 if (realhostname_sa(remote_hostname, sizeof(remote_hostname) - 1,
887 who, who->sa_len) == HOSTNAME_INVALIDADDR && registerd_host_only)
888 fatal(net, "Couldn't resolve your address into a host name.\r\n\
889 Please contact your net administrator");
890 remote_hostname[sizeof(remote_hostname) - 1] = '\0';
892 trimdomain(remote_hostname, UT_HOSTSIZE);
893 if (!isdigit(remote_hostname[0]) && strlen(remote_hostname) > utmp_len)
894 err = getnameinfo(who, who->sa_len, remote_hostname,
895 sizeof(remote_hostname), NULL, 0,
896 NI_NUMERICHOST|NI_WITHSCOPEID);
897 /* XXX: do 'err' check */
899 (void) gethostname(host_name, sizeof(host_name) - 1);
900 host_name[sizeof(host_name) - 1] = '\0';
901 hostname = host_name;
903 #if defined(AUTHENTICATION) || defined(ENCRYPTION)
904 auth_encrypt_init(hostname, remote_hostname, "TELNETD", 1);
912 level = getterminaltype(user_name);
913 setenv("TERM", terminaltype ? terminaltype : "network", 1);
915 #if defined(_SC_CRAY_SECURE_SYS)
917 if (setulvl(dv.dv_actlvl) < 0)
918 fatal(net,"cannot setulvl()");
919 if (setucmp(dv.dv_actcmp) < 0)
920 fatal(net, "cannot setucmp()");
922 #endif /* _SC_CRAY_SECURE_SYS */
924 telnet(net, pty, remote_hostname); /* begin server process */
929 #if defined(CRAY2) && defined(UNICOS5) && defined(UNICOS50)
931 Xterm_output(ibufp, obuf, icountp, ocount)
933 int *icountp, ocount;
936 ret = term_output(*ibufp, obuf, *icountp, ocount);
941 #define term_output Xterm_output
942 #endif /* defined(CRAY2) && defined(UNICOS5) && defined(UNICOS50) */
945 * Main loop. Select from pty and network, and
946 * hand data to telnet receiver finite state machine.
954 #define TABBUFSIZ 512
955 char defent[TABBUFSIZ];
956 char defstrs[TABBUFSIZ];
965 * Initialize the slc mapping table.
970 * Do some tests where it is desireable to wait for a response.
971 * Rather than doing them slowly, one at a time, do them all
974 if (my_state_is_wont(TELOPT_SGA))
975 send_will(TELOPT_SGA, 1);
977 * Is the client side a 4.2 (NOT 4.3) system? We need to know this
978 * because 4.2 clients are unable to deal with TCP urgent data.
980 * To find out, we send out a "DO ECHO". If the remote system
981 * answers "WILL ECHO" it is probably a 4.2 client, and we note
982 * that fact ("WILL ECHO" ==> that the client will echo what
983 * WE, the server, sends it; it does NOT mean that the client will
984 * echo the terminal input).
986 send_do(TELOPT_ECHO, 1);
989 if (his_state_is_wont(TELOPT_LINEMODE)) {
990 /* Query the peer for linemode support by trying to negotiate
991 * the linemode option.
995 send_do(TELOPT_LINEMODE, 1); /* send do linemode */
997 #endif /* LINEMODE */
1000 * Send along a couple of other options that we wish to negotiate.
1002 send_do(TELOPT_NAWS, 1);
1003 send_will(TELOPT_STATUS, 1);
1004 flowmode = 1; /* default flow control state */
1005 restartany = -1; /* uninitialized... */
1006 send_do(TELOPT_LFLOW, 1);
1009 * Spin, waiting for a response from the DO ECHO. However,
1010 * some REALLY DUMB telnets out there might not respond
1011 * to the DO ECHO. So, we spin looking for NAWS, (most dumb
1012 * telnets so far seem to respond with WONT for a DO that
1013 * they don't understand...) because by the time we get the
1014 * response, it will already have processed the DO ECHO.
1015 * Kludge upon kludge.
1017 while (his_will_wont_is_changing(TELOPT_NAWS))
1022 * The client might have sent a WILL NAWS as part of its
1023 * startup code; if so, we'll be here before we get the
1024 * response to the DO ECHO. We'll make the assumption
1025 * that any implementation that understands about NAWS
1026 * is a modern enough implementation that it will respond
1027 * to our DO ECHO request; hence we'll do another spin
1028 * waiting for the ECHO option to settle down, which is
1029 * what we wanted to do in the first place...
1031 if (his_want_state_is_will(TELOPT_ECHO) &&
1032 his_state_is_will(TELOPT_NAWS)) {
1033 while (his_will_wont_is_changing(TELOPT_ECHO))
1037 * On the off chance that the telnet client is broken and does not
1038 * respond to the DO ECHO we sent, (after all, we did send the
1039 * DO NAWS negotiation after the DO ECHO, and we won't get here
1040 * until a response to the DO NAWS comes back) simulate the
1041 * receipt of a will echo. This will also send a WONT ECHO
1042 * to the client, since we assume that the client failed to
1043 * respond because it believes that it is already in DO ECHO
1044 * mode, which we do not want.
1046 if (his_want_state_is_will(TELOPT_ECHO)) {
1048 {sprintf(nfrontp, "td: simulating recv\r\n");
1049 nfrontp += strlen(nfrontp);});
1050 willoption(TELOPT_ECHO);
1054 * Finally, to clean things up, we turn on our echo. This
1055 * will break stupid 4.2 telnets out of local terminal echo.
1058 if (my_state_is_wont(TELOPT_ECHO))
1059 send_will(TELOPT_ECHO, 1);
1063 * Turn on packet mode
1065 (void) ioctl(p, TIOCPKT, (char *)&on);
1068 #if defined(LINEMODE) && defined(KLUDGELINEMODE)
1070 * Continuing line mode support. If client does not support
1071 * real linemode, attempt to negotiate kludge linemode by sending
1072 * the do timing mark sequence.
1074 if (lmodetype < REAL_LINEMODE)
1075 send_do(TELOPT_TM, 1);
1076 #endif /* defined(LINEMODE) && defined(KLUDGELINEMODE) */
1079 * Call telrcv() once to pick up anything received during
1080 * terminal type negotiation, 4.2/4.3 determination, and
1081 * linemode negotiation.
1085 (void) ioctl(f, FIONBIO, (char *)&on);
1086 (void) ioctl(p, FIONBIO, (char *)&on);
1087 #if defined(CRAY2) && defined(UNICOS5)
1088 init_termdriver(f, p, interrupt, sendbrk);
1091 #if defined(SO_OOBINLINE)
1092 (void) setsockopt(net, SOL_SOCKET, SO_OOBINLINE,
1093 (char *)&on, sizeof on);
1094 #endif /* defined(SO_OOBINLINE) */
1097 (void) signal(SIGTSTP, SIG_IGN);
1101 * Ignoring SIGTTOU keeps the kernel from blocking us
1102 * in ttioct() in /sys/tty.c.
1104 (void) signal(SIGTTOU, SIG_IGN);
1107 (void) signal(SIGCHLD, cleanup);
1109 #if defined(CRAY2) && defined(UNICOS5)
1111 * Cray-2 will send a signal when pty modes are changed by slave
1112 * side. Set up signal handler now.
1114 if ((int)signal(SIGUSR1, termstat) < 0)
1116 else if (ioctl(p, TCSIGME, (char *)SIGUSR1) < 0)
1117 warn("ioctl:TCSIGME");
1119 * Make processing loop check terminal characteristics early on.
1127 t = open(_PATH_TTY, O_RDWR);
1129 (void) ioctl(t, TIOCNOTTY, (char *)0);
1135 #if defined(CRAY) && defined(NEWINIT) && defined(TIOCSCTTY)
1137 ioctl(p, TIOCSCTTY, 0);
1141 * Show banner that getty never gave.
1143 * We put the banner in the pty input buffer. This way, it
1144 * gets carriage return null processing, etc., just like all
1145 * other pty --> client data.
1148 #if !defined(CRAY) || !defined(NEWINIT)
1153 if (getent(defent, "default") == 1) {
1157 HE = Getstr("he", &cp);
1158 HN = Getstr("hn", &cp);
1159 IM = Getstr("im", &cp);
1161 (void) strcpy(host_name, HN);
1168 edithost(HE, host_name);
1169 if (hostinfo && *IM)
1173 (void) strncat(ptyibuf2, ptyip, pcc+1);
1175 pcc = strlen(ptyip);
1178 * Last check to make sure all our states are correct.
1182 #endif /* LINEMODE */
1185 {sprintf(nfrontp, "td: Entering processing loop\r\n");
1186 nfrontp += strlen(nfrontp);});
1189 * Startup the login process on the slave side of the terminal
1190 * now. We delay this until here to insure option negotiation
1193 startslave(host, level, user_name);
1195 nfd = ((f > p) ? f : p) + 1;
1197 fd_set ibits, obits, xbits;
1200 if (ncc < 0 && pcc < 0)
1203 #if defined(CRAY2) && defined(UNICOS5)
1206 #endif /* defined(CRAY2) && defined(UNICOS5) */
1211 * Never look for input if there's still
1212 * stuff in the corresponding output buffer
1214 if (nfrontp - nbackp || pcc > 0) {
1219 if (pfrontp - pbackp || ncc > 0) {
1227 if ((c = select(nfd, &ibits, &obits, &xbits,
1228 (struct timeval *)0)) < 1) {
1230 if (errno == EINTR) {
1241 if (FD_ISSET(net, &xbits)) {
1246 * Something to read from the network...
1248 if (FD_ISSET(net, &ibits)) {
1249 #if !defined(SO_OOBINLINE)
1251 * In 4.2 (and 4.3 beta) systems, the
1252 * OOB indication and data handling in the kernel
1253 * is such that if two separate TCP Urgent requests
1254 * come in, one byte of TCP data will be overlaid.
1255 * This is fatal for Telnet, but we try to live
1258 * In addition, in 4.2 (and...), a special protocol
1259 * is needed to pick up the TCP Urgent data in
1260 * the correct sequence.
1262 * What we do is: if we think we are in urgent
1263 * mode, we look to see if we are "at the mark".
1264 * If we are, we do an OOB receive. If we run
1265 * this twice, we will do the OOB receive twice,
1266 * but the second will fail, since the second
1267 * time we were "at the mark", but there wasn't
1268 * any data there (the kernel doesn't reset
1269 * "at the mark" until we do a normal read).
1270 * Once we've read the OOB data, we go ahead
1271 * and do normal reads.
1273 * There is also another problem, which is that
1274 * since the OOB byte we read doesn't put us
1275 * out of OOB state, and since that byte is most
1276 * likely the TELNET DM (data mark), we would
1277 * stay in the TELNET SYNCH (SYNCHing) state.
1278 * So, clocks to the rescue. If we've "just"
1279 * received a DM, then we test for the
1280 * presence of OOB data when the receive OOB
1281 * fails (and AFTER we did the normal mode read
1282 * to clear "at the mark").
1287 (void) ioctl(net, SIOCATMARK, (char *)&atmark);
1289 ncc = recv(net, netibuf, sizeof (netibuf), MSG_OOB);
1290 if ((ncc == -1) && (errno == EINVAL)) {
1291 ncc = read(net, netibuf, sizeof (netibuf));
1292 if (sequenceIs(didnetreceive, gotDM)) {
1293 SYNCHing = stilloob(net);
1297 ncc = read(net, netibuf, sizeof (netibuf));
1300 ncc = read(net, netibuf, sizeof (netibuf));
1302 settimer(didnetreceive);
1303 #else /* !defined(SO_OOBINLINE)) */
1304 ncc = read(net, netibuf, sizeof (netibuf));
1305 #endif /* !defined(SO_OOBINLINE)) */
1306 if (ncc < 0 && errno == EWOULDBLOCK)
1314 DIAG((TD_REPORT | TD_NETDATA),
1315 {sprintf(nfrontp, "td: netread %d chars\r\n", ncc);
1316 nfrontp += strlen(nfrontp);});
1317 DIAG(TD_NETDATA, printdata("nd", netip, ncc));
1321 * Something to read from the pty...
1323 if (FD_ISSET(p, &ibits)) {
1325 pcc = read(p, ptyibuf, BUFSIZ);
1327 pcc = readstream(p, ptyibuf, BUFSIZ);
1330 * On some systems, if we try to read something
1331 * off the master side before the slave side is
1332 * opened, we get EIO.
1334 if (pcc < 0 && (errno == EWOULDBLOCK ||
1343 #if !defined(CRAY2) || !defined(UNICOS5)
1346 * If ioctl from pty, pass it through net
1348 if (ptyibuf[0] & TIOCPKT_IOCTL) {
1349 copy_termbuf(ptyibuf+1, pcc-1);
1353 #endif /* LINEMODE */
1354 if (ptyibuf[0] & TIOCPKT_FLUSHWRITE) {
1355 netclear(); /* clear buffer back */
1358 * There are client telnets on some
1359 * operating systems get screwed up
1360 * royally if we send them urgent
1365 neturg = nfrontp-1; /* off by one XXX */
1367 printoption("td: send IAC", DM));
1371 if (his_state_is_will(TELOPT_LFLOW) &&
1373 (TIOCPKT_NOSTOP|TIOCPKT_DOSTOP))) {
1375 ptyibuf[0] & TIOCPKT_DOSTOP ? 1 : 0;
1376 if (newflow != flowmode) {
1378 (void) sprintf(nfrontp,
1380 IAC, SB, TELOPT_LFLOW,
1385 DIAG(TD_OPTIONS, printsub('>',
1386 (unsigned char *)nfrontp-4,
1392 #else /* defined(CRAY2) && defined(UNICOS5) */
1396 pcc = term_output(&unptyip, ptyibuf2,
1401 #endif /* defined(CRAY2) && defined(UNICOS5) */
1406 if ((&netobuf[BUFSIZ] - nfrontp) < 2)
1408 c = *ptyip++ & 0377, pcc--;
1411 #if defined(CRAY2) && defined(UNICOS5)
1412 else if (c == '\n' &&
1413 my_state_is_wont(TELOPT_BINARY) && newmap)
1415 #endif /* defined(CRAY2) && defined(UNICOS5) */
1417 if ((c == '\r') && (my_state_is_wont(TELOPT_BINARY))) {
1418 if (pcc > 0 && ((*ptyip & 0377) == '\n')) {
1419 *nfrontp++ = *ptyip++ & 0377;
1425 #if defined(CRAY2) && defined(UNICOS5)
1427 * If chars were left over from the terminal driver,
1428 * note their existence.
1430 if (!uselinemode && unpcc) {
1435 #endif /* defined(CRAY2) && defined(UNICOS5) */
1437 if (FD_ISSET(f, &obits) && (nfrontp - nbackp) > 0)
1441 if (FD_ISSET(p, &obits) && (pfrontp - pbackp) > 0)
1445 } /* end of telnet */
1449 # define TCSIG TIOCSIG
1455 int flowison = -1; /* current state of flow: -1 is unknown */
1457 int readstream(p, ibuf, bufsize)
1464 struct termios *tsp;
1471 strbufc.maxlen = BUFSIZ;
1472 strbufc.buf = (char *)ctlbuf;
1473 strbufd.maxlen = bufsize-1;
1475 strbufd.buf = ibuf+1;
1478 ret = getmsg(p, &strbufc, &strbufd, &flags);
1479 if (ret < 0) /* error of some sort -- probably EAGAIN */
1482 if (strbufc.len <= 0 || ctlbuf[0] == M_DATA) {
1484 if (strbufd.len > 0) { /* real data */
1485 return(strbufd.len + 1); /* count header char */
1494 * It's a control message. Return 1, to look at the flag we set
1497 switch (ctlbuf[0]) {
1499 if (ibuf[1] & FLUSHW)
1500 ibuf[0] = TIOCPKT_FLUSHWRITE;
1504 ip = (struct iocblk *) (ibuf+1);
1506 switch (ip->ioc_cmd) {
1510 tsp = (struct termios *)
1511 (ibuf+1 + sizeof(struct iocblk));
1512 vstop = tsp->c_cc[VSTOP];
1513 vstart = tsp->c_cc[VSTART];
1514 ixon = tsp->c_iflag & IXON;
1519 tp = (struct termio *) (ibuf+1 + sizeof(struct iocblk));
1520 vstop = tp->c_cc[VSTOP];
1521 vstart = tp->c_cc[VSTART];
1522 ixon = tp->c_iflag & IXON;
1529 newflow = (ixon && (vstart == 021) && (vstop == 023)) ? 1 : 0;
1530 if (newflow != flowison) { /* it's a change */
1532 ibuf[0] = newflow ? TIOCPKT_DOSTOP : TIOCPKT_NOSTOP;
1537 /* nothing worth doing anything about */
1541 #endif /* STREAMSPTY */
1544 * Send interrupt to process on other side of pty.
1545 * If it is in raw mode, just write NULL;
1546 * otherwise, write intr char.
1551 ptyflush(); /* half-hearted */
1553 #if defined(STREAMSPTY) && defined(TIOCSIGNAL)
1554 /* Streams PTY style ioctl to post a signal */
1557 (void) ioctl(pty, TIOCSIGNAL, &sig);
1558 (void) ioctl(pty, I_FLUSH, FLUSHR);
1562 (void) ioctl(pty, TCSIG, (char *)SIGINT);
1565 *pfrontp++ = slctab[SLC_IP].sptr ?
1566 (unsigned char)*slctab[SLC_IP].sptr : '\177';
1572 * Send quit to process on other side of pty.
1573 * If it is in raw mode, just write NULL;
1574 * otherwise, write quit char.
1579 ptyflush(); /* half-hearted */
1581 (void) ioctl(pty, TCSIG, (char *)SIGQUIT);
1584 *pfrontp++ = slctab[SLC_ABORT].sptr ?
1585 (unsigned char)*slctab[SLC_ABORT].sptr : '\034';
1593 ptyflush(); /* half-hearted */
1595 (void) ioctl(pty, TCSIG, (char *)SIGTSTP);
1597 *pfrontp++ = slctab[SLC_SUSP].sptr ?
1598 (unsigned char)*slctab[SLC_SUSP].sptr : '\032';
1600 #endif /* SIGTSTP */
1604 * When we get an AYT, if ^T is enabled, use that. Otherwise,
1605 * just send back "[Yes]".
1610 #if defined(SIGINFO) && defined(TCSIG)
1611 if (slctab[SLC_AYT].sptr && *slctab[SLC_AYT].sptr != _POSIX_VDISABLE) {
1612 (void) ioctl(pty, TCSIG, (char *)SIGINFO);
1616 (void) strcpy(nfrontp, "\r\n[Yes]\r\n");
1625 #if defined(LINEMODE) && defined(USE_TERMIO) && (VEOF == VMIN)
1626 if (!tty_isediting()) {
1627 extern char oldeofc;
1628 *pfrontp++ = oldeofc;
1632 *pfrontp++ = slctab[SLC_EOF].sptr ?
1633 (unsigned char)*slctab[SLC_EOF].sptr : '\004';