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