Skip to content

Commit

Permalink
Fix how the client checks for presence of Upgrade: websocket, Connect…
Browse files Browse the repository at this point in the history
…ion: upgrade (#604)

The values of the `Upgrade` and `Connection` response headers can
contain multiple tokens, for example

    Connection: upgrade, keep-alive

The WebSocket RFC describes the checking of these as follows:

   2.  If the response lacks an |Upgrade| header field or the |Upgrade|
       header field contains a value that is not an ASCII case-
       insensitive match for the value "websocket", the client MUST
       _Fail the WebSocket Connection_.

   3.  If the response lacks a |Connection| header field or the
       |Connection| header field doesn't contain a token that is an
       ASCII case-insensitive match for the value "Upgrade", the client
       MUST _Fail the WebSocket Connection_.

It is careful to note "contains a value", "contains a token".

Previously, the client would reject with "bad handshake" if the header
doesn't contain exactly the value it looks for.

Change the checks to use `tokenListContainsValue` instead, which is
incidentally what the server is already doing for similar checks.
  • Loading branch information
bluetech committed Aug 20, 2020
1 parent b65e629 commit 873e67e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
4 changes: 2 additions & 2 deletions client.go
Expand Up @@ -348,8 +348,8 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h
}

if resp.StatusCode != 101 ||
!strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
!strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
!tokenListContainsValue(resp.Header, "Upgrade", "websocket") ||
!tokenListContainsValue(resp.Header, "Connection", "upgrade") ||
resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
// Before closing the network connection on return from this
// function, slurp up some of the response to aid application
Expand Down
17 changes: 17 additions & 0 deletions client_server_test.go
Expand Up @@ -481,6 +481,23 @@ func TestBadMethod(t *testing.T) {
}
}

func TestDialExtraTokensInRespHeaders(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
challengeKey := r.Header.Get("Sec-Websocket-Key")
w.Header().Set("Upgrade", "foo, websocket")
w.Header().Set("Connection", "upgrade, keep-alive")
w.Header().Set("Sec-Websocket-Accept", computeAcceptKey(challengeKey))
w.WriteHeader(101)
}))
defer s.Close()

ws, _, err := cstDialer.Dial(makeWsProto(s.URL), nil)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer ws.Close()
}

func TestHandshake(t *testing.T) {
s := newServer(t)
defer s.Close()
Expand Down

0 comments on commit 873e67e

Please sign in to comment.