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