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