]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - telnet.c
Integrate unfix.org's IPv6 patches up to level 10, with rather a lot
[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
248     Pinger pinger;
249 } *Telnet;
250
251 #define TELNET_MAX_BACKLOG 4096
252
253 #define SB_DELTA 1024
254
255 static void c_write1(Telnet telnet, int c)
256 {
257     int backlog;
258     char cc = (char) c;
259     backlog = from_backend(telnet->frontend, 0, &cc, 1);
260     sk_set_frozen(telnet->s, backlog > TELNET_MAX_BACKLOG);
261 }
262
263 static void log_option(Telnet telnet, char *sender, int cmd, int option)
264 {
265     char *buf;
266     /*
267      * The strange-looking "<?""?>" below is there to avoid a
268      * trigraph - a double question mark followed by > maps to a
269      * closing brace character!
270      */
271     buf = dupprintf("%s:\t%s %s", sender,
272                     (cmd == WILL ? "WILL" : cmd == WONT ? "WONT" :
273                      cmd == DO ? "DO" : cmd == DONT ? "DONT" : "<?""?>"),
274                     telopt(option));
275     logevent(telnet->frontend, buf);
276     sfree(buf);
277 }
278
279 static void send_opt(Telnet telnet, int cmd, int option)
280 {
281     unsigned char b[3];
282
283     b[0] = IAC;
284     b[1] = cmd;
285     b[2] = option;
286     telnet->bufsize = sk_write(telnet->s, (char *)b, 3);
287     log_option(telnet, "client", cmd, option);
288 }
289
290 static void deactivate_option(Telnet telnet, const struct Opt *o)
291 {
292     if (telnet->opt_states[o->index] == REQUESTED ||
293         telnet->opt_states[o->index] == ACTIVE)
294         send_opt(telnet, o->nsend, o->option);
295     telnet->opt_states[o->index] = REALLY_INACTIVE;
296 }
297
298 /*
299  * Generate side effects of enabling or disabling an option.
300  */
301 static void option_side_effects(Telnet telnet, const struct Opt *o, int enabled)
302 {
303     if (o->option == TELOPT_ECHO && o->send == DO)
304         telnet->echoing = !enabled;
305     else if (o->option == TELOPT_SGA && o->send == DO)
306         telnet->editing = !enabled;
307     if (telnet->ldisc)                 /* cause ldisc to notice the change */
308         ldisc_send(telnet->ldisc, NULL, 0, 0);
309
310     /* Ensure we get the minimum options */
311     if (!telnet->activated) {
312         if (telnet->opt_states[o_echo.index] == INACTIVE) {
313             telnet->opt_states[o_echo.index] = REQUESTED;
314             send_opt(telnet, o_echo.send, o_echo.option);
315         }
316         if (telnet->opt_states[o_we_sga.index] == INACTIVE) {
317             telnet->opt_states[o_we_sga.index] = REQUESTED;
318             send_opt(telnet, o_we_sga.send, o_we_sga.option);
319         }
320         if (telnet->opt_states[o_they_sga.index] == INACTIVE) {
321             telnet->opt_states[o_they_sga.index] = REQUESTED;
322             send_opt(telnet, o_they_sga.send, o_they_sga.option);
323         }
324         telnet->activated = TRUE;
325     }
326 }
327
328 static void activate_option(Telnet telnet, const struct Opt *o)
329 {
330     if (o->send == WILL && o->option == TELOPT_NAWS)
331         telnet_size(telnet, telnet->term_width, telnet->term_height);
332     if (o->send == WILL &&
333         (o->option == TELOPT_NEW_ENVIRON ||
334          o->option == TELOPT_OLD_ENVIRON)) {
335         /*
336          * We may only have one kind of ENVIRON going at a time.
337          * This is a hack, but who cares.
338          */
339         deactivate_option(telnet, o->option ==
340                           TELOPT_NEW_ENVIRON ? &o_oenv : &o_nenv);
341     }
342     option_side_effects(telnet, o, 1);
343 }
344
345 static void refused_option(Telnet telnet, const struct Opt *o)
346 {
347     if (o->send == WILL && o->option == TELOPT_NEW_ENVIRON &&
348         telnet->opt_states[o_oenv.index] == INACTIVE) {
349         send_opt(telnet, WILL, TELOPT_OLD_ENVIRON);
350         telnet->opt_states[o_oenv.index] = REQUESTED;
351     }
352     option_side_effects(telnet, o, 0);
353 }
354
355 static void proc_rec_opt(Telnet telnet, int cmd, int option)
356 {
357     const struct Opt *const *o;
358
359     log_option(telnet, "server", cmd, option);
360     for (o = opts; *o; o++) {
361         if ((*o)->option == option && (*o)->ack == cmd) {
362             switch (telnet->opt_states[(*o)->index]) {
363               case REQUESTED:
364                 telnet->opt_states[(*o)->index] = ACTIVE;
365                 activate_option(telnet, *o);
366                 break;
367               case ACTIVE:
368                 break;
369               case INACTIVE:
370                 telnet->opt_states[(*o)->index] = ACTIVE;
371                 send_opt(telnet, (*o)->send, option);
372                 activate_option(telnet, *o);
373                 break;
374               case REALLY_INACTIVE:
375                 send_opt(telnet, (*o)->nsend, option);
376                 break;
377             }
378             return;
379         } else if ((*o)->option == option && (*o)->nak == cmd) {
380             switch (telnet->opt_states[(*o)->index]) {
381               case REQUESTED:
382                 telnet->opt_states[(*o)->index] = INACTIVE;
383                 refused_option(telnet, *o);
384                 break;
385               case ACTIVE:
386                 telnet->opt_states[(*o)->index] = INACTIVE;
387                 send_opt(telnet, (*o)->nsend, option);
388                 option_side_effects(telnet, *o, 0);
389                 break;
390               case INACTIVE:
391               case REALLY_INACTIVE:
392                 break;
393             }
394             return;
395         }
396     }
397     /*
398      * If we reach here, the option was one we weren't prepared to
399      * cope with. So send a negative ack.
400      */
401     send_opt(telnet, (cmd == WILL ? DONT : WONT), option);
402 }
403
404 static void process_subneg(Telnet telnet)
405 {
406     unsigned char b[2048], *p, *q;
407     int var, value, n;
408     char *e;
409
410     switch (telnet->sb_opt) {
411       case TELOPT_TSPEED:
412         if (telnet->sb_len == 1 && telnet->sb_buf[0] == TELQUAL_SEND) {
413             char *logbuf;
414             b[0] = IAC;
415             b[1] = SB;
416             b[2] = TELOPT_TSPEED;
417             b[3] = TELQUAL_IS;
418             strcpy((char *)(b + 4), telnet->cfg.termspeed);
419             n = 4 + strlen(telnet->cfg.termspeed);
420             b[n] = IAC;
421             b[n + 1] = SE;
422             telnet->bufsize = sk_write(telnet->s, (char *)b, n + 2);
423             logevent(telnet->frontend, "server:\tSB TSPEED SEND");
424             logbuf = dupprintf("client:\tSB TSPEED IS %s", telnet->cfg.termspeed);
425             logevent(telnet->frontend, logbuf);
426             sfree(logbuf);
427         } else
428             logevent(telnet->frontend, "server:\tSB TSPEED <something weird>");
429         break;
430       case TELOPT_TTYPE:
431         if (telnet->sb_len == 1 && telnet->sb_buf[0] == TELQUAL_SEND) {
432             char *logbuf;
433             b[0] = IAC;
434             b[1] = SB;
435             b[2] = TELOPT_TTYPE;
436             b[3] = TELQUAL_IS;
437             for (n = 0; telnet->cfg.termtype[n]; n++)
438                 b[n + 4] = (telnet->cfg.termtype[n] >= 'a'
439                             && telnet->cfg.termtype[n] <=
440                             'z' ? telnet->cfg.termtype[n] + 'A' -
441                             'a' : telnet->cfg.termtype[n]);
442             b[n + 4] = IAC;
443             b[n + 5] = SE;
444             telnet->bufsize = sk_write(telnet->s, (char *)b, n + 6);
445             b[n + 4] = 0;
446             logevent(telnet->frontend, "server:\tSB TTYPE SEND");
447             logbuf = dupprintf("client:\tSB TTYPE IS %s", b + 4);
448             logevent(telnet->frontend, logbuf);
449             sfree(logbuf);
450         } else
451             logevent(telnet->frontend, "server:\tSB TTYPE <something weird>\r\n");
452         break;
453       case TELOPT_OLD_ENVIRON:
454       case TELOPT_NEW_ENVIRON:
455         p = telnet->sb_buf;
456         q = p + telnet->sb_len;
457         if (p < q && *p == TELQUAL_SEND) {
458             char *logbuf;
459             p++;
460             logbuf = dupprintf("server:\tSB %s SEND", telopt(telnet->sb_opt));
461             logevent(telnet->frontend, logbuf);
462             sfree(logbuf);
463             if (telnet->sb_opt == TELOPT_OLD_ENVIRON) {
464                 if (telnet->cfg.rfc_environ) {
465                     value = RFC_VALUE;
466                     var = RFC_VAR;
467                 } else {
468                     value = BSD_VALUE;
469                     var = BSD_VAR;
470                 }
471                 /*
472                  * Try to guess the sense of VAR and VALUE.
473                  */
474                 while (p < q) {
475                     if (*p == RFC_VAR) {
476                         value = RFC_VALUE;
477                         var = RFC_VAR;
478                     } else if (*p == BSD_VAR) {
479                         value = BSD_VALUE;
480                         var = BSD_VAR;
481                     }
482                     p++;
483                 }
484             } else {
485                 /*
486                  * With NEW_ENVIRON, the sense of VAR and VALUE
487                  * isn't in doubt.
488                  */
489                 value = RFC_VALUE;
490                 var = RFC_VAR;
491             }
492             b[0] = IAC;
493             b[1] = SB;
494             b[2] = telnet->sb_opt;
495             b[3] = TELQUAL_IS;
496             n = 4;
497             e = telnet->cfg.environmt;
498             while (*e) {
499                 b[n++] = var;
500                 while (*e && *e != '\t')
501                     b[n++] = *e++;
502                 if (*e == '\t')
503                     e++;
504                 b[n++] = value;
505                 while (*e)
506                     b[n++] = *e++;
507                 e++;
508             }
509             if (*telnet->cfg.username) {
510                 b[n++] = var;
511                 b[n++] = 'U';
512                 b[n++] = 'S';
513                 b[n++] = 'E';
514                 b[n++] = 'R';
515                 b[n++] = value;
516                 e = telnet->cfg.username;
517                 while (*e)
518                     b[n++] = *e++;
519             }
520             b[n++] = IAC;
521             b[n++] = SE;
522             telnet->bufsize = sk_write(telnet->s, (char *)b, n);
523             logbuf = dupprintf("client:\tSB %s IS %s%s%s%s",
524                                telopt(telnet->sb_opt),
525                                *telnet->cfg.username ? "USER=" : "",
526                                telnet->cfg.username,
527                                *telnet->cfg.username ? " " : "",
528                                n == 6 ? "<nothing>" :
529                                (*telnet->cfg.environmt ? "<stuff>" : ""));
530             logevent(telnet->frontend, logbuf);
531             sfree(logbuf);
532         }
533         break;
534     }
535 }
536
537 static void do_telnet_read(Telnet telnet, char *buf, int len)
538 {
539
540     while (len--) {
541         int c = (unsigned char) *buf++;
542
543         switch (telnet->state) {
544           case TOP_LEVEL:
545           case SEENCR:
546             if (c == NUL && telnet->state == SEENCR)
547                 telnet->state = TOP_LEVEL;
548             else if (c == IAC)
549                 telnet->state = SEENIAC;
550             else {
551                 if (!telnet->in_synch)
552                     c_write1(telnet, c);
553
554 #if 1
555                 /* I can't get the F***ing winsock to insert the urgent IAC
556                  * into the right position! Even with SO_OOBINLINE it gives
557                  * it to recv too soon. And of course the DM byte (that
558                  * arrives in the same packet!) appears several K later!!
559                  *
560                  * Oh well, we do get the DM in the right place so I'll
561                  * just stop hiding on the next 0xf2 and hope for the best.
562                  */
563                 else if (c == DM)
564                     telnet->in_synch = 0;
565 #endif
566                 if (c == CR && telnet->opt_states[o_they_bin.index] != ACTIVE)
567                     telnet->state = SEENCR;
568                 else
569                     telnet->state = TOP_LEVEL;
570             }
571             break;
572           case SEENIAC:
573             if (c == DO)
574                 telnet->state = SEENDO;
575             else if (c == DONT)
576                 telnet->state = SEENDONT;
577             else if (c == WILL)
578                 telnet->state = SEENWILL;
579             else if (c == WONT)
580                 telnet->state = SEENWONT;
581             else if (c == SB)
582                 telnet->state = SEENSB;
583             else if (c == DM) {
584                 telnet->in_synch = 0;
585                 telnet->state = TOP_LEVEL;
586             } else {
587                 /* ignore everything else; print it if it's IAC */
588                 if (c == IAC) {
589                     c_write1(telnet, c);
590                 }
591                 telnet->state = TOP_LEVEL;
592             }
593             break;
594           case SEENWILL:
595             proc_rec_opt(telnet, WILL, c);
596             telnet->state = TOP_LEVEL;
597             break;
598           case SEENWONT:
599             proc_rec_opt(telnet, WONT, c);
600             telnet->state = TOP_LEVEL;
601             break;
602           case SEENDO:
603             proc_rec_opt(telnet, DO, c);
604             telnet->state = TOP_LEVEL;
605             break;
606           case SEENDONT:
607             proc_rec_opt(telnet, DONT, c);
608             telnet->state = TOP_LEVEL;
609             break;
610           case SEENSB:
611             telnet->sb_opt = c;
612             telnet->sb_len = 0;
613             telnet->state = SUBNEGOT;
614             break;
615           case SUBNEGOT:
616             if (c == IAC)
617                 telnet->state = SUBNEG_IAC;
618             else {
619               subneg_addchar:
620                 if (telnet->sb_len >= telnet->sb_size) {
621                     telnet->sb_size += SB_DELTA;
622                     telnet->sb_buf = sresize(telnet->sb_buf, telnet->sb_size,
623                                              unsigned char);
624                 }
625                 telnet->sb_buf[telnet->sb_len++] = c;
626                 telnet->state = SUBNEGOT;       /* in case we came here by goto */
627             }
628             break;
629           case SUBNEG_IAC:
630             if (c != SE)
631                 goto subneg_addchar;   /* yes, it's a hack, I know, but... */
632             else {
633                 process_subneg(telnet);
634                 telnet->state = TOP_LEVEL;
635             }
636             break;
637         }
638     }
639 }
640
641 static int telnet_closing(Plug plug, const char *error_msg, int error_code,
642                           int calling_back)
643 {
644     Telnet telnet = (Telnet) plug;
645
646     if (telnet->s) {
647         sk_close(telnet->s);
648         telnet->s = NULL;
649         notify_remote_exit(telnet->frontend);
650     }
651     if (error_msg) {
652         /* A socket error has occurred. */
653         logevent(telnet->frontend, error_msg);
654         connection_fatal(telnet->frontend, "%s", error_msg);
655     }                                  /* Otherwise, the remote side closed the connection normally. */
656     return 0;
657 }
658
659 static int telnet_receive(Plug plug, int urgent, char *data, int len)
660 {
661     Telnet telnet = (Telnet) plug;
662     if (urgent)
663         telnet->in_synch = TRUE;
664     do_telnet_read(telnet, data, len);
665     return 1;
666 }
667
668 static void telnet_sent(Plug plug, int bufsize)
669 {
670     Telnet telnet = (Telnet) plug;
671     telnet->bufsize = bufsize;
672 }
673
674 /*
675  * Called to set up the Telnet connection.
676  *
677  * Returns an error message, or NULL on success.
678  *
679  * Also places the canonical host name into `realhost'. It must be
680  * freed by the caller.
681  */
682 static const char *telnet_init(void *frontend_handle, void **backend_handle,
683                                Config *cfg,
684                                char *host, int port, char **realhost,
685                                int nodelay, int keepalive)
686 {
687     static const struct plug_function_table fn_table = {
688         telnet_closing,
689         telnet_receive,
690         telnet_sent
691     };
692     SockAddr addr;
693     const char *err;
694     Telnet telnet;
695
696     telnet = snew(struct telnet_tag);
697     telnet->fn = &fn_table;
698     telnet->cfg = *cfg;                /* STRUCTURE COPY */
699     telnet->s = NULL;
700     telnet->echoing = TRUE;
701     telnet->editing = TRUE;
702     telnet->activated = FALSE;
703     telnet->sb_buf = NULL;
704     telnet->sb_size = 0;
705     telnet->frontend = frontend_handle;
706     telnet->term_width = telnet->cfg.width;
707     telnet->term_height = telnet->cfg.height;
708     telnet->state = TOP_LEVEL;
709     telnet->ldisc = NULL;
710     telnet->pinger = NULL;
711     *backend_handle = telnet;
712
713     /*
714      * Try to find host.
715      */
716     {
717         char *buf;
718         buf = dupprintf("Looking up host \"%s\"%s", host,
719                         (cfg->addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
720                          (cfg->addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" :
721                           "")));
722         logevent(telnet->frontend, buf);
723         sfree(buf);
724     }
725     addr = name_lookup(host, port, realhost, &telnet->cfg, cfg->addressfamily);
726     if ((err = sk_addr_error(addr)) != NULL) {
727         sk_addr_free(addr);
728         return err;
729     }
730
731     if (port < 0)
732         port = 23;                     /* default telnet port */
733
734     /*
735      * Open socket.
736      */
737     {
738         char *buf, addrbuf[100];
739         sk_getaddr(addr, addrbuf, 100);
740         buf = dupprintf("Connecting to %s port %d", addrbuf, port);
741         logevent(telnet->frontend, buf);
742         sfree(buf);
743     }
744     telnet->s = new_connection(addr, *realhost, port, 0, 1,
745                                nodelay, keepalive, (Plug) telnet, &telnet->cfg);
746     if ((err = sk_socket_error(telnet->s)) != NULL)
747         return err;
748
749     telnet->pinger = pinger_new(&telnet->cfg, &telnet_backend, telnet);
750
751     /*
752      * Initialise option states.
753      */
754     if (telnet->cfg.passive_telnet) {
755         const struct Opt *const *o;
756
757         for (o = opts; *o; o++)
758             telnet->opt_states[(*o)->index] = INACTIVE;
759     } else {
760         const struct Opt *const *o;
761
762         for (o = opts; *o; o++) {
763             telnet->opt_states[(*o)->index] = (*o)->initial_state;
764             if (telnet->opt_states[(*o)->index] == REQUESTED)
765                 send_opt(telnet, (*o)->send, (*o)->option);
766         }
767         telnet->activated = TRUE;
768     }
769
770     /*
771      * Set up SYNCH state.
772      */
773     telnet->in_synch = FALSE;
774
775     /*
776      * We can send special commands from the start.
777      */
778     update_specials_menu(telnet->frontend);
779
780     return NULL;
781 }
782
783 static void telnet_free(void *handle)
784 {
785     Telnet telnet = (Telnet) handle;
786
787     sfree(telnet->sb_buf);
788     if (telnet->s)
789         sk_close(telnet->s);
790     if (telnet->pinger)
791         pinger_free(telnet->pinger);
792     sfree(telnet);
793 }
794 /*
795  * Reconfigure the Telnet backend. There's no immediate action
796  * necessary, in this backend: we just save the fresh config for
797  * any subsequent negotiations.
798  */
799 static void telnet_reconfig(void *handle, Config *cfg)
800 {
801     Telnet telnet = (Telnet) handle;
802     pinger_reconfig(telnet->pinger, &telnet->cfg, cfg);
803     telnet->cfg = *cfg;                /* STRUCTURE COPY */
804 }
805
806 /*
807  * Called to send data down the Telnet connection.
808  */
809 static int telnet_send(void *handle, char *buf, int len)
810 {
811     Telnet telnet = (Telnet) handle;
812     unsigned char *p, *end;
813     static const unsigned char iac[2] = { IAC, IAC };
814     static const unsigned char cr[2] = { CR, NUL };
815 #if 0
816     static const unsigned char nl[2] = { CR, LF };
817 #endif
818
819     if (telnet->s == NULL)
820         return 0;
821
822     p = (unsigned char *)buf;
823     end = (unsigned char *)(buf + len);
824     while (p < end) {
825         unsigned char *q = p;
826
827         while (p < end && iswritable(*p))
828             p++;
829         telnet->bufsize = sk_write(telnet->s, (char *)q, p - q);
830
831         while (p < end && !iswritable(*p)) {
832             telnet->bufsize = 
833                 sk_write(telnet->s, (char *)(*p == IAC ? iac : cr), 2);
834             p++;
835         }
836     }
837
838     return telnet->bufsize;
839 }
840
841 /*
842  * Called to query the current socket sendability status.
843  */
844 static int telnet_sendbuffer(void *handle)
845 {
846     Telnet telnet = (Telnet) handle;
847     return telnet->bufsize;
848 }
849
850 /*
851  * Called to set the size of the window from Telnet's POV.
852  */
853 static void telnet_size(void *handle, int width, int height)
854 {
855     Telnet telnet = (Telnet) handle;
856     unsigned char b[24];
857     int n;
858     char *logbuf;
859
860     telnet->term_width = width;
861     telnet->term_height = height;
862
863     if (telnet->s == NULL || telnet->opt_states[o_naws.index] != ACTIVE)
864         return;
865     n = 0;
866     b[n++] = IAC;
867     b[n++] = SB;
868     b[n++] = TELOPT_NAWS;
869     b[n++] = telnet->term_width >> 8;
870     if (b[n-1] == IAC) b[n++] = IAC;   /* duplicate any IAC byte occurs */
871     b[n++] = telnet->term_width & 0xFF;
872     if (b[n-1] == IAC) b[n++] = IAC;   /* duplicate any IAC byte occurs */
873     b[n++] = telnet->term_height >> 8;
874     if (b[n-1] == IAC) b[n++] = IAC;   /* duplicate any IAC byte occurs */
875     b[n++] = telnet->term_height & 0xFF;
876     if (b[n-1] == IAC) b[n++] = IAC;   /* duplicate any IAC byte occurs */
877     b[n++] = IAC;
878     b[n++] = SE;
879     telnet->bufsize = sk_write(telnet->s, (char *)b, n);
880     logbuf = dupprintf("client:\tSB NAWS %d,%d",
881                        telnet->term_width, telnet->term_height);
882     logevent(telnet->frontend, logbuf);
883     sfree(logbuf);
884 }
885
886 /*
887  * Send Telnet special codes.
888  */
889 static void telnet_special(void *handle, Telnet_Special code)
890 {
891     Telnet telnet = (Telnet) handle;
892     unsigned char b[2];
893
894     if (telnet->s == NULL)
895         return;
896
897     b[0] = IAC;
898     switch (code) {
899       case TS_AYT:
900         b[1] = AYT;
901         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
902         break;
903       case TS_BRK:
904         b[1] = BREAK;
905         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
906         break;
907       case TS_EC:
908         b[1] = EC;
909         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
910         break;
911       case TS_EL:
912         b[1] = EL;
913         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
914         break;
915       case TS_GA:
916         b[1] = GA;
917         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
918         break;
919       case TS_NOP:
920         b[1] = NOP;
921         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
922         break;
923       case TS_ABORT:
924         b[1] = ABORT;
925         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
926         break;
927       case TS_AO:
928         b[1] = AO;
929         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
930         break;
931       case TS_IP:
932         b[1] = IP;
933         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
934         break;
935       case TS_SUSP:
936         b[1] = SUSP;
937         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
938         break;
939       case TS_EOR:
940         b[1] = EOR;
941         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
942         break;
943       case TS_EOF:
944         b[1] = xEOF;
945         telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
946         break;
947       case TS_EOL:
948         /* In BINARY mode, CR-LF becomes just CR -
949          * and without the NUL suffix too. */
950         if (telnet->opt_states[o_we_bin.index] == ACTIVE)
951             telnet->bufsize = sk_write(telnet->s, "\r", 1);
952         else
953             telnet->bufsize = sk_write(telnet->s, "\r\n", 2);
954         break;
955       case TS_SYNCH:
956         b[1] = DM;
957         telnet->bufsize = sk_write(telnet->s, (char *)b, 1);
958         telnet->bufsize = sk_write_oob(telnet->s, (char *)(b + 1), 1);
959         break;
960       case TS_RECHO:
961         if (telnet->opt_states[o_echo.index] == INACTIVE ||
962             telnet->opt_states[o_echo.index] == REALLY_INACTIVE) {
963             telnet->opt_states[o_echo.index] = REQUESTED;
964             send_opt(telnet, o_echo.send, o_echo.option);
965         }
966         break;
967       case TS_LECHO:
968         if (telnet->opt_states[o_echo.index] == ACTIVE) {
969             telnet->opt_states[o_echo.index] = REQUESTED;
970             send_opt(telnet, o_echo.nsend, o_echo.option);
971         }
972         break;
973       case TS_PING:
974         if (telnet->opt_states[o_they_sga.index] == ACTIVE) {
975             b[1] = NOP;
976             telnet->bufsize = sk_write(telnet->s, (char *)b, 2);
977         }
978         break;
979       default:
980         break;  /* never heard of it */
981     }
982 }
983
984 static const struct telnet_special *telnet_get_specials(void *handle)
985 {
986     static const struct telnet_special specials[] = {
987         {"Are You There", TS_AYT},
988         {"Break", TS_BRK},
989         {"Synch", TS_SYNCH},
990         {"Erase Character", TS_EC},
991         {"Erase Line", TS_EL},
992         {"Go Ahead", TS_GA},
993         {"No Operation", TS_NOP},
994         {NULL, TS_SEP},
995         {"Abort Process", TS_ABORT},
996         {"Abort Output", TS_AO},
997         {"Interrupt Process", TS_IP},
998         {"Suspend Process", TS_SUSP},
999         {NULL, TS_SEP},
1000         {"End Of Record", TS_EOR},
1001         {"End Of File", TS_EOF},
1002         {NULL, TS_EXITMENU}
1003     };
1004     return specials;
1005 }
1006
1007 static Socket telnet_socket(void *handle)
1008 {
1009     Telnet telnet = (Telnet) handle;
1010     return telnet->s;
1011 }
1012
1013 static int telnet_sendok(void *handle)
1014 {
1015     /* Telnet telnet = (Telnet) handle; */
1016     return 1;
1017 }
1018
1019 static void telnet_unthrottle(void *handle, int backlog)
1020 {
1021     Telnet telnet = (Telnet) handle;
1022     sk_set_frozen(telnet->s, backlog > TELNET_MAX_BACKLOG);
1023 }
1024
1025 static int telnet_ldisc(void *handle, int option)
1026 {
1027     Telnet telnet = (Telnet) handle;
1028     if (option == LD_ECHO)
1029         return telnet->echoing;
1030     if (option == LD_EDIT)
1031         return telnet->editing;
1032     return FALSE;
1033 }
1034
1035 static void telnet_provide_ldisc(void *handle, void *ldisc)
1036 {
1037     Telnet telnet = (Telnet) handle;
1038     telnet->ldisc = ldisc;
1039 }
1040
1041 static void telnet_provide_logctx(void *handle, void *logctx)
1042 {
1043     /* This is a stub. */
1044 }
1045
1046 static int telnet_exitcode(void *handle)
1047 {
1048     Telnet telnet = (Telnet) handle;
1049     if (telnet->s != NULL)
1050         return -1;                     /* still connected */
1051     else
1052         /* Telnet doesn't transmit exit codes back to the client */
1053         return 0;
1054 }
1055
1056 /*
1057  * cfg_info for Telnet does nothing at all.
1058  */
1059 static int telnet_cfg_info(void *handle)
1060 {
1061     return 0;
1062 }
1063
1064 Backend telnet_backend = {
1065     telnet_init,
1066     telnet_free,
1067     telnet_reconfig,
1068     telnet_send,
1069     telnet_sendbuffer,
1070     telnet_size,
1071     telnet_special,
1072     telnet_get_specials,
1073     telnet_socket,
1074     telnet_exitcode,
1075     telnet_sendok,
1076     telnet_ldisc,
1077     telnet_provide_ldisc,
1078     telnet_provide_logctx,
1079     telnet_unthrottle,
1080     telnet_cfg_info,
1081     23
1082 };