Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 33 additions & 34 deletions accept.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"errors"
"fmt"
"io"
"iter"
"log"
"net/http"
"net/textproto"
Expand Down Expand Up @@ -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
}
Expand All @@ -275,11 +275,11 @@ func selectSubprotocol(r *http.Request, subprotocols []string) string {
return ""
}
Comment on lines 267 to 276

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calling headerTokens inside the subprotocols loop re-canonicalizes the header key and re-scans Sec-WebSocket-Protocol once per configured subprotocol, which can be slower than master when several subprotocols are configured and miss.

A single pass over headerTokens tracking the best-ranked match preserves server preference order and client casing while scanning the header once:

Suggested change
func selectSubprotocol(r *http.Request, subprotocols []string) string {
if len(subprotocols) == 0 {
return ""
}
selected, rank := "", len(subprotocols)
for cp := range headerTokens(r.Header, "Sec-WebSocket-Protocol") {
for i, sp := range subprotocols[:rank] {
if strings.EqualFold(sp, cp) {
selected, rank = cp, i
if rank == 0 {
return selected
}
break
}
}
}
return selected
}

🤖 Created with the help of Coder Agents.


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
Expand All @@ -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
Expand All @@ -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
}
Expand All @@ -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
}
Comment on lines 329 to 353

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Storing params as an iter.Seq[string] closure field causes the closure and range state to escape to the heap when acceptDeflate or verifyServerExtensions iterates over it, and mode.opts() allocates *compressionOptions before parameters are validated. This adds allocations even on a normal permessage-deflate; client_max_window_bits handshake compared to master, and allocates on every rejected permessage-deflate offer.

Storing rawParams string and hasParams bool on websocketExtension (iterating via strings.SplitSeq directly or an inlinable params() method) and having acceptDeflate return compressionOptions by value, allocating the pointer only in the ok branch, avoids those per-offer escapes and drops allocations below master for the common handshake too.

A brief comment on hasParams explaining why it is needed (so permessage-deflate; yields an empty parameter and fails validation, while bare permessage-deflate yields none) would also help preserve that edge case.

🤖 Created with the help of Coder Agents.


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")
Expand Down
44 changes: 44 additions & 0 deletions accept_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
}
}
})
}
}
Comment on lines +595 to +631

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both new unit tests already pass on master, and this benchmark only covers delimiter-only inputs on Accept. A slice-collecting implementation that skips empty tokens and empty parameters would still pass all current tests and match these benchmark numbers.

Could we expand coverage to include:

  • Non-empty repeated tokens across Connection, Upgrade, Sec-WebSocket-Protocol (with multiple server preferences), and Sec-WebSocket-Extensions
  • Repeated rejected permessage-deflate offers (would catch the acceptDeflate escape above) and permessage-deflate with many valid parameters
  • CompressionDisabled with extension headers
  • Client-side verifyServerResponse headers
  • A regression test checking that allocations and allocated bytes stay flat between small and larger token counts (e.g., via testing.Benchmark), so regressions fail go test rather than relying on manual benchmark inspection

🤖 Created with the help of Coder Agents.


type mockHijacker struct {
http.ResponseWriter
hijack func() (net.Conn, *bufio.ReadWriter, error)
Expand Down
23 changes: 16 additions & 7 deletions dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -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")
}
Comment on lines +319 to 335

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: a found flag is a bit clearer than counting to 2 and lets the loop return immediately when copts == nil or the first extension is not permessage-deflate, while keeping parameter validation after the loop preserves error precedence:

Suggested change
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")
}
var ext websocketExtension
found := false
for e := range websocketExtensions(h) {
if found || copts == nil || e.name != "permessage-deflate" {
return nil, errors.New("WebSocket protcol violation: unsupported extensions from server")
}
ext = e
found = true
}
if !found {
return nil, nil
}

🤖 Created with the help of Coder Agents.


_copts := *copts
copts = &_copts

for _, p := range ext.params {
for p := range ext.params {
switch p {
case "client_no_context_takeover":
copts.clientNoContextTakeover = true
Expand Down
10 changes: 10 additions & 0 deletions dial_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading