-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.go
571 lines (506 loc) · 11.1 KB
/
server.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
// Copyright 2009 Jeff R. Allen. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file of the Go
// distribution.
package main
import (
"encoding/gob"
"encoding/json"
"flag"
"io"
"log"
"net"
"os"
"runtime"
"time"
)
var managers map[string]*consoleManager
var fake *bool = flag.Bool("fake", false, "run a fake server")
var config *string = flag.String("config", "", "the JSON config file")
func init() {
flag.Parse()
}
func addConsole(cons string, dial string) {
m, ok := managers[cons]
if !ok {
log.Printf("Adding console %v on %v.", cons, dial)
m = NewConsoleManager(cons, dial)
managers[cons] = m
go m.run()
} else {
log.Print("Duplicate console %v, ignoring it.")
}
}
func main() {
managers = make(map[string]*consoleManager)
if *config == "" {
log.Fatal("usage: goconserver -config config.js")
}
r, err := os.OpenFile(*config, os.O_RDONLY, 0)
if err != nil {
log.Fatalf("Cannot read config file %v: %v", *config, err)
}
dec := json.NewDecoder(r)
var conf interface{}
err = dec.Decode(&conf)
if err != nil {
log.Fatal("JSON decode: ", err)
}
hash, ok := conf.(map[string]interface{})
if !ok {
log.Fatal("JSON format error: got %T", conf)
}
consoles, ok := hash["consoles"]
if !ok {
log.Fatal("JSON format error: key consoles not found")
}
c2, ok := consoles.(map[string]interface{})
if !ok {
log.Fatalf("JSON format error: consoles key wrong type, %T", consoles)
}
for k, v := range c2 {
s, ok := v.(string)
if ok {
addConsole(k, s)
} else {
log.Fatal("Dial string for console %v is not a string.", k)
}
}
if *fake {
ready := make(chan bool)
go fakeserver(ready)
_ = <-ready
addConsole("fake", ":2070")
}
l, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal("Cannot start server: ", err)
}
log.Print("Goconserver listening on ", l.Addr())
for {
rw, e := l.Accept()
if e != nil {
log.Print("accept: ", e)
continue
}
c := newConn(rw)
go c.run()
}
}
func fakeserver(ready chan bool) {
l, err := net.Listen("tcp", ":2070")
if err != nil {
log.Fatal("Cannot start fake server: ", err)
}
log.Print("Fake server listening on ", l.Addr())
ready <- true
for {
rw, e := l.Accept()
if e != nil {
log.Print("(fake) accept: ", e)
continue
}
go func() {
for {
var buf [1]byte
n, err := rw.Read(buf[:])
if err != nil || n != 1 {
log.Print("(fake) read error: ", err)
break
}
// just echo their typing back
rw.Write(buf[:])
}
rw.Close()
}()
}
}
type connection struct {
rw net.Conn
}
type connCmd int
const (
Listen connCmd = iota
Write
Take
Steal
Close
)
type connReq struct {
Cmd connCmd
Name string
Input []byte
}
type connReplyCode int
const (
Ok connReplyCode = iota
Err
ReadWrite
ReadOnly
Data
)
type connReply struct {
Code connReplyCode
Err string
Data []byte
}
func newConn(rw net.Conn) (c *connection) {
c = new(connection)
c.rw = rw
return
}
func (c *connection) decoder(ch chan connReq) {
dec := gob.NewDecoder(c.rw)
for {
req := new(connReq)
err := dec.Decode(req)
if err != nil {
if err != io.EOF {
log.Print("connection ", c.rw, ", could not decode: ", err)
}
break
}
ch <- *req
}
close(ch)
}
func (c *connection) run() {
var mgr *consoleManager
evCh := make(chan consoleEvent, 1000)
var inCh chan []byte
reqCh := make(chan connReq)
go c.decoder(reqCh)
enc := gob.NewEncoder(c.rw)
L:
for {
reply := new(connReply)
select {
case req, closed := <-reqCh:
if !closed {
log.Print("connection ", c, " terminated")
break L
}
switch req.Cmd {
default:
log.Print("connection ", c.rw, " bad command")
break L
case Listen:
log.Print("connection ", c.rw, " wants to listen to ", req.Name)
var ok bool
mgr, ok = managers[req.Name]
if !ok {
reply.Code = Err
reply.Err = "unknown console name"
enc.Encode(reply)
} else {
listen := consoleRequest{cmd: conListen, ch: evCh}
mgr.reqCh <- listen
reply.Code = Ok
err := enc.Encode(reply)
if err != nil {
log.Print("connection ", c.rw, " failed to send reply: ", err)
break L
}
}
case Take:
fallthrough
case Steal:
if mgr == nil {
reply.Code = Err
reply.Err = "not connected to a console yet"
} else {
// talk to the consoleManager asynchronously to ask to take ownership
inCh = make(chan []byte, 10)
okCh := make(chan bool)
cmd := conTake
if req.Cmd == Steal {
cmd = conSteal
}
r := consoleRequest{cmd: cmd, inch: inCh, ok: okCh}
mgr.reqCh <- r
ok := <-okCh
if ok {
reply.Code = ReadWrite
} else {
reply.Code = ReadOnly
reply.Err = "another user already has the console for read/write"
close(inCh)
inCh = nil
}
}
err := enc.Encode(reply)
if err != nil {
log.Print("connection ", c.rw, " failed to send reply: ", err)
break L
}
case Write:
//if inCh == nil || closed(inCh) {
if inCh == nil {
// ignore write when we are not owner
log.Print("Write when we don't own the console.")
} else {
log.Print("Writing ", req.Input, " into channel ", inCh)
inCh <- req.Input
runtime.Gosched()
}
case Close:
break L
}
case ev := <-evCh:
reply.Code = Data
reply.Data = ev.data
err := enc.Encode(reply)
if err != nil {
log.Print("connection ", c.rw, ", failed to send data: ", err)
break L
}
}
}
// tell the consoleManager we aren't listening now
close(evCh)
// tell the consoleManager we won't be writing any more
//if inCh != nil && !closed(inCh) {
if inCh != nil {
close(inCh)
}
log.Print("connection ", c.rw, " closing")
c.rw.Close()
}
type consoleEvent struct {
data []byte
}
type consoleCmd int
const (
conListen consoleCmd = iota
conTake
conSteal
)
type consoleRequest struct {
cmd consoleCmd
ch chan consoleEvent
inch chan []byte
ok chan bool // for asynchronous reply
}
type inputReq struct {
data []byte
raw bool
}
type consoleManager struct {
cons, addr string
c net.Conn
quitCh chan bool
dataCh chan []byte
inputCh chan inputReq // from the consoleManager to the sender
owner chan []byte
reqCh chan consoleRequest
}
type listener struct {
ch chan consoleEvent
next *listener
}
func NewConsoleManager(cons, addr string) (m *consoleManager) {
m = new(consoleManager)
m.cons = cons
m.addr = addr
m.quitCh = make(chan bool)
m.dataCh = make(chan []byte, 10)
m.inputCh = make(chan inputReq, 10)
m.reqCh = make(chan consoleRequest, 10)
return
}
func (m *consoleManager) run() {
var listeners *listener
reconnect := true
// keep trying to reconnect
for reconnect {
c, err := net.Dial("tcp", m.addr)
if err != nil {
log.Print("Failed to connect to ", m.cons, ": ", err)
time.Sleep(10 * 1e9)
continue
}
log.Print("Connected to ", m.cons, " on ", m.addr)
m.c = c
connDead := make(chan bool)
go func() { m.send(); close(connDead) }()
go func() { m.recv(); close(connDead) }()
// big event loop for consoleManager
L:
for {
select {
case _ = <-m.quitCh:
reconnect = false
break L
case _ = <-connDead:
break L
case req, closed := <-m.reqCh:
if !closed {
break L
}
if req.cmd == conListen {
l := new(listener)
l.ch = req.ch
l.next = listeners
listeners = l
} else if req.cmd == conTake || req.cmd == conSteal {
if req.cmd == conTake && m.owner != nil {
// not available for taking
req.ok <- false
log.Print("Console not taken")
} else {
log.Print("Console taken by ", req.inch)
m.setOwner(req.inch)
req.ok <- true
}
} else {
log.Print("Ignoring unknown request command: ", req.cmd)
}
case data, closed := <-m.dataCh:
if !closed {
break L
}
// multicast the data to the listeners
for l := listeners; l != nil; l = l.next {
//if closed(l.ch) {
// TODO: need to remove this node from the list, not just mark nil
// l.ch = nil
// log.Print("Marking listener ", l, " no longer active.")
//}
if l.ch != nil {
select {
case l.ch <- consoleEvent{data}:
default:
log.Print("Listener ", l, " lost an event.")
}
}
}
}
}
c.Close()
}
return
}
func (m *consoleManager) setOwner(ch chan []byte) {
if m.owner != nil {
// tell the current owner he's been pwned
close(m.owner)
}
m.owner = ch
// a pump to move things into the console (because
// when we try to do this in the same select as everything
// else, we never see anything on ch
go func(ch chan []byte) {
log.Print("pumper starting for chan ", ch)
for in := range ch {
log.Print("bytes arrived:", len(in))
m.inputCh <- inputReq{data: in, raw: false}
}
m.owner = nil
log.Print("pumper done")
}(ch)
}
type iacState int
const (
None iacState = iota
IAC
IAC2
IACWill
)
func (m *consoleManager) recv() {
var st iacState = None
file, err := os.OpenFile(m.cons, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
log.Printf("Error opening log file %s: %v", file, err)
return
}
for {
var buf [1]byte
n, err := m.c.Read(buf[:])
if err != nil {
if err != io.EOF {
log.Print("Error reading from net: ", err)
}
break
}
switch st {
default:
// huh?
log.Print("Unexpected IAC state", st)
st = None
case None:
if buf[0] == 0xff {
st = IAC
continue
}
// else: keep going below, process byte normally
case IAC:
switch buf[0] {
// don't, do, won't
case 254, 253, 252:
st = IAC2
continue
// will
case 251:
st = IACWill
continue
default:
// IAC IAC, so back to none and handle like a normal char (no continue)
st = None
}
case IAC2:
// we don't care, just eat the byte
st = None
continue
case IACWill:
var iacbuf [3]byte
iacbuf[0] = 255 // IAC
iacbuf[1] = 253 // DO
// we only want to reply "do" for 1 (8-bit) and 3 (sga)
if buf[0] == 1 || buf[0] == 3 {
iacbuf[2] = buf[0]
m.inputCh <- inputReq{raw: true, data: iacbuf[:]}
}
st = None
continue
}
x, err := file.Write(buf[0:n])
if err != nil {
log.Print("Error writing to file: ", err)
return
}
if x != n {
log.Print("Error writing to file: short write", n, "!=", x)
return
}
// send the stuff up to the manager
m.dataCh <- buf[0:n]
}
log.Print("Connection to ", m.cons, " closed.")
}
func (m *consoleManager) send() {
var buf [512]byte
m.c.SetWriteDeadline(time.Now().Add(1 * time.Second))
for req := range m.inputCh {
// for each write, out starts as an empty slice of the buffer,
// and append grows it if necessary, including growing
// the underlying buffer maybe
out := buf[0:0]
for i := 0; i < len(req.data); i++ {
if !req.raw && req.data[i] == 0xff {
out = append(out, 0xff)
}
out = append(out, req.data[i])
}
log.Print("Sending ", len(out), " bytes into m.c")
x, err := m.c.Write(out[:])
if err != nil {
log.Print("Error writing to connection: ", err)
return
}
if x != len(out) {
log.Print("Error writing to connection: short write", x, "!=", len(out))
return
}
}
}
// vim:ts=2