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