aboutsummaryrefslogtreecommitdiff
path: root/internal/net/wsconn.go
blob: 95f714c9480a6ce50fc1c606635a8aaf377425a4 (plain)
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
package net

import (
	"time"

	"github.com/gorilla/websocket"
)

type wsConn struct {
	conn *websocket.Conn
}

func newWSConn(conn *websocket.Conn) *wsConn {
	// Bound incoming message size so a client cannot push arbitrarily large
	// frames into memory before the session's truncation logic runs.
	conn.SetReadLimit(maxLineLength * 4)
	return &wsConn{conn: conn}
}

func (w *wsConn) ReadMessage() (string, error) {
	_, msg, err := w.conn.ReadMessage()
	return string(msg), err
}

func (w *wsConn) Write(b []byte) (int, error) {
	err := w.conn.WriteMessage(websocket.TextMessage, b)
	return len(b), err
}

// RemoteAddr reports the peer address for the login throttle.
func (w *wsConn) RemoteAddr() string {
	if w.conn == nil {
		return ""
	}
	return w.conn.RemoteAddr().String()
}

// SetWriteDeadline delegates to the underlying websocket connection, which
// supports deadlines natively.
func (w *wsConn) SetWriteDeadline(ts time.Time) error {
	return w.conn.SetWriteDeadline(ts)
}

func (w *wsConn) Close() error {
	return w.conn.Close()
}

func (w *wsConn) SetEcho(on bool) error {
	return w.conn.WriteMessage(websocket.TextMessage, w.EchoSequence(on))
}

// EchoSequence returns the browser echo-control bytes for the websocket
// transport; queued sessions send these through the session writer so a
// stalled browser cannot block the caller (see Session.SetEcho).
func (w *wsConn) EchoSequence(on bool) []byte {
	if on {
		return []byte("\x1b]10;0\x07")
	}
	return []byte("\x1b]10;1\x07")
}

// SetEchoState is a no-op: the websocket transport keeps no local echo state.
func (w *wsConn) SetEchoState(bool) {}