|
| 1 | +// +build !js |
| 2 | + |
1 | 3 | package websocket
|
2 | 4 |
|
3 | 5 | import (
|
| 6 | + "context" |
| 7 | + "encoding/binary" |
4 | 8 | "errors"
|
5 | 9 | "fmt"
|
| 10 | + "log" |
| 11 | + "time" |
| 12 | + |
| 13 | + "nhooyr.io/websocket/internal/errd" |
6 | 14 | )
|
7 | 15 |
|
8 | 16 | // StatusCode represents a WebSocket status code.
|
@@ -74,3 +82,200 @@ func CloseStatus(err error) StatusCode {
|
74 | 82 | }
|
75 | 83 | return -1
|
76 | 84 | }
|
| 85 | + |
| 86 | +// Close performs the WebSocket close handshake with the given status code and reason. |
| 87 | +// |
| 88 | +// It will write a WebSocket close frame with a timeout of 5s and then wait 5s for |
| 89 | +// the peer to send a close frame. |
| 90 | +// All data messages received from the peer during the close handshake will be discarded. |
| 91 | +// |
| 92 | +// The connection can only be closed once. Additional calls to Close |
| 93 | +// are no-ops. |
| 94 | +// |
| 95 | +// The maximum length of reason must be 125 bytes. Avoid |
| 96 | +// sending a dynamic reason. |
| 97 | +// |
| 98 | +// Close will unblock all goroutines interacting with the connection once |
| 99 | +// complete. |
| 100 | +func (c *Conn) Close(code StatusCode, reason string) error { |
| 101 | + return c.closeHandshake(code, reason) |
| 102 | +} |
| 103 | + |
| 104 | +func (c *Conn) closeHandshake(code StatusCode, reason string) (err error) { |
| 105 | + defer errd.Wrap(&err, "failed to close WebSocket") |
| 106 | + |
| 107 | + writeErr := c.writeClose(code, reason) |
| 108 | + closeHandshakeErr := c.waitCloseHandshake() |
| 109 | + |
| 110 | + if writeErr != nil { |
| 111 | + return writeErr |
| 112 | + } |
| 113 | + |
| 114 | + if CloseStatus(closeHandshakeErr) == -1 { |
| 115 | + return closeHandshakeErr |
| 116 | + } |
| 117 | + |
| 118 | + return nil |
| 119 | +} |
| 120 | + |
| 121 | +var errAlreadyWroteClose = errors.New("already wrote close") |
| 122 | + |
| 123 | +func (c *Conn) writeClose(code StatusCode, reason string) error { |
| 124 | + c.closeMu.Lock() |
| 125 | + wroteClose := c.wroteClose |
| 126 | + c.wroteClose = true |
| 127 | + c.closeMu.Unlock() |
| 128 | + if wroteClose { |
| 129 | + return errAlreadyWroteClose |
| 130 | + } |
| 131 | + |
| 132 | + ce := CloseError{ |
| 133 | + Code: code, |
| 134 | + Reason: reason, |
| 135 | + } |
| 136 | + |
| 137 | + var p []byte |
| 138 | + var marshalErr error |
| 139 | + if ce.Code != StatusNoStatusRcvd { |
| 140 | + p, marshalErr = ce.bytes() |
| 141 | + if marshalErr != nil { |
| 142 | + log.Printf("websocket: %v", marshalErr) |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + writeErr := c.writeControl(context.Background(), opClose, p) |
| 147 | + if CloseStatus(writeErr) != -1 { |
| 148 | + // Not a real error if it's due to a close frame being received. |
| 149 | + writeErr = nil |
| 150 | + } |
| 151 | + |
| 152 | + // We do this after in case there was an error writing the close frame. |
| 153 | + c.setCloseErr(fmt.Errorf("sent close frame: %w", ce)) |
| 154 | + |
| 155 | + if marshalErr != nil { |
| 156 | + return marshalErr |
| 157 | + } |
| 158 | + return writeErr |
| 159 | +} |
| 160 | + |
| 161 | +func (c *Conn) waitCloseHandshake() error { |
| 162 | + defer c.close(nil) |
| 163 | + |
| 164 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) |
| 165 | + defer cancel() |
| 166 | + |
| 167 | + err := c.readMu.lock(ctx) |
| 168 | + if err != nil { |
| 169 | + return err |
| 170 | + } |
| 171 | + defer c.readMu.unlock() |
| 172 | + |
| 173 | + if c.readCloseFrameErr != nil { |
| 174 | + return c.readCloseFrameErr |
| 175 | + } |
| 176 | + |
| 177 | + for { |
| 178 | + h, err := c.readLoop(ctx) |
| 179 | + if err != nil { |
| 180 | + return err |
| 181 | + } |
| 182 | + |
| 183 | + for i := int64(0); i < h.payloadLength; i++ { |
| 184 | + _, err := c.br.ReadByte() |
| 185 | + if err != nil { |
| 186 | + return err |
| 187 | + } |
| 188 | + } |
| 189 | + } |
| 190 | +} |
| 191 | + |
| 192 | +func parseClosePayload(p []byte) (CloseError, error) { |
| 193 | + if len(p) == 0 { |
| 194 | + return CloseError{ |
| 195 | + Code: StatusNoStatusRcvd, |
| 196 | + }, nil |
| 197 | + } |
| 198 | + |
| 199 | + if len(p) < 2 { |
| 200 | + return CloseError{}, fmt.Errorf("close payload %q too small, cannot even contain the 2 byte status code", p) |
| 201 | + } |
| 202 | + |
| 203 | + ce := CloseError{ |
| 204 | + Code: StatusCode(binary.BigEndian.Uint16(p)), |
| 205 | + Reason: string(p[2:]), |
| 206 | + } |
| 207 | + |
| 208 | + if !validWireCloseCode(ce.Code) { |
| 209 | + return CloseError{}, fmt.Errorf("invalid status code %v", ce.Code) |
| 210 | + } |
| 211 | + |
| 212 | + return ce, nil |
| 213 | +} |
| 214 | + |
| 215 | +// See http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number |
| 216 | +// and https://tools.ietf.org/html/rfc6455#section-7.4.1 |
| 217 | +func validWireCloseCode(code StatusCode) bool { |
| 218 | + switch code { |
| 219 | + case statusReserved, StatusNoStatusRcvd, StatusAbnormalClosure, StatusTLSHandshake: |
| 220 | + return false |
| 221 | + } |
| 222 | + |
| 223 | + if code >= StatusNormalClosure && code <= StatusBadGateway { |
| 224 | + return true |
| 225 | + } |
| 226 | + if code >= 3000 && code <= 4999 { |
| 227 | + return true |
| 228 | + } |
| 229 | + |
| 230 | + return false |
| 231 | +} |
| 232 | + |
| 233 | +func (ce CloseError) bytes() ([]byte, error) { |
| 234 | + p, err := ce.bytesErr() |
| 235 | + if err != nil { |
| 236 | + err = fmt.Errorf("failed to marshal close frame: %w", err) |
| 237 | + ce = CloseError{ |
| 238 | + Code: StatusInternalError, |
| 239 | + } |
| 240 | + p, _ = ce.bytesErr() |
| 241 | + } |
| 242 | + return p, err |
| 243 | +} |
| 244 | + |
| 245 | +const maxCloseReason = maxControlPayload - 2 |
| 246 | + |
| 247 | +func (ce CloseError) bytesErr() ([]byte, error) { |
| 248 | + if len(ce.Reason) > maxCloseReason { |
| 249 | + return nil, fmt.Errorf("reason string max is %v but got %q with length %v", maxCloseReason, ce.Reason, len(ce.Reason)) |
| 250 | + } |
| 251 | + |
| 252 | + if !validWireCloseCode(ce.Code) { |
| 253 | + return nil, fmt.Errorf("status code %v cannot be set", ce.Code) |
| 254 | + } |
| 255 | + |
| 256 | + buf := make([]byte, 2+len(ce.Reason)) |
| 257 | + binary.BigEndian.PutUint16(buf, uint16(ce.Code)) |
| 258 | + copy(buf[2:], ce.Reason) |
| 259 | + return buf, nil |
| 260 | +} |
| 261 | + |
| 262 | +func (c *Conn) setCloseErr(err error) { |
| 263 | + c.closeMu.Lock() |
| 264 | + c.setCloseErrLocked(err) |
| 265 | + c.closeMu.Unlock() |
| 266 | +} |
| 267 | + |
| 268 | +func (c *Conn) setCloseErrLocked(err error) { |
| 269 | + if c.closeErr == nil { |
| 270 | + c.closeErr = fmt.Errorf("WebSocket closed: %w", err) |
| 271 | + } |
| 272 | +} |
| 273 | + |
| 274 | +func (c *Conn) isClosed() bool { |
| 275 | + select { |
| 276 | + case <-c.closed: |
| 277 | + return true |
| 278 | + default: |
| 279 | + return false |
| 280 | + } |
| 281 | +} |
0 commit comments