forked from skycoin/dmsg-deprecated
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.go
376 lines (323 loc) · 9.45 KB
/
transport.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
package dmsg
import (
"context"
"errors"
"fmt"
"io"
"net"
"sync"
"github.com/skycoin/skycoin/src/util/logging"
"github.com/skycoin/dmsg/cipher"
"github.com/skycoin/dmsg/ioutil"
)
// Errors related to REQUEST frames.
var (
ErrRequestRejected = errors.New("failed to create transport: request rejected")
ErrRequestCheckFailed = errors.New("failed to create transport: request check failed")
ErrAcceptCheckFailed = errors.New("failed to create transport: accept check failed")
)
// Transport represents a connection from dmsg.Client to remote dmsg.Client (via dmsg.Server intermediary).
type Transport struct {
net.Conn // underlying connection to dmsg.Server
log *logging.Logger
id uint16 // tp ID that identifies this dmsg.Transport
local cipher.PubKey // local PK
remote cipher.PubKey // remote PK
inCh chan Frame // handles incoming frames (from dmsg.Client)
inMx sync.Mutex // protects 'inCh'
ackWaiter ioutil.Uint16AckWaiter // awaits for associated ACK frames
ackBuf []byte // buffer for unsent ACK frames
buf net.Buffers // buffer for non-read FWD frames
bufCh chan struct{} // chan for indicating whether this is a new FWD frame
bufSize int // keeps track of the total size of 'buf'
bufMx sync.Mutex // protects fields responsible for handling FWD and ACK frames
serving chan struct{} // chan which closes when serving begins
servingOnce sync.Once // ensures 'serving' only closes once
done chan struct{} // chan which closes when transport stops serving
doneOnce sync.Once // ensures 'done' only closes once
doneFunc func(id uint16) // contains a method to remove the transport from dmsg.Client
}
// NewTransport creates a new dms_tp.
func NewTransport(conn net.Conn, log *logging.Logger, local, remote cipher.PubKey, id uint16, doneFunc func(id uint16)) *Transport {
tp := &Transport{
Conn: conn,
log: log,
id: id,
local: local,
remote: remote,
inCh: make(chan Frame),
ackWaiter: ioutil.NewUint16AckWaiter(),
ackBuf: make([]byte, 0, tpAckCap),
buf: make(net.Buffers, 0, tpBufFrameCap),
bufCh: make(chan struct{}, 1),
serving: make(chan struct{}),
done: make(chan struct{}),
doneFunc: doneFunc,
}
if err := tp.ackWaiter.RandSeq(); err != nil {
log.Fatalln("failed to set ack_waiter seq:", err)
}
return tp
}
func (tp *Transport) serve() (started bool) {
tp.servingOnce.Do(func() {
started = true
close(tp.serving)
})
return started
}
// Regarding the use of mutexes:
// 1. `done` is always closed before `inCh`/`bufCh` is closed.
// 2. mutexes protect `inCh`/`bufCh` to ensure that closing and writing to these chans does not happen concurrently.
// 3. Our worry now, is writing to `inCh`/`bufCh` AFTER they have been closed.
// 4. But as, under the mutexes protecting `inCh`/`bufCh`, checking `done` comes first,
// and we know that `done` is closed before `inCh`/`bufCh`, we can guarantee that it avoids writing to closed chan.
func (tp *Transport) close() (closed bool) {
if tp == nil {
return false
}
tp.doneOnce.Do(func() {
closed = true
close(tp.done)
tp.doneFunc(tp.id)
tp.bufMx.Lock()
close(tp.bufCh)
tp.bufMx.Unlock()
tp.inMx.Lock()
close(tp.inCh)
tp.inMx.Unlock()
})
tp.serve() // just in case.
tp.ackWaiter.StopAll()
return closed
}
// Close closes the dmsg_tp.
func (tp *Transport) Close() error {
if tp.close() {
_ = writeFrame(tp.Conn, MakeFrame(CloseType, tp.id, []byte{0})) //nolint:errcheck
}
return nil
}
// IsClosed returns whether dms_tp is closed.
func (tp *Transport) IsClosed() bool {
select {
case <-tp.done:
return true
default:
return false
}
}
// LocalPK returns the local public key of the transport.
func (tp *Transport) LocalPK() cipher.PubKey {
return tp.local
}
// RemotePK returns the remote public key of the transport.
func (tp *Transport) RemotePK() cipher.PubKey {
return tp.remote
}
// Type returns the transport type.
func (tp *Transport) Type() string {
return Type
}
// HandleFrame allows 'tp.Serve' to handle the frame (typically from 'ClientConn').
func (tp *Transport) HandleFrame(f Frame) error {
tp.inMx.Lock()
defer tp.inMx.Unlock()
for {
if tp.IsClosed() {
return io.ErrClosedPipe
}
select {
case tp.inCh <- f:
return nil
default:
}
}
}
// WriteRequest writes a REQUEST frame to dmsg_server to be forwarded to associated client.
func (tp *Transport) WriteRequest() error {
f := MakeFrame(RequestType, tp.id, combinePKs(tp.local, tp.remote))
if err := writeFrame(tp.Conn, f); err != nil {
tp.log.WithError(err).Error("HandshakeFailed")
tp.close()
return err
}
return nil
}
// WriteAccept writes an ACCEPT frame to dmsg_server to be forwarded to associated client.
func (tp *Transport) WriteAccept() (err error) {
defer func() {
if err != nil {
tp.log.WithError(err).WithField("remote", tp.remote).Warnln("(HANDSHAKE) Rejected locally.")
} else {
tp.log.WithField("remote", tp.remote).Infoln("(HANDSHAKE) Accepted locally.")
}
}()
f := MakeFrame(AcceptType, tp.id, combinePKs(tp.remote, tp.local))
if err = writeFrame(tp.Conn, f); err != nil {
tp.close()
return err
}
return nil
}
// ReadAccept awaits for an ACCEPT frame to be read from the remote client.
// TODO(evanlinjin): Cleanup errors.
func (tp *Transport) ReadAccept(ctx context.Context) (err error) {
defer func() {
if err != nil {
tp.log.WithError(err).WithField("remote", tp.remote).Warnln("(HANDSHAKE) Rejected by remote.")
} else {
tp.log.WithField("remote", tp.remote).Infoln("(HANDSHAKE) Accepted by remote.")
}
}()
select {
case <-tp.done:
tp.close()
return io.ErrClosedPipe
case <-ctx.Done():
_ = tp.Close() //nolint:errcheck
return ctx.Err()
case f, ok := <-tp.inCh:
if !ok {
tp.close()
return io.ErrClosedPipe
}
switch ft, id, p := f.Disassemble(); ft {
case AcceptType:
// locally-initiated tps should:
// - have a payload structured as 'init_pk:resp_pk'.
// - init_pk should be of local client.
// - resp_pk should be of remote client.
// - use an even number with the intermediary dmsg_server.
initPK, respPK, ok := splitPKs(p)
if !ok || initPK != tp.local || respPK != tp.remote || !isInitiatorID(id) {
_ = tp.Close() //nolint:errcheck
return ErrAcceptCheckFailed
}
return nil
case CloseType:
tp.close()
return ErrRequestRejected
default:
_ = tp.Close() //nolint:errcheck
return ErrAcceptCheckFailed
}
}
}
// Serve handles received frames.
func (tp *Transport) Serve() {
// return is transport is already being served, or is closed
if !tp.serve() {
return
}
// ensure transport closes when serving stops
// also write CLOSE frame if this is the first time 'close' is triggered
defer func() {
if tp.close() {
_ = writeCloseFrame(tp.Conn, tp.id, 0) //nolint:errcheck
}
}()
for {
select {
case <-tp.done:
return
case f, ok := <-tp.inCh:
if !ok {
return
}
log := tp.log.WithField("remoteClient", tp.remote).WithField("received", f)
switch p := f.Pay(); f.Type() {
case FwdType:
if len(p) < 2 {
log.Warnln("Rejected [FWD]: Invalid payload size.")
return
}
tp.bufMx.Lock()
// Acknowledgement logic: if read buffer has free space, send ACK. If not, add to 'ackBuf'.
ack := MakeFrame(AckType, tp.id, p[:2])
if tp.bufSize += len(p[2:]); tp.bufSize > tpBufCap {
tp.ackBuf = append(tp.ackBuf, ack...)
} else {
go func() {
if err := writeFrame(tp.Conn, ack); err != nil {
tp.close()
}
}()
}
// add payload to 'buf'
tp.buf = append(tp.buf, p[2:])
// notify of new data via 'bufCh' (only if not closed)
if !tp.IsClosed() {
select {
case tp.bufCh <- struct{}{}:
default:
}
}
log.WithField("bufSize", fmt.Sprintf("%d/%d", tp.bufSize, tpBufCap)).Infoln("Injected [FWD]")
tp.bufMx.Unlock()
case AckType:
if len(p) != 2 {
log.Warnln("Rejected [ACK]: Invalid payload size.")
return
}
tp.ackWaiter.Done(ioutil.DecodeUint16Seq(p[:2]))
log.Infoln("Injected [ACK]")
case CloseType:
log.Infoln("Injected [CLOSE]: Closing transport...")
tp.close() // ensure there is no sending of CLOSE frame
return
case RequestType:
log.Warnln("Rejected [REQUEST]: ID already occupied, possibly malicious server.")
_ = tp.Conn.Close()
return
default:
tp.log.Infof("Rejected [%s]: Unexpected frame, possibly malicious server (ignored for now).", f.Type())
}
}
}
}
// Read implements io.Reader
// TODO(evanlinjin): read deadline.
func (tp *Transport) Read(p []byte) (n int, err error) {
<-tp.serving
startRead:
tp.bufMx.Lock()
n, err = tp.buf.Read(p)
if tp.bufSize -= n; tp.bufSize < tpBufCap && len(tp.ackBuf) > 0 {
acks := tp.ackBuf
tp.ackBuf = make([]byte, 0, tpAckCap)
go func() {
if err := writeFrame(tp.Conn, acks); err != nil {
tp.close()
}
}()
}
tp.bufMx.Unlock()
if tp.IsClosed() {
return n, err
}
if n > 0 || len(p) == 0 {
return n, nil
}
<-tp.bufCh
goto startRead
}
// Write implements io.Writer
// TODO(evanlinjin): write deadline.
func (tp *Transport) Write(p []byte) (int, error) {
<-tp.serving
if tp.IsClosed() {
return 0, io.ErrClosedPipe
}
err := tp.ackWaiter.Wait(context.Background(), func(seq ioutil.Uint16Seq) error {
if err := writeFwdFrame(tp.Conn, tp.id, seq, p); err != nil {
tp.close()
return err
}
return nil
})
if err != nil {
return 0, err
}
return len(p), nil
}