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