From 91c749491ed77b8030adf277058bc1bc00040202 Mon Sep 17 00:00:00 2001 From: Steven Masley Date: Wed, 2 Dec 2026 22:00:29 +0000 Subject: [PATCH 1/5] perf: parse WebSocket handshake headers lazily Use iterators for header tokens and extension parameters instead of collecting split values into slices. Preserve handshake negotiation behavior. --- accept.go | 67 +++++++++++++++++++++++++------------------------- accept_test.go | 44 +++++++++++++++++++++++++++++++++ dial.go | 23 +++++++++++------ dial_test.go | 10 ++++++++ 4 files changed, 103 insertions(+), 41 deletions(-) diff --git a/accept.go b/accept.go index 25c1be7d..cc77acca 100644 --- a/accept.go +++ b/accept.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "io" + "iter" "log" "net/http" "net/textproto" @@ -264,9 +265,8 @@ func match(pattern, s string) (bool, error) { } func selectSubprotocol(r *http.Request, subprotocols []string) string { - cps := headerTokens(r.Header, "Sec-WebSocket-Protocol") for _, sp := range subprotocols { - for _, cp := range cps { + for cp := range headerTokens(r.Header, "Sec-WebSocket-Protocol") { if strings.EqualFold(sp, cp) { return cp } @@ -275,11 +275,11 @@ func selectSubprotocol(r *http.Request, subprotocols []string) string { return "" } -func selectDeflate(extensions []websocketExtension, mode CompressionMode) (*compressionOptions, bool) { +func selectDeflate(extensions iter.Seq[websocketExtension], mode CompressionMode) (*compressionOptions, bool) { if mode == CompressionDisabled { return nil, false } - for _, ext := range extensions { + for ext := range extensions { switch ext.name { // We used to implement x-webkit-deflate-frame too for Safari but Safari has bugs... // See https://github.com/coder/websocket/issues/218 @@ -295,7 +295,7 @@ func selectDeflate(extensions []websocketExtension, mode CompressionMode) (*comp func acceptDeflate(ext websocketExtension, mode CompressionMode) (*compressionOptions, bool) { copts := mode.opts() - for _, p := range ext.params { + for p := range ext.params { switch p { case "client_no_context_takeover": copts.clientNoContextTakeover = true @@ -318,7 +318,7 @@ func acceptDeflate(ext websocketExtension, mode CompressionMode) (*compressionOp } func headerContainsTokenIgnoreCase(h http.Header, key, token string) bool { - for _, t := range headerTokens(h, key) { + for t := range headerTokens(h, key) { if strings.EqualFold(t, token) { return true } @@ -328,43 +328,42 @@ func headerContainsTokenIgnoreCase(h http.Header, key, token string) bool { type websocketExtension struct { name string - params []string + params iter.Seq[string] } -func websocketExtensions(h http.Header) []websocketExtension { - var exts []websocketExtension - extStrs := headerTokens(h, "Sec-WebSocket-Extensions") - for _, extStr := range extStrs { - if extStr == "" { - continue - } - - vals := strings.Split(extStr, ";") - for i := range vals { - vals[i] = strings.TrimSpace(vals[i]) - } - - e := websocketExtension{ - name: vals[0], - params: vals[1:], +func websocketExtensions(h http.Header) iter.Seq[websocketExtension] { + return func(yield func(websocketExtension) bool) { + for token := range headerTokens(h, "Sec-WebSocket-Extensions") { + name, rawParams, hasParams := strings.Cut(token, ";") + params := func(yieldParam func(string) bool) { + if !hasParams { + return + } + for param := range strings.SplitSeq(rawParams, ";") { + if !yieldParam(strings.TrimSpace(param)) { + return + } + } + } + if !yield(websocketExtension{name: strings.TrimSpace(name), params: params}) { + return + } } - - exts = append(exts, e) } - return exts } -func headerTokens(h http.Header, key string) []string { +func headerTokens(h http.Header, key string) iter.Seq[string] { key = textproto.CanonicalMIMEHeaderKey(key) - var tokens []string - for _, v := range h[key] { - v = strings.TrimSpace(v) - for _, t := range strings.Split(v, ",") { - t = strings.TrimSpace(t) - tokens = append(tokens, t) + return func(yield func(string) bool) { + for _, v := range h[key] { + for token := range strings.SplitSeq(v, ",") { + token = strings.TrimSpace(token) + if token != "" && !yield(token) { + return + } + } } } - return tokens } var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") diff --git a/accept_test.go b/accept_test.go index 92dbfcc7..caa1b4b9 100644 --- a/accept_test.go +++ b/accept_test.go @@ -560,6 +560,12 @@ func Test_selectDeflate(t *testing.T) { header: "permessage-deflate; meow", expOK: false, }, + { + name: "permessage-deflate/empty-parameter", + mode: CompressionNoContextTakeover, + header: "permessage-deflate;;", + expOK: false, + }, { name: "permessage-deflate/unknown-parameter", mode: CompressionNoContextTakeover, @@ -586,6 +592,44 @@ func Test_selectDeflate(t *testing.T) { } } +func BenchmarkAcceptDelimiterHeaders(b *testing.B) { + cases := []struct { + name string + header string + value string + }{ + {"connection-commas", "Connection", strings.Repeat(",", http.DefaultMaxHeaderBytes) + "Upgrade"}, + {"extension-commas", "Sec-WebSocket-Extensions", strings.Repeat(",", http.DefaultMaxHeaderBytes)}, + {"extension-semicolons", "Sec-WebSocket-Extensions", strings.Repeat(";", http.DefaultMaxHeaderBytes)}, + } + + for _, tc := range cases { + b.Run(tc.name, func(b *testing.B) { + r := httptest.NewRequest("GET", "/", nil) + r.Header.Set("Connection", "Upgrade") + r.Header.Set("Upgrade", "websocket") + r.Header.Set("Sec-WebSocket-Version", "13") + r.Header.Set("Sec-WebSocket-Key", xrand.Base64(16)) + r.Header.Set(tc.header, tc.value) + + errHijack := errors.New("hijack error") + b.ReportAllocs() + for b.Loop() { + w := mockHijacker{ + ResponseWriter: httptest.NewRecorder(), + hijack: func() (net.Conn, *bufio.ReadWriter, error) { + return nil, nil, errHijack + }, + } + _, err := Accept(w, r, &AcceptOptions{CompressionMode: CompressionNoContextTakeover}) + if !errors.Is(err, errHijack) { + b.Fatalf("expected hijack error, got %v", err) + } + } + }) + } +} + type mockHijacker struct { http.ResponseWriter hijack func() (net.Conn, *bufio.ReadWriter, error) diff --git a/dial.go b/dial.go index 92820ed6..45e50686 100644 --- a/dial.go +++ b/dial.go @@ -8,6 +8,7 @@ import ( "context" "crypto/rand" "encoding/base64" + "errors" "fmt" "io" "net/http" @@ -315,20 +316,28 @@ func verifySubprotocol(subprotos []string, resp *http.Response) error { } func verifyServerExtensions(copts *compressionOptions, h http.Header) (*compressionOptions, error) { - exts := websocketExtensions(h) - if len(exts) == 0 { + var ext websocketExtension + count := 0 + for e := range websocketExtensions(h) { + if count == 0 { + ext = e + } + count++ + if count == 2 { + break + } + } + if count == 0 { return nil, nil } - - ext := exts[0] - if ext.name != "permessage-deflate" || len(exts) > 1 || copts == nil { - return nil, fmt.Errorf("WebSocket protcol violation: unsupported extensions from server: %+v", exts[1:]) + if ext.name != "permessage-deflate" || count > 1 || copts == nil { + return nil, errors.New("WebSocket protcol violation: unsupported extensions from server") } _copts := *copts copts = &_copts - for _, p := range ext.params { + for p := range ext.params { switch p { case "client_no_context_takeover": copts.clientNoContextTakeover = true diff --git a/dial_test.go b/dial_test.go index 11b88ab8..f37c01b8 100644 --- a/dial_test.go +++ b/dial_test.go @@ -346,6 +346,16 @@ func Test_verifyServerHandshake(t *testing.T) { }, success: false, }, + { + name: "emptyExtensionName", + response: func(w http.ResponseWriter) { + w.Header().Set("Connection", "Upgrade") + w.Header().Set("Upgrade", "websocket") + w.Header().Set("Sec-WebSocket-Extensions", ";;;") + w.WriteHeader(http.StatusSwitchingProtocols) + }, + success: false, + }, { name: "unsupportedDeflateParam", response: func(w http.ResponseWriter) { From f49d720e7a5acad2b9a557dc5f8852a9a3db3693 Mon Sep 17 00:00:00 2001 From: Steven Masley Date: Thu, 3 Dec 2026 16:31:38 +0000 Subject: [PATCH 2/5] perf: bound allocations for repeated WebSocket extensions Assert that allocations and bytes stay flat as non-empty handshake tokens grow. Store extension parameters without per-offer closures and allocate compression options only for accepted offers. --- accept.go | 49 +++++++++++-------- accept_test.go | 124 +++++++++++++++++++++++++++++++++++++++++++++++++ dial.go | 2 +- 3 files changed, 154 insertions(+), 21 deletions(-) diff --git a/accept.go b/accept.go index cc77acca..2259daa4 100644 --- a/accept.go +++ b/accept.go @@ -284,18 +284,18 @@ func selectDeflate(extensions iter.Seq[websocketExtension], mode CompressionMode // We used to implement x-webkit-deflate-frame too for Safari but Safari has bugs... // See https://github.com/coder/websocket/issues/218 case "permessage-deflate": - copts, ok := acceptDeflate(ext, mode) - if ok { - return copts, true + if candidate, ok := acceptDeflate(ext, mode); ok { + copts := candidate + return &copts, true } } } return nil, false } -func acceptDeflate(ext websocketExtension, mode CompressionMode) (*compressionOptions, bool) { - copts := mode.opts() - for p := range ext.params { +func acceptDeflate(ext websocketExtension, mode CompressionMode) (compressionOptions, bool) { + copts := *mode.opts() + for p := range ext.params() { switch p { case "client_no_context_takeover": copts.clientNoContextTakeover = true @@ -312,7 +312,7 @@ func acceptDeflate(ext websocketExtension, mode CompressionMode) (*compressionOp // We can't adjust the deflate window, but decoding with a larger window is acceptable. continue } - return nil, false + return compressionOptions{}, false } return copts, true } @@ -327,25 +327,34 @@ func headerContainsTokenIgnoreCase(h http.Header, key, token string) bool { } type websocketExtension struct { - name string - params iter.Seq[string] + name string + rawParams string + // A trailing semicolon yields an empty parameter; no semicolon yields none. + hasParams bool +} + +func (ext websocketExtension) params() iter.Seq[string] { + return func(yield func(string) bool) { + if !ext.hasParams { + return + } + for p := range strings.SplitSeq(ext.rawParams, ";") { + if !yield(strings.TrimSpace(p)) { + return + } + } + } } func websocketExtensions(h http.Header) iter.Seq[websocketExtension] { return func(yield func(websocketExtension) bool) { for token := range headerTokens(h, "Sec-WebSocket-Extensions") { name, rawParams, hasParams := strings.Cut(token, ";") - params := func(yieldParam func(string) bool) { - if !hasParams { - return - } - for param := range strings.SplitSeq(rawParams, ";") { - if !yieldParam(strings.TrimSpace(param)) { - return - } - } - } - if !yield(websocketExtension{name: strings.TrimSpace(name), params: params}) { + if !yield(websocketExtension{ + name: strings.TrimSpace(name), + rawParams: rawParams, + hasParams: hasParams, + }) { return } } diff --git a/accept_test.go b/accept_test.go index caa1b4b9..05adf312 100644 --- a/accept_test.go +++ b/accept_test.go @@ -8,6 +8,7 @@ import ( "net" "net/http" "net/http/httptest" + "runtime" "strings" "sync" "testing" @@ -592,6 +593,129 @@ func Test_selectDeflate(t *testing.T) { } } +func TestHeaderParsingAllocations(t *testing.T) { + // Allocation counters are process-wide, so this test must not run in parallel. + oldProcs := runtime.GOMAXPROCS(1) + defer runtime.GOMAXPROCS(oldProcs) + const ( + key = "dGhlIHNhbXBsZSBub25jZQ==" + runs = 100 + rounds = 3 + ) + newRequest := func() *http.Request { + r := httptest.NewRequest("GET", "/", nil) + r.Header.Set("Connection", "Upgrade") + r.Header.Set("Upgrade", "websocket") + r.Header.Set("Sec-WebSocket-Version", "13") + r.Header.Set("Sec-WebSocket-Key", key) + return r + } + + cases := []struct { + name string + prepare func(int) func() bool + }{ + {"connection", func(n int) func() bool { + r := newRequest() + r.Header.Set("Connection", strings.Repeat("keep-alive,", n)+"Upgrade") + w := httptest.NewRecorder() + return func() bool { _, err := verifyClientRequest(w, r); return err == nil } + }}, + {"upgrade", func(n int) func() bool { + r := newRequest() + r.Header.Set("Upgrade", strings.Repeat("other,", n)+"websocket") + w := httptest.NewRecorder() + return func() bool { _, err := verifyClientRequest(w, r); return err == nil } + }}, + {"subprotocol-preferences", func(n int) func() bool { + r := newRequest() + r.Header.Set("Sec-WebSocket-Protocol", strings.Repeat("other,", n)+"Echo,FOO") + return func() bool { return selectSubprotocol(r, []string{"missing", "foo", "echo"}) == "FOO" } + }}, + {"extension-names", func(n int) func() bool { + h := http.Header{} + h.Set("Sec-WebSocket-Extensions", strings.Repeat("x,", n)+"permessage-deflate") + return func() bool { + copts, ok := selectDeflate(websocketExtensions(h), CompressionNoContextTakeover) + return ok && copts != nil + } + }}, + {"rejected-deflate-offers", func(n int) func() bool { + h := http.Header{} + h.Set("Sec-WebSocket-Extensions", strings.Repeat("permessage-deflate;unknown,", n)+"permessage-deflate") + return func() bool { + copts, ok := selectDeflate(websocketExtensions(h), CompressionNoContextTakeover) + return ok && copts != nil + } + }}, + {"rejected-deflate-parameters", func(n int) func() bool { + h := http.Header{} + h.Set("Sec-WebSocket-Extensions", "permessage-deflate;"+strings.Repeat("client_no_context_takeover;", n)+"unknown") + return func() bool { + copts, ok := selectDeflate(websocketExtensions(h), CompressionNoContextTakeover) + return !ok && copts == nil + } + }}, + {"compression-disabled", func(n int) func() bool { + h := http.Header{} + h.Set("Sec-WebSocket-Extensions", strings.Repeat("x,", n)+"permessage-deflate") + return func() bool { + copts, ok := selectDeflate(websocketExtensions(h), CompressionDisabled) + return !ok && copts == nil + } + }}, + {"client-response", func(n int) func() bool { + h := http.Header{} + h.Set("Connection", strings.Repeat("keep-alive,", n)+"Upgrade") + h.Set("Upgrade", strings.Repeat("other,", n)+"websocket") + h.Set("Sec-WebSocket-Accept", secWebSocketAccept(key)) + h.Set("Sec-WebSocket-Extensions", "permessage-deflate; server_no_context_takeover") + resp := &http.Response{StatusCode: http.StatusSwitchingProtocols, Header: h} + opts := &DialOptions{} + copts := CompressionNoContextTakeover.opts() + return func() bool { + result, err := verifyServerResponse(opts, copts, key, resp) + return err == nil && result != nil + } + }}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + measure := func(n int) (allocs, bytes uint64) { + run := tc.prepare(n) + if !run() { + t.Fatal("unexpected handshake result") + } + for round := 0; round < rounds; round++ { + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + for i := 0; i < runs; i++ { + if !run() { + t.Fatal("unexpected handshake result") + } + } + runtime.ReadMemStats(&after) + if delta := after.Mallocs - before.Mallocs; round == 0 || delta < allocs { + allocs = delta + } + if delta := after.TotalAlloc - before.TotalAlloc; round == 0 || delta < bytes { + bytes = delta + } + } + return allocs, bytes + } + smallAllocs, smallBytes := measure(2) + largeAllocs, largeBytes := measure(1024) + // Allow less than one extra byte per added token. + if largeAllocs > smallAllocs+3*runs || largeBytes > smallBytes+512*runs { + t.Errorf("allocations grow with token count: 2 tokens = %d allocs, %d bytes; 1024 tokens = %d allocs, %d bytes (per %d runs)", + smallAllocs, smallBytes, largeAllocs, largeBytes, runs) + } + }) + } +} + func BenchmarkAcceptDelimiterHeaders(b *testing.B) { cases := []struct { name string diff --git a/dial.go b/dial.go index 45e50686..f512d9de 100644 --- a/dial.go +++ b/dial.go @@ -337,7 +337,7 @@ func verifyServerExtensions(copts *compressionOptions, h http.Header) (*compress _copts := *copts copts = &_copts - for p := range ext.params { + for p := range ext.params() { switch p { case "client_no_context_takeover": copts.clientNoContextTakeover = true From 49c938532a55382c9c8f6392e8f62b862f1af432 Mon Sep 17 00:00:00 2001 From: Steven Masley Date: Thu, 3 Dec 2026 19:01:45 +0000 Subject: [PATCH 3/5] perf(accept): scan subprotocol offers once Retain only higher-ranked server preferences after a match. Check exact heap allocation counts with a fixed byte ceiling across the handshake parsing cases. --- accept.go | 18 ++++++++++--- accept_test.go | 73 +++++++++++++++++++++++++------------------------- 2 files changed, 51 insertions(+), 40 deletions(-) diff --git a/accept.go b/accept.go index 2259daa4..22ec4bd9 100644 --- a/accept.go +++ b/accept.go @@ -265,14 +265,24 @@ func match(pattern, s string) (bool, error) { } func selectSubprotocol(r *http.Request, subprotocols []string) string { - for _, sp := range subprotocols { - for cp := range headerTokens(r.Header, "Sec-WebSocket-Protocol") { + if len(subprotocols) == 0 { + return "" + } + var selected string + for cp := range headerTokens(r.Header, "Sec-WebSocket-Protocol") { + for i, sp := range subprotocols { if strings.EqualFold(sp, cp) { - return cp + if i == 0 { + return cp + } + selected = cp + // Only a higher server preference can displace this match. + subprotocols = subprotocols[:i] + break } } } - return "" + return selected } func selectDeflate(extensions iter.Seq[websocketExtension], mode CompressionMode) (*compressionOptions, bool) { diff --git a/accept_test.go b/accept_test.go index 05adf312..67be4981 100644 --- a/accept_test.go +++ b/accept_test.go @@ -612,27 +612,28 @@ func TestHeaderParsingAllocations(t *testing.T) { } cases := []struct { - name string - prepare func(int) func() bool + name string + wantAllocs uint64 + prepare func(int) func() bool }{ - {"connection", func(n int) func() bool { + {"connection", 3, func(n int) func() bool { r := newRequest() r.Header.Set("Connection", strings.Repeat("keep-alive,", n)+"Upgrade") w := httptest.NewRecorder() return func() bool { _, err := verifyClientRequest(w, r); return err == nil } }}, - {"upgrade", func(n int) func() bool { + {"upgrade", 3, func(n int) func() bool { r := newRequest() r.Header.Set("Upgrade", strings.Repeat("other,", n)+"websocket") w := httptest.NewRecorder() return func() bool { _, err := verifyClientRequest(w, r); return err == nil } }}, - {"subprotocol-preferences", func(n int) func() bool { + {"subprotocol-preferences", 1, func(n int) func() bool { r := newRequest() r.Header.Set("Sec-WebSocket-Protocol", strings.Repeat("other,", n)+"Echo,FOO") return func() bool { return selectSubprotocol(r, []string{"missing", "foo", "echo"}) == "FOO" } }}, - {"extension-names", func(n int) func() bool { + {"extension-names", 2, func(n int) func() bool { h := http.Header{} h.Set("Sec-WebSocket-Extensions", strings.Repeat("x,", n)+"permessage-deflate") return func() bool { @@ -640,7 +641,7 @@ func TestHeaderParsingAllocations(t *testing.T) { return ok && copts != nil } }}, - {"rejected-deflate-offers", func(n int) func() bool { + {"rejected-deflate-offers", 2, func(n int) func() bool { h := http.Header{} h.Set("Sec-WebSocket-Extensions", strings.Repeat("permessage-deflate;unknown,", n)+"permessage-deflate") return func() bool { @@ -648,7 +649,7 @@ func TestHeaderParsingAllocations(t *testing.T) { return ok && copts != nil } }}, - {"rejected-deflate-parameters", func(n int) func() bool { + {"rejected-deflate-parameters", 1, func(n int) func() bool { h := http.Header{} h.Set("Sec-WebSocket-Extensions", "permessage-deflate;"+strings.Repeat("client_no_context_takeover;", n)+"unknown") return func() bool { @@ -656,7 +657,7 @@ func TestHeaderParsingAllocations(t *testing.T) { return !ok && copts == nil } }}, - {"compression-disabled", func(n int) func() bool { + {"compression-disabled", 0, func(n int) func() bool { h := http.Header{} h.Set("Sec-WebSocket-Extensions", strings.Repeat("x,", n)+"permessage-deflate") return func() bool { @@ -664,7 +665,7 @@ func TestHeaderParsingAllocations(t *testing.T) { return !ok && copts == nil } }}, - {"client-response", func(n int) func() bool { + {"client-response", 6, func(n int) func() bool { h := http.Header{} h.Set("Connection", strings.Repeat("keep-alive,", n)+"Upgrade") h.Set("Upgrade", strings.Repeat("other,", n)+"websocket") @@ -682,35 +683,35 @@ func TestHeaderParsingAllocations(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - measure := func(n int) (allocs, bytes uint64) { - run := tc.prepare(n) - if !run() { - t.Fatal("unexpected handshake result") - } - for round := 0; round < rounds; round++ { - var before, after runtime.MemStats - runtime.ReadMemStats(&before) - for i := 0; i < runs; i++ { - if !run() { - t.Fatal("unexpected handshake result") - } - } - runtime.ReadMemStats(&after) - if delta := after.Mallocs - before.Mallocs; round == 0 || delta < allocs { - allocs = delta - } - if delta := after.TotalAlloc - before.TotalAlloc; round == 0 || delta < bytes { - bytes = delta + run := tc.prepare(1024) + if !run() { + t.Fatal("unexpected handshake result") + } + var allocs, bytes uint64 + for round := 0; round < rounds; round++ { + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + for i := 0; i < runs; i++ { + if !run() { + t.Fatal("unexpected handshake result") } } - return allocs, bytes + runtime.ReadMemStats(&after) + if delta := after.Mallocs - before.Mallocs; round == 0 || delta < allocs { + allocs = delta + } + if delta := after.TotalAlloc - before.TotalAlloc; round == 0 || delta < bytes { + bytes = delta + } + } + if allocs != tc.wantAllocs*runs { + t.Errorf("got %d allocations over %d runs, want %d per run", allocs, runs, tc.wantAllocs) } - smallAllocs, smallBytes := measure(2) - largeAllocs, largeBytes := measure(1024) - // Allow less than one extra byte per added token. - if largeAllocs > smallAllocs+3*runs || largeBytes > smallBytes+512*runs { - t.Errorf("allocations grow with token count: 2 tokens = %d allocs, %d bytes; 1024 tokens = %d allocs, %d bytes (per %d runs)", - smallAllocs, smallBytes, largeAllocs, largeBytes, runs) + // A token-sized slice can increase bytes without increasing the count. + // Allow for allocator rounding and the race build's larger allocations. + const maxBytesPerRun = 256 + if bytes > maxBytesPerRun*runs { + t.Errorf("got %d allocated bytes over %d runs, want at most %d per run", bytes, runs, maxBytesPerRun) } }) } From 64b2fd91576e553a6954891bc340c8247bc600cc Mon Sep 17 00:00:00 2001 From: Steven Masley Date: Thu, 3 Dec 2026 19:08:45 +0000 Subject: [PATCH 4/5] refactor(dial): reject unsupported extensions during iteration --- dial.go | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/dial.go b/dial.go index f512d9de..9299bbd7 100644 --- a/dial.go +++ b/dial.go @@ -317,22 +317,17 @@ func verifySubprotocol(subprotos []string, resp *http.Response) error { func verifyServerExtensions(copts *compressionOptions, h http.Header) (*compressionOptions, error) { var ext websocketExtension - count := 0 + found := false for e := range websocketExtensions(h) { - if count == 0 { - ext = e - } - count++ - if count == 2 { - break + if found || copts == nil || e.name != "permessage-deflate" { + return nil, errors.New("WebSocket protcol violation: unsupported extensions from server") } + ext = e + found = true } - if count == 0 { + if !found { return nil, nil } - if ext.name != "permessage-deflate" || count > 1 || copts == nil { - return nil, errors.New("WebSocket protcol violation: unsupported extensions from server") - } _copts := *copts copts = &_copts From b076a33fb467dc5ba8b64c97e5d21375970025a6 Mon Sep 17 00:00:00 2001 From: Steven Masley Date: Fri, 4 Dec 2026 16:03:27 +0000 Subject: [PATCH 5/5] docs(accept): explain why empty extension parameters are tracked --- accept.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/accept.go b/accept.go index 22ec4bd9..dc690930 100644 --- a/accept.go +++ b/accept.go @@ -339,7 +339,8 @@ func headerContainsTokenIgnoreCase(h http.Header, key, token string) bool { type websocketExtension struct { name string rawParams string - // A trailing semicolon yields an empty parameter; no semicolon yields none. + // Both "name" and "name;" leave rawParams empty. Keep the distinction + // so validation rejects the empty parameter in "name;". hasParams bool }