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