Repository navigation
Expand file tree
/
Copy pathtunneld.go
More file actions
528 lines (469 loc) · 15.2 KB
/
Copy pathtunneld.go
File metadata and controls
528 lines (469 loc) · 15.2 KB
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package main
import (
"log"
"math"
// "log"
"bytes"
"encoding/binary"
"net"
"time"
tox "github.com/TokTok/go-toxcore-c"
"github.com/kitech/goplusplus"
)
type Tunneld struct {
tox *tox.Tox
chpool *ChannelPool
kcpNextUpdateWait int
toxPollChan chan ToxPollEvent
// toxReadyReadChan chan ToxReadyReadEvent
// toxMessageChan chan ToxMessageEvent
kcpPollChan chan KcpPollEvent
kcpCheckCloseChan chan KcpCheckCloseEvent
// kcpReadyReadChan chan KcpReadyReadEvent
// kcpOutputChan chan KcpOutputEvent
serverReadyReadChan chan ServerReadyReadEvent
serverCloseChan chan ServerCloseEvent
channelGCChan chan ChannelGCEvent
}
func NewTunneld() *Tunneld {
this := new(Tunneld)
this.chpool = NewChannelPool()
t := makeTox("toxtund")
this.tox = t
// callbacks
t.CallbackSelfConnectionStatus(this.onToxnetSelfConnectionStatus, nil)
t.CallbackFriendRequest(this.onToxnetFriendRequest, nil)
t.CallbackFriendConnectionStatus(this.onToxnetFriendConnectionStatus, nil)
t.CallbackFriendMessage(this.onToxnetFriendMessage, nil)
t.CallbackFriendLossyPacket(this.onToxnetFriendLossyPacket, nil)
t.CallbackFriendLosslessPacket(this.onToxnetFriendLosslessPacket, nil)
///
return this
}
func (this *Tunneld) serve() {
this.toxPollChan = make(chan ToxPollEvent, mpcsz)
// this.toxReadyReadChan = make(chan ToxReadyReadEvent, 0)
// this.toxMessageChan = make(chan ToxMessageEvent, 0)
this.kcpPollChan = make(chan KcpPollEvent, mpcsz)
this.kcpCheckCloseChan = make(chan KcpCheckCloseEvent, mpcsz)
// this.kcpReadyReadChan = make(chan KcpReadyReadEvent, 0)
// this.kcpOutputChan = make(chan KcpOutputEvent, 0)
this.channelGCChan = make(chan ChannelGCEvent, mpcsz)
this.serverReadyReadChan = make(chan ServerReadyReadEvent, mpcsz)
this.serverCloseChan = make(chan ServerCloseEvent, mpcsz)
// install pollers
go func() {
for {
time.Sleep(time.Duration(smuse.tox_interval) * time.Millisecond)
// time.Sleep(30 * time.Millisecond)
this.toxPollChan <- ToxPollEvent{}
}
}()
go func() {
for {
if this.kcpNextUpdateWait > 0 {
time.Sleep(time.Duration(this.kcpNextUpdateWait) * time.Millisecond)
} else {
// time.Sleep(20 * time.Millisecond)
time.Sleep(time.Duration(smuse.kcp_interval) * time.Millisecond)
}
this.kcpPollChan <- KcpPollEvent{}
}
}()
go func() {
for {
time.Sleep(1000 * time.Millisecond)
this.kcpCheckCloseChan <- KcpCheckCloseEvent{}
}
}()
go func() {
for {
time.Sleep(15 * time.Second)
this.channelGCChan <- ChannelGCEvent{}
}
}()
// like event handler
for {
select {
// case evt := <-this.kcpReadyReadChan:
// this.processKcpReadyRead(evt.ch)
// case evt := <-this.kcpOutputChan:
// this.processKcpOutput(evt.buf, evt.size, evt.extra)
case evt := <-this.serverReadyReadChan:
this.processServerReadyRead(evt.ch, evt.buf, evt.size)
case evt := <-this.serverCloseChan:
this.promiseChannelClose(evt.ch)
case <-this.toxPollChan:
iterate(this.tox)
// case evt := <-this.toxReadyReadChan:
// this.processFriendLossyPacket(this.tox, evt.friendNumber, evt.message, nil)
// case evt := <-this.toxMessageChan:
// debug.Println(evt)
// this.processFriendMessage(this.tox, evt.friendNumber, evt.message, nil)
case <-this.kcpPollChan:
this.serveKcp()
case <-this.kcpCheckCloseChan:
this.kcpCheckClose()
case <-this.channelGCChan:
this.channelGC()
}
}
}
///////////
// TODO 计算kcpNextUpdateWait的逻辑优化
func kcp_poll(pool map[int32]*Channel) (chks []*Channel, nxtss []uint32) {
for _, ch := range pool {
if ch.kcp == nil {
continue
}
curts := uint32(iclock())
rts := ch.kcp.Check()
if rts == curts {
nxtss = append(nxtss, 10)
chks = append(chks, ch)
} else {
nxtss = append(nxtss, rts-curts)
}
}
return
}
func (this *Tunneld) serveKcp() {
zbuf := make([]byte, 0)
if true {
chks, nxtss := kcp_poll(this.chpool.pool)
mints := gopp.MinU32(nxtss)
if mints > 10 && mints != math.MaxUint32 {
this.kcpNextUpdateWait = int(mints)
return
} else {
this.kcpNextUpdateWait = 10
}
for _, ch := range chks {
if ch.kcp == nil {
continue
}
ch.kcp.Update()
n := ch.kcp.Recv(zbuf)
switch n {
case -3:
this.processKcpReadyRead(ch)
case -2: // just empty kcp recv queue
// errl.Println("kcp recv internal error:", n, this.kcp.PeekSize())
case -1: // EAGAIN
default:
errl.Println("unknown recv:", n)
}
}
}
}
func (this *Tunneld) kcpCheckClose() {
closed := make([]*Channel, 0)
for _, ch := range this.chpool.pool {
if ch.kcp == nil {
continue
}
if ch.server_socket_close == true && ch.server_kcp_close == false {
cnt := ch.kcp.WaitSnd()
if cnt == 0 {
debug.Println("channel empty:", ch.chidcli, ch.chidsrv, ch.conv)
ch.server_kcp_close = true
closed = append(closed, ch)
}
}
}
for _, ch := range closed {
this.promiseChannelClose(ch)
}
}
func (this *Tunneld) onKcpOutput(buf []byte, size int, extra interface{}) {
if size <= 0 {
// 如果总是出现,并且不影响程序运行,那么也就不是bug了
// info.Println("wtf")
return
}
debug.Println(len(buf), "//", size, "//", string(gopp.SubBytes(buf, 52)))
ch := extra.(*Channel)
msg := string([]byte{254}) + string(buf[:size])
err := this.FriendSendLossyPacket(ch.toxid, msg)
// msg := string([]byte{191}) + string(buf[:size])
// err := this.tox.FriendSendLosslessPacket(0, msg)
if err != nil {
debug.Println(err)
} else {
debug.Println("kcp->tox:", len(msg), time.Now().String())
}
}
func (this *Tunneld) processKcpReadyRead(ch *Channel) {
if ch.conn == nil {
errl.Println("Not Connected:", ch.chidsrv, ch.chidcli, ch.tname)
// return
}
buf := make([]byte, ch.kcp.PeekSize())
n := ch.kcp.Recv(buf)
if len(buf) != n {
errl.Println("Invalide kcp recv data", ch.tname)
}
pkt := parsePacket(buf)
if pkt.isconnack() {
} else if pkt.isdata() {
ch := this.chpool.pool[pkt.Chidsrv]
debug.Println("processing channel data:", ch.chidsrv, len(pkt.Data), gopp.StrSuf(string(pkt.Data), 52))
buf := pkt.Data
wn, err := ch.conn.Write(buf)
if err != nil {
errl.Println(err)
}
debug.Println("kcp->srv:", wn)
appevt.Trigger("reqbytes", wn, len(buf)+25)
} else {
}
}
// should block
func (this *Tunneld) connectToBackend(ch *Channel) {
this.chpool.putServer(ch)
// Dial
var conn net.Conn
var err error
// TODO 如果连接失败,响应的包会导致client崩溃
if ch.tproto == "tcp" {
conn, err = net.Dial("tcp", net.JoinHostPort(ch.ip, ch.port))
} else if ch.tproto == "udp" {
conn, err = net.Dial("udp", net.JoinHostPort(ch.ip, ch.port))
} else {
log.Panicln("not supported proto:", ch.tproto)
}
if err != nil {
errl.Println(err, ch.chidcli, ch.chidsrv, ch.conv, ch.tname)
// 连接结束
debug.Println("connection closed, cleaning up...:", ch.chidcli, ch.chidsrv, ch.conv)
ch.server_socket_close = true
this.serverCloseChan <- ServerCloseEvent{ch}
appevt.Trigger("connact", -1)
return
}
ch.conn = conn
info.Println("connected to:", conn.RemoteAddr().String(), ch.chidcli, ch.chidsrv, ch.conv, ch.tname)
// info.Println("channel connected,", ch.chidcli, ch.chidsrv, ch.conv, pkt.msgid)
repkt := ch.makeConnectACKPacket()
r, err := this.FriendSendMessage(ch.toxid, string(repkt.toJson()))
if err != nil {
debug.Println(err, r)
}
appevt.Trigger("newconn")
appevt.Trigger("connok")
appevt.Trigger("connact", 1)
// can connect backend now,不能阻塞,开新的goroutine
this.pollServerReadyRead(ch)
}
func (this *Tunneld) pollServerReadyRead(ch *Channel) {
// TODO 使用内存池
rbuf := make([]byte, rdbufsz)
debug.Println("copying server to client:", ch.chidsrv, ch.chidsrv, ch.conv)
// 使用kcp的mtu设置了,这里不再需要限制读取的包大小
for {
n, err := ch.conn.Read(rbuf)
if err != nil {
errl.Println(err, ch.chidsrv, ch.chidsrv, ch.conv)
break
}
// 控制kcp.WaitSnd()的大小
for {
if uint32(ch.kcp.WaitSnd()) < ch.kcp.snd_wnd*5 {
// this.processServerReadyRead(ch, rbuf, n)
sendbuf := gopp.BytesDup(rbuf[:n])
this.serverReadyReadChan <- ServerReadyReadEvent{ch, sendbuf, n}
break
} else {
time.Sleep(3 * time.Millisecond)
}
}
}
// 连接结束
debug.Println("connection closed, cleaning up...:", ch.chidcli, ch.chidsrv, ch.conv)
ch.server_socket_close = true
this.serverCloseChan <- ServerCloseEvent{ch}
appevt.Trigger("connact", -1)
}
func (this *Tunneld) processServerReadyRead(ch *Channel, buf []byte, size int) {
sbuf := buf
pkt := ch.makeDataPacket(sbuf)
sn := ch.kcp.Send(pkt.toJson())
debug.Println("srv->kcp:", sn, size)
appevt.Trigger("respbytes", size, len(pkt.toJson())+25) // 25 = kcp header len + 1tox
}
func (this *Tunneld) promiseChannelClose(ch *Channel) {
debug.Println("cleaning up:", ch.chidcli, ch.chidsrv, ch.conv)
if ch.server_socket_close == true && ch.server_kcp_close == true && ch.client_socket_close == false {
// server close and no data, connection finished
pkt := ch.makeCloseFINPacket()
_, err := this.FriendSendMessage(ch.toxid, string(pkt.toJson()))
if err != nil {
// 连接失败
debug.Println(err)
return
}
ch.addCloseReason("server_close")
info.Println("server socket closed, kcp empty, close by server",
ch.chidcli, ch.chidsrv, ch.conv, ch.closeReason())
this.chpool.rmServer(ch)
appevt.Trigger("closereason", ch.closeReason())
} else if ch.server_socket_close == true && ch.server_kcp_close == false && ch.client_socket_close == false {
ch.addCloseReason("server_close2")
info.Println("server socket closed, but kcp not empty", ch.chidcli, ch.chidsrv, ch.conv, ch.closeReason())
appevt.Trigger("closereason", ch.closeReason())
} else if ch.server_socket_close == false && ch.client_socket_close == true {
// 客户端先关闭,服务端无条件关闭,比较容易
ch.addCloseReason("client_close")
info.Println("force close...", ch.chidcli, ch.chidsrv, ch.conv, ch.closeReason())
ch.server_socket_close = true // ch.conn真正关闭可能有延时,造成此处重复处理。提前设置关闭标识。
ch.conn.Close()
appevt.Trigger("closereason", ch.closeReason())
} else if ch.server_socket_close == true && ch.client_socket_close == true {
ch.addCloseReason("both_close")
info.Println("both socket closed", ch.chidcli, ch.chidsrv, ch.conv, ch.closeReason())
this.chpool.rmServer(ch)
appevt.Trigger("closereason", ch.closeReason())
} else {
info.Println("what state:", ch.chidcli, ch.chidsrv, ch.conv,
ch.server_socket_close, ch.server_kcp_close, ch.client_socket_close)
panic("Ooops")
}
}
// TODO
func (this *Tunneld) channelGC() {
for _, ch := range this.chpool.pool {
if ch == nil {
}
}
}
////////////////
func (this *Tunneld) onToxnetSelfConnectionStatus(t *tox.Tox, status int, extra interface{}) {
info.Println("mytox status:", status)
if status == 0 {
switchServer(t)
} else {
addLiveBots(t)
t.WriteSavedata(tox_savedata_fname)
}
if status == 0 {
appevt.Trigger("selfonline", false)
appevt.Trigger("selfoffline")
} else {
appevt.Trigger("selfonline", true)
}
}
func (this *Tunneld) onToxnetFriendRequest(t *tox.Tox, friendId string, message string, userData interface{}) {
debug.Println(friendId, message)
t.FriendAddNorequest(friendId)
t.WriteSavedata(tox_savedata_fname)
}
func (this *Tunneld) onToxnetFriendConnectionStatus(t *tox.Tox, friendNumber uint32, status int, userData interface{}) {
fid, _ := this.tox.FriendGetPublicKey(friendNumber)
info.Println("peer status (fn/st/id):", friendNumber, status, fid)
if status == 0 {
// friendInChannel?
switchServer(t)
}
livebotsOnFriendConnectionStatus(t, friendNumber, status)
if status == 0 {
appevt.Trigger("peeronline", false)
appevt.Trigger("peeroffline")
} else {
appevt.Trigger("peeronline", true)
}
}
// a tool function
func (this *Tunneld) makeKcpConv(friendId string, pkt *Packet) uint32 {
// crc32: toxid+host+port+time
return makeKcpConv(friendId, pkt.Remoteip, pkt.Remoteport)
}
func (this *Tunneld) onToxnetFriendMessage(t *tox.Tox, friendNumber uint32, message string, userData interface{}) {
debug.Println(friendNumber, len(message), gopp.StrSuf(message, 52))
friendId, err := this.tox.FriendGetPublicKey(friendNumber)
if err != nil {
errl.Println(err)
}
pkt := parsePacket(bytes.NewBufferString(message).Bytes())
if pkt == nil {
info.Println("maybe not command, just normal message", gopp.StrSuf(message, 52))
} else {
if pkt.Command == CMDCONNSYN {
log.Println(message)
info.Printf("New conn on tunnel %s to %s:%s:%s\n", pkt.Tunname, pkt.Tunproto, pkt.Remoteip, pkt.Remoteport)
ch := NewChannelWithId(pkt.Chidcli, pkt.Tunname)
ch.tproto = pkt.Tunproto
ch.conv = this.makeKcpConv(friendId, pkt)
ch.ip = pkt.Remoteip
ch.port = pkt.Remoteport
ch.toxid = friendId
ch.kcp = NewKCP(ch.conv, this.onKcpOutput, ch)
ch.kcp.SetMtu(tunmtu)
ch.kcp.WndSize(smuse.wndsz, smuse.wndsz)
go this.connectToBackend(ch)
} else if pkt.Command == CMDCLOSEFIN {
if ch, ok := this.chpool.pool2[pkt.Conv]; ok {
info.Println("recv client close fin,", ch.chidcli, ch.chidsrv, ch.conv, pkt.Msgid)
ch.client_socket_close = true
this.promiseChannelClose(ch)
} else {
info.Println("recv client close fin, but maybe server already closed",
pkt.Command, pkt.Chidcli, pkt.Chidsrv, pkt.Conv, pkt.Msgid)
}
} else {
errl.Println("wtf, unknown cmmand:", pkt.Command, pkt.Chidcli, pkt.Chidsrv, pkt.Conv)
}
}
}
func (this *Tunneld) onToxnetFriendLossyPacket(t *tox.Tox, friendNumber uint32, message string, userData interface{}) {
debug.Println(friendNumber, len(message), gopp.StrSuf(message, 52), time.Now().String())
buf := bytes.NewBufferString(message).Bytes()
if buf[0] == 254 {
buf = buf[1:]
// kcp包前4字段为conv,little hacky
conv := binary.LittleEndian.Uint32(buf)
ch := this.chpool.pool2[conv]
if ch == nil {
info.Println("channel not found, maybe has some problem, maybe closed", conv)
} else {
n := ch.kcp.Input(buf, true, true)
debug.Println("tox->kcp:", conv, n, len(buf), gopp.StrSuf(string(buf), 52))
}
} else {
info.Println("unknown message:", buf[0])
}
}
func (this *Tunneld) onToxnetFriendLosslessPacket(t *tox.Tox, friendNumber uint32, message string, userData interface{}) {
debug.Println(friendNumber, len(message), gopp.StrSuf(message, 52))
buf := bytes.NewBufferString(message).Bytes()
if buf[0] == 191 {
buf = buf[1:]
// kcp包前4字节为conv,little hacky
if len(buf) < 4 {
errl.Println("wtf")
}
conv := binary.LittleEndian.Uint32(buf)
ch := this.chpool.pool2[conv]
if ch == nil {
errl.Println("channel not found, maybe has some problem, maybe already closed", conv)
} else {
n := ch.kcp.Input(buf, true, true)
debug.Println("tox->kcp:", conv, n, len(buf), gopp.StrSuf(string(buf), 52))
}
} else {
info.Println("unknown message:", buf[0])
}
}
func (this *Tunneld) FriendSendMessage(friendId string, message string) (uint32, error) {
friendNumber, err := this.tox.FriendByPublicKey(friendId)
if err != nil {
return 0, err
}
return this.tox.FriendSendMessage(friendNumber, message)
}
func (this *Tunneld) FriendSendLossyPacket(friendId string, message string) error {
friendNumber, err := this.tox.FriendByPublicKey(friendId)
if err != nil {
return err
}
return this.tox.FriendSendLossyPacket(friendNumber, message)
}