-
Notifications
You must be signed in to change notification settings - Fork 2
/
handshack.go
122 lines (93 loc) · 1.95 KB
/
handshack.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 sharpshooter
import (
"github.com/soyum2222/sharpshooter/protocol"
"math/rand"
"net"
"time"
)
func init() {
rand.Seed(time.Now().Unix())
}
func firstHandShack(h *headquarters, remote net.Addr) {
_, ok := h.Snipers.Load(remote.String())
if ok {
return
}
sn := NewSniper(h.conn, remote.(*net.UDPAddr))
// verification status
// avoid malicious packages
if sn.status != STATUS_NONE {
return
}
h.Snipers.Store(remote.String(), sn)
sn.latestSendId = rand.Uint32()
ammo := protocol.Ammo{
Id: sn.latestSendId,
Kind: protocol.SECONDHANDSHACK,
Body: nil,
}
go func() {
var try int
ticker := time.NewTicker(time.Millisecond * 200)
defer ticker.Stop()
loop:
if try > DEFAULT_INIT_HANDSHACK_TIMEOUT {
return
}
sn.status = STATUS_SECONDHANDSHACK
_, _ = sn.conn.WriteToUDP(protocol.Marshal(ammo), sn.aim)
select {
case <-ticker.C:
try++
goto loop
case <-sn.handShakeSign:
return
}
}()
}
func secondHandShack(h *headquarters, remote net.Addr, id uint32) {
i, ok := h.Snipers.Load(remote.String())
if !ok {
return
}
sn := i.(*Sniper)
// verification status
// avoid malicious packages
if sn.status != STATUS_NONE {
return
}
sn.status = STATUS_THIRDHANDSHACK
ammo := protocol.Ammo{
Id: id,
Kind: protocol.THIRDHANDSHACK,
Body: nil,
}
_, _ = sn.conn.WriteToUDP(protocol.Marshal(ammo), sn.aim)
}
func thirdHandShack(h *headquarters, remote net.Addr, id uint32) {
i, ok := h.Snipers.Load(remote.String())
if !ok {
return
}
sn := i.(*Sniper)
// verification status
// avoid malicious packages
if sn.status != STATUS_SECONDHANDSHACK {
return
}
if id != sn.latestSendId {
h.Snipers.Delete(remote.String())
return
}
sn.latestSendId = 0
//if sn.status != STATUS_SECONDHANDSHACK {
// return
//}
sn.status = STATUS_NORMAL
SystemTimedSched.Put(sn.healthMonitor, time.Now().Add(time.Second*3))
select {
case sn.handShakeSign <- struct{}{}:
default:
}
h.accept <- sn
}