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