]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - telnet.c
Colin's and my fixes to connection_fatal().
[PuTTY.git] / telnet.c
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #include "putty.h"
5
6 #ifndef FALSE
7 #define FALSE 0
8 #endif
9 #ifndef TRUE
10 #define TRUE 1
11 #endif
12
13 #define IAC     255                    /* interpret as command: */
14 #define DONT    254                    /* you are not to use option */
15 #define DO      253                    /* please, you use option */
16 #define WONT    252                    /* I won't use option */
17 #define WILL    251                    /* I will use option */
18 #define SB      250                    /* interpret as subnegotiation */
19 #define SE      240                    /* end sub negotiation */
20
21 #define GA      249                    /* you may reverse the line */
22 #define EL      248                    /* erase the current line */
23 #define EC      247                    /* erase the current character */
24 #define AYT     246                    /* are you there */
25 #define AO      245                    /* abort output--but let prog finish */
26 #define IP      244                    /* interrupt process--permanently */
27 #define BREAK   243                    /* break */
28 #define DM      242                    /* data mark--for connect. cleaning */
29 #define NOP     241                    /* nop */
30 #define EOR     239                    /* end of record (transparent mode) */
31 #define ABORT   238                    /* Abort process */
32 #define SUSP    237                    /* Suspend process */
33 #define xEOF    236                    /* End of file: EOF is already used... */
34
35 #define TELOPT_BINARY   0              /* 8-bit data path */
36 #define TELOPT_ECHO     1              /* echo */
37 #define TELOPT_RCP      2              /* prepare to reconnect */
38 #define TELOPT_SGA      3              /* suppress go ahead */
39 #define TELOPT_NAMS     4              /* approximate message size */
40 #define TELOPT_STATUS   5              /* give status */
41 #define TELOPT_TM       6              /* timing mark */
42 #define TELOPT_RCTE     7              /* remote controlled transmission and echo */
43 #define TELOPT_NAOL     8              /* negotiate about output line width */
44 #define TELOPT_NAOP     9              /* negotiate about output page size */
45 #define TELOPT_NAOCRD   10             /* negotiate about CR disposition */
46 #define TELOPT_NAOHTS   11             /* negotiate about horizontal tabstops */
47 #define TELOPT_NAOHTD   12             /* negotiate about horizontal tab disposition */
48 #define TELOPT_NAOFFD   13             /* negotiate about formfeed disposition */
49 #define TELOPT_NAOVTS   14             /* negotiate about vertical tab stops */
50 #define TELOPT_NAOVTD   15             /* negotiate about vertical tab disposition */
51 #define TELOPT_NAOLFD   16             /* negotiate about output LF disposition */
52 #define TELOPT_XASCII   17             /* extended ascic character set */
53 #define TELOPT_LOGOUT   18             /* force logout */
54 #define TELOPT_BM       19             /* byte macro */
55 #define TELOPT_DET      20             /* data entry terminal */
56 #define TELOPT_SUPDUP   21             /* supdup protocol */
57 #define TELOPT_SUPDUPOUTPUT 22         /* supdup output */
58 #define TELOPT_SNDLOC   23             /* send location */
59 #define TELOPT_TTYPE    24             /* terminal type */
60 #define TELOPT_EOR      25             /* end or record */
61 #define TELOPT_TUID     26             /* TACACS user identification */
62 #define TELOPT_OUTMRK   27             /* output marking */
63 #define TELOPT_TTYLOC   28             /* terminal location number */
64 #define TELOPT_3270REGIME 29           /* 3270 regime */
65 #define TELOPT_X3PAD    30             /* X.3 PAD */
66 #define TELOPT_NAWS     31             /* window size */
67 #define TELOPT_TSPEED   32             /* terminal speed */
68 #define TELOPT_LFLOW    33             /* remote flow control */
69 #define TELOPT_LINEMODE 34             /* Linemode option */
70 #define TELOPT_XDISPLOC 35             /* X Display Location */
71 #define TELOPT_OLD_ENVIRON 36          /* Old - Environment variables */
72 #define TELOPT_AUTHENTICATION 37       /* Authenticate */
73 #define TELOPT_ENCRYPT  38             /* Encryption option */
74 #define TELOPT_NEW_ENVIRON 39          /* New - Environment variables */
75 #define TELOPT_TN3270E  40             /* TN3270 enhancements */
76 #define TELOPT_XAUTH    41
77 #define TELOPT_CHARSET  42             /* Character set */
78 #define TELOPT_RSP      43             /* Remote serial port */
79 #define TELOPT_COM_PORT_OPTION 44      /* Com port control */
80 #define TELOPT_SLE      45             /* Suppress local echo */
81 #define TELOPT_STARTTLS 46             /* Start TLS */
82 #define TELOPT_KERMIT   47             /* Automatic Kermit file transfer */
83 #define TELOPT_SEND_URL 48
84 #define TELOPT_FORWARD_X 49
85 #define TELOPT_PRAGMA_LOGON     138
86 #define TELOPT_SSPI_LOGON       139
87 #define TELOPT_PRAGMA_HEARTBEAT 140
88 #define TELOPT_EXOPL    255            /* extended-options-list */
89
90 #define TELQUAL_IS      0              /* option is... */
91 #define TELQUAL_SEND    1              /* send option */
92 #define TELQUAL_INFO    2              /* ENVIRON: informational version of IS */
93 #define BSD_VAR 1
94 #define BSD_VALUE 0
95 #define RFC_VAR 0
96 #define RFC_VALUE 1
97
98 #define CR 13
99 #define LF 10
100 #define NUL 0
101
102 #define iswritable(x) \
103         ( (x) != IAC && \
104               (telnet->opt_states[o_we_bin.index] == ACTIVE || (x) != CR))
105
106 static char *telopt(int opt)
107 {
108 #define i(x) if (opt == TELOPT_ ## x) return #x;
109     i(BINARY);
110     i(ECHO);
111     i(RCP);
112     i(SGA);
113     i(NAMS);
114     i(STATUS);
115     i(TM);
116     i(RCTE);
117     i(NAOL);
118     i(NAOP);
119     i(NAOCRD);
120     i(NAOHTS);
121     i(NAOHTD);
122     i(NAOFFD);
123     i(NAOVTS);
124     i(NAOVTD);
125     i(NAOLFD);
126     i(XASCII);
127     i(LOGOUT);
128     i(BM);
129     i(DET);
130     i(SUPDUP);
131     i(SUPDUPOUTPUT);
132     i(SNDLOC);
133     i(TTYPE);
134     i(EOR);
135     i(TUID);
136     i(OUTMRK);
137     i(TTYLOC);
138     i(X3PAD);
139     i(NAWS);
140     i(TSPEED);
141     i(LFLOW);
142     i(LINEMODE);
143     i(XDISPLOC);
144     i(OLD_ENVIRON);
145     i(AUTHENTICATION);
146     i(ENCRYPT);
147     i(NEW_ENVIRON);
148     i(TN3270E);
149     i(XAUTH);
150     i(CHARSET);
151     i(RSP);
152     i(COM_PORT_OPTION);
153     i(SLE);
154     i(STARTTLS);
155     i(KERMIT);
156     i(SEND_URL);
157     i(FORWARD_X);
158     i(PRAGMA_LOGON);
159     i(SSPI_LOGON);
160     i(PRAGMA_HEARTBEAT);
161     i(EXOPL);
162 #undef i
163     return "<unknown>";
164 }
165
166 static void telnet_size(void *handle, int width, int height);
167
168 struct Opt {
169     int send;                          /* what we initially send */
170     int nsend;                         /* -ve send if requested to stop it */
171     int ack, nak;                      /* +ve and -ve acknowledgements */
172     int option;                        /* the option code */
173     int index;                         /* index into telnet->opt_states[] */
174     enum {
175         REQUESTED, ACTIVE, INACTIVE, REALLY_INACTIVE
176     } initial_state;
177 };
178
179 enum {
180     OPTINDEX_NAWS,
181     OPTINDEX_TSPEED,
182     OPTINDEX_TTYPE,
183     OPTINDEX_OENV,
184     OPTINDEX_NENV,
185     OPTINDEX_ECHO,
186     OPTINDEX_WE_SGA,
187     OPTINDEX_THEY_SGA,
188     OPTINDEX_WE_BIN,
189     OPTINDEX_THEY_BIN,
190     NUM_OPTS
191 };
192
193 static const struct Opt o_naws =
194     { WILL, WONT, DO, DONT, TELOPT_NAWS, OPTINDEX_NAWS, REQUESTED };
195 static const struct Opt o_tspeed =
196     { WILL, WONT, DO, DONT, TELOPT_TSPEED, OPTINDEX_TSPEED, REQUESTED };
197 static const struct Opt o_ttype =
198     { WILL, WONT, DO, DONT, TELOPT_TTYPE, OPTINDEX_TTYPE, REQUESTED };
199 static const struct Opt o_oenv = { WILL, WONT, DO, DONT, TELOPT_OLD_ENVIRON,
200     OPTINDEX_OENV, INACTIVE
201 };
202 static const struct Opt o_nenv = { WILL, WONT, DO, DONT, TELOPT_NEW_ENVIRON,
203     OPTINDEX_NENV, REQUESTED
204 };
205 static const struct Opt o_echo =
206     { DO, DONT, WILL, WONT, TELOPT_ECHO, OPTINDEX_ECHO, REQUESTED };
207 static const struct Opt o_we_sga =
208     { WILL, WONT, DO, DONT, TELOPT_SGA, OPTINDEX_WE_SGA, REQUESTED };
209 static const struct Opt o_they_sga =
210     { DO, DONT, WILL, WONT, TELOPT_SGA, OPTINDEX_THEY_SGA, REQUESTED };
211 static const struct Opt o_we_bin =
212     { WILL, WONT, DO, DONT, TELOPT_BINARY, OPTINDEX_WE_BIN, INACTIVE };
213 static const struct Opt o_they_bin =
214     { DO, DONT, WILL, WONT, TELOPT_BINARY, OPTINDEX_THEY_BIN, INACTIVE };
215
216 static const struct Opt *const opts[] = {
217     &o_naws, &o_tspeed, &o_ttype, &o_oenv, &o_nenv, &o_echo,
218     &o_we_sga, &o_they_sga, &o_we_bin, &o_they_bin, NULL
219 };
220
221 typedef struct telnet_tag {
222     const struct plug_function_table *fn;
223     /* the above field _must_ be first in the structure */
224
225     Socket s;
226
227     void *frontend;
228     void *ldisc;
229     int term_width, term_height;
230
231     int opt_states[NUM_OPTS];
232
233     int echoing, editing;
234     int activated;
235     int bufsize;
236     int in_synch;
237     int sb_opt, sb_len;
238     unsigned char *sb_buf;
239     int sb_size;
240
241     enum {
242         TOP_LEVEL, SEENIAC, SEENWILL, SEENWONT, SEENDO, SEENDONT,
243             SEENSB, SUBNEGOT, SUBNEG_IAC, SEENCR
244     } state;
245
246     Config cfg;
247 } *Telnet;
248
249 #define TELNET_MAX_BACKLOG 4096
250
251 #define SB_DELTA 1024
252
253 static void c_write1(Telnet telnet, int c)
254 {
255     int backlog;
256     char cc = (char) c;
257     backlog = from_backend(telnet->frontend, 0, &cc, 1);
258     sk_set_frozen(telnet->s, backlog > TELNET_MAX_BACKLOG);
259 }
260
261 static void log_option(Telnet telnet, char *sender, int cmd, int option)
262 {
263     char *buf;
264     /*
265      * The strange-looking "<?""?>" below is there to avoid a
266      * trigraph - a double question mark followed by > maps to a
267      * closing brace character!
268      */
269     buf = dupprintf("%s:\t%s %s", sender,
270                     (cmd == WILL ? "WILL" : cmd == WONT ? "WONT" :
271                      cmd == DO ? "DO" : cmd == DONT ? "DONT" : "<?""?>"),
272                     telopt(option));
273     logevent(telnet->frontend, buf);
274     sfree(buf);
275 }
276
277 static void send_opt(Telnet telnet, int cmd, int option)
278 {
279     unsigned char b[3];
280
281     b[0] = IAC;
282     b[1] = cmd;
283     b[2] = option;
284     telnet->bufsize = sk_write(telnet->s, (char *)b, 3);
285     log_option(telnet, "client", cmd, option);
286 }
287
288 static void deactivate_option(Telnet telnet, const struct Opt *o)
289 {
290     if (telnet->opt_states[o->index] == REQUESTED ||
291         telnet->opt_states[o->index] == ACTIVE)
292         send_opt(telnet, o->nsend, o->option);
293     telnet->opt_states[o->index] = REALLY_INACTIVE;
294 }
295
296 /*
297  * Generate side effects of enabling or disabling an option.
298  */
299 static void option_side_effects(Telnet telnet, const struct Opt *o, int enabled)
300 {
301     if (o->option == TELOPT_ECHO && o->send == DO)
302         telnet->echoing = !enabled;
303     else if (o->option == TELOPT_SGA && o->send == DO)
304         telnet->editing = !enabled;
305     if (telnet->ldisc)                 /* cause ldisc to notice the change */
306         ldisc_send(telnet->ldisc, NULL, 0, 0);
307
308     /* Ensure we get the minimum options */
309     if (!telnet->activated) {
310         if (telnet->opt_states[o_echo.index] == INACTIVE) {
311             telnet->opt_states[o_echo.index] = REQUESTED;
312             send_opt(telnet, o_echo.send, o_echo.option);
313         }
314         if (telnet->opt_states[o_we_sga.index] == INACTIVE) {
315             telnet->opt_states[o_we_sga.index] = REQUESTED;
316             send_opt(telnet, o_we_sga.send, o_we_sga.option);
317         }
318         if (telnet->opt_states[o_they_sga.index] == INACTIVE) {
319             telnet->opt_states[o_they_sga.index] = REQUESTED;
320             send_opt(telnet, o_they_sga.send, o_they_sga.option);
321         }
322         telnet->activated = TRUE;
323     }
324 }
325
326 static void activate_option(Telnet telnet, const struct Opt *o)
327 {
328     if (o->send == WILL && o->option == TELOPT_NAWS)
329         telnet_size(telnet, telnet->term_width, telnet->term_height);
330     if (o->send == WILL &&
331         (o->option == TELOPT_NEW_ENVIRON ||
332          o->option == TELOPT_OLD_ENVIRON)) {
333         /*
334          * We may only have one kind of ENVIRON going at a time.
335          * This is a hack, but who cares.
336          */
337         deactivate_option(telnet, o->option ==
338                           TELOPT_NEW_ENVIRON ? &o_oenv : &o_nenv);
339     }
340     option_side_effects(telnet, o, 1);
341 }
342
343 static void refused_option(Telnet telnet, const struct Opt *o)
344 {
345     if (o->send == WILL && o->option == TELOPT_NEW_ENVIRON &&
346         telnet->opt_states[o_oenv.index] == INACTIVE) {
347         send_opt(telnet, WILL, TELOPT_OLD_ENVIRON);
348         telnet->opt_states[o_oenv.index] = REQUESTED;
349     }
350     option_side_effects(telnet, o, 0);
351 }
352
353 static void proc_rec_opt(Telnet telnet, int cmd, int option)
354 {
355     const struct Opt *const *o;
356
357     log_option(telnet, "server", cmd, option);
358     for (o = opts; *o; o++) {
359         if ((*o)->option == option && (*o)->ack == cmd) {
360             switch (telnet->opt_states[(*o)->index]) {
361               case REQUESTED:
362                 telnet->opt_states[(*o)->index] = ACTIVE;
363                 activate_option(telnet, *o);
364                 break;
365               case ACTIVE:
366                 break;
367               case INACTIVE:
368                 telnet->opt_states[(*o)->index] = ACTIVE;
369                 send_opt(telnet, (*o)->send, option);
370                 activate_option(telnet, *o);
371                 break;
372               case REALLY_INACTIVE:
373                 send_opt(telnet, (*o)->nsend, option);
374                 break;
375             }
376             return;
377         } else if ((*o)->option == option && (*o)->nak == cmd) {
378             switch (telnet->opt_states[(*o)->index]) {
379               case REQUESTED:
380                 telnet->opt_states[(*o)->index] = INACTIVE;
381                 refused_option(telnet, *o);
382                 break;
383               case ACTIVE:
384                 telnet->opt_states[(*o)->index] = INACTIVE;
385                 send_opt(telnet, (*o)->nsend, option);
386                 option_side_effects(telnet, *o, 0);
387                 break;
388               case INACTIVE:
389               case REALLY_INACTIVE:
390                 break;
391             }
392             return;
393         }
394     }
395     /*
396      * If we reach here, the option was one we weren't prepared to
397      * cope with. So send a negative ack.
398      */
399     send_opt(telnet, (cmd == WILL ? DONT : WONT), option);
400 }
401
402 static void process_subneg(Telnet telnet)
403 {
404     unsigned char b[2048], *p, *q;
405     int var, value, n;
406     char *e;
407
408     switch (telnet->sb_opt) {
409       case TELOPT_TSPEED:
410         if (telnet->sb_len == 1 && telnet->sb_buf[0] == TELQUAL_SEND) {
411             char *logbuf;
412             b[0] = IAC;
413             b[1] = SB;
414             b[2] = TELOPT_TSPEED;
415             b[3] = TELQUAL_IS;
416             strcpy((char *)(b + 4), telnet->cfg.termspeed);
417             n = 4 + strlen(telnet->cfg.termspeed);
418             b[n] = IAC;
419             b[n + 1] = SE;
420             telnet->bufsize = sk_write(telnet->s, (char *)b, n + 2);
421             logevent(telnet->frontend, "server:\tSB TSPEED SEND");
422             logbuf = dupprintf("client:\tSB TSPEED IS %s", telnet->cfg.termspeed);
423             logevent(telnet->frontend, logbuf);
424             sfree(logbuf);
425         } else
426             logevent(telnet->frontend, "server:\tSB TSPEED <something weird>");
427         break;
428       case TELOPT_TTYPE:
429         if (telnet->sb_len == 1 && telnet->sb_buf[0] == TELQUAL_SEND) {
430             char *logbuf;
431             b[0] = IAC;
432             b[1] = SB;
433             b[2] = TELOPT_TTYPE;
434             b[3] = TELQUAL_IS;
435             for (n = 0; telnet->cfg.termtype[n]; n++)
436                 b[n + 4] = (telnet->cfg.termtype[n] >= 'a'
437                             && telnet->cfg.termtype[n] <=
438                             'z' ? telnet->cfg.termtype[n] + 'A' -
439                             'a' : telnet->cfg.termtype[n]);
440             b[n + 4] = IAC;
441             b[n + 5] = SE;
442             telnet->bufsize = sk_write(telnet->s, (char *)b, n + 6);
443             b[n + 4] = 0;
444             logevent(telnet->frontend, "server:\tSB TTYPE SEND");
445             logbuf = dupprintf("client:\tSB TTYPE IS %s", b + 4);
446             logevent(telnet->frontend, logbuf);
447             sfree(logbuf);
448         } else
449             logevent(telnet->frontend, "server:\tSB TTYPE <something weird>\r\n");
450         break;
451       case TELOPT_OLD_ENVIRON:
452       case TELOPT_NEW_ENVIRON:
453         p = telnet->sb_buf;
454         q = p + telnet->sb_len;
455         if (p < q && *p == TELQUAL_SEND) {
456             char *logbuf;
457             p++;
458             logbuf = dupprintf("server:\tSB %s SEND", telopt(telnet->sb_opt));
459             logevent(telnet->frontend, logbuf);
460             sfree(logbuf);
461             if (telnet->sb_opt == TELOPT_OLD_ENVIRON) {
462                 if (telnet->cfg.rfc_environ) {
463                     value = RFC_VALUE;
464                     var = RFC_VAR;
465                 } else {
466                     value = BSD_VALUE;
467                     var = BSD_VAR;
468                 }
469                 /*
470                  * Try to guess the sense of VAR and VALUE.
471                  */
472                 while (p < q) {
473                     if (*p == RFC_VAR) {
474                         value = RFC_VALUE;
475                         var = RFC_VAR;
476                     } else if (*p == BSD_VAR) {
477                         value = BSD_VALUE;
478                         var = BSD_VAR;
479                     }
480                     p++;
481                 }
482             } else {
483                 /*
484                  * With NEW_ENVIRON, the sense of VAR and VALUE
485                  * isn't in doubt.
486                  */
487                 value = RFC_VALUE;
488                 var = RFC_VAR;
489             }
490             b[0] = IAC;
491             b[1] = SB;
492             b[2] = telnet->sb_opt;
493             b[3] = TELQUAL_IS;
494             n = 4;
495             e = telnet->cfg.environmt;
496             while (*e) {
497                 b[n++] = var;
498                 while (*e && *e != '\t')
499                     b[n++] = *e++;
500                 if (*e == '\t')
501                     e++;
502                 b[n++] = value;
503                 while (*e)
504                     b[n++] = *e++;
505                 e++;
506             }
507             if (*telnet->cfg.username) {
508                 b[n++] = var;
509                 b[n++] = 'U';
510                 b[n++] = 'S';
511                 b[n++] = 'E';
512                 b[n++] = 'R';
513                 b[n++] = value;
514                 e = telnet->cfg.username;
515                 while (*e)
516                     b[n++] = *e++;
517             }
518             b[n++] = IAC;
519             b[n++] = SE;
520             telnet->bufsize = sk_write(telnet->s, (char *)b, n);
521             logbuf = dupprintf("client:\tSB %s IS %s", telopt(telnet->sb_opt),
522                                n == 6 ? "<nothing>" : "<stuff>");
523             logevent(telnet->frontend, logbuf);
524             sfree(logbuf);
525         }
526         break;
527     }
528 }
529
530 static void do_telnet_read(Telnet telnet, char *buf, int len)
531 {
532
533     while (len--) {
534         int c = (unsigned char) *buf++;
535
536         switch (telnet->state) {
537           case TOP_LEVEL:
538           case SEENCR:
539             if (c == NUL && telnet->state == SEENCR)
540                 telnet->state = TOP_LEVEL;
541             else if (c == IAC)
542                 telnet->state = SEENIAC;
543             else {
544                 if (!telnet->in_synch)
545                     c_write1(telnet, c);
546
547 #if 1
548                 /* I can't get the F***ing winsock to insert the urgent IAC
549                  * into the right position! Even with SO_OOBINLINE it gives
550                  * it to recv too soon. And of course the DM byte (that
551                  * arrives in the same packet!) appears several K later!!
552                  *
553                  * Oh well, we do get the DM in the right place so I'll
554                  * just stop hiding on the next 0xf2 and hope for the best.
555                  */
556                 else if (c == DM)
557                     telnet->in_synch = 0;
558 #endif
559                 if (c == CR && telnet->opt_states[o_they_bin.index] != ACTIVE)
560                     telnet->state = SEENCR;
561                 else
562                     telnet->state = TOP_LEVEL;
563             }
564             break;
565           case SEENIAC:
566             if (c == DO)
567                 telnet->state = SEENDO;
568             else if (c == DONT)
569                 telnet->state = SEENDONT;
570             else if (c == WILL)
571                 telnet->state = SEENWILL;
572             else if (c == WONT)
573                 telnet->state = SEENWONT;
574             else if (c == SB)
575                 telnet->state = SEENSB;
576             else if (c == DM) {
577                 telnet->in_synch = 0;
578                 telnet->state = TOP_LEVEL;
579             } else {
580                 /* ignore everything else; print it if it's IAC */
581                 if (c == IAC) {
582                     c_write1(telnet, c);
583                 }
584                 telnet->state = TOP_LEVEL;
585             }
586             break;
587           case SEENWILL:
588             proc_rec_opt(telnet, WILL, c);
589             telnet->state = TOP_LEVEL;
590             break;
591           case SEENWONT:
592             proc_rec_opt(telnet, WONT, c);
593             telnet->state = TOP_LEVEL;
594             break;
595           case SEENDO:
596             proc_rec_opt(telnet, DO, c);
597             telnet->state = TOP_LEVEL;
598             break;
599           case SEENDONT:
600             proc_rec_opt(telnet, DONT, c);
601             telnet->state = TOP_LEVEL;
602             break;
603           case SEENSB:
604             telnet->sb_opt = c;
605             telnet->sb_len = 0;
606             telnet->state = SUBNEGOT;
607             break;
608           case SUBNEGOT:
609             if (c == IAC)
610                 telnet->state = SUBNEG_IAC;
611             else {
612               subneg_addchar:
613                 if (telnet->sb_len >= telnet->sb_size) {
614                     telnet->sb_size += SB_DELTA;
615                     telnet->sb_buf = sresize(telnet->sb_buf, telnet->sb_size,
616                                              unsigned char);
617                 }
618                 telnet->sb_buf[telnet->sb_len++] = c;
619                 telnet->state = SUBNEGOT;       /* in case we came here by goto */
620             }
621             break;
622           case SUBNEG_IAC:
623             if (c != SE)
624                 goto subneg_addchar;   /* yes, it's a hack, I know, but... */
625             else {
626                 process_subneg(telnet);
627                 telnet->state = TOP_LEVEL;
628             }
629             break;
630         }
631     }
632 }
633
634 static int telnet_closing(Plug plug, char *error_msg, int error_code,
635                           int calling_back)
636 {
637     Telnet telnet = (Telnet) plug;
638
639     if (telnet->s) {
640         sk_close(telnet->s);
641         telnet->s = NULL;
642     }
643     if (error_msg) {
644         /* A socket error has occurred. */
645         logevent(telnet->frontend, error_msg);
646         connection_fatal(telnet->frontend, "%s", error_msg);
647     }                                  /* Otherwise, the remote side closed the connection normally. */
648     return 0;
649 }
650
651 static int telnet_receive(Plug plug, int urgent, char *data, int len)
652 {
653     Telnet telnet = (Telnet) plug;
654     if (urgent)
655         telnet->in_synch = TRUE;
656     do_telnet_read(telnet, data, len);
657     return 1;
658 }
659
660 static void telnet_sent(Plug plug, int bufsize)
661 {
662     Telnet telnet = (Telnet) plug;
663     telnet->bufsize = bufsize;
664 }
665
666 /*
667  * Called to set up the Telnet connection.
668  *
669  * Returns an error message, or NULL on success.
670  *
671  * Also places the canonical host name into `realhost'. It must be
672  * freed by the caller.
673  */
674 static char *telnet_init(void *frontend_handle, void **backend_handle,
675                          Config *cfg,
676                          char *host, int port, char **realhost, int nodelay)
677 {
678     static const struct plug_function_table fn_table = {
679         telnet_closing,
680         telnet_receive,
681         telnet_sent
682     };
683     SockAddr addr;
684     char *err;
685     Telnet telnet;
686
687     telnet = snew(struct telnet_tag);
688     telnet->fn = &fn_table;
689     telnet->cfg = *cfg;                /* STRUCTURE COPY */
690     telnet->s = NULL;
691     telnet->echoing = TRUE;
692     telnet->editing = TRUE;
693     telnet->activated = FALSE;
694     telnet->sb_buf = NULL;
695     telnet->sb_size = 0;
696     telnet->frontend = frontend_handle;
697     telnet->term_width = telnet->cfg.width;
698     telnet->term_height = telnet->cfg.height;
699     telnet->state = TOP_LEVEL;
700     *backend_handle = telnet;
701
702     /*
703      * Try to find host.
704      */
705     {
706         char *buf;
707         buf = dupprintf("Looking up host \"%s\"", host);
708         logevent(telnet->frontend, buf);
709         sfree(buf);
710     }
711     addr = name_lookup(host, port, realhost, &telnet->cfg);
712     if ((err = sk_addr_error(addr)) != NULL)
713         return err;
714
715     if (port < 0)
716         port = 23;                     /* default telnet port */
717
718     /*
719      * Open socket.
720      */
721     {
722         char *buf, addrbuf[100];
723         sk_getaddr(addr, addrbuf, 100);
724         buf = dupprintf("Connecting to %s port %d", addrbuf, port);
725         logevent(telnet->frontend, buf);
726         sfree(buf);
727     }
728     telnet->s = new_connection(addr, *realhost, port, 0, 1,
729                                nodelay, (Plug) telnet, &telnet->cfg);
730     if ((err = sk_socket_error(telnet->s)) != NULL)
731         return err;
732
733     sk_addr_free(addr);
734
735     /*
736      * Initialise option states.
737      */
738     if (telnet->cfg.passive_telnet) {
739         const struct Opt *const *o;
740
741         for (o = opts; *o; o++)
742             telnet->opt_states[(*o)->index] = INACTIVE;
743     } else {
744         const struct Opt *const *o;
745
746         for (o = opts; *o; o++) {
747             telnet->opt_states[(*o)->index] = (*o)->initial_state;
748             if (telnet->opt_states[(*o)->index] == REQUESTED)
749                 send_opt(telnet, (*o)->send, (*o)->option);
750         }
751         telnet->activated = TRUE;
752     }
753
754     /*
755      * Set up SYNCH state.
756      */
757     telnet->in_synch = FALSE;
758
759     return NULL;
760 }
761
762 static void telnet_free(void *handle)
763 {
764     Telnet telnet = (Telnet) handle;
765
766     sfree(telnet->sb_buf);
767     if (telnet->s)
768         sk_close(telnet->s);
769     sfree(telnet);
770 }
771 /*
772  * Reconfigure the Telnet backend. There's no immediate action
773  * necessary, in this backend: we just save the fresh config for
774  * any subsequent negotiations.
775  */
776 static void telnet_reconfig(void *handle, Config *cfg)
777 {
778     Telnet telnet = (Telnet) handle;
779     telnet->cfg = *cfg;                /* STRUCTURE COPY */
780 }
781
782 /*
783  * Called to send data down the Telnet connection.
784  */
785 static int telnet_send(void *handle, char *buf, int len)
786 {
787     Telnet telnet = (Telnet) handle;
788     unsigned char *p, *end;
789     static const unsigned char iac[2] = { IAC, IAC };
790     static const unsigned char cr[2] = { CR, NUL };
791 #if 0
792     static const unsigned char nl[2] = { CR, LF };
793 #endif
794
795     if (telnet->s == NULL)
796         return 0;
797
798     p = (unsigned char *)buf;
799     end = (unsigned char *)(buf + len);
800     while (p < end) {
801         unsigned char *q = p;
802
803         while (p < end && iswritable(*p))
804             p++;
805         telnet->bufsize = sk_write(telnet->s, (char *)q, p - q);
806
807         while (p < end && !iswritable(*p)) {
808             telnet->bufsize = 
809                 sk_write(telnet->s, (char *)(*p == IAC ? iac : cr), 2);
810             p++;
811         }
812     }
813
814     return telnet->bufsize;
815 }
816
817 /*
818  * Called to query the current socket sendability status.
819  */
820 static int telnet_sendbuffer(void *handle)
821 {
822     Telnet telnet = (Telnet) handle;
823     return telnet->bufsize;
824 }
825
826 /*
827  * Called to set the size of the window from Telnet's POV.
828  */
829 static void telnet_size(void *handle, int width, int height)
830 {
831     Telnet telnet = (Telnet) handle;
832     unsigned char b[24];
833     int n;
834     char *logbuf;
835
836     telnet->term_width = width;
837     telnet->term_height = height;
838
839     if (telnet->s == NULL || telnet->opt_states[o_naws.index] != ACTIVE)
840         return;
841     n = 0;
842     b[n++] = IAC;
843     b[n++] = SB;
844     b[n++] = TELOPT_NAWS;
845     b[n++] = telnet->term_width >> 8;
846     if (b[n-1] == IAC) b[n++] = IAC;   /* duplicate any IAC byte occurs */
847     b[n++] = telnet->term_width & 0xFF;
848     if (b[n-1] == IAC) b[n++] = IAC;   /* duplicate any IAC byte occurs */
849     b[n++] = telnet->term_height >> 8;
850     if (b[n-1] == IAC) b[n++] = IAC;   /* duplicate any IAC byte occurs */
851     b[n++] = telnet->term_height & 0xFF;
852     if (b[n-1] == IAC) b[n++] = IAC;   /* duplicate any IAC byte occurs */
853     b[n++] = IAC;
854     b[n++] = SE;
855     telnet->bufsize = sk_write(telnet->s, (char *)b, n);
856     logbuf = dupprintf("client:\tSB NAWS %d,%d",
857                        telnet->term_width, telnet->term_height);
858     logevent(telnet->frontend, logbuf);
859     sfree(logbuf);
860 }
861
862 /*
863  * Send Telnet special codes.
864  */
865 static void telnet_special(void *handle, Telnet_Special code)
866 {
867     Telnet telnet = (Telnet) handle;
868     unsigned char b[2];
869
870     if (telnet->s == NULL)
871         return;
872
873     b[0] = IAC;
874     switch (code) {
875       case TS_AYT:
876         b[1] = AYT;
877         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
878         break;
879       case TS_BRK:
880         b[1] = BREAK;
881         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
882         break;
883       case TS_EC:
884         b[1] = EC;
885         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
886         break;
887       case TS_EL:
888         b[1] = EL;
889         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
890         break;
891       case TS_GA:
892         b[1] = GA;
893         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
894         break;
895       case TS_NOP:
896         b[1] = NOP;
897         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
898         break;
899       case TS_ABORT:
900         b[1] = ABORT;
901         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
902         break;
903       case TS_AO:
904         b[1] = AO;
905         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
906         break;
907       case TS_IP:
908         b[1] = IP;
909         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
910         break;
911       case TS_SUSP:
912         b[1] = SUSP;
913         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
914         break;
915       case TS_EOR:
916         b[1] = EOR;
917         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
918         break;
919       case TS_EOF:
920         b[1] = xEOF;
921         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
922         break;
923       case TS_EOL:
924         /* In BINARY mode, CR-LF becomes just CR -
925          * and without the NUL suffix too. */
926         if (telnet->opt_states[o_we_bin.index] == ACTIVE)
927             telnet->bufsize = sk_write(telnet->s, "\r", 1);
928         else
929             telnet->bufsize = sk_write(telnet->s, "\r\n", 2);
930         break;
931       case TS_SYNCH:
932         b[1] = DM;
933         telnet->bufsize = sk_write(telnet->s, (char *)b, 1);
934         telnet->bufsize = sk_write_oob(telnet->s, (char *)(b + 1), 1);
935         break;
936       case TS_RECHO:
937         if (telnet->opt_states[o_echo.index] == INACTIVE ||
938             telnet->opt_states[o_echo.index] == REALLY_INACTIVE) {
939             telnet->opt_states[o_echo.index] = REQUESTED;
940             send_opt(telnet, o_echo.send, o_echo.option);
941         }
942         break;
943       case TS_LECHO:
944         if (telnet->opt_states[o_echo.index] == ACTIVE) {
945             telnet->opt_states[o_echo.index] = REQUESTED;
946             send_opt(telnet, o_echo.nsend, o_echo.option);
947         }
948         break;
949       case TS_PING:
950         if (telnet->opt_states[o_they_sga.index] == ACTIVE) {
951             b[1] = NOP;
952             telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
953         }
954         break;
955     }
956 }
957
958 static const struct telnet_special *telnet_get_specials(void *handle)
959 {
960     static const struct telnet_special specials[] = {
961         {"Are You There", TS_AYT},
962         {"Break", TS_BRK},
963         {"Synch", TS_SYNCH},
964         {"Erase Character", TS_EC},
965         {"Erase Line", TS_EL},
966         {"Go Ahead", TS_GA},
967         {"No Operation", TS_NOP},
968         {"", 0},
969         {"Abort Process", TS_ABORT},
970         {"Abort Output", TS_AO},
971         {"Interrupt Process", TS_IP},
972         {"Suspend Process", TS_SUSP},
973         {"", 0},
974         {"End Of Record", TS_EOR},
975         {"End Of File", TS_EOF},
976         {NULL, 0}
977     };
978     return specials;
979 }
980
981 static Socket telnet_socket(void *handle)
982 {
983     Telnet telnet = (Telnet) handle;
984     return telnet->s;
985 }
986
987 static int telnet_sendok(void *handle)
988 {
989     /* Telnet telnet = (Telnet) handle; */
990     return 1;
991 }
992
993 static void telnet_unthrottle(void *handle, int backlog)
994 {
995     Telnet telnet = (Telnet) handle;
996     sk_set_frozen(telnet->s, backlog > TELNET_MAX_BACKLOG);
997 }
998
999 static int telnet_ldisc(void *handle, int option)
1000 {
1001     Telnet telnet = (Telnet) handle;
1002     if (option == LD_ECHO)
1003         return telnet->echoing;
1004     if (option == LD_EDIT)
1005         return telnet->editing;
1006     return FALSE;
1007 }
1008
1009 static void telnet_provide_ldisc(void *handle, void *ldisc)
1010 {
1011     Telnet telnet = (Telnet) handle;
1012     telnet->ldisc = ldisc;
1013 }
1014
1015 static void telnet_provide_logctx(void *handle, void *logctx)
1016 {
1017     /* This is a stub. */
1018 }
1019
1020 static int telnet_exitcode(void *handle)
1021 {
1022     Telnet telnet = (Telnet) handle;
1023     if (telnet->s != NULL)
1024         return -1;                     /* still connected */
1025     else
1026         /* Telnet doesn't transmit exit codes back to the client */
1027         return 0;
1028 }
1029
1030 Backend telnet_backend = {
1031     telnet_init,
1032     telnet_free,
1033     telnet_reconfig,
1034     telnet_send,
1035     telnet_sendbuffer,
1036     telnet_size,
1037     telnet_special,
1038     telnet_get_specials,
1039     telnet_socket,
1040     telnet_exitcode,
1041     telnet_sendok,
1042     telnet_ldisc,
1043     telnet_provide_ldisc,
1044     telnet_provide_logctx,
1045     telnet_unthrottle,
1046     23
1047 };