AmendHub

Download

jcs

/

subtext

/

telnet.c

 

(View History)

jcs   telnet: Fix some corner cases, add rxvt as vt100 terminal Latest amendment: 637 on 2026-09-18

1 /*
2 * Copyright (c) 2021 joshua stein <jcs@jcs.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17 #include <stdio.h>
18 #include <string.h>
19
20 #include "logger.h"
21 #include "session.h"
22 #include "subtext.h"
23 #include "telnet.h"
24 #include "tcp.h"
25 #include "util.h"
26
27 #define SE 240 /* end of sub-negotiation options */
28 #define NOP 241 /* no operation */
29 #define SB 250 /* start of sub-negotiation options */
30 #define WILL 251 /* confirm willingness to negotiate */
31 #define WONT 252 /* confirm unwillingness to negotiate */
32 #define DO 253 /* indicate willingness to negotiate */
33 #define DONT 254 /* indicate unwillingness to negotiate */
34 #define IAC 255 /* start of a negotiation sequence */
35
36 #define IS 0 /* sub-negotiation */
37 #define SEND 1 /* sub-negotiation */
38
39 #define IAC_BINARY 0 /* Transmit Binary */
40 #define IAC_ECHO 1 /* Echo Option */
41 #define IAC_SGA 3 /* Suppress Go Ahead Option */
42 #define IAC_STATUS 5 /* Status Option */
43 #define IAC_TM 6 /* Timing Mark Option */
44 #define IAC_NAOCRD 10 /* Output Carriage-Return Disposition Option */
45 #define IAC_NAOHTS 11 /* Output Horizontal Tabstops Option */
46 #define IAC_NAOHTD 12 /* Output Horizontal Tab Disposition Option */
47 #define IAC_NAOFFD 13 /* Output Formfeed Disposition Option */
48 #define IAC_NAOVTS 14 /* Output Vertical Tabstops Option */
49 #define IAC_NAOVTD 15 /* Output Vertical Tab Disposition Option */
50 #define IAC_NAOLFD 16 /* Output Linefeed Disposition */
51 #define IAC_XASCII 17 /* Extended Ascii Option */
52 #define IAC_LOGOUT 18 /* Logout Option */
53 #define IAC_BM 19 /* Byte Macro Option */
54 #define IAC_SUPDUP 22 /* SUPDUP-OUTPUT Option */
55 #define IAC_SENDLOC 23 /* SEND-LOCATION Option */
56 #define IAC_TTYPE 24 /* Terminal Type Option */
57 #define IAC_EOR 25 /* End of Record Option */
58 #define IAC_OUTMRK 27 /* Marking Telnet Option */
59 #define IAC_TTYLOC 28 /* Terminal Location Number Option */
60 #define IAC_DET 20 /* Data Entry Terminal Option DODIIS */
61 #define IAC_X3PAD 30 /* X.3 PAD Option */
62 #define IAC_NAWS 31 /* Window Size Option */
63 #define IAC_TSPEED 32 /* Terminal Speed Option */
64 #define IAC_FLOWCTRL 33 /* Remote Flow Control Option */
65 #define IAC_LINEMODE 34 /* Linemode Option */
66 #define IAC_XDISPLOC 35 /* X Display Location Option */
67 #define IAC_ENVIRON 36 /* Environment Option */
68 #define IAC_AUTH 37 /* Authentication */
69 #define IAC_ENCRYPT 38 /* Encryption Option */
70 #define IAC_NEWENV 39 /* Environment Option */
71 #define IAC_CHARSET 42 /* Charset Option */
72 #define IAC_COMPORT 44 /* Com Port Control Option */
73
74 enum {
75 TELNET_PB_STATE_UNUSED = 0,
76 TELNET_PB_STATE_LISTENING,
77 TELNET_PB_STATE_CONNECTED
78 };
79
80 enum {
81 TELNET_IAC_STATE_IDLE = 0,
82 TELNET_IAC_STATE_IAC,
83 TELNET_IAC_STATE_WILL,
84 TELNET_IAC_STATE_WONT,
85 TELNET_IAC_STATE_DO,
86 TELNET_IAC_STATE_DONT,
87 TELNET_IAC_STATE_SB
88 };
89
90 struct telnet_node {
91 short id;
92 short state;
93 char name[8];
94 ip_addr ip;
95 char ip_s[20];
96 struct session *session;
97 unsigned short obuflen;
98 unsigned char obuf[1024];
99 unsigned char ibuf[64];
100 unsigned short ibuflen;
101 unsigned short ibufoff;
102 unsigned short sending_iac;
103 short iac_state;
104 unsigned char iac_sb[128];
105 short sb_len;
106 unsigned short naws_count;
107 /* docs say 4*MTU+1024, but MTU will probably be <1500 */
108 unsigned char tcp_buf[(4 * 1500) + 1024];
109 bool from_trusted_proxy;
110 TCPiopb rcv_pb, send_pb, listen_pb;
111 StreamPtr stream;
112 wdsEntry tcp_wds[2];
113 };
114
115 /* add one to be able to print busy messages */
116 #define MAX_TELNET_NODES (MAX_SESSIONS + 1)
117
118 static struct telnet_node *telnet_nodes[MAX_TELNET_NODES] = { NULL };
119 static struct telnet_node *telnet_listener_node = NULL;
120 static TCPiopb telnet_exit_pb;
121 static TCPStatusPB telnet_status_pb;
122 static bool did_initial_log = false;
123 static UDPiopb udp_ban_pb;
124 static StreamPtr udp_ban_stream = 0;
125 static char *udp_ban_rcv_buf = NULL;
126 #define UDP_BAN_RCV_BUF_SIZE 2048
127 static wdsEntry udp_ban_wds[2];
128 static char udp_ban_send_buf[16];
129
130 /* terminals that will have vt100 set by default */
131 static const char * vt100_terms[] = {
132 "ansi",
133 "rxvt",
134 "screen",
135 "syncterm",
136 "tmux",
137 "vt100",
138 "xterm",
139 NULL,
140 };
141
142 void telnet_deinit(void);
143 void telnet_setup(struct session *session);
144 void telnet_listen_on_node(struct telnet_node *node);
145 short telnet_escape_output(struct session *session);
146 void telnet_output_iac(struct session *session, const char *iacs,
147 size_t len);
148 void telnet_print_busy(struct telnet_node *node);
149
150 struct node_funcs telnet_node_funcs = {
151 telnet_setup,
152 telnet_input,
153 telnet_output,
154 telnet_close
155 };
156
157 void
158 telnet_init(void)
159 {
160 short n, error;
161
162 if (!db->config.telnet_port)
163 return;
164
165 if (_TCPInit() != noErr)
166 panic("Failed initializing MacTCP");
167
168 /* pre-allocate nodes */
169 for (n = 0; n < MAX_TELNET_NODES; n++) {
170 if (telnet_nodes[n] == NULL) {
171 telnet_nodes[n] = xmalloczero(sizeof(struct telnet_node));
172 if (telnet_nodes[n] == NULL)
173 panic("Failed allocating telnet node %d", n);
174 }
175 telnet_nodes[n]->id = n;
176 }
177
178 if (db->config.trusted_proxy_ip != 0 &&
179 db->config.trusted_proxy_udp_port != 0) {
180 udp_ban_rcv_buf = xmalloc(UDP_BAN_RCV_BUF_SIZE);
181 if (udp_ban_rcv_buf == NULL)
182 panic("Failed allocating UDP ban buf");
183 error = _UDPCreate(&udp_ban_pb, &udp_ban_stream,
184 (Ptr)udp_ban_rcv_buf, UDP_BAN_RCV_BUF_SIZE, NULL, NULL,
185 NULL, false);
186 if (error)
187 panic("UDPCreate failed: %d", error);
188 }
189 }
190
191 bool
192 telnet_reinit(void)
193 {
194 telnet_deinit();
195 telnet_init();
196 did_initial_log = false;
197 return true;
198 }
199
200 void
201 telnet_deinit(void)
202 {
203 if (telnet_listener_node) {
204 _TCPRelease(&telnet_exit_pb, telnet_listener_node->stream, nil,
205 nil, false);
206 telnet_listener_node->state = TELNET_PB_STATE_UNUSED;
207 telnet_listener_node = NULL;
208 }
209
210 if (udp_ban_stream) {
211 _UDPRelease(&udp_ban_pb, udp_ban_stream, NULL, false);
212 udp_ban_stream = 0;
213 }
214
215 if (udp_ban_rcv_buf)
216 xfree(&udp_ban_rcv_buf);
217 }
218
219 void
220 telnet_atexit(void)
221 {
222 struct telnet_node *node;
223 short n;
224
225 for (n = 0; n < MAX_TELNET_NODES; n++) {
226 node = telnet_nodes[n];
227 if (!node)
228 continue;
229
230 if (node->state > TELNET_PB_STATE_UNUSED)
231 _TCPRelease(&telnet_exit_pb, node->stream, nil, nil, false);
232
233 xfree(&node);
234 telnet_nodes[n] = NULL;
235 }
236
237 telnet_deinit();
238 }
239
240 void
241 telnet_listen_on_node(struct telnet_node *node)
242 {
243 char ip_s[20];
244 short error, id;
245 ip_addr ip;
246 tcp_port port;
247 long mask;
248
249 id = node->id;
250 memset(node, 0, sizeof(struct telnet_node));
251 node->id = id;
252
253 snprintf(node->name, sizeof(node->name), "ttyt%d", id);
254
255 error = _TCPCreate(&node->listen_pb, &node->stream,
256 (Ptr)&node->tcp_buf, sizeof(node->tcp_buf), nil, nil, nil, false);
257 if (error)
258 panic("TCPCreate[%d] failed: %d", node->id, error);
259
260 error = _TCPGetOurIP(&ip, &mask);
261 if (error)
262 panic("TCPGetOurIP failed: %d", error);
263
264 port = db->config.telnet_port;
265
266 if (!did_initial_log) {
267 long2ip(ip, ip_s);
268 logger_printf("[telnet] Listening on %s:%d", ip_s, port);
269 did_initial_log = true;
270 }
271
272 error = _TCPPassiveOpen(&node->listen_pb, node->stream, nil, nil, &ip,
273 &port, nil, nil, true);
274 if (error)
275 panic("TCPPassiveOpen[%d] on port %d failed: %d",
276 node->id, db->config.telnet_port, error);
277
278 node->state = TELNET_PB_STATE_LISTENING;
279 telnet_listener_node = node;
280 }
281
282 void
283 telnet_idle(void)
284 {
285 struct telnet_node *node;
286 short n, error;
287
288 if (!db->config.telnet_port)
289 return;
290
291 for (n = 0; n < MAX_TELNET_NODES; n++) {
292 node = telnet_nodes[n];
293
294 switch (node->state) {
295 case TELNET_PB_STATE_UNUSED:
296 if (telnet_listener_node == NULL)
297 telnet_listen_on_node(node);
298 break;
299 case TELNET_PB_STATE_LISTENING:
300 error = _TCPStatus(&node->send_pb, node->stream,
301 &telnet_status_pb, nil, nil, false);
302 if (error == connectionDoesntExist) {
303 /*
304 * The connection closed before it could be handled, but
305 * telnet_status_pb.connectionState will still be
306 * listening, so force it into a bogus state to recycle it.
307 */
308 telnet_status_pb.connectionState = -1;
309 }
310
311 switch (telnet_status_pb.connectionState) {
312 case ConnectionStateListening:
313 goto next_node;
314 case ConnectionStateSYNReceived:
315 case ConnectionStateSYNSent:
316 /* TODO: enforce our own timeout on these? */
317 break;
318 case ConnectionStateEstablished: {
319 char *loc = NULL;
320
321 /* start up a new socket for listening */
322 telnet_listener_node = NULL;
323
324 node->ip = telnet_status_pb.remoteHost;
325 long2ip(telnet_status_pb.remoteHost, node->ip_s);
326
327 if (db->config.trusted_proxy_ip != 0 &&
328 db->config.trusted_proxy_ip == node->ip) {
329 node->from_trusted_proxy = true;
330 snprintf(node->name, sizeof(node->name), "ttyw%d",
331 node->id);
332 }
333
334 if (db->ipdb && !node->from_trusted_proxy)
335 loc = ipdb_lookup(db->ipdb, node->ip);
336
337 logger_printf("[%s] New telnet connection from %s%s%s%s%s",
338 node->name, node->ip_s,
339 (loc ? " (" : ""), (loc ? loc : ""), (loc ? ") " : ""),
340 node->from_trusted_proxy ? " (via trusted proxy)" : "");
341
342 node->state = TELNET_PB_STATE_CONNECTED;
343 node->session = session_create(node->name,
344 node->from_trusted_proxy ? "web" : "telnet",
345 &telnet_node_funcs);
346 if (node->session == NULL) {
347 logger_printf("[%s] No free nodes, disconnecting",
348 node->name);
349 telnet_print_busy(node);
350 _TCPRelease(&node->listen_pb, node->stream, nil,
351 nil, false);
352 node->state = TELNET_PB_STATE_UNUSED;
353 if (loc)
354 xfree(&loc);
355 goto next_node;
356 }
357 node->session->cookie = (void *)node;
358 node->session->tspeed = 19200;
359 node->session->is_telnet = true;
360 node->session->log.ip_address = telnet_status_pb.remoteHost;
361 if (node->from_trusted_proxy)
362 node->session->can_nomodem = true;
363 if (loc) {
364 strlcpy(node->session->location, loc,
365 sizeof(node->session->location));
366 strlcpy(node->session->log.location, loc,
367 sizeof(node->session->log.location));
368 xfree(&loc);
369 }
370 break;
371 }
372 default:
373 if (telnet_status_pb.remoteHost == 0)
374 long2ip(node->listen_pb.csParam.open.remoteHost,
375 node->ip_s);
376 else
377 long2ip(telnet_status_pb.remoteHost, node->ip_s);
378
379 logger_printf("[%s] Telnet connection from "
380 "%s in state %d, aborting", node->name, node->ip_s,
381 telnet_status_pb.connectionState);
382
383 if (node->session)
384 node->session->ending = 1;
385 else {
386 _TCPRelease(&node->listen_pb, node->stream, nil, nil,
387 false);
388 node->state = TELNET_PB_STATE_UNUSED;
389 telnet_listener_node = NULL;
390 }
391 goto next_node;
392 }
393 break;
394 case TELNET_PB_STATE_CONNECTED:
395 if (!node->session) {
396 node->state = TELNET_PB_STATE_UNUSED;
397 break;
398 }
399
400 /*
401 * Send buffered data any time we can, the user might not be
402 * in an explicit session_flush() like during chat
403 */
404 telnet_output(node->session);
405 break;
406 }
407
408 next_node:
409 continue;
410 }
411 }
412
413 void
414 telnet_setup(struct session *session)
415 {
416 const char iacs[] = {
417 IAC, WILL, IAC_SGA, /* we will supress go-ahead */
418 IAC, WILL, IAC_ECHO, /* and we will echo for you */
419 IAC, WILL, IAC_BINARY, /* don't mess with binary data we send */
420 IAC, DO, IAC_BINARY, /* and you can send us binary */
421 IAC, DO, IAC_TSPEED, /* send your TSPEED */
422 IAC, DO, IAC_NAWS, /* send your NAWS */
423 IAC, DO, IAC_TTYPE, /* send your TTYPE */
424 IAC, DO, IAC_NEWENV, /* send your NEWENV vars */
425 };
426 struct telnet_node *node = (struct telnet_node *)session->cookie;
427 size_t size = sizeof(iacs);
428
429 if (!node->from_trusted_proxy)
430 /* we only care about NEWENV when we need REMOTE_ADDR */
431 size -= 3;
432
433 telnet_output_iac(session, iacs, size);
434 session_flush(session);
435
436 /* see if we can quickly read and parse any incoming IAC */
437 telnet_input(session);
438 session_flush(session);
439 }
440
441 short
442 telnet_input(struct session *session)
443 {
444 struct telnet_node *node = (struct telnet_node *)session->cookie;
445 unsigned short rlen;
446 short error, n, j, used;
447 unsigned char c;
448 char iac_out[8] = { IAC, 0 };
449
450 error = _TCPStatus(&node->rcv_pb, node->stream, &telnet_status_pb, nil,
451 nil, false);
452 if (error ||
453 telnet_status_pb.connectionState != ConnectionStateEstablished) {
454 session->ending = 1;
455 return 0;
456 }
457
458 if (telnet_status_pb.amtUnreadData == 0)
459 return 0;
460
461 rlen = telnet_status_pb.amtUnreadData;
462
463 if (session->direct_output) {
464 if (session->ibuflen + session->ibufoff + rlen >
465 sizeof(session->ibuf)) {
466 /* if we're already halfway through the buffer, reset */
467 if (session->ibufoff >= (sizeof(session->ibuf) / 2)) {
468 memmove(session->ibuf, session->ibuf + session->ibufoff,
469 session->ibuflen);
470 session->ibufoff = 0;
471 }
472 if (session->ibuflen + session->ibufoff >=
473 sizeof(session->ibuf))
474 return 0;
475 rlen = sizeof(session->ibuf) - session->ibuflen -
476 session->ibufoff;
477 }
478
479 error = _TCPRcv(&node->rcv_pb, node->stream,
480 (Ptr)(session->ibuf + session->ibufoff + session->ibuflen), &rlen,
481 nil, nil, false);
482 if (error) {
483 session_logf(session, "TCP read failed (%d), closing connection",
484 error);
485 session->ending = 1;
486 return 0;
487 }
488 if (rlen == 0)
489 return 0;
490 session->last_input_at = Time;
491 session->ibuflen += rlen;
492 return rlen;
493 }
494
495 if (node->ibuflen + rlen > sizeof(node->ibuf))
496 rlen = sizeof(node->ibuf) - node->ibuflen;
497
498 error = _TCPRcv(&node->rcv_pb, node->stream,
499 (Ptr)(node->ibuf + node->ibuflen), &rlen, nil, nil, false);
500 if (error) {
501 session_logf(session, "TCP read failed (%d), closing connection",
502 error);
503 session->ending = true;
504 return 0;
505 }
506
507 if (rlen == 0)
508 return 0;
509
510 session->last_input_at = Time;
511 node->ibuflen += rlen;
512
513 used = 0;
514 for (n = 0; n < node->ibuflen; n++) {
515 if (session->ibuflen >= sizeof(session->ibuf))
516 break;
517
518 c = node->ibuf[n];
519 used++;
520
521 switch (node->iac_state) {
522 case TELNET_IAC_STATE_IDLE:
523 if (c == IAC)
524 node->iac_state = TELNET_IAC_STATE_IAC;
525 else
526 session->ibuf[session->ibuflen++] = c;
527 break;
528 case TELNET_IAC_STATE_IAC:
529 switch (c) {
530 case IAC:
531 /* escaped iac */
532 session->ibuf[session->ibuflen++] = c;
533 node->iac_state = TELNET_IAC_STATE_IDLE;
534 break;
535 case NOP:
536 node->iac_state = TELNET_IAC_STATE_IDLE;
537 break;
538 case WILL:
539 /* client will do something */
540 node->iac_state = TELNET_IAC_STATE_WILL;
541 break;
542 case WONT:
543 /* client will not do something */
544 node->iac_state = TELNET_IAC_STATE_WONT;
545 break;
546 case DO:
547 /* client wants us to do something */
548 node->iac_state = TELNET_IAC_STATE_DO;
549 break;
550 case DONT:
551 /* client wants us not to do something */
552 node->iac_state = TELNET_IAC_STATE_DONT;
553 break;
554 case SB:
555 /* sub-negotiate */
556 node->iac_state = TELNET_IAC_STATE_SB;
557 node->sb_len = 0;
558 break;
559 default:
560 /* unsupported command, ignore it */
561 node->iac_state = TELNET_IAC_STATE_IDLE;
562 break;
563 }
564 break;
565 case TELNET_IAC_STATE_SB: {
566 unsigned short sboff;
567
568 /* keep reading until we see [^IAC] IAC SE */
569 if (c == SE && node->sb_len > 0 &&
570 node->iac_sb[node->sb_len - 1] == IAC) {
571 switch (node->iac_sb[0]) {
572 case IAC_NAWS:
573 /* IAC SB NAWS 0 80 0 24 (80x24) */
574 /* IAC SB NAWS 1 255 255 1 123 (256x378) */
575 /* if either value is 255, it will be 255,255 */
576 sboff = 1;
577
578 if (node->iac_sb[sboff] == 255)
579 sboff++;
580 session->terminal_columns = (node->iac_sb[sboff++] << 8);
581 if (node->iac_sb[sboff] == 255)
582 sboff++;
583 session->terminal_columns |= node->iac_sb[sboff++];
584
585 if (node->iac_sb[sboff] == 255)
586 sboff++;
587 session->terminal_lines = (node->iac_sb[sboff++] << 8);
588 if (node->iac_sb[sboff] == 255)
589 sboff++;
590 session->terminal_lines |= node->iac_sb[sboff++];
591
592 if (session->terminal_columns < MIN_TERMINAL_COLUMNS)
593 session->terminal_columns = MIN_TERMINAL_COLUMNS;
594 if (session->terminal_lines < MIN_TERMINAL_LINES)
595 session->terminal_lines = MIN_TERMINAL_LINES;
596
597 if (node->naws_count++ < 20)
598 session_logf_buffered(session, "IAC NAWS %d, %d",
599 session->terminal_columns,
600 session->terminal_lines);
601 break;
602 case IAC_TTYPE:
603 /* IAC SB TTYPE IS XTERM IAC SE */
604 node->iac_sb[node->sb_len - 1] = '\0';
605 strlcpy(session->terminal_type,
606 (char *)&node->iac_sb + 2,
607 sizeof(session->terminal_type));
608 session_logf_buffered(session, "IAC TTYPE IS %s",
609 session->terminal_type);
610
611 for (j = 0; vt100_terms[j] != NULL; j++) {
612 if (strncasecmp(session->terminal_type,
613 vt100_terms[j], strlen(vt100_terms[j])) == 0) {
614 session_logf_buffered(session,
615 "Activating vt100 ANSI support for "
616 "matching %s", vt100_terms[j]);
617 session->vt100 = true;
618 break;
619 }
620 }
621
622 break;
623 case IAC_NEWENV: {
624 char k[sizeof(node->iac_sb)], v[sizeof(node->iac_sb)];
625 unsigned char l = 0;
626 bool inv = false;
627 char *loc = NULL;
628
629 k[0] = v[0] = '\0';
630
631 /* \40\0\0USER\1blah\0DISPLAY\1... */
632 for (j = 3; j < node->sb_len; j++) {
633 if (j == node->sb_len - 1 ||
634 node->iac_sb[j] == 0 || node->iac_sb[j] == 3) {
635 v[l] = '\0';
636 if (l) {
637 loc = NULL;
638
639 if (node->from_trusted_proxy &&
640 strcmp(k, "REMOTE_ADDR") == 0) {
641 node->ip = ip2long(v);
642 strlcpy(node->ip_s, v,
643 sizeof(node->ip_s));
644 node->session->log.ip_address =
645 node->ip;
646
647 if (db->ipdb &&
648 (loc = ipdb_lookup(db->ipdb,
649 node->ip))) {
650 strlcpy(node->session->location,
651 loc,
652 sizeof(node->session->location));
653 strlcpy(node->session->log.location,
654 loc,
655 sizeof(node->session->log.location));
656 }
657 }
658
659 session_logf_buffered(session,
660 "NEWENV \"%s\" = \"%s\"%s%s%s", k, v,
661 loc ? " (" : "",
662 loc ? loc : "",
663 loc ? ")" : "");
664
665 if (loc)
666 xfree(&loc);
667 }
668 l = 0;
669 inv = false;
670 } else if (node->iac_sb[j] == 1) {
671 k[l] = '\0';
672 l = 0;
673 inv = true;
674 } else {
675 if (inv)
676 v[l++] = node->iac_sb[j];
677 else
678 k[l++] = node->iac_sb[j];
679 }
680 }
681 break;
682 }
683 case IAC_TSPEED: {
684 unsigned long tspeed;
685
686 /* IAC SB TSPEED IS 38400,19200 SE */
687 node->iac_sb[node->sb_len - 1] = '\0';
688
689 session_logf_buffered(session, "IAC TSPEED IS %s",
690 node->iac_sb + 2);
691
692 for (j = 2; j < node->sb_len; j++) {
693 if (node->iac_sb[j] == ',') {
694 node->iac_sb[j] = '\0';
695 break;
696 }
697 }
698
699 tspeed = atol((const char *)(node->iac_sb + 2));
700 if (tspeed > 0) {
701 if (tspeed > 57600)
702 tspeed = 57600;
703 node->session->tspeed = node->session->log.tspeed =
704 (unsigned short)tspeed;
705 }
706 break;
707 }
708 }
709 node->iac_state = TELNET_IAC_STATE_IDLE;
710 } else {
711 /* accumulate bytes into iac_sb buffer */
712 if (node->sb_len < sizeof(node->iac_sb))
713 node->iac_sb[node->sb_len++] = c;
714 else {
715 /* IAC overflow */
716 node->iac_state = TELNET_IAC_STATE_IDLE;
717 node->sb_len = 0;
718 session_logf(session, "IAC SB overflow");
719 }
720 }
721 break;
722 }
723 case TELNET_IAC_STATE_WILL:
724 switch (c) {
725 case IAC_ECHO:
726 case IAC_SGA:
727 iac_out[1] = DO;
728 iac_out[2] = IAC_ECHO;
729 telnet_output_iac(session, iac_out, 3);
730 break;
731 case IAC_NEWENV:
732 if (!node->from_trusted_proxy)
733 break;
734 case IAC_TTYPE:
735 case IAC_TSPEED:
736 iac_out[1] = SB;
737 iac_out[2] = c;
738 iac_out[3] = SEND;
739 iac_out[4] = IAC;
740 iac_out[5] = SE;
741 telnet_output_iac(session, iac_out, 6);
742 break;
743 case IAC_LINEMODE:
744 #if 0
745 iac_out[1] = SB;
746 iac_out[2] = IAC_LINEMODE;
747 iac_out[3] = 1;
748 iac_out[4] = 0;
749 iac_out[5] = IAC;
750 iac_out[6] = SE;
751 telnet_output_iac(session, iac_out, 7);
752 #endif
753 break;
754 case IAC_ENCRYPT:
755 iac_out[1] = DONT;
756 iac_out[2] = IAC_ENCRYPT;
757 telnet_output_iac(session, iac_out, 3);
758 break;
759 }
760 node->iac_state = TELNET_IAC_STATE_IDLE;
761 break;
762 case TELNET_IAC_STATE_WONT:
763 /* we don't care about any of these yet */
764 node->iac_state = TELNET_IAC_STATE_IDLE;
765 break;
766 case TELNET_IAC_STATE_DO:
767 switch (c) {
768 case IAC_BINARY:
769 iac_out[1] = WILL;
770 iac_out[2] = IAC_BINARY;
771 telnet_output_iac(session, iac_out, 3);
772 break;
773 case IAC_ECHO:
774 case IAC_NAWS:
775 case IAC_TSPEED:
776 case IAC_FLOWCTRL:
777 case IAC_SGA:
778 case IAC_LINEMODE:
779 /* we already sent WILLs for these at the beginning */
780 break;
781 default:
782 iac_out[1] = WONT;
783 iac_out[2] = c;
784 telnet_output_iac(session, iac_out, 3);
785 break;
786 }
787 node->iac_state = TELNET_IAC_STATE_IDLE;
788 break;
789 case TELNET_IAC_STATE_DONT:
790 node->iac_state = TELNET_IAC_STATE_IDLE;
791 break;
792 default:
793 warn("telnet_input in bogus IAC state %d", node->iac_state);
794 break;
795 }
796 }
797
798 if (used == node->ibuflen)
799 node->ibuflen = 0;
800 else {
801 memmove(node->ibuf, node->ibuf + used, node->ibuflen - used);
802 node->ibuflen -= used;
803 }
804
805 if (node->obuflen)
806 session_flush(session);
807
808 return rlen;
809 }
810
811 short
812 telnet_escape_output(struct session *session)
813 {
814 struct telnet_node *node = (struct telnet_node *)session->cookie;
815 unsigned char c;
816 unsigned long added = 0;
817
818 if (session->obuflen == 0 || session->ending)
819 return 0;
820
821 if (session->obuflen == 1 && session->obuf[0] != IAC) {
822 if (node->obuflen >= sizeof(node->obuf))
823 return 0;
824 node->obuf[node->obuflen++] = session->obuf[0];
825 session->obuflen = 0;
826 } else if (session->direct_output) {
827 added = MIN(session->obuflen, sizeof(node->obuf) - node->obuflen);
828 memcpy(node->obuf + node->obuflen, session->obuf, added);
829 node->obuflen += added;
830 } else {
831 /* copy session obuf to node buffer, escaping IACs */
832 for (added = 0; added < session->obuflen; added++) {
833 if (node->obuflen >= sizeof(node->obuf) - 1)
834 break;
835
836 c = session->obuf[added];
837
838 if (!node->sending_iac && c == IAC) {
839 node->obuf[node->obuflen++] = IAC;
840 node->obuf[node->obuflen++] = IAC;
841 } else
842 node->obuf[node->obuflen++] = c;
843 }
844 }
845
846 if (added > 0) {
847 if (added < session->obuflen)
848 memmove(session->obuf, session->obuf + added,
849 session->obuflen - added);
850
851 session->obuflen -= added;
852 }
853
854 return added;
855 }
856
857 short
858 telnet_output(struct session *session)
859 {
860 struct telnet_node *node = (struct telnet_node *)session->cookie;
861 unsigned long now = Ticks;
862 short error, ret = 0;
863
864 if (session->obuflen != 0)
865 telnet_escape_output(session);
866
867 if (node->obuflen == 0 || session->ending)
868 return 0;
869
870 /* wait for previous _TCPSend to complete */
871 while (node->send_pb.ioResult > 0) {
872 if (uthread_current == NULL)
873 /* this was an opportunistic flush anyway, no sense waiting */
874 return 0;
875
876 uthread_yield();
877
878 if (session->ending)
879 return 0;
880 }
881
882 process_result:
883 if (node->tcp_wds[0].length) {
884 /* shift out old data */
885 if (node->obuflen < node->tcp_wds[0].length)
886 panic("data in tcp_wds > obuflen");
887
888 if (node->obuflen > node->tcp_wds[0].length) {
889 memmove(node->obuf, node->obuf + node->tcp_wds[0].length,
890 node->obuflen - node->tcp_wds[0].length);
891 node->obuflen -= node->tcp_wds[0].length;
892 } else
893 node->obuflen = 0;
894
895 node->tcp_wds[0].length = 0;
896
897 if (node->obuflen == 0)
898 return ret;
899 }
900
901 /*
902 * _TCPSend only knows how many wds pointers were passed in when it
903 * reads the next one and its pointer is zero (or size is zero?)
904 */
905 node->tcp_wds[0].ptr = (Ptr)&node->obuf;
906 node->tcp_wds[0].length = node->obuflen;
907 node->tcp_wds[1].ptr = 0;
908 node->tcp_wds[1].length = 0;
909
910 ret = node->tcp_wds[0].length;
911
912 error = _TCPSend(&node->send_pb, node->stream, node->tcp_wds, nil, nil,
913 true);
914 if (error) {
915 warn("TCPSend[%d] failed: %d", node->id, error);
916 session->ending = true;
917 }
918
919 /* if we can send in less than 500ms, avoid a uthread switch */
920 while (Ticks - now <= 30) {
921 if (node->send_pb.ioResult <= 0)
922 goto process_result;
923 }
924
925 return ret;
926 }
927
928 void
929 telnet_output_iac(struct session *session, const char *iacs, size_t len)
930 {
931 struct telnet_node *node = (struct telnet_node *)session->cookie;
932
933 if (session->ending)
934 return;
935
936 telnet_escape_output(session);
937
938 node->sending_iac = 1;
939 session_output(session, iacs, len);
940 telnet_escape_output(session);
941 node->sending_iac = 0;
942 }
943
944 void
945 telnet_close(struct session *session)
946 {
947 struct telnet_node *node = (struct telnet_node *)session->cookie;
948 size_t len;
949 short error;
950 unsigned char *tmp;
951
952 if (node->from_trusted_proxy)
953 session->ban_node_source = false;
954
955 if (session->ban_node_source && !node->from_trusted_proxy &&
956 db->config.trusted_proxy_ip != 0 &&
957 db->config.trusted_proxy_udp_port != 0) {
958 session_logf(session, "Closing telnet connection from %s and "
959 "banning IP", node->ip_s);
960
961 tmp = (unsigned char *)&node->ip;
962 len = snprintf(udp_ban_send_buf, sizeof(udp_ban_send_buf),
963 "%d.%d.%d.%d", tmp[0], tmp[1], tmp[2], tmp[3]);
964 udp_ban_wds[0].ptr = (Ptr)&udp_ban_send_buf;
965 udp_ban_wds[0].length = len;
966 udp_ban_wds[1].ptr = 0;
967 udp_ban_wds[1].length = 0;
968
969 error = _UDPSend(&udp_ban_pb, udp_ban_stream, udp_ban_wds,
970 db->config.trusted_proxy_ip,
971 db->config.trusted_proxy_udp_port, NULL, NULL, false);
972 if (error)
973 session_logf(session, "Failed sending IP ban UDP packet: %d",
974 error);
975 } else {
976 session_logf(session, "Closing telnet connection from %s",
977 node->ip_s);
978
979 _TCPClose(&telnet_exit_pb, node->stream, nil, nil, false);
980 /* TODO: allow some time to fully close? */
981 }
982
983 error = _TCPRelease(&telnet_exit_pb, node->stream, nil, nil, false);
984 if (error) {
985 warn("error shutting down telnet session: %d", error);
986 return;
987 }
988
989 session->cookie = NULL;
990 node->state = TELNET_PB_STATE_UNUSED;
991 }
992
993 void
994 telnet_print_busy(struct telnet_node *node)
995 {
996 size_t len, n, olen;
997 unsigned long now;
998 short error;
999 char *data = NULL;
1000
1001 /* manually print to node without session_output */
1002 if (db->views[DB_VIEW_NO_FREE_NODES]) {
1003 data = db->views[DB_VIEW_NO_FREE_NODES];
1004 len = strlen(data);
1005 for (n = 0, olen = 0; n < len && olen < sizeof(node->obuf) - 1;
1006 n++) {
1007 node->obuf[olen++] = data[n];
1008 if (data[n] == '\r' && data[n + 1] != '\n')
1009 node->obuf[olen++] = '\n';
1010 }
1011 len = olen;
1012 } else {
1013 len = snprintf((char *)&node->obuf, sizeof(node->obuf),
1014 "No free nodes, please call back later.\r\n");
1015 }
1016
1017 node->tcp_wds[0].ptr = (Ptr)&node->obuf;
1018 node->tcp_wds[0].length = len;
1019 node->tcp_wds[1].ptr = 0;
1020 node->tcp_wds[1].length = 0;
1021
1022 now = Ticks;
1023 error = _TCPSend(&node->send_pb, node->stream, node->tcp_wds, nil, nil,
1024 true);
1025 if (error)
1026 return;
1027
1028 for (;;) {
1029 /* spin for 500ms to let the send finish */
1030 if (Ticks - now > 30 || node->send_pb.ioResult <= 0)
1031 return;
1032 }
1033 }