/
client.go
229 lines (206 loc) · 5.12 KB
/
client.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
package server
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/elazarl/goproxy"
"github.com/gorilla/websocket"
"github.com/kyoukaya/rhine/proxy"
"github.com/kyoukaya/rhine/proxy/gamestate"
"github.com/kyoukaya/angelina/server/msg"
)
const (
// Time allowed to write a message to the peer.
writeWait = 5 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
)
var (
newline = []byte{'\n'}
space = []byte{' '}
)
// Client is a middleman between the websocket connection and the hub.
type Client struct {
ange *Ange
mod *proxy.RhineModule
hookCounter uint64 // Incrementing counter to produce unique hook IDs
hooks map[uint64]*clientHook
listener chan gamestate.StateEvent
// The websocket connection.
conn *websocket.Conn
// Buffered channel of outbound messages.
send chan []byte
}
func (c *Client) sendWrapper(data []byte) {
select {
case c.send <- data:
default:
c.ange.Warnf("[Ange] Failed to send data to %p", c)
}
}
func (c *Client) removeHook(id uint64) error {
hook := c.hooks[id]
if hook == nil {
return fmt.Errorf("Unable to find hook ID %d to unhook", id)
}
hook.Unhook()
delete(c.hooks, id)
return nil
}
func (c *Client) unhookAll() {
for k, hook := range c.hooks {
hook.Unhook()
delete(c.hooks, k)
}
}
func (c *Client) addHook(data *msg.Hook) error {
var hook proxy.Hooker
switch data.Kind {
case packetHook:
hook = c.mod.Hook(data.Target, 0, c.hookHandler)
case gameStateHook:
hook = c.mod.StateHook(data.Target, c.listener, data.Event)
default:
return fmt.Errorf("Unknown hook type '%s'", data.Kind)
}
c.hooks[c.hookCounter] = &clientHook{
kind: data.Kind,
target: data.Target,
event: data.Event,
hook: hook,
}
ret, err := msg.ServerHooked(c.hookCounter, data.Kind, data.Target, data.Event)
if err != nil {
return err
}
c.hookCounter++
c.sendWrapper(ret)
return nil
}
func (c *Client) hookHandler(op string, data []byte, pktCtx *goproxy.ProxyCtx) []byte {
b, err := msg.ServerHookEvt(packetHook, op, json.RawMessage(data))
if err != nil {
c.ange.Warnln("[Ange] ", err)
return data
}
c.sendWrapper(b)
return data
}
func (c *Client) stateListener() {
for {
l, open := <-c.listener
if !open {
return
}
b, err := msg.ServerHookEvt(gameStateHook, l.Path, l.Payload)
if err != nil {
c.ange.Warnln("[Ange] ", err)
continue
}
c.sendWrapper(b)
}
}
// readPump pumps messages from the websocket connection to the hub.
//
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most one reader on a connection by executing all
// reads from this goroutine.
func (c *Client) readPump() {
defer func() {
c.ange.unregister <- c
c.conn.Close()
}()
// c.conn.SetReadLimit(maxMessageSize)
err := c.conn.SetReadDeadline(time.Now().Add(pongWait))
if err != nil {
c.ange.Warnln("[Ange] ", err)
return
}
c.conn.SetPongHandler(func(string) error {
return c.conn.SetReadDeadline(time.Now().Add(pongWait))
})
for {
_, msg, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure, websocket.CloseNormalClosure) {
c.ange.Warnln("[Ange] ", err)
}
break
}
msg = bytes.TrimSpace(bytes.Replace(msg, newline, space, -1))
c.ange.messages <- &messageT{
client: c,
payload: msg,
}
}
}
// writePump pumps messages from the hub to the websocket connection.
//
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *Client) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
if !ok {
// The hub closed the channel.
return
}
err := c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err != nil {
c.ange.Warnln("[Ange] ", err)
continue
}
w, err := c.conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
_, err = w.Write(message)
if err != nil {
c.ange.Warnln("[Ange] ", err)
continue
}
if err := w.Close(); err != nil {
return
}
case <-ticker.C:
err := c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err != nil {
c.ange.Warnln("[Ange] ", err)
return
}
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
// ServeWs handles websocket requests from the peer.
func (ange *Ange) ServeWs(w http.ResponseWriter, r *http.Request) {
conn, err := ange.upgrader.Upgrade(w, r, nil)
if err != nil {
ange.Warnf("[Ange] %s", err.Error())
return
}
client := &Client{
ange: ange,
hooks: make(map[uint64]*clientHook),
listener: make(chan gamestate.StateEvent, 32),
conn: conn,
send: make(chan []byte, 128),
}
client.ange.register <- client
go client.stateListener()
go client.writePump()
go client.readPump()
}