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