-
Notifications
You must be signed in to change notification settings - Fork 1
/
peer.go
383 lines (333 loc) · 7.32 KB
/
peer.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
377
378
379
380
381
382
383
package nest2go
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/gorilla/websocket"
. "github.com/lawwong/nest2go/closable"
. "github.com/lawwong/nest2go/datapkg"
. "github.com/lawwong/nest2go/protomsg"
"github.com/lawwong/nest2go/uuid"
"time"
)
type PeerBase struct {
ws *websocket.Conn
app *AppBase
decodeKey []byte
encodeKey []byte
decodeStream cipher.Stream
encodeStream cipher.Stream
eventChan chan EventData
opChan chan OpRequest
writeMsg chan []byte
writeErr chan error
Closable
}
func (p *PeerBase) EventChan() <-chan EventData {
if p != nil {
return p.eventChan
}
return nil
}
func (p *PeerBase) OpChan() <-chan OpRequest {
if p != nil {
return p.opChan
}
return nil
}
func newPeerBase(ws *websocket.Conn, app *AppBase, privateKey *rsa.PrivateKey) *PeerBase {
p := &PeerBase{
ws: ws,
app: app,
eventChan: make(chan EventData),
opChan: make(chan OpRequest),
writeMsg: make(chan []byte),
writeErr: make(chan error),
Closable: MakeClosable(),
}
p.HandleClose(nil)
go p.runHandshake(privateKey)
return p
}
func (p *PeerBase) runHandshake(privateKey *rsa.PrivateKey) {
var data []byte
var err error
var notifyAppFunc func(*PeerBase)
handshakeOk := make(chan struct{})
defer printErr(p.app.log, &err, "PeerBase.runHandshake", p.ws.LocalAddr(), p.ws.RemoteAddr())
defer func() {
if err != nil {
p.Close()
} else {
close(handshakeOk)
}
}()
go func() {
select {
case <-handshakeOk:
case <-time.After(2 * time.Second):
p.Close()
}
}()
if _, data, err = p.ws.ReadMessage(); err == nil {
// do handshake
if privateKey != nil {
// decode with rsa private key
data, err = rsa.DecryptOAEP(sha1.New(), nil, privateKey, data, nil)
if err != nil {
return
}
}
// parse message
hsReq := new(HandshakeReq)
err = proto.Unmarshal(data, hsReq)
if err != nil {
return
}
// build HandshakeRes
hsRes := &HandshakeRes{
// client should test if it's equal
Challenge: hsReq.Challenge,
}
// switch mode
switch hsReq.GetMode() {
case HandshakeReq_PEER:
//p.eMux = newEventMux()
//p.oMux = newOpReqMux()
// notify new peer to app
notifyAppFunc = func(p *PeerBase) {
select {
case p.app.onpeer <- p:
case <-p.app.CloseChan():
p.Close()
case <-p.CloseChan():
}
}
if privateKey != nil {
p.encodeKey = hsReq.GetAesKey()
p.decodeKey = make([]byte, len(p.encodeKey))
_, err = rand.Read(p.decodeKey)
if err != nil {
return
}
hsRes.AesKey = p.decodeKey
}
case HandshakeReq_NEW_AGENT:
agent := p.app.newAgent(p)
//agent.setPeer(p)
// notify new agent to app
notifyAppFunc = func(p *PeerBase) {
select {
case p.app.onagent <- agent:
case <-p.app.CloseChan():
p.Close()
case <-p.CloseChan():
}
}
hsRes.Session = agent.session.ByteSlice()
if privateKey != nil {
p.encodeKey = hsReq.GetAesKey()
p.decodeKey = make([]byte, len(p.encodeKey))
_, err = rand.Read(p.decodeKey)
if err != nil {
return
}
hsRes.AesKey = p.decodeKey
}
case HandshakeReq_AGENT:
var session *uuid.Uuid
*session, err = uuid.FromByteSlice(hsReq.GetSession())
if err != nil {
return
}
agent, err := p.app.verifyAgent(session, hsReq.GetSerialNum())
if err != nil {
return
}
agent.setPeer(p)
}
// make cipher stream
if privateKey != nil {
encodeBlock, err := aes.NewCipher(p.encodeKey)
if err != nil {
return
}
decodeBlock, err := aes.NewCipher(p.decodeKey)
if err != nil {
return
}
encodeIv := hsReq.GetAesIv()
if len(encodeIv) != aes.BlockSize {
err = fmt.Errorf("IV length must equal block size!")
return
}
decodeIv := make([]byte, aes.BlockSize)
_, err = rand.Read(decodeIv)
if err != nil {
return
}
// FIXME : thread safe?
p.encodeStream = cipher.NewCTR(encodeBlock, encodeIv)
p.decodeStream = cipher.NewCTR(decodeBlock, decodeIv)
hsRes.AesIv = decodeIv
}
data, err = proto.Marshal(hsRes)
if err != nil {
return
}
if p.encodeStream != nil {
p.encodeStream.XORKeyStream(data, data)
}
err := p.ws.WriteMessage(websocket.BinaryMessage, data)
if err != nil {
return
}
go p.runReader()
go p.runWriter()
if notifyAppFunc != nil {
// app can handle event/op, send event/op, close peer/agent
notifyAppFunc(p)
}
}
}
func (p *PeerBase) runReader() {
var data []byte
var err error
msg := new(DataMsg)
for {
_, data, err = p.ws.ReadMessage()
if err != nil {
break
}
if p.decodeStream != nil {
p.decodeStream.XORKeyStream(data, data)
}
err = proto.Unmarshal(data, msg)
if err != nil {
p.app.log.Warnf("%q peer %q : %s", p.ws.LocalAddr(), p.ws.RemoteAddr(), err)
continue
}
switch msg.GetType() {
case DataMsg_EVENT:
p.eventChan <- MakeEventData(
msg.GetCode(),
msg.GetData(),
)
case DataMsg_OP:
p.opChan <- MakeOpRequest(
msg.GetCode(),
msg.GetSerial(),
msg.GetData(),
p,
)
}
}
p.app.log.Infof("%q peer %q : %s", p.ws.LocalAddr(), p.ws.RemoteAddr(), err)
close(p.eventChan)
close(p.opChan)
p.Close()
}
func (p *PeerBase) runWriter() {
for {
select {
case data := <-p.writeMsg:
if len(data) == 0 {
p.writeErr <- nil
} else {
if p.encodeStream != nil {
p.encodeStream.XORKeyStream(data, data)
}
p.writeErr <- p.ws.WriteMessage(websocket.BinaryMessage, data)
}
case <-p.CloseChan():
break
}
}
close(p.writeErr)
}
func (p *PeerBase) SendEvent(code int32, data []byte) error {
msg := DataMsg{
Type: DataMsgTypeEvent,
Code: &code,
Data: data,
}
d, _ := proto.Marshal(&msg) // must succeed
select {
case p.writeMsg <- d:
return <-p.writeErr
case <-p.CloseChan():
return ErrServiceClosed
}
}
func (p *PeerBase) SendOpResponse(req OpRequest, resCode int32, data []byte) error {
var code int32 = req.Code()
var serial int32 = req.Serial()
msg := DataMsg{
Type: DataMsgTypeOp,
Code: &code,
ResCode: &resCode,
Data: data,
}
if serial = req.Serial(); serial != 0 {
msg.Serial = &serial
}
d, _ := proto.Marshal(&msg) // must succeed
select {
case p.writeMsg <- d:
return <-p.writeErr
case <-p.CloseChan():
return ErrServiceClosed
}
}
func (p *PeerBase) HandleClose(handler CloseHandler) {
p.Closable.HandleCloseFunc(func() {
if err := p.ws.Close(); err != nil {
p.app.log.Infof("%q peer %q closed. %s", p.ws.LocalAddr(), p.ws.RemoteAddr(), err)
}
if handler != nil {
handler.HandleClose()
}
})
}
func (p *PeerBase) HandleCloseFunc(handleFunc CloseHandlerFunc) {
p.HandleClose(CloseHandler(handleFunc))
}
func BroadcastEventByChan(peerChan <-chan *PeerBase, code int32, data []byte) {
if peerChan == nil {
return
}
go func() {
msg := DataMsg{
Type: DataMsgTypeEvent,
Code: proto.Int32(code),
Data: data,
}
d, _ := proto.Marshal(&msg) // must succeed
for p := range peerChan {
if p != nil {
go func(p *PeerBase) {
select {
case p.writeMsg <- d:
<-p.writeErr
case <-p.CloseChan():
}
}(p)
}
}
}()
}
func BroadcastEvent(peers []*PeerBase, code int32, data []byte) {
if len(peers) == 0 {
return
}
peerChan := make(chan *PeerBase)
BroadcastEventByChan(peerChan, code, data)
for _, p := range peers {
peerChan <- p
}
close(peerChan)
}