-
Notifications
You must be signed in to change notification settings - Fork 2
/
handshake.go
89 lines (79 loc) · 1.58 KB
/
handshake.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
package emux
import (
"bytes"
"context"
"fmt"
"io"
"sync"
)
// DefaultHandshake
// 0 5
// +---------+---------+---------+---------+---------+
// | "EMUX " |
// +---------+---------+---------+---------+---------+
var (
HandshakeData = []byte("EMUX ")
DefaultClientHandshake = NewHandshake(HandshakeData, true)
DefaultServerHandshake = NewHandshake(HandshakeData, false)
)
type Handshake interface {
Handshake(ctx context.Context, rw io.ReadWriter) error
}
type handshake struct {
mut sync.Mutex
bufPool sync.Pool
data []byte
send bool
}
func NewHandshake(h []byte, send bool) Handshake {
return &handshake{
bufPool: sync.Pool{
New: func() interface{} {
return make([]byte, len(h))
},
},
send: send,
data: h,
}
}
func (h *handshake) Handshake(ctx context.Context, rw io.ReadWriter) error {
if ctx == context.Background() {
return h.handshake(rw)
}
done := make(chan struct{})
var err error
go func() {
err = h.handshake(rw)
close(done)
}()
select {
case <-ctx.Done():
return ErrClosed
case <-done:
return err
}
}
func (h *handshake) handshake(rw io.ReadWriter) error {
if h.send {
_, err := rw.Write(h.data)
if err != nil {
return err
}
}
buf := h.bufPool.Get().([]byte)
defer h.bufPool.Put(buf)
_, err := io.ReadFull(rw, buf)
if err != nil {
return err
}
if !bytes.Equal(h.data, buf) {
return fmt.Errorf("handshake error %q", buf)
}
if !h.send {
_, err = rw.Write(h.data)
if err != nil {
return err
}
}
return nil
}