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