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