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. 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.
16 *
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.
28 */
29
30 #if 0
31 #ifndef lint
32 static const char sccsid[] = "@(#)telnetd.c 8.4 (Berkeley) 5/30/95";
33 #endif
34 #endif
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
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
47 #include <arpa/inet.h>
48
49 #ifdef AUTHENTICATION
50 #include <libtelnet/auth.h>
51 #endif
52 #ifdef ENCRYPTION
53 #include <libtelnet/encrypt.h>
54 #endif
55 #include <libtelnet/misc.h>
56
57 char remote_hostname[MAXHOSTNAMELEN];
58 size_t utmp_len = sizeof(remote_hostname) - 1;
59 int registerd_host_only = 0;
60
61
62 /*
63 * I/O data buffers,
64 * pointers, and counters.
65 */
66 char ptyibuf[BUFSIZ], *ptyip = ptyibuf;
67 char ptyibuf2[BUFSIZ];
68
69 int readstream(int, char *, int);
70 void doit(struct sockaddr *);
71 int terminaltypeok(char *);
72
73 int hostinfo = 1; /* do we print login banner? */
74
75 static int debug = 0;
76 int keepalive = 1;
77 const char *altlogin;
78
79 void doit(struct sockaddr *);
80 int terminaltypeok(char *);
81 void startslave(char *, int, char *);
82 extern void usage(void);
83 static void _gettermname(void);
84
85 /*
86 * The string to pass to getopt(). We do it this way so
87 * that only the actual options that we support will be
88 * passed off to getopt().
89 */
90 char valid_opts[] = {
91 'd', ':', 'h', 'k', 'n', 'p', ':', 'S', ':', 'u', ':', 'U',
92 '4', '6',
93 #ifdef AUTHENTICATION
94 'a', ':', 'X', ':',
95 #endif
96 #ifdef BFTPDAEMON
97 'B',
98 #endif
99 #ifdef DIAGNOSTICS
100 'D', ':',
101 #endif
102 #ifdef ENCRYPTION
103 'e', ':',
104 #endif
105 #ifdef LINEMODE
106 'l',
107 #endif
108 '\0'
109 };
110
111 int family = AF_INET;
112
113 #ifndef MAXHOSTNAMELEN
114 #define MAXHOSTNAMELEN 256
115 #endif /* MAXHOSTNAMELEN */
116
117 char *hostname;
118 char host_name[MAXHOSTNAMELEN];
119
120 extern void telnet(int, int, char *);
121
122 int level;
123 char user_name[256];
124
125 int
main(int argc,char * argv[])126 main(int argc, char *argv[])
127 {
128 u_long ultmp;
129 struct sockaddr_storage from;
130 int on = 1, fromlen;
131 int ch;
132 #if defined(IPPROTO_IP) && defined(IP_TOS)
133 int tos = -1;
134 #endif
135 char *ep;
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 #define MAXTOS 255
273 ultmp = strtoul(optarg, &ep, 0);
274 if (*ep || ep == optarg || ultmp > MAXTOS)
275 warnx("%s%s%s",
276 "bad TOS argument '", optarg,
277 "'; will try to use default TOS");
278 else
279 tos = ultmp;
280 #endif
281 break;
282
283 case 'u':
284 utmp_len = (size_t)atoi(optarg);
285 if (utmp_len >= sizeof(remote_hostname))
286 utmp_len = sizeof(remote_hostname) - 1;
287 break;
288
289 case 'U':
290 registerd_host_only = 1;
291 break;
292
293 #ifdef AUTHENTICATION
294 case 'X':
295 /*
296 * Check for invalid authentication types
297 */
298 auth_disable_name(optarg);
299 break;
300 #endif /* AUTHENTICATION */
301
302 case '4':
303 family = AF_INET;
304 break;
305
306 #ifdef INET6
307 case '6':
308 family = AF_INET6;
309 break;
310 #endif
311
312 default:
313 warnx("%c: unknown option", ch);
314 /* FALLTHROUGH */
315 case '?':
316 usage();
317 /* NOTREACHED */
318 }
319 }
320
321 argc -= optind;
322 argv += optind;
323
324 if (debug) {
325 int s, ns, foo, error;
326 const char *service = "telnet";
327 struct addrinfo hints, *res;
328
329 if (argc > 1) {
330 usage();
331 /* NOT REACHED */
332 } else if (argc == 1)
333 service = *argv;
334
335 memset(&hints, 0, sizeof(hints));
336 hints.ai_flags = AI_PASSIVE;
337 hints.ai_family = family;
338 hints.ai_socktype = SOCK_STREAM;
339 hints.ai_protocol = 0;
340 error = getaddrinfo(NULL, service, &hints, &res);
341
342 if (error) {
343 errx(1, "tcp/%s: %s\n", service, gai_strerror(error));
344 if (error == EAI_SYSTEM)
345 errx(1, "tcp/%s: %s\n", service, strerror(errno));
346 usage();
347 }
348
349 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
350 if (s < 0)
351 err(1, "socket");
352 (void) setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
353 (char *)&on, sizeof(on));
354 if (debug > 1)
355 (void) setsockopt(s, SOL_SOCKET, SO_DEBUG,
356 (char *)&on, sizeof(on));
357 if (bind(s, res->ai_addr, res->ai_addrlen) < 0)
358 err(1, "bind");
359 if (listen(s, 1) < 0)
360 err(1, "listen");
361 foo = res->ai_addrlen;
362 ns = accept(s, res->ai_addr, &foo);
363 if (ns < 0)
364 err(1, "accept");
365 (void) setsockopt(ns, SOL_SOCKET, SO_DEBUG,
366 (char *)&on, sizeof(on));
367 (void) dup2(ns, 0);
368 (void) close(ns);
369 (void) close(s);
370 #ifdef convex
371 } else if (argc == 1) {
372 ; /* VOID*/ /* Just ignore the host/port name */
373 #endif
374 } else if (argc > 0) {
375 usage();
376 /* NOT REACHED */
377 }
378
379 openlog("telnetd", LOG_PID | LOG_ODELAY, LOG_DAEMON);
380 fromlen = sizeof (from);
381 if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
382 warn("getpeername");
383 _exit(1);
384 }
385 if (keepalive &&
386 setsockopt(0, SOL_SOCKET, SO_KEEPALIVE,
387 (char *)&on, sizeof (on)) < 0) {
388 syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
389 }
390
391 #if defined(IPPROTO_IP) && defined(IP_TOS)
392 if (from.ss_family == AF_INET) {
393 # if defined(HAS_GETTOS)
394 struct tosent *tp;
395 if (tos < 0 && (tp = gettosbyname("telnet", "tcp")))
396 tos = tp->t_tos;
397 # endif
398 if (tos < 0)
399 tos = 020; /* Low Delay bit */
400 if (tos
401 && (setsockopt(0, IPPROTO_IP, IP_TOS,
402 (char *)&tos, sizeof(tos)) < 0)
403 && (errno != ENOPROTOOPT) )
404 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
405 }
406 #endif /* defined(IPPROTO_IP) && defined(IP_TOS) */
407 net = 0;
408 doit((struct sockaddr *)&from);
409 /* NOTREACHED */
410 return(0);
411 } /* end of main */
412
413 void
usage()414 usage()
415 {
416 fprintf(stderr, "usage: telnetd");
417 #ifdef AUTHENTICATION
418 fprintf(stderr,
419 " [-4] [-6] [-a (debug|other|user|valid|off|none)]\n\t");
420 #endif
421 #ifdef BFTPDAEMON
422 fprintf(stderr, " [-B]");
423 #endif
424 fprintf(stderr, " [-debug]");
425 #ifdef DIAGNOSTICS
426 fprintf(stderr, " [-D (options|report|exercise|netdata|ptydata)]\n\t");
427 #endif
428 #ifdef AUTHENTICATION
429 fprintf(stderr, " [-edebug]");
430 #endif
431 fprintf(stderr, " [-h]");
432 #if defined(LINEMODE) && defined(KLUDGELINEMODE)
433 fprintf(stderr, " [-k]");
434 #endif
435 #ifdef LINEMODE
436 fprintf(stderr, " [-l]");
437 #endif
438 fprintf(stderr, " [-n]");
439 fprintf(stderr, "\n\t");
440 #ifdef HAS_GETTOS
441 fprintf(stderr, " [-S tos]");
442 #endif
443 #ifdef AUTHENTICATION
444 fprintf(stderr, " [-X auth-type]");
445 #endif
446 fprintf(stderr, " [-u utmp_hostname_length] [-U]");
447 fprintf(stderr, " [port]\n");
448 exit(1);
449 }
450
451 /*
452 * getterminaltype
453 *
454 * Ask the other end to send along its terminal type and speed.
455 * Output is the variable terminaltype filled in.
456 */
457 static unsigned char ttytype_sbbuf[] = {
458 IAC, SB, TELOPT_TTYPE, TELQUAL_SEND, IAC, SE
459 };
460
461
462 #ifndef AUTHENTICATION
463 #define undef2 __unused
464 #else
465 #define undef2
466 #endif
467
468 static int
getterminaltype(char * name undef2)469 getterminaltype(char *name undef2)
470 {
471 int retval = -1;
472
473 settimer(baseline);
474 #ifdef AUTHENTICATION
475 /*
476 * Handle the Authentication option before we do anything else.
477 */
478 if (auth_level >= 0) {
479 send_do(TELOPT_AUTHENTICATION, 1);
480 while (his_will_wont_is_changing(TELOPT_AUTHENTICATION))
481 ttloop();
482 if (his_state_is_will(TELOPT_AUTHENTICATION)) {
483 retval = auth_wait(name);
484 }
485 }
486 #endif
487
488 #ifdef ENCRYPTION
489 send_will(TELOPT_ENCRYPT, 1);
490 #endif /* ENCRYPTION */
491 send_do(TELOPT_TTYPE, 1);
492 send_do(TELOPT_TSPEED, 1);
493 send_do(TELOPT_XDISPLOC, 1);
494 send_do(TELOPT_NEW_ENVIRON, 1);
495 send_do(TELOPT_OLD_ENVIRON, 1);
496 while (
497 #ifdef ENCRYPTION
498 his_do_dont_is_changing(TELOPT_ENCRYPT) ||
499 #endif /* ENCRYPTION */
500 his_will_wont_is_changing(TELOPT_TTYPE) ||
501 his_will_wont_is_changing(TELOPT_TSPEED) ||
502 his_will_wont_is_changing(TELOPT_XDISPLOC) ||
503 his_will_wont_is_changing(TELOPT_NEW_ENVIRON) ||
504 his_will_wont_is_changing(TELOPT_OLD_ENVIRON)) {
505 ttloop();
506 }
507 #ifdef ENCRYPTION
508 /*
509 * Wait for the negotiation of what type of encryption we can
510 * send with. If autoencrypt is not set, this will just return.
511 */
512 if (his_state_is_will(TELOPT_ENCRYPT)) {
513 encrypt_wait();
514 }
515 #endif /* ENCRYPTION */
516 if (his_state_is_will(TELOPT_TSPEED)) {
517 static unsigned char sb[] =
518 { IAC, SB, TELOPT_TSPEED, TELQUAL_SEND, IAC, SE };
519
520 output_datalen(sb, sizeof sb);
521 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
522 }
523 if (his_state_is_will(TELOPT_XDISPLOC)) {
524 static unsigned char sb[] =
525 { IAC, SB, TELOPT_XDISPLOC, TELQUAL_SEND, IAC, SE };
526
527 output_datalen(sb, sizeof sb);
528 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
529 }
530 if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
531 static unsigned char sb[] =
532 { IAC, SB, TELOPT_NEW_ENVIRON, TELQUAL_SEND, IAC, SE };
533
534 output_datalen(sb, sizeof sb);
535 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
536 }
537 else if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
538 static unsigned char sb[] =
539 { IAC, SB, TELOPT_OLD_ENVIRON, TELQUAL_SEND, IAC, SE };
540
541 output_datalen(sb, sizeof sb);
542 DIAG(TD_OPTIONS, printsub('>', sb + 2, sizeof sb - 2););
543 }
544 if (his_state_is_will(TELOPT_TTYPE)) {
545
546 output_datalen(ttytype_sbbuf, sizeof ttytype_sbbuf);
547 DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
548 sizeof ttytype_sbbuf - 2););
549 }
550 if (his_state_is_will(TELOPT_TSPEED)) {
551 while (sequenceIs(tspeedsubopt, baseline))
552 ttloop();
553 }
554 if (his_state_is_will(TELOPT_XDISPLOC)) {
555 while (sequenceIs(xdisplocsubopt, baseline))
556 ttloop();
557 }
558 if (his_state_is_will(TELOPT_NEW_ENVIRON)) {
559 while (sequenceIs(environsubopt, baseline))
560 ttloop();
561 }
562 if (his_state_is_will(TELOPT_OLD_ENVIRON)) {
563 while (sequenceIs(oenvironsubopt, baseline))
564 ttloop();
565 }
566 if (his_state_is_will(TELOPT_TTYPE)) {
567 char first[256], last[256];
568
569 while (sequenceIs(ttypesubopt, baseline))
570 ttloop();
571
572 /*
573 * If the other side has already disabled the option, then
574 * we have to just go with what we (might) have already gotten.
575 */
576 if (his_state_is_will(TELOPT_TTYPE) && !terminaltypeok(terminaltype)) {
577 (void) strncpy(first, terminaltype, sizeof(first)-1);
578 first[sizeof(first)-1] = '\0';
579 for(;;) {
580 /*
581 * Save the unknown name, and request the next name.
582 */
583 (void) strncpy(last, terminaltype, sizeof(last)-1);
584 last[sizeof(last)-1] = '\0';
585 _gettermname();
586 if (terminaltypeok(terminaltype))
587 break;
588 if ((strncmp(last, terminaltype, sizeof(last)) == 0) ||
589 his_state_is_wont(TELOPT_TTYPE)) {
590 /*
591 * We've hit the end. If this is the same as
592 * the first name, just go with it.
593 */
594 if (strncmp(first, terminaltype, sizeof(first)) == 0)
595 break;
596 /*
597 * Get the terminal name one more time, so that
598 * RFC1091 compliant telnets will cycle back to
599 * the start of the list.
600 */
601 _gettermname();
602 if (strncmp(first, terminaltype, sizeof(first)) != 0) {
603 (void) strncpy(terminaltype, first, sizeof(terminaltype)-1);
604 terminaltype[sizeof(terminaltype)-1] = '\0';
605 }
606 break;
607 }
608 }
609 }
610 }
611 return(retval);
612 } /* end of getterminaltype */
613
614 static void
_gettermname(void)615 _gettermname(void)
616 {
617 /*
618 * If the client turned off the option,
619 * we can't send another request, so we
620 * just return.
621 */
622 if (his_state_is_wont(TELOPT_TTYPE))
623 return;
624 settimer(baseline);
625 output_datalen(ttytype_sbbuf, sizeof ttytype_sbbuf);
626 DIAG(TD_OPTIONS, printsub('>', ttytype_sbbuf + 2,
627 sizeof ttytype_sbbuf - 2););
628 while (sequenceIs(ttypesubopt, baseline))
629 ttloop();
630 }
631
632 int
terminaltypeok(char * s)633 terminaltypeok(char *s)
634 {
635 char buf[1024];
636
637 if (terminaltype == NULL)
638 return(1);
639
640 /*
641 * tgetent() will return 1 if the type is known, and
642 * 0 if it is not known. If it returns -1, it couldn't
643 * open the database. But if we can't open the database,
644 * it won't help to say we failed, because we won't be
645 * able to verify anything else. So, we treat -1 like 1.
646 */
647 if (tgetent(buf, s) == 0)
648 return(0);
649 return(1);
650 }
651
652 /*
653 * Get a pty, scan input lines.
654 */
655 void
doit(struct sockaddr * who)656 doit(struct sockaddr *who)
657 {
658 int err_; /* XXX */
659 int ptynum;
660
661 /*
662 * Initialize the slc mapping table.
663 */
664 get_slc_defaults();
665
666 /*
667 * Find an available pty to use.
668 */
669 #ifndef convex
670 pty = getpty(&ptynum);
671 if (pty < 0)
672 fatal(net, "All network ports in use");
673 #else
674 for (;;) {
675 char *lp;
676
677 if ((lp = getpty()) == NULL)
678 fatal(net, "Out of ptys");
679
680 if ((pty = open(lp, 2)) >= 0) {
681 strlcpy(line,lp,sizeof(line));
682 line[5] = 't';
683 break;
684 }
685 }
686 #endif
687
688 /* get name of connected client */
689 if (realhostname_sa(remote_hostname, sizeof(remote_hostname) - 1,
690 who, who->sa_len) == HOSTNAME_INVALIDADDR && registerd_host_only)
691 fatal(net, "Couldn't resolve your address into a host name.\r\n\
692 Please contact your net administrator");
693 remote_hostname[sizeof(remote_hostname) - 1] = '\0';
694
695 if (!isdigit(remote_hostname[0]) && strlen(remote_hostname) > utmp_len)
696 err_ = getnameinfo(who, who->sa_len, remote_hostname,
697 sizeof(remote_hostname), NULL, 0,
698 NI_NUMERICHOST);
699 /* XXX: do 'err_' check */
700
701 (void) gethostname(host_name, sizeof(host_name) - 1);
702 host_name[sizeof(host_name) - 1] = '\0';
703 hostname = host_name;
704
705 #ifdef AUTHENTICATION
706 #ifdef ENCRYPTION
707 /* The above #ifdefs should actually be "or"'ed, not "and"'ed.
708 * This is a byproduct of needing "#ifdef" and not "#if defined()"
709 * for unifdef. XXX MarkM
710 */
711 auth_encrypt_init(hostname, remote_hostname, "TELNETD", 1);
712 #endif
713 #endif
714
715 init_env();
716 /*
717 * get terminal type.
718 */
719 *user_name = 0;
720 level = getterminaltype(user_name);
721 setenv("TERM", terminaltype ? terminaltype : "network", 1);
722
723 telnet(net, pty, remote_hostname); /* begin server process */
724
725 /*NOTREACHED*/
726 } /* end of doit */
727
728 /*
729 * Main loop. Select from pty and network, and
730 * hand data to telnet receiver finite state machine.
731 */
732 void
telnet(int f,int p,char * host)733 telnet(int f, int p, char *host)
734 {
735 int on = 1;
736 #define TABBUFSIZ 512
737 char defent[TABBUFSIZ];
738 char defstrs[TABBUFSIZ];
739 #undef TABBUFSIZ
740 char *HE;
741 char *HN;
742 char *IM;
743 char *IF;
744 char *if_buf;
745 int if_fd = -1;
746 struct stat statbuf;
747 int nfd;
748
749 /*
750 * Do some tests where it is desireable to wait for a response.
751 * Rather than doing them slowly, one at a time, do them all
752 * at once.
753 */
754 if (my_state_is_wont(TELOPT_SGA))
755 send_will(TELOPT_SGA, 1);
756 /*
757 * Is the client side a 4.2 (NOT 4.3) system? We need to know this
758 * because 4.2 clients are unable to deal with TCP urgent data.
759 *
760 * To find out, we send out a "DO ECHO". If the remote system
761 * answers "WILL ECHO" it is probably a 4.2 client, and we note
762 * that fact ("WILL ECHO" ==> that the client will echo what
763 * WE, the server, sends it; it does NOT mean that the client will
764 * echo the terminal input).
765 */
766 send_do(TELOPT_ECHO, 1);
767
768 #ifdef LINEMODE
769 if (his_state_is_wont(TELOPT_LINEMODE)) {
770 /* Query the peer for linemode support by trying to negotiate
771 * the linemode option.
772 */
773 linemode = 0;
774 editmode = 0;
775 send_do(TELOPT_LINEMODE, 1); /* send do linemode */
776 }
777 #endif /* LINEMODE */
778
779 /*
780 * Send along a couple of other options that we wish to negotiate.
781 */
782 send_do(TELOPT_NAWS, 1);
783 send_will(TELOPT_STATUS, 1);
784 flowmode = 1; /* default flow control state */
785 restartany = -1; /* uninitialized... */
786 send_do(TELOPT_LFLOW, 1);
787
788 /*
789 * Spin, waiting for a response from the DO ECHO. However,
790 * some REALLY DUMB telnets out there might not respond
791 * to the DO ECHO. So, we spin looking for NAWS, (most dumb
792 * telnets so far seem to respond with WONT for a DO that
793 * they don't understand...) because by the time we get the
794 * response, it will already have processed the DO ECHO.
795 * Kludge upon kludge.
796 */
797 while (his_will_wont_is_changing(TELOPT_NAWS))
798 ttloop();
799
800 /*
801 * But...
802 * The client might have sent a WILL NAWS as part of its
803 * startup code; if so, we'll be here before we get the
804 * response to the DO ECHO. We'll make the assumption
805 * that any implementation that understands about NAWS
806 * is a modern enough implementation that it will respond
807 * to our DO ECHO request; hence we'll do another spin
808 * waiting for the ECHO option to settle down, which is
809 * what we wanted to do in the first place...
810 */
811 if (his_want_state_is_will(TELOPT_ECHO) &&
812 his_state_is_will(TELOPT_NAWS)) {
813 while (his_will_wont_is_changing(TELOPT_ECHO))
814 ttloop();
815 }
816 /*
817 * On the off chance that the telnet client is broken and does not
818 * respond to the DO ECHO we sent, (after all, we did send the
819 * DO NAWS negotiation after the DO ECHO, and we won't get here
820 * until a response to the DO NAWS comes back) simulate the
821 * receipt of a will echo. This will also send a WONT ECHO
822 * to the client, since we assume that the client failed to
823 * respond because it believes that it is already in DO ECHO
824 * mode, which we do not want.
825 */
826 if (his_want_state_is_will(TELOPT_ECHO)) {
827 DIAG(TD_OPTIONS, output_data("td: simulating recv\r\n"));
828 willoption(TELOPT_ECHO);
829 }
830
831 /*
832 * Finally, to clean things up, we turn on our echo. This
833 * will break stupid 4.2 telnets out of local terminal echo.
834 */
835
836 if (my_state_is_wont(TELOPT_ECHO))
837 send_will(TELOPT_ECHO, 1);
838
839 #if (!defined(__BEOS__) && !defined(__HAIKU__))
840 /*
841 * Turn on packet mode
842 */
843 (void) ioctl(p, TIOCPKT, (char *)&on);
844 #endif
845
846 #if defined(LINEMODE) && defined(KLUDGELINEMODE)
847 /*
848 * Continuing line mode support. If client does not support
849 * real linemode, attempt to negotiate kludge linemode by sending
850 * the do timing mark sequence.
851 */
852 if (lmodetype < REAL_LINEMODE)
853 send_do(TELOPT_TM, 1);
854 #endif /* defined(LINEMODE) && defined(KLUDGELINEMODE) */
855
856 /*
857 * Call telrcv() once to pick up anything received during
858 * terminal type negotiation, 4.2/4.3 determination, and
859 * linemode negotiation.
860 */
861 telrcv();
862
863 (void) ioctl(f, FIONBIO, (char *)&on);
864 (void) ioctl(p, FIONBIO, (char *)&on);
865
866 #if defined(SO_OOBINLINE)
867 (void) setsockopt(net, SOL_SOCKET, SO_OOBINLINE,
868 (char *)&on, sizeof on);
869 #endif /* defined(SO_OOBINLINE) */
870
871 #ifdef SIGTSTP
872 (void) signal(SIGTSTP, SIG_IGN);
873 #endif
874 #ifdef SIGTTOU
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 #endif
881
882 (void) signal(SIGCHLD, cleanup);
883
884 #ifdef TIOCNOTTY
885 {
886 int t;
887 t = open(_PATH_TTY, O_RDWR);
888 if (t >= 0) {
889 (void) ioctl(t, TIOCNOTTY, (char *)0);
890 (void) close(t);
891 }
892 }
893 #endif
894
895 /*
896 * Show banner that getty never gave.
897 *
898 * We put the banner in the pty input buffer. This way, it
899 * gets carriage return null processing, etc., just like all
900 * other pty --> client data.
901 */
902
903 if (getent(defent, "default") == 1) {
904 char *cp=defstrs;
905
906 HE = Getstr("he", &cp);
907 HN = Getstr("hn", &cp);
908 IM = Getstr("im", &cp);
909 IF = Getstr("if", &cp);
910 if (HN && *HN)
911 (void) strlcpy(host_name, HN, sizeof(host_name));
912 if (IF) {
913 if_fd = open(IF, O_RDONLY, 000);
914 IM = 0;
915 }
916 if (IM == 0)
917 IM = strdup("");
918 } else {
919 IM = strdup(DEFAULT_IM);
920 HE = 0;
921 }
922 edithost(HE, host_name);
923 if (hostinfo && *IM)
924 putf(IM, ptyibuf2);
925 if (if_fd != -1) {
926 if (fstat(if_fd, &statbuf) != -1 && statbuf.st_size > 0) {
927 if_buf = (char *) mmap (0, statbuf.st_size,
928 PROT_READ, 0, if_fd, 0);
929 if (if_buf != MAP_FAILED) {
930 putf(if_buf, ptyibuf2);
931 munmap(if_buf, statbuf.st_size);
932 }
933 }
934 close (if_fd);
935 }
936
937 if (pcc)
938 (void) strncat(ptyibuf2, ptyip, pcc+1);
939 ptyip = ptyibuf2;
940 pcc = strlen(ptyip);
941 #ifdef LINEMODE
942 /*
943 * Last check to make sure all our states are correct.
944 */
945 init_termbuf();
946 localstat();
947 #endif /* LINEMODE */
948
949 DIAG(TD_REPORT, output_data("td: Entering processing loop\r\n"));
950
951 /*
952 * Startup the login process on the slave side of the terminal
953 * now. We delay this until here to insure option negotiation
954 * is complete.
955 */
956 startslave(host, level, user_name);
957
958 nfd = ((f > p) ? f : p) + 1;
959 for (;;) {
960 fd_set ibits, obits, xbits;
961 int c;
962
963 if (ncc < 0 && pcc < 0)
964 break;
965
966 FD_ZERO(&ibits);
967 FD_ZERO(&obits);
968 FD_ZERO(&xbits);
969 /*
970 * Never look for input if there's still
971 * stuff in the corresponding output buffer
972 */
973 if (nfrontp - nbackp || pcc > 0) {
974 FD_SET(f, &obits);
975 } else {
976 FD_SET(p, &ibits);
977 }
978 if (pfrontp - pbackp || ncc > 0) {
979 FD_SET(p, &obits);
980 } else {
981 FD_SET(f, &ibits);
982 }
983 if (!SYNCHing) {
984 FD_SET(f, &xbits);
985 }
986 if ((c = select(nfd, &ibits, &obits, &xbits,
987 (struct timeval *)0)) < 1) {
988 if (c == -1) {
989 if (errno == EINTR) {
990 continue;
991 }
992 }
993 sleep(5);
994 continue;
995 }
996
997 /*
998 * Any urgent data?
999 */
1000 if (FD_ISSET(net, &xbits)) {
1001 SYNCHing = 1;
1002 }
1003
1004 /*
1005 * Something to read from the network...
1006 */
1007 if (FD_ISSET(net, &ibits)) {
1008 #if !defined(SO_OOBINLINE)
1009 /*
1010 * In 4.2 (and 4.3 beta) systems, the
1011 * OOB indication and data handling in the kernel
1012 * is such that if two separate TCP Urgent requests
1013 * come in, one byte of TCP data will be overlaid.
1014 * This is fatal for Telnet, but we try to live
1015 * with it.
1016 *
1017 * In addition, in 4.2 (and...), a special protocol
1018 * is needed to pick up the TCP Urgent data in
1019 * the correct sequence.
1020 *
1021 * What we do is: if we think we are in urgent
1022 * mode, we look to see if we are "at the mark".
1023 * If we are, we do an OOB receive. If we run
1024 * this twice, we will do the OOB receive twice,
1025 * but the second will fail, since the second
1026 * time we were "at the mark", but there wasn't
1027 * any data there (the kernel doesn't reset
1028 * "at the mark" until we do a normal read).
1029 * Once we've read the OOB data, we go ahead
1030 * and do normal reads.
1031 *
1032 * There is also another problem, which is that
1033 * since the OOB byte we read doesn't put us
1034 * out of OOB state, and since that byte is most
1035 * likely the TELNET DM (data mark), we would
1036 * stay in the TELNET SYNCH (SYNCHing) state.
1037 * So, clocks to the rescue. If we've "just"
1038 * received a DM, then we test for the
1039 * presence of OOB data when the receive OOB
1040 * fails (and AFTER we did the normal mode read
1041 * to clear "at the mark").
1042 */
1043 if (SYNCHing) {
1044 int atmark;
1045
1046 (void) ioctl(net, SIOCATMARK, (char *)&atmark);
1047 if (atmark) {
1048 ncc = recv(net, netibuf, sizeof (netibuf), MSG_OOB);
1049 if ((ncc == -1) && (errno == EINVAL)) {
1050 ncc = read(net, netibuf, sizeof (netibuf));
1051 if (sequenceIs(didnetreceive, gotDM)) {
1052 SYNCHing = stilloob(net);
1053 }
1054 }
1055 } else {
1056 ncc = read(net, netibuf, sizeof (netibuf));
1057 }
1058 } else {
1059 ncc = read(net, netibuf, sizeof (netibuf));
1060 }
1061 settimer(didnetreceive);
1062 #else /* !defined(SO_OOBINLINE)) */
1063 ncc = read(net, netibuf, sizeof (netibuf));
1064 #endif /* !defined(SO_OOBINLINE)) */
1065 if (ncc < 0 && errno == EWOULDBLOCK)
1066 ncc = 0;
1067 else {
1068 if (ncc <= 0) {
1069 break;
1070 }
1071 netip = netibuf;
1072 }
1073 DIAG((TD_REPORT | TD_NETDATA),
1074 output_data("td: netread %d chars\r\n", ncc));
1075 DIAG(TD_NETDATA, printdata("nd", netip, ncc));
1076 }
1077
1078 /*
1079 * Something to read from the pty...
1080 */
1081 if (FD_ISSET(p, &ibits)) {
1082 pcc = read(p, ptyibuf, BUFSIZ);
1083 /*
1084 * On some systems, if we try to read something
1085 * off the master side before the slave side is
1086 * opened, we get EIO.
1087 */
1088 if (pcc < 0 && (errno == EWOULDBLOCK ||
1089 #ifdef EAGAIN
1090 errno == EAGAIN ||
1091 #endif
1092 errno == EIO)) {
1093 pcc = 0;
1094 } else {
1095 if (pcc <= 0)
1096 break;
1097 #ifdef LINEMODE
1098 /*
1099 * If ioctl from pty, pass it through net
1100 */
1101 if (ptyibuf[0] & TIOCPKT_IOCTL) {
1102 copy_termbuf(ptyibuf+1, pcc-1);
1103 localstat();
1104 pcc = 1;
1105 }
1106 #endif /* LINEMODE */
1107 #if (!defined(__BEOS__) && !defined(__HAIKU__))
1108 if (ptyibuf[0] & TIOCPKT_FLUSHWRITE) {
1109 netclear(); /* clear buffer back */
1110 #ifndef NO_URGENT
1111 /*
1112 * There are client telnets on some
1113 * operating systems get screwed up
1114 * royally if we send them urgent
1115 * mode data.
1116 */
1117 output_data("%c%c", IAC, DM);
1118 neturg = nfrontp-1; /* off by one XXX */
1119 DIAG(TD_OPTIONS,
1120 printoption("td: send IAC", DM));
1121
1122 #endif
1123 }
1124 if (his_state_is_will(TELOPT_LFLOW) &&
1125 (ptyibuf[0] &
1126 (TIOCPKT_NOSTOP|TIOCPKT_DOSTOP))) {
1127 int newflow =
1128 ptyibuf[0] & TIOCPKT_DOSTOP ? 1 : 0;
1129 if (newflow != flowmode) {
1130 flowmode = newflow;
1131 output_data("%c%c%c%c%c%c",
1132 IAC, SB, TELOPT_LFLOW,
1133 flowmode ? LFLOW_ON
1134 : LFLOW_OFF,
1135 IAC, SE);
1136 DIAG(TD_OPTIONS, printsub('>',
1137 (unsigned char *)nfrontp-4,
1138 4););
1139 }
1140 }
1141 pcc--;
1142 #endif /* !__BEOS__ */
1143 //ptyip = ptyibuf+1;
1144 ptyip = ptyibuf;
1145 }
1146 }
1147
1148 while (pcc > 0) {
1149 if ((&netobuf[BUFSIZ] - nfrontp) < 2)
1150 break;
1151 c = *ptyip++ & 0377, pcc--;
1152 if (c == IAC)
1153 output_data("%c", c);
1154 output_data("%c", c);
1155 if ((c == '\r') && (my_state_is_wont(TELOPT_BINARY))) {
1156 if (pcc > 0 && ((*ptyip & 0377) == '\n')) {
1157 output_data("%c", *ptyip++ & 0377);
1158 pcc--;
1159 } else
1160 output_data("%c", '\0');
1161 }
1162 }
1163
1164 if (FD_ISSET(f, &obits) && (nfrontp - nbackp) > 0)
1165 netflush();
1166 if (ncc > 0)
1167 telrcv();
1168 if (FD_ISSET(p, &obits) && (pfrontp - pbackp) > 0)
1169 ptyflush();
1170 }
1171 cleanup(0);
1172 } /* end of telnet */
1173
1174 #ifndef TCSIG
1175 # ifdef TIOCSIG
1176 # define TCSIG TIOCSIG
1177 # endif
1178 #endif
1179
1180 /*
1181 * Send interrupt to process on other side of pty.
1182 * If it is in raw mode, just write NULL;
1183 * otherwise, write intr char.
1184 */
1185 void
interrupt(void)1186 interrupt(void)
1187 {
1188 ptyflush(); /* half-hearted */
1189
1190 #ifdef TCSIG
1191 (void) ioctl(pty, TCSIG, SIGINT);
1192 #else /* TCSIG */
1193 init_termbuf();
1194 *pfrontp++ = slctab[SLC_IP].sptr ?
1195 (unsigned char)*slctab[SLC_IP].sptr : '\177';
1196 #endif /* TCSIG */
1197 }
1198
1199 /*
1200 * Send quit to process on other side of pty.
1201 * If it is in raw mode, just write NULL;
1202 * otherwise, write quit char.
1203 */
1204 void
sendbrk(void)1205 sendbrk(void)
1206 {
1207 ptyflush(); /* half-hearted */
1208 #ifdef TCSIG
1209 (void) ioctl(pty, TCSIG, SIGQUIT);
1210 #else /* TCSIG */
1211 init_termbuf();
1212 *pfrontp++ = slctab[SLC_ABORT].sptr ?
1213 (unsigned char)*slctab[SLC_ABORT].sptr : '\034';
1214 #endif /* TCSIG */
1215 }
1216
1217 void
sendsusp(void)1218 sendsusp(void)
1219 {
1220 #ifdef SIGTSTP
1221 ptyflush(); /* half-hearted */
1222 # ifdef TCSIG
1223 (void) ioctl(pty, TCSIG, SIGTSTP);
1224 # else /* TCSIG */
1225 *pfrontp++ = slctab[SLC_SUSP].sptr ?
1226 (unsigned char)*slctab[SLC_SUSP].sptr : '\032';
1227 # endif /* TCSIG */
1228 #endif /* SIGTSTP */
1229 }
1230
1231 /*
1232 * When we get an AYT, if ^T is enabled, use that. Otherwise,
1233 * just send back "[Yes]".
1234 */
1235 void
recv_ayt(void)1236 recv_ayt(void)
1237 {
1238 #if defined(SIGINFO) && defined(TCSIG)
1239 if (slctab[SLC_AYT].sptr && *slctab[SLC_AYT].sptr != _POSIX_VDISABLE) {
1240 (void) ioctl(pty, TCSIG, SIGINFO);
1241 return;
1242 }
1243 #endif
1244 output_data("\r\n[Yes]\r\n");
1245 }
1246
1247 void
doeof(void)1248 doeof(void)
1249 {
1250 init_termbuf();
1251
1252 #if defined(LINEMODE) && defined(USE_TERMIO) && (VEOF == VMIN)
1253 if (!tty_isediting()) {
1254 extern char oldeofc;
1255 *pfrontp++ = oldeofc;
1256 return;
1257 }
1258 #endif
1259 *pfrontp++ = slctab[SLC_EOF].sptr ?
1260 (unsigned char)*slctab[SLC_EOF].sptr : '\004';
1261 }
1262