This repository has been archived by the owner on Jun 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
262 lines (241 loc) · 5.56 KB
/
client.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
package turnc
import (
"errors"
"io"
"net"
"sync"
"time"
"go.uber.org/zap"
"gortc.io/stun"
"gortc.io/turn"
)
// Client for TURN server.
//
// Provides transparent net.Conn interfaces to remote peers.
type Client struct {
log *zap.Logger
con net.Conn
conClose bool
stun STUNClient
mux sync.RWMutex
username stun.Username
password string
realm stun.Realm
integrity stun.MessageIntegrity
alloc *Allocation // the only allocation
refreshRate time.Duration
done chan struct{}
}
// Options contains available config for TURN client.
type Options struct {
Conn net.Conn
STUN STUNClient // optional STUN client
Log *zap.Logger // defaults to Nop
// Long-term integrity.
Username string
Password string
// STUN client options.
RTO time.Duration
NoRetransmit bool
// TURN options.
RefreshRate time.Duration
RefreshDisabled bool
// ConnManualClose disables connection automatic close on Close().
ConnManualClose bool
}
// RefreshRate returns current rate of refresh requests.
func (c *Client) RefreshRate() time.Duration { return c.refreshRate }
const defaultRefreshRate = time.Minute
// New creates and initializes new TURN client.
func New(o Options) (*Client, error) {
if o.Conn == nil {
return nil, errors.New("connection not provided")
}
if o.Log == nil {
o.Log = zap.NewNop()
}
c := &Client{
password: o.Password,
log: o.Log,
conClose: true,
}
if o.ConnManualClose {
o.Log.Debug("manual close is enabled")
c.conClose = false
}
if o.STUN == nil {
// Setting up de-multiplexing.
m := newMultiplexer(o.Conn, c.log)
go m.discardData() // discarding any non-stun/turn data
o.Conn = bypassWriter{
reader: m.turnL,
writer: m.conn,
}
// Starting STUN client on multiplexed connection.
var err error
stunOptions := []stun.ClientOption{
stun.WithHandler(c.stunHandler),
}
if o.NoRetransmit {
stunOptions = append(stunOptions, stun.WithNoRetransmit)
}
if o.RTO > 0 {
stunOptions = append(stunOptions, stun.WithRTO(o.RTO))
}
o.STUN, err = stun.NewClient(bypassWriter{
reader: m.stunL,
writer: m.conn,
}, stunOptions...)
if err != nil {
return nil, err
}
}
c.done = make(chan struct{})
c.stun = o.STUN
c.con = o.Conn
c.refreshRate = defaultRefreshRate
if o.RefreshRate > 0 {
c.refreshRate = o.RefreshRate
}
if o.RefreshDisabled {
c.refreshRate = 0
}
if o.Username != "" {
c.username = stun.NewUsername(o.Username)
}
go c.readUntilClosed()
return c, nil
}
// STUNClient abstracts STUN protocol interaction.
type STUNClient interface {
Indicate(m *stun.Message) error
Do(m *stun.Message, f func(e stun.Event)) error
Close() error
}
var dataIndication = stun.NewType(stun.MethodData, stun.ClassIndication)
func (c *Client) stunHandler(e stun.Event) {
if e.Error != nil {
// Just ignoring.
return
}
if e.Message.Type != dataIndication {
return
}
var (
data turn.Data
addr turn.PeerAddress
)
if err := e.Message.Parse(&data, &addr); err != nil {
c.log.Error("failed to parse while handling incoming STUN message", zap.Error(err))
return
}
c.mux.RLock()
for i := range c.alloc.perms {
for j := range c.alloc.perms[i].conn {
if !turn.Addr(c.alloc.perms[i].conn[j].peerAddr).Equal(turn.Addr(addr)) {
continue
}
if _, err := c.alloc.perms[i].conn[j].peerL.Write(data); err != nil {
c.log.Error("failed to write", zap.Error(err))
}
}
}
c.mux.RUnlock()
}
func (c *Client) handleChannelData(data *turn.ChannelData) {
c.log.Debug("handleChannelData", zap.Int("n", int(data.Number)))
c.mux.RLock()
for i := range c.alloc.perms {
for j := range c.alloc.perms[i].conn {
if data.Number != c.alloc.perms[i].conn[j].Binding() {
continue
}
if _, err := c.alloc.perms[i].conn[j].peerL.Write(data.Data); err != nil {
c.log.Error("failed to write", zap.Error(err))
}
}
}
c.mux.RUnlock()
}
func (c *Client) readUntilClosed() {
buf := make([]byte, 1500)
for {
n, err := c.con.Read(buf)
if err != nil {
if err == io.EOF {
continue
}
c.log.Debug("read error", zap.Error(err))
c.log.Info("connection closed")
break
}
data := buf[:n]
if !turn.IsChannelData(data) {
continue
}
cData := &turn.ChannelData{
Raw: make([]byte, n),
}
copy(cData.Raw, data)
if err := cData.Decode(); err != nil {
panic(err)
}
go c.handleChannelData(cData)
}
close(c.done)
}
func (c *Client) sendData(buf []byte, peerAddr *turn.PeerAddress) (int, error) {
err := c.stun.Indicate(stun.MustBuild(stun.TransactionID,
stun.NewType(stun.MethodSend, stun.ClassIndication),
turn.Data(buf), peerAddr,
))
if err == nil {
return len(buf), nil
}
return 0, err
}
func (c *Client) sendChan(buf []byte, n turn.ChannelNumber) (int, error) {
if !n.Valid() {
return 0, turn.ErrInvalidChannelNumber
}
d := &turn.ChannelData{
Data: buf,
Number: n,
}
d.Encode()
return c.con.Write(d.Raw)
}
func (c *Client) do(req, res *stun.Message) error {
var stunErr error
if doErr := c.stun.Do(req, func(e stun.Event) {
if e.Error != nil {
stunErr = e.Error
return
}
if res == nil {
return
}
if err := e.Message.CloneTo(res); err != nil {
stunErr = err
}
}); doErr != nil {
return doErr
}
return stunErr
}
func (c *Client) Close() error {
if !c.conClose {
// TODO(ernado): Cleanup all resources.
return nil
}
c.log.Error("closing connection")
if err := c.con.Close(); err != nil {
return err
}
if err := c.stun.Close(); err != nil {
c.log.Error("failed to close stun client", zap.Error(err))
}
<-c.done
c.log.Error("done signaled")
return nil
}