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