Initial import from FreeBSD RELENG_4:
[games.git] / crypto / kerberosIV / appl / telnet / telnet / telnet.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 #ifdef HAVE_TERMCAP_H
36 #include <termcap.h>
37 #endif
38
39 RCSID("$Id: telnet.c,v 1.25 1999/03/11 13:49:34 joda Exp $");
40
41 #define strip(x) (eight ? (x) : ((x) & 0x7f))
42
43 static unsigned char    subbuffer[SUBBUFSIZE],
44                         *subpointer, *subend;    /* buffer for sub-options */
45 #define SB_CLEAR()      subpointer = subbuffer;
46 #define SB_TERM()       { subend = subpointer; SB_CLEAR(); }
47 #define SB_ACCUM(c)     if (subpointer < (subbuffer+sizeof subbuffer)) { \
48                                 *subpointer++ = (c); \
49                         }
50
51 #define SB_GET()        ((*subpointer++)&0xff)
52 #define SB_PEEK()       ((*subpointer)&0xff)
53 #define SB_EOF()        (subpointer >= subend)
54 #define SB_LEN()        (subend - subpointer)
55
56 char    options[256];           /* The combined options */
57 char    do_dont_resp[256];
58 char    will_wont_resp[256];
59
60 int
61         eight = 3,
62         binary = 0,
63         autologin = 0,  /* Autologin anyone? */
64         skiprc = 0,
65         connected,
66         showoptions,
67         ISend,          /* trying to send network data in */
68         debug = 0,
69         crmod,
70         netdata,        /* Print out network data flow */
71         crlf,           /* Should '\r' be mapped to <CR><LF> (or <CR><NUL>)? */
72         telnetport,
73         SYNCHing,       /* we are in TELNET SYNCH mode */
74         flushout,       /* flush output */
75         autoflush = 0,  /* flush output when interrupting? */
76         autosynch,      /* send interrupt characters with SYNCH? */
77         localflow,      /* we handle flow control locally */
78         restartany,     /* if flow control enabled, restart on any character */
79         localchars,     /* we recognize interrupt/quit */
80         donelclchars,   /* the user has set "localchars" */
81         donebinarytoggle,       /* the user has put us in binary */
82         dontlecho,      /* do we suppress local echoing right now? */
83         globalmode;
84
85 char *prompt = 0;
86
87 cc_t escape;
88 cc_t rlogin;
89 #ifdef  KLUDGELINEMODE
90 cc_t echoc;
91 #endif
92
93 /*
94  * Telnet receiver states for fsm
95  */
96 #define TS_DATA         0
97 #define TS_IAC          1
98 #define TS_WILL         2
99 #define TS_WONT         3
100 #define TS_DO           4
101 #define TS_DONT         5
102 #define TS_CR           6
103 #define TS_SB           7               /* sub-option collection */
104 #define TS_SE           8               /* looking for sub-option end */
105
106 static int      telrcv_state;
107 #ifdef  OLD_ENVIRON
108 unsigned char telopt_environ = TELOPT_NEW_ENVIRON;
109 #else
110 # define telopt_environ TELOPT_NEW_ENVIRON
111 #endif
112
113 jmp_buf toplevel;
114 jmp_buf peerdied;
115
116 int     flushline;
117 int     linemode;
118
119 #ifdef  KLUDGELINEMODE
120 int     kludgelinemode = 1;
121 #endif
122
123 /*
124  * The following are some clocks used to decide how to interpret
125  * the relationship between various variables.
126  */
127
128 Clocks clocks;
129
130 static int is_unique(char *name, char **as, char **ae);
131
132
133 /*
134  * Initialize telnet environment.
135  */
136
137 void
138 init_telnet(void)
139 {
140     env_init();
141
142     SB_CLEAR();
143     memset(options, 0, sizeof options);
144
145     connected = ISend = localflow = donebinarytoggle = 0;
146 #if     defined(AUTHENTICATION) || defined(ENCRYPTION)
147     auth_encrypt_connect(connected);
148 #endif  /* defined(AUTHENTICATION) || defined(ENCRYPTION)  */
149     restartany = -1;
150
151     SYNCHing = 0;
152
153     /* Don't change NetTrace */
154
155     escape = CONTROL(']');
156     rlogin = _POSIX_VDISABLE;
157 #ifdef  KLUDGELINEMODE
158     echoc = CONTROL('E');
159 #endif
160
161     flushline = 1;
162     telrcv_state = TS_DATA;
163 }
164
165
166 /*
167  * These routines are in charge of sending option negotiations
168  * to the other side.
169  *
170  * The basic idea is that we send the negotiation if either side
171  * is in disagreement as to what the current state should be.
172  */
173
174 void
175 send_do(int c, int init)
176 {
177     if (init) {
178         if (((do_dont_resp[c] == 0) && my_state_is_do(c)) ||
179                                 my_want_state_is_do(c))
180             return;
181         set_my_want_state_do(c);
182         do_dont_resp[c]++;
183     }
184     NET2ADD(IAC, DO);
185     NETADD(c);
186     printoption("SENT", DO, c);
187 }
188
189 void
190 send_dont(int c, int init)
191 {
192     if (init) {
193         if (((do_dont_resp[c] == 0) && my_state_is_dont(c)) ||
194                                 my_want_state_is_dont(c))
195             return;
196         set_my_want_state_dont(c);
197         do_dont_resp[c]++;
198     }
199     NET2ADD(IAC, DONT);
200     NETADD(c);
201     printoption("SENT", DONT, c);
202 }
203
204 void
205 send_will(int c, int init)
206 {
207     if (init) {
208         if (((will_wont_resp[c] == 0) && my_state_is_will(c)) ||
209                                 my_want_state_is_will(c))
210             return;
211         set_my_want_state_will(c);
212         will_wont_resp[c]++;
213     }
214     NET2ADD(IAC, WILL);
215     NETADD(c);
216     printoption("SENT", WILL, c);
217 }
218
219 void
220 send_wont(int c, int init)
221 {
222     if (init) {
223         if (((will_wont_resp[c] == 0) && my_state_is_wont(c)) ||
224                                 my_want_state_is_wont(c))
225             return;
226         set_my_want_state_wont(c);
227         will_wont_resp[c]++;
228     }
229     NET2ADD(IAC, WONT);
230     NETADD(c);
231     printoption("SENT", WONT, c);
232 }
233
234
235 void
236 willoption(int option)
237 {
238         int new_state_ok = 0;
239
240         if (do_dont_resp[option]) {
241             --do_dont_resp[option];
242             if (do_dont_resp[option] && my_state_is_do(option))
243                 --do_dont_resp[option];
244         }
245
246         if ((do_dont_resp[option] == 0) && my_want_state_is_dont(option)) {
247
248             switch (option) {
249
250             case TELOPT_ECHO:
251             case TELOPT_BINARY:
252             case TELOPT_SGA:
253                 settimer(modenegotiated);
254                 /* FALL THROUGH */
255             case TELOPT_STATUS:
256 #if     defined(AUTHENTICATION)
257             case TELOPT_AUTHENTICATION:
258 #endif
259 #if     defined(ENCRYPTION)
260             case TELOPT_ENCRYPT:
261 #endif
262                 new_state_ok = 1;
263                 break;
264
265             case TELOPT_TM:
266                 if (flushout)
267                     flushout = 0;
268                 /*
269                  * Special case for TM.  If we get back a WILL,
270                  * pretend we got back a WONT.
271                  */
272                 set_my_want_state_dont(option);
273                 set_my_state_dont(option);
274                 return;                 /* Never reply to TM will's/wont's */
275
276             case TELOPT_LINEMODE:
277             default:
278                 break;
279             }
280
281             if (new_state_ok) {
282                 set_my_want_state_do(option);
283                 send_do(option, 0);
284                 setconnmode(0);         /* possibly set new tty mode */
285             } else {
286                 do_dont_resp[option]++;
287                 send_dont(option, 0);
288             }
289         }
290         set_my_state_do(option);
291 #if     defined(ENCRYPTION)
292         if (option == TELOPT_ENCRYPT)
293                 encrypt_send_support();
294 #endif
295 }
296
297 void
298 wontoption(int option)
299 {
300         if (do_dont_resp[option]) {
301             --do_dont_resp[option];
302             if (do_dont_resp[option] && my_state_is_dont(option))
303                 --do_dont_resp[option];
304         }
305
306         if ((do_dont_resp[option] == 0) && my_want_state_is_do(option)) {
307
308             switch (option) {
309
310 #ifdef  KLUDGELINEMODE
311             case TELOPT_SGA:
312                 if (!kludgelinemode)
313                     break;
314                 /* FALL THROUGH */
315 #endif
316             case TELOPT_ECHO:
317                 settimer(modenegotiated);
318                 break;
319
320             case TELOPT_TM:
321                 if (flushout)
322                     flushout = 0;
323                 set_my_want_state_dont(option);
324                 set_my_state_dont(option);
325                 return;         /* Never reply to TM will's/wont's */
326
327 #ifdef ENCRYPTION
328             case TELOPT_ENCRYPT:
329               encrypt_not();
330               break;
331 #endif
332             default:
333                 break;
334             }
335             set_my_want_state_dont(option);
336             if (my_state_is_do(option))
337                 send_dont(option, 0);
338             setconnmode(0);                     /* Set new tty mode */
339         } else if (option == TELOPT_TM) {
340             /*
341              * Special case for TM.
342              */
343             if (flushout)
344                 flushout = 0;
345             set_my_want_state_dont(option);
346         }
347         set_my_state_dont(option);
348 }
349
350 static void
351 dooption(int option)
352 {
353         int new_state_ok = 0;
354
355         if (will_wont_resp[option]) {
356             --will_wont_resp[option];
357             if (will_wont_resp[option] && my_state_is_will(option))
358                 --will_wont_resp[option];
359         }
360
361         if (will_wont_resp[option] == 0) {
362           if (my_want_state_is_wont(option)) {
363
364             switch (option) {
365
366             case TELOPT_TM:
367                 /*
368                  * Special case for TM.  We send a WILL, but pretend
369                  * we sent WONT.
370                  */
371                 send_will(option, 0);
372                 set_my_want_state_wont(TELOPT_TM);
373                 set_my_state_wont(TELOPT_TM);
374                 return;
375
376             case TELOPT_BINARY:         /* binary mode */
377             case TELOPT_NAWS:           /* window size */
378             case TELOPT_TSPEED:         /* terminal speed */
379             case TELOPT_LFLOW:          /* local flow control */
380             case TELOPT_TTYPE:          /* terminal type option */
381             case TELOPT_SGA:            /* no big deal */
382 #if     defined(ENCRYPTION)
383             case TELOPT_ENCRYPT:        /* encryption variable option */
384 #endif
385                 new_state_ok = 1;
386                 break;
387
388             case TELOPT_NEW_ENVIRON:    /* New environment variable option */
389 #ifdef  OLD_ENVIRON
390                 if (my_state_is_will(TELOPT_OLD_ENVIRON))
391                         send_wont(TELOPT_OLD_ENVIRON, 1); /* turn off the old */
392                 goto env_common;
393             case TELOPT_OLD_ENVIRON:    /* Old environment variable option */
394                 if (my_state_is_will(TELOPT_NEW_ENVIRON))
395                         break;          /* Don't enable if new one is in use! */
396             env_common:
397                 telopt_environ = option;
398 #endif
399                 new_state_ok = 1;
400                 break;
401
402 #if     defined(AUTHENTICATION)
403             case TELOPT_AUTHENTICATION:
404                 if (autologin)
405                         new_state_ok = 1;
406                 break;
407 #endif
408
409             case TELOPT_XDISPLOC:       /* X Display location */
410                 if (env_getvalue((unsigned char *)"DISPLAY"))
411                     new_state_ok = 1;
412                 break;
413
414             case TELOPT_LINEMODE:
415 #ifdef  KLUDGELINEMODE
416                 kludgelinemode = 0;
417                 send_do(TELOPT_SGA, 1);
418 #endif
419                 set_my_want_state_will(TELOPT_LINEMODE);
420                 send_will(option, 0);
421                 set_my_state_will(TELOPT_LINEMODE);
422                 slc_init();
423                 return;
424
425             case TELOPT_ECHO:           /* We're never going to echo... */
426             default:
427                 break;
428             }
429
430             if (new_state_ok) {
431                 set_my_want_state_will(option);
432                 send_will(option, 0);
433                 setconnmode(0);                 /* Set new tty mode */
434             } else {
435                 will_wont_resp[option]++;
436                 send_wont(option, 0);
437             }
438           } else {
439             /*
440              * Handle options that need more things done after the
441              * other side has acknowledged the option.
442              */
443             switch (option) {
444             case TELOPT_LINEMODE:
445 #ifdef  KLUDGELINEMODE
446                 kludgelinemode = 0;
447                 send_do(TELOPT_SGA, 1);
448 #endif
449                 set_my_state_will(option);
450                 slc_init();
451                 send_do(TELOPT_SGA, 0);
452                 return;
453             }
454           }
455         }
456         set_my_state_will(option);
457 }
458
459 static void
460 dontoption(int option)
461 {
462
463         if (will_wont_resp[option]) {
464             --will_wont_resp[option];
465             if (will_wont_resp[option] && my_state_is_wont(option))
466                 --will_wont_resp[option];
467         }
468
469         if ((will_wont_resp[option] == 0) && my_want_state_is_will(option)) {
470             switch (option) {
471             case TELOPT_LINEMODE:
472                 linemode = 0;   /* put us back to the default state */
473                 break;
474 #ifdef  OLD_ENVIRON
475             case TELOPT_NEW_ENVIRON:
476                 /*
477                  * The new environ option wasn't recognized, try
478                  * the old one.
479                  */
480                 send_will(TELOPT_OLD_ENVIRON, 1);
481                 telopt_environ = TELOPT_OLD_ENVIRON;
482                 break;
483 #endif
484 #if 0
485 #ifdef ENCRYPTION
486             case TELOPT_ENCRYPT:
487               encrypt_not();
488               break;
489 #endif
490 #endif
491             }
492             /* we always accept a DONT */
493             set_my_want_state_wont(option);
494             if (my_state_is_will(option))
495                 send_wont(option, 0);
496             setconnmode(0);                     /* Set new tty mode */
497         }
498         set_my_state_wont(option);
499 }
500
501 /*
502  * Given a buffer returned by tgetent(), this routine will turn
503  * the pipe seperated list of names in the buffer into an array
504  * of pointers to null terminated names.  We toss out any bad,
505  * duplicate, or verbose names (names with spaces).
506  */
507
508 static char *name_unknown = "UNKNOWN";
509 static char *unknown[] = { 0, 0 };
510
511 static char **
512 mklist(char *buf, char *name)
513 {
514         int n;
515         char c, *cp, **argvp, *cp2, **argv, **avt;
516
517         if (name) {
518                 if ((int)strlen(name) > 40) {
519                         name = 0;
520                         unknown[0] = name_unknown;
521                 } else {
522                         unknown[0] = name;
523                         strupr(name);
524                 }
525         } else
526                 unknown[0] = name_unknown;
527         /*
528          * Count up the number of names.
529          */
530         for (n = 1, cp = buf; *cp && *cp != ':'; cp++) {
531                 if (*cp == '|')
532                         n++;
533         }
534         /*
535          * Allocate an array to put the name pointers into
536          */
537         argv = (char **)malloc((n+3)*sizeof(char *));
538         if (argv == 0)
539                 return(unknown);
540
541         /*
542          * Fill up the array of pointers to names.
543          */
544         *argv = 0;
545         argvp = argv+1;
546         n = 0;
547         for (cp = cp2 = buf; (c = *cp);  cp++) {
548                 if (c == '|' || c == ':') {
549                         *cp++ = '\0';
550                         /*
551                          * Skip entries that have spaces or are over 40
552                          * characters long.  If this is our environment
553                          * name, then put it up front.  Otherwise, as
554                          * long as this is not a duplicate name (case
555                          * insensitive) add it to the list.
556                          */
557                         if (n || (cp - cp2 > 41))
558                                 ;
559                         else if (name && (strncasecmp(name, cp2, cp-cp2) == 0))
560                                 *argv = cp2;
561                         else if (is_unique(cp2, argv+1, argvp))
562                                 *argvp++ = cp2;
563                         if (c == ':')
564                                 break;
565                         /*
566                          * Skip multiple delimiters. Reset cp2 to
567                          * the beginning of the next name. Reset n,
568                          * the flag for names with spaces.
569                          */
570                         while ((c = *cp) == '|')
571                                 cp++;
572                         cp2 = cp;
573                         n = 0;
574                 }
575                 /*
576                  * Skip entries with spaces or non-ascii values.
577                  * Convert lower case letters to upper case.
578                  */
579 #define ISASCII(c) (!((c)&0x80))
580                 if ((c == ' ') || !ISASCII(c))
581                         n = 1;
582                 else if (islower(c))
583                         *cp = toupper(c);
584         }
585
586         /*
587          * Check for an old V6 2 character name.  If the second
588          * name points to the beginning of the buffer, and is
589          * only 2 characters long, move it to the end of the array.
590          */
591         if ((argv[1] == buf) && (strlen(argv[1]) == 2)) {
592                 --argvp;
593                 for (avt = &argv[1]; avt < argvp; avt++)
594                         *avt = *(avt+1);
595                 *argvp++ = buf;
596         }
597
598         /*
599          * Duplicate last name, for TTYPE option, and null
600          * terminate the array.  If we didn't find a match on
601          * our terminal name, put that name at the beginning.
602          */
603         cp = *(argvp-1);
604         *argvp++ = cp;
605         *argvp = 0;
606
607         if (*argv == 0) {
608                 if (name)
609                         *argv = name;
610                 else {
611                         --argvp;
612                         for (avt = argv; avt < argvp; avt++)
613                                 *avt = *(avt+1);
614                 }
615         }
616         if (*argv)
617                 return(argv);
618         else
619                 return(unknown);
620 }
621
622 static int
623 is_unique(char *name, char **as, char **ae)
624 {
625         char **ap;
626         int n;
627
628         n = strlen(name) + 1;
629         for (ap = as; ap < ae; ap++)
630                 if (strncasecmp(*ap, name, n) == 0)
631                         return(0);
632         return (1);
633 }
634
635 static char termbuf[1024];
636
637 static int
638 telnet_setupterm(const char *tname, int fd, int *errp)
639 {
640         if (tgetent(termbuf, tname) == 1) {
641                 termbuf[1023] = '\0';
642                 if (errp)
643                         *errp = 1;
644                 return(0);
645         }
646         if (errp)
647                 *errp = 0;
648         return(-1);
649 }
650
651 int resettermname = 1;
652
653 static char *
654 gettermname()
655 {
656         char *tname;
657         static char **tnamep = 0;
658         static char **next;
659         int err;
660
661         if (resettermname) {
662                 resettermname = 0;
663                 if (tnamep && tnamep != unknown)
664                         free(tnamep);
665                 if ((tname = (char *)env_getvalue((unsigned char *)"TERM")) &&
666                                 telnet_setupterm(tname, 1, &err) == 0) {
667                         tnamep = mklist(termbuf, tname);
668                 } else {
669                         if (tname && ((int)strlen(tname) <= 40)) {
670                                 unknown[0] = tname;
671                                 strupr(tname);
672                         } else
673                                 unknown[0] = name_unknown;
674                         tnamep = unknown;
675                 }
676                 next = tnamep;
677         }
678         if (*next == 0)
679                 next = tnamep;
680         return(*next++);
681 }
682 /*
683  * suboption()
684  *
685  *      Look at the sub-option buffer, and try to be helpful to the other
686  * side.
687  *
688  *      Currently we recognize:
689  *
690  *              Terminal type, send request.
691  *              Terminal speed (send request).
692  *              Local flow control (is request).
693  *              Linemode
694  */
695
696 static void
697 suboption()
698 {
699     unsigned char subchar;
700
701     printsub('<', subbuffer, SB_LEN()+2);
702     switch (subchar = SB_GET()) {
703     case TELOPT_TTYPE:
704         if (my_want_state_is_wont(TELOPT_TTYPE))
705             return;
706         if (SB_EOF() || SB_GET() != TELQUAL_SEND) {
707             return;
708         } else {
709             char *name;
710             unsigned char temp[50];
711             int len;
712
713             name = gettermname();
714             len = strlen(name) + 4 + 2;
715             if (len < NETROOM()) {
716                 snprintf((char *)temp, sizeof(temp),
717                          "%c%c%c%c%s%c%c", IAC, SB, TELOPT_TTYPE,
718                          TELQUAL_IS, name, IAC, SE);
719                 ring_supply_data(&netoring, temp, len);
720                 printsub('>', &temp[2], len-2);
721             } else {
722                 ExitString("No room in buffer for terminal type.\n", 1);
723                 /*NOTREACHED*/
724             }
725         }
726         break;
727     case TELOPT_TSPEED:
728         if (my_want_state_is_wont(TELOPT_TSPEED))
729             return;
730         if (SB_EOF())
731             return;
732         if (SB_GET() == TELQUAL_SEND) {
733             long output_speed, input_speed;
734             unsigned char temp[50];
735             int len;
736
737             TerminalSpeeds(&input_speed, &output_speed);
738
739             snprintf((char *)temp, sizeof(temp),
740                      "%c%c%c%c%u,%u%c%c", IAC, SB, TELOPT_TSPEED,
741                      TELQUAL_IS,
742                      (unsigned)output_speed,
743                      (unsigned)input_speed, IAC, SE);
744             len = strlen((char *)temp+4) + 4;   /* temp[3] is 0 ... */
745
746             if (len < NETROOM()) {
747                 ring_supply_data(&netoring, temp, len);
748                 printsub('>', temp+2, len - 2);
749             }
750 /*@*/       else printf("lm_will: not enough room in buffer\n");
751         }
752         break;
753     case TELOPT_LFLOW:
754         if (my_want_state_is_wont(TELOPT_LFLOW))
755             return;
756         if (SB_EOF())
757             return;
758         switch(SB_GET()) {
759         case LFLOW_RESTART_ANY:
760             restartany = 1;
761             break;
762         case LFLOW_RESTART_XON:
763             restartany = 0;
764             break;
765         case LFLOW_ON:
766             localflow = 1;
767             break;
768         case LFLOW_OFF:
769             localflow = 0;
770             break;
771         default:
772             return;
773         }
774         setcommandmode();
775         setconnmode(0);
776         break;
777
778     case TELOPT_LINEMODE:
779         if (my_want_state_is_wont(TELOPT_LINEMODE))
780             return;
781         if (SB_EOF())
782             return;
783         switch (SB_GET()) {
784         case WILL:
785             lm_will(subpointer, SB_LEN());
786             break;
787         case WONT:
788             lm_wont(subpointer, SB_LEN());
789             break;
790         case DO:
791             lm_do(subpointer, SB_LEN());
792             break;
793         case DONT:
794             lm_dont(subpointer, SB_LEN());
795             break;
796         case LM_SLC:
797             slc(subpointer, SB_LEN());
798             break;
799         case LM_MODE:
800             lm_mode(subpointer, SB_LEN(), 0);
801             break;
802         default:
803             break;
804         }
805         break;
806
807 #ifdef  OLD_ENVIRON
808     case TELOPT_OLD_ENVIRON:
809 #endif
810     case TELOPT_NEW_ENVIRON:
811         if (SB_EOF())
812             return;
813         switch(SB_PEEK()) {
814         case TELQUAL_IS:
815         case TELQUAL_INFO:
816             if (my_want_state_is_dont(subchar))
817                 return;
818             break;
819         case TELQUAL_SEND:
820             if (my_want_state_is_wont(subchar)) {
821                 return;
822             }
823             break;
824         default:
825             return;
826         }
827         env_opt(subpointer, SB_LEN());
828         break;
829
830     case TELOPT_XDISPLOC:
831         if (my_want_state_is_wont(TELOPT_XDISPLOC))
832             return;
833         if (SB_EOF())
834             return;
835         if (SB_GET() == TELQUAL_SEND) {
836             unsigned char temp[50], *dp;
837             int len;
838
839             if ((dp = env_getvalue((unsigned char *)"DISPLAY")) == NULL) {
840                 /*
841                  * Something happened, we no longer have a DISPLAY
842                  * variable.  So, turn off the option.
843                  */
844                 send_wont(TELOPT_XDISPLOC, 1);
845                 break;
846             }
847             snprintf((char *)temp, sizeof(temp),
848                      "%c%c%c%c%s%c%c", IAC, SB, TELOPT_XDISPLOC,
849                      TELQUAL_IS, dp, IAC, SE);
850             len = strlen((char *)temp+4) + 4;   /* temp[3] is 0 ... */
851
852             if (len < NETROOM()) {
853                 ring_supply_data(&netoring, temp, len);
854                 printsub('>', temp+2, len - 2);
855             }
856 /*@*/       else printf("lm_will: not enough room in buffer\n");
857         }
858         break;
859
860 #if     defined(AUTHENTICATION)
861         case TELOPT_AUTHENTICATION: {
862                 if (!autologin)
863                         break;
864                 if (SB_EOF())
865                         return;
866                 switch(SB_GET()) {
867                 case TELQUAL_IS:
868                         if (my_want_state_is_dont(TELOPT_AUTHENTICATION))
869                                 return;
870                         auth_is(subpointer, SB_LEN());
871                         break;
872                 case TELQUAL_SEND:
873                         if (my_want_state_is_wont(TELOPT_AUTHENTICATION))
874                                 return;
875                         auth_send(subpointer, SB_LEN());
876                         break;
877                 case TELQUAL_REPLY:
878                         if (my_want_state_is_wont(TELOPT_AUTHENTICATION))
879                                 return;
880                         auth_reply(subpointer, SB_LEN());
881                         break;
882                 case TELQUAL_NAME:
883                         if (my_want_state_is_dont(TELOPT_AUTHENTICATION))
884                                 return;
885                         auth_name(subpointer, SB_LEN());
886                         break;
887                 }
888         }
889         break;
890 #endif
891 #if     defined(ENCRYPTION)
892         case TELOPT_ENCRYPT:
893                 if (SB_EOF())
894                         return;
895                 switch(SB_GET()) {
896                 case ENCRYPT_START:
897                         if (my_want_state_is_dont(TELOPT_ENCRYPT))
898                                 return;
899                         encrypt_start(subpointer, SB_LEN());
900                         break;
901                 case ENCRYPT_END:
902                         if (my_want_state_is_dont(TELOPT_ENCRYPT))
903                                 return;
904                         encrypt_end();
905                         break;
906                 case ENCRYPT_SUPPORT:
907                         if (my_want_state_is_wont(TELOPT_ENCRYPT))
908                                 return;
909                         encrypt_support(subpointer, SB_LEN());
910                         break;
911                 case ENCRYPT_REQSTART:
912                         if (my_want_state_is_wont(TELOPT_ENCRYPT))
913                                 return;
914                         encrypt_request_start(subpointer, SB_LEN());
915                         break;
916                 case ENCRYPT_REQEND:
917                         if (my_want_state_is_wont(TELOPT_ENCRYPT))
918                                 return;
919                         /*
920                          * We can always send an REQEND so that we cannot
921                          * get stuck encrypting.  We should only get this
922                          * if we have been able to get in the correct mode
923                          * anyhow.
924                          */
925                         encrypt_request_end();
926                         break;
927                 case ENCRYPT_IS:
928                         if (my_want_state_is_dont(TELOPT_ENCRYPT))
929                                 return;
930                         encrypt_is(subpointer, SB_LEN());
931                         break;
932                 case ENCRYPT_REPLY:
933                         if (my_want_state_is_wont(TELOPT_ENCRYPT))
934                                 return;
935                         encrypt_reply(subpointer, SB_LEN());
936                         break;
937                 case ENCRYPT_ENC_KEYID:
938                         if (my_want_state_is_dont(TELOPT_ENCRYPT))
939                                 return;
940                         encrypt_enc_keyid(subpointer, SB_LEN());
941                         break;
942                 case ENCRYPT_DEC_KEYID:
943                         if (my_want_state_is_wont(TELOPT_ENCRYPT))
944                                 return;
945                         encrypt_dec_keyid(subpointer, SB_LEN());
946                         break;
947                 default:
948                         break;
949                 }
950                 break;
951 #endif
952     default:
953         break;
954     }
955 }
956
957 static unsigned char str_lm[] = { IAC, SB, TELOPT_LINEMODE, 0, 0, IAC, SE };
958
959 void
960 lm_will(unsigned char *cmd, int len)
961 {
962     if (len < 1) {
963 /*@*/   printf("lm_will: no command!!!\n");     /* Should not happen... */
964         return;
965     }
966     switch(cmd[0]) {
967     case LM_FORWARDMASK:        /* We shouldn't ever get this... */
968     default:
969         str_lm[3] = DONT;
970         str_lm[4] = cmd[0];
971         if (NETROOM() > sizeof(str_lm)) {
972             ring_supply_data(&netoring, str_lm, sizeof(str_lm));
973             printsub('>', &str_lm[2], sizeof(str_lm)-2);
974         }
975 /*@*/   else printf("lm_will: not enough room in buffer\n");
976         break;
977     }
978 }
979
980 void
981 lm_wont(unsigned char *cmd, int len)
982 {
983     if (len < 1) {
984 /*@*/   printf("lm_wont: no command!!!\n");     /* Should not happen... */
985         return;
986     }
987     switch(cmd[0]) {
988     case LM_FORWARDMASK:        /* We shouldn't ever get this... */
989     default:
990         /* We are always DONT, so don't respond */
991         return;
992     }
993 }
994
995 void
996 lm_do(unsigned char *cmd, int len)
997 {
998     if (len < 1) {
999 /*@*/   printf("lm_do: no command!!!\n");       /* Should not happen... */
1000         return;
1001     }
1002     switch(cmd[0]) {
1003     case LM_FORWARDMASK:
1004     default:
1005         str_lm[3] = WONT;
1006         str_lm[4] = cmd[0];
1007         if (NETROOM() > sizeof(str_lm)) {
1008             ring_supply_data(&netoring, str_lm, sizeof(str_lm));
1009             printsub('>', &str_lm[2], sizeof(str_lm)-2);
1010         }
1011 /*@*/   else printf("lm_do: not enough room in buffer\n");
1012         break;
1013     }
1014 }
1015
1016 void
1017 lm_dont(unsigned char *cmd, int len)
1018 {
1019     if (len < 1) {
1020 /*@*/   printf("lm_dont: no command!!!\n");     /* Should not happen... */
1021         return;
1022     }
1023     switch(cmd[0]) {
1024     case LM_FORWARDMASK:
1025     default:
1026         /* we are always WONT, so don't respond */
1027         break;
1028     }
1029 }
1030
1031 static unsigned char str_lm_mode[] = {
1032         IAC, SB, TELOPT_LINEMODE, LM_MODE, 0, IAC, SE
1033 };
1034
1035 void
1036 lm_mode(unsigned char *cmd, int len, int init)
1037 {
1038         if (len != 1)
1039                 return;
1040         if ((linemode&MODE_MASK&~MODE_ACK) == *cmd)
1041                 return;
1042         if (*cmd&MODE_ACK)
1043                 return;
1044         linemode = *cmd&(MODE_MASK&~MODE_ACK);
1045         str_lm_mode[4] = linemode;
1046         if (!init)
1047             str_lm_mode[4] |= MODE_ACK;
1048         if (NETROOM() > sizeof(str_lm_mode)) {
1049             ring_supply_data(&netoring, str_lm_mode, sizeof(str_lm_mode));
1050             printsub('>', &str_lm_mode[2], sizeof(str_lm_mode)-2);
1051         }
1052 /*@*/   else printf("lm_mode: not enough room in buffer\n");
1053         setconnmode(0); /* set changed mode */
1054 }
1055
1056
1057
1058 /*
1059  * slc()
1060  * Handle special character suboption of LINEMODE.
1061  */
1062
1063 struct spc {
1064         cc_t val;
1065         cc_t *valp;
1066         char flags;     /* Current flags & level */
1067         char mylevel;   /* Maximum level & flags */
1068 } spc_data[NSLC+1];
1069
1070 #define SLC_IMPORT      0
1071 #define SLC_EXPORT      1
1072 #define SLC_RVALUE      2
1073 static int slc_mode = SLC_EXPORT;
1074
1075 void
1076 slc_init()
1077 {
1078         struct spc *spcp;
1079
1080         localchars = 1;
1081         for (spcp = spc_data; spcp < &spc_data[NSLC+1]; spcp++) {
1082                 spcp->val = 0;
1083                 spcp->valp = 0;
1084                 spcp->flags = spcp->mylevel = SLC_NOSUPPORT;
1085         }
1086
1087 #define initfunc(func, flags) { \
1088                                         spcp = &spc_data[func]; \
1089                                         if ((spcp->valp = tcval(func))) { \
1090                                             spcp->val = *spcp->valp; \
1091                                             spcp->mylevel = SLC_VARIABLE|flags; \
1092                                         } else { \
1093                                             spcp->val = 0; \
1094                                             spcp->mylevel = SLC_DEFAULT; \
1095                                         } \
1096                                     }
1097
1098         initfunc(SLC_SYNCH, 0);
1099         /* No BRK */
1100         initfunc(SLC_AO, 0);
1101         initfunc(SLC_AYT, 0);
1102         /* No EOR */
1103         initfunc(SLC_ABORT, SLC_FLUSHIN|SLC_FLUSHOUT);
1104         initfunc(SLC_EOF, 0);
1105         initfunc(SLC_SUSP, SLC_FLUSHIN);
1106         initfunc(SLC_EC, 0);
1107         initfunc(SLC_EL, 0);
1108         initfunc(SLC_EW, 0);
1109         initfunc(SLC_RP, 0);
1110         initfunc(SLC_LNEXT, 0);
1111         initfunc(SLC_XON, 0);
1112         initfunc(SLC_XOFF, 0);
1113         initfunc(SLC_FORW1, 0);
1114         initfunc(SLC_FORW2, 0);
1115         /* No FORW2 */
1116
1117         initfunc(SLC_IP, SLC_FLUSHIN|SLC_FLUSHOUT);
1118 #undef  initfunc
1119
1120         if (slc_mode == SLC_EXPORT)
1121                 slc_export();
1122         else
1123                 slc_import(1);
1124
1125 }
1126
1127 void
1128 slcstate()
1129 {
1130     printf("Special characters are %s values\n",
1131                 slc_mode == SLC_IMPORT ? "remote default" :
1132                 slc_mode == SLC_EXPORT ? "local" :
1133                                          "remote");
1134 }
1135
1136 void
1137 slc_mode_export()
1138 {
1139     slc_mode = SLC_EXPORT;
1140     if (my_state_is_will(TELOPT_LINEMODE))
1141         slc_export();
1142 }
1143
1144 void
1145 slc_mode_import(int def)
1146 {
1147     slc_mode = def ? SLC_IMPORT : SLC_RVALUE;
1148     if (my_state_is_will(TELOPT_LINEMODE))
1149         slc_import(def);
1150 }
1151
1152 unsigned char slc_import_val[] = {
1153         IAC, SB, TELOPT_LINEMODE, LM_SLC, 0, SLC_VARIABLE, 0, IAC, SE
1154 };
1155 unsigned char slc_import_def[] = {
1156         IAC, SB, TELOPT_LINEMODE, LM_SLC, 0, SLC_DEFAULT, 0, IAC, SE
1157 };
1158
1159 void
1160 slc_import(int def)
1161 {
1162     if (NETROOM() > sizeof(slc_import_val)) {
1163         if (def) {
1164             ring_supply_data(&netoring, slc_import_def, sizeof(slc_import_def));
1165             printsub('>', &slc_import_def[2], sizeof(slc_import_def)-2);
1166         } else {
1167             ring_supply_data(&netoring, slc_import_val, sizeof(slc_import_val));
1168             printsub('>', &slc_import_val[2], sizeof(slc_import_val)-2);
1169         }
1170     }
1171 /*@*/ else printf("slc_import: not enough room\n");
1172 }
1173
1174 void
1175 slc_export()
1176 {
1177     struct spc *spcp;
1178
1179     TerminalDefaultChars();
1180
1181     slc_start_reply();
1182     for (spcp = &spc_data[1]; spcp < &spc_data[NSLC+1]; spcp++) {
1183         if (spcp->mylevel != SLC_NOSUPPORT) {
1184             if (spcp->val == (cc_t)(_POSIX_VDISABLE))
1185                 spcp->flags = SLC_NOSUPPORT;
1186             else
1187                 spcp->flags = spcp->mylevel;
1188             if (spcp->valp)
1189                 spcp->val = *spcp->valp;
1190             slc_add_reply(spcp - spc_data, spcp->flags, spcp->val);
1191         }
1192     }
1193     slc_end_reply();
1194     slc_update();
1195     setconnmode(1);     /* Make sure the character values are set */
1196 }
1197
1198 void
1199 slc(unsigned char *cp, int len)
1200 {
1201         struct spc *spcp;
1202         int func,level;
1203
1204         slc_start_reply();
1205
1206         for (; len >= 3; len -=3, cp +=3) {
1207
1208                 func = cp[SLC_FUNC];
1209
1210                 if (func == 0) {
1211                         /*
1212                          * Client side: always ignore 0 function.
1213                          */
1214                         continue;
1215                 }
1216                 if (func > NSLC) {
1217                         if ((cp[SLC_FLAGS] & SLC_LEVELBITS) != SLC_NOSUPPORT)
1218                                 slc_add_reply(func, SLC_NOSUPPORT, 0);
1219                         continue;
1220                 }
1221
1222                 spcp = &spc_data[func];
1223
1224                 level = cp[SLC_FLAGS]&(SLC_LEVELBITS|SLC_ACK);
1225
1226                 if ((cp[SLC_VALUE] == (unsigned char)spcp->val) &&
1227                     ((level&SLC_LEVELBITS) == (spcp->flags&SLC_LEVELBITS))) {
1228                         continue;
1229                 }
1230
1231                 if (level == (SLC_DEFAULT|SLC_ACK)) {
1232                         /*
1233                          * This is an error condition, the SLC_ACK
1234                          * bit should never be set for the SLC_DEFAULT
1235                          * level.  Our best guess to recover is to
1236                          * ignore the SLC_ACK bit.
1237                          */
1238                         cp[SLC_FLAGS] &= ~SLC_ACK;
1239                 }
1240
1241                 if (level == ((spcp->flags&SLC_LEVELBITS)|SLC_ACK)) {
1242                         spcp->val = (cc_t)cp[SLC_VALUE];
1243                         spcp->flags = cp[SLC_FLAGS];    /* include SLC_ACK */
1244                         continue;
1245                 }
1246
1247                 level &= ~SLC_ACK;
1248
1249                 if (level <= (spcp->mylevel&SLC_LEVELBITS)) {
1250                         spcp->flags = cp[SLC_FLAGS]|SLC_ACK;
1251                         spcp->val = (cc_t)cp[SLC_VALUE];
1252                 }
1253                 if (level == SLC_DEFAULT) {
1254                         if ((spcp->mylevel&SLC_LEVELBITS) != SLC_DEFAULT)
1255                                 spcp->flags = spcp->mylevel;
1256                         else
1257                                 spcp->flags = SLC_NOSUPPORT;
1258                 }
1259                 slc_add_reply(func, spcp->flags, spcp->val);
1260         }
1261         slc_end_reply();
1262         if (slc_update())
1263                 setconnmode(1); /* set the  new character values */
1264 }
1265
1266 void
1267 slc_check()
1268 {
1269     struct spc *spcp;
1270
1271     slc_start_reply();
1272     for (spcp = &spc_data[1]; spcp < &spc_data[NSLC+1]; spcp++) {
1273         if (spcp->valp && spcp->val != *spcp->valp) {
1274             spcp->val = *spcp->valp;
1275             if (spcp->val == (cc_t)(_POSIX_VDISABLE))
1276                 spcp->flags = SLC_NOSUPPORT;
1277             else
1278                 spcp->flags = spcp->mylevel;
1279             slc_add_reply(spcp - spc_data, spcp->flags, spcp->val);
1280         }
1281     }
1282     slc_end_reply();
1283     setconnmode(1);
1284 }
1285
1286
1287 unsigned char slc_reply[128];
1288 unsigned char *slc_replyp;
1289
1290 void
1291 slc_start_reply()
1292 {
1293         slc_replyp = slc_reply;
1294         *slc_replyp++ = IAC;
1295         *slc_replyp++ = SB;
1296         *slc_replyp++ = TELOPT_LINEMODE;
1297         *slc_replyp++ = LM_SLC;
1298 }
1299
1300 void
1301 slc_add_reply(unsigned char func, unsigned char flags, cc_t value)
1302 {
1303         if ((*slc_replyp++ = func) == IAC)
1304                 *slc_replyp++ = IAC;
1305         if ((*slc_replyp++ = flags) == IAC)
1306                 *slc_replyp++ = IAC;
1307         if ((*slc_replyp++ = (unsigned char)value) == IAC)
1308                 *slc_replyp++ = IAC;
1309 }
1310
1311 void
1312 slc_end_reply()
1313 {
1314     int len;
1315
1316     *slc_replyp++ = IAC;
1317     *slc_replyp++ = SE;
1318     len = slc_replyp - slc_reply;
1319     if (len <= 6)
1320         return;
1321     if (NETROOM() > len) {
1322         ring_supply_data(&netoring, slc_reply, slc_replyp - slc_reply);
1323         printsub('>', &slc_reply[2], slc_replyp - slc_reply - 2);
1324     }
1325 /*@*/else printf("slc_end_reply: not enough room\n");
1326 }
1327
1328 int
1329 slc_update()
1330 {
1331         struct spc *spcp;
1332         int need_update = 0;
1333
1334         for (spcp = &spc_data[1]; spcp < &spc_data[NSLC+1]; spcp++) {
1335                 if (!(spcp->flags&SLC_ACK))
1336                         continue;
1337                 spcp->flags &= ~SLC_ACK;
1338                 if (spcp->valp && (*spcp->valp != spcp->val)) {
1339                         *spcp->valp = spcp->val;
1340                         need_update = 1;
1341                 }
1342         }
1343         return(need_update);
1344 }
1345
1346 #ifdef  OLD_ENVIRON
1347 #  define old_env_var OLD_ENV_VAR
1348 #  define old_env_value OLD_ENV_VALUE
1349 #endif
1350
1351 void
1352 env_opt(unsigned char *buf, int len)
1353 {
1354         unsigned char *ep = 0, *epc = 0;
1355         int i;
1356
1357         switch(buf[0]&0xff) {
1358         case TELQUAL_SEND:
1359                 env_opt_start();
1360                 if (len == 1) {
1361                         env_opt_add(NULL);
1362                 } else for (i = 1; i < len; i++) {
1363                         switch (buf[i]&0xff) {
1364 #ifdef  OLD_ENVIRON
1365                         case OLD_ENV_VAR:
1366                         case OLD_ENV_VALUE:
1367                                 /*
1368                                  * Although OLD_ENV_VALUE is not legal, we will
1369                                  * still recognize it, just in case it is an
1370                                  * old server that has VAR & VALUE mixed up...
1371                                  */
1372                                 /* FALL THROUGH */
1373 #else
1374                         case NEW_ENV_VAR:
1375 #endif
1376                         case ENV_USERVAR:
1377                                 if (ep) {
1378                                         *epc = 0;
1379                                         env_opt_add(ep);
1380                                 }
1381                                 ep = epc = &buf[i+1];
1382                                 break;
1383                         case ENV_ESC:
1384                                 i++;
1385                                 /*FALL THROUGH*/
1386                         default:
1387                                 if (epc)
1388                                         *epc++ = buf[i];
1389                                 break;
1390                         }
1391                 }
1392                 if (ep) {
1393                         *epc = 0;
1394                         env_opt_add(ep);
1395                 }
1396                 env_opt_end(1);
1397                 break;
1398
1399         case TELQUAL_IS:
1400         case TELQUAL_INFO:
1401                 /* Ignore for now.  We shouldn't get it anyway. */
1402                 break;
1403
1404         default:
1405                 break;
1406         }
1407 }
1408
1409 #define OPT_REPLY_SIZE  256
1410 unsigned char *opt_reply;
1411 unsigned char *opt_replyp;
1412 unsigned char *opt_replyend;
1413
1414 void
1415 env_opt_start()
1416 {
1417         if (opt_reply)
1418                 opt_reply = (unsigned char *)realloc(opt_reply, OPT_REPLY_SIZE);
1419         else
1420                 opt_reply = (unsigned char *)malloc(OPT_REPLY_SIZE);
1421         if (opt_reply == NULL) {
1422 /*@*/           printf("env_opt_start: malloc()/realloc() failed!!!\n");
1423                 opt_reply = opt_replyp = opt_replyend = NULL;
1424                 return;
1425         }
1426         opt_replyp = opt_reply;
1427         opt_replyend = opt_reply + OPT_REPLY_SIZE;
1428         *opt_replyp++ = IAC;
1429         *opt_replyp++ = SB;
1430         *opt_replyp++ = telopt_environ;
1431         *opt_replyp++ = TELQUAL_IS;
1432 }
1433
1434 void
1435 env_opt_start_info()
1436 {
1437         env_opt_start();
1438         if (opt_replyp)
1439             opt_replyp[-1] = TELQUAL_INFO;
1440 }
1441
1442 void
1443 env_opt_add(unsigned char *ep)
1444 {
1445         unsigned char *vp, c;
1446
1447         if (opt_reply == NULL)          /*XXX*/
1448                 return;                 /*XXX*/
1449
1450         if (ep == NULL || *ep == '\0') {
1451                 /* Send user defined variables first. */
1452                 env_default(1, 0);
1453                 while ((ep = env_default(0, 0)))
1454                         env_opt_add(ep);
1455
1456                 /* Now add the list of well know variables.  */
1457                 env_default(1, 1);
1458                 while ((ep = env_default(0, 1)))
1459                         env_opt_add(ep);
1460                 return;
1461         }
1462         vp = env_getvalue(ep);
1463         if (opt_replyp + (vp ? strlen((char *)vp) : 0) +
1464                                 strlen((char *)ep) + 6 > opt_replyend)
1465         {
1466                 int len;
1467                 opt_replyend += OPT_REPLY_SIZE;
1468                 len = opt_replyend - opt_reply;
1469                 opt_reply = (unsigned char *)realloc(opt_reply, len);
1470                 if (opt_reply == NULL) {
1471 /*@*/                   printf("env_opt_add: realloc() failed!!!\n");
1472                         opt_reply = opt_replyp = opt_replyend = NULL;
1473                         return;
1474                 }
1475                 opt_replyp = opt_reply + len - (opt_replyend - opt_replyp);
1476                 opt_replyend = opt_reply + len;
1477         }
1478         if (opt_welldefined((char *)ep)) {
1479 #ifdef  OLD_ENVIRON
1480                 if (telopt_environ == TELOPT_OLD_ENVIRON)
1481                         *opt_replyp++ = old_env_var;
1482                 else
1483 #endif
1484                         *opt_replyp++ = NEW_ENV_VAR;
1485         } else
1486                 *opt_replyp++ = ENV_USERVAR;
1487         for (;;) {
1488                 while ((c = *ep++)) {
1489                         switch(c&0xff) {
1490                         case IAC:
1491                                 *opt_replyp++ = IAC;
1492                                 break;
1493                         case NEW_ENV_VAR:
1494                         case NEW_ENV_VALUE:
1495                         case ENV_ESC:
1496                         case ENV_USERVAR:
1497                                 *opt_replyp++ = ENV_ESC;
1498                                 break;
1499                         }
1500                         *opt_replyp++ = c;
1501                 }
1502                 if ((ep = vp)) {
1503 #ifdef  OLD_ENVIRON
1504                         if (telopt_environ == TELOPT_OLD_ENVIRON)
1505                                 *opt_replyp++ = old_env_value;
1506                         else
1507 #endif
1508                                 *opt_replyp++ = NEW_ENV_VALUE;
1509                         vp = NULL;
1510                 } else
1511                         break;
1512         }
1513 }
1514
1515 int
1516 opt_welldefined(char *ep)
1517 {
1518         if ((strcmp(ep, "USER") == 0) ||
1519             (strcmp(ep, "DISPLAY") == 0) ||
1520             (strcmp(ep, "PRINTER") == 0) ||
1521             (strcmp(ep, "SYSTEMTYPE") == 0) ||
1522             (strcmp(ep, "JOB") == 0) ||
1523             (strcmp(ep, "ACCT") == 0))
1524                 return(1);
1525         return(0);
1526 }
1527
1528 void
1529 env_opt_end(int emptyok)
1530 {
1531         int len;
1532
1533         len = opt_replyp - opt_reply + 2;
1534         if (emptyok || len > 6) {
1535                 *opt_replyp++ = IAC;
1536                 *opt_replyp++ = SE;
1537                 if (NETROOM() > len) {
1538                         ring_supply_data(&netoring, opt_reply, len);
1539                         printsub('>', &opt_reply[2], len - 2);
1540                 }
1541 /*@*/           else printf("slc_end_reply: not enough room\n");
1542         }
1543         if (opt_reply) {
1544                 free(opt_reply);
1545                 opt_reply = opt_replyp = opt_replyend = NULL;
1546         }
1547 }
1548
1549
1550
1551 int
1552 telrcv(void)
1553 {
1554     int c;
1555     int scc;
1556     unsigned char *sbp = NULL;
1557     int count;
1558     int returnValue = 0;
1559
1560     scc = 0;
1561     count = 0;
1562     while (TTYROOM() > 2) {
1563         if (scc == 0) {
1564             if (count) {
1565                 ring_consumed(&netiring, count);
1566                 returnValue = 1;
1567                 count = 0;
1568             }
1569             sbp = netiring.consume;
1570             scc = ring_full_consecutive(&netiring);
1571             if (scc == 0) {
1572                 /* No more data coming in */
1573                 break;
1574             }
1575         }
1576
1577         c = *sbp++ & 0xff, scc--; count++;
1578 #if     defined(ENCRYPTION)
1579         if (decrypt_input)
1580                 c = (*decrypt_input)(c);
1581 #endif
1582
1583         switch (telrcv_state) {
1584
1585         case TS_CR:
1586             telrcv_state = TS_DATA;
1587             if (c == '\0') {
1588                 break;  /* Ignore \0 after CR */
1589             }
1590             else if ((c == '\n') && my_want_state_is_dont(TELOPT_ECHO) && !crmod) {
1591                 TTYADD(c);
1592                 break;
1593             }
1594             /* Else, fall through */
1595
1596         case TS_DATA:
1597             if (c == IAC) {
1598                 telrcv_state = TS_IAC;
1599                 break;
1600             }
1601                     /* 
1602                      * The 'crmod' hack (see following) is needed
1603                      * since we can't set CRMOD on output only.
1604                      * Machines like MULTICS like to send \r without
1605                      * \n; since we must turn off CRMOD to get proper
1606                      * input, the mapping is done here (sigh).
1607                      */
1608             if ((c == '\r') && my_want_state_is_dont(TELOPT_BINARY)) {
1609                 if (scc > 0) {
1610                     c = *sbp&0xff;
1611 #if     defined(ENCRYPTION)
1612                     if (decrypt_input)
1613                         c = (*decrypt_input)(c);
1614 #endif
1615                     if (c == 0) {
1616                         sbp++, scc--; count++;
1617                         /* a "true" CR */
1618                         TTYADD('\r');
1619                     } else if (my_want_state_is_dont(TELOPT_ECHO) &&
1620                                         (c == '\n')) {
1621                         sbp++, scc--; count++;
1622                         TTYADD('\n');
1623                     } else {
1624 #if     defined(ENCRYPTION)
1625                         if (decrypt_input)
1626                             (*decrypt_input)(-1);
1627 #endif
1628
1629                         TTYADD('\r');
1630                         if (crmod) {
1631                                 TTYADD('\n');
1632                         }
1633                     }
1634                 } else {
1635                     telrcv_state = TS_CR;
1636                     TTYADD('\r');
1637                     if (crmod) {
1638                             TTYADD('\n');
1639                     }
1640                 }
1641             } else {
1642                 TTYADD(c);
1643             }
1644             continue;
1645
1646         case TS_IAC:
1647 process_iac:
1648             switch (c) {
1649
1650             case WILL:
1651                 telrcv_state = TS_WILL;
1652                 continue;
1653
1654             case WONT:
1655                 telrcv_state = TS_WONT;
1656                 continue;
1657
1658             case DO:
1659                 telrcv_state = TS_DO;
1660                 continue;
1661
1662             case DONT:
1663                 telrcv_state = TS_DONT;
1664                 continue;
1665
1666             case DM:
1667                     /*
1668                      * We may have missed an urgent notification,
1669                      * so make sure we flush whatever is in the
1670                      * buffer currently.
1671                      */
1672                 printoption("RCVD", IAC, DM);
1673                 SYNCHing = 1;
1674                 ttyflush(1);
1675                 SYNCHing = stilloob();
1676                 settimer(gotDM);
1677                 break;
1678
1679             case SB:
1680                 SB_CLEAR();
1681                 telrcv_state = TS_SB;
1682                 continue;
1683
1684
1685             case IAC:
1686                 TTYADD(IAC);
1687                 break;
1688
1689             case NOP:
1690             case GA:
1691             default:
1692                 printoption("RCVD", IAC, c);
1693                 break;
1694             }
1695             telrcv_state = TS_DATA;
1696             continue;
1697
1698         case TS_WILL:
1699             printoption("RCVD", WILL, c);
1700             willoption(c);
1701             telrcv_state = TS_DATA;
1702             continue;
1703
1704         case TS_WONT:
1705             printoption("RCVD", WONT, c);
1706             wontoption(c);
1707             telrcv_state = TS_DATA;
1708             continue;
1709
1710         case TS_DO:
1711             printoption("RCVD", DO, c);
1712             dooption(c);
1713             if (c == TELOPT_NAWS) {
1714                 sendnaws();
1715             } else if (c == TELOPT_LFLOW) {
1716                 localflow = 1;
1717                 setcommandmode();
1718                 setconnmode(0);
1719             }
1720             telrcv_state = TS_DATA;
1721             continue;
1722
1723         case TS_DONT:
1724             printoption("RCVD", DONT, c);
1725             dontoption(c);
1726             flushline = 1;
1727             setconnmode(0);     /* set new tty mode (maybe) */
1728             telrcv_state = TS_DATA;
1729             continue;
1730
1731         case TS_SB:
1732             if (c == IAC) {
1733                 telrcv_state = TS_SE;
1734             } else {
1735                 SB_ACCUM(c);
1736             }
1737             continue;
1738
1739         case TS_SE:
1740             if (c != SE) {
1741                 if (c != IAC) {
1742                     /*
1743                      * This is an error.  We only expect to get
1744                      * "IAC IAC" or "IAC SE".  Several things may
1745                      * have happend.  An IAC was not doubled, the
1746                      * IAC SE was left off, or another option got
1747                      * inserted into the suboption are all possibilities.
1748                      * If we assume that the IAC was not doubled,
1749                      * and really the IAC SE was left off, we could
1750                      * get into an infinate loop here.  So, instead,
1751                      * we terminate the suboption, and process the
1752                      * partial suboption if we can.
1753                      */
1754                     SB_ACCUM(IAC);
1755                     SB_ACCUM(c);
1756                     subpointer -= 2;
1757                     SB_TERM();
1758
1759                     printoption("In SUBOPTION processing, RCVD", IAC, c);
1760                     suboption();        /* handle sub-option */
1761                     telrcv_state = TS_IAC;
1762                     goto process_iac;
1763                 }
1764                 SB_ACCUM(c);
1765                 telrcv_state = TS_SB;
1766             } else {
1767                 SB_ACCUM(IAC);
1768                 SB_ACCUM(SE);
1769                 subpointer -= 2;
1770                 SB_TERM();
1771                 suboption();    /* handle sub-option */
1772                 telrcv_state = TS_DATA;
1773             }
1774         }
1775     }
1776     if (count)
1777         ring_consumed(&netiring, count);
1778     return returnValue||count;
1779 }
1780
1781 static int bol = 1, local = 0;
1782
1783 int
1784 rlogin_susp(void)
1785 {
1786     if (local) {
1787         local = 0;
1788         bol = 1;
1789         command(0, "z\n", 2);
1790         return(1);
1791     }
1792     return(0);
1793 }
1794
1795 static int
1796 telsnd()
1797 {
1798     int tcc;
1799     int count;
1800     int returnValue = 0;
1801     unsigned char *tbp = NULL;
1802
1803     tcc = 0;
1804     count = 0;
1805     while (NETROOM() > 2) {
1806         int sc;
1807         int c;
1808
1809         if (tcc == 0) {
1810             if (count) {
1811                 ring_consumed(&ttyiring, count);
1812                 returnValue = 1;
1813                 count = 0;
1814             }
1815             tbp = ttyiring.consume;
1816             tcc = ring_full_consecutive(&ttyiring);
1817             if (tcc == 0) {
1818                 break;
1819             }
1820         }
1821         c = *tbp++ & 0xff, sc = strip(c), tcc--; count++;
1822         if (rlogin != _POSIX_VDISABLE) {
1823                 if (bol) {
1824                         bol = 0;
1825                         if (sc == rlogin) {
1826                                 local = 1;
1827                                 continue;
1828                         }
1829                 } else if (local) {
1830                         local = 0;
1831                         if (sc == '.' || c == termEofChar) {
1832                                 bol = 1;
1833                                 command(0, "close\n", 6);
1834                                 continue;
1835                         }
1836                         if (sc == termSuspChar) {
1837                                 bol = 1;
1838                                 command(0, "z\n", 2);
1839                                 continue;
1840                         }
1841                         if (sc == escape) {
1842                                 command(0, (char *)tbp, tcc);
1843                                 bol = 1;
1844                                 count += tcc;
1845                                 tcc = 0;
1846                                 flushline = 1;
1847                                 break;
1848                         }
1849                         if (sc != rlogin) {
1850                                 ++tcc;
1851                                 --tbp;
1852                                 --count;
1853                                 c = sc = rlogin;
1854                         }
1855                 }
1856                 if ((sc == '\n') || (sc == '\r'))
1857                         bol = 1;
1858         } else if (sc == escape) {
1859             /*
1860              * Double escape is a pass through of a single escape character.
1861              */
1862             if (tcc && strip(*tbp) == escape) {
1863                 tbp++;
1864                 tcc--;
1865                 count++;
1866                 bol = 0;
1867             } else {
1868                 command(0, (char *)tbp, tcc);
1869                 bol = 1;
1870                 count += tcc;
1871                 tcc = 0;
1872                 flushline = 1;
1873                 break;
1874             }
1875         } else
1876             bol = 0;
1877 #ifdef  KLUDGELINEMODE
1878         if (kludgelinemode && (globalmode&MODE_EDIT) && (sc == echoc)) {
1879             if (tcc > 0 && strip(*tbp) == echoc) {
1880                 tcc--; tbp++; count++;
1881             } else {
1882                 dontlecho = !dontlecho;
1883                 settimer(echotoggle);
1884                 setconnmode(0);
1885                 flushline = 1;
1886                 break;
1887             }
1888         }
1889 #endif
1890         if (MODE_LOCAL_CHARS(globalmode)) {
1891             if (TerminalSpecialChars(sc) == 0) {
1892                 bol = 1;
1893                 break;
1894             }
1895         }
1896         if (my_want_state_is_wont(TELOPT_BINARY)) {
1897             switch (c) {
1898             case '\n':
1899                     /*
1900                      * If we are in CRMOD mode (\r ==> \n)
1901                      * on our local machine, then probably
1902                      * a newline (unix) is CRLF (TELNET).
1903                      */
1904                 if (MODE_LOCAL_CHARS(globalmode)) {
1905                     NETADD('\r');
1906                 }
1907                 NETADD('\n');
1908                 bol = flushline = 1;
1909                 break;
1910             case '\r':
1911                 if (!crlf) {
1912                     NET2ADD('\r', '\0');
1913                 } else {
1914                     NET2ADD('\r', '\n');
1915                 }
1916                 bol = flushline = 1;
1917                 break;
1918             case IAC:
1919                 NET2ADD(IAC, IAC);
1920                 break;
1921             default:
1922                 NETADD(c);
1923                 break;
1924             }
1925         } else if (c == IAC) {
1926             NET2ADD(IAC, IAC);
1927         } else {
1928             NETADD(c);
1929         }
1930     }
1931     if (count)
1932         ring_consumed(&ttyiring, count);
1933     return returnValue||count;          /* Non-zero if we did anything */
1934 }
1935
1936 /*
1937  * Scheduler()
1938  *
1939  * Try to do something.
1940  *
1941  * If we do something useful, return 1; else return 0.
1942  *
1943  */
1944
1945
1946 static int
1947 Scheduler(int block) /* should we block in the select ? */
1948 {
1949                 /* One wants to be a bit careful about setting returnValue
1950                  * to one, since a one implies we did some useful work,
1951                  * and therefore probably won't be called to block next
1952                  * time (TN3270 mode only).
1953                  */
1954     int returnValue;
1955     int netin, netout, netex, ttyin, ttyout;
1956
1957     /* Decide which rings should be processed */
1958
1959     netout = ring_full_count(&netoring) &&
1960             (flushline ||
1961                 (my_want_state_is_wont(TELOPT_LINEMODE)
1962 #ifdef  KLUDGELINEMODE
1963                         && (!kludgelinemode || my_want_state_is_do(TELOPT_SGA))
1964 #endif
1965                 ) ||
1966                         my_want_state_is_will(TELOPT_BINARY));
1967     ttyout = ring_full_count(&ttyoring);
1968
1969     ttyin = ring_empty_count(&ttyiring);
1970
1971     netin = !ISend && ring_empty_count(&netiring);
1972
1973     netex = !SYNCHing;
1974
1975     /* If we have seen a signal recently, reset things */
1976
1977     /* Call to system code to process rings */
1978
1979     returnValue = process_rings(netin, netout, netex, ttyin, ttyout, !block);
1980
1981     /* Now, look at the input rings, looking for work to do. */
1982
1983     if (ring_full_count(&ttyiring)) {
1984             returnValue |= telsnd();
1985     }
1986
1987     if (ring_full_count(&netiring)) {
1988         returnValue |= telrcv();
1989     }
1990     return returnValue;
1991 }
1992
1993 /*
1994  * Select from tty and network...
1995  */
1996 void
1997 my_telnet(char *user)
1998 {
1999     sys_telnet_init();
2000
2001 #if     defined(AUTHENTICATION) || defined(ENCRYPTION)
2002     {
2003         static char local_host[256] = { 0 };
2004
2005         if (!local_host[0]) {
2006                 /* XXX - should be k_gethostname? */
2007                 gethostname(local_host, sizeof(local_host));
2008                 local_host[sizeof(local_host)-1] = 0;
2009         }
2010         auth_encrypt_init(local_host, hostname, "TELNET", 0);
2011         auth_encrypt_user(user);
2012     }
2013 #endif
2014     if (telnetport) {
2015 #if     defined(AUTHENTICATION)
2016         if (autologin)
2017                 send_will(TELOPT_AUTHENTICATION, 1);
2018 #endif
2019 #if     defined(ENCRYPTION)
2020         send_do(TELOPT_ENCRYPT, 1);
2021         send_will(TELOPT_ENCRYPT, 1);
2022 #endif
2023         send_do(TELOPT_SGA, 1);
2024         send_will(TELOPT_TTYPE, 1);
2025         send_will(TELOPT_NAWS, 1);
2026         send_will(TELOPT_TSPEED, 1);
2027         send_will(TELOPT_LFLOW, 1);
2028         send_will(TELOPT_LINEMODE, 1);
2029         send_will(TELOPT_NEW_ENVIRON, 1);
2030         send_do(TELOPT_STATUS, 1);
2031         if (env_getvalue((unsigned char *)"DISPLAY"))
2032             send_will(TELOPT_XDISPLOC, 1);
2033         if (binary)
2034             tel_enter_binary(binary);
2035     }
2036
2037     for (;;) {
2038         int schedValue;
2039
2040         while ((schedValue = Scheduler(0)) != 0) {
2041             if (schedValue == -1) {
2042                 setcommandmode();
2043                 return;
2044             }
2045         }
2046
2047         if (Scheduler(1) == -1) {
2048             setcommandmode();
2049             return;
2050         }
2051     }
2052 }
2053
2054 /*
2055  * netclear()
2056  *
2057  *      We are about to do a TELNET SYNCH operation.  Clear
2058  * the path to the network.
2059  *
2060  *      Things are a bit tricky since we may have sent the first
2061  * byte or so of a previous TELNET command into the network.
2062  * So, we have to scan the network buffer from the beginning
2063  * until we are up to where we want to be.
2064  *
2065  *      A side effect of what we do, just to keep things
2066  * simple, is to clear the urgent data pointer.  The principal
2067  * caller should be setting the urgent data pointer AFTER calling
2068  * us in any case.
2069  */
2070
2071 static void
2072 netclear()
2073 {
2074 #if     0       /* XXX */
2075     char *thisitem, *next;
2076     char *good;
2077 #define wewant(p)       ((nfrontp > p) && ((*p&0xff) == IAC) && \
2078                                 ((*(p+1)&0xff) != EC) && ((*(p+1)&0xff) != EL))
2079
2080     thisitem = netobuf;
2081
2082     while ((next = nextitem(thisitem)) <= netobuf.send) {
2083         thisitem = next;
2084     }
2085
2086     /* Now, thisitem is first before/at boundary. */
2087
2088     good = netobuf;     /* where the good bytes go */
2089
2090     while (netoring.add > thisitem) {
2091         if (wewant(thisitem)) {
2092             int length;
2093
2094             next = thisitem;
2095             do {
2096                 next = nextitem(next);
2097             } while (wewant(next) && (nfrontp > next));
2098             length = next-thisitem;
2099             memmove(good, thisitem, length);
2100             good += length;
2101             thisitem = next;
2102         } else {
2103             thisitem = nextitem(thisitem);
2104         }
2105     }
2106
2107 #endif  /* 0 */
2108 }
2109
2110 /*
2111  * These routines add various telnet commands to the data stream.
2112  */
2113
2114 static void
2115 doflush()
2116 {
2117     NET2ADD(IAC, DO);
2118     NETADD(TELOPT_TM);
2119     flushline = 1;
2120     flushout = 1;
2121     ttyflush(1);                        /* Flush/drop output */
2122     /* do printoption AFTER flush, otherwise the output gets tossed... */
2123     printoption("SENT", DO, TELOPT_TM);
2124 }
2125
2126 void
2127 xmitAO(void)
2128 {
2129     NET2ADD(IAC, AO);
2130     printoption("SENT", IAC, AO);
2131     if (autoflush) {
2132         doflush();
2133     }
2134 }
2135
2136
2137 void
2138 xmitEL(void)
2139 {
2140     NET2ADD(IAC, EL);
2141     printoption("SENT", IAC, EL);
2142 }
2143
2144 void
2145 xmitEC(void)
2146 {
2147     NET2ADD(IAC, EC);
2148     printoption("SENT", IAC, EC);
2149 }
2150
2151
2152 int
2153 dosynch()
2154 {
2155     netclear();                 /* clear the path to the network */
2156     NETADD(IAC);
2157     setneturg();
2158     NETADD(DM);
2159     printoption("SENT", IAC, DM);
2160     return 1;
2161 }
2162
2163 int want_status_response = 0;
2164
2165 int
2166 get_status()
2167 {
2168     unsigned char tmp[16];
2169     unsigned char *cp;
2170
2171     if (my_want_state_is_dont(TELOPT_STATUS)) {
2172         printf("Remote side does not support STATUS option\n");
2173         return 0;
2174     }
2175     cp = tmp;
2176
2177     *cp++ = IAC;
2178     *cp++ = SB;
2179     *cp++ = TELOPT_STATUS;
2180     *cp++ = TELQUAL_SEND;
2181     *cp++ = IAC;
2182     *cp++ = SE;
2183     if (NETROOM() >= cp - tmp) {
2184         ring_supply_data(&netoring, tmp, cp-tmp);
2185         printsub('>', tmp+2, cp - tmp - 2);
2186     }
2187     ++want_status_response;
2188     return 1;
2189 }
2190
2191 void
2192 intp(void)
2193 {
2194     NET2ADD(IAC, IP);
2195     printoption("SENT", IAC, IP);
2196     flushline = 1;
2197     if (autoflush) {
2198         doflush();
2199     }
2200     if (autosynch) {
2201         dosynch();
2202     }
2203 }
2204
2205 void
2206 sendbrk(void)
2207 {
2208     NET2ADD(IAC, BREAK);
2209     printoption("SENT", IAC, BREAK);
2210     flushline = 1;
2211     if (autoflush) {
2212         doflush();
2213     }
2214     if (autosynch) {
2215         dosynch();
2216     }
2217 }
2218
2219 void
2220 sendabort(void)
2221 {
2222     NET2ADD(IAC, ABORT);
2223     printoption("SENT", IAC, ABORT);
2224     flushline = 1;
2225     if (autoflush) {
2226         doflush();
2227     }
2228     if (autosynch) {
2229         dosynch();
2230     }
2231 }
2232
2233 void
2234 sendsusp(void)
2235 {
2236     NET2ADD(IAC, SUSP);
2237     printoption("SENT", IAC, SUSP);
2238     flushline = 1;
2239     if (autoflush) {
2240         doflush();
2241     }
2242     if (autosynch) {
2243         dosynch();
2244     }
2245 }
2246
2247 void
2248 sendeof(void)
2249 {
2250     NET2ADD(IAC, xEOF);
2251     printoption("SENT", IAC, xEOF);
2252 }
2253
2254 void
2255 sendayt(void)
2256 {
2257     NET2ADD(IAC, AYT);
2258     printoption("SENT", IAC, AYT);
2259 }
2260
2261 /*
2262  * Send a window size update to the remote system.
2263  */
2264
2265 void
2266 sendnaws()
2267 {
2268     long rows, cols;
2269     unsigned char tmp[16];
2270     unsigned char *cp;
2271
2272     if (my_state_is_wont(TELOPT_NAWS))
2273         return;
2274
2275 #define PUTSHORT(cp, x) { if ((*cp++ = ((x)>>8)&0xff) == IAC) *cp++ = IAC; \
2276                             if ((*cp++ = ((x))&0xff) == IAC) *cp++ = IAC; }
2277
2278     if (TerminalWindowSize(&rows, &cols) == 0) {        /* Failed */
2279         return;
2280     }
2281
2282     cp = tmp;
2283
2284     *cp++ = IAC;
2285     *cp++ = SB;
2286     *cp++ = TELOPT_NAWS;
2287     PUTSHORT(cp, cols);
2288     PUTSHORT(cp, rows);
2289     *cp++ = IAC;
2290     *cp++ = SE;
2291     if (NETROOM() >= cp - tmp) {
2292         ring_supply_data(&netoring, tmp, cp-tmp);
2293         printsub('>', tmp+2, cp - tmp - 2);
2294     }
2295 }
2296
2297 void
2298 tel_enter_binary(int rw)
2299 {
2300     if (rw&1)
2301         send_do(TELOPT_BINARY, 1);
2302     if (rw&2)
2303         send_will(TELOPT_BINARY, 1);
2304 }
2305
2306 void
2307 tel_leave_binary(int rw)
2308 {
2309     if (rw&1)
2310         send_dont(TELOPT_BINARY, 1);
2311     if (rw&2)
2312         send_wont(TELOPT_BINARY, 1);
2313 }