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