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