-
Notifications
You must be signed in to change notification settings - Fork 0
/
econ.go
310 lines (262 loc) · 7.02 KB
/
econ.go
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package econ
import (
"bytes"
"context"
"errors"
"fmt"
"time"
"github.com/reiver/go-telnet"
)
var (
// ErrAuthenticationFailed is returned when the external console authentication failed
ErrAuthenticationFailed = errors.New("authentication failed")
// PasswordLine is the line that is expected when the external console requests a password
PasswordLine = "Enter password:"
// AuthenticationSuccessLine is the line that is expected when the external console grants access
AuthenticationSuccessLine = "Authentication successful. External console access granted."
// LogoutCommand is the command that is used to logout from the external console
LogoutCommand = "logout"
)
// DialTo creates a new econ connection that can be used to write or read lines from
// the teeworlds server via the external console. (The New function is a wrapper around DialTo)
// address is the <IP>:<PORT(ec_port)> address
// the password is the one you set via: ec_password
// You may want to decrease the ec_auth_timeout in order to get disconnected faster and not to block
// any of the 4 existing econ slots.
// You can also set your ec_bantime to anything other than 0 in order to ban people that try to connect to you external console and try incorrect credentials
// ec_output_level [1,2] allows to increase the logging level of your external console. This allows for more verbose econ output parsing
func DialTo(address, password string, options ...Option) (conn *Conn, err error) {
c := &Conn{
ctx: context.Background(),
telnetConn: nil,
address: address,
password: password,
maxReconnectDelay: 10 * time.Second,
}
defer func() {
if err != nil {
_ = c.Close()
}
}()
for _, option := range options {
option(c)
}
c.ctx, c.cancel = context.WithCancel(c.ctx)
c.backoff = newBackoffPolicy(max(50*time.Millisecond, c.maxReconnectDelay/20), c.maxReconnectDelay)
err = c.reconnect()
if err != nil {
return nil, err
}
return c, nil
}
// Conn is the telnet connection to a teeworlds external console terminal(econ)
type Conn struct {
ctx context.Context
cancel context.CancelFunc
telnetConn *telnet.Conn
address string
password string
maxReconnectDelay time.Duration
authCommandList []string
backoff backoffFunc
}
// Close must be called when the connection is to be quit
func (c *Conn) Close() (err error) {
c.cancel()
if c.telnetConn != nil {
_ = c.logout()
err = c.telnetConn.Close()
c.telnetConn = nil
}
return err
}
func (c *Conn) logout() error {
return c.unguardedWriteLine(LogoutCommand)
}
// ReadLine reads a line from the external console
// if the connection is lost, it attempts to reconnect multiple times before
// trying to read the line again.
func (c *Conn) ReadLine() (line string, err error) {
err = c.guard(func() (err error) {
line, err = c.unguardedReadLine()
return err
})
return line, err
}
func (c *Conn) guard(f func() error) error {
// try without retry overhead
err := f()
if err == nil {
return nil
}
// add retry overhead
return c.retry(func() (retry bool, err error) {
err = c.reconnect()
if err != nil {
return false, err
}
err = f()
if err == nil {
return false, nil
}
return true, err
})
}
// no reconnect mechanisms guard this line reading
func (c *Conn) unguardedReadLine() (string, error) {
if c.telnetConn == nil {
return "", errors.New("telnet connection is nil")
}
// a line may at most have 256 characters
stackArray := [256]byte{}
stackArraySlice := stackArray[:0]
lineBuffer := bytes.NewBuffer(stackArraySlice)
singleCharBuffer := [1]byte{}
singleCharBufferSlice := singleCharBuffer[:]
// we read single byte arrays until we hit a linebreak
for {
n, err := c.telnetConn.Read(singleCharBufferSlice)
if err != nil {
return "", err
}
// failed to read one byte
if n == 0 {
continue
}
// we do hit a linebreak
// we expect the next two characters to be 0xFF
if singleCharBuffer[0] == '\n' {
buffer := [2]byte{0xFF, 0xFF} // explicitly initialize with non zero value
bufferSlice := buffer[:]
// seemingly every line ends with two \x00\x00
n, err = c.telnetConn.Read(bufferSlice)
if err != nil {
return "", err
}
if n != 2 || !bytes.Equal(bufferSlice, []byte{0x00, 0x00}) {
return "", errors.New("failed to read \\x00\\x00")
}
// successfully got the two 0x00,
// no need to append newline characters here
break
}
// n == 1 && buffer[0] != '\n'
_ = lineBuffer.WriteByte(singleCharBuffer[0])
}
return lineBuffer.String(), nil
}
// WriteLine writes a line to the external console and forces its execution by appending a \n
func (c *Conn) WriteLine(line string) (err error) {
return c.guard(func() error {
return c.unguardedWriteLine(line)
})
}
// WriteLine writes a line to the external console and forces its execution by appending a \n
func (c *Conn) unguardedWriteLine(line string) error {
if c.telnetConn == nil {
return errors.New("telnet connection is nil")
}
stream := []byte(line + "\n")
for len(stream) > 0 {
n, err := c.telnetConn.Write(stream)
if err != nil {
return err
}
stream = stream[n:]
}
return nil
}
func (c *Conn) retry(f func() (bool, error)) error {
t, drained := newTimer(0)
defer closeTimer(t, &drained)
i := 0
var wait time.Duration
for {
// retry
select {
case <-t.C:
drained = true
case <-c.ctx.Done():
return c.ctx.Err()
}
retry, err := f()
if err == nil {
return nil
}
if !retry {
return err
}
i++
wait = c.backoff(i)
resetTimer(t, wait, &drained)
}
}
func (c *Conn) connect() error {
// reconnect tcp connection
telnetConn, err := telnet.DialTo(c.address)
if err != nil {
return err
}
// update internal state
c.telnetConn = telnetConn
return nil
}
func (c *Conn) reconnect() error {
if c.telnetConn != nil {
_ = c.logout()
_ = c.telnetConn.Close()
}
// keep track of the last error that was returned
return c.retry(func() (retry bool, err error) {
err = c.connect()
if err != nil {
return true, err
}
defer func() {
if err != nil {
c.telnetConn.Close()
c.telnetConn = nil
}
}()
err = c.authenticate()
if err == nil {
return false, nil
}
if errors.Is(err, ErrAuthenticationFailed) {
return false, err
}
return true, err
})
}
// authenticate in the external console
func (c *Conn) authenticate() (err error) {
password := c.password
line, err := c.unguardedReadLine()
if err != nil {
// forward network error
return err
}
if line != PasswordLine {
return fmt.Errorf("%w: could not find password request line: %s", ErrAuthenticationFailed, line)
}
err = c.unguardedWriteLine(password)
if err != nil {
// forward network error
return err
}
line, err = c.unguardedReadLine()
if err != nil {
// forward network error
return err
}
if line != AuthenticationSuccessLine {
return fmt.Errorf("%w: %s", ErrAuthenticationFailed, line)
}
for _, cmd := range c.authCommandList {
err = c.unguardedWriteLine(cmd)
if err != nil {
return err
}
}
return nil
}