-
Notifications
You must be signed in to change notification settings - Fork 51
/
protomux.go
272 lines (231 loc) · 6.06 KB
/
protomux.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
package protomux
import (
"context"
"fmt"
"net"
"sync"
"time"
"go.aporeto.io/enforcerd/trireme-lib/controller/internal/enforcer/applicationproxy/common"
"go.aporeto.io/enforcerd/trireme-lib/controller/internal/enforcer/applicationproxy/markedconn"
"go.aporeto.io/enforcerd/trireme-lib/controller/internal/enforcer/applicationproxy/serviceregistry"
"go.uber.org/zap"
)
// ProtoListener is
type ProtoListener struct {
net.Listener
connection chan net.Conn
mark int
}
// NewProtoListener creates a listener for a particular protocol.
func NewProtoListener(mark int) *ProtoListener {
return &ProtoListener{
connection: make(chan net.Conn),
mark: mark,
}
}
// Accept accepts new connections over the channel.
func (p *ProtoListener) Accept() (net.Conn, error) {
c, ok := <-p.connection
if !ok {
return nil, fmt.Errorf("mux: listener closed")
}
return c, nil
}
// MultiplexedListener is the root listener that will split
// connections to different protocols.
type MultiplexedListener struct {
root net.Listener
done chan struct{}
shutdown chan struct{}
wg sync.WaitGroup
protomap map[common.ListenerType]*ProtoListener
puID string
defaultListener *ProtoListener
localIPs map[string]struct{}
mark int
sync.RWMutex
}
// NewMultiplexedListener returns a new multiplexed listener. Caller
// must register protocols outside of the new object creation.
func NewMultiplexedListener(l net.Listener, mark int, puID string) *MultiplexedListener {
return &MultiplexedListener{
root: l,
done: make(chan struct{}),
shutdown: make(chan struct{}),
wg: sync.WaitGroup{},
protomap: map[common.ListenerType]*ProtoListener{},
localIPs: markedconn.GetInterfaces(),
mark: mark,
puID: puID,
}
}
// RegisterListener registers a new listener. It returns the listener that the various
// protocol servers should use. If defaultListener is set, this will become
// the default listener if no match is found. Obviously, there cannot be more
// than one default.
func (m *MultiplexedListener) RegisterListener(ltype common.ListenerType) (*ProtoListener, error) {
m.Lock()
defer m.Unlock()
if _, ok := m.protomap[ltype]; ok {
return nil, fmt.Errorf("Cannot register same listener type multiple times")
}
p := &ProtoListener{
Listener: m.root,
connection: make(chan net.Conn),
mark: m.mark,
}
m.protomap[ltype] = p
return p, nil
}
// UnregisterListener unregisters a listener. It returns an error if there are services
// associated with this listener.
func (m *MultiplexedListener) UnregisterListener(ltype common.ListenerType) error {
m.Lock()
defer m.Unlock()
delete(m.protomap, ltype)
return nil
}
// RegisterDefaultListener registers a default listener.
func (m *MultiplexedListener) RegisterDefaultListener(p *ProtoListener) error {
m.Lock()
defer m.Unlock()
if m.defaultListener != nil {
return fmt.Errorf("Default listener already registered")
}
m.defaultListener = p
return nil
}
// UnregisterDefaultListener unregisters the default listener.
func (m *MultiplexedListener) UnregisterDefaultListener() error {
m.Lock()
defer m.Unlock()
if m.defaultListener == nil {
return fmt.Errorf("No default listener registered")
}
m.defaultListener = nil
return nil
}
// Close terminates the server without the context.
func (m *MultiplexedListener) Close() {
close(m.shutdown)
}
// Serve will demux the connections
func (m *MultiplexedListener) Serve(ctx context.Context) error {
defer func() {
close(m.done)
m.wg.Wait()
m.RLock()
defer m.RUnlock()
for _, l := range m.protomap {
close(l.connection)
// Drain the connections enqueued for the listener.
for c := range l.connection {
c.Close() // nolint
}
}
}()
go func() {
for {
select {
case <-time.After(5 * time.Second):
m.Lock()
m.localIPs = markedconn.GetInterfaces()
m.Unlock()
case <-ctx.Done():
return
}
}
}()
for {
select {
case <-ctx.Done():
return nil
case <-m.shutdown:
return nil
default:
c, err := m.root.Accept()
if err != nil {
// check if the error is due to shutdown in progress
select {
case <-ctx.Done():
return nil
case <-m.shutdown:
return nil
default:
}
// if it is an actual error (which can happen in Windows we can't get origin ip/port from our driver),
// then log an error and continue accepting connections.
zap.L().Error("error from Accept", zap.Error(err))
break
}
m.wg.Add(1)
go m.serve(c)
}
}
}
func (m *MultiplexedListener) serve(conn net.Conn) {
defer m.wg.Done()
c, ok := conn.(*markedconn.ProxiedConnection)
if !ok {
zap.L().Error("Wrong connection type")
return
}
ip, port := c.GetOriginalDestination()
remoteAddr := c.RemoteAddr()
if remoteAddr == nil {
zap.L().Error("Connection remote address cannot be found. Abort")
return
}
local := false
m.Lock()
localIPs := m.localIPs
m.Unlock()
if _, ok = localIPs[networkOfAddress(remoteAddr.String())]; ok {
local = true
}
var listenerType common.ListenerType
if local {
_, serviceData, err := serviceregistry.Instance().RetrieveDependentServiceDataByIDAndNetwork(m.puID, ip, port, "")
if err != nil {
zap.L().Error("Cannot discover target service",
zap.String("ContextID", m.puID),
zap.String("ip", ip.String()),
zap.Int("port", port),
zap.String("Remote IP", remoteAddr.String()),
zap.Error(err),
)
return
}
listenerType = serviceData.ServiceType
} else {
pctx, err := serviceregistry.Instance().RetrieveExposedServiceContext(ip, port, "")
if err != nil {
zap.L().Error("Cannot discover target service",
zap.String("ip", ip.String()),
zap.Int("port", port),
zap.String("Remote IP", remoteAddr.String()),
)
return
}
listenerType = pctx.Type
}
m.RLock()
target, ok := m.protomap[listenerType]
m.RUnlock()
if !ok {
c.Close() // nolint
return
}
select {
case target.connection <- c:
case <-m.done:
c.Close() // nolint
}
}
func networkOfAddress(addr string) string {
ip, _, err := net.SplitHostPort(addr)
if err != nil {
return addr
}
return ip
}