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