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