-
Notifications
You must be signed in to change notification settings - Fork 2
/
connect.go
330 lines (277 loc) · 6.88 KB
/
connect.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
// Copyright 2022 Kirill Scherba <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// TRU Connect module
package tru
import (
"bytes"
"crypto/rsa"
"encoding/binary"
"errors"
"net"
"sync"
"time"
"github.com/google/uuid"
)
const waitConnectionTimeout = 5 * time.Second
const (
ClientConnectTimeout = waitConnectionTimeout
ServerConnectTimeout = waitConnectionTimeout
)
type connect struct {
connects map[string]*connectData // Connections map
m sync.RWMutex // Connections maps mutex
}
type connectData struct {
uuid string
wch chan *connectData
ch *Channel
}
type connectPacketData struct {
uuid []byte // Connection UUID
data []byte // Packet data
}
// MarshalBinary marshal connection data
func (c *connectPacketData) MarshalBinary() (out []byte, err error) {
buf := new(bytes.Buffer)
le := binary.LittleEndian
binary.Write(buf, le, uint8(len(c.uuid)))
binary.Write(buf, le, c.uuid)
binary.Write(buf, le, c.data)
out = buf.Bytes()
return
}
// UnmarshalBinary unmarshal connection data
func (c *connectPacketData) UnmarshalBinary(data []byte) (err error) {
buf := bytes.NewReader(data)
le := binary.LittleEndian
var l uint8
err = binary.Read(buf, le, &l)
if err != nil {
return
}
uuid := make([]byte, l)
err = binary.Read(buf, le, &uuid)
if err != nil {
return
}
c.uuid = uuid
if buflen := buf.Len(); buflen > 0 {
c.data = make([]byte, buflen)
err = binary.Read(buf, le, &c.data)
return
}
c.data = nil
return
}
// Connect to tru channel (remote peer) by address
func (tru *Tru) Connect(addr string, reader ...ReaderFunc) (ch *Channel, err error) {
// Generate RSA key
c, err := tru.newCrypt()
if err != nil {
return
}
pub, err := c.publicKeyToBytes(&c.privateKey.PublicKey)
if err != nil {
return
}
// Create uuid and connect packet
uuid := uuid.New().String()
cp := connectPacketData{[]byte(uuid), pub}
data, err := cp.MarshalBinary()
if err != nil {
return
}
pac, err := tru.newPacket().SetStatus(statusConnect).SetData(data).MarshalBinary()
if err != nil {
return
}
// Create wait connection channel and save connection data to map
wch := tru.connect.add(uuid)
defer tru.connect.delete(uuid)
defer close(wch)
// Send connect message
_, err = tru.WriteTo(pac, addr)
if err != nil {
return
}
// Wait answer to connect message or timeout
ch, err = tru.connect.wait(wch)
if err != nil {
return
}
// Add reader to channel
if len(reader) > 0 {
ch.reader = reader[0]
}
return
}
// wait channel connected or timeout
func (c *connect) wait(wch chan *connectData) (ch *Channel, err error) {
select {
case cd := <-wch:
ch = cd.ch
return
case <-time.After(waitConnectionTimeout):
err = errors.New("can't connect to peer during timeout")
return
}
}
// add add connection data to connections map
func (c *connect) add(uuid string) (wch chan *connectData) {
c.m.Lock()
defer c.m.Unlock()
wch = make(chan *connectData)
c.connects[uuid] = &connectData{uuid, wch, nil}
return
}
// delete delete connection data from connections map
func (c *connect) delete(uuid string) {
c.m.Lock()
defer c.m.Unlock()
delete(c.connects, uuid)
}
// get get connection data from connections map
func (c *connect) get(uuid string) (cd *connectData, ok bool) {
c.m.RLock()
defer c.m.RUnlock()
cd, ok = c.connects[uuid]
return
}
// serve process connect packets
func (c *connect) serve(tru *Tru, addr net.Addr, pac *Packet) (err error) {
switch pac.Status() {
// Got by server. Client send to server statusConnect packet with client
// public key
case statusConnect:
// Unmarshal received data
cp := connectPacketData{}
err = cp.UnmarshalBinary(pac.Data())
if err != nil {
return
}
// Create new tru channel
var ch *Channel
ch, err = tru.newChannel(addr, true)
if err != nil {
return
}
// Get public key
var pub []byte
pub, err = ch.publicKeyToBytes(&ch.privateKey.PublicKey)
if err != nil {
return
}
// Encrypt public key with received clients public key
var pubcli *rsa.PublicKey
pubcli, err = ch.bytesToPublicKey(cp.data)
if err != nil {
return
}
cp.data, err = ch.encrypt(pubcli, pub)
if err != nil {
return
}
var data []byte
data, err = cp.MarshalBinary()
// Create packet and send it to tru channel
pac = tru.newPacket().SetStatus(statusConnectServerAnswer).SetData(data)
ch.writeToSender(pac)
// Got by client. Server answer to client with statusConnectServerAnswer
// packet with server public key
case statusConnectServerAnswer:
// Unmarshal received data
cp := connectPacketData{}
err = cp.UnmarshalBinary(pac.Data())
if err != nil {
return
}
// Get connection data from connection map and create new tru channel
cd, ok := c.get(string(cp.uuid))
if !ok {
err = errors.New("wrong connect server answer packet")
return
}
cd.ch, err = tru.newChannel(addr)
if err != nil {
return
}
// Got servers public key from packet
var data []byte
data, err = cd.ch.decrypt(cp.data)
if err != nil {
return
}
var pub *rsa.PublicKey
pub, err = cd.ch.crypt.bytesToPublicKey(data)
if err != nil {
return
}
// Make session key
key := cd.ch.makeSesionKey()
cp.data, err = cd.ch.encrypt(pub, key)
if err != nil {
return
}
// Create output connect packet data
data, err = cp.MarshalBinary()
if err != nil {
return
}
// Create packet and send it to tru channel
pac = tru.newPacket().SetStatus(statusConnectClientAnswer).SetData(data)
cd.ch.writeToSender(pac)
cd.ch.setSesionKey(key)
// Got by server. Client answer to server with statusConnectClientAnswer packet with
// current session key
case statusConnectClientAnswer:
// Unmarshal received data
cp := connectPacketData{}
err = cp.UnmarshalBinary(pac.Data())
if err != nil {
return
}
// Get channel
ch, ok := tru.getChannel(addr.String())
if !ok {
err = errors.New("connected channel does not exists")
return
}
// Decrypt and set session key
var key []byte
key, err = ch.decrypt(cp.data)
if err != nil {
return
}
ch.setSesionKey(key)
// Create output connect packet data
var data []byte
cp.data = nil
data, err = cp.MarshalBinary()
if err != nil {
return
}
// Create packet and send it to tru channel
pac = tru.newPacket().SetStatus(statusConnectDone).SetData(data)
ch.writeToSender(pac)
// Got by client. Server answer to client with statusConnectDone packet
case statusConnectDone:
// Unmarshal received data
cp := connectPacketData{}
err = cp.UnmarshalBinary(pac.Data())
if err != nil {
return
}
// Get connection data from connection map and get tru channel
cd, ok := c.get(string(cp.uuid))
if !ok {
err = errors.New("wrong connect done packet")
return
}
// Send connectData to client connect wait channel
cd.wch <- cd
default:
err = errors.New("wrong packet status")
}
return
}