Add subprotocol negotiation to Dialer.

This commit is contained in:
Gary Burd 2013-12-14 07:48:43 -08:00
parent 87accaef66
commit b118f62ec0
4 changed files with 61 additions and 30 deletions

View File

@ -67,6 +67,7 @@ func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufS
resp.Header.Get("Sec-Websocket-Accept") != acceptKey { resp.Header.Get("Sec-Websocket-Accept") != acceptKey {
return nil, resp, ErrBadHandshake return nil, resp, ErrBadHandshake
} }
c.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
return c, resp, nil return c, resp, nil
} }
@ -85,6 +86,9 @@ type Dialer struct {
// Input and output buffer sizes. If the buffer size is zero, then a // Input and output buffer sizes. If the buffer size is zero, then a
// default value of 4096 is used. // default value of 4096 is used.
ReadBufferSize, WriteBufferSize int ReadBufferSize, WriteBufferSize int
// Subprotocols specifies the client's requested subprotocols.
Subprotocols []string
} }
var errMalformedURL = errors.New("malformed ws or wss URL") var errMalformedURL = errors.New("malformed ws or wss URL")
@ -206,6 +210,15 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
writeBufferSize = 4096 writeBufferSize = 4096
} }
if len(d.Subprotocols) > 0 {
h := http.Header{}
for k, v := range requestHeader {
h[k] = v
}
h.Set("Sec-Websocket-Protocol", strings.Join(d.Subprotocols, ", "))
requestHeader = h
}
conn, resp, err := NewClient( conn, resp, err := NewClient(
netConn, netConn,
&url.URL{Host: host + port, Opaque: opaque}, &url.URL{Host: host + port, Opaque: opaque},

View File

@ -8,11 +8,11 @@ import (
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
"reflect"
"testing" "testing"
"time" "time"
) )
@ -24,15 +24,24 @@ type handshakeHandler struct {
func (t handshakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (t handshakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" { if r.Method != "GET" {
http.Error(w, "Method not allowed", 405) http.Error(w, "Method not allowed", 405)
t.Logf("bad method: %s", r.Method) t.Logf("method = %s, want GET", r.Method)
return return
} }
if r.Header.Get("Origin") != "http://"+r.Host { if origin := r.Header.Get("Origin"); origin != "http://"+r.Host {
http.Error(w, "Origin not allowed", 403) http.Error(w, "Origin not allowed", 403)
t.Logf("bad origin: %s", r.Header.Get("Origin")) t.Logf("Origin = %s, want %s", origin, r.Host)
return return
} }
ws, err := Upgrade(w, r, http.Header{"Set-Cookie": {"sessionID=1234"}}, 1024, 1024) subprotos := Subprotocols(r)
if !reflect.DeepEqual(subprotos, handshakeDialer.Subprotocols) {
http.Error(w, "bad protocol", 400)
t.Logf("Subprotocols = %v, want %v", subprotos, handshakeDialer.Subprotocols)
return
}
ws, err := Upgrade(w, r, http.Header{
"Set-Cookie": {"sessionID=1234"},
"Sec-Websocket-Protocol": {subprotos[0]},
}, 1024, 1024)
if _, ok := err.(HandshakeError); ok { if _, ok := err.(HandshakeError); ok {
t.Logf("bad handshake: %v", err) t.Logf("bad handshake: %v", err)
http.Error(w, "Not a websocket handshake", 400) http.Error(w, "Not a websocket handshake", 400)
@ -42,6 +51,12 @@ func (t handshakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return return
} }
defer ws.Close() defer ws.Close()
if ws.Subprotocol() != subprotos[0] {
t.Logf("ws.Subprotocol() = %s, want %s", ws.Subprotocol(), subprotos[0])
return
}
for { for {
op, r, err := ws.NextReader() op, r, err := ws.NextReader()
if err != nil { if err != nil {
@ -66,18 +81,19 @@ func (t handshakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
} }
var handshakeDialer = &Dialer{
Subprotocols: []string{"p1", "p2"},
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func TestHandshake(t *testing.T) { func TestHandshake(t *testing.T) {
s := httptest.NewServer(handshakeHandler{t}) s := httptest.NewServer(handshakeHandler{t})
defer s.Close() defer s.Close()
u, _ := url.Parse(s.URL) ws, resp, err := handshakeDialer.Dial(httpToWs(s.URL), http.Header{"Origin": {s.URL}})
c, err := net.Dial("tcp", u.Host)
if err != nil { if err != nil {
t.Fatalf("Dial: %v", err) t.Fatalf("Dial: %v", err)
} }
ws, resp, err := NewClient(c, u, http.Header{"Origin": {s.URL}}, 1024, 1024)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
defer ws.Close() defer ws.Close()
var sessionID string var sessionID string
@ -90,24 +106,11 @@ func TestHandshake(t *testing.T) {
t.Error("Set-Cookie not received from the server.") t.Error("Set-Cookie not received from the server.")
} }
w, _ := ws.NextWriter(TextMessage) if ws.Subprotocol() != handshakeDialer.Subprotocols[0] {
io.WriteString(w, "HELLO") t.Errorf("ws.Subprotocol() = %s, want %s", ws.Subprotocol(), handshakeDialer.Subprotocols[0])
w.Close()
ws.SetReadDeadline(time.Now().Add(1 * time.Second))
op, r, err := ws.NextReader()
if err != nil {
t.Fatalf("NextReader: %v", err)
}
if op != TextMessage {
t.Fatalf("op=%d, want %d", op, TextMessage)
}
b, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("ReadAll: %v", err)
}
if string(b) != "HELLO" {
t.Fatalf("message=%s, want %s", b, "HELLO")
} }
sendRecv(t, ws)
} }
type dialHandler struct { type dialHandler struct {
@ -142,9 +145,15 @@ func (t dialHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
func sendRecv(t *testing.T, ws *Conn) { func sendRecv(t *testing.T, ws *Conn) {
const message = "Hello World!" const message = "Hello World!"
if err := ws.SetWriteDeadline(time.Now().Add(time.Second)); err != nil {
t.Fatalf("SetWriteDeadline: %v", err)
}
if err := ws.WriteMessage(TextMessage, []byte(message)); err != nil { if err := ws.WriteMessage(TextMessage, []byte(message)); err != nil {
t.Fatalf("WriteMessage: %v", err) t.Fatalf("WriteMessage: %v", err)
} }
if err := ws.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
t.Fatalf("SetReadDeadline: %v", err)
}
_, p, err := ws.ReadMessage() _, p, err := ws.ReadMessage()
if err != nil { if err != nil {
t.Fatalf("ReadMessage: %v", err) t.Fatalf("ReadMessage: %v", err)

10
conn.go
View File

@ -103,8 +103,9 @@ func newMaskKey() [4]byte {
// Conn represents a WebSocket connection. // Conn represents a WebSocket connection.
type Conn struct { type Conn struct {
conn net.Conn conn net.Conn
isServer bool isServer bool
subprotocol string
// Write fields // Write fields
mu chan bool // used as mutex to protect write to conn and closeSent mu chan bool // used as mutex to protect write to conn and closeSent
@ -151,6 +152,11 @@ func newConn(conn net.Conn, isServer bool, readBufSize, writeBufSize int) *Conn
return c return c
} }
// Subprotocol returns the negotiated protocol for the connection.
func (c *Conn) Subprotocol() string {
return c.subprotocol
}
// Close closes the underlying network connection without sending or waiting for a close frame. // Close closes the underlying network connection without sending or waiting for a close frame.
func (c *Conn) Close() error { func (c *Conn) Close() error {
return c.conn.Close() return c.conn.Close()

View File

@ -83,6 +83,9 @@ func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header,
} }
c := newConn(netConn, true, readBufSize, writeBufSize) c := newConn(netConn, true, readBufSize, writeBufSize)
if responseHeader != nil {
c.subprotocol = responseHeader.Get("Sec-Websocket-Protocol")
}
p := c.writeBuf[:0] p := c.writeBuf[:0]
p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...) p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)