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