Skip to content

Commit aa4d85f

Browse files
authored
Merge pull request #240 from nhooyr/restructure
Disable compression by default and switch to stdlib compress
2 parents 02861b4 + 0a61ffe commit aa4d85f

19 files changed

+1024
-800
lines changed

README.md

+1-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ go get nhooyr.io/websocket
1616
- Minimal and idiomatic API
1717
- First class [context.Context](https://blog.golang.org/context) support
1818
- Fully passes the WebSocket [autobahn-testsuite](https://github.com/crossbario/autobahn-testsuite)
19-
- [Single dependency](https://pkg.go.dev/nhooyr.io/websocket?tab=imports)
19+
- [Zero dependencies](https://pkg.go.dev/nhooyr.io/websocket?tab=imports)
2020
- JSON and protobuf helpers in the [wsjson](https://pkg.go.dev/nhooyr.io/websocket/wsjson) and [wspb](https://pkg.go.dev/nhooyr.io/websocket/wspb) subpackages
2121
- Zero alloc reads and writes
2222
- Concurrent writes
@@ -112,7 +112,6 @@ Advantages of nhooyr.io/websocket:
112112
- Gorilla's implementation is slower and uses [unsafe](https://golang.org/pkg/unsafe/).
113113
- Full [permessage-deflate](https://tools.ietf.org/html/rfc7692) compression extension support
114114
- Gorilla only supports no context takeover mode
115-
- We use [klauspost/compress](https://github.com/klauspost/compress) for much lower memory usage ([gorilla/websocket#203](https://github.com/gorilla/websocket/issues/203))
116115
- [CloseRead](https://pkg.go.dev/nhooyr.io/websocket#Conn.CloseRead) helper ([gorilla/websocket#492](https://github.com/gorilla/websocket/issues/492))
117116
- Actively maintained ([gorilla/websocket#370](https://github.com/gorilla/websocket/issues/370))
118117

accept.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ type AcceptOptions struct {
5151
OriginPatterns []string
5252

5353
// CompressionMode controls the compression mode.
54-
// Defaults to CompressionNoContextTakeover.
54+
// Defaults to CompressionDisabled.
5555
//
5656
// See docs on CompressionMode for details.
5757
CompressionMode CompressionMode

accept_js.go

-20
This file was deleted.

accept_test.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ func TestAccept(t *testing.T) {
5555
r.Header.Set("Sec-WebSocket-Key", "meow123")
5656
r.Header.Set("Sec-WebSocket-Extensions", "permessage-deflate; harharhar")
5757

58-
_, err := Accept(w, r, nil)
58+
_, err := Accept(w, r, &AcceptOptions{
59+
CompressionMode: CompressionContextTakeover,
60+
})
5961
assert.Contains(t, err, `unsupported permessage-deflate parameter`)
6062
})
6163

autobahn_test.go

+11-3
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ var excludedAutobahnCases = []string{
2828

2929
// We skip the tests related to requestMaxWindowBits as that is unimplemented due
3030
// to limitations in compress/flate. See https://github.com/golang/go/issues/3155
31-
// Same with klauspost/compress which doesn't allow adjusting the sliding window size.
3231
"13.3.*", "13.4.*", "13.5.*", "13.6.*",
3332
}
3433

@@ -37,10 +36,17 @@ var autobahnCases = []string{"*"}
3736
func TestAutobahn(t *testing.T) {
3837
t.Parallel()
3938

40-
if os.Getenv("AUTOBAHN_TEST") == "" {
39+
if os.Getenv("AUTOBAHN") == "" {
4140
t.SkipNow()
4241
}
4342

43+
if os.Getenv("AUTOBAHN") == "fast" {
44+
// These are the slow tests.
45+
excludedAutobahnCases = append(excludedAutobahnCases,
46+
"9.*", "13.*", "12.*",
47+
)
48+
}
49+
4450
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*15)
4551
defer cancel()
4652

@@ -61,7 +67,9 @@ func TestAutobahn(t *testing.T) {
6167
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
6268
defer cancel()
6369

64-
c, _, err := websocket.Dial(ctx, fmt.Sprintf(wstestURL+"/runCase?case=%v&agent=main", i), nil)
70+
c, _, err := websocket.Dial(ctx, fmt.Sprintf(wstestURL+"/runCase?case=%v&agent=main", i), &websocket.DialOptions{
71+
CompressionMode: websocket.CompressionContextTakeover,
72+
})
6573
assert.Success(t, err)
6674
err = wstest.EchoLoop(ctx, c)
6775
t.Logf("echoLoop: %v", err)

close.go

+205
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
1+
// +build !js
2+
13
package websocket
24

35
import (
6+
"context"
7+
"encoding/binary"
48
"errors"
59
"fmt"
10+
"log"
11+
"time"
12+
13+
"nhooyr.io/websocket/internal/errd"
614
)
715

816
// StatusCode represents a WebSocket status code.
@@ -74,3 +82,200 @@ func CloseStatus(err error) StatusCode {
7482
}
7583
return -1
7684
}
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

Comments
 (0)