summaryrefslogtreecommitdiff
path: root/sys/src/games/blit/telnet.c
blob: af072acaf3933ef57ff1670531b0a90e0ff9d6aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <u.h>
#include <libc.h>
#include <thread.h>
#include "dat.h"
#include "fns.h"

Channel *telnetrxch, *telnettxch;
extern Channel *uartrxch, *uarttxch;
int teldebug;

enum {
	SE = 240,
	NOP = 241,
	BRK = 243,
	IP = 244,
	AO = 245,
	AYT = 246,
	EC = 247,
	EL = 248,
	GA = 249,
	SB = 250,
	WILL = 251,
	WONT = 252,
	DO = 253,
	DONT = 254,
	IAC = 255,
	
	XMITBIN = 0,
	ECHO = 1,
	SUPRGA = 3,
	LINEEDIT = 34,
	
};

int telfd;

static void
netrproc(void *)
{
	static uchar buf[512];
	int n, c;
	uchar *p;
	
	for(;;){
		n = read(telfd, buf, sizeof(buf));
		if(n < 0) sysfatal("read: %r");
		for(p = buf; p < buf + n; p++){
			c = *p;
			send(telnetrxch, &c);
		}
	}
}

static void
netwproc(void *)
{
	static uchar buf[512];
	int c;
	uchar *p;
	
	for(;;){
		recv(telnettxch, &c);
		p = buf;
		do
			*p++ = c;
		while(nbrecv(telnettxch, &c) > 0);
		if(write(telfd, buf, p - buf) < p - buf)
			sysfatal("write: %r");
	}
}

static void
telnetrthread(void *)
{
	int c;

	for(;;){
		recv(telnetrxch, &c);
		if(c != IAC){
			send(uartrxch, &c);
			continue;
		}
		recv(telnetrxch, &c);
		switch(c){
		case NOP: break;
		case WILL:
			recv(telnetrxch, &c);
			if(teldebug) fprint(2, "WILL %d\n", c);
			break;
		case WONT:
			recv(telnetrxch, &c);
			if(teldebug) fprint(2, "WONT %d\n", c);
			break;
		case DO:
			recv(telnetrxch, &c);
			if(teldebug) fprint(2, "DO %d\n", c);
			break;
		case DONT:
			recv(telnetrxch, &c);
			if(teldebug) fprint(2, "DONT %d\n", c);
			break;
		case IAC:
			send(uartrxch, &c);
			break;
		default:	
			fprint(2, "unknown telnet command %d\n", c);
		}
	}
}

static void
cmd(int a, int b)
{
	send(telnettxch, &a);
	if(b >= 0) send(telnettxch, &b);
}

static void
telnetwthread(void *)
{
	int c;

	for(;;){
		recv(uarttxch, &c);
		send(telnettxch, &c);
		if(c == 0xff)
			send(telnettxch, &c);
	}
}

void
telnetinit(char *dialstr)
{
	telfd = dial(netmkaddr(dialstr, nil, "telnet"), nil, nil, nil);
	if(telfd < 0) sysfatal("dial: %r");
	telnetrxch = chancreate(sizeof(int), 128);
	telnettxch = chancreate(sizeof(int), 128);
	cmd(WILL, XMITBIN);
	cmd(DO, XMITBIN);
	cmd(DONT, ECHO);
	cmd(DO, SUPRGA);
	cmd(WILL, SUPRGA);
	cmd(WONT, LINEEDIT);
	cmd(DONT, LINEEDIT);
	proccreate(netrproc, nil, mainstacksize);
	proccreate(netwproc, nil, mainstacksize);
	threadcreate(telnetrthread, nil, mainstacksize);
	threadcreate(telnetwthread, nil, mainstacksize);
}