This repository has been archived by the owner on Oct 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 74
/
websockets.go
331 lines (283 loc) · 7.84 KB
/
websockets.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
331
// Package websockets manages active websocket connections and messages received
// from and sent to them
package websockets
import (
"bytes"
"errors"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/bakape/meguca/auth"
"github.com/bakape/meguca/util"
"github.com/gorilla/websocket"
)
const pingWriteTimeout = time.Second * 30
var (
// Overrideable for faster tests
pingTimer = time.Minute
upgrader = websocket.Upgrader{
HandshakeTimeout: 5 * time.Second,
CheckOrigin: func(_ *http.Request) bool {
return true
},
}
)
// errInvalidPayload denotes a malformed messages received from the client
type errInvalidPayload []byte
func (e errInvalidPayload) Error() string {
return fmt.Sprintf("invalid message: %s", string(e))
}
// errInvalidFrame denotes an invalid websocket frame in some other way than
// errInvalidMessage
type errInvalidFrame string
func (e errInvalidFrame) Error() string {
return string(e)
}
// Client stores and manages a websocket-connected remote client and its
// interaction with the server and database
type Client struct {
// Synchronized to any change feed and registered in the global Clients map.
// Should only be mutated from Clients, which also contains weather this
// Client is synced. The local property exists mainly to reduce lock
// contention on Clients.
synced bool
// Post currently open by the client
openPost openPost
// Currently subscribed to update feed, if any
feedID uint64
// Underlying websocket connection
conn *websocket.Conn
// Token of an authenticated user session, if any
sessionToken string
// Client IP
ip string
// Internal message receiver channel
receive chan receivedMessage
// Only used to pass messages from the Send method.
sendExternal chan []byte
// Close the client and free all used resources
close chan error
}
type receivedMessage struct {
typ int
msg []byte
}
// Data of a post currently being written to by a Client
type openPost struct {
hasImage bool
bytes.Buffer
bodyLength int
id, op uint64
time int64
board string
}
// Handler is an http.HandleFunc that responds to new websocket connection
// requests.
func Handler(res http.ResponseWriter, req *http.Request) {
conn, err := upgrader.Upgrade(res, req, nil)
if err != nil {
ip := auth.GetIP(req)
log.Printf("websockets: %s: %s\n", ip, err)
return
}
c := newClient(conn, req)
if err := c.listen(); err != nil {
c.logError(err)
}
}
// newClient creates a new websocket client
func newClient(conn *websocket.Conn, req *http.Request) *Client {
return &Client{
ip: auth.LookUpIdent(req).IP,
close: make(chan error, 2),
receive: make(chan receivedMessage),
// Allows for ~6 seconds of messages at 0.2 second intervals, until the
// buffer overflows.
sendExternal: make(chan []byte, 1<<5),
conn: conn,
}
}
// Listen listens for incoming messages on the channels and processes them
func (c *Client) listen() error {
go c.receiverLoop()
// Clean up, when loop exits
err := c.listenerLoop()
Clients.remove(c)
return c.closeConnections(err)
}
// Separate function to ease error handling of the internal client loop
func (c *Client) listenerLoop() error {
// Periodically ping the client to ensure external proxies and CDNs do not
// close the connection. Those have a tendency of sending 1001 to both ends
// after rather short timeout, if no messages have been sent.
ping := time.NewTicker(pingTimer)
defer ping.Stop()
for {
select {
case err := <-c.close:
return err
case msg := <-c.sendExternal:
if err := c.send(msg); err != nil {
return err
}
case <-ping.C:
deadline := time.Now().Add(pingWriteTimeout)
err := c.conn.WriteControl(websocket.PingMessage, nil, deadline)
if err != nil {
return err
}
case msg := <-c.receive:
if err := c.handleMessage(msg.typ, msg.msg); err != nil {
return err
}
}
}
}
// Close all connections an goroutines associated with the Client
func (c *Client) closeConnections(err error) error {
// Close update feed, if any
if c.feedID != 0 {
feeds.Remove <- subRequest{c.feedID, c}
c.feedID = 0
}
// Close receiver loop
c.Close(nil)
// Send the client the reason for closing
var closeType int
switch err.(type) {
case *websocket.CloseError:
switch err.(*websocket.CloseError).Code {
// Normal client-side websocket closure
case websocket.CloseNormalClosure, websocket.CloseGoingAway:
err = nil
closeType = websocket.CloseNormalClosure
// Ignore abnormal websocket closure as a network fault
case websocket.CloseAbnormalClosure:
err = nil
}
case nil:
closeType = websocket.CloseNormalClosure
default:
c.sendMessage(MessageInvalid, err.Error())
closeType = websocket.CloseInvalidFramePayloadData
}
// Try to send the client a close frame. This might fail, so ignore any
// errors.
if closeType != 0 {
msg := websocket.FormatCloseMessage(closeType, "")
deadline := time.Now().Add(time.Second)
c.conn.WriteControl(websocket.CloseMessage, msg, deadline)
}
// Close socket
closeError := c.conn.Close()
if closeError != nil {
err = util.WrapError(closeError.Error(), err)
}
return err
}
// Send a message to the client. Can be used concurrently.
func (c *Client) Send(msg []byte) {
select {
case c.sendExternal <- msg:
default:
c.Close(errors.New("send buffer overflow"))
}
}
// Sends a message to the client. Not safe for concurrent use.
func (c *Client) send(msg []byte) error {
return c.conn.WriteMessage(websocket.TextMessage, msg)
}
// Format a message type as JSON and send it to the client. Not safe for
// concurrent use.
func (c *Client) sendMessage(typ MessageType, msg interface{}) error {
encoded, err := EncodeMessage(typ, msg)
if err != nil {
return err
}
return c.send(encoded)
}
// receiverLoop proxies the blocking conn.ReadMessage() into the main client
// select loop.
func (c *Client) receiverLoop() {
for {
var (
err error
msg receivedMessage
)
msg.typ, msg.msg, err = c.conn.ReadMessage() // Blocking
if err != nil {
c.Close(err)
return
}
select {
case <-c.close:
return
case c.receive <- msg:
}
}
}
// handleMessage parses a message received from the client through websockets
func (c *Client) handleMessage(msgType int, msg []byte) error {
if msgType != websocket.TextMessage {
return errInvalidFrame("only text frames allowed")
}
if len(msg) < 2 {
return errInvalidPayload(msg)
}
// First two characters of a message define its type
uncast, err := strconv.ParseUint(string(msg[:2]), 10, 8)
if err != nil {
return errInvalidPayload(msg)
}
typ := MessageType(uncast)
if !c.synced && typ != MessageSynchronise {
return errInvalidPayload(msg)
}
return c.runHandler(typ, msg)
}
// Run the appropriate handler for the websocket message
func (c *Client) runHandler(typ MessageType, msg []byte) error {
data := msg[2:]
handler, ok := handlers[typ]
if !ok {
return errInvalidPayload(msg)
}
return handler(data, c)
}
// logError writes the client's websocket error to the error log (or stdout)
func (c *Client) logError(err error) {
log.Printf("error by %s: %v\n", c.ip, err)
}
// Close closes a websocket connection with the provided status code and
// optional reason
func (c *Client) Close(err error) {
select {
case <-c.close:
default:
// Exit both for-select loops, if they have not exited yet
for i := 0; i < 2; i++ {
select {
case c.close <- err:
default:
}
}
}
}
// Small helper method for more DRY-ness. Not thread-safe.
func (c *Client) isLoggedIn() bool {
return c.sessionToken != ""
}
// Helper for determining, if the client currently has an open post not older
// than 29 minutes. If the post is older, it is closed automatically.
func (c *Client) hasPost() (bool, error) {
switch {
case c.openPost.id == 0:
return false, errNoPostOpen
case c.openPost.time < time.Now().Add(-time.Minute*29).Unix():
return false, closePost(nil, c)
default:
return true, nil
}
}