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