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