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