-
Notifications
You must be signed in to change notification settings - Fork 71
/
control.go
110 lines (87 loc) · 1.81 KB
/
control.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
package tunnel
import (
"encoding/json"
"errors"
"net"
"sync"
)
var errControlClosed = errors.New("control connection is closed")
type control struct {
// enc and dec are responsible for encoding and decoding json values forth
// and back
enc *json.Encoder
dec *json.Decoder
// underlying connection responsible for encoder and decoder
nc net.Conn
// identifier associated with this control
identifier string
mu sync.Mutex // guards the following
closed bool // if Close() and quits
}
func newControl(nc net.Conn) *control {
c := &control{
enc: json.NewEncoder(nc),
dec: json.NewDecoder(nc),
nc: nc,
}
return c
}
func (c *control) send(v interface{}) error {
if c.enc == nil {
return errors.New("encoder is not initialized")
}
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return errControlClosed
}
c.mu.Unlock()
return c.enc.Encode(v)
}
func (c *control) recv(v interface{}) error {
if c.dec == nil {
return errors.New("decoder is not initialized")
}
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return errControlClosed
}
c.mu.Unlock()
return c.dec.Decode(v)
}
func (c *control) Close() error {
if c.nc == nil {
return nil
}
c.mu.Lock()
c.closed = true
c.mu.Unlock()
return c.nc.Close()
}
type controls struct {
sync.Mutex
controls map[string]*control
}
func newControls() *controls {
return &controls{
controls: make(map[string]*control),
}
}
func (c *controls) getControl(identifier string) (*control, bool) {
c.Lock()
control, ok := c.controls[identifier]
c.Unlock()
return control, ok
}
func (c *controls) addControl(identifier string, control *control) {
control.identifier = identifier
c.Lock()
c.controls[identifier] = control
c.Unlock()
}
func (c *controls) deleteControl(identifier string) {
c.Lock()
delete(c.controls, identifier)
c.Unlock()
}