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