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