]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - telnet.c
Rethink the whole line discipline architecture. Instead of having
[PuTTY.git] / telnet.c
1 #include <windows.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 #include "putty.h"
6
7 #ifndef FALSE
8 #define FALSE 0
9 #endif
10 #ifndef TRUE
11 #define TRUE 1
12 #endif
13
14 static Socket s = NULL;
15
16 #define IAC     255             /* interpret as command: */
17 #define DONT    254             /* you are not to use option */
18 #define DO      253             /* please, you use option */
19 #define WONT    252             /* I won't use option */
20 #define WILL    251             /* I will use option */
21 #define SB      250             /* interpret as subnegotiation */
22 #define SE      240             /* end sub negotiation */
23
24 #define GA      249             /* you may reverse the line */
25 #define EL      248             /* erase the current line */
26 #define EC      247             /* erase the current character */
27 #define AYT     246             /* are you there */
28 #define AO      245             /* abort output--but let prog finish */
29 #define IP      244             /* interrupt process--permanently */
30 #define BREAK   243             /* break */
31 #define DM      242             /* data mark--for connect. cleaning */
32 #define NOP     241             /* nop */
33 #define EOR     239             /* end of record (transparent mode) */
34 #define ABORT   238             /* Abort process */
35 #define SUSP    237             /* Suspend process */
36 #define xEOF    236             /* End of file: EOF is already used... */
37
38 #define TELOPT_BINARY   0       /* 8-bit data path */
39 #define TELOPT_ECHO     1       /* echo */
40 #define TELOPT_RCP      2       /* prepare to reconnect */
41 #define TELOPT_SGA      3       /* suppress go ahead */
42 #define TELOPT_NAMS     4       /* approximate message size */
43 #define TELOPT_STATUS   5       /* give status */
44 #define TELOPT_TM       6       /* timing mark */
45 #define TELOPT_RCTE     7       /* remote controlled transmission and echo */
46 #define TELOPT_NAOL     8       /* negotiate about output line width */
47 #define TELOPT_NAOP     9       /* negotiate about output page size */
48 #define TELOPT_NAOCRD   10      /* negotiate about CR disposition */
49 #define TELOPT_NAOHTS   11      /* negotiate about horizontal tabstops */
50 #define TELOPT_NAOHTD   12      /* negotiate about horizontal tab disposition */
51 #define TELOPT_NAOFFD   13      /* negotiate about formfeed disposition */
52 #define TELOPT_NAOVTS   14      /* negotiate about vertical tab stops */
53 #define TELOPT_NAOVTD   15      /* negotiate about vertical tab disposition */
54 #define TELOPT_NAOLFD   16      /* negotiate about output LF disposition */
55 #define TELOPT_XASCII   17      /* extended ascic character set */
56 #define TELOPT_LOGOUT   18      /* force logout */
57 #define TELOPT_BM       19      /* byte macro */
58 #define TELOPT_DET      20      /* data entry terminal */
59 #define TELOPT_SUPDUP   21      /* supdup protocol */
60 #define TELOPT_SUPDUPOUTPUT 22  /* supdup output */
61 #define TELOPT_SNDLOC   23      /* send location */
62 #define TELOPT_TTYPE    24      /* terminal type */
63 #define TELOPT_EOR      25      /* end or record */
64 #define TELOPT_TUID     26      /* TACACS user identification */
65 #define TELOPT_OUTMRK   27      /* output marking */
66 #define TELOPT_TTYLOC   28      /* terminal location number */
67 #define TELOPT_3270REGIME 29    /* 3270 regime */
68 #define TELOPT_X3PAD    30      /* X.3 PAD */
69 #define TELOPT_NAWS     31      /* window size */
70 #define TELOPT_TSPEED   32      /* terminal speed */
71 #define TELOPT_LFLOW    33      /* remote flow control */
72 #define TELOPT_LINEMODE 34      /* Linemode option */
73 #define TELOPT_XDISPLOC 35      /* X Display Location */
74 #define TELOPT_OLD_ENVIRON 36   /* Old - Environment variables */
75 #define TELOPT_AUTHENTICATION 37/* Authenticate */
76 #define TELOPT_ENCRYPT  38      /* Encryption option */
77 #define TELOPT_NEW_ENVIRON 39   /* New - Environment variables */
78 #define TELOPT_EXOPL    255     /* extended-options-list */
79
80 #define TELQUAL_IS      0       /* option is... */
81 #define TELQUAL_SEND    1       /* send option */
82 #define TELQUAL_INFO    2       /* ENVIRON: informational version of IS */
83 #define BSD_VAR 1
84 #define BSD_VALUE 0
85 #define RFC_VAR 0
86 #define RFC_VALUE 1
87
88 #define CR 13
89 #define LF 10
90 #define NUL 0
91
92 #define iswritable(x) ( (x) != IAC && (x) != CR )
93
94 static char *telopt(int opt) {
95 #define i(x) if (opt == TELOPT_ ## x) return #x;
96     i(BINARY); i(ECHO); i(RCP); i(SGA); i(NAMS); i(STATUS); i(TM); i(RCTE);
97     i(NAOL); i(NAOP); i(NAOCRD); i(NAOHTS); i(NAOHTD); i(NAOFFD); i(NAOVTS);
98     i(NAOVTD); i(NAOLFD); i(XASCII); i(LOGOUT); i(BM); i(DET); i(SUPDUP);
99     i(SUPDUPOUTPUT); i(SNDLOC); i(TTYPE); i(EOR); i(TUID); i(OUTMRK);
100     i(TTYLOC); i(X3PAD); i(NAWS); i(TSPEED); i(LFLOW); i(LINEMODE);
101     i(XDISPLOC); i(OLD_ENVIRON); i(AUTHENTICATION); i(ENCRYPT);
102     i(NEW_ENVIRON); i(EXOPL);
103 #undef i
104     return "<unknown>";
105 }
106
107 static void telnet_size(void);
108
109 struct Opt {
110     int send;                          /* what we initially send */
111     int nsend;                         /* -ve send if requested to stop it */
112     int ack, nak;                      /* +ve and -ve acknowledgements */
113     int option;                        /* the option code */
114     enum {
115         REQUESTED, ACTIVE, INACTIVE, REALLY_INACTIVE
116     } state;
117 };
118
119 static struct Opt o_naws = {WILL, WONT, DO, DONT, TELOPT_NAWS, REQUESTED};
120 static struct Opt o_tspeed = {WILL, WONT, DO, DONT, TELOPT_TSPEED, REQUESTED};
121 static struct Opt o_ttype = {WILL, WONT, DO, DONT, TELOPT_TTYPE, REQUESTED};
122 static struct Opt o_oenv = {WILL, WONT, DO, DONT, TELOPT_OLD_ENVIRON,
123     INACTIVE};
124 static struct Opt o_nenv = {WILL, WONT, DO, DONT, TELOPT_NEW_ENVIRON,
125     REQUESTED};
126 static struct Opt o_echo = {DO, DONT, WILL, WONT, TELOPT_ECHO, REQUESTED};
127 static struct Opt o_we_sga = {WILL, WONT, DO, DONT, TELOPT_SGA, REQUESTED};
128 static struct Opt o_they_sga = {DO, DONT, WILL, WONT, TELOPT_SGA, REQUESTED};
129
130 static struct Opt *opts[] = {
131     &o_naws, &o_tspeed, &o_ttype, &o_oenv, &o_nenv, &o_echo,
132     &o_we_sga, &o_they_sga, NULL
133 };
134
135 static int echoing = TRUE, editing = TRUE;
136
137 static int in_synch;
138 static int sb_opt, sb_len;
139 static char *sb_buf = NULL;
140 static int sb_size = 0;
141 #define SB_DELTA 1024
142
143 static void c_write1(int c) {
144     char cc = (char)c;
145     from_backend(0, &cc, 1);
146 }
147
148 static void log_option (char *sender, int cmd, int option) {
149     char buf[50];
150     sprintf(buf, "%s:\t%s %s", sender,
151             (cmd == WILL ? "WILL" : cmd == WONT ? "WONT" :
152              cmd == DO ? "DO" : cmd == DONT ? "DONT" : "<??>"),
153             telopt(option));
154     logevent(buf);
155 }
156
157 static void send_opt (int cmd, int option) {
158     unsigned char b[3];
159
160     b[0] = IAC; b[1] = cmd; b[2] = option;
161     sk_write(s, b, 3);
162     log_option("client", cmd, option);
163 }
164
165 static void deactivate_option (struct Opt *o) {
166     if (o->state == REQUESTED || o->state == ACTIVE)
167         send_opt (o->nsend, o->option);
168     o->state = REALLY_INACTIVE;
169 }
170
171 /*
172  * Generate side effects of enabling or disabling an option.
173  */
174 static void option_side_effects(struct Opt *o, int enabled) {
175     if (o->option == TELOPT_ECHO && o->send == DO)
176         echoing = !enabled;
177     else if (o->option = TELOPT_SGA && o->send == DO)
178         editing = !enabled;
179     ldisc_send(NULL, 0);               /* cause ldisc to notice the change */
180 }
181
182 static void activate_option (struct Opt *o) {
183     if (o->send == WILL && o->option == TELOPT_NAWS)
184         telnet_size();
185     if (o->send == WILL &&
186         (o->option == TELOPT_NEW_ENVIRON ||
187          o->option == TELOPT_OLD_ENVIRON)) {
188         /*
189          * We may only have one kind of ENVIRON going at a time.
190          * This is a hack, but who cares.
191          */
192         deactivate_option (o->option==TELOPT_NEW_ENVIRON ? &o_oenv : &o_nenv);
193     }
194     option_side_effects(o, 1);
195 }
196
197 static void refused_option (struct Opt *o) {
198     if (o->send == WILL && o->option == TELOPT_NEW_ENVIRON &&
199         o_oenv.state == INACTIVE) {
200         send_opt (WILL, TELOPT_OLD_ENVIRON);
201         o_oenv.state = REQUESTED;
202     }
203     option_side_effects(o, 0);
204 }
205
206 static void proc_rec_opt (int cmd, int option) {
207     struct Opt **o;
208
209     log_option ("server", cmd, option);
210     for (o = opts; *o; o++) {
211         if ((*o)->option == option && (*o)->ack == cmd) {
212             switch ((*o)->state) {
213               case REQUESTED:
214                 (*o)->state = ACTIVE;
215                 activate_option (*o);
216                 break;
217               case ACTIVE:
218                 break;
219               case INACTIVE:
220                 (*o)->state = ACTIVE;
221                 send_opt ((*o)->send, option);
222                 activate_option (*o);
223                 break;
224               case REALLY_INACTIVE:
225                 send_opt ((*o)->nsend, option);
226                 break;
227             }
228             return;
229         } else if ((*o)->option == option && (*o)->nak == cmd) {
230             switch ((*o)->state) {
231               case REQUESTED:
232                 (*o)->state = INACTIVE;
233                 refused_option (*o);
234                 break;
235               case ACTIVE:
236                 (*o)->state = INACTIVE;
237                 send_opt ((*o)->nsend, option);
238                 option_side_effects(*o, 0);
239                 break;
240               case INACTIVE:
241               case REALLY_INACTIVE:
242                 break;
243             }
244             return;
245         }
246     }
247     /*
248      * If we reach here, the option was one we weren't prepared to
249      * cope with. So send a negative ack.
250      */
251     send_opt ((cmd == WILL ? DONT : WONT), option);
252 }
253
254 static void process_subneg (void) {
255     unsigned char b[2048], *p, *q;
256     int var, value, n;
257     char *e;
258
259     switch (sb_opt) {
260       case TELOPT_TSPEED:
261         if (sb_len == 1 && sb_buf[0] == TELQUAL_SEND) {
262             char logbuf[sizeof(cfg.termspeed)+80];
263             b[0] = IAC; b[1] = SB; b[2] = TELOPT_TSPEED;
264             b[3] = TELQUAL_IS;
265             strcpy(b+4, cfg.termspeed);
266             n = 4 + strlen(cfg.termspeed);
267             b[n] = IAC; b[n+1] = SE;
268             sk_write(s, b, n+2);
269             logevent("server:\tSB TSPEED SEND");
270             sprintf(logbuf, "client:\tSB TSPEED IS %s", cfg.termspeed);
271             logevent (logbuf);
272         } else
273             logevent ("server:\tSB TSPEED <something weird>");
274         break;
275       case TELOPT_TTYPE:
276         if (sb_len == 1 && sb_buf[0] == TELQUAL_SEND) {
277             char logbuf[sizeof(cfg.termtype)+80];
278             b[0] = IAC; b[1] = SB; b[2] = TELOPT_TTYPE;
279             b[3] = TELQUAL_IS;
280             for (n = 0; cfg.termtype[n]; n++)
281                 b[n+4] = (cfg.termtype[n] >= 'a' && cfg.termtype[n] <= 'z' ?
282                           cfg.termtype[n] + 'A'-'a' : cfg.termtype[n]);
283             b[n+4] = IAC; b[n+5] = SE;
284             sk_write(s, b, n+6);
285             b[n+4] = 0;
286             logevent("server:\tSB TTYPE SEND");
287             sprintf(logbuf, "client:\tSB TTYPE IS %s", b+4);
288             logevent(logbuf);
289         } else
290             logevent("server:\tSB TTYPE <something weird>\r\n");
291         break;
292       case TELOPT_OLD_ENVIRON:
293       case TELOPT_NEW_ENVIRON:  
294         p = sb_buf;
295         q = p + sb_len;
296         if (p < q && *p == TELQUAL_SEND) {
297             char logbuf[50];
298             p++;
299             sprintf (logbuf, "server:\tSB %s SEND", telopt(sb_opt));
300             logevent (logbuf);
301             if (sb_opt == TELOPT_OLD_ENVIRON) {
302                 if (cfg.rfc_environ) {
303                     value = RFC_VALUE;
304                     var = RFC_VAR;
305                 } else {
306                     value = BSD_VALUE;
307                     var = BSD_VAR;
308                 }
309                 /*
310                  * Try to guess the sense of VAR and VALUE.
311                  */
312                 while (p < q) {
313                     if (*p == RFC_VAR) {
314                         value = RFC_VALUE;
315                         var = RFC_VAR;
316                     } else if (*p == BSD_VAR) {
317                         value = BSD_VALUE;
318                         var = BSD_VAR;
319                     }
320                     p++;
321                 }
322             } else {
323                 /*
324                  * With NEW_ENVIRON, the sense of VAR and VALUE
325                  * isn't in doubt.
326                  */
327                 value = RFC_VALUE;
328                 var = RFC_VAR;
329             }
330             b[0] = IAC; b[1] = SB; b[2] = sb_opt;
331             b[3] = TELQUAL_IS;
332             n = 4;
333           e = cfg.environmt;
334             while (*e) {
335                 b[n++] = var;
336                 while (*e && *e != '\t') b[n++] = *e++;
337                 if (*e == '\t') e++;
338                 b[n++] = value;
339                 while (*e) b[n++] = *e++;
340                 e++;
341             }
342             if (*cfg.username) {
343                 b[n++] = var; b[n++] = 'U'; b[n++] = 'S';
344                 b[n++] = 'E'; b[n++] = 'R'; b[n++] = value;
345                 e = cfg.username;
346                 while (*e) b[n++] = *e++;
347             }
348             b[n++] = IAC; b[n++] = SE;
349             sk_write(s, b, n);
350             sprintf(logbuf, "client:\tSB %s IS %s", telopt(sb_opt),
351                     n==6 ? "<nothing>" : "<stuff>");
352             logevent (logbuf);
353         }
354         break;
355     }
356 }
357
358 static enum {
359     TOPLEVEL, SEENIAC, SEENWILL, SEENWONT, SEENDO, SEENDONT,
360     SEENSB, SUBNEGOT, SUBNEG_IAC, SEENCR
361 } telnet_state = TOPLEVEL;
362
363 static void do_telnet_read (char *buf, int len) {
364
365     while (len--) {
366         int c = (unsigned char) *buf++;
367
368         switch (telnet_state) {
369           case TOPLEVEL:
370           case SEENCR:
371             if (c == NUL && telnet_state == SEENCR)
372                 telnet_state = TOPLEVEL;
373             else if (c == IAC)
374                 telnet_state = SEENIAC;
375             else {
376                 if (!in_synch)
377                     c_write1(c);
378
379 #if 1
380                 /* I can't get the F***ing winsock to insert the urgent IAC
381                  * into the right position! Even with SO_OOBINLINE it gives
382                  * it to recv too soon. And of course the DM byte (that
383                  * arrives in the same packet!) appears several K later!!
384                  *
385                  * Oh well, we do get the DM in the right place so I'll
386                  * just stop hiding on the next 0xf2 and hope for the best.
387                  */
388                 else if (c == DM) in_synch = 0;
389 #endif
390                 if (c == CR)
391                     telnet_state = SEENCR;
392                 else
393                     telnet_state = TOPLEVEL;
394             }
395             break;
396           case SEENIAC:
397             if (c == DO) telnet_state = SEENDO;
398             else if (c == DONT) telnet_state = SEENDONT;
399             else if (c == WILL) telnet_state = SEENWILL;
400             else if (c == WONT) telnet_state = SEENWONT;
401             else if (c == SB) telnet_state = SEENSB;
402             else if (c == DM) {
403                 in_synch = 0;
404                 telnet_state = TOPLEVEL;
405             } 
406             else {
407                 /* ignore everything else; print it if it's IAC */
408                 if (c == IAC) {
409                     c_write1(c);
410                 }
411                 telnet_state = TOPLEVEL;
412             }
413             break;
414           case SEENWILL:
415             proc_rec_opt (WILL, c);
416             telnet_state = TOPLEVEL;
417             break;
418           case SEENWONT:
419             proc_rec_opt (WONT, c);
420             telnet_state = TOPLEVEL;
421             break;
422           case SEENDO:
423             proc_rec_opt (DO, c);
424             telnet_state = TOPLEVEL;
425             break;
426           case SEENDONT:
427             proc_rec_opt (DONT, c);
428             telnet_state = TOPLEVEL;
429             break;
430           case SEENSB:
431             sb_opt = c;
432             sb_len = 0;
433             telnet_state = SUBNEGOT;
434             break;
435           case SUBNEGOT:
436             if (c == IAC)
437                 telnet_state = SUBNEG_IAC;
438             else {
439                 subneg_addchar:
440                 if (sb_len >= sb_size) {
441                     char *newbuf;
442                     sb_size += SB_DELTA;
443                     newbuf = (sb_buf ?
444                               srealloc(sb_buf, sb_size) :
445                               smalloc(sb_size));
446                     if (newbuf)
447                         sb_buf = newbuf;
448                     else
449                         sb_size -= SB_DELTA;
450                 }
451                 if (sb_len < sb_size)
452                     sb_buf[sb_len++] = c;
453                 telnet_state = SUBNEGOT;/* in case we came here by goto */
454             }
455             break;
456           case SUBNEG_IAC:
457             if (c != SE)
458                 goto subneg_addchar;   /* yes, it's a hack, I know, but... */
459             else {
460                 process_subneg();
461                 telnet_state = TOPLEVEL;
462             }
463             break;
464         }
465     }
466 }
467
468 static int telnet_receive(Socket s, int urgent, char *data, int len) {
469     if (urgent==3) {
470         /* A socket error has occurred. */
471         connection_fatal(data);
472         len = 0;
473     }
474     if (!len) {
475         /* Connection has closed. */
476         sk_close(s);
477         s = NULL;
478         return 0;
479     }
480     do_telnet_read (data, len);
481     return 1;
482 }
483
484 /*
485  * Called to set up the Telnet connection.
486  *
487  * Returns an error message, or NULL on success.
488  *
489  * Also places the canonical host name into `realhost'.
490  */
491 static char *telnet_init (char *host, int port, char **realhost) {
492     SockAddr addr;
493     char *err;
494
495     /*
496      * Try to find host.
497      */
498     addr = sk_namelookup(host, realhost);
499     if ( (err = sk_addr_error(addr)) )
500         return err;
501
502     if (port < 0)
503         port = 23;                     /* default telnet port */
504
505     /*
506      * Open socket.
507      */
508     s = sk_new(addr, port, 0, telnet_receive);
509     if ( (err = sk_socket_error(s)) )
510         return err;
511
512     sk_addr_free(addr);
513
514     /*
515      * Initialise option states.
516      */
517     {
518         struct Opt **o;
519
520         for (o = opts; *o; o++)
521             if ((*o)->state == REQUESTED)
522                 send_opt ((*o)->send, (*o)->option);
523     }
524
525     /*
526      * Set up SYNCH state.
527      */
528     in_synch = FALSE;
529
530     return NULL;
531 }
532
533 /*
534  * Called to send data down the Telnet connection.
535  */
536 static void telnet_send (char *buf, int len) {
537     char *p;
538     static unsigned char iac[2] = { IAC, IAC };
539     static unsigned char cr[2] = { CR, NUL };
540     static unsigned char nl[2] = { CR, LF };
541
542     if (s == NULL)
543         return;
544
545     p = buf;
546     while (p < buf+len) {
547         char *q = p;
548
549         while (iswritable((unsigned char)*p) && p < buf+len) p++;
550         sk_write(s, q, p-q);
551
552         while (p < buf+len && !iswritable((unsigned char)*p)) {
553             sk_write(s, (unsigned char)*p == IAC ? iac : nl, 2);
554             p++;
555         }
556     }
557 }
558
559 /*
560  * Called to set the size of the window from Telnet's POV.
561  */
562 static void telnet_size(void) {
563     unsigned char b[16];
564     char logbuf[50];
565
566     if (s == NULL || o_naws.state != ACTIVE)
567         return;
568     b[0] = IAC; b[1] = SB; b[2] = TELOPT_NAWS;
569     b[3] = cols >> 8; b[4] = cols & 0xFF;
570     b[5] = rows >> 8; b[6] = rows & 0xFF;
571     b[7] = IAC; b[8] = SE;
572     sk_write(s, b, 9);
573     sprintf(logbuf, "client:\tSB NAWS %d,%d",
574             ((unsigned char)b[3] << 8) + (unsigned char)b[4],
575             ((unsigned char)b[5] << 8) + (unsigned char)b[6]);
576     logevent (logbuf);
577 }
578
579 /*
580  * Send Telnet special codes.
581  */
582 static void telnet_special (Telnet_Special code) {
583     unsigned char b[2];
584
585     if (s == NULL)
586         return;
587
588     b[0] = IAC;
589     switch (code) {
590       case TS_AYT: b[1] = AYT; sk_write(s, b, 2); break;
591       case TS_BRK: b[1] = BREAK; sk_write(s, b, 2); break;
592       case TS_EC: b[1] = EC; sk_write(s, b, 2); break;
593       case TS_EL: b[1] = EL; sk_write(s, b, 2); break;
594       case TS_GA: b[1] = GA; sk_write(s, b, 2); break;
595       case TS_NOP: b[1] = NOP; sk_write(s, b, 2); break;
596       case TS_ABORT: b[1] = ABORT; sk_write(s, b, 2); break;
597       case TS_AO: b[1] = AO; sk_write(s, b, 2); break;
598       case TS_IP: b[1] = IP; sk_write(s, b, 2); break;
599       case TS_SUSP: b[1] = SUSP; sk_write(s, b, 2); break;
600       case TS_EOR: b[1] = EOR; sk_write(s, b, 2); break;
601       case TS_EOF: b[1] = xEOF; sk_write(s, b, 2); break;
602       case TS_SYNCH:
603         b[1] = DM;
604         sk_write (s, b, 1);
605         sk_write_oob (s, b+1, 1);
606         break;
607       case TS_RECHO:
608         if (o_echo.state == INACTIVE || o_echo.state == REALLY_INACTIVE) {
609             o_echo.state = REQUESTED;
610             send_opt (o_echo.send, o_echo.option);
611         }
612         break;
613       case TS_LECHO:
614         if (o_echo.state == ACTIVE) {
615             o_echo.state = REQUESTED;
616             send_opt (o_echo.nsend, o_echo.option);
617         }
618         break;
619       case TS_PING: 
620         if (o_they_sga.state == ACTIVE) {
621             b[1] = NOP; 
622             sk_write(s, b, 2); 
623         }
624         break;
625     }
626 }
627
628 static Socket telnet_socket(void) { return s; }
629
630 static int telnet_sendok(void) { return 1; }
631
632 static int telnet_ldisc(int option) {
633     if (option == LD_ECHO) return echoing;
634     if (option == LD_EDIT) return editing;
635     return FALSE;
636 }
637
638 Backend telnet_backend = {
639     telnet_init,
640     telnet_send,
641     telnet_size,
642     telnet_special,
643     telnet_socket,
644     telnet_sendok,
645     telnet_ldisc,
646     23
647 };