BSD 4_3_Net_2 release
[unix-history] / usr / src / usr.bin / telnet / telnet.c
index 93d274e..46a980c 100644 (file)
 /*
 /*
- * Copyright (c) 1983 Regents of the University of California.
- * All rights reserved.  The Berkeley software License Agreement
- * specifies the terms and conditions for redistribution.
+ * Copyright (c) 1988, 1990 Regents of the University of California.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 4. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
 
 #ifndef lint
  */
 
 #ifndef lint
-char copyright[] =
-"@(#) Copyright (c) 1983 Regents of the University of California.\n\
- All rights reserved.\n";
-#endif not lint
-
-#ifndef lint
-static char sccsid[] = "@(#)telnet.c   5.12 (Berkeley) 4/22/86";
-#endif not lint
+static char sccsid[] = "@(#)telnet.c   5.53 (Berkeley) 3/22/91";
+#endif /* not lint */
 
 
-/*
- * User telnet program.
- */
 #include <sys/types.h>
 #include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/ioctl.h>
-#include <sys/time.h>
 
 
-#include <netinet/in.h>
+#if    defined(unix)
+#include <signal.h>
+/* By the way, we need to include curses.h before telnet.h since,
+ * among other things, telnet.h #defines 'DO', which is a variable
+ * declared in curses.h.
+ */
+#endif /* defined(unix) */
 
 
-#define        TELOPTS
 #include <arpa/telnet.h>
 #include <arpa/telnet.h>
-#include <arpa/inet.h>
 
 
-#include <stdio.h>
 #include <ctype.h>
 #include <ctype.h>
-#include <errno.h>
-#include <signal.h>
-#include <setjmp.h>
-#include <netdb.h>
-#include <strings.h>
-
 
 
+#include "ring.h"
 
 
-#ifndef        FD_SETSIZE
-/*
- * The following is defined just in case someone should want to run
- * this telnet on a 4.2 system.
- *
- */
-
-#define        FD_SET(n, p)    ((p)->fds_bits[0] |= (1<<(n)))
-#define        FD_CLR(n, p)    ((p)->fds_bits[0] &= ~(1<<(n)))
-#define        FD_ISSET(n, p)  ((p)->fds_bits[0] & (1<<(n)))
-#define FD_ZERO(p)     ((p)->fds_bits[0] = 0)
+#include "defines.h"
+#include "externs.h"
+#include "types.h"
+#include "general.h"
 
 
-#endif
 \f
 #define        strip(x)        ((x)&0x7f)
 
 \f
 #define        strip(x)        ((x)&0x7f)
 
-char   ttyobuf[2*BUFSIZ], *tfrontp = ttyobuf, *tbackp = ttyobuf;
-#define        TTYADD(c)       { if (!(SYNCHing||flushout)) { *tfrontp++ = c; } }
-#define        TTYLOC()        (tfrontp)
-#define        TTYMAX()        (ttyobuf+sizeof ttyobuf-1)
-#define        TTYMIN()        (netobuf)
-#define        TTYBYTES()      (tfrontp-tbackp)
-#define        TTYROOM()       (TTYMAX()-TTYLOC()+1)
-
-char   netobuf[2*BUFSIZ], *nfrontp = netobuf, *nbackp = netobuf;
-#define        NETADD(c)       { *nfrontp++ = c; }
-#define        NET2ADD(c1,c2)  { NETADD(c1); NETADD(c2); }
-#define NETLOC()       (nfrontp)
-#define        NETMAX()        (netobuf+sizeof netobuf-1)
-#define        NETBYTES()      (nfrontp-nbackp)
-#define        NETROOM()       (NETMAX()-NETLOC()+1)
-char   *neturg = 0;            /* one past last byte of urgent data */
-
-char   subbuffer[100], *subpointer, *subend;   /* buffer for sub-options */
+static unsigned char   subbuffer[SUBBUFSIZE],
+                       *subpointer, *subend;    /* buffer for sub-options */
 #define        SB_CLEAR()      subpointer = subbuffer;
 #define        SB_CLEAR()      subpointer = subbuffer;
-#define        SB_TERM()       subend = subpointer;
+#define        SB_TERM()       { subend = subpointer; SB_CLEAR(); }
 #define        SB_ACCUM(c)     if (subpointer < (subbuffer+sizeof subbuffer)) { \
                                *subpointer++ = (c); \
                        }
 
 #define        SB_ACCUM(c)     if (subpointer < (subbuffer+sizeof subbuffer)) { \
                                *subpointer++ = (c); \
                        }
 
-char   hisopts[256];
-char   myopts[256];
-
-char   doopt[] = { IAC, DO, '%', 'c', 0 };
-char   dont[] = { IAC, DONT, '%', 'c', 0 };
-char   will[] = { IAC, WILL, '%', 'c', 0 };
-char   wont[] = { IAC, WONT, '%', 'c', 0 };
+#define        SB_GET()        ((*subpointer++)&0xff)
+#define        SB_PEEK()       ((*subpointer)&0xff)
+#define        SB_EOF()        (subpointer >= subend)
+#define        SB_LEN()        (subend - subpointer)
 
 
-struct cmd {
-       char    *name;          /* command name */
-       char    *help;          /* help string */
-       int     (*handler)();   /* routine which executes command */
-       int     dohelp;         /* Should we give general help information? */
-       int     needconnect;    /* Do we need to be connected to execute? */
-};
-
-int    connected;
-int    net;
-int    tout;
-int    showoptions = 0;
-int    debug = 0;
-int    crmod = 0;
-int    netdata = 0;
-static FILE    *NetTrace;
-int    telnetport = 1;
-
-
-char   *prompt;
-char   escape = CTRL(]);
-char   echoc = CTRL(E);
-
-int    SYNCHing = 0;           /* we are in TELNET SYNCH mode */
-int    flushout = 0;           /* flush output */
-int    autoflush = 0;          /* flush output when interrupting? */
-int    autosynch = 0;          /* send interrupt characters with SYNCH? */
-int    localchars = 0;         /* we recognize interrupt/quit */
-int    donelclchars = 0;       /* the user has set "localchars" */
-int    dontlecho = 0;          /* do we suppress local echoing right now? */
-
-char   line[200];
-int    margc;
-char   *margv[20];
-
-jmp_buf        toplevel;
-jmp_buf        peerdied;
+char   options[256];           /* The combined options */
+char   do_dont_resp[256];
+char   will_wont_resp[256];
 
 
-extern int errno;
+int
+       eight = 0,
+       autologin = 0,  /* Autologin anyone? */
+       skiprc = 0,
+       connected,
+       showoptions,
+       In3270,         /* Are we in 3270 mode? */
+       ISend,          /* trying to send network data in */
+       debug = 0,
+       crmod,
+       netdata,        /* Print out network data flow */
+       crlf,           /* Should '\r' be mapped to <CR><LF> (or <CR><NUL>)? */
+#if    defined(TN3270)
+       noasynchtty = 0,/* User specified "-noasynch" on command line */
+       noasynchnet = 0,/* User specified "-noasynch" on command line */
+       askedSGA = 0,   /* We have talked about suppress go ahead */
+#endif /* defined(TN3270) */
+       telnetport,
+       SYNCHing,       /* we are in TELNET SYNCH mode */
+       flushout,       /* flush output */
+       autoflush = 0,  /* flush output when interrupting? */
+       autosynch,      /* send interrupt characters with SYNCH? */
+       localflow,      /* we handle flow control locally */
+       localchars,     /* we recognize interrupt/quit */
+       donelclchars,   /* the user has set "localchars" */
+       donebinarytoggle,       /* the user has put us in binary */
+       dontlecho,      /* do we suppress local echoing right now? */
+       globalmode;
+
+char *prompt = 0;
+
+cc_t escape;
+cc_t rlogin;
+#ifdef KLUDGELINEMODE
+cc_t echoc;
+#endif
 
 
+/*
+ * Telnet receiver states for fsm
+ */
+#define        TS_DATA         0
+#define        TS_IAC          1
+#define        TS_WILL         2
+#define        TS_WONT         3
+#define        TS_DO           4
+#define        TS_DONT         5
+#define        TS_CR           6
+#define        TS_SB           7               /* sub-option collection */
+#define        TS_SE           8               /* looking for sub-option end */
 
 
-struct sockaddr_in sin;
+static int     telrcv_state;
 
 
-struct cmd *getcmd();
-struct servent *sp;
+jmp_buf        toplevel = { 0 };
+jmp_buf        peerdied;
 
 
-struct tchars otc, ntc;
-struct ltchars oltc, nltc;
-struct sgttyb ottyb, nttyb;
-int    globalmode = 0;
-int    flushline = 1;
+int    flushline;
+int    linemode;
 
 
-char   *hostname;
-char   hnamebuf[32];
+#ifdef KLUDGELINEMODE
+int    kludgelinemode = 1;
+#endif
 
 /*
  * The following are some clocks used to decide how to interpret
  * the relationship between various variables.
  */
 
 
 /*
  * The following are some clocks used to decide how to interpret
  * the relationship between various variables.
  */
 
-struct {
-    int
-       system,                 /* what the current time is */
-       echotoggle,             /* last time user entered echo character */
-       modenegotiated,         /* last time operating mode negotiated */
-       didnetreceive,          /* last time we read data from network */
-       gotDM;                  /* when did we last see a data mark */
-} clocks;
-
-#define        settimer(x)     clocks.x = clocks.system++
+Clocks clocks;
+\f
+#ifdef notdef
+Modelist modelist[] = {
+       { "telnet command mode", COMMAND_LINE },
+       { "character-at-a-time mode", 0 },
+       { "character-at-a-time mode (local echo)", LOCAL_ECHO|LOCAL_CHARS },
+       { "line-by-line mode (remote echo)", LINE | LOCAL_CHARS },
+       { "line-by-line mode", LINE | LOCAL_ECHO | LOCAL_CHARS },
+       { "line-by-line mode (local echoing suppressed)", LINE | LOCAL_CHARS },
+       { "3270 mode", 0 },
+};
+#endif
+
 \f
 /*
 \f
 /*
- * Various utility routines.
+ * Initialize telnet environment.
  */
 
  */
 
-char *ambiguous;               /* special return value */
-#define Ambiguous(t)   ((t)&ambiguous)
+    void
+init_telnet()
+{
+    env_init();
 
 
+    SB_CLEAR();
+    ClearArray(options);
 
 
-char **
-genget(name, table, next)
-char   *name;          /* name to match */
-char   **table;                /* name entry in table */
-char   **(*next)();    /* routine to return next entry in table */
-{
-       register char *p, *q;
-       register char **c, **found;
-       register int nmatches, longest;
-
-       longest = 0;
-       nmatches = 0;
-       found = 0;
-       for (c = table; p = *c; c = (*next)(c)) {
-               for (q = name; *q == *p++; q++)
-                       if (*q == 0)            /* exact match? */
-                               return (c);
-               if (!*q) {                      /* the name was a prefix */
-                       if (q - name > longest) {
-                               longest = q - name;
-                               nmatches = 1;
-                               found = c;
-                       } else if (q - name == longest)
-                               nmatches++;
-               }
-       }
-       if (nmatches > 1)
-               return Ambiguous(char **);
-       return (found);
-}
+    connected = In3270 = ISend = localflow = donebinarytoggle = 0;
+#if    defined(ENCRYPT) || defined(AUTHENTICATE)
+    auth_encrypt_connect(connected);
+#endif
 
 
-/*
- * Make a character string into a number.
- *
- * Todo:  1.  Could take random integers (12, 0x12, 012, 0b1).
- */
+    SYNCHing = 0;
 
 
-special(s)
-register char *s;
-{
-       register char c;
-       char b;
-
-       switch (*s) {
-       case '^':
-               b = *++s;
-               if (b == '?') {
-                   c = b | 0x40;               /* DEL */
-               } else {
-                   c = b & 0x1f;
-               }
-               break;
-       default:
-               c = *s;
-               break;
-       }
-       return c;
+    /* Don't change NetTrace */
+
+    escape = CONTROL(']');
+    rlogin = _POSIX_VDISABLE;
+#ifdef KLUDGELINEMODE
+    echoc = CONTROL('E');
+#endif
+
+    flushline = 1;
+    telrcv_state = TS_DATA;
 }
 }
+\f
 
 
-/*
- * Construct a control character sequence
- * for a special character.
- */
-char *
-control(c)
-       register int c;
+#ifdef notdef
+#include <varargs.h>
+
   /*VARARGS*/
+    static void
+printring(va_alist)
+    va_dcl
 {
 {
-       static char buf[3];
+    va_list ap;
+    char buffer[100];          /* where things go */
+    char *ptr;
+    char *format;
+    char *string;
+    Ring *ring;
+    int i;
 
 
-       if (c == 0x7f)
-               return ("^?");
-       if (c == '\377') {
-               return "off";
-       }
-       if (c >= 0x20) {
-               buf[0] = c;
-               buf[1] = 0;
+    va_start(ap);
+
+    ring = va_arg(ap, Ring *);
+    format = va_arg(ap, char *);
+    ptr = buffer;
+
+    while ((i = *format++) != 0) {
+       if (i == '%') {
+           i = *format++;
+           switch (i) {
+           case 'c':
+               *ptr++ = va_arg(ap, int);
+               break;
+           case 's':
+               string = va_arg(ap, char *);
+               ring_supply_data(ring, buffer, ptr-buffer);
+               ring_supply_data(ring, string, strlen(string));
+               ptr = buffer;
+               break;
+           case 0:
+               ExitString("printring: trailing %%.\n", 1);
+               /*NOTREACHED*/
+           default:
+               ExitString("printring: unknown format character.\n", 1);
+               /*NOTREACHED*/
+           }
        } else {
        } else {
-               buf[0] = '^';
-               buf[1] = '@'+c;
-               buf[2] = 0;
+           *ptr++ = i;
        }
        }
-       return (buf);
+    }
+    ring_supply_data(ring, buffer, ptr-buffer);
 }
 }
-
+#endif
 
 /*
 
 /*
- * upcase()
+ * These routines are in charge of sending option negotiations
+ * to the other side.
  *
  *
- *     Upcase (in place) the argument.
+ * The basic idea is that we send the negotiation if either side
+ * is in disagreement as to what the current state should be.
  */
 
  */
 
-void
-upcase(argument)
-register char *argument;
+    void
+send_do(c, init)
+    register int c, init;
 {
 {
-    register int c;
+    if (init) {
+       if (((do_dont_resp[c] == 0) && my_state_is_do(c)) ||
+                               my_want_state_is_do(c))
+           return;
+       set_my_want_state_do(c);
+       do_dont_resp[c]++;
+    }
+    NET2ADD(IAC, DO);
+    NETADD(c);
+    printoption("SENT", DO, c);
+}
 
 
-    while (c = *argument) {
-       if (islower(c)) {
-           *argument = toupper(c);
-       }
-       argument++;
+    void
+send_dont(c, init)
+    register int c, init;
+{
+    if (init) {
+       if (((do_dont_resp[c] == 0) && my_state_is_dont(c)) ||
+                               my_want_state_is_dont(c))
+           return;
+       set_my_want_state_dont(c);
+       do_dont_resp[c]++;
     }
     }
+    NET2ADD(IAC, DONT);
+    NETADD(c);
+    printoption("SENT", DONT, c);
 }
 }
-\f
-/*
- * Check to see if any out-of-band data exists on a socket (for
- * Telnet "synch" processing).
- */
 
 
-int
-stilloob(s)
-int    s;              /* socket number */
+    void
+send_will(c, init)
+    register int c, init;
 {
 {
-    static struct timeval timeout = { 0 };
-    fd_set     excepts;
-    int value;
-
-    do {
-       FD_ZERO(&excepts);
-       FD_SET(s, &excepts);
-       value = select(s+1, (fd_set *)0, (fd_set *)0, &excepts, &timeout);
-    } while ((value == -1) && (errno = EINTR));
-
-    if (value < 0) {
-       perror("select");
-       quit();
+    if (init) {
+       if (((will_wont_resp[c] == 0) && my_state_is_will(c)) ||
+                               my_want_state_is_will(c))
+           return;
+       set_my_want_state_will(c);
+       will_wont_resp[c]++;
     }
     }
-    if (FD_ISSET(s, &excepts)) {
-       return 1;
-    } else {
-       return 0;
+    NET2ADD(IAC, WILL);
+    NETADD(c);
+    printoption("SENT", WILL, c);
+}
+
+    void
+send_wont(c, init)
+    register int c, init;
+{
+    if (init) {
+       if (((will_wont_resp[c] == 0) && my_state_is_wont(c)) ||
+                               my_want_state_is_wont(c))
+           return;
+       set_my_want_state_wont(c);
+       will_wont_resp[c]++;
     }
     }
+    NET2ADD(IAC, WONT);
+    NETADD(c);
+    printoption("SENT", WONT, c);
 }
 
 
 }
 
 
-/*
- *  netflush
- *             Send as much data as possible to the network,
- *     handling requests for urgent data.
- */
+       void
+willoption(option)
+       int option;
+{
+       int new_state_ok = 0;
 
 
+       if (do_dont_resp[option]) {
+           --do_dont_resp[option];
+           if (do_dont_resp[option] && my_state_is_do(option))
+               --do_dont_resp[option];
+       }
 
 
-netflush(fd)
-{
-    int n;
+       if ((do_dont_resp[option] == 0) && my_want_state_is_dont(option)) {
 
 
-    if ((n = nfrontp - nbackp) > 0) {
-       if (!neturg) {
-           n = write(fd, nbackp, n);   /* normal write */
-       } else {
-           n = neturg - nbackp;
-           /*
-            * In 4.2 (and 4.3) systems, there is some question about
-            * what byte in a sendOOB operation is the "OOB" data.
-            * To make ourselves compatible, we only send ONE byte
-            * out of band, the one WE THINK should be OOB (though
-            * we really have more the TCP philosophy of urgent data
-            * rather than the Unix philosophy of OOB data).
-            */
-           if (n > 1) {
-               n = send(fd, nbackp, n-1, 0);   /* send URGENT all by itself */
+           switch (option) {
+
+           case TELOPT_ECHO:
+#          if defined(TN3270)
+               /*
+                * The following is a pain in the rear-end.
+                * Various IBM servers (some versions of Wiscnet,
+                * possibly Fibronics/Spartacus, and who knows who
+                * else) will NOT allow us to send "DO SGA" too early
+                * in the setup proceedings.  On the other hand,
+                * 4.2 servers (telnetd) won't set SGA correctly.
+                * So, we are stuck.  Empirically (but, based on
+                * a VERY small sample), the IBM servers don't send
+                * out anything about ECHO, so we postpone our sending
+                * "DO SGA" until we see "WILL ECHO" (which 4.2 servers
+                * DO send).
+                 */
+               {
+                   if (askedSGA == 0) {
+                       askedSGA = 1;
+                       if (my_want_state_is_dont(TELOPT_SGA))
+                           send_do(TELOPT_SGA, 1);
+                   }
+               }
+                   /* Fall through */
+           case TELOPT_EOR:
+#endif     /* defined(TN3270) */
+           case TELOPT_BINARY:
+           case TELOPT_SGA:
+               settimer(modenegotiated);
+               /* FALL THROUGH */
+           case TELOPT_STATUS:
+#if    defined(AUTHENTICATE)
+           case TELOPT_AUTHENTICATION:
+#endif
+#if    defined(ENCRYPT)
+           case TELOPT_ENCRYPT:
+#endif
+               new_state_ok = 1;
+               break;
+
+           case TELOPT_TM:
+               if (flushout)
+                   flushout = 0;
+               /*
+                * Special case for TM.  If we get back a WILL,
+                * pretend we got back a WONT.
+                */
+               set_my_want_state_dont(option);
+               set_my_state_dont(option);
+               return;                 /* Never reply to TM will's/wont's */
+
+           case TELOPT_LINEMODE:
+           default:
+               break;
+           }
+
+           if (new_state_ok) {
+               set_my_want_state_do(option);
+               send_do(option, 0);
+               setconnmode(0);         /* possibly set new tty mode */
            } else {
            } else {
-               n = send(fd, nbackp, n, MSG_OOB);       /* URGENT data */
+               do_dont_resp[option]++;
+               send_dont(option, 0);
            }
        }
            }
        }
-    }
-    if (n < 0) {
-       if (errno != ENOBUFS && errno != EWOULDBLOCK) {
-           setcommandmode();
-           perror(hostname);
-           close(fd);
-           neturg = 0;
-           longjmp(peerdied, -1);
-           /*NOTREACHED*/
-       }
-       n = 0;
-    }
-    if (netdata && n) {
-       Dump('>', nbackp, n);
-    }
-    nbackp += n;
-    if (nbackp >= neturg) {
-       neturg = 0;
-    }
-    if (nbackp == nfrontp) {
-       nbackp = nfrontp = netobuf;
-    }
+       set_my_state_do(option);
+#if    defined(ENCRYPT)
+       if (option == TELOPT_ENCRYPT)
+               encrypt_send_support();
+#endif
 }
 }
-\f
-/*
- * nextitem()
- *
- *     Return the address of the next "item" in the TELNET data
- * stream.  This will be the address of the next character if
- * the current address is a user data character, or it will
- * be the address of the character following the TELNET command
- * if the current address is a TELNET IAC ("I Am a Command")
- * character.
- */
 
 
-char *
-nextitem(current)
-char   *current;
+       void
+wontoption(option)
+       int option;
 {
 {
-    if ((*current&0xff) != IAC) {
-       return current+1;
-    }
-    switch (*(current+1)&0xff) {
-    case DO:
-    case DONT:
-    case WILL:
-    case WONT:
-       return current+3;
-    case SB:           /* loop forever looking for the SE */
-       {
-           register char *look = current+2;
+       if (do_dont_resp[option]) {
+           --do_dont_resp[option];
+           if (do_dont_resp[option] && my_state_is_dont(option))
+               --do_dont_resp[option];
+       }
 
 
-           for (;;) {
-               if ((*look++&0xff) == IAC) {
-                   if ((*look++&0xff) == SE) {
-                       return look;
-                   }
-               }
+       if ((do_dont_resp[option] == 0) && my_want_state_is_do(option)) {
+
+           switch (option) {
+
+#ifdef KLUDGELINEMODE
+           case TELOPT_SGA:
+               if (!kludgelinemode)
+                   break;
+               /* FALL THROUGH */
+#endif
+           case TELOPT_ECHO:
+               settimer(modenegotiated);
+               break;
+
+           case TELOPT_TM:
+               if (flushout)
+                   flushout = 0;
+               set_my_want_state_dont(option);
+               set_my_state_dont(option);
+               return;         /* Never reply to TM will's/wont's */
+
+           default:
+               break;
            }
            }
+           set_my_want_state_dont(option);
+           if (my_state_is_do(option))
+               send_dont(option, 0);
+           setconnmode(0);                     /* Set new tty mode */
+       } else if (option == TELOPT_TM) {
+           /*
+            * Special case for TM.
+            */
+           if (flushout)
+               flushout = 0;
+           set_my_want_state_dont(option);
        }
        }
-    default:
-       return current+2;
-    }
+       set_my_state_dont(option);
 }
 }
-/*
- * netclear()
- *
- *     We are about to do a TELNET SYNCH operation.  Clear
- * the path to the network.
- *
- *     Things are a bit tricky since we may have sent the first
- * byte or so of a previous TELNET command into the network.
- * So, we have to scan the network buffer from the beginning
- * until we are up to where we want to be.
- *
- *     A side effect of what we do, just to keep things
- * simple, is to clear the urgent data pointer.  The principal
- * caller should be setting the urgent data pointer AFTER calling
- * us in any case.
- */
 
 
-netclear()
+       static void
+dooption(option)
+       int option;
 {
 {
-    register char *thisitem, *next;
-    char *good;
-#define        wewant(p)       ((nfrontp > p) && ((*p&0xff) == IAC) && \
-                               ((*(p+1)&0xff) != EC) && ((*(p+1)&0xff) != EL))
+       int new_state_ok = 0;
 
 
-    thisitem = netobuf;
+       if (will_wont_resp[option]) {
+           --will_wont_resp[option];
+           if (will_wont_resp[option] && my_state_is_will(option))
+               --will_wont_resp[option];
+       }
 
 
-    while ((next = nextitem(thisitem)) <= nbackp) {
-       thisitem = next;
-    }
+       if (will_wont_resp[option] == 0) {
+         if (my_want_state_is_wont(option)) {
 
 
-    /* Now, thisitem is first before/at boundary. */
+           switch (option) {
 
 
-    good = netobuf;    /* where the good bytes go */
+           case TELOPT_TM:
+               /*
+                * Special case for TM.  We send a WILL, but pretend
+                * we sent WONT.
+                */
+               send_will(option, 0);
+               set_my_want_state_wont(TELOPT_TM);
+               set_my_state_wont(TELOPT_TM);
+               return;
 
 
-    while (nfrontp > thisitem) {
-       if (wewant(thisitem)) {
-           int length;
+#      if defined(TN3270)
+           case TELOPT_EOR:            /* end of record */
+#      endif   /* defined(TN3270) */
+           case TELOPT_BINARY:         /* binary mode */
+           case TELOPT_NAWS:           /* window size */
+           case TELOPT_TSPEED:         /* terminal speed */
+           case TELOPT_LFLOW:          /* local flow control */
+           case TELOPT_TTYPE:          /* terminal type option */
+           case TELOPT_SGA:            /* no big deal */
+           case TELOPT_ENVIRON:        /* environment variable option */
+#if    defined(ENCRYPT)
+           case TELOPT_ENCRYPT:        /* encryption variable option */
+#endif
+               new_state_ok = 1;
+               break;
+#if    defined(AUTHENTICATE)
+           case TELOPT_AUTHENTICATION:
+               if (autologin)
+                       new_state_ok = 1;
+               break;
+#endif
 
 
-           next = thisitem;
-           do {
-               next = nextitem(next);
-           } while (wewant(next) && (nfrontp > next));
-           length = next-thisitem;
-           bcopy(thisitem, good, length);
-           good += length;
-           thisitem = next;
-       } else {
-           thisitem = nextitem(thisitem);
+           case TELOPT_XDISPLOC:       /* X Display location */
+               if (env_getvalue((unsigned char *)"DISPLAY"))
+                   new_state_ok = 1;
+               break;
+
+           case TELOPT_LINEMODE:
+#ifdef KLUDGELINEMODE
+               kludgelinemode = 0;
+               send_do(TELOPT_SGA, 1);
+#endif
+               set_my_want_state_will(TELOPT_LINEMODE);
+               send_will(option, 0);
+               set_my_state_will(TELOPT_LINEMODE);
+               slc_init();
+               return;
+
+           case TELOPT_ECHO:           /* We're never going to echo... */
+           default:
+               break;
+           }
+
+           if (new_state_ok) {
+               set_my_want_state_will(option);
+               send_will(option, 0);
+               setconnmode(0);                 /* Set new tty mode */
+           } else {
+               will_wont_resp[option]++;
+               send_wont(option, 0);
+           }
+         } else {
+           /*
+            * Handle options that need more things done after the
+            * other side has acknowledged the option.
+            */
+           switch (option) {
+           case TELOPT_LINEMODE:
+#ifdef KLUDGELINEMODE
+               kludgelinemode = 0;
+               send_do(TELOPT_SGA, 1);
+#endif
+               set_my_state_will(option);
+               slc_init();
+               send_do(TELOPT_SGA, 0);
+               return;
+           }
+         }
        }
        }
-    }
+       set_my_state_will(option);
+}
+
+       static void
+dontoption(option)
+       int option;
+{
 
 
-    nbackp = netobuf;
-    nfrontp = good;            /* next byte to be sent */
-    neturg = 0;
+       if (will_wont_resp[option]) {
+           --will_wont_resp[option];
+           if (will_wont_resp[option] && my_state_is_wont(option))
+               --will_wont_resp[option];
+       }
+
+       if ((will_wont_resp[option] == 0) && my_want_state_is_will(option)) {
+           switch (option) {
+           case TELOPT_LINEMODE:
+               linemode = 0;   /* put us back to the default state */
+               break;
+           }
+           /* we always accept a DONT */
+           set_my_want_state_wont(option);
+           if (my_state_is_will(option))
+               send_wont(option, 0);
+           setconnmode(0);                     /* Set new tty mode */
+       }
+       set_my_state_wont(option);
 }
 }
-\f
+
 /*
 /*
- * Send as much data as possible to the terminal.
+ * Given a buffer returned by tgetent(), this routine will turn
+ * the pipe seperated list of names in the buffer into an array
+ * of pointers to null terminated names.  We toss out any bad,
+ * duplicate, or verbose names (names with spaces).
  */
 
  */
 
+static char *name_unknown = "UNKNOWN";
+static char *unknown[] = { 0, 0 };
 
 
-ttyflush()
+       char **
+mklist(buf, name)
+       char *buf, *name;
 {
 {
-    int n;
+       register int n;
+       register char c, *cp, **argvp, *cp2, **argv, **avt;
 
 
-    if ((n = tfrontp - tbackp) > 0) {
-       if (!(SYNCHing||flushout)) {
-           n = write(tout, tbackp, n);
-       } else {
-           ioctl(fileno(stdout), TIOCFLUSH, (char *) 0);
-           /* we leave 'n' alone! */
+       if (name) {
+               if (strlen(name) > 40) {
+                       name = 0;
+                       unknown[0] = name_unknown;
+               } else {
+                       unknown[0] = name;
+                       upcase(name);
+               }
+       } else
+               unknown[0] = name_unknown;
+       /*
+        * Count up the number of names.
+        */
+       for (n = 1, cp = buf; *cp && *cp != ':'; cp++) {
+               if (*cp == '|')
+                       n++;
        }
        }
-    }
-    if (n < 0) {
-       return;
-    }
-    tbackp += n;
-    if (tbackp == tfrontp) {
-       tbackp = tfrontp = ttyobuf;
-    }
+       /*
+        * Allocate an array to put the name pointers into
+        */
+       argv = (char **)malloc((n+3)*sizeof(char *));
+       if (argv == 0)
+               return(unknown);
+
+       /*
+        * Fill up the array of pointers to names.
+        */
+       *argv = 0;
+       argvp = argv+1;
+       n = 0;
+       for (cp = cp2 = buf; (c = *cp);  cp++) {
+               if (c == '|' || c == ':') {
+                       *cp++ = '\0';
+                       /*
+                        * Skip entries that have spaces or are over 40
+                        * characters long.  If this is our environment
+                        * name, then put it up front.  Otherwise, as
+                        * long as this is not a duplicate name (case
+                        * insensitive) add it to the list.
+                        */
+                       if (n || (cp - cp2 > 41))
+                               ;
+                       else if (name && (strncasecmp(name, cp2, cp-cp2) == 0))
+                               *argv = cp2;
+                       else if (is_unique(cp2, argv+1, argvp))
+                               *argvp++ = cp2;
+                       if (c == ':')
+                               break;
+                       /*
+                        * Skip multiple delimiters. Reset cp2 to
+                        * the beginning of the next name. Reset n,
+                        * the flag for names with spaces.
+                        */
+                       while ((c = *cp) == '|')
+                               cp++;
+                       cp2 = cp;
+                       n = 0;
+               }
+               /*
+                * Skip entries with spaces or non-ascii values.
+                * Convert lower case letters to upper case.
+                */
+               if ((c == ' ') || !isascii(c))
+                       n = 1;
+               else if (islower(c))
+                       *cp = toupper(c);
+       }
+       
+       /*
+        * Check for an old V6 2 character name.  If the second
+        * name points to the beginning of the buffer, and is
+        * only 2 characters long, move it to the end of the array.
+        */
+       if ((argv[1] == buf) && (strlen(argv[1]) == 2)) {
+               --argvp;
+               for (avt = &argv[1]; avt < argvp; avt++)
+                       *avt = *(avt+1);
+               *argvp++ = buf;
+       }
+
+       /*
+        * Duplicate last name, for TTYPE option, and null
+        * terminate the array.  If we didn't find a match on
+        * our terminal name, put that name at the beginning.
+        */
+       cp = *(argvp-1);
+       *argvp++ = cp;
+       *argvp = 0;
+
+       if (*argv == 0) {
+               if (name)
+                       *argv = name;
+               else {
+                       --argvp;
+                       for (avt = argv; avt < argvp; avt++)
+                               *avt = *(avt+1);
+               }
+       }
+       if (*argv)
+               return(argv);
+       else
+               return(unknown);
+}
+
+       int
+is_unique(name, as, ae)
+       register char *name, **as, **ae;
+{
+       register char **ap;
+       register int n;
+
+       n = strlen(name) + 1;
+       for (ap = as; ap < ae; ap++)
+               if (strncasecmp(*ap, name, n) == 0)
+                       return(0);
+       return (1);
+}
+
+#ifdef TERMCAP
+char termbuf[1024];
+
+       /*ARGSUSED*/
+       int
+setupterm(tname, fd, errp)
+       char *tname;
+       int fd, *errp;
+{
+       if (tgetent(termbuf, tname) == 1) {
+               termbuf[1023] = '\0';
+               if (errp)
+                       *errp = 1;
+               return(0);
+       }
+       if (errp)
+               *errp = 0;
+       return(-1);
+}
+#else
+#define        termbuf ttytype
+extern char ttytype[];
+#endif
+
+int resettermname = 1;
+
+       char *
+gettermname()
+{
+       char *tname;
+       static char **tnamep = 0;
+       static char **next;
+       int err;
+
+       if (resettermname) {
+               resettermname = 0;
+               if (tnamep && tnamep != unknown)
+                       free(tnamep);
+               if ((tname = (char *)env_getvalue((unsigned char *)"TERM")) &&
+                               (setupterm(tname, 1, &err) == 0)) {
+                       tnamep = mklist(termbuf, tname);
+               } else {
+                       if (tname && (strlen(tname) <= 40)) {
+                               unknown[0] = tname;
+                               upcase(tname);
+                       } else
+                               unknown[0] = name_unknown;
+                       tnamep = unknown;
+               }
+               next = tnamep;
+       }
+       if (*next == 0)
+               next = tnamep;
+       return(*next++);
 }
 }
-\f
 /*
 /*
- * Various signal handling routines.
+ * suboption()
+ *
+ *     Look at the sub-option buffer, and try to be helpful to the other
+ * side.
+ *
+ *     Currently we recognize:
+ *
+ *             Terminal type, send request.
+ *             Terminal speed (send request).
+ *             Local flow control (is request).
+ *             Linemode
  */
 
  */
 
-deadpeer()
+    static void
+suboption()
 {
 {
+    printsub('<', subbuffer, SB_LEN()+2);
+    switch (SB_GET()) {
+    case TELOPT_TTYPE:
+       if (my_want_state_is_wont(TELOPT_TTYPE))
+           return;
+       if (SB_EOF() || SB_GET() != TELQUAL_SEND) {
+           return;
+       } else {
+           char *name;
+           unsigned char temp[50];
+           int len;
+
+#if    defined(TN3270)
+           if (tn3270_ttype()) {
+               return;
+           }
+#endif /* defined(TN3270) */
+           name = gettermname();
+           len = strlen(name) + 4 + 2;
+           if (len < NETROOM()) {
+               sprintf((char *)temp, "%c%c%c%c%s%c%c", IAC, SB, TELOPT_TTYPE,
+                               TELQUAL_IS, name, IAC, SE);
+               ring_supply_data(&netoring, temp, len);
+               printsub('>', &temp[2], len-2);
+           } else {
+               ExitString("No room in buffer for terminal type.\n", 1);
+               /*NOTREACHED*/
+           }
+       }
+       break;
+    case TELOPT_TSPEED:
+       if (my_want_state_is_wont(TELOPT_TSPEED))
+           return;
+       if (SB_EOF())
+           return;
+       if (SB_GET() == TELQUAL_SEND) {
+           long ospeed, ispeed;
+           unsigned char temp[50];
+           int len;
+
+           TerminalSpeeds(&ispeed, &ospeed);
+
+           sprintf((char *)temp, "%c%c%c%c%d,%d%c%c", IAC, SB, TELOPT_TSPEED,
+                   TELQUAL_IS, ospeed, ispeed, IAC, SE);
+           len = strlen((char *)temp+4) + 4;   /* temp[3] is 0 ... */
+
+           if (len < NETROOM()) {
+               ring_supply_data(&netoring, temp, len);
+               printsub('>', temp+2, len - 2);
+           }
+/*@*/      else printf("lm_will: not enough room in buffer\n");
+       }
+       break;
+    case TELOPT_LFLOW:
+       if (my_want_state_is_wont(TELOPT_LFLOW))
+           return;
+       if (SB_EOF())
+           return;
+       switch(SB_GET()) {
+       case 1:
+           localflow = 1;
+           break;
+       case 0:
+           localflow = 0;
+           break;
+       default:
+           return;
+       }
        setcommandmode();
        setcommandmode();
-       longjmp(peerdied, -1);
+       setconnmode(0);
+       break;
+
+    case TELOPT_LINEMODE:
+       if (my_want_state_is_wont(TELOPT_LINEMODE))
+           return;
+       if (SB_EOF())
+           return;
+       switch (SB_GET()) {
+       case WILL:
+           lm_will(subpointer, SB_LEN());
+           break;
+       case WONT:
+           lm_wont(subpointer, SB_LEN());
+           break;
+       case DO:
+           lm_do(subpointer, SB_LEN());
+           break;
+       case DONT:
+           lm_dont(subpointer, SB_LEN());
+           break;
+       case LM_SLC:
+           slc(subpointer, SB_LEN());
+           break;
+       case LM_MODE:
+           lm_mode(subpointer, SB_LEN(), 0);
+           break;
+       default:
+           break;
+       }
+       break;
+
+    case TELOPT_ENVIRON:
+       if (SB_EOF())
+           return;
+       switch(SB_PEEK()) {
+       case TELQUAL_IS:
+       case TELQUAL_INFO:
+           if (my_want_state_is_dont(TELOPT_ENVIRON))
+               return;
+           break;
+       case TELQUAL_SEND:
+           if (my_want_state_is_wont(TELOPT_ENVIRON)) {
+               return;
+           }
+           break;
+       default:
+           return;
+       }
+       env_opt(subpointer, SB_LEN());
+       break;
+
+    case TELOPT_XDISPLOC:
+       if (my_want_state_is_wont(TELOPT_XDISPLOC))
+           return;
+       if (SB_EOF())
+           return;
+       if (SB_GET() == TELQUAL_SEND) {
+           unsigned char temp[50], *dp;
+           int len;
+
+           if ((dp = env_getvalue((unsigned char *)"DISPLAY")) == NULL) {
+               /*
+                * Something happened, we no longer have a DISPLAY
+                * variable.  So, turn off the option.
+                */
+               send_wont(TELOPT_XDISPLOC, 1);
+               break;
+           }
+           sprintf((char *)temp, "%c%c%c%c%s%c%c", IAC, SB, TELOPT_XDISPLOC,
+                   TELQUAL_IS, dp, IAC, SE);
+           len = strlen((char *)temp+4) + 4;   /* temp[3] is 0 ... */
+
+           if (len < NETROOM()) {
+               ring_supply_data(&netoring, temp, len);
+               printsub('>', temp+2, len - 2);
+           }
+/*@*/      else printf("lm_will: not enough room in buffer\n");
+       }
+       break;
+
+#if    defined(AUTHENTICATE)
+       case TELOPT_AUTHENTICATION: {
+               if (!autologin)
+                       break;
+               if (SB_EOF())
+                       return;
+               switch(SB_GET()) {
+               case TELQUAL_IS:
+                       if (my_want_state_is_dont(TELOPT_AUTHENTICATION))
+                               return;
+                       auth_is(subpointer, SB_LEN());
+                       break;
+               case TELQUAL_SEND:
+                       if (my_want_state_is_wont(TELOPT_AUTHENTICATION))
+                               return;
+                       auth_send(subpointer, SB_LEN());
+                       break;
+               case TELQUAL_REPLY:
+                       if (my_want_state_is_wont(TELOPT_AUTHENTICATION))
+                               return;
+                       auth_reply(subpointer, SB_LEN());
+                       break;
+               case TELQUAL_NAME:
+                       if (my_want_state_is_dont(TELOPT_AUTHENTICATION))
+                               return;
+                       auth_name(subpointer, SB_LEN());
+                       break;
+               }
+       }
+       break;
+#endif
+#if    defined(ENCRYPT)
+       case TELOPT_ENCRYPT:
+               if (SB_EOF())
+                       return;
+               switch(SB_GET()) {
+               case ENCRYPT_START:
+                       if (my_want_state_is_dont(TELOPT_ENCRYPT))
+                               return;
+                       encrypt_start(subpointer, SB_LEN());
+                       break;
+               case ENCRYPT_END:
+                       if (my_want_state_is_dont(TELOPT_ENCRYPT))
+                               return;
+                       encrypt_end();
+                       break;
+               case ENCRYPT_SUPPORT:
+                       if (my_want_state_is_wont(TELOPT_ENCRYPT))
+                               return;
+                       encrypt_support(subpointer, SB_LEN());
+                       break;
+               case ENCRYPT_REQSTART:
+                       if (my_want_state_is_wont(TELOPT_ENCRYPT))
+                               return;
+                       encrypt_request_start(subpointer, SB_LEN());
+                       break;
+               case ENCRYPT_REQEND:
+                       if (my_want_state_is_wont(TELOPT_ENCRYPT))
+                               return;
+                       /*
+                        * We can always send an REQEND so that we cannot
+                        * get stuck encrypting.  We should only get this
+                        * if we have been able to get in the correct mode
+                        * anyhow.
+                        */
+                       encrypt_request_end();
+                       break;
+               case ENCRYPT_IS:
+                       if (my_want_state_is_dont(TELOPT_ENCRYPT))
+                               return;
+                       encrypt_is(subpointer, SB_LEN());
+                       break;
+               case ENCRYPT_REPLY:
+                       if (my_want_state_is_wont(TELOPT_ENCRYPT))
+                               return;
+                       encrypt_reply(subpointer, SB_LEN());
+                       break;
+               case ENCRYPT_ENC_KEYID:
+                       if (my_want_state_is_dont(TELOPT_ENCRYPT))
+                               return;
+                       encrypt_enc_keyid(subpointer, SB_LEN());
+                       break;
+               case ENCRYPT_DEC_KEYID:
+                       if (my_want_state_is_wont(TELOPT_ENCRYPT))
+                               return;
+                       encrypt_dec_keyid(subpointer, SB_LEN());
+                       break;
+               default:
+                       break;
+               }
+               break;
+#endif
+    default:
+       break;
+    }
 }
 
 }
 
-intr()
+static unsigned char str_lm[] = { IAC, SB, TELOPT_LINEMODE, 0, 0, IAC, SE };
+
+    void
+lm_will(cmd, len)
+    unsigned char *cmd;
+    int len;
 {
 {
-    if (localchars) {
-       intp();
+    if (len < 1) {
+/*@*/  printf("lm_will: no command!!!\n");     /* Should not happen... */
        return;
     }
        return;
     }
-    setcommandmode();
-    longjmp(toplevel, -1);
+    switch(cmd[0]) {
+    case LM_FORWARDMASK:       /* We shouldn't ever get this... */
+    default:
+       str_lm[3] = DONT;
+       str_lm[4] = cmd[0];
+       if (NETROOM() > sizeof(str_lm)) {
+           ring_supply_data(&netoring, str_lm, sizeof(str_lm));
+           printsub('>', &str_lm[2], sizeof(str_lm)-2);
+       }
+/*@*/  else printf("lm_will: not enough room in buffer\n");
+       break;
+    }
 }
 
 }
 
-intr2()
+    void
+lm_wont(cmd, len)
+    unsigned char *cmd;
+    int len;
 {
 {
-    if (localchars) {
-       sendbrk();
+    if (len < 1) {
+/*@*/  printf("lm_wont: no command!!!\n");     /* Should not happen... */
+       return;
+    }
+    switch(cmd[0]) {
+    case LM_FORWARDMASK:       /* We shouldn't ever get this... */
+    default:
+       /* We are always DONT, so don't respond */
        return;
     }
 }
 
        return;
     }
 }
 
-doescape()
+    void
+lm_do(cmd, len)
+    unsigned char *cmd;
+    int len;
 {
 {
-    command(0);
+    if (len < 1) {
+/*@*/  printf("lm_do: no command!!!\n");       /* Should not happen... */
+       return;
+    }
+    switch(cmd[0]) {
+    case LM_FORWARDMASK:
+    default:
+       str_lm[3] = WONT;
+       str_lm[4] = cmd[0];
+       if (NETROOM() > sizeof(str_lm)) {
+           ring_supply_data(&netoring, str_lm, sizeof(str_lm));
+           printsub('>', &str_lm[2], sizeof(str_lm)-2);
+       }
+/*@*/  else printf("lm_do: not enough room in buffer\n");
+       break;
+    }
 }
 }
-\f
-/*
- * The following are routines used to print out debugging information.
- */
 
 
-
-static
-Dump(direction, buffer, length)
-char   direction;
-char   *buffer;
-int    length;
+    void
+lm_dont(cmd, len)
+    unsigned char *cmd;
+    int len;
 {
 {
-#   define BYTES_PER_LINE      32
-#   define min(x,y)    ((x<y)? x:y)
-    char *pThis;
-    int offset;
-
-    offset = 0;
-
-    while (length) {
-       /* print one line */
-       fprintf(NetTrace, "%c 0x%x\t", direction, offset);
-       pThis = buffer;
-       buffer = buffer+min(length, BYTES_PER_LINE);
-       while (pThis < buffer) {
-           fprintf(NetTrace, "%.2x", (*pThis)&0xff);
-           pThis++;
-       }
-       fprintf(NetTrace, "\n");
-       length -= BYTES_PER_LINE;
-       offset += BYTES_PER_LINE;
-       if (length < 0) {
-           return;
-       }
-       /* find next unique line */
+    if (len < 1) {
+/*@*/  printf("lm_dont: no command!!!\n");     /* Should not happen... */
+       return;
+    }
+    switch(cmd[0]) {
+    case LM_FORWARDMASK:
+    default:
+       /* we are always WONT, so don't respond */
+       break;
     }
 }
 
     }
 }
 
+static unsigned char str_lm_mode[] = {
+       IAC, SB, TELOPT_LINEMODE, LM_MODE, 0, IAC, SE
+};
 
 
-/*VARARGS*/
-printoption(direction, fmt, option, what)
-       char *direction, *fmt;
-       int option, what;
+       void
+lm_mode(cmd, len, init)
+       unsigned char *cmd;
+       int len, init;
 {
 {
-       if (!showoptions)
+       if (len != 1)
                return;
                return;
-       printf("%s ", direction+1);
-       if (fmt == doopt)
-               fmt = "do";
-       else if (fmt == dont)
-               fmt = "dont";
-       else if (fmt == will)
-               fmt = "will";
-       else if (fmt == wont)
-               fmt = "wont";
-       else
-               fmt = "???";
-       if (option < (sizeof telopts/sizeof telopts[0]))
-               printf("%s %s", fmt, telopts[option]);
-       else
-               printf("%s %d", fmt, option);
-       if (*direction == '<') {
-               printf("\r\n");
+       if ((linemode&MODE_MASK&~MODE_ACK) == *cmd)
+               return;
+       if (*cmd&MODE_ACK)
                return;
                return;
+       linemode = *cmd&(MODE_MASK&~MODE_ACK);
+       str_lm_mode[4] = linemode;
+       if (!init)
+           str_lm_mode[4] |= MODE_ACK;
+       if (NETROOM() > sizeof(str_lm_mode)) {
+           ring_supply_data(&netoring, str_lm_mode, sizeof(str_lm_mode));
+           printsub('>', &str_lm_mode[2], sizeof(str_lm_mode)-2);
        }
        }
-       printf(" (%s)\r\n", what ? "reply" : "don't reply");
+/*@*/  else printf("lm_mode: not enough room in buffer\n");
+       setconnmode(0); /* set changed mode */
 }
 }
+
 \f
 \f
+
 /*
 /*
- * Mode - set up terminal to a specific mode.
+ * slc()
+ * Handle special character suboption of LINEMODE.
  */
 
  */
 
+struct spc {
+       cc_t val;
+       cc_t *valp;
+       char flags;     /* Current flags & level */
+       char mylevel;   /* Maximum level & flags */
+} spc_data[NSLC+1];
 
 
-mode(f)
-       register int f;
+#define SLC_IMPORT     0
+#define        SLC_EXPORT      1
+#define SLC_RVALUE     2
+static int slc_mode = SLC_EXPORT;
+
+       void
+slc_init()
 {
 {
-       static int prevmode = 0;
-       struct tchars *tc;
-       struct ltchars *ltc;
-       struct sgttyb sb;
-       int onoff, old;
-       struct  tchars notc2;
-       struct  ltchars noltc2;
-       static struct   tchars notc =   { -1, -1, -1, -1, -1, -1 };
-       static struct   ltchars noltc = { -1, -1, -1, -1, -1, -1 };
-
-       globalmode = f;
-       if (prevmode == f)
-               return;
-       old = prevmode;
-       prevmode = f;
-       sb = nttyb;
-       switch (f) {
+       register struct spc *spcp;
 
 
-       case 0:
-               onoff = 0;
-               tc = &otc;
-               ltc = &oltc;
-               break;
+       localchars = 1;
+       for (spcp = spc_data; spcp < &spc_data[NSLC+1]; spcp++) {
+               spcp->val = 0;
+               spcp->valp = 0;
+               spcp->flags = spcp->mylevel = SLC_NOSUPPORT;
+       }
 
 
-       case 1:         /* remote character processing, remote echo */
-       case 2:         /* remote character processing, local echo */
-               sb.sg_flags |= CBREAK;
-               if (f == 1)
-                       sb.sg_flags &= ~(ECHO|CRMOD);
-               else
-                       sb.sg_flags |= ECHO|CRMOD;
-               sb.sg_erase = sb.sg_kill = -1;
-               tc = &notc;
-               /*
-                * If user hasn't specified one way or the other,
-                * then default to not trapping signals.
-                */
-               if (!donelclchars) {
-                       localchars = 0;
-               }
-               if (localchars) {
-                       notc2 = notc;
-                       notc2.t_intrc = ntc.t_intrc;
-                       notc2.t_quitc = ntc.t_quitc;
-                       tc = &notc2;
-               } else
-                       tc = &notc;
-               ltc = &noltc;
-               onoff = 1;
-               break;
-       case 3:         /* local character processing, remote echo */
-       case 4:         /* local character processing, local echo */
-       case 5:         /* local character processing, no echo */
-               sb.sg_flags &= ~CBREAK;
-               sb.sg_flags |= CRMOD;
-               if (f == 4)
-                       sb.sg_flags |= ECHO;
-               else
-                       sb.sg_flags &= ~ECHO;
-               notc2 = ntc;
-               tc = &notc2;
-               noltc2 = oltc;
-               ltc = &noltc2;
-               /*
-                * If user hasn't specified one way or the other,
-                * then default to trapping signals.
-                */
-               if (!donelclchars) {
-                       localchars = 1;
-               }
-               if (localchars) {
-                       notc2.t_brkc = nltc.t_flushc;
-                       noltc2.t_flushc = -1;
-               } else {
-                       notc2.t_intrc = notc2.t_quitc = -1;
-               }
-               noltc2.t_suspc = escape;
-               noltc2.t_dsuspc = -1;
-               onoff = 1;
-               break;
+#define        initfunc(func, flags) { \
+                                       spcp = &spc_data[func]; \
+                                       if (spcp->valp = tcval(func)) { \
+                                           spcp->val = *spcp->valp; \
+                                           spcp->mylevel = SLC_VARIABLE|flags; \
+                                       } else { \
+                                           spcp->val = 0; \
+                                           spcp->mylevel = SLC_DEFAULT; \
+                                       } \
+                                   }
+
+       initfunc(SLC_SYNCH, 0);
+       /* No BRK */
+       initfunc(SLC_AO, 0);
+       initfunc(SLC_AYT, 0);
+       /* No EOR */
+       initfunc(SLC_ABORT, SLC_FLUSHIN|SLC_FLUSHOUT);
+       initfunc(SLC_EOF, 0);
+#ifndef        SYSV_TERMIO
+       initfunc(SLC_SUSP, SLC_FLUSHIN);
+#endif
+       initfunc(SLC_EC, 0);
+       initfunc(SLC_EL, 0);
+#ifndef        SYSV_TERMIO
+       initfunc(SLC_EW, 0);
+       initfunc(SLC_RP, 0);
+       initfunc(SLC_LNEXT, 0);
+#endif
+       initfunc(SLC_XON, 0);
+       initfunc(SLC_XOFF, 0);
+#ifdef SYSV_TERMIO
+       spc_data[SLC_XON].mylevel = SLC_CANTCHANGE;
+       spc_data[SLC_XOFF].mylevel = SLC_CANTCHANGE;
+#endif
+       initfunc(SLC_FORW1, 0);
+#ifdef USE_TERMIO
+       initfunc(SLC_FORW2, 0);
+       /* No FORW2 */
+#endif
 
 
-       default:
-               return;
-       }
-       ioctl(fileno(stdin), TIOCSLTC, (char *)ltc);
-       ioctl(fileno(stdin), TIOCSETC, (char *)tc);
-       ioctl(fileno(stdin), TIOCSETP, (char *)&sb);
-       ioctl(fileno(stdin), FIONBIO, (char *)&onoff);
-       ioctl(fileno(stdout), FIONBIO, (char *)&onoff);
-       if (f >= 3)
-               signal(SIGTSTP, doescape);
-       else if (old >= 3) {
-               signal(SIGTSTP, SIG_DFL);
-               sigsetmask(sigblock(0) & ~(1<<(SIGTSTP-1)));
-       }
-}
-\f
-/*
- * These routines decides on what the mode should be (based on the values
- * of various global variables).
- */
+       initfunc(SLC_IP, SLC_FLUSHIN|SLC_FLUSHOUT);
+#undef initfunc
 
 
-char *modedescriptions[] = {
-       "telnet command mode",                                  /* 0 */
-       "character-at-a-time mode",                             /* 1 */
-       "character-at-a-time mode (local echo)",                /* 2 */
-       "line-by-line mode (remote echo)",                      /* 3 */
-       "line-by-line mode",                                    /* 4 */
-       "line-by-line mode (local echoing suppressed)",         /* 5 */
-};
+       if (slc_mode == SLC_EXPORT)
+               slc_export();
+       else
+               slc_import(1);
 
 
-getconnmode()
+}
+
+    void
+slcstate()
 {
 {
-    static char newmode[8] = { 4, 5, 3, 3, 2, 2, 1, 1 };
-    int modeindex = 0;
+    printf("Special characters are %s values\n",
+               slc_mode == SLC_IMPORT ? "remote default" :
+               slc_mode == SLC_EXPORT ? "local" :
+                                        "remote");
+}
 
 
-    if (hisopts[TELOPT_ECHO]) {
-       modeindex += 2;
-    }
-    if (hisopts[TELOPT_SGA]) {
-       modeindex += 4;
-    }
-    if (dontlecho && (clocks.echotoggle > clocks.modenegotiated)) {
-       modeindex += 1;
-    }
-    return newmode[modeindex];
+    void
+slc_mode_export()
+{
+    slc_mode = SLC_EXPORT;
+    if (my_state_is_will(TELOPT_LINEMODE))
+       slc_export();
 }
 
 }
 
-setconnmode()
+    void
+slc_mode_import(def)
+    int def;
 {
 {
-    mode(getconnmode());
+    slc_mode = def ? SLC_IMPORT : SLC_RVALUE;
+    if (my_state_is_will(TELOPT_LINEMODE))
+       slc_import(def);
 }
 
 }
 
+unsigned char slc_import_val[] = {
+       IAC, SB, TELOPT_LINEMODE, LM_SLC, 0, SLC_VARIABLE, 0, IAC, SE
+};
+unsigned char slc_import_def[] = {
+       IAC, SB, TELOPT_LINEMODE, LM_SLC, 0, SLC_DEFAULT, 0, IAC, SE
+};
 
 
-setcommandmode()
+    void
+slc_import(def)
+    int def;
 {
 {
-    mode(0);
+    if (NETROOM() > sizeof(slc_import_val)) {
+       if (def) {
+           ring_supply_data(&netoring, slc_import_def, sizeof(slc_import_def));
+           printsub('>', &slc_import_def[2], sizeof(slc_import_def)-2);
+       } else {
+           ring_supply_data(&netoring, slc_import_val, sizeof(slc_import_val));
+           printsub('>', &slc_import_val[2], sizeof(slc_import_val)-2);
+       }
+    }
+/*@*/ else printf("slc_import: not enough room\n");
 }
 }
-\f
-char   sibuf[BUFSIZ], *sbp;
-char   tibuf[BUFSIZ], *tbp;
-int    scc, tcc;
-
 
 
-/*
- * Select from tty and network...
- */
-telnet()
+    void
+slc_export()
 {
 {
-       register int c;
-       int tin = fileno(stdin);
-       int on = 1;
-       fd_set ibits, obits, xbits;
-
-       tout = fileno(stdout);
-       setconnmode();
-       scc = 0;
-       tcc = 0;
-       FD_ZERO(&ibits);
-       FD_ZERO(&obits);
-       FD_ZERO(&xbits);
-
-       ioctl(net, FIONBIO, (char *)&on);
-#if    defined(SO_OOBINLINE)
-       setsockopt(net, SOL_SOCKET, SO_OOBINLINE, &on, sizeof on);
-#endif /* defined(SO_OOBINLINE) */
-       if (telnetport) {
-           if (!hisopts[TELOPT_SGA]) {
-               willoption(TELOPT_SGA, 0);
-           }
-           if (!myopts[TELOPT_TTYPE]) {
-               dooption(TELOPT_TTYPE, 0);
-           }
+    register struct spc *spcp;
+
+    TerminalDefaultChars();
+
+    slc_start_reply();
+    for (spcp = &spc_data[1]; spcp < &spc_data[NSLC+1]; spcp++) {
+       if (spcp->mylevel != SLC_NOSUPPORT) {
+           if (spcp->val == (cc_t)(_POSIX_VDISABLE))
+               spcp->flags = SLC_NOSUPPORT;
+           else
+               spcp->flags = spcp->mylevel;
+           if (spcp->valp)
+               spcp->val = *spcp->valp;
+           slc_add_reply(spcp - spc_data, spcp->flags, spcp->val);
        }
        }
-       for (;;) {
-               if (scc < 0 && tcc < 0) {
-                       break;
-               }
+    }
+    slc_end_reply();
+    (void)slc_update();
+    setconnmode(1);    /* Make sure the character values are set */
+}
 
 
-               if (((globalmode < 4) || flushline) && NETBYTES()) {
-                       FD_SET(net, &obits);
-               } else {
-                       FD_SET(tin, &ibits);
-               }
-               if (TTYBYTES()) {
-                       FD_SET(tout, &obits);
-               } else {
-                       FD_SET(net, &ibits);
-               }
-               if (!SYNCHing) {
-                       FD_SET(net, &xbits);
+       void
+slc(cp, len)
+       register unsigned char *cp;
+       int len;
+{
+       register struct spc *spcp;
+       register int func,level;
+
+       slc_start_reply();
+
+       for (; len >= 3; len -=3, cp +=3) {
+
+               func = cp[SLC_FUNC];
+
+               if (func == 0) {
+                       /*
+                        * Client side: always ignore 0 function.
+                        */
+                       continue;
                }
                }
-               if ((c = select(16, &ibits, &obits, &xbits,
-                                               (struct timeval *)0)) < 1) {
-                       if (c == -1) {
-                               /*
-                                * we can get EINTR if we are in line mode,
-                                * and the user does an escape (TSTP), or
-                                * some other signal generator.
-                                */
-                               if (errno == EINTR) {
-                                       continue;
-                               }
-                       }
-                       sleep(5);
+               if (func > NSLC) {
+                       if ((cp[SLC_FLAGS] & SLC_LEVELBITS) != SLC_NOSUPPORT)
+                               slc_add_reply(func, SLC_NOSUPPORT, 0);
                        continue;
                }
 
                        continue;
                }
 
-               /*
-                * Any urgent data?
-                */
-               if (FD_ISSET(net, &xbits)) {
-                   FD_CLR(net, &xbits);
-                   SYNCHing = 1;
-                   ttyflush(); /* flush already enqueued data */
-               }
+               spcp = &spc_data[func];
 
 
-               /*
-                * Something to read from the network...
-                */
-               if (FD_ISSET(net, &ibits)) {
-                       int canread;
+               level = cp[SLC_FLAGS]&(SLC_LEVELBITS|SLC_ACK);
 
 
-                       FD_CLR(net, &ibits);
-                       if (scc == 0) {
-                           sbp = sibuf;
-                       }
-                       canread = sibuf + sizeof sibuf - sbp;
-#if    !defined(SO_OOBINLINE)
+               if ((cp[SLC_VALUE] == (unsigned char)spcp->val) &&
+                   ((level&SLC_LEVELBITS) == (spcp->flags&SLC_LEVELBITS))) {
+                       continue;
+               }
+
+               if (level == (SLC_DEFAULT|SLC_ACK)) {
                        /*
                        /*
-                        * In 4.2 (and some early 4.3) systems, the
-                        * OOB indication and data handling in the kernel
-                        * is such that if two separate TCP Urgent requests
-                        * come in, one byte of TCP data will be overlaid.
-                        * This is fatal for Telnet, but we try to live
-                        * with it.
-                        *
-                        * In addition, in 4.2 (and...), a special protocol
-                        * is needed to pick up the TCP Urgent data in
-                        * the correct sequence.
-                        *
-                        * What we do is:  if we think we are in urgent
-                        * mode, we look to see if we are "at the mark".
-                        * If we are, we do an OOB receive.  If we run
-                        * this twice, we will do the OOB receive twice,
-                        * but the second will fail, since the second
-                        * time we were "at the mark", but there wasn't
-                        * any data there (the kernel doesn't reset
-                        * "at the mark" until we do a normal read).
-                        * Once we've read the OOB data, we go ahead
-                        * and do normal reads.
-                        *
-                        * There is also another problem, which is that
-                        * since the OOB byte we read doesn't put us
-                        * out of OOB state, and since that byte is most
-                        * likely the TELNET DM (data mark), we would
-                        * stay in the TELNET SYNCH (SYNCHing) state.
-                        * So, clocks to the rescue.  If we've "just"
-                        * received a DM, then we test for the
-                        * presence of OOB data when the receive OOB
-                        * fails (and AFTER we did the normal mode read
-                        * to clear "at the mark").
+                        * This is an error condition, the SLC_ACK
+                        * bit should never be set for the SLC_DEFAULT
+                        * level.  Our best guess to recover is to
+                        * ignore the SLC_ACK bit.
                         */
                         */
-                   if (SYNCHing) {
-                       int atmark;
-
-                       ioctl(net, SIOCATMARK, (char *)&atmark);
-                       if (atmark) {
-                           c = recv(net, sibuf, canread, MSG_OOB);
-                           if ((c == -1) && (errno == EINVAL)) {
-                               c = read(net, sibuf, canread);
-                               if (clocks.didnetreceive < clocks.gotDM) {
-                                   SYNCHing = stilloob(net);
-                               }
-                           }
-                       } else {
-                           c = read(net, sibuf, canread);
-                       }
-                   } else {
-                       c = read(net, sibuf, canread);
-                   }
-                   settimer(didnetreceive);
-#else  /* !defined(SO_OOBINLINE) */
-                   c = read(net, sbp, canread);
-#endif /* !defined(SO_OOBINLINE) */
-                   if (c < 0 && errno == EWOULDBLOCK) {
-                       c = 0;
-                   } else if (c <= 0) {
-                       break;
-                   }
-                   if (netdata) {
-                       Dump('<', sbp, c);
-                   }
-                   scc += c;
+                       cp[SLC_FLAGS] &= ~SLC_ACK;
                }
 
                }
 
-               /*
-                * Something to read from the tty...
-                */
-               if (FD_ISSET(tin, &ibits)) {
-                       FD_CLR(tin, &ibits);
-                       if (tcc == 0) {
-                           tbp = tibuf;        /* nothing left, reset */
-                       }
-                       c = read(tin, tbp, tibuf+sizeof tibuf - tbp);
-                       if (c < 0 && errno == EWOULDBLOCK) {
-                               c = 0;
-                       } else {
-                               /* EOF detection for line mode!!!! */
-                               if (c == 0 && globalmode >= 3) {
-                                       /* must be an EOF... */
-                                       *tbp = ntc.t_eofc;
-                                       c = 1;
-                               }
-                               if (c <= 0) {
-                                       tcc = c;
-                                       break;
-                               }
-                       }
-                       tcc += c;
+               if (level == ((spcp->flags&SLC_LEVELBITS)|SLC_ACK)) {
+                       spcp->val = (cc_t)cp[SLC_VALUE];
+                       spcp->flags = cp[SLC_FLAGS];    /* include SLC_ACK */
+                       continue;
                }
 
                }
 
-               while (tcc > 0) {
-                       register int sc;
+               level &= ~SLC_ACK;
 
 
-                       if (NETROOM() < 2) {
-                               flushline = 1;
-                               break;
-                       }
-                       c = *tbp++ & 0xff, sc = strip(c), tcc--;
-                       if (sc == escape) {
-                               command(0);
-                               tcc = 0;
-                               flushline = 1;
-                               break;
-                       } else if ((globalmode >= 4) && (sc == echoc)) {
-                               if (tcc > 0 && strip(*tbp) == echoc) {
-                                       tbp++;
-                                       tcc--;
-                               } else {
-                                       dontlecho = !dontlecho;
-                                       settimer(echotoggle);
-                                       setconnmode();
-                                       tcc = 0;
-                                       flushline = 1;
-                                       break;
-                               }
-                       }
-                       if (localchars) {
-                               if (sc == ntc.t_intrc) {
-                                       intp();
-                                       break;
-                               } else if (sc == ntc.t_quitc) {
-                                       sendbrk();
-                                       break;
-                               } else if (sc == nltc.t_flushc) {
-                                       NET2ADD(IAC, AO);
-                                       if (autoflush) {
-                                           doflush();
-                                       }
-                                       break;
-                               } else if (globalmode > 2) {
-                                       ;
-                               } else if (sc == nttyb.sg_kill) {
-                                       NET2ADD(IAC, EL);
-                                       break;
-                               } else if (sc == nttyb.sg_erase) {
-                                       NET2ADD(IAC, EC);
-                                       break;
-                               }
-                       }
-                       switch (c) {
-                       case '\n':
-                               /*
-                                * If echoing is happening locally,
-                                * then a newline (unix) is CRLF (TELNET).
-                                */
-                               if (!hisopts[TELOPT_ECHO]) {
-                                       NETADD('\r');
-                               }
-                               NETADD('\n');
-                               flushline = 1;
-                               break;
-                       case '\r':
-                               NET2ADD('\r', '\0');
-                               flushline = 1;
-                               break;
-                       case IAC:
-                               NET2ADD(IAC, IAC);
-                               break;
-                       default:
-                               NETADD(c);
-                               break;
-                       }
+               if (level <= (spcp->mylevel&SLC_LEVELBITS)) {
+                       spcp->flags = cp[SLC_FLAGS]|SLC_ACK;
+                       spcp->val = (cc_t)cp[SLC_VALUE];
                }
                }
-               if (((globalmode < 4) || flushline) &&
-                   FD_ISSET(net, &obits) && (NETBYTES() > 0)) {
-                       FD_CLR(net, &obits);
-                       netflush(net);
-               }
-               if (scc > 0)
-                       telrcv();
-               if (FD_ISSET(tout, &obits) && (TTYBYTES() > 0)) {
-                       FD_CLR(tout, &obits);
-                       ttyflush();
+               if (level == SLC_DEFAULT) {
+                       if ((spcp->mylevel&SLC_LEVELBITS) != SLC_DEFAULT)
+                               spcp->flags = spcp->mylevel;
+                       else
+                               spcp->flags = SLC_NOSUPPORT;
                }
                }
+               slc_add_reply(func, spcp->flags, spcp->val);
        }
        }
-       setcommandmode();
+       slc_end_reply();
+       if (slc_update())
+               setconnmode(1); /* set the  new character values */
 }
 }
-\f
-/*
- * Telnet receiver states for fsm
- */
-#define        TS_DATA         0
-#define        TS_IAC          1
-#define        TS_WILL         2
-#define        TS_WONT         3
-#define        TS_DO           4
-#define        TS_DONT         5
-#define        TS_CR           6
-#define        TS_SB           7               /* sub-option collection */
-#define        TS_SE           8               /* looking for sub-option end */
 
 
-telrcv()
+    void
+slc_check()
 {
 {
-       register int c;
-       static int state = TS_DATA;
-
-       while ((scc > 0) && (TTYROOM() > 2)) {
-               c = *sbp++ & 0xff, scc--;
-               switch (state) {
-
-               case TS_CR:
-                       state = TS_DATA;
-                       if (c == '\0') {
-                           break;      /* Ignore \0 after CR */
-                       } else if (c == '\n') {
-                           if (hisopts[TELOPT_ECHO] && !crmod) {
-                               TTYADD(c);
-                           }
-                           break;
-                       }
-                       /* Else, fall through */
+    register struct spc *spcp;
+
+    slc_start_reply();
+    for (spcp = &spc_data[1]; spcp < &spc_data[NSLC+1]; spcp++) {
+       if (spcp->valp && spcp->val != *spcp->valp) {
+           spcp->val = *spcp->valp;
+           if (spcp->val == (cc_t)(_POSIX_VDISABLE))
+               spcp->flags = SLC_NOSUPPORT;
+           else
+               spcp->flags = spcp->mylevel;
+           slc_add_reply(spcp - spc_data, spcp->flags, spcp->val);
+       }
+    }
+    slc_end_reply();
+    setconnmode(1);
+}
 
 
-               case TS_DATA:
-                       if (c == IAC) {
-                               state = TS_IAC;
-                               continue;
-                       }
-                           /*
-                            * The 'crmod' hack (see following) is needed
-                            * since we can't * set CRMOD on output only.
-                            * Machines like MULTICS like to send \r without
-                            * \n; since we must turn off CRMOD to get proper
-                            * input, the mapping is done here (sigh).
-                            */
-                       if (c == '\r') {
-                               if (scc > 0) {
-                                       c = *sbp&0xff;
-                                       if (c == 0) {
-                                               sbp++, scc--;
-                                               /* a "true" CR */
-                                               TTYADD('\r');
-                                       } else if (!hisopts[TELOPT_ECHO] &&
-                                                               (c == '\n')) {
-                                               sbp++, scc--;
-                                               TTYADD('\n');
-                                       } else {
-                                               TTYADD('\r');
-                                               if (crmod) {
-                                                       TTYADD('\n');
-                                               }
-                                       }
-                               } else {
-                                       state = TS_CR;
-                                       TTYADD('\r');
-                                       if (crmod) {
-                                               TTYADD('\n');
-                                       }
-                               }
-                       } else {
-                               TTYADD(c);
-                       }
-                       continue;
 
 
-               case TS_IAC:
-                       switch (c) {
-                       
-                       case WILL:
-                               state = TS_WILL;
-                               continue;
+unsigned char slc_reply[128];
+unsigned char *slc_replyp;
 
 
-                       case WONT:
-                               state = TS_WONT;
-                               continue;
+       void
+slc_start_reply()
+{
+       slc_replyp = slc_reply;
+       *slc_replyp++ = IAC;
+       *slc_replyp++ = SB;
+       *slc_replyp++ = TELOPT_LINEMODE;
+       *slc_replyp++ = LM_SLC;
+}
 
 
-                       case DO:
-                               state = TS_DO;
-                               continue;
+       void
+slc_add_reply(func, flags, value)
+       unsigned char func;
+       unsigned char flags;
+       cc_t value;
+{
+       if ((*slc_replyp++ = func) == IAC)
+               *slc_replyp++ = IAC;
+       if ((*slc_replyp++ = flags) == IAC)
+               *slc_replyp++ = IAC;
+       if ((*slc_replyp++ = (unsigned char)value) == IAC)
+               *slc_replyp++ = IAC;
+}
 
 
-                       case DONT:
-                               state = TS_DONT;
-                               continue;
+    void
+slc_end_reply()
+{
+    register int len;
 
 
-                       case DM:
-                               /*
-                                * We may have missed an urgent notification,
-                                * so make sure we flush whatever is in the
-                                * buffer currently.
-                                */
-                               SYNCHing = 1;
-                               ttyflush();
-                               SYNCHing = stilloob(net);
-                               settimer(gotDM);
-                               break;
+    *slc_replyp++ = IAC;
+    *slc_replyp++ = SE;
+    len = slc_replyp - slc_reply;
+    if (len <= 6)
+       return;
+    if (NETROOM() > len) {
+       ring_supply_data(&netoring, slc_reply, slc_replyp - slc_reply);
+       printsub('>', &slc_reply[2], slc_replyp - slc_reply - 2);
+    }
+/*@*/else printf("slc_end_reply: not enough room\n");
+}
 
 
-                       case NOP:
-                       case GA:
-                               break;
+       int
+slc_update()
+{
+       register struct spc *spcp;
+       int need_update = 0;
 
 
-                       case SB:
-                               SB_CLEAR();
-                               state = TS_SB;
-                               continue;
+       for (spcp = &spc_data[1]; spcp < &spc_data[NSLC+1]; spcp++) {
+               if (!(spcp->flags&SLC_ACK))
+                       continue;
+               spcp->flags &= ~SLC_ACK;
+               if (spcp->valp && (*spcp->valp != spcp->val)) {
+                       *spcp->valp = spcp->val;
+                       need_update = 1;
+               }
+       }
+       return(need_update);
+}
 
 
+       void
+env_opt(buf, len)
+       register unsigned char *buf;
+       register int len;
+{
+       register unsigned char *ep = 0, *epc = 0;
+       register int i;
+
+       switch(buf[0]&0xff) {
+       case TELQUAL_SEND:
+               env_opt_start();
+               if (len == 1) {
+                       env_opt_add(NULL);
+               } else for (i = 1; i < len; i++) {
+                       switch (buf[i]&0xff) {
+                       case ENV_VALUE:
+                               if (ep) {
+                                       *epc = 0;
+                                       env_opt_add(ep);
+                               }
+                               ep = epc = &buf[i+1];
+                               break;
+                       case ENV_ESC:
+                               i++;
+                               /*FALL THROUGH*/
                        default:
                        default:
+                               if (epc)
+                                       *epc++ = buf[i];
                                break;
                        }
                                break;
                        }
-                       state = TS_DATA;
-                       continue;
-
-               case TS_WILL:
-                       printoption(">RCVD", will, c, !hisopts[c]);
-                       if (c == TELOPT_TM) {
-                               if (flushout) {
-                                       flushout = 0;
-                               }
-                       } else if (!hisopts[c]) {
-                               willoption(c, 1);
+                       if (ep) {
+                               *epc = 0;
+                               env_opt_add(ep);
                        }
                        }
-                       state = TS_DATA;
-                       continue;
+               }
+               env_opt_end(1);
+               break;
 
 
-               case TS_WONT:
-                       printoption(">RCVD", wont, c, hisopts[c]);
-                       if (c == TELOPT_TM) {
-                               if (flushout) {
-                                       flushout = 0;
-                               }
-                       } else if (hisopts[c]) {
-                               wontoption(c, 1);
-                       }
-                       state = TS_DATA;
-                       continue;
+       case TELQUAL_IS:
+       case TELQUAL_INFO:
+               /* Ignore for now.  We shouldn't get it anyway. */
+               break;
 
 
-               case TS_DO:
-                       printoption(">RCVD", doopt, c, !myopts[c]);
-                       if (!myopts[c])
-                               dooption(c);
-                       state = TS_DATA;
-                       continue;
+       default:
+               break;
+       }
+}
 
 
-               case TS_DONT:
-                       printoption(">RCVD", dont, c, myopts[c]);
-                       if (myopts[c]) {
-                               myopts[c] = 0;
-                               sprintf(nfrontp, wont, c);
-                               nfrontp += sizeof (wont) - 2;
-                               flushline = 1;
-                               setconnmode();  /* set new tty mode (maybe) */
-                               printoption(">SENT", wont, c);
-                       }
-                       state = TS_DATA;
-                       continue;
-               case TS_SB:
-                       if (c == IAC) {
-                               state = TS_SE;
-                       } else {
-                               SB_ACCUM(c);
-                       }
-                       continue;
+#define        OPT_REPLY_SIZE  256
+unsigned char *opt_reply;
+unsigned char *opt_replyp;
+unsigned char *opt_replyend;
 
 
-               case TS_SE:
-                       if (c != SE) {
-                               if (c != IAC) {
-                                       SB_ACCUM(IAC);
-                               }
-                               SB_ACCUM(c);
-                               state = TS_SB;
-                       } else {
-                               SB_TERM();
-                               suboption();    /* handle sub-option */
-                               state = TS_DATA;
-                       }
-               }
+       void
+env_opt_start()
+{
+       if (opt_reply)
+               opt_reply = (unsigned char *)realloc(opt_reply, OPT_REPLY_SIZE);
+       else
+               opt_reply = (unsigned char *)malloc(OPT_REPLY_SIZE);
+       if (opt_reply == NULL) {
+/*@*/          printf("env_opt_start: malloc()/realloc() failed!!!\n");
+               opt_reply = opt_replyp = opt_replyend = NULL;
+               return;
        }
        }
+       opt_replyp = opt_reply;
+       opt_replyend = opt_reply + OPT_REPLY_SIZE;
+       *opt_replyp++ = IAC;
+       *opt_replyp++ = SB;
+       *opt_replyp++ = TELOPT_ENVIRON;
+       *opt_replyp++ = TELQUAL_IS;
 }
 }
-\f
-willoption(option, reply)
-       int option, reply;
-{
-       char *fmt;
 
 
-       switch (option) {
+       void
+env_opt_start_info()
+{
+       env_opt_start();
+       if (opt_replyp)
+           opt_replyp[-1] = TELQUAL_INFO;
+}
 
 
-       case TELOPT_ECHO:
-       case TELOPT_SGA:
-               settimer(modenegotiated);
-               hisopts[option] = 1;
-               fmt = doopt;
-               setconnmode();          /* possibly set new tty mode */
-               break;
+       void
+env_opt_add(ep)
+       register unsigned char *ep;
+{
+       register unsigned char *vp, c;
 
 
-       case TELOPT_TM:
-               return;                 /* Never reply to TM will's/wont's */
+       if (opt_reply == NULL)          /*XXX*/
+               return;                 /*XXX*/
 
 
-       default:
-               fmt = dont;
-               break;
+       if (ep == NULL || *ep == '\0') {
+               env_default(1);
+               while (ep = env_default(0))
+                       env_opt_add(ep);
+               return;
+       }
+       vp = env_getvalue(ep);
+       if (opt_replyp + (vp ? strlen((char *)vp) : 0) +
+                               strlen((char *)ep) + 6 > opt_replyend)
+       {
+               register int len;
+               opt_replyend += OPT_REPLY_SIZE;
+               len = opt_replyend - opt_reply;
+               opt_reply = (unsigned char *)realloc(opt_reply, len);
+               if (opt_reply == NULL) {
+/*@*/                  printf("env_opt_add: realloc() failed!!!\n");
+                       opt_reply = opt_replyp = opt_replyend = NULL;
+                       return;
+               }
+               opt_replyp = opt_reply + len - (opt_replyend - opt_replyp);
+               opt_replyend = opt_reply + len;
+       }
+       *opt_replyp++ = ENV_VAR;
+       for (;;) {
+               while (c = *ep++) {
+                       switch(c&0xff) {
+                       case IAC:
+                               *opt_replyp++ = IAC;
+                               break;
+                       case ENV_VALUE:
+                       case ENV_VAR:
+                       case ENV_ESC:
+                               *opt_replyp++ = ENV_ESC;
+                               break;
+                       }
+                       *opt_replyp++ = c;
+               }
+               if (ep = vp) {
+                       *opt_replyp++ = ENV_VALUE;
+                       vp = NULL;
+               } else
+                       break;
        }
        }
-       sprintf(nfrontp, fmt, option);
-       nfrontp += sizeof (dont) - 2;
-       if (reply)
-               printoption(">SENT", fmt, option);
-       else
-               printoption("<SENT", fmt, option);
 }
 
 }
 
-wontoption(option, reply)
-       int option, reply;
+       void
+env_opt_end(emptyok)
+       register int emptyok;
 {
 {
-       char *fmt;
+       register int len;
+
+       len = opt_replyp - opt_reply + 2;
+       if (emptyok || len > 6) {
+               *opt_replyp++ = IAC;
+               *opt_replyp++ = SE;
+               if (NETROOM() > len) {
+                       ring_supply_data(&netoring, opt_reply, len);
+                       printsub('>', &opt_reply[2], len - 2);
+               }
+/*@*/          else printf("slc_end_reply: not enough room\n");
+       }
+       if (opt_reply) {
+               free(opt_reply);
+               opt_reply = opt_replyp = opt_replyend = NULL;
+       }
+}
 
 
-       switch (option) {
+\f
 
 
-       case TELOPT_ECHO:
-       case TELOPT_SGA:
-               settimer(modenegotiated);
-               hisopts[option] = 0;
-               fmt = dont;
-               setconnmode();                  /* Set new tty mode */
+    int
+telrcv()
+{
+    register int c;
+    register int scc;
+    register unsigned char *sbp;
+    int count;
+    int returnValue = 0;
+
+    scc = 0;
+    count = 0;
+    while (TTYROOM() > 2) {
+       if (scc == 0) {
+           if (count) {
+               ring_consumed(&netiring, count);
+               returnValue = 1;
+               count = 0;
+           }
+           sbp = netiring.consume;
+           scc = ring_full_consecutive(&netiring);
+           if (scc == 0) {
+               /* No more data coming in */
                break;
                break;
+           }
+       }
 
 
-       case TELOPT_TM:
-               return;         /* Never reply to TM will's/wont's */
+       c = *sbp++ & 0xff, scc--; count++;
+#if    defined(ENCRYPT)
+       if (decrypt_input)
+               c = (*decrypt_input)(c);
+#endif
 
 
-       default:
-               fmt = dont;
-       }
-       sprintf(nfrontp, fmt, option);
-       nfrontp += sizeof (doopt) - 2;
-       if (reply)
-               printoption(">SENT", fmt, option);
-       else
-               printoption("<SENT", fmt, option);
-}
+       switch (telrcv_state) {
 
 
-dooption(option)
-       int option;
-{
-       char *fmt;
+       case TS_CR:
+           telrcv_state = TS_DATA;
+           if (c == '\0') {
+               break;  /* Ignore \0 after CR */
+           }
+           else if ((c == '\n') && my_want_state_is_dont(TELOPT_ECHO) && !crmod) {
+               TTYADD(c);
+               break;
+           }
+           /* Else, fall through */
 
 
-       switch (option) {
+       case TS_DATA:
+           if (c == IAC) {
+               telrcv_state = TS_IAC;
+               break;
+           }
+#          if defined(TN3270)
+           if (In3270) {
+               *Ifrontp++ = c;
+               while (scc > 0) {
+                   c = *sbp++ & 0377, scc--; count++;
+#if    defined(ENCRYPT)
+                   if (decrypt_input)
+                       c = (*decrypt_input)(c);
+#endif
+                   if (c == IAC) {
+                       telrcv_state = TS_IAC;
+                       break;
+                   }
+                   *Ifrontp++ = c;
+               }
+           } else
+#          endif /* defined(TN3270) */
+                   /*
+                    * The 'crmod' hack (see following) is needed
+                    * since we can't * set CRMOD on output only.
+                    * Machines like MULTICS like to send \r without
+                    * \n; since we must turn off CRMOD to get proper
+                    * input, the mapping is done here (sigh).
+                    */
+           if ((c == '\r') && my_want_state_is_dont(TELOPT_BINARY)) {
+               if (scc > 0) {
+                   c = *sbp&0xff;
+#if    defined(ENCRYPT)
+                   if (decrypt_input)
+                       c = (*decrypt_input)(c);
+#endif
+                   if (c == 0) {
+                       sbp++, scc--; count++;
+                       /* a "true" CR */
+                       TTYADD('\r');
+                   } else if (my_want_state_is_dont(TELOPT_ECHO) &&
+                                       (c == '\n')) {
+                       sbp++, scc--; count++;
+                       TTYADD('\n');
+                   } else {
+#if    defined(ENCRYPT)
+                       if (decrypt_input)
+                           (*decrypt_input)(-1);
+#endif
 
 
-       case TELOPT_TM:
-               fmt = will;
+                       TTYADD('\r');
+                       if (crmod) {
+                               TTYADD('\n');
+                       }
+                   }
+               } else {
+                   telrcv_state = TS_CR;
+                   TTYADD('\r');
+                   if (crmod) {
+                           TTYADD('\n');
+                   }
+               }
+           } else {
+               TTYADD(c);
+           }
+           continue;
+
+       case TS_IAC:
+process_iac:
+           switch (c) {
+           
+           case WILL:
+               telrcv_state = TS_WILL;
+               continue;
+
+           case WONT:
+               telrcv_state = TS_WONT;
+               continue;
+
+           case DO:
+               telrcv_state = TS_DO;
+               continue;
+
+           case DONT:
+               telrcv_state = TS_DONT;
+               continue;
+
+           case DM:
+                   /*
+                    * We may have missed an urgent notification,
+                    * so make sure we flush whatever is in the
+                    * buffer currently.
+                    */
+               printoption("RCVD", IAC, DM);
+               SYNCHing = 1;
+               (void) ttyflush(1);
+               SYNCHing = stilloob();
+               settimer(gotDM);
                break;
 
                break;
 
-       case TELOPT_TTYPE:              /* terminal type option */
-       case TELOPT_SGA:                /* no big deal */
-               fmt = will;
-               myopts[option] = 1;
+           case SB:
+               SB_CLEAR();
+               telrcv_state = TS_SB;
+               continue;
+
+#          if defined(TN3270)
+           case EOR:
+               if (In3270) {
+                   if (Ibackp == Ifrontp) {
+                       Ibackp = Ifrontp = Ibuf;
+                       ISend = 0;      /* should have been! */
+                   } else {
+                       Ibackp += DataFromNetwork(Ibackp, Ifrontp-Ibackp, 1);
+                       ISend = 1;
+                   }
+               }
+               printoption("RCVD", IAC, EOR);
+               break;
+#          endif /* defined(TN3270) */
+
+           case IAC:
+#          if !defined(TN3270)
+               TTYADD(IAC);
+#          else /* !defined(TN3270) */
+               if (In3270) {
+                   *Ifrontp++ = IAC;
+               } else {
+                   TTYADD(IAC);
+               }
+#          endif /* !defined(TN3270) */
                break;
 
                break;
 
-       case TELOPT_ECHO:               /* We're never going to echo... */
-       default:
-               fmt = wont;
+           case NOP:
+           case GA:
+           default:
+               printoption("RCVD", IAC, c);
                break;
                break;
+           }
+           telrcv_state = TS_DATA;
+           continue;
+
+       case TS_WILL:
+           printoption("RCVD", WILL, c);
+           willoption(c);
+           SetIn3270();
+           telrcv_state = TS_DATA;
+           continue;
+
+       case TS_WONT:
+           printoption("RCVD", WONT, c);
+           wontoption(c);
+           SetIn3270();
+           telrcv_state = TS_DATA;
+           continue;
+
+       case TS_DO:
+           printoption("RCVD", DO, c);
+           dooption(c);
+           SetIn3270();
+           if (c == TELOPT_NAWS) {
+               sendnaws();
+           } else if (c == TELOPT_LFLOW) {
+               localflow = 1;
+               setcommandmode();
+               setconnmode(0);
+           }
+           telrcv_state = TS_DATA;
+           continue;
+
+       case TS_DONT:
+           printoption("RCVD", DONT, c);
+           dontoption(c);
+           flushline = 1;
+           setconnmode(0);     /* set new tty mode (maybe) */
+           SetIn3270();
+           telrcv_state = TS_DATA;
+           continue;
+
+       case TS_SB:
+           if (c == IAC) {
+               telrcv_state = TS_SE;
+           } else {
+               SB_ACCUM(c);
+           }
+           continue;
+
+       case TS_SE:
+           if (c != SE) {
+               if (c != IAC) {
+                   /*
+                    * This is an error.  We only expect to get
+                    * "IAC IAC" or "IAC SE".  Several things may
+                    * have happend.  An IAC was not doubled, the
+                    * IAC SE was left off, or another option got
+                    * inserted into the suboption are all possibilities.
+                    * If we assume that the IAC was not doubled,
+                    * and really the IAC SE was left off, we could
+                    * get into an infinate loop here.  So, instead,
+                    * we terminate the suboption, and process the
+                    * partial suboption if we can.
+                    */
+                   SB_ACCUM(IAC);
+                   SB_ACCUM(c);
+                   subpointer -= 2;
+                   SB_TERM();
+
+                   printoption("In SUBOPTION processing, RCVD", IAC, c);
+                   suboption();        /* handle sub-option */
+                   SetIn3270();
+                   telrcv_state = TS_IAC;
+                   goto process_iac;
+               }
+               SB_ACCUM(c);
+               telrcv_state = TS_SB;
+           } else {
+               SB_ACCUM(IAC);
+               SB_ACCUM(SE);
+               subpointer -= 2;
+               SB_TERM();
+               suboption();    /* handle sub-option */
+               SetIn3270();
+               telrcv_state = TS_DATA;
+           }
        }
        }
-       sprintf(nfrontp, fmt, option);
-       nfrontp += sizeof (doopt) - 2;
-       printoption(">SENT", fmt, option);
+    }
+    if (count)
+       ring_consumed(&netiring, count);
+    return returnValue||count;
 }
 
 }
 
-/*
- * suboption()
- *
- *     Look at the sub-option buffer, and try to be helpful to the other
- * side.
- *
- *     Currently we recognize:
- *
- *             Terminal type, send request.
- */
+static int bol = 1, local = 0;
 
 
-suboption()
+    int
+rlogin_susp()
 {
 {
-    switch (subbuffer[0]&0xff) {
-    case TELOPT_TTYPE:
-       if ((subbuffer[1]&0xff) != TELQUAL_SEND) {
-           ;
-       } else {
-           char *name;
-           char namebuf[41];
-           char *getenv();
-           int len;
+    if (local) {
+       local = 0;
+       bol = 1;
+       command(0, "z\n", 2);
+       return(1);
+    }
+    return(0);
+}
+
+    static int
+telsnd()
+{
+    int tcc;
+    int count;
+    int returnValue = 0;
+    unsigned char *tbp;
+
+    tcc = 0;
+    count = 0;
+    while (NETROOM() > 2) {
+       register int sc;
+       register int c;
 
 
-           name = getenv("TERM");
-           if ((name == 0) || ((len = strlen(name)) > 40)) {
-               name = "UNKNOWN";
+       if (tcc == 0) {
+           if (count) {
+               ring_consumed(&ttyiring, count);
+               returnValue = 1;
+               count = 0;
            }
            }
-           if ((len + 4+2) < NETROOM()) {
-               strcpy(namebuf, name);
-               upcase(namebuf);
-               sprintf(nfrontp, "%c%c%c%c%s%c%c", IAC, SB, TELOPT_TTYPE,
-                                   TELQUAL_IS, namebuf, IAC, SE);
-               nfrontp += 4+strlen(namebuf)+2;
+           tbp = ttyiring.consume;
+           tcc = ring_full_consecutive(&ttyiring);
+           if (tcc == 0) {
+               break;
            }
        }
            }
        }
-
-    default:
-       break;
+       c = *tbp++ & 0xff, sc = strip(c), tcc--; count++;
+       if (rlogin != _POSIX_VDISABLE) {
+               if (bol) {
+                       bol = 0;
+                       if (sc == rlogin) {
+                               local = 1;
+                               continue;
+                       }
+               } else if (local) {
+                       local = 0;
+                       if (sc == '.' || c == termEofChar) {
+                               bol = 1;
+                               command(0, "close\n", 6);
+                               continue;
+                       }
+                       if (sc == termSuspChar) {
+                               bol = 1;
+                               command(0, "z\n", 2);
+                               continue;
+                       }
+                       if (sc == escape) {
+                               command(0, (char *)tbp, tcc);
+                               bol = 1;
+                               count += tcc;
+                               tcc = 0;
+                               flushline = 1;
+                               break;
+                       }
+                       if (sc != rlogin) {
+                               ++tcc;
+                               --tbp;
+                               --count;
+                               c = sc = rlogin;
+                       }
+               }
+               if ((sc == '\n') || (sc == '\r'))
+                       bol = 1;
+       } else if (sc == escape) {
+           /*
+            * Double escape is a pass through of a single escape character.
+            */
+           if (tcc && strip(*tbp) == escape) {
+               tbp++;
+               tcc--;
+               count++;
+               bol = 0;
+           } else {
+               command(0, (char *)tbp, tcc);
+               bol = 1;
+               count += tcc;
+               tcc = 0;
+               flushline = 1;
+               break;
+           }
+       } else
+           bol = 0;
+#ifdef KLUDGELINEMODE
+       if (kludgelinemode && (globalmode&MODE_EDIT) && (sc == echoc)) {
+           if (tcc > 0 && strip(*tbp) == echoc) {
+               tcc--; tbp++; count++;
+           } else {
+               dontlecho = !dontlecho;
+               settimer(echotoggle);
+               setconnmode(0);
+               flushline = 1;
+               break;
+           }
+       }
+#endif
+       if (MODE_LOCAL_CHARS(globalmode)) {
+           if (TerminalSpecialChars(sc) == 0) {
+               bol = 1;
+               break;
+           }
+       }
+       if (my_want_state_is_wont(TELOPT_BINARY)) {
+           switch (c) {
+           case '\n':
+                   /*
+                    * If we are in CRMOD mode (\r ==> \n)
+                    * on our local machine, then probably
+                    * a newline (unix) is CRLF (TELNET).
+                    */
+               if (MODE_LOCAL_CHARS(globalmode)) {
+                   NETADD('\r');
+               }
+               NETADD('\n');
+               bol = flushline = 1;
+               break;
+           case '\r':
+               if (!crlf) {
+                   NET2ADD('\r', '\0');
+               } else {
+                   NET2ADD('\r', '\n');
+               }
+               bol = flushline = 1;
+               break;
+           case IAC:
+               NET2ADD(IAC, IAC);
+               break;
+           default:
+               NETADD(c);
+               break;
+           }
+       } else if (c == IAC) {
+           NET2ADD(IAC, IAC);
+       } else {
+           NETADD(c);
+       }
     }
     }
+    if (count)
+       ring_consumed(&ttyiring, count);
+    return returnValue||count;         /* Non-zero if we did anything */
 }
 \f
 /*
 }
 \f
 /*
- *     The following are data structures and routines for
- *     the "send" command.
+ * Scheduler()
+ *
+ * Try to do something.
+ *
+ * If we do something useful, return 1; else return 0.
  *
  */
  *
  */
-struct sendlist {
-    char       *name;          /* How user refers to it (case independent) */
-    int                what;           /* Character to be sent (<0 ==> special) */
-    char       *help;          /* Help information (0 ==> no help) */
-    int                (*routine)();   /* Routine to perform (for special ops) */
-};
 
 
-/*ARGSUSED*/
-dosynch(s)
-struct sendlist *s;
-{
-    netclear();                        /* clear the path to the network */
-    NET2ADD(IAC, DM);
-    neturg = NETLOC()-1;       /* Some systems are off by one XXX */
-}
 
 
-doflush()
+    int
+Scheduler(block)
+    int        block;                  /* should we block in the select ? */
 {
 {
-    NET2ADD(IAC, DO);
-    NETADD(TELOPT_TM);
-    flushline = 1;
-    flushout = 1;
-    ttyflush();
-    /* do printoption AFTER flush, otherwise the output gets tossed... */
-    printoption("<SENT", doopt, TELOPT_TM);
-}
+               /* One wants to be a bit careful about setting returnValue
+                * to one, since a one implies we did some useful work,
+                * and therefore probably won't be called to block next
+                * time (TN3270 mode only).
+                */
+    int returnValue;
+    int netin, netout, netex, ttyin, ttyout;
 
 
-intp()
-{
-    NET2ADD(IAC, IP);
-    if (autoflush) {
-       doflush();
-    }
-    if (autosynch) {
-       dosynch();
-    }
-}
+    /* Decide which rings should be processed */
 
 
-sendbrk()
-{
-    NET2ADD(IAC, BREAK);
-    if (autoflush) {
-       doflush();
-    }
-    if (autosynch) {
-       dosynch();
+    netout = ring_full_count(&netoring) &&
+           (flushline ||
+               (my_want_state_is_wont(TELOPT_LINEMODE)
+#ifdef KLUDGELINEMODE
+                       && (!kludgelinemode || my_want_state_is_do(TELOPT_SGA))
+#endif
+               ) ||
+                       my_want_state_is_will(TELOPT_BINARY));
+    ttyout = ring_full_count(&ttyoring);
+
+#if    defined(TN3270)
+    ttyin = ring_empty_count(&ttyiring) && (shell_active == 0);
+#else  /* defined(TN3270) */
+    ttyin = ring_empty_count(&ttyiring);
+#endif /* defined(TN3270) */
+
+#if    defined(TN3270)
+    netin = ring_empty_count(&netiring);
+#   else /* !defined(TN3270) */
+    netin = !ISend && ring_empty_count(&netiring);
+#   endif /* !defined(TN3270) */
+
+    netex = !SYNCHing;
+
+    /* If we have seen a signal recently, reset things */
+#   if defined(TN3270) && defined(unix)
+    if (HaveInput) {
+       HaveInput = 0;
+       (void) signal(SIGIO, inputAvailable);
     }
     }
-}
-
+#endif /* defined(TN3270) && defined(unix) */
 
 
-#define        SENDQUESTION    -1
-#define        SENDESCAPE      -3
-
-struct sendlist Sendlist[] = {
-    { "ao", AO, "Send Telnet Abort output" },
-    { "ayt", AYT, "Send Telnet 'Are You There'" },
-    { "brk", BREAK, "Send Telnet Break" },
-    { "ec", EC, "Send Telnet Erase Character" },
-    { "el", EL, "Send Telnet Erase Line" },
-    { "escape", SENDESCAPE, "Send current escape character" },
-    { "ga", GA, "Send Telnet 'Go Ahead' sequence" },
-    { "ip", IP, "Send Telnet Interrupt Process" },
-    { "nop", NOP, "Send Telnet 'No operation'" },
-    { "synch", SYNCH, "Perform Telnet 'Synch operation'", dosynch },
-    { "?", SENDQUESTION, "Display send options" },
-    { 0 }
-};
+    /* Call to system code to process rings */
 
 
-struct sendlist Sendlist2[] = {                /* some synonyms */
-       { "break", BREAK, 0 },
+    returnValue = process_rings(netin, netout, netex, ttyin, ttyout, !block);
 
 
-       { "intp", IP, 0 },
-       { "interrupt", IP, 0 },
-       { "intr", IP, 0 },
+    /* Now, look at the input rings, looking for work to do. */
 
 
-       { "help", SENDQUESTION, 0 },
+    if (ring_full_count(&ttyiring)) {
+#   if defined(TN3270)
+       if (In3270) {
+           int c;
 
 
-       { 0 }
-};
+           c = DataFromTerminal(ttyiring.consume,
+                                       ring_full_consecutive(&ttyiring));
+           if (c) {
+               returnValue = 1;
+               ring_consumed(&ttyiring, c);
+           }
+       } else {
+#   endif /* defined(TN3270) */
+           returnValue |= telsnd();
+#   if defined(TN3270)
+       }
+#   endif /* defined(TN3270) */
+    }
 
 
-char **
-getnextsend(name)
-char *name;
+    if (ring_full_count(&netiring)) {
+#      if !defined(TN3270)
+       returnValue |= telrcv();
+#      else /* !defined(TN3270) */
+       returnValue = Push3270();
+#      endif /* !defined(TN3270) */
+    }
+    return returnValue;
+}
+\f
+/*
+ * Select from tty and network...
+ */
+    void
+telnet(user)
+    char *user;
 {
 {
-    struct sendlist *c = (struct sendlist *) name;
+    sys_telnet_init();
 
 
-    return (char **) (c+1);
-}
+#if defined(ENCRYPT) || defined(AUTHENTICATE)
+    {
+       static char local_host[256] = { 0 };
+       int len = sizeof(local_host);
 
 
-struct sendlist *
-getsend(name)
-char *name;
-{
-    struct sendlist *sl;
-
-    if (sl = (struct sendlist *)
-                               genget(name, (char **) Sendlist, getnextsend)) {
-       return sl;
-    } else {
-       return (struct sendlist *)
-                               genget(name, (char **) Sendlist2, getnextsend);
+       if (!local_host[0]) {
+               gethostname(local_host, &len);
+               local_host[sizeof(local_host)-1] = 0;
+       }
+       auth_encrypt_init(local_host, hostname, "TELNET", 0);
+       auth_encrypt_user(user);
     }
     }
-}
+#endif
+#   if !defined(TN3270)
+    if (telnetport) {
+#if    defined(AUTHENTICATE)
+       if (autologin)
+               send_will(TELOPT_AUTHENTICATION, 1);
+#endif
+#if    defined(ENCRYPT)
+       send_do(TELOPT_ENCRYPT, 1);
+       send_will(TELOPT_ENCRYPT, 1);
+#endif
+       send_do(TELOPT_SGA, 1);
+       send_will(TELOPT_TTYPE, 1);
+       send_will(TELOPT_NAWS, 1);
+       send_will(TELOPT_TSPEED, 1);
+       send_will(TELOPT_LFLOW, 1);
+       send_will(TELOPT_LINEMODE, 1);
+       send_will(TELOPT_ENVIRON, 1);
+       send_do(TELOPT_STATUS, 1);
+       if (env_getvalue((unsigned char *)"DISPLAY"))
+           send_will(TELOPT_XDISPLOC, 1);
+       if (eight)
+           tel_enter_binary(eight);
+    }
+#   endif /* !defined(TN3270) */
 
 
-sendcmd(argc, argv)
-int    argc;
-char   **argv;
-{
-    int what;          /* what we are sending this time */
-    int count;         /* how many bytes we are going to need to send */
-    int hadsynch;      /* are we going to process a "synch"? */
-    int i;
-    int question = 0;  /* was at least one argument a question */
-    struct sendlist *s;        /* pointer to current command */
+#   if !defined(TN3270)
+    for (;;) {
+       int schedValue;
 
 
-    if (argc < 2) {
-       printf("need at least one argument for 'send' command\n");
-       printf("'send ?' for help\n");
-       return 0;
-    }
-    /*
-     * First, validate all the send arguments.
-     * In addition, we see how much space we are going to need, and
-     * whether or not we will be doing a "SYNCH" operation (which
-     * flushes the network queue).
-     */
-    count = 0;
-    hadsynch = 0;
-    for (i = 1; i < argc; i++) {
-       s = getsend(argv[i]);
-       if (s == 0) {
-           printf("Unknown send argument '%s'\n'send ?' for help.\n",
-                       argv[i]);
-           return 0;
-       } else if (s == Ambiguous(struct sendlist *)) {
-           printf("Ambiguous send argument '%s'\n'send ?' for help.\n",
-                       argv[i]);
-           return 0;
+       while ((schedValue = Scheduler(0)) != 0) {
+           if (schedValue == -1) {
+               setcommandmode();
+               return;
+           }
        }
        }
-       switch (s->what) {
-       case SENDQUESTION:
-           break;
-       case SENDESCAPE:
-           count += 1;
-           break;
-       case SYNCH:
-           hadsynch = 1;
-           count += 2;
-           break;
-       default:
-           count += 2;
-           break;
+
+       if (Scheduler(1) == -1) {
+           setcommandmode();
+           return;
        }
     }
        }
     }
-    /* Now, do we have enough room? */
-    if (NETROOM() < count) {
-       printf("There is not enough room in the buffer TO the network\n");
-       printf("to process your request.  Nothing will be done.\n");
-       printf("('send synch' will throw away most data in the network\n");
-       printf("buffer, if this might help.)\n");
-       return 0;
-    }
-    /* OK, they are all OK, now go through again and actually send */
-    for (i = 1; i < argc; i++) {
-       if (!(s = getsend(argv[i]))) {
-           fprintf(stderr, "Telnet 'send' error - argument disappeared!\n");
-           quit();
-           /*NOTREACHED*/
+#   else /* !defined(TN3270) */
+    for (;;) {
+       int schedValue;
+
+       while (!In3270 && !shell_active) {
+           if (Scheduler(1) == -1) {
+               setcommandmode();
+               return;
+           }
        }
        }
-       if (s->routine) {
-           (*s->routine)(s);
+
+       while ((schedValue = Scheduler(0)) != 0) {
+           if (schedValue == -1) {
+               setcommandmode();
+               return;
+           }
+       }
+               /* If there is data waiting to go out to terminal, don't
+                * schedule any more data for the terminal.
+                */
+       if (ring_full_count(&ttyoring)) {
+           schedValue = 1;
        } else {
        } else {
-           switch (what = s->what) {
-           case SYNCH:
-               dosynch();
-               break;
-           case SENDQUESTION:
-               for (s = Sendlist; s->name; s++) {
-                   if (s->help) {
-                       printf(s->name);
-                       if (s->help) {
-                           printf("\t%s", s->help);
-                       }
-                       printf("\n");
+           if (shell_active) {
+               if (shell_continue() == 0) {
+                   ConnectScreen();
+               }
+           } else if (In3270) {
+               schedValue = DoTerminalOutput();
+           }
+       }
+       if (schedValue && (shell_active == 0)) {
+           if (Scheduler(1) == -1) {
+               setcommandmode();
+               return;
+           }
+       }
+    }
+#   endif /* !defined(TN3270) */
+}
+\f
+#if    0       /* XXX - this not being in is a bug */
+/*
+ * nextitem()
+ *
+ *     Return the address of the next "item" in the TELNET data
+ * stream.  This will be the address of the next character if
+ * the current address is a user data character, or it will
+ * be the address of the character following the TELNET command
+ * if the current address is a TELNET IAC ("I Am a Command")
+ * character.
+ */
+
+    static char *
+nextitem(current)
+    char *current;
+{
+    if ((*current&0xff) != IAC) {
+       return current+1;
+    }
+    switch (*(current+1)&0xff) {
+    case DO:
+    case DONT:
+    case WILL:
+    case WONT:
+       return current+3;
+    case SB:           /* loop forever looking for the SE */
+       {
+           register char *look = current+2;
+
+           for (;;) {
+               if ((*look++&0xff) == IAC) {
+                   if ((*look++&0xff) == SE) {
+                       return look;
                    }
                }
                    }
                }
-               question = 1;
-               break;
-           case SENDESCAPE:
-               NETADD(escape);
-               break;
-           default:
-               NET2ADD(IAC, what);
-               break;
            }
        }
            }
        }
+    default:
+       return current+2;
     }
     }
-    return !question;
 }
 }
-\f
+#endif /* 0 */
+
 /*
 /*
- * The following are the routines and data structures referred
- * to by the arguments to the "toggle" command.
+ * netclear()
+ *
+ *     We are about to do a TELNET SYNCH operation.  Clear
+ * the path to the network.
+ *
+ *     Things are a bit tricky since we may have sent the first
+ * byte or so of a previous TELNET command into the network.
+ * So, we have to scan the network buffer from the beginning
+ * until we are up to where we want to be.
+ *
+ *     A side effect of what we do, just to keep things
+ * simple, is to clear the urgent data pointer.  The principal
+ * caller should be setting the urgent data pointer AFTER calling
+ * us in any case.
  */
 
  */
 
-lclchars()
-{
-    donelclchars = 1;
-    return 1;
-}
-
-togdebug()
+    static void
+netclear()
 {
 {
-#ifndef        NOT43
-    if (net > 0 &&
-       setsockopt(net, SOL_SOCKET, SO_DEBUG, (char *)&debug, sizeof(debug))
-                                                                       < 0) {
-           perror("setsockopt (SO_DEBUG)");
-    }
-#else  NOT43
-    if (debug) {
-       if (net > 0 && setsockopt(net, SOL_SOCKET, SO_DEBUG, 0, 0) < 0)
-           perror("setsockopt (SO_DEBUG)");
-    } else
-       printf("Cannot turn off socket debugging\n");
-#endif NOT43
-    return 1;
-}
-
-
-
-int togglehelp();
-
-struct togglelist {
-    char       *name;          /* name of toggle */
-    char       *help;          /* help message */
-    int                (*handler)();   /* routine to do actual setting */
-    int                dohelp;         /* should we display help information */
-    int                *variable;
-    char       *actionexplanation;
-};
-
-struct togglelist Togglelist[] = {
-    { "autoflush",
-       "toggle flushing of output when sending interrupt characters",
-           0,
-               1,
-                   &autoflush,
-                       "flush output when sending interrupt characters" },
-    { "autosynch",
-       "toggle automatic sending of interrupt characters in urgent mode",
-           0,
-               1,
-                   &autosynch,
-                       "send interrupt characters in urgent mode" },
-    { "crmod",
-       "toggle mapping of received carriage returns",
-           0,
-               1,
-                   &crmod,
-                       "map carriage return on output" },
-    { "localchars",
-       "toggle local recognition of certain control characters",
-           lclchars,
-               1,
-                   &localchars,
-                       "recognize certain control characters" },
-    { " ", "", 0, 1 },         /* empty line */
-    { "debug",
-       "(debugging) toggle debugging",
-           togdebug,
-               1,
-                   &debug,
-                       "turn on socket level debugging" },
-    { "netdata",
-       "(debugging) toggle printing of hexadecimal network data",
-           0,
-               1,
-                   &netdata,
-                       "print hexadecimal representation of network traffic" },
-    { "options",
-       "(debugging) toggle viewing of options processing",
-           0,
-               1,
-                   &showoptions,
-                       "show option processing" },
-    { " ", "", 0, 1 },         /* empty line */
-    { "?",
-       "display help information",
-           togglehelp,
-               1 },
-    { "help",
-       "display help information",
-           togglehelp,
-               0 },
-    { 0 }
-};
+#if    0       /* XXX */
+    register char *thisitem, *next;
+    char *good;
+#define        wewant(p)       ((nfrontp > p) && ((*p&0xff) == IAC) && \
+                               ((*(p+1)&0xff) != EC) && ((*(p+1)&0xff) != EL))
 
 
-togglehelp()
-{
-    struct togglelist *c;
+    thisitem = netobuf;
 
 
-    for (c = Togglelist; c->name; c++) {
-       if (c->dohelp) {
-           printf("%s\t%s\n", c->name, c->help);
-       }
+    while ((next = nextitem(thisitem)) <= netobuf.send) {
+       thisitem = next;
     }
     }
-    return 0;
-}
-
-char **
-getnexttoggle(name)
-char *name;
-{
-    struct togglelist *c = (struct togglelist *) name;
 
 
-    return (char **) (c+1);
-}
+    /* Now, thisitem is first before/at boundary. */
 
 
-struct togglelist *
-gettoggle(name)
-char *name;
-{
-    return (struct togglelist *)
-                       genget(name, (char **) Togglelist, getnexttoggle);
-}
+    good = netobuf;    /* where the good bytes go */
 
 
-toggle(argc, argv)
-int    argc;
-char   *argv[];
-{
-    int retval = 1;
-    char *name;
-    struct togglelist *c;
+    while (netoring.add > thisitem) {
+       if (wewant(thisitem)) {
+           int length;
 
 
-    if (argc < 2) {
-       fprintf(stderr,
-           "Need an argument to 'toggle' command.  'toggle ?' for help.\n");
-       return 0;
-    }
-    argc--;
-    argv++;
-    while (argc--) {
-       name = *argv++;
-       c = gettoggle(name);
-       if (c == Ambiguous(struct togglelist *)) {
-           fprintf(stderr, "'%s': ambiguous argument ('toggle ?' for help).\n",
-                                       name);
-           return 0;
-       } else if (c == 0) {
-           fprintf(stderr, "'%s': unknown argument ('toggle ?' for help).\n",
-                                       name);
-           return 0;
+           next = thisitem;
+           do {
+               next = nextitem(next);
+           } while (wewant(next) && (nfrontp > next));
+           length = next-thisitem;
+           memcpy(good, thisitem, length);
+           good += length;
+           thisitem = next;
        } else {
        } else {
-           if (c->variable) {
-               *c->variable = !*c->variable;           /* invert it */
-               printf("%s %s.\n", *c->variable? "Will" : "Won't",
-                                                       c->actionexplanation);
-           }
-           if (c->handler) {
-               retval &= (*c->handler)(c);
-           }
+           thisitem = nextitem(thisitem);
        }
     }
        }
     }
-    return retval;
+
+#endif /* 0 */
 }
 \f
 /*
 }
 \f
 /*
- * The following perform the "set" command.
+ * These routines add various telnet commands to the data stream.
  */
 
  */
 
-struct setlist {
-    char *name;                                /* name */
-    char *help;                                /* help information */
-    char *charp;                       /* where it is located at */
-};
-
-struct setlist Setlist[] = {
-    { "echo",  "character to toggle local echoing on/off", &echoc },
-    { "escape",        "character to escape back to telnet command mode", &escape },
-    { " ", "" },
-    { " ", "The following need 'localchars' to be toggled true", 0 },
-    { "erase", "character to cause an Erase Character", &nttyb.sg_erase },
-    { "flushoutput", "character to cause an Abort Oubput", &nltc.t_flushc },
-    { "interrupt", "character to cause an Interrupt Process", &ntc.t_intrc },
-    { "kill",  "character to cause an Erase Line", &nttyb.sg_kill },
-    { "quit",  "character to cause a Break", &ntc.t_quitc },
-    { "eof",   "character to cause an EOF ", &ntc.t_eofc },
-    { 0 }
-};
-
-char **
-getnextset(name)
-char *name;
-{
-    struct setlist *c = (struct setlist *)name;
-
-    return (char **) (c+1);
-}
-
-struct setlist *
-getset(name)
-char *name;
+    static void
+doflush()
 {
 {
-    return (struct setlist *) genget(name, (char **) Setlist, getnextset);
+    NET2ADD(IAC, DO);
+    NETADD(TELOPT_TM);
+    flushline = 1;
+    flushout = 1;
+    (void) ttyflush(1);                        /* Flush/drop output */
+    /* do printoption AFTER flush, otherwise the output gets tossed... */
+    printoption("SENT", DO, TELOPT_TM);
 }
 
 }
 
-setcmd(argc, argv)
-int    argc;
-char   *argv[];
+    void
+xmitAO()
 {
 {
-    int value;
-    struct setlist *ct;
-
-    /* XXX back we go... sigh */
-    if (argc != 3) {
-       if ((argc == 2) &&
-                   ((!strcmp(argv[1], "?")) || (!strcmp(argv[1], "help")))) {
-           for (ct = Setlist; ct->name; ct++) {
-               printf("%s\t%s\n", ct->name, ct->help);
-           }
-           printf("?\tdisplay help information\n");
-       } else {
-           printf("Format is 'set Name Value'\n'set ?' for help.\n");
-       }
-       return 0;
-    }
-
-    ct = getset(argv[1]);
-    if (ct == 0) {
-       fprintf(stderr, "'%s': unknown argument ('set ?' for help).\n",
-                       argv[1]);
-       return 0;
-    } else if (ct == Ambiguous(struct setlist *)) {
-       fprintf(stderr, "'%s': ambiguous argument ('set ?' for help).\n",
-                       argv[1]);
-       return 0;
-    } else {
-       if (strcmp("off", argv[2])) {
-           value = special(argv[2]);
-       } else {
-           value = -1;
-       }
-       *(ct->charp) = value;
-       printf("%s character is '%s'.\n", ct->name, control(*(ct->charp)));
+    NET2ADD(IAC, AO);
+    printoption("SENT", IAC, AO);
+    if (autoflush) {
+       doflush();
     }
     }
-    return 1;
 }
 }
-\f
-/*
- * The following are the data structures and routines for the
- * 'mode' command.
- */
 
 
-dolinemode()
+
+    void
+xmitEL()
 {
 {
-    if (hisopts[TELOPT_SGA]) {
-       wontoption(TELOPT_SGA, 0);
-    }
-    if (hisopts[TELOPT_ECHO]) {
-       wontoption(TELOPT_ECHO, 0);
-    }
+    NET2ADD(IAC, EL);
+    printoption("SENT", IAC, EL);
 }
 
 }
 
-docharmode()
+    void
+xmitEC()
 {
 {
-    if (!hisopts[TELOPT_SGA]) {
-       willoption(TELOPT_SGA, 0);
-    }
-    if (!hisopts[TELOPT_ECHO]) {
-       willoption(TELOPT_ECHO, 0);
-    }
+    NET2ADD(IAC, EC);
+    printoption("SENT", IAC, EC);
 }
 
 }
 
-struct cmd Modelist[] = {
-    { "character",     "character-at-a-time mode",     docharmode, 1, 1 },
-    { "line",          "line-by-line mode",            dolinemode, 1, 1 },
-    { 0 },
-};
 
 
-char **
-getnextmode(name)
-char *name;
+    int
+dosynch()
 {
 {
-    struct cmd *c = (struct cmd *) name;
-
-    return (char **) (c+1);
+    netclear();                        /* clear the path to the network */
+    NETADD(IAC);
+    setneturg();
+    NETADD(DM);
+    printoption("SENT", IAC, DM);
+    return 1;
 }
 
 }
 
-struct cmd *
-getmodecmd(name)
-char *name;
-{
-    return (struct cmd *) genget(name, (char **) Modelist, getnextmode);
-}
+int want_status_response = 0;
 
 
-modecmd(argc, argv)
-int    argc;
-char   *argv[];
+    int
+get_status()
 {
 {
-    struct cmd *mt;
+    unsigned char tmp[16];
+    register unsigned char *cp;
 
 
-    if ((argc != 2) || !strcmp(argv[1], "?") || !strcmp(argv[1], "help")) {
-       printf("format is:  'mode Mode', where 'Mode' is one of:\n\n");
-       for (mt = Modelist; mt->name; mt++) {
-           printf("%s\t%s\n", mt->name, mt->help);
-       }
+    if (my_want_state_is_dont(TELOPT_STATUS)) {
+       printf("Remote side does not support STATUS option\n");
        return 0;
     }
        return 0;
     }
-    mt = getmodecmd(argv[1]);
-    if (mt == 0) {
-       fprintf(stderr, "Unknown mode '%s' ('mode ?' for help).\n", argv[1]);
-       return 0;
-    } else if (mt == Ambiguous(struct cmd *)) {
-       fprintf(stderr, "Ambiguous mode '%s' ('mode ?' for help).\n", argv[1]);
-       return 0;
-    } else {
-       (*mt->handler)();
+    cp = tmp;
+
+    *cp++ = IAC;
+    *cp++ = SB;
+    *cp++ = TELOPT_STATUS;
+    *cp++ = TELQUAL_SEND;
+    *cp++ = IAC;
+    *cp++ = SE;
+    if (NETROOM() >= cp - tmp) {
+       ring_supply_data(&netoring, tmp, cp-tmp);
+       printsub('>', tmp+2, cp - tmp - 2);
     }
     }
+    ++want_status_response;
     return 1;
 }
     return 1;
 }
-\f
-/*
- * The following data structures and routines implement the
- * "display" command.
- */
 
 
-display(argc, argv)
-int    argc;
-char   *argv[];
+    void
+intp()
 {
 {
-#define        dotog(tl)       if (tl->variable && tl->actionexplanation) { \
-                           if (*tl->variable) { \
-                               printf("will"); \
-                           } else { \
-                               printf("won't"); \
-                           } \
-                           printf(" %s.\n", tl->actionexplanation); \
-                       }
-
-#define        doset(sl)   if (sl->name && *sl->name != ' ') { \
-                       printf("[%s]\t%s.\n", control(*sl->charp), sl->name); \
-                   }
-
-    struct togglelist *tl;
-    struct setlist *sl;
-
-    if (argc == 1) {
-       for (tl = Togglelist; tl->name; tl++) {
-           dotog(tl);
-       }
-       printf("\n");
-       for (sl = Setlist; sl->name; sl++) {
-           doset(sl);
-       }
-    } else {
-       int i;
-
-       for (i = 1; i < argc; i++) {
-           sl = getset(argv[i]);
-           tl = gettoggle(argv[i]);
-           if ((sl == Ambiguous(struct setlist *)) ||
-                               (tl == Ambiguous(struct togglelist *))) {
-               printf("?Ambiguous argument '%s'.\n", argv[i]);
-               return 0;
-           } else if (!sl && !tl) {
-               printf("?Unknown argument '%s'.\n", argv[i]);
-               return 0;
-           } else {
-               if (tl) {
-                   dotog(tl);
-               }
-               if (sl) {
-                   doset(sl);
-               }
-           }
-       }
+    NET2ADD(IAC, IP);
+    printoption("SENT", IAC, IP);
+    flushline = 1;
+    if (autoflush) {
+       doflush();
+    }
+    if (autosynch) {
+       dosynch();
     }
     }
-    return 1;
-#undef doset(sl)
-#undef dotog(tl)
-}
-\f
-/*
- * The following are the data structures, and many of the routines,
- * relating to command processing.
- */
-
-/*
- * Set the escape character.
- */
-setescape(argc, argv)
-       int argc;
-       char *argv[];
-{
-       register char *arg;
-       char buf[50];
-
-       printf(
-           "Deprecated usage - please use 'set escape%s%s' in the future.\n",
-                               (argc > 2)? " ":"", (argc > 2)? argv[1]: "");
-       if (argc > 2)
-               arg = argv[1];
-       else {
-               printf("new escape character: ");
-               gets(buf);
-               arg = buf;
-       }
-       if (arg[0] != '\0')
-               escape = arg[0];
-       printf("Escape character is '%s'.\n", control(escape));
-       fflush(stdout);
-       return 1;
-}
-
-/*VARARGS*/
-togcrmod()
-{
-    crmod = !crmod;
-    printf("Deprecated usage - please use 'toggle crmod' in the future.\n");
-    printf("%s map carriage return on output.\n", crmod ? "Will" : "Won't");
-    fflush(stdout);
-    return 1;
-}
-
-/*VARARGS*/
-suspend()
-{
-       setcommandmode();
-       kill(0, SIGTSTP);
-       /* reget parameters in case they were changed */
-       ioctl(0, TIOCGETP, (char *)&ottyb);
-       ioctl(0, TIOCGETC, (char *)&otc);
-       ioctl(0, TIOCGLTC, (char *)&oltc);
-       return 1;
 }
 
 }
 
-/*VARARGS*/
-bye()
+    void
+sendbrk()
 {
 {
-       register char *op;
-
-       if (connected) {
-               shutdown(net, 2);
-               printf("Connection closed.\n");
-               close(net);
-               connected = 0;
-               /* reset his options */
-               for (op = hisopts; op < &hisopts[256]; op++)
-                       *op = 0;
-       }
-       return 1;
+    NET2ADD(IAC, BREAK);
+    printoption("SENT", IAC, BREAK);
+    flushline = 1;
+    if (autoflush) {
+       doflush();
+    }
+    if (autosynch) {
+       dosynch();
+    }
 }
 
 }
 
-/*VARARGS*/
-quit()
+    void
+sendabort()
 {
 {
-       (void) call(bye, "bye", 0);
-       exit(0);
-       /*NOTREACHED*/
+    NET2ADD(IAC, ABORT);
+    printoption("SENT", IAC, ABORT);
+    flushline = 1;
+    if (autoflush) {
+       doflush();
+    }
+    if (autosynch) {
+       dosynch();
+    }
 }
 
 }
 
-/*
- * Print status about the connection.
- */
-/*ARGSUSED*/
-status(argc, argv)
-int    argc;
-char   *argv[];
+    void
+sendsusp()
 {
 {
-    if (connected) {
-       printf("Connected to %s.\n", hostname);
-       if (argc < 2) {
-           printf("Operating in %s.\n", modedescriptions[getconnmode()]);
-           if (localchars) {
-               printf("Catching signals locally.\n");
-           }
-       }
-    } else {
-       printf("No connection.\n");
+    NET2ADD(IAC, SUSP);
+    printoption("SENT", IAC, SUSP);
+    flushline = 1;
+    if (autoflush) {
+       doflush();
+    }
+    if (autosynch) {
+       dosynch();
     }
     }
-    printf("Escape character is '%s'.\n", control(escape));
-    fflush(stdout);
-    return 1;
 }
 
 }
 
-tn(argc, argv)
-       int argc;
-       char *argv[];
+    void
+sendeof()
 {
 {
-       register struct hostent *host = 0;
-
-       if (connected) {
-               printf("?Already connected to %s\n", hostname);
-               return 0;
-       }
-       if (argc < 2) {
-               (void) strcpy(line, "Connect ");
-               printf("(to) ");
-               gets(&line[strlen(line)]);
-               makeargv();
-               argc = margc;
-               argv = margv;
-       }
-       if (argc > 3) {
-               printf("usage: %s host-name [port]\n", argv[0]);
-               return 0;
-       }
-       sin.sin_addr.s_addr = inet_addr(argv[1]);
-       if (sin.sin_addr.s_addr != -1) {
-               sin.sin_family = AF_INET;
-               (void) strcpy(hnamebuf, argv[1]);
-               hostname = hnamebuf;
-       } else {
-               host = gethostbyname(argv[1]);
-               if (host) {
-                       sin.sin_family = host->h_addrtype;
-#ifndef        NOT43
-                       bcopy(host->h_addr_list[0], (caddr_t)&sin.sin_addr,
-                               host->h_length);
-#else  NOT43
-                       bcopy(host->h_addr, (caddr_t)&sin.sin_addr,
-                               host->h_length);
-#endif NOT43
-                       hostname = host->h_name;
-               } else {
-                       printf("%s: unknown host\n", argv[1]);
-                       return 0;
-               }
-       }
-       sin.sin_port = sp->s_port;
-       if (argc == 3) {
-               sin.sin_port = atoi(argv[2]);
-               if (sin.sin_port == 0) {
-                       sp = getservbyname(argv[2], "tcp");
-                       if (sp)
-                               sin.sin_port = sp->s_port;
-                       else {
-                               printf("%s: bad port number\n", argv[2]);
-                               return 0;
-                       }
-               } else {
-                       sin.sin_port = atoi(argv[2]);
-                       sin.sin_port = htons(sin.sin_port);
-               }
-               telnetport = 0;
-       } else {
-               telnetport = 1;
-       }
-       signal(SIGINT, intr);
-       signal(SIGQUIT, intr2);
-       signal(SIGPIPE, deadpeer);
-       printf("Trying...\n");
-       do {
-               net = socket(AF_INET, SOCK_STREAM, 0);
-               if (net < 0) {
-                       perror("telnet: socket");
-                       return 0;
-               }
-#ifndef        NOT43
-               if (debug &&
-                               setsockopt(net, SOL_SOCKET, SO_DEBUG,
-                                       (char *)&debug, sizeof(debug)) < 0)
-#else  NOT43
-               if (debug && setsockopt(net, SOL_SOCKET, SO_DEBUG, 0, 0) < 0)
-#endif NOT43
-                       perror("setsockopt (SO_DEBUG)");
-
-               if (connect(net, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
-#ifndef        NOT43
-                       if (host && host->h_addr_list[1]) {
-                               int oerrno = errno;
-
-                               fprintf(stderr,
-                                   "telnet: connect to address %s: ",
-                                   inet_ntoa(sin.sin_addr));
-                               errno = oerrno;
-                               perror((char *)0);
-                               host->h_addr_list++;
-                               bcopy(host->h_addr_list[0],
-                                   (caddr_t)&sin.sin_addr, host->h_length);
-                               fprintf(stderr, "Trying %s...\n",
-                                       inet_ntoa(sin.sin_addr));
-                               (void) close(net);
-                               continue;
-                       }
-#endif NOT43
-                       perror("telnet: connect");
-                       signal(SIGINT, SIG_DFL);
-                       signal(SIGQUIT, SIG_DFL);
-                       return 0;
-               }
-               connected++;
-       } while (connected == 0);
-       call(status, "status", "notmuch", 0);
-       if (setjmp(peerdied) == 0)
-               telnet();
-       fprintf(stderr, "Connection closed by foreign host.\n");
-       exit(1);
-       /*NOTREACHED*/
+    NET2ADD(IAC, xEOF);
+    printoption("SENT", IAC, xEOF);
 }
 
 }
 
-
-#define HELPINDENT (sizeof ("connect"))
-
-char   openhelp[] =    "connect to a site";
-char   closehelp[] =   "close current connection";
-char   quithelp[] =    "exit telnet";
-char   zhelp[] =       "suspend telnet";
-char   statushelp[] =  "print status information";
-char   helphelp[] =    "print help information";
-char   sendhelp[] =    "transmit special characters ('send ?' for more)";
-char   sethelp[] =     "set operating parameters ('set ?' for more)";
-char   togglestring[] ="toggle operating parameters ('toggle ?' for more)";
-char   displayhelp[] = "display operating parameters";
-char   modehelp[] =
-               "try to enter line-by-line or character-at-a-time mode";
-
-int    help();
-
-struct cmd cmdtab[] = {
-       { "close",      closehelp,      bye,            1, 1 },
-       { "display",    displayhelp,    display,        1, 0 },
-       { "mode",       modehelp,       modecmd,        1, 1 },
-       { "open",       openhelp,       tn,             1, 0 },
-       { "quit",       quithelp,       quit,           1, 0 },
-       { "send",       sendhelp,       sendcmd,        1, 1 },
-       { "set",        sethelp,        setcmd,         1, 0 },
-       { "status",     statushelp,     status,         1, 0 },
-       { "toggle",     togglestring,   toggle,         1, 0 },
-       { "z",          zhelp,          suspend,        1, 0 },
-       { "?",          helphelp,       help,           1, 0 },
-       0
-};
-
-char   crmodhelp[] =   "deprecated command -- use 'toggle crmod' instead";
-char   escapehelp[] =  "deprecated command -- use 'set escape' instead";
-
-struct cmd cmdtab2[] = {
-       { "help",       helphelp,       help,           0, 0 },
-       { "escape",     escapehelp,     setescape,      1, 0 },
-       { "crmod",      crmodhelp,      togcrmod,       1, 0 },
-       0
-};
-
-/*
- * Help command.
- */
-help(argc, argv)
-       int argc;
-       char *argv[];
+    void
+sendayt()
 {
 {
-       register struct cmd *c;
-
-       if (argc == 1) {
-               printf("Commands may be abbreviated.  Commands are:\n\n");
-               for (c = cmdtab; c->name; c++)
-                       if (c->dohelp) {
-                               printf("%-*s\t%s\n", HELPINDENT, c->name,
-                                                                   c->help);
-                       }
-               return 0;
-       }
-       while (--argc > 0) {
-               register char *arg;
-               arg = *++argv;
-               c = getcmd(arg);
-               if (c == Ambiguous(struct cmd *))
-                       printf("?Ambiguous help command %s\n", arg);
-               else if (c == (struct cmd *)0)
-                       printf("?Invalid help command %s\n", arg);
-               else
-                       printf("%s\n", c->help);
-       }
-       return 0;
+    NET2ADD(IAC, AYT);
+    printoption("SENT", IAC, AYT);
 }
 }
+
 /*
 /*
- * Call routine with argc, argv set from args (terminated by 0).
- * VARARGS2
+ * Send a window size update to the remote system.
  */
  */
-call(routine, args)
-       int (*routine)();
-       char *args;
-{
-       register char **argp;
-       register int argc;
-
-       for (argc = 0, argp = &args; *argp++ != 0; argc++)
-               ;
-       return (*routine)(argc, &args);
-}
 
 
-makeargv()
+    void
+sendnaws()
 {
 {
-       register char *cp;
-       register char **argp = margv;
-
-       margc = 0;
-       for (cp = line; *cp;) {
-               while (isspace(*cp))
-                       cp++;
-               if (*cp == '\0')
-                       break;
-               *argp++ = cp;
-               margc += 1;
-               while (*cp != '\0' && !isspace(*cp))
-                       cp++;
-               if (*cp == '\0')
-                       break;
-               *cp++ = '\0';
-       }
-       *argp++ = 0;
-}
+    long rows, cols;
+    unsigned char tmp[16];
+    register unsigned char *cp;
 
 
-char **
-getnextcmd(name)
-char *name;
-{
-    struct cmd *c = (struct cmd *) name;
+    if (my_state_is_wont(TELOPT_NAWS))
+       return;
 
 
-    return (char **) (c+1);
-}
+#define        PUTSHORT(cp, x) { if ((*cp++ = ((x)>>8)&0xff) == IAC) *cp++ = IAC; \
+                           if ((*cp++ = ((x))&0xff) == IAC) *cp++ = IAC; }
 
 
-struct cmd *
-getcmd(name)
-char *name;
-{
-    struct cmd *cm;
+    if (TerminalWindowSize(&rows, &cols) == 0) {       /* Failed */
+       return;
+    }
 
 
-    if (cm = (struct cmd *) genget(name, (char **) cmdtab, getnextcmd)) {
-       return cm;
-    } else {
-       return (struct cmd *) genget(name, (char **) cmdtab2, getnextcmd);
+    cp = tmp;
+
+    *cp++ = IAC;
+    *cp++ = SB;
+    *cp++ = TELOPT_NAWS;
+    PUTSHORT(cp, cols);
+    PUTSHORT(cp, rows);
+    *cp++ = IAC;
+    *cp++ = SE;
+    if (NETROOM() >= cp - tmp) {
+       ring_supply_data(&netoring, tmp, cp-tmp);
+       printsub('>', tmp+2, cp - tmp - 2);
     }
 }
 
     }
 }
 
-command(top)
-       int top;
+    void
+tel_enter_binary(rw)
+    int rw;
 {
 {
-       register struct cmd *c;
-
-       setcommandmode();
-       if (!top) {
-               putchar('\n');
-       } else {
-               signal(SIGINT, SIG_DFL);
-               signal(SIGQUIT, SIG_DFL);
-       }
-       for (;;) {
-               printf("%s> ", prompt);
-               if (gets(line) == 0) {
-                       if (feof(stdin))
-                               quit();
-                       break;
-               }
-               if (line[0] == 0)
-                       break;
-               makeargv();
-               c = getcmd(margv[0]);
-               if (c == Ambiguous(struct cmd *)) {
-                       printf("?Ambiguous command\n");
-                       continue;
-               }
-               if (c == 0) {
-                       printf("?Invalid command\n");
-                       continue;
-               }
-               if (c->needconnect && !connected) {
-                       printf("?Need to be connected first.\n");
-                       continue;
-               }
-               if ((*c->handler)(margc, margv)) {
-                       break;
-               }
-       }
-       if (!top) {
-               if (!connected) {
-                       longjmp(toplevel, 1);
-                       /*NOTREACHED*/
-               }
-               setconnmode();
-       }
+    if (rw&1)
+       send_do(TELOPT_BINARY, 1);
+    if (rw&2)
+       send_will(TELOPT_BINARY, 1);
 }
 }
-\f
-/*
- * main.  Parse arguments, invoke the protocol or command parser.
- */
-
 
 
-main(argc, argv)
-       int argc;
-       char *argv[];
+    void
+tel_leave_binary(rw)
+    int rw;
 {
 {
-       sp = getservbyname("telnet", "tcp");
-       if (sp == 0) {
-               fprintf(stderr, "telnet: tcp/telnet: unknown service\n");
-               exit(1);
-       }
-       NetTrace = stdout;
-       ioctl(0, TIOCGETP, (char *)&ottyb);
-       ioctl(0, TIOCGETC, (char *)&otc);
-       ioctl(0, TIOCGLTC, (char *)&oltc);
-#if    defined(LNOFLSH)
-       ioctl(0, TIOCLGET, (char *)&autoflush);
-       autoflush = !(autoflush&LNOFLSH);       /* if LNOFLSH, no autoflush */
-#else  /* LNOFLSH */
-       autoflush = 1;
-#endif /* LNOFLSH */
-       ntc = otc;
-       nltc = oltc;
-       nttyb = ottyb;
-       setbuf(stdin, (char *)0);
-       setbuf(stdout, (char *)0);
-       prompt = argv[0];
-       if (argc > 1 && !strcmp(argv[1], "-d")) {
-               debug = 1;
-               argv++;
-               argc--;
-       }
-       if (argc > 1 && !strcmp(argv[1], "-n")) {
-           argv++;
-           argc--;
-           if (argc > 1) {             /* get file name */
-               NetTrace = fopen(argv[1], "w");
-               argv++;
-               argc--;
-               if (NetTrace == NULL) {
-                   NetTrace = stdout;
-               }
-           }
-       }
-       if (argc != 1) {
-               if (setjmp(toplevel) != 0)
-                       exit(0);
-               tn(argc, argv);
-       }
-       setjmp(toplevel);
-       for (;;)
-               command(1);
+    if (rw&1)
+       send_dont(TELOPT_BINARY, 1);
+    if (rw&2)
+       send_wont(TELOPT_BINARY, 1);
 }
 }