-
Notifications
You must be signed in to change notification settings - Fork 5
/
raw_conn.go
122 lines (102 loc) · 2.16 KB
/
raw_conn.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
package gouxp
import (
"encoding/binary"
"net"
"sync"
"sync/atomic"
"github.com/shaoyuan1943/gokcp"
)
type connCloser interface {
close(err error)
}
type RawConn struct {
connCloser
kcp *gokcp.KCP
addr net.Addr
rwc net.PacketConn
cryptoCodec CryptCodec
handler ConnHandler
closeC chan struct{}
closed atomic.Value
kcpStatus *gokcp.KCPStatus
stopKCPStatusC chan struct{}
fecEncoder *FecCodecEncoder
fecDecoder *FecCodecDecoder
lastActiveTime uint32
buffer []byte
bufferLen int
sync.Mutex
}
func (conn *RawConn) encrypt(data []byte) (cipherData []byte, err error) {
if conn.cryptoCodec != nil {
cipherData, err = conn.cryptoCodec.Encrypt(data)
return
}
cipherData = data
err = nil
return
}
func (conn *RawConn) decrypt(cipherData []byte) (plaintextData []byte, err error) {
if conn.cryptoCodec != nil {
plaintextData, err = conn.cryptoCodec.Decrypt(cipherData)
return
}
plaintextData = cipherData[macSize:]
err = nil
return
}
func (conn *RawConn) write(data []byte) error {
_, err := conn.rwc.WriteTo(data, conn.addr)
return err
}
func (conn *RawConn) onKCPDataInput(data []byte) error {
conn.Lock()
defer conn.Unlock()
return conn.kcp.Input(data)
}
func (conn *RawConn) onKCPDataOutput(data []byte) error {
binary.LittleEndian.PutUint16(data[macSize:], uint16(protoTypeData))
cipherData, err := conn.encrypt(data)
if err != nil {
return err
}
if conn.fecEncoder != nil && conn.fecDecoder != nil {
fecData, err := conn.fecEncoder.Encode(cipherData)
if err != nil {
return err
}
if fecData != nil {
for _, v := range fecData {
err = conn.write(v)
if err != nil {
return err
}
}
}
} else {
err = conn.write(cipherData)
if err != nil {
return err
}
}
return nil
}
func (conn *RawConn) recvFromKCP() error {
for {
size := conn.kcp.PeekSize()
if size > 0 {
conn.buffer = conn.buffer[:size]
n, err := conn.kcp.Recv(conn.buffer)
if err != nil {
return err
}
if n != size {
return gokcp.ErrDataInvalid
}
conn.handler.OnNewDataComing(conn.buffer)
} else {
break
}
}
return nil
}