1 | package soju
|
---|
2 |
|
---|
3 | import (
|
---|
4 | "context"
|
---|
5 | "fmt"
|
---|
6 | "io"
|
---|
7 | "net"
|
---|
8 | "strings"
|
---|
9 | "sync"
|
---|
10 | "time"
|
---|
11 | "unicode"
|
---|
12 |
|
---|
13 | "golang.org/x/time/rate"
|
---|
14 | "gopkg.in/irc.v3"
|
---|
15 | "nhooyr.io/websocket"
|
---|
16 | )
|
---|
17 |
|
---|
18 | // ircConn is a generic IRC connection. It's similar to net.Conn but focuses on
|
---|
19 | // reading and writing IRC messages.
|
---|
20 | type ircConn interface {
|
---|
21 | ReadMessage() (*irc.Message, error)
|
---|
22 | WriteMessage(*irc.Message) error
|
---|
23 | Close() error
|
---|
24 | SetReadDeadline(time.Time) error
|
---|
25 | SetWriteDeadline(time.Time) error
|
---|
26 | RemoteAddr() net.Addr
|
---|
27 | LocalAddr() net.Addr
|
---|
28 | }
|
---|
29 |
|
---|
30 | func newNetIRCConn(c net.Conn) ircConn {
|
---|
31 | type netConn net.Conn
|
---|
32 | return struct {
|
---|
33 | *irc.Conn
|
---|
34 | netConn
|
---|
35 | }{irc.NewConn(c), c}
|
---|
36 | }
|
---|
37 |
|
---|
38 | type websocketIRCConn struct {
|
---|
39 | conn *websocket.Conn
|
---|
40 | readDeadline, writeDeadline time.Time
|
---|
41 | remoteAddr string
|
---|
42 | }
|
---|
43 |
|
---|
44 | func newWebsocketIRCConn(c *websocket.Conn, remoteAddr string) ircConn {
|
---|
45 | return &websocketIRCConn{conn: c, remoteAddr: remoteAddr}
|
---|
46 | }
|
---|
47 |
|
---|
48 | func (wic *websocketIRCConn) ReadMessage() (*irc.Message, error) {
|
---|
49 | ctx := context.Background()
|
---|
50 | if !wic.readDeadline.IsZero() {
|
---|
51 | var cancel context.CancelFunc
|
---|
52 | ctx, cancel = context.WithDeadline(ctx, wic.readDeadline)
|
---|
53 | defer cancel()
|
---|
54 | }
|
---|
55 | _, b, err := wic.conn.Read(ctx)
|
---|
56 | if err != nil {
|
---|
57 | switch websocket.CloseStatus(err) {
|
---|
58 | case websocket.StatusNormalClosure, websocket.StatusGoingAway:
|
---|
59 | return nil, io.EOF
|
---|
60 | default:
|
---|
61 | return nil, err
|
---|
62 | }
|
---|
63 | }
|
---|
64 | return irc.ParseMessage(string(b))
|
---|
65 | }
|
---|
66 |
|
---|
67 | func (wic *websocketIRCConn) WriteMessage(msg *irc.Message) error {
|
---|
68 | b := []byte(strings.ToValidUTF8(msg.String(), string(unicode.ReplacementChar)))
|
---|
69 | ctx := context.Background()
|
---|
70 | if !wic.writeDeadline.IsZero() {
|
---|
71 | var cancel context.CancelFunc
|
---|
72 | ctx, cancel = context.WithDeadline(ctx, wic.writeDeadline)
|
---|
73 | defer cancel()
|
---|
74 | }
|
---|
75 | return wic.conn.Write(ctx, websocket.MessageText, b)
|
---|
76 | }
|
---|
77 |
|
---|
78 | func isErrWebSocketClosed(err error) bool {
|
---|
79 | return err != nil && strings.HasSuffix(err.Error(), "failed to close WebSocket: already wrote close")
|
---|
80 | }
|
---|
81 |
|
---|
82 | func (wic *websocketIRCConn) Close() error {
|
---|
83 | err := wic.conn.Close(websocket.StatusNormalClosure, "")
|
---|
84 | // TODO: remove once this PR is merged:
|
---|
85 | // https://github.com/nhooyr/websocket/pull/303
|
---|
86 | if isErrWebSocketClosed(err) {
|
---|
87 | return nil
|
---|
88 | }
|
---|
89 | return err
|
---|
90 | }
|
---|
91 |
|
---|
92 | func (wic *websocketIRCConn) SetReadDeadline(t time.Time) error {
|
---|
93 | wic.readDeadline = t
|
---|
94 | return nil
|
---|
95 | }
|
---|
96 |
|
---|
97 | func (wic *websocketIRCConn) SetWriteDeadline(t time.Time) error {
|
---|
98 | wic.writeDeadline = t
|
---|
99 | return nil
|
---|
100 | }
|
---|
101 |
|
---|
102 | func (wic *websocketIRCConn) RemoteAddr() net.Addr {
|
---|
103 | return websocketAddr(wic.remoteAddr)
|
---|
104 | }
|
---|
105 |
|
---|
106 | func (wic *websocketIRCConn) LocalAddr() net.Addr {
|
---|
107 | // Behind a reverse HTTP proxy, we don't have access to the real listening
|
---|
108 | // address
|
---|
109 | return websocketAddr("")
|
---|
110 | }
|
---|
111 |
|
---|
112 | type websocketAddr string
|
---|
113 |
|
---|
114 | func (websocketAddr) Network() string {
|
---|
115 | return "ws"
|
---|
116 | }
|
---|
117 |
|
---|
118 | func (wa websocketAddr) String() string {
|
---|
119 | return string(wa)
|
---|
120 | }
|
---|
121 |
|
---|
122 | type connOptions struct {
|
---|
123 | Logger Logger
|
---|
124 | RateLimitDelay time.Duration
|
---|
125 | RateLimitBurst int
|
---|
126 | }
|
---|
127 |
|
---|
128 | type conn struct {
|
---|
129 | conn ircConn
|
---|
130 | srv *Server
|
---|
131 | logger Logger
|
---|
132 |
|
---|
133 | lock sync.Mutex
|
---|
134 | outgoing chan<- *irc.Message
|
---|
135 | closed bool
|
---|
136 | closedCh chan struct{}
|
---|
137 | }
|
---|
138 |
|
---|
139 | func newConn(srv *Server, ic ircConn, options *connOptions) *conn {
|
---|
140 | outgoing := make(chan *irc.Message, 64)
|
---|
141 | c := &conn{
|
---|
142 | conn: ic,
|
---|
143 | srv: srv,
|
---|
144 | outgoing: outgoing,
|
---|
145 | logger: options.Logger,
|
---|
146 | closedCh: make(chan struct{}),
|
---|
147 | }
|
---|
148 |
|
---|
149 | go func() {
|
---|
150 | ctx, cancel := c.NewContext(context.Background())
|
---|
151 | defer cancel()
|
---|
152 |
|
---|
153 | rl := rate.NewLimiter(rate.Every(options.RateLimitDelay), options.RateLimitBurst)
|
---|
154 | for msg := range outgoing {
|
---|
155 | if err := rl.Wait(ctx); err != nil {
|
---|
156 | break
|
---|
157 | }
|
---|
158 |
|
---|
159 | c.logger.Debugf("sent: %v", msg)
|
---|
160 | c.conn.SetWriteDeadline(time.Now().Add(writeTimeout))
|
---|
161 | if err := c.conn.WriteMessage(msg); err != nil {
|
---|
162 | c.logger.Printf("failed to write message: %v", err)
|
---|
163 | break
|
---|
164 | }
|
---|
165 | }
|
---|
166 | if err := c.conn.Close(); err != nil && !isErrClosed(err) {
|
---|
167 | c.logger.Printf("failed to close connection: %v", err)
|
---|
168 | } else {
|
---|
169 | c.logger.Printf("connection closed")
|
---|
170 | }
|
---|
171 | // Drain the outgoing channel to prevent SendMessage from blocking
|
---|
172 | for range outgoing {
|
---|
173 | // This space is intentionally left blank
|
---|
174 | }
|
---|
175 | }()
|
---|
176 |
|
---|
177 | c.logger.Printf("new connection")
|
---|
178 | return c
|
---|
179 | }
|
---|
180 |
|
---|
181 | func (c *conn) isClosed() bool {
|
---|
182 | c.lock.Lock()
|
---|
183 | defer c.lock.Unlock()
|
---|
184 | return c.closed
|
---|
185 | }
|
---|
186 |
|
---|
187 | // Close closes the connection. It is safe to call from any goroutine.
|
---|
188 | func (c *conn) Close() error {
|
---|
189 | c.lock.Lock()
|
---|
190 | defer c.lock.Unlock()
|
---|
191 |
|
---|
192 | if c.closed {
|
---|
193 | return fmt.Errorf("connection already closed")
|
---|
194 | }
|
---|
195 |
|
---|
196 | err := c.conn.Close()
|
---|
197 | c.closed = true
|
---|
198 | close(c.outgoing)
|
---|
199 | close(c.closedCh)
|
---|
200 | return err
|
---|
201 | }
|
---|
202 |
|
---|
203 | func (c *conn) ReadMessage() (*irc.Message, error) {
|
---|
204 | msg, err := c.conn.ReadMessage()
|
---|
205 | if isErrClosed(err) {
|
---|
206 | return nil, io.EOF
|
---|
207 | } else if err != nil {
|
---|
208 | return nil, err
|
---|
209 | }
|
---|
210 |
|
---|
211 | c.logger.Debugf("received: %v", msg)
|
---|
212 | return msg, nil
|
---|
213 | }
|
---|
214 |
|
---|
215 | // SendMessage queues a new outgoing message. It is safe to call from any
|
---|
216 | // goroutine.
|
---|
217 | //
|
---|
218 | // If the connection is closed before the message is sent, SendMessage silently
|
---|
219 | // drops the message.
|
---|
220 | func (c *conn) SendMessage(msg *irc.Message) {
|
---|
221 | c.lock.Lock()
|
---|
222 | defer c.lock.Unlock()
|
---|
223 |
|
---|
224 | if c.closed {
|
---|
225 | return
|
---|
226 | }
|
---|
227 | c.outgoing <- msg
|
---|
228 | }
|
---|
229 |
|
---|
230 | func (c *conn) RemoteAddr() net.Addr {
|
---|
231 | return c.conn.RemoteAddr()
|
---|
232 | }
|
---|
233 |
|
---|
234 | func (c *conn) LocalAddr() net.Addr {
|
---|
235 | return c.conn.LocalAddr()
|
---|
236 | }
|
---|
237 |
|
---|
238 | // NewContext returns a copy of the parent context with a new Done channel. The
|
---|
239 | // returned context's Done channel is closed when the connection is closed,
|
---|
240 | // when the returned cancel function is called, or when the parent context's
|
---|
241 | // Done channel is closed, whichever happens first.
|
---|
242 | //
|
---|
243 | // Canceling this context releases resources associated with it, so code should
|
---|
244 | // call cancel as soon as the operations running in this Context complete.
|
---|
245 | func (c *conn) NewContext(parent context.Context) (context.Context, context.CancelFunc) {
|
---|
246 | ctx, cancel := context.WithCancel(parent)
|
---|
247 |
|
---|
248 | go func() {
|
---|
249 | defer cancel()
|
---|
250 |
|
---|
251 | select {
|
---|
252 | case <-ctx.Done():
|
---|
253 | // The parent context has been cancelled, or the caller has called
|
---|
254 | // cancel()
|
---|
255 | case <-c.closedCh:
|
---|
256 | // The connection has been closed
|
---|
257 | }
|
---|
258 | }()
|
---|
259 |
|
---|
260 | return ctx, cancel
|
---|
261 | }
|
---|