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