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