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