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