+ int c;
+ int gotterminaltype = 0;
+
+ /*
+ * Try to get a terminal type from the foreign host.
+ */
+
+ {
+ static char sbuf[] = { IAC, DO, TELOPT_TTYPE };
+
+ terminaltype = 0;
+ if (write(f, sbuf, sizeof sbuf) == -1) {
+ syslog(LOG_ERR, "write sbuf: %m\n");
+ exit(1);
+ }
+ for (;;) { /* ugly, but we are VERY early */
+ while ((c = Get(f)) != IAC) {
+ NIACCUM(c);
+ }
+ if ((c = Get(f)) == WILL) {
+ if ((c = Get(f)) == TELOPT_TTYPE) {
+ static char sbbuf[] = { IAC, SB, TELOPT_TTYPE,
+ TELQUAL_SEND, IAC, SE };
+ if (write(f, sbbuf, sizeof sbbuf) == -1) {
+ syslog(LOG_ERR, "write sbbuf: %m\n");
+ exit(1);
+ }
+ break;
+ } else {
+ NIACCUM(IAC);
+ NIACCUM(WILL);
+ NIACCUM(c);
+ }
+ } else if (c == WONT) {
+ if ((c = Get(f)) == TELOPT_TTYPE) {
+ terminaltype = "TERM=network";
+ break;
+ } else {
+ NIACCUM(IAC);
+ NIACCUM(WONT);
+ NIACCUM(c);
+ }
+ } else {
+ NIACCUM(IAC);
+ NIACCUM(c);
+ }
+ }
+ if (!terminaltype) {
+ for (;;) {
+ while ((c = Get(f)) != IAC) {
+ NIACCUM(c);
+ }
+ if ((c = Get(f)) != SB) {
+ NIACCUM(IAC);
+ NIACCUM(c);
+ } else if ((c = Get(f)) != TELOPT_TTYPE) {
+ NIACCUM(IAC);
+ NIACCUM(SB);
+ NIACCUM(c);
+ } else if ((c = Get(f)) != TELQUAL_IS) {
+ NIACCUM(IAC);
+ NIACCUM(SB);
+ NIACCUM(TELOPT_TTYPE);
+ NIACCUM(c);
+ } else { /* Yaaaay! */
+ static char terminalname[5+41] = "TERM=";
+
+ terminaltype = terminalname+strlen(terminalname);
+
+ while (terminaltype <
+ (terminalname + sizeof terminalname-1)) {
+ if ((c = Get(f)) == IAC) {
+ if ((c = Get(f)) == SE) {
+ break; /* done */
+ } else {
+ *terminaltype++ = IAC; /* ? */
+ if (isupper(c)) {
+ c = tolower(c);
+ }
+ *terminaltype++ = c;
+ }
+ } else {
+ if (isupper(c)) {
+ c = tolower(c);
+ }
+ *terminaltype++ = c; /* accumulate name */
+ }
+ }
+ *terminaltype = 0;
+ terminaltype = terminalname;
+ gotterminaltype = 1;
+ break;
+ }
+ }
+ }
+ envinit[0] = terminaltype;
+ envinit[1] = 0;
+ }