Home | History | Annotate | Line # | Download | only in telnet
commands.c revision 1.72
      1 /*	$NetBSD: commands.c,v 1.72 2018/12/14 06:08:18 maya Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 1997 and 1998 WIDE Project.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the project nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1988, 1990, 1993
     34  *	The Regents of the University of California.  All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. Neither the name of the University nor the names of its contributors
     45  *    may be used to endorse or promote products derived from this software
     46  *    without specific prior written permission.
     47  *
     48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     58  * SUCH DAMAGE.
     59  */
     60 
     61 #include <sys/cdefs.h>
     62 #ifndef lint
     63 #if 0
     64 static char sccsid[] = "@(#)commands.c	8.4 (Berkeley) 5/30/95";
     65 #else
     66 __RCSID("$NetBSD: commands.c,v 1.72 2018/12/14 06:08:18 maya Exp $");
     67 #endif
     68 #endif /* not lint */
     69 
     70 #include <sys/param.h>
     71 #include <sys/file.h>
     72 #include <sys/wait.h>
     73 #include <sys/socket.h>
     74 #include <netinet/in.h>
     75 #include <arpa/inet.h>
     76 
     77 #include <ctype.h>
     78 #include <errno.h>
     79 #include <netdb.h>
     80 #include <pwd.h>
     81 #include <signal.h>
     82 #include <stdarg.h>
     83 #include <unistd.h>
     84 
     85 #include <arpa/telnet.h>
     86 
     87 #include "general.h"
     88 #include "ring.h"
     89 #include "externs.h"
     90 #include "defines.h"
     91 #include "types.h"
     92 #include <libtelnet/misc.h>
     93 #ifdef AUTHENTICATION
     94 #include <libtelnet/auth.h>
     95 #endif
     96 #ifdef ENCRYPTION
     97 #include <libtelnet/encrypt.h>
     98 #endif
     99 
    100 #include <netinet/in_systm.h>
    101 #include <netinet/ip.h>
    102 
    103 
    104 #if	defined(IPPROTO_IP) && defined(IP_TOS)
    105 int tos = -1;
    106 #endif	/* defined(IPPROTO_IP) && defined(IP_TOS) */
    107 
    108 char	*hostname;
    109 static char _hostname[MAXHOSTNAMELEN];
    110 
    111 typedef struct {
    112 	const char	*name;	/* command name */
    113 	const char	*help;	/* help string (NULL for no help) */
    114 	int	(*handler)	/* routine which executes command */
    115 			(int, char *[]);
    116 	int	needconnect;	/* Do we need to be connected to execute? */
    117 } Command;
    118 
    119 static char line[256];
    120 static char saveline[256];
    121 static int margc;
    122 static char *margv[20];
    123 
    124 static void makeargv(void);
    125 static int special(char *);
    126 static const char *control(cc_t);
    127 static int sendcmd(int, char **);
    128 static int send_esc(char *);
    129 static int send_docmd(char *);
    130 static int send_dontcmd(char *);
    131 static int send_willcmd(char *);
    132 static int send_wontcmd(char *);
    133 static int send_help(char *);
    134 static int lclchars(int);
    135 static int togdebug(int);
    136 static int togcrlf(int);
    137 static int togbinary(int);
    138 static int togrbinary(int);
    139 static int togxbinary(int);
    140 static int togglehelp(int);
    141 static void settogglehelp(int);
    142 static int toggle(int, char *[]);
    143 static struct setlist *getset(char *);
    144 static int setcmd(int, char *[]);
    145 static int unsetcmd(int, char *[]);
    146 static int dokludgemode(int);
    147 static int dolinemode(int);
    148 static int docharmode(int);
    149 static int dolmmode(int, int );
    150 static int modecmd(int, char *[]);
    151 static int display(int, char *[]);
    152 static int setescape(int, char *[]);
    153 static int togcrmod(int, char *[]);
    154 static int bye(int, char *[]);
    155 static void slc_help(int);
    156 static struct slclist *getslc(char *);
    157 static int slccmd(int, char *[]);
    158 static struct env_lst *env_help(const unsigned char *, unsigned char *);
    159 static struct envlist *getenvcmd(char *);
    160 #ifdef AUTHENTICATION
    161 static int auth_help(char *);
    162 #endif
    163 static int status(int, char *[]);
    164 static const char *sockaddr_ntop (struct sockaddr *);
    165 typedef int (*intrtn_t)(int, char **);
    166 static int call(intrtn_t, ...);
    167 static Command *getcmd(char *);
    168 static int help(int, char *[]);
    169 
    170 static void
    171 makeargv(void)
    172 {
    173     char *cp, *cp2, c;
    174     char **argp = margv;
    175     static char bang[] = "!";
    176 
    177     margc = 0;
    178     cp = line;
    179     if (*cp == '!') {		/* Special case shell escape */
    180 	strlcpy(saveline, line, sizeof(saveline)); /* save for shell command */
    181 	*argp++ = bang;		/* No room in string to get this */
    182 	margc++;
    183 	cp++;
    184     }
    185     while ((c = *cp) != '\0') {
    186 	int inquote = 0;
    187 	while (isspace((unsigned char)c))
    188 	    c = *++cp;
    189 	if (c == '\0')
    190 	    break;
    191 	*argp++ = cp;
    192 	margc += 1;
    193 	for (cp2 = cp; c != '\0'; c = *++cp) {
    194 	    if (inquote) {
    195 		if (c == inquote) {
    196 		    inquote = 0;
    197 		    continue;
    198 		}
    199 	    } else {
    200 		if (c == '\\') {
    201 		    if ((c = *++cp) == '\0')
    202 			break;
    203 		} else if (c == '"') {
    204 		    inquote = '"';
    205 		    continue;
    206 		} else if (c == '\'') {
    207 		    inquote = '\'';
    208 		    continue;
    209 		} else if (isspace((unsigned char)c))
    210 		    break;
    211 	    }
    212 	    *cp2++ = c;
    213 	}
    214 	*cp2 = '\0';
    215 	if (c == '\0')
    216 	    break;
    217 	cp++;
    218     }
    219     *argp++ = 0;
    220 }
    221 
    222 /*
    223  * Make a character string into a number.
    224  *
    225  * Todo:  1.  Could take random integers (12, 0x12, 012, 0b1).
    226  */
    227 
    228 static int
    229 special(char *s)
    230 {
    231 	char c;
    232 	char b;
    233 
    234 	switch (*s) {
    235 	case '^':
    236 		b = *++s;
    237 		if (b == '?') {
    238 		    c = b | 0x40;		/* DEL */
    239 		} else {
    240 		    c = b & 0x1f;
    241 		}
    242 		break;
    243 	default:
    244 		c = *s;
    245 		break;
    246 	}
    247 	return c;
    248 }
    249 
    250 /*
    251  * Construct a control character sequence
    252  * for a special character.
    253  */
    254 static const char *
    255 control(cc_t c)
    256 {
    257 	static char buf[5];
    258 	/*
    259 	 * The only way I could get the Sun 3.5 compiler
    260 	 * to shut up about
    261 	 *	if ((unsigned int)c >= 0x80)
    262 	 * was to assign "c" to an unsigned int variable...
    263 	 * Arggg....
    264 	 */
    265 	unsigned int uic = (unsigned int)c;
    266 
    267 	if (uic == 0x7f)
    268 		return ("^?");
    269 	if (c == (cc_t)_POSIX_VDISABLE) {
    270 		return "off";
    271 	}
    272 	if (uic >= 0x80) {
    273 		buf[0] = '\\';
    274 		buf[1] = ((c>>6)&07) + '0';
    275 		buf[2] = ((c>>3)&07) + '0';
    276 		buf[3] = (c&07) + '0';
    277 		buf[4] = 0;
    278 	} else if (uic >= 0x20) {
    279 		buf[0] = c;
    280 		buf[1] = 0;
    281 	} else {
    282 		buf[0] = '^';
    283 		buf[1] = '@'+c;
    284 		buf[2] = 0;
    285 	}
    286 	return (buf);
    287 }
    288 
    289 
    290 
    291 /*
    292  *	The following are data structures and routines for
    293  *	the "send" command.
    294  *
    295  */
    296 
    297 struct sendlist {
    298     const char	*name;		/* How user refers to it (case independent) */
    299     const char	*help;		/* Help information (0 ==> no help) */
    300     int		needconnect;	/* Need to be connected */
    301     int		narg;		/* Number of arguments */
    302     int		(*handler)	/* Routine to perform (for special ops) */
    303 			(char *);
    304     int		nbyte;		/* Number of bytes to send this command */
    305     int		what;		/* Character to be sent (<0 ==> special) */
    306 };
    307 
    308 
    310 static struct sendlist Sendlist[] = {
    311     { "ao",	"Send Telnet Abort output",		1, 0, 0, 2, AO },
    312     { "ayt",	"Send Telnet 'Are You There'",		1, 0, 0, 2, AYT },
    313     { "brk",	"Send Telnet Break",			1, 0, 0, 2, BREAK },
    314     { "break",	0,					1, 0, 0, 2, BREAK },
    315     { "ec",	"Send Telnet Erase Character",		1, 0, 0, 2, EC },
    316     { "el",	"Send Telnet Erase Line",		1, 0, 0, 2, EL },
    317     { "escape",	"Send current escape character",	1, 0, send_esc, 1, 0 },
    318     { "ga",	"Send Telnet 'Go Ahead' sequence",	1, 0, 0, 2, GA },
    319     { "ip",	"Send Telnet Interrupt Process",	1, 0, 0, 2, IP },
    320     { "intp",	0,					1, 0, 0, 2, IP },
    321     { "interrupt", 0,					1, 0, 0, 2, IP },
    322     { "intr",	0,					1, 0, 0, 2, IP },
    323     { "nop",	"Send Telnet 'No operation'",		1, 0, 0, 2, NOP },
    324     { "eor",	"Send Telnet 'End of Record'",		1, 0, 0, 2, EOR },
    325     { "abort",	"Send Telnet 'Abort Process'",		1, 0, 0, 2, ABORT },
    326     { "susp",	"Send Telnet 'Suspend Process'",	1, 0, 0, 2, SUSP },
    327     { "eof",	"Send Telnet End of File Character",	1, 0, 0, 2, xEOF },
    328     { "synch",	"Perform Telnet 'Synch operation'",	1, 0, dosynch, 2, 0 },
    329     { "getstatus", "Send request for STATUS",		1, 0, get_status, 6, 0 },
    330     { "?",	"Display send options",			0, 0, send_help, 0, 0 },
    331     { "help",	0,					0, 0, send_help, 0, 0 },
    332     { "do",	0,					0, 1, send_docmd, 3, 0 },
    333     { "dont",	0,					0, 1, send_dontcmd, 3, 0 },
    334     { "will",	0,					0, 1, send_willcmd, 3, 0 },
    335     { "wont",	0,					0, 1, send_wontcmd, 3, 0 },
    336     { .name = 0 }
    337 };
    338 
    339 #define	GETSEND(name) ((struct sendlist *) genget(name, (char **) Sendlist, \
    340 				sizeof(struct sendlist)))
    341 
    342 static int
    343 sendcmd(int  argc, char **argv)
    344 {
    345     int count;		/* how many bytes we are going to need to send */
    346     int i;
    347     struct sendlist *s;	/* pointer to current command */
    348     int success = 0;
    349     int needconnect = 0;
    350 
    351     if (argc < 2) {
    352 	printf("need at least one argument for 'send' command\n");
    353 	printf("'send ?' for help\n");
    354 	return 0;
    355     }
    356     /*
    357      * First, validate all the send arguments.
    358      * In addition, we see how much space we are going to need, and
    359      * whether or not we will be doing a "SYNCH" operation (which
    360      * flushes the network queue).
    361      */
    362     count = 0;
    363     for (i = 1; i < argc; i++) {
    364 	s = GETSEND(argv[i]);
    365 	if (s == 0) {
    366 	    printf("Unknown send argument '%s'\n'send ?' for help.\n",
    367 			argv[i]);
    368 	    return 0;
    369 	} else if (Ambiguous(s)) {
    370 	    printf("Ambiguous send argument '%s'\n'send ?' for help.\n",
    371 			argv[i]);
    372 	    return 0;
    373 	}
    374 	if (i + s->narg >= argc) {
    375 	    fprintf(stderr,
    376 	    "Need %d argument%s to 'send %s' command.  'send %s ?' for help.\n",
    377 		s->narg, s->narg == 1 ? "" : "s", s->name, s->name);
    378 	    return 0;
    379 	}
    380 	count += s->nbyte;
    381 	if (s->handler == send_help) {
    382 	    send_help(NULL);
    383 	    return 0;
    384 	}
    385 
    386 	i += s->narg;
    387 	needconnect += s->needconnect;
    388     }
    389     if (!connected && needconnect) {
    390 	printf("?Need to be connected first.\n");
    391 	printf("'send ?' for help\n");
    392 	return 0;
    393     }
    394     /* Now, do we have enough room? */
    395     if (NETROOM() < count) {
    396 	printf("There is not enough room in the buffer TO the network\n");
    397 	printf("to process your request.  Nothing will be done.\n");
    398 	printf("('send synch' will throw away most data in the network\n");
    399 	printf("buffer, if this might help.)\n");
    400 	return 0;
    401     }
    402     /* OK, they are all OK, now go through again and actually send */
    403     count = 0;
    404     for (i = 1; i < argc; i++) {
    405 	if ((s = GETSEND(argv[i])) == 0) {
    406 	    fprintf(stderr, "Telnet 'send' error - argument disappeared!\n");
    407 	    (void) quit(0, NULL);
    408 	    /*NOTREACHED*/
    409 	}
    410 	if (s->handler) {
    411 	    count++;
    412 	    success += (*s->handler)(argv[i+1]);
    413 	    i += s->narg;
    414 	} else {
    415 	    NET2ADD(IAC, s->what);
    416 	    printoption("SENT", IAC, s->what);
    417 	}
    418     }
    419     return (count == success);
    420 }
    421 
    422 static int
    423 send_esc(char *s)
    424 {
    425     NETADD(escape);
    426     return 1;
    427 }
    428 
    429 static int
    430 send_docmd(char *name)
    431 {
    432     return(send_tncmd(send_do, "do", name));
    433 }
    434 
    435 static int
    436 send_dontcmd(char *name)
    437 {
    438     return(send_tncmd(send_dont, "dont", name));
    439 }
    440 static int
    441 send_willcmd(char *name)
    442 {
    443     return(send_tncmd(send_will, "will", name));
    444 }
    445 static int
    446 send_wontcmd(char *name)
    447 {
    448     return(send_tncmd(send_wont, "wont", name));
    449 }
    450 
    451 int
    452 send_tncmd(void	(*func)(int, int), const char	*cmd, char *name)
    453 {
    454     const char **cpp;
    455     int val = 0;
    456 
    457     if (isprefix(name, "?")) {
    458 	int col, len;
    459 
    460 	printf("usage: send %s <value|option>\n", cmd);
    461 	printf("\"value\" must be from 0 to 255\n");
    462 	printf("Valid options are:\n\t");
    463 
    464 	col = 8;
    465 	for (cpp = telopts; *cpp; cpp++) {
    466 	    len = strlen(*cpp) + 3;
    467 	    if (col + len > 65) {
    468 		printf("\n\t");
    469 		col = 8;
    470 	    }
    471 	    printf(" \"%s\"", *cpp);
    472 	    col += len;
    473 	}
    474 	printf("\n");
    475 	return 0;
    476     }
    477     cpp = (void *)genget(name, __UNCONST(telopts), sizeof(char *));
    478     if (Ambiguous(cpp)) {
    479 	fprintf(stderr,"'%s': ambiguous argument ('send %s ?' for help).\n",
    480 					name, cmd);
    481 	return 0;
    482     }
    483     if (cpp) {
    484 	val = cpp - telopts;
    485     } else {
    486 	char *cp = name;
    487 
    488 	while (*cp >= '0' && *cp <= '9') {
    489 	    val *= 10;
    490 	    val += *cp - '0';
    491 	    cp++;
    492 	}
    493 	if (*cp != 0) {
    494 	    fprintf(stderr, "'%s': unknown argument ('send %s ?' for help).\n",
    495 					name, cmd);
    496 	    return 0;
    497 	} else if (val < 0 || val > 255) {
    498 	    fprintf(stderr, "'%s': bad value ('send %s ?' for help).\n",
    499 					name, cmd);
    500 	    return 0;
    501 	}
    502     }
    503     if (!connected) {
    504 	printf("?Need to be connected first.\n");
    505 	return 0;
    506     }
    507     (*func)(val, 1);
    508     return 1;
    509 }
    510 
    511 static int
    512 send_help(char *n)
    513 {
    514     struct sendlist *s;	/* pointer to current command */
    515     for (s = Sendlist; s->name; s++) {
    516 	if (s->help)
    517 	    printf("%-15s %s\n", s->name, s->help);
    518     }
    519     return(0);
    520 }
    521 
    522 /*
    524  * The following are the routines and data structures referred
    525  * to by the arguments to the "toggle" command.
    526  */
    527 
    528 static int
    529 lclchars(int n)
    530 {
    531     donelclchars = 1;
    532     return 1;
    533 }
    534 
    535 static int
    536 togdebug(int n)
    537 {
    538     if (net > 0 &&
    539 	(SetSockOpt(net, SOL_SOCKET, SO_DEBUG, telnet_debug)) < 0) {
    540 	    perror("setsockopt (SO_DEBUG)");
    541     }
    542     return 1;
    543 }
    544 
    545 static int
    546 togcrlf(int n)
    547 {
    548     if (crlf) {
    549 	printf("Will send carriage returns as telnet <CR><LF>.\n");
    550     } else {
    551 	printf("Will send carriage returns as telnet <CR><NUL>.\n");
    552     }
    553     return 1;
    554 }
    555 
    556 int binmode;
    557 
    558 static int
    559 togbinary(int val)
    560 {
    561     donebinarytoggle = 1;
    562 
    563     if (val >= 0) {
    564 	binmode = val;
    565     } else {
    566 	if (my_want_state_is_will(TELOPT_BINARY) &&
    567 				my_want_state_is_do(TELOPT_BINARY)) {
    568 	    binmode = 1;
    569 	} else if (my_want_state_is_wont(TELOPT_BINARY) &&
    570 				my_want_state_is_dont(TELOPT_BINARY)) {
    571 	    binmode = 0;
    572 	}
    573 	val = binmode ? 0 : 1;
    574     }
    575 
    576     if (val == 1) {
    577 	if (my_want_state_is_will(TELOPT_BINARY) &&
    578 					my_want_state_is_do(TELOPT_BINARY)) {
    579 	    printf("Already operating in binary mode with remote host.\n");
    580 	} else {
    581 	    printf("Negotiating binary mode with remote host.\n");
    582 	    tel_enter_binary(3);
    583 	}
    584     } else {
    585 	if (my_want_state_is_wont(TELOPT_BINARY) &&
    586 					my_want_state_is_dont(TELOPT_BINARY)) {
    587 	    printf("Already in network ascii mode with remote host.\n");
    588 	} else {
    589 	    printf("Negotiating network ascii mode with remote host.\n");
    590 	    tel_leave_binary(3);
    591 	}
    592     }
    593     return 1;
    594 }
    595 
    596 static int
    597 togrbinary(int val)
    598 {
    599     donebinarytoggle = 1;
    600 
    601     if (val == -1)
    602 	val = my_want_state_is_do(TELOPT_BINARY) ? 0 : 1;
    603 
    604     if (val == 1) {
    605 	if (my_want_state_is_do(TELOPT_BINARY)) {
    606 	    printf("Already receiving in binary mode.\n");
    607 	} else {
    608 	    printf("Negotiating binary mode on input.\n");
    609 	    tel_enter_binary(1);
    610 	}
    611     } else {
    612 	if (my_want_state_is_dont(TELOPT_BINARY)) {
    613 	    printf("Already receiving in network ascii mode.\n");
    614 	} else {
    615 	    printf("Negotiating network ascii mode on input.\n");
    616 	    tel_leave_binary(1);
    617 	}
    618     }
    619     return 1;
    620 }
    621 
    622 static int
    623 togxbinary(int val)
    624 {
    625     donebinarytoggle = 1;
    626 
    627     if (val == -1)
    628 	val = my_want_state_is_will(TELOPT_BINARY) ? 0 : 1;
    629 
    630     if (val == 1) {
    631 	if (my_want_state_is_will(TELOPT_BINARY)) {
    632 	    printf("Already transmitting in binary mode.\n");
    633 	} else {
    634 	    printf("Negotiating binary mode on output.\n");
    635 	    tel_enter_binary(2);
    636 	}
    637     } else {
    638 	if (my_want_state_is_wont(TELOPT_BINARY)) {
    639 	    printf("Already transmitting in network ascii mode.\n");
    640 	} else {
    641 	    printf("Negotiating network ascii mode on output.\n");
    642 	    tel_leave_binary(2);
    643 	}
    644     }
    645     return 1;
    646 }
    647 
    648 #ifdef	ENCRYPTION
    649 extern int EncryptAutoEnc(int);
    650 extern int EncryptAutoDec(int);
    651 extern int EncryptDebug(int);
    652 extern int EncryptVerbose(int);
    653 #endif	/* ENCRYPTION */
    654 
    655 struct togglelist {
    656     const char	*name;		/* name of toggle */
    657     const char	*help;		/* help message */
    658     int		(*handler)	/* routine to do actual setting */
    659 			(int);
    660     int		*variable;
    661     const char	*actionexplanation;
    662 };
    663 
    664 static struct togglelist Togglelist[] = {
    665     { "autoflush",
    666 	"flushing of output when sending interrupt characters",
    667 	    0,
    668 		&autoflush,
    669 		    "flush output when sending interrupt characters" },
    670     { "autosynch",
    671 	"automatic sending of interrupt characters in urgent mode",
    672 	    0,
    673 		&autosynch,
    674 		    "send interrupt characters in urgent mode" },
    675 #ifdef AUTHENTICATION
    676     { "autologin",
    677 	"automatic sending of login and/or authentication info",
    678 	    0,
    679 		&autologin,
    680 		    "send login name and/or authentication information" },
    681     { "authdebug",
    682 	"Toggle authentication debugging",
    683 	    auth_togdebug,
    684 		0,
    685 		     "print authentication debugging information" },
    686 #endif
    687 #ifdef	ENCRYPTION
    688     { "autoencrypt",
    689       "automatic encryption of data stream",
    690 	    EncryptAutoEnc,
    691 		0,
    692 		     "automatically encrypt output" },
    693     { "autodecrypt",
    694       "automatic decryption of data stream",
    695 	    EncryptAutoDec,
    696 		0,
    697 		     "automatically decrypt input" },
    698     { "verbose_encrypt",
    699       "Toggle verbose encryption output",
    700 	    EncryptVerbose,
    701 		0,
    702 		     "print verbose encryption output" },
    703     { "encdebug",
    704       "Toggle encryption debugging",
    705 	    EncryptDebug,
    706 		0,
    707 		     "print encryption debugging information" },
    708 #endif	/* ENCRYPTION */
    709     { "skiprc",
    710 	"don't read ~/.telnetrc file",
    711 	    0,
    712 		&skiprc,
    713 		    "skip reading of ~/.telnetrc file" },
    714     { "binary",
    715 	"sending and receiving of binary data",
    716 	    togbinary,
    717 		0,
    718 		    0 },
    719     { "inbinary",
    720 	"receiving of binary data",
    721 	    togrbinary,
    722 		0,
    723 		    0 },
    724     { "outbinary",
    725 	"sending of binary data",
    726 	    togxbinary,
    727 		0,
    728 		    0 },
    729     { "crlf",
    730 	"sending carriage returns as telnet <CR><LF>",
    731 	   togcrlf,
    732 		&crlf,
    733 		    0 },
    734     { "crmod",
    735 	"mapping of received carriage returns",
    736 	    0,
    737 		&crmod,
    738 		    "map carriage return on output" },
    739     { "localchars",
    740 	"local recognition of certain control characters",
    741 	    lclchars,
    742 		&localchars,
    743 		    "recognize certain control characters" },
    744     { " ", "", 0, NULL, NULL },		/* empty line */
    745     { "debug",
    746 	"debugging",
    747 	    togdebug,
    748 		&telnet_debug,
    749 		    "turn on socket level debugging" },
    750     { "netdata",
    751 	"printing of hexadecimal network data (debugging)",
    752 	    0,
    753 		&netdata,
    754 		    "print hexadecimal representation of network traffic" },
    755     { "prettydump",
    756 	"output of \"netdata\" to user readable format (debugging)",
    757 	    0,
    758 		&prettydump,
    759 		    "print user readable output for \"netdata\"" },
    760     { "options",
    761 	"viewing of options processing (debugging)",
    762 	    0,
    763 		&showoptions,
    764 		    "show option processing" },
    765     { "termdata",
    766 	"(debugging) toggle printing of hexadecimal terminal data",
    767 	    0,
    768 		&termdata,
    769 		    "print hexadecimal representation of terminal traffic" },
    770     { "?",
    771 	0,
    772 	    togglehelp, NULL, NULL },
    773     { "help",
    774 	0,
    775 	    togglehelp, NULL, NULL },
    776     { .name = 0 }
    777 };
    778 
    779 static int
    780 togglehelp(int n)
    781 {
    782     struct togglelist *c;
    783 
    784     for (c = Togglelist; c->name; c++) {
    785 	if (c->help) {
    786 	    if (*c->help)
    787 		printf("%-15s toggle %s\n", c->name, c->help);
    788 	    else
    789 		printf("\n");
    790 	}
    791     }
    792     printf("\n");
    793     printf("%-15s %s\n", "?", "display help information");
    794     return 0;
    795 }
    796 
    797 static void
    798 settogglehelp(int set)
    799 {
    800     struct togglelist *c;
    801 
    802     for (c = Togglelist; c->name; c++) {
    803 	if (c->help) {
    804 	    if (*c->help)
    805 		printf("%-15s %s %s\n", c->name, set ? "enable" : "disable",
    806 						c->help);
    807 	    else
    808 		printf("\n");
    809 	}
    810     }
    811 }
    812 
    813 #define	GETTOGGLE(name) (struct togglelist *) \
    814 		genget(name, (char **) Togglelist, sizeof(struct togglelist))
    815 
    816 static int
    817 toggle(int  argc, char *argv[])
    818 {
    819     int retval = 1;
    820     char *name;
    821     struct togglelist *c;
    822 
    823     if (argc < 2) {
    824 	fprintf(stderr,
    825 	    "Need an argument to 'toggle' command.  'toggle ?' for help.\n");
    826 	return 0;
    827     }
    828     argc--;
    829     argv++;
    830     while (argc--) {
    831 	name = *argv++;
    832 	c = GETTOGGLE(name);
    833 	if (Ambiguous(c)) {
    834 	    fprintf(stderr, "'%s': ambiguous argument ('toggle ?' for help).\n",
    835 					name);
    836 	    return 0;
    837 	} else if (c == 0) {
    838 	    fprintf(stderr, "'%s': unknown argument ('toggle ?' for help).\n",
    839 					name);
    840 	    return 0;
    841 	} else {
    842 	    if (c->variable) {
    843 		*c->variable = !*c->variable;		/* invert it */
    844 		if (c->actionexplanation) {
    845 		    printf("%s %s.\n", *c->variable? "Will" : "Won't",
    846 							c->actionexplanation);
    847 		}
    848 	    }
    849 	    if (c->handler) {
    850 		retval &= (*c->handler)(-1);
    851 	    }
    852 	}
    853     }
    854     return retval;
    855 }
    856 
    857 /*
    859  * The following perform the "set" command.
    860  */
    861 
    862 struct termios new_tc = { .c_iflag = 0 };
    863 
    864 struct setlist {
    865     const char *name;			/* name */
    866     const char *help;			/* help information */
    867     void (*handler)(char *);
    868     cc_t *charp;			/* where it is located at */
    869 };
    870 
    871 static struct setlist Setlist[] = {
    872 #ifdef	KLUDGELINEMODE
    873     { "echo", 	"character to toggle local echoing on/off", 0, &echoc },
    874 #endif
    875     { "escape",	"character to escape back to telnet command mode", 0, &escape },
    876     { "rlogin", "rlogin escape character", 0, &rlogin },
    877     { "tracefile", "file to write trace information to", SetNetTrace, (cc_t *)NetTraceFile},
    878     { " ", "", NULL, NULL },
    879     { " ", "The following need 'localchars' to be toggled true", 0, 0 },
    880     { "flushoutput", "character to cause an Abort Output", 0, termFlushCharp },
    881     { "interrupt", "character to cause an Interrupt Process", 0, termIntCharp },
    882     { "quit",	"character to cause an Abort process", 0, termQuitCharp },
    883     { "eof",	"character to cause an EOF ", 0, termEofCharp },
    884     { " ", "", NULL, NULL },
    885     { " ", "The following are for local editing in linemode", 0, 0 },
    886     { "erase",	"character to use to erase a character", 0, termEraseCharp },
    887     { "kill",	"character to use to erase a line", 0, termKillCharp },
    888     { "lnext",	"character to use for literal next", 0, termLiteralNextCharp },
    889     { "susp",	"character to cause a Suspend Process", 0, termSuspCharp },
    890     { "reprint", "character to use for line reprint", 0, termRprntCharp },
    891     { "worderase", "character to use to erase a word", 0, termWerasCharp },
    892     { "start",	"character to use for XON", 0, termStartCharp },
    893     { "stop",	"character to use for XOFF", 0, termStopCharp },
    894     { "forw1",	"alternate end of line character", 0, termForw1Charp },
    895     { "forw2",	"alternate end of line character", 0, termForw2Charp },
    896     { "ayt",	"alternate AYT character", 0, termAytCharp },
    897     { .name = 0 }
    898 };
    899 
    900 static struct setlist *
    901 getset(char *name)
    902 {
    903     return (struct setlist *)
    904 		genget(name, (char **) Setlist, sizeof(struct setlist));
    905 }
    906 
    907 void
    908 set_escape_char(char *s)
    909 {
    910 	if (rlogin != _POSIX_VDISABLE) {
    911 		rlogin = (s && *s) ? special(s) : _POSIX_VDISABLE;
    912 		printf("Telnet rlogin escape character is '%s'.\n",
    913 					control(rlogin));
    914 	} else {
    915 		escape = (s && *s) ? special(s) : _POSIX_VDISABLE;
    916 		printf("Telnet escape character is '%s'.\n", control(escape));
    917 	}
    918 }
    919 
    920 static int
    921 setcmd(int  argc, char *argv[])
    922 {
    923     int value;
    924     struct setlist *ct;
    925     struct togglelist *c;
    926 
    927     if (argc < 2 || argc > 3) {
    928 	printf("Format is 'set Name Value'\n'set ?' for help.\n");
    929 	return 0;
    930     }
    931     if ((argc == 2) && (isprefix(argv[1], "?") || isprefix(argv[1], "help"))) {
    932 	for (ct = Setlist; ct->name; ct++)
    933 	    printf("%-15s %s\n", ct->name, ct->help);
    934 	printf("\n");
    935 	settogglehelp(1);
    936 	printf("%-15s %s\n", "?", "display help information");
    937 	return 0;
    938     }
    939 
    940     ct = getset(argv[1]);
    941     if (ct == 0) {
    942 	c = GETTOGGLE(argv[1]);
    943 	if (c == 0) {
    944 	    fprintf(stderr, "'%s': unknown argument ('set ?' for help).\n",
    945 			argv[1]);
    946 	    return 0;
    947 	} else if (Ambiguous(c)) {
    948 	    fprintf(stderr, "'%s': ambiguous argument ('set ?' for help).\n",
    949 			argv[1]);
    950 	    return 0;
    951 	}
    952 	if (c->variable) {
    953 	    if ((argc == 2) || (strcmp("on", argv[2]) == 0))
    954 		*c->variable = 1;
    955 	    else if (strcmp("off", argv[2]) == 0)
    956 		*c->variable = 0;
    957 	    else {
    958 		printf("Format is 'set togglename [on|off]'\n'set ?' for help.\n");
    959 		return 0;
    960 	    }
    961 	    if (c->actionexplanation) {
    962 		printf("%s %s.\n", *c->variable? "Will" : "Won't",
    963 							c->actionexplanation);
    964 	    }
    965 	}
    966 	if (c->handler)
    967 	    (*c->handler)(1);
    968     } else if (argc != 3) {
    969 	printf("Format is 'set Name Value'\n'set ?' for help.\n");
    970 	return 0;
    971     } else if (Ambiguous(ct)) {
    972 	fprintf(stderr, "'%s': ambiguous argument ('set ?' for help).\n",
    973 			argv[1]);
    974 	return 0;
    975     } else if (ct->handler) {
    976 	(*ct->handler)(argv[2]);
    977 	printf("%s set to \"%s\".\n", ct->name, (char *)ct->charp);
    978     } else {
    979 	if (strcmp("off", argv[2])) {
    980 	    value = special(argv[2]);
    981 	} else {
    982 	    value = _POSIX_VDISABLE;
    983 	}
    984 	*(ct->charp) = (cc_t)value;
    985 	printf("%s character is '%s'.\n", ct->name, control(*(ct->charp)));
    986     }
    987     slc_check();
    988     return 1;
    989 }
    990 
    991 static int
    992 unsetcmd(int  argc, char *argv[])
    993 {
    994     struct setlist *ct;
    995     struct togglelist *c;
    996     char *name;
    997 
    998     if (argc < 2) {
    999 	fprintf(stderr,
   1000 	    "Need an argument to 'unset' command.  'unset ?' for help.\n");
   1001 	return 0;
   1002     }
   1003     if (isprefix(argv[1], "?") || isprefix(argv[1], "help")) {
   1004 	for (ct = Setlist; ct->name; ct++)
   1005 	    printf("%-15s %s\n", ct->name, ct->help);
   1006 	printf("\n");
   1007 	settogglehelp(0);
   1008 	printf("%-15s %s\n", "?", "display help information");
   1009 	return 0;
   1010     }
   1011 
   1012     argc--;
   1013     argv++;
   1014     while (argc--) {
   1015 	name = *argv++;
   1016 	ct = getset(name);
   1017 	if (ct == 0) {
   1018 	    c = GETTOGGLE(name);
   1019 	    if (c == 0) {
   1020 		fprintf(stderr, "'%s': unknown argument ('unset ?' for help).\n",
   1021 			name);
   1022 		return 0;
   1023 	    } else if (Ambiguous(c)) {
   1024 		fprintf(stderr, "'%s': ambiguous argument ('unset ?' for help).\n",
   1025 			name);
   1026 		return 0;
   1027 	    }
   1028 	    if (c->variable) {
   1029 		*c->variable = 0;
   1030 		if (c->actionexplanation) {
   1031 		    printf("%s %s.\n", *c->variable? "Will" : "Won't",
   1032 							c->actionexplanation);
   1033 		}
   1034 	    }
   1035 	    if (c->handler)
   1036 		(*c->handler)(0);
   1037 	} else if (Ambiguous(ct)) {
   1038 	    fprintf(stderr, "'%s': ambiguous argument ('unset ?' for help).\n",
   1039 			name);
   1040 	    return 0;
   1041 	} else if (ct->handler) {
   1042 	    (*ct->handler)(0);
   1043 	    printf("%s reset to \"%s\".\n", ct->name, (char *)ct->charp);
   1044 	} else {
   1045 	    *(ct->charp) = _POSIX_VDISABLE;
   1046 	    printf("%s character is '%s'.\n", ct->name, control(*(ct->charp)));
   1047 	}
   1048     }
   1049     return 1;
   1050 }
   1051 
   1052 /*
   1054  * The following are the data structures and routines for the
   1055  * 'mode' command.
   1056  */
   1057 #ifdef	KLUDGELINEMODE
   1058 extern int kludgelinemode;
   1059 
   1060 static int
   1061 dokludgemode(int n)
   1062 {
   1063     kludgelinemode = 1;
   1064     send_wont(TELOPT_LINEMODE, 1);
   1065     send_dont(TELOPT_SGA, 1);
   1066     send_dont(TELOPT_ECHO, 1);
   1067     return 1;
   1068 }
   1069 #endif
   1070 
   1071 static int
   1072 dolinemode(int n)
   1073 {
   1074 #ifdef	KLUDGELINEMODE
   1075     if (kludgelinemode)
   1076 	send_dont(TELOPT_SGA, 1);
   1077 #endif
   1078     send_will(TELOPT_LINEMODE, 1);
   1079     send_dont(TELOPT_ECHO, 1);
   1080     return 1;
   1081 }
   1082 
   1083 static int
   1084 docharmode(int n)
   1085 {
   1086 #ifdef	KLUDGELINEMODE
   1087     if (kludgelinemode)
   1088 	send_do(TELOPT_SGA, 1);
   1089     else
   1090 #endif
   1091     send_wont(TELOPT_LINEMODE, 1);
   1092     send_do(TELOPT_ECHO, 1);
   1093     return 1;
   1094 }
   1095 
   1096 static int
   1097 dolmmode(int bit, int on)
   1098 {
   1099     unsigned char c;
   1100     extern int linemode;
   1101 
   1102     if (my_want_state_is_wont(TELOPT_LINEMODE)) {
   1103 	printf("?Need to have LINEMODE option enabled first.\n");
   1104 	printf("'mode ?' for help.\n");
   1105 	return 0;
   1106     }
   1107 
   1108     if (on)
   1109 	c = (linemode | bit);
   1110     else
   1111 	c = (linemode & ~bit);
   1112     lm_mode(&c, 1, 1);
   1113     return 1;
   1114 }
   1115 
   1116 int
   1117 set_mode(int bit)
   1118 {
   1119     return dolmmode(bit, 1);
   1120 }
   1121 
   1122 int
   1123 clear_mode(int bit)
   1124 {
   1125     return dolmmode(bit, 0);
   1126 }
   1127 
   1128 struct modelist {
   1129 	const char	*name;	/* command name */
   1130 	const char	*help;	/* help string */
   1131 	int	(*handler)	/* routine which executes command */
   1132 			(int);
   1133 	int	needconnect;	/* Do we need to be connected to execute? */
   1134 	int	arg1;
   1135 };
   1136 
   1137 static struct modelist ModeList[] = {
   1138     { "character", "Disable LINEMODE option",	docharmode, 1, 0 },
   1139 #ifdef	KLUDGELINEMODE
   1140     { "",	"(or disable obsolete line-by-line mode)", 0, 0, 0 },
   1141 #endif
   1142     { "line",	"Enable LINEMODE option",	dolinemode, 1, 0 },
   1143 #ifdef	KLUDGELINEMODE
   1144     { "",	"(or enable obsolete line-by-line mode)", 0, 0, 0 },
   1145 #endif
   1146     { "", "", 0, 0, 0 },
   1147     { "",	"These require the LINEMODE option to be enabled", 0, 0, 0 },
   1148     { "isig",	"Enable signal trapping",	set_mode, 1, MODE_TRAPSIG },
   1149     { "+isig",	0,				set_mode, 1, MODE_TRAPSIG },
   1150     { "-isig",	"Disable signal trapping",	clear_mode, 1, MODE_TRAPSIG },
   1151     { "edit",	"Enable character editing",	set_mode, 1, MODE_EDIT },
   1152     { "+edit",	0,				set_mode, 1, MODE_EDIT },
   1153     { "-edit",	"Disable character editing",	clear_mode, 1, MODE_EDIT },
   1154     { "softtabs", "Enable tab expansion",	set_mode, 1, MODE_SOFT_TAB },
   1155     { "+softtabs", 0,				set_mode, 1, MODE_SOFT_TAB },
   1156     { "-softtabs", "Disable character editing",	clear_mode, 1, MODE_SOFT_TAB },
   1157     { "litecho", "Enable literal character echo", set_mode, 1, MODE_LIT_ECHO },
   1158     { "+litecho", 0,				set_mode, 1, MODE_LIT_ECHO },
   1159     { "-litecho", "Disable literal character echo", clear_mode, 1, MODE_LIT_ECHO },
   1160     { "help",	0,				modehelp, 0, 0 },
   1161 #ifdef	KLUDGELINEMODE
   1162     { "kludgeline", 0,				dokludgemode, 1, 0 },
   1163 #endif
   1164     { "", "", 0, 0, 0 },
   1165     { "?",	"Print help information",	modehelp, 0, 0 },
   1166     { .name = 0 },
   1167 };
   1168 
   1169 
   1170 int
   1171 modehelp(int n)
   1172 {
   1173     struct modelist *mt;
   1174 
   1175     printf("format is:  'mode Mode', where 'Mode' is one of:\n\n");
   1176     for (mt = ModeList; mt->name; mt++) {
   1177 	if (mt->help) {
   1178 	    if (*mt->help)
   1179 		printf("%-15s %s\n", mt->name, mt->help);
   1180 	    else
   1181 		printf("\n");
   1182 	}
   1183     }
   1184     return 0;
   1185 }
   1186 
   1187 #define	GETMODECMD(name) (struct modelist *) \
   1188 		genget(name, (char **) ModeList, sizeof(struct modelist))
   1189 
   1190 static int
   1191 modecmd(int  argc, char *argv[])
   1192 {
   1193     struct modelist *mt;
   1194 
   1195     if (argc != 2) {
   1196 	printf("'mode' command requires an argument\n");
   1197 	printf("'mode ?' for help.\n");
   1198     } else if ((mt = GETMODECMD(argv[1])) == 0) {
   1199 	fprintf(stderr, "Unknown mode '%s' ('mode ?' for help).\n", argv[1]);
   1200     } else if (Ambiguous(mt)) {
   1201 	fprintf(stderr, "Ambiguous mode '%s' ('mode ?' for help).\n", argv[1]);
   1202     } else if (mt->needconnect && !connected) {
   1203 	printf("?Need to be connected first.\n");
   1204 	printf("'mode ?' for help.\n");
   1205     } else if (mt->handler) {
   1206 	return (*mt->handler)(mt->arg1);
   1207     }
   1208     return 0;
   1209 }
   1210 
   1211 /*
   1213  * The following data structures and routines implement the
   1214  * "display" command.
   1215  */
   1216 
   1217 static int
   1218 display(int  argc, char *argv[])
   1219 {
   1220     struct togglelist *tl;
   1221     struct setlist *sl;
   1222 
   1223 #define	dotog(tl)	if (tl->variable && tl->actionexplanation) { \
   1224 			    if (*tl->variable) { \
   1225 				printf("will"); \
   1226 			    } else { \
   1227 				printf("won't"); \
   1228 			    } \
   1229 			    printf(" %s.\n", tl->actionexplanation); \
   1230 			}
   1231 
   1232 #define	doset(sl)   if (sl->name && *sl->name != ' ') { \
   1233 			if (sl->handler == 0) \
   1234 			    printf("%-15s [%s]\n", sl->name, control(*sl->charp)); \
   1235 			else \
   1236 			    printf("%-15s \"%s\"\n", sl->name, (char *)sl->charp); \
   1237 		    }
   1238 
   1239     if (argc == 1) {
   1240 	for (tl = Togglelist; tl->name; tl++) {
   1241 	    dotog(tl);
   1242 	}
   1243 	printf("\n");
   1244 	for (sl = Setlist; sl->name; sl++) {
   1245 	    doset(sl);
   1246 	}
   1247     } else {
   1248 	int i;
   1249 
   1250 	for (i = 1; i < argc; i++) {
   1251 	    sl = getset(argv[i]);
   1252 	    tl = GETTOGGLE(argv[i]);
   1253 	    if (Ambiguous(sl) || Ambiguous(tl)) {
   1254 		printf("?Ambiguous argument '%s'.\n", argv[i]);
   1255 		return 0;
   1256 	    } else if (!sl && !tl) {
   1257 		printf("?Unknown argument '%s'.\n", argv[i]);
   1258 		return 0;
   1259 	    } else {
   1260 		if (tl) {
   1261 		    dotog(tl);
   1262 		}
   1263 		if (sl) {
   1264 		    doset(sl);
   1265 		}
   1266 	    }
   1267 	}
   1268     }
   1269 /*@*/optionstatus();
   1270 #ifdef	ENCRYPTION
   1271     EncryptStatus();
   1272 #endif	/* ENCRYPTION */
   1273     return 1;
   1274 #undef	doset
   1275 #undef	dotog
   1276 }
   1277 
   1278 /*
   1280  * The following are the data structures, and many of the routines,
   1281  * relating to command processing.
   1282  */
   1283 
   1284 /*
   1285  * Set the escape character.
   1286  */
   1287 static int
   1288 setescape(int argc, char *argv[])
   1289 {
   1290 	char *arg;
   1291 	char buf[50];
   1292 
   1293 	printf(
   1294 	    "Deprecated usage - please use 'set escape%s%s' in the future.\n",
   1295 				(argc > 2)? " ":"", (argc > 2)? argv[1]: "");
   1296 	if (argc > 2)
   1297 		arg = argv[1];
   1298 	else {
   1299 		printf("new escape character: ");
   1300 		(void) fgets(buf, sizeof(buf), stdin);
   1301 		arg = buf;
   1302 	}
   1303 	if (arg[0] != '\0')
   1304 		escape = arg[0];
   1305 
   1306 	printf("Escape character is '%s'.\n", control(escape));
   1307 	(void) fflush(stdout);
   1308 	return 1;
   1309 }
   1310 
   1311 /*VARARGS*/
   1312 static int
   1313 togcrmod(int argc, char *argv[])
   1314 {
   1315     crmod = !crmod;
   1316     printf("Deprecated usage - please use 'toggle crmod' in the future.\n");
   1317     printf("%s map carriage return on output.\n", crmod ? "Will" : "Won't");
   1318     (void) fflush(stdout);
   1319     return 1;
   1320 }
   1321 
   1322 /*VARARGS*/
   1323 int
   1324 suspend(int argc, char *argv[])
   1325 {
   1326     setcommandmode();
   1327     {
   1328 	long oldrows, oldcols, newrows, newcols, err;
   1329 
   1330 	err = (TerminalWindowSize(&oldrows, &oldcols) == 0) ? 1 : 0;
   1331 	(void) kill(0, SIGTSTP);
   1332 	/*
   1333 	 * If we didn't get the window size before the SUSPEND, but we
   1334 	 * can get them now (?), then send the NAWS to make sure that
   1335 	 * we are set up for the right window size.
   1336 	 */
   1337 	if (TerminalWindowSize(&newrows, &newcols) && connected &&
   1338 	    (err || ((oldrows != newrows) || (oldcols != newcols)))) {
   1339 		sendnaws();
   1340 	}
   1341     }
   1342     /* reget parameters in case they were changed */
   1343     TerminalSaveState();
   1344     setconnmode(0);
   1345     return 1;
   1346 }
   1347 
   1348 /*ARGSUSED*/
   1349 int
   1350 shell(int argc, char *argv[])
   1351 {
   1352     long oldrows, oldcols, newrows, newcols;
   1353     long volatile err;	/* Avoid vfork clobbering */
   1354 
   1355     setcommandmode();
   1356 
   1357     err = (TerminalWindowSize(&oldrows, &oldcols) == 0) ? 1 : 0;
   1358     switch(vfork()) {
   1359     case -1:
   1360 	perror("Fork failed");
   1361 	break;
   1362 
   1363     case 0:
   1364 	{
   1365 	    /*
   1366 	     * Fire up the shell in the child.
   1367 	     */
   1368 	    const char *shellp, *shellname;
   1369 
   1370 	    shellp = getenv("SHELL");
   1371 	    if (shellp == NULL)
   1372 		shellp = "/bin/sh";
   1373 	    if ((shellname = strrchr(shellp, '/')) == 0)
   1374 		shellname = shellp;
   1375 	    else
   1376 		shellname++;
   1377 	    if (argc > 1)
   1378 		execl(shellp, shellname, "-c", &saveline[1], NULL);
   1379 	    else
   1380 		execl(shellp, shellname, NULL);
   1381 	    perror("execl");
   1382 	    _exit(1);
   1383 	}
   1384     default:
   1385 	    (void)wait((int *)0);	/* Wait for the shell to complete */
   1386 
   1387 	    if (TerminalWindowSize(&newrows, &newcols) && connected &&
   1388 		(err || ((oldrows != newrows) || (oldcols != newcols)))) {
   1389 		    sendnaws();
   1390 	    }
   1391 	    break;
   1392     }
   1393     return 1;
   1394 }
   1395 
   1396 /*VARARGS*/
   1397 static int
   1398 bye(int  argc, char *argv[])
   1399 {
   1400     extern int resettermname;
   1401 
   1402     if (connected) {
   1403 	(void) shutdown(net, 2);
   1404 	printf("Connection closed.\n");
   1405 	(void) NetClose(net);
   1406 	connected = 0;
   1407 	resettermname = 1;
   1408 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
   1409 	auth_encrypt_connect(connected);
   1410 #endif	/* defined(AUTHENTICATION) */
   1411 	/* reset options */
   1412 	tninit();
   1413     }
   1414     if ((argc != 2) || (strcmp(argv[1], "fromquit") != 0)) {
   1415 	longjmp(toplevel, 1);
   1416 	/* NOTREACHED */
   1417     }
   1418     return 1;			/* Keep lint, etc., happy */
   1419 }
   1420 
   1421 /*VARARGS*/
   1422 int
   1423 quit(int argc, char *argv[])
   1424 {
   1425 	(void) call(bye, "bye", "fromquit", 0);
   1426 	Exit(0);
   1427 	/*NOTREACHED*/
   1428 }
   1429 
   1430 /*VARARGS*/
   1431 int
   1432 logout(int argc, char *argv[])
   1433 {
   1434 	send_do(TELOPT_LOGOUT, 1);
   1435 	(void) netflush();
   1436 	return 1;
   1437 }
   1438 
   1439 
   1440 /*
   1442  * The SLC command.
   1443  */
   1444 
   1445 struct slclist {
   1446 	const char	*name;
   1447 	const char	*help;
   1448 	void	(*handler)(int);
   1449 	int	arg;
   1450 };
   1451 
   1452 struct slclist SlcList[] = {
   1453     { "export",	"Use local special character definitions",
   1454 						slc_mode_export,	0 },
   1455     { "import",	"Use remote special character definitions",
   1456 						slc_mode_import,	1 },
   1457     { "check",	"Verify remote special character definitions",
   1458 						slc_mode_import,	0 },
   1459     { "help",	0,				slc_help,		0 },
   1460     { "?",	"Print help information",	slc_help,		0 },
   1461     { .name = 0 },
   1462 };
   1463 
   1464 static void
   1465 slc_help(int n)
   1466 {
   1467     struct slclist *c;
   1468 
   1469     for (c = SlcList; c->name; c++) {
   1470 	if (c->help) {
   1471 	    if (*c->help)
   1472 		printf("%-15s %s\n", c->name, c->help);
   1473 	    else
   1474 		printf("\n");
   1475 	}
   1476     }
   1477 }
   1478 
   1479 static struct slclist *
   1480 getslc(char *name)
   1481 {
   1482     return (struct slclist *)
   1483 		genget(name, (char **) SlcList, sizeof(struct slclist));
   1484 }
   1485 
   1486 static int
   1487 slccmd(int  argc, char *argv[])
   1488 {
   1489     struct slclist *c;
   1490 
   1491     if (argc != 2) {
   1492 	fprintf(stderr,
   1493 	    "Need an argument to 'slc' command.  'slc ?' for help.\n");
   1494 	return 0;
   1495     }
   1496     c = getslc(argv[1]);
   1497     if (c == 0) {
   1498 	fprintf(stderr, "'%s': unknown argument ('slc ?' for help).\n",
   1499     				argv[1]);
   1500 	return 0;
   1501     }
   1502     if (Ambiguous(c)) {
   1503 	fprintf(stderr, "'%s': ambiguous argument ('slc ?' for help).\n",
   1504     				argv[1]);
   1505 	return 0;
   1506     }
   1507     (*c->handler)(c->arg);
   1508     slcstate();
   1509     return 1;
   1510 }
   1511 
   1512 /*
   1514  * The ENVIRON command.
   1515  */
   1516 
   1517 struct envlist {
   1518 	const char	*name;
   1519 	const char	*help;
   1520 	struct env_lst *(*handler)(const unsigned char *, unsigned char *);
   1521 	int	narg;
   1522 };
   1523 
   1524 struct envlist EnvList[] = {
   1525     { "define",	"Define an environment variable",
   1526 						env_define,	2 },
   1527     { "undefine", "Undefine an environment variable",
   1528 						env_undefine,	1 },
   1529     { "export",	"Mark an environment variable for automatic export",
   1530 						env_export,	1 },
   1531     { "unexport", "Don't mark an environment variable for automatic export",
   1532 						env_unexport,	1 },
   1533     { "send",	"Send an environment variable", env_send,	1 },
   1534     { "list",	"List the current environment variables",
   1535 						env_list,	0 },
   1536 #if defined(OLD_ENVIRON) && defined(ENV_HACK)
   1537     { "varval", "Reverse VAR and VALUE (auto, right, wrong, status)",
   1538 						env_varval,    1 },
   1539 #endif
   1540     { "help",	0,				env_help,		0 },
   1541     { "?",	"Print help information",	env_help,		0 },
   1542     { .name = 0 },
   1543 };
   1544 
   1545 static struct env_lst *
   1546 env_help(const unsigned char *us1, unsigned char *us2)
   1547 {
   1548     struct envlist *c;
   1549 
   1550     for (c = EnvList; c->name; c++) {
   1551 	if (c->help) {
   1552 	    if (*c->help)
   1553 		printf("%-15s %s\n", c->name, c->help);
   1554 	    else
   1555 		printf("\n");
   1556 	}
   1557     }
   1558     return NULL;
   1559 }
   1560 
   1561 static struct envlist *
   1562 getenvcmd(char *name)
   1563 {
   1564     return (struct envlist *)
   1565 		genget(name, (char **) EnvList, sizeof(struct envlist));
   1566 }
   1567 
   1568 int
   1569 env_cmd(int  argc, char *argv[])
   1570 {
   1571     struct envlist *c;
   1572 
   1573     if (argc < 2) {
   1574 	fprintf(stderr,
   1575 	    "Need an argument to 'environ' command.  'environ ?' for help.\n");
   1576 	return 0;
   1577     }
   1578     c = getenvcmd(argv[1]);
   1579     if (c == 0) {
   1580 	fprintf(stderr, "'%s': unknown argument ('environ ?' for help).\n",
   1581     				argv[1]);
   1582 	return 0;
   1583     }
   1584     if (Ambiguous(c)) {
   1585 	fprintf(stderr, "'%s': ambiguous argument ('environ ?' for help).\n",
   1586     				argv[1]);
   1587 	return 0;
   1588     }
   1589     if (c->narg + 2 != argc) {
   1590 	fprintf(stderr,
   1591 	    "Need %s%d argument%s to 'environ %s' command.  'environ ?' for help.\n",
   1592 		c->narg < argc + 2 ? "only " : "",
   1593 		c->narg, c->narg == 1 ? "" : "s", c->name);
   1594 	return 0;
   1595     }
   1596     (*c->handler)(argv[2], argv[3]);
   1597     return 1;
   1598 }
   1599 
   1600 struct env_lst {
   1601 	struct env_lst *next;	/* pointer to next structure */
   1602 	struct env_lst *prev;	/* pointer to previous structure */
   1603 	unsigned char *var;	/* pointer to variable name */
   1604 	unsigned char *value;	/* pointer to variable value */
   1605 	int export;		/* 1 -> export with default list of variables */
   1606 	int welldefined;	/* A well defined variable */
   1607 };
   1608 
   1609 struct env_lst envlisthead;
   1610 
   1611 struct env_lst *
   1612 env_find(const unsigned char *var)
   1613 {
   1614 	struct env_lst *ep;
   1615 
   1616 	for (ep = envlisthead.next; ep; ep = ep->next) {
   1617 		if (strcmp((const char *)ep->var, (const char *)var) == 0)
   1618 			return(ep);
   1619 	}
   1620 	return(NULL);
   1621 }
   1622 
   1623 void
   1624 env_init(void)
   1625 {
   1626 	extern char **environ;
   1627 	char **epp, *cp;
   1628 	struct env_lst *ep;
   1629 
   1630 	for (epp = environ; *epp; epp++) {
   1631 		if ((cp = strchr(*epp, '=')) != NULL) {
   1632 			*cp = '\0';
   1633 			ep = env_define((unsigned char *)*epp,
   1634 					(unsigned char *)cp+1);
   1635 			ep->export = 0;
   1636 			*cp = '=';
   1637 		}
   1638 	}
   1639 	/*
   1640 	 * Special case for DISPLAY variable.  If it is ":0.0" or
   1641 	 * "unix:0.0", we have to get rid of "unix" and insert our
   1642 	 * hostname.
   1643 	 */
   1644 	if ((ep = env_find("DISPLAY"))
   1645 	    && ((*ep->value == ':')
   1646 		|| (strncmp((char *)ep->value, "unix:", 5) == 0))) {
   1647 		char hbuf[MAXHOSTNAMELEN + 1];
   1648 		char *cp2 = strchr((char *)ep->value, ':');
   1649 
   1650 		gethostname(hbuf, sizeof hbuf);
   1651 		hbuf[sizeof(hbuf) - 1] = '\0';
   1652 		cp = (char *)malloc(strlen(hbuf) + strlen(cp2) + 1);
   1653 		sprintf((char *)cp, "%s%s", hbuf, cp2);
   1654 		free(ep->value);
   1655 		ep->value = (unsigned char *)cp;
   1656 	}
   1657 	/*
   1658 	 * If USER is not defined, but LOGNAME is, then add
   1659 	 * USER with the value from LOGNAME.  By default, we
   1660 	 * don't export the USER variable.
   1661 	 */
   1662 	if ((env_find("USER") == NULL) && (ep = env_find("LOGNAME"))) {
   1663 		env_define((const unsigned char *)"USER", ep->value);
   1664 		env_unexport((const unsigned char *)"USER", NULL);
   1665 	}
   1666 	env_export((const unsigned char *)"DISPLAY", NULL);
   1667 	env_export((const unsigned char *)"PRINTER", NULL);
   1668 }
   1669 
   1670 struct env_lst *
   1671 env_define(const unsigned char *var, unsigned char *value)
   1672 {
   1673 	struct env_lst *ep;
   1674 
   1675 	if ((ep = env_find(var)) != NULL) {
   1676 		if (ep->var)
   1677 			free(ep->var);
   1678 		if (ep->value)
   1679 			free(ep->value);
   1680 	} else {
   1681 		ep = (struct env_lst *)malloc(sizeof(struct env_lst));
   1682 		ep->next = envlisthead.next;
   1683 		envlisthead.next = ep;
   1684 		ep->prev = &envlisthead;
   1685 		if (ep->next)
   1686 			ep->next->prev = ep;
   1687 	}
   1688 	ep->welldefined = opt_welldefined(var);
   1689 	ep->export = 1;
   1690 	ep->var = (unsigned char *)strdup((const char *)var);
   1691 	ep->value = (unsigned char *)strdup((const char *)value);
   1692 	return(ep);
   1693 }
   1694 
   1695 struct env_lst *
   1696 env_undefine(const unsigned char *var, unsigned char *d)
   1697 {
   1698 	struct env_lst *ep;
   1699 
   1700 	if ((ep = env_find(var)) != NULL) {
   1701 		ep->prev->next = ep->next;
   1702 		if (ep->next)
   1703 			ep->next->prev = ep->prev;
   1704 		if (ep->var)
   1705 			free(ep->var);
   1706 		if (ep->value)
   1707 			free(ep->value);
   1708 		free(ep);
   1709 	}
   1710 	return NULL;
   1711 }
   1712 
   1713 struct env_lst *
   1714 env_export(const unsigned char *var, unsigned char *d)
   1715 {
   1716 	struct env_lst *ep;
   1717 
   1718 	if ((ep = env_find(var)) != NULL)
   1719 		ep->export = 1;
   1720 	return NULL;
   1721 }
   1722 
   1723 struct env_lst *
   1724 env_unexport(const unsigned char *var, unsigned char *d)
   1725 {
   1726 	struct env_lst *ep;
   1727 
   1728 	if ((ep = env_find(var)) != NULL)
   1729 		ep->export = 0;
   1730 	return NULL;
   1731 }
   1732 
   1733 struct env_lst *
   1734 env_send(const unsigned char *var, unsigned char *d)
   1735 {
   1736 	struct env_lst *ep;
   1737 
   1738 	if (my_state_is_wont(TELOPT_NEW_ENVIRON)
   1739 #ifdef	OLD_ENVIRON
   1740 	    && my_state_is_wont(TELOPT_OLD_ENVIRON)
   1741 #endif
   1742 		) {
   1743 		fprintf(stderr,
   1744 		    "Cannot send '%s': Telnet ENVIRON option not enabled\n",
   1745 									var);
   1746 		return NULL;
   1747 	}
   1748 	ep = env_find(var);
   1749 	if (ep == 0) {
   1750 		fprintf(stderr, "Cannot send '%s': variable not defined\n",
   1751 									var);
   1752 		return NULL;
   1753 	}
   1754 	env_opt_start_info();
   1755 	env_opt_add(ep->var);
   1756 	env_opt_end(0);
   1757 	return NULL;
   1758 }
   1759 
   1760 struct env_lst *
   1761 env_list(const unsigned char *d1, unsigned char *d2)
   1762 {
   1763 	struct env_lst *ep;
   1764 
   1765 	for (ep = envlisthead.next; ep; ep = ep->next) {
   1766 		printf("%c %-20s %s\n", ep->export ? '*' : ' ',
   1767 					ep->var, ep->value);
   1768 	}
   1769 	return NULL;
   1770 }
   1771 
   1772 unsigned char *
   1773 env_default(int init, int welldefined)
   1774 {
   1775 	static struct env_lst *nep = NULL;
   1776 
   1777 	if (init) {
   1778 		nep = &envlisthead;
   1779 		return NULL;
   1780 	}
   1781 	if (nep) {
   1782 		while ((nep = nep->next) != NULL) {
   1783 			if (nep->export && (nep->welldefined == welldefined))
   1784 				return(nep->var);
   1785 		}
   1786 	}
   1787 	return(NULL);
   1788 }
   1789 
   1790 unsigned char *
   1791 env_getvalue(const unsigned char *var)
   1792 {
   1793 	struct env_lst *ep;
   1794 
   1795 	if ((ep = env_find(var)) != NULL)
   1796 		return(ep->value);
   1797 	return(NULL);
   1798 }
   1799 
   1800 #if defined(OLD_ENVIRON) && defined(ENV_HACK)
   1801 void
   1802 env_varval(const unsigned char *what)
   1803 {
   1804 	extern int old_env_var, old_env_value, env_auto;
   1805 	int len = strlen((char *)what);
   1806 
   1807 	if (len == 0)
   1808 		goto unknown;
   1809 
   1810 	if (strncasecmp((char *)what, "status", len) == 0) {
   1811 		if (env_auto)
   1812 			printf("%s%s", "VAR and VALUE are/will be ",
   1813 					"determined automatically\n");
   1814 		if (old_env_var == OLD_ENV_VAR)
   1815 			printf("VAR and VALUE set to correct definitions\n");
   1816 		else
   1817 			printf("VAR and VALUE definitions are reversed\n");
   1818 	} else if (strncasecmp((char *)what, "auto", len) == 0) {
   1819 		env_auto = 1;
   1820 		old_env_var = OLD_ENV_VALUE;
   1821 		old_env_value = OLD_ENV_VAR;
   1822 	} else if (strncasecmp((char *)what, "right", len) == 0) {
   1823 		env_auto = 0;
   1824 		old_env_var = OLD_ENV_VAR;
   1825 		old_env_value = OLD_ENV_VALUE;
   1826 	} else if (strncasecmp((char *)what, "wrong", len) == 0) {
   1827 		env_auto = 0;
   1828 		old_env_var = OLD_ENV_VALUE;
   1829 		old_env_value = OLD_ENV_VAR;
   1830 	} else {
   1831 unknown:
   1832 		printf("Unknown \"varval\" command. (\"auto\", \"right\", \"wrong\", \"status\")\n");
   1833 	}
   1834 }
   1835 #endif
   1836 
   1837 #ifdef AUTHENTICATION
   1838 /*
   1839  * The AUTHENTICATE command.
   1840  */
   1841 
   1842 struct authlist {
   1843 	const char	*name;
   1844 	const char	*help;
   1845 	int	(*handler)(char *);
   1846 	int	narg;
   1847 };
   1848 
   1849 struct authlist AuthList[] = {
   1850     { "status",	"Display current status of authentication information",
   1851 						auth_status,	0 },
   1852     { "disable", "Disable an authentication type ('auth disable ?' for more)",
   1853 						auth_disable,	1 },
   1854     { "enable", "Enable an authentication type ('auth enable ?' for more)",
   1855 						auth_enable,	1 },
   1856     { "help",	0,				auth_help,		0 },
   1857     { "?",	"Print help information",	auth_help,		0 },
   1858     { .name = 0 },
   1859 };
   1860 
   1861 static int
   1862 auth_help(char *s)
   1863 {
   1864     struct authlist *c;
   1865 
   1866     for (c = AuthList; c->name; c++) {
   1867 	if (c->help) {
   1868 	    if (*c->help)
   1869 		printf("%-15s %s\n", c->name, c->help);
   1870 	    else
   1871 		printf("\n");
   1872 	}
   1873     }
   1874     return 0;
   1875 }
   1876 
   1877 int
   1878 auth_cmd(int  argc, char *argv[])
   1879 {
   1880     struct authlist *c;
   1881 
   1882     if (argc < 2) {
   1883 	fprintf(stderr,
   1884 	    "Need an argument to 'auth' command.  'auth ?' for help.\n");
   1885 	return 0;
   1886     }
   1887 
   1888     c = (struct authlist *)
   1889 		genget(argv[1], (char **) AuthList, sizeof(struct authlist));
   1890     if (c == 0) {
   1891 	fprintf(stderr, "'%s': unknown argument ('auth ?' for help).\n",
   1892     				argv[1]);
   1893 	return 0;
   1894     }
   1895     if (Ambiguous(c)) {
   1896 	fprintf(stderr, "'%s': ambiguous argument ('auth ?' for help).\n",
   1897     				argv[1]);
   1898 	return 0;
   1899     }
   1900     if (c->narg + 2 != argc) {
   1901 	fprintf(stderr,
   1902 	    "Need %s%d argument%s to 'auth %s' command.  'auth ?' for help.\n",
   1903 		c->narg < argc + 2 ? "only " : "",
   1904 		c->narg, c->narg == 1 ? "" : "s", c->name);
   1905 	return 0;
   1906     }
   1907     return((*c->handler)(argv[2]));
   1908 }
   1909 #endif
   1910 
   1911 #ifdef	ENCRYPTION
   1912 /*
   1913  * The ENCRYPT command.
   1914  */
   1915 
   1916 struct encryptlist {
   1917 	const char	*name;
   1918 	const char	*help;
   1919 	int	(*handler)(char *, char *);
   1920 	int	needconnect;
   1921 	int	minarg;
   1922 	int	maxarg;
   1923 };
   1924 
   1925 static int
   1926 	EncryptHelp(char *, char *);
   1927 typedef int (*encrypthandler)(char *, char *);
   1928 
   1929 struct encryptlist EncryptList[] = {
   1930     { "enable", "Enable encryption. ('encrypt enable ?' for more)",
   1931 						EncryptEnable, 1, 1, 2 },
   1932     { "disable", "Disable encryption. ('encrypt enable ?' for more)",
   1933 						EncryptDisable, 0, 1, 2 },
   1934     { "type", "Set encryption type. ('encrypt type ?' for more)",
   1935 						EncryptType, 0, 1, 1 },
   1936     { "start", "Start encryption. ('encrypt start ?' for more)",
   1937 				(encrypthandler) EncryptStart, 1, 0, 1 },
   1938     { "stop", "Stop encryption. ('encrypt stop ?' for more)",
   1939 				(encrypthandler) EncryptStop, 1, 0, 1 },
   1940     { "input", "Start encrypting the input stream",
   1941 				(encrypthandler) EncryptStartInput, 1, 0, 0 },
   1942     { "-input", "Stop encrypting the input stream",
   1943 				(encrypthandler) EncryptStopInput, 1, 0, 0 },
   1944     { "output", "Start encrypting the output stream",
   1945 				(encrypthandler) EncryptStartOutput, 1, 0, 0 },
   1946     { "-output", "Stop encrypting the output stream",
   1947 				(encrypthandler) EncryptStopOutput, 1, 0, 0 },
   1948 
   1949     { "status",       "Display current status of authentication information",
   1950 				(encrypthandler) EncryptStatus,	0, 0, 0 },
   1951     { "help", 0,				 EncryptHelp,	0, 0, 0 },
   1952     { "?",    "Print help information",		 EncryptHelp,	0, 0, 0 },
   1953     { .name = 0 },
   1954 };
   1955 
   1956 static int
   1957 EncryptHelp(char *s1, char *s2)
   1958 {
   1959 	struct encryptlist *c;
   1960 
   1961 	for (c = EncryptList; c->name; c++) {
   1962 		if (c->help) {
   1963 			if (*c->help)
   1964 				printf("%-15s %s\n", c->name, c->help);
   1965 			else
   1966 				printf("\n");
   1967 		}
   1968 	}
   1969 	return (0);
   1970 }
   1971 
   1972 int
   1973 encrypt_cmd(int argc, char *argv[])
   1974 {
   1975 	struct encryptlist *c;
   1976 
   1977 	if (argc < 2) {
   1978 		fprintf(stderr,
   1979 		    "Need an argument to 'encrypt' command.  "
   1980 		    "'encrypt ?' for help.\n");
   1981 		return (0);
   1982 	}
   1983 
   1984 	c = (struct encryptlist *)
   1985 	    genget(argv[1], (char **) EncryptList, sizeof(struct encryptlist));
   1986 	if (c == NULL) {
   1987 		fprintf(stderr,
   1988 		    "'%s': unknown argument ('encrypt ?' for help).\n",
   1989 		    argv[1]);
   1990 		return (0);
   1991 	}
   1992 	if (Ambiguous(c)) {
   1993 		fprintf(stderr,
   1994 		    "'%s': ambiguous argument ('encrypt ?' for help).\n",
   1995 		    argv[1]);
   1996 		return (0);
   1997 	}
   1998 	argc -= 2;
   1999 	if (argc < c->minarg || argc > c->maxarg) {
   2000 		if (c->minarg == c->maxarg) {
   2001 			fprintf(stderr, "Need %s%d argument%s ",
   2002 			    c->minarg < argc ? "only " : "", c->minarg,
   2003 			    c->minarg == 1 ? "" : "s");
   2004 		} else {
   2005 			fprintf(stderr, "Need %s%d-%d arguments ",
   2006 			    c->maxarg < argc ? "only " : "", c->minarg,
   2007 			    c->maxarg);
   2008 		}
   2009 		fprintf(stderr,
   2010 		    "to 'encrypt %s' command.  'encrypt ?' for help.\n",
   2011 		    c->name);
   2012 		return (0);
   2013 	}
   2014 	if (c->needconnect && !connected) {
   2015 		if (!(argc && (isprefix(argv[2], "help") ||
   2016 		    isprefix(argv[2], "?")))) {
   2017 			printf("?Need to be connected first.\n");
   2018 			return (0);
   2019 		}
   2020 	}
   2021 	return ((*c->handler)(argv[2], argv[3]));
   2022 }
   2023 #endif	/* ENCRYPTION */
   2024 
   2025 
   2026 /*
   2027  * Print status about the connection.
   2028  */
   2029 /*ARGSUSED*/
   2030 static int
   2031 status(int argc, char *argv[])
   2032 {
   2033     if (connected) {
   2034 	printf("Connected to %s.\n", hostname);
   2035 	if ((argc < 2) || strcmp(argv[1], "notmuch")) {
   2036 	    int mode = getconnmode();
   2037 
   2038 	    if (my_want_state_is_will(TELOPT_LINEMODE)) {
   2039 		printf("Operating with LINEMODE option\n");
   2040 		printf("%s line editing\n", (mode&MODE_EDIT) ? "Local" : "No");
   2041 		printf("%s catching of signals\n",
   2042 					(mode&MODE_TRAPSIG) ? "Local" : "No");
   2043 		slcstate();
   2044 #ifdef	KLUDGELINEMODE
   2045 	    } else if (kludgelinemode && my_want_state_is_dont(TELOPT_SGA)) {
   2046 		printf("Operating in obsolete linemode\n");
   2047 #endif
   2048 	    } else {
   2049 		printf("Operating in single character mode\n");
   2050 		if (localchars)
   2051 		    printf("Catching signals locally\n");
   2052 	    }
   2053 	    printf("%s character echo\n", (mode&MODE_ECHO) ? "Local" : "Remote");
   2054 	    if (my_want_state_is_will(TELOPT_LFLOW))
   2055 		printf("%s flow control\n", (mode&MODE_FLOW) ? "Local" : "No");
   2056 #ifdef	ENCRYPTION
   2057 	    encrypt_display();
   2058 #endif	/* ENCRYPTION */
   2059 	}
   2060     } else {
   2061 	printf("No connection.\n");
   2062     }
   2063     printf("Escape character is '%s'.\n", control(escape));
   2064     (void) fflush(stdout);
   2065     return 1;
   2066 }
   2067 
   2068 /*
   2069  * Function that gets called when SIGINFO is received.
   2070  */
   2071 int
   2072 ayt_status(void)
   2073 {
   2074     return call(status, "status", "notmuch", 0);
   2075 }
   2076 
   2077 static const char *
   2078 sockaddr_ntop(struct sockaddr *sa)
   2079 {
   2080     static char addrbuf[NI_MAXHOST];
   2081     const int niflags = NI_NUMERICHOST;
   2082 
   2083     if (getnameinfo(sa, sa->sa_len, addrbuf, sizeof(addrbuf),
   2084 	    NULL, 0, niflags) == 0)
   2085 	return addrbuf;
   2086     else
   2087 	return NULL;
   2088 }
   2089 
   2090 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
   2091 static int setpolicy (int, struct addrinfo *, char *);
   2092 
   2093 static int
   2094 setpolicy(int netw, struct addrinfo *res, char *policy)
   2095 {
   2096 	char *buf;
   2097 	int level;
   2098 	int optname;
   2099 
   2100 	if (policy == NULL)
   2101 		return 0;
   2102 
   2103 	buf = ipsec_set_policy(policy, strlen(policy));
   2104 	if (buf == NULL) {
   2105 		printf("%s\n", ipsec_strerror());
   2106 		return -1;
   2107 	}
   2108 	level = res->ai_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
   2109 	optname = res->ai_family == AF_INET ? IP_IPSEC_POLICY : IPV6_IPSEC_POLICY;
   2110 	if (setsockopt(netw, level, optname, buf, ipsec_get_policylen(buf)) < 0){
   2111 		perror("setsockopt");
   2112 		return -1;
   2113 	}
   2114 
   2115 	free(buf);
   2116 	return 0;
   2117 }
   2118 #endif
   2119 
   2120 int
   2121 tn(int argc, char *argv[])
   2122 {
   2123     struct addrinfo hints, *res, *res0;
   2124     const char *cause = "telnet: unknown";
   2125     int error;
   2126     char *cmd, *hostp = 0;
   2127     const char *portp = 0;
   2128     const char *user = 0;
   2129 
   2130     if (connected) {
   2131 	printf("?Already connected to %s\n", hostname);
   2132 	return 0;
   2133     }
   2134     if (argc < 2) {
   2135 	(void) strlcpy(line, "open ", sizeof(line));
   2136 	printf("(to) ");
   2137 	(void) fgets(&line[strlen(line)], sizeof(line) - strlen(line), stdin);
   2138 	makeargv();
   2139 	argc = margc;
   2140 	argv = margv;
   2141     }
   2142     cmd = *argv;
   2143     --argc; ++argv;
   2144     while (argc) {
   2145 	if (strcmp(*argv, "help") == 0 || isprefix(*argv, "?"))
   2146 	    goto usage;
   2147 	if (strcmp(*argv, "-l") == 0) {
   2148 	    --argc; ++argv;
   2149 	    if (argc == 0)
   2150 		goto usage;
   2151 	    user = *argv++;
   2152 	    --argc;
   2153 	    continue;
   2154 	}
   2155 	if (strcmp(*argv, "-a") == 0) {
   2156 	    --argc; ++argv;
   2157 	    autologin = 1;
   2158 	    continue;
   2159 	}
   2160 	if (hostp == 0) {
   2161 	    hostp = *argv++;
   2162 	    --argc;
   2163 	    continue;
   2164 	}
   2165 	if (portp == 0) {
   2166 	    portp = *argv++;
   2167 	    --argc;
   2168 	    continue;
   2169 	}
   2170     usage:
   2171 	printf("usage: %s [-l user] [-a] host-name [port]\n", cmd);
   2172 	return 0;
   2173     }
   2174     if (hostp == 0)
   2175 	goto usage;
   2176 
   2177     (void) strlcpy(_hostname, hostp, sizeof(_hostname));
   2178     hostname = hostp;
   2179 
   2180     if (!portp) {
   2181 	telnetport = 1;
   2182 	portp = "telnet";
   2183     } else if (portp[0] == '-') {
   2184 	/* use telnet negotiation if port number/name preceded by minus sign */
   2185 	telnetport = 1;
   2186 	portp++;
   2187     } else
   2188 	telnetport = 0;
   2189 
   2190     memset(&hints, 0, sizeof(hints));
   2191     hints.ai_family = family;
   2192     hints.ai_socktype = SOCK_STREAM;
   2193     hints.ai_protocol = 0;
   2194     hints.ai_flags = AI_NUMERICHOST;	/* avoid forward lookup */
   2195     error = getaddrinfo(hostname, portp, &hints, &res0);
   2196     if (!error) {
   2197 	/* numeric */
   2198 	if (doaddrlookup &&
   2199 	    getnameinfo(res0->ai_addr, res0->ai_addrlen,
   2200 		_hostname, sizeof(_hostname), NULL, 0, NI_NAMEREQD) == 0)
   2201 	    ; /* okay */
   2202 	else
   2203 	    strlcpy(_hostname, hostname, sizeof(_hostname));
   2204     } else {
   2205 	/* FQDN - try again with forward DNS lookup */
   2206 	memset(&hints, 0, sizeof(hints));
   2207 	hints.ai_family = family;
   2208 	hints.ai_socktype = SOCK_STREAM;
   2209 	hints.ai_protocol = 0;
   2210 	hints.ai_flags = AI_CANONNAME;
   2211 	error = getaddrinfo(hostname, portp, &hints, &res0);
   2212 	if (error == EAI_SERVICE) {
   2213 	    fprintf(stderr, "tcp/%s: unknown service\n", portp);
   2214 	    return 0;
   2215 	} else if (error) {
   2216 	    fprintf(stderr, "%s: %s\n", hostname, gai_strerror(error));
   2217 	    return 0;
   2218 	}
   2219 	if (res0->ai_canonname)
   2220 	    (void)strlcpy(_hostname, res0->ai_canonname, sizeof(_hostname));
   2221 	else
   2222 	    (void)strlcpy(_hostname, hostname, sizeof(_hostname));
   2223     }
   2224     hostname = _hostname;
   2225 
   2226     net = -1;
   2227     for (res = res0; res; res = res->ai_next) {
   2228 	printf("Trying %s...\n", sockaddr_ntop(res->ai_addr));
   2229 	net = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
   2230 	if (net < 0) {
   2231 	    cause = "telnet: socket";
   2232 	    continue;
   2233 	}
   2234 
   2235 	if (telnet_debug && SetSockOpt(net, SOL_SOCKET, SO_DEBUG, 1) < 0) {
   2236 	    perror("setsockopt (SO_DEBUG)");
   2237 	}
   2238 
   2239 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
   2240 	if (setpolicy(net, res, ipsec_policy_in) < 0) {
   2241 	    (void) NetClose(net);
   2242 	    net = -1;
   2243 	    continue;
   2244 	}
   2245 	if (setpolicy(net, res, ipsec_policy_out) < 0) {
   2246 	    (void) NetClose(net);
   2247 	    net = -1;
   2248 	    continue;
   2249 	}
   2250 #endif
   2251 
   2252 	if (connect(net, res->ai_addr, res->ai_addrlen) < 0) {
   2253 	    if (res->ai_next) {
   2254 		int oerrno = errno;
   2255 
   2256 		fprintf(stderr, "telnet: connect to address %s: ",
   2257 						sockaddr_ntop(res->ai_addr));
   2258 		errno = oerrno;
   2259 		perror((char *)0);
   2260 	    }
   2261 	    cause = "telnet: Unable to connect to remote host";
   2262 	    (void) NetClose(net);
   2263 	    net = -1;
   2264 	    continue;
   2265 	}
   2266 
   2267 	connected++;
   2268 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
   2269 	auth_encrypt_connect(connected);
   2270 #endif	/* defined(AUTHENTICATION) || defined(ENCRYPTION) */
   2271 	break;
   2272     }
   2273     freeaddrinfo(res0);
   2274     if (net < 0 || connected == 0) {
   2275 	perror(cause);
   2276 	return 0;
   2277     }
   2278 
   2279     cmdrc(hostp, hostname);
   2280     if (autologin && user == NULL) {
   2281 	struct passwd *pw;
   2282 
   2283 	user = getenv("USER");
   2284 	if (user == NULL ||
   2285 	    ((pw = getpwnam(user)) && pw->pw_uid != getuid())) {
   2286 		if ((pw = getpwuid(getuid())) != NULL)
   2287 			user = pw->pw_name;
   2288 		else
   2289 			user = NULL;
   2290 	}
   2291     }
   2292     if (user) {
   2293 	env_define((const unsigned char *)"USER", __UNCONST(user));
   2294 	env_export((const unsigned char *)"USER", NULL);
   2295     }
   2296     (void) call(status, "status", "notmuch", 0);
   2297     telnet(user);
   2298     (void) NetClose(net);
   2299     ExitString("Connection closed by foreign host.\n",1);
   2300     /*NOTREACHED*/
   2301 }
   2302 
   2303 #define HELPINDENT ((int)sizeof ("connect"))
   2304 
   2305 static char
   2306 	openhelp[] =	"connect to a site",
   2307 	closehelp[] =	"close current connection",
   2308 	logouthelp[] =	"forcibly logout remote user and close the connection",
   2309 	quithelp[] =	"exit telnet",
   2310 	statushelp[] =	"print status information",
   2311 	helphelp[] =	"print help information",
   2312 	sendhelp[] =	"transmit special characters ('send ?' for more)",
   2313 	sethelp[] = 	"set operating parameters ('set ?' for more)",
   2314 	unsethelp[] = 	"unset operating parameters ('unset ?' for more)",
   2315 	togglestring[] ="toggle operating parameters ('toggle ?' for more)",
   2316 	slchelp[] =	"change state of special characters ('slc ?' for more)",
   2317 	displayhelp[] =	"display operating parameters",
   2318 #ifdef AUTHENTICATION
   2319 	authhelp[] =	"turn on (off) authentication ('auth ?' for more)",
   2320 #endif
   2321 #ifdef	ENCRYPTION
   2322 	encrypthelp[] = "turn on (off) encryption ('encrypt ?' for more)",
   2323 #endif	/* ENCRYPTION */
   2324 	zhelp[] =	"suspend telnet",
   2325 	shellhelp[] =	"invoke a subshell",
   2326 	envhelp[] =	"change environment variables ('environ ?' for more)",
   2327 	modestring[] = "try to enter line or character mode ('mode ?' for more)";
   2328 
   2329 static Command cmdtab[] = {
   2330 	{ "close",	closehelp,	bye,		1 },
   2331 	{ "logout",	logouthelp,	logout,		1 },
   2332 	{ "display",	displayhelp,	display,	0 },
   2333 	{ "mode",	modestring,	modecmd,	0 },
   2334 	{ "open",	openhelp,	tn,		0 },
   2335 	{ "quit",	quithelp,	quit,		0 },
   2336 	{ "send",	sendhelp,	sendcmd,	0 },
   2337 	{ "set",	sethelp,	setcmd,		0 },
   2338 	{ "unset",	unsethelp,	unsetcmd,	0 },
   2339 	{ "status",	statushelp,	status,		0 },
   2340 	{ "toggle",	togglestring,	toggle,		0 },
   2341 	{ "slc",	slchelp,	slccmd,		0 },
   2342 #ifdef AUTHENTICATION
   2343 	{ "auth",	authhelp,	auth_cmd,	0 },
   2344 #endif
   2345 #ifdef	ENCRYPTION
   2346 	{ "encrypt",	encrypthelp,	encrypt_cmd,	0 },
   2347 #endif
   2348 	{ "z",		zhelp,		suspend,	0 },
   2349 	{ "!",		shellhelp,	shell,		0 },
   2350 	{ "environ",	envhelp,	env_cmd,	0 },
   2351 	{ "?",		helphelp,	help,		0 },
   2352 	{ NULL,		NULL,		NULL,		0 }
   2353 };
   2354 
   2355 static char	crmodhelp[] =	"deprecated command -- use 'toggle crmod' instead";
   2356 static char	escapehelp[] =	"deprecated command -- use 'set escape' instead";
   2357 
   2358 static Command cmdtab2[] = {
   2359 	{ "help",	0,		help,		0 },
   2360 	{ "escape",	escapehelp,	setescape,	0 },
   2361 	{ "crmod",	crmodhelp,	togcrmod,	0 },
   2362 	{ NULL,		NULL,		NULL,		0 }
   2363 };
   2364 
   2365 
   2366 /*
   2367  * Call routine with argc, argv set from args (terminated by 0).
   2368  */
   2369 
   2370 /*VARARGS1*/
   2371 static int
   2372 call(intrtn_t routine, ...)
   2373 {
   2374     va_list ap;
   2375     char *args[100];
   2376     int argno = 0;
   2377 
   2378     va_start(ap, routine);
   2379     while ((args[argno++] = va_arg(ap, char *)) != 0) {
   2380 	;
   2381     }
   2382     va_end(ap);
   2383     return (*routine)(argno-1, args);
   2384 }
   2385 
   2386 
   2387 static Command *
   2388 getcmd(char *name)
   2389 {
   2390     Command *cm;
   2391 
   2392     if ((cm = (Command *) genget(name, (char **) cmdtab, sizeof(Command))) != NULL)
   2393 	return cm;
   2394     return (Command *) genget(name, (char **) cmdtab2, sizeof(Command));
   2395 }
   2396 
   2397 void
   2398 command(int top, const char *tbuf, int cnt)
   2399 {
   2400     Command *c;
   2401 
   2402     setcommandmode();
   2403     if (!top) {
   2404 	putchar('\n');
   2405     } else {
   2406 	(void) signal(SIGINT, SIG_DFL);
   2407 	(void) signal(SIGQUIT, SIG_DFL);
   2408     }
   2409     for (;;) {
   2410 	if (rlogin == _POSIX_VDISABLE)
   2411 		printf("%s> ", prompt);
   2412 	if (tbuf) {
   2413 	    char *cp;
   2414 	    cp = line;
   2415 	    while (cnt > 0 && (*cp++ = *tbuf++) != '\n')
   2416 		cnt--;
   2417 	    tbuf = 0;
   2418 	    if (cp == line || *--cp != '\n' || cp == line)
   2419 		goto getline;
   2420 	    *cp = '\0';
   2421 	    if (rlogin == _POSIX_VDISABLE)
   2422 		printf("%s\n", line);
   2423 	} else {
   2424 	getline:
   2425 	    if (rlogin != _POSIX_VDISABLE)
   2426 		printf("%s> ", prompt);
   2427 	    if (fgets(line, sizeof(line), stdin) == NULL) {
   2428 		if (feof(stdin) || ferror(stdin)) {
   2429 		    (void) quit(0, NULL);
   2430 		    /*NOTREACHED*/
   2431 		}
   2432 		break;
   2433 	    }
   2434 	}
   2435 	if (line[0] == 0)
   2436 	    break;
   2437 	makeargv();
   2438 	if (margv[0] == 0) {
   2439 	    break;
   2440 	}
   2441 	c = getcmd(margv[0]);
   2442 	if (Ambiguous(c)) {
   2443 	    printf("?Ambiguous command\n");
   2444 	    continue;
   2445 	}
   2446 	if (c == 0) {
   2447 	    printf("?Invalid command\n");
   2448 	    continue;
   2449 	}
   2450 	if (c->needconnect && !connected) {
   2451 	    printf("?Need to be connected first.\n");
   2452 	    continue;
   2453 	}
   2454 	if ((*c->handler)(margc, margv)) {
   2455 	    break;
   2456 	}
   2457     }
   2458     if (!top) {
   2459 	if (!connected) {
   2460 	    longjmp(toplevel, 1);
   2461 	    /*NOTREACHED*/
   2462 	}
   2463 	setconnmode(0);
   2464     }
   2465 }
   2466 
   2467 /*
   2469  * Help command.
   2470  */
   2471 static int
   2472 help(int argc, char *argv[])
   2473 {
   2474 	Command *c;
   2475 
   2476 	if (argc == 1) {
   2477 		printf("Commands may be abbreviated.  Commands are:\n\n");
   2478 		for (c = cmdtab; c->name; c++)
   2479 			if (c->help) {
   2480 				printf("%-*s\t%s\n", HELPINDENT, c->name,
   2481 								    c->help);
   2482 			}
   2483 		return 0;
   2484 	}
   2485 	while (--argc > 0) {
   2486 		char *arg;
   2487 		arg = *++argv;
   2488 		c = getcmd(arg);
   2489 		if (Ambiguous(c))
   2490 			printf("?Ambiguous help command %s\n", arg);
   2491 		else if (c == (Command *)0)
   2492 			printf("?Invalid help command %s\n", arg);
   2493 		else
   2494 			printf("%s\n", c->help);
   2495 	}
   2496 	return 0;
   2497 }
   2498 
   2499 static char *rcname = 0;
   2500 static char rcbuf[128];
   2501 
   2502 void
   2503 cmdrc(const char *m1, const char *m2)
   2504 {
   2505     Command *c;
   2506     FILE *rcfile;
   2507     int gotmachine = 0;
   2508     int l1 = strlen(m1);
   2509     int l2 = strlen(m2);
   2510     char m1save[MAXHOSTNAMELEN + 1];
   2511 
   2512     if (skiprc)
   2513 	return;
   2514 
   2515     strlcpy(m1save, m1, sizeof(m1save));
   2516     m1 = m1save;
   2517 
   2518     if (rcname == 0) {
   2519 	rcname = getenv("HOME");
   2520 	if (rcname)
   2521 	    strlcpy(rcbuf, rcname, sizeof(rcbuf));
   2522 	else
   2523 	    rcbuf[0] = '\0';
   2524 	strlcat(rcbuf, "/.telnetrc", sizeof(rcbuf));
   2525 	rcname = rcbuf;
   2526     }
   2527 
   2528     if ((rcfile = fopen(rcname, "r")) == 0) {
   2529 	return;
   2530     }
   2531 
   2532     for (;;) {
   2533 	if (fgets(line, sizeof(line), rcfile) == NULL)
   2534 	    break;
   2535 	if (line[0] == 0)
   2536 	    break;
   2537 	if (line[0] == '#')
   2538 	    continue;
   2539 	if (gotmachine) {
   2540 	    if (!isspace((unsigned char)line[0]))
   2541 		gotmachine = 0;
   2542 	}
   2543 	if (gotmachine == 0) {
   2544 	    if (isspace((unsigned char)line[0]))
   2545 		continue;
   2546 	    if (strncasecmp(line, m1, l1) == 0)
   2547 		strncpy(line, &line[l1], sizeof(line) - l1);
   2548 	    else if (strncasecmp(line, m2, l2) == 0)
   2549 		strncpy(line, &line[l2], sizeof(line) - l2);
   2550 	    else if (strncasecmp(line, "DEFAULT", 7) == 0)
   2551 		strncpy(line, &line[7], sizeof(line) - 7);
   2552 	    else
   2553 		continue;
   2554 	    if (line[0] != ' ' && line[0] != '\t' && line[0] != '\n')
   2555 		continue;
   2556 	    gotmachine = 1;
   2557 	}
   2558 	makeargv();
   2559 	if (margv[0] == 0)
   2560 	    continue;
   2561 	c = getcmd(margv[0]);
   2562 	if (Ambiguous(c)) {
   2563 	    printf("?Ambiguous command: %s\n", margv[0]);
   2564 	    continue;
   2565 	}
   2566 	if (c == 0) {
   2567 	    printf("?Invalid command: %s\n", margv[0]);
   2568 	    continue;
   2569 	}
   2570 	/*
   2571 	 * This should never happen...
   2572 	 */
   2573 	if (c->needconnect && !connected) {
   2574 	    printf("?Need to be connected first for %s.\n", margv[0]);
   2575 	    continue;
   2576 	}
   2577 	(*c->handler)(margc, margv);
   2578     }
   2579     fclose(rcfile);
   2580 }
   2581