/
parser.go
177 lines (152 loc) · 4.46 KB
/
parser.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
package main
import (
"errors"
"fmt"
"github.com/dchest/uniuri"
"github.com/kurafuto/kyubu/packets"
"net"
"sync"
"time"
)
var (
ErrPacketSkipped = errors.New("kurafuto: Packet skipped")
ErrParserFinished = errors.New("kurafuto: Parser finished (timed out)")
)
// A Hook is a function which takes a packet, and information about where the
// packet came from (player and direction). A return value of `true` means the
// packet has been "handled", and the parser will skip to the next packet.
type Hook func(*Player, packets.PacketDirection, packets.Packet) bool
type hookInfo struct {
Id string
F Hook
}
// AllPackets is a special sentinel type that allows registration of hooks run
// on every packet received by a hooked Parser. It may break things if there is
// a packet registered with `Id() == 0xff`.
type AllPackets struct {
}
func (p AllPackets) Id() byte {
return 0xff
}
func (p AllPackets) Size() int {
return 1
}
func (p AllPackets) Bytes() []byte {
return []byte{0xff}
}
// Parser is a wrapper implementation of a Kyubu packets.Parser, which allows
// function hooks to be run when specific packets are parsed out of the stream.
// It also allows read timeouts, where if a packet isn't received in the specified
// time, the parser is "finished", and will stop consuming packets.
type Parser struct {
player *Player
conn net.Conn
parser packets.Parser
hooks map[byte][]hookInfo
Direction packets.PacketDirection
Disable bool // Allows all hooks to be bypassed.
finished bool
mutex sync.Mutex
Timeout time.Duration
}
func (p *Parser) Finish() {
if p == nil {
return
}
p.mutex.Lock()
defer p.mutex.Unlock()
p.finished = true
}
// Next returns the next packet parsed out of the internal parser, and fires any
// hooks related to this packet type. If any of the hooks return "handled", Next
// will return `kurafuto.ErrPacketSkipped`. Users of the parser are expected to
// re-call Next. If the parser is "finished", or times out it will return
// `kurafuto.ErrParserFinished` forever.
func (p *Parser) Next() (packets.Packet, error) {
if p == nil {
return nil, ErrParserFinished
}
p.mutex.Lock()
if p.finished {
p.mutex.Unlock()
return nil, ErrParserFinished
}
p.mutex.Unlock()
// Force a deadline, this means if we don't get a response in the given
// time, we can consider the parser "finished".
p.conn.SetReadDeadline(time.Now().Add(p.Timeout))
packet, err := p.parser.Next()
if e, ok := err.(net.Error); ok && e.Timeout() {
p.Finish()
return nil, ErrParserFinished
}
// An empty Time{} indicates removing the read deadline. I think.
// It's what Go's net/timeout_test.go does, so whatever.
p.conn.SetReadDeadline(time.Time{})
if packet == nil {
return packet, err
}
if p.Disable {
// Return early, we're ignoring hooks.
return packet, err
}
skipPacket := func(h []hookInfo) bool {
for _, hook := range h {
if skip := hook.F(p.player, p.Direction, packet); skip {
return true
}
}
return false
}
// Run AllPacket hooks first
if hooks, ok := p.hooks[0xff]; ok {
if skip := skipPacket(hooks); skip {
return packet, ErrPacketSkipped
}
}
// Regular hooks for this packet
if hooks, ok := p.hooks[packet.Id()]; ok {
if skip := skipPacket(hooks); skip {
return packet, ErrPacketSkipped
}
}
return packet, err
}
func (p *Parser) Register(packet packets.Packet, hook Hook) (string, error) {
if _, ok := p.hooks[packet.Id()]; !ok {
p.hooks[packet.Id()] = []hookInfo{}
}
id := uniuri.NewLen(8)
info := hookInfo{Id: id, F: hook}
p.hooks[packet.Id()] = append(p.hooks[packet.Id()], info)
return id, nil
}
func (p *Parser) Unregister(hookId string) (bool, error) {
for id, hooks := range p.hooks {
for i, hook := range hooks {
if hook.Id != hookId {
continue
}
// This just removes the hook we're looking for. Bless Golang.
p.hooks[id] = append(p.hooks[id][:i], p.hooks[id][i+1:]...)
return true, nil
}
}
return false, fmt.Errorf("kurafuto: No hook registered for id %s", hookId)
}
// UnregisterAll forcefully unregisters all currently registered hooks by recreating
// the internal hooks list.
func (p *Parser) UnregisterAll() {
p.hooks = make(map[byte][]hookInfo)
}
func NewParser(player *Player, conn net.Conn, dir packets.PacketDirection, t time.Duration) packets.Parser {
return &Parser{
player: player,
conn: conn,
parser: packets.NewParser(conn, dir),
hooks: make(map[byte][]hookInfo),
Direction: dir,
mutex: sync.Mutex{},
Timeout: t,
}
}